Skip to content

Instantly share code, notes, and snippets.

View chenharryhua's full-sized avatar

Harry Chen chenharryhua

  • Tabcorp
  • Melbourne Australia
View GitHub Profile
for {
d <- IO.deferred[Int]
a <- d.complete(1)
b <- d.complete(2)
} yield (a, b)
import fs2.Stream
val r1 = Stream.resource(Resource.make(IO.println("acquire 1"))(_ => IO.println("release 1")))
val r2 = Stream.bracket(IO.println("acquire 2"))(_ => IO.println("release 2"))
val ss =
r1.onFinalizeWeak(IO.println("final 1"))
.flatMap(_ => r2.onFinalize(IO.println("final 2"))).evalMap(_ => IO.println("do work"))
++ fs2.Stream.eval(IO.println("----")) ++ fs2.Stream.sleep[IO](2.second)
ss.compile.drain.unsafeRunSync()
val a1 = for {
_ <- IO.println("a1")
_ <- IO.sleep(5.seconds)
} yield 1
val a2 = for {
_ <- IO.println("a2")
_ <- IO.sleep(5.seconds)
} yield 2
import better.files._
object GridlandMetro extends App {
// https://www.hackerrank.com/challenges/gridland-metro/problem
def gridlandMetro(n: Int, m: Int, k: Int, track: Array[Array[Long]]): Long = {
val total = n * m.toLong
val exist = track
.groupBy(_(0))
.map { case (_, arr) =>
// https://www.hackerrank.com/challenges/bfsshortreach/problem
def height(neighbors: Map[Int, Set[Int]], level: Int, stack: Set[Int], rst: Map[Int, Int]): Map[Int, Int] =
if (stack.isEmpty) rst
else {
val known = stack.filterNot(rst.contains).map((_ -> level)).toMap ++ rst
val set = stack.flatMap(neighbors.get).flatten.filterNot(known.contains)
height(neighbors, level + 1, set, known)
}
// https://www.hackerrank.com/challenges/journey-to-the-moon/problem
object journeyToMoon {
final case class DisjointSet(ds: Map[UUID, Set[Int]] = Map.empty) {
def find(v1: Int, v2: Int): Vector[UUID] =
ds.flatMap { case (k, v) => if (v.contains(v1) || v.contains(v2)) Some(k) else None }.toVector
def exists(v: Int): Boolean = ds.exists(_._2.contains(v))
import cats.syntax.all._
import cats.data._
import cats._
val f = Validated.invalid[Eval[String], Eval[Int]](Eval.always { println("eval fail"); "oops" })
val s = Validated.valid[Eval[String], Eval[Int]](Eval.always { println("eval succ"); 1 })
val combine: Validated[Eval[String], Eval[Int]] = f *> s
val res = combine.bimap(_.value, _.value) match {
// https://www.hackerrank.com/challenges/insertion-sort/problem
def insertionSort(arr: Array[Int]): Int =
arr
.foldLeft((TreeMap.empty[Int, Int], 0L)) { case ((tm, s), (v)) =>
val d = tm.rangeFrom(v + 1).values.sum
val up = tm.updatedWith(v) {
case Some(x) => Some(x + 1)
case None => Some(1)
}
/*
https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem
*/
def subs(str: String): List[String] = str.inits.flatMap(_.tails.toList.init.map(_.sorted)).toList
subs(str).groupBy(identity).map(x => x._2.size).map(x => (x-1)*x/2).sum
implicit def eqEnum[E <: Enumeration](implicit ev: shapeless.Witness.Aux[E]): Eq[E#Value] =
(x: E#Value, y: E#Value) => ev.value(x.id) == ev.value(y.id)