Gilberto Langarica
Gilberto Langarica

Reputation: 75

Fill matrix with random numbers within range?

I am new to programming and python. I am trying to create a matrix(6, 6) with random numbers within a certain range. Each number must be twice. Should I use matrix, multi dimensional array or list of lists? I'd like to know what is the easiest way to achieve this.

This is what I have right now:

rows = 6
columns = 6
range(0, 18)

matrix = [[0 for x in range(rows)] for y in range(columns)]

# Loop into matrix to fill with random numbers withing the range property.
# Matrix should have the same number twice.
for row in matrix:
    print(row)

Upvotes: 1

Views: 899

Answers (2)

Juan C
Juan C

Reputation: 6132

Assuming you're looking for integers, it's as easy as this:

import numpy as np
import random
number_sample = list(range(18))*2 #Get two times numbers from 0 to 17
random.shuffle(number_sample) #Shuffle said numbers
np.array(number_sample).reshape(6,6) #Reshape into matrix

Output:

array([[ 1,  0,  5,  1,  8, 15],
       [ 9,  3, 15, 17,  0, 14],
       [ 7,  9, 11,  7, 16, 13],
       [ 4, 10,  8, 12,  5,  6],
       [ 6, 11,  4, 14,  3, 13],
       [10, 16,  2, 17,  2, 12]])

Edit: Changed answer to reflect changes in your question

Upvotes: 3

janos
janos

Reputation: 124648

You could:

  • Generate a list of 36 numbers having each value of 0-17 twice as 2 * list(range(18))
  • Shuffle the list of numbers
  • Slice the list to equal chunks of 6

The result will be a matrix that meets your requirements, using only the standard library.

Something like this:

import random

nums = 2 * list(range(18))
random.shuffle(nums)
matrix = [nums[i:i+6] for i in range(0, 36, 6)]

Upvotes: 3

Related Questions