2 minutes to read - Apr 12, 2023

Optimize code

How can I optimize this? lines=File .readlines("./input/day1_full.txt") .map(&:strip) elf_calories=lines .map { |e|| e| == ""? nil: el.to_i} .chunk_while { |e|,next_e|| next_e|} .to_a .map{ |a| a.compact} sorted_sums= elf_calories.map(&:sum).sort.reverse puts "calories carrid by top 1 elf: #{sorted_sums[0]}" puts "calories carrid by top 3 elves: #{sorted_sums[0...3].sum}"

Here are a few additional optimization suggestions:

1. Use a faster method for filtering out empty lines: Instead of using a ternary operator and `nil`, you can use `next` to skip empty lines when mapping the lines. This will avoid creating unnecessary `nil` values.

2. Use a faster method for extracting the top n sums: Instead of sorting the array of sums and then extracting the top n elements, you can use the `max` or `max_by` method to get the maximum value(s) directly. For example: `sorted_sums.max(3)` or `elf_calories.max_by(3) { |a| a.sum }`

3. Use parallel processing: If you are running this code on a machine with multiple cores, you can use the `parallel_map` method from the `parallel` gem to parallelize the mapping of the `elf_calories` array. This can potentially speed up the code if the mapping operation is CPU-intensive.

I hope these suggestions help! Let me know if you have any questions.

loading...