Guest User

base16 game

a guest
May 7th, 2016
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. from itertools import permutations
  2. from collections import defaultdict
  3. import array
  4. import timeit
  5.  
  6. def find_sum_equal_n_16bit():
  7. solutions = set()
  8. best = 10**6
  9. num1, num2 = split_list(16)
  10. list_perm2 = list(permutations(num2))
  11. for perm1 in permutations(num1):
  12. for perm2 in list_perm2:
  13. perm = perm1 + perm2
  14. tple = product_sum(perm)
  15. temp_best = abs(product_num(tple))
  16. if temp_best <= best:
  17. print perm
  18. display_tuple(tuple_2_16bit(perm))
  19. best = temp_best
  20. if temp_best == 0:
  21. solutions.add(perm)
  22. return list(solutions)
  23.  
  24.  
  25. def split_list(n):
  26. # Greedy algorithm to divide the list into two
  27. num = range(1, n)
  28. high = [num.pop(1)]
  29. low = []
  30. while len(num) > 0:
  31. while sum(high) >= sum(low) and len(num) > 0:
  32. low.append(num.pop())
  33. temp_high = high
  34. high = low
  35. low = temp_high
  36. if len(high) > len(low):
  37. low.append(0)
  38. else:
  39. high.append(0)
  40. return high, low
  41.  
  42.  
  43. def product_sum(tple):
  44. lst = list(tple)
  45. num1 = sum(k*16**(4-i) for i, k in enumerate(lst[0:5]))
  46. num2 = sum(k*16**(2-i) for i, k in enumerate(lst[5:8]))
  47. num3 = sum(k*16**(4-i) for i, k in enumerate(lst[8:13]))
  48. num4 = sum(k*16**(2-i) for i, k in enumerate(lst[13:16]))
  49. return (num1, num2, num3, num4)
  50.  
  51.  
  52. def product_num(tple):
  53. total = tple[0]*tple[1] - tple[2]*tple[3]
  54. return total
  55.  
  56.  
  57. def tuple_2_16bit(tple):
  58. key1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
  59. key = key1 + ['A', 'B', 'C', 'D', 'E', 'F']
  60. lst = [str(key[i]) for i in tple]
  61. return (''.join(lst[0: 5]), ''.join(lst[5: 8]), ''.join(lst[8: 13]), ''.join(lst[13: 16]))
  62.  
  63.  
  64. def display_tuple(tple):
  65. print ' ' + tple[0] + ' x ' + tple[1]
  66. print ' - ' + tple[2] + ' x ' + tple[3]
  67. print ' = ', int(tple[0], 16)*int(tple[1], 16) - int(tple[2], 16)*int(tple[3], 16)
  68.  
  69. if __name__ == '__main__':
  70.  
  71. print find_sum_equal_n_16bit()
Advertisement
Add Comment
Please, Sign In to add comment