You can not select more than 25 topics
			Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
		
		
		
		
		
			
		
			
				
					
					
						
							71 lines
						
					
					
						
							1.3 KiB
						
					
					
				
			
		
		
	
	
							71 lines
						
					
					
						
							1.3 KiB
						
					
					
				#!/usr/bin/env julia
 | 
						|
 | 
						|
using Test
 | 
						|
 | 
						|
function priority(char)
 | 
						|
  v = Int(char)
 | 
						|
  if v <= Int('Z')
 | 
						|
    return v - Int('A') + 27
 | 
						|
  else
 | 
						|
    return v - Int('a') + 1
 | 
						|
  end
 | 
						|
end
 | 
						|
 | 
						|
function rucksack_errors(infile)
 | 
						|
  psum = 0
 | 
						|
 | 
						|
  open(infile, "r") do io
 | 
						|
    for line in eachline(io)
 | 
						|
      n = length(line)
 | 
						|
      a = Set{Int32}()
 | 
						|
      b = Set{Int32}()
 | 
						|
      for c in line[1:Int(n/2)]
 | 
						|
        push!(a, priority(c))
 | 
						|
      end
 | 
						|
      for c in line[Int(n/2)+1:n]
 | 
						|
        push!(b, priority(c))
 | 
						|
      end
 | 
						|
      psum += pop!(intersect(a, b))
 | 
						|
    end
 | 
						|
  end
 | 
						|
 | 
						|
  return psum
 | 
						|
end
 | 
						|
 | 
						|
function rucksack_badges(infile)
 | 
						|
  psum = 0
 | 
						|
 | 
						|
  open(infile, "r") do io
 | 
						|
    for lines in Iterators.partition(eachline(io), 3)
 | 
						|
      all = intersect!(Set(lines[1]), Set(lines[2]), Set(lines[3]))
 | 
						|
      psum += priority(pop!(all))
 | 
						|
    end
 | 
						|
  end
 | 
						|
 | 
						|
  return psum
 | 
						|
end
 | 
						|
 | 
						|
 | 
						|
function test()
 | 
						|
  @testset "elf rucksack errors" verbose=true begin
 | 
						|
    @test rucksack_errors("example.txt") == 157
 | 
						|
    @test rucksack_errors("input.txt") == 8394
 | 
						|
  end
 | 
						|
  @testset "elf rucksack badges" verbose=true begin
 | 
						|
    @test rucksack_badges("example.txt") == 70
 | 
						|
    @test rucksack_badges("input.txt") == 2413
 | 
						|
  end
 | 
						|
end
 | 
						|
 | 
						|
function main()
 | 
						|
  if size(ARGS, 1) == 0
 | 
						|
    test()
 | 
						|
  else
 | 
						|
    infile = ARGS[1]
 | 
						|
    println("infile = ", infile)
 | 
						|
    println("error priority sum: ", rucksack_errors(infile))
 | 
						|
  end
 | 
						|
end
 | 
						|
 | 
						|
main()
 |