How to resolve the algorithm Constrained random points on a circle step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Constrained random points on a circle step by step in the Swift programming language

Table of Contents

Problem Statement

Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that

10 ≤

x

2

y

2

≤ 15

{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}

. Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once. There are several possible approaches to accomplish this. Here are two possible algorithms.

  1. Generate random pairs of integers and filter out those that don't satisfy this condition:
  2. Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Constrained random points on a circle step by step in the Swift programming language

Source code in the swift programming language

let nPoints = 100

func generatePoint() -> (Int, Int) {
  while true {
    let x = Int.random(in: -15...16)
    let y = Int.random(in: -15...16)
    let r2 = x * x + y * y

    if r2 >= 100 && r2 <= 225 {
      return (x, y)
    }
  }
}

func filteringMethod() {
  var rows = [[String]](repeating: Array(repeating: " ", count: 62), count: 31)

  for _ in 0..<nPoints {
    let (x, y) = generatePoint()

    rows[y + 15][x + 15 * 2] = "*"
  }

  for row in rows {
    print(row.joined())
  }
}

func precalculatingMethod() {
  var possiblePoints = [(Int, Int)]()

  for y in -15...15 {
    for x in -15...15 {
      let r2 = x * x + y * y

      if r2 >= 100 && r2 <= 225 {
        possiblePoints.append((x, y))
      }
    }
  }

  possiblePoints.shuffle()

  var rows = [[String]](repeating: Array(repeating: " ", count: 62), count: 31)

  for (x, y) in possiblePoints {
    rows[y + 15][x + 15 * 2] = "*"
  }

  for row in rows {
    print(row.joined())
  }
}

print("Filtering method:")
filteringMethod()

print("Precalculating method:")
precalculatingMethod()


  

You may also check:How to resolve the algorithm Animation step by step in the Raku programming language
You may also check:How to resolve the algorithm Factorions step by step in the Lambdatalk programming language
You may also check:How to resolve the algorithm Average loop length step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Super-d numbers step by step in the Clojure programming language
You may also check:How to resolve the algorithm Real constants and functions step by step in the Axe programming language