Last active
March 18, 2020 00:21
-
-
Save erikthered/874dd11be9e38ad448b8f3b528ec24c9 to your computer and use it in GitHub Desktop.
CSV merge for coding test
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
package main | |
import ( | |
"encoding/csv" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"strconv" | |
) | |
func main() { | |
file1, err := os.Open("input1.csv") | |
if err != nil { | |
log.Fatalln("Couldn't open CSV file", err) | |
} | |
r1 := csv.NewReader(file1) | |
file2, err := os.Open("input2.csv") | |
if err != nil { | |
log.Fatalln("Couldn't open CSV file", err) | |
} | |
r2 := csv.NewReader(file2) | |
outputFile, err := os.Create("./output.csv") | |
if err != nil { | |
log.Fatal("Couldn't create output file", err) | |
} | |
writer := csv.NewWriter(outputFile) | |
for { | |
rec1, err1 := r1.Read() | |
rec2, err2 := r2.Read() | |
if err1 == io.EOF || err2 == io.EOF { | |
break // End of file | |
} | |
if err1 != nil { | |
log.Fatal("Error parsing row in input1.csv", err1) | |
} | |
if err2 != nil { | |
log.Fatal("Error parsing row in input2.csv", err2) | |
} | |
if rec1[2] == "min_score" { | |
row := []string{rec1[0], rec1[1], rec2[1], rec2[2]} | |
if err := writer.Write(row); err != nil { | |
log.Fatal("Failed to write to output file", err) | |
} | |
} else { | |
minScore1, msErr1 := strconv.Atoi(rec1[2]) | |
minScore2, msErr2 := strconv.Atoi(rec2[2]) | |
if msErr1 != nil { | |
log.Fatal("Error parsing min_score", msErr1) | |
} | |
if msErr2 != nil { | |
log.Fatal("Error parsing min_score", msErr2) | |
} | |
var minScore int | |
if minScore1 < minScore2 { | |
minScore = minScore1 | |
} else { | |
minScore = minScore2 | |
} | |
row := []string{rec1[0], rec1[1], rec2[1], strconv.Itoa(minScore)} | |
if err := writer.Write(row); err != nil { | |
log.Fatal("Failed to write to output file", err) | |
} | |
} | |
writer.Flush() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment