Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

First Java progam- Can someone explain this algorithm + code? Im having a hardti

ID: 3857052 • Letter: F

Question

First Java progam- Can someone explain this algorithm + code? Im having a hardtime writing the code for it.

Consider the following relation: Given an integer n >4 the Collatz successors of n are defined to be: n is even AND ((n-1) mod 3 = 0) Otherwise C(n) [2 xn, (n - 1)/3) - 2×n Given an integer n > 4 the Collatz graph Gn(V,E) where V is the set of vertices of Gn, and E is the set of edges of Gn, is constructed by: 1. 2. Set n to be a vertex in V For each vertex j E V add C (n), the Collatz successor[s] of j, to V. Add the edges from j to its successors to E. It can be shown that under the assumption that the conjecture holds, and by definition of the graph, Gg(V, E) is an infinite tree that spans all the positive integers except for 1, 2, and 4. Consider the following tree construction (enumeration) algorithm: 8 and an empty queue, Q, insert n into Q I. 2. Given the integer n Do forever: a. Remove the head element from Q (assume it is the integer j) b. Print j to a file c. Insert the successor[s] of j to Q. Assignment Instructions: Your assignment is to write a Java program that implements the above algorithm using a Queue Abstract Data Type. The program terminates the tree construction after 20 iteration of the given algorithm

Explanation / Answer


import java.util.*;
import java.io.*;
public class foo1
{
  
   public static void main(String[] args) throws IOException
   {
       int n = 8;
       PrintWriter writer = new PrintWriter("tree.txt", "UTF-8");// Please change file location according to your setup
       Queue<Integer> queue = new LinkedList<>();// In-built java queue
       queue.add(n);// Insert n
       int iterations = 20;// As mentioned in problem only 20 iterations
       while(iterations > 0)
       {
           int head = queue.remove();// Remove from queue
           System.out.println("Removed node: " + head);
           writer.println(head);
           int[] succ = getSuccessor(head);
           for (int i = 0; i < succ.length; i++)
           {
               queue.add(succ[i]);//Add all successors of head to queue
           }
          
           iterations--;
       }
   }
  
   public static int[] getSuccessor(int n)
   {
       assert (n > 4);
       if (n % 2 == 0 && (n - 1) % 3 == 0)// if n is even and (n-1)mod3=0
       {
           int[] a= {2 * n, (n - 1) / 3};// 2*n, n-1/3
           return a;
       }
       else
       {
           int[] a = {2 * n};
           return a;
       }
          
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote