Skip to content

Instantly share code, notes, and snippets.

@reyoung
Created November 1, 2018 09:04
Show Gist options
  • Save reyoung/157d49a279640783b60945e09e0d523a to your computer and use it in GitHub Desktop.
Save reyoung/157d49a279640783b60945e09e0d523a to your computer and use it in GitHub Desktop.
#include <iostream>
void PrintRow(size_t N, size_t start, size_t i);
void CyclePrint(size_t N, size_t start=1) {
if (N <= 0) {
return;
}
for (size_t i=0;i<N; ++i) {
PrintRow(N, start, i);
}
}
void PrintRow(size_t N, size_t start, size_t i) {
if (N <= 0) {
return;
}
if (i == 0) { // first row
for (size_t j=0;j<N;++j) {
std::cout << start + j;
if (j + 1 == N && start == 1) {
std::cout << "\n";
} else {
std::cout << " ";
}
}
} else {
size_t start_elem = start + N + 3*(N - 1) - i - 1;
if (i + 1 == N) { // last row, reversely print
for (size_t j=0;j<N;++j) {
std::cout << start_elem - j;
if (j+1 == N && start == 1) {
std::cout << "\n";
} else {
std::cout << " ";
}
}
} else { // middle rows, recursively call
size_t last_elem = N + i + start - 1 ;
std::cout << start_elem << " ";
PrintRow(N-2, start + N + 3*(N - 1) - 1, i - 1);
std::cout << last_elem;
if (start == 1) {
std::cout << "\n";
} else {
std::cout << " ";
}
}
}
}
int main(){
CyclePrint(3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment