Skip to content

Instantly share code, notes, and snippets.

@AhmetCanSolak
Last active June 8, 2017 08:10
Show Gist options
  • Save AhmetCanSolak/559349b2912c4c18c728c35696dfa8f6 to your computer and use it in GitHub Desktop.
Save AhmetCanSolak/559349b2912c4c18c728c35696dfa8f6 to your computer and use it in GitHub Desktop.
Fill a 2D array diagonally. In other words, reshape 1D array to 2D array diagonally.
// An C++ example to fill a 2D array diagonally, written by AhmetCanSolak
#include <bits/stdc++.h>
int main(void){
// Fill this array with the 1D array you want to reshape, current values are just for testing!
std::vector<int> my_one_dimensional_array={1,2,3,4,5,6,7,8,9,10};
//Calculate the required size for 2D result
int z =1;
while( ( ((z) * ((z)+1))/2 ) < my_one_dimensional_array.size()){
z++;
}
//Initialize the required variables and reshape 1D array into 2D array diagonall!!!
int my_two_dimensional_array[z][z] = {};
bool direction=true;
for(int a=1;a<=z;a++){
for(int b=1;b<=z;b++){
my_two_dimensional_array[a-1][b-1] = my_one_dimensional_array[ ( ((a+b) * ((a+b)-1))/2 - (b-1) ) - 1 ];
}
}
//Print the result
int upper_limit = sizeof(my_two_dimensional_array)/sizeof(my_two_dimensional_array[0]);
for (int i = 0; i < upper_limit; i++){
for (int j = 0; j < upper_limit; j++){
std::cout << my_two_dimensional_array[i][j] << ' ';
}
std::cout << "\n";
}
return 0;
//End of the program...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment