Spent ages trying to get this figured using array striding but eventually my head exploded and I resorted to using indices.
importnumpyasnpfromioimportStringIOimportmathdefcount_trees(arr,steps_right,steps_down):n_rows,n_cols=arr.shapen_down_steps=math.floor(n_rows/steps_down)across_positions=[(steps_right*n)%n_colsforninrange(n_down_steps)]flat_array_positions=[(rownum*n_cols*steps_down)+across_positions[rownum]forrownuminrange(n_down_steps)]total_trees=arr.ravel()[flat_array_positions].sum()returntotal_treeswithopen('input.txt','r')asf:data=f.read().replace('.','0').replace('#','1')# using converters parameter to change #/. to 1/0 is a pain if
# we don't know the number of columns. So string-replace them all first
trees_map=np.genfromtxt(StringIO(data),delimiter=1,dtype='uint8')part_2_slopes=((1,1),(3,1),(5,1),(7,1),(1,2))part_1_slope=part_2_slopes[1]print(f"Part 1: {count_trees(trees_map,*part_1_slope)} trees hit")part_2_trees=[count_trees(trees_map,*s)forsinpart_2_slopes]part_2_res=np.prod(part_2_trees)print(f"Part 2: Product of total trees hit is {part_2_res}")
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Python implementation using numpy.
Spent ages trying to get this figured using array striding but eventually my head exploded and I resorted to using indices.