Search code examples
j

loop in J language ^:


Assume that I have 10 random points on 2D graph, and each point is connected with a spring. So every points is converging to the center of the force for every iterations.

What I am trying to make is a loop that adds a random vector to an existing vector set after each iteration.

So it starts from

v=: <(? 10 2 $ 20)   NB. 10 random vectors 
n=: <(? 1 2 $ 20)    NB. new random vector
force v              NB. force function moves the vectors toward to the center 
add n                NB. add n into v, then #v = 11
force v
add n
force v
add n 
...

I'm still working on the force function which seems like to be not hard, but I got really stuck on the add section. Can anyone help me on this? My final goal is to make a loop repeating add force section like 100 times

Thank you!


Solution

  • I agree with Eelvex that the boxes seem redundant. Perhaps the following is a useful way to think about what you are trying to accomplish?

       new=: 2 ?@$ 20"_      NB. generates random, length 2 vector
       add=: ] , new         NB. appends new to right argument
       add^:(3) Init=: 4 2 ?@$ 20
    11  9
     9 16
     9 13
     0 17
     3  3
     7 17
     6  6
    

    If you have a verb force you could apply that at each iteration too:

       force=: -:            NB. example verb (halves right argument)
       force@add^:(5) Init=: 4 2 ?@$ 20   NB. 5 iterations
    0.46875  0.3125
    0.15625 0.53125
    0.28125 0.53125
     0.5625 0.53125
    0.59375 0.59375
      1.125   0.375
      0.125   2.375
       2.25     3.5
          5     9.5