Terminated by signal 4 - swift

Already checked other question on this topic, and I can't seem to utilize it to resolve my issue, so I'm creating a new question in order to see if I can't gain some insight on this issue and help others who may run into this using the Online Swift Playground.
Getting Terminated by signal 4 using the following code:
import Foundation
//enter equation here
var equation: String = "2 +( 3* 4)/ 2+22 ="
var equationWithoutWhitespace = equation.filter {!$0.isWhitespace}
//converts String equationWithoutWhitespace to array of Charcters e
let e = Array(equationWithoutWhitespace)
func add(_ firstVal: Int, _ secondVal: Int) -> Int {return Int(firstVal + secondVal)}
func sub(_ firstVal: Int, _ secondVal: Int) -> Int {return Int(firstVal - secondVal)}
func mul(_ firstVal: Int, _ secondVal: Int) -> Int {return Int(firstVal * secondVal)}
func div(_ firstVal: Int, _ secondVal: Int) -> Int {return Int(firstVal / secondVal)}
func power(_ firstVal: Double, _ secondVal: Double) -> Int {return Int(pow(firstVal,secondVal))}
func root(_ firstVal: Double, _ secondVal: Double) -> Int {return Int(pow(firstVal,1/secondVal))}
func checkParenthesis(_ equation: [Character]) -> (low: Int, high: Int){
var low = 0
var high = 0
for (index,value) in equation.enumerated() {
if(equation[index] == "("){
low = index
}
else if(equation[index] == ")"){
high = index
}
}
return (low, high)
}
func doMath(firstVal: Character, op: Character, secondVal: Character) -> Int {
var firstVar: Int! = Int("\(firstVal)")
var secondVar: Int! = Int("\(secondVal)")
switch op {
case "+":
return add(firstVar,secondVar)
case "-":
return sub(firstVar,secondVar)
case "*":
return mul(firstVar,secondVar)
case "/":
return div(firstVar,secondVar)
case "x",
"X":
var firstV: Double! = Double("\(firstVar)")
var secondV: Double! = Double("\(secondVar)")
return power(firstV,secondV)
case "r",
"R":
var firstV: Double! = Double("\(firstVar)")
var secondV: Double! = Double("\(secondVar)")
return root(firstV,secondV)
default:
print("error with operation detection")
return 0
}
}
//create new equation
var e2 = e
//get index of parenthesis & operation
var low = checkParenthesis(e2).low
var high = checkParenthesis(e2).high - 1
var op = low + 1
//if there were parenthesis, do this
if(low != 0 && high != 0){
//remove parenthesis
e2.remove(at: checkParenthesis(e2).low)
e2.remove(at: checkParenthesis(e2).high)
print(doMath(firstVal: e2[low],op: e2[op],secondVal: e2[high]))
}
Edit: this is a partial snippet of the complete project, it is essentially a text based calculator but it utilizes different rules than normal PEMDAS

I was looking over it again today, and I found using print(e2[low], e2[op], e2[high], low, op, high), I was able to check what values I was getting for my command, and realized I was 1 position off, because earlier I was compensating for removing the parenthesis, but later moved that function further down in the program. Because of this, var high = checkParenthesis(e2).high - 1 was 1 value off and not giving me an integer, but instead a character. Changing the - 1 to - 2 fixed the issue and everything works as it should. Thanks to everyone for your help!

Related

Nested function techniques for different "flow paths" in swift

I'm learning object oriented things and trying to incorporate nested functions into my code so I can gain understanding of how these different operations flow and work, specifically nested functions.
I want to pass values from one function to another then another and, depending on the calculations within each nested func, output certain final numbers. I'm having trouble understanding how to grab and re-declare return values inside a method so they can be used again.
Crude single nested example:
func increaseNumbers(numOne: Double, numTwo: Double) -> (Double, Double) {
var numOneIncreased = numOne + 2
var numTwoIncreased = numTwo + 5
func playWithNumbersMore(warpOne: Double, warpTwo: Double) -> (Double, Double) {
if warpOne < 50 {
var adjustedOne = warpOne + 16.5
var adjustedTwo = warpTwo + 20.8
} else { do nothing... }
return (adjustedOne, adjustedTwo)
}
playWithNumbersMore(warpOne: numOneIncreased, warpTwo: numTwoIncreased)
// How do i re-assign the return values inside playWithNumbersMore?
return (something, somethingTwo)
}
Crudely speaking this is what I want to do if possible:
func increaseNumbers(numOne: Double, numTwo: Double) -> (Double, Double) {
var numOneIncreased = numOne + 2
var numTwoIncreased = numTwo + 5
func playWithNumbersMore(warpOne: Double, warpTwo: Double) -> (Double, Double) {
if warpOne < 50 {
var adjustedOne = warpOne + 16.5
var adjustedTwo = warpTwo + 20.8
} else { do nothing... }
return (adjustedOne, adjustedTwo)
}
// I want to be able to take return values and do more with them... as well as redefine them
// on completion of final "parent function"
// Sort of like this:
var newNumbToPlayOne = adjustedOne
var newNumbToPlayTwo = adjustedTwo
func playMoreWithNewNumbers...
}
Is this possible or am I off the rails?
func increaseNumbers(numOne: Double, numTwo: Double) -> (Double, Double) {
var numOneIncreased = numOne + 2
var numTwoIncreased = numTwo + 5
func playWithNumbersMore(warpOne: Double, warpTwo: Double) -> (Double, Double) {
if warpOne < 50 {
var adjustedOne = warpOne + 16.5
var adjustedTwo = warpTwo + 20.8
return (adjustedOne, adjustedTwo)
}
let result = playWithNumbersMore(warpOne: numOneIncreased, warpTwo: numTwoIncreased)
numOneIncreased = result.0 // result.0 is a adjustedOne
numTwoIncreased = result.1 // result.1 is a adjustedTwo
return result
}
This is how you can use the result of playWithNumbersMore data.
Am I wrong or it is what a are look for?

Sum and For loop together in Swift

I want to know how many common characters in the given sets.
Input: J = "aA", S = "aAAbbbb"
Output: 3
In the python solution for this as follows:
lookup = set(J)
return sum(s in lookup for s in S)
I have following solution in Swift it works, but it looks too wordy. I want to learn shorter way of it.
class Solution {
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J) ;
var sy = 0;
for c in S
{
if lookup.contains(c)
{
sy += 1;
}
}
return sy;
}
}
As a small variation of Sh_Khan's answer you can use reduce to
count the number of matching elements without creating an intermediate
array:
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J)
return S.reduce(0) { lookup.contains($1) ? $0 + 1 : $0 }
}
In Swift 5 there will be a count(where:) sequence method for this purpose,
see SE-0220 count(where:).
You can try
class Solution {
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J)
return S.filter { lookup.contains($0) }.count
}
}

where do i go from here? swift

func step(_ g: Int, _ m: Int, _ n: Int) -> (Int, Int)? {
var z = [m]
var x = m
var y = n
while x < y {
x += 1
z += [x]
}
for i in z {
var k = 2
while k < n {
if i % k != 0 && i != k {
}
k += 1
}
}
print(z)
return (0, 0)
}
print (step(2, 100, 130))
so it currently returns the set of numbers 100-130 in the form of an array. the overall function will do more than what i am asking about but for now i just want to create an array that takes the numbers 100-130, or more specifically the numbers x- y and returns an array of prime. the if i%k part need the help. yes i know it is redundant and elongated but im new at this. that being said try to only use the simple shortcuts.
that being said i would also be ok with examples of ways to make it more efficient but im going to need explanations on some of it because.. well im new. for context assume if only been doing this for 20-30 days (coding in general)
you can do this:
let a = 102
let b = 576 // two numbers you want to check within
/**** This function returns your array of primes ****/
func someFunc(x: Int, y: Int) -> [Int] {
var array = Array(x...y) // This is a quick way to map and create array from a range . /// Array(1...5) . ---> [1,2,3,4,5]
for element in array {
if !isPrime(n: element) { // check if numberis prime in a for loop
array.remove(at: array.index(of: element)!) // remove if it isnt
}
}
return array
}
someFunc(x: a, y: b) //this is how you call this func. someFunc(x: 4, y: 8) ---> [5, 7]
// THis is a supporting function to find a prime number .. pretty straight forward, explanation in source link below.
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
var i = 2
while i*i <= n {
if n % i == 0 {
return false
}
i = i + 1
}
return true
}
Source: Check if a number is prime?
Firstly, it's a good idea to separate out logic into functions where possible. E.g. Here's a generic function for calculating if a number is prime (adapted from this answer):
func isPrime<T>(_ n: T) -> Bool where T: BinaryInteger {
guard n > 1 else {
return false
}
guard n > 3 else {
return true
}
var i = T(2)
while (i * i) <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
To get the numbers by step, Swift provides the stride function. So your function can simplify to:
func step(_ g: Int, _ m: Int, _ n: Int) -> (Int, Int)? {
let z = stride(from: m, to: n, by: g).filter { isPrime($0) }
print(z)
return (0, 0)
}
To explain, stride will return a Sequence of the numbers that you want to step through, which you can then filter to get only those that return true when passed to the function isPrime.
By the way, your example of print(step(2, 100, 130)) should print nothing, because you'll be checking all the even numbers from 100 to 130, which will obviously be non-prime.
I'd also recommend that you don't use single-letter variable names. g, m, n and z aren't descriptive. You want clarity over brevity so that others can understand your code.
This returns an array of primes between 2 numbers:
extension Int {
func isPrime() -> Bool {
if self <= 3 { return self == 2 || self == 3 }
for i in 2...self/2 {
if self % i == 0 {
return false
}
}
return true
}
}
func getPrimes(from start: Int, to end: Int) -> [Int] {
var primes = [Int]()
let range = start > end ? end...start : start...end
for number in range {
if number.isPrime() { primes.append(number) }
}
return primes
}
In the extension you basically loop through every number in between 2 and selected number/2 to check if its divisible or not and return false if it is, else it will return true.
The getPrimes() basically takes in 2 numbers, if the start number is higher than the end number they switch places (a failsafe). Then you just check if the number is prime or not with help of the extension and append the value to the array if it is prime.
func step(_ steps: Int, _ start: Int, _ end: Int) {
var primes = [Int]()
var number = start
repeat {
if number.isPrime() { primes.append(number) }
number+=steps
} while number <= end
}
Here is another function if you want to take steps in the difference higher than 1

Swift compilation time with nil coalescing operator

After reading of the article about swift compiling time. I am interested in why usage of more than 2 sequence coalescing operator increase compilation time significantly.
Example:
Compilation time 3.65 sec.
func fn() -> Int {
let a: Int? = nil
let b: Int? = nil
let c: Int? = nil
return 999 + (a ?? 0) + (b ?? 0) + (c ?? 0)
}
Compilation time 0.09 sec.
func fn() -> Int {
let a: Int? = nil
let b: Int? = nil
let c: Int? = nil
var res: Int = 999
if let a = a {
res += a
}
if let b = b {
res += b
}
if let c = c {
res += c
}
return res
}
I'm almost certain that this has to do with type inference. When interpreting all of those + and ?? operators the compiler is doing a lot of work behind the scenes to infer the types of those arguments. There are around thirty overloads for the + operator alone and when you chain several of them together you are making the compiler's job much more complicated than you might think.

How to handle closure recursivity

Here's a very simple recursive function:
func lap (n: Int) -> Int {
if n == 0 { return 0 }
return lap (n - 1)
}
If I want to convert it as closure:
let lap = {
(n: Int) -> Int in
if n == 0 { return 0 }
return lap (n - 1)
}
I got a compiler error: "Variable used within its own initial value"
you can workaround it with two step assignment
var lap : (Int) -> Int!
lap = {
(n: Int) -> Int in
if n == 0 { return 0 }
return lap(n - 1)
}
or you can use Y combinator
func Y<T, R>( f: (T -> R) -> (T -> R) ) -> (T -> R) {
return { t in f(Y(f))(t) }
}
let lap = Y {
(f : Int -> Int) -> (Int -> Int) in
return { (n : Int) -> Int in return n == 0 ? 0 : f(n - 1) }
}
// with type inference
let lap2 = Y {
f in { n in n == 0 ? 0 : f(n - 1) }
}
This is a workaround of the memory leak problem that #zneak found (It doesn't have memory leak but captured the wrong value)
func f(n: Int) {
var f = Foo()
var lap: #objc_block (Int)->Int = { $0 }
var obj: NSObject = reinterpretCast(lap)
lap = {
[weak obj] (n: Int) -> Int in // unowned will cause crush
if n == 0 { return 0 }
println(f)
var lap2 : #objc_block (Int)->Int = reinterpretCast(obj)
return lap2 (n - 1)
}
lap(n)
}
for i in 0..<5 {
f(i)
}
class Foo {
init() {
println("init");
}
deinit {
println("deinit")
}
}
EDIT This has been resolved with Swift 2 using nested functions. Apple suggests this code:
func f(n: Int) {
func lap(n: Int) -> Int {
if n == 0 { return 0 }
print(n)
return lap(n - 1)
}
lap(n)
}
for i in 0..<1000000 { f(i) }
Although this is not obvious from the current example, so-called local functions capture the locals of the enclosing scope.
Using a location function does not leak, whereas a closure would. However, clearly, lap can't be reassigned in this case.
I received an email from Apple's Joe Groff stating that they still plan on making it possible to capture closures as weak and mutable variables at a later point. This does confirm, however, that there's no way to do it right now except with a local function.
Your current solution has a memory leak in it: lap's closure has a strong reference to itself, meaning that it cannot ever be released. This can easily be verified by launching the following program with the Leaks instrument attached:
import Foundation
func f(n: Int) {
var lap: (Int)->Int = { $0 }
lap = {
(n: Int) -> Int in
if n == 0 { return 0 }
println(n)
return lap (n - 1)
}
lap(n)
}
for i in 0..<1000000 {
f(i)
}
Unfortunately, as the explicit capture syntax cannot be applied to closure types (you get an error that says "'unowned' cannot be applied to non-class type '(Int) -> Int'"), there appears to be no easy way to achieve this without leaking. I filed a bug report about it.
Here's a response to my own question:
var lap: (Int)->Int = { $0 }
lap = {
(n: Int) -> Int in
if n == 0 { return 0 }
println(n)
return lap (n - 1)
}
What about this:
let lap = {(Void) -> ((Int) -> Int) in
func f(n: Int) -> Int {
print(n)
return n == 0 ? 0 : f(n - 1)
}
return f
}()
It's quite simple, I've just defined a recursive local function inside a closure which returns the function.
However, I have to say that the answer from #Bryan Chen about the Y combinator is awesome.
I had the same problem and was not statisfied with anything that was out there, so I created a library and made it available on GitHub.
Using this library (with Swift 3.0) your code would look like this:
let lap = Recursion<Int, Int> { (n, f) in
n == 0 ? 0 : f(n-1)
}.closure