I have 2 inputs adress
and street
. I need to make 2 arrays size street
. One array with odd numbers and another with even numbers. Than i need to reverse odd array. Than I need to check what array contains input adress
and to return same index element from another array.
This is error what is show to me:
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file test/solution.swift, line 6
func overTheRoad(address: Int, street: Int) -> Int {
var odd = Array(stride(from: 1, through: street * 2, by: 2))
let even = Array(stride(from: 2, through: street * 2, by: 2))
odd.reverse()
if address % 2 == 0{
let index = even.firstIndex(of: address)!
return odd[index]
}else{
let index = odd.firstIndex(of: address)!
return even[index]
}
}
This is how to suppose work:
You’ve just moved into a perfectly straight street with exactly n identical houses on either side of the road. Naturally, you would like to find out the house number of the people on the other side of the street. The street looks something like this:
Street
1| |6
3| |4
5| |2
you
Evens increase on the right; odds decrease on the left. House numbers start at 1 and increase without gaps. When n = 3, 1 is opposite 6, 3 opposite 4, and 5 opposite 2.
Example (address, n –> output)
Given your house number address and length of street n, give the house number on the opposite side of the street.
1, 3 --> 6
3, 3 --> 4
2, 3 --> 5
3, 5 --> 8
2
Answers
}
Instead of force unwrapping, you should unwrap it safely with a guard let (or if let) statement. In case of no address value is found in the array, you can return nil.
Adding on to Hüsamettin Eyibil’s answer, there one big thing that could be improved here: You’re generating 2 arrays here, only to query them for a single value and discard the rest. Half the time, each of them isn’t even used a single time!
There’s actually a pretty simple, closed-form math solution:
Here I chose to
fatalError
on invalid input, but it might make sense to just returnnil
instead.