program RandomArrayPlacement;
{$mode objfpc}{$H+} // Enable object pascal extensions
uses
SysUtils;
const
ARRAY_SIZE = 8;
type
// Define a distinct type for our 8x8 grid
TGrid = array[1..ARRAY_SIZE, 1..ARRAY_SIZE] of Integer;
{------------------------------------------------------------------
Generates a random integer between Min and Max (inclusive).
Example: GetRandomValue(10, 99) might return 42.
------------------------------------------------------------------}
function GetRandomValue(Min, Max: Integer): Integer;
begin
// Random(Range) returns 0 to Range-1, so we offset it by Min
GetRandomValue := Random(Max - Min + 1) + Min;
end;
{------------------------------------------------------------------
Fills an 8x8 array with zeros, then places exactly one
random value (from 1 to 99) in a random column of each row.
------------------------------------------------------------------}
procedure PopulateGrid(var Grid: TGrid);
var
Row, Col: Integer;
RandomValue: Integer;
begin
// 1. Initialize the entire grid with zeros
for Row := 1 to ARRAY_SIZE do
begin
for Col := 1 to ARRAY_SIZE do
begin
Grid[Row, Col] := 0;
end;
end;
// 2. Place one random value per row
for Row := 1 to ARRAY_SIZE do
begin
// Pick a random column index between 1 and 8
Col := GetRandomValue(1, ARRAY_SIZE);
// Generate a random payload value (e.g., between 1 and 99)
// Adjust these bounds to fit whatever range your project needs
RandomValue := GetRandomValue(1, 99);
// Assign the value to the chosen cell
Grid[Row, Col] := RandomValue;
end;
end;
{------------------------------------------------------------------
Helper procedure to cleanly print the matrix to the console
------------------------------------------------------------------}
procedure PrintGrid(const Grid: TGrid);
var
Row, Col: Integer;
begin
for Row := 1 to ARRAY_SIZE do
begin
for Col := 1 to ARRAY_SIZE do
begin
// Format output to keep columns aligned neatly
Write(Grid[Row, Col]:4);
end;
WriteLn; // Move to the next line after finishing a row
end;
end;
// --- Main Program ---
var
MyGrid: TGrid;
begin
// Initialize the random number generator seed using the system time
Randomize;
WriteLn('Generating 8x8 grid with one random value per row:');
WriteLn('--------------------------------------------------');
PopulateGrid(MyGrid);
PrintGrid(MyGrid);
end.
(*
run:
Generating 8x8 grid with one random value per row:
--------------------------------------------------
0 20 0 0 0 0 0 0
0 0 0 0 0 0 0 34
0 27 0 0 0 0 0 0
0 0 0 0 8 0 0 0
0 54 0 0 0 0 0 0
0 0 74 0 0 0 0 0
0 0 0 0 0 0 46 0
0 0 0 0 7 0 0 0
*)