Calculate sum in while loop to array - php

When the number 6 is giving I need to calculate till 6: for example: 1+2+3+4+5+6=21. I also need to add the sums of each to an array like: 1+2=3, 1+2+3=6, 1+2+3+4=10, ...
I have tried to make the while loop to be printed and this working fine but nog for array purpose:
<?php
$number = $_POST['number'];
$i = 1;
$cal = 0;
$tussenBerekening = array();
while ($i <= $number) {
echo $i;
$cal = $cal + $i;
array_push($tussenBerekening, $cal);
if ($i != $number) {
echo " + ";
} else {
echo " = " . $cal;
}
$i++;
}
?>
This is my new code, it prints, but no total sum.
<?php
$number = $_POST['number'];
$i = 2;
$cal = 0;
$sum = 1;
$berekeningen = array();
while ($i <= $number) {
$sum .= "+" . $i;
array_push($berekeningen, $sum);
$i++;
}
print_r($berekeningen);
?>

Here's a solution:
$i = 1;
$number = 6;
while ($i <= $number) {
// generate array with values from 1 to $i
$array = range(1, $i);
// if there're more than 1 element in array - output sum
if (count($array) > 1) {
// 1+2+... part // sum of elements of array
echo implode('+', $array) . ' = ' . array_sum($array) . '<br />';
}
$i++;
}

Related

Why can't I use a function to simplify my "for loops"

I build a webpage to crack simple MD5 hash of a four digit pin for fun. The method I used was basically try all combination and check against the MD5 value the user has entered. Below is the PHP code I created to accomplish the goal.
Debug Output:
<?php
$answer = "PIN not found";
if (isset($_GET['md5'])) {
$txt = 'abcdefjhig';
$time_pre = microtime(TRUE);
$value = $_GET['md5'];
$show = 15;
for ($i = 0; $i <= 9; $i++) {
$first = $i;
for ($j = 0; $j <= 9; $j++) {
$second = $j;
for ($k = 0; $k <= 9; $k++) {
$third = $k;
for ($x = 0; $x <= 9; $x++) {
$fourth = $x;
$whole = $first . $second . $third . $fourth;
$check = hash('md5', $whole);
if ($check == $value) {
$answer = $whole;
echo "The pin is $answer";
}
if ($show > 0) {
print"$check $whole \n";
$show = $show - 1;
}
}
}
}
}
echo "\n";
$time_post = microtime(TRUE);
print "Elapsed time:";
print $time_post - $time_pre;
}
?>
Notice that in the middle there are four very similar for loops,I tried to simplify this by using functions, but it just returns one four digit number which is 9999 instead of all of them.
Below is the function I created:
function construct($input){
for($i=0; $i<=9, $i++){
$input=$i;
}
return $input
}
Then I tried to call this function for four times to form all of the four digit numbers but it just gives me 9999. Can anybody help? Thanks a lot.
Try this:
for ($i=0; $i<=9999 ; $i++) {
$whole = sprintf('%04d', $i);
$check=hash('md5', $whole);
if($check==$value){
$answer=$whole;
echo "The pin is $answer";
break; //remove this if you do not want to break the loop here
}
if ($show>0) {
print"$check $whole \n";
$show=$show-1;
}
}
You're using numbers from 0 to 9999, so why just loop through those numbers? You can add zero's by using str_pad() like so:
for ($i = 0; $i <= 9999; $i++) {
$whole = str_pad($i, 4, '0', STR_PAD_LEFT);
}
Also I'd like to mention that you really should think about better formatting of your code, especially indentation

How to create second array and display numbers that are greater than average number of first array?

I want to make second array that gives all numbers using rand function that are greater than average number of first array.
I've created new array and I've tried with if statement to display all numbers greater than average number, and to put those values into a new empty array
$arrNums = array();
$arrNewNums = array();
$intSum = 0;
$intTotalNum = 20;
for($i = 0; $i < $intTotalNum; $i++)
{
$intRand = rand(9, 99);
$arrNums[] = $intRand;
$intSum = $intSum + $arrNums[$i];
$averageNum = $intSum / count($arrNums);
foreach($arrNums as $key => $value)
{
if($value > $averageNum)
{
$arrNewNums[] = rand();
}
}
}
echo '<pre>';
print_r($arrNums);
echo "<br>";
echo "Average number from array is " . $averageNum;
echo "<br>";
print_r($arrNewNums);
I would like to get the output of 20 numbers greater than average number, for example 56.4, but instead of that I'm getting 100 numbers and they are all for example 864165243, 738017258 and so on and so on...
This is the correct code for your task:
$arrNums = array();
$arrNewNums = array();
$intSum = 0;
$intTotalNum = 20;
for($i = 0; $i < $intTotalNum; $i++)
{
$intRand = rand(9, 99);
$arrNums[] = $intRand;
$intSum += $intRand;
}
// count average value AFTER you have all items in array
// $averageNum = array_sum($arrNums) / count($arrNums);
// Without `array_sum`:
$averageNum = $intSum / count($arrNums);
// check values of array AFTER you have all items in array
foreach($arrNums as $value) {
if($value > $averageNum) {
// add `$value` to `$arrNewNums`, not some random variable.
$arrNewNums[] = $value;
}
}
echo '<pre>';
print_r($arrNums);
echo "<br>";
echo "Average number from array is " . $averageNum;
echo "<br>";
print_r($arrNewNums);

I want to echo out a total number per repeat

I have created a small script which gives me random numbers. Now I want to create a list of this random number list with repeating numbers.
It should generate match numbers of this list of random numbers (A match number is a number which repeats)
For instance 4 – 6 – 9 – 32 – 34 – 31 – 5 – 32 (The match number here is 8 because after 8 numbers we have a repeater). I would like all the match numbers to be echo beside each other with a space in between.
Can someone help me?
I have tried creating an if statement but I can't get it working.
for ($rnd=1;$rnd<=50;$rnd++)
{
$random = mt_rand(0,100) . " ";
echo $random;
}
Explanation coming soon.
$numbers = array();
for($i = 1; $i <= 50; $i++) {
$number = mt_rand(0,100);
if(!isset($numbers[$number])) $numbers[$number] = array();
$numbers[$number][] = $i;
}
foreach($numbers as $key => $value) {
$start = '';
foreach($value as $k => $v) {
echo $start . $key . ' (Match Number: ' . $v . ')';
$start = ' - ';
}
echo '<br />';
}
If I don't misunderstood your question then this is what you want. Let's do this way-
<?php
$existing = [];
$repeat_numbers = [];
for ($rnd=1;$rnd<=50;$rnd++)
{
$random = mt_rand(0,100);
if(in_array($random,$existing)){
$repeat_numbers[] = $rnd; // pushing the repeating index
}
$existing[] = $random;
echo $random.PHP_EOL;
}
echo implode('-',$repeat_numbers);
?>
WORKING DEMO: https://3v4l.org/eEhB8
AS PER THE COMMENT
<?php
$existing = [];
$repeat_numbers = [];
for ($rnd=1;$rnd<=50;$rnd++)
{
$randoms[] = mt_rand(0,100);
}
echo implode('-',$randoms).PHP_EOL;
$i = 1;
foreach($randoms as $rnd){
if(in_array($rnd,$existing)){
$repeat_numbers[] = $i;
$i=1;
}
$existing[] = $rnd;
$i++;
}
echo implode('-',$repeat_numbers);
?>
WORKING DEMO https://3v4l.org/Xjc5X
AS PER THE LATEST COMMENT
<?php
$existing = [];
$repeat_numbers = [];
$randoms = explode('-','3-31-34-29-28-5-28-23-31-4-1-31-11-17-23-9-20-24-22-3-11-24-26-4-10');
$i = 1;
foreach($randoms as $rnd){
if(in_array($rnd,$existing)){
$repeat_numbers[] = $i;
$i=1;
$existing = []; // This like will do the magic for you
}
$existing[] = $rnd;
$i++;
}
echo implode('-',$repeat_numbers);
?>
WORKING DEMO: https://3v4l.org/hIT22
FINAL EDIT:
<?php
$existing = [];
$repeat_numbers = [];
$randoms = explode('-','4-9-13-18-19-34-23-9-9-13-44-5-13-13-88-26-29-27-34-67-65-83-26');
$i = 1;
foreach($randoms as $rnd){
if(in_array($rnd,$existing)){
$repeat_numbers[] = $i;
$i=1;
$existing = [];
}else{
$existing[] = $rnd;
$i++;
}
}
echo implode('-',$repeat_numbers);
?>
WORKING DEMO: https://3v4l.org/9j7iq
EDITED AGAIN:
<?php
$existing = [];
$repeat_numbers = [];
$randoms = explode('-','4-9-13-18-19-34-23-9-9-13-44-5-13-13-88-26-29-27-34-67-65-83-26');
//print_r($randoms);
$i = 0;
foreach($randoms as $rnd){
$i++;
if(in_array($rnd,$existing)){
$repeat_numbers[] = $i;
if(count($existing)==1){
$i=1;
}else{
$i=0;
}
$existing = [];
}
$existing[] = $rnd;
//print_r($existing);
}
echo implode('-',$repeat_numbers);
?>
WORKING DEMO: https://3v4l.org/VfIJY

get a set of values from an array

i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>

Max, Min and sum Random Number php

Here's the code
<?php
echo "<table border=\"0\">";
for ($d = 1; $d <= $times;$d++ )
{
echo "<tr><td>";
echo rand(1,6), "\n";
echo "</td></tr>";
}
echo "</table>"; ?>
I'm trying to get the max,min and sum of the rand(1,6), "\n";
But i can't figure it out. And it's killing me.
$rands = array(); // rand() storage
for($d = 1; $d <= $times; $d++){
$rands[$d] = rand(1, 6); // store rands
}
var_dump($min = min($rands)); // min() of rands
var_dump($min = max($rands)); // max() of rands
^ see sample code.
(PS: I use [$d] as he has a 1-based increment and it may be needed for his further logic. This way the rands keys match his $d and can be easily accessed later on.)
You need to collect the random numbers in an array, too:
echo "<table border=\"0\">";
$rands = array();
#################
for ($d = 1; $d <= $times; $d++)
{
echo "<tr><td>";
echo $rands[] = rand(1,6), "\n";
###########
echo "</td></tr>";
}
echo "</table>"; ?>
Afterwards you can make use of max, min and array_sum (all these links come with nice examples).
As your code already shows you should start to differ between code that does data-processing and code that does the HTML output:
// handle the data
$randomNumbers = array();
foreach (range(1, $times) as $d)
{
$randomNumbers[$d] = rand(1,6);
}
// output the data
echo '<table border="0">';
foreach ($randomNumbers as $number) {
printf("<tr><td>%d</tr></td>", $number);
}
echo "</table>";
<?php
$min = 10;
$max = -1;
$sum = 0;
for ($d = 1; $d <= $times; $d++) {
$n = rand(1, 6);
if ($n < $min) $min = $n;
if ($n > $max) $max = $n;
$sum += $n;
}
echo $min . ' ' . $max . ' ' . $sum . '<br/>';
?>
$sum=0;
for ($d = 1; $d <= $times;$d++ ) {
echo "<tr><td>";
$r=rand(1,6);
$sum +=$r;
echo "$r, \n";
echo "</td></tr>";
if ($d==1) { $min=$r; $max=$r; }
if ($r>$max) $max=$r;
if ($r<$min) $min=$r;
}
// do something with $min, $max and $sum;
<?php
$total = 0;
echo "<table border=\"0\">";
for ($d = 1; $d <= $times;$d++ )
{
$rand = rand(1,6);
$total += $rand;
$array[] = $rand;
echo "<tr><td>";
echo $rand, "\n";
echo "</td></tr>";
}
echo "</table>"; ?>
echo $total;
echo min($array);
echo max($array);

Categories