Skip to content

Instantly share code, notes, and snippets.

@analogpotato
Created February 18, 2022 01:24
Show Gist options
  • Select an option

  • Save analogpotato/6d4ca4733b343aa665de471a56cb43d9 to your computer and use it in GitHub Desktop.

Select an option

Save analogpotato/6d4ca4733b343aa665de471a56cb43d9 to your computer and use it in GitHub Desktop.
Function returning the first non-iterative value from an array
import Foundation
var array = [1,2,1,3,5]
func arrayCalculation(_ array: [Int]) -> Int {
var dictionary: [Int:Int] = [:]
var sortedArray: [Int] = []
// With this portion of the code, I'm iterating over the array and adding the dictionary items to an array
for item in array {
dictionary[item] = (dictionary[item] ?? 0) + 1
}
//From here, I'm sorting the array of objects based on their key value, I chose this method since the original array is in ascending order, but the sort method might have to change based on the array type
let sorted = dictionary.sorted(by: {$0.key < $1.key})
// At this point, I'm appending the keys from the sorted dictionary that match a value of 1, making it so they are non-iterative
for item in sorted {
if item.value == 1 {
sortedArray.append(item.key)
}
}
//Returning the key value of the first non-iterative value which should be 2
return sortedArray.first!
}
arrayCalculation(array) // Calling the function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment