juan_gandhi: (Default)
"Задача такая: есть Seq[Seq[String]]; сделать interleave. Я нарисовал tailrec версию, но... но надо было очередь мне впендюрить, конечно, а то не эффективно ж. Ну все равно. Работает."

Так это, меня зацепило, как же это на самом-то деле делать, чтобы эффективно и на структурах данных. Лег спать, перед сном подумал, и быстро понял.

We are having a special kind of tree: a root, and a bunch of branches, each one linear. Now we need to do BFS. For BFS we need a queue. That's the solution.
juan_gandhi: (Default)
Problem: given a list of pairs of nonnegative integers, where pairs represent edges of a directed graph, check if the graph is a linear order.

Solutions:
def isLinear(src: List[(Int, Int)]): Boolean = {
  val m = src.toMap.withDefaultValue(-1)
  val tails = m.values.toSet
  src.isEmpty || (src.size == m.size) && {
    src find { case (a,_) => !tails(a) } match {
      case Some((start,_)) =>
        val visited =
          Stream.iterate(start)(m).takeWhile(0 <=).take(src.size+2)
        visited.length == src.size + 1
      case None => false
    }
  }
}

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

November 2025

S M T W T F S
       1
23456 7 8
9 1011 12 1314 15
16171819 20 2122
23 24 2526272829
30      

Syndicate

RSS Atom

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Nov. 27th, 2025 12:12 pm
Powered by Dreamwidth Studios