In: Computer Science
*****IN JAVA*****
A run is a sequence of adjacent repeated values. Write a code snippet that generates a sequence of 20 random die tosses in an array and that prints the die values, marking the runs by including them in parentheses, like this:
1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 (3 3)
Use the following pseudocode:
inRun = false
for each valid index i in the array
If inRun
If values [i] is different from the preceding value
Print )
inRun = false
If not inRun
If values[i] is the same as the following value
Print (
inRun = true
Print values[i]
//special processing to print last value
If inRun and last value == previous value, print “ “ + value + “)”)
else if inRun and last value != previous value, print “) “ + value )
else print “ “ + last value
Solution:
I have used the given pseudocode.
I also added some changes for formatted printing and removing exceptions.
Code:
import java.util.*;
public class Run
{
public static void main(String[] args)
{
int i;
Random rand = new Random();
int[] die = new int[20];
for (i = 0; i < die.length; i++)
die[i] = rand.nextInt(6)+1;
boolean inRun = false;
for (i = 0; i < die.length-1; i++)
{
if(inRun)
{
if( i>0 && die[i]!=die[i-1])
{
System.out.print(")");
inRun = false;
}
else
System.out.print(" ");
}
if(!inRun)
{
if(i>0)
System.out.print(" ");
if(die[i]==die[i+1])
{
System.out.print("(");
inRun = true;
}
}
System.out.print(die[i]);
}
if(inRun && die[die.length-1] == die[die.length-2])
{
System.out.print(" "+ die[die.length-1] + ")");
}
else if(inRun && die[die.length-1] != die[die.length-2])
{
System.out.print(")"+ die[die.length-1]);
}
else
{
System.out.print(" " + die[die.length-1]);
}
}
}
Output of 5 random runs:
Note:Each line is an output of seperate runs.
1 2 6 1 (4 4 4) 6 4 2 3 1 (4 4) 6 2 (5 5) 2 1
3 6 1 (3 3) 1 5 2 5 2 1 (3 3) (2 2) 3 1 2 (3 3)
1 (2 2) 1 5 4 5 1 5 3 4 6 4 2 3 (1 1) 6 4 1
3 1 (5 5 5 5 5) 2 4 1 5 4 2 3 6 (3 3) 2 6 1
6 (4 4) 5 1 5 2 (1 1 1 1) (3 3) 4 5 1 4 (1 1)4