Skip to content

Instantly share code, notes, and snippets.

@x86-39
Last active December 29, 2023 23:51
Show Gist options
  • Save x86-39/498113659f8a76ed4b7a0f6ee9a130d9 to your computer and use it in GitHub Desktop.
Save x86-39/498113659f8a76ed4b7a0f6ee9a130d9 to your computer and use it in GitHub Desktop.
Ansible Advent of Code 2023, Day 5 Part 1
---
# Set the input
- name: Set example input
ansible.builtin.set_fact:
day5_input: |-
seeds: 79 14 55 13
seed-to-soil map:
50 98 2
52 50 48
soil-to-fertilizer map:
0 15 37
37 52 2
39 0 15
fertilizer-to-water map:
49 53 8
0 11 42
42 0 7
57 7 4
water-to-light map:
88 18 7
18 25 70
light-to-temperature map:
45 77 23
81 45 19
68 64 13
temperature-to-humidity map:
0 69 1
1 0 69
humidity-to-location map:
60 56 37
56 93 4
when: day5_input is not defined
# Parse the input into seperate lists
- name: Get seperate inputs
ansible.builtin.set_fact:
seeds: "{{ day5_input | split('\n\n') | first | regex_replace('^seeds: ', '') | split(' ') | map('int') | list }}"
maps: "{{ day5_input | split('\n\n') | reject('match', '^seeds: ') }}"
# Store maps as dicts
- name: Store maps as dicts
ansible.builtin.set_fact:
maps_dict:
seed_to_soil: "{{ seperate_lists[0] }}"
soil_to_fertilizer: "{{ seperate_lists[1] }}"
fertilizer_to_water: "{{ seperate_lists[2] }}"
water_to_light: "{{ seperate_lists[3] }}"
light_to_temperature: "{{ seperate_lists[4] }}"
temperature_to_humidity: "{{ seperate_lists[5] }}"
humidity_to_location: "{{ seperate_lists[6] }}"
vars:
seperate_lists: "{{ maps | map('split', '\n') | map('reject', 'match', '^.*map:$') }}"
# Part 1, convert seeds
- name: Convert ranges for each seed
ansible.builtin.set_fact:
seeds_converted: "{{ seeds_converted | default([]) + [convert_range | int] }}"
# Loop over range of seed indexes
loop: "{{ range(0, seeds | length) | list }}"
vars:
# Less efficient loop
convert_range: "
{# COMMENT: Set the seed #}
{%- set ns = namespace(seed = seeds[item]) -%}
{# COMMENT: For every mapping... #}
{% for mapping in maps_dict | dict2items %}
{# COMMENT: Set this so we can break the loop once it's already been converted #}
{%- set breakns = namespace(break = false) -%}
{# COMMENT: For every range in the mapping... #}
{% for dst_start, src_start, size in mapping.value | map('split', ' ') | map('map', 'int') | list %}
{# COMMENT: If we haven't already converted this seed... #}
{% if not breakns.break | bool %}
{# COMMENT: If the seed is in the range... #}
{% if ns.seed | int >= src_start | int and ns.seed | int < src_start | int + size | int %}
{# COMMENT: Convert the seed #}
{%- set ns.seed = dst_start | int + (ns.seed | int - src_start | int) -%}
{%- set breakns.break = true -%}
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
{{ ns.seed }}"
# Get the lowest seed location
- name: ANSWER TO PART 1 | Get the lowest seed location
ansible.builtin.debug:
msg: "{{ seeds_converted | min }}"
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment