Skip to content

Instantly share code, notes, and snippets.

@enghqii
Last active April 19, 2016 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save enghqii/77dfd4761182a2936e69 to your computer and use it in GitHub Desktop.
Save enghqii/77dfd4761182a2936e69 to your computer and use it in GitHub Desktop.
Lagrange Snail Matrix Generator - http://enghqii.tistory.com/24
#include <iostream>
#include <sstream>
using namespace std;
typedef int uint;
std::string LagrangeGenerator(const uint k){
uint** arr = new uint*[k];
for(uint i=0;i<k;i++){ arr[i] = new uint[k]; }
for(uint i=0;i<k;i++){
for(uint j=0;j<k;j++){
arr[i][j] = 0;
}
}
// 달팽이 배열 만들기.
uint i=0, j=0;
uint n = 1;
uint dir = 0; // 0 to 3
arr[i][j] = n++;
auto dircng = [](uint dir){
dir++;
dir%=4;
return dir;
};
while(true){
switch(dir){
case 0:
if(j+1 >= k || arr[i][j+1] != 0){ dir = dircng(dir); continue; }
j += 1;
break;
case 1:
if(i+1 >= k || arr[i+1][j] != 0){ dir = dircng(dir); continue; }
i += 1;
break;
case 2:
if(j-1 >= k || arr[i][j-1] != 0){ dir = dircng(dir); continue; }
j -= 1;
break;
case 3:
if(i-1 >= k || arr[i-1][j] != 0){ dir = dircng(dir); continue; }
i -= 1;
break;
}
arr[i][j] = n++;
if(n-1 >= k*k)
break;
}
/*
for(int i=0;i<k;i++){
for(int j=0;j<k;j++){
cout<<arr[i][j]<<'\t';
}
cout<<endl;
}
*/
// 만듬.
std::ostringstream ret;
ret<<"=1.0*";
for(uint j=0; j < k * k; j++){
uint y = arr[j/k][j%k];
double factor = 1;
for(uint f = 0; f < k*k; f++){
if(j != f){
ret << "(x-" << f << ")";
ret << "/"<<j-f<<"*";
}
}
ret<<y;
ret<<"+";
}
ret<<"0;";
for(uint i=0;i<k;i++){ delete [] arr[i]; }
delete[] arr;
return ret.str();
}
int main(int argc,char** argv){
if(argc < 2){
cout<<"no argument specified."<<endl;
return 0;
}
try{
int k = std::stoi(argv[1]);
if(k <= 0){
cout<<"argument out of range"<<endl;
return 0;
}
cout<<LagrangeGenerator(k).c_str()<<endl;
}catch(std::exception const & e){
cout<<"error : " << e.what() <<endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment