Activity 2. Say It Out Loud sequence. In this activity, given the first number o
ID: 3683417 • Letter: A
Question
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
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);
}
}
// helper function of SayItOutLoud
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);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.