Increment in For loop

Asked

Viewed 68 times

1

I need a count that goes from 1 to 24, but in that order:

1,9,17,2,10,18,3,11,19,4,12,20,5,13,21,6,14,22,7,15,23,8,16,24

I did so, but I wanted something more "elegant".

for($x=1;$x<9;$x++){
    echo $x.' '.($x+8).' '.($x+16);
}

What could be done?

2 answers

1

Elegance is inherently subjective. I will say that there is no more elegant form, except the fact that the code could be more spaced to become more readable.

Sounds like the point of the exercise. But there are those who would say that for this specific case, in this language the most elegant is not to use a loop but to make a echo with all the data. Although it would probably be against what asks for the exercise (although I think it is common for exercises to be ill-defined and not to say that can not use a loop, or ask to do in the fewest possible lines, which again can be more interesting without the for, but with the least amount of characters for may be better, but still I think I shouldn’t count characters that give readability.

Sure could do with recursion, some will say it’s more elegant.

There are a few small details that could be different, but I don’t think it’s worth the effort, it would get weirder.

Only night the comma was not used. Either it does not produce the expected result or the problem statement is not well defined above.

1


I could not identify any pattern in the sequence that could facilitate its creation. The closest I came was doing:

foreach (range(0, 23) as $i)
    echo ($i*8 + 1) % 23, ' ';

But the way out is:

1 9 17 2 10 18 3 11 19 4 12 20 5 13 21 6 14 22 7 15 0 8 16 1 

Obviously failing when the output value should be 23 or 24, since the general term used will never return a value greater than 22, that is, it worked for 91.67% of the sequence.

However, taking advantage of its logic, if you need to iterate on these values, you should define a generator:

function sequencia() {
    foreach (range(1, 8) as $i) {
        yield $i;
        yield $i + 8;
        yield $i + 16;
    }
}

This way you can take advantage of the returned values - instead of just printed on the screen:

foreach(sequencia() as $i)
    echo $i, ' ';

Generating:

1 9 17 2 10 18 3 11 19 4 12 20 5 13 21 6 14 22 7 15 23 8 16 24

If you like a more functional footprint:

function sequencia()
{
    return array_reduce(
        array_map(
            function ($x, $y, $z) {
                return [$x, $y, $z];
            },
            ...array_chunk(range(1, 24), 8)
        ), 
        "array_merge",
        []
    );
}

The result will be exactly the desired sequence, but in my view, is to add complexity without reasons. As Maniero said, elegance is relative.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.