Skip to content

Instantly share code, notes, and snippets.

@aurorapar
Last active January 29, 2019 04:46
Show Gist options
  • Save aurorapar/5d3778145ed071dd46efa8b387d00237 to your computer and use it in GitHub Desktop.
Save aurorapar/5d3778145ed071dd46efa8b387d00237 to your computer and use it in GitHub Desktop.
import UIKit
// Assuming this is the values, not the even indexes
func sumOfEvens(array: [Int]) -> Int
{
var total = 0
for value in array
{
if value % 2 == 0
{
total += value
}
}
return total
}
func rangeArray(x: Int, y: Int) -> [Int]
{
var total = [Int]()
if x > y
{
return total
}
for index in x...y
{
total.append(index)
}
return total
}
func averages(array: [Double]) -> (mean: Double, median: Double, mode: Double)
{
var mean = 0.0
var median = 0.0
var mode = 0.0
var sortedArray = array
sortedArray.sort()
median = sortedArray[ sortedArray.count / 2 ]
var counts = [Double: Int]()
for value in sortedArray
{
switch counts[value]
{
case nil:
counts[value] = 0
default:
counts[value] = counts[value] != nil ?? counts[value] + 1 : 0
}
mean += value
}
mean = mean / Double(sortedArray.count)
var highest = 0
for (item, amount) in counts
{
if amount > highest
{
mode = item
highest = amount
}
}
}
var mySums = sumOfEvens(array: [12, 4, 3, 5, 4, 6, 9, 7, 17, 13])
print(mySums)
mySums = sumOfEvens(array: [1, 5, 9, 13, 11, 7, 9, 3])
print(mySums)
mySums = sumOfEvens(array: [8, 4, 6, 8, 4, 6, 4, 6, 8])
print(mySums)
mySums = sumOfEvens(array: [1])
print(mySums)
mySums = sumOfEvens(array: [2])
print(mySums)
mySums = sumOfEvens(array: [])
print(mySums)
var myArrays = rangeArray(x: 12,y: 17)
print(myArrays)
myArrays = rangeArray(x: -2,y: 7)
print(myArrays)
myArrays = rangeArray(x: 12,y: 12)
print(myArrays)
myArrays = rangeArray(x: 17,y: 12)
print(myArrays)
myArrays = rangeArray(x: -2,y: -4)
print(myArrays)
myArrays = rangeArray(x: 0,y: 0)
print(myArrays)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment