Last active
August 7, 2019 14:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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