简体   繁体   中英

Please help me with this simple, elementary pseudocode

This should be very easy for you guys, but I still can't get it visualized in my mind. Here's what I'm trying to do:

if (flag)
    for (i = 0; i < 10; i++)
        {LARGE_BLOCK_OF_CODE (that visits an array in order)}
else
    for (i = 9; i >= 0; i--)
        {LARGE_BLOCK_OF_CODE (that visits an array in REVERSE order)}

The problem is that this block of code cannot be placed in a function, and I don't want to copy/paste it twice. Is there any way I can do that in this manner:

if (flag)
    loop = for (i = 0; i < 10; i++);
else
    loop = for (i = 9; i >= 0; i--);

loop
{LARGE_BLOCK_OF_CODE (that visits an array in the order specified in 'loop')}

??

Create variables for the start and end of the loop, and create a third variable to determine the 'direction' for the iteration.

Then just let the loop run through your ONE block of code. Like this...

int iStart = 0;
int iEnd = 9;
int iIncrement = +1;

if (reverse)
{
    iStart = 9;
    iEnd = 0;
    iIncrement = -1;
}

for (i = iStart; i != iEnd; i += iIncrement)
{
    //...large block of code here...
}

Put that LARGE_BLOCK_OF_CODE in a function, receiving order as a parameter. Then reuse it in any number of loops you need.

I don't know how big your array is. Maybe it is possible to generate an additional array that holds the required indexes in the required order:

indexes = []

for (i = 0; i < 10; i++)
  indexes.add(i)

if (!flag)
  indexes.reverse()

for each (i in indexes)
  {LARGE_BLOCK_OF_CODE}
for (i = flag?0:9; i != flag?10:0; i += flag?1:-1)
{
//LARGE_BLOCK_OF_CODE 
}

Well I know...:p thats too many if else.

And yes, FlipScript's solution is better though it might not look neat. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM