Skip to content

Instantly share code, notes, and snippets.

@alonecuzzo
Created January 5, 2016 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alonecuzzo/341e980effd548177870 to your computer and use it in GitHub Desktop.
Save alonecuzzo/341e980effd548177870 to your computer and use it in GitHub Desktop.
WIP for polish notation
//: Playground - noun: a place where people can play
import UIKit
//"2+3+4"
//"234++"
func polish(input: String) -> String {
if input.characters.count <= 1 {
return "broke"
}
let count = input.characters.count
let delta = (count == 2 || count == 3) ? 1 : 2
let head = String(input[input.startIndex])
let tail = input[input.startIndex.advancedBy(delta)..<input.endIndex]
switch count {
case 2:
return tail + String(head)
case 3:
return head + polish(tail)
default:
//if second character is *, the head
// we're looking instead at the second to last operation
let secondTolastIndex = input.endIndex.advancedBy(-4)
if input[secondTolastIndex] == "+" {
return String(input[input.startIndex])
+ polish(tail)
+ String(input[input.startIndex.advancedBy(1)])
} else if input[secondTolastIndex] == "*" {
let head = String(input[input.startIndex..<input.startIndex.advancedBy(3)])
let tail = input[input.startIndex.advancedBy(3)..<input.endIndex]
return polish(head) + polish(tail)
}
return String(input[input.startIndex.advancedBy(1)]) + "input: \(input)"
}
}
//if the second character is * then the head is
//2 * 3 + 4 - 23*4+
//2 + 3 * 4 - 234*+
//2 + 3 * 4 + 8 - 234*+8+
let input = "2+3*4"
let head = input[input.startIndex..<input.startIndex.advancedBy(2)]
let tail = input[input.endIndex.advancedBy(-4)]
//tail + String(head)
//let head = input[0]
//let tail = input[1]
polish(input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment