pattymills
pattymills

Reputation: 137

Shuffle 2D vector by column

My current code shuffles the 2d vector by row, but now I want to shuffle the vector by column. I need to do them one at a time in order to preserve a certain property (the n-rooks property in multijittered sampling).

I know this seems like a trivial question that has probably been asked countless times, but I spent the last 40 minutes trying to google it and apparently my google skills are trash.

Thanks.

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>



int main()
{
   std::vector<std::vector<int>> v { {1,4,7}, {2,5,8}, {3,6,9} };

   for (int i = 0; i < 3; i++) {
       for (int j = 0; j < 3; j++) {
           std::cout << v[i][j] << " ";
       }
       std::cout << std::endl;
   }
   std::cout << std::endl;

   unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
   shuffle(v.begin(),v.end(), std::default_random_engine(seed));

   for (int i = 0; i < 3; i++) {
       for (int j = 0; j < 3; j++) {
           std::cout << v[i][j] << " ";
       }
       std::cout << std::endl;
   }

   return 0;
}

Output:

1 4 7 
2 5 8 
3 6 9 

3 6 9 
1 4 7 
2 5 8

Upvotes: 0

Views: 223

Answers (1)

Thomas Sablik
Thomas Sablik

Reputation: 16446

One way is to shuffle each inner vector with the same "random" engine

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>

int main()
{
   std::vector<std::vector<int>> v { {1,4,7}, {2,5,8}, {3,6,9} };

   for (int i = 0; i < 3; i++) {
       for (int j = 0; j < 3; j++) {
           std::cout << v[i][j] << " ";
       }
       std::cout << std::endl;
   }
   std::cout << std::endl;

   unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
   for (auto &inner : v) {
      shuffle(inner.begin(),inner.end(), std::default_random_engine(seed));
   }

   for (int i = 0; i < 3; i++) {
       for (int j = 0; j < 3; j++) {
           std::cout << v[i][j] << " ";
       }
       std::cout << std::endl;
   }

   return 0;
}

Upvotes: 2

Related Questions