Counting sticks that touch red lines in Julia

Viewed 83

I want to randomly "scatter" sticks of length 1 like shown in the diagram.
I also want to count the sticks that touched the red lines.

enter image description here

My approach was to create normalized vectors that are oriented randomly in space.
The problem is that they are all at the origin and I am also not sure how to identify and count those who touch the red lines

a = [randn(), randn()]; 
line = a/norm(a) # Normalized vector in random direction
1 Answers

Here is one of the ways to approach your question using simulation:

julia> using Statistics

julia> function gen_point()
           α = rand() * 2π
           range_x = 5 # anything as your lines are horizontal
           range_y::Int = 5 # must be a positive integer
           @assert range_y >= 1
           x0 = [rand() * range_x, rand() * range_y]
           xd = [cos(α), sin(α)]
           return (x0, x0 .+ xd)
       end
gen_point (generic function with 1 method)

julia> intersects(point) = floor(point[1][2]) != floor(point[2][2])
intersects (generic function with 1 method)

julia> mean((intersects(gen_point()) for _ in 1:100_000))
0.63731

julia> 2/π # our simulation recovers the theoretical result
0.6366197723675814

Some comments:

  • In my solution I sample the angle in (0,2pi) range;
  • I use x_range and y_range to define the rectangle in which the lines are scattered (x_range can be anything, but it is important that y_range is an integer);
  • I have not optimized the code for speed, but for simplicity; in my gen_point function I generate a 2-element vector holding 2-element vectors indicating (x,y) locations of endpoints of the line; the intersects function - as you can see is quite simple: if y-axis of both endpoints do not have the same integer part this means that the line must intersect horizontal line of the form y=i, where i is an integer (I ignore the case where we would sample points that have exactly integer y axis value, as this is negligible);
  • note that your plot is incorrect as x and y axes are scaled differently so actually the lines you have drawn do not all have length 1 (this is a side comment - not affecting the solution)
Related