yny.all
BAN USERBFS Java Elegant solution
import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class Tree001 {
@Value // Lombok: produce all getters
@RequiredArgsConstructor
// Lombok: produce Node(x,y,Collection<Node>)
class Node {
public Node(int x, int y) {
this(x, y, new ArrayList<>());
}
private final int x, y;
private final Collection<Node> nodes;
}
public boolean find(Node root, int x, int y) {
return find(Arrays.asList(root), x, y);
}
public boolean find(Collection<Node> nodes, int x, int y) {
if (nodes.isEmpty()) return false;
Set<Integer> xSet = nodes.stream().map(Node::getX).collect(Collectors.toSet());
Set<Integer> ySet = nodes.stream().map(Node::getY).collect(Collectors.toSet());
if (xSet.contains(x) && ySet.contains(y)) return true;
return find(nodes.stream().flatMap(n -> n.getNodes().stream()).collect(Collectors.toList()), x, y);
}
@Test
public void test() {
Node root = new Node(1, 120, Arrays.asList(
new Node(5, 15, Arrays.asList(
new Node(35, 40),
new Node(45, 50),
new Node(55, 65))),
new Node(30, 70, Arrays.asList(
new Node(90, 100))),
new Node(80, 110)));
assertThat(find(root, 45, 100), is(Boolean.TRUE));
assertThat(find(root, 30, 100), is(Boolean.FALSE));
assertThat(find(root, 30, 70), is(Boolean.TRUE));
assertThat(find(root, 70, 30), is(Boolean.FALSE));
}
}
RepCliftonMalone, Android Engineer at ABC TECH SUPPORT
Hello, I am a Seo Analyst with 5 years of experience in helping large ecommerce websites reach higher organic positions ...
RepEzraDavis, abc at A9
I am a hardworking and disciplined newly-certified architect with internship experience in designing commercial buildings and creating accurate 2D and ...
Repsylviatobins, Applications Developer at 247quickbookshelp
Hi, I am Sylvia Law librarian. I am an information resource expert. I work in law schools, corporate law departments ...
- yny.all March 09, 2016