Labanino
Labanino

Reputation: 3960

Issues trimming last word in a loop result

I am playing with a HackerRank exercise and this should be the result:

61 then 62 then 63 then 64 then 65 then 66 then 67 then 68 then 69 then 70

but I am getting a then after the 70.

<?php

function countUp($start) {

    for ($i = 61; $i <= 70; $i++) {
        echo $i . " then ";
    }

}

$start = intval(trim(fgets(STDIN)));

countUp($start);

What am I doing wrong? Thanks.

EDIT: I tried:

echo "61"; 
for ($i = 62; $i <= 70; $i++) {
    echo " then ".$i;
}

But the test case is giving me errors:

enter image description here

In case you wanna try it: https://www.hackerrank.com/tests/ioa3k1bq

Upvotes: 1

Views: 85

Answers (4)

Mohamed Aldanaf
Mohamed Aldanaf

Reputation: 63

use like this :

<?php

function countUp($start) {

    for ($i = 61; $i <= 70; $i++) {
        $txt.= $i . " then ";
    }
  $str= preg_replace('/\W\w+\s*(\W*)$/', '$1', $txt);
  echo $str
}

$start = intval(trim(fgets(STDIN)));

countUp($start);

Upvotes: 0

Pinke Helga
Pinke Helga

Reputation: 6702

The one-liner:

echo implode(' then ', range($n = intval(file_get_contents('php://stdin')), $n+9));

Upvotes: 1

steven7mwesigwa
steven7mwesigwa

Reputation: 6730

I have read through your failed test. I hope this works for you.

<?php>

function countUp($start) {

  $FIRST_NUM = $start + 1;
  $LAST_NUM = $start + 10;

    for ($i = $FIRST_NUM; $i <= $LAST_NUM; $i++) {

        if($i == $LAST_NUM) {echo $i; break;}

        echo $i . " then ";
    }

}
$start = intval(trim(fgets(STDIN)));
countUp($start);  // try countUp(60); to test this

Upvotes: 1

Marco somefox
Marco somefox

Reputation: 368

You should check when the last number is being printed and print the number without a further "then"

for ($i = 61; $i <= 70; $i++) {
    echo $i;
    if($i <= 69)
        echo " then ";
}

Another solution could use an array to enable implode(http://php.net/manual/en/function.implode.php)

$numbs = [];
for ($i = 61; $i <= 70; $i++) {
    array_push($numbs, $i);
}
return implode(" then ", $numbs);

Upvotes: -1

Related Questions