I need a function which finds the left and right neighbor-element within an integer-array, based upon a given index. If the given element is 0, then it shall return largest index as left neighbor. When the given index is the largest index, then it shall return 0 as right neighbor.
Here's the solution, I have created:
// ------- Actual function ----------------------
func findNeighborsWithin(array: [Int], viewingElement index: Int) -> [Int] {
var neighbors = [Int]()
if index > 0 {
neighbors.append(index - 1)
} else {
neighbors.append(array.count - 1)
}
if index < array.count - 1 {
neighbors.append(index + 1)
} else {
neighbors.append(0)
}
return neighbors
}
// ------------------------------------------------
// Testing/Example-usage
let array = [0, 1, 2, 4, 8, 16, 32, 64]
print("Index 0 -> \(findNeighborsWithin(array: array, viewingElement: 0))")
print("Index \(array.count - 1) -> \(findNeighborsWithin(array: array, viewingElement: array.count - 1))")
for i in 0..<5 {
let randInt = Int.random(in: 0..<array.count)
print("Index \(randInt) -> \(findNeighborsWithin(array: array, viewingElement: randInt))")
}
/*
Index 0 -> [7, 1]
Index 7 -> [6, 0]
Index 4 -> [3, 5]
Index 6 -> [5, 7]
Index 3 -> [2, 4]
Index 5 -> [4, 6]
Index 6 -> [5, 7]
*/
What's are your thoughts on my solution, including naming and formatting? Is there a better solution? How can it become improved? What would you have done differently and why?