packageadventofcode2018.day2importjava.io.FilefunrepeatCounts(s:String):Set<Int>=s.groupBy{it}.values.map{it.size}.toSet()fundifference(s1:String,s2:String):Int=s1.zip(s2,{x,y->if(x==y)0else1}).sum()funcommon(s1:String,s2:String):String=s1.zip(s2,{x,y->if(x==y)x.toString()else""}).joinToString(separator="")fun<T>pairs(xs:Collection<T>):List<Pair<T,T>>=when{xs.isEmpty()->listOf()else->{valhead=xs.first()valtail=xs.drop(1)(tail.map{headtoit})+pairs(tail)}}funmain(args:Array<String>){valfile=if(args.isEmpty())"input.txt"elseargs[0]valinput=File(file).readLines().map(String::trim)// Part 1valcounts=input.map(::repeatCounts)valnumPairs=counts.filter{s->s.contains(2)}.sizevalnumTriples=counts.filter{s->s.contains(3)}.sizeprintln("Part 1 checksum: ${numPairs * numTriples}")// Part 2valdifferentByOnePairs=pairs(input).filter{(x,y)->difference(x,y)==1}println(differentByOnePairs.map{(x,y)->common(x,y)})}
Were you also annoyed that Kotlin has .groupBy but not .frequencies?
Have you thought about looking into Sequence? You could make your pairs function lazily? Using List means you're materializing the entirety of your double for-loop right away.
The lack of frequencies didn't bother me - it's easy to add. And yes, I've been thinking for the rest of the day that I should use lazy sequences. In this case the execution time remains O(N²) but as you say the memory footprint becomes more like constant. Definitely a good practice when you can't find a better algorithm.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Enjoyed this one. My Kotlin solution:
Were you also annoyed that Kotlin has
.groupBy
but not.frequencies
?Have you thought about looking into
Sequence
? You could make your pairs function lazily? UsingList
means you're materializing the entirety of your double for-loop right away.The lack of
frequencies
didn't bother me - it's easy to add. And yes, I've been thinking for the rest of the day that I should use lazy sequences. In this case the execution time remains O(N²) but as you say the memory footprint becomes more like constant. Definitely a good practice when you can't find a better algorithm.