Of Code and Me

Somewhere to write down all the stuff I'm going to forget and then need

Phone number code puzzle November 4, 2011

Filed under: Coding,Scala — Rupert Bates @ 1:53 pm

Once upon a time I was presented with the following test in an interview:

Given a mapping of digits to an array of characters, ie.
"1"={},
"2"={"A","B","C"},
"3"={"D","E","F"},

etc.

Print out all the string permutations a given input of digits maps to.
So for instance the string “23” should return:
AD
AE
AF
BD
BE
BF
CD
CE
CF

Another way to think of this is a function that returns all the possible combinations of letters the digits could represent if they were keypresses on a standard phone keypad.

I did a pretty bad job at this when I was asked it, partly because it was quite late at night, and partly because it’s not the sort of thing you find yourself doing that often, but today I found myself with a little bit of spare time on my hands and thought I’d give it another go.

I chose to do it in Scala rather than in Java which I had used last time and of course this led to the solution being much more elegant and succinct. If fact this is exactly the sort of problem that demonstrates the value of functional programming.

import collection.immutable.{List, Map}
import java.lang.String

object PhoneNumbers extends App {
  val input = "1234"
  val data = Map(
    0 -> List("0"),
    1 -> List("1"),
    2 -> List("a", "b", "c"),
    3 -> List("d", "e", "f"),
    4 -> List("g", "h", "i"),
    5 -> List("j", "k", "l"),
    6 -> List("m", "n", "o"),
    7 -> List("p", "q", "r", "s"),
    8 -> List("t", "u", "v"),
    9 -> List("w", "x", "y", "z")
  )
  getCombinations(input.substring(0, 1), input.substring(1))
    .foreach(f => Console.println(f))

  def getCombinations(current: String, remaining: String): List[String] = {
    val vals = data(Integer.parseInt(current));
    if (remaining.length() == 0)
      return vals

    val restOfString = getCombinations(remaining.substring(0, 1), remaining.substring(1))

    vals
      .map(f => restOfString.map(f2 => f + f2))
      .flatten
  }
}

 

Using Manifests in Scala to create a new instance of type T in a generic class February 5, 2011

Filed under: Scala — Rupert Bates @ 3:41 pm

To create a new instance of T in the class

class MyClass[T]

you can use the Manifest class as follows:

class MyClass[T](implicit man: Manifest[T]) {
  // get a new instance of T
  def getNewInstance =  man.erasure.newInstance
  // get Class[T]
  def getClassT = man.erasure.asInstanceOf[Class[T]]
}

What I initially didn’t get when I was trying to use this technique was how you can use it with a constructor which takes a non implicit argument. To do this you need the following syntax:

class MyClass[T](myConstructorParam : String)(implicit man: Manifest[T]) {
  // get a new instance of T
  def getNewInstance =  man.erasure.newInstance
  // get Class[T]
  def getClassT = man.erasure.asInstanceOf[Class[T]]
}
 

error: value tools is not a member of package scala when using the scala console in IntelliJ IDEA October 20, 2010

Filed under: Error,IntelliJ,Scala — Rupert Bates @ 3:28 pm

If you get the following error whilst trying to use the scala console in Intellij IDEA:


<script>:3: error: value tools is not a member of package scala
var value: scala.tools.nsc.InterpreterSettings = _
^
<script>:4: error: value tools is not a member of package scala
def set(x: Any) = value = x.asInstanceOf[scala.tools.nsc.InterpreterSettings]
^
Exception in thread "main" java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:185)
at scala.None$.get(Option.scala:183)
at scala.tools.nsc.Interpreter.bind(Interpreter.scala:622)
at scala.tools.nsc.Interpreter$$anonfun$quietBind$1.apply(Interpreter.scala:630)
at scala.tools.nsc.Interpreter$$anonfun$quietBind$1.apply(Interpreter.scala:630)
at scala.tools.nsc.Interpreter$$anonfun$beQuietDuring$2.apply(Interpreter.scala:171)
at scala.util.control.Exception$Catch.apply(Exception.scala:79)
at scala.tools.nsc.Interpreter.beQuietDuring(Interpreter.scala:169)
at scala.tools.nsc.Interpreter.quietBind(Interpreter.scala:630)
at scala.tools.nsc.Interpreter.recordRequest(Interpreter.scala:276)
at scala.tools.nsc.Interpreter.loadAndRunReq$1(Interpreter.scala:584)
at scala.tools.nsc.Interpreter.interpret(Interpreter.scala:597)
at scala.tools.nsc.Interpreter.interpret(Interpreter.scala:575)
at scala.tools.nsc.InterpreterLoop.reallyInterpret$1(InterpreterLoop.scala:471)
at scala.tools.nsc.InterpreterLoop.interpretStartingWith(InterpreterLoop.scala:514)
at scala.tools.nsc.InterpreterLoop.command(InterpreterLoop.scala:361)
at scala.tools.nsc.InterpreterLoop.processLine$1(InterpreterLoop.scala:242)
at scala.tools.nsc.InterpreterLoop.repl(InterpreterLoop.scala:248)
at scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:558)
at scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:609)
at org.jetbrains.plugins.scala.compiler.rt.ConsoleRunner.main(ConsoleRunner.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)

You can fix it as follows:

  1. From the ‘Run’ menu click ‘Edit Configurations’
  2. Select the Scala Console run configuration and type -usejavacp in the ‘ConsoleArgs’ box
  3. Click Apply

To make this the default for all Scala ConsoleĀ  run configurations

  1. right click on the top leve Scala Console icon and select ‘Edit Defaults’
  2. Type -usejavacp in the ‘ConsoleArgs’ box
  3. Click Ok

It should now work correctly

 

How to fix the Scala interpreter on 64 bit Windows October 13, 2010

Filed under: Scala — Rupert Bates @ 2:18 pm

If you install Scala 2.8 on 64 bit Windows using the IzPack Installer and then run the interpreter it will start up and immediately close again. If you try to run the scala.bat file that launches it from a command prompt you will thenĀ see the error ‘\scala was unexpected at this time.’

This is because by default the Scala is installed in the directory C:\Program Files (x86)\scala\bin and this directory name breaks the batch script at line 19:

set _SCALA_HOME=%SCALA_HOME%

To fix it all you have to do is change this line to:

set _SCALA_HOME=”%SCALA_HOME%”

Ie. surround the %SCALA_HOME% variable with speech marks. Note that to edit this file you will need adminstrator privileges