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

August 2025

S M T W T F S
      12
3456789
10 11 12 13141516
171819 20212223
24252627282930
31      

Syndicate

RSS Atom

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Aug. 21st, 2025 04:00 am
Powered by Dreamwidth Studios