I'm reading overflow for years but never had to post anything (thanks to great answers) until now because i can't rly find solution for my problem.
I'm kinda new to PHP.
So I'm creating game where you have to find a longest word with 12 random generated letters. I actually did this successfully in C# and Java, but now I'm porting some of code to PHP because i'm working on multiplayer version and some stuff will be on server.
So i did all this using this great thread (Answer by Thomas Jungblut):
Find the longest word given a collection
Now i tried to do same in PHP but, it's weird for me. I get some crazy result's and i dont know how to replicate this java method in php:
arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
I'm not getting any error, but obvisuly thing is not working, is there anyone that can maybe help me to work this out?
UPDATE: BTW, i know post might be confusing im new to posting here...so forgive me ^^
I "fixed" code, it will now find me longest word. But there is bug somewhere. Bug is allowing algortithm to use one character more than once, which should not be possible.
I think problem is here:
$newDict[$index] = array_splice($allowedCharacters, $index +1, count($allowedCharacters) - ($index +1));
This is my Current Code:
parse_dictionary.php
<?php
$ouput = array();
$mysqli = new mysqli('localhost','root','','multiquiz_db');
$mysqli->set_charset('utf8');
if ($result = $mysqli->query("SELECT word FROM words_live")) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
//echo(mb_convert_encoding($row['word'], 'HTML-ENTITIES', 'utf-8'));
array_push($ouput, $row['word']);
}
//echo utf8_decode(json_encode($ouput));
}
$result->close();
$mysqli->close();
?>
Trie.php
<?php
class Trie
{
public $children = array();
public $value = null;
public $word = null;
public function __construct($value = null)
{
$this->value = $value;
}
public function adda($array)
{
$this->addb($array, 0);
}
public function addb($array, $offset)
{
foreach ($this->children as $child)
{
if($child->value == $array[$offset])
{
$child->addb($array, $offset + 1);
return;
}
}
$trieNode = new Trie($array[$offset]);
array_push($this->children, $trieNode);
if($offset < count($array) - 1)
{
$trieNode->addb($array, $offset+1);
}
else
{
$trieNode->word = implode(" ", $array);
}
}
}
?>
Index.php
<?php
include 'Trie.php';
include 'parse_dictionary.php';
ini_set('memory_limit', '1024M'); // or you could use 1G
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding("UTF-8");
class LongestWord
{
public $root = null;
public function __construct($ouput)
{
$this->root = new Trie();
foreach ($ouput as $word)
{
//echo($word);
//echo(str_split_unicode($word)[0]);
$this->root->adda(str_split_unicode($word));
}
}
public function search($cs)
{
return $this->visit($this->root, $cs);
}
function visit($n, $allowedCharacters)
{
$bestMatch = null;
if(count($n->children) == 0)
{
$bestMatch = $n->word;
}
foreach($n->children as $child)
{
if($this->contains($allowedCharacters, $child->value))
{
$result = $this->visit($child, $this->remove($allowedCharacters, $child->value));
if($bestMatch == null || $result != null && strlen($bestMatch) < strlen($result))
{
$bestMatch = $result;
}
}
}
return $bestMatch;
}
function remove($allowedCharacters, $value)
{
$newDict = $allowedCharacters;
if(($key = array_search($value, $newDict)))
{
unset($newDict[$key]);
}
return $newDict;
}
function contains($allowedCharacters, $value)
{
foreach($allowedCharacters as $x)
{
if($value == $x)
{
// echo $value . "=====". $x. "|||||||";
return true;
}
else
{
//echo $value . "!!===". $x. "|||||||";
}
}
return false;
}
}
function str_split_unicode($str, $l = 0) {
if ($l > 0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
$chars = 'IIOIOFNČGDĆJ';
$testCharacters = str_split_unicode($chars);
$lw = new LongestWord($ouput);
echo($lw->search($testCharacters));
?>
As you're using MySQL, here's an approach that will let the DB server do the work.
It's a bit dirty, because you have to add several WHERE conditions with regex matching, which will have a rather poor performance. (Unfortunately, I could not come up with a regex that would require all of the letters in one expression, but I'd be happy to be corrected.)
However, I have tested it on a database table of >200000 entries; it delivers results within less than 0.3 sec.
SELECT word
FROM words_live
WHERE
word REGEXP "a" AND
word REGEXP "b" AND
word REGEXP "c" AND
word REGEXP "d"
ORDER BY LENGTH(word) DESC
LIMIT 1;
Obviously, you must generate one word REGEXP "a" condition per letter in your PHP code when constructing the query.
The query should then give you exactly one result, namely the longest word in the database containing all of the characters.
I solved problem with this function, full working code updated in question post
function remove($allowedCharacters, $value)
{
$newDict = $allowedCharacters;
if(($key = array_search($value, $newDict)))
{
unset($newDict[$key]);
}
return $newDict;
}
removed old one:
function remove($allowedCharacters, $value)
{
$newDict = [count($allowedCharacters) - 1];
$index = 0;
foreach($allowedCharacters as $x)
{
if($x != $value)
{
$newDict[$index++] = $x;
}
else
{
//we removed the first hit, now copy the rest
break;
}
}
//System.arraycopy(allowedCharacters, index + 1, newDict, index, allowedCharacters.length - (index + 1)); JAVA arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
//$newDict[$index] = array_splice($allowedCharacters, $index +1, count($allowedCharacters) - ($index +1));
//$newDict = $allowedCharacters;
return $newDict;
}
Related
I am building a function that would receive 2 params, a string and a number.
it would basically print the first letters $n of $s.
I need to run a loop, please don't advise other non looping methods.
And yes, I need to keep the loop true throughout the function, it's suppose to close when the if is met.
For some reason the loop isn't closing, even though there's a return in the if condition that is being met when $stringCounter equals $n (=10 in this example.)
function printCounter($s, $n)
{
$stringCaller = '';
$stringCounter = strlen($stringCaller);
while (1) {
$stringCaller .= $s;
if ($stringCounter == $n) {
return $stringCaller;
}
}
}
printCounter('aba', '10');
You should imove the calc of $stringCounter inside the loop otherwise this never change
$stringCaller = '';
while (1) {
$stringCounter = strlen($stringCaller);
$stringCaller .= $s;
if ($stringCounter >= $n) {
return $stringCaller;
}
}
On my oppinion, TS is searching next approach:
function printCounter($s, $n)
{
$result = '';
$str_lenght = strlen($s);
if(!$str_lenght) {
return $result;
}
while (true) {
$result .= $s;
$result_lenght = strlen($result);
if($result_lenght/$str_lenght >= $n) {
return $result_lenght;
}
}
}
echo printCounter('aba', '10');
exit;
You can fix part of the issue by updating $stringCounter inside the loop.
function printCounter($s, $n)
{
$stringCaller = '';
while (1) {
$stringCaller .= $s;
$stringCounter = strlen($stringCaller); // check strlen after each addition of $s
if ($stringCounter == $n) {
return $stringCaller;
}
}
}
However, even after you fix that issue, there will still be cases where your loop will never exit (such as the example in your question) because $stringCounter can only equal $n if $n is a multiple of strlen($s).
For the example printCounter('aba', '10');
Iteration $stringCounter ($stringCounter == $n)
1 3 false
2 6 false
3 9 false
4 12 false
Obviously $stringCounter will only get farther away from $n from that point.
So to ensure that the function will exit, check for inequality instead with:
if ($stringCounter >= $n) {
If you need the function to return exactly $n characters, the function will need to be a little more complex and take a substring of $s to make up the remaining characters when $stringCounter + strlen($s) will be greater than $n, or return an $n character substring of your result like this:
function printCounter($s, $n)
{
$result = '';
while (1) {
$result .= $s;
if (strlen($result) >= $n) {
return substr($result, 0, $n);
}
}
}
Need to write a code block which check is one string is a rotation of another.
Looked at loads of posts on here and it is all in Java or C++ but I need to do it in PHP.
I have tried a few different things, trying to work from the C++ and Java examples but I am not having any luck, here is my current code:
<?php
function isSubstring($s1, $s2) {
if(strlen($s1) != strlen($s2)) {
return false;
}
if(WHAT TO PUT HERE) {
echo "it is!";
} else {
echo "nope";
}
}
isSubstring("hello", "helol");
?>
Many ways available. Here one more using built-in function count_chars on both strings, and then comparing both resulting arrays :
function isSubstring($s1, $s2) {
if (strlen($s1) != strlen($s2)) {
echo "nope";
return;
}
$s1cnt = count_chars($s1, 1);
$s2cnt = count_chars($s2, 1);
if($s1cnt === $s2cnt) {
echo "it is!";
} else {
echo "nope";
}
}
Edit : as MonkeyZeus pointed out, beware of comparison with multibyte characters. It may bite a little bit :
isSubstring('crढap', 'paࢤrc');
will give true as answer. ढ is UTF-8 indian devanagari three byte char : E0 A2 A4 and ࢤ is also three byte chars (arabic) : E0 A4 A2, and the count_chars function counts the individual bytes. So it would be safe to use if chars are from only one language, else get some headache pills...
It seems to me that to manage this kind of things we need to have chars that are made of 3 bytes.
I would go for something like this:
function isSubstring($s1, $s2)
{
// If the strings match exactly then no need to proceed
if($s1 === $s2)
{
echo "it is!";
return;
}
elseif(strlen($s1) !== strlen($s2))
{
// Strings must be of equal length or else no need to proceed
echo "nope";
return;
}
// Put each character into an array
$s1 = str_split($s1);
$s2 = str_split($s2);
// Sort alphabetically based on value
sort($s1);
sort($s2);
// Triple check the arrays against one-another
if($s1 === $s2)
{
echo "it is!";
}
else
{
echo "nope";
}
}
Here is a multibyte safe function to compare the two strings:
function mb_isAnagram($s1, $s2) {
if (strlen($s1) != strlen($s2)) {
return false;
} else {
$c1 = preg_split('//u', $s1, null, PREG_SPLIT_NO_EMPTY);
$c2 = preg_split('//u', $s2, null, PREG_SPLIT_NO_EMPTY);
sort($c1);
sort($c2);
if ($c1 === $c2) {
return true;
} else {
return false;
}
}
}
You could split each string and sort it, like this:
$split1 = unpack("C*",$s1);
asort($split1);
Then you can traverse both arrays comparing the values.
<?php
function isRotationalString($str1,$str2){
$len = strlen($str1);
if($str1 === $str2){
return true;
}else{
if($len == strlen($str2)){
$flag = true;
for($i=0;$i<$len;$i++){
if($str1[0]==$str2[$i]){
$tst = $i;$start = true;break;
}
}
if($start){
for($j=0;$j<$len;$j++){
$m = $j+$tst;
if($m < $len){
if($str1[$j] != $str2[$m]){
$flag = false;break;
}
}else{
if($m>=$len)
{
$k = $m - $len;
if($str1[$j] != $str2[$k]){
$flag = false;break;
}
}
}
}
}else{
$flag = false;
}
return $flag;
}
}
}
echo isRotationalString("abcd","bcda")?'It is':'It is not';
?>
above script will check whether a string is a rotation of another string or not?
isRotationalString("abcd","bcda") => It is
isRotationalString("abcd","cbda") => It is Not
This is the function for string rotation.
echo isRotationalString("abcdef","efabcd")?'It is':'It is not';
function isRotationalString($str1,$str2){
$len = strlen($str1);
if($str1 === $str2){
return true;
} else {
if($len == strlen($str2)) {
$stringMatchedArr1 = $stringMatchedArr2 = [];
for($i=0; $i<$len; $i++) {
$substr = substr($str1,$i );
$pos = strpos($str2, $substr);
if($pos !== false) {
$stringMatchedArr1[] = $substr;
}
}
for($j=1; $j <= $len; $j++) {
$substr = substr($str1, 0, $j );
$pos = strpos($str2, $substr);
if($pos !== false) {
$stringMatchedArr2[] = $substr;
}
}
foreach($stringMatchedArr2 as $string1) {
foreach($stringMatchedArr1 as $string2) {
if($string1.$string2 == $str1)
return true;
}
}
}
}
}
I would sort the characters in the strings by making it an array and then imploding them to a string again.
if (sort(str_split($s1)) == sort(str_split($s2))) {
That would do the trick in one line.
Edit: Thanks Don't Panic, edited my answer!
I have the following code:
for($a=1; $a<strlen($string); $a++){
for($b=1; $a+$b<strlen($string); $b++){
for($c=1; $a+$b+$c<strlen($string); $c++){
for($d=1; $a+$b+$c+$d<strlen($string); $d++){
$tempString = substr_replace($string, ".", $a, 0);
$tempString = substr_replace($tempString, ".", $a+$b+1, 0);
$tempString = substr_replace($tempString, ".", $a+$b+$c+2, 0);
$tempString = substr_replace($tempString, ".", $a+$b+$c+$d+3, 0);
echo $tempString."</br>";
}
}
}
}
What it does is to make all possible combinatons of a string with several dots.
Example:
t.est123
te.st123
tes.t123
...
test12.3
Then, I add one more dot:
t.e.st123
t.es.t123
...
test1.2.3
Doing the way I'm doing now, I need to create lots and lots of for loops, each for a determined number of dots. I don't know how I can turn that example into a functon or other easier way of doing this.
Your problem is a combination problem. Note: I'm not a math freak, I only researched this information because of interest.
http://en.wikipedia.org/wiki/Combination#Number_of_k-combinations
Also known as n choose k. The Binomial coefficient is a function which gives you the number of combinations.
A function I found here: Calculate value of n choose k
function choose($n, $k) {
if ($k == 0) {return 1;}
return($n * choose($n - 1, $k - 1)) / $k;
}
// 6 positions between characters (test123), 4 dots
echo choose(6, 4); // 15 combinations
To get all combinations you also have to choose between different algorithms.
Good post: https://stackoverflow.com/a/127856/1948627
UPDATE:
I found a site with an algorithm in different programming languages. (But not PHP)
I've converted it to PHP:
function bitprint($u){
$s= [];
for($n= 0;$u > 0;++$n, $u>>= 1) {
if(($u & 1) > 0) $s[] = $n;
}
return $s;
}
function bitcount($u){
for($n= 0;$u > 0;++$n, $u&= ($u - 1));
return $n;
}
function comb($c, $n){
$s= [];
for($u= 0;$u < 1 << $n;$u++) {
if(bitcount($u) == $c) $s[] = bitprint($u);
}
return $s;
}
echo '<pre>';
print_r(comb(4, 6));
It outputs an array with all combinations (positions between the chars).
The next step is to replace the string with the dots:
$string = 'test123';
$sign = '.';
$combs = comb(4, 6);
// get all combinations (Th3lmuu90)
/*
$combs = [];
for($i=0; $i<strlen($string); $i++){
$combs = array_merge($combs, comb($i, strlen($string)-1));
}
*/
foreach ($combs as $comb) {
$a = $string;
for ($i = count($comb) - 1; $i >= 0; $i--) {
$a = substr_replace($a, $sign, $comb[$i] + 1, 0);
}
echo $a.'<br>';
}
// output:
t.e.s.t.123
t.e.s.t1.23
t.e.st.1.23
t.es.t.1.23
te.s.t.1.23
t.e.s.t12.3
t.e.st.12.3
t.es.t.12.3
te.s.t.12.3
t.e.st1.2.3
t.es.t1.2.3
te.s.t1.2.3
t.est.1.2.3
te.st.1.2.3
tes.t.1.2.3
This is quite an unusual question, but I can't help but try to wrap around what you are tying to do. My guess is that you want to see how many combinations of a string there are with a dot moving between characters, finally coming to rest right before the last character.
My understanding is you want a count and a printout of string similar to what you see here:
t.est
te.st
tes.t
t.es.t
te.s.t
t.e.s.t
count: 6
To facilitate this functionality I came up with a class, this way you could port it to other parts of code and it can handle multiple strings. The caveat here is the strings must be at least two characters and not contain a period. Here is the code for the class:
class DotCombos
{
public $combos;
private function combos($string)
{
$rebuilt = "";
$characters = str_split($string);
foreach($characters as $index => $char) {
if($index == 0 || $index == count($characters)) {
continue;
} else if(isset($characters[$index]) && $characters[$index] == ".") {
break;
} else {
$rebuilt = substr($string, 0, $index) . "." . substr($string, $index);
print("$rebuilt\n");
$this->combos++;
}
}
return $rebuilt;
}
public function allCombos($string)
{
if(strlen($string) < 2) {
return null;
}
$this->combos = 0;
for($i = 0; $i < count(str_split($string)) - 1; $i++) {
$string = $this->combos($string);
}
}
}
To make use of the class you would do this:
$combos = new DotCombos();
$combos->allCombos("test123");
print("Count: $combos->combos");
The output would be:
t.est123
te.st123
tes.t123
test.123
test1.23
test12.3
t.est12.3
te.st12.3
tes.t12.3
test.12.3
test1.2.3
t.est1.2.3
te.st1.2.3
tes.t1.2.3
test.1.2.3
t.est.1.2.3
te.st.1.2.3
tes.t.1.2.3
t.es.t.1.2.3
te.s.t.1.2.3
t.e.s.t.1.2.3
Count: 21
Hope that is what you are looking for (or at least helps)....
I have this PHP code which is supposed to increase a URL shortener mask on each new entry.
My problem is that it dosen't append a new char when it hits the last one (z).
(I know incrementing is a safety issue since you can guess earlier entries, but this is not a problem in this instance)
If i add 00, it can figure out 01 and so on... but is there a simple fix to why it won't do it on its own?
(The param is the last entry)
<?php
class shortener
{
public function ShortURL($str = null)
{
if (!is_null($str))
{
for($i = (strlen($str) - 1);$i >= 0;$i--)
{
if($str[$i] != 'Z')
{
$str[$i] = $this->_increase($str[$i]);
#var_dump($str[$i]);
break;
}
else
{
$str[$i] = '0';
if($i == 0)
{
$str = '0'.$str;
}
}
}
return $str;
}
else {
return '0';
}
}
private function _increase($letter)
{
//Lowercase: 97 - 122
//Uppercase: 65 - 90
// 0 - 9 : 48 - 57
$ord = ord($letter);
if($ord == 122)
{
$ord = 65;
}
elseif ($ord == 57)
{
$ord = 97;
}
else
{
$ord++;
}
return chr($ord);
}
}
?>
Effectively, all you are doing is encoding a number into Base62. So if we take the string, decode it into base 10, increment it, and reencode it into Base62, it will be much easier to know what we are doing, and the length of the string will take care of itself.
class shortener
{
public function ShortURL($str = null)
{
if ($str==null) return 0;
$int_val = $this->toBase10($str);
$int_val++;
return $this->toBase62($int_val);
}
public function toBase62($num, $b=62) {
$base='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$r = $num % $b ;
$res = $base[$r];
$q = floor($num/$b);
while ($q) {
$r = $q % $b;
$q =floor($q/$b);
$res = $base[$r].$res;
}
return $res;
}
function toBase10( $num, $b=62) {
$base='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$limit = strlen($num);
$res=strpos($base,$num[0]);
for($i=1;$i<$limit;$i++) {
$res = $b * $res + strpos($base,$num[$i]);
}
return $res;
}
}
I am stuck in resolving a PHP script.
I want to calculate a result from a set of instructions. Instructions comprise of a keyword and a number that are separated by a space per line. Instructions are loaded from file and results are output to the screen. Any number of Instructions can be specified. Instructions are operators (add, divide, subtract, multiply). The instructions will ignore mathematical precedence. The last instruction should be “apply” and a number (e.g., “apply 3”). The calculator is then initialised with that number and the previous instructions are applied to that number.
[Input]
add 2
multiply 3
apply 3
[Output]
15
this is what i have tried but i cant get the logic to complete the methods
class Calculator {
public $result = 0;
public $queue = Array();
public parseString($text) {
// parse input string
$cmds = explode(" ", $text);
foreach($cmds as $cmd) {
$cmd = trim($cmd);
if(!$cmd) continue; // blank or space, ignoring
$this->queue[] = $cmd;
}
// lets process commands
$command = false;
foreach($this->queue as $index => $cmd) {
if(is_number($cmd)) {
// if it's number fire previous command if exists
if(!$command || !method_exists($this, $command)) {
throw new Exception("Unknown command $command");
}
$this->$command($index, $cmd);
}else{
$command = $cmd;
}
}
}
public function apply($index, $number) {
// manipulate $result, $queue, $number
}
public function add($index, $number) {
// manipulate $result, $queue, $number
}
public function substract($index, $number) {
// manipulate $result, $queue, $number
}
}
$calculator = new Calculator();
$calculator->parseString('...');
how can i call or switch the add,divide,multiply,substract and how to distinguish and trigger apply word
any kind of help will be appreciated.
You should process the apply first and then cut it out of your queue array. Before you start looping through with the commands, simply test for the apply command and run it first. This simplifies the whole process.
After many minutes of experimentation and chatting, has been resolved.
<?php
error_reporting(E_ALL);
class Calculator {
public $result = 0;
public $queue = array();
public function parseString($text) {
// parse input string
$split = explode(" ", $text); //This gets your input into new lines
for ($i = 0; $i < count($split); $i += 2) $pairs[] = array($split[$i], $split[$i+1]);
foreach ($pairs as $bits) {
if ($bits[0] == "apply") {
$this->apply($bits[1]); //Set result equal to apply.
$this->queue[] = "output";
} else {
$this->queue[] = $bits; //Set the queue item as an array of (command, value).
}
}
//var_dump($this->queue);
//die;
// lets process commands
foreach ($this->queue as $index => $cmd) {
if ($cmd == "output") {
echo "Answer: " .$this->result;
return;
} else {
switch($cmd[0]) {
case "add":
$this->add($cmd[1]);
break;
case "subtract":
$this->subtract($cmd[1]);
break;
case "multiply":
$this->multiply($cmd[1]);
break;
case "divide":
$this->divide($cmd[1]);
break;
default:
echo "Unknown command!";
break;
}
}
}
}
public function apply($number) {
// manipulate $result, $queue, $number
$this->result = $number;
}
public function add($number) {
// manipulate $result, $queue, $number
$this->result += $number;
}
public function subtract($number) {
// manipulate $result, $queue, $number
$this->result -= $number;
}
public function multiply($number) {
// manipulate $result, $queue, $number
$this->result *= $number;
}
public function divide($number) {
// manipulate $result, $queue, $number
$this->result /= $number;
}
}
?>
Try using the array_shift and array_pop functions:
//pop the apply num off end off the queue
$result= array_pop($this->queue);
//now pop the apply operator off end of the queue
$operator = array_pop($this->queue);
//now get the first operator and numbers using array_shift
$operator = array_shift($this->queue); //get first operator
$num = array_shift($this->queue); //get first number
//loop perform operation on result using number till done.
while($num !== null)
{
$result = $operator($result, $num);
$operator = array_shift($this->queue);
$num = array_shift($this->queue);
}