Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,167 questions

40,723 answers

573 users

How to find all symmetric pairs in an array of pairs with Java

1 Answer

0 votes
import java.util.HashSet;
import java.util.Set;
 
class Pair
{
    public int x, y;
 
    Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
 
public class MyClass
{
    public static void findPairs(Pair[] pairs) {
        Set<String> set = new HashSet<>();
 
        for (Pair one_pair: pairs) {
            String onepair = "(" + one_pair.x + ", " + one_pair.y + ")";
 
            set.add(onepair);
 
            String reverse_onepair = "(" + one_pair.y + ", " + one_pair.x + ")";
 
            if (set.contains(reverse_onepair)) {
                System.out.println(onepair + " - " + reverse_onepair);
            }
        }
    }
 
    public static void main(String[] args)
    {
        Pair[] pairs = {
            new Pair(7, 2), new Pair(1, 8), new Pair(4, 6), new Pair(5, 1),
            new Pair(9, 3), new Pair(2, 7), new Pair(1, 5)
        };
 
        findPairs(pairs);
    }
}




/*
run:

(2, 7) - (7, 2)
(1, 5) - (5, 1)

*/

 





answered Aug 6, 2022 by avibootz

Related questions

...