Skip to content

Instantly share code, notes, and snippets.

@tsprates
Last active March 17, 2022 21:20
Show Gist options
  • Save tsprates/7c6db08ac83991851f86 to your computer and use it in GitHub Desktop.
Save tsprates/7c6db08ac83991851f86 to your computer and use it in GitHub Desktop.
ConwaySequence or Look-and-say sequence. http://en.wikipedia.org/wiki/Look-and-say_sequence
/**
* Conway Sequence
*
* @see http://en.wikipedia.org/wiki/Look-and-say_sequence
* @author Thiago Prates
*/
public class ConwaySequence {
/**
* Generate a element at position n according to *Conway Sequence*.
*
* @param long n Position in the sequence.
* @return long Element at position supplied by user.
*/
public static String get(long n) {
if (n < 0) {
throw new IllegalArgumentException();
}
StringBuilder s = new StringBuilder("1");
StringBuilder ret = new StringBuilder();
char currentNumber;
long num;
while (n > 0) {
for (int i = 0, len = s.length(); i < len;) {
currentNumber = s.charAt(i);
num = 1;
for (int j = i + 1; j < len && currentNumber == s.charAt(j); j++) {
num++;
}
ret.append(num).append(currentNumber);
i += num;
}
s = ret;
ret = new StringBuilder();
n--;
}
return s.toString();
}
public static void main(String[] args) {
System.out.println(ConwaySequence.get(Long.parseLong(args[0])));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment