gpt4 book ai didi

java - 如何显示数组的元素而不是值

转载 作者:行者123 更新时间:2023-12-01 13:49:49 25 4
gpt4 key购买 nike

嗨,我正在尝试创建一段代码,生成一个随机长度为 15 的数组,然后为每个元素提供一个 0-100 之间的随机数,我希望能够测试点 1 之间的距离(设置为0)并且存储在数组中的距离例如元素2的值为60,因此距点1的距离为60,我不想显示距点1的距离,而是想显示哪些点从最小到最大最接近点1,到目前为止我首先将数组排序为最小的数字,但是我想知道如何显示哪个元素存储什么距离,而不是相反,例如距离点 1(0) 最近的点是点 4(89,第二个最近的点第 1 点是第 3(25) 点,这是我到目前为止的代码:

static double distance(double x1, double x2)  
{
return Math.sqrt((x2-x1)*(x2-x1) );
//Math.sqrt is the square root of the 2 co-ordinates
}
public static void main(String[] args)
{

Random randomGenerator = new Random();
double x2, x1; //The Points
x1 = 0;
double distance;//The Math to work out distance
int randomInt2 = randomGenerator.nextInt(15)+1;//For Length of array
double [] distances = new double [randomInt2];//The Array
double store;


System.out.println("Distance Generated for point 1 : 0" );
System.out.println("Amount of points created is: "+randomInt2 );

int range = 0;//Amount of Points
while (range < randomInt2) {
int randomInt3 = randomGenerator.nextInt(1000);//Distance for all points besides first
x2 = randomInt3;
distance = distance(x1,x2);
store = distance;//stores the distance to be put into array
distances[range] = store;
range++;//increments amount of points each time
}

for (double val : distances) {
System.out.print("["+val+"],");
}

Arrays.sort(distances);// sorts array from highest to lowest
System.out.println("\nThe Nearest to point 1 is: " + distances[0]);

任何帮助将不胜感激

最佳答案

Java 的 SortedMap 提供了一种按键排序的方法,同时保持与关联值的关系。

double[] distances = new double[]{ 1, 3, 2, 0.5 };
SortedMap<Double, Integer> arrayIndexByDistance = new TreeMap<>();
for (int i = 0; i < distances.length; i++) {
arrayIndexByDistance.put(distances[i], i);
}
System.out.println("Distances (sorted): " + arrayIndexByDistance.keySet());
System.out.println("Indexes (sorted by distance): " + arrayIndexByDistance.values());

输出:

Distances (sorted): [0.5, 1.0, 2.0, 3.0]
Indexes (sorted by distance): [3, 0, 2, 1]

关于java - 如何显示数组的元素而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20048710/

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