I ran the same code in Xcode 7beta/rc Playground project and got an error:
Execution was interrupted, reason: EXC_BAD_ACCESS(code=EXC_I386_GPFLT)
in
let n: Int = Int(Process.arguments[1])!
How do I solve in Playground project since other solutions don't seem to be related?
Binary tree: http://benchmarksgame.alioth.debian.org/u64q/program.php?test=binarytrees&lang=swift&id=1
class TreeNode {
var left, right : TreeNode?
var item : Int
init(_ left: TreeNode?, _ right: TreeNode?, _ item: Int) {
self.left = left
self.right = right
self.item = item
}
func check() -> Int {
guard let left = left, let right = right else {
return item
}
return item + left.check() - right.check()
}
}
func bottomUpTree(item: Int, _ depth: Int) -> TreeNode {
if depth > 0 {
return
TreeNode(
bottomUpTree(2*item-1, depth-1),
bottomUpTree(2*item, depth-1),
item
)
}
else {
return
TreeNode(nil,nil,item)
}
}
let n: Int = Int(Process.arguments[1])!
let minDepth = 4
let maxDepth = n
let stretchDepth = n + 1
let check = bottomUpTree(0,stretchDepth).check()
print("stretch tree of depth \(stretchDepth)\t check: \(check)")
let longLivedTree = bottomUpTree(0,maxDepth)
var depth = minDepth
while depth <= maxDepth {
let iterations = 1 << (maxDepth - depth + minDepth)
var check = 0
for i in 0..<iterations {
check += bottomUpTree(i,depth).check()
check += bottomUpTree(-i,depth).check()
}
print("\(iterations*2)\t trees of depth \(depth)\t check: \(check)")
depth += 2
}
print("long lived tree of depth \(maxDepth)\t check: \(longLivedTree.check())")
Process.arguments holds the value that is passed as arguments for a command-line application.
But you're using it in a Playground: there's no access to command line input from a Playground (they are Sandboxed), so Process.arguments is nil and your app crashes when you're doing Process.arguments[1].
The solution is to use this in an actual application, not in a Playground.
You can use a custom "readLine()" function and a global input variable, each element in the input array is presenting a line:
import Foundation
var currentLine = 0
let input = ["5", "5 6 3"]
func readLine() -> String? {
if currentLine < input.endIndex {
let line = input[currentLine]
currentLine += 1
return line
} else {
return nil
}
}
let firstLine = readLine() // 5
let secondLine = readLine() // 5 6 3
let thirdLine = readLine() // nil
Related
All words of the ternary language consist of only 3 letters: a, b, and c and all have a strictly specified length N. Words that do not contain two identical subsequences of letters in a row are considered correct. For example, abcacb is the correct word, and ababc is not the correct one, since the ab subsequences go there.
I tried to solve the problem with a complete enumeration of all possible combinations and a function that looked for a repeating sequence. However, this turned out to be the wrong decision. The problem needs to be solved somehow using the branch and bound method. I have absolutely no idea how this problem can be solved by this method. I would be very happy if someone provides examples or explains to me. I have already spent six days to solve this problem and am very tired.
My wrong solution:
import Foundation
func findRepetition(_ p: String) -> [String:Int] {
var repDict: [String:Int] = [:]
var p = p
while p.count != 0 {
for i in 0...p.count-1 {
repDict[String(Array(p)[0..<i]), default: 0] += 1
}
p = String(p.dropFirst())
}
return repDict
}
var correctWords = [String]()
var wrongWords = [String]()
func getRepeats(_ p: String) -> Bool {
let p = p
var a = findRepetition(p)
for i in a {
var substring = String(Array(repeating: i.key, count: 2).joined())
if p.contains(substring) {
wrongWords.append(p)
return false
}
}
correctWords.append(p)
return true
}
var counter = 0
func allLexicographicRecur (_ string: [String.Element], _ data: [String], _ last: Int, _ index: Int){
var length = string.count-1
var data = data
for i in 0...length {
data[index] = String(string[i])
if index == last {
if getRepeats(data.joined()) {
counter += 1
}
}else{
allLexicographicRecur(string, data, last, index+1)
}
}
}
func threeLanguage(_ l: Int) {
var alphabet = "abc"
var data = Array(repeating: "", count: l)
allLexicographicRecur(alphabet.sorted(), data, l-1, 0)
print("The specified word length: \(l), the number of correct words: \(counter)\n")
print("Correct words:\n\(correctWords)\n")
print("Wrong words:\n\(wrongWords)")
}
threeLanguage(3)
Example:
abca is the right word.
abab is wrong (ab).
aaaa is also wrong (a).
abcabc is also incorrect (abc).
If I correctly understood your problem, you need to separate you input string to parts N-length and check parts by your rules. Smth like this
let constant: Int = 3
extension String {
private func components(withLength length: Int) -> [String] {
return stride(from: 0, to: count, by: length).map {
let start = index(startIndex, offsetBy: $0)
let end = index(start, offsetBy: length, limitedBy: endIndex) ?? endIndex
return String(self[start ..< end])
}
}
var numberOfValidWords: Int {
var numberOfIncorrectWords = 0
let length = count - constant
let array = components(withLength: constant)
for component in array {
let computedLength = replacingOccurrences(of: component, with: "").count
if computedLength != length {
print("as is lengths are not equal, this part is met in string several times")
numberOfIncorrectWords += 1
continue
}
}
return array.count - numberOfIncorrectWords
}
}
Hope it will be helpful
Where is the bug in this serialize() function
I wrote a function deserialize() in Swift to construct a binary tree from an array of optional Integer. I tested this function by comparing the output with the output of a tree constructed using manual method with same array. They look the same, which is good !
However, when I run another function isSameTree(), that is used to compare 2 trees (I am sure this function is working correctly), on deserialize()'s output and manual method's output, I have different results !
I assume deserialize() is not correct, but I could not find the bug!
// helper code
public class BinaryNode {
public var value: Int
public var left: BinaryNode?
public var right: BinaryNode?
public init(_ value: Int) {
self.value = value
self.left = nil
self.right = nil
}
}
extension BinaryNode {
public var description: String {
return diagram(for: self)
}
private func diagram(for node: BinaryNode?,
_ top: String = "",
_ root: String = "",
_ bottom: String = "") -> String {
guard let node = node else {
return root + "nil\n"
}
if node.left == nil && node.right == nil {
return root + "\(node.value)\n"
}
return diagram(for: node.right,
top + " ", top + "┌──", top + "│ ")
+ root + "\(node.value)\n"
+ diagram(for: node.left,
bottom + "│ ", bottom + "└──", bottom + " ")
}
}
public func deserialize(_ array: inout [Int?]) -> BinaryNode? {
guard !array.isEmpty, let value = array.removeFirst() else {
return nil
}
let node = BinaryNode(value)
node.left = deserialize(&array)
node.right = deserialize(&array)
return node
}
func isSameTree(_ p: BinaryNode?, _ q: BinaryNode?) -> Bool {
guard let p = p else {
return q == nil
}
guard let q = q else {
return p == nil
}
if p.value != q.value {
return false
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}
// Using deserialize to construct trees
var a1: [Int?] = [1,nil,2,3]
var a2: [Int?] = [1,nil,2,nil,3]
if let tree = deserialize(&a1) {
print(tree.description)
}
if let tree = deserialize(&a2) {
print(tree.description)
}
// Using manual to construct trees
let a3: BinaryNode = {
let one = BinaryNode(1)
let two = BinaryNode(2)
let three = BinaryNode(3)
one.right = two
two.left = three
return one
}()
print(a3.description)
let a4: BinaryNode = {
let one = BinaryNode(1)
let two = BinaryNode(2)
let three = BinaryNode(3)
one.right = two
two.right = three
return one
}()
print(a4.description)
// The print statements above show similar trees are constructed
// However, below results are not same
isSameTree(deserialize(&a1), deserialize(&a2)) // true <- this is wrong
isSameTree(a3, a4) // false <--- this is correct
Seems you have forgotten that your deserialize(_:) is destructive for its parameter... Please remember why you need &.
//Re-load a1 & a2...
a1 = [1,nil,2,3]
a2 = [1,nil,2,nil,3]
print(isSameTree(deserialize(&a1), deserialize(&a2))) //-> false
print(isSameTree(a3, a4)) //-> false
I have an array of objects
var arrayOfObjects: [Object]?
And they all have a property called depth. I want to find the very next object in that array that has the same depth with a specific object I know the index of:
[
...objects_before...,
object_I_know: {depth:3},
...objects_after...
]
Is there a more efficient way other than using a for loop starting from the object_I_know index, and traversing down until it finds one?
let nextIndex: Int? = (givenIndex ..< array.endIndex).first { index in
return array[index].depth == array[givenIndex].depth
}
The item with the object with the same depth would be at that nextIndex if there is one
let nextObject: Object? = (nextIndex == nil) ? nil : array[nextIndex!]
Here's a sample model I came up with for testing:
struct S {
let id: Int
let depth: Int
}
var id = 0
let getID: () -> Int = { defer { id += 1 }; return id }
let objects = [
S(id: getID(), depth: 1),
S(id: getID(), depth: 3),
S(id: getID(), depth: 2),
S(id: getID(), depth: 3),
S(id: getID(), depth: 4),
]
Here's a solution that account for the situations in which there are no elements which match the predicate, or only 1 such element:
let isDepth3: (S) -> Bool = { $0.depth == 3 }
// Get the index of the first item (can be nil)
let indexOfFirstDepth3 = objects.index(where: isDepth3)
// Get the index after that (can be nil), so that we can exclude everything before it
let firstIndexOfRemainingItems = indexOfFirstDepth3.flatMap { objects.index($0, offsetBy: +1, limitedBy: objects.endIndex) }
let indexOfSecondDepth3 = firstIndexOfRemainingItems.flatMap {
// Slice the `objects` array, to omit all the items before up to and including the first depth 3 item.
// Then find the index of the next next 3 item thereafter.
return objects[$0...].index(where: isDepth3)
}
// Print results
func stringifyOptional<T>(_ item: T?) -> String {
return item.map{ String(describing: $0) } ?? "nil"
}
print("First item with depth 3 is \(stringifyOptional(indexOfFirstDepth3.map{ objects[$0] })) at index \(stringifyOptional(indexOfFirstDepth3))")
print("Second item with depth 3 is \(stringifyOptional(indexOfSecondDepth3.map{ objects[$0] })) at index \(stringifyOptional(indexOfFirstDepth3))")
If you're sure that you'll have 2 such elements, and you're sure that force unwrapping will be safe, then this can be simplified dramatically:
let isDepth3: (S) -> Bool = { $0.depth == 3 }
let indexOfFirstDepth3 = objects.index(where: isDepth3)!
let indexOfSecondDepth3 = objects[indexOfFirstDepth3...].index(where: isDepth3)!
// Just printing the result
print("First item with depth 3 is \(objects[indexOfFirstDepth3]) at index \(indexOfFirstDepth3)")
print("Second item with depth 3 is \(objects[indexOfFirstDepth3])) at index \(indexOfFirstDepth3)")
Context
struct DepthObject { let depth: Int }
let objs = [a, b, c, d ,e]
let index = 1 //predetermined index
let depthToFind = objs[index].depth
let startIndex = index + 1
let remainingArray = objs[startIndex...] //The slice we want to work with
One way
let aMessage: String? = remainingArray
.first { $0.depth == depthToFind }
.flatMap { "The world is yours \($0)" }
Decide based on it
if let nextDepthObject = remainingArray.first(where: { $0.depth == depthToFind }) {
//Found the next one!
} else {
//Didn't find it!
}
Loop it
var nextDepthObject: DepthObject? = nil
for sliceDepthObject in remainingArray {
if sliceDepthObject.depth == depthToFind {
nextDepthObject = sliceDepthObject
break
}
}
Implementing a particular approach
func nextDepthObject(within array: Array<DepthObject>, startingAt index: Int) -> DepthObject? {
guard index + 1 < array.count && index < array.count else {
return nil
}
let depthToFind = array[index].depth
let suffixArray = array[(index + 1)...]
return suffixArray.first { $0.depth == depthToFind }
}
let theNextOne: DepthObject? = nextDepthObject(within: objs, startingAt: index)
You can add an extension over Collection (which Array conforms to):
extension Collection {
func next(startingWith next: Self.Index, where match: (Element) -> Bool) -> Element? {
guard next < endIndex else { return nil }
return self[next..<endIndex].first(where: match)
}
}
You'd use it like this:
let nextMatch = arrayOfObjects.next(startingWith: foundIndex+1) { $0.depth == searchedDepth }
class Object {
var name: String
var depth: Float
init(name: String, depth: Float) {
self.name = name
self.depth = depth
}
}
let o1 = Object(name: "object1", depth: 10)
let o2 = Object(name: "object2", depth: 12)
let o3 = Object(name: "object3", depth: 4)
let o4 = Object(name: "object4", depth: 12)
let o5 = Object(name: "object5", depth: 14)
let array = [o1, o2, o3, o4, o5]
let knownIndex = 1
let knownDepth = array[knownIndex].depth
var searchResults = [Object]()
// iterate through the second half of the array after the known
// index and break the loop when a match is found
for i in knownIndex + 1..<array.count {
if array[i].depth == knownDepth {
searchResults = [array[i]]
break
}
}
// after the loop is finished (either by going all the way to the
// end or breaking after a match is found), check your search results
if searchResults.count > 0 {
print("match found: \(searchResults[0].name)")
} else {
print("no match found")
}
index(where:) uses a loop also, unbeknownst to the commenter, except that the compiler does it for you behind the scenes. index(where:) also loops through the entire array which is not very efficient if you already know the starting index (which OP does).
I would like to be able to find and replace occurrences of a substring in a native Swift string without bridging to the NS class. How can I accomplish this?
This is not a duplicate of this question, as that question is about replacing a single character. This question is about finding and replacing a substring, which may contain many characters.
Method without Foundation:
extension String {
func replacing(_ oldString: String, with newString: String) -> String {
guard !oldString.isEmpty, !newString.isEmpty else { return self }
let charArray = Array(self.characters)
let oldCharArray = Array(oldString.characters)
let newCharArray = Array(newString.characters)
var matchedChars = 0
var resultCharArray = [Character]()
for char in charArray {
if char == oldCharArray[matchedChars] {
matchedChars += 1
if matchedChars == oldCharArray.count {
resultCharArray.append(contentsOf: newCharArray)
matchedChars = 0
}
} else {
for i in 0 ..< matchedChars {
resultCharArray.append(oldCharArray[i])
}
if char == oldCharArray[0] {
matchedChars = 1
} else {
matchedChars = 0
resultCharArray.append(char)
}
}
}
return String(resultCharArray)
}
}
Example usage:
let myString = "Hello World HelHelloello Hello HellHellooo"
print(myString.replacing("Hello", with: "Hi"))
Output:
Hi World HelHiello Hi HellHioo
Method using Foundation:
You can use the replacingOccurrences method on the String struct.
let myString = "Hello World"
let newString = myString.replacingOccurrences(of: "World", with: "Everyone")
print(newString) // prints "Hello Everyone"
generic and pure Swift approach
func splitBy<T: RangeReplaceableCollection>(_ s:T, by:T)->[T] where T.Iterator.Element:Equatable {
var tmp = T()
var res = [T]()
var i:T.IndexDistance = 0
let count = by.count
var pc:T.Iterator.Element {
get {
i %= count
let idx = by.index(by.startIndex, offsetBy: i)
return by[idx]
}
}
for sc in s {
if sc != pc {
i = 0
if sc != pc {
} else {
i = i.advanced(by: 1)
}
} else {
i = i.advanced(by: 1)
}
tmp.append(sc)
if i == count {
tmp.removeSubrange(tmp.index(tmp.endIndex, offsetBy: -i)..<tmp.endIndex)
res.append(tmp)
tmp.removeAll()
}
}
res.append(tmp)
return res
}
func split(_ s:String, by:String)->[String] {
return splitBy(s.characters, by: by.characters).map(String.init)
}
extension RangeReplaceableCollection where Self.Iterator.Element: Equatable {
func split(by : Self)->[Self] {
return splitBy(self, by: by)
}
}
how to use it?
let str = "simple text where i would like to replace something with anything"
let pat = "something"
let rep = "anything"
let s0 = str.characters.split(by: pat.characters).map(String.init)
let res = s0.joined(separator: rep)
print(res) // simple text where i would like to replace anything with anything
let res2 = split(str, by: pat).joined(separator: rep)
print(res2) // simple text where i would like to replace anything with anything
let arr = [1,2,3,4,1,2,3,4,1,2,3]
let p = [4,1]
print(arr.split(by: p)) // [[1, 2, 3], [2, 3], [2, 3]]
This is the swift code I have as an exercise from my class, I am re-writing it(as I am new to it).
At the position of
let end = starIndex.advancedBy(position), I am getting an error message of String.Index does not have a member named advancedBy I am not sure what this means or how to correct it just yet, many thanks for any help in understanding what I am doing wrong.
//: Playground - noun: a place where people can play
import UIKit
var str : String = "Hello, playground"
str
let strFix = " Can not change"
str = "Good bye"
//strFix = "Testing"
var str2 = str + "F"
var townName = "NeverLand"
let population = 30000
let numOfStopLight : Int = 10
print("\(townName) has populations of \(population)
and has \ (numOfStopLight) Stop Lights")
for c in townName.unicodeScalars
{
print ("\(c)")
}
let starIndex = str.startIndex
let position = 3
let end = starIndex.advancedBy(position)
let charAt = str[end]
let range = starIndex...end
str[range]
let aChar: Character = "\u{1F60E}"
str.append(aChar)
let dollarSign = "\u{24}" //$, Unicode scalar U+0024
let blackHeart = "\u{2665}" // , Unicode scalar U+2665
let sparklingHeart = "\u{1F496}" // , Unicod scalar U=1F496
str.append(Character(sparklingHeart))
for c in str.characters
{
print("\(c)")
}
for c in str.unicodeScalars
{
print("\(c.value)")
}
/////////////////////
struct Car
{
var make : String = ""
var price : Double = 0.0
let color : String = "RED"
func getMske()->String
{
return make
}
mutating func setMake (m: String)
{
make = m
}
func showCar()->String
{
return "Make:\(make) Price=\(price) Color= \(color)"
}
}
//let us make some Car
var myCar = Car(make: "Nissan", price: 45000.0)
print(myCar.showCar())
myCar.setMake("Nissan2016")
print (myCar.showCar())
//show pass value
func doChange (var c: Car)
{
c.setMake("Toyota")
print (c.showCar())
}
doChange(myCar)
print (myCar.showCar())
//let us have a class
class Xcar
{
var make :String = ""
var price : Double = 0.0
var color : String = ""
init(m :String, p: Double, c: String)
{
self.make = m
self.price = p
self.color = c
}
func setMake(m: String)
{
self.make = m
}
func showXCar()->String
{
return "Make: \(make) Price=\(price) Color=\(color)"
}
}
func doChangex( c:Xcar)
{
c.setMake("BMW")
print("\(c.showXCar())")
}
var hisCar = Xcar(m: "Fiat", p: 15000.0, c: "Blue")
print ("\(hisCar.showXCar())")
doChangex(hisCar)
//notice the function did change
//because it was a class
print ("\(hisCar.showXCar())")
//What is optional
let a: Float?
let b: Float?
let c :Float?
a = 10
b = 20
c = 5
//this is implicit unrap
let ave = (a! + b! + c!)/3.0
if let x = a, y = b, z = c
{
print ("\((x + y + z) / 3.0)")
}
else
{
print ("missing value...")
}
// note Array, Double, Float, Int and Dictionary are all struct
var intArray = [Int] ()
intArray.append(50)
intArray.append(100)
intArray.append(600)
intArray.maxElement()
intArray.capacity
intArray.count
intArray.description
intArray.dropFirst()
intArray.first
intArray.description
intArray.removeFirst()
intArray.description
for c in intArray
{
print("\(c)")
}
var dict = [Int :String ] ()
dict = [235 :"Jack", 100: "Joe", 60: "Lisa"]
dict.description
for(key, value) in dict
{
print ("\(key)")
}
var name = dict[235]
Try doing it in one line
let startIndex = str.startIndex.advancedBy(3)
The code has a number of issues and we don't know what the expected output is, but here are a few items:
The line with just 'str' on it should be removed.
You may be running an older version of Xcode or OS (or both). This is Swift2 and you should be using Xcode 7 or higher.
Also, there are 'var' that should be 'let' (hisCar) and there are a number of unused variables.
The good news is once you fix the issues that, the code runs correctly (as far as I can tell)