Home > other >  c# for loop - Transform sequence of number (4,5,6,7) into another sequence(1,3,5,7) using an equatio
c# for loop - Transform sequence of number (4,5,6,7) into another sequence(1,3,5,7) using an equatio

Time:12-17

So I have an array from 0 to 8, however I only want the odd elements 1,3,5 and 7. However I have another array that also goes from 0 to 8, but I need the elements 4,5,6 and 7.

As you can see below, Deck1Flags is perfect just as I want in, but in the same for loop I want to transform i = 4 into i = 1, and i = 5 needs to become i = 3, for the ReloadTimesSec[i] array, which needs elements 1,3,5, and 7:

for (int i = 4; i < 8; i  ) // Transform this: 4,5,6,7 into 1,3,5,7.
{
    if (!Deck1Flags[i]) continue; // element 4, 5, 6 and 7 perfect
           
    if (ReloadTimesSec[i] > 0f) continue; // wrong! I need i to be 1, 3, 5 and 7.
    ...
}

Since its only 4 numbers, I could do it manually, but im always interested in lesser well known methods that I can learn a lot from. I know I can get all even numbers by just doing i*2 for example. Is there a nice trick like that to get all odds? Without iterating over the whole loop and checking each number manually ofcourse. That would be a beginner programming problem, and is not the question.

CodePudding user response:

Don't mix things, better if you can have one more variable j and do your work with j.

for (int i = 4, j = 1; i < 8 && j <= 7; i  , j  =2)
{

}

CodePudding user response:

What you might need is something like y = k * x d (which is a linear function) where k equals 2 and d equals -7. So by inserting your numbers like 4, 5, 6 and 7 you will end up with 1, 3, 5 and 7.

for (int i = 4; i < 8; i  )
{
    int j = 2 * i - 7;

    if (!Deck1Flags[i])
        continue;
       
    if (ReloadTimesSec[j] > 0f)
        continue;

    ....
}

I am not a mathematician but here is my attempt:

  I) 1 = k * 4   d
 II) 3 = k * 5   d
III) 5 = k * 6   d
 IV) 7 = k * 7   d

From I)
d = k * 4   1

From II)
k = (3 - d) / 5

Combine I and II:
     d = ((3 - d) * 4) / 5   1
     d = (12 - 4d) / 5   1
 d   1 = (12 - 4d) / 5
5d   5 = 12 - 4d
 d   5 = 12
     d = 7

Using d in I)
7 = k * 4   1
8 = k * 4
2 = k

In addition to the solution above you should ask yourself why you even need to indices that are differently in that way. Do you store multiple information per element in the first array as separate elements in the second array? Whatever is the reason for it, as a result your code will be hard to read and understand.

  • Related