PHP regex equivalent of nth-child [closed] - php

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";
}
}

Related

How to add specific numbers within an array in php [closed]

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

Pairs of opposite values [closed]

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.

PHP: Number of consecutive elements in array [closed]

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.

How can I find how often the sum of three consecutive values in a set equal a certain value?

9 numbers. Count how often the sum of 3 consecutive numbers in this set of numbers equaled to 16:
2, 7, 7, 1, 8, 2, 7, 8, 7,
The answer is 2. 2 + 7 + 7 = 16 and 7 + 1 + 8 = 16
But I can't seem to get the answer, because I don't know how to "loop" back and skip the first number and do the process over.
How would one be able to solve this utilizing arrays, and how would one solve this without utilizing arrays?
The 9 numbers are randomly generated, and it has to stay that way, but for the sake of solving, I used seed of 3 using srand(3). This is my current code below:
<?php
srand(3);
$count = 1;
$answer = 0;
$num1 = 0;
$num2 = 0;
$num3 = 0;
for ($i = 0; $i < 9; $i++)
{
$num = rand(0, 9);
echo $num . ', ';
if ($count == 1)
$num1 = $num;
else if ($count == 2)
$num2 = $num;
else if ($count == 3)
{
$num3 = $num;
$count = 1;
}
if ($num1 + $num2 + $num3 == 16)
$answer++;
$count++;
}
echo '<br />*******' . $answer . '*******';
?>
Obviously this isn't the right answer because I had to do the check again, but skipping the first number, and so on and so forth until (the last indexed number - index 3)
Probably not the most efficient solution, but its hard to think at 11 at night:
$array = array(2, 7, 7, 1, 8, 2, 7, 8, 7);
$count = count($array);
for ($x = 0; $x < $count; $x++) {
$parts = array_chunk($array, 3);
foreach ($parts as $part) {
if (array_sum($part) == 16 && count($part) == 3) {
print_r($part);
}
}
array_shift($array);
}
Another solution which I think is the more efficient, logic similar to what #Jeroen Vannevel answered:
$array = array(2, 7, 7, 1, 8, 2, 7, 8, 7);
$count = count($array) - 2;
for ($x = 0; $x < $count; $x++) {
if ($array[$x] + $array[$x+1] + $array[$x+2] == 16) {
echo "{$array[$x]} + {$array[$x+1]} + {$array[$x+2]} = 16 <br />";
}
}
Not a PHP writer but this could be your approach:
Fill the array from indices 0 up to and including 8 with a random value.
Iterate from index 0 to index [length - 3]. (length is 9)
Calculate the sum of the values on index [currentIndex], [currentIndex + 1] and [currentIndex + 2].
Whenever the value of that sum equals 16, increment your [count] variable by 1.

How to increment a number by 2 in a PHP For Loop [duplicate]

This question already has answers here:
PHP while loop add by 2
(3 answers)
Closed 1 year ago.
The following is a simplified version of my code:
<?php for($n=1; $n<=8; $n++): ?>
<p><?php echo $n; ?></p>
<p><?php echo $n; ?></p>
<?php endfor; ?>
I want the loop to run 8 times and I want the number in the first paragraph to increment by 1 with each loop, e.g.
1, 2, 3, 4, 5, 6, 7, 8 (this is obviously simple)
However, I want the number in the second paragraph to increment by 2 with each loop, e.g...
1, 3, 5, 7, 9, 11, 13, 15
I can't figure out how to make the number in the second paragraph increment by 2 with each loop. If I change it to $n++ then it increments by 2, but it then makes the loop run only 4 times instead of 8.
Any help would be much appreciated. Thanks!
You should do it like this:
for ($i=1; $i <=10; $i+=2)
{
echo $i.'<br>';
}
"+=" you can increase your variable as much or less you want.
"$i+=5" or "$i+=.5"
<?php
for ($n = 0; $n <= 7; $n++) {
echo '<p>'.($n + 1).'</p>';
echo '<p>'.($n * 2 + 1).'</p>';
}
?>
First paragraph:
1, 2, 3, 4, 5, 6, 7, 8
Second paragraph:
1, 3, 5, 7, 9, 11, 13, 15
You should use other variable:
$m=0;
for($n=1; $n<=8; $n++):
$n = $n + $m;
$m++;
echo '<p>'. $n .'</p>';
endfor;
Simple solution
<?php
$x = 1;
for($x = 1; $x < 8; $x++) {
$x = $x + 1;
echo $x;
};
?>
Another simple solution with +=:
$y = 1;
for ($x = $y; $x <= 15; $y++) {
printf("The number of first paragraph is: $y <br>");
printf("The number of second paragraph is: $x+=2 <br>");
}
<?php
$x = 1;
for($x = 1; $x < 8; $x++) {
$x = $x + 2;
echo $x;
};
?>

Categories