I need to get 50 random numbers out of range 1-100 without repeating. The current way i do is :
$array = array();
while (count($array) <= 50) {
$temp = random_int(1,100);
if (!in_array($temp, $array))
$array[] = $temp;
}
However, the looping is too many because I need to generate for more than 100,000 times.
Is there other ways that I can get a 50 random non-repeating numbers without looping ?
For example:
$number= range(1,100);
$array = array_slice(shuffle($number),0,50);
I can't use shuffle because it uses pseudo random number.
Is there other ways to achieve what I need, or ways that could shorten time.
pre fill a array of numbers and pick from them, and then remove it.
it prevents the unnecessary random generations you have
$numbers = [];
for ($i = 1; $i <= 100; $i++) {
$numbers[] = $i;
}
$randomNumbers = [];
for ($i = 1; $i <= 50; $i++) {
$r = rand(0, count($numbers) - 1);
$randomNumbers[] = $numbers[$r];
array_splice($numbers, $r, 1);
}
This would be my approach:
This gives you 50 numbers in any case, and they are defenitely different from each other. PLUS: you dont have to prefill some other array:
$start = microtime(true);
for($i = 0; $i <= 100000; $i++){
$arr = [];
while(sizeof($arr) < 50){
$num = rand(1, 100);
$arr[$num] = $num;
}
if(array_unique($arr) !== $arr || sizeof($arr) !== 50 ){
print("FAIL");
}
//print(array_unique($arr) == $arr ? "true" : "false");print("<br>");
//print(sizeof($arr));print("<br>");
//print_r(array_count_values ($arr));print("<br>");
//print_r($arr);print("<br>");
}
$time_elapsed_secs = microtime(true) - $start;
print($time_elapsed_secs);print("<br>");
Running this 100000 times takes about 0.4sec for me.
The actual generation is done in this part:
$arr = [];
while(sizeof($arr) < 50){
$num = rand(1, 100);
$arr[$num] = $num;
}
We can do in 2 steps:
$x = 0;
$arr = [];
while($x < 50){
$tmp = rand(1, 100);
if(!in_array($tmp, $arr)){
$arr[] = $tmp;
$x++;
}
}
I am trying to deal a hand of five cards to a player and score them. My scoring program seems to be working fine, but I am running into the issue of duplicate cards getting dealt from time to time. I tried using a while loop to check for duplicate cards, but this seems kind of hackish. My code is below. Please keep in mind that I am definitely a neophyte, so the simpler the solution the better! Thanks so much.
// create suits array
$suits = array("996", "997", "998", "999");
// create faces array
$faces = array();
$faces[1] = "1";
$faces[2] = "2";
$faces[3] = "3";
$faces[4] = "4";
$faces[5] = "5";
$faces[6] = "6";
$faces[7] = "7";
$faces[8] = "8";
$faces[9] = "9";
$faces[10] = "10";
$faces[11] = "11";
$faces[12] = "12";
$faces[13] = "13";
// create player's hand
$card = array();
for ($i = 0; $i < 5; $i++)
{
$face_value = shuffle($faces);
$suit_value = shuffle($suits);
$card[$i] = $faces[$face_value].$suits[$suit_value];
$counter = 0;
while ($counter < 100)
{
if (in_array($card[$i], $card))
{
$face_value = shuffle($faces);
$suit_value = shuffle($suits);
$card[$i] = $faces[$face_value].$suits[$suit_value];
}
$counter++;
}
print ("<img src=\"../images/4/$card[$i].gif\">");
}
It might be more efficient to simply set up an array that has 52 elements, one for each of the cards.
$cards = range(0,51);
shuffle($cards);
$hand = array();
for ($i = 0; $i < 5; $i++)
{
$hand[$i] = $cards[$i];
}
Note that you can extract the suit and rank of a card $i simply, by doing
$suit = $hand[$i] % 4;
$rank = $hand[$i] / 4;
This will prevent duplicates.
EDIT: Suit and rank were reversed. They should be correct now.
Because you said you like it easy, you could create your arrays with range().
To avoid getting duplicate hands, check the $card array with before assigning the new hand.
the new code would look like:
// create suits array
$suits = range(996, 999);
// create faces array
$faces = range(0, 13);
// create player's hand
$card = array();
while ( count($card) < 5 )
{
$face_value = shuffle($faces);
$suit_value = shuffle($suits);
$newcard = $faces[$face_value].$suits[$suit_value];
if ( in_array($card, $newcard) ) {
$card[] = $newcard;
print ("<img src=\"../images/4/$newcard.gif\">");
}
}
I would definitely create a deck with all 52 cards in it like so:
// create suits array
$suits = range(996, 999);
// create entire deck
$deck = range(0, 51);
shuffle($deck);
// create player's hand
for ($i = 0; $i < 5; $i++) {
$suit_value = $suits[$deck[$i] % 4];
$face_value = floor($deck[$i] / 4) + 1;
print ("<img src=\"../images/4/{$face_value}{$suit_value}.gif\">");
}
For example:
$size = 0;
$array = $array;
$size = 1;
$array = $array[x];
$size = 5;
$array = $array[x][x][x][x][x];
I got a $config array that can either have 1 dimension or many. Depending on setting of the var $size the elements I need walk gonna be on that position. If size = 1, I will be looking for $config[1]. If size = 2 I will be looking for $config[1][1] ...
Thanks,
$foo = $array;
for($i=0;$i<$size;++$i) {
$foo = $foo[x];
}
$array = $array[x][x][x][x][x];
for ($x = 0; $x < 5; $x++) {
if (!is_array($array[1])) break;
$array = $array[1];
}
You can make infinite loop and reach end of array.
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Is there a php function like python's zip?
(14 answers)
Closed 10 months ago.
So, imagine you have 3 arrays:
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
And you want to combine them into new arrays based on index:
1,6,11
2,7,12
3,8,13
4,9,14
5,10,15
What on earth could achieve this? Also, the total number of arrays is not known.
EDIT: Here's a snippet of my code so far (pulling data from a DB):
<?php
$ufSubmissions = $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_user_feedback WHERE user = '$ufUser' ORDER BY date DESC") );
$cleanedResponses = array();
foreach ($ufSubmissions as $submission) {
$cleanedResponses[] = unserialize($submission->responses);
}
array_map(null, $cleanedResponses));
?>
Doesn't seem to be working though, even $cleaned responses is an array of arrays.
Mostly like Alex Barrett's answer, but allows for an unknown number of arrays.
<?php
$values = array(
array(1,2,3,4,5),
array(6,7,8,9,10),
array(11,12,13,14,15),
);
function array_pivot($values)
{
array_unshift($values, null);
return call_user_func_array('array_map', $values);
}
print_r(array_pivot($values));
If your arrays are all the same length, you can pass as many as you want to the array_map function with null as the callback parameter.
array_map(null,
array(1, 2, 3, 4, 5),
array(6, 7, 8, 9, 10),
array(11, 12, 13, 14, 15));
The above will return the following two-dimensional array:
array(array(1, 6, 11),
array(2, 7, 12),
array(3, 8, 13),
array(4, 9, 14),
array(5, 10, 15));
This is a documented trick, so quite safe to use.
$ret = array();
for ($i =0; $i < count($input[0]); $i++){
$tmp = array();
foreach ($input as $array) {
$tmp[] = $array[$i];
}
$ret[] = $tmp;
}
Em... What's the problem? If they are equal sized, then you do
<?php
$a = array(1,2,3,4,5);
$b = array(6,7,8,9,10);
$c = array(11,12,13,14,15);
$d = array();
for ($i = 0; $i < sizeof($a); $i++) {
$d[] = array($a[$i], $b[$i], $c[$i]);
}
var_dump($d);
This is not tested, read it to get the idea instead of paste it.
The point is to put everything alltoghether in a feed and then redistribute it onto new arrays of a max length, the last one could not be full.
<?php
// initial vars
$max_size = 3; // of the new arrays
$total_array = $a + $b + $c; // the three arrays summed in the right order
$current_size = length($total_array);
$num_of_arrays = ceil($current_size / $max_size);
// redistributing
$result_arrays = array();
for($i = 0; $i < $num_of_arrays; $i++){ // iterate over the arrays
$new_array= array();
for($t = 0; $t < $max_size){
$pos = $num_of_arrays * $t + $i;
if(isset($total_array[$pos]) {
$new_array[] = $total_array[$pos];
}
}
$result_arrays[] = $new_array;
}
?>
// This takes an unlimited number of arguments and merges into arrays on index
// If there is only 1 argument it is treated as an array of arrays
// returns an array of arrays
function merge_on_indexes () {
$args = func_get_args();
$out = array();
if (count($args) == 1) for ($i = 0; isset($args[0][$i]); $i++) for ($j = 0; isset($args[0][$i][$j]); $j++) $out[$j][] = $args[0][$i][$j]; else for ($i = 0; isset($args[$i]); $i++) for ($j = 0; isset($args[$i][$j]); $j++) $out[$j][] = $args[$i][$j];
return $out;
}
// Usage examples
// Both return array('data1','data3','data5'),array('data2','data4','data6')
$arr1 = array('data1','data2');
$arr2 = array('data3','data4');
$arr2 = array('data5','data6');
$result = merge_on_indexes($arr1,$arr2);
print_r($result);
$multiDimArr = array(
array('data1','data2'),
array('data3','data4'),
array('data5','data6')
);
$result = merge_on_indexes($multiDimArr);
print_r($result);
$arr = get_defined_vars(); //gets all your variables
$arrCount = 0;
$arrOfarrs = array();
foreach($arr as $var){ //go through each variable
if(is_array($var)){ //and see if it is an array
$arrCount++; //we found another array
for($i == 0;$i < count($var); $i++){ //run through the new array
$arrOfarrs[$i][] == $var[$i]; //and add the corresponding elem
}
}
}
I have two arrays like this
array x [Firefox,IE,Chrome,Opera]
array y [40,30,25,5]
Required final [[Firefox,40],[IE,30],[Chrome,25],[Opera,5]]
I need this in PHP.I think I can run a for loop and do something like this .
final23 [0][i] = x[i];
final23 [1][i] = y[i];
Is there any better way or built in function in PHP ?
$result = array();
$size = max(count($x), count($y));
for ($i = 0; $i < $size; $i++) {
$result[] = array(
isset($x[$i]) ? $x[$i] : null,
isset($y[$i]) ? $y[$i] : null
);
}
$x = array("Mozzila","IE","Firefox","Opera");
$y = array(40,30,25,5);
$final = array();
$i = 0;
foreach($x as $a){
$final[] = array($a,$y[$i]);
$i++;
}
Learn about Associated array.
$arr = new Array("40"=>"FireFox","30"=>"IE","25"=>"Chrome","5"=>"Opera");