Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,657 questions

55,409 answers

573 users

How to check if a given row is sorted in a matrix with PHP

2 Answers

0 votes
function isRowSorted($matrix, $row) {
    $cols = count($matrix[0]);
    
    for ($i = 1; $i < $cols; $i++) {
        if ($matrix[$row][$i - 1] > $matrix[$row][$i]) {
            return false;
        }
    }
    return true;
}

$matrix = array(
            array( 4,  7,  9, 12), 
            array( 1,  8,  3,  4), 
            array(-9, -4, -3,  2), 
            array(-8, -3, -9,  4), 
            array( 2,  6,  7, 18)
        );
        
echo "Row 0: " . isRowSorted($matrix, 0) . "\n";
echo "Row 1: " . isRowSorted($matrix, 1) . "\n";
echo "Row 2: " . isRowSorted($matrix, 2) . "\n";
echo "Row 3: " . isRowSorted($matrix, 3) . "\n";
echo "Row 4: " . isRowSorted($matrix, 4) . "\n";



/*
run:

Row 0: 1
Row 1: 
Row 2: 1
Row 3: 
Row 4: 1

*/

 



answered Jun 23, 2023 by avibootz
0 votes
function isRowSorted($matrix, $row) {
    $cols = count($matrix[0]);
    
    $sorted = array_values($matrix[$row]);
    sort($sorted);

    return $matrix[$row] === $sorted;
}
 
$matrix = array(
            array( 4,  7,  9, 12), 
            array( 1,  8,  3,  4), 
            array(-9, -4, -3,  2), 
            array(-8, -3, -9,  4), 
            array( 2,  6,  7, 18)
        );
         
echo "Row 0: " . isRowSorted($matrix, 0) . "\n";
echo "Row 1: " . isRowSorted($matrix, 1) . "\n";
echo "Row 2: " . isRowSorted($matrix, 2) . "\n";
echo "Row 3: " . isRowSorted($matrix, 3) . "\n";
echo "Row 4: " . isRowSorted($matrix, 4) . "\n";
 

 
 
/*
run:
 
Row 0: 1
Row 1: 
Row 2: 1
Row 3: 
Row 4: 1
 
*/

 



answered Jun 25, 2023 by avibootz

Related questions

1 answer 145 views
2 answers 192 views
1 answer 148 views
1 answer 147 views
1 answer 163 views
...