scala.collection.BitSet Scala Examples

The following examples show how to use scala.collection.BitSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Huffman.scala    From bonsai   with MIT License 5 votes vote down vote up
package com.stripe.bonsai
package example

import org.github.jamm.MemoryMeter

import scala.collection.BitSet
import scala.collection.mutable.PriorityQueue
import scala.util.Random.nextGaussian

object HuffmanExample extends App {
  sealed trait HuffmanTree[+A]

  object HuffmanTree {
    case class Branch[+A](zero: HuffmanTree[A], one: HuffmanTree[A]) extends HuffmanTree[A]
    case class Leaf[+A](value: A) extends HuffmanTree[A]

    def apply[A](symbols: Map[A, Double]): HuffmanTree[A] = {
      require(symbols.nonEmpty)

      val queue = new PriorityQueue[(HuffmanTree[A], Double)]()(Ordering.by(-_._2))

      // Initialize the queue with leaf nodes.
      symbols.foreach { case (symbol, weight) =>
        queue.enqueue(Leaf(symbol) -> weight)
      }

      // Iteratively build up optimal Huffman tree.
      while (queue.size > 1) {
        val (t0, w0) = queue.dequeue()
        val (t1, w1) = queue.dequeue()
        queue.enqueue(Branch(t0, t1) -> (w0 + w1))
      }

      // Return the final tree.
      queue.dequeue()._1
    }

    implicit def huffmanTreeOps[A] = new TreeOps[HuffmanTree[A], Option[A]] {
      type Node = HuffmanTree[A]

      def root(tree: HuffmanTree[A]): Option[HuffmanTree[A]] = Some(tree)
      def children(tree: HuffmanTree[A]): Iterable[HuffmanTree[A]] = tree match {
        case Branch(l, r) => l :: r :: Nil
        case _ => Nil
      }
      def label(tree: HuffmanTree[A]): Option[A] = tree match {
        case Leaf(value) => Some(value)
        case _ => None
      }
    }
  }

  implicit class HuffmanTreeOps[T, A](tree: T)(implicit treeOps: TreeOps[T, Option[A]]) {
    import HuffmanTree.{ Branch, Leaf }
    import treeOps._

    def decode(bits: BitSet, len: Int): Vector[A] = {
      val root = tree.root.get
      val (_, result) = (0 until len)
        .foldLeft((root, Vector.empty[A])) { case ((node, acc), i) =>
          node.label match {
            case Some(value) => (root, acc :+ value)
            case None if bits(i) => (node.children.head, acc)
            case None => (node.children.iterator.drop(1).next, acc)
          }
        }
      result
    }
  }

  val symbols = Map((' ' to '~').map { symbol =>
    symbol -> math.abs(nextGaussian)
  }: _*)
  val bigTree = HuffmanTree(symbols)
  val smallTree = Tree(bigTree)

  val meter = new MemoryMeter()
  val bigTreeSize = meter.measureDeep(bigTree)
  val smallTreeSize = meter.measureDeep(smallTree)
  println(s"big tree:   ${bigTreeSize} bytes")
  println(s"small tree: ${smallTreeSize} bytes")
  println(f"${bigTreeSize / smallTreeSize.toDouble}%.1fx reduction")
} 
Example 2
Source File: BitSetDecoratorTest.scala    From scala-collection-contrib   with Apache License 2.0 5 votes vote down vote up
package scala.collection.decorators

import org.junit.{Assert, Test}

import scala.collection.BitSet

class BitSetDecoratorTest {

  import Assert.{assertEquals, assertSame}
  import BitSet.empty

  @Test
  def shiftEmptyLeft(): Unit = {
    for (shiftBy <- 0 to 128) {
      assertSame(empty, empty << shiftBy)
    }
  }

  @Test
  def shiftLowestBitLeft(): Unit = {
    for (shiftBy <- 0 to 128) {
      assertEquals(BitSet(shiftBy), BitSet(0) << shiftBy)
    }
  }

  @Test
  def shiftNegativeLeft(): Unit = {
    assertEquals(BitSet(0), BitSet(1) << -1)
  }

  @Test
  def largeShiftLeft(): Unit = {
    val bs = BitSet(0 to 300 by 5: _*)
    for (shiftBy <- 0 to 128) {
      assertEquals(bs.map(_ + shiftBy), bs << shiftBy)
    }
  }

  @Test
  def skipZeroWordsOnShiftLeft(): Unit = {
    val result = BitSet(5 * 64 - 1) << 64
    assertEquals(BitSet(6 * 64 - 1), result)
    assertEquals(6, result.nwords)
  }

  @Test
  def shiftEmptyRight(): Unit = {
    for (shiftBy <- 0 to 128) {
      assertSame(empty, empty >> shiftBy)
    }
  }

  @Test
  def shiftLowestBitRight(): Unit = {
    assertEquals(BitSet(0), BitSet(0) >> 0)
    for (shiftBy <- 1 to 128) {
      assertSame(empty, BitSet(0) >> shiftBy)
    }
  }

  @Test
  def shiftToLowestBitRight(): Unit = {
    for (shiftBy <- 0 to 128) {
      assertEquals(BitSet(0), BitSet(shiftBy) >> shiftBy)
    }
  }

  @Test
  def shiftNegativeRight(): Unit = {
    assertEquals(BitSet(1), BitSet(0) >> -1)
  }

  @Test
  def largeShiftRight(): Unit = {
    val bs = BitSet(0 to 300 by 5: _*)
    for (shiftBy <- 0 to 128) {
      assertEquals(bs.collect {
        case b if b >= shiftBy => b - shiftBy
      }, bs >> shiftBy)
    }
  }

} 
Example 3
Source File: FactoryTest.scala    From scala-library-compat   with Apache License 2.0 5 votes vote down vote up
package test.scala.collection

import org.junit.{Assert, Test}

import scala.collection.compat._
import scala.collection.{BitSet, immutable, mutable}

class FactoryTest {

  implicitly[Factory[Char, String]]
  implicitly[Factory[Char, Array[Char]]]
  implicitly[Factory[Int, collection.BitSet]]
  implicitly[Factory[Int, mutable.BitSet]]
  implicitly[Factory[Int, immutable.BitSet]]
  implicitly[Factory[Nothing, Seq[Nothing]]]

  def f[A] = implicitly[Factory[A, Stream[A]]]

  BitSet: Factory[Int, BitSet]
  Iterable: Factory[Int, Iterable[Int]]
  immutable.TreeSet: Factory[Int, immutable.TreeSet[Int]]
  Map: Factory[(Int, String), Map[Int, String]]
  immutable.TreeMap: Factory[(Int, String), immutable.TreeMap[Int, String]]

  @Test
  def streamFactoryPreservesLaziness(): Unit = {
    val factory = implicitly[Factory[Int, Stream[Int]]]
    var counter = 0
    val source  = Stream.continually { counter += 1; 1 }
    val result  = factory.fromSpecific(source)
    Assert.assertEquals(1, counter) // One element has been evaluated because Stream is not lazy in its head
  }
  @Test
  def factoriesAreReusable(): Unit = {
    def generically[M[X] <: Iterable[X]](in: M[Int], factory: Factory[Int, M[Int]]): Unit = {
      val l = Iterator(-3, -2, -1).to(factory)
      val m = in.iterator.to(factory)
      Assert.assertEquals(in, m)
    }

    generically[List](List(1, 2, 3), List)
    generically[Seq](Seq(1, 2, 3), Seq)
    generically[IndexedSeq](IndexedSeq(1, 2, 3), IndexedSeq)
    generically[Vector](Vector(1, 2, 3), Vector)
    generically[Set](Set(1, 2, 3), Set)
  }

} 
Example 4
Source File: Utils.scala    From inox   with Apache License 2.0 5 votes vote down vote up
package inox
package parsing

import scala.collection.BitSet

object Utils {

  def traverse[A](xs: Seq[Option[A]]): Option[Seq[A]] = {
    val zero: Option[Seq[A]] = Some(Seq[A]())

    xs.foldRight(zero) {
      case (Some(x), Some(xs)) => Some(x +: xs)
      case _ => None
    }
  }

  def traverse[E, A](xs: Seq[Either[E, A]]): Either[Seq[E], Seq[A]] = {
    val zero: Either[Seq[E], Seq[A]] = Right(Seq[A]())

    xs.foldRight(zero) {
      case (Right(x), Right(xs)) => Right(x +: xs)
      case (Right(_), Left(es)) => Left(es)
      case (Left(e), Right(_)) => Left(Seq(e))
      case (Left(e), Left(es)) => Left(e +: es)
    }
  }

  def either[E, A, B, R](a: Either[Seq[E], A], b: Either[Seq[E], B])(f: (A, B) => R): Either[Seq[E], R] = {
    (a, b) match {
      case (Left(eas), Left(ebs)) => Left(eas ++ ebs)
      case (Left(eas), _) => Left(eas)
      case (_, Left(ebs)) => Left(ebs)
      case (Right(xa), Right(xb)) => Right(f(xa, xb))
    }
  }

  def plural(n: Int, s: String, p: String): String = {
    if (n == 1) s else p
  }

  def classify[A, B, C](xs: Seq[A])(f: A => Either[B, C]): (Seq[B], Seq[C]) = {
    val mapped = xs.map(f)
    val lefts = mapped.collect {
      case Left(x) => x
    }
    val rights = mapped.collect {
      case Right(x) => x
    }
    (lefts, rights)
  }

  def toFraction(whole: String, trailing: String, repeating: String): (BigInt, BigInt) = {

    type Fraction = (BigInt, BigInt)

    def add(a: Fraction, b: Fraction): Fraction = {
      val (na, da) = a
      val (nb, db) = b

      (na * db + nb * da, da * db)
    }

    def normalize(a: Fraction): Fraction = {
      val (na, da) = a

      val gcd = na.gcd(da)

      (na / gcd, da / gcd)
    }

    val t = BigInt(10).pow(trailing.length)

    val nonRepeatingPart: Fraction = (BigInt(whole + trailing), t)
    if (repeating.length == 0) {
      normalize(nonRepeatingPart)
    }
    else {
      val r = BigInt(10).pow(repeating.length)
      val sign = if (whole.startsWith("-")) -1 else 1
      val repeatingPart: Fraction = (sign * BigInt(repeating), (r - 1) * t)

      normalize(add(nonRepeatingPart, repeatingPart))
    }
  }
}