Search code examples
listscalaimmutabilityscala-2.10

Scala creating a list with some data at specific indices and 0 at all the rest indices


I have a list named positiveDays which contains values (2,4,6) and I want to create a list DaysDetails having value of 1 at all the positiveDays indices and 0 at the rest indices.

Example -

positiveDays(2,4,6)

O/p List -> DaysDetails(0,0,1,0,1,0,1)

Can anyone suggest me a way to do that without use of var?


Solution

  • This should work (only when positiveDays List is not empty):

    val positiveDays = List(2,4,6)
    List.tabulate(1 + positiveDays.last) {
      pos => if (positiveDays.contains(pos)) 1 else 0 
    }
    

    To correctly handle the case when positiveDays is empty you could use:

    List.tabulate(positiveDays.lastOption.fold(0)(1 + _)) {
      pos => if (positiveDays.contains(pos)) 1 else 0 
    }