[英]How to generate random numbers using a seed, and populating a 2D array with them
我需要幫助,使用種子獲取介於1到10之間的隨機數,然后將其放入2D數組中。 數字必須小數點后兩位。 這是輸出必須看起來的示例:
Please enter the grid size: 3
Please enter the random number seed: 4
7.31 9.19 9.19
6.80 0.78 0.25
6.99 8.05 1.51
Column min values:
6.80 0.78 0.25
Row min values:
7.31
0.25
1.51
Diagonal min value: 0.78
這是我到目前為止的代碼。 我知道不多。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the grid size: ");
int size = input.nextInt();
System.out.print("Please enter the random number seed: ");
double[][] array = new double[size][size];
System.out.println();
getArray(array);
printArray(array);
}
public static void getArray(double[][] a){
Scanner input = new Scanner(System.in);
int seed = input.nextInt();
Random random = new Random(seed);
for(int i=0; i<a.length; i++){
for(int j=0; j<a[i].length; j++){
a[i][j] = random.nextDouble() * 10;
}
}
}
public static void printArray(double[][] a){
for(int i=0; i<a.length; i++){
for(int j=0; j<a[i].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
這是我的輸出:
Please enter the grid size: 3
Please enter the random number seed: 1
7.308781907032909 4.100808114922017 2.077148413097171
3.3271705595951118 9.677559094241207 0.061171822657613006
9.637047970232077 9.398653887819098 9.471949176631938
我的主要問題是使我的數字達到兩位小數。 非常感謝。
您可以使用System.out.printf
for (double[] d : tab) {
for (double n : d) {
System.out.printf("%.2f\t", n);
}
System.out.println();
}
0,73 0,09 0,49
0,46 0,45 0,70
0,28 0,76 0,22
如果您使用的是java-8 ,則可能需要查看以下代碼來生成隨機數數組。
Stream.generate
:生成一個流。 將Supplier
作為參數。 在這里,我們給它() -> r.doubles(3).toArray()
,這基本上意味着:使用隨機對象,生成3
隨機雙精度數並返回一個數組。 limit(3)
:將Stream.generate
返回的arrays
數限制為3
toArray(double[][]::new)
:由於它是我們之前創建的double[]
的stream
,因此我們希望有一個包含這些對象的新數組,因此我們在這里創建的是double[]
數組double[]
。 因此, double[][]
是此流管道的終端操作。 int seed = 5;
Random r = new Random(seed);
double[][] tab = Stream.generate(() -> r.doubles(3).toArray())
.limit(3)
.toArray(double[][]::new);
我想您的主要問題是獲取隨機數,該數字要小數點后兩位。 盡管這可能不是執行此操作的最佳或最有效的方法,但此解決方案相對容易。
您可以使用:
Random ran = new Random(seed);
double number = ran.nextInt(1001) / 100.0D;
因此,您基本上會得到一個介於0到1000之間的隨機數(1001,因為上限是互斥的),然后將其除以100,從而得到一個帶小數部分的雙精度數,該數字小數點后兩位。
至於獲取最小值,您可以遍歷數組並跟蹤最小的數字。 然后將該數字與所有其他數字進行比較(如果另一個數字較小則對其進行更新),然后打印該數字。
我希望這有幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.