JAVA!! - Activity 2. Say It Out Loud sequence. In this activity, given the first
ID: 3681305 • Letter: J
Question
JAVA!! - Activity 2. Say It Out Loud sequence. In this activity, given the first number of a sequence (called “seed” and given as a string), you will have to generate the rest of a sequence of integers (that you will store as strings, for convenience purposes) as follows:
Each integer is obtained by reading aloud the previous integer.
For instance, if the sequence starts with “1”, then the sequence goes as follows:
“1”
which is read aloud as “one 1” à therefore the next number is “11”
“11”
which is read aloud as “two 1’s” à therefore the next number is “21”
“21”
which is read aloud as “one 2 one 1” à therefore yielding “1211”
“1211”
which is read aloud as “one 1 one 2 two 1’s” à “111221”
“111221”
which is read aloud as “three 1’s two 2’s one 1” à “312211”
“312211”
etc.
For the sake of another example, when starting with a “8”, then the sequence goes as follows:1
“8”
which is read aloud as “one 8” à “18”
“18”
which is read aloud as “one 1 one 8” à “1118”
“1118”
which is read aloud as “three 1’s one 8” à “3118”
“3118”
which is read aloud as “one 3 two 1’s one 8” à “132318”
“132118”
etc.
The method you will have to implement is called: SayItOutLoud
Parameters:
· A string – the seed; and
· A 1D array of strings – the sequence that you have to build (so you will store the sequence of integers in it, as strings)
Return type: void
Given:
public static void SayItOutLoud(String[] sequence, String seed) {
// your code goes here
}
“1”
which is read aloud as “one 1” à therefore the next number is “11”
“11”
which is read aloud as “two 1’s” à therefore the next number is “21”
“21”
which is read aloud as “one 2 one 1” à therefore yielding “1211”
“1211”
which is read aloud as “one 1 one 2 two 1’s” à “111221”
“111221”
which is read aloud as “three 1’s two 2’s one 1” à “312211”
“312211”
etc.
Explanation / Answer
public class LookAndSay {
public static void SayItOutLoud(String[] sequence, String seed) {
for (int i=0; i<sequence.length; i++) {
sequence[i] = seed;
seed = lookandsay(seed);
}
}
public static String lookandsay(String number){
StringBuilder result= new StringBuilder();
char repeat= number.charAt(0);
number= number.substring(1) + " ";
int times= 1;
for(char actual: number.toCharArray()){
if(actual != repeat){
result.append(times + "" + repeat);
times= 1;
repeat= actual;
}else{
times+= 1;
}
}
return result.toString();
}
public static void main(String[] args){
String seed = "8";
String sed[] = new String[7];
SayItOutLoud(sed, seed);
for(String s: sed)
System.out.println(s);
}
}
/*
Output:
8
18
1118
3118
132118
1113122118
311311222118
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.