Skip to content

Instantly share code, notes, and snippets.

@delascuevas
Created February 15, 2016 23:59
Show Gist options
  • Save delascuevas/aa3a9943964be32e0550 to your computer and use it in GitHub Desktop.
Save delascuevas/aa3a9943964be32e0550 to your computer and use it in GitHub Desktop.
Pascal's triangle rows. Each frame represents a row in Pascal's triangle. Each column is a number in binary where ones are ON and zeroes are OFF
/**
* Pascal's triangle rows
* Animation by JuanMa Cuevas.
*
* Each frame represents a row
* in Pascal's triangle.
* Each column is a number in binary
* where ones are ON and zeroes are OFF
* see animation here https://commons.wikimedia.org/wiki/File:Pascal%27s_Triangle_animated_binary_rows.gif
*/
import java.math.BigInteger;
int SIZE_PIXEL = 16;
int oX;
int oY;
ArrayList<BigInteger> stepList;
void setup() {
size(400, 400);
stroke(0, 0);
//fill(255, 204, 0);
fill(247, 236, 24);
frameRate(2);
stepList = new ArrayList<BigInteger>();
stepList.add(new BigInteger("1"));
}
void draw() {
background(0);
drawList();
nextStep();
//saveFrame();
}
void drawList() {
printStepList();
oX = originX(stepList.size());
oY = originY(stepList.size());
int pos = 0;
for (int i=0; i<stepList.size(); i++) {
drawOnes(stepList.get(i), pos);
pos++;
}
}
void printStepList() {
for (int i=0; i<stepList.size(); i++) {
print(stepList.get(i));
print(' ');
}
println();
}
void nextStep() {
for (int i=stepList.size()-1; i>0; i--) {
stepList.set(i, stepList.get(i).add(stepList.get(i-1)));
}
stepList.add(stepList.get(0));
}
int getValue(IntList list, int index) {
if (index<0 || index>=list.size()) return 0;
return list.get(index);
}
//////
IntList ones(BigInteger a) {
int i=0;
IntList ones = new IntList();
while (a.compareTo(BigInteger.ZERO)==1) {
if ((a.and(BigInteger.ONE)).equals(BigInteger.ONE)) {
//print (i+" ");
ones.append(i);
}
a = a.shiftRight(1);
i++;
}
return ones;
}
int originX(int step) {
return (width/2)-(step*SIZE_PIXEL/2);
}
int originY(int step) {
return height - 2*SIZE_PIXEL;
}
void drawOnes(BigInteger num, int pos) {
IntList ones = ones(num);
while (ones.size()>0) {
int i = ones.remove(0);
pixel(pos, i);
}
}
void drawPixel(int step, int x, int y) {
int gridW = step * SIZE_PIXEL;
}
void pixel(int x, int y) {
rect(oX+x*SIZE_PIXEL, oY-y*SIZE_PIXEL, SIZE_PIXEL, SIZE_PIXEL);
//fill(0);//random(256),random(256),random(256));
//ellipse(oX+x*SIZE_PIXEL, oY-y*SIZE_PIXEL, SIZE_PIXEL, SIZE_PIXEL);
//fill(255);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment