I am trying to populate a list of tuples however only one element is being added to the list. I have two functions. def f
which generates the tuple to be added to the List of tuples (and works fine because I tested that), and def iterator
which is supposed to be populating the list.
def mainFn(): List[(Int, Int, Set[Int])] = {
def myList = List[(Int, Int, Set[Int])]()
//t: tuple (r,c)
def f(t:(Int,Int)): List[(Int, Int, Set[Int])] = {
//if element is 0 add hypothesis otherwise move to next element
if (sudoku.grid(t._1)(t._2) == 0){
(t._1,t._2,hypothesis(t._1,t._2))::Nil
}
else Nil
}
def iterator(t:(Int,Int),li : List[(Int, Int, Set[Int])]): List[(Int, Int, Set[Int])] = {
if (t==(0,0)) li ++ f(t)
else if (t._2 < 9) li ++ f((t._1,t._2+1))//shifting to the element on the right
else li ++ f((t._1+1, 0))//shifting to the next row
}
iterator((0,0),myList)
}
I have a Sudoku grid of the form List[List[Int]]
and I want to visit each cell of the grid and if the element is 0 generate a tuple of the form (Int, Int, Set[Int])
otherwise move to the next cell. I cannot however use any looping structures, only recursive calls are permitted. I cannot figure out how to recursively call iterator so that it loops all the way through the sudoku grid.
I ended up using a different approach (still quite similar though):
def allHypothesis(): List[(Int, Int, Set[Int])] = {
def myList = List[(Int, Int, Set[Int])]()
def f(t:(Int,Int), li: List[(Int, Int, Set[Int])]) : List[(Int, Int, Set[Int])] ={
val (row, column) = t;
if (row == 8 && column == 9) li
else if (column == 9) f((row+1,0),li)
else if (sudoku.grid(row)(column)==0) f((row,column+1), li:+(row,column,hypothesis(row, column)))
else f((row,column+1),li)
}
f((0,0),myList)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.