Dec. 5th, 2008
slideshow: amazing javascript
Dec. 5th, 2008 10:45 amhere
I spent years trying to grok js. Now I feel like I eventually got it. It is a wild, beautiful language. It is not very powerful, since it does not have arrays and sets; but you can implement in it much more than you'd expect.
I spent years trying to grok js. Now I feel like I eventually got it. It is a wild, beautiful language. It is not very powerful, since it does not have arrays and sets; but you can implement in it much more than you'd expect.
Вот это вот решение неправильное:
Really? So simple? Or am I missing something? (Have not written unittests yet).
public static <X> Set<Set<X>> factor(Set<X> s, BinaryRelationship<X, X> r) { Map<X, Set<X>> elementToCongruenceClass = new HashMap<X, Set<X>>(); for (X x : s) { elementToCongruenceClass.put(x, Set(x)); } for (X x1 : s) for (X x2 : s) { if (r.eval(x1, x2) || r.eval(x2, x1)) { Set<X> merged = elementToCongruenceClass.get(x1); merged.addAll(elementToCongruenceClass.get(x2)); elementToCongruenceClass.put(x2, merged); } } return Set(elementToCongruenceClass.values()); }
Really? So simple? Or am I missing something? (Have not written unittests yet).
а вот это фактормножество правильное:
Dec. 5th, 2008 11:46 pmpublic static <X> Set<Set<X>> factor(Set<X> s, BinaryRelationship<X, X> r) { Map<X, Set<X>> equivalenceClasses = new HashMap<X, Set<X>>(); for (X x : s) { equivalenceClasses.put(x, Set(x)); } for (X x1 : s) for (X x2 : s) { if (x1 == x2) continue; // skip same value if (equivalenceClasses.get(x1) == equivalenceClasses.get(x2)) continue; // skip same class if (r.eval(x1, x2) || r.eval(x2, x1)) { Set<X> class1 = equivalenceClasses.get(x1); Set<X> class2 = equivalenceClasses.get(x2); Set<X> merged = new HashSet<X>(class1); merged.addAll(class2); for (X x3 : >merged) { equivalenceClasses.put(x3, merged); } } } return new HashSet<Set<X>>(equivalenceClasses.values()); }
Вот пример:
Set<Integer> set = Set(1, 2, 3, 4, 5); Set<Set<Integer>> expected = new HashSet(); expected.add(Set(1, 2, 3, 4, 5)); Set<Set<Integer>> actual = factor(set, new BinaryRelationship<Integer, Integer>() { public boolean eval(Pair<Integer, Integer> p) { return (p.x() >= 3 && p.x() - 1 == p.y()) || (p.x() <= 3 && p.x() + 1 == p.y()); } }); assertEquals(expected, actual);