Java Visitor Pattern Hacker Rank Solution

Hello coders, In this post, you will learn how to solve Java Visitor Pattern Hacker Rank Solution. This problem is a part of the Java programming series. One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions.

We also provide Hackerrank solutions in CC++Java programming, and Python Programming languages so whatever your domain we will give you an answer in your field.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

Java Visitor Pattern Hacker Rank Solution
Java Visitor Pattern – Hacker Rank Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

Java Visitor Pattern Hacker Rank Solution

Objective

Note: In this problem you must NOT generate any output on your own. Any such solution will be considered as being against the rules and its author will be disqualified. The output of your solution must be generated by the uneditable code provided for you in the solution template.

An important concept in Object-Oriented Programming is the open/closed principle, which means writing code that is open to extension but closed to modification. In other words, new functionality should be added by writing an extension for the existing code rather than modifying it and potentially breaking other code that uses it. This challenge simulates a real-life problem where the open/closed principle can and should be applied.

Tree class implementing a rooted tree is provided in the editor. It has the following publicly available methods:

  • getValue(): Returns the value stored in the node.
  • getColor(): Returns the color of the node.
  • getDepth(): Returns the depth of the node. Recall that the depth of a node is the number of edges between the node and the tree’s root, so the tree’s root has depth  and each descendant node’s depth is equal to the depth of its parent node .

In this challenge, we treat the internal implementation of the tree as being closed to modification, so we cannot directly modify it; however, as with real-world situations, the implementation is written in such a way that it allows external classes to extend and build upon its functionality. More specifically, it allows objects of the TreeVis class (a Visitor Design Pattern) to visit the tree and traverse the tree structure via the accept method.

There are two parts to this challenge.

Part I: Implement Three Different Visitors

Each class has three methods you must write implementations for:

  1. getResult(): Return an integer denoting the , which is different for each class:
    • The SumInLeavesVisitor implementation must return the sum of the values in the tree’s leaves only.
    • The ProductRedNodesVisitor implementation must return the product of values stored in all red nodes, including leaves, computed modulo . Note that the product of zero values is equal to .
    • The FancyVisitor implementation must return the absolute difference between the sum of values stored in the tree’s non-leaf nodes at even depth and the sum of values stored in the tree’s green leaf nodes. Recall that zero is an even number.
  2. visitNode(TreeNode node): Implement the logic responsible for visiting the tree’s non-leaf nodes such that the getResult method returns the correct  for the implementing class’ visitor.
  3. visitLeaf(TreeLeaf leaf): Implement the logic responsible for visiting the tree’s leaf nodes such that the getResult method returns the correct  for the implementing class’ visitor.

Part II: Read and Build the Tree

Read the -node tree, where each node is numbered from  to . The tree is given as a list of node values (), a list of node colors (), and a list of edges. Construct this tree as an instance of the Tree class. The tree is always rooted at node number .

Your implementations of the three visitor classes will be tested on the tree you built from the given input.

Input Format

The first line contains a single integer, , denoting the number of nodes in the tree. The second line contains  space-separated integers describing the respective values of .
The third line contains  space-separated binary integers describing the respective values of . Each  denotes the color of the  node, where  denotes red and  denotes green.
Each of the  subsequent lines contains two space-separated integers,  and , describing an edge between nodes  and .

Constraints

  • It is guaranteed that the tree is rooted at node .

Output Format

Do not print anything to stdout, as this is handled by locked stub code in the editor. The three getResult() methods provided for you must return an integer denoting the  for that class’ visitor (defined above). Note that the value returned by ProductRedNodesVisitor‘s getResult method must be computed modulo .

Sample Input

5
4 7 2 5 12
0 1 0 0 1
1 2
1 3
3 4
3 5

Sample Output

24
40
15

Explanation

Java Visitor Pattern Hacker Rank Solution

Locked stub code in the editor tests your three class implementations as follows:

  1. Creates a SumInLeavesVisitor object whose getResult method returns the sum of the leaves in the tree, which is . The locked stub code prints the returned value on a new line.
  2. Creates a ProductOfRedNodesVisitor object whose getResult method returns the product of the red nodes, which is . The locked stub code prints the returned value on a new line.
  3. Creates a FancyVisitor object whose getResult method returns the absolute difference between the sum of the values of non-leaf nodes at even depth and the sum of the values of green leaf nodes, which is . The locked stub code prints the returned value on a new line.


Java Visitor Pattern Hacker Rank Solution

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
enum Color {
	RED, GREEN
}
abstract class Tree {
	private int value;
	private Color color;
	private int depth;
	public Tree(int value, Color color, int depth) {
		this.value = value;
		this.color = color;
		this.depth = depth;
	}
	public int getValue() {
		return value;
	}
	public Color getColor() {
		return color;
	}
	public int getDepth() {
		return depth;
	}
	public abstract void accept(TreeVis visitor);
}
class TreeNode extends Tree {
	private ArrayList<Tree> children = new ArrayList<>();
	public TreeNode(int value, Color color, int depth) {
		super(value, color, depth);
	}
	public void accept(TreeVis visitor) {
		visitor.visitNode(this);
		for (Tree child : children) {
			child.accept(visitor);
		}
	}
	public void addChild(Tree child) {
		children.add(child);
	}
}
class TreeLeaf extends Tree {
	public TreeLeaf(int value, Color color, int depth) {
		super(value, color, depth);
	}
	public void accept(TreeVis visitor) {
		visitor.visitLeaf(this);
	}
}
abstract class TreeVis {
	public abstract int getResult();
	public abstract void visitNode(TreeNode node);
	public abstract void visitLeaf(TreeLeaf leaf);
}
/* ---------- */
class SumInLeavesVisitor extends TreeVis{
	int result=0;
	public int getResult(){
		return result;
	}
	public void visitNode(TreeNode node){
	}
	public void visitLeaf(TreeLeaf leaf){
		result+=leaf.getValue();
	}
}
class ProductOfRedNodesVisitor extends TreeVis{
	long result=1;
	final int M=1000000007;
	public int getResult(){
		return (int)result;
	}
	public void visitNode(TreeNode node){
		if(node.getColor()==Color.RED){
			result=(result*node.getValue())%M;
		}
	}
	public void visitLeaf(TreeLeaf leaf){
		if(leaf.getColor()==Color.RED){
			result=(result * leaf.getValue())%M;
		}
	}
}
class FancyVisitor extends TreeVis{
	int even=0;
	int green=0;
	public int getResult(){
		return Math.abs(even-green);
	}
	public void visitNode(TreeNode node){
		if(node.getDepth()%2==0){
			even+=node.getValue();
		}
	}
	public void visitLeaf(TreeLeaf leaf){
		if(leaf.getColor()==Color.GREEN){
			green+=leaf.getValue();
		}
	}
}
class Solution{
	static int values[];
	static Color colors[];
	static Map<Integer, Set<Integer>> nodesMap = new HashMap<>();
	public static Tree solve(){
		Scanner in=new Scanner(System.in);
		int nnodes=in.nextInt();
		values= new int[nnodes];
		for(int i=0;i<nnodes;i++)values[i]=in.nextInt();
		colors = new Color[nnodes];
		for(int i=0;i<nnodes;i++)colors[i]=(in.nextInt()==0)?Color.RED:Color.GREEN;
		Tree rootNode;
		if(nnodes==1){
			rootNode=new TreeLeaf(values[0],colors[0],0);
		}else{
			rootNode=new TreeNode(values[0],colors[0],0);
			for(int i=0;i<(nnodes-1);i++) {
				int u = in.nextInt();
				int v = in.nextInt();
				Set<Integer> uEdges = nodesMap.get(u);
				if(uEdges==null)uEdges = new HashSet<>();
				uEdges.add(v);
				nodesMap.put(u, uEdges);
				Set<Integer> vEdges = nodesMap.get(v);
				if(vEdges==null)vEdges = new HashSet<>();
				vEdges.add(u);
				nodesMap.put(v, vEdges);
			}
			for(int nodeid:nodesMap.get(1)){
				nodesMap.get(nodeid).remove(1);
				createEdge(rootNode, nodeid);
			}
		}
		return rootNode;
	}
	private static void createEdge(Tree parent,int nodeid){
		Set<Integer> nodeEdges = nodesMap.get(nodeid);
		boolean hasChild = nodeEdges!=null && !nodeEdges.isEmpty();
		if(hasChild){
			TreeNode node = new TreeNode(values[nodeid-1],colors[nodeid-1],parent.getDepth()+1);
			((TreeNode)parent).addChild(node);
			for(int neighborid:nodeEdges){
				nodesMap.get(neighborid).remove(nodeid);
				createEdge(node, neighborid);
			}
		}else{
			TreeLeaf leaf = new TreeLeaf(values[nodeid-1],colors[nodeid-1],parent.getDepth()+1);
			((TreeNode)parent).addChild(leaf);
		}
	}
/* ---------- */
	public static void main(String[] args) {
		Tree root = solve();
		SumInLeavesVisitor vis1 = new SumInLeavesVisitor();
		ProductOfRedNodesVisitor vis2 = new ProductOfRedNodesVisitor();
		FancyVisitor vis3 = new FancyVisitor();
		root.accept(vis1);
		root.accept(vis2);
		root.accept(vis3);
		int res1 = vis1.getResult();
		int res2 = vis2.getResult();
		int res3 = vis3.getResult();
		System.out.println(res1);
	 	System.out.println(res2);
		System.out.println(res3);
	}
}

Disclaimer: The above Problem (Java Visitor Pattern ) is generated by Hackerrank but the Solution is Provided by Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.

FAQ:

1. HackerRank Java All Problems Solutions

Hackerrank java problems solutions with practical program code examples and step-by-step full complete explanation.

2. Can HackerRank learn Java?

Welcome to the world of Java! In this challenge, we practice printing to stdout. The code stubs in your editor declare a Solution class and the main method. 

3. What is HackerRank Java test?

The HackerRank Skills Certification Test is a standardized assessment to help developers prove their coding skills.

4. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

5. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite

6. Can I learn Java per month?

you can’t master it in 1 month, it needs continuous hard work and experience. JAVA is a vast language even developers don’t know fully. you go in-depth about each particular class in java. Java is such a platform which have been used in all platform like android, web, and cloud so keep working on your interest. 

Where can I find HackerRank solutions in Java?

in this post you will get all the solutions of HackerRank java Problems.

Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe.

Sharing Is Caring

Leave a Comment