Advent of Code 2017, Day 4: High-Entropy Passphrases

#ruby #advent of code 2017

Part A

Back to warming exercises on Day 4. Our input contains passwords and we need to tell how many valid passwords there are. Password is valid if it does not contain duplicated words.

data = File.readlines("4.txt", chomp: true)

def valid?(password)
  words = password.split(" ")
  counts = {}

  words.each do |word|
    if counts[word]
      return false
    end

    counts[word] = true
  end

  true
end

puts data.select { |password| valid?(password) }.size

Part B

In the second part password is valid if it does not contain two words that are anagrams. To check if words are anagrams we can sort their characters and see if they are equal.

data = File.readlines("4.txt", chomp: true)

def valid?(password)
  words = password.split(" ")
  counts = {}

  words.each do |word|
    base = word.split("").sort.join
    if counts[base]
      return false
    end

    counts[base] = true
  end

  true
end

puts data.select { |password| valid?(password) }.size