2014-10-03 62 views
1

我的任務是使用Maple解決4x4數獨遊戲難題。我構造了一個4x4矩陣,其每個元素都是一個列表。每個列表包含數字1,2,3,4。 我的算法是找到一個只包含一個數字的網格,並使用它來消除水平和垂直網格中列表中相同的數字。爲什麼我不能在程序中改變矩陣?

這是我的代碼: 我使用了一個名爲removeElement的過程來從列表中消除一個數字,但它在消除後似乎是相同的。矩陣是不可變的嗎?如何解決它? 另外,我使用了一個名爲tester的計數器來檢查程序,看看矩陣是否可以改變。

solveSudoku := proc(M) 
local i; local j; local goAhead; local k; local index; 
local tester; 
tester:=0; 
while tester<10 do 
    i:=1; j:=1; 
    for i from 1 to 4 do 
    for j from 1 to 4 do 
     if(nops(M[i,j]) = 1) then 

      # The current matrix element has only one possibility 
      # cancel all possibilities in horizontal 

      for k from 1 to 4 do 
       #Every element of the matrix is a list 
       #I was trying to remove a number from a list 
       #the statement below DOES NOT remove number at all 
       index:= hasElement(M[i,k],op(M[i,j])); 

       if index <> -1 and k <> j then 

        removeElement(M[i,k],index); 

       end if; 
      end do: 

      # now the horizontal numbers are eliminated 
      # cancel all possibilities in vertical 
      k:=1; 
      for k from 1 to 4 do 
       index:= hasElement(M[k,j],op(M[i,j])); 
       if index <> -1 and k <> i then 

        removeElement(M[k,j],index); 

       end if; 
      end do: 

     end if; 

    end do; 
    end do; 

    tester:=tester+1; 
end do: 

print (M); 
end proc: 

這裏是remove元素過程:

removeElement := proc(L,index) 
    local boundary := index; 
     if nops(L) <> 0 then 
      return [op(1..boundary-1,L),op(boundary+1..,L)]; 
     end if; 
    return []; 
end proc; 
+1

它看起來像removeElement返回一個新的數組,而不是修改現有的。每次調用該過程時都需要使用返回值。 – 2014-10-03 22:45:41

回答

1

列表是不可變的;矩陣是可變的。要更正您的代碼,您需要替換該行 removeElement(M [k,j],index);M [k,j]:= removeElement(M [k,j],index)

如果您只是在調用該過程的代碼中丟棄該值,那麼將過程的返回值沒有意義。這就是你在做的。

0

矩陣是可變的,但列表不是。如發佈,solveSudoku正在將一個列表傳遞給removeElement作爲後者的參數L

solveSudoku,你叫removeElement線或許應該這樣來使用,而不是,

M[k,j] := removeElement(M[k,j],index); 

另外,通過對MremoveElement不是入門M[k,j]的價值。即,

removeElement(M, k, j, index); 

solveSudoku通話,然後裏面removeElement類似,

M[k,j] := [op(1..boundary-1,L),op(boundary+1..,L)]; return NULL; 

當然,你應該只把這些方法中的一種:其中,項M[k,j]solveSudoku被更新的第一種方式,或者在removeElement更新的第二種方式。

nb。當您調用像F(...,M[k,j],...)這樣的過程時,您將矩陣條目M[k,j]的值傳遞給F。但是當你像F(...,M,...)那樣打電話時,你實際上是通過引用傳遞Matrix M的。

相關問題