2

I've got a 2d array of zeros: 250 by 250. And I want to generate a random straight random line of a specific length (haven't yet decided). Obviously, since it's a line the values that turn from zero to one must be connected in some way, vertically, horizontally, or diagonally; and it also has to be straight. How could I do this? I'm quite stuck with this problem, any help would be appreciated.

4
  • Please put your code attempt. Commented Oct 30, 2021 at 17:51
  • So by "line on a 2d array" you mean that the array is like an image of (zero/white) pixels and you want to draw a line by changing pixels (to one/black)? You can only approximate a specific length (and angle), and the way the pixels are adjusted along the angle is also approximate. It won't be too hard to make a function for whatever approximation rules you might come up with, but maybe it'll be simpler to use some existing image editing library. Commented Oct 30, 2021 at 17:54
  • Do you mean a line of some random length N somewhere in your 2D array, where the line could be at any angle? Commented Oct 30, 2021 at 18:05
  • You could do it with the python library PIL. PIL is a library to manipulate images and also can do simple drawing. You can convert between images and numpy arrays. If you want to do it yourself without a library, it can be very tricky. In that case I suggest to do some reseach, make some attemtps and post the code you have. Commented Oct 31, 2021 at 3:31

1 Answer 1

2

We can do:

import numpy as np
SIZE = 250
arr = np.zeros((SIZE, SIZE))
M_POS = np.arange(-SIZE, SIZE)
M_POS = np.r_[M_POS,  1 / M_POS[M_POS!=0]]
M = np.random.choice(M_POS, 1)[0]
N = np.random.choice(np.arange(-SIZE, SIZE), 1)[0]
L = 50
P0 = np.array([0, N])
X_Y  = np.array([1, 1 / M]) if abs(M) < 1 else np.array([1, M])
draw_in = np.add(np.repeat([P0], L, axis=0), 
                 np.repeat([X_Y], L, axis=0) * np.arange(L)[:, np.newaxis]).astype(int)
draw_in = draw_in[((draw_in < SIZE) & (draw_in>0)).all(axis=1)]
arr[draw_in[:, 0], draw_in[:, 1]] = 1
Sign up to request clarification or add additional context in comments.

1 Comment

You are wlecome:) I am glad to help Could you consider Accept the answer? @Koza Kurumlu ?

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.