Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
$a = array(2, 6, 24, 16, 7, 10);
I know how to add all the numbers using array_sum() but if I want to add only the numbers between 2 and 16 how can do that?
This is one of the solution that that I've come up with:
$a = array(2, 6, 24, 16, 7, 10);
$r = array_slice($a, 0, -2);
print_r (array_sum($r));
Just want to know if there is any other way to get the result.
To deal with dynamic bound limits you can extend the initial approach(array_slice + array_sum) using array_search function:
$arr = [2, 6, 24, 16, 7, 10];
$a = 10;
$b = 24;
$lowerBound = array_search($a, $arr);
$upperBound = array_search($b, $arr);
if (($low = $lowerBound) > $upperBound) { // if bounds were confused
$lowerBound = $upperBound;
$upperBound = $low;
}
$sum = array_sum(array_slice($arr, $lowerBound, $upperBound - $lowerBound + 1));
print_r($sum); // 57
Related
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 6 years ago.
Improve this question
I have strings: 23-65, 123-45, 2-5435, 345-4
I want to add zeros to them so all of them will look like ###-#### (three digits dash four digits): 023-0065, 123-0045, 002-5435, 345-0004
How can i do it in php?
Thanks!
You will need to split them using
$parts = explode('-', $number);`
then use str_pad function:
$parts[0] = str_pad($parts[0], 3, "0");
$parts[1] = str_pad($parts[0], 4, "0");
and then concatenate them again
$number = implode('-', $parts);
Alternatively you can pad them using vsprintf:
$number = vsprintf('%03d-%04d', $parts);
Try:
$str = "23-65, 123-45, 2-5435, 345-4";
$numArray = explode(",",$str);
$str_new = "";
foreach($numArray as $nums) {
$nums = explode("-",$nums);
$num1 = str_pad($nums[0], 3, '0', STR_PAD_LEFT);
$num2 = str_pad($nums[1], 4, '0', STR_PAD_LEFT);
$str_new .= $num1."-".$num2.",";
}
$str_new = rtrim($str_new,",");
Output:
023-0065, 123-0045,0 2-5435, 345-0004
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need to identify some objects in an array by their position and I'm struggling with the logic. I'm looking for the PHP equivalent nth-child(5n + 1) as a condition, resulting in objects in positions 0, 5, 10, et al. within a loop.
Logically it's probably simplest to divide by 5 and look for a whole number, e.g. 0/5 = 0 pass, 1/5 = .2 fail, 5/5 = 1 pass.
If the
for ($i = 0; $i < $total; $i++) {
// obviously this doesn't work because it's nonsense :)
$rhythm = preg_match(/^(\d+){N % 5 == 0}/, $i)
if ($rhythm) {
// is 0, 5, 10,
// etc
} else {
// 1, 2, 3, 4,
// 6, 7, 8, 9,
// etc
}
Regex is absolutely the wrong tool for the job. Although if you really wanted, /[05]$/ would do it.
Try $rhythm = $i % 5 == 0; instead. You can change the 0 to another number (1-4) to do the +1 part of the condition.
I guess you could do it like this as well.
for ($i = 0; $i < $total; $i+=5) {
{
// is 0, 5, 10,
// etc
array[ $i ] = "whatever05";
for ($j = 1; $j < 5; $j++ )
{
// 1, 2, 3, 4,
// 6, 7, 8, 9,
// etc
if ( ($i + $j) >= $total )
break;
array[ $i + $j ] = "whatever12346789";
}
}
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 need to write a function that when i have an array with n numbers from -10 to 10 (without 0) 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);
In example right answer is 5 (pairs are bolded)
i figure out something like that:
<?php
$array = [3, 6, -3, 5, -10, 3, 10, 1, 7, -1, -9, -8, 7, 7, -7, -2, -7];
function pairs($array=[]){
$copy = $array;
$arrayLength = count($copy);
$pairs=0;
while($arrayLength!=0){
$a = array_values($array)[0];
$b = -$a;
for( $i=1 ; $i==$arrayLength ; $i++ ){
if($array[$i]==$b){
unset($array[$i]);
$pairs++;
$arrayLength--;
}
else{
unset($array[$i]);
$arrayLength--;
}
}
return $pairs;
}
unset($copy);
}
var_dump(pairs($array));
?>
Try out this one:
function pairs($array=[]){
$pairs = [];
// counting the positive and negative of each number in the set
foreach($array as $v){
$av = abs($v);
if(!isset($pairs[$av]))
$pairs[$av] = [
'pos' => 0,
'neg' => 0
];
($v > 0) ? $pairs[$av]['pos']++ : $pairs[$av]['neg']++;
}
$pair_count = 0;
// getting the number of pairs for each number, based on those counts
foreach($pairs as $pair){
$pair_count += min($pair['pos'],$pair['neg']);
}
return $pair_count;
}
DEMO
This gets rid of the annoying need to rebuild the array indexes every time you unset (part of where your issues with your provided function are coming from), and also makes it so you only need to loop through it twice and therefore is more efficient, especially for large data sets.
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 8 years ago.
Improve this question
I have been working on one problem:
Find the largest group of consecutive numbers in an array.
Say we have an array [5, 43, 4, 56, 3, 2, 44, 57, 58, 1], the biggest group of consecutive numbers in this array is 5 (1, 2, 3, 4, and 5).
The solution algorithm must be time complexity of O(n).
I have solved this with the following ruby code but I am having trouble porting it to PHP as the solution requires.
arr = [8, 13, 14, 10, 6, 7, 8, 14, 5, 3, 5, 2, 6, 7, 4]
result = []
stage = []
for i in arr:
if len(stage) > 0 and i != stage[-1]+1:
if len(stage) > 1:
result.append(stage)
stage = []
stage.append(i)
print result
$a = [8, 13, 14, 10, 6, 7, 8, 14, 5, 3, 5, 2, 6, 7, 4];
$res = [];
$stage = [];
foreach($a as $i) {
if(count($stage) > 0 && $i != $stage[count($stage)-1]+1) {
if(count($stage) > 1) {
$res[] = $stage;
}
$stage = [];
}
$stage[] = $i;
}
print_r($res);
It's not O(n) but you can try this:
// Define array
$array = array(5,8,3,2,10,11,15,13,12,1,4,5,16);
// Sorting
asort($array);
$previous = null;
$result = array();
$consecutiveArray = array();
// Slice array by consecutive sequences
foreach($array as $number) {
if ($number == $previous + 1) {
$consecutiveArray[] = $number;
} else {
$result[] = $consecutiveArray;
$consecutiveArray = array($number);
}
$previous = $number;
}
$result[] = $consecutiveArray;
// Get length of each sub array
$count = array_map('count', $result);
You can get max length by max($count).
This solution gives you following array:
array(
0 => array(1,2,3,4,5)
1 => array(5)
2 => array(8)
3 => array(10,11,12,13)
4 => array(15,16)
Here is a python (my PHP is not too good) that does what your description asks, in o(n) if your sequence is decreasing:
lists = dict()
for i in val:
if i in lists:
continue
a = {i}
if (i + 1) in lists:
b = lists[i+1]
b.update(a)
a = b
if (i - 1) in lists:
b = lists[i-1]
# this messes up the complexity
for k in b:
lists[k] = a
a.update(b)
lists[i] = a
The idea is that lists maintain a dict of sets indexed on all the elements in the list. Whenever you encounter a new element, the previous and next sets are merged, if present.
The update operation is technically o(n), but it is not compounded by the external loop, as there can only be n insertion into sets by merging. The overall is o(n)
If the sequence is not sorted, the merge of the +1 and -1 sets gives a not-so-good complexity.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am creating an incrementing number starting with 1001. If the number goes 1001,1002,1003... when it reaches 10, will it be formatted like 1010 or will it be 10010? I need it to just go in order and be 1010 and when it reaches 100, 1100.
$prefix = "1"; // update the prefix here
$number = 1;
$number++;
$unique = str_pad($number, 3, "0", STR_PAD_LEFT);
$unique = $prefix . $unique;
print_r($unique);
When your count reaches 10, the number printed will be 1010. As described here, str_pad "Pads a string to a certain length with another string" You can create a test with the following:
$prefix = "1"; // update the prefix here
$number = 1;
for ($number = 1; $number <= 100; $number++)
{
$unique = str_pad($number, 3, "0", STR_PAD_LEFT);
$unique = $prefix . $unique;
print($unique."\n");
}
When your count reaches 100, the number printed will be 1100.
However, if you were to go up to 1000, 11000 would be printed - str_pad apparently will not truncate the string to match the specified size.
It will be 1010, but you can test this yourself easily:
$prefix = "1"; // update the prefix here
$number = 9;
$number++;
$unique = str_pad($number, 3, "0", STR_PAD_LEFT);
$unique = $prefix . $unique;
print_r($unique); // 1010
The second argument of str_pad specifies padding. If padding is 3, then 1 becomes 001, 10 becomes 010, 100 becomes 100.
With your code it will be 10010.
It looks like you are making this more complicated than it needs to be. Why not just start with $number = 1001 and increment it and then turn it into a string?
$number = 1001;
$number++;
$unique = strval($number);
print_r($unique);