Skip to content

Instantly share code, notes, and snippets.

@Nekodigi
Created August 7, 2022 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nekodigi/68c218a5ea57458d927446cf1da6cb95 to your computer and use it in GitHub Desktop.
Save Nekodigi/68c218a5ea57458d927446cf1da6cb95 to your computer and use it in GitHub Desktop.
int diskN = 6;//number of disk
ArrayList<Step> steps = new ArrayList<Step>();
int[][] disks = new int[3][diskN];
int diskW, diskH;
int index = 0;
void setup(){
size(1000, 500);
colorMode(HSB, 360, 100, 100);
diskW = width/3;
diskH = height/diskN;
move(diskN, 0, 2);
for(Step step : steps){
//println(step);
}
for(int i=0; i<diskN; i++){
disks[0][i] = diskN-i;
}
frameRate(10);
}
void draw(){
background(0);
for(int j=0; j<3; j++){
for(int i=0; i<diskN; i++){
int state = disks[j][i];
int w = (int)map(state, 0, diskN, 0, diskW);
int x = (int)map(j, 0, 3, 0, width)+(diskW/2-w/2);
int y = (int)map(i, diskN-1, -1, 0, height);
int hue = (int)map(state, 0, diskN, 0, 360);
fill(hue, 100, 100);
rect(x, y, w, diskH);
}
}
if(index >= steps.size())return;
Step step = steps.get(index++);
applyMove(step);
}
void applyMove(Step step){
int from = step.from;
int to = step.to;
int fromNdisk = getNumberOfDisk(from);
int toNdisk = getNumberOfDisk(to);
if(fromNdisk > 0){
disks[to][toNdisk] = disks[from][fromNdisk-1];
disks[from][fromNdisk-1] = 0;
}
}
int getNumberOfDisk(int stick){//get max disk index in stick
for(int i=0; i<diskN; i++){
int disk = disks[stick][i];
if(disk == 0)return i;
}
return diskN;
}
void move(int no, int from, int to){//move disk from "from" stick to "to" stick
int other = 3-from-to;//the other stick which is either of from stick and to stick.
if(no > 1)move(no-1, from, other);
steps.add(new Step(no, from, to));
if(no > 1)move(no-1, other, to);
}
class Step{
int no;//index of disk
int from;
int to;
Step(int no, int from, int to){
this.no = no;
this.from = from;
this.to = to;
}
String toString(){
return no+":"+from+","+to;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment