The goal is to write a function that generate Gray codes for a certain value.
Currently I have this :
def gray(i: Int): List[String] = {
if(i == 0) List("")
else {
val l = gray(i - 1)
(l map {"0" + _}) ::: (l map{"1" + _})
}
}
Output for gray(3) : List(000, 001, 010, 011, 100, 101, 110, 111)
Then I have tried to construct this List with a for loop. Imagine that :
for n = 2, I will have :
def gray(i: Int): List[String] = {
(for{a <- 0 to 1
b <- 0 to 1} yield a+""+b).toList
}
for n = 3, I will have :
def gray(i: Int): List[String] = {
(for{a <- 0 to 1
b <- 0 to 1
c <- 0 to 1} yield a+""+b+""+c).toList
}
Obviously this doesn't take in account i, so I was wondering if we can build such a function which construct a custom for loop expression using i.
By construct I mean :
if i == 2, create 2 variables for the loop and yield them, if i == 3 then create 3 and yield them, etc.
Is is possible ? (I'm a beginner in Scala)
List(0,1)becausel map {"0" + _}) ::: (l map{"1" + _}will returnList("0") ::: List("1")