Skip to content

Instantly share code, notes, and snippets.

@moflo
Created February 7, 2019 16:39
Show Gist options
  • Save moflo/014d540808f4242c2fcd7b1287effb6a to your computer and use it in GitHub Desktop.
Save moflo/014d540808f4242c2fcd7b1287effb6a to your computer and use it in GitHub Desktop.
import UIKit
// CSV column filtering
// Generate function which takes CSV string and column names as input and return array of sums of column data
// For example, a string of CSV data includes a header row, and columns consisting of Double and Strings.
func csvSum(_ csv:String,_ names: String) -> [Double]? {
let rows :[String] = csv.split(separator: "\n").map { String($0) }
let header :[String] = rows[0].split(separator: ",").map { String($0) }
var cols = [String:[String]]()
for j in 0..<header.count {
let col_name = String(header[j])
cols[col_name] = [String]()
for i in 1..<rows.count {
let row_data = rows[i].split(separator: ",")[j]
cols[col_name]!.append( String(row_data) )
}
}
let selected_cols = names.split(separator: ",").map { return String($0) }
let cols_filtered = cols.filter { selected_cols.contains($0.key) }
var cols_double = [String:Double]()
for (k,v) in cols_filtered {
var data = [Double]()
for d in v {
let d_s :Double = Double(d) ?? 0.0
data.append(d_s)
}
cols_double[k] = data.reduce(0.0, +)
}
var sum_ordered :[Double]? = nil
for c in selected_cols {
if let sum = cols_double[c] {
if sum_ordered == nil { sum_ordered = [sum] }
else { sum_ordered!.append(sum) }
}
}
return sum_ordered
}
let CSVString = "A,B,C,D\n2.1,1.0,Abc,2.0\n1.9,1.0,Cba,1.0"
let names = "A,B,D"
let sums = csvSum(CSVString,names)
print(sums == [4.0,2.0,3.0])
// Palindrome comparison
// Determine largest palindrome of the product of numbers between 0 and 999 (ie., three digits)
func isPalindromeString(_ i:Int,_ j:Int) -> Int {
// Use String methods to compare Int digits as characters...
let s = String("\(i*j)")
let len = s.count
let mid1 = s.index(s.startIndex, offsetBy: len/2)
let left = s[s.startIndex...mid1]
let s2 = String(s.reversed())
let mid2 = s2.index(s2.startIndex, offsetBy: len/2)
let right = s2[s2.startIndex...mid2]
return left == right ? i*j : 0
}
func maxPal() -> Int {
for i in stride(from: 999, to: 0, by: -1) {
for j in stride(from: 999, to: 0, by: -1) {
let prod = isPalindromeString(i,j)
if (prod > 0) { return prod }
}
}
return 0
}
print(maxPal())
// Data label transpose
// Given two arrays, one of labels and one of data URLs, return a dictionary of labels and matching URLs
func genLabelDict(_ labels: [String],_ data:[String]) -> [String:[String]] {
var dict = [String:[String]]()
for (i,v) in labels.enumerated() {
if (dict[v] == nil) { dict[v] = [data[i]] }
else { dict[v]!.append(data[i]) }
}
return dict
}
let labels = [ "cat","dog","cat","fox"]
let data = ["URL1","URL2","URL3","URL4"]
print(genLabelDict(labels,data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment