我正在写一张有52张牌的牌组。一切都很完美,但我无法弄清楚如何在不使用java中的任何库并使用java内置的排序方法的情况下对其进行混洗。这是我的代码。我一直试图找出一段时间的东西,到目前为止,我无法做到。
String [] deck2=new String [52];
String[] deck=new String [52];
String suits[]={"Spades","Hearts","Diamonds","Clubs"};
String rank[]={"2","3","4","5","6","7","8","9","10","Jack","King","Queen","Ace"};
for(int i=0;i<deck.length;i++){
deck[i]=rank[i%13]+" "+"of "+suits[i/13];
deck2[i]=deck[i];
System.out.println(deck[i]);
}}}
答案 0 :(得分:0)
for (int i = 0; i < 500; i++) {
int from = (int) (Math.random() * array.length); //The place to get the first from
int to = (int) (Math.random() * array.length); // The place to get the second from
String perm = array[from]; // Store the "from" value
array[from] = array[to]; // Set the first value to the second
array[to] = perm; // Set the second value to the first
}
我不知道,为什么你不想使用java内置库,他们是有原因的。
要创建一个没有任何内置方法的随机数很难。很久以前我找到了一种方法,使用float,并使其溢出
float random = 1 << 32 + 1256224; //Have a random number here, it doesn't matter
我没有测试过,这可能不起作用。
float random = 1 << 32 + 1256224;
String [] deck2=new String [52];
String[] deck=new String [52];
String suits[]={"Spades","Hearts","Diamonds","Clubs"};
String rank[]={"2","3","4","5","6","7","8","9","10","Jack","King","Queen","Ace"};
for(int i=0;i<deck.length;i++){
deck[i]=rank[i%13]+" "+"of "+suits[i/13];
deck2[i]=deck[i];
System.out.println(deck[i]);
}
for (int i = 0; i < 500; i++) {
int from = (int) (Math.random() * array.length); //The place to get the first from
int to = (int) (Math.random() * array.length); // The place to get the second from
String perm = array[from]; // Store the "from" value
array[from] = array[to]; // Set the first value to the second
array[to] = perm; // Set the second value to the first
}
}}
答案 1 :(得分:0)
当然有可能。毕竟,一个库只不过是一些代码,你可以写自己。您必须编写自己的随机数生成器。这是一个简单的例子:
private static long x = System.currentTimeMillis();
public static long rndNumber() {
x ^= (x << 21);
x ^= (x >>> 35);
x ^= (x << 4);
return x < 0 ? -x : x;
}
public static void shuffle(int a[]) {
for (int i = a.length - 1; i > 0; i--) {
int pos = (int) (rndNumber() % a.length);
int temp = a[i];
a[i] = a[pos];
a[pos] = temp;
}
}
public static void main(String[] args) {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println(Arrays.toString(a));
shuffle(a);
System.out.println(Arrays.toString(a));
}