DEV Community

Xavier Chretien
Xavier Chretien

Posted on

Day 4: Look and say

Let's go for day 4! Finally posting every day is really pleasant! I wanted to thank you who are reading this and a big thank you for your comments on the previous posts 😃

Now let's place the problem of the day!

Details

  • Difficulty: Medium
  • Asked by: Epic

Problem

The "look and say" sequence is defined as follows: beginning with the term 1 each subsequent term
visually describes the digits appearing in the previous term. The first few terms are as follows:

1
11
21
1211
111221
Enter fullscreen mode Exit fullscreen mode

As an example, the fourth term is 1211, since the third term consists of one 2 and one 1.

Given an integer N, print the Nth term of this sequence.

My solution

I have to say this one took a moment to understand. After some research, I gave up trying to find a solution to determine the Nth term with some magic mathematics finally, I just determine all the terms until N. Not the best solution I agree.

/**
 * Determine the nth term of the "look and say" sequence
 *
 * @param n, index of the term we want, must be positive
 * @return the nth "look and say" term
 */
fun lookAndSayAt(n: Int): String {
    if(n < 1) return ""
    else if(n == 1) return "1"

    var scanningTerm = "1"

    for (i in 1 until n) {
        var currentTerm = ""

        var currentValue = scanningTerm[0]
        var numberOfCurrentValue = 1
        for (c in scanningTerm.substring(1)) {
            if (c == currentValue)
                numberOfCurrentValue++
            else {
                currentTerm += "$numberOfCurrentValue$currentValue"
                currentValue = c
                numberOfCurrentValue = 1
            }
        }
        currentTerm += "$numberOfCurrentValue$currentValue"
        scanningTerm = currentTerm
    }
    return scanningTerm
}
Enter fullscreen mode Exit fullscreen mode

So do you have another solution? 😃

Top comments (1)

Collapse
 
rodiongork profile image
Rodion Gorkovenko

Sorry for intervention, just noticed familiar problem :) Regretfully it is bit too well known and a number of ready solutions could be found on the web...

There is modification of the problem - Binary Look and Say which, instead of growing, decreases by and by. So it makes curious question - to count when the sequence boils down to small loop. Straightforward solution may be inefficient for long values and sequences...