PHP string Computation - php

Im doing a php activity, that will compute the sum of given number of integer.
Sample Output:
int number = 367;
Final output
16
16 is the total sum of 3+6+7.
Here's my Code:
$number = "367";
$int = 0;
for ($i = 0 ; $i < number.length(); $i++ ){
$char = number.charAt(i);
$int += Integer.parseInt(char1.toString());
}
echo $int;
Still i can't get the right answer anyone can help me? Thank you !
regards jay

I'm not exactly sure what you're doing but it seems like you're mixing PHP and Javascript. If you're looking for a PHP solution it's a lot easier than that. Give this a try:
$number = 367;
echo array_sum(str_split($number));

Related

Numbers to letters with logical sequence

I have this array which links numbers to letters at the moment like this:
1-26 = A-Z
But there is more, 27=AA and 28=AB etc...
so basically when I do this:
var_dump($array[2]); //shows B
var_dump($array[29]); //shows AC
Now this array I made myself but it's becoming way too long. Is there a way to actually get this going on till lets say 32? I know there is chr but I dont think I can use this.
Is there an easier way to actually get this without using this way too long of an array?
It's slower calculating it this way, but you can take advantage of the fact that PHP lets you increment letters in the same way as numbers, Perl style:
function excelColumnRange($number) {
$character = 'A';
while ($number > 1) {
++$character;
--$number;
}
return $character;
}
var_dump(excelColumnRange(2));
var_dump(excelColumnRange(29));
here is the code which you are looking for :
<?php
$start = "A";
$max = 50;
$result = array();
for($i=1; $i<=$max; $i++) {
$result[$i] = $start++;
}
print_r($result);
?>
Ref: http://www.xpertdeveloper.com/2011/01/php-strings-unusual-behaviour/
This should work for you:
Even without any loops. First I calculate how many times the alphabet (26) goes into the number. With this I define how many times it has to str_repleat() A. Then I simply subtract this number and calculate the number in the alphabet with the number which is left.
<?php
function numberToLetter($number) {
$fullSets = (($num = floor(($number-1) / 26)) < 0 ? 0 : $num);
return str_repeat("A", $fullSets) . (($v = ($number-$fullSets*26)) > 0 ? chr($v+64) : "");
}
echo numberToLetter(53);
?>
output:
AAA

Thinking Process of an algorithm of find the missing element in a given permutation from Codility

I found this perfect answer for the Codility's PermMissingElem Question.
function solution($A) {
$N = count($A);
$sum = ($N + 2) * ($N + 1) / 2;
for($i = 0; $i < $N; $i++){
$sum -= $A[$i];
}
return intval($sum);
}
However I found its puzzled for me regarding the $sum's function. What kind of function is this? It's amazingly correctly, yet, how come someone could make up such function? Is there anyone can somehow reverse engineer the thinking process?
I really want to know the process how it came about.
Thank You !
The sum of integers from 1 to N can be calculated by this formula:
N(N+1)/2
Basically, you take the first number and the last number and add them together, and then the second number and the second to last number..etc.
For example:
The sum of 1 to 100:
(1+100) + (2+99) + (3+98) + (4+97) ...
= (100/2)(101)
= 50 x 101
Here's a good explanation:
http://www.wikihow.com/Sum-the-Integers-from-1-to-N

Find the missing number in the given array of numbers using PHP

Am new to php i have faced an interview some days ago, and the interviewer asked a question like the following one.
The given array has 99 numbers, which contains the digits from 1 to 100
with one digit missing. Describe two different algorithms that finds you the missing number. The algorithm should optimize for low storage and fast processing. Output should show the execution time of each algorithm.
And i have searched google about it, and come to know its a common puzzle used to ask in interviews. I found out the answer like this way.
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
idx = i;
} else {
sum += arr[i];
}
}
// the total sum of numbers between 1 and arr.length.
int total = (arr.length + 1) * arr.length / 2;
System.out.println("missing number is: " + (total - sum) + " at index " + idx);
But the code is not in php,
Can u please help me to find out the php code and algorithm name. So i can improve my answer in the next interviews.
In PHP you can easily use some array functions and achieve that. Best way is,
$missing = array_diff(range(1,100),$array);
DEMO.
Another way to do it is by using the array_sum function and the knowledge that all numbers from 1 to 100 added together equals 5050.
$missing = 5050-array_sum($array);
Converted to PHP, it is nearly the same.
(Not tested)
Of course, there are better ways, like the one Rikesh posted, but this is the exact one you asked for:
$sum = 0
$idx = -1
for($i = 0; $i < count($arr); $i++){
if($arr[$i] == 0){
$idx = $i;
}else{
$sum += $arr[$i];
}
}
$total = (count($arr) + 1) * (count($arr) / 2);
echo "Missing: " . ($total - $sum) . " at index " . $idx;
$arr=range(1,99);
$j=1;
for($i=0;$i<100;$i++){
if(!in_array($j,$arr)){
echo $j.'is missing';
}
$j++;
}

PHP loop thru hex numbers from a form POST always gives the first number as 0. why?

i have a form with two text fields, "from" and "to."
when i enter values such as "100000" and "10000F" and do a for loop, it always comes out like:
0 100001 100002 100003 100004 100005 100006 100007 100008 100009 10000a 10000b 10000c 10000d 10000e 10000f
if i plug in the range for the loop manually, i get:
100000 100001 100002 100003 100004 100005 100006 100007 100008 100009 10000a 10000b 10000c 10000d 10000e 10000f
using:
for ($i = '0x'.$_POST['from']; $i <= '0x'.$_POST['to']; $i++) { print dechex($i)."\n"; }
versus:
for ($i = 0x100000; $i <= 0x10000F; $i++) { print dechex($i)."\n"; }
if anyone knows what i am doing wrong here, please let me know.
i have also tried tried adding the "0x" to the numbers via the form with the same results.
thanks!
While $i++ is converting $i to a number, this doesn't run until after the first loop. Apparently dechex doesn't try to interpret strings as numbers and just barfs.
To force conversion, prefix the string expression with a +:
for ($i = +('0x'.$_POST['from']); $i <= '0x'.$_POST['to']; $i++) {
print dechex($i)."\n";
}
Tested and working on PHP 5.2.6.
(Note that casting does not work! (int)('0x100000') returns 0.)
You should use intval() to convert a hex string to a number. dechex() will take the number and turn it back into a hex string:
$from = intval('100001', 16);
$to = intval('10000f', 16);
for ($i = $from; $i <= $to; $i++) {
print dechex($i) . "\n";
}
'0x'.$_POST['from']; is a string $i = 0x100000 is a number
Your first iteration will cast the string value to a number using standard PHP casting (as an integer value to the first non-numeric character, which is the 'x' giving a start value of 0)
You can also do
for ($i = intval('0x'.$_POST['from'], 0); $i <= intval('0x'.$_POST['to'], 0); $i++) { print dechex($i)."\n"; }
You need to convert your hex string to an actual integer first. Something like this function does.
Otherwise, PHP will handle it as a string.

number increment with customized style

I've tried to do a number(decimal) increment which looks like 001 002 003...123,124 in a loop and couldn't find a simple solution.What I've thought now is to check out whether the number is long enough ,if not prefix it some "0".But it seems not good.Any better ideas?
Thanks.
$x = 6
$y = sprintf("%03d",$x);
http://php.net/manual/en/function.sprintf.php
for($i=1;$i<1000;$i++){
$number = sprintf("%03d",$i);
echo "$number <br />";
}
Two options come immediately to mind. First, try str_pad(). It does exactly what you seem to describe.
Second, you could use sprintf() as another has suggested.
If you are not sure how long the various numbers will turn out to be (e.g., they are determined dynamically and no way of knowing what they will be until afterwards), you can use the following code:
<?php
$numbers = array();
for ($i = 0; $i < 2000; $i++)
{
$numbers[] = $i;
}
array_walk($numbers, function(&$item, $key, $len) { $item = sprintf('%0'.$len.'d', $item); }, strlen(max($numbers)));
print_r($numbers);
?>

Categories