Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have one array and i want to multiply like 106 multiply by 76 but i want to multiply in this pattern it is not giving proper result
1 0 6
6 7
_____________
7 4 2
6 3 6 x
_________________
7 1 0 2
The code is running properly but there is mistake in the addition i guess the output of the code is 424991 It should be 7102
<?php
$data=array(
'digit1' => 1,
'digit2' => 0,
'digit3' => 6,
'digit4' => 6,
'digit5' => 7 );
$a=$data['digit1']*$data['digit4'];
$b=$data['digit2']*$data['digit4'];
$b1=$data['digit3']*$data['digit4'];
$c=$data['digit1']*$data['digit5'];
$d=$data['digit2']*$data['digit5'];
$d1=$data['digit3']*$data['digit5'];
$e=$b+$a+$b1;
echo $e;
$f=$c+$d+$d1;
echo $f;
echo $e+$f;
?>
By using floor and modulus, you should be able to solve your problem.
Try this updated code.
$data = array(
'digit1' => 1,
'digit2' => 0,
'digit3' => 6,
'digit4' => 6,
'digit5' => 7
);
# ------------------------------------------------------------
$product = $data['digit5'] * $data['digit3'];
$a = $product % 10;
$carry = floor($product / 10);
$product = ($data['digit5'] * $data['digit2']) + $carry;
$b = $product % 10;
$carry = floor($product / 10);
$product = ($data['digit5'] * $data['digit1']) + $carry;
$c = $product;
#-------------------------------------------------------------
$product = $data['digit4'] * $data['digit3'];
$d = $product % 10;
$carry = floor($product / 10);
$product = ($data['digit4'] * $data['digit2']) + $carry;
$e = $product % 10;
$carry = floor($product / 10);
$product = ($data['digit4'] * $data['digit1']) + $carry;
$f = $product;
#-------------------------------------------------------------
$x = intval($c . $b . $a);
$y = intval($f . $e . $d) * 10;
#-------------------------------------------------------------
echo sprintf("%' 10d\n", $c.$b.$a);
echo sprintf("%' 9d\n", $f.$e.$d);
echo "----------\n";
echo sprintf("%' 10d\n", $x + $y);
You can thank me later for doing your assignment for you.
In your program, you do not take into account the placevalues.
For example, when you multiply $data['digit1'] by $data['digit4'], you should be multiplying 100 by 60, but you are instead multiplying 1 by 6.
And the reason you have a larger number (6 digits) is because you're echoing two values.
This is what your program is doing (step by step):
$data = array(
'digit1' => 1,
'digit2' => 0,
'digit3' => 6,
'digit4' => 6,
'digit5' => 7
);
$a=$data['digit1']*$data['digit4']; // $a = 6
$b=$data['digit2']*$data['digit4']; // $b = 0
$b1=$data['digit3']*$data['digit4']; // $b1 = 36
$c=$data['digit1']*$data['digit5']; // $c = 7
$d=$data['digit2']*$data['digit5']; // $d = 0
$d1=$data['digit3']*$data['digit5']; // $d1 = 42
$e=$b+$a+$b1; // $e = 42
echo $e; // OUTPUT 42
$f=$c+$d+$d1; // $f = 49
echo $f; // OUTPUT 42
echo $e+$f; // OUTPUT 91
This is creating your output 424991.
If you wanted to get your program to work as-is (instead of using a dynamic program like below), then the following should work:
$data = array(
'digit1' => 1,
'digit2' => 0,
'digit3' => 6,
'digit4' => 6,
'digit5' => 7
);
$a=$data['digit1']*100*$data['digit4']*10;
$b=$data['digit2']*10*$data['digit4']*10;
$b1=$data['digit3']*1*$data['digit4']*10;
$c=$data['digit1']*100*$data['digit5']*1;
$d=$data['digit2']*10*$data['digit5']*1;
$d1=$data['digit3']*1*$data['digit5']*1;
$e=$b+$a+$b1;
$f=$c+$d+$d1;
echo $e+$f;
Your code is a bit too rigid, so may I suggest a more dynamic version?
Given any two numeric strings in PHP:
$num1 = "106";
$num2 = "67";
You can split each one into arrays of numbers:
$num1Split = str_split($num1);
$num2Split = str_split($num2);
And then multiply it out:
$total = 0;
for($i = 0; $i < count($num1Split); $i++)
for($j = 0; $j < count($num2Split); $j++)
$total += $num1Split[$i]*pow(10,count($num1Split)-$i-1) * $num2Split[$j]*pow(10,count($num2Split)-$j-1);
echo $total;
Related
I am trying to implement the prefix sum logic in php codility.
Here is the problem that I'm trying to solve:
You are given a non-empty, zero-indexed array A of n (1 ¬ n ¬ 100 000)
integers a0, a1, . . . , an−1 (0 ¬ ai ¬ 1 000). This array represents
number of mushrooms growing on the consecutive spots along a road. You
are also given integers k and m (0 ¬ k, m < n). A mushroom picker is
at spot number k on the road and should perform m moves. In one move
she moves to an adjacent spot. She collects all the mushrooms growing
on spots she visits. The goal is to calculate the maximum number of
mushrooms that the mushroom picker can collect in m moves. For
example, consider array A such that: [2, 3, 7, 5, 1, 3, 9]
The mushroom picker starts at spot k = 4 and should perform m = 6
moves. She might move to spots 3, 2, 3, 4, 5, 6 and thereby collect 1
+ 5 + 7 + 3 + 9 = 25 mushrooms. This is the maximal number of mushrooms she can collect.
Here's my code in php:
$P = [2, 3, 7, 5, 1, 3, 9]; // mushroom count per position
$k = 4; // start position of picker
$m = 6; // moves allowed
$n = count($P);
$result = 0;
$pref = $this->getPrefixSum($P);
$leftBoundary = min($m, $k);
for ($i=0; $i < $leftBoundary; $i++) {
$leftPos = $k - $i;
$rightPos = min($n - 1, max($k, $k + $m - 2 * $i));
$result = max($result, $pref[$rightPos] - $pref[$leftPos]);
}
$rightBoundary = min($m + 1, $n - $k);
for ($i=0; $i < $rightBoundary ; $i++) {
$rightPos = $k + $i;
$leftPos = max(0, min($k, $k - ($m - 2 * $i)));
$result = max($result, $pref[$rightPos] - $pref[$leftPos]);
}
function getPrefixSum($A)
{
$prefixSums = array();
$prefixSums[0] = $A[0];
for ($i=1; $i < count($A); $i++) {
$prefixSums[$i] = $prefixSums[$i - 1] + $A[$i];
}
return $prefixSums;
}
Unfortunately, I am getting a result of 19 only (Expected answer was 25). Do you guys have any idea if I'm missing anything? Any help would be appreciated.
There are multiple mistakes translating the code from the example. The primary problem is that your prefixSum function is producing an array with one less index than the example code. Here's a comparison:
# them
[0, 2, 5, 12, 17, 18, 21, 30]
# you
Array
(
[0] => 2
[1] => 5
[2] => 12
[3] => 17
[4] => 18
[5] => 21
[6] => 30
)
Otherwise, you've omitted operations that they included, so I'll highlight them in the working code below:
function getPrefixSum($A) {
$prefixSums = [0];
# ^^^
for ($i = 1; $i < count($A) + 1; $i++) {
# ^^^^
$prefixSums[$i] = $prefixSums[$i-1] + $A[$i-1];
# ^^
}
return $prefixSums;
}
$P = [2, 3, 7, 5, 1, 3, 9]; // mushroom count per position
$k = 4; // start position of picker
$m = 6; // moves allowed
$n = count($P);
$result = 0;
$pref = getPrefixSum($P);
$leftBoundary = min($m, $k) + 1;
# ^^^^
for ($i = 0; $i < $leftBoundary; $i++) {
$leftPos = $k - $i;
$rightPos = min($n - 1, max($k, $k + $m - 2 * $i));
$result = max($result, $pref[$rightPos+1] - $pref[$leftPos]);
# ^^
}
$rightBoundary = min($m + 1, $n - $k);
for ($i = 0; $i < $rightBoundary; $i++) {
$rightPos = $k + $i;
$leftPos = max(0, min($k, $k - ($m - 2 * $i)));
$result = max($result, $pref[$rightPos+1] - $pref[$leftPos]);
# ^^
}
echo "$result\n";
Output:
25
Try it out.
So this might be quite bizarre, but... Imagine a grid of 10x10, each numbered left to right, top to down, starting at 1 and ending in 100.
I want to input a grid number ($plot) and get each grid number that surrounds it.
I started by making an array:
$plot = 45;
$arr = array(
$plot-11, $plot-10, $plot-9,
$plot-1, $plot, $plot+1,
$plot+9, $plot+10, $plot+11
);
This works fine.
Except if I add a plot near the edge of the grid (like $plot = 50) it would give me results at the start of the next row. Eg:
Any clever ways to solve this?
You can filter the array and only keep cells which have a distance of 1 or 0:
$plot = 50;
$arr = array(
$plot-11, $plot-10, $plot-9,
$plot-1, $plot, $plot+1,
$plot+9, $plot+10, $plot+11
);
$plotX = ($plot - 1) % 10 + 1;
$plotY = ceil($plot / 10);
$arr = array_filter($arr, function($item) use($plotX, $plotY){
return 1 >= abs($plotX - (($item - 1) % 10 + 1))
&& 1 >= abs($plotY - ceil($item / 10));
});
var_export($arr);
Result:
array (
0 => 39,
1 => 40,
3 => 49,
4 => 50,
6 => 59,
7 => 60,
)
This question already has answers here:
PHP: Create an array for a range
(4 answers)
Closed 6 years ago.
Can someone tell me how can I create array of numbers dynamically, without any for loop?
e.g. I want to create array like:
[0] => 10
[1] => 20
[2] => 30
[3] => 40
..
[9] => 100
You could use range(). The third argument is the number to step between values when interpolating between the start and ending values.
$numbers = range(10, 100, 10);
Good answers before me, but the best, what match exactly your assignment is use range(start, end, step) this way:
$numbers = range(10, 100, 10);
var_dump($numbers);
use
$numbers = range(10, 100, 10);
It will create and array starting with 10 to 100 with 10 steps.
1.You can use for loop like below (don't hate for loop):-
<?php
$numbers = array();
for($i=10;$i<=100;$i=$i+10)
{
$numbers[] = $i;
}
print_r($numbers);
?>
Output:-https://eval.in/612601
2.range() option (better one):-
<?php
$numbers = range(10, 100, 10);
print_r($numbers);
?>
Output:- https://eval.in/612607
You could use multiple ways.
Use a for loop:
$dynamic_array = [];
for($i = 10; $i <= 100; $i += 10){
$dynamic_array[] = $i;
}
print_r($dynamic_array);
Use a do, while loop:
$dynamic_array2 = [];
$i = 10;
do{
$dynamic_array2[] = $i;
$i += 10;
} while($i <= 100);
print_r($dynamic_array2);
Use the Range() function:
$dynamic_array3 = range(10, 100, 10);
print_r($dynamic_array3);
I would suggest the range function as it is the shortest and easiest.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Can someone show me how I would write a php function that converts a base 36 string to a base 10 integer without using the base convert function
the function should work like this
echo base36_to_base10('614qa'); //prints 10130482
echo base36_to_base10('614z1'); //prints 10130797
Just use the native base_convert function:
echo base_convert('614qa', 36, 10);
or if you prefer:
function base36to10($value) {
return base_convert($value, 36, 10);
}
If you can'r or won't use base_convert, this should do it:
function base36to10($value) {
// check for correct input
if (preg_match('/^[0-9A-Z]+$/i', $value) == 0) {
return NULL;
}
// reverse and change to uppercase
$value = strtoupper(strrev($value));
// converted value
$converted = 0;
// cycle on character
for ($c = 0, $l = strlen($value); $c < $l; ++$c) {
// if the character is a digit
if (ctype_digit($value[$c])) {
// convert directly
$v = (int) $value[$c];
}
// else convert ascii value
else {
$v = ord($value[$c]) - 55; // -55 == 10 - 65
}
// add to converted
$converted += $v * pow(36, $c);
}
// now return
return $converted;
}
Slightly different option using a array of symbols:
function base36_to_base10($input) {
$symbols = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'
,'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
//flip the array so symbols are keys (or just write it that way to begin with)
$symbols = array_flip($symbols);
// reverse input string and convert to array
// (reversing the string simplifies incrementing place value as you iterate it)
$x = str_split(strrev($input));
$sum = 0;
foreach ($x as $place => $symbol) {
// increment sum with base 10 representation of base 36 place value
$sum += $symbols[$symbol] * pow(36, $place);
// or with PHP 5.6+
//$sum += $symbols[$symbol] * 36 ** $place;
}
return $sum;
}
How it works with one of your examples:
reverse input = 614qa -> aq416
initialize sum = 0
a -> 10, 10 * 36^0 = 10, sum + 10 = 10
q -> 26, 26 * 36^1 = 936, sum + 936 = 946
4 -> 4, 4 * 36^2 = 5184, sum + 5184 = 6130
1 -> 1, 1 * 36^3 = 46656, sum + 46656 = 52786
6 -> 6, 6 * 36^4 = 10077696, sum + 10077696 = 10130482
I have the following array with undefined number of elements
$marks=array('2','4','9','3');
target=50;
I want to randomly loop through the array, add up the values I fetch until the total is my target.
$total=0; /////initialize total
for($i=0;$i<=sizeof($marks);++$i)
{
/////////Pick up random values add them up until $total==$target
/////////return the new array with selected elements that sums up to
/////////target
}
I hope my question is clear, also note that the loop should not iterate too many times since the elements might never add up to the total. I have tried adding the items in line but to no avail. Thanks in advance
I think this'll work for you and always return you value of count to be 50 only
$marks = array(6,7,9,6,7,9,3,4,12,23,4,6,4,5,7,8,4);
$target = 50;
function sum($marks, $target) {
$count = 0;
$result = [];
for ($i = 0; $i <= $target; $i++) {
if ($count < $target) {
$add = $marks[array_rand($marks)];
$count = $count + $add;
$result['add'][] = $add;
} elseif ($count == $target) {
break;
} elseif ($count >= $target) {
$extra = $count - $target;
$count = $count-$extra;
$result['extra'] = $extra;
}
}
return $result;
}
print_r(sum($marks, $target));
The way you describe your logic, a while loop might make more sense:
<?php
$marks = array(2, 4, 9, 3);
$target = 50;
$sum = 0;
$i = 0; // to keep track of which iteration we're on
// PHP can natively randomize an array:
shuffle($marks);
while ($sum < $target && $i < count($marks)) {
$sum += $marks[$i];
$i++; // keep track of which iteration we're on
}
// after the loop, we've either added every number in $marks,
// or $sum >= $target
Don't forget that it might exceed $target without ever being equal to it, as Dagon pointed out in a comment.
Look into PHP's native array shuffle: https://secure.php.net/manual/en/function.shuffle.php
This may be a good alternative for the above answer.
Why I say so is that I have set it in such a way that it doesn't let the total go over the target, and when there is such a situation, the current number in the array is decremented by one and added as a new element so that if there is no possible number in the stack, there will be one eventually making this loop not go on infinitely. :)
<?php
$marks = ['2', '4', '9', '3'];
$target = 50;
$total = 0;
$numbersUsed = [];
while($total != $target) {
$index = rand(0, count($marks) - 1);
$number = $marks[$index];
if($number + $total > $target) {
$number = 0;
$marks[] = $marks[$index] - 1;
} else {
$numbersUsed[] = $number;
}
$total += $number;
echo $total . "\n";
}
// To see which numbers were used:
print_r($numbersUsed);
?>
Testing:
Starting with the array ['2', '4', '9', '3'],
We loop and get the result:
4 13 17 20 22 31 35 44 46 48 48 48 48 50
And we get this array which includes the numbers used to get the final result:
Array
(
[0] => 4
[1] => 9
[2] => 4
[3] => 3
[4] => 2
[5] => 9
[6] => 4
[7] => 9
[8] => 2
[9] => 2
[10] => 2
)