I am having some problems with PHP.
I used while to sum a number's digits always that it has more than two digits, some how, it gets into an infinity loop.
e.g: 56 = 5 + 6 = 11 = 1+1= 2.
Here is the code:
$somaP = 0;
$numPer = (string)$numPer; //$numPer = number calculated previously
while (strlen($numPer) > 1){
for ($j = 0; $j < strlen($numPer); $j++){
$somaP = $somaP + (int)($numPer[$j]);
}
$numPer = (string) $somaP;
}
Can anyone help me? Guess it is a simple mistake, but I couldn't fix it.
You need to reset the value of $somaP in your while loop.
Currently it continues to increase its value every time through the loop.
Try this:
$numPer = (string)$numPer; //$numPer = number calculated previously
while (strlen($numPer) > 1){
$somaP = 0;
for ($j = 0; $j < strlen($numPer); $j++){
$somaP = $somaP + (int)($numPer[$j]);
}
$numPer = (string) $somaP;
}
Take a look at this line:
$numPer = (string) $somaP;
It seems that the length of $somaP is never lesser (or equal) than 1. So the length of $numPer is never lesser (or equal) than 1.
What are you trying to do?
It's unclear to me.
This for example would add every number in a string together?
E.g "1234" = 1+2+3+4 = 10
$total = 0;
for($i = 0; i < strlen($string); $i++){
$total += $string[$i];
}
echo $total;
This looks cleaner I would say:
$numPer = 56;
while ($numPer > 9){
$numPer = array_sum(str_split($numPer));
}
echo $numPer;
PHP handles all string <> number conversions for you, so no need to do (string) on a number unless really needed.
Related
OK, simple question. New to PHP. How do I accomplish something similar to the following in PHP? This is no specific language intentionally.
i = 0;
j = 0;
k = 50;
While i <= 5
While j <= 10
myarray(i,j) = k
i = i + 1
j = j + 1
k = k + 2
next
next
I have found much info regarding arrays and loops in PHP and none seem to accomplish this simple task. Please don't be snarky... just give me a hand here.
You start each inner while j<=10.
Note that you didn't set $j to 0.
So correct the code is follows:
$i = 0;
$k = 50;
While( $i <= 5 ) {
$j = 0;
While( $j <= 10) {
$myarray[$i][$j] = $k;
$j++;
$k = $k + 2;
}
$i++;
}
Your pseudo code leaves some ambiguities, but maybe you mean to do the following:
$k=50;
for ($i=0; $i<=5; $i++)
for ($j=0; $j<=10; $j++, $k+=2)
$myarray[$i][$j]=$k;
This is a nested for-loop. The actual assignment to $myarray will happen 6*11=66 times in total and $k will have values from 50 to 115.
In PHP arrays don't need to be declared. You can simply assign a value to an arbitrary index of a given variable.
Here is a little demo.
I have an array filled with data over the period of a month. The data is computed for every 15 minutes over that period, meaning it's got about 2880 entries.
I need to reduce it by about 10% in order to display the data in a chart (288 data points will render much more nicely than 2880).
Here's what I've tried (it works, but it might be a very bad method):
$count = count($this->Data1Month);
for($i = 0; $i < $count; $i += 10) {
$tempArray[] = $this->DataMonth[$i];
}
$this->Data1Month = $tempArray;
I think you have the most efficient solution, but you do have a mistake though. Array indexes start at zero so 0+10 needs to be 9, like so:
$count = count($this->Data1Month);
for($i = 0; $i < $count; $i += 9) {
$tempArray[] = $this->DataMonth[$i];
}
$this->Data1Month = $tempArray;
i had applied for a job recently and the requirement was to complete a test and then interview
2 questions were given for test which was very simple and i did it successfully but still i was told that i have failed the test because the script took more than 18 seconds to complete execution. here is the program i dont understand what else i could do to make it fast. although i have failed the test but still wants to know else i could do?
Program language is PHP and i had to do it using command line input
here is the question:
K Difference
Given N numbers , [N<=10^5] we need to count the total pairs of numbers that have a difference of K. [K>0 and K<1e9]
Input Format:
1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.
Output Format:
One integer saying the no of pairs of numbers that have a diff K.
Sample Input #00:
5 2
1 5 3 4 2
Sample Output #00:3
Sample Input #01:
10 1
363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793
Sample Output #01:
0
Note: Java/C# code should be in a class named "Solution"
Read input from STDIN and write output to STDOUT.
and this is the solution
$fr = fopen("php://stdin", "r");
$fw = fopen("php://stdout", "w");
fscanf($fr, "%d", $total_nums);
fscanf($fr, "%d", $diff);
$ary_nums = array();
for ($i = 0; $i < $total_nums; $i++) {
fscanf($fr, "%d", $ary_nums[$i]);
}
$count = 0;
sort($ary_nums);
for ($i = $total_nums - 1; $i > 0; $i--) {
for ($j = $i - 1; $j >= 0; $j--) {
if ($ary_nums[$i] - $ary_nums[$j] == $diff) {
$count++;
$j = 0;
}
}
}
fprintf($fw, "%d", $count);
Your algorithm's runtime is O(N^2) that is approximately 10^5 * 10^5 = 10^10. With some basic observation it can be reduced to O(NlgN) which is approximately 10^5*16 = 1.6*10^6 only.
Algorithm:
Sort the array ary_nums.
for every i'th integer of the array, make a binary search to find if ary_nums[i]-K, is present in the array or not. If present increase result, skip i'th integer otherwise.
sort($ary_nums);
for ($i = $total_nums - 1; $i > 0; $i--) {
$hi = $i-1;
$low = 0;
while($hi>=$low){
$mid = ($hi+$low)/2;
if($ary_nums[$mid]==$ary_nums[$i]-$diff){
$count++;
break;
}
if($ary_nums[$mid]<$ary_nums[$i]-$diff){
$low = $mid+1;
}
else{
$hi = $mid-1;
}
}
}
}
I got the same question for my technical interview. I wonder if we are interviewing for the same company. :)
Anyway, here is my answer I came up with (after the interview):
// Insert code to get the input here
$count = 0;
sort ($arr);
for ($i = 0, $max = $N - 1; $i < $max; $i++)
{
$lower_limit = $i + 1;
$upper_limit = $max;
while ($lower_limit <= $upper_limit)
{
$midpoint = ceil (($lower_limit + $upper_limit) / 2);
$diff = $arr[$midpoint] - $arr[$i];
if ($diff == $K)
{
// Found it. Increment the count and break the inner loop.
$count++;
$lower_limit = $upper_limit + 1;
}
elseif ($diff < $K)
{
// Search to the right of midpoint
$lower_limit = $midpoint + 1;
}
else
{
// Search to the left of midpoint
$upper_limit = $midpoint - 1;
}
}
}
#Fallen: Your code failed for the following inputs:
Enter the numbers N and K: 10 3
Enter numbers for the set: 1 2 3 4 5 6 7 8 9 10
Result: 6
I think it has to do with your calculation of $mid (not accounting for odd number)
hello i'm beginner for programming I've got a homework. googled it but couldnt find anything...
i need to get the total value of numbers from 1 to 10. this need to be done in loop. but couldn't figure which loop should i use. if you can also give me an example code thats would be great.
This is a homework question, I'm not sure why people are just giving you an answer to copy-paste.
Achieving the sum of numbers 1..10 is pretty simple. You will need to initialise an empty int var before your loop, and for each iteration from 0 up to and including 10 you will add your int var to the current iteration.
For example:
sum = 0;
for num in range 1 to 10:
sum = sum + num;
<?php
$start = 0; // set the variable that will hold our total
for($i=1;$i<11;$i++){ // set a loop, read here: http://php.net/manual/en/control-structures.for.php for more info
$start += $i; // add $i to our start value
}
echo $start; // display our final value
I would use a for loop.
$total = 0;
for($i = 1; $i <= 10; $i++){
$total += $i;
}
Using the for loop:
<?php
$sum = 0;
for($i = 1; $i <= 10; $i++){
$sum += $i;
}
Using the foreach loop:
<?php
$sum = 0;
foreach(range(1,10) as $num){
$sum += $num;
}
echo $sum; // prints 55
And disregarding your assignment, here is an easier way:
echo array_sum(range(1,10));
i want after i've been submit form it can show hit counter..
but i want after it reach "20" it can back to zero..bcoz the limit of submit is 20 times so it can't over the limit.
how do i make it works?I've been try to this code...
<?
$limit="20";
$Query_counter=mysql_query("SELECT model FROM inspec");
$Show_counter=mysql_fetch_array($Query_counter);
$show_counter = $show_counter["model"]+1;
if($show_counter > $limit[0]) {
$show_counter = 0;
}elseif ($show_counter > $limit[1]) {
$show_counter = 0;
}
$Query_update=mysql_query("UPDATE inspec SET model=$Show_counter");
$Show_counter=number_format($Show_counter);
$Show_counter=str_replace(",",".",$Show_counter);
echo "Hit:</br><strong>$show_counter</strong>";
?>
To make a counter go up to a certain value then loop back to zero, you can use the modulus operator, which in a lot of languages (including PHP and MySQL) is %
$x = 0;
$limit = 4;
for ($i = 0; $i < 10; ++$i) {
$x = ++$x % $limit;
echo $x;
}
// 1, 2, 3, 0, 1, 2, 3, 0, 1, 2
I hope that makes enough sense. I can't really figure out from the question what exactly you want... Perhaps something like this?
UPDATE `mytable` SET `mycounter` = (`mycounter` + 1) % {{the limit}}
The concept here is to test to see if the variable you're incrementing exceeds some acceptable range as a result of the next increment. Simple increment the variable, then test its value.
In your case, just add a test after you increment the counter:
$show_counter = $show_counter["model"]+1;
if($show_counter > $limit){
$show_counter = 0;
}
Be sure to define $limit to whatever number you want to cycle on.
If you want to do this for multiple thresholds you can add additional tests. Note that you could hard-code $limit to any number or any variable you want, it's just the thing you're testing against.
<?
$Query_counter=mysql_query("SELECT model FROM inspec");
$Show_counter=mysql_fetch_array($Query_counter);
$show_counter = $show_counter["model"]+1;
$x = 0;
$limit = 20;
for ($i = 0; $i < 30; ++$i) {
$x = ++$x % $limit;
echo $x;
}
$Query_update=mysql_query("UPDATE inspec SET model= (model + 1) % 20");
$Show_counter=number_format($Show_counter);
$Show_counter=str_replace(",",".",$Show_counter);
echo "Hit:</br><strong>$show_counter</strong>";
?>