有70個硬幣,其中有一個假硬幣。需要以最少的稱量數量檢測假幣。你只有一個體重秤,你知道假硬幣更輕。模擬使用陣列的假硬幣
我不確定下面的問題的模擬是對還是錯,即在數組中表示它並進行比較,就像我在代碼中所做的那樣。我試圖用一個數組來模擬它,除了一個零被認爲是假硬幣。以下是我的代碼。請讓我知道,如果我錯了。
如果有人能夠證明/解釋爲什麼三分法在簡單的數學中更好,這將是非常有幫助的。
爲下面的代碼僞代碼:
INPUT : integer n
if n = 1 then
the coin is fake
else
divide the coins into piles of A = ceiling(n/3), B = ceiling(n/3),
and C = n-2*ceiling(n/3)
weigh A and B
if the scale balances then
iterate with C
else
iterate with the lighter of A and B
代碼:
import random
def getmin(data, start, end, total_items):
if total_items == 1:
#for sure we have a fake coin
return (0, start)
elif total_items == 2:
if data[start] > data[end]:
return (1, end)
elif data[start] < data[end]:
return (1, start)
else:
partition = total_items/3
a_weight = sum(data[start:start+partition])
b_weight = sum(data[start+partition:start+2*partition])
c_weight = sum(data[start+2*partition:end])
if a_weight == b_weight:
result = getmin(data, start+2*partition, end, end-(start+2*partition))
return (1+result[0], result[1])
else:
if a_weight > b_weight:
result = getmin(data, start+partition, start+2*partition, partition)
return (1+result[0], result[1])
else:
result = getmin(data, start, start+partition, partition)
return (1+result[0], result[1])
n = int(raw_input())
data = [1]*n
data[random.randint(0, n-1)] = 0
total_weighing, position = getmin(data, 0, len(data), len(data))
print(total_weighing, position)
如果您尚未確定是否有問題,則不應發佈。爲您測試程序不在SO的範圍內。簡單的代碼審查屬於codereview網站。 – Prune
@Prune我不想檢查我的程序。我正在檢查我的陣列模擬是否是解決假硬幣問題的正確方法。代碼只是爲了更好地說明我的問題。 –
明白了;謝謝。我收回了我的近距離投票,並且我會在我的答案中編輯該部分。 – Prune