Can somebody explain me this script?
I don't understand what is "$myarray[$myarray[i]]" ?
<?php
$myarray = array (1, 2, 3, 5, 8, 15, 42, 23, 53);
$sum = 2;
for ($i = 0; $i < 5; $i++) {
$sum += $myarray[$myarray[$i]];
}
echo $sum;
?>
<?php
$myarray = array (1, 2, 3, 5, 8, 15, 42, 23, 53);
$sum = 2;
for ($i = 0; $i < 5; $i++) {
$sum += $myarray[$myarray[$i]];
}
echo $sum;
?>
I'm assuming you know how loop is working LOL.
So, when the loop starts $i = 0 then
$myarray[$myarray[$i]] => $myarray[$myarray[0]] //$myarray[0] = 1
So
$sum += $myarray[1] //here $myarray[1] = 2 (second index of array)
$sum += 2; => this statement is equivalent to $sum = $sum + 2;
so, $sum = 4 when first iteration of loop completes.
when $i = 1
$myarray[$myarray[1]] => $myarray[$myarray[2]] (3rd index is 3)
$sum += $myarray[3]
Since last time $sum was 4, so 4+3 = 7, $sum is 7 now, and so on..
check this DEMO, this will clear you all.
Cheers!
You will get the values from the index.
for ($i = 0; $i < 5; $i++) {
$sum += $myarray[$myarray[$i]];
}
Will do :
($myarray[0] = 1) $myarray[1] => $sum+2
($myarray[1] = 2) $myarray[2] => $sum+3
($myarray[2] = 3) $myarray[3] => $sum+5
($myarray[3] = 5) $myarray[5] => $sum+15
($myarray[4] = 8) $myarray[8] => $sum+53
Related
I use this code
function maxSum($arr, $n, $k)
{
$show=[];
$max_sum = PHP_INT_MIN ;
for ( $i = 0; $i < $n - $k + 1; $i++)
{
$current_sum = 0;
for ( $j = 0; $j < $k; $j++)
$current_sum = $current_sum +
$arr[$i + $j];
$max_sum = max($current_sum, $max_sum );
array_push($show,$max_sum);
}
return $show;
}
$arr = array(1, 4, 2, 10, 2, 3, 1, 0, 2);
$k = 3;
$n = count($arr);
print_r(maxSum($arr, $n, $k));
It works fine to find sums of 3 array items. Now I would like to do the opposite - to find how many array items should I sum to get 10 or close to 10.
Help is appreciated.
I have an array with n numbers from -10 to 10 (without 0). Implement function which returns quantity of pairs from the array which sum gives 0.
For example:
$input = array (3, 6, -3, 5, -10, 3, 10, 1, 7, -1, -9, -8, 7, 7, -7, -2, -7);
The right answer is 5 (pairs are bolded)
I made something like this but it gives me 10 pairs:
$length = count($input) - 1;
$count = 0;
for ($i = 0; $i <= $length; $i++) {
for ($j = $i + 1; $j <= $length; $j++) {
if ($input[$i] + $input[$j] == 0) {
$count++;
}
}
}
echo $count;
<?php
$input = array (3, 6, -3, 5, -10, 3, 10, 1, 7, -1, -9, -8, 7, 7, -7, -2, -7);
$length = count($input) - 1;
$count = 0;
for ($i = 0; $i <= $length; $i++){
$flag[$i]=0;
}
for ($i = 0; $i <= $length; $i++) {
for ($j = $i + 1; $j <= $length; $j++) {
if ($input[$i] + $input[$j] == 0 && $flag[$i]==0 && $flag[$j]==0) {
$count++;
$flag[$i]=1;
$flag[$j]=1;
}
}
}
echo $count;
?>
The correct code is given above. Since you have to mark the elements which are already used in making pair. For example, you have two +3 and one -3, which makes 2 pairs since you didn't mark it, that it has already made a pair with existing one.
You did two for loops, so you are counting the pairs twice. You can do some test, every input array you insert in the function will return an even number. Then do $count = $count/2; at final.
You need to define why its not working - it is but its finding 7 + -7 6 times: So you need to flag that this match has been found like the below code - with some added output so you can see what is happening:
$input = array (3, 6, -3, 5, -10, 3, 10, 1, 7, -1, -9, -8, 7, 7, -7, -2, -7);
$length = count($input) - 1;
$count = 0;
$matched = array();
for ($i = 0; $i < count($input); $i++) {
echo "<br />Group ".$i.": <strong>".$input[$i]."</strong>, ";
$groupmatch = 0;
$matchon = "";
for ($j = $i + 1; $j < count($input); $j++) {
echo $input[$j].", ";
$check = $input[$i] ."+". $input[$j];
if ($input[$i] + $input[$j] == 0 && !array_search($check,$matched)) {
$count++;
$groupmatch++;
$matchon .= $check.", ";
array_push($matched, $check);
}
}
echo "<br />Groupmatch: ".$groupmatch."<br/>";
echo $matchon."<br />";
}
echo $count;
<?php
$numbers = array(1,2,3,4);
$total = count($numbers);
$sum = 0;
$output = "";
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
if ($i < $total) {
$sum = $sum + $number;
}
}
echo $sum;
?>
I'm going through PHP on TeamTreehouse.com, whilst learning php this was one of the quiz question, the answer is 6. I don't know why the answer is 6, can someone explain?
The variable $i is initialized by 0 (zero).
Before the condition if ($i < $total) is tested $i is incremented by 1. So even the first time it equals 1.
In the third pass $i equals 3, and in the fourth pass it equals 4 which is NOT < $total.
Therefore only 3 of the 4 elements of $numbers are summed up: 1 + 2 + 3, which equals 6.
See the comments in the code below:
<?php
$numbers = array(1,2,3,4);
$total = count($numbers); // Gives 4
$sum = 0;
$output = "";
$i = 0; // $i = 0
foreach($numbers as $number) {
$i = $i + 1; // $i = 1, even at the first time
// after 3 passes $i is equal to $total (=4)
if ($i < $total) { // So, only 3 of the 4 elements of $number are honored
$sum = $sum + $number;
}
}
echo $sum; // Thus $sum = 1 + 2 + 3 = 6
// The last element (=4) is never summed up
?>
This would sum up all 4 elements, giving 10 as the result:
foreach($numbers as $number) {
if ($i < $total) {
$sum = $sum + $number;
}
$i = $i + 1;
}
<?php
$numbers = array(1,2,3,4);
$total = count($numbers); #value of $total is 4 here
$sum = 0;
$output = ""; #intital empty
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
if ($i < $total) {
$sum = $sum + $number;
}
}
echo $sum;
?>
You increment the $i by 1 so it becomes 1 which is smaller than $total(which is 4). Your program will add till $i become 4. It just add first three number in your array.
1+2+3=6.
That's why you are getting 6.
I hope you get it. :)
The condition limits the iterations. When $i is 4 it is no longer less than $total and so the last number doesn't get added.
I have this array:
$a = array(1, 2, 3, 4, 5, 7, 8, 10, 12);
Is there a function to convert this to:
$b = array(1, 1, 1, 1, 2, 1, 2, 2);
So basicaly:
$b = array ($a[1]-$a[0], $a[2]-$a[1], $a[3]-$a[2], ... ,$a[n]-$a[n-1]);
Here is the code I have so far:
$a = $c = array(1, 2, 3, 4, 5, 7, 8, 10, 12);
array_shift($c);
$d = array();
foreach ($a as $key => $value){
$d[$key] = $c[$key]-$value;
}
array_pop($d);
There isn't a built-in function that can do this for you, but you could turn your code into one instead. Also, rather than making a second array, $c, you could use a regular for loop to loop through the values:
function cumulate($array = array()) {
// re-index the array for guaranteed-success with the for-loop
$array = array_values($array);
$cumulated = array();
$count = count($array);
if ($count == 1) {
// there is only a single element in the array; no need to loop through it
return $array;
} else {
// iterate through each element (starting with the second) and subtract
// the prior-element's value from the current
for ($i = 1; $i < $count; $i++) {
$cumulated[] = $array[$i] - $array[$i - 1];
}
}
return $cumulated;
}
I think php has not a build in function for this. There are many ways to solve this, but you already wrote the answer:
$len = count($a);
$b = array();
for ($i = 0; $i < $len - 1; $i++) {
$b[] = $a[$i+1] - $a[$i];
}
This question already has answers here:
PHP get the item in an array that has the most duplicates
(2 answers)
Closed 1 year ago.
I have an array of numbers like this:
$array = array(1,1,1,4,3,1);
How do I get the count of most repeated value?
This should work:
$count=array_count_values($array);//Counts the values in the array, returns associatve array
arsort($count);//Sort it from highest to lowest
$keys=array_keys($count);//Split the array so we can find the most occuring key
echo "The most occuring value is $keys[0][1] with $keys[0][0] occurences."
I think array_count_values function can be useful to you. Look at this manual for details : http://php.net/manual/en/function.array-count-values.php
You can count the number of occurrences of values in an array with array_count_values:
$counts = array_count_values($array);
Then just do a reverse sort on the counts:
arsort($counts);
Then check the top value to get your mode.
$mode = key($counts);
If your array contains strings or integers only you can use array_count_values and arsort:
$array = array(1, 1, 1, 4, 3, 1);
$counts = array_count_values($array);
arsort($counts);
That would leave the most used element as the first one of $counts. You can get the count amount and value afterwards.
It is important to note that if there are several elements with the same amount of occurrences in the original array I can't say for sure which one you will get. Everything depends on the implementations of array_count_values and arsort. You will need to thoroughly test this to prevent bugs afterwards if you need any particular one, don't make any assumptions.
If you need any particular one, you'd may be better off not using arsort and write the reduction loop yourself.
$array = array(1, 1, 1, 4, 3, 1);
/* Our return values, with some useless defaults */
$max = 0;
$max_item = $array[0];
$counts = array_count_values($array);
foreach ($counts as $value => $amount) {
if ($amount > $max) {
$max = $amount;
$max_item = $value;
}
}
After the foreach loop, $max_item contains the last item that appears the most in the original array as long as array_count_values returns the elements in the order they are found (which appears to be the case based on the example of the documentation). You can get the first item to appear the most in your original array by using a non-strict comparison ($amount >= $max instead of $amount > $max).
You could even get all elements tied for the maximum amount of occurrences this way:
$array = array(1, 1, 1, 4, 3, 1);
/* Our return values */
$max = 0;
$max_items = array();
$counts = array_count_values($array);
foreach ($counts as $value => $amount) {
if ($amount > $max) {
$max = $amount;
$max_items = array($value);
} elif ($amount = $max) {
$max_items[] = $value;
}
}
$vals = array_count_values($arr);
asort($vals);
//you may need this end($vals);
echo key($vals);
I cant remember if asort sorts asc or desc by default, you can see the comment in the code.
<?php
$arrrand = '$arr = array(';
for ($i = 0; $i < 100000; $i++)
{
$arrrand .= rand(0, 1000) . ',';
}
$arrrand = substr($arrrand, 0, -1);
$arrrand .= ');';
eval($arrrand);
$start1 = microtime();
$count = array_count_values($arr);
$end1 = microtime();
echo $end1 - $start1;
echo '<br>';
$start2 = microtime();
$tmparr = array();
foreach ($arr as $key => $value);
{
if (isset($tmparr[$value]))
{
$tmparr[$value]++;
} else
{
$tmparr[$value] = 1;
}
}
$end2 = microtime();
echo $end2 - $start2;
Here check both solutions:
1 by array_count_values()
and one by hand.
<?php
$input = array(1,2,2,2,8,9);
$output = array();
$maxElement = 0;
for($i=0;$i<count($input);$i++) {
$count = 0;
for ($j = 0; $j < count($input); $j++) {
if ($input[$i] == $input[$j]) {
$count++;
}
}
if($count>$maxElement){
$maxElement = $count;
$a = $input[$i];
}
}
echo $a.' -> '.$maxElement;
The output will be 2 -> 3
$arrays = array(1, 2, 2, 2, 3, 1); // sample array
$count=array_count_values($arrays); // getting repeated value with count
asort($count); // sorting array
$key=key($count);
echo $arrays[$key]; // get most repeated value from array
String S;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String: ");
S = in.nextLine();
int count =1;
int max = 1;
char maxChar=S.charAt(0);
for(int i=1; i <S.length(); i++)
{
count = S.charAt(i) == S.charAt(i - 1) ? (count + 1):1;
if(count > max)
{
max = count;
maxChar = S.charAt(i);
}
}
System.out.println("Longest run: "+max+", for the character "+maxChar);
here is the solution
class TestClass {
public $keyVal;
public $keyPlace = 0;
//put your code here
public function maxused_num($array) {
$temp = array();
$tempval = array();
$r = 0;
for ($i = 0; $i <= count($array) - 1; $i++) {
$r = 0;
for ($j = 0; $j <= count($array) - 1; $j++) {
if ($array[$i] == $array[$j]) {
$r = $r + 1;
}
}
$tempval[$i] = $r;
$temp[$i] = $array[$i];
}
//fetch max value
$max = 0;
for ($i = 0; $i <= count($tempval) - 1; $i++) {
if ($tempval[$i] > $max) {
$max = $tempval[$i];
}
}
//get value
for ($i = 0; $i <= count($tempval) - 1; $i++) {
if ($tempval[$i] == $max) {
$this->keyVal = $tempval[$i];
$this->keyPlace = $i;
break;
}
}
// 1.place holder on array $this->keyPlace;
// 2.number of reapeats $this->keyVal;
return $array[$this->keyPlace];
}
}
$catch = new TestClass();
$array = array(1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 1, 2, 3, 1, 1, 2, 5, 7, 1, 9, 0, 11, 22, 1, 1, 22, 22, 35, 66, 1, 1, 1);
echo $catch->maxused_num($array);