Skip to content

Instantly share code, notes, and snippets.

@TheRealOrange
Created July 22, 2024 04:32
Show Gist options
  • Save TheRealOrange/7710c57e887c64565c5f4911731bcc71 to your computer and use it in GitHub Desktop.
Save TheRealOrange/7710c57e887c64565c5f4911731bcc71 to your computer and use it in GitHub Desktop.
import random
import heapq
import time
def shuffle2d(arr):
flattened = [arr[i][j] for i in range(len(arr)) for j in range(len(arr[i]))]
random.shuffle(flattened)
it = iter(flattened)
for i in range(len(arr)):
for j in range(len(arr[i])):
arr[i][j] = next(it)
return arr
player_shapes = ['T', 'S', 'C']
room_inventories = [['T', 'T'], ['S', 'S'], ['C', 'C']]
unique = 3
rooms = 3
room_inventories = shuffle2d(room_inventories)
def player(room, player_shapes, room_inventories):
total = room_inventories[room] + [player_shapes[room]]
if len(set(total)) == unique and len(total) == unique:
return None
if len(room_inventories[room]) == 0:
return None
select = random.choice(room_inventories[room])
if select != player_shapes[room] and room_inventories[room].count(select) == 1:
return None
send = random.choice([i for i in range(rooms) if (i != room and select != player_shapes[i])])
return room, send, select
def valid(player_shapes, room_inventories):
for i in range(rooms):
total = [player_shapes[i]] + room_inventories[i]
if len(set(total)) != unique or len(total) > unique:
return False
return True
def game(player_shapes, room_inventories):
execution_queue = []
log = []
for i in range(rooms):
heapq.heappush(execution_queue, (random.randint(3, 10), 'r', i))
while not valid(player_shapes, room_inventories):
ind, task_type, data = heapq.heappop(execution_queue)
if task_type == 'r':
curr_room = data
action = player(curr_room, player_shapes, room_inventories)
if not (action is None):
heapq.heappush(execution_queue, (ind + 2, 'a', action))
heapq.heappush(execution_queue, (ind + random.randint(3, 10), 'r', curr_room))
elif task_type == 'a':
curr_room, sendto, selected = data
room_inventories[curr_room].remove(selected)
room_inventories[sendto].append(selected)
log.append(data)
return log
total = 0
swaps = 0
longest = 0
rounds = 100000
mode_cnt = [0 for i in range(100)]
start_time = time.time()
for i in range(rounds):
player_shapes = ['T', 'S', 'C']
room_inventories = [['T', 'T'], ['S', 'S'], ['C', 'C']]
random.shuffle(player_shapes)
room_inventories = shuffle2d(room_inventories)
swap_cnt = len(game(player_shapes, room_inventories))
swaps += swap_cnt
mode_cnt[swap_cnt] += 1
if swap_cnt > longest:
longest = swap_cnt
total += 1
print("--- %s seconds ---" % (time.time() - start_time))
print("rounds:", rounds)
print("mode no. of swaps:", mode_cnt.index(max(mode_cnt)))
print("mean no. of swaps:",swaps/total)
print("max no. of swaps:", longest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment