Java随机生成长宽的矩形_java – 将正方形或矩形分解为大量随机大小的正方形或矩形...
提供的代碼創建一個
k-d tree.您可以使用它在矩形上繪制線條,將其劃分為更小的矩形.獲得樹后,可以按如下方式使用它將區域劃分為這些矩形:
>在樹的根部選擇節點.
>通過這一點繪制一條垂直線.
>選擇它的左子,在你剛剛通過它的父線繪制的線左側的這一點畫一條水平線(這條線在你剛繪制的線上停止).
>選擇它是正確的孩子,在你剛剛通過它的父線繪制的線的右側繪制一條水平線(此線也在您通過父線繪制的線處停止).
>以遞歸方式執行此操作,在樹的每個級別切換垂直和水平線.
碼:
int MAX_HEIGHT = 100;
int MAX_WIDTH = 100;
int NUM_POINTS = 6;
// Generate random list of points
List pointList = new List();
Random rand = new Random();
for(int i = 0; i < NUM_POINTS ; i++)
{
pointList.add(new Point(rand.nextInt(MAX_HEIGHT), rand.nextInt(MAX_WIDTH));
}
BinaryTree tree = CreateKDTree(pointList, 0);
// Recursive function for creating a K-D Tree from a list of points
// This tree can be used to draw lines that divide the space up
// into rectangles.
public BinaryTree CreateKDTree(List pointList, int depth)
{
// Have to create the PointComparator class that just selects the
// specified coordinate and sorts based on that
Coordinate coord= depth % 2 == 0 ? X_COORDINATE : Y_COORDINATE
Collections.sort(pointList, new PointComparator(coord));
int median = pointList.size() / 2;
// unfortunately Java doesn't have a BinaryTree structure so
// you have to create this too
BinaryTree node = new BinaryTree(pointList[median]);
if(pointList.size() == 1) return node;
if(median > 0)
node.left(CreateKDTree(pointList.subList(0, median), depth + 1);
if(median + 1 < subList.size())
node.right(CreateKDTree(pointList.subList(median + 1, subList.size()), depth + 1);
return node;
}
總結
以上是生活随笔為你收集整理的Java随机生成长宽的矩形_java – 将正方形或矩形分解为大量随机大小的正方形或矩形...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java郝斌_郝斌Java自学教程全集打
- 下一篇: java美元兑换,(Java实现) 美元