We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I know you can create grids using nested loops
for(int i=0;i<3;i++){
for(int j=0;j<2;j++){
rect(i*w,j*h,w,h);
}
}
Can we create same grid with just one loop, no nested loop?
for(int i=0;i<6;i++){
rect(w*i%3,h*i%2,w,h);
}
Answers
Use i % columns for x and i / columns for y. So here that would be
The / is using integer division here, you don't want it to return a fractional value, so i should be an int. I've added brackets to make it clearer and to rule out it returning a fractional value should h be a float.
W/o parenthesis:
rect(i%3 * w, i/3 * h, w, h);
:ar!I am stupid! Thanks @Koogs :) :)
GoToLoop thank you too for correct :) :)
Don't rely on operator precedence for stuff like this. It is cryptic and it'll bite you sooner or later.
The modulo (A.K.A. remainder)
%
operator, b/c it's related to the division/
operator, it's got its same precedence, along w/ the multiplication*
operator, like we've all learnt from actual math! :PHmm. For most people -- especially in a community with beginners in one or more languages -- I think it is better that they be really clear and not assume they have internalized Java operator precedence. Especially in a community with Java, JavaScript, Python, Ruby, and R flavors et cetera.
Here are operator precedence descriptions for ~60 languages, and while the whole extended C family is mostly the same on the basics, gotchas abound....
Bonus code golf game: Operator precedence: How wrong can I be?
@jeremydouglass, addition, subtraction, multiplication & division's precedence is learned at basic school. :-B
Just a lil' twist that the modulo (remainder) operator is related to division. ;;)
I think that % twist is the whole point.
If you are expected to put А В Б in order, it doesn't matter that you learned A B in grade school. If you don't know one of them, you don't know the order.
I'm not against people learning, of course. I'm just saying you can't assume that Oracle's operator precedence table should be intuitive or common knowledge for people with basic math.
I think using a nested for loop in
setup()
and putting the data into an array of aclass Cell
that holds the position and values of the cells is the best approachI personally think the code with nested for loop has a better readability than
%
stuff anyway ..... and for me readability and maintainability have priority in writing code.Chrisir
Fair enough -- I suppose the whole point of doing it in a single loop, or with no parens, or in as few chars as possible is "can this work?" -- and not trying to find the most readable or maintainable solution.
;-)
In jruby_art and propane we have created a grid convenience method after
Nodebox
it is both really convenient and efficient.thanks I just edited my post above with some code example
74 lines of code answering a question that wasn't asked. 8)
you people must have so much spare time.