Related
First of all, thanks for looking at my question.
I only want to add up the positive numbers in the $numbers using a if,else statement.
$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = 0;
if ($numbers < 0 {
$numbers = 0;
}
elseif (now i want only the positive numbers to add up in the $total.)
I'm an first years student and I am trying to understand the logic.
I'm not gonna give the direct answer, but the way here is you need a simple loop, can be for or a foreach loop, so every iteration you just need to check whether the current number in the loop is grater than zero.
Example:
$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = 0;
foreach($numbers as $number) { // each loop, this `$number` will hold each number inside that array
if($number > 0) { // if its greater than zero, then make the arithmetic here inside the if block
// add them up here
// $total
} else {
// so if the number is less than zero, it will go to this block
}
}
Or as michael said in the comments, a function also can be used in this purpose:
$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = array_sum(array_filter($numbers, function ($num){
return $num > 0;
}));
echo $total;
$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = 0;
foreach($numbers as $number)
{
if($number > 0)
$total += $number;
}
this loops through all elements of the array(foreach = for each number in the array) and checks if the element is bigger than 0, if it is, add it to the $total
I have an array:
[a, b, c, d, e, f, ... , z]
and I would generate the set of all possible subarrays, withuout repetition, whose cardinality is between X and Y.
Let's assume php:
$array = array(1, 2, 3, 4, 5, 6, 7, 8);
$results = myFunction($array, 3, 5);
My function should returns something like:
array(
array(1, 2, 3),
array(1, 2, 4),
...
array(4, 5, 6, 7, 8),
);
My attempt was to count in binary, from 0 to 2^n (where n is the cardinality of the set) and if the number of 1s is between X and Y, add the array made of 1s element to the result set.
Eg.
8 = 0000 0111 => add (6,7,8) to result
9 = 0000 1000 => no
10 = 0000 1001 => no
...
but it's very ugly!
Any better algorithm?
I'm using php, but feel free to use whatever language you like.
A pretty straightforward solution (requires generators, I think, it's php 5.5+)
// generate combinations of size $m
function comb($m, $a) {
if (!$m) {
yield [];
return;
}
if (!$a) {
return;
}
$h = $a[0];
$t = array_slice($a, 1);
foreach(comb($m - 1, $t) as $c)
yield array_merge([$h], $c);
foreach(comb($m, $t) as $c)
yield $c;
}
and then
$a = ['a','b','c','d','e','f', 'g'];
foreach(range(3, 5) as $n)
foreach(comb($n, $a) as $c)
echo join(' ', $c), "\n";
I want generate a range of numbers orderly. I mean opposite of rand function in php. I test with range but it generate only array of numbers
For example
min 1 and max 3
rand(1,3);// 2,1,3
but i want 1,2,3
Any in built in functions in php like rand for getting this features without using any loops?
Use range() to generate numbers
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
echo $number;
}
You can achieve this using for loop
for ($i = 1; $i <= 3; $i++) {
echo $i;
}
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
echo $number;
}
If you are using php then take a look at range function
If I understand your slightly missleading question.. this might do it:
$string = implode(', ', range(1,3));
echo $string;
And not a loop in sight :)
Or as a one liner:
echo implode(', ', range(1,3));
I have this array:
$numbers = array(1, 2, 3);
I can grab a random value from it like so:
$numbers[array_rand($numbers)];
But I need to come up with different random variations of these values. For example
1
13
123
3
32
12
3
12
13
231
etc...
As you can see a number can't repeat more than once in each set, so we can't have sets like:
113
232
33
etc...
How can this be done?
This solution lets you handle with any size of array...same operation..
<?php
$numbers = array(1, 2, 3);
$count=count($numbers);
$result="";
$iterations=rand(1,$count);
for($i=0;$i<$iterations;$i++)
{
$selected=$numbers[array_rand($numbers)];
$numbers=remove_item_by_value($numbers,$selected);
$result=$result.$selected;
}
function remove_item_by_value($array, $val) {
foreach($array as $key => $value) {
if ($value == $val)
unset($array[$key]);
}
return $array;
}
echo $result;
?>
Now it will return you even random sized string:).
Define the array, get a random length, shuffle the array, slice the array:
$numbers = array(1, 2, 3);
$length = rand(1, count($numbers));
shuffle($numbers);
$result = array_slice($numbers, -$length);
Demo
One possible solution is:
$number1 = array(1, 2, 3);
$number2 = array(1, 2, 3);
$number3 = array(1, 2, 3);
$loop = 10;
for($i=0;$i<$loop;$i++) {
$bool1 = mt_rand(0, 1);
$bool2 = mt_rand(0, 1);
$randomNumber = $number1[array_rand($number1)];
if($bool1)
$randomNumber .= $number2[array_rand($number2)];
if($bool2)
$randomNumber .= $number3[array_rand($number3)];
echo $randomNumber;
}
This both randomly decides to choose between 1-3 digits and can use the numbers 1-3 as many times as possible. Just change $loop to the amount of times you want to run the generator.
I also just realised you could simplify this further:
$numbers = array(1, 1, 1, 2, 2, 2, 3, 3, 3);
$limit = mt_rand(1, 3);
$keys = array_rand($numbers, $limit);
$number = "";
if($limit == 1)
$number .= $numbers[$keys];
else {
foreach ($keys as $value) {
$number .= $numbers[$value];
}
}
Insert each number the maximum amount of times into the array you want it to appear in any number (maximum number of digits you want to generate). And randomly generate a number between 1-3 with mt_rand() to use as your array_rand() limit.
Well, define "random" (what are the chances of getting a 1-digit long string, or a 2-digit long, or a 3-digit long?), but here's one method:
$len = rand( 1, count( $numbers ) );
$result = '';
shuffle( $numbers );
for( $i = 0; $i < $len; ++$i ) {
$result .= $numbers[ $i ];
}
Note that this changes the original array. Make a copy of it if it shouldn't be changed.
I need to randomly generate an two-dimensional n by n array. In this example, n = 10. The array should have this structure. One example:
$igra[]=array(0,1,2,3,4,5,6,7,8,9);
$igra[]=array(6,9,1,5,0,2,7,3,4,8);
$igra[]=array(2,5....................
$igra[]=array(1,7.....................
$igra[]=array(5,4...................
$igra[]=array(4,2...................
$igra[]=array(9,0.....................
$igra[]=array(8,3.....................
$igra[]=array(7,6....................
$igra[]=array(3,8....................
where
`$igra[x][z]!=$igra[y][z]` (x={0,9},y={0,9});
as you see it's like a matrix of numbers each row of it and column also consist from numbers 0-9, and there is never one number two times in each row or in each column.
how to generate such an array, and each time randomly.
Okay, so here's my version:
$n = 10;
$v1 = range(0, $n-1);
$v2 = range(0, $n-1);
shuffle($v1);
shuffle($v2);
foreach ($v1 as $x => $value)
foreach ($v2 as $y)
$array[$y][$x] = $value++ % $n;
This should be a really fast algorithm, because it involves only generating two random arrays and doesn't involve any swapping at all. It should be random, too, but I cannot prove it. (At least I don't know how to prove something like this.)
This is an optimized version of a very simple algorithm:
First a non-random matrix is created this way (imagine we want only 5*5, not 10*10):
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3
In this matrix we now randomly swap columns. As we don't change the columns themselves your rules still are obeyed. Then we randomly swap rows.
Now, as you can see the above algorithm doesn't swap anything and it doesn't generate the above matrix either. That's because it generates the cols and rows to swap in advance ($v1 and $v2) and then directly writes to the correct position in the resulting array.
Edit: Just did some benchmarking: For $n = 500 it takes 0.3 seconds.
Edit2: After replacing the for loops with foreach loops it only takes 0.2 seconds.
This is what I did. Made a valid matrix (2d array) that isn't random. So starting out, row 0 is 0-9, row 1 is 1-0 (ie: 1,2,3...8,9,0), row 2 is 2-1 (2,3...9,0,1)...row 8 is 8-7...etc. Then shuffle that array to randomize the rows and perform a simple column swap to randomize the columns. Should get back exactly what you want. Try this:
<?php
//simple function to show the matrix in a table.
function show($matrix){
echo '<table border=1 cellspacing=0 cellpadding=5 style="float: left; margin-right:20px;">';
foreach($matrix as $m){
echo '<tr>';
foreach($m as $n){
echo '<td>'.$n.'</td>';
}
echo '</tr>';
}
echo '</table>';
}
//empty array to store the matrix
$matrix = array();
//this is what keeps the current number to put into matrix
$cnt = 0;
//create the simple matrix
for($i=0;$i<=9;$i++){
for($j=0;$j<=9;$j++){
$matrix[$i][$j] = $cnt % 10;
$cnt++;
}
$cnt++;
}
//display valid simple matrix
show($matrix);
//shuffle the rows in matrix to make it random
shuffle($matrix);
//display matrix with shuffled rows.
show($matrix);
//swap the columns in matrix to make it more random.
for($i=0;$i<=9;$i++){
//pick a random column
$r = mt_rand(0, 9);
//now loop through each row and swap the columns $i with $r
for($j=0;$j<=9;$j++){
//store the old column value in another var
$old = $matrix[$j][$i];
//swap the column on this row with the random one
$matrix[$j][$i] = $matrix[$j][$r];
$matrix[$j][$r] = $old;
}
}
//display final matrix with random rows and cols
show($matrix);
?>
In my solution, by not generating a random array and checking if it already exists, it should run much faster (especially if the array ever went above 0-9). When you get down to the last row, there is only one possible combination of numbers. You will be generating random arrays trying to find that one answer. It would be pretty much the same as picking a number from 1 to 10 and generating a random number until it hits the one you picked. It could be on the first try, but then again you could pick 1000 random numbers and never get the one you wanted.
Hmm.. I see you got some good answers already, but here's my version:
$n = 10;
$seed_row = range(0, $n - 1);
shuffle($seed_row);
$result = array();
for($x = 0; $x < $n; $x++)
{
$tmp_ar = array();
$rnd_start = $seed_row[$x];
for($y = $rnd_start; $y < ($n + $rnd_start); $y++)
{
if($y >= $n) $idx = $y - $n;
else $idx = $y;
$tmp_ar[] = $seed_row[$idx];
}
$result[] = $tmp_ar;
}
for($x = 0; $x < $n; $x++)
{
echo implode(', ', $result[$x]) . "<br/>\n";
}
sample output:
4, 3, 0, 2, 6, 5, 7, 1, 8, 9
0, 2, 6, 5, 7, 1, 8, 9, 4, 3
7, 1, 8, 9, 4, 3, 0, 2, 6, 5
2, 6, 5, 7, 1, 8, 9, 4, 3, 0
6, 5, 7, 1, 8, 9, 4, 3, 0, 2
9, 4, 3, 0, 2, 6, 5, 7, 1, 8
8, 9, 4, 3, 0, 2, 6, 5, 7, 1
5, 7, 1, 8, 9, 4, 3, 0, 2, 6
1, 8, 9, 4, 3, 0, 2, 6, 5, 7
3, 0, 2, 6, 5, 7, 1, 8, 9, 4
It creates a random random array as a starting point
Then it walks through the seed array taking each element as a starting point for itself to create a new base.