killburn
killburn

Reputation: 83

PHP look-and-say sequence

I'm trying to code Conway look-and-say sequence in PHP. Here is my code:

function look_and_say ($number) {
    $arr = str_split($number . " ");
    $target = $arr[0];
    $count = 0;
    $res = "";
    foreach($arr as $num){
        if($num == $target){
            $count++;
        }else{
            $res .= $count . $target;
            $count = 1;
            $target = $num;
        }        
    }
    return $res;
}

As I run the function, look_and_say(9900) I am getting value I expected: 2920. My question is for assigning $arr to be $arr = str_split($number) rather than $arr = str_split($number . " "), the result omits the very last element of the $arr and return 29.

Is it normal to add empty space at the end of the $arr foreach to examine the last element or is there any better way to practice this code - besides regex way.

Upvotes: 0

Views: 629

Answers (2)

Ivan Kalita
Ivan Kalita

Reputation: 2287

I want to suggest you other way using two nested while loops:

<?php

function lookAndSay($number) {
    $digits = str_split($number);
    $result = '';
    $i = 0;
    while ($i < count($digits)) {
        $lastDigit = $digits[$i];
        $count = 0;
        while ($i < count($digits) && $lastDigit === $digits[$i]) {
            $i++;
            $count++;
        }
        $result .= $count . $lastDigit;
    }

    return $result; 
}

Upvotes: 1

mega6382
mega6382

Reputation: 9396

There are 2 methods I was able to come up with.

1 is to add concatenate at the result after the loop too.

function look_and_say ($number) {
    $arr = str_split($number);
    $target = $arr[0];
    $count = 0;
    $res = "";
    foreach($arr as $num){
        if($num == $target){
            $count++;
        }else{
            $res .= $count . $target;
            $count = 1;
            $target = $num;
        }        
    }
    $res .= $count . $target;
    return $res;
}

And the 2nd one is to add another if clause inside the loop and determine the last iteration:

function look_and_say ($number) {
    $arr = str_split($number);
    $target = $arr[0];
    $count = 0;
    $res = "";
    $i=0;
    $total = count($arr);
    foreach($arr as $num){        
        if($i == ($total-1))
        {
            $count++;
            $res .= $count . $target;
        }
        elseif($num == $target){
            $count++;
        }else{
            $res .= $count . $target;
            $count = 1;
            $target = $num;
        }
        $i++;
    }
    return $res;
}

Upvotes: 1

Related Questions