gpt4 book ai didi

java - 谢尔宾斯基三角

转载 作者:行者123 更新时间:2023-11-29 02:59:12 26 4
gpt4 key购买 nike

第k个谢尔宾斯基三角形是一个内部分割如下的三角形:

  1. 取三角形各边的三个中点。这些点构成黑色内接三角形的顶点。
  2. 剩下的 3 个内接三角形是第 (k-1) 个谢尔宾斯基三角形。完成drawTriangle的代码SierpinskiTriangle 类中的方法以及 k = 4 时 Sierpinski 程序输出的屏幕截图。

我在这里真的很挣扎,我写了这段代码,但它没有给我我需要的东西,任何帮助和一步一步的解释都会非常有帮助。而我的三角形不停留,过了一会儿就消失了。提前致谢

import java.awt.*;
import javax.swing.*;

public class Sierpinski_Triangle extends JPanel {
private static int numberLevelsOfRecursion;

public Sierpinski_Triangle(int numLevels) {
numberLevelsOfRecursion = numLevels;
}

public void paintComponent(Graphics computerScreen) {
super.paintComponent(computerScreen);
Point top = new Point(250, 50);
Point left = new Point(50, 450);
Point right = new Point(450, 450);
drawTriangle(computerScreen, numberLevelsOfRecursion, top, left, right);
}

/**
* Draw a Sierpinski triangle
*
* @param screen
* the surface on which to draw the Sierpinski image
* @param levels
* number of levels of triangles-within-triangles
* @param top
* coordinates of the top point of the triangle
* @param left
* coordinates of the lower-left point of the triangle
* @param right
* coordinates of the lower-right point of the triangle
*/
public static void drawTriangle(Graphics g, int levels, Point top, Point left, Point right) {
/**
* You must COMPLETER THE CODE HERE to draw the Sierpinski Triangle
* recursive code needed to draw the Sierpinski Triangle
*/
Point p1 = top;
Point p2 = left;
Point p3 = right;
if (levels == 2) {
// base case: simple triangle
Polygon tri = new Polygon();
tri.addPoint(250, 50);
tri.addPoint(50, 450);
tri.addPoint(450, 450);
g.setColor(Color.RED);
g.fillPolygon(tri);
} else {
// Get the midpoint on each edge in the triangle
Point p12 = midpoint(p1, p2);
Point p23 = midpoint(p2, p3);
Point p31 = midpoint(p3, p1);
// recurse on 3 triangular areas
drawTriangle(g, levels - 1, p1, p12, p31);
drawTriangle(g, levels - 1, p12, p2, p23);
drawTriangle(g, levels - 1, p31, p23, p3);
}
}

private static Point midpoint(Point p1, Point p2) {
return new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
}

public static void main(String[] args) {
JFrame frame = new JFrame("SierpinskiTriangle");
Sierpinski_Triangle applet = new Sierpinski_Triangle(1);
frame.add(applet);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450, 450);
frame.setVisible(true);
}
}

最佳答案

摆脱基本案例中的固定大小三角形。你必须改变这个:

        tri.addPoint(250, 50);
tri.addPoint(50, 450);
tri.addPoint(450, 450);

        tri.addPoint(p1.x, p1.y);
tri.addPoint(p2.x, p2.y);
tri.addPoint(p3.x, p3.y);

为了防止堆栈溢出,您应该更改此设置:

    if (levels == 2) {

为此:

    if (levels <= 2) {

并通过将初始参数设置为高于 1 来添加更多递归级别(否则您只会看到那个大红色三角形):

    Sierpinski_Triangle applet = new Sierpinski_Triangle(5);

Sierpinski Triangle, 9 level recursion

关于java - 谢尔宾斯基三角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36109551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com