Created
October 5, 2008 12:55
-
-
Save taka2/14881 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.*; | |
import java.awt.event.*; | |
import java.math.*; | |
import javax.swing.*; | |
import javax.swing.event.*; | |
public class Sierpinski extends JPanel | |
{ | |
private static final int DRAW_LEVEL = 128; | |
private static final int RECT_SIZE = 4; | |
public static void main(String args[]) | |
{ | |
final Sierpinski s = new Sierpinski(); | |
final JFrame jf = new JFrame("Sierpinski triangle"); | |
jf.setSize(new Dimension(RECT_SIZE * DRAW_LEVEL + 30, RECT_SIZE * DRAW_LEVEL + 80)); | |
jf.setLayout(new BorderLayout()); | |
jf.add(s, BorderLayout.CENTER); | |
JSlider slider = new JSlider(SwingConstants.HORIZONTAL, 2, 32, 2); | |
slider.addChangeListener(new ChangeListener() { | |
public void stateChanged(ChangeEvent ce) | |
{ | |
JSlider js = (JSlider)ce.getSource(); | |
s.divNumber = js.getValue(); | |
jf.repaint(); | |
} | |
}); | |
slider.setPaintTicks(true); | |
slider.setMajorTickSpacing(1); | |
slider.setMinorTickSpacing(1); | |
slider.setPaintLabels(true); | |
slider.setSnapToTicks(true); | |
jf.add(slider, BorderLayout.NORTH); | |
jf.setVisible(true); | |
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
} | |
public int divNumber = 2; | |
public void drawPascal(Graphics g, int level) | |
{ | |
if(level == 0) | |
{ | |
// 何もしない | |
} | |
else | |
{ | |
int x = ((RECT_SIZE * DRAW_LEVEL + 30) / 2) - ((RECT_SIZE / 2) * level); | |
int y = (level - 1) * RECT_SIZE; | |
for(int i=0; i<level; i++) | |
{ | |
BigInteger combination = combination((level-1), i); | |
if(combination.mod(BigInteger.valueOf(divNumber)).equals(BigInteger.ZERO)) | |
{ | |
// 偶数は塗らない | |
g.drawRect(x + (i * RECT_SIZE), y, RECT_SIZE, RECT_SIZE); | |
} | |
else | |
{ | |
// 奇数は塗る | |
g.fillRect(x + (i * RECT_SIZE), y, RECT_SIZE, RECT_SIZE); | |
} | |
} | |
drawPascal(g, (level - 1)); | |
} | |
} | |
public void paint(Graphics g) | |
{ | |
drawPascal(g, DRAW_LEVEL); | |
} | |
public BigInteger combination(int n, int k) | |
{ | |
BigInteger bunsi = fact(BigInteger.valueOf(n)); | |
BigInteger bunbo1 = fact(BigInteger.valueOf(n-k)); | |
BigInteger bunbo2 = fact(BigInteger.valueOf(k)); | |
BigInteger bunbo = bunbo1.multiply(bunbo2); | |
return bunsi.divide(bunbo); | |
} | |
public BigInteger fact(BigInteger n) | |
{ | |
if(n.equals(BigInteger.ZERO)) | |
{ | |
return BigInteger.ONE; | |
} | |
else | |
{ | |
return n.multiply(fact(BigInteger.valueOf(n.intValue() - 1))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment