# 4521ca25d8c082dff90dd2b943026bf5a66cca90addc83bd7986f15cf99eee32 Elan 2.0.0-alpha4 valid

# A program to investigate the Collatz Conjecture
# https://en.wikipedia.org/wiki/Collatz_conjecture
main
  variable x set to 1
  while x > 0
    set x to inputInt("Enter a starting number (0 to quit)")
    # Array of the values we have seen so far
    variable p set to [x]
    # capture the max value so we can scale the graph
    variable max set to x
    while x > 1
      # Collatz sequence
      if (x mod 2) is 0 then
        set x to divAsInt(x, 2)
      else
        set x to x*3 + 1
      end if
      if x > max then
        set max to x
      end if
      call p.append(x)
      # draw what we have got so far, scaled to the canvas
      variable vg set to new List<of VectorGraphic>()
      for i in range(0, p.length() - 1)
        set vg to vg.withAppend((new LineVG()).withX1(scx(i, p)).withY1(scy(p[i], max)).withX2(scx(i + 1, p)).withY2(scy(p[i + 1], max)).withStrokeWidth(1))
      end for
      call displayVectorGraphics(vg)
      call print(x)
      call sleep_ms(100)
    end while
  end while
  call print("Finished")
end main

# scale x.  We pass in p just to get its length
function scx(i as Int, p as List<of Int>) returns Float
  return divAsFloat(i*100, p.length())
end function

# scale y
# subtract from 70 because y increases down the canvas
# subtract 1 so that 1 is always at the same place on the canvas
function scy(pi as Int, max as Int) returns Float
  return 70 - divAsFloat((pi - 1)*65, (max - 1))
end function

constant grey set to 0x808080
