Question

I'm trying to generate the Sierpinski triangle (chaos game version) in J. The general iterative algorithm to generate it, given 3 vertices, is:

point = (0, 0)
loop:
    v = randomly pick one of the 3 vertices
    point = (point + v) / 2
    draw point

I'm trying to create the idiomatic version in J. So far this is what I have:

load 'plot'

numpoints =: 200000
verticesx =: 0         0.5     1
verticesy =: 0 , (2 o. 0.5) ,  0

rolls =: ?. numpoints$3

pointsx =: -:@+ /\. rolls { verticesx
pointsy =: -:@+ /\. rolls { verticesy

'point' plot pointsx ; pointsy

This works, but I'm not sure I understand what's going on with -:@+ /\.. I think it's only working because of a mathematical quirk. I was trying to make a dyadic average function that would run as an accumulation through the list of points in the same way that + does in +/ \ i. 10, but I couldn't get anything like that to work. How would I do that?

Update:

To be clear, I'm trying to create a binary function avg that I could use in this way:

avg /\ randompoints

avg =: -:@+ doesn't work with this, for some reason. So I think what I'm having trouble with is properly defining an avg function with the proper variadicity.

Was it helpful?

Solution

To be as close to the algorithm as possible, I would probably do something like this:

v =: 3 2$ 0 0 0.5, (2 o. 0.5), 1 0
ps =: 1 2 $ (?3) { v
next =: 4 :'y,((?x){v) -:@+ ({: y)'

ps =: (3&next)^:20000 ps
'point' plot ({.;{:) |: ps

but your version is much more efficient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top