Problems pushing an integer into an array - php

I've been trying to solve Project Euler problem 1 and I feel I'm missing something fundamental. Would you please help me fix my bug?
I tried this first:
<?php
/*
** Project Euler Problem 1
** If we list all the natural numbers below 10 that are multiples of 3 or 5,
** we get 3, 5, 6 and 9. The sum of these multiples is 23.
** Find the sum of all the multiples of 3 or 5 below 1000.
*/
$numberOne = 3;
$numberTwo = 5;
$endingIndex = 1000;
$multiplesOfNumbers = array();
for ($index = 1; $index <= $endingIndex; $index++) {
if ($index % $numberOne == 0 && $index % $numberTwo == 0) {
$multipleOfNumbers[] = $index;
}
}
echo $multiplesOfNumbers;
?>
Output:
Array
So I tried to do it with array_push instead, like this:
<?php
/*
** Project Euler Problem 1
** If we list all the natural numbers below 10 that are multiples of 3 or 5,
** we get 3, 5, 6 and 9. The sum of these multiples is 23.
** Find the sum of all the multiples of 3 or 5 below 1000.
*/
$numberOne = 3;
$numberTwo = 5;
$endingIndex = 1000;
$multiplesOfNumbers = array();
for ($index = 1; $index <= $endingIndex; $index++) {
if ($index % $numberOne == 0 && $index % $numberTwo == 0) {
// $multipleOfNumbers[] = $index;
array_push($multiplesOfNumbers, $index);
}
}
echo $multiplesOfNumbers;
?>
The output is the same. What am I missing?

Try this way:
print_r($multiplesOfNumbers);

echo will not print the array elements. use print_r instead

You have to loop through the array to get the values of the array (using a foreach) or use something like var_dump() or print_r() to echo the array.

Related

I want to get elements from array in order: three, four, three, four and so on

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;
}

Can someone help me return a value?

I have created a loop which returns a random number between two values. Cool.
But now I want the script to return the following value too: The number of unique numbers between two similar numbers.
Example:
4
5
8
22
45
3
85
44
4
55
15
23
As you see there is a double which is the four and there are 7 numbers inbetween. So I would like the script to echo these numbers two so in this case it should echo 7 but if there are more doubles in the list it should echo all the numbers between certain doubles.
This is what I have:
for ($x = 0; $x <= 100; $x++) {
$min=0;
$max=50;
echo rand($min,$max);
echo "<br>";
}
Can someone help me or guide me? I'm learning :)
Thanks!
So You need to seperate script for three parts:
getting randoms and save them to array (name it 'result'),
analyze them,
print (echo) results
Simply - instead of printing every step of loop, save them to array(), exit loop, analyze every item with other, example:
take i element of list
check is i+j element is the same
if is it the same - save j-i to second array() (name it 'ranges')
And after this, print two arrays (named by me as 'result' and 'ranges')
UPDATE:
Here's solution, hope You enjoy:
$result = array(); #variable is set as array object
$ranges = array(); #same
# 1st part - collecting random numbers
for ($x = 0; $x < 20; $x++)
{
$min=0;
$max=50;
$result[] = rand($min,$max); #here's putting random number to array
}
$result_size = count($result); #variable which is containg size of $result array
# 2nd part - getting ranges between values
for ($i = 0; $i < $result_size; $i++)
{
for ($j = 0; $j < $result_size; $j++)
{
if($i == $j) continue; # we don't want to compare numbers with itself,so miss it and continue
else if($result[$i] == $result[$j])
{
$range = $i - $j; # get range beetwen numbers
if($range > 0 ) # this is for miss double results like 14 and -14 for same comparing
{
$ranges[$result[$i]] = $range;
}
}
}
}
#3rd part - priting results
echo("RANDOM NUMBERS:<br>");
foreach($result as $number)
{
echo ("$number ");
}
echo("<br><br>RANGES BETWEEN SAME VALUES:<br>");
foreach($ranges as $number => $range)
{
echo ("For numbers: $number range is: $range<br>");
}
Here's sample of echo ($x is set as 20):
RANDOM NUMBERS:
6 40 6 29 43 32 17 44 48 21 40 2 33 47 42 3 22 26 39 46
RANGES BETWEEN SAME VALUES:
For numbers: 6 range is: 2
For numbers: 40 range is: 9
Here is your fish:
Put the rand into an array $list = array(); and $list[] = rand($min,$max); then process the array with two for loops.
$min=0;
$max=50;
$list = array();
for ($x = 0; $x <= 100; ++$x) {
$list[] = rand($min,$max);
}
print "<pre>";print_r($list);print "</pre>";
$ranges = array();
$count = count($list);
for ($i = 0; $i < $count; ++$i) {
$a = $list[$i];
for ($j = $i+1; $j < $count; ++$j) {
$b = $list[$j];
if($a == $b) {
$ranges[] = $j-$i;
}
}
}
print "<pre>";print_r($ranges);print "</pre>";

Create line breaks in output based on array index

I want to display output like this:
1 2 3 4
5 6 7 8
9 1 2
I've tried this code:
$num = ['1','2','3','4','....'];
$size = sizeof($num) / 4;
foreach ($num as $key => $value) {
echo $value;
if($key >= round($size){
echo "<br>"
}
}
But the output is like this:
1 2 3 4
5
6
7
8
...
Can anyone suggest how to write the loop?
$num= ['1','2','3','4','5','6','7','8','9'];
$size = sizeof($num) / 4;
foreach ($num as $key => $value){
echo $value;
if(($key+1) % 4 == 0){
echo "<br>";
}
}
You can use modulus instead of round. Cool I didn't know about sizeOf! Good to know. Mark this as the right answer pwease if this works!
Another way to do this if you didn't want to write out all the numbers that are in the Num Array is to just push them into an array with a while loop.
$num= [];
$i = 1;
//Set the Num Variable to have as many numbers as you want without having to manually enter them in
while ($i < 100) {
array_push($num, $i);
$i++;
}
//Run the actual code that adds breaks ever 4 lines
$size = sizeof($num) / 4;
foreach ($num as $key => $value){
echo $value;
if(($key+1) % 4 == 0){
echo "<br>";
}
}
Sorry if this answer looks the same as the first answer but I will explain it clearer
To achieve what you want
Step 1: Create a for loop
The loop will start from 1 to it's total size of the array
for ($x = 1; $x <= sizeof($num); $x++){
}
Then inside your loop
you can use ternary for simplicity
This line of code
# if $x variable is equal to limit number which you wanted to break
# $num[$x-1] -> subtract to by 1 because we know array always start at index 0
if ($x % 4 == 0) {
$num[$x-1]."<br>"; #put a break after it
} else {
echo $num[$x-1];
}
is same as this
echo ($x % 4 == 0) ? $num[$x-1]."<br>" : $num[$x-1];
So try this
<?php
$num= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];
$size = sizeof($num) / 4;
for ($x = 1; $x <= sizeof($num); $x++){
echo ($x % 4 == 0) ? $num[$x-1]."<br>" : $num[$x-1];
}
DEMO
You can try this:
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 8, 19, 20];
$len = 1;
foreach ($numbers as $number) {
echo $number . ' ';
$len++;
if ($len > 4) {
echo '<br>';
$len = 1;
}
}

Program to find X-numbers in an array

in an N numbers of array a number is a X-number if it is divisible by atleast one other number in the array. Program to find how many such numbers exists in an given array
example 1 : in array [1,2,3] , number of x-numbers is 2 ( 2 and 3 as they are divisible by number 1 )
example 2 : in array [2,3,5,8] , number of x-numbers is 1 ( 8 is divisible by 2 )
example 3 : in array [2,3,6,12] , number of x-numbers is 2 ( 6 is divisible by 2 and 3 , 12 is divisible by 2 and 3 and 6 )
I am using the below code, but i want to optimize it in a way if the array size increase the performance should not hamper :
$arr = array(2,3,6,12);
$count = 0;
function check_special_num($tnum, $tarr){
sort($tarr);
for($i=0;$i<sizeof($tarr);$i++){
if( $tnum % $tarr[$i] == 0 ){
return true;
}
}
return false;
}
for($i=0;$i<sizeof($arr);$i++){
$temp = $arr;
$num = $arr[$i];
array_splice($temp, $i, 1);
if( check_special_num( $num, $temp ) ){
$count += 1;
}
}
echo $count;
Coding language is PHP
It might be faster this way:
$arr = array(2,3,6,12);
function x_numbers_count($arr) {
$count = 0;
sort($arr);
foreach ($arr as $i => $number) {
for ($j = 0; $j < $i; $j++) {
if ($number % $arr[$j] == 0) {
$count++;
break;
}
}
}
return $count;
}
echo x_numbers_count($arr);
The main differences, which can be expected to improve performance:
the array is sorted only once, before beginning to work (this could also improve your own method, without changing anything else)
the search loop stops as soon as it is to reach the current investigated number
less variables are used

how to find the sum of all the multiples of 3 or 5 below 1000 in php, issue?

i have an small issue with the way this problem is resolved.
some would say: println((0 /: ((0 until 1000).filter(x => x % 3 == 0 || x % 5 == 0))) (_+_)) is the solution witch adds to 233168
my way was to do:
$maxnumber = 1000;
for ($i = 3; $i < $maxnumber; $i += 3)
{
$t += $i;
echo $i.',';
}
echo '<br>';
for ($j = 5; $j < $maxnumber; $j += 5)
{
$d += $j;
echo $j.',';
}
echo '<br>';
echo $t;
echo '<br>';
echo $d;
echo '<br>';
echo $t+$d;
this will give me :
3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,183,186,189,192,195,198,201,204,207,210,213,216,219,222,225,228,231,234,237,240,243,246,249,252,255,258,261,264,267,270,273,276,279,282,285,288,291,294,297,300,303,306,309,312,315,318,321,324,327,330,333,336,339,342,345,348,351,354,357,360,363,366,369,372,375,378,381,384,387,390,393,396,399,402,405,408,411,414,417,420,423,426,429,432,435,438,441,444,447,450,453,456,459,462,465,468,471,474,477,480,483,486,489,492,495,498,501,504,507,510,513,516,519,522,525,528,531,534,537,540,543,546,549,552,555,558,561,564,567,570,573,576,579,582,585,588,591,594,597,600,603,606,609,612,615,618,621,624,627,630,633,636,639,642,645,648,651,654,657,660,663,666,669,672,675,678,681,684,687,690,693,696,699,702,705,708,711,714,717,720,723,726,729,732,735,738,741,744,747,750,753,756,759,762,765,768,771,774,777,780,783,786,789,792,795,798,801,804,807,810,813,816,819,822,825,828,831,834,837,840,843,846,849,852,855,858,861,864,867,870,873,876,879,882,885,888,891,894,897,900,903,906,909,912,915,918,921,924,927,930,933,936,939,942,945,948,951,954,957,960,963,966,969,972,975,978,981,984,987,990,993,996,999
5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125,130,135,140,145,150,155,160,165,170,175,180,185,190,195,200,205,210,215,220,225,230,235,240,245,250,255,260,265,270,275,280,285,290,295,300,305,310,315,320,325,330,335,340,345,350,355,360,365,370,375,380,385,390,395,400,405,410,415,420,425,430,435,440,445,450,455,460,465,470,475,480,485,490,495,500,505,510,515,520,525,530,535,540,545,550,555,560,565,570,575,580,585,590,595,600,605,610,615,620,625,630,635,640,645,650,655,660,665,670,675,680,685,690,695,700,705,710,715,720,725,730,735,740,745,750,755,760,765,770,775,780,785,790,795,800,805,810,815,820,825,830,835,840,845,850,855,860,865,870,875,880,885,890,895,900,905,910,915,920,925,930,935,940,945,950,955,960,965,970,975,980,985,990,995
$t - 166833
$d - 99500
and total:
266333
why am i wrong?
Some numbers are multiples of both 3 and 5. (Your algorithm adds these numbers to the total twice.)
Because 6 * 5 == 30 and 10 * 3 == 30, you're adding the some numbers up twice.
$sum = 0;
$i = 0;
foreach(range(0, 999) as $i) {
if($i % 3 == 0 || $i % 5 == 0) $sum += $i;
}
Because you double-count numbers that are multiple of both 3 and 5, i.e. multiples of 15.
You can account for this naively by subtracting all multiples of 15.
for ($j = 15; $j < $maxnumber; $j += 15)
{
$e += $j;
echo $j.',';
}
$total = $total - $d;
In your case, if it is 15, you will add the number twice.
Try this:
$t = 0;
$d = 0;
for ($i = 0; $i <= $maxnumber; $i++){
if ($i % 3 == 0)
$t+= $i;
else if ($i % 5 == 0)
$d += $i;
}
echo $t.'<br>'.$d;
I think that in your code, if a number is a multiple of 3 and 5, it is added twice. Take 15 for example. It's in your list of multiples of 3 and in the list of multiples of 5. Is this the behaviour you want?
One of the best approach to this solution (to achieve optimum time complexity), run an Arithmetic Progression series and find the number of terms in all series by using AP formula: T=a+(n-1)d, then find sum by : S=n/2[2*a+(n-1)d]
where : a=first term ,n=no. of term , d=common deference, T=nth term
The code solution below has been implemented to suit the question above - so the values 3 and 5 are hard-coded. However, the function can modified such that values are passed in as variable parameters.
function solution($number){
$val1 = 3;
$val2 = 5;
$common_term = $val1 * $val2;
$sum_of_terms1 = calculateSumofMulitples($val1,$number);
$sum_of_terms2 = calculateSumofMulitples($val2,$number);
$sum_of_cterms = calculateSumofMulitples($common_term,$number);
$final_result = $sum_of_terms1 + $sum_of_terms2 - $sum_of_cterms;
return $final_result;
}
function calculateSumofMulitples($val, $number)
{
//first, we begin by running an aithmetic prograssion for $val up to $number say N to get the no of terms [using T=a +(n-1)d]
$no_of_terms = (int) ($number / $val);
if($number % $val == 0) $no_of_terms = (int) ( ($number-1)/$val ); //since we are computing for a no of terms below N and not up to/exactly/up to N. if N divides val with no remainder, use no of terms = (N-1)/val
//second, we compute the sum of terms [using Sn = n/2[2a + (n-1)d]
$sum_of_terms = ($no_of_terms * 0.5) * ( (2*$val) + ($no_of_terms - 1) * $val );
// sum of multiples
return $sum_of_terms;
}
You can run a single loop checking whether the number is multiple of 3 OR 5:
for ($i = 0; $i < $maxnumber; $i++)
{
if($i%3 || $i%5){
$t += $i;
echo $i.',';}
}
I think the original code is not including numbers which are multiples of both 3 and 5 in the total: if the test for multiple of 3 matches, it takes that and goes on.
If you total the multiples of 15 up to 1000, you get 33165, which is exactly the difference between your total, 266333, and the original total, 233168.
Here's my solution to the question:
<?php
$sum = 0;
$arr = [];
for($i = 1; $i < 1000; $i++){
if((int)$i % 3 === 0 || (int)$i % 5 === 0)
{
$sum += $i;
array_push($arr,$i);
}
}
echo $sum;
echo '<br>';
print_r($arr);//Displays the values meeting the criteria as an array of values

Categories