Skip to content

Instantly share code, notes, and snippets.

@eliblaney
Created February 24, 2019 18:24
Show Gist options
  • Save eliblaney/d5fb85dd49720823e7715aaab6bc7125 to your computer and use it in GitHub Desktop.
Save eliblaney/d5fb85dd49720823e7715aaab6bc7125 to your computer and use it in GitHub Desktop.
LookAndSay sequence implementation in Java
package com.eliblaney.lookandsay;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LookAndSay {
// Usage: [total]
public static void main(String... args) {
int total = 10;
try {
if(args.length > 0)
total = Integer.parseInt(args[0]);
} catch(NumberFormatException e) {
System.err.println("Argument 1 must be an integer: [total]");
return;
}
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader r = new BufferedReader(ir);
System.out.print("First number: ");
String num = null;
do {
if(num != null) {
System.out.print("Invalid number, please type a number: ");
main(args);
}
try {
num = r.readLine();
} catch(IOException e) {
System.err.println("Could not read input");
e.printStackTrace();
return;
}
} while(!num.matches("^\\d+$"));
System.out.println(num);
LookAndSay sequence = new LookAndSay(num);
for(int i = 0; i < total; i++) {
System.out.println(sequence.next());
}
try {
r.close();
ir.close();
} catch(IOException e) {
System.err.println("Could not close readers");
e.printStackTrace();
}
}
private String num;
public LookAndSay(String start) {
this.num = start;
}
public String next() {
String ret = "";
char n = '*';
int count = 1;
for(char c : this.num.toCharArray()) {
if(c == n)
count++;
else {
ret += count + "" + n;
n = c;
count = 1;
}
}
ret = (ret + count + "" + n).substring(2);
return this.num = ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment