Getting highest even number out of an array - php

I need to get the greatest even number out of this array with a for-loop. I know how to get the highest number from the loop, but it's not even.
This is the code I have so far:
<?php
// array aangemaakt
$aReeks = array(23, 245, 1, 2, 12, -10, 46, 6, 66, 9999, -55, 348, 56, 6, 66, 983);
$resultaat = 0;
for ($i = 0; $i < count($aReeks); $i++) {
if ($resultaat < $aReeks[$i])
$resultaat = $aReeks[$i];
}
echo $resultaat;
?>

if($resultaat < $aReeks[$i] && $aReeks[$i] % 2 == 0)
modulo of division by two is zero -> even number

To find the highest odd number inside an array, you can use array_filter and max.
$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983);
echo(max(array_filter($aReeks, function($var){return(!($var & 1));})));
//348
If you just need to find if a number is even or odd, you can use:
//if Even Number
$number = "222";
if(!($number & 1)){...}
//if Odd Number
$number = "221";
if($number & 1){...}

Related

PHP - Get range either side of integer

In PHP, I am getting a range like this...
$number = range(0,50,10);
This is working, but now I am trying to modify it so that given a number, it will get the range 5 digits either side of that number.
So, for example, given the number 25, I would like...
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
To further slightly complicate things, I would only like these numbers to be positive, so if the start number was 3, then it would only get the range 1-8
Just subtract and add to the number in the center. Use the max() function to restrict the beginning to at least 1.
$n = 25;
$numbers = range(max(1, $n-5), $n+5)
max() will help you out here.
$width = 5; // Width of your range
$center = 3; // Center of your range
$r = range(max(1, $center-$width), $center+$width);
You could try something like this:
for ($i = $number - 5; $i <= $number + 5; $i++) {
if ($i > 0) {
return $i;
} else {
return "negative";
}
}
I am new to PHP and not entirely sure if that will work 😬

array_splice() isn't working properly inside a loop

This code works as expected and removes the array element when the value is either 5 or 10. But it only works when I have 1 value which is 5 or 10 in the array.
If I have more than 1 value which is 5 or 10 it removes only 1 of them and leaves the other elements in the array.
My code:
for($i = 0; $i <= 10; $i++) {
if($somevar[$i] == 5 || $somevar[$i] == 10) {
echo 'the sumvar'.$somevar[$i].' exists<br>';
array_splice($somevar, $i, 1);
}
}
As an example if I have: [3, 5, 4] the result is as expected: [3, 4]. But if I have an array like: [3, 5, 10, 4] it just removes the 5, but not the 10: [3, 10, 4].
I can't seem to find it what I'm doing wrong and why my code doesn't work as expected?
You seem to miss that the array-elements are renumbered after the splice-operation.
You would have to adjust the loop-variable:
for($i = 0; $i < sizeof($somevar); $i++) {
if($somevar[$i] == 5 || $somevar[$i] == 10) {
echo 'the sumvar'.$somevar[$i].' exists<br>';
array_splice($somevar, $i, 1);
<b>$i--;</b>
}
}

Summing only positive numbers in PHP array

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

Creating an N x N array of integers that "staircase" and "wrap around"

I am having trouble trying to figure out how to get data ordered like below. The total numbers don't matter; it would follow the same pattern from any number in the logical order of 0, 1, 2, 3, 4, 5, 6, etc. So essentially, starting at 0, 2, 3, 4, etc. where 1 would be placed after the maximum number, and where 0 can be a variable I set statically. I am having issues with progressing all the way to max number and then continuing, e.g.
..., 97, 98, 99, 100, 1, 2, ...
and then progressing with the order,
..., 98, 99, 100, 1, 2, 3, ...
and so on until 1, 2, 3, 4, 5, 6, ...
and store this all into the multidimensional array below.
$set = array(
array('0','0','0','0','0','0','0','0','0','0','0'),
array('0','2','3','4','5','6','7','8','9','10','1'),
array('0','3','4','5','6','7','8','9','10','1','2'),
array('0','4','5','6','7','8','9','10','1','2','3'),
array('0','5','6','7','8','9','10','1','2','3','4'),
array('0','6','7','8','9','10','1','2','3','4','5'),
array('0','7','8','9','10','1','2','3','4','5','6'),
array('0','8','9','10','1','2','3','4','5','6','7'),
array('0','9','10','1','2','3','4','5','6','7','8'),
array('0','10','1','2','3','4','5','6','7','8','9'),
array('0','1','2','3','4','5','6','7','8','9','10'),
);
I did the above because I couldn't figure out a looping pattern; if I could figure that out I wouldn't need to enter in the data manually and could create a form by which any number could be chosen, following this pattern.
Notice that other than the first row and column, each row is just the previous shifted left, with the next value added on:
$max = 10;
// First row (full of 0)
$set = array(array_fill(0, $max + 1, 0));
$row = array();
for($i = 1; $i <= $max; $i++)
$row[] = $i;
$row[] = 1; // $row = [2,3,4,...,$max,1]
for($i = 0; $i < $max; $i++){
$set[] = array_merge(array(0), $row);
$row = array_map(function($x) use ($max){ // Requires PHP 5.3
$result = ($x + 1) % $max;
return 0 === $result ? $max : $result;
}, $row);
}
Codepad
It's of course fairly trivial to make this store strings instead of integers if you require that.
$array = array();
$max = 10;
for ($i = 0; $i < $max; $i++)
{
$num = $i + 2;
$array[$i][] = 0;
for ($j = 0; $j < $max; $j++)
{
if ($num == $max + 1)
$num = 1;
$array[$i][] = $num;
$num++;
}
}
var_dump($array);

php array generation challenge

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.

Categories