Swi Interview Questions
You are given a list of points to cover and the order in which you must do so.
Write an ios Swi code to give the shortest number of steps you can take to
achieve it. You begin from the first point of the given list.
Because the order in which the points are covered is already known, the problem is
reduced to figuring out how to calculate the distance between two points (A, B) and
the distance between two points (A, B) and the distance between two points (A, B)
and the distance between two points (A, B) and the distance between two points (A,
B) and the distance (C, D). It is worth noting that just X = abs(A-C) and Y = abs(A-C) are
important (B-D). You will progress along the diagonal while X and Y are both positive,
and X and Y will both decrease by one. When one of them reaches zero, you move on
to the next stage, reducing the remaining number by one. In other words, the total
number of steps would be equal to the maximum number of steps (X, Y)
The code in ios Swi to solve this given problem is given below:
Page 35
© Copyright by Interviewbit
import Foundation
class Solution {
func coverEveryPoint(_ X: inout [Int], _ Y: inout [Int]) -> Int {
if X.count != Y.count || X.count == 0 || X.count == 1 {
return 0
}
var dist = 0
for j in 0 ..< X.count - 1 {
let xOne = X[j]
let yOne = Y[j]
let xTwo = X[j + 1]
let yTwo = Y[j + 1]
dist += distanceFinder((xOne , yOne), (xTwo, yTwo))
}
return dist
}
func distanceFinder(_ X: (x: Int, y: Int), _ Y: (x: Int, y: Int)) -> Int {
return (abs(X.y - Y.y) - abs(X.x - Y.x)) > 0 ? abs(X.y - Y.y) : abs(X.x - Y.x)
}
}