Skip to content

Instantly share code, notes, and snippets.

@vikaskore
Last active August 7, 2019 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikaskore/75b1499235d99924511d47f14dd69718 to your computer and use it in GitHub Desktop.
Save vikaskore/75b1499235d99924511d47f14dd69718 to your computer and use it in GitHub Desktop.
Circular array, iterate to all element in array starting at any given index
//
// CircularArrayViewController.swift
// Samples
//
// Created by VikasK on 22/07/19.
// Copyright © 2019 Vikaskore Software. All rights reserved.
//
import UIKit
class CircularArrayViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var testArray = [1,2,3,4,5,6,7,8,9]
let reOrderedArray = rotate(array: &testArray, index: 8)
print("Reordered Array Elements: \(reOrderedArray)")
}
func rotate(array: inout [Int], index: Int) -> Array<Int> {
//The resulting array will be same array
if index == 0 || array.count <= 1 {
return array
}
// Calculate the effective number to re-arrange
let length = array.count
let rotations = (length + index) % length
let leftPart = Array(array[0..<rotations])
let rightPart = Array(array[rotations..<length])
array = rightPart + leftPart
return array
}
}
/* Output
rotate(array: &testArray, index: 8)
Reordered Array Elements: [9, 1, 2, 3, 4, 5, 6, 7, 8]
rotate(array: &testArray, index: 3)
Reordered Array Elements: [4, 5, 6, 7, 8, 9, 1, 2, 3]
rotate(array: &testArray, index: 0)
Reordered Array Elements: [1, 2, 3, 4, 5, 6, 7, 8, 9]
rotate(array: &testArray, index: 10)
Reordered Array Elements: [2, 3, 4, 5, 6, 7, 8, 9, 1]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment