This is the scenario:
There is characterstring like this:
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
And I have a method that generates a random string with a variable length depends on the characters variable:
public function generateCodes($length, $qty)
{
$codes = [];
if ($length > 0 && $qty > 0) {
for ($i = 0; $i < $qty; $i++) {
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $characters[mt_rand(0, strlen($characters) - 1)];
if (!in_array($code, $codes)) {
$codes[] = $code;
}
}
}
}
}
What I want is to calculate the possible unique codes for a specific $length. But how can I reach this?
This is my attempt so far - but I do not consider something important.
public function calculateCombinations($length)
{
$combinations = 0;
if ($length > 0) {
for ($i = 0; $i < $length; $i++) {
$combinations = $combinations + pow(2, $length -1);
}
}
return $combinations;
}
What is the right formula for this?
Thanks in advance!
Related
I want to use gaussian elimination to solve the following matrix Matrix and this is the answer I'm expecting. I would like to get back an equation in the form as is displayed in answer but i can't figure out how to do it.
public function gauss($A, $x) {
# Just make a single matrix
for ($i=0; $i < count($A); $i++) {
$A[$i][] = $x[$i];
}
$n = count($A);
for ($i=0; $i < $n; $i++) {
# Search for maximum in this column
$maxEl = abs($A[$i][$i]);
$maxRow = $i;
for ($k=$i+1; $k < $n; $k++) {
if (abs($A[$k][$i]) > $maxEl) {
$maxEl = abs($A[$k][$i]);
$maxRow = $k;
}
}
# Swap maximum row with current row (column by column)
for ($k=$i; $k < $n+1; $k++) {
$tmp = $A[$maxRow][$k];
$A[$maxRow][$k] = $A[$i][$k];
$A[$i][$k] = $tmp;
}
# Make all rows below this one 0 in current column
for ($k=$i+1; $k < $n; $k++) {
$c = -$A[$k][$i]/$A[$i][$i];
for ($j=$i; $j < $n+1; $j++) {
if ($i==$j) {
$A[$k][$j] = 0;
} else {
$A[$k][$j] += $c * $A[$i][$j];
}
}
}
}
# Solve equation Ax=b for an upper triangular matrix $A
$x = array_fill(0, $n, 0);
for ($i=$n-1; $i > -1; $i--) {
$x[$i] = $A[$i][$n]/$A[$i][$i];
for ($k=$i-1; $k > -1; $k--) {
$A[$k][$n] -= $A[$k][$i] * $x[$i];
}
}
return $x;
}
I hope someone can help me to rewrite this code so it gives the solution i've provided or recommend a library which is capable of doing this.
I've searched for possible solutions on Google but haven't been able to find one yet.
Thanks in advance.
Here, there is a example string "XjYAKpR" .. how to create all new string possibility with that string ??
I've tried before
function containAllRots($s, $arr) {
$n = strlen($s);
$a = array();
for ($i = 0; $i < $n ; $i++) {
$rotated = rotate(str_split($s), $i);
$a[] = $rotated;
}
print_r($a);die();
if (array_diff($arr, $a)) {
return True;
}
else
{
return False;
}
}
I make 2 function rotate and generate
function rotate($l, $n) {
$b = $l[$n];
$sisa = array_values(array_diff($l, array($b)));
for ($i = 0; $i < count($sisa) ; $i++) {
$random[] = generate($sisa, $b);
}
print_r($random);die();
$hasil = $l[$n] . implode("",$random);
return $hasil;
}
function generate($sisa, $b) {
$string = implode("",$sisa);
$length = count($sisa);
$size = strlen($string);
$str = '';
for( $i = 0; $i < $length; $i++ ) {
$str .= $string[ rand( 0, $size - 1 ) ];
}
Here there is a pair of functions that lets you calculate a permutation set
(no repetitions are taken in account)
function extends_permutation($char, $perm) {
$result = [];
$times = count($perm);
for ($i=0; $i<$times; $i++) {
$temp = $perm;
array_splice($temp, $i, 0, $char);
array_push($result, $temp);
}
array_push($result, array_merge($perm, [$char]));
return $result;
}
function extends_set_of_permutations($char, $set) {
$step = [];
foreach ($set as $perm) {
$step = array_merge($step, extends_permutation($char, $perm));
}
return $step;
}
you can use them to generate the required set of permutations. Something like this:
$seed = "XjYAKpR";
// the first set of permutations contains only the
// possible permutation of a one char string (1)
$result_set = [[$seed[0]]];
$rest = str_split(substr($seed,1));
foreach($rest as $char) {
$result_set = extends_set_of_permutations($char, $result_set);
}
$result_set = array_map('implode', $result_set);
sort($result_set);
At the end of the execution you will have the 5040 permutations generated by your string in the result_set array (sorted in alphabetical order).
Add a char and you will have more than 40000 results.
The functions are quite naive in implementation and naming, both aspects can be improved.
I found it online and there are no comments.
It comes with a Complex.class that basically simulates complex numbers and their operations.
I'd like to comment it myself but I really can't identify which algorithm is being used. I went online and found that the Cooley-Tukey algorithm is the most widespread, but I'm not sure that this code uses it.
private $dim;
private $p;
private $ind;
private $func;
private $w1;
private $w1i;
private $w2;
public function __construct($dim) {
$this->dim = $dim;
$this->p = log($this->dim, 2);
}
public function fft($func) {
$this->func = $func;
// Copying func in w1 as a complex.
for ($i = 0; $i < $this->dim; $i++)
$this->w1[$i] = new Complex($func[$i], 0);
$w[0] = new Complex(1, 0);
$w[1] = new Complex(cos((-2 * M_PI) / $this->dim), sin((-2 * M_PI) / $this->dim));
for ($i = 2; $i < $this->dim; $i++)
$w[$i] = Complex::Cmul($w[$i-1], $w[1]);
return $this->calculate($w);
}
private function calculate($w) {
$k = 1;
$ind[0] = 0;
for ($j = 0; $j < $this->p; $j++) {
for ($i = 0; $i < $k; $i++) {
$ind[$i] *= 2;
$ind[$i+$k] = $ind[$i] + 1;
}
$k *= 2;
}
for ($i = 0; $i < $this->p; $i++) {
$indw = 0;
for ($j = 0; $j < pow(2, $i); $j++) {
$inf = ($this->dim / pow(2, $i)) * $j;
$sup = (($this->dim / pow(2, $i)) * ($j+1)) - 1;
$comp = ($this->dim / pow(2, $i)) / 2;
for ($k = $inf; $k <= floor($inf+(($sup-$inf)/2)); $k++)
$this->w2[$k] = Complex::Cadd(Complex::Cmul($this->w1[$k], $w[0]), Complex::Cmul($this->w1[$k+$comp], $w[$ind[$indw]]));
$indw++;
for ($k = floor($inf+(($sup-$inf)/2)+1); $k <= $sup; $k++)
$this->w2[$k] = Complex::Cadd(Complex::Cmul($this->w1[$k], $w[$ind[$indw]]), Complex::Cmul($this->w1[$k-$comp], $w[0]));
$indw++;
}
for($j = 0; $j < $this->dim; $j++)
$this->w1[$j] = $this->w2[$j];
}
for ($i = 0; $i < $this->dim; $i++)
$this->w1[$i] = $this->w2[$ind[$i]];
return $this->w1;
}
This is a radix 2 FFT implementation based on the Cooley-Tukey algorithm, with the work being done in the function "compute". It will only work with FFT lengths that are a power of 2, although I don't see any parameter checking in the function itself.
$i iterates over the multiple FFT passes (of which there are log2(N) where N is the length of the FFT), and in each pass, the twiddle factors (stored in $w) are multiplied by the output from the previous stage before finding the complex sum and difference.
There are much better implementations of FFTs out there, such as FFTW, that implement a mixed radix approach, which allow an arbitrary length of FFT to be computed.
I was challenged by a friend to code some PHP to find the longest palindrome in provided text, my solution is below, how could I make it more efficient?
$string = file_get_contents("http://challenge.greplin.com/static/gettysburg.txt");
echo $string;
function isPalendrone($string) {
if ($string == strrev($string))
return true;
else
return false;
}
$longest = "";
for($i = 0; $i < strlen($string)-1; $i++) {
$afterCurrent = substr($string, $i);
for($j = 0; $j < strlen($afterCurrent)-1; $j++) {
$section = substr($afterCurrent, 0, $j);
if(isPalendrone($section)) {
if(strlen($longest)<strlen($section)) {
$longest = $section;
}
}
}
}
echo "<br /><br/>The longest was: ".$longest."<br /> which is ".strlen($longest)." chars long";
This reverses the entire string and just does substr() matches against each:
$rev = strrev($txt);
$len = strlen($txt);
$longest_len = 0;
$longest_str = null;
for ($i = 0; $i < $len; ++$i)
{
for ($j = $len - $i; $j > $longest_len; --$j)
{
if (substr($txt, $i, $j) == substr($rev, $len-$i-$j, $j))
{
$longest_len = $j;
$longest_str = substr($txt, $i, $j);
break;
}
}
}
I didn't try to optimize the implementation. e.g., It might be a little faster to skip the substr and do a char-by-char approach, because you could break out faster. In that case, you wouldn't really even need to reverse the string.
To get the longest palindrome - you have to start with longest string (not with shortest like you do now), check it and break on first match.
Also you'd better just keep 2 pointers ($i and $j) and not perform substr twice. It is enough to have i and j and substr once, right before you perform if(isPalendrone()) condition.
My implementation (~20% faster than yours):
<?php
$string = 'FourscoreandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth';
function isPalendrone($string) {
return $string == strrev($string);
}
$longest = '';
$length = strlen($string);
for ($i = 0; $i < $length - 1; $i++) {
for ($j = $length - $i; $j > 1; $j--) {
if (isPalendrone(substr($string, $i, $j))) {
$new = substr($string, $i, $j);
if (strlen($new) > strlen($longest)) $longest = $new;
break;
}
}
}
echo "<br /><br/>The longest was: ".$longest."<br /> which is ".strlen($longest)." chars long";
I want to generate a random number in PHP where the digits itself should not repeat in that number.
Is that possible?
Can you paste sample code here?
Ex: 674930, 145289. [i.e Same digit shouldn't come]
Thanks
Here is a good way of doing it:
$amountOfDigits = 6;
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $amountOfDigits;$i++)
$digits .= $numbers[$i];
echo $digits; //prints 217356
If you wanted it in a neat function you could create something like this:
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
function randomize($len = false)
{
$ints = array();
$len = $len ? $len : rand(2,9);
if($len > 9)
{
trigger_error('Maximum length should not exceed 9');
return 0;
}
while(true)
{
$current = rand(0,9);
if(!in_array($current,$ints))
{
$ints[] = $current;
}
if(count($ints) == $len)
{
return implode($ints);
}
}
}
echo randomize(); //Numbers that are all unique with a random length.
echo randomize(7); //Numbers that are all unique with a length of 7
Something along those lines should do it
<?php
function genRandomString() {
$length = 10; // set length of string
$characters = '0123456789'; // for undefined string
$string ="";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
$s = genRandomString(); //this is your random print var
or
function rand_string( $length )
{
$chars = "0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ )
{
$str .= $chars[ rand( 0, $size – 1 ) ];
}
return $str;
}
$rid= rand_string( 6 ); // 6 means length of generate string
?>
$result= "";
$numbers= "0123456789";
$length = 8;
$i = 0;
while ($i < $length)
{
$char = substr($numbers, mt_rand(0, strlen($numbers)-1), 1);
//prevents duplicates
if (!strstr($result, $char))
{
$result .= $char;
$i++;
}
}
This should do the trick. In $numbers you can put any char you want, for example: I have used this to generate random passwords, productcodes etc.
The least amount of code I saw for something like this was:
function random_num($n=5)
{
return rand(0, pow(10, $n));
}
But I'm assuming it requires more processing to do this than these other methods.