How write all possible words in php? [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Generate all combinations of arbitrary alphabet up to arbitrary length
I'm trying to make write all possible words of 10 letters(zzzzzzzzzz) in php. How can I do that? it will look like that : http://i.imgur.com/sgUnL.png
I tried some ways to it but they are only making 10 letters randomly not increasing from 1 letter. By the way execution time and how it's big is not problem. i just need to algorithm for it, if somebody show it with code it'll be more helpful of course..

function words($length, $prefix='') {
if ($length == 0) return;
foreach(range('a', 'z') as $letter) {
echo $prefix . $letter, "\n";
words($length-1, $prefix . $letter);
}
}
Usage:
words(10);
Try it here: http://codepad.org/zdTGLtjY (with words up to 3 letters)

Version 1:
for($s = 'a'; $s <= 'zzzzzzzzzz'; print $s++.PHP_EOL);
as noted by Paul in comments below, this will only go to zzzzzzzzyz. A bit slower (if anyone cares) but correct version would be:
//modified to include arnaud576875's method of checking exit condition
for($s = 'a'; !isset($s[10]); print $s++.PHP_EOL);

<?php
function makeWord($length, $prefix='')
{
if ($length <= 0)
{
echo $prefix . "\n";
return;
}
foreach(range('a', 'z') as $letter)
{
makeWord($length - 1, $prefix . $letter);
}
}
// Use the function to write the words.
$minSize = 1;
$maxSize = 3;
for ($i = $minSize; $i <= $maxSize; $i++)
{
makeWord($i);
}
?>

Related

Split a number by 13 digits using php [duplicate]

This question already has answers here:
Break long string into pieces php
(5 answers)
Closed 3 years ago.
I want to make a program which splits a long number into pieces of 13 digited number such that I can loop for every 13 digits just using php.
$number = 012345678901230123456789123
Should output
0123456789123
0123456789123
And it should be for any large number having the number of digit multiple of 13.It looks about looping and algorithm but I want to make it as short as possible and I have doubts on how to do it. So I am just asking about the main concept.
The most dynamic solution is probably to use array_functions on the string.
So str_split to make it array then chunk it in size 13 and implode the arrays.
$number = "012345678901230123456789123";
$arr = array_chunk(str_split($number), 13);
foreach($arr as &$val){
$val = implode($val);
}
https://3v4l.org/LsNFt
You can create a function where you can use your string and size as parameter and return an array of strings of the desired length:
function splitString($str, $packetSize) {
$output = [];
$size = strlen($str);
for ($i = 0; $i < $size; $i += $packetSize) {
if ($i + $packetSize < $size) {
$output[]= substr($str, $i, $packetSize);
} else {
$output[]=substr($str, $i);
}
}
return $output;
}

PHP 2 chars decrement (AB -> AA) [duplicate]

This question already has answers here:
Increment letters like number by certain value in php
(2 answers)
Closed 4 years ago.
I am implementing some export functions using PHPExcel.
Since PHP can increment alphabet automatically it had been working fine but I have an issue when trying to decrement it.
I can decrement a single character like this $decremented = chr(ord($someChar) - 1);, but it does not work on 2 characters (such as 'AA','BB', .. etc.)
Is there any way that I can decrement two characters? Like 'ZZ' -> 'ZX', 'AA'->'Z'
Any help or thoughts would be really appreciated!
Here's a decrement function that will work for you:
function decrement($str) {
$index = strlen($str)-1;
$ord = ord($str[$index]);
if ($ord > 65) {
// The final character is still greater than A, decrement
return substr($str, 0, $index) . chr($ord-1);
}
if ($index > 0) {
// Strip the final 2 characters and append a Z
return substr($str, 0, $index-1) . 'Z';
}
// Can't be decremented
return false;
}
https://3v4l.org/WaaKY
Somebody wrote a function for this here.
function decrementLetter($char) {
$len = strlen($char);
// last character is A or a
if(ord($char[$len - 1]) === 65 || ord($char[$len - 1]) === 97){
if($len === 1){ // one character left
return null;
}
else{ // 'ABA'--; => 'AAZ'; recursive call
$char = decrementLetter(substr($char, 0, -1)).'Z';
}
}
else{
$char[$len - 1] = chr(ord($char[$len - 1]) - 1);
}
return $char;
}

Time complexity of an algorithm: find length of a longest palindromic substring

I've written a small PHP function to find a length of a longest palindromic substring of a string. To avoid many loops I've used a recursion.
The idea behind algorithm is, to loop through an array and for each center (including centers between characters and on a character), recursively check left and right caret values for equality. Iteration for a particular center ends when characters are not equal or one of the carets is out of the array (word) range.
Questions:
1) Could you please write a math calculations which should be used to explain time complexity of this algorithm? In my understanding its O(n^2), but I'm struggling to confirm that with a detailed calculations.
2) What do you think about this solution, any improvement suggestions (considering it was written in 45 mins just for practice)? Are there better approaches from the time complexity perspective?
To simplify the example I've dropped some input checks (more in comments).
Thanks guys, cheers.
<?php
/**
* Find length of the longest palindromic substring of a string.
*
* O(n^2)
* questions by developer
* 1) Is the solution meant to be case sensitive? (no)
* 2) Do phrase palindromes need to be taken into account? (no)
* 3) What about punctuation? (no)
*/
$input = 'tttabcbarabb';
$input2 = 'taat';
$input3 = 'aaaaaa';
$input4 = 'ccc';
$input5 = 'bbbb';
$input6 = 'axvfdaaaaagdgre';
$input7 = 'adsasdabcgeeegcbgtrhtyjtj';
function getLenRecursive($l, $r, $word)
{
if ($word === null || strlen($word) === 0) {
return 0;
}
if ($l < 0 || !isset($word[$r]) || $word[$l] != $word[$r]) {
$longest = ($r - 1) - ($l + 1) + 1;
return !$longest ? 1 : $longest;
}
--$l;
++$r;
return getLenRecursive($l, $r, $word);
}
function getLongestPalSubstrLength($inp)
{
if ($inp === null || strlen($inp) === 0) {
return 0;
}
$longestLength = 1;
for ($i = 0; $i <= strlen($inp); $i++) {
$l = $i - 1;
$r = $i + 1;
$length = getLenRecursive($l, $r, $inp); # around char
if ($i > 0) {
$length2 = getLenRecursive($l, $i, $inp); # around center
$longerOne = $length > $length2 ? $length : $length2;
} else {
$longerOne = $length;
}
$longestLength = $longerOne > $longestLength ? $longerOne : $longestLength;
}
return $longestLength;
}
echo 'expected: 5, got: ';
var_dump(getLongestPalSubstrLength($input));
echo 'expected: 4, got: ';
var_dump(getLongestPalSubstrLength($input2));
echo 'expected: 6, got: ';
var_dump(getLongestPalSubstrLength($input3));
echo 'expected: 3, got: ';
var_dump(getLongestPalSubstrLength($input4));
echo 'expected: 4, got: ';
var_dump(getLongestPalSubstrLength($input5));
echo 'expected: 5, got: ';
var_dump(getLongestPalSubstrLength($input6));
echo 'expected: 9, got: ';
var_dump(getLongestPalSubstrLength($input7));
Your code doesn't really need to be recursive. A simple while loop would do just fine.
Yes, complexity is O(N^2). You have N options for selecting the middle point. The number of recursion steps goes from 1 to N/2. The sum of all that is 2 * (N/2) * (n/2 + 1) /2 and that is O(N^2).
For code review, I wouldn't do recursion here since it's fairly straightforward and you don't need the stack at all. I would replace it with a while loop (still in a separate function, to make the code more readable).

Another FizzBuzz solution [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I was in a job interview and was asked to solve FizzBuzz with PHP.
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
I never heard of FizzBuzz before but here is how I solved it because I didn't know modulo or how to use it.:
for ($i = 1; $i <= 100; $i++){
if($i / 3 == round($i / 3) && $i / 5 == round($i / 5)){
echo $i . " is FizzBuzz<br />";
}
else if($i / 3 == round($i / 3)){
echo $i . " is Fizz<br />";
}
else if($i / 5 == round($i / 5)){
echo $i . " is Buzz<br />";
}
else {
echo $i."<br />";
}
}
I googled and didn't find any solution with round and that got me thinking that maybe there is something wrong with it, this is one of the solutions I found that is close to mine:
for ($i = 1; $i <= 100; $i++){
if($i % 3 == 0 && $i % 5 ==0){
echo "FizzBuzz<br />";
}
else if($i % 3 == 0){
echo "Fizz<br />";
}
else if($i % 5 == 0){
echo "Buzz<br />";
}
else {
echo $i."<br />";
}
}
My code is working fine but is there anything wrong with it that I don't see?
Actually they are testing how you will solve such simple task. It should be increadibly optimized, the code shouldbe clean and easy readable.
Your version of code is not good.
The version you've found in the internet is better, but it's not ideal from the point of the optimization.
Try to think how to get the goal with less actions.
Some tips:
do not use functions (such as range) for this task - it will only slow down the script execution time
use operator "for" for this task, do not use any other (while, do-while, foreach), because operator "for" the best fits in this case (you know how many iterations you need).
do not use round function, use modulus operator "%", because any function works slower than any operator
in the result you need to get code, in which the number of operations will be the least as possible (the number of "if" statements, the number of operators like "==" or "%"
Use 15 instead of % 3 && % 5 - less calculations - faster execution time.
My example of code:
for ($i = 1; $i <= 100; $i++) {
if ($i % 15 == 0) {
echo 'FizzBuzz<br>';
} elseif ($i % 3 == 0) {
echo 'Fizz<br>';
} elseif ($i % 5 == 0) {
echo 'Buzz<br>';
} else {
echo $i . '<br>';
}
}
Code style and lack of optimization gives impression of a newbie to the interviewer. My tips are:
Follow PSR-2
Never use else (restructure, use early returns/continues)
Always try to reduce the number of ifs (code complexity)
Use "identical" operators for comparison when dealing with integers and nulls (and any other type)
Do not use <br/> when HTML is never mentioned
Try to keep maintainability:
Extract match calculations in variables/functions, so they can be easily changed
Do not overcomplicate.
Try to optimize mathematically:
Use %15 instead of %3 and %5 check
You can also skip the above at all (check for %15), as you already have calculated that. Boolean operations are much faster.
Try not to calculate something twice.
IMHO, to follow all good practices your code should look like this:
for ($i = 1; $i <= 100; $i++) {
$isFizz = (0 === $i % 3);
$isBuzz = (0 === $i % 5);
if (!$isFizz && !$isBuzz) {
echo $i . PHP_EOL;
continue;
}
if ($isFizz) {
echo 'Fizz';
}
if ($isBuzz) {
echo 'Buzz';
}
echo PHP_EOL;
}
Test
There is yet another tricky solution
for ($i = 1; $i <= 100; $i++) {
switch ($i % 15) {
case 3:
case 6:
case 9:
echo 'Fizz';
break;
case 5:
case 10:
echo 'Buzz';
break;
case 0:
echo 'FizzBuzz';
break;
default:
echo $i;
break;
}
echo PHP_EOL;
}
if you read carefully it says "instead".
this is another short and clean solution of the FizzBuzz problem :
foreach (range(1, 100) as $number) {
if(0 !== $number % 3 && 0 !== $number % 5) {
echo $number.'<br>';
continue;
}
if(0 === $number % 3) {
echo 'Fizz';
}
if(0 === $number % 5) {
echo 'Buzz';
}
echo '<br>';
}
the output is :
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16

Check if a String Starts with a Number in PHP [duplicate]

This question already has answers here:
Closed 12 years ago.
The community reviewed whether to reopen this question 10 months ago and left it closed:
Original close reason(s) were not resolved
Possible Duplicate:
Check if a String Ends with a Number in PHP
I'm trying to implement the function below. Would it be best to use some type of regex here? I need to capture the number too.
function startsWithNumber($string) {
$startsWithNumber = false;
// Logic
return $startsWithNumber;
}
You can use substr and ctype_digit:
function startsWithNumber($string) {
return strlen($string) > 0 && ctype_digit(substr($string, 0, 1));
}
The additional strlen is just required as ctype_digit returns true for an empty string before PHP 5.1.
Or, if you rather want to use a regular expression:
function startsWithNumber($str) {
return preg_match('/^\d/', $str) === 1;
}
Something like to this may work to you:
function str2int($string) {
$length = strlen($string);
for ($i = 0, $int = ''; $i < $length; $i++) {
if (is_numeric($string[$i]))
$int .= $string[$i];
else break;
}
return (int) $int;
}

Categories