PHP look-and-say sequence - php

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.

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;
}

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;
}

Related

How can I achieve this in php string to bbbvvvvzzxxc => 3v4v2z2xc

How can I achieve php char count with php :
input : bbbvvvvzzxxc
output : 3b4v2z2xc
I try this code :
$str = "aabbbccaaaac";
$arr1 = str_split($str);
$count=1;
foreach($arr1 as $key=>$char) {
if($key==0){
$pre=$char;
}
if($pre==$char){
$count++;
} else{
$count=1;
$pre=$char;
}
echo $pre.'---'.$char.'__';
if($pre != $char){
echo $char. $count ;
} else {
// echo $char;
}
}
but not working :
its simple to set count of character
$str = "aabbbccaaaac";
$arr1 = str_split($str);
$count=0;
$pre = '';
$result = ''; // our result string
foreach($arr1 as $char){
if($char == $pre){
$count++;
}else{
if($count > 0){ // To check whether it was the first iteration
$result .= $count.$pre;
}
$count = 1;
$pre = $char;
}
}
$result .= $count.$pre; // For last iteration
echo $result;

Printing prime numbers from an user's input php

I'm trying ta make a program that will ask the user for a number and then show all the prime numbers between 0 to this number in an array.
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
function isPrime($n)
{
if ($n <= 1)
return false;
for ($i = 2; $i < $n; $i++)
if ($n % $i == 0)
return false;
return true;
}
function printPrime($n)
{
for ($i = 2; $i <= $n; $i++)
{
if (isPrime($i))
echo $i . " ";
}
}
$n = 7;
printPrime($n);
/*end of your code here */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This code work, but with a $n fixed.
I don't know how to use an input who ask the user a number
It's a code who verify itself and show us when it's ok
The code that i have to complete is this one (we only have this at first):
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This is your script:
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
function isPrime($n) {
if ($n <= 1) return false;
for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return false;
return true;
}
function printPrime($n) {
for ($i = 2; $i < $n; $i++) if (isPrime($i)) $result[] = $i;
return $result;
}
$result = printPrime($smaller_than);
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
function getSmallerPrimes($smaller_than) {
if ($smaller_than <= 2) {
return [];
}
$result = [2];
$sqrt = sqrt($smaller_than);
for ($n = 3; $n < $smaller_than; $n += 2) {
$isPrime = true;
foreach($result as $prime) {
if ($n % $prime == 0) {
$isPrime = false;
break;
}
if ($prime > $sqrt) {
break;
}
}
if ($isPrime) {
$result[] = $n;
}
}
return $result;
}
$input = 23;
echo implode(' ', getSmallerPrimes($input));
Result: 2 3 5 7 11 13 17 19

how to use the for loop to extract data from a list of url using php

The for loop in the code below does not work properly.
$html= #file_get_html($url);
$job_array = array();
foreach($html->find('a') as $link) {
// $links=$html->find('a');
if (strpos($link->href, '/job-category/') !== false) {
$job_array[] = $link->href . "<br/>";
}
for ($a = 0; $a <= ($link->href); $a++) {
//$page_number = 20;
// for ($i = 1; $i <= $page_number; $i++) {
$html2 = file_get_html($link->href);
$response = array();
foreach ($html2->find('div#mainContent') as $header) {
$response[] = $header->innertext . "<br/>";
print_r($response);
}
}
I think
$link->href
isn't a number and the for loop can't use a non-number to compare $a to and iterate over. Perhaps you can do:
$html= #file_get_html($url);
$job_array = array();
$myNumberToIterateWith = 0;
foreach($html->find('a') as $link) {
// $links=$html->find('a');
$myNumberToIterateWith++;
if (strpos($link->href, '/job-category/') !== false) {
$job_array[] = $link->href . " ";
}
for ($a = 0; $a <= $myNumberToIterateWith; $a++) {
//$page_number = 20;
// for ($i = 1; $i <= $page_number; $i++) {
$html2 = file_get_html($link->href);
$response = array();
foreach ($html2->find('div#mainContent') as $header) {
$response[] = $header->innertext . "<br/>";
print_r($response);
}
}
Though I'm not sure what you wish the result to be. It is helpful to provide clues as to what you wish to accomplish with the code.

Comma separated string to parent child relationship array php

I have a comma separated string like
$str = "word1,word2,word3";
And i want to make a parent child relationship array from it.
Here is an example:
Try this simply making own function as
$str = "word1,word2,word3";
$res = [];
function makeNested($arr) {
if(count($arr)<2)
return $arr;
$key = array_shift($arr);
return array($key => makeNested($arr));
}
print_r(makeNested(explode(',', $str)));
Demo
function tooLazyToCode($string)
{
$structure = null;
foreach (array_reverse(explode(',', $string)) as $part) {
$structure = ($structure == null) ? $part : array($part => $structure);
}
return $structure;
}
Please check below code it will take half of the time of the above answers:
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
$result = array($arr[$i] => $result);
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
Here is another code for you, it will give you result as you have asked :
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
if($i == 0){
$result = array($arr[$i] => $result);
}else{
$result = array(array($arr[$i] => $result));
}
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';

PHP strings concatenation

My code cycles through a CSV file, converting it to XML:
<?php
for ($i = 1; $i < $arraySize; $i++) {
$n = 0;
if (substr($csv[$i][0], 0, 1) == $let) {
$surName = $dom->createElement('name');
$name = $csv[$i][0];
$nameText = $dom->createTextNode($name);
$surName->appendChild($nameText);
$text = str_replace(chr(94), ",", $csv[$i][4]);
$n = $i + 1;
$next = $csv[$n][0];
while ($next == 'NULL') {
$repl = str_replace(chr(94), ",", $csv[$n][4]);
$text = $repl;
$n++;
$next = $csv[$n][0];
}
$bio = $dom->createElement('bio');
$bioText = $dom->createTextNode($text);
$bio->appendChild($bioText);
$person = $dom->createElement('person');
$person->appendChild($surName);
$person->appendChild($bio);
$people->appendChild($person);
}
}
$xmlString = $dom->saveXML();
echo $xmlString;
?>
The problem is the $text = $repl; Typing $text .= $repl; brings:
error on line 1 at column 1: Document is empty.
but omitting the . just gives the last line of text.
the backup code works:
public function test($let){
$csv = $this->readCSV("data\AlphaIndex1M.csv");
$arraySize=sizeof($csv);
$let = strtoupper($let);
//echo '';
for($i=1; $i
echo $csv[$i][0];// .'
echo ', -->'.$csv[$i][4];
$n = $i+1;
$next = $csv[$n][0];
//if($next == 'NULL'){ }
while($next == 'NULL'){
echo $csv[$n][4]. " ";
$n++;
$next=$csv[$n][0];
}
//echo ''
echo '';
}
}
//echo ''
}
You have to initialize your $text before you can append stuff!
So write this before you use it:
$test = "";
(before the while loop or even before the for loop if you want all to be appended)

Categories