For Loop Puzzles 2: Solutions

preview_player
Показать описание
Here's some solutions to the second set of for loop puzzles. There were many other excellent solutions but I've put a few of the first and best in the slides along with my own solutions.

I've also decided that one solution a particularly devious problem was so elegant and simple that it should be awarded a 6 star rating!
Рекомендации по теме
Комментарии
Автор

I think this is more elegant for the frog:
for(i = 28845; ; i=28845+61453-i;);

rotflmaopmpqxyz
Автор

Thanks for including my code :)

By the way the ternary (?: ) operator can be replaced with only logical operators, for example:
(a == 0 ? b = 1 : b = 0);
Is the same as
(((a == 0) && (b = 1)), ((a == 0) || (b = 0)));
because of the short-circuit evaluation (and left to right associativity).
The part before/after the ', ' can be left out, basically that's what I used for the last one, so it's not that amazing, if you replace it back with the ternary operator.

bcsaba
Автор

I know it's been years but I still wanna share my idea for 5:30 (+ - alternating):
for (int i = 1;; (i % 2 == 0) ? i = abs(i) + 1 : i = 0 - abs(i) - 1); //you can change i to i=0
It'd be possible to modify it and do the same without the abs(), if you use a logical operator instead as you showed in the recent branch-less programming vid, as well as many of the solutions shown in this one.

rotemlv
Автор

I felt my original answer for the powers of five was a bit limited as it only works for 5, no other powers. Had a think and re-wrote it.
for (int i = 1, int x = 3;; i = ((i/x)/x)/i);
explanation.
1/x/x gives the inverse of x squared, so you can just put it over 1 to get the square.

Also for the sawtooth problem here's how it works.
(i>0)*-1 is what decrements and is basically saying if i does not equal zero minus one from i. Remember that comparisons will return 1 if it's true and 0 if false.
((i==0)*f) if and only if i equals zero set i equal to f
only one of the above will play out in a single loop, thus making it possible for i to be equal to 0 without setting it to equal f before it can increment, as seen below.
f+(i==0) if i equals zero add 1 to f

stormthehouse