// https://developer.apple.com/documentation/foundation import Foundation // Foundation is a framework that provides a base layer of functionality // Literally everything in Swift is built on top of Foundation // Read the file /** - Parameters: - file: The file to be read - Returns: The contents of the file as a string */ func openFile(_ file: String) -> String { var text = "" do { text = try String(contentsOfFile: file, encoding: .utf8) } catch { print("Error reading file") } return text } /** - Parameters: - text: The text to be parsed - Returns: An array of dictoinaries representing the data */ func parseCSV(_ text: String) -> [[String: String]] { var data = [[String: String]]() let rows = text.components(separatedBy: "\n") let headers = rows[0].components(separatedBy: ",") for row in rows[1...] { let values = row.components(separatedBy: ",") if values.count == headers.count { var dict = [String: String]() for (index, header) in headers.enumerated() { dict[header] = values[index] } data.append(dict) } } return data } // The idea is to pair up the people who have the most in common // We have people's preferences (P1-P5, all optional), and we want to find the most likely teammates func mostLikelyTeammates(_ people:[[String: String]], _ groupSize: Int) -> [String: Int] { var teammates = [String: Int]() for (index, person) in people.enumerated() { for (index2, person2) in people.enumerated() { if index != index2 { var count = 0 for (key, value) in person { if value == person2[key] { count += 1 } } let key = "\(people[index]["Name"] ?? "John Doe"), \(people[index2]["Name"] ?? "Stan Smith")" teammates[key] = count } } } return teammates } func exportJSON(_ data: [[String: Any]], to file: String) throws { let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted) let fileURL = URL(fileURLWithPath: file) try jsonData.write(to: fileURL) print("Successfully written to \(file)") } // No duplicates (i.e. John Doe, Stan Smith is the same as Stan Smith, John Doe) var filteredTeammates = mostLikelyTeammates(parseCSV(openFile("data.csv")), 2).filter { $0.value > 0 } let sortedTeammates = filteredTeammates.filter { $0.value > 0 }.sorted { $0.value > $1.value } let jsonExportData = sortedTeammates.map { ["pair": $0.key, "count": $0.value] } do { try exportJSON(jsonExportData, to: "mostLikelyTeammates.json") } catch { print("Error exporting JSON: \(error)") }