Sum and For loop together in Swift - 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
}
}

Related

Terminated by signal 4

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!

How can I extract numbers from string in Swift in a specific way

I'm struggling to extract numbers from a string in Swift. I'm doing the following:
let expression: String = "abc123aa223bb45"
for (indx, ch) in expression.enumerated() {
if ch.isLetter { continue }
else if ch.isNumber {
var val: Int = 0
while(indx < expression.count && ch.isNumber){
val = val * 10 + (ch.asciiValue - 48)
//how can I proceed and increment both indx and ch ...
}
// here I'm going to do smthing with every extracted number
}
}
Can somebody help me finish this problem I've reached?
I also use the extension
extension Character {
var asciiValue: Int {
get {
let s = String(self).unicodeScalars
return Int(s[s.startIndex].value)
}
}
}
as you can see in the posted fragment of code
The following code snippet will extract numbers from a String
let expression: String = "abc123aa223bb45"
let stringArray = expression.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
if let number = Int(item) {
print(number)
}
}
You could also make an extension of Int that has a function like
extension Int {
static func parse(from string: String) -> Int? {
return Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
}
}
and can be use like this
let expression: String = "abc123aa223bb45"
if let number = Int.parse(from: expression) {
print(number)
}
I'm trying to write a program that evaluates expression with braces and operators: ^,+,-,/,*
But I'm having some issues ( I've done this many times with C++ and C# but I cannot manage to do it with swift. It really gives me a huge headache ):
import Foundation
extension Character {
var asciiValue: Int {
get {
let s = String(self).unicodeScalars
return Int(s[s.startIndex].value)
}
}
}
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Double, power: Int) -> Double {
return (pow(Double(radix), Double(power)))
}
func calc(a: Double, b: Double, o: Character) -> Double {
switch o {
case "+":
return a + b
case "-":
return a - b
case "/":
return a / b
case "*":
return a * b
case "^":
return a ^^ Int(b)
default:
return 0
}
}
func nice(o: Character) -> Int {
if o == "-" || o == "+" { return 1 }
if o == "*" || o == "/" { return 2 }
if o == "^" { return 3 }
return 2020
}
func evaluate(expression: String) -> Double {
var vals = [Double]()
var ops = [Character]()
for (indx, ch) in expression.enumerated() {
if ch == " " { continue }
else if ch == "(" { ops.append(ch) }
else if ch.isNumber {
var val: Int = 0
while(indx < expression.count && ch.isNumber){
val = val * 10 + ch.asciiValue - 48 // gives strange error
//TODO increment indx and ch
}
vals.append(Double(val))
} else if ch == ")" {
while !ops.isEmpty && ops.last != "(" {
let val_2: Double = vals.popLast()!
let val_1: Double = vals.popLast()!
let op: Character = ops.popLast()!
vals.append(calc(a: val_1, b: val_2, o: op))
}
if !ops.isEmpty { _ = ops.popLast() } // opening brace
} else {
while(!ops.isEmpty && nice(o: ops.last!) >= nice(o: ch)){
let val_2: Double = vals.popLast()!
let val_1: Double = vals.popLast()!
let op: Character = ops.popLast()!
vals.append(calc(a: val_1, b: val_2, o: op))
}
ops.append(ch);
}
}
while !ops.isEmpty {
let val_2: Double = vals.popLast()!
let val_1: Double = vals.popLast()!
let op: Character = ops.popLast()!
vals.append(calc(a: val_1, b: val_2, o: op))
}
return vals.last!
}
let exp: String = "2^3+(2+3)"
print(evaluate(expression: exp))

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

Nicer syntax for ternary with a let?

Is there a nicer way to do the assignment to DEF in the following example? I want to convert type A to Type B, but still preserve the nil possibility whenever I can.
Can't seem to stumble into a better way of doing this, however. Suggestions?
class ABC {
var DEF: Int?
func X (someValue: Int8?) {
DEF = someValue != nil ? Int(someValue) : nil
}
}
Swift 1:
class ABC {
var DEF: Int?
func X (someValue: Int8?) {
DEF = someValue.map{Int($0)}
}
}
Swift 2:
class ABC {
var DEF: Int?
func X (someValue: Int8?) {
DEF = someValue.map(Int.init)
}
}
map() takes an optional, unwraps it, and applies a function to it. If the optional resolves to nil, map() returns nil.
You are describing optional map:
var i: Int? = 2
let j = i.map { $0 * 2 } // j = .Some(4)
i = nil
let k = i.map { $0 * 2 } // k = nil
Think of this map like array or other collection map, where optionals are collections that have either zero (nil) or one (non-nil) element.
Note, if the operation you want to perform itself returns an optional, you need flatMap to avoid getting a double-optional:
let s: String? = "2"
let i = s.map { Int($0) } // i will be an Int??
let j = s.flatMap { Int($0) } // flattens to Int?

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