PHP array collect - php

I have alphabet array 24 character: "A B C D E F G H I J K L M N O P Q R S T U V W X"
I want collect all case with: 3 unique characters.
First case: ABC, DEF, GHI, JKL, MNO, PQR, STU, VWX

This is a little late coming, but for anyone else reading over this: If you are looking to split a string into 3-character chunks, try PHP's built in str_split() function. It takes in a $string and $split_length argument. For example:
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWX';
$grouped = str_split($alphabet, 3);
var_export( $grouped );
This outputs the following array:
array ( 0 => 'ABC', 1 => 'DEF', 2 => 'GHI',
3 => 'JKL', 4 => 'MNO', 5 => 'PQR',
6 => 'STU', 7 => 'VWX', )
This works for the example given in the question. If you want to have every possible combination of those 24 letters, Artefacto's answer makes more sense.

There's a 1:1 relationship between the permutations of the letters of the alphabet and your sets lists. Basically, once you have a permutation of the alphabet, you just have to call array_chunk to get the sets.
Now, 24! of anything (that is 620448401733239439360000) will never fit in memory (be it RAM or disk), so the best you can do is to generate a number n between 1 and 24! (the permutation number) and then generate such permutation. For this last step, see for example Generation of permutations following Lehmer and Howell and the papers there cited.

$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$c = strlen($alphabet);
$result = array();
for ($i = 0; $i < $c; ++$i) {
$current0 = $i;
for ($j = 0; $j < $c; ++$j) {
if ($current0 == $j) continue;
$current1 = $j;
for ($k = 0; $k < $c; ++$k) {
if (isset($current0 == $k || $current1 == $k)) continue;
$result[] = $alphabet[$i].$alphabet[$j].$alphabet[$k];
}
}
}
Hope I understood your question right. This one iterates over the alphabet in three loops and always skips the characters which are already used. Then I push the result to $result.
But better try the script with only five letters ;) Using alls strlen($alphabet) (don't wanna count now...) will need incredibly much memory.
(I am sure there is some hacky version which is faster than that, but this is most straightforward I think.)

Related

php generate string combinations of missing letters

I have some word lets say BKOO.
I need to remove all combinations of missing letters to generate sub words of this initial word. First remove only 1 letter, then n letters to build at least 2 letters words.
So from our example it means to make words like KOO, BOO, OO, BK, BO.
My current algorithm btw says it is possible to generate 7 combinations out of BKOO. (I also include the initial word).
Array
(
[0] => BKOO
[1] => Array
(
[0] => BKOO
[1] => KOO
[2] => OO
[3] => KO
[4] => BOO
[5] => BO
[6] => BKO
[7] => BK
)
)
Note there isnt words like BOK or OOK because that would mean do the reorder, but i dont want to do this. I want just leave letters out of current word, and don't do reorder.
Now problem is, this very slow for lenght like 15. It takes forever. How to speed it up?
function comb($s, $r = [], $init = false) {
if ($init) {
$s = mb_strtoupper($s);
$r[] = $s;
}
$l = strlen($s);
if (!$s || $l < 3) return [];
for ($i=0; $i<$l; $i++) {
$t = rem_index($s, $i);
$r[] = $t;
$r = array_merge($r, comb($t));
}
$ret = array_unique((array)$r);
return $init ? array_values($ret) : $ret;
}
// remove character at position
function rem_index($str, $ind)
{
return substr($str,0,$ind++). substr($str,$ind);
}
$s = 'BKOO';
print_r(comb($s, [], true));
https://www.tehplayground.com/62pjCAs70j7qpLJj
NERD SECTION: 🤓 😄
Interesting note - first i thought i will generate array of some dropping indexes eg, first drop only 1 letter so say drop 0 then 1 etc etc, then 2-combinations so drop 1 and 2, 1 and 3 etc, but then i thought it would be quite difficult to drop N letters out of string at once, so i came with idea that i always drop some letter from the string, and recursively call the function again if you get me, so the next level is one char dropped already and does the drop iteration again. Problem is it is very slow for some reason.
Btw if you have also the math background, what is equation to compute the resulting combinations? To me the rough computation is lets say for 15 letters word 14 * 13 * 12 or at least it does such iteration, but that would be milions of combinations and obviously its not like that even for shorter words like 8.
Thanks.
You can iterate the string to get it.
function foo(&$res,$str,$min_length){
if(strlen($str) <= $min_length){
return;
}
$remains=[];
for($i=0; $i<strlen($str); $i++){
$remain = substr($str,0,$i) . substr($str,$i+1);
if(!isset($res[$remain])) { // only process unprocessed sub string
$res[$remain] = $remain;
$remains[] = $remain;
}
}
foreach($remains as $remain){
if(strlen($remain) == $min_length){
$res[$remain] = $remain;
}else {
foo($res, $remain, $min_length);
}
}
return;
}
$str = "BKOO";
$res = [];
foo($res,$str,2);
var_dump(array_values($res));

Make an output of 1 2 4 8 11 12 14 18... using one for loop

How can I generate a sequence of numbers like
1 2 4 8 11 12 14 18 ...
(plus 10 every 4 numbers) with the following additional requirements:
using only one loop
output should stop when a value in the sequence is greater than a specified input
Examples
$input = 24;
1 2 4 8 11 12 14 18 21 22 24
$input = 20;
1 2 4 8 11 12 14 18
Here's what I tried so far:
<?php
// sample user input
$input = 20;
$number = 1;
$counter = 0;
$array = array();
//conditions
while ($counter < 4) {
$counter++;
array_push($array, $number);
$number += $number;
}
//outputs
for ($x = 0; $x < count($array); $x++) {
echo $array[$x];
echo " ";
}
Code: (Demo)
function arrayBuilder($max,$num=1){
$array=[];
for($i=0; ($val=($num<<$i%4)+10*floor($i/4))<=$max; ++$i){
$array[]=$val;
}
return $array;
}
echo implode(',',arrayBuilder(28)),"\n"; // 1,2,4,8,11,12,14,18,21,22,24,28
echo implode(',',arrayBuilder(28,2)),"\n"; // 2,4,8,16,12,14,18,26,22,24,28
echo implode(',',arrayBuilder(20)),"\n"; // 1,2,4,8,11,12,14,18
echo implode(',',arrayBuilder(24)),"\n"; // 1,2,4,8,11,12,14,18,21,22,24
This method is very similar to localheinz's answer, but uses a technique introduced to me by beetlejuice which is faster and php version safe. I only read localheinz's answer just before posting; this is a matter of nearly identical intellectual convergence. I am merely satisfying the brief with the best methods that I can think of.
How/Why does this work without a lookup array or if statements?
When you call arrayBuilder(), you must send a $max value (representing the highest possible value in the returned array) and optionally, you can nominate $num (the first number in the returned array) otherwise the default value is 1.
Inside arrayBuilder(), $array is declared as an empty array. This is important if the user's input value(s) do not permit a single iteration in the for loop. This line of code is essential for good coding practices to ensure that under no circumstances should a Notice/Warning/Error occur.
A for loop is the most complex loop in php (so says the manual), and its three expressions are the perfect way to package the techniques that I use.
The first expression $i=0; is something that php developers see all of the time. It is a one-time declaration of $i equalling 0 which only occurs before the first iteration.
The second expression is the only tricky/magical aspect of my entire code block. This expression is called before every iteration. I'll try to break it down: (parentheses are vital to this expression to avoid unintended results due to operator precedence
( open parenthesis to contain leftside of comparison operator
$val= declare $val for use inside loop on each iteration
($num<<$i%4) because of precedence this is the same as $num<<($i%4) meaning: "find the remainder of $i divided by 4 then use the bitwise "shift left" operator to "multiply $num by 2 for every "remainder". This is a very fast way of achieving the 4-number pattern of [don't double],[double once],[double twice],[double three times] to create: 1,2,4,8, 2,4,8,16, and so on. bitwise operators are always more efficient than arithmetic operators.The use of the arithmetic operator modulo ensure that the intended core number pattern repeats every four iterations.
+ add (not concatenation in case there is any confusion)
10*floor($i/4) round down $i divided by 4 then multiply by 10 so that the first four iterations get a bonus of 0, the next four get 10, the next four get 20, and so on.
) closing parenthesis to contain leftside of comparison operator
<=$max allow iteration until the $max value is exceeded.
++$i is pre-incrementing $i at the end of every iteration.
Complex solution using while loop:
$input = 33;
$result = [1]; // result array
$k = 0; // coeficient
$n = 1;
while ($n < $input) {
$size = count($result); // current array size
if ($size < 4) { // filling 1st 4 values (i.e. 1, 2, 4, 8)
$n += $n;
$result[] = $n;
}
if ($size % 4 == 0) { // determining each 4-values sequence
$multiplier = 10 * ++$k;
}
if ($size >= 4) {
$n = $multiplier + $result[$size - (4 * $k)];
if ($n >= $input) {
break;
}
$result[] = $n;
}
}
print_r($result);
The output:
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 8
[4] => 11
[5] => 12
[6] => 14
[7] => 18
[8] => 21
[9] => 22
[10] => 24
[11] => 28
[12] => 31
[13] => 32
)
On closer inspection, each value in the sequence of values you desire can be calculated by adding the corresponding values of two sequences.
Sequence A
0 0 0 0 10 10 10 10 20 20 20 20
Sequence B
1 2 4 8 1 2 4 8 1 2 4 8
Total
1 2 4 8 11 12 14 18 21 22 24 28
Solution
Prerequisite
The index of the sequences start with 0. Alternatively, they could start with 1, but then we would have to deduct 1, so to keep things simple, we start with 0.
Sequence A
$a = 10 * floor($n / 4);
The function floor() accepts a numeric value, and will cut off the fraction.
Also see https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
Sequence B
$b = 2 ** ($n % 4);
The operator ** combines a base with the exponent and calculates the result of raising base to the power of exponent.
In PHP versions prior to PHP 5.6 you will have to resort to using pow(), see http://php.net/manual/en/function.pow.php.
The operator % combines two values and calculates the remainder of dividing the former by the latter.
Total
$value = $a + $b;
Putting it together
$input = 20;
// sequence a
$a = function ($n) {
return 10 * floor($n / 4);
};
// sequence b
$b = function ($n) {
return 2 ** ($n % 4);
};
// collect values in an array
$values = [];
// use a for loop, stop looping when value is greater than input
for ($n = 0; $input >= $value = $a($n) + $b($n) ; ++$n) {
$values[] = $value;
}
echo implode(' ', $values);
For reference, see:
http://php.net/manual/en/control-structures.for.php
http://php.net/manual/en/function.floor.php
http://php.net/manual/en/language.operators.arithmetic.php
http://php.net/manual/en/function.implode.php
For an example, see:
https://3v4l.org/pp9Ci

Create fixed length non-repeating permutation of larger set

I know this topic is much discussed but I can't seem to find any implementation that fits my needs.
I have the following set of characters:
a b c d e f g h
I want to get all possible permutations or combinations (non repeating), but on a limited (variable) set of characters, meaning if I input the characters and the number 2, the results should look like
ab ba ac ca ad da ae ea af fa ag ga ah ha
bc cb bd db be eb bf fb bg gb bh hb
cd dc ce ec cf fc cg gc ch hc
de ed df fd dg gd dh hd
ef fe eg ge eh he
fg gf fh hf
gh hg
I hope you understand where I'm going with this. I currently have an implementation that gives me the permutations of all characters, but I can't wrap my head around how to implement a limited space for those permutations:
public function getPermutations($letters) {
if (strlen($letters) < 2) {
return array($letters);
}
$permutations = array();
$tail = substr($letters, 1);
foreach ($this->getPermutations($tail) as $permutation) {
$length = strlen($permutation);
for ($i = 0; $i <= $length; $i++) {
$permutations[] = substr($permutation, 0, $i) . $letters[0] . substr($permutation, $i);
}
}
return $permutations;
}
If you only need one element at a time, you can save on memory by generating each element individually.
If we wanted to generate a random string in your set of expected outputs, we could use this algorithm:
Given a set of characters S, and a desired output length K:
While the output has less than K characters:
Pick a random number P between 1 and |S|.
Append the P'th character to the output.
Remove the P'th character from S.
where |S| is the current number of elements in S.
We can actually encode this sequence of choices into an integer. One way to do that is to change the algorithm as such:
Given a set of characters S, and a desired output length K:
Let I = 0.
While the output has less than K characters:
I = I * (|S| + 1).
Pick a random number P between 1 and the number of elements in S.
I = I + P.
Append the P'th character to the output.
Remove the P'th character from S.
After running this algorithm, the value I will uniquely encode this particular sequence of choices. It basically encodes this as a mixed-radix number; one digit uses base N, the next uses N-1, and so on until the last digit which is base N-K+1 (N being the number of letters in the input).
Naturally, we can also decode this again, and in PHP, that would be something like this:
// Returns the total number of $count-length strings generatable from $letters.
function getPermCount($letters, $count)
{
$result = 1;
// k characters from a set of n has n!/(n-k)! possible combinations
for($i = strlen($letters) - $count + 1; $i <= strlen($letters); $i++) {
$result *= $i;
}
return $result;
}
// Decodes $index to a $count-length string from $letters, no repeat chars.
function getPerm($letters, $count, $index)
{
$result = '';
for($i = 0; $i < $count; $i++)
{
$pos = $index % strlen($letters);
$result .= $letters[$pos];
$index = ($index-$pos)/strlen($letters);
$letters = substr($letters, 0, $pos) . substr($letters, $pos+1);
}
return $result;
}
(Note that for simplicity, this particular decoding algorithm does not correspond exactly to the encoding algorithm I previously described, but maintains the desirable property of a given $index mapping to a unique result.)
To use this code, you would do something like this:
$letters = 'abcd';
echo '2 letters from 4:<br>';
for($i = 0; $i < getPermCount($letters, 2); $i++)
echo getPerm($letters, 2, $i).'<br>';
echo '<br>3 letters from 4:<br>';
for($i = 0; $i < getPermCount($letters, 3); $i++)
echo getPerm($letters, 3, $i).'<br>';
?>
$strings = get_perm( range('a', 'h'), 4 );
function get_perm( $a, $c, $step = 0, $ch = array(), $result = array() ){
if( $c == 1 ){ //if we have last symbol in chain
for( $k = 0; $k < count( $a ); $k++ ){
if( #in_array( $k, $ch ) ) continue; // if $k exist in array we already have such symbol in string
$tmp = '';
foreach( $ch as $c ) $tmp .= $a[$c]; // concat chain of previous symbols
$result[] = $tmp . $a[$k]; // and adding current + saving to our array to return
}
}else{
for( $i = 0; $i < count( $a ); $i++ ){
if( #in_array( $i, $ch ) ) continue;
$ch[$step] = $i; // saving current symbol for 2 things: check if that this symbol don't duplicate later and to know what symbols and in what order need to be saved
get_perm( $a, $c-1, $step+1, $ch, &$result );
// recursion,
// decrementing amount of symbols left to create string,
// incrementing step to correctly save array or already used symbols,
// $ch - array of already used symbols,
// &$result - pointer to result array
}
}
return $result;
}
NOTICE
a-h with 6 symbols = 20k values in array
a-z with 4 symbols = 358799 values in array
So a-z with 10 symbols will die for sure =) It will require too much memory.
You need to try to save output to file or database if you would need big amount of values. Or extend memory limit to php but not sure if this is best way.

give an array a-z until possibly ZZZ... key with php or python

Let's say i have an unknown string in an array, it will look like
$arr = array(
'string 1',
'string 2',
'string 3',
'string 4',
'string 5',
// up to a certain unknown amount
1. How can we give them a value like below?
'string 1' => a,
'string 2' => b,
'string 26' => z,
'string 27' => A,
'string 52' => Z,
'string 53' => aa,
// up to a certain unknown amount possibly until ZZZZ, or maybe more.
update heres what ive done so far
function num2a($a){
# A-Z
for ($i=65; $i < 91 ; $i++) {
#echo chr($i);
$arr[] = chr($i);
}
# a-z
for ($i=97; $i < 123 ; $i++) {
#echo chr($i);
$arr[] = chr($i);
}
// a-Z
if ( 0 <= $a && $a <= 51 ) {
echo $arr[$a];
}
// aa-ZZ not done
if ( 52 <= $a && $a <= 53 ) {
for ($x=0; $x < 1; $x++) {
# A = 0
# a = 26
# somehow if i put $a = 52 it will do a aa
$a = $a - 26;
$arr[$a] = $arr[$a] . $arr[$a];
echo $arr[$a];
}
}
}
In Python it's relatively easy to have an infinite array using generators, as well as arbitrarily long ones, lazily evaluated ones, etc. What you'd want to do to map this kind of thing to keys is to have an infinitely long, lazily evaluated list, or generator.
import itertools
import string
First you want itertools, which has lots of handy functions for manipulating infinite size arrays. string includes some standard string constants.
def lower_then_upper():
return iter(string.letters)
iter here isn't strictly required, but it will turn the standard list into a generator, for consistency.
def get_n(n=2):
generators = []
for gen in range(n):
generators.append(lower_then_upper())
tuples = itertools.product(*generators)
return itertools.imap(''.join, tuples)
Here we start putting things together, this function will return the list of strings of a fixed length made of up the letters. Line by line, the bits before tuples ensures that there is a generator for all strings available for each letter position. i.e. three a-Z lists would be created if n=3.
Below, itertools.product does a cartesian product of all the things available, which in Python luckily iterates the last first, so you get for n=2: `['aa', 'ab', ..., 'ZX', 'ZY', 'ZZ'].
The final line, itertools.imap applies the function ''.join to every item in tuples. Until now they were of the form (('a', 'a'), ('a', 'b'), …, this ensures they are a string, in the same way that ''.join(['a', 'a']) == 'aa'.
def get_infinite():
n = 0
while True:
n += 1
for item in get_n(n):
yield item
Here is where the magic happens. It will exhaust the iterator for n=1 before going on to exhaust n=2, and so on.
def inf_hello():
while True:
yield "hello world"
This is just a demo infinite list
mapped = itertools.izip(get_infinite(), inf_hello())
Now, we zip them together to get an infinite array of key/value pairs:
>>> list(itertools.islice(mapped, 1000, 1010))
[('sm', 'hello world'), ('sn', 'hello world'), ('so', 'hello world'), ('sp', 'hello world'), ('sq', 'hello world'), ('sr', 'hello world'), ('ss', 'hello world'), ('st', 'hello world'), ('su', 'hello world'), ('sv', 'hello world')]
as we can see if we introspect it 1000 elements in.
Alternatively, we can give it a long list and get a dictionary:
>>> numbers = dict(itertools.izip(get_infinite(), range(0, 10000)))
>>> print numbers['a'], numbers['aa'], numbers['caW']
0 52 8212
Hope this helps.
Warning, in psuedo-code. This is an idea, first create a map like so
map['1'->'26'] = 'a'->'z'
map['27'->'52'] = 'A'->'Z'
Now from the list of data all you need is the number. You can use the number to get appropriate values like so,
int numFromData = getNumber('string 53')
while( numFromData > 0){
int mapKey = numFromData % 52; //since we have 52 mapped values
print( map[ mapKey] );
numFromData /= 52;
}
I think that should work, no guarantees, but the idea is correct.
Well you can give it numeric keys easily:
$strArray = explode(",",$string);
$str = ""; // Your String
$results = array();
$input = explode(",", $str);
foreach($input as $v) {
$value = explode("=>", $v);
if(!isset($results[$value[0]])) {
$results[$value[0]] = $value[1];
}
}
1) If you don't really need upper case
for($i="a";$i!="bc";++$i)
print $i."\n";

Generating Ordered (Weighted) Combinations of Arbitrary Length in PHP

Given a list of common words, sorted in order of prevalence of use, is it possible to form word combinations of an arbitrary length (any desired number of words) in order of the 'most common' sequences. For example,if the most common words are 'a, b, c' then for combinations of length two, the following would be generated:
aa
ab
ba
bb
ac
bc
ca
cb
cc
Here is the correct list for length 3:
aaa
aab
aba
abb
baa
bab
bba
bbb
aac
abc
bac
bbc
aca
acb
bca
bcb
acc
bcc
caa
cab
cba
cbb
cac
cbc
cca
ccb
ccc
This is simple to implement for combinations of 2 or 3 words (set length) for any number of elements, but can this be done for arbitrary lengths? I want to implement this in PHP, but pseudocode or even a summary of the algorithm would be much appreciated!
Here's a recursive function that might be what you need. The idea is, when given a length and a letter, to first generate all sequences that are one letter shorter that don't include that letter. Add the new letter to the end and you have the first part of the sequence that involves that letter. Then move the new letter to the left. Cycle through each sequence of letters including the new one to the right.
So if you had gen(5, d)
It would start with
(aaaa)d
(aaab)d
...
(cccc)d
then when it got done with the a-c combinations it would do
(aaa)d(a)
...
(aaa)d(d)
(aab)d(d)
...
(ccc)d(d)
then when it got done with d as the 4th letter it would move it to the 3rd
(aa)d(aa)
etc., etc.
<?php
/**
* Word Combinations (version c) 6/22/2009 1:20:14 PM
*
* Based on pseudocode in answer provided by Erika:
* http://stackoverflow.com/questions/1024471/generating-ordered-weighted-combinations-of-arbitrary-length-in-php/1028356#1028356
* (direct link to Erika's answer)
*
* To see the results of this script, run it:
* http://stage.dustinfineout.com/stackoverflow/20090622/word_combinations_c.php
**/
init_generator();
function init_generator() {
global $words;
$words = array('a','b','c');
generate_all(5);
}
function generate_all($len){
global $words;
for($i = 0; $i < count($words); $i++){
$res = generate($len, $i);
echo join("<br />", $res);
echo("<br/>");
}
}
function generate($len, $max_index = -1){
global $words;
// WHEN max_index IS NEGATIVE, STARTING POSITION
if ($max_index < 0) {
$max_index = count($words) - 1;
}
$list = array();
if ($len <= 0) {
$list[] = "";
return $list;
}
if ($len == 1) {
if ($max_index >= 1) {
$add = generate(1, ($max_index - 1));
foreach ($add as $addit) {
$list[] = $addit;
}
}
$list[] = $words[$max_index];
return $list;
}
if($max_index == 0) {
$list[] = str_repeat($words[$max_index], $len);
return $list;
}
for ($i = 1; $i <= $len; $i++){
$prefixes = generate(($len - $i), ($max_index - 1));
$postfixes = generate(($i - 1), $max_index);
foreach ($prefixes as $pre){
//print "prefix = $pre<br/>";
foreach ($postfixes as $post){
//print "postfix = $post<br/>";
$list[] = ($pre . $words[$max_index] . $post);
}
}
}
return $list;
}
?>
I googled for php permutations and got: http://www.php.happycodings.com/Algorithms/code21.html
I haven't looked into the code if it is good or not. But it seems to do what you want.
I don't know what the term is for what you're trying to calculate, but it's not combinations or even permutations, it's some sort of permutations-with-repetition.
Below I've enclosed some slightly-adapted code from the nearest thing I have lying around that does something like this, a string permutation generator in LPC. For a, b, c it generates
abc
bac
bca
acb
cab
cba
Probably it can be tweaked to enable the repetition behavior you want.
varargs mixed array permutations(mixed array list, int num) {
mixed array out = ({});
foreach(mixed item : permutations(list[1..], num - 1))
for(int i = 0, int j = sizeof(item); i <= j; i++)
out += ({ implode(item[0 .. i - 1] + ({ list[0] }) + item[i..], "") });
if(num < sizeof(list))
out += permutations(list[1..], num);
return out;
}
FWIW, another way of stating your problem is that, for an input of N elements, you want the set of all paths of length N in a fully-connected, self-connected graph with the input elements as nodes.
I'm assuming that when saying it's easy for fixed length, you're using m nested loops, where m is the lenght of the sequence (2 and 3 in your examples).
You could use recursion like this:
Your words are numbered 0, 1, .. n, you need to generate all sequences of length m:
generate all sequences of length m:
{
start with 0, and generate all sequences of length m-1
start with 1, and generate all sequences of length m-1
...
start with n, and generate all sequences of length m-1
}
generate all sequences of length 0
{
// nothing to do
}
How to implement this? Well, in each call you can push one more element to the end of the array, and when you hit the end of the recursion, print out array's contents:
// m is remaining length of sequence, elements is array with numbers so far
generate(m, elements)
{
if (m == 0)
{
for j = 0 to elements.length print(words[j]);
}
else
{
for i = 0 to n - 1
{
generate(m-1, elements.push(i));
}
}
}
And finally, call it like this: generate(6, array())

Categories