Home > Blockchain >  How would I convert this if-code to a for-loop?
How would I convert this if-code to a for-loop?

Time:11-18

I was wondering how I could possibly convert this holy nest of if and && checks, into a simple for-loop? Any solutions are appreciated, since I'm completely lost and my brain has given up.

if (localModulebytes[i   1] == convertedByteArray[1]
    && localModulebytes[i   2] == convertedByteArray[2]
    && localModulebytes[i   3] == convertedByteArray[3]
    && localModulebytes[i   4] == convertedByteArray[4]
    && localModulebytes[i   5] == convertedByteArray[5]
    && localModulebytes[i   6] == convertedByteArray[6]
    && localModulebytes[i   7] == convertedByteArray[7]
    && localModulebytes[i   8] == convertedByteArray[8]
    && localModulebytes[i   9] == convertedByteArray[9]
    )
{
    // Code
    similarities  ;
}

I tried this code, which gave similaries that were way beyond the ones from my bee-nest to code:

for (var j = 1; j < 9; j  )
{
    if (localModulebytes[i   j] == convertedByteArray[j])
    {
        similarities  ;
    }
}

CodePudding user response:

That's because you increase the similarities more times in the loop. You can try something like this

var sim = true;
for (var j = 1; j < 9; j  ) {
    if (localModulebytes[i   j] != convertedByteArray[j]) {
        sim = false;
        break;
    }
}
if(sim) similarities  ;

CodePudding user response:

GreenChicken's answer is the way to do this with a for loop, but there's also LINQ:

if (Enumerable.Range(1,9).All(j => localModulebytes[i   j] == convertedByteArray[j])) {
      similarities;
}

Which isn't necessarily better, but I'll offer the alternative.

CodePudding user response:

To convert your initial code to a looped check, you could do something like:

var similar = true;
for ( var j = 1; j < 10; j   )
    if ( localModulebytes[i   j] != convertedByteArray[j] )
    {
        similar = false;
        break;
    }
if (similar) similarities  ;

But, considering you used the variable name similarities I suspected you wanted to count how many of those items were the same, not all of the 9. Your follow-up comment showed my assumption to be incorrect.

  • Related