Sha256: 0b041c89521ff9ec8b7e075fdd19208e17d2877dd5654e866e8acbd6445dd5c6

Contents?: true

Size: 1.2 KB

Versions: 396

Compression:

Stored size: 1.2 KB

Contents

import scala.annotation.tailrec

trait BaseConverter {
  def baseToInt(base: Int, s: String): Int = {
    if (s.isEmpty) throw new IllegalArgumentException("Invalid base string")

    s.foldLeft(0){case (acc, c) => accumulate(base, acc, c)}
  }

  private def accumulate(base: Int, acc: Int, c: Char) = {
    if (base <= 0) throw new IllegalArgumentException("Invalid base")
    if (!c.isDigit || c.asDigit < 0 || c.asDigit >= base)
      throw new IllegalArgumentException("Invalid base char - " + c)

    c.asDigit + (acc * base)
  }

  def intToBase(base: Int, n: Int): String = {
    if (base <= 0) throw new IllegalArgumentException("Invalid base")
    if (n < 0) throw new IllegalArgumentException("Only positive numbers supported")

    @tailrec
    def internalToBase(n: Int, acc: String): String = {
      val baseChar = ((n % base) + '0').toChar
      val accum = baseChar + acc

      n match {
        case 0 => if (acc.isEmpty) accum else acc
        case _ => internalToBase(n / base, accum)
      }
    }

    internalToBase(n, "")
  }
}

object Trinary extends BaseConverter {
  private val base = 3

  def trinaryToInt(s: String): Int = baseToInt(base, s)

  def intToTrinary(n: Int): String = intToBase(base, n)
}

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.159 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.158 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.157 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.156 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.155 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.154 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.153 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.152 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.151 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.150 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.149 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.148 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.147 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.146 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.145 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.144 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.143 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.142 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.141 tracks/scala/exercises/trinary/example.scala
trackler-2.2.1.140 tracks/scala/exercises/trinary/example.scala