Skip to content

Instantly share code, notes, and snippets.

@rxnlabs
Created July 16, 2015 15:47
Show Gist options
  • Save rxnlabs/5052b7d444fa9f939cc1 to your computer and use it in GitHub Desktop.
Save rxnlabs/5052b7d444fa9f939cc1 to your computer and use it in GitHub Desktop.
Programming interview question
<?php
/*
Output a list of numbers multiple times depending on their value (e.g. output 9 nine times, or 18 eighteen times). Works well if it doesn't matter if you listall the numbers preceding the last number
*/
$array = array(1,2,3,4,5,6,7,8,9,12,18);
foreach ($array as $num) {
$string = '';
$count = 1 * $num;
for ($i=0;$i < $count; $i++) {
$string .= (string)$num;
}
echo $string.PHP_EOL;
}
exit;
<?php
/*
Output a list of numbers multiple times depending on their value and the numbers that precede the last number (e.g. output 9 nine times but also output 8 eight times, 7 seven times, etc...).
*/
$num = 9;
if ($num > 1) {
$count = $num - ($num - 1);
} else {
$count = 0;
}
for ($count;$count <= $num; $count++) {
$string = '';
for ($i=0; $i < $count; $i++) {
$string .= $count;
}
echo $string.PHP_EOL;
}
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment