Skip to content

Instantly share code, notes, and snippets.

@ksprwhite
Last active April 17, 2018 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksprwhite/ba0d2629b5653241718559dcb2c2af61 to your computer and use it in GitHub Desktop.
Save ksprwhite/ba0d2629b5653241718559dcb2c2af61 to your computer and use it in GitHub Desktop.
matrix to .txt
<?php
$matrix = generateMatrix(20, 20);
$homePath = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'
? $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH']
: $_SERVER['HOME']);
$filename = $homePath . '\\matrix.txt';
$file = fopen($filename, 'w') or die('imposible escribir en ' . $filename);
$content = '';
$widthColumns = [];
foreach ($matrix as $row) {
foreach ($row as $x => $number) {
if (!isset($widthColumns[$x])) {
$widthColumns[$x] = [];
}
$widthColumns[$x][] = strlen((string) $number);
}
}
foreach ($widthColumns as $i => $c) {
$widthColumns[$i] = max($c);
}
foreach ($matrix as $row) {
foreach ($row as $column => $number) {
if ($widthColumns[$column] > strlen((string) $number)) {
$content .= str_repeat(' ', $widthColumns[$column] - strlen((string) $number));
}
$content .= $number . ', ';
}
$content .= PHP_EOL;
}
echo $content . PHP_EOL;
if (fwrite($file, $content)) {
echo 'matriz escrita en el fichero: ' . $filename;
exit(0);
} else {
echo 'error al escribir en el fichero: ' . $filename;
exit(1);
}
fclose($file);
function generateMatrix($sizeX = 1, $sizeY = 1)
{
$sizeX = max(1, $sizeX);
$sizeY = max(1, $sizeY);
$size = [$sizeX, $sizeY];
$matrix = []; // definimos la matriz
// columnas
$columns = range(0, $size[0] - 1); // genera un array entre 0 y $size[0]
// filas
$rows = range(0, $size[1] - 1); // genera un array entre 0 y $size[1]
/* 2 iteraciones (foreach), una para las filas y otro para las columnas */
// iteramos las filas
foreach ($rows as $row) {
// definimos la fila como un array y cada elemento
// de ese array es una columna
if (!isset($matrix[$row])) {
$matrix[$row] = [];
}
// iteramos las columnas
foreach ($columns as $column) {
// el aleatorio será par si la columna es impar
$pair = ($column + 1) % 2 !== 0;
// generamos el aleatorio entre 1 y $size[0] * $size[1]
$random = getRandom(1, $size[0] * $size[1], $pair);
// agregamos el numero aleatorio
$matrix[$row][$column] = $random;
}
}
return $matrix;
}
// funcion para obtener un aleatorio par o impar
function getRandom($min = 0, $max = 999, $pair = true)
{
do {
$number = random_int($min, $max);
} while ($pair ? ($number % 2 !== 0) : ($number % 2 === 0));
return $number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment