gpt4 book ai didi

java - 我怎样才能将我的私有(private)整数放入公共(public)整数中

转载 作者:行者123 更新时间:2023-12-01 21:48:48 24 4
gpt4 key购买 nike

我想多次使用 Math.random 来打乱数组,但我不知道如何将随机 int 放入打乱中并多次使用 random int 。

 public static void scramble(int[] array){ 
for(int i = 0 ; i < array.length - 1; i++){
int temp = array[i];
array[i] = array[random];
array[random] = temp;}}

public int random (){
return (int)(Math.random() *9) + 1;}

输出

100 101 102 103 104 105 106 107 108 109 //Default
101 104 102 105 103 106 108 109 100 107 //Scrambled
100 101 102 103 104 105 106 107 108 109//Then sorted

整个驱动程序

    import java.lang.Math;

public class Driver03{
public static void main(String[] args){
int[] array = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109};
print(array);
scramble(array);
print(array);

print(array);}

public static void print(int[] array){
for(int x = 0; x < array.length; x++){
System.out.print(" " + array[x]);}
System.out.println("");}

public static void scramble(int[] array){
int random = random();
for(int i = 0 ; i < array.length - 1; i++){
int temp = array[i];
array[i] = array[random];
array[random] = temp;}}

public int random (){
return (int)(Math.random() *9) + 1;}

}

最佳答案

这是使用 Fisher-Yates shuffling algorithm 的实现。

  public static void main( String[] args )
{
int[] values = new int[] { 100, 101, 102, 103, 104, 105, 106, 107, 108, 109 };
System.out.println( "Start: " + Arrays.toString( values ) );
scramble( values );
System.out.println( "Scrambled: " + Arrays.toString( values ) );
Arrays.sort( values );
System.out.println( "Sorted: " + Arrays.toString( values ) );
}

public static void scramble( int[] array )
{
// Scramble using the Fisher-Yates shuffle.
Random rnd = new Random();
for ( int i = 0; i < array.length - 1; i++ )
{
int random = i + rnd.nextInt( array.length - 1 - i );
int temp = array[ random ];
array[ random ] = array[ i ];
array[ i ] = temp;
}
}

它不使用 Math.random() 而是使用 Random 的实例。

关于java - 我怎样才能将我的私有(private)整数放入公共(public)整数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58771106/

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