what i want to do is something like memory game, but I keep cannot get the same number with the out put
$numbers = range(1, 15);
shuffle($numbers);
foreach($numbers as $key){
echo $numbers[array_rand($numbers)];
break;
}
now the out put will be something like this
4 2 3 3
1 5 3 6
2 3 4 5
10 9 8 10
but how to I do it as rand array and with same 2 array number, which is i can match the number.
what i want in out put is
2 3 1 4
3 4 2 1
5 6 9 7
7 9 6 5
so like this i can get the match in 2 same number
any idea how to do it?
thanks
Your question is a bit confusing and vague. I extrapolate that you want to shuffle and display an array of numbers, two of each, in random order. To do that:
<?php
$numbers = range(1, 5);
$numbers = array_merge($numbers, $numbers);
shuffle($numbers);
echo implode(' ', $numbers);
This outputs, for instance, 3 5 1 5 1 2 3 4 2 4.
The array_rand() call in the foreach in your code makes absolutely no sense. If the above isn't what you wanted, please revise your question to be clearer.
First you have to do an array with couple values
// Generate array with values from 1 to 8
$arNumbers = range(1, 8);
// Duplicate the array so get copy of each number
$arNumbers = array_merge($arNumbers, $arNumbers);
// Shuffle the array
shuffle($arNumbers);
// And now display them
foreach($arNumbers as $nNumber)
{
// Do some business
}
Hope it helps :)
Try this. It is a simple way.
$numbers=range(1, 15);
//Get 4 unique random keys from $numbers array.
$rand_keys = array_rand($numbers, 4);
//print out the random numbers using the
//random keys.
foreach ($rand_keys as $k=>$i) {
echo $numbers[$i]." ";
}
Hope this will helps you...
If I get you correctly, you can achieve what you want to do with the following:
// make sure these are even numbers
$rows = 4;
$cols = 4;
$set = range(1, ($rows * $cols) / 2);
$numbers = array_merge($set, $set);
shuffle($numbers);
foreach (array_chunk($numbers, $cols) as $row) {
foreach ($row as $col) {
printf('%-5d', $col);
}
echo "\n";
}
Outputs:
3 7 2 1
4 6 8 5
6 3 8 4
2 5 7 1
Do something like:
$numbers = range(1, 15);
shuffle($numbers);
$used_numbers = array();
foreach($numbers as $key){
$this_number = $numbers[array_rand($numbers)];
$used_numbers[] = $this_number;
echo $this_number;
break;
}
$_SESSION['numbers'] = $used_numbers;
Then you can use the $_SESSION to access the numbers on another page (after reload perhaps), or use the same $used_numbers array to access them.
If you try:
$numbers = range(1, 15);
shuffle($numbers);
$used_numbers = array();
foreach($numbers as $key){
$this_number = $numbers[array_rand($numbers)];
$used_numbers[] = $this_number;
echo $this_number;
break;
}
echo '<br />';
foreach($used_numbers AS $number) {
echo $number;
}
You will see it returns the same number.
Related
I want to get elements from an array like this: get first three element, then four elements, then again three elements, and again four, and so on in a loop.
For example:
0 1 2
3 4 5 6
7 8 9
10 11 12 13
and so on....
I tried something like this:
foreach($items as $key => $item) {
if($key <= 2) {
echo 'test';
}
if($key > 2 && $key < 6) {
echo 'other test';
}
if($key > 6 && $key < 9) {
echo 'test';
}
}
However, I don't want to use if() like these, because I don't know how many items will be in the array: it comes from a database.
I think, I need something like array_chunk($items, 3) but for size parameter I need 3 and 4 in loop
Could be like this you can make another array of specifying the number of elements you want in each iteration.
<?php
$number_of_elements = [3,4,3,4];
$your_array = ['a', 'b','c','d','e'];
foreach($number_of_elements as $number){
for($i = 0; $i<=$number; $i++){
$result = $your_array[$i];
print_r($result);
}
print_r('<br>');
}
In JavaScript you can solve your problem using a for loop and the built in slice function of the array.
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let offset = 0;
for(let i = 0; i < array.length;){
offset = offset === 3 ? 4 : 3;
const subArray = array.slice(i, i + offset);
console.log(subArray);
i += offset;
}
I have a multidimentionnal array like this example
$arr = array (
range(9,4),
range(8,0),
range(2,7),
range(-1,17)
);
after showing its content I get this
9 8 7 6 5 4
8 7 6 5 4 3 2 1 0
2 3 4 5 6 7
-1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Now the result I want to get is this
-1 0 0 1 1 2
2 2 3 3 3 4 4 4 4
5 5 5 5 6 6
6 6 7 7 7 7 8 8 8 9 9 10 11 12 13 14 15 16 17
I defined a function that sorts the array and returns the result I need, but I want to know if there is a simple way to do it using predefined functions or a simple and fast algorithm
this is my function
function sort_multi($arr)
{
$length = 0;
foreach ($arr as $value)
$length += count($value);
$sorted = false;
while(!$sorted)
{
$x = 0;
$y = 0;
$sorted = true;
while(($x+$y)<($length-1) && isset($arr[$x][$y]))
{
$new_x = isset($arr[$x][$y+1])?$x:($x+1);
$new_y = isset($arr[$x][$y+1])?($y+1):0;
if(($new_x+$new_y)<$length && isset($arr[$new_x][$new_y]))
if($arr[$x][$y] > $arr[$new_x][$new_y])
{
perm($arr[$x][$y], $arr[$new_x][$new_y]);
$sorted=false;
}
$x = $new_x;
$y = $new_y;
}
}
return $arr;
}
the definition of perm is
function perm(&$a,&$b)
{
$inter = $a;
$a = $b;
$b = $inter;
}
I think array_walk_recursive could work well for something like this.
// Fill a temp array with all the values from the multidimensional array...
$temp = array();
array_walk_recursive($arr, function($item) use (&$temp) {
$temp[] = $item;
});
sort($temp); // sort it...
// refill the multidimensional array with the sorted values.
array_walk_recursive($arr, function(&$item) use (&$temp) {
$item = array_shift($temp);
});
I don't know which is the best way. But you can do it brute force: Sample Output
$arr = array (
range(9,4),
range(8,0),
range(2,7),
range(-1,17),
);
// simple checking of number of items per batch (since this is sort of like array_chunk, but jagged)
$chunks = array_map(function($batch){ return count($batch); }, $arr);
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)) as $v) {
$values[] = $v; // simple flattening
}
sort($values); // sort ascending (prepping)
foreach($chunks as $key => $batch) {
// number of items in a batch
// simple cutting (i can't find the function for this, i think there is)
for($x = 0; $x < $batch; $x++) {
$final[$key][] = $values[$x];
unset($values[$x]);
}
$values = array_values($values); // reindex again (resetter)
}
echo '<pre>';
print_r($final);
I Usually prefer a Bubble Sort, because at longest it will take the same as brute force. Usually it is slightly more efficient though.
I have the following array
$example=array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
$limit=4 // 4 at the beginning only...
//it used to get incremented automatically to 8,12,16....
At first i want 1,2,3,4as an output for which i have done
foreach($example as $eg)
{
if($eg>$limit)
continue;
}
and i am easily getting 1,2,3,4 at the first then 1,2,3,4,5,6,7,8 then1,2,3,4,5,6,7,8,9,10,11,12
But now i what i want is 1,2,3,4 at the very beginning then 5,6,7,8 then 9,10,11,12 lyk this... how can i get that???
please do help me... :)
AS the
foreach($example as $eg)
{
if($eg>$limit)
continue;
}
is returning only 1,2,3,4 at $limit=4 and 1,2,3,4,5,6,7,8 at $limit=8
i need 1,2,3,4 at $limit=4 and 5,6,7,8 at $limit=8
Have you tried using the helpful built-in functions?
array_chunk($example,$limit);
Alternatively, for more page-like behaviour:
$pagenum = 2; // change based on page
$offset = $pagenum * $limit;
array_slice($example,$offset,$limit);
You would first chunk the array so each chunk has 4 elements, then loop through each chunk:
To change the numbers shown depending on which group, you could do:
$group = $_GET['group'];
$items = array_chunk($example, ceil(count($example)/4)[$group-1];
echo implode(", ", $items);
Then you can go to
yoursite.com/page.php?group=1
And it will output
1, 2, 3, 4
And when you go to
yoursite.com/page.php?group=2
It will output
5, 6, 7, 8
etc.
You can try something like this
$example=array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
$limit = 8;
$limit -= 4;
for($i = $limit; $i < ($limit + 4); $i++)
{
echo $example[$i].' ';
}
Output
//for $limit 4 output 1 2 3 4
//for $limit 8 output 5 6 7 8
//for $limit 16 output 13 14 15 16
I am trying to figure out how I can loop out possible combinations of a x amount of integers to sum a specifik number.
Let's say, I have number 7 and I need to figure out how I can sum that number with integers in pairs 3.
1+2+4 = 7
3+3+1 = 7
5+1+1 = 7
2+2+3 = 7
Repeated combinations of numbers doesn't interest me, e.g.:
1+2+4 = 7
2+4+1 = 7
4+2+1 = 7
Anyone got any ideas of how I should proceed to reach this result?
Thanks.
Here is the solution for your problem.
function printPartitions($target, $max, $s){
if($target === 0 )
echo $s;
else
{
if($max > 1)
{
printPartitions($target, $max-1, $s);
}
if($max <= $target)
{
printPartitions($target-$max, $max, $max . " " . $s);
}
}
}
printPartitions(5, 5, "<br/>");
You have to specify the $target Value, $max value.
e.g.
printPartitions(7, 7, "<br/>");
It will give you output like:
1 1 1 1 1 1 1
1 1 1 1 1 2
1 1 1 2 2
1 2 2 2
1 1 1 1 3
1 1 2 3
2 2 3
1 3 3
1 1 1 4
1 2 4
3 4
1 1 5
2 5
1 6
7
I've got a solution to my problem. I feel I should defientely share it here, if anyone would ever need it. My solutions is based on this post: https://stackoverflow.com/a/19067884/3293843
<?php
function sampling($chars, $size, $combinations = array()) {
# if it's the first iteration, the first set
# of combinations is the same as the set of characters
if (empty($combinations)) {
$combinations = $chars;
}
# we're done if we're at size 1
if ($size == 1) {
return $combinations;
}
# initialise array to put new values in
$new_combinations = array();
# loop through existing combinations and character set to create strings
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination .'#'. $char;
}
}
# call same function again for the next iteration
return sampling($chars, $size - 1, $new_combinations);
}
// example
$chars = array('1', '2', '3','4');
$target = 7;
$maxLengthOfIntegers = 3;
$output = sampling($chars, $maxLengthOfIntegers);
$repeatedEntries = array();
//presenting the output
foreach($output as $out){
$explodeOut = explode('#',$out);
sort($explodeOut);
if(array_sum($explodeOut) == $target){
$sortedPattern = implode('',$explodeOut);
if(!in_array($sortedPattern,$repeatedEntries)){
echo $sortedPattern.'<br/>';
$repeatedEntries[] = $sortedPattern;
}
}
}
?>
Thank you for your time and efforts.
Regards,
Jacob
you can try this algorithm
$ans = array();
for($i=1;$i<=5;$i++)
{
$i1 = 7-$i;
$i2 = intval($i1 - $i);
$value = $i."+".$i1."+".$i2;
$ans = array_unshift($ans,$value);
}
print_r($ans);
hope this helps.. PLease let me know
i have this php code:
<?php
function GetRand($N, $min=1, $max=59) {
$Local = array();
mt_srand(time());
for ($i=0;$i<$N;$i++)
$LocalArr [] = mt_rand($min, $max);
return $LocalArr;
}
$A = GetRand(5);
foreach($A as $K=>$v) echo "$v ";
?>
The result is 5 numbers between 1 and 59. The problem is that sometimes i receive results like this:
43 9 13 9 7
In those 5 numbers, there is the number 9 twice. I would like to change the php code, so everytime when there is a number that repeats, this number should be skipped and instead of the repeated number should be represented another number, so that every time i have 5 numbers and no duplicates between them.
Thank you very much in Advance!
$numbers = range(1, 59);
shuffle($numbers);
var_dump(array_slice($numbers, 0, 5));
Try this (untested):
<?php
$randoms = array(rand(1,59));
while(sizeof($randoms) <= 5) {
$randoms[] = rand(1,59);
$randoms = array_unique($randoms);
}