SharkBytes
SharkBytes

Reputation: 211

C++ Can I Substitute Nested For Loop with 1 Loop

So I've been trying to do some code simplification, mainly because I'm not that fond of having Nested For loops however I'm experiencing trouble trying to simplify the below code. The code does functions perfectly fine and does as intended (code below is stripped down!).

int fill{200}, wid{600}, hei{400};
for (int w{ 0 }; w < fill; w++) {
    for (int h{ 0 }; h < hei; h++) {
        int offset{ w + h * (wid + fill) }
        //Offset is used to traverse a 1d array "fill" amount of times.
        /*Before:
        000000
        000000
        000000
        000000
          After:
        110000
        110000
        110000
        110000*/
    }
}

I've tried to reproduce the same output with 1 less Loop but I either don't get the right result or I go outside of the array. So I'm wondering can it be done?

Upvotes: 1

Views: 1834

Answers (1)

luk32
luk32

Reputation: 16070

I am not sure if I would recommend it, but for the science... there you go. It gives OK to me. The idea is simple. You combine two numbers into one with multiplication, and retrieve them via division and modulo.

Just remember to be sure not to overflow at the multiplication. I will also leave a note that I did not check if all the types are chosen correctly. For example this alone int offset{ w + h * (wid + fill) }; raises a flag to me. So the below code is just for the math/method mainly.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    std::vector<int> loop1, loop2;
    int fill{200}, wid{600}, hei{400};

    for (int w{ 0 }; w < fill; w++) {
      for (int h{ 0 }; h < hei; h++) {
        int offset{ w + h * (wid + fill) };
        loop1.push_back(offset);
      }
    }

    for (int i{ 0 }; i < fill*hei; i++) {
      int w = i / hei;
      int h = i % hei;
      int offset{ w + h * (wid + fill) };
      loop2.push_back(offset);
    }

    if (loop2 == loop1) cout << "OK\n";
    else cout << "NOT OK\n";
    return 0;
}

Upvotes: 2

Related Questions