混合一个字母数组

huangapple go评论58阅读模式
英文:

Mixing up an array of letters

问题

以下是翻译好的内容:

对于我的作业我们得到了一个程序该程序使用字母表的前四个字母创建一个4x4的数组数组已经被排序好了除了作业中的混淆部分我已经完成了所有的内容混淆函数是从构造函数中调用的而不是从主方法中调用的它的作用是打乱数组中的字母顺序到目前为止我尝试过使用集合的shuffle方法但我发现它用于整数而不是字符值我还尝试将数组转换为列表但我无法弄清楚如何将列表放回数组中我应该如何打乱数组中的字母顺序

public LetterPuzzle() {
    puzzle = new char[4][4];
    letters = new char[4];
    
    for (int x=0; x<letters.length; x++) {
        letters = makeRow();
        puzzle[x] = letters;
    }
    System.out.println("Original: " + puzzle);
    scramble();
}

private char[] makeRow()
{
    char [] let = new char[4];
    for (char c='A'; c<'E'; c++)
        let[(int)(c-'A')] = c;
    return let;
}

/**
 * 将谜题表示为带有行和列标题的4x4矩阵
 * @return 以矩阵形式表示的谜题字符串
 */
public String toString() {
    String s = "   0  1  2  3\n";
    s = s + "--------------\n";
    for (int x=0; x<puzzle.length; x++) {
        s = s + x + "|";
        for (int y=0; y<puzzle.length; y++) {
            s = s + " " + puzzle[x][y]+ " ";
        }
        s = s + "\n";
    }
    return s;
}

/******由学生完成*****/
/**
 * 检查一行中是否有重复项
 * @param row 要检查的行:必须是值在0到puzzle.length之间
 * @return 如果有重复项返回false,否则返回true
 * @throws IllegalArgumentException 如果行超出范围
 */
public boolean checkRow(int row) {
    for (row = 0; row < puzzle.length; row++){
        for(int j = row + 1 ; j < puzzle.length; j++) {
            if( puzzle[row].equals(puzzle[j])) {
                return false;
            }
            else if(row > 0) {
                throw new IllegalArgumentException("行超出范围");
            } 
            return true;
        }
    }
    return true;
}

/**
 * 检查一列中是否有重复项
 * @param col 要检查的列:必须是值在0到puzzle.length之间
 * @return 如果有重复项返回false,否则返回true
 * @throws IllegalArgumentException 如果列超出范围
 */
public boolean checkColumn(int col) {
    for(col = 0; col < puzzle.length; col++){
        for(int j = col + 1; j < puzzle.length; j++) {
            if( puzzle[col].equals(puzzle[j])) {
                return false;
            }
            else if(col > 0) {
                throw new IllegalArgumentException("列超出范围");
            } 
        }
    } 
    return true;
}

/**
 * 打乱谜题,使字母随机排序
 */
void scramble( ){

}

public static void main (String [] args) {
    LetterPuzzle puzz = new LetterPuzzle();
    System.out.println(puzz);
    // 在此处添加代码来测试您的方法并显示结果
}
英文:

For my assignment we were given a program that creates a 4x4 array using the first four letters of the alphabet. The array already is sorted to start out. I have completed everything except for the scramble part of the assignment. Scramble is called from the constructor, not the main method and is supposed to mix up the letters within the array. So far I have tried to shuffle from collection but I have found that it is used for integers, not char values. I have also tried to convert from an array to a list but I can't figure out how to put the list back into the array. How can I mix up the letters within the array?

public LetterPuzzle() {
puzzle = new char[4][4];
letters = new char[4];
for (int x=0; x&lt;letters.length; x++) {
letters = makeRow();
puzzle[x] = letters;
}
System.out.println(&quot;Original: &quot; + puzzle);
scramble();
}
private char[] makeRow()
{
char [] let = new char[4];
for (char c=&#39;A&#39;; c&lt;&#39;E&#39;; c++)
let[(int)(c-&#39;A&#39;)] = c;
return let;
}
/**
* Represents puzzle as 4x4 matrix with row &amp; column headings
* @return puzzle as matrix String
*/
public String toString() {
String s = &quot;   0  1  2  3\n&quot;;
s = s + &quot;--------------\n&quot;;
for (int x=0; x&lt;puzzle.length; x++) {
s = s + x + &quot;|&quot;;
for (int y=0; y&lt;puzzle.length; y++) {
s = s + &quot; &quot; + puzzle[x][y]+ &quot; &quot;;
}
s = s + &quot;\n&quot;;
}
return s;
}
/******TO BE COMPLETED BY STUDENT*****/
/**
* Checks for duplicates in a row
* @param row is the row to be checked: must be a value 0 .. puzzle.length
* @return false if there are duplicates, true if not
* @throws IllegalArgumentException if row is out of bounds
*/
public boolean checkRow(int row) {
for (row = 0; row &lt; puzzle.length; row++){
for(int j = row + 1 ; j &lt; puzzle.length; j++) {
if( puzzle[row].equals(puzzle[j])) {
return false;
}
else if(row &gt; 0) {
throw new IllegalArgumentException(&quot;Row is out of bounds&quot;);
} 
return true;
}
}
return true;
}
/**
* Checks for duplicates in a column
* @param col is the column to be checked: must be a value 0 .. puzzle.length
* @return false if there are duplicates, true if not
* @throws IllegalArgumentException if row is out of bounds
*/
public boolean checkColumn(int col) {
for(col = 0; col &lt; puzzle.length; col++){
for(int j = col + 1; j &lt; puzzle.length; j++) {
if( puzzle[col].equals(puzzle[j])) {
return false;
}
else if(col &gt; 0) {
throw new IllegalArgumentException(&quot;Column out of bounds&quot;);
} 
}
} 
return true;
}
/**
* Scrambles puzzle so that letters appear in random order
*/
void scramble( ){
}
public static void main (String [] args) {
LetterPuzzle puzz = new LetterPuzzle();
System.out.println(puzz);
// Add code here to test your methods &amp; display results
}

答案1

得分: 2

如果您使用一个Character包装类来存储字符,您可以轻松地进行如下洗牌操作:

Character[] chars =
{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' };
Collections.shuffle(Arrays.asList(chars));
System.out.println(Arrays.toString(chars));

打印结果:

[g, b, d, a, c, i, f, e, h]

如果您想要使用原始数组,您可以这样进行洗牌操作:

char[] chars = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'};
  • 生成一个介于0arrayLength-1(包括)之间的索引next
  • 交换chars[next]chars[i]
  • chars[next]现在已经固定。
  • 重复这个过程,生成一个介于0arrayLength-2之间的索引。
  • i == 0时,操作完成。
public static void shuffle(char[] chars) {
    Random r = new Random();
    for (int i = chars.length-1; i >= 0; i--) {
        int next = r.nextInt(i+1);
        char c = chars[next];
        chars[next] = chars[i];
        chars[i] = c;
    }
}
英文:

If you use a Character wrapper class to store your characters you can easily shuffle it as follows:

Character[] chars =
{ &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39; };
Collections.shuffle(Arrays.asList(chars));
System.out.println(Arrays.toString(chars));

Prints

[g, b, d, a, c, i, f, e, h]

If you want to use primitive arrays you can shuffle them like this.

char[] chars = { &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;};
  • generate an index next between 0 and the arrayLength-1 inclusive
  • swap chars[next] with chars[i].
  • chars[next] is now permanently fixed.
  • repeat the process, generating an index between 0 and arrayLength-2.
  • when i == 0, you're done.
public static void shuffle(char[] chars) {
Random r = new Random();
for (int i = chars.length-1; i &gt;= 0; i--) {
int next = r.nextInt(i+1);
char c = chars[next];
chars[next] = chars[i];
chars[i] = c;
}
}
</details>
# 答案2
**得分**: 0

尝试为每个新数组索引获取随机位置。类似这样的内容。


void scramble () {
puzzle = new char[4][4];
scrambledPuzzle = new char[4][4];  // 将所有位置填充为空字符或其他内容
letters = new char[4];
int letterIndex = 0;
for (int x=0; x<letters.length; x++) {
for (int y=0; y<letters.length; y++) {
while (true) {
Random rand = new Random(); 
int upperbound = letters.length;
int index = rand.nextInt(upperbound); // 获取当前字母的随机位置
if(scrambledPuzzle[x][index] == ''){ // 尚未填充的位置
scrambledPuzzle[x][index] = letters[y]; // 将字母放置在这里
break;
}
}
}
}
}
英文:

try to get a random position for each new array index. something like this.


void scramble () {
puzzle = new char[4][4];
scrambledPuzzle = new char[4][4];  // fill all of this with empty char or 
something 
letters = new char[4];
int letterIndex = 0;
for (int x=0; x&lt;letters.length; x++) {
for (int y=0; y&lt;letters.length; y++) {
for( true ) {
Random rand = new Random(); 
int upperbound = letter.length;
int index = rand.nextInt(upperbound) ; //get a random position for current letter
if(scrambledPuzzle[x][index] == &#39;&#39;){ // not yet filled position
scrambledPuzzle[x][index] = letters[y]; // place it here
break;
}
}
}
}
}

huangapple
  • 本文由 发表于 2020年9月22日 01:37:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63997366.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定