I'm quite new to php but learning fast, what I'm trying to do is loop a function which generates a random string of characters maybe 10 times and save each random string into an array.
function getRandom()
{
$length = 5;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
return $randomString;
}
Here is my get random string function but now how would I loop it a set number of times and save $randomString into an array each time, any pointers would be great,
Just have to declare an array and save it. For eg:
$arr = array(); // declare the array
for($i = 0; $i < 10; $i++) {
$arr[] = getRandom();
}
var_dump($arr); // to check if you are getting the desired result
This should work:
$length = 5;
$data = array();
// Set the top value in this case I'm using 10
for ($i=0; $i <= 10; $i++) {
$data[$i] = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0,$length);
}
// Print to see new array
print_r($data)
Related
I'm trying to implement a radix sort in binary, because i want to check if the speed of bit shifting operations counterbalance the number of steps required.
My counting sort seems to work, but as soon as i have several passes for the radix sort, the result break.
Any help greatly appreciated.
/*
* bits is to store the value of the current digit for each number in the input array
*/
function countSort(&$arr, $digit) {
$bits = $output = array_fill(0, NB_ELEMS, 0);
$count = [0,0];
// Store count of occurrences in count[]
for ($i = 0; $i < NB_ELEMS; $i++) {
$nb = $arr[$i];
$bit = ($nb >> $digit) & 1;
$bits[$i] = $bit;
$count[$bit]++;
}
// Cumulative count
$count[1] = NB_ELEMS;
// Rearranging
for ($i = 0; $i < NB_ELEMS; $i++) {
$nb = $arr[$i];
$bit = $bits[$i];
$output[$count[$bit] - 1] = $nb;
$count[$bit]--;
}
// Switch arrays
$arr = $output;
}
function radixSort(&$arr, $nb_digits) {
// Do counting sort for every binary digit
for($digit = 0; $digit < $nb_digits; $digit++) {
countSort($arr, $digit);
}
}
$tab = [4,3,12,8,7];
$max_value = max($tab);
$nb_digits = floor(log($max_value, 2)) + 1;
radixSort($tab, $nb_digits);
Ok, thanks to a friend, i found my problem : the counting sort implementation which i use stacks the same digit numbers using the counter as top index, and then decrementing it. And that's ok for counting sort (so one iteration), but it scrambles everything when you use it in radix sort (multiple counting sort iterations).
So i used instead a method in which you shift your counters one time right, which gives you for the n+1 digit your starting point, and then increment it.
And boom you're good to go.
function countSort2(&$arr, $digit) {
$bits = $output = array_fill(0, NB_ELEMS, 0); // output array
$count = [0,0];
// Store count of occurrences in count[]
for ($i = 0; $i < NB_ELEMS; $i++) {
$nb = $arr[$i];
$bit = ($nb >> $digit) & 1;
$bits[$i] = $bit;
$count[$bit]++;
}
// Cumulative count shifted
$count[1] = $count[0];
$count[0] = 0;
// Rearranging
for ($i = 0; $i < NB_ELEMS; $i++) {
$nb = $arr[$i];
$bit = $bits[$i];
$output[$count[$bit]] = $nb;
$count[$bit]++;
}
// Switch arrays
$arr = $output;
}
I also made some tests (1M items, max value 1M, 100 iterations), and a method storing values instead of counting them, and merging thereafter seems twice as fast (function just after that). Anyway, both methods are far under native sort performance.
Any comment appreciated
function byDigitSortArrayMerge(&$arr, $digit) {
$output = array_fill(0, NB_ELEMS - 1, 0); // output array
$bits = array_fill(0, NB_ELEMS - 1, 0); // output array
$by_bit = [[], []];
// Store count of occurrences in count[]
for ($i = 0; $i < NB_ELEMS; $i++) {
$nb = $arr[$i];
$bit = ($nb >> $digit) & 1;
$by_bit[$bit][] = $nb;
}
$arr = array_merge($by_bit[0], $by_bit[1]);
}
Hello there i am making a program which will let me help generate a random string with a specified limit and random strings of *&# but then the combination of *&# should not repeat.
Ex: if I input 3 then the O/P should be
#**
**#
**#
It should generate a random string of length 3 up to 3 rows with different patterns also the pattern should not repeat. I am using the below code but not able to attain it.
$n = 3;
for($i = 0; $i < n; $i++)
{
for($j=0;$j<=$n;j++)
{
echo "*#";
}
echo "<br />";
}
But I am not able to generate the output, where is my logic failing?
If you want to make sure the same pattern doesn't show up more than once you'll have to keep a record of the generated strings. In the most basic form it could look like this:
public function generate() {
$amount = 3; // The amount of strings you want.
$generated_strings = []; // Keep a record of the generated strings.
do {
$random = $this->generateRandomString(); // Generate a random string
if(!in_array($random, $generated_strings)) { // Keep the record if its not already present.
$generated_strings[] = $random;
}
} while(sizeof($generated_strings) !== $amount); // Repeat this process until you have three strings.
print_r($generated_strings);
}
public function generateRandomString($length = 3) {
$characters = '*&#';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Not necessarily the most optimized algorithm but it should work.
I am using a string generator, somewhat random, combining the chars you have provided. The second part is filling the output array with generated strings that are not already present.
<?php
function randomize($n) {
$s = '';
for ($i = 0; $i < $n; $i++) {
$s. = (rand(0, 10) < 5 ? '*' : '#');
}
return $s;
}
$n = 3;
$output = array();
for ($i = 0; $i < $n; $i++) {
$tmp = randomize($n);
while (in_array($tmp, $output)) {
$tmp = randomize($n);
}
$output[] = $tmp;
}
print_r($output);
Visible here
You can use a while loop and array unique to do this.
I first have an array with possible chars.
Then I loop until result array is desired lenght.
I use array unique to remove any duplicates inside the loop.
I use rand(0,2) to "select" a random character from possible characters array.
$arr = ["*", "&", "#"];
$res = array();
$n =7;
While(count($res) != $n){
$temp="";
For($i=0;$i<$n;$i++){
$temp .= $arr[Rand(0,count($arr)-1)];
}
$res[] = $temp;
$res = array_unique($res);
}
Var_dump($res);
https://3v4l.org/Ko4Wd
Updated with out of scope details not clearly specified by OP.
I am trying to make card game.
I have 6 variable that are stored in array. Than I use fisherYates method to randomize array, and display four of them.
Problem is, when I randomize it this way only, it will give only random output of those six, with all different types.
So I want that some repeats like, if you draw four cards, you get output of
ex: club, club, diamond,heart, or heart, star,star,heart.. if you get a point..
I thought to do it like this way: put the array in loop of 4 times, and every time it loops, it stores first, or last value in new array, so that way, I can have greater chances of combination of same cards in output array.
But I'm stuck, and I don't know how to do it :/
this is what I've tried so far
$diamond = 'cube.jpg';
$heart = 'heart.jpg';
$spade = 'spade.jpg';
$club = 'tref.jpg';
$star='star.jpg';
$qmark='qmark.jpg';
$time=microtime(35);
$arr=[$diamond,$heart,$spade,$club,$star,$qmark];
function fisherYatesShuffle(&$items, $time)
{
for ($i = count($items) - 1; $i > 0; $i--)
{
$j = #mt_rand(0, $i);
$tmp = $items[$i];
$items[$i] = $items[$j];
$items[$j] = $tmp;
}
return $items;
}
$i=0;
do {
$niz[$i]=fisherYatesShuffle($arr,$time);
reset($niz);
$i++;
} while ($i <= 3);
Got a solution. Was just to simply do foreach of first element of multidimensional array :)
Code goes like this:
$diamond = 'cube.jpg';
$heart = 'heart.jpg';
$spade = 'spade.jpg';
$club = 'tref.jpg';
$star='star.jpg';
$qmark='qmark.jpg';
$time=microtime(35);
$arr=[$diamond,$heart,$spade,$club,$star,$qmark];
$niz=array();
$i=0;
do {
$niz[$i]=fisherYatesShuffle($arr,$time);
//reset($niz);
$i++;
} while ($i <= 3);
foreach ($niz as $key ) {
$randomArr[]=$key[0]; ;
}
function fisherYatesShuffle(&$items, $time)
{
for ($i = count($items) - 1; $i > 0; $i--)
{
$j = #mt_rand(0, $i);
$tmp = $items[$i];
$items[$i] = $items[$j];
$items[$j] = $tmp;
}
return $items;
}
print_r($randomArr);
I've recently send my CV to one company that was hiring PHP developers. They send me back a task to solve, to mesure if I'm experienced enough.
The task goes like that:
You have an array with 10k unique elements, sorted descendant. Write function that generates this array and next write three different functions which inserts new element into array, in the way that after insert array still will be sorted descendant. Write some code to measure speed of those functions. You can't use PHP sorting functions.
So I've wrote function to generate array and four functions to insert new element to array.
/********** Generating array (because use of range() was to simple :)): *************/
function generateSortedArray($start = 300000, $elementsNum = 10000, $dev = 30){
$arr = array();
for($i = 1; $i <= $elementsNum; $i++){
$rand = mt_rand(1, $dev);
$start -= $rand;
$arr[] = $start;
}
return $arr;
}
/********************** Four insert functions: **************************/
// for loop, and array copying
function insert1(&$arr, $elem){
if(empty($arr)){
$arr[] = $elem;
return true;
}
$c = count($arr);
$lastIndex = $c - 1;
$tmp = array();
$inserted = false;
for($i = 0; $i < $c; $i++){
if(!$inserted && $arr[$i] <= $elem){
$tmp[] = $elem;
$inserted = true;
}
$tmp[] = $arr[$i];
if($lastIndex == $i && !$inserted) $tmp[] = $elem;
}
$arr = $tmp;
return true;
}
// new element inserted at the end of array
// and moved up until correct place
function insert2(&$arr, $elem){
$c = count($arr);
array_push($arr, $elem);
for($i = $c; $i > 0; $i--){
if($arr[$i - 1] >= $arr[$i]) break;
$tmp = $arr[$i - 1];
$arr[$i - 1] = $arr[$i];
$arr[$i] = $tmp;
}
return true;
}
// binary search for correct place + array_splice() to insert element
function insert3(&$arr, $elem){
$startIndex = 0;
$stopIndex = count($arr) - 1;
$middle = 0;
while($startIndex < $stopIndex){
$middle = ceil(($stopIndex + $startIndex) / 2);
if($elem > $arr[$middle]){
$stopIndex = $middle - 1;
}else if($elem <= $arr[$middle]){
$startIndex = $middle;
}
}
$offset = $elem >= $arr[$startIndex] ? $startIndex : $startIndex + 1;
array_splice($arr, $offset, 0, array($elem));
}
// for loop to find correct place + array_splice() to insert
function insert4(&$arr, $elem){
$c = count($arr);
$inserted = false;
for($i = 0; $i < $c; $i++){
if($elem >= $arr[$i]){
array_splice($arr, $i, 0, array($elem));
$inserted = true;
break;
}
}
if(!$inserted) $arr[] = $elem;
return true;
}
/*********************** Speed tests: *************************/
// check if array is sorted descending
function checkIfArrayCorrect($arr, $expectedCount = null){
$c = count($arr);
if(isset($expectedCount) && $c != $expectedCount) return false;
$correct = true;
for($i = 0; $i < $c - 1; $i++){
if(!isset($arr[$i + 1]) || $arr[$i] < $arr[$i + 1]){
$correct = false;
break;
}
}
return $correct;
}
// claculates microtimetime diff
function timeDiff($startTime){
$diff = microtime(true) - $startTime;
return $diff;
}
// prints formatted execution time info
function showTime($func, $time){
printf("Execution time of %s(): %01.7f s\n", $func, $time);
}
// generated elements num
$elementsNum = 10000;
// generate starting point
$start = 300000;
// generated elements random range 1 - $dev
$dev = 50;
echo "Generating array with descending order, $elementsNum elements, begining from $start\n";
$startTime = microtime(true);
$arr = generateSortedArray($start, $elementsNum, $dev);
showTime('generateSortedArray', timeDiff($startTime));
$step = 2;
echo "Generating second array using range range(), $elementsNum elements, begining from $start, step $step\n";
$startTime = microtime(true);
$arr2 = range($start, $start - $elementsNum * $step, $step);
showTime('range', timeDiff($startTime));
echo "Checking if array is correct\n";
$startTime = microtime(true);
$sorted = checkIfArrayCorrect($arr, $elementsNum);
showTime('checkIfArrayCorrect', timeDiff($startTime));
if(!$sorted) die("Array is not in descending order!\n");
echo "Array OK\n";
$toInsert = array();
// number of elements to insert from every range
$randElementNum = 20;
// some ranges of elements to insert near begining, middle and end of generated array
// start value => end value
$ranges = array(
300000 => 280000,
160000 => 140000,
30000 => 0,
);
foreach($ranges as $from => $to){
$values = array();
echo "Generating $randElementNum random elements from range [$from - $to] to insert\n";
while(count($values) < $randElementNum){
$values[mt_rand($from, $to)] = 1;
}
$toInsert = array_merge($toInsert, array_keys($values));
}
// some elements to insert on begining and end of array
array_push($toInsert, 310000);
array_push($toInsert, -1000);
echo "Generated elements: \n";
for($i = 0; $i < count($toInsert); $i++){
if($i > 0 && $i % 5 == 0) echo "\n";
printf("%8d, ", $toInsert[$i]);
if($i == count($toInsert) - 1) echo "\n";
}
// functions to test
$toTest = array('insert1' => null, 'insert2' => null, 'insert3' => null, 'insert4' => null);
foreach($toTest as $func => &$time){
echo "\n\n================== Testing speed of $func() ======================\n\n";
$tmpArr = $arr;
$startTime = microtime(true);
for($i = 0; $i < count($toInsert); $i++){
$func($tmpArr, $toInsert[$i]);
}
$time = timeDiff($startTime, 'checkIfArraySorted');
showTime($func, $time);
echo "Checking if after using $func() array is still correct: \n";
if(!checkIfArrayCorrect($tmpArr, count($arr) + count($toInsert))){
echo "Array INCORRECT!\n\n";
}else{
echo "Array OK!\n\n";
}
echo "Few elements from begining of array:\n";
print_r(array_slice($tmpArr, 0, 5));
echo "Few elements from end of array:\n";
print_r(array_slice($tmpArr, -5));
//echo "\n================== Finished testing $func() ======================\n\n";
}
echo "\n\n================== Functions time summary ======================\n\n";
print_r($toTest);
Results can be found here: http://ideone.com/1xQ3T
Unfortunately I was rated only 13 points out of 30 for this task (don't know how it was calculated or what exactly was taken in account). I can only assume that's because there are better ways to insert new element into sorted array in PHP. I'm searching this topic for some time now but couldn't find anything good. Maby you know of better approach or some articles about that topic?
Btw on my localhost (PHP 5.3.6-13ubuntu3.6 with Suhosin-Patch, AMD Athlon(tm) II X4 620) insert2() is fastest, but on ideone (PHP 5.2.11) insert3() is fastest.
Any ideas why? I suppose that array_splice() is tuned up somehow :).
//EDIT
Yesterday I thought about it again, and figured out the better way to do inserts. If you only need sorted structure and a way to iterate over it and your primary concern is the speed of insert operation, than the best choise would be using SplMaxHeap class. In SplMaxHeap class inserts are damn fast :) I've modified my script to show how fast inserts are. Code is here: http://ideone.com/vfX98 (ideone has php 5.2 so there won't be SplMaxHeap class)
On my localhost I get results like that:
================== Functions time summary ======================
insert1() => 0.5983521938
insert2() => 0.2605950832
insert3() => 0.3288729191
insert4() => 0.3288729191
SplMaxHeap::insert() => 0.0000801086
It may just be me, but maybe they were looking for readability and maintainability as well?
I mean, you're naming your variables $arr, and $c and $middle, without even bothering to place proper documentation.
Example:
/**
* generateSortedArray() Function to generate a descending sorted array
*
* #param int $start Beginning with this number
* #param int $elementsNum Number of elements in array
* #param int $dev Maximum difference between elements
* #return array Sorted descending array.
*/
function generateSortedArray($start = 300000, $elementsNum = 10000, $dev = 30) {
$arr = array(); #Variable definition
for ($i = 1; $i <= $elementsNum; $i++) {
$rand = mt_rand(1, $dev); #Generate a random number
$start -= $rand; #Substract from initial value
$arr[] = $start; #Push to array
}
return $arr;
}
I am a newbie in Php and this might be a quite basic question.
I would like to set string array and put values to array then get values which
I put to string array. so basically,
I want
ArrayList arr = new ArrayList<String>;
int limitSize = 20;
for(i = 0; i < limitSize; i++){
String data = i + "th";
arr.add(data);
System.out.println(arr.get(i));
};
How can I do this in php?
It's far less verbose in PHP. Since it isn't strongly typed, you can just append any values onto the array. It can be done with an incremental for loop:
$array = array();
$size = 20;
for ($i = 0; $i < $size; $i++) {
// Append onto array with []
$array[] = "{$i}th";
}
...or with a foreach and range()
foreach (range(0,$size-1) as $i) {
// Append onto array with []
$array[] = "{$i}th";
}
It is strongly recommended that you read the documentation on PHP arrays.
$arr = array();
$limitSize = 20;
for($i = 0; $i < $limitSize; $i++){
$data = $i . "th";
$arr[] = $data;
echo $arr[$i] . "\n";
}
In php arrays are always dynamic. so you can just use array_push($arrayName,$val) to add values and use regular for loop processing and do
for ($i=0; $i<count($arrName); $i++) {
echo $arr[$i];
}
to print /get value at i.