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.
ANSWER:
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
Get Answers For Free
Most questions answered within 1 hours.