Day 22: Monkey Market
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
Python3
Hey there lemmy, I recently transitioned from using notepad to Visual Studio Code along with running a local LLM for autocomplete(faster than copilot, big plus but hot af room)
I was able to make this python script with a bunch of fancy comments and typing silliness. I ended up spamming so many comments. yay documentation! lol
Solve time: ~3 seconds (can swing up to 5 seconds)
Code
from tqdm import tqdm from os.path import dirname,isfile,realpath,join from collections.abc import Callable def profiler(method) -> Callable[..., any]: from time import perf_counter_ns def wrapper_method(*args: any, **kwargs: any) -> any: start_time = perf_counter_ns() ret = method(*args, **kwargs) stop_time = perf_counter_ns() - start_time time_len = min(9, ((len(str(stop_time))-1)//3)*3) time_conversion = {9: 'seconds', 6: 'milliseconds', 3: 'microseconds', 0: 'nanoseconds'} print(f"Method {method.__name__} took : {stop_time / (10**time_len)} {time_conversion[time_len]}") return ret return wrapper_method # Process a secret to a new secret number # @param n: The secret number to be processed # @return: The new secret number after processing def process_secret(n: int) -> int: """ Process a secret number by XORing it with the result of shifting left and right operations on itself. The process involves several bitwise operations to ensure that the resulting number is different from the original one. First, multiply the original secret number by 64 with a left bit shift, then XOR the original secret number with the new number and prune to get a new secret number Second, divide the previous secret number by 32 with a right bit shift, then XOR the previous secret number with the new number and prune to get another new secret number Third, multiply the previous secret number by 2048 with a left bit shift, then XOR the previous secret number with the new number and prune to get the final secret number Finally, return the new secret number after these operations. """ n ^= (n << 6) n &= 0xFFFFFF n ^= (n >> 5) n &= 0xFFFFFF n ^= (n << 11) return n & 0xFFFFFF # Solve Part 1 and Part 2 of the challenge at the same time @profiler def solve(secrets: list[int]) -> tuple[int, int]: # Build a dictionary for each buyer with the tuple of changes being the key and the sum of prices of the earliest occurrence for each buyer as the value # At the same time we solve Part 1 of the challenge by adding the last price for each secret last_price_sum = 0 changes_map = {} for start_secret in (secrets): # Keep track of seen patterns for current secret changes_seen = set() # tuple of last 4 changes # first change is 0 because it is ignored last_four_changes = tuple([ (cur_secret:=process_secret(start_secret)), -(cur_secret%10) + ((cur_secret:=process_secret(cur_secret)) % 10) , -(cur_secret%10) + ((cur_secret:=process_secret(cur_secret)) % 10) , -(cur_secret%10) + ((cur_secret:=process_secret(cur_secret)) % 10) ] ) current_price = sum(last_four_changes) # Map 4-tuple of changes -> sum of prices index of earliest occurrence for all secrets for i in range(3, 1999): # sliding window of last four changes last_four_changes = (*last_four_changes[1:], -(cur_secret%10) + (current_price := (cur_secret:=process_secret(cur_secret)) % 10) ) # if we have seen this pattern before, then we continue to next four changes # otherwise, we add the price to the mapped value # this ensures we only add the first occurence of a patten for each list of prices each secret produces if last_four_changes not in changes_seen: # add to the set of seen patterns for this buyer changes_seen.add(last_four_changes) # If not recorded yet, store the price # i+4 is the index of the price where we sell changes_map[last_four_changes] = changes_map.get(last_four_changes, 0) + current_price # Sum the 2000th price to the total sum for all secrets last_price_sum += cur_secret # Return the sum of all prices at the 2000th iteration and the maximum amount of bananas that one pattern can obtain return last_price_sum,max(changes_map.values()) if __name__ == "__main__": # Read buyers' initial secrets from file or define them here BASE_DIR = dirname(realpath(__file__)) with open(join(BASE_DIR, r'input'), "r") as f: secrets = [int(x) for x in f.read().split()] last_price_sum,best_score = solve(secrets) print("Part 1:") print(f"sum of each of the 2000th secret number:", last_price_sum) print("Part 2:") print("Max bananas for one of patterns:", best_score)
Bit odd having
main()
returning an actual value, probably would have named it something else, otherwise, nicely documented solution.I bet VSC is a lot nicer to work in than notepad :D
you have a point to call name it something else, but lazy to do that. should I simply call it
solve()
maybe, that would work fine.I do want to note that having it return a value is not unheard of, it is just part of being lazy with the naming of the functions.
I definitely would not have the code outside of
main()
be included in the main function as it is just something to grab the input pass it to the solver function( main in this case, but as you noted should be called something else ) and print out the results. if you imported it as a module, then you can callmain()
with any input and get back the results to do whatever you want with. Just something I think makes the code better to look at and use.While doing this is highly unnecessary for these challenge, I wish to keep a little bit of proper syntax than just writing the script with everything at the top level. It feels dirty.
Coding in notepad was a bit brutal, but I stuck with notepad for years and never really cared because I copy pasta quite a bit from documentation or what not.(now a days, gpt helps me fix my shit code, now that hallucinations are reduced decently) even with VSCode, I don’t pay attention to many of its features. I still kinda treat it as a text editor, but extra nagging on top.(nagging is a positive I guess, but I am an ape who gives little fucks) I do like VSCode having a workspace explorer on the side. I dislike needing to alt-tab to various open file explorer windows. Having tabs for open files is really nice, too.
VSCode is nice, and running my Qwen-coder-1.5B locally is neat for helping somethings out. Not like I rely on it for helping with coding, but rather use it for comments or sometimes I stop to think or sometimes the autocomplete is updated in realtime while I am typing. really neat stuff, I think running locally is better than copilot because of it just being more real-time than the latency with interacting with MS servers. though I do think about all the random power it is using and extra waste heat from me constantly typing and it having to constantly keep up with the new context.
The quality took a little hit with the smaller model than just copilot, but so far it is not bad at all for things I expect it to help with. It definitely is capable of helping out. I do get annoyed when the autocomplete tries too hard to help by generating a lot more stuff that I don’t want.(even if the first part of what it generated is what I wanted but the rest is not) thankfully, that is not too often.
I give the local llm is helping with 70% of the comments and 15% of the code on average but it is not too consistent for the code.
For python, there is not enough syntax overhead to worry about and the autocomplete isn’t needed as much.
Its normal for main to return a value, its just usually a status thing, rather than actual data. But given python doesn’t really treat main as anything special, it hardly matters