初学者的问题在这里:
我有一个给定的单词,应该按出现顺序为每个字母分配数字。
然后随机排列单词并根据字母的外观打印数字
单词:CODEWORD
按字母顺序排序:CDDEOORW
分配编号:
C D D E O O R W
0 1 2 3 4 5 6 7
根据原始单词的“随机”字母:
C O D E W O R D
0 4 1 3 7 5 6 2
(我不介意以整数格式存储字符)
package hallo;
import java.util.Arrays;
public class test {
public static void shuffle(char[] k)
{
char[] m = k.clone();
Arrays.sort(m);
//array where I store my numbers
int[] numbers = new int[k.length];
//2d array to assign numbers to letters
int[][] per = new int[2][m.length];
// 2d array to store the "shuffled" word
int[][] per2 = new int[2][k.length];
//fill numbers array with integers to ascii order
for(int i=0;i<m.length;i++){
numbers[i] = i;
// 0 1 2 3 4 5 6 7
}
// fill first 2d array
for (int i = 0; i < m.length; i++) {
per[0][i] = m[i];
per[1][i] = numbers[i];
}
// now to fill the second array with "shuffled" word
for (int j = 0; j < k.length; j++) {
for (int i = 0; i < k.length; i++) { // k and m length is the same
if (per[0][i] == k[j]) {
per2[0][i] = per[0][i];
per2[1][i] = per[1][i];
//fill the numbers array with the new order
numbers[j] = per[1][i];
}
}
}
System.out.println("numbers: ->"+Arrays.toString(numbers));
}
public static void main(String[] args){
char[] word = {'C','O', 'D', 'E', 'W', 'O', 'R', 'D'};
shuffle(word);
// expected : 0 4 1 3 7 5 6 2
}
}
预期的输出为0 4 1 3 7 5 6 2,如上面的可视化所示。
但实际输出为0 5 2 3 7 5 6 2
看起来像O和D多次出现的字符会导致此问题。
我试图在找到字母后立即中断for循环,或将字母出现的数字存储在单独的数组中,但到目前为止没有任何效果。任何帮助或纠正将不胜感激。
填充数字[j]的循环不会检查位置是否已添加。结果,对于每次出现字符,都将相同的索引添加到结果中。您可以使用布尔数组来标记已使用的索引。并且仅在不使用索引的情况下检查排序数组m中的字符。
public static void shuffle (char[] k) {
char[] m = k.clone();
Arrays.sort(m);
boolean[] used = new boolean[k.length];
int[] numbers = new int[k.length];
for(int i=0;i<k.length;i++) {
for (int j=0; j<m.length; j++) {
if (k[i] == m[j] && !used[j]) {
numbers[i] = j;
used[j] = true;
break;
}
}
}
System.out.println("numbers: ->"+Arrays.toString(numbers));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句