以下是我正在处理的问题和我的代码片段。 有没有更好的方法来实现这个?我在下面为此使用了基本的控制结构。
将行和列存储在 map 中并根据键/值对搜索 map 是否更好?
There is a security keypad at the entrance of a building. It has 9 numbers 1 - 9 in a 3x3 matrix format.
1 2 3
4 5 6
7 8 9The security has decided to allow one digit error for a person but that digit should be horizontal or vertical. Example: for 5 the user is allowed to enter 2, 4, 6, 8 or for 4 the user is allowed to enter 1, 5, 7. IF the security code to enter is 1478 and if the user enters 1178 he should be allowed.
以下是我正在处理的代码片段:
ArrayList<Integer> list = new ArrayList<Integer>();
int num = 9;
int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
for(int i =0;i< arr.length;i++){
for(int j = 0; j <arr.length;j++){
if(num == arr[i][j]){
row = i;
col = j;
break;
}
}
}
for(int j1 = 0; j1< 3 ; j1++){
if(arr[row][j1] != num){
list.add(arr[row][j1]);
}
}
for(int i1 = 0 ; i1 <3;i1++){
if(arr[i1][col] != num){
list.add(arr[i1][col]);
}
}
最佳答案
有很多方法可以解决这个问题,但我认为使用 HashMaps 和 HashSets 可以比多次迭代更有效地解决这个问题。
如果我是你,我会首先使用 HashMap 和哈希集构建数据模型。这是因为 hash map 和 hash set 具有快速查找,(无迭代)
HashMap<Integer,HashSet<Integer>> values = new HashMap<Integer, HashSet<Integer>>();
//now put in the accepted values for one
HashSet<Integer> oneValues = new HashSet<Integer>();
oneValues.put(1);
oneValues.put(2);
oneValues.put(4);
values.put(1, oneValues);
//put in 2 values
......
然后当你解析你的输入时,如果你想看看输入的值是否被代码所接受,只需做类似的事情
private boolean isAccepted(int input, int combinationValue)
{
// check to see if the inputed value in the accepted values set
return values.get(combinationValue).contains(input);
}
关于java - 在 Java 中为一个数字生成多个组合列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3984320/