Created
November 20, 2019 00:23
-
-
Save Samasaur1/0c75ba05a929e734ee4d7600a1ac87f9 to your computer and use it in GitHub Desktop.
Functions to generate the points of a regular n-gon with side length s
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Darwin | |
func positionOfPoint(_ i: Int, sideLength s: Double, exteriorAngle alpha: Double) -> (x: Double, y: Double) { | |
if i == 0 { | |
return (0, 0) | |
} | |
let previousResult = positionOfPoint(i - 1, sideLength: s, exteriorAngle: alpha) | |
return (previousResult.x + (s * cos(Double(i - 1) * alpha)), previousResult.y + (s * sin(Double(i - 1) * alpha))) | |
} | |
positionOfPoint(0, sideLength: 5, exteriorAngle: Double.pi / 2) | |
positionOfPoint(1, sideLength: 5, exteriorAngle: Double.pi / 2) | |
positionOfPoint(2, sideLength: 5, exteriorAngle: Double.pi / 2) | |
positionOfPoint(3, sideLength: 5, exteriorAngle: Double.pi / 2) | |
func listOfPoints(sides n: Int, sideLength s: Double) -> [(x: Double, y: Double)] { | |
let alpha = Double.pi * 2 / Double(n) | |
var array: [(x: Double, y: Double)] = [(0, 0)] | |
for i in 1..<n { | |
array.append((array[i-1].x + (s * cos(Double(i - 1) * alpha)), array[i-1].y + (s * sin(Double(i - 1) * alpha)))) | |
} | |
return array | |
} | |
listOfPoints(sides: 4, sideLength: 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment