英文:
A, B, C, D, E, F, G, H in the matrix, provided that they use the letters at a maximum and a minimum of 2 times
问题
像这样...
如图所示,同一字母的3个字母应最多写2次,最少写2次。
这是我的代码部分
Random r = new Random();
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
char c = (char)(r.nextInt(8) + 'a');
cards[i][j] = new Card(c);
}
}
在一个4x4的纸牌游戏中,我们试图找到在卡片下面写着的相同的2个字母。
英文:
like this ...
As shown in the picture, 3 letters of the same letter should be written at most and at least 2 times.
this is my pillow code part
Random r = new Random();
for (int i = 0 ; i < 4 ; i++){
for (int j = 0 ; j < 4 ; j++){
char c = (char)(r.nextInt(8) + 'a');
cards[i][j] = new Card(c);
}
}
In a 4x4 card game we were trying to find the same 2 letters written under the cards.
答案1
得分: 0
你无需使用Random
类。正如@Yunnosch在他的评论中提到的,您需要创建一个字母对数组,将数组复制到java.util.List
中,对该List
进行洗牌,然后将洗牌后的List
复制到您的矩阵中。
以下是测试运行的输出。
[b, e, e, b]
[g, d, f, d]
[f, h, h, a]
[c, g, a, c]
以下是我使用的代码。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ShuffleExample {
public static void main(String[] args) {
char[][] cards = new char[4][4];
char[] letters = { 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd',
'e', 'e', 'f', 'f', 'g', 'g', 'h', 'h' };
List<Character> pairs = new ArrayList<>();
for (int i = 0; i < letters.length; i++) {
pairs.add(letters[i]);
}
Collections.shuffle(pairs);
int index = 0;
for (int i = 0; i < cards.length; i++) {
for (int j = 0; j < cards[i].length; j++) {
cards[i][j] = pairs.get(index++);
}
}
for (int i = 0; i < cards.length; i++) {
System.out.println(Arrays.toString(cards[i]));
}
}
}
英文:
You don't need to use the Random
class at all. As @Yunnosch mentioned in his comment, you need to create an array of letter pairs, copy the array to a java.util.List
, shuffle the List
, and copy the shuffled List
to your matrix.
Here's the output from a test run.
[b, e, e, b]
[g, d, f, d]
[f, h, h, a]
[c, g, a, c]
Here's the code I used.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ShuffleExample {
public static void main(String[] args) {
char[][] cards = new char[4][4];
char[] letters = { 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd',
'e', 'e', 'f', 'f', 'g', 'g', 'h', 'h' };
List<Character> pairs = new ArrayList<>();
for (int i = 0; i < letters.length; i++) {
pairs.add(letters[i]);
}
Collections.shuffle(pairs);
int index = 0;
for (int i = 0; i < cards.length; i++) {
for (int j = 0; j < cards[i].length; j++) {
cards[i][j] = pairs.get(index++);
}
}
for (int i = 0; i < cards.length; i++) {
System.out.println(Arrays.toString(cards[i]));
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论