How to pick capital letters from a Swift string? - ios

I need capital letters from a string. With NSString it was sth like:
for (var i = 0; i<str.length; i++) {
let c = str.characterAtIndex(i)
if c >= 'A' && c < 'Z' {
//..
}
}
In Swift it starts like:
for (var i = 0; i<countElements(str); i++) {
//..
}
But I do not know i.e. how to pick i-th character, I am checking this

Here's a slightly more idiomatic version in swift
func capitalLetters(s: String) -> [Character] {
return filter(s) { ("A"..."Z").contains($0) }
}
capitalLetters("fOo BAr") // ["O", "B", "A"]
or even:
func capitalLetters(s: String) -> [Character] {
func isCapital(c: Character) -> Bool {
return ("A"..."Z").contains(c)
}
return filter(s, isCapital)
}
capitalLetters("fOo BAr")
or also, you could make the syntax nicer by providing an extension
extension String {
func capitalLetters() -> [Character] {
func isCapital(c: Character) -> Bool {
return ("A"..."Z").contains(c)
}
return filter(self, isCapital)
}
}
"fOo BAr".capitalLetters()

For example this work fine in Swift :
var st = "Hello World"
for ch in st {
if ch >= "A" && ch <= "Z"{
println(ch)
}
}
And print
H
W
Or you could this instead :
var range = "A"..."Z"
for ch in st {
if range.contains(String(ch)) {
println(ch)
}
}
Or the solution of #Gabrielle updated to Swift 2.0:
func capitalLetters(s: String) -> [Character] {
return s.characters.filter { ("A"..."Z").contains($0) }
}
capitalLetters("fOo BAr") // ["O", "B", "A"]

Related

Check for balanced parentheses in an expression in Swift

I am trying to write this in swift as I could not find any solution written in swift but seem to have hit a roadblock with this implementation.
On the pop and push function, I am not sure if Character is the right return/argument.
class BalancedParam {
struct stack {
var top = -1
var items = [Character]()
mutating func push(_ x: Character) {
items.append(x)
if top == 99 {
print("Stack full")
} else {
top += 1
items[top] = x
}
}
mutating func pop() -> Character {
if top == -1 {
print("Underflow error")
return "0"
} else {
let element = items[top]
top -= 1
return element
}
}
mutating func isEmpty() -> Bool {
return (top == -1) ? true : false
}
}
static func isMatchingPair(_ character1: Character, _ character2: Character) -> Bool {
if character1 == "(" && character2 == ")" {
return true
} else if character1 == "{" && character2 == "}" {
return true
} else if character1 == "[" && character2 == "]" {
return true
} else {
return false
}
}
static func areParenthesisBalanced(_ exp: [Character]) -> Bool {
// Declare an empty character stack
var st = stack()
for i in 0..<exp.count {
if exp[i] == "{" || exp[i] == "(" || exp[i] == "[" {
st.push(exp[i])
}
if exp[i] == "}" || exp[i] == ")" || exp[i] == "]" {
if st.isEmpty() {
return false
} else if !isMatchingPair(st.pop(), exp[i] ) {
return false
}
}
}
if st.isEmpty() {
return true //balanced
} else {
//not balanced
return false
}
}
}
let exp: [Character] = ["{", "(", ")", "}", "[", "]"]
if BalancedParam.areParenthesisBalanced(exp) {
print("Balanced ")
} else {
print("Not Balanced ")
}
I will appreciate any help in understanding what I am doing wrong. Thanks
You can not assign to an empty array, i.e items[top] = x, you can only use this syntax if the array is of size top+1 or larger
So this is not ok
var arr = [Int]()
arr[0] = 1
but this is
var arr = [Int]()
arr.append(0)
arr[0] = 1
Another option since you have a cap on your array size is to init an array of that size and then continue to use the original syntax
var arr = Array(repeating: 0, count: 99)
arr[0] = 1

ArrayType in extension where clause

extension Array where Element: _ArrayType, Element.Generator.Element: Any {
func transpose() -> [Element] {
if self.isEmpty { return [Element]() }
let count = self[0].count
var out = [Element](repeating: Element(), count: count)
for outer in self {
for (index, inner) in outer.enumerated() {
out[index].append(inner)
}
}
return out
}
}
I am getting this error in Swift 3.0 after converting it from Swift 2.2. The elements of the array are also array. So how to define it in Swift 3.0?
extension Array where Element : Collection, Element.Index == Int, Element.IndexDistance == Int {
func transpose() -> [[Element.Iterator.Element]] {
typealias InnerElement = Element.Iterator.Element
if self.isEmpty { return [] }
let count = self[0].count
var out = [[InnerElement]](repeating: [InnerElement](), count: count)
for outer in self {
for (index, inner) in outer.enumerated() {
out[index].append(inner)
}
}
return out
}
}

Recursive n Queens on nxn chess board implementation in Swift

I am trying to create a recursive Swift implementation for the solution of the classic puzzle: "How can we distribute n queens on a chess grid of n × n so that no queen can threaten another".
With existing code I encountered the following problems:
Code does not produce all the solutions for n<=8
Code does not product ANY solution for n>=9
Can't seem to compare solutions for n=8 (8x8) and larger because I compute the hash for each Solution class (board) by shifting bits which represent existence of queen or empty tile:
public override var hash: Int {
var hash = 0
for i in 0...self.board.count-1 {
for j in 0...self.board.count-1 {
if self.board[i][j].state == .Queen {
hash |= 1
hash <<= 1
} else {
hash <<= 1
}
}
}
return hash
}
when board is >8x8 value gets corrupted as it is larger than 64 bits (swift Int is Int64). What's a good solution for that?
My current code:
import UIKit
public typealias Board = Array<Array<Cell>>
#objc protocol QueenPlacementDelegate : class {
func solutionsFound(numOfSolutions : Int)
}
class QueenPlacement: NSObject {
var boardView : TTTBoardView?
var boardSize : Int = 0
var solutions : Set<Solution>?
weak var delegate : QueenPlacementDelegate?
private var startCondX : Int = 0
private var startCondY : Int = 0
func start() {
if boardSize == 0 {
print("Board size was not initialized")
return
}
self.solutions = Set<Solution>()
var done = false
self.startCondX = 0; self.startCondY = 0;
while (!done) {
let solution = Solution(boardSize: self.boardSize)
let board = solution.board
self.placeQueen(startCondX, yLoc: startCondY, board: board)
let solutionBoard = self.findSolutionForBoard(board)
if self.numOfQueensOnBoard(solutionBoard) == self.boardSize {
print("solution found")
solution.board = solutionBoard
self.solutions!.insert(solution)
}
done = self.advanceStartConditionsAndCheckIfDone()
if (done) {
if self.solutions!.count > 0 {
self.delegate!.solutionsFound(self.solutions!.count)
}
}
}
}
func advanceStartConditionsAndCheckIfDone() -> Bool {
startCondX++
if startCondX >= self.boardSize {
startCondX = 0
startCondY++
if startCondY >= self.boardSize {
return true
}
}
return false
}
func placeQueen(xLoc : Int, yLoc : Int, board : Board) {
board[xLoc][yLoc].state = .Queen
}
func findSolutionForBoard(board : Board) -> Board
{
let queensPlaced = self.numOfQueensOnBoard(board)
if queensPlaced == self.boardSize {
return board
}
else
{
for i in 0...self.boardSize-1 {
for j in 0...self.boardSize-1 {
if self.canPlaceQueen(xLoc: i, yLoc: j, board: board) {
self.placeQueen(i, yLoc: j, board: board)
}
}
}
let newQueensPlaced = self.numOfQueensOnBoard(board)
// recursion exit conditions: could not place any new queen
if newQueensPlaced > queensPlaced {
self.findSolutionForBoard(board)
} else {
return board
}
}
return board
}
func numOfQueensOnBoard(board : Board) -> Int {
var queensPlaced = 0
for i in 0...self.boardSize-1 {
for j in 0...self.boardSize-1 {
if board[i][j].state == .Queen {
queensPlaced++
}
}
}
return queensPlaced
}
func canPlaceQueen(xLoc xLoc : Int, yLoc : Int, board: Board) -> Bool {
for i in 0...self.boardSize-1 {
if board[i][yLoc].state == .Queen {
return false;
}
if board[xLoc][i].state == .Queen {
return false;
}
}
var x : Int
var y : Int
x = xLoc; y = yLoc;
while ++x < self.boardSize && ++y < self.boardSize {
if board[x][y].state == .Queen {
return false
}
}
x = xLoc; y = yLoc;
while --x >= 0 && ++y < self.boardSize {
if board[x][y].state == .Queen {
return false
}
}
x = xLoc; y = yLoc;
while ++x < self.boardSize && --y >= 0 {
if board[x][y].state == .Queen {
return false
}
}
x = xLoc; y = yLoc;
while --x >= 0 && --y >= 0 {
if board[x][y].state == .Queen {
return false
}
}
return true
}
// singleton!
static let sharedInstance = QueenPlacement()
private override init() {}
}
What is wrong here?
P.S.
for easier reading - full code repo can be found here
It's not an answer in a way that I don't know what is the problem with your version, but here is another one (looks working as I tested it), a little bit simplier (based on Scala By Example - The N-Queens Problem).
func queens(n: Int) -> [[Int]] {
guard n > 3 else {
return [[Int]]()
}
func placeQueens(k: Int) -> [[Int]] {
guard k > 0 else {
return [[-1]] //stupid hack to let the app go to the for-loop in the * marked place
}
var res = [[Int]]()
for var q in placeQueens(k - 1) { //* marked place
if let first = q.first where first == -1 { //this is for removing the hacky -1
q.removeAll()
}
for column in 1...n {
if isSafe(column, queens: q) {
var solution = q
solution.append(column)
res.append(solution)
}
}
}
return res
}
return placeQueens(n)
}
func isSafe(column: Int, queens: [Int]) -> Bool {
for (index, q) in queens.enumerate() {
let dy = (index + 1) - (queens.count + 1)
let dx = q - column
let isDiagonal = dy * dy == dx * dx
if q == column || isDiagonal {
return false
}
}
return true
}
And if you want to draw the solutions out:
func drawTable(table: [Int]) -> String {
var res = ""
table.forEach {
for column in 1...table.count {
if $0 == column {
res += "X "
} else {
res += ". "
}
}
res += "\n"
}
return res
}
And
queens(4).forEach {
print(drawTable($0))
}
Computing the 73712 solutions of n = 13 took some minutes, above that you would probably run out of memory this way.

Working with Unicode code points in Swift

If you are not interested in the details of Mongolian but just want a quick answer about using and converting Unicode values in Swift, then skip down to the first part of the accepted answer.
Background
I want to render Unicode text for traditional Mongolian to be used in iOS apps. The better and long term solution is to use an AAT smart font that would render this complex script. (Such fonts do exist but their license does not allow modification and non-personal use.) However, since I have never made a font, let alone all of the rendering logic for an AAT font, I just plan to do the rendering myself in Swift for now. Maybe at some later date I can learn to make a smart font.
Externally I will use Unicode text, but internally (for display in a UITextView) I will convert the Unicode to individual glyphs that are stored in a dumb font (coded with Unicode PUA values). So my rendering engine needs to convert Mongolian Unicode values (range: U+1820 to U+1842) to glyph values stored in the PUA (range: U+E360 to U+E5CF). Anyway, this is my plan since it is what I did in Java in the past, but maybe I need to change my whole way of thinking.
Example
The following image shows su written twice in Mongolian using two different forms for the letter u (in red). (Mongolian is written vertically with letters being connected like cursive letters in English.)
In Unicode these two strings would be expressed as
var suForm1: String = "\u{1830}\u{1826}"
var suForm2: String = "\u{1830}\u{1826}\u{180B}"
The Free Variation Selector (U+180B) in suForm2 is recognized (correctly) by Swift String to be a unit with the u (U+1826) that precedes it. It is considered by Swift to be a single character, an extended grapheme cluster. However, for the purposes of doing the rendering myself, I need to differentiate u (U+1826) and FVS1 (U+180B) as two distinct UTF-16 code points.
For internal display purposes, I would convert the above Unicode strings to the following rendered glyph strings:
suForm1 = "\u{E46F}\u{E3BA}"
suForm2 = "\u{E46F}\u{E3BB}"
Question
I have been playing around with Swift String and Character. There are a lot of convenient things about them, but since in my particular case I deal exclusively with UTF-16 code units, I wonder if I should be using the old NSString rather than Swift's String. I realize that I can use String.utf16 to get UTF-16 code points, but the conversion back to String isn't very nice.
Would it be better to stick with String and Character or should I use NSString and unichar?
What I have read
Strings and Characters documentation
Strings in Swift
NSString and Unicode
Updates to this question have been hidden in order to clean the page up. See the edit history.
Updated for Swift 3
String and Character
For almost everyone in the future who visits this question, String and Character will be the answer for you.
Set Unicode values directly in code:
var str: String = "I want to visit 北京, Москва, मुंबई, القاهرة, and 서울시. 😊"
var character: Character = "🌍"
Use hexadecimal to set values
var str: String = "\u{61}\u{5927}\u{1F34E}\u{3C0}" // a大🍎π
var character: Character = "\u{65}\u{301}" // é = "e" + accent mark
Note that the Swift Character can be composed of multiple Unicode code points, but appears to be a single character. This is called an Extended Grapheme Cluster.
See this question also.
Convert to Unicode values:
str.utf8
str.utf16
str.unicodeScalars // UTF-32
String(character).utf8
String(character).utf16
String(character).unicodeScalars
Convert from Unicode hex values:
let hexValue: UInt32 = 0x1F34E
// convert hex value to UnicodeScalar
guard let scalarValue = UnicodeScalar(hexValue) else {
// early exit if hex does not form a valid unicode value
return
}
// convert UnicodeScalar to String
let myString = String(scalarValue) // 🍎
Or alternatively:
let hexValue: UInt32 = 0x1F34E
if let scalarValue = UnicodeScalar(hexValue) {
let myString = String(scalarValue)
}
A few more examples
let value0: UInt8 = 0x61
let value1: UInt16 = 0x5927
let value2: UInt32 = 0x1F34E
let string0 = String(UnicodeScalar(value0)) // a
let string1 = String(UnicodeScalar(value1)) // 大
let string2 = String(UnicodeScalar(value2)) // 🍎
// convert hex array to String
let myHexArray = [0x43, 0x61, 0x74, 0x203C, 0x1F431] // an Int array
var myString = ""
for hexValue in myHexArray {
myString.append(UnicodeScalar(hexValue))
}
print(myString) // Cat‼🐱
Note that for UTF-8 and UTF-16 the conversion is not always this easy. (See UTF-8, UTF-16, and UTF-32 questions.)
NSString and unichar
It is also possible to work with NSString and unichar in Swift, but you should realize that unless you are familiar with Objective C and good at converting the syntax to Swift, it will be difficult to find good documentation.
Also, unichar is a UInt16 array and as mentioned above the conversion from UInt16 to Unicode scalar values is not always easy (i.e., converting surrogate pairs for things like emoji and other characters in the upper code planes).
Custom string structure
For the reasons mentioned in the question, I ended up not using any of the above methods. Instead I wrote my own string structure, which was basically an array of UInt32 to hold Unicode scalar values.
Again, this is not the solution for most people. First consider using extensions if you only need to extend the functionality of String or Character a little.
But if you really need to work exclusively with Unicode scalar values, you could write a custom struct.
The advantages are:
Don't need to constantly switch between Types (String, Character, UnicodeScalar, UInt32, etc.) when doing string manipulation.
After Unicode manipulation is finished, the final conversion to String is easy.
Easy to add more methods when they are needed
Simplifies converting code from Java or other languages
Disadavantages are:
makes code less portable and less readable for other Swift developers
not as well tested and optimized as the native Swift types
it is yet another file that has to be included in a project every time you need it
You can make your own, but here is mine for reference. The hardest part was making it Hashable.
// This struct is an array of UInt32 to hold Unicode scalar values
// Version 3.4.0 (Swift 3 update)
struct ScalarString: Sequence, Hashable, CustomStringConvertible {
fileprivate var scalarArray: [UInt32] = []
init() {
// does anything need to go here?
}
init(_ character: UInt32) {
self.scalarArray.append(character)
}
init(_ charArray: [UInt32]) {
for c in charArray {
self.scalarArray.append(c)
}
}
init(_ string: String) {
for s in string.unicodeScalars {
self.scalarArray.append(s.value)
}
}
// Generator in order to conform to SequenceType protocol
// (to allow users to iterate as in `for myScalarValue in myScalarString` { ... })
func makeIterator() -> AnyIterator<UInt32> {
return AnyIterator(scalarArray.makeIterator())
}
// append
mutating func append(_ scalar: UInt32) {
self.scalarArray.append(scalar)
}
mutating func append(_ scalarString: ScalarString) {
for scalar in scalarString {
self.scalarArray.append(scalar)
}
}
mutating func append(_ string: String) {
for s in string.unicodeScalars {
self.scalarArray.append(s.value)
}
}
// charAt
func charAt(_ index: Int) -> UInt32 {
return self.scalarArray[index]
}
// clear
mutating func clear() {
self.scalarArray.removeAll(keepingCapacity: true)
}
// contains
func contains(_ character: UInt32) -> Bool {
for scalar in self.scalarArray {
if scalar == character {
return true
}
}
return false
}
// description (to implement Printable protocol)
var description: String {
return self.toString()
}
// endsWith
func endsWith() -> UInt32? {
return self.scalarArray.last
}
// indexOf
// returns first index of scalar string match
func indexOf(_ string: ScalarString) -> Int? {
if scalarArray.count < string.length {
return nil
}
for i in 0...(scalarArray.count - string.length) {
for j in 0..<string.length {
if string.charAt(j) != scalarArray[i + j] {
break // substring mismatch
}
if j == string.length - 1 {
return i
}
}
}
return nil
}
// insert
mutating func insert(_ scalar: UInt32, atIndex index: Int) {
self.scalarArray.insert(scalar, at: index)
}
mutating func insert(_ string: ScalarString, atIndex index: Int) {
var newIndex = index
for scalar in string {
self.scalarArray.insert(scalar, at: newIndex)
newIndex += 1
}
}
mutating func insert(_ string: String, atIndex index: Int) {
var newIndex = index
for scalar in string.unicodeScalars {
self.scalarArray.insert(scalar.value, at: newIndex)
newIndex += 1
}
}
// isEmpty
var isEmpty: Bool {
return self.scalarArray.count == 0
}
// hashValue (to implement Hashable protocol)
var hashValue: Int {
// DJB Hash Function
return self.scalarArray.reduce(5381) {
($0 << 5) &+ $0 &+ Int($1)
}
}
// length
var length: Int {
return self.scalarArray.count
}
// remove character
mutating func removeCharAt(_ index: Int) {
self.scalarArray.remove(at: index)
}
func removingAllInstancesOfChar(_ character: UInt32) -> ScalarString {
var returnString = ScalarString()
for scalar in self.scalarArray {
if scalar != character {
returnString.append(scalar)
}
}
return returnString
}
func removeRange(_ range: CountableRange<Int>) -> ScalarString? {
if range.lowerBound < 0 || range.upperBound > scalarArray.count {
return nil
}
var returnString = ScalarString()
for i in 0..<scalarArray.count {
if i < range.lowerBound || i >= range.upperBound {
returnString.append(scalarArray[i])
}
}
return returnString
}
// replace
func replace(_ character: UInt32, withChar replacementChar: UInt32) -> ScalarString {
var returnString = ScalarString()
for scalar in self.scalarArray {
if scalar == character {
returnString.append(replacementChar)
} else {
returnString.append(scalar)
}
}
return returnString
}
func replace(_ character: UInt32, withString replacementString: String) -> ScalarString {
var returnString = ScalarString()
for scalar in self.scalarArray {
if scalar == character {
returnString.append(replacementString)
} else {
returnString.append(scalar)
}
}
return returnString
}
func replaceRange(_ range: CountableRange<Int>, withString replacementString: ScalarString) -> ScalarString {
var returnString = ScalarString()
for i in 0..<scalarArray.count {
if i < range.lowerBound || i >= range.upperBound {
returnString.append(scalarArray[i])
} else if i == range.lowerBound {
returnString.append(replacementString)
}
}
return returnString
}
// set (an alternative to myScalarString = "some string")
mutating func set(_ string: String) {
self.scalarArray.removeAll(keepingCapacity: false)
for s in string.unicodeScalars {
self.scalarArray.append(s.value)
}
}
// split
func split(atChar splitChar: UInt32) -> [ScalarString] {
var partsArray: [ScalarString] = []
if self.scalarArray.count == 0 {
return partsArray
}
var part: ScalarString = ScalarString()
for scalar in self.scalarArray {
if scalar == splitChar {
partsArray.append(part)
part = ScalarString()
} else {
part.append(scalar)
}
}
partsArray.append(part)
return partsArray
}
// startsWith
func startsWith() -> UInt32? {
return self.scalarArray.first
}
// substring
func substring(_ startIndex: Int) -> ScalarString {
// from startIndex to end of string
var subArray: ScalarString = ScalarString()
for i in startIndex..<self.length {
subArray.append(self.scalarArray[i])
}
return subArray
}
func substring(_ startIndex: Int, _ endIndex: Int) -> ScalarString {
// (startIndex is inclusive, endIndex is exclusive)
var subArray: ScalarString = ScalarString()
for i in startIndex..<endIndex {
subArray.append(self.scalarArray[i])
}
return subArray
}
// toString
func toString() -> String {
var string: String = ""
for scalar in self.scalarArray {
if let validScalor = UnicodeScalar(scalar) {
string.append(Character(validScalor))
}
}
return string
}
// trim
// removes leading and trailing whitespace (space, tab, newline)
func trim() -> ScalarString {
//var returnString = ScalarString()
let space: UInt32 = 0x00000020
let tab: UInt32 = 0x00000009
let newline: UInt32 = 0x0000000A
var startIndex = self.scalarArray.count
var endIndex = 0
// leading whitespace
for i in 0..<self.scalarArray.count {
if self.scalarArray[i] != space &&
self.scalarArray[i] != tab &&
self.scalarArray[i] != newline {
startIndex = i
break
}
}
// trailing whitespace
for i in stride(from: (self.scalarArray.count - 1), through: 0, by: -1) {
if self.scalarArray[i] != space &&
self.scalarArray[i] != tab &&
self.scalarArray[i] != newline {
endIndex = i + 1
break
}
}
if endIndex <= startIndex {
return ScalarString()
}
return self.substring(startIndex, endIndex)
}
// values
func values() -> [UInt32] {
return self.scalarArray
}
}
func ==(left: ScalarString, right: ScalarString) -> Bool {
return left.scalarArray == right.scalarArray
}
func +(left: ScalarString, right: ScalarString) -> ScalarString {
var returnString = ScalarString()
for scalar in left.values() {
returnString.append(scalar)
}
for scalar in right.values() {
returnString.append(scalar)
}
return returnString
}
//Swift 3.0
// This struct is an array of UInt32 to hold Unicode scalar values
struct ScalarString: Sequence, Hashable, CustomStringConvertible {
private var scalarArray: [UInt32] = []
init() {
// does anything need to go here?
}
init(_ character: UInt32) {
self.scalarArray.append(character)
}
init(_ charArray: [UInt32]) {
for c in charArray {
self.scalarArray.append(c)
}
}
init(_ string: String) {
for s in string.unicodeScalars {
self.scalarArray.append(s.value)
}
}
// Generator in order to conform to SequenceType protocol
// (to allow users to iterate as in `for myScalarValue in myScalarString` { ... })
//func generate() -> AnyIterator<UInt32> {
func makeIterator() -> AnyIterator<UInt32> {
let nextIndex = 0
return AnyIterator {
if (nextIndex > self.scalarArray.count-1) {
return nil
}
return self.scalarArray[nextIndex + 1]
}
}
// append
mutating func append(scalar: UInt32) {
self.scalarArray.append(scalar)
}
mutating func append(scalarString: ScalarString) {
for scalar in scalarString {
self.scalarArray.append(scalar)
}
}
mutating func append(string: String) {
for s in string.unicodeScalars {
self.scalarArray.append(s.value)
}
}
// charAt
func charAt(index: Int) -> UInt32 {
return self.scalarArray[index]
}
// clear
mutating func clear() {
self.scalarArray.removeAll(keepingCapacity: true)
}
// contains
func contains(character: UInt32) -> Bool {
for scalar in self.scalarArray {
if scalar == character {
return true
}
}
return false
}
// description (to implement Printable protocol)
var description: String {
var string: String = ""
for scalar in scalarArray {
string.append(String(describing: UnicodeScalar(scalar))) //.append(UnicodeScalar(scalar)!)
}
return string
}
// endsWith
func endsWith() -> UInt32? {
return self.scalarArray.last
}
// insert
mutating func insert(scalar: UInt32, atIndex index: Int) {
self.scalarArray.insert(scalar, at: index)
}
// isEmpty
var isEmpty: Bool {
get {
return self.scalarArray.count == 0
}
}
// hashValue (to implement Hashable protocol)
var hashValue: Int {
get {
// DJB Hash Function
var hash = 5381
for i in 0 ..< scalarArray.count {
hash = ((hash << 5) &+ hash) &+ Int(self.scalarArray[i])
}
/*
for i in 0..< self.scalarArray.count {
hash = ((hash << 5) &+ hash) &+ Int(self.scalarArray[i])
}
*/
return hash
}
}
// length
var length: Int {
get {
return self.scalarArray.count
}
}
// remove character
mutating func removeCharAt(index: Int) {
self.scalarArray.remove(at: index)
}
func removingAllInstancesOfChar(character: UInt32) -> ScalarString {
var returnString = ScalarString()
for scalar in self.scalarArray {
if scalar != character {
returnString.append(scalar: scalar) //.append(scalar)
}
}
return returnString
}
// replace
func replace(character: UInt32, withChar replacementChar: UInt32) -> ScalarString {
var returnString = ScalarString()
for scalar in self.scalarArray {
if scalar == character {
returnString.append(scalar: replacementChar) //.append(replacementChar)
} else {
returnString.append(scalar: scalar) //.append(scalar)
}
}
return returnString
}
// func replace(character: UInt32, withString replacementString: String) -> ScalarString {
func replace(character: UInt32, withString replacementString: ScalarString) -> ScalarString {
var returnString = ScalarString()
for scalar in self.scalarArray {
if scalar == character {
returnString.append(scalarString: replacementString) //.append(replacementString)
} else {
returnString.append(scalar: scalar) //.append(scalar)
}
}
return returnString
}
// set (an alternative to myScalarString = "some string")
mutating func set(string: String) {
self.scalarArray.removeAll(keepingCapacity: false)
for s in string.unicodeScalars {
self.scalarArray.append(s.value)
}
}
// split
func split(atChar splitChar: UInt32) -> [ScalarString] {
var partsArray: [ScalarString] = []
var part: ScalarString = ScalarString()
for scalar in self.scalarArray {
if scalar == splitChar {
partsArray.append(part)
part = ScalarString()
} else {
part.append(scalar: scalar) //.append(scalar)
}
}
partsArray.append(part)
return partsArray
}
// startsWith
func startsWith() -> UInt32? {
return self.scalarArray.first
}
// substring
func substring(startIndex: Int) -> ScalarString {
// from startIndex to end of string
var subArray: ScalarString = ScalarString()
for i in startIndex ..< self.length {
subArray.append(scalar: self.scalarArray[i]) //.append(self.scalarArray[i])
}
return subArray
}
func substring(startIndex: Int, _ endIndex: Int) -> ScalarString {
// (startIndex is inclusive, endIndex is exclusive)
var subArray: ScalarString = ScalarString()
for i in startIndex ..< endIndex {
subArray.append(scalar: self.scalarArray[i]) //.append(self.scalarArray[i])
}
return subArray
}
// toString
func toString() -> String {
let string: String = ""
for scalar in self.scalarArray {
string.appending(String(describing:UnicodeScalar(scalar))) //.append(UnicodeScalar(scalar)!)
}
return string
}
// values
func values() -> [UInt32] {
return self.scalarArray
}
}
func ==(left: ScalarString, right: ScalarString) -> Bool {
if left.length != right.length {
return false
}
for i in 0 ..< left.length {
if left.charAt(index: i) != right.charAt(index: i) {
return false
}
}
return true
}
func +(left: ScalarString, right: ScalarString) -> ScalarString {
var returnString = ScalarString()
for scalar in left.values() {
returnString.append(scalar: scalar) //.append(scalar)
}
for scalar in right.values() {
returnString.append(scalar: scalar) //.append(scalar)
}
return returnString
}

Order array of objects into every possible sequence in Swift

Wondering if there is a clean way of doing this in Swift. Maybe using one or a couple of the global functions, ie Map / Reduce etc
The array contains unique custom objects of n quantity.
For example, with 3 items. But could have more or less. [1,2,3]
Would return an Array of Arrays
[
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
]
Here is a way in Java to complete the task. Just need to get into Swift form.
https://gist.github.com/JadenGeller/5d49e46d4084fc493e72
He created structs to handle permutations:
var greetingPermutations = PermutationSequenceGenerator(elements: ["hi", "hey", "hello"])
while let greetingSequence = greetingPermutations.next(){
for greeting in greetingSequence {
print("\(greeting) ")
}
println()
}
or:
var numberSpace = PermutationSpaceGenerator(objects: Array(1...4))
while let numberArray = numberSpace.next() {
println(numberArray)
}
EDIT:
Here is a simpler way found on objc.io
Add Extension
extension Array {
var decompose : (head: T, tail: [T])? {
return (count > 0) ? (self[0], Array(self[1..<count])) : nil
}
}
Add outside your extension / and class
infix operator >>= {}
func >>=<A, B>(xs: [A], f: A -> [B]) -> [B] {
return xs.map(f).reduce([], combine: +)
}
Normal Class Functions
func between<T>(x: T, ys: [T]) -> [[T]] {
if let (head, tail) = ys.decompose {
return [[x] + ys] + between(x, ys: tail).map { [head] + $0 }
} else {
return [[x]]
}
}
func permutations<T>(xs: [T]) -> [[T]] {
if let (head, tail) = xs.decompose {
return permutations(tail) >>= { permTail in
self.between(head, ys: permTail)
}
} else {
return [[]]
}
}
Testing
let example = permutations([1,2,3,5,6,7,8])
println(example)
This code extends Array with decompose function and also adds >>== operator (flattening) More about flattening: http://www.objc.io/snippets/4.html
Probably too c-ish, but here is an alternative to the already posted examples.
var a = [1, 2, 3, 4, 5]
var b = [[Int]]()
func perms<T>(n: Int, inout a: [T], inout b: [[T]]) {
if n == 0 {
b.append(a)
} else {
for i in 0..<n {
perms(n - 1, &a, &b)
var j = 0
if n % 2 == 0 {
j = i
}
swap(&a[j], &a[n - 1])
}
}
}
perms(a.count, &a, &b)
println(b)
Swift 5
Updated version of #DogCoffee for swift 5.x, all within an array extension :
extension Array {
private var decompose : (head: Element, tail: [Element])? {
return (count > 0) ? (self[0], Array(self[1..<count])) : nil
}
private func between<T>(x: T, ys: [T]) -> [[T]] {
if let (head, tail) = ys.decompose {
return [[x] + ys] + between(x: x, ys: tail).map { [head] + $0 }
} else {
return [[x]]
}
}
private func permutations<T>(xs: [T]) -> [[T]] {
if let (head, tail) = xs.decompose {
return permutations(xs: tail) >>= { permTail in
self.between(x: head, ys: permTail)
}
} else {
return [[]]
}
}
func allPermutations() -> [[Element]] {
return permutations(xs: self)
}
}
infix operator >>=
func >>=<A, B>(xs: [A], f: (A) -> [B]) -> [B] {
return xs.map(f).reduce([], +)
}

Resources