0

So, i have a small issue witch creating random numbers for an 2d array in python.

I have a matrix looking like this

matrix:
       row = ['.' for i in range(w)]
        self.matrix = [row]
        for j in range(h - 1):
            row = ['.' for i in range(w)]
            self.matrix.append(row)

w = int(input("please insert the width of the array: "))
h = int(input("please insert the height of the array: "))

user = int(input("please insert a number for objects: "))

x = random.sample(range(w), user)
y = random.sample(range(h), user)

list(zip(x, y))

So, now i want to create so many random numbers as user input. For example, it the user inputs 100, i need 100 numbers from x and y, so that i can use them as position, to insert objects randomly into the array.

But if the width and height are smaller then userinput i get an error.

5
  • This here "in sample raise ValueError("Sample larger than population")" Commented Dec 17, 2015 at 13:06
  • Your user value is greater than len(range(w)) (or len(range(h))) Commented Dec 17, 2015 at 13:08
  • Yeah, but is there a way to overcome this, i have tried with other random possibilities, but haven't come to a solution. Commented Dec 17, 2015 at 13:10
  • 3
    Calling random.sample twice independently doesn't make a lot of sense to me. That means that all of the points you choose from the grid will have completely unique x coordinates and y coordinates - for example, you'll never end up with both (0,0) and (0,1). If you want actually random coords, you need to create a single list of all coordinates and call sample on that list just once. Commented Dec 17, 2015 at 13:12
  • That does make more sense, i will try it out. Thx :) Commented Dec 17, 2015 at 13:19

1 Answer 1

2

Using the following two lines for x and yshould give you the results you expect:

x = [random.randint(0, w-1) for c in range(user)]
y = [random.randint(0, h-1) for c in range(user)]
Sign up to request clarification or add additional context in comments.

1 Comment

yes, that did work, thanks so much, it helps me alot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.