A
A
ak_wi2019-10-10 13:01:58
PHP
ak_wi, 2019-10-10 13:01:58

How to implement in PHP: the positions of two neighboring numbers are shown by the program after five displays of other numbers?

Those. there is a sequence 1,2,3,4,5,6,7,8,9,10,11,12 etc. unlimited length
It must be output as: 1, 3, 5, 7, 9, 11, 2, 4, 6, 8, 10, 12

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mahmudchon, 2019-10-10
@mahmudchon

In your example it goes through 6.

$str_0 = '';
$str_1 = '';
$str_2 = '';
$y = 0;
for($x = 1; $x <= 30; $x++) {
    if($x % 2 !== 0) {
        $str_1 .= $x . ',';
    } else {
        $str_2 .= $x . ',';
    }
    $y++;
    if($y == 10) {
        $str_0 .= $str_1 . $str_2;
        $str_1 = '';
        $str_2 = '';
        $y = 0;
    }
    
}
echo substr($str_0, 0, strlen($str_0) - 1);
//1,3,5,7,9,2,4,6,8,10,11,13,15,17,19,12,14,16,18,20,21,23,25,27,29,22,24,26,28,30

T
tsarevfs, 2019-10-10
@tsarevfs

It's not possible the way you described.
let "1" come first. This means that "2" stands in 5 positions at 1 + 6 = 7th place. The position for "3" is also defined - 7+6=13. Similarly, you can get the position of all other numbers.
But then we have no numbers left to fill in the "holes".

T
tatarrr95, 2019-10-10
@tatarrr95

$array = [1,2,3,4,5,6,7,8,9,10,11,12];
$a = array_fill(0, count($array)/2, '');
$answer = array_fill(0, count($array), '');
$j=0;
for($i=0; $i<count($array); $i+=2){
    $a[$j] = [$array[$i], $array[$i+1]];
    $j++;
}
for($i=0; $i<count($a); $i++){
    $answer[$i] = $a[$i][0];
    $answer[$i+6] = $a[$i][1];
}
print implode(", ", $answer);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question