1.

You are on a two-dimensional infinite grid where you can move in any of the eight directions (x,y) to (x-1, y-1), (x-1, y), (x-1, y+1), (x , y-1), (x , y+1), (x+1, y-1), (x+1, y) , (x+1, y+1).

Answer»

You are given a list of points to cover and the order in which you must do so. Write an ios Swift 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 Swift to solve this given problem is given below:

import Foundationclass 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) }}


Discussion

No Comment Found