Skip to content

Commit 4f48fb2

Browse files
committed
Made some micro optimizations to Golomb Ruler
1 parent 5aeabfe commit 4f48fb2

File tree

1 file changed

+13
-16
lines changed

1 file changed

+13
-16
lines changed

GolombRulers/GolombRulers.py

+13-16
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from queue import PriorityQueue
22
import math
33
import time
4+
import sys
45

56

67
def widthsToTickMarks(widths):
@@ -23,31 +24,26 @@ def widthsToMeasurableDistances(widths):
2324
return measurableDistances
2425

2526

26-
def getChildren(widths, maxChildren):
27+
def getChildren(widths, maxChildren, mds):
2728
children = []
2829

29-
mds = widthsToMeasurableDistances(widths)
30-
31-
# can be made more efficient
32-
# might need to make this go higher
3330
for md in range(1, maxChildren):
3431
if md not in mds:
3532
children.append(widths + [md])
3633

3734
return children
3835

3936

40-
def isValid(widths):
41-
return max(widthsToMeasurableDistances(widths).values()) <= 1
37+
def isValid(mds):
38+
return max(mds.values()) <= 1
4239

4340

4441
def getCost(widths):
4542
return sum(widths)
4643

4744

48-
def getHeuristic(widths, order):
45+
def getHeuristic(widths, order, mds):
4946
unusedWidths = []
50-
mds = widthsToMeasurableDistances(widths)
5147
md = 1
5248
while len(unusedWidths) + len(widths) < order - 1:
5349
if md not in mds:
@@ -61,25 +57,26 @@ def search(order):
6157
queue = PriorityQueue()
6258
maxChildren = math.floor(order * 1.5)
6359
while True:
64-
queue.put((0, []))
60+
queue.put((0, [], {}))
6561
while not queue.empty():
66-
f, widths = queue.get()
62+
f, widths, mds = queue.get()
6763
if len(widths) == order - 1:
6864
return widths
6965

70-
children = getChildren(widths, maxChildren)
66+
children = getChildren(widths, maxChildren, mds)
7167
for child in children:
72-
if not isValid(child):
68+
mds = widthsToMeasurableDistances(child)
69+
if not isValid(mds):
7370
continue
7471
g = getCost(child)
75-
h = getHeuristic(child, order)
76-
queue.put((g + h, child))
72+
h = getHeuristic(child, order, mds)
73+
queue.put((g + h, child, mds))
7774
print("Solution not found with maxChildren = " + str(maxChildren));
7875
maxChildren += 1
7976

8077

8178
def main():
82-
order = int(input())
79+
order = int(sys.argv[1])
8380
start = time.time()
8481
print(widthsToTickMarks(search(order)))
8582
print("Time: " + str(time.time() - start))

0 commit comments

Comments
 (0)