Translation of: Rust
import Foundation

extension String {
  func dropLastIf(_ char: Character) -> String {
    if last == char {
      return String(dropLast())
    } else {
      return self
    }
  }
}

enum Align {
  case left, center, right
}

func getLines(input: String) -> [String] {
  input
    .components(separatedBy: "\n")
    .map({ $0.replacingOccurrences(of: " ", with: "").dropLastIf("$") })
}

func getColWidths(from: String) -> [Int] {
  var widths = [Int]()
  let lines = getLines(input: from)

  for line in lines {
    let lens = line.components(separatedBy: "$").map({ $0.count })

    for (i, len) in lens.enumerated() {
      if i < widths.count {
        widths[i] = max(widths[i], len)
      } else {
        widths.append(len)
      }
    }
  }

  return widths
}

func alignCols(input: String, align: Align = .left) -> String {
  let widths = getColWidths(from: input)
  let lines = getLines(input: input)
  var res = ""

  for line in lines {
    for (str, width) in zip(line.components(separatedBy: "$"), widths) {
      let blanks = width - str.count
      let pre: Int, post: Int

      switch align {
      case .left:
        (pre, post) = (0, blanks)
      case .center:
        (pre, post) = (blanks / 2, (blanks + 1) / 2)
      case .right:
        (pre, post) = (blanks, 0)
      }

      res += String(repeating: " ", count: pre)
      res += str
      res += String(repeating: " ", count: post)
      res += " "
    }

    res += "\n"
  }

  return res
}

let input = """
            Given$a$text$file$of$many$lines,$where$fields$within$a$line$
            are$delineated$by$a$single$'dollar'$character,$write$a$program
            that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
            column$are$separated$by$at$least$one$space.
            Further,$allow$for$each$word$in$a$column$to$be$either$left$
            justified,$right$justified,$or$center$justified$within$its$column.
            """

print(alignCols(input: input))
print()
print(alignCols(input: input, align: .center))
print()
print(alignCols(input: input, align: .right))

The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.


func rot13char(c: UnicodeScalar) -> UnicodeScalar {
  switch c {
  case "A"..."M", "a"..."m":
    return UnicodeScalar(UInt32(c) + 13)
  case "N"..."Z", "n"..."z":
    return UnicodeScalar(UInt32(c) - 13)
  default:
    return c
  }
}

func rot13(str: String) -> String {
  return String(map(str.unicodeScalars){ c in Character(rot13char(c)) })
}

println(rot13("The quick brown fox jumps over the lazy dog"))

implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is "rotated" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.


extension Sequence {
  func sorted<Value>(
    on: KeyPath<Element, Value>,
    using: (Value, Value) -> Bool
  ) -> [Element] where Value: Comparable {
    return withoutActuallyEscaping(using, do: {using -> [Element] in
      return self.sorted(by: { using($0[keyPath: on], $1[keyPath: on]) })
    })
  }
}

struct Person {
  var name: String
  var role: String
}

let a = Person(name: "alice", role: "manager")
let b = Person(name: "bob", role: "worker")
let c = Person(name: "charlie", role: "driver")

print([c, b, a].sorted(on: \.name, using: <))

sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.


for i in 1...5 {
    for _ in 1...i {
        print("*", terminator: "")
    }
    print()
}

demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.


// make an empty map
var a = [String: Int]()
// or
var b: [String: Int] = [:]

// make an empty map with an initial capacity
var c = [String: Int](minimumCapacity: 42)

// set a value
c["foo"] = 3

// make a map with a literal
var d = ["foo": 2, "bar": 42, "baz": -1]

"Create an associative array, also known as a dictionary, map, or hash."


import Cocoa

class LinearCongruntialGenerator {

    var state = 0 //seed of 0 by default
    let a, c, m, shift: Int

    //we will use microsoft random by default
    init() {
        self.a = 214013
        self.c = 2531011
        self.m = Int(pow(2.0, 31.0)) //2^31 or 2147483648
        self.shift = 16
    }

    init(a: Int, c: Int, m: Int, shift: Int) {
        self.a = a
        self.c = c
        self.m = m //2^31 or 2147483648
        self.shift = shift
    }

    func seed(seed: Int) -> Void {
        state = seed;
    }

    func random() -> Int {
        state = (a * state + c) % m
        return state >> shift
    }
}

let microsoftLinearCongruntialGenerator = LinearCongruntialGenerator()
let BSDLinearCongruntialGenerator = LinearCongruntialGenerator(a: 1103515245, c: 12345, m: 2147483648, shift: 0)

print("Microsft Rand:")
for(var i = 0; i < 10; i++)
{
    print(microsoftLinearCongruntialGenerator.random())
}

print("") //new line for readability
print("BSD Rand:")
for(var i = 0; i < 10; i++)
{
    print(BSDLinearCongruntialGenerator.random())
}

The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.


import Darwin

func ethiopian(var #int1:Int, var #int2:Int) -> Int {
  var lhs = [int1], rhs = [int2]

  func isEven(#n:Int) -> Bool {return n % 2 == 0}
  func double(#n:Int) -> Int {return n * 2}
  func halve(#n:Int) -> Int {return n / 2}

  while int1 != 1 {
    lhs.append(halve(n: int1))
    rhs.append(double(n: int2))
    int1 = halve(n: int1)
    int2 = double(n: int2)
  }

  var returnInt = 0
  for (a,b) in zip(lhs, rhs) {
    if (!isEven(n: a)) {
      returnInt += b
    }
  }
  return returnInt
}

println(ethiopian(int1: 17, int2: 34))

The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.


import Darwin
import Foundation

var solution = ""

println("24 Game")
println("Generating 4 digits...")

func randomDigits() -> [Int] {
  var result = [Int]()
  for i in 0 ..< 4 {
    result.append(Int(arc4random_uniform(9)+1))
  }
  return result
}

// Choose 4 digits
let digits = randomDigits()

print("Make 24 using these digits : ")

for digit in digits {
  print("\(digit) ")
}
println()

// get input from operator
var input = NSString(data:NSFileHandle.fileHandleWithStandardInput().availableData, encoding:NSUTF8StringEncoding)!

var enteredDigits = [Double]()

var enteredOperations = [Character]()

let inputString = input as String

// store input in the appropriate table
for character in inputString {
  switch character {
  case "1", "2", "3", "4", "5", "6", "7", "8", "9":
    let digit = String(character)
    enteredDigits.append(Double(digit.toInt()!))
  case "+", "-", "*", "/":
    enteredOperations.append(character)
  case "\n":
    println()
  default:
    println("Invalid expression")
  }
}

// check value of expression provided by the operator
var value = 0.0

if enteredDigits.count == 4 && enteredOperations.count == 3 {
  value = enteredDigits[0]
  for (i, operation) in enumerate(enteredOperations) {
    switch operation {
    case "+":
      value = value + enteredDigits[i+1]
    case "-":
      value = value - enteredDigits[i+1]
    case "*":
      value = value * enteredDigits[i+1]
    case "/":
      value = value / enteredDigits[i+1]
    default:
      println("This message should never happen!")
    }
  }
}

func evaluate(dPerm: [Double], oPerm: [String]) -> Bool {
  var value = 0.0

  if dPerm.count == 4 && oPerm.count == 3 {
    value = dPerm[0]
    for (i, operation) in enumerate(oPerm) {
      switch operation {
      case "+":
        value = value + dPerm[i+1]
      case "-":
        value = value - dPerm[i+1]
      case "*":
        value = value * dPerm[i+1]
      case "/":
        value = value / dPerm[i+1]
      default:
        println("This message should never happen!")
      }
    }
  }
  return (abs(24 - value) < 0.001)
}

func isSolvable(inout digits: [Double]) -> Bool {

  var result = false
  var dPerms = [[Double]]()
  permute(&digits, &dPerms, 0)

  let total = 4 * 4 * 4
  var oPerms = [[String]]()
  permuteOperators(&oPerms, 4, total)

  for dig in dPerms {
    for opr in oPerms {
      var expression = ""

      if evaluate(dig, opr) {
        for digit in dig {
          expression += "\(digit)"
        }

        for oper in opr {
          expression += oper
        }

        solution = beautify(expression)
        result = true
      }
    }
  }
  return result
}

func permute(inout lst: [Double], inout res: [[Double]], k: Int) -> Void {
  for i in k ..< lst.count {
    swap(&lst[i], &lst[k])
    permute(&lst, &res, k + 1)
    swap(&lst[k], &lst[i])
  }
  if k == lst.count {
    res.append(lst)
  }
}

// n=4, total=64, npow=16
func permuteOperators(inout res: [[String]], n: Int, total: Int) -> Void {
  let posOperations = ["+", "-", "*", "/"]
  let npow = n * n
  for i in 0 ..< total {
    res.append([posOperations[(i / npow)], posOperations[((i % npow) / n)], posOperations[(i % n)]])
  }
}

func beautify(infix: String) -> String {
  let newString = infix as NSString

  var solution = ""

  solution += newString.substringWithRange(NSMakeRange(0, 1))
  solution += newString.substringWithRange(NSMakeRange(12, 1))
  solution += newString.substringWithRange(NSMakeRange(3, 1))
  solution += newString.substringWithRange(NSMakeRange(13, 1))
  solution += newString.substringWithRange(NSMakeRange(6, 1))
  solution += newString.substringWithRange(NSMakeRange(14, 1))
  solution += newString.substringWithRange(NSMakeRange(9, 1))

  return solution
}

if value != 24 {
  println("The value of the provided expression is \(value) instead of 24!")
  if isSolvable(&enteredDigits) {
    println("A possible solution could have been " + solution)
  } else {
    println("Anyway, there was no known solution to this one.")
  }
} else {
  println("Congratulations, you found a solution!")
}

The code accepts four digits, either from user input or randomly generated, and calculates arithmetic expressions following the 24 game rules. It also displays examples of the solutions it generates.


Iterative[edit]
func factorial(_ n: Int) -> Int {
	return n < 2 ? 1 : (2...n).reduce(1, *)
}
Recursive[edit]
func factorial(_ n: Int) -> Int {
	return n < 2 ? 1 : n * factorial(n - 1)
}

The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.


Works with: Swift version 5.7

func generateRandomNumArray(numDigits: Int = 4) -> [Character]
{
	guard (1 ... 9).contains(numDigits) else { fatalError("number out of range") }

	return Array("123456789".shuffled()[0 ..< numDigits])
}

func parseGuess(_ guess: String, numDigits: Int = 4) -> String?
{
	guard guess.count == numDigits else { return nil }
    // Only digits 0 to 9 allowed, no Unicode fractions or numbers from other languages
	let guessArray = guess.filter{ $0.isASCII && $0.isWholeNumber }

  	guard Set(guessArray).count == numDigits else { return nil }

  	return guessArray
}

func pluralIfNeeded(_ count: Int, _ units: String) -> String
{
	return "\(count) " + units + (count == 1 ? "" : "s")
}

var guessAgain = "y"
while guessAgain == "y"
{
  	let num = generateRandomNumArray()
  	var bulls = 0
  	var cows = 0

  	print("Please enter a 4 digit number with digits between 1-9, no repetitions: ")

  	if let guessStr = readLine(strippingNewline: true), let guess = parseGuess(guessStr)
	{
		for (guess, actual) in zip(guess, num)
		{
			if guess == actual
			{
	  			bulls += 1
			}
			else if num.contains(guess)
			{
	  			cows += 1
			}
  		}

		print("Actual number: " + num)
		print("Your score: \(pluralIfNeeded(bulls, "bull")) and \(pluralIfNeeded(cows, "cow"))\n")
		print("Would you like to play again? (y): ")

		guessAgain = readLine(strippingNewline: true)?.lowercased() ?? "n"
	}
	else
	{
		print("Invalid input")
  	}
}

import Foundation

func generateRandomNumArray(numDigits: Int = 4) -> [Int] {
  guard numDigits > 0 else {
    return []
  }

  let needed =  min(9, numDigits)
  var nums = Set<Int>()

  repeat {
    nums.insert(.random(in: 1...9))
  } while nums.count != needed

  return Array(nums)
}

func parseGuess(_ guess: String) -> [Int]? {
  guard guess.count == 4 else {
    return nil
  }

  let guessArray = guess.map(String.init).map(Int.init).compactMap({ $0 })

  guard Set(guessArray).count == 4 else {
    return nil
  }

  return guessArray
}

while true {
  let num = generateRandomNumArray()
  var bulls = 0
  var cows = 0

  print("Please enter a 4 digit number with digits between 1-9, no repetitions: ")

  guard let guessStr = readLine(strippingNewline: true), let guess = parseGuess(guessStr) else {
    print("Invalid input")
    continue
  }

  for (guess, actual) in zip(guess, num) {
    if guess == actual {
      bulls += 1
    } else if num.contains(guess) {
      cows += 1
    }
  }

  print("Actual number: \(num.map(String.init).joined())")
  print("Your score: \(bulls) bulls and \(cows) cows\n")
  print("Would you like to play again? (y): ")

  guard readLine(strippingNewline: true)!.lowercased() == "y" else {
    exit(0)
  }
}

The code generates a unique four-digit random number from 1 to 9. It prompts the user for guesses, rejects malformed inputs, and calculates a score based on the guess. The user wins if the guess matches the random number. The score is determined by the number of 'bulls' (correct digits in the correct position) and 'cows' (correct digits in the wrong position). The game ends when the user guesses the number correctly. The code is optimized using Swift 5's standard library.


Works with: Swift version 1.2+
func dot(v1: [Double], v2: [Double]) -> Double {
  return reduce(lazy(zip(v1, v2)).map(*), 0, +)
}

println(dot([1, 3, -5], [4, -2, -1]))

Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].


import Foundation

var ⌚ = NSDate()
println(⌚)

the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.


class Sphere: UIView{

  override func drawRect(rect: CGRect)
  {
    let context = UIGraphicsGetCurrentContext()
    let locations: [CGFloat] = [0.0, 1.0]

    let colors = [UIColor.whiteColor().CGColor,
      UIColor.blueColor().CGColor]

    let colorspace = CGColorSpaceCreateDeviceRGB()

    let gradient = CGGradientCreateWithColors(colorspace,
      colors, locations)

    var startPoint = CGPoint()
    var endPoint = CGPoint()
    startPoint.x = self.center.x - (self.frame.width * 0.1)
    startPoint.y = self.center.y - (self.frame.width * 0.15)
    endPoint.x = self.center.x
    endPoint.y = self.center.y
    let startRadius: CGFloat = 0
    let endRadius: CGFloat = self.frame.width * 0.38

    CGContextDrawRadialGradient (context, gradient, startPoint,
      startRadius, endPoint, endRadius,
      0)
  }
}

var s = Sphere(frame: CGRectMake(0, 0, 200, 200))

struct ContentView: View {

    var body: some View {

      let gradient = RadialGradient(gradient: Gradient(colors:[.white, .black]),
      center: .init(x: 0.4, y: 0.4), startRadius: 10, endRadius: 100)

      return Circle()
          .fill(gradient)
          .frame(width: 200, height: 200)

    }
}

"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection, using SwiftUI in Playground."


func addSuffix(n:Int) -> String {
    if n % 100 / 10 == 1 {
        return "th"
    }

    switch n % 10 {
    case 1:
        return "st"
    case 2:
        return "nd"
    case 3:
        return "rd"
    default:
        return "th"
    }
}

for i in 0...25 {
    print("\(i)\(addSuffix(i)) ")
}
println()
for i in 250...265 {
    print("\(i)\(addSuffix(i)) ")
}
println()
for i in 1000...1025 {
    print("\(i)\(addSuffix(i)) ")
}
println()

The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.


extension String {
  func stripCharactersInSet(chars: [Character]) -> String {
    return String(seq: filter(self) {find(chars, $0) == nil})
  }
}

let aString = "She was a soul stripper. She took my heart!"
let chars: [Character] = ["a", "e", "i"]

println(aString.stripCharactersInSet(chars))

"Function to remove specific characters from a given string"


import Foundation

print("Input max number: ", terminator: "")

guard let maxN = Int(readLine() ?? "0"), maxN > 0 else {
  fatalError("Please input a number greater than 0")
}

func getFactor() -> (Int, String) {
  print("Enter a factor and phrase: ", terminator: "")

  guard let factor1Input = readLine() else {
    fatalError("Please enter a factor")
  }

  let sep1 = factor1Input.components(separatedBy: " ")
  let phrase = sep1.dropFirst().joined(separator: " ")

  guard let factor = Int(sep1[0]), factor != 0, !phrase.isEmpty else {
    fatalError("Please enter a factor and phrase")
  }

  return (factor, phrase)
}

let (factor1, phrase1) = getFactor()
let (factor2, phrase2) = getFactor()
let (factor3, phrase3) = getFactor()

for i in 1...maxN {
  let factors = [
    (i.isMultiple(of: factor1), phrase1),
    (i.isMultiple(of: factor2), phrase2),
    (i.isMultiple(of: factor3), phrase3)
  ].filter({ $0.0 }).map({ $0.1 }).joined()

  print("\(factors.isEmpty ? String(i) : factors)")
}

implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.


Works with: Swift version 5
var str = ", World"
str = "Hello" + str
print(str)

Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.


import Cocoa

var found = false
let randomNum = Int(arc4random_uniform(10) + 1)

println("Guess a number between 1 and 10\n")
while (!found) {
    var fh = NSFileHandle.fileHandleWithStandardInput()

    println("Enter a number: ")
    let data = fh.availableData
    var str = NSString(data: data, encoding: NSUTF8StringEncoding)
    if (str?.integerValue == randomNum) {
        found = true
        println("Well guessed!")
    }
}

"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing."


var letters = [Character]()

for i in 97...122 {
    let char = Character(UnicodeScalar(i))
    letters.append(char)
}

generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.


for num in [5, 50, 9000] {
    println(String(num, radix: 2))
}

generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.


Translation of: Objective-C
import Foundation

func haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double {
    let lat1rad = lat1 * Double.pi/180
    let lon1rad = lon1 * Double.pi/180
    let lat2rad = lat2 * Double.pi/180
    let lon2rad = lon2 * Double.pi/180

    let dLat = lat2rad - lat1rad
    let dLon = lon2rad - lon1rad
    let a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(lat1rad) * cos(lat2rad)
    let c = 2 * asin(sqrt(a))
    let R = 6372.8

    return R * c
}

print(haversine(lat1:36.12, lon1:-86.67, lat2:33.94, lon2:-118.40))

Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.


import Foundation

let request = NSURLRequest(URL: NSURL(string: "http://rosettacode.org/")!)

// Using trailing closure
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in

    // data is binary
    if (data != nil) {
        let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
        println(string)
    }
}

CFRunLoopRun() // dispatch

Print the content of a specified URL to the console using HTTP request.


func luhn(_ number: String) -> Bool {
    return number.reversed().enumerated().map({
        let digit = Int(String($0.element))!
        let even = $0.offset % 2 == 0
        return even ? digit : digit == 9 ? 9 : digit * 2 % 9
    }).reduce(0, +) % 10 == 0
}

luhn("49927398716") // true
luhn("49927398717") // false

The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.


class Josephus {

    class func lineUp(#numberOfPeople:Int) -> [Int] {
        var people = [Int]()
        for (var i = 0; i < numberOfPeople; i++) {
            people.append(i)
        }
        return people
    }

    class func execute(#numberOfPeople:Int, spacing:Int) -> Int {
        var killIndex = 0
        var people = self.lineUp(numberOfPeople: numberOfPeople)

        println("Prisoners executed in order:")
        while (people.count > 1) {
            killIndex = (killIndex + spacing - 1) % people.count
            executeAndRemove(&people, killIndex: killIndex)
        }
        println()
        return people[0]
    }

    class func executeAndRemove(inout people:[Int], killIndex:Int) {
        print("\(people[killIndex]) ")
        people.removeAtIndex(killIndex)
    }

    class func execucteAllButM(#numberOfPeople:Int, spacing:Int, save:Int) -> [Int] {
        var killIndex = 0
        var people = self.lineUp(numberOfPeople: numberOfPeople)

        println("Prisoners executed in order:")
        while (people.count > save) {
            killIndex = (killIndex + spacing - 1) % people.count
            executeAndRemove(&people, killIndex: killIndex)
        }
        println()
        return people
    }
}

println("Josephus is number: \(Josephus.execute(numberOfPeople: 41, spacing: 3))")
println()
println("Survivors: \(Josephus.execucteAllButM(numberOfPeople: 41, spacing: 3, save: 3))")

- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).
- Calculate the position of any prisoner in the killing sequence.
- Provide an option to save a certain number of prisoners (m).
- The numbering of prisoners can start from either 0 or 1.
- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.


The Builtin Way[edit]
print(String(repeating:"*", count: 5))

The code repeats a given string or character a specified number of times. It uses the String.extend() method for faster evaluation and includes an optimized version that uses bit operations and iterative doubling for efficient repetition of larger strings. The efficiency of repeating a single character and a string of one character is almost the same.


RegularExpressionSearch[edit]

import Foundation

let str = "I am a string"
if let range = str.rangeOfString("string$", options: .RegularExpressionSearch) {
  println("Ends with 'string'")
}

import Foundation

let orig = "I am the original string"
let result = orig.stringByReplacingOccurrencesOfString("original", withString: "modified", options: .RegularExpressionSearch)
println(result)
NSRegularExpression[edit]

import Foundation

if let regex = NSRegularExpression(pattern: "string$", options: nil, error: nil) {
  let str = "I am a string"
  if let result = regex.firstMatchInString(str, options: nil, range: NSRange(location: 0, length: count(str.utf16))) {
    println("Ends with 'string'")
  }
}

  for x in regex.matchesInString(str, options: nil, range: NSRange(location: 0, length: count(str.utf16))) {
    let match = x as! NSTextCheckingResult
    // match.range gives the range of the whole match
    // match.rangeAtIndex(i) gives the range of the i'th capture group (starting from 1)
  }

import Foundation

let orig = "I am the original string"
if let regex = NSRegularExpression(pattern: "original", options: nil, error: nil) {
let result = regex.stringByReplacingMatchesInString(orig, options: nil, range: NSRange(location: 0, length: count(orig.utf16)), withTemplate: "modified")
  println(result)
}

- Matches a string with a regular expression
- Loops through matches
- Substitutes a part of the string using a regular expression
- Tests the substitution functionality
- Tests the undocumented substitution functionality.


let a = 6
let b = 4

print("sum =\(a+b)")
print("difference = \(a-b)")
print("product = \(a*b)")
print("Integer quotient = \(a/b)")
print("Remainder = (a%b)")
print("No operator for Exponential")

take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.


import Foundation

func countSubstring(str: String, substring: String) -> Int {
  return str.components(separatedBy: substring).count - 1
}

print(countSubstring(str: "the three truths", substring: "th"))
print(countSubstring(str: "ababababab", substring: "abab"))

The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.


Translation of: JavaScript
func hanoi(n:Int, a:String, b:String, c:String) {
    if (n > 0) {
        hanoi(n - 1, a, c, b)
        println("Move disk from \(a) to \(c)")
        hanoi(n - 1, b, a, c)
    }
}

hanoi(4, "A", "B", "C")

func hanoi(n:Int, a:String, b:String, c:String) {
  if (n > 0) {
    hanoi(n - 1, a: a, b: c, c: b)
    print("Move disk from \(a) to \(c)")
    hanoi(n - 1, a: b, b: a, c: c)
  }
}

hanoi(4, a:"A", b:"B", c:"C")

Implement a recursive solution to the Towers of Hanoi problem in Swift 2.1.


func factorial<T: BinaryInteger>(_ n: T) -> T {
  guard n != 0 else {
    return 1
  }

  return stride(from: n, to: 0, by: -1).reduce(1, *)
}

func binomial<T: BinaryInteger>(_ x: (n: T, k: T)) -> T {
  let nFac = factorial(x.n)
  let kFac = factorial(x.k)

  return nFac / (factorial(x.n - x.k) * kFac)
}

print("binomial(\(5), \(3)) = \(binomial((5, 3)))")
print("binomial(\(20), \(11)) = \(binomial((20, 11)))")

The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.


Works with: Swift version 2.1
func shellsort<T where T : Comparable>(inout seq: [T]) {
    var inc = seq.count / 2
    while inc > 0 {
        for (var i, el) in EnumerateSequence(seq) {
            while i >= inc && seq[i - inc] > el {
                seq[i] = seq[i - inc]
                i -= inc
            }
            seq[i] = el
        }
        if inc == 2 {
            inc = 1
        } else {
            inc = inc * 5 / 11
        }
    }
}

Input:
var data = [22, 7, 2, -5, 8, 4]

implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


Works with: Swift version 3.x+
var val = 0
repeat {
  val += 1
  print(val)
} while val % 6 != 0
Works with: Swift version 2.x
var val = 0
repeat {
  val++
  print(val)
} while val % 6 != 0
Works with: Swift version 1.x
var val = 0
do {
   val++
   println(val)
} while val % 6 != 0

The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.


Grapheme Length[edit]

Works with: Swift version 2.x
let numberOfCharacters = "møøse".characters.count  // 5
Works with: Swift version 1.2
let numberOfCharacters = count("møøse")            // 5
Works with: Swift version 1.0-1.1
let numberOfCharacters = countElements("møøse")    // 5
Character Length[edit]

Works with: Swift version 2.x
let numberOfCodePoints = "møøse".unicodeScalars.count           // 5
Works with: Swift version 1.2
let numberOfCodePoints = count("møøse".unicodeScalars)          // 5
Works with: Swift version 1.0-1.1
let numberOfCodePoints = countElements("møøse".unicodeScalars)  // 5
Byte Length[edit]

Works with: Swift version 2.x
let numberOfBytesUTF8 = "møøse".utf8.count           // 7
Works with: Swift version 1.2
let numberOfBytesUTF8 = count("møøse".utf8)          // 7
Works with: Swift version 1.0-1.1
let numberOfBytesUTF8 = countElements("møøse".utf8)  // 7

Works with: Swift version 2.x
let numberOfBytesUTF16 = "møøse".utf16.count * 2           // 10
Works with: Swift version 1.2
let numberOfBytesUTF16 = count("møøse".utf16) * 2          // 10
Works with: Swift version 1.0-1.1
let numberOfBytesUTF16 = countElements("møøse".utf16) * 2  // 10

determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. It handles Unicode code points, grapheme clusters and non-BMP code points correctly. The code also provides the functionality to count the number of UTF-8 and UTF-16 code units.


let txt = "0123456789"
println(dropFirst(txt))
println(dropLast(txt))
println(dropFirst(dropLast(txt)))

demonstrate how to remove the first and last characters from a string in Swift. The program works with any valid Unicode code point and references logical characters, not 8-bit or 16-bit code units. The methods used include generic functions from Swift standard library, slicing by range subscripting, mutating the string, and extending String type to define BASIC-style functions. The functions return the characters they remove.


import Foundation

let globalCenter = NSDistributedNotificationCenter.defaultCenter()
let time = NSDate().timeIntervalSince1970

globalCenter.addObserverForName("OnlyOne", object: nil, queue: NSOperationQueue.mainQueue()) {not in
    if let senderTime = not.userInfo?["time"] as? NSTimeInterval where senderTime != time {
        println("More than one running")
        exit(0)
    } else {
        println("Only one")
    }
}

func send() {
    globalCenter.postNotificationName("OnlyOne", object: nil, userInfo: ["time": time])

    let waitTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * NSEC_PER_SEC))

    dispatch_after(waitTime, dispatch_get_main_queue()) {
        send()
    }
}

send()
CFRunLoopRun()

ensure that only one instance of an application is running at a time. If another instance is detected, a message is displayed and the program exits. The code utilizes NSDistributedNotificationCenter and is compatible with Swift 1.2.


Translation of: Java
import Foundation

typealias SodukuPuzzle = [[Int]]

class Soduku {
    let mBoardSize:Int!
    let mBoxSize:Int!
    var mBoard:SodukuPuzzle!
    var mRowSubset:[[Bool]]!
    var mColSubset:[[Bool]]!
    var mBoxSubset:[[Bool]]!

    init(board:SodukuPuzzle) {
        mBoard = board
        mBoardSize = board.count
        mBoxSize = Int(sqrt(Double(mBoardSize)))
        mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false))
        mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false))
        mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false))
        initSubsets()
    }

    func computeBoxNo(i:Int, _ j:Int) -> Int {
        let boxRow = i / mBoxSize
        let boxCol = j / mBoxSize

        return boxRow * mBoxSize + boxCol
    }

    func initSubsets() {
        for i in 0..<mBoard.count {
            for j in 0..<mBoard.count {
                let value = mBoard[i][j]

                if value != 0 {
                    setSubsetValue(i, j, value, true);
                }
            }
        }
    }

    func isValid(i:Int, _ j:Int, var _ val:Int) -> Bool {
        val--
        let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val]
        return !isPresent
    }

    func printBoard() {
        for i in 0..<mBoardSize {
            if i % mBoxSize == 0 {
                println(" -----------------------")
            }

            for j in 0..<mBoardSize {
                if j % mBoxSize == 0 {
                    print("| ")
                }

                print(mBoard[i][j] != 0 ? String(mBoard[i][j]) : " ")
                print(" ")
            }

            println("|")
        }

        println(" -----------------------")
    }

    func setSubsetValue(i:Int, _ j:Int, _ value:Int, _ present:Bool) {
        mRowSubset[i][value - 1] = present
        mColSubset[j][value - 1] = present
        mBoxSubset[computeBoxNo(i, j)][value - 1] = present
    }

    func solve() {
        solve(0, 0)
    }

    func solve(var i:Int, var _ j:Int) -> Bool {
        if i == mBoardSize {
            i = 0
            j++
            if j == mBoardSize {
                return true
            }
        }

        if mBoard[i][j] != 0 {
            return solve(i + 1, j)
        }

        for value in 1...mBoardSize {
            if isValid(i, j, value) {
                mBoard[i][j] = value
                setSubsetValue(i, j, value, true)

                if solve(i + 1, j) {
                    return true
                }

                setSubsetValue(i, j, value, false)
            }
        }

        mBoard[i][j] = 0
        return false
    }
}

let board = [
    [4, 0, 0, 0, 0, 0, 0, 6, 0],
    [5, 0, 0, 0, 8, 0, 9, 0, 0],
    [3, 0, 0, 0, 0, 1, 0, 0, 0],
    [0, 2, 0, 7, 0, 0, 0, 0, 1],
    [0, 9, 0, 0, 0, 0, 0, 4, 0],
    [8, 0, 0, 0, 0, 3, 0, 5, 0],
    [0, 0, 0, 2, 0, 0, 0, 0, 7],
    [0, 0, 6, 0, 5, 0, 0, 0, 8],
    [0, 1, 0, 0, 0, 0, 0, 0, 6]
]

let puzzle = Soduku(board: board)
puzzle.solve()
puzzle.printBoard()

"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format."


extension BidirectionalCollection where Self: MutableCollection
{
	mutating func shuffleInPlace()
	{
		var index = self.index(before: self.endIndex)
		while index != self.startIndex
		{
			// Note the use of ... below. This makes the current element eligible for being selected
			let randomInt = Int.random(in: 0 ... self.distance(from: startIndex, to: index))
			let randomIndex = self.index(startIndex, offsetBy: randomInt)
			self.swapAt(index, randomIndex)
			index = self.index(before: index)
		}
	}
}

var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a.shuffleInPlace()
print(a)

Implement the Knuth shuffle algorithm, also known as the Fisher-Yates shuffle, which randomly shuffles the elements of an array. The algorithm works by iterating from the last element of the array down to the first, each time selecting a random element from the untraversed part of the array and swapping it with the current element. The algorithm modifies the input array in-place, but can be adjusted to return a new array if necessary. The code is designed to work with any mutable bidirectional collection in Swift 5.x and above, and can be further generalized to work with any mutable collection with a random-access index type.


import Foundation

func lastFridays(of year: Int) -> [Date] {

	let calendar = Calendar.current
	var dates = [Date]()

	for month in 2...13 {

		let lastDayOfMonth = DateComponents(calendar: calendar,
		                                    year: year,
		                                    month: month,
		                                    day: 0,
		                                    hour: 12)

		let date = calendar.date(from: lastDayOfMonth)!

		let isFriday = calendar.component(.weekday, from: date) == 6

		if isFriday {

			dates.append(calendar.date(from: lastDayOfMonth)!)

		} else {

			let lastWeekofMonth = calendar.ordinality(of: .weekOfMonth,
			                                          in: .month,
			                                          for: date)!

			let lastWithFriday = lastWeekofMonth - (calendar.component(.weekday, from: date) > 6 ? 0 : 1)

			let lastFridayOfMonth = DateComponents(calendar: calendar,
			                                       year: year,
			                                       month: month - 1,
			                                       hour: 12,
			                                       weekday: 6,
			                                       weekOfMonth: lastWithFriday)

			dates.append(calendar.date(from: lastFridayOfMonth)!)
		}
	}
	return dates
}

var dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short

print(lastFridays(of: 2013).map(dateFormatter.string).joined(separator: "\n"))

1/27/12
2/24/12
3/30/12
4/27/12
5/25/12
6/29/12
7/27/12
8/31/12
9/28/12
10/26/12
11/30/12
12/28/12

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


Works with: Swift version 2.x+
print("Goodbye, World!", terminator: "")
Works with: Swift version 1.x
print("Goodbye, World!")

"Display the string 'Goodbye, World!' without appending a newline at the end."


func usage(_ e:String) {
  print("error: \(e)")
  print("./caeser -e 19 a-secret-string")
  print("./caeser -d 19 tskxvjxlskljafz")
}

func charIsValid(_ c:Character) -> Bool {
  return c.isASCII && ( c.isLowercase || 45 == c.asciiValue ) // '-' = 45
}

func charRotate(_ c:Character, _ by:Int) -> Character {
  var cv:UInt8! = c.asciiValue
  if 45 == cv { cv = 96 }  // if '-', set it to 'a'-1
  cv += UInt8(by)
  if 122 < cv { cv -= 27 } // if larget than 'z', reduce by 27
  if 96 == cv { cv = 45 }  // restore '-'
  return Character(UnicodeScalar(cv))
}

func caesar(_ enc:Bool, _ key:Int, _ word:String) -> String {
  let r = enc ? key : 27 - key
  func charRotateWithKey(_ c:Character) -> Character {
    return charRotate(c,r)
  }
  return String(word.map(charRotateWithKey))
}

func main() {
  var encrypt = true

  if 4 != CommandLine.arguments.count {
    return usage("caesar expects exactly three arguments")
  }

  switch ( CommandLine.arguments[1] ) {
  case "-e":
    encrypt = true
  case "-d":
    encrypt = false
  default:
    return usage("first argument must be -e (encrypt) or -d (decrypt)")
  }

  guard let key = Int(CommandLine.arguments[2]) else {
    return usage("second argument not a number (must be in range 0-26)")
  }

  if key < 0 || 26 < key {
    return usage("second argument not in range 0-26")
  }

  if !CommandLine.arguments[3].allSatisfy(charIsValid) {
    return usage("third argument must only be lowercase ascii characters, or -")
  }

  let ans = caesar(encrypt,key,CommandLine.arguments[3])
  print("\(ans)")
}

func test() {
  if ( Character("a") != charRotate(Character("a"),0) ) {
    print("Test Fail 1")
  }
  if ( Character("-") != charRotate(Character("-"),0) ) {
    print("Test Fail 2")
  }
  if ( Character("-") != charRotate(Character("z"),1) ) {
    print("Test Fail 3")
  }
  if ( Character("z") != charRotate(Character("-"),26)) {
    print("Test Fail 4")
  }
  if ( "ihgmkzma" != caesar(true,8,"a-zecret") ) {
    print("Test Fail 5")
  }
  if ( "a-zecret" != caesar(false,8,"ihgmkzma") ) {
    print("Test Fail 6")
  }
}

test()
main()

implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigenère cipher with a key length of 1 and to Rot-13 with a key of 13.


func lcm(a:Int, b:Int) -> Int {
    return abs(a * b) / gcd_rec(a, b)
}

The code calculates the least common multiple (LCM) of two integers, m and n. It identifies the smallest positive integer that is a factor of both m and n. If either m or n is zero, the LCM is zero. The code can calculate the LCM by iterating all multiples of m until it finds one that is also a multiple of n, or by using the formula lcm(m, n) = |m x n|/gcd(m, n), where gcd is the greatest common divisor. Additionally, the code can find the LCM by merging the prime decompositions of both m and n. This code uses the Swift GCD function.


struct CUSIP {
  var value: String

  private static let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

  init?(value: String) {
    if value.count == 9 && String(value.last!) == CUSIP.checkDigit(cusipString: String(value.dropLast())) {
      self.value = value
    } else if value.count == 8, let checkDigit = CUSIP.checkDigit(cusipString: value) {
      self.value = value + checkDigit
    } else {
      return nil
    }
  }

  static func checkDigit(cusipString: String) -> String? {
    guard cusipString.count == 8, cusipString.allSatisfy({ $0.isASCII }) else {
      return nil
    }

    let sum = cusipString.uppercased().enumerated().reduce(0, {sum, pair in
      let (i, char) = pair
      var v: Int

      switch char {
      case "*":
        v = 36
      case "@":
        v = 37
      case "#":
        v = 38
      case _ where char.isNumber:
        v = char.wholeNumberValue!
      case _:
        v = Int(char.asciiValue! - 65) + 10
      }

      if i & 1 == 1 {
        v *= 2
      }

      return sum + (v / 10) + (v % 10)
    })

    return String((10 - (sum % 10)) % 10)
  }
}

let testCases = [
  "037833100",
  "17275R102",
  "38259P508",
  "594918104",
  "68389X106",
  "68389X105"
]

for potentialCUSIP in testCases {
  print("\(potentialCUSIP) -> ", terminator: "")

  switch CUSIP(value: potentialCUSIP) {
  case nil:
    print("Invalid")
  case _:
    print("Valid")
  }
}

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


for i in [1,2,3] {
   print(i)
}

Works with: Swift version 2.x+
[1,2,3].forEach {
   print($0)
}

Iterates through and prints each element in a collection in order using a "for each" loop or an alternative loop if "for each" is not available. The code is applicable to any type that conforms to the SequenceType protocol, including arrays, collections, generators, and ranges.


Works with: Swift version 3.x
let text = "Hello,How,Are,You,Today"
let tokens = text.components(separatedBy: ",") // for single or multi-character separator
print(tokens)
let result = tokens.joined(separator: ".")
print(result)
Works with: Swift version 2.x
let text = "Hello,How,Are,You,Today"
let tokens = text.characters.split(",").map{String($0)} // for single-character separator
print(tokens)
let result = tokens.joinWithSeparator(".")
print(result)
Works with: Swift version 1.x
let text = "Hello,How,Are,You,Today"
let tokens = split(text, { $0 == "," }) // for single-character separator
println(tokens)
let result = ".".join(tokens)
println(result)
For multi-character separators:import Foundation

let text = "Hello,How,Are,You,Today"
let tokens = text.componentsSeparatedByString(",")
print(tokens)

"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period."


// Iterative

func gcd(a: Int, b: Int) -> Int {

    var a = abs(a)
    var b = abs(b)

    if (b > a) { swap(&a, &b) }

    while (b > 0) { (a, b) = (b, a % b) }

    return a
}

// Recursive

func gcdr (a: Int, b: Int) -> Int {

    var a = abs(a)
    var b = abs(b)

    if (b > a) { swap(&a, &b) }

    return gcd_rec(a,b)
}

private func gcd_rec(a: Int, b: Int) -> Int {

    return b == 0 ? a : gcd_rec(b, a % b)
}

for (a,b) in [(1,1), (100, -10), (10, -100), (-36, -17), (27, 18), (30, -42)] {

    println("Iterative: GCD of \(a) and \(b) is \(gcd(a, b))")
    println("Recursive: GCD of \(a) and \(b) is \(gcdr(a, b))")
}

calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.


Works with: Swift version 2.x+
func isNumeric(a: String) -> Bool {
  return Double(a) != nil
}
Works with: Swift version 1.x

func isNumeric(a: String) -> Bool {
  return a.toInt() != nil
}

"Create a function that checks if a given string can be interpreted as a numeric value, including floating point and negative numbers."


import Foundation

// With https
let request = NSURLRequest(URL: NSURL(string: "https://sourceforge.net")!)

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in // callback

    // data is binary
    if (data != nil) {
        let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
        println(string)
    }
}

CFRunLoopRun() // dispatch

Send a GET request to the URL "https://www.w3.org/", validate the host certificate, and print the obtained resource to the console without any authentication.


Translation of: Rust
struct Point {
  var x: Double
  var y: Double
}

struct Polygon {
  var points: [Point]

  init(points: [Point]) {
    self.points = points
  }

  init(points: [(Double, Double)]) {
    self.init(points: points.map({ Point(x: $0.0, y: $0.1) }))
  }
}

func isInside(_ p1: Point, _ p2: Point, _ p3: Point) -> Bool {
  (p3.x - p2.x) * (p1.y - p2.y) > (p3.y - p2.y) * (p1.x - p2.x)
}

func computeIntersection(_ p1: Point, _ p2: Point, _ s: Point, _ e: Point) -> Point {
  let dc = Point(x: p1.x - p2.x, y: p1.y - p2.y)
  let dp = Point(x: s.x - e.x, y: s.y - e.y)
  let n1 = p1.x * p2.y - p1.y * p2.x
  let n2 = s.x * e.y - s.y * e.x
  let n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x)

  return Point(x: (n1 * dp.x - n2 * dc.x) * n3, y: (n1 * dp.y - n2 * dc.y) * n3)
}

func sutherlandHodgmanClip(subjPoly: Polygon, clipPoly: Polygon) -> Polygon {
  var ring = subjPoly.points
  var p1 = clipPoly.points.last!

  for p2 in clipPoly.points {
    let input = ring
    var s = input.last!

    ring = []

    for e in input {
      if isInside(e, p1, p2) {
        if !isInside(s, p1, p2) {
          ring.append(computeIntersection(p1, p2, s, e))
        }

        ring.append(e)
      } else if isInside(s, p1, p2) {
        ring.append(computeIntersection(p1, p2, s, e))
      }

      s = e
    }

    p1 = p2
  }

  return Polygon(points: ring)
}

let subj = Polygon(points: [
  (50.0, 150.0),
  (200.0, 50.0),
  (350.0, 150.0),
  (350.0, 300.0),
  (250.0, 300.0),
  (200.0, 250.0),
  (150.0, 350.0),
  (100.0, 250.0),
  (100.0, 200.0)
])

let clip = Polygon(points: [
  (100.0, 100.0),
  (300.0, 100.0),
  (300.0, 300.0),
  (100.0, 300.0)
])

print(sutherlandHodgmanClip(subjPoly: subj, clipPoly: clip))

implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.


Translation of: Python
public struct KnapsackItem: Hashable {
  public var name: String
  public var weight: Int
  public var value: Int

  public init(name: String, weight: Int, value: Int) {
    self.name = name
    self.weight = weight
    self.value = value
  }
}

public func knapsack(items: [KnapsackItem], limit: Int) -> [KnapsackItem] {
  var table = Array(repeating: Array(repeating: 0, count: limit + 1), count: items.count + 1)

  for j in 1...items.count {
    let item = items[j-1]

    for w in 1...limit {
      if item.weight > w {
        table[j][w] = table[j-1][w]
      } else {
        table[j][w] = max(table[j-1][w], table[j-1][w-item.weight] + item.value)
      }
    }
  }

  var result = [KnapsackItem]()
  var w = limit

  for j in stride(from: items.count, to: 0, by: -1) where table[j][w] != table[j-1][w] {
    let item = items[j-1]

    result.append(item)

    w -= item.weight
  }

  return result
}

typealias GroupedItem = (name: String, weight: Int, val: Int, n: Int)

let groupedItems: [GroupedItem] = [
  ("map", 9, 150, 1),
  ("compass", 13, 35, 1),
  ("water", 153, 200, 3),
  ("sandwich", 50, 60, 2),
  ("glucose", 15, 60, 2),
  ("tin", 68, 45, 3),
  ("banana", 27, 60, 3),
  ("apple", 39, 40, 3),
  ("cheese", 23, 30, 1),
  ("beer", 52, 10, 3),
  ("suntan cream", 11, 70, 1),
  ("camera", 32, 30, 1),
  ("t-shirt", 24, 15, 2),
  ("trousers", 48, 10, 2),
  ("umbrella", 73, 40, 1),
  ("waterproof trousers", 42, 70, 1),
  ("waterproof overclothes", 43, 75, 1),
  ("note-case", 22, 80, 1),
  ("sunglasses", 7, 20, 1),
  ("towel", 18, 12, 2),
  ("socks", 4, 50, 1),
  ("book", 30, 10, 2)
]

let items = groupedItems.flatMap({item in
  (0..<item.n).map({_ in KnapsackItem(name: item.name, weight: item.weight, value: item.val) })
})

let bagged = knapsack(items: items, limit: 400)
let (totalVal, totalWeight) = bagged.reduce((0, 0), {cur, item in (cur.0 + item.value, cur.1 + item.weight) })

print("Bagged the following \(bagged.count) items:")

for item in bagged {
  print("\t\(item.name)")
}

print("For a total value of \(totalVal) and weight of \(totalWeight)")

The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. It selects items based on their importance value and weight, ensuring the total weight does not exceed the limit and the total value is maximized. The code considers the quantity available of each item and only allows whole units to be selected.


Translation of: C
import Foundation

let startTime = NSDate()
var signalReceived: sig_atomic_t = 0

signal(SIGINT) { signal in signalReceived = 1 }

for var i = 0;; {
    if signalReceived == 1 { break }
    usleep(500_000)
    if signalReceived == 1 { break }
    print(++i)
}

let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")

an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.


Works with: Swift version 2.x+
let s = "1234"
if let x = Int(s) {
  print("\(x + 1)")
}
Works with: Swift version 1.x
let s = "1234"
if let x = s.toInt() {
  println("\(x + 1)")
}


import Foundation

func getPrefix(_ text:[String]) -> String? {
    var common:String = text[0]
    for i in text {
        common = i.commonPrefix(with: common)
    }
    return common
}

var test = ["/home/user1/tmp/coverage/test",
 "/home/user1/tmp/covert/operator",
 "/home/user1/tmp/coven/members"]

var output:String = getPrefix(test)!
print(output)

The code creates a function that identifies and returns the common directory path from a given set of directory paths, using a specified directory separator. It is tested using the forward slash as the directory separator and three specific string paths as input. The function ensures the returned path is a valid directory, not just the longest common string. It's designed to work specifically in Swift on Linux.


extension Array {
  public mutating func satalloShuffle() {
    for i in stride(from: index(before: endIndex), through: 1, by: -1) {
      swapAt(i, .random(in: 0..<i))
    }
  }

  public func satalloShuffled() -> [Element] {
    var arr = Array(self)

    arr.satalloShuffle()

    return arr
  }
}

let testCases = [
  [],
  [10, 20],
  [10, 20, 30],
  [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
]

for testCase in testCases {
  let shuffled = testCase.satalloShuffled()

  guard zip(testCase, shuffled).allSatisfy(!=) else {
    fatalError("satallo shuffle failed")
  }

  print("\(testCase) shuffled = \(shuffled)")
}

implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.


using a switch statement[edit]
for i in 1...100 {
    switch (i % 3, i % 5) {
    case (0, 0):
        print("FizzBuzz")
    case (0, _):
        print("Fizz")
    case (_, 0):
        print("Buzz")
    default:
        print(i)
    }
}
using two if statements and an Optional[edit]
for i in 1...100{
    var s:String?
    if i%3==0{s="Fizz"}
    if i%5==0{s=(s ?? "")+"Buzz"}
    print(s ?? i)
}
using a precomputed cycle[edit]
import Foundation

let formats: [String] = [
  "%d",
  "%d",
  "fizz",
  "%d",
  "buzz",
  "fizz",
  "%d",
  "%d",
  "fizz",
  "buzz",
  "%d",
  "fizz",
  "%d",
  "%d",
  "fizzbuzz",
]

var count = 0
var index = 0
while count < 100 {
  count += 1
  print(String(format: formats[index], count))
  index += 1
  index %= 15
}

print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.


import Foundation
import Numerics
import QDBMP

public typealias Color = (red: UInt8, green: UInt8, blue: UInt8)

public class BitmapDrawer {
  public let imageHeight: Int
  public let imageWidth: Int

  var grid: [[Color?]]

  private let bmp: OpaquePointer

  public init(height: Int, width: Int) {
    self.imageHeight = height
    self.imageWidth = width
    self.grid = [[Color?]](repeating: [Color?](repeating: nil, count: height), count: width)
    self.bmp = BMP_Create(UInt(width), UInt(height), 24)

    checkError()
  }

  deinit {
    BMP_Free(bmp)
  }

  private func checkError() {
    let err = BMP_GetError()

    guard err == BMP_STATUS(0) else {
      fatalError("\(err)")
    }
  }

  public func save(to path: String = "~/Desktop/out.bmp") {
    for x in 0..<imageWidth {
      for y in 0..<imageHeight {
        guard let color = grid[x][y] else { continue }

        BMP_SetPixelRGB(bmp, UInt(x), UInt(y), color.red, color.green, color.blue)
        checkError()
      }
    }

    (path as NSString).expandingTildeInPath.withCString {s in
      BMP_WriteFile(bmp, s)
    }
  }

  public func setPixel(x: Int, y: Int, to color: Color?) {
    grid[x][y] = color
  }
}

let imageSize = 10_000
let canvas = BitmapDrawer(height: imageSize, width: imageSize)
let maxIterations = 256
let cxMin = -2.0
let cxMax = 1.0
let cyMin = -1.5
let cyMax = 1.5
let scaleX = (cxMax - cxMin) / Double(imageSize)
let scaleY = (cyMax - cyMin) / Double(imageSize)

for x in 0..<imageSize {
  for y in 0..<imageSize {
    let cx = cxMin + Double(x) * scaleX
    let cy = cyMin + Double(y) * scaleY

    let c = Complex(cx, cy)
    var z = Complex(0.0, 0.0)
    var i = 0

    for t in 0..<maxIterations {
      if z.magnitude > 2 {
        break
      }

      z = z * z + c
      i = t
    }

    canvas.setPixel(x: x, y: y, to: Color(red: UInt8(i), green: UInt8(i), blue: UInt8(i)))
  }
}

canvas.save()

generate and draw the Mandelbrot set using various algorithms and functions, utilizing the Swift Numerics package and the Quick 'N Dirty BMP C library imported in Swift.


let a = [1, 2, 3, 4, 5]
println(a.reduce(0, +)) // prints 15
println(a.reduce(1, *)) // prints 120

println(reduce(a, 0, +)) // prints 15
println(reduce(a, 1, *)) // prints 120

Calculate the sum and product of all integers in an array.


func isLeapYear(year: Int) -> Bool {
    return year.isMultiple(of: 100) ? year.isMultiple(of: 400) : year.isMultiple(of: 4)
}

[1900, 1994, 1996, 1997, 2000].forEach { year in
    print("\(year): \(isLeapYear(year: year) ? "YES" : "NO")")
}

"Determines if a specified year is a leap year in the Gregorian calendar."


    import Foundation
    public class MD5 {
        /** specifies the per-round shift amounts */
        private let s: [UInt32] = [7, 12, 17, 22,  7, 12, 17, 22,  7, 12, 17, 22,  7, 12, 17, 22,
                           5,  9, 14, 20,  5,  9, 14, 20,  5,  9, 14, 20,  5,  9, 14, 20,
                           4, 11, 16, 23,  4, 11, 16, 23,  4, 11, 16, 23,  4, 11, 16, 23,
                           6, 10, 15, 21,  6, 10, 15, 21,  6, 10, 15, 21,  6, 10, 15, 21]

        /** binary integer part of the sines of integers (Radians) */
        private let K: [UInt32] = (0 ..< 64).map { UInt32(0x100000000 * abs(sin(Double($0 + 1)))) }

        let a0: UInt32 = 0x67452301
        let b0: UInt32 = 0xefcdab89
        let c0: UInt32 = 0x98badcfe
        let d0: UInt32 = 0x10325476

        private var message: NSData

        //MARK: Public

        public init(_ message: NSData) {
            self.message = message
        }

        public func calculate() -> NSData? {
            var tmpMessage: NSMutableData = NSMutableData(data: message)
            let wordSize = sizeof(UInt32)

            var aa = a0
            var bb = b0
            var cc = c0
            var dd = d0

            // Step 1. Append Padding Bits
            tmpMessage.appendBytes([0x80]) // append one bit (Byte with one bit) to message

            // append "0" bit until message length in bits ≡ 448 (mod 512)
            while tmpMessage.length % 64 != 56 {
                tmpMessage.appendBytes([0x00])
            }

            // Step 2. Append Length a 64-bit representation of lengthInBits
            var lengthInBits = (message.length * 8)
            var lengthBytes = lengthInBits.bytes(64 / 8)
            tmpMessage.appendBytes(reverse(lengthBytes));

            // Process the message in successive 512-bit chunks:
            let chunkSizeBytes = 512 / 8
            var leftMessageBytes = tmpMessage.length
            for var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes {
                let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))

                // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
                // println("wordSize \(wordSize)");
                var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0)
                for x in 0..<M.count {
                    var range = NSRange(location:x * wordSize, length: wordSize)
                    chunk.getBytes(&M[x], range:range);
                }

                // Initialize hash value for this chunk:
                var A:UInt32 = a0
                var B:UInt32 = b0
                var C:UInt32 = c0
                var D:UInt32 = d0

                var dTemp:UInt32 = 0

                // Main loop
                for j in 0...63 {
                    var g = 0
                    var F:UInt32 = 0

                    switch (j) {
                    case 0...15:
                        F = (B & C) | ((~B) & D)
                        g = j
                        break
                    case 16...31:
                        F = (D & B) | (~D & C)
                        g = (5 * j + 1) % 16
                        break
                    case 32...47:
                        F = B ^ C ^ D
                        g = (3 * j + 5) % 16
                        break
                    case 48...63:
                        F = C ^ (B | (~D))
                        g = (7 * j) % 16
                        break
                    default:
                        break
                    }
                    dTemp = D
                    D = C
                    C = B
                    B = B &+ rotateLeft((A &+ F &+ K[j] &+ M[g]), s[j])
                    A = dTemp
                }

                aa = aa &+ A
                bb = bb &+ B
                cc = cc &+ C
                dd = dd &+ D
            }

            var buf: NSMutableData = NSMutableData();
            buf.appendBytes(&aa, length: wordSize)
            buf.appendBytes(&bb, length: wordSize)
            buf.appendBytes(&cc, length: wordSize)
            buf.appendBytes(&dd, length: wordSize)

            return buf.copy() as? NSData;
        }

        //MARK: Class
        class func calculate(message: NSData) -> NSData?
        {
            return MD5(message).calculate();
        }

        //MARK: Private
        private func rotateLeft(x:UInt32, _ n:UInt32) -> UInt32 {
            return (x &<< n) | (x &>> (32 - n))
        }
    }

import Foundation

let shift : [UInt32] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]
let table: [UInt32] = (0 ..< 64).map { UInt32(0x100000000 * abs(sin(Double($0 + 1)))) }

func md5(var message: [UInt8]) -> [UInt8] {
  var messageLenBits = UInt64(message.count) * 8
  message.append(0x80)
  while message.count % 64 != 56 {
    message.append(0)
  }

  var lengthBytes = [UInt8](count: 8, repeatedValue: 0)
  UnsafeMutablePointer<UInt64>(lengthBytes).memory = messageLenBits.littleEndian
  message += lengthBytes

  var a : UInt32 = 0x67452301
  var b : UInt32 = 0xEFCDAB89
  var c : UInt32 = 0x98BADCFE
  var d : UInt32 = 0x10325476
  for chunkOffset in stride(from: 0, to: message.count, by: 64) {
    let chunk = UnsafePointer<UInt32>(UnsafePointer<UInt8>(message) + chunkOffset)
    let originalA = a
    let originalB = b
    let originalC = c
    let originalD = d
    for j in 0 ..< 64 {
      var f : UInt32 = 0
      var bufferIndex = j
      let round = j >> 4
      switch round {
      case 0:
        f = (b & c) | (~b & d)
      case 1:
        f = (b & d) | (c & ~d)
        bufferIndex = (bufferIndex*5 + 1) & 0x0F
      case 2:
        f = b ^ c ^ d
        bufferIndex = (bufferIndex*3 + 5) & 0x0F
      case 3:
        f = c ^ (b | ~d)
        bufferIndex = (bufferIndex * 7) & 0x0F
      default:
        assert(false)
      }
      let sa = shift[(round<<2)|(j&3)]
      let tmp = a &+ f &+ UInt32(littleEndian: chunk[bufferIndex]) &+ table[j]
      a = d
      d = c
      c = b
      b = b &+ (tmp << sa | tmp >> (32-sa))
    }
    a = a &+ originalA
    b = b &+ originalB
    c = c &+ originalC
    d = d &+ originalD
  }

  var result = [UInt8](count: 16, repeatedValue: 0)
  for (i, n) in enumerate([a, b, c, d]) {
    UnsafeMutablePointer<UInt32>(result)[i] = n.littleEndian
  }
  return result
}

func toHexString(bytes: [UInt8]) -> String {
  return "".join(bytes.map { String(format:"%02x", $0) })
}

for (hashCode, string) in [
  ("d41d8cd98f00b204e9800998ecf8427e", ""),
  ("0cc175b9c0f1b6a831c399e269772661", "a"),
  ("900150983cd24fb0d6963f7d28e17f72", "abc"),
  ("f96b697d7cb7938d525a2f31aaf161d0", "message digest"),
  ("c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"),
  ("d174ab98d277d9f5a5611c2c9f419d9f",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"),
  ("57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
    "123456789012345678901234567890123456789012345678901234567890")] {
      println(hashCode)
      println(toHexString(md5(Array(string.utf8))))
      println()
}

The code is a direct implementation of the MD5 Message Digest Algorithm, which generates a correct message digest for an input string without using any built-in or external hashing libraries. The implementation does not mimic all calling modes, but focuses on key functionality. It also includes notes on challenges, implementation choices, and limitations. The code provides practical examples of bit manipulation, working with little-endian data, and handling boundary conditions. It also includes verification strings and hashes from RFC 1321 for validation. The implementation is based on the pseudo-code from the Wikipedia article and does not rely on any external libraries.


let res = [2, 4, 6].map({x in
  return (1...7)
      .filter({ $0 != x })
      .map({y -> (Int, Int, Int)? in
        let z = 12 - (x + y)

        guard y != z && 1 <= z && z <= 7 else {
          return nil
        }

        return (x, y, z)
      }).compactMap({ $0 })
}).flatMap({ $0 })

for result in res {
  print(result)
}

var res = [(Int, Int, Int)]()

for x in [2, 4, 6] {
  for y in 1...7 where x != y {
    let z = 12 - (x + y)

    guard y != z && 1 <= z && z <= 7 else {
      continue
    }

    res.append((x, y, z))
  }
}

for result in res {
  print(result)
}

The code generates all valid combinations of numbers between 1 and 7 (inclusive) for the police, sanitation, and fire departments in a city. The numbers for each department are unique and add up to 12. The police department number is always even.


demonstrate how to copy a string in Swift by assigning its value, highlighting the difference between copying the string's content and creating an additional reference to the existing string.


func F(n: Int) -> Int {
  return n == 0 ? 1 : n - M(F(n-1))
}

func M(n: Int) -> Int {
  return n == 0 ? 0 : n - F(M(n-1))
}

for i in 0..20 {
  print("\(F(i)) ")
}
println()
for i in 0..20 {
  print("\(M(i)) ")
}
println()

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions use each other to calculate the sequence values based on the given formulas. If the programming language does not support mutual recursion, this is stated explicitly. No special pre-declaration is required for the functions.


import Darwin

let myList = [1, 2, 4, 5, 62, 234, 1, -1]
print(myList[Int(arc4random_uniform(UInt32(myList.count)))])

demonstrate how to select a random element from a list.


import Foundation

let encoded = "http%3A%2F%2Ffoo%20bar%2F"
if let normal = encoded.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
  println(normal)
}

provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


func binarySearch<T: Comparable>(xs: [T], x: T) -> Int? {
  var recurse: ((Int, Int) -> Int?)!
  recurse = {(low, high) in switch (low + high) / 2 {
    case _ where high < low: return nil
    case let mid where xs[mid] > x: return recurse(low, mid - 1)
    case let mid where xs[mid] < x: return recurse(mid + 1, high)
    case let mid: return mid
  }}
  return recurse(0, xs.count - 1)
}

func binarySearch<T: Comparable>(xs: [T], x: T) -> Int? {
  var (low, high) = (0, xs.count - 1)
  while low <= high {
    switch (low + high) / 2 {
      case let mid where xs[mid] > x: high = mid - 1
      case let mid where xs[mid] < x: low = mid + 1
      case let mid: return mid
    }
  }
  return nil
}

func testBinarySearch(n: Int) {
  let odds = Array(stride(from: 1, through: n, by: 2))
  let result = flatMap(0...n) {binarySearch(odds, $0)}
  assert(result == Array(0..<odds.count))
  println("\(odds) are odd natural numbers")
  for it in result {
    println("\(it) is ordinal of \(odds[it])")
  }
}

testBinarySearch(12)

func flatMap<T, U>(source: [T], transform: (T) -> U?) -> [U] {
  return source.reduce([]) {(var xs, x) in if let x = transform(x) {xs.append(x)}; return xs}
}

[1, 3, 5, 7, 9, 11] are odd natural numbers
0 is ordinal of 1
1 is ordinal of 3
2 is ordinal of 5
3 is ordinal of 7
4 is ordinal of 9
5 is ordinal of 11

The code implements a binary search algorithm to find a specific number in a sorted integer array. It takes the starting and ending points of a range, and a secret value as inputs. The search can be performed both recursively and iteratively. The code also handles multiple values equal to the given value and returns the index of the found element. If the element is not found, it returns the insertion point. The code also includes variations of the algorithm that return the leftmost and rightmost insertion points. It also ensures there are no overflow bugs when calculating the midpoint of the range.


let args = Process.arguments
println("This program is named \(args[0]).")
println("There are \(args.count-1) arguments.")
for i in 1..<args.count {
  println("the argument #\(i) is \(args[i])")
}

Works with: Swift version 1.2+
println("This program is named \(String.fromCString(Process.unsafeArgv[0])!).")
println("There are \(Process.argc-1) arguments.")
for i in 1 ..< Int(Process.argc) {
  println("the argument #\(i) is \(String.fromCString(Process.unsafeArgv[i])!)")
}
Works with: Swift version 1.0-1.1
println("This program is named \(String.fromCString(C_ARGV[0])!).")
println("There are \(C_ARGC-1) arguments.")
for i in 1 ..< Int(C_ARGC) {
  println("the argument #\(i) is \(String.fromCString(C_ARGV[i])!)")
}

"Code retrieves and prints the list of command-line arguments given to the program. It also provides an example of how to use the program with command-line arguments. Additionally, it includes references for understanding program name and parsing command-line arguments intelligently."


import Foundation

let jsonString = "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"
if let jsonData = jsonString.data(using: .utf8) {
	if let jsonObject: Any = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) {
		print("Dictionary: \(jsonObject)")
	}
}

let obj = [
	"foo": [1, "Orange"],
	"bar": 1
] as [String : Any]

if let objData = try? JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted) {
	if let jsonString2 = String(data: objData, encoding: .utf8) {
		print("JSON: \(jsonString2)")
	}
}

"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON."


extension FloatingPoint where Self: ExpressibleByFloatLiteral {
  @inlinable
  public func power(_ e: Int) -> Self {
    var res = Self(1)

    for _ in 0..<e {
      res *= self
    }

    return res
  }

  @inlinable
  public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self {
    var d = Self(0)
    var res = Self(1)

    guard self != 0 else {
      return 0
    }

    guard n >= 1 else {
      return .nan
    }

    repeat {
      d = (self / res.power(n - 1) - res) / Self(n)
      res += d
    } while d >= epsilon * 10 || d <= -epsilon * 10

    return res
  }
}

print(81.root(n: 4))
print(13.root(n: 5))

Implement the principal nth root algorithm for a positive real number A.


"Determines and returns the hostname of the system where the Swift 3 program is running."


struct Leonardo: Sequence, IteratorProtocol {
    private let add : Int
    private var n0: Int
    private var n1: Int

    init(n0: Int = 1, n1: Int = 1, add: Int = 1) {
        self.n0 = n0
        self.n1 = n1
        self.add = add
    }

    mutating func next() -> Int? {
        let n = n0
        n0 = n1
        n1 += n + add
        return n
    }
}

print("First 25 Leonardo numbers:")
print(Leonardo().prefix(25).map{String($0)}.joined(separator: " "))

print("First 25 Fibonacci numbers:")
print(Leonardo(n0: 0, add: 0).prefix(25).map{String($0)}.joined(separator: " "))

generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.


import Darwin
import Foundation

println("24 Game")
println("Generating 4 digits...")

func randomDigits() -> Int[] {
    var result = Int[]();
    for var i = 0; i < 4; i++ {
        result.append(Int(arc4random_uniform(9)+1))
    }
    return result;
}

// Choose 4 digits
let digits = randomDigits()

print("Make 24 using these digits : ")

for digit in digits {
    print("\(digit) ")
}
println()

// get input from operator
var input = NSString(data:NSFileHandle.fileHandleWithStandardInput().availableData, encoding:NSUTF8StringEncoding)

var enteredDigits = Int[]()

var enteredOperations = Character[]()

let inputString = input as String

// store input in the appropriate table
for character in inputString {
    switch character {
        case "1", "2", "3", "4", "5", "6", "7", "8", "9":
            let digit = String(character)
            enteredDigits.append(digit.toInt()!)
        case "+", "-", "*", "/":
            enteredOperations.append(character)
        case "\n":
            println()
        default:
            println("Invalid expression")
    }
}

// check value of expression provided by the operator
var value = Int()

if enteredDigits.count == 4 && enteredOperations.count == 3 {
    value = enteredDigits[0]
    for (i, operation) in enumerate(enteredOperations) {
        switch operation {
            case "+":
                value = value + enteredDigits[i+1]
            case "-":
                value = value - enteredDigits[i+1]
            case "*":
                value = value * enteredDigits[i+1]
            case "/":
                value = value / enteredDigits[i+1]
            default:
                println("This message should never happen!")
        }
    }
}

if value != 24 {
    println("The value of the provided expression is \(value) instead of 24!")
} else {
    println("Congratulations, you found a solution!")
}

"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits."


import Foundation

// "WWWBWW" -> [(3, W), (1, B), (2, W)]
func encode(input: String) -> [(Int, Character)] {
    return input.characters.reduce([(Int, Character)]()) {
        if $0.last?.1 == $1 { var r = $0; r[r.count - 1].0++; return r }
        return $0 + [(1, $1)]
    }
}

// [(3, W), (1, B), (2, W)] -> "WWWBWW"
func decode(encoded: [(Int, Character)]) -> String {
    return encoded.reduce("") { $0 + String(count: $1.0, repeatedValue: $1.1) }
}

let input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
let output = decode(encode(input))
print(output == input)

"Implement a run-length encoding function that compresses a string of uppercase characters by storing the length of repeated characters. Also, provide a function to reverse the compression. The output can be any format that can be used to recreate the original input. An example of this is converting 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' to '12W1B12W3B24W1B14W'. The function also includes the ability to convert the encoded array back into the string using NSScanner."


let s = "hello"
println(s + " literal")
let s1 = s + " literal"
println(s1)

Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


Works with: Swift 2.0
import Foundation

let wordsURL = NSURL(string: "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")!

let wordsstring = try NSString(contentsOfURL:wordsURL , encoding: NSUTF8StringEncoding)
let allwords = wordsstring.componentsSeparatedByString("\n")

let words = allwords//[0..<100] // used to limit the size while testing

extension String {
    var charactersAscending : String {
        return String(Array(characters).sort())
    }
}

var charsToWords = [String:Set<String>]()

var biggest = 0
var biggestlists = [Set<String>]()

for thisword in words {
    let chars = thisword.charactersAscending

    var knownwords = charsToWords[chars] ?? Set<String>()
    knownwords.insert(thisword)
    charsToWords[chars] = knownwords

    if knownwords.count > biggest {
        biggest = knownwords.count

        biggestlists = [knownwords]
    }
    else if knownwords.count == biggest {
        biggestlists.append(knownwords)
    }
}

print("Found \(biggestlists.count) sets of anagrams with \(biggest) members each")
for (i, thislist) in biggestlists.enumerate() {
    print("set \(i): \(thislist.sort())")
}

"Code identifies sets of anagrams with the most words from the provided word list."


Translation of: Ruby
import Foundation
func sierpinski_carpet(n:Int) -> String {
    func middle(str:String) -> String {
        let spacer = str.stringByReplacingOccurrencesOfString("#", withString:" ", options:nil, range:nil)
        return str + spacer + str
    }

    var carpet = ["#"]
    for i in 1...n {
        let a = carpet.map{$0 + $0 + $0}
        let b = carpet.map(middle)
        carpet = a + b + a
    }
    return "\n".join(carpet)
}

println(sierpinski_carpet(3))

generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.


Works with: Swift version 2+
enum HuffmanTree<T> {
  case Leaf(T)
  indirect case Node(HuffmanTree<T>, HuffmanTree<T>)

  func printCodes(prefix: String) {
    switch(self) {
    case let .Leaf(c):
      print("\(c)\t\(prefix)")
    case let .Node(l, r):
      l.printCodes(prefix + "0")
      r.printCodes(prefix + "1")
    }
  }
}

func buildTree<T>(freqs: [(T, Int)]) -> HuffmanTree<T> {
  assert(freqs.count > 0, "must contain at least one character")
  // leaves sorted by increasing frequency
  let leaves : [(Int, HuffmanTree<T>)] = freqs.sort { (p1, p2) in p1.1 < p2.1 }.map { (x, w) in (w, .Leaf(x)) }
  // nodes sorted by increasing frequency
  var nodes = [(Int, HuffmanTree<T>)]()
  // iterate through leaves and nodes in order of increasing frequency
  for var i = 0, j = 0; ; {
    assert(i < leaves.count || j < nodes.count)
    // get subtree of least frequency
    var e1 : (Int, HuffmanTree<T>)
    if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 {
      e1 = leaves[i]
      i++
    } else {
      e1 = nodes[j]
      j++
    }

    // if there's no subtrees left, then that one was the answer
    if i == leaves.count && j == nodes.count {
      return e1.1
    }

    // get next subtree of least frequency
    var e2 : (Int, HuffmanTree<T>)
    if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 {
      e2 = leaves[i]
      i++
    } else {
      e2 = nodes[j]
      j++
    }
    // create node from two subtrees
    nodes.append((e1.0 + e2.0, .Node(e1.1, e2.1)))
  }
}

func getFreqs<S : SequenceType where S.Generator.Element : Hashable>(seq: S) -> [(S.Generator.Element, Int)] {
  var freqs : [S.Generator.Element : Int] = [:]
  for c in seq {
    freqs[c] = (freqs[c] ?? 0) + 1
  }
  return Array(freqs)
}

let str = "this is an example for huffman encoding"
let charFreqs = getFreqs(str.characters)
let tree = buildTree(charFreqs)
print("Symbol\tHuffman code")
tree.printCodes("")

The code generates a Huffman encoding for each character in a given string. It first creates a tree of nodes based on the frequency of each character. It then traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for the character. The code uses two sorted lists, one for leaves and one for nodes, and merges them as it iterates through them.


for i in stride(from: 10, through: 0, by: -1) {
  println(i)
}

for i in lazy(0...10).reverse() {
  println(i)
}

for i in reverse(0 ... 10) {
  println(i)
}

for var i = 10; i >= 0; i-- {
  println(i)
}

for i in (0...10).reversed() {
    print(i)
}

The code executes a downward for loop, counting down from 10 to 0.


public func convertToUnicodeScalars(
  str: String,
  minChar: UInt32,
  maxChar: UInt32
) -> [UInt32] {
  var scalars = [UInt32]()

  for scalar in str.unicodeScalars {
    let val = scalar.value

    guard val >= minChar && val <= maxChar else {
      continue
    }

    scalars.append(val)
  }

  return scalars
}

public struct Vigenere {
  private let keyScalars: [UInt32]
  private let smallestScalar: UInt32
  private let largestScalar: UInt32
  private let sizeAlphabet: UInt32

  public init?(key: String, smallestCharacter: Character = "A", largestCharacter:  Character = "Z") {
    let smallScalars = smallestCharacter.unicodeScalars
    let largeScalars = largestCharacter.unicodeScalars

    guard smallScalars.count == 1, largeScalars.count == 1 else {
      return nil
    }

    self.smallestScalar = smallScalars.first!.value
    self.largestScalar = largeScalars.first!.value
    self.sizeAlphabet = (largestScalar - smallestScalar) + 1

    let scalars = convertToUnicodeScalars(str: key, minChar: smallestScalar, maxChar: largestScalar)

    guard !scalars.isEmpty else {
      return nil
    }

    self.keyScalars = scalars

  }

  public func decrypt(_ str: String) -> String? {
    let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)

    guard !txtBytes.isEmpty else {
      return nil
    }

    var res = ""

    for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar {
      guard let char =
        UnicodeScalar((c &+ sizeAlphabet &- keyScalars[i % keyScalars.count]) % sizeAlphabet &+ smallestScalar)
      else {
        return nil
      }

      res += String(char)
    }

    return res
  }

  public func encrypt(_ str: String) -> String? {
    let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)

    guard !txtBytes.isEmpty else {
      return nil
    }

    var res = ""

    for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar {
      guard let char =
        UnicodeScalar((c &+ keyScalars[i % keyScalars.count] &- 2 &* smallestScalar) % sizeAlphabet &+ smallestScalar)
      else {
        return nil
      }

      res += String(char)
    }

    return res
  }
}

let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
let key = "VIGENERECIPHER";
let cipher = Vigenere(key: key)!

print("Key: \(key)")
print("Plain Text: \(text)")

let encoded = cipher.encrypt(text.uppercased())!

print("Cipher Text: \(encoded)")

let decoded = cipher.decrypt(encoded)!

print("Decoded: \(decoded)")

print("\nLarger set:")

let key2 = "Vigenère cipher"
let text2 = "This is a ünicode string 😃"

let cipher2 = Vigenere(key: key2, smallestCharacter: " ", largestCharacter: "🛹")!

print("Key: \(key2)")
print("Plain Text: \(text2)")

let encoded2 = cipher2.encrypt(text2)!

print("Cipher Text: \(encoded2)")

let decoded2 = cipher2.decrypt(encoded2)!

print("Decoded: \(decoded2)")

"Implements Vigenère cipher for both encryption and decryption, handling keys and text of unequal length. The code capitalizes all characters and discards non-alphabetic ones. It can also support a larger range of characters if needed."


for i in stride(from: 1, to: 10, by: 2) {
  print(i)
}

for var i = 1; i < 10; i += 2 {
  print(i)
}

demonstrate a for-loop with a step-value greater than one, printing all odd digits. Note that an alternate method was removed in Swift 3.


var i = 42 // initial value doesn't matter

func sum(inout i: Int, lo: Int, hi: Int, @autoclosure term: () -> Double) -> Double {
  var result = 0.0
  for i = lo; i <= hi; i++ {
    result += term()
  }
  return result
}

println(sum(&i, 1, 100, 1 / Double(i)))

implement Jensen's Device, a computer programming technique developed by Jørn Jensen. The technique is an exercise in call by name, demonstrated through a program that calculates the 100th harmonic number. The program utilizes the assumption that an expression passed as an actual parameter to a procedure will be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. This is particularly important for the first parameter to the sum function, which must be passed by name or by reference to ensure changes to it are visible in the caller's context. The global variable does not need to use the same identifier as the formal parameter.


Works with: Swift version 3
import Foundation

extension Array {
    mutating func shuffle() {
        guard count > 1 else { return }

        for i in 0..<self.count - 1 {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            guard i != j else { continue }
            swap(&self[i], &self[j])
        }
    }
}

enum Direction:Int {
    case north = 1
    case south = 2
    case east = 4
    case west = 8

    static var allDirections:[Direction] {
        return [Direction.north, Direction.south, Direction.east, Direction.west]
    }

    var opposite:Direction {
        switch self {
        case .north:
            return .south
        case .south:
            return .north
        case .east:
            return .west
        case .west:
            return .east
        }
    }

    var diff:(Int, Int) {
        switch self {
        case .north:
            return (0, -1)
        case .south:
            return (0, 1)
        case .east:
            return (1, 0)
        case .west:
            return (-1, 0)
        }
    }

    var char:String {
        switch self {
        case .north:
            return "N"
        case .south:
            return "S"
        case .east:
            return "E"
        case .west:
            return "W"
        }
    }

}

class MazeGenerator {
    let x:Int
    let y:Int
    var maze:[[Int]]

    init(_ x:Int, _ y:Int) {
        self.x  = x
        self.y = y
        let column = [Int](repeating: 0, count: y)
        self.maze = [[Int]](repeating: column, count: x)
        generateMaze(0, 0)
    }

    private func generateMaze(_ cx:Int, _ cy:Int) {
        var directions = Direction.allDirections
        directions.shuffle()
        for direction in directions {
            let (dx, dy) = direction.diff
            let nx = cx + dx
            let ny = cy + dy
            if inBounds(nx, ny) && maze[nx][ny] == 0 {
                maze[cx][cy] |= direction.rawValue
                maze[nx][ny] |= direction.opposite.rawValue
                generateMaze(nx, ny)
            }
        }
    }

    private func inBounds(_ testX:Int, _ testY:Int) -> Bool {
        return inBounds(value:testX, upper:self.x) && inBounds(value:testY, upper:self.y)
    }

    private func inBounds(value:Int, upper:Int) -> Bool {
        return (value >= 0) && (value < upper)
    }

    func display() {
        let cellWidth = 3
        for j in 0..<y {
            // Draw top edge
            var topEdge = ""
            for i in 0..<x {
                topEdge += "+"
                topEdge += String(repeating: (maze[i][j] & Direction.north.rawValue) == 0 ? "-" : " ", count: cellWidth)
            }
            topEdge += "+"
            print(topEdge)

            // Draw left edge
            var leftEdge = ""
            for i in 0..<x {
                leftEdge += (maze[i][j] & Direction.west.rawValue) == 0 ? "|" : " "
                leftEdge += String(repeating: " ", count: cellWidth)
            }
            leftEdge += "|"
            print(leftEdge)
        }

        // Draw bottom edge
        var bottomEdge = ""
        for _ in 0..<x {
            bottomEdge += "+"
            bottomEdge += String(repeating: "-", count: cellWidth)
        }
        bottomEdge += "+"
        print(bottomEdge)
    }

    func displayInts() {
        for j in 0..<y {
            var line = ""
            for i in 0..<x {
                line += String(maze[i][j]) + "\t"
            }
            print(line)
        }
    }

    func displayDirections() {
        for j in 0..<y {
            var line = ""
            for i in 0..<x {
                line += getDirectionsAsString(maze[i][j]) + "\t"
            }
            print(line)
        }
    }

    private func getDirectionsAsString(_ value:Int) -> String {
        var line = ""
        for direction in Direction.allDirections {
            if (value & direction.rawValue) != 0 {
                line += direction.char
            }
        }
        return line
    }
}

let x = 20
let y = 10
let maze = MazeGenerator(x, y)
maze.display()

generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.


Works with: Swift 4.2
//
//  main.swift
//  pi digits
//
//  Created by max goren on 11/11/21.
//  Copyright © 2021 maxcodes. All rights reserved.
//

import Foundation

var r = [Int]()
var i = 0
var k = 2800
var b = 0
var c = 0
var d = 0

for _ in 0...2800 {
    r.append(2000);
}
while k > 0 {
    d = 0;
    i = k;
    while (true) {
        d = d + r[i] * 10000
        b = 2 * i - 1
        r[i] = d % b
        d = d / b
        i = i - 1
        if i == 0 {
            break;
        }
        d = d * i;
    }
    print(c +  d / 10000, "")
    c = d % 10000
    k = k - 14
}

are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.


let a = [1,2,1,3,2]
let b = [1,2,0,4,4,0,0,0]
println(lexicographicalCompare(a, b)) // this is "less than"

"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise."


func ackerman(m:Int, n:Int) -> Int {
    if m == 0 {
        return n+1
    } else if n == 0 {
        return ackerman(m-1, 1)
    } else {
        return ackerman(m-1, ackerman(m, n-1))
    }
}

Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.


	let maxn = 31

	func nq(n: Int) -> Int {
	    var cols = Array(repeating: 0, count: maxn)
	    var diagl = Array(repeating: 0, count: maxn)
	    var diagr = Array(repeating: 0, count: maxn)
	    var posibs = Array(repeating: 0, count: maxn)
	    var num = 0
	    for q0 in 0...n-3 {
		for q1 in q0+2...n-1 {
		    let bit0: Int = 1<<q0
		    let bit1: Int = 1<<q1
		    var d: Int = 0
		    cols[0] = bit0 | bit1 | (-1<<n)
		    diagl[0] = (bit0<<1|bit1)<<1
		    diagr[0] = (bit0>>1|bit1)>>1

		    var posib: Int = ~(cols[0] | diagl[0] | diagr[0])

		    while (d >= 0) {
			while(posib != 0) {
			    let bit: Int = posib & -posib
			    let ncols: Int = cols[d] | bit
			    let ndiagl: Int = (diagl[d] | bit) << 1;
			    let ndiagr: Int = (diagr[d] | bit) >> 1;
			    let nposib: Int = ~(ncols | ndiagl | ndiagr);
			    posib^=bit
			    num += (ncols == -1 ? 1 : 0)
			    if (nposib != 0){
				if(posib != 0) {
				    posibs[d] = posib
				    d += 1
				}
				cols[d] = ncols
				diagl[d] = ndiagl
				diagr[d] = ndiagr
				posib = nposib
			    }
			}
			d -= 1
			posib = d<0 ? n : posibs[d]

		    }
		}

	    }
	    return num*2
	}
	if(CommandLine.arguments.count == 2) {

	    let board_size: Int = Int(CommandLine.arguments[1])!
	    print ("Number of solutions for board size \(board_size) is: \(nq(n:board_size))")

	} else {
	    print("Usage: 8q <n>")
	}

solve the N-queens problem, extending the eight queens puzzle to a board of size NxN. It also provides the number of solutions for small values of N (refer OEIS: A000170). This is a port of an optimized C code.


let array1 = [1,2,3]
let array2 = [4,5,6]
let array3 = array1 + array2

demonstrate how to concatenate two arrays.


Translation of: Python
Dynamic Programming[edit]
struct KnapsackItem {
  var name: String
  var weight: Int
  var value: Int
}

func knapsack(items: [KnapsackItem], limit: Int) -> [KnapsackItem] {
  var table = Array(repeating: Array(repeating: 0, count: limit + 1), count: items.count + 1)

  for j in 1..<items.count+1 {
    let item = items[j-1]

    for w in 1..<limit+1 {
      if item.weight > w {
        table[j][w] = table[j-1][w]
      } else {
        table[j][w] = max(table[j-1][w], table[j-1][w-item.weight] + item.value)
      }
    }
  }

  var result = [KnapsackItem]()
  var w = limit

  for j in stride(from: items.count, to: 0, by: -1) where table[j][w] != table[j-1][w] {
    let item = items[j-1]

    result.append(item)

    w -= item.weight
  }

  return result
}

let items = [
  KnapsackItem(name: "map", weight: 9, value: 150), KnapsackItem(name: "compass", weight: 13, value: 35),
  KnapsackItem(name: "water", weight: 153, value: 200), KnapsackItem(name: "sandwich", weight: 50, value: 160),
  KnapsackItem(name: "glucose", weight: 15, value: 60), KnapsackItem(name: "tin", weight: 68, value: 45),
  KnapsackItem(name: "banana", weight: 27, value: 60), KnapsackItem(name: "apple", weight: 39, value: 40),
  KnapsackItem(name: "cheese", weight: 23, value: 30), KnapsackItem(name: "beer", weight: 52, value: 10),
  KnapsackItem(name: "suntan cream", weight: 11, value: 70), KnapsackItem(name: "camera", weight: 32, value: 30),
  KnapsackItem(name: "t-shirt", weight: 24, value: 15), KnapsackItem(name: "trousers", weight: 48, value: 10),
  KnapsackItem(name: "umbrella", weight: 73, value: 40), KnapsackItem(name: "waterproof trousers", weight: 42, value: 70),
  KnapsackItem(name: "waterproof overclothes", weight: 43, value: 75), KnapsackItem(name: "note-case", weight: 22, value: 80),
  KnapsackItem(name: "sunglasses", weight: 7, value: 20), KnapsackItem(name: "towel", weight: 18, value: 12),
  KnapsackItem(name: "socks", weight: 4, value: 50), KnapsackItem(name: "book", weight: 30, value: 10)
]

let kept = knapsack(items: items, limit: 400)

print("Kept: ")

for item in kept {
  print("  \(item.name)")
}

let (tValue, tWeight) = kept.reduce((0, 0), { ($0.0 + $1.value, $0.1 + $1.weight) })

print("For a total value of \(tValue) and a total weight of \(tWeight)")

The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.