I have code that finds the runs in a random set of integers and surrounds them w
ID: 3664659 • Letter: I
Question
I have code that finds the runs in a random set of integers and surrounds them with parens. It is a little messed up though because if a run is at the end like 547(887) it puts the paren around the last number as well as the ones in the run. Can you fix this for me?
Thanks
import java.util.Random;
public class Run
{
public static void main(String[] arg)
{
int [] die = new int [20];
Random rand = new Random();
for (int i = 0; i < die.length; i++) {
die[i] = rand.nextInt(6) + 1;
}
boolean inRun = false;
for (int i = 0; i < die.length - 1; i++) {
if (inRun) {
if (die[1] != die[i - 1]) {
System.out.print(")");
inRun = false;
}
}
if (!inRun) {
if (die[i] == die[i +1]){
System.out.print("(");
inRun = true;
}
System.out.print(die[i]);
}
}
if (inRun) {
System.out.print(die[die.length - 1]);
System.out.print(")");
}
else {
System.out.print(die[die.length - 1]);
}
}
}
Explanation / Answer
import java.util.Random;
public class Run
{
public static void main(String[] arg)
{
int [] die = new int [20];
Random rand = new Random();
for (int i = 0; i < die.length; i++)
{
die[i] = rand.nextInt(6) + 1;
System.out.println(die[i]);
}
boolean inRun = false;
for (int i = 0; i < die.length - 1; i++)
{
if (inRun)
{
System.out.print(")");
inRun = false;
}
if (!inRun)
{
System.out.print("(");
inRun = true;
System.out.print(die[i]);
}
}
if (inRun)
{
System.out.print(die[die.length - 1]);
System.out.print(")");
}
else
{
System.out.print(die[die.length - 1]);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.