Write a complete recursive java program to compute the heights of the tick marks
ID: 3876024 • Letter: W
Question
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 n=2m, where m >=1) , and the marks are to be placed at every point between 0 and 2m, not including the endpoints. The endpoints 0 and 2m will have height 0. Here are the rules for computing the heights of the ticks for a ruler of length n=2m:
The middle point of the ruler has height log(n), where the logarithm is base 2. Stop if n <= 2.
Break the ruler into two equal halves of length n/2 each and set n=n/2
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 input value n=8.
012131210
012345678
Here is an example for input value n=16.
01213121412131210
01234567890123456
Your program should prompt the user for an integer (using a dialog box), 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 e. Finally, your program should print the heights of the ruler's points as illustrated above.
Explanation / Answer
As per your requirement the below one is solution please follow it and for our comfort assuming L as n and another m as n
public static void fun(int l)
{
// 1. The middle point of the ruler has height log(L), where the logarithm is base 2. Stop if L <= 2.
// actually stop when L is 1, so we can print 1
if(l < 2)
return;
// 2. Break the ruler into two equal halves of length L/2 each and set L=L/2
int l2 = l/2;
// 3. Repeat step 1 for both halves resulting from step 2.
fun(l2);
// print this tick mark
// For the printing of the positions of the points, just print the last digit of the position.
System.out.print(((int)(Math.log(l)/Math.log(2)))%10);
// print upper tick marks
fun(l2);
}
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter L: ");
int l = kb.nextInt();
// check if l is a power of 2
if(Math.log(l)/Math.log(2) ==Math.floor(Math.log(l)/Math.log(2)))
{
// print 0 marks at either side
System.out.print("0");
fun(l);
System.out.print("0");
System.out.println();
// now print scale
for(int i = 0; i <= l; i++)
System.out.print(i%10);
System.out.println();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.