Increment in For loop

1

I need a count ranging 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 it that way, but I wanted something more "elegant."

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

What could be done?

    
asked by anonymous 04.06.2018 / 21:59

2 answers

1

I could not identify any patterns in the sequence that would make it easier to create. The closest I got was doing:

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

But the output 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 your logic, if you need to iterate over these values, you should define a generator:

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

In this way you can take advantage of the returned values - rather than 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 sequence you want, but in my view, it's adding complexity with no motives. As Maniero said, elegance is relative.

    
05.06.2018 / 19:56
1

Elegance is inherently subjective. I'll say that there is no more elegant way, save the fact that the code could be more spaced out to become more readable.

It seems to me to be the purpose 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 data. Although it would probably be against what the exercise asks for (although I find it common to be poorly defined exercises and do not say that you can not use a loop, or ask to do as few lines as possible, which again can be more interesting without the for , but with the least amount of characters for might be better, but still I think I should not count characters that give readability.

Of course I could do with recursion, there are those who will say that it is more elegant.

There are a few small details that might be different, but I do not 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.

    
04.06.2018 / 22:54