Question

Write a complete recursive java program to compute the heights of the tick marks on a...

Write a complete recursive java program to compute the heights of the tick marks on a ruler. Assume that the length of the ruler is a power of 2 (say L=2^n, where n >=1) , and the marks are to be placed at every point between 0 and 2^n, not including the endpoints.

The endpoints 0 and 2^n will have height 0. Here are the rules for computing the heights of the ticks for a ruler of length L=2^n:

1. The middle point of the ruler has height log(L), where the logarithm is base 2. Stop if L <= 2.

2. Break the ruler into two equal halves of length L/2 each and set L=L/2

3. Repeat step 1 for both halves resulting from step 2.

You may use an array of the appropriate size to hold the heights.

When printing your output, print the heights on one line, and the position of the points below. For the printing of the positions of the points, just print the last digit of the position. Here is an example for n=8. 012131210 012345678

Here is an example for n=16. 01213121412131210 01234567890123456

Your program should prompt the user for an integer, check to make sure the length entered by the user is a power of 2 and at least 2.

To check if a number is a power of 2, you need the Math.log and Math.round methods. Be careful that the Math.log routine in Java is base e (not base 2).

You will need to do the appropriate conversion between base 2 and base .

Finally, your program should print the heights of the ruler's points as illustrated above.

Homework Answers

Answer #1

ANSWER:

  • I have provided the properly commented code in both text and image format so you can easily copy the code as well as check for correct indentation.
  • I have provided the output image of the code so you can easily cross-check for the correct output of the code.
  • Have a nice and healthy day!!

CODE TEXT

import java.util.*;

public class Main
{
// recursive function rulerRec, output String
public static String rulerRec(int L){
// base rule if L<=2
if(L<=2){
return "1";
}
// otherwise
// finding center height, Log2(L)
int center = (int)(Math.log(L) / Math.log(2));
  
// breaking L into half
int breakL = L/2;
// calling ruler function for left portions
String left = rulerRec(L/2);
// calling ruler function for right portions
String right = rulerRec(L/2);
  
// combining center,left and right value
String result = left+center+right;
  
// returning result
return result;
}
  
   public static void main(String[] args) {
  
   // prompting user to enter appropriate Length
   System.out.print("Please enter height of Ruler, equals (2^n):");
   // defining scanner object
   Scanner sc = new Scanner(System.in);
   // scanning input
   int L = sc.nextInt();
  
   // checking if L in form 2^n
   if ((Math.log(L) / Math.log(2)) != (int)(Math.log(L) / Math.log(2))){
   System.out.print("L not equals (2^n)!!");
   return;
   }
  
   // otherwise, calling recusrsive function
   String result = rulerRec(L);
   // adding 0 in last and first for height 0 and L
   String heights = "0"+result+"0";
  
   // defining position string
   String posString = "";
   for(int i=0;i<=L;i++){
   String stri= ""+ i;
   posString += stri.charAt(stri.length() - 1);
   }
  
   // displaying results
       System.out.println(heights);
       System.out.println(posString);
   }
}

CODE IMAGE

OUTPUT IMAGE

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
(Use Java ) please write comment on every line I need to understand the code Problem...
(Use Java ) please write comment on every line I need to understand the code Problem Description: Write a program that prompts the user to enter a point (x, y) and checks whether the point is within the rectangle centered at (0, 0) with width 10 and height 5. For example, (2, 2) is inside the rectangle and (6, 4) is outside the rectangle, as shown in the Figure. (Hint: A point is in the rectangle if its horizontal distance...
Java Program Implement a class called AnimalTrainer. Include the following data types in your class with...
Java Program Implement a class called AnimalTrainer. Include the following data types in your class with the default values denoted by dataType name : defaultValue - String animal : empty string - int lapsRan : 0 - boolean resting : false - boolean eating : false - double energy : 100.00 For the animal property implement both getter/setter methods. For all other properties implement ONLY a getter method Now implement the following constructors: 1. Constructor 1 – accepts a String...
In this lab, you will write a program that creates a binary search tree based on...
In this lab, you will write a program that creates a binary search tree based on user input. Then, the user will indicate what order to print the values in. **Please write in C code** Start with the bst.h and bst.c base code provided to you. You will need to modify the source and header file to complete this lab. bst.h: #ifndef BST_H #define BST_H typedef struct BSTNode { int value; struct BSTNode* left; struct BSTNode* right; } BSTNode; BSTNode*...
Project 2 statement Please write this in JAVA. Please read this entire statement carefully before you...
Project 2 statement Please write this in JAVA. Please read this entire statement carefully before you start doing anything… This project involves implementing a simple university personnel management program. The program contains two different kinds of objects: students and faculty. For each object, the program stores relevant information such as university ID, name, etc. Different information is stored depending on the type of the object. For example, a student has a GPA, while a faculty has a title and department...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code to initialize the CustomerAccountsDB database table and add a set of customer accounts is provided. Finish the code in these 3 methods in CustomerAccountDB.java to update or query the database: -purchase(double amountOfPurchase) -payment(double amountOfPayment) -getCustomerName() Hint: For getCustomerName(), look at the getAccountBalance() method to see an example of querying data from the database. For the purchase() and payment() methods, look at the addCustomerAccount() method...
Note: Do not use classes or any variables of type string to complete this assignment Write...
Note: Do not use classes or any variables of type string to complete this assignment Write a program that reads in a sequence of characters entered by the user and terminated by a period ('.'). Your program should allow the user to enter multiple lines of input by pressing the enter key at the end of each line. The program should print out a frequency table, sorted in decreasing order by number of occurences, listing each letter that ocurred along...
Write a program of wordSearch puzzle that use the following text file as an input. The...
Write a program of wordSearch puzzle that use the following text file as an input. The output should be like this: PIXEL found (left) at (0,9). ( Use JAVA Array ) .Please do not use arrylist and the likes! Hints • The puzzle can be represented as a right-sized two-dimensional array of characters (char). • A String can be converted into a right-sized array of characters via the String method toCharArray. . A word can occur in any of 8...
please write the code in java so it can run on jGRASP import java.util.Scanner; 2 import...
please write the code in java so it can run on jGRASP import java.util.Scanner; 2 import java.io.*; //This imports input and output (io) classes that we use 3 //to read and write to files. The * is the wildcard that will 4 //make all of the io classes available if I need them 5 //It saves me from having to import each io class separately. 6 /** 7 This program reads numbers from a file, calculates the 8 mean (average)...
In java create a dice game called sequences also known as straight shooter. Each player in...
In java create a dice game called sequences also known as straight shooter. Each player in turn rolls SIX dice and scores points for any sequence of CONSECUTIVE numbers thrown beginning with 1. In the event of two or more of the same number being rolled only one counts. However, a throw that contains three 1's cancels out player's score and they mst start from 0. A total of scores is kept and the first player to reach 100 points,...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called keys with other objects called values. It is implemented as a Java class that uses arrays internally. 1. Theory. A map is a set of key-value pairs. Each key is said to be associated with its corresponding value, so there is at most one pair in the set with a given key. You can perform the following operations on maps. You can test if...