Scala data structure and complexity O(1) -


today had interview scala , request was:

implement data structure fixed size n , these functionalities:

  • get(index)
  • set(index,value)
  • setall(value)

the complexity should o(1)

example:    val ds = ds(100)    ds.set(4,5)    ds.get(4) //would return  5    ds.set(1,4)    ds.setall(10)    ds.get(4) //would return  10    ds.get(7) //would return  10    ds.set(1,7)    ds.get(1) //would return  7 

please find code have sent below.
question is right solution , if there better way of doing ?

import scala.collection.mutable.hashmap  trait operations {    def get(index: int): int   def set(index: int, value: int)   def setall(value: int) }  class ds(n: int) extends operations {    var mymutablehashmap = new hashmap[int, int]().withdefaultvalue(0)    def get(index: int) = mymutablehashmap(index)    def set(index: int, value: int) = {     if (index <= n) mymutablehashmap += (index -> value)   }    def setall(value: int) = {      mymutablehashmap = new hashmap[int, int]().withdefaultvalue(value)   }  }  object task {    def main(args: array[string]): unit = {      val ds = new ds(100)      ds.set(4, 5)     ds.get(4)      println(ds.get(4)) // -> 5      ds.setall(10)     println(ds.get(4)) //-> 10     println(ds.get(7)) //-> 10     ds.set(1, 7)     println(ds.get(1)) //-> 7    }  } 

i not sure if better, think hashmap might bit of overkill. following solution might have smaller footprint , takes less code. although, rather implement more generic, should fulfill requirements mentioned.

trait operations {   def get(index: int): int   def set(index: int, value: int): unit   def setall(fill: int): unit }  class ds(size: int) extends operations {   val underlying: array[int] = new array(size)    def get(index: int): int = underlying(index)    def set(index: int, value: int): unit = underlying(index) = value    def setall(fill: int): unit = (0 until size).foreach(underlying(_) = fill) } 

alternative, might give better 'setall' complexity @ cost ...

trait operations {   def get(index: int): int   def set(index: int, value: int): unit   def setall(fill: int): unit }  class ds(size: int) extends operations {   var underlying: array[integer] = new array(size)   var default: integer = new integer(0)    def get(index: int): int = {     val result = underlying(index)     if (result == null) default else result   }    def set(index: int, value: int): unit = underlying(index) = value    def setall(fill: int): unit = {     default = fill     underlying = new array(size)   } } 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -