|
| 1 | +package ood.design; |
| 2 | + |
| 3 | +import annotation.Platform; |
| 4 | +import annotation.Site; |
| 5 | + |
| 6 | +import java.util.*; |
| 7 | + |
| 8 | +/** |
| 9 | + * One to one element mapping |
| 10 | + * */ |
| 11 | +@Platform(Site.RANDOM) |
| 12 | +public class PairSocks { |
| 13 | + |
| 14 | + public List<List<Sock>> pairSocks(List<Sock> socks,List<Rule> rules){ |
| 15 | + List<List<Sock>> result = new ArrayList<>(); |
| 16 | + |
| 17 | + Map<String,Sock> map = buildMap(socks); |
| 18 | + Map<String,String> ruleMap = buildRuleMap(rules); |
| 19 | + |
| 20 | + for(Sock s : socks){ |
| 21 | + String pairsWith = ruleMap.get(s.getKey()); |
| 22 | + if(map.containsKey(pairsWith)){ |
| 23 | + result.add(List.of(s,map.get(pairsWith))); |
| 24 | + map.remove(pairsWith); |
| 25 | + map.remove(s.getKey()); |
| 26 | + } |
| 27 | + } |
| 28 | + return result; |
| 29 | + } |
| 30 | + |
| 31 | + private Map<String, String> buildRuleMap(List<Rule> rules){ |
| 32 | + Map<String, String> map = new HashMap<>(); |
| 33 | + for(Rule r : rules){ |
| 34 | + map.put("left"+r.leftColor,"right"+r.rightColor); |
| 35 | + map.put("right"+r.rightColor,"left"+r.leftColor); |
| 36 | + } |
| 37 | + return map; |
| 38 | + } |
| 39 | + |
| 40 | + private Map<String, Sock> buildMap(List<Sock> socks){ |
| 41 | + Map<String,Sock> map = new HashMap<>(); |
| 42 | + for(Sock s : socks){ |
| 43 | + map.put(s.leg+s.color , s); |
| 44 | + } |
| 45 | + return map; |
| 46 | + } |
| 47 | + |
| 48 | + public static void main(String[] args){ |
| 49 | + List<Sock> socks = Arrays.asList( |
| 50 | + new Sock(1, "red","left"), |
| 51 | + new Sock(2, "red","right"), |
| 52 | + new Sock(3, "blue","left"), |
| 53 | + new Sock(4, "black","right"), |
| 54 | + new Sock(5, "black","left"), |
| 55 | + new Sock(6, "red","right") |
| 56 | + ); |
| 57 | + |
| 58 | + System.out.println(new PairSocks().pairSocks( |
| 59 | + socks, |
| 60 | + List.of(new Rule("blue", "black"),new Rule("black", "red")) |
| 61 | + )); |
| 62 | + } |
| 63 | + |
| 64 | + private static class Sock{ |
| 65 | + public int id; |
| 66 | + public String leg,color; |
| 67 | + |
| 68 | + public Sock(int i , String c, String l){ |
| 69 | + this.id = i ; this.leg = l;this.color = c; |
| 70 | + } |
| 71 | + |
| 72 | + public String getKey(){ |
| 73 | + return leg+color; |
| 74 | + } |
| 75 | + |
| 76 | + @Override |
| 77 | + public String toString(){ |
| 78 | + return "Sock{"+ |
| 79 | + "id="+id+ |
| 80 | + ", leg='"+leg+'\''+ |
| 81 | + ", color='"+color+'\''+ |
| 82 | + '}'; |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + private static class Rule { |
| 87 | + public String leftColor, rightColor; |
| 88 | + |
| 89 | + public Rule(String l,String r){ |
| 90 | + this.leftColor = l;this.rightColor = r; |
| 91 | + } |
| 92 | + } |
| 93 | +} |
0 commit comments