A run is a sequence of adjacent repeated values. Write a program that generates
ID: 3870348 • Letter: A
Question
A run is a sequence of adjacent repeated values. Write a program 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 1
its gotta use these methods
public class Sequence
{
private int[] values;
private int size;
public Sequence(int capacity)
{
values = new int[capacity];
size = 0;
}
public void add(int value)
{
if (size < values.length)
{
values[size] = value;
size++;
}
}
/**
* Returns the string of values, with runs enclosed in parentheses.
* @return the string of values with the runs marked
* for example "1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 3 1"
*/
public String markRuns()
{
//your code here
}
Explanation / Answer
Please find my implementation.
import java.util.Random;
public class Sequence
{
private int[] values;
private int size;
public Sequence(int capacity)
{
values = new int[capacity];
size = 0;
}
public void add(int value)
{
if (size < values.length)
{
values[size] = value;
size++;
}
}
/**
* Returns the string of values, with runs enclosed in parentheses.
* @return the string of values with the runs marked
* for example "1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 3 1"
*/
public String markRuns()
{
//your code here
Random random = new Random();
for(int i=0; i<values.length; i++) {
int rand = random.nextInt(6)+1;
add(rand);
}
String str = "";
boolean isDup = false;
// iterating over array
for(int i=0; i<values.length-1; i++) {
// if two consequtive numbers are same and this is the first number in sequence
if(values[i] == values[i+1] && !isDup) {
str = str + "("+values[i]+" ";
isDup = true;
}else {
if(isDup) {
str = str + +values[i] + ") ";
isDup = false;
}else
str = str + values[i]+" ";
}
}
return str;
}
public static void main(String[] args) {
Sequence seq = new Sequence(20);
System.out.println(seq.markRuns());
}
}
/*
Sample run:
2 6 4 3 2 5 2 5 (6 6) 2 4 1 (3 3) 5 1 (3 3)
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.