Reputation: 305
I was given a problem - there is a box containing label and has value in it. for example - box with label 'a' contains value 2, box with label 'b' contains value 7 etc. I was asked to find the pairs that adds to sum 10. I wrote below code to find the pair using hashmap. But it contains same result twice with only difference of position of letter. For example - (a,e) is same as (e,a) How can I keep/print only the unique pair?
Below is my code :
public class BoxValue {
public void pair()
{
int sum = 10;
HashMap<Integer, Character> m = new HashMap<Integer, Character>();
m.put(2, 'a');
m.put(7, 'b');
m.put(4, 'c');
m.put(3, 'd');
m.put(8, 'e');
m.put(6, 'f');
Set<Integer> s = m.keySet();
for(Integer in : s)
{
if(m.containsKey(sum-in))
System.out.println(m.get(in)+","+m.get(sum-in));
}
}
public static void main(String[] args) {
BoxValue bv = new BoxValue();
bv.pair();
}
}
Upvotes: 2
Views: 103
Reputation: 5455
I would just use a Set
to keep track of which complements you've already seen:
Set<Integer> seen = new HashSet<>();
for (Integer in : m.keySet())
{
if(m.containsKey(sum-in) && !seen.contains(in))
{
System.out.println(m.get(in) + "," + m.get(sum-in));
seen.add(sum-in);
}
}
You can do it without any additional storage if you're able to modify the map, at the loss of some clarity:
for (Integer in : m.keySet())
{
if(m.containsKey(sum-in) && m.get(in) != null)
{
System.out.println(m.get(in) + "," + m.get(sum-in));
m.put(sum-in, null);
}
}
Output:
a,e
d,b
c,f
Upvotes: 1
Reputation: 18430
You can use a map for keys
List<Integer> s = new ArrayList<>(m.keySet()); // Create a key list
HashMap<Integer, Boolean> pos = new HashMap<Integer, Boolean>(); // Map for used key
for (int i = 0; i < s.size(); i++) {
if (m.containsKey(sum - s.get(i)) && !pos.containsKey(sum - s.get(i)))
System.out.println(m.get(s.get(i)) + "," + m.get(sum - s.get(i)));
pos.put(s.get(i), true); // Update map
}
Upvotes: 0