查找矩阵中的唯一元素
我正在使用一个称为矩阵的二维数组。我需要检索数组中的唯一元素。
无 ABCG F
y1 a1 b2 c1 g1 f1
y2 a1 b1 c2 g2 f1
y3 a2 b1 c2 g1 f2
y4 a1 b2 c2 g2 f1
y5 a2 b2 c1 g1 f2
例如,对于 A 列,我应该得到 a1 和 a2。对于 B、b1 和 b2,依此类推。
我尝试过不同的方法,但到目前为止没有任何效果。这是我整理的:
public void UniqueElement(String line){
List tempList = Arrays.asList(line);
Set set = new HashSet(tempList);
System.out.println("");
System.out.printf("%s", set);
}//UniqueElement Method
这是我得到的:
[nil,A,B,C,G,F] [y1,a1,b2,c1,g1,f1] [y2,a1,b1,c2,g2,f1] [y3,a2,b1,c2,g1,f2] [y4,a1,b2,c2,g2,f1]
有人可以建议另一种方法来尝试在我的矩阵中挑选出独特的项目吗?
谢谢
I am working with a 2D array called matrix. I need to retrieve the unique elements in the array.
nil A B C G F
y1 a1 b2 c1 g1 f1
y2 a1 b1 c2 g2 f1
y3 a2 b1 c2 g1 f2
y4 a1 b2 c2 g2 f1
y5 a2 b2 c1 g1 f2
So for instance, for column A, I should get a1 and a2. For B, b1 and b2, and so on.
I have tried out different thing, but nothing has worked thus far. Here is what I put together:
public void UniqueElement(String line){
List tempList = Arrays.asList(line);
Set set = new HashSet(tempList);
System.out.println("");
System.out.printf("%s", set);
}//UniqueElement Method
Here is what I get:
[nil,A,B,C,G,F]
[y1,a1,b2,c1,g1,f1]
[y2,a1,b1,c2,g2,f1]
[y3,a2,b1,c2,g1,f2]
[y4,a1,b2,c2,g2,f1]
Could someone suggest another approach to try to single out unique items in my matrix?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行嵌套的 foreach 循环并遍历数组中的元素。当您进行操作时,将“新”或未见过的元素存储在列表中。要确定是否看到某个元素,请每次遍历列表,如果找到匹配项,则移至下一个数组元素。否则(不匹配),将该元素添加到列表中并移至下一个数组元素。
该算法非常暴力并且扩展性不佳,但它会为您提供唯一元素的列表。
You could do nested
foreach
loops and walk through the elements in the array. As you go, store "new" or unseen elements in a list. To decide if you've seen an element, walk the list each time and if you get a match, move to the next array element. Otherwise (no match), add the element to the list and move to the next array element.This algorithm is very brute-force and does not scale well, but it will give you a list of the unique elements.
如果您可以节省内存...循环遍历每个项目并将其用作 Map 的键,每次遇到该键时递增该值。完成后,循环遍历 Map 并输出值为 1 的键。
事实上,由于您只关心唯一性,因此可以使用布尔值作为值。 true = 唯一,false = 不唯一
If you can spare the memory... Loop over each item and use it as the key to a Map, incrementing the value each time the key is encountered. Once you are done, loop over the Map and output the keys who's value is 1.
In fact, since you only care about uniqueness, you could use a Boolean as the value. true = unique, false = not unique