0
我目前正在處理大量遞歸調用的側項目。我不是計算機科學家,所以我不確定如何優化我的代碼。我知道遞歸函數效率不高,我聽說你經常可以用tail調用替換它,但我不確定如何去做這件事。這個函數需要三個數組:appendList,sequence和used。其他參數,基數,長度,索引和最後一個詞是整數。優化遞歸函數
function Recursion(appendList, base, length, sequence, used, lastWord, index)
#Global variables:
global G_Seq_List
global G_Seq_Index
used = ones(UInt8, 1, base^length)
used[1] = 0
if index == base^length
check = zeros(UInt8, base^length, 1)
for i = 1 : base^length
index = 1
for j = 1 : length
k = mod(i+j-1,base^length)
index = index + base^(length - j)*sequence[k+1]
end
check[index] = check[index] + 1
if check[index] != 1
return
end
end
G_Seq_List[G_Seq_Index,:] = sequence[:]
G_Seq_Index = G_Seq_Index + 1
return
end
#Builds Sequence
for i = 1 : base^length
if appendList[i , mod(lastWord - 1, base^(length - 1)) + 1] == 1
if used[i] == 1
tempUsed = used
tempUsed[i] = 0
tempCounter = index + 1
tempSequence = sequence
tempSequence[tempCounter] = mod(i - 1, base)
Recursion(appendList, base, length, tempSequence, tempUsed, i, tempCounter)
end
end
end
end
將此遞歸轉換爲尾部調用是否快速修復?如果不是,我可以做些什麼來優化這個功能?
你能解釋一下你用這個函數來完成什麼嗎?此外,進行優化的第一步是瞭解*爲什麼要優化。它慢嗎?典型的輸入大小是多少? – justhalf