How to initialize a matrix with random characters in PHP

1 Answer

0 votes
const ROWS = 3;
const COLS = 4;

function print_matrix(array $matrix): void {
    foreach ($matrix as $row) {
        foreach ($row as $ch) {
            // str_pad to mimic setw(3) alignment
            echo str_pad($ch, 3, " ", STR_PAD_LEFT);
        }
        echo PHP_EOL;
    }
}

function get_random_character(): string {
    $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $index = random_int(0, strlen($characters) - 1);
    
    return $characters[$index];
}

function initialize_matrix_with_random_characters(int $rows, int $cols): array {
    $matrix = [];
    for ($i = 0; $i < $rows; $i++) {
        $row = [];
        for ($j = 0; $j < $cols; $j++) {
            $row[] = get_random_character();
        }
        $matrix[] = $row;
    }
    
    return $matrix;
}

function main(): void {
    $matrix = initialize_matrix_with_random_characters(ROWS, COLS);

    print_matrix($matrix);
}

main();

         
         
/*
run:
  
  A  4  R  t
  N  w  p  N
  b  D  1  H
  
*/

 



answered 11 hours ago by avibootz
edited 10 hours ago by avibootz
...