Created
December 4, 2019 07:42
-
-
Save Nimblz/c56493281e38a1d5d38b9d7960f96f16 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Number of valid passwords: | |
814 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local lowest = 234208 | |
local highest = 765869 | |
local function numDigits(number) | |
return math.floor( math.log(number, 10) + 1 ) | |
end | |
-- gross | |
local function digitAt(number, x) | |
local stringified = tostring(number) | |
return tonumber(stringified:sub(x,x)) | |
end | |
local function toDigitTable(number) | |
local digitTable = {} | |
for i = 1, numDigits(number) do | |
table.insert(digitTable, digitAt(number, i)) | |
end | |
return digitTable | |
end | |
local function isValid(number) | |
local digits = toDigitTable(number) | |
local isSixDigit = #digits == 6 | |
local digitsDecrease = false | |
local containsPair = false | |
local validPairs = {} | |
local lastDigit = 0 | |
for _, digit in ipairs(digits) do | |
-- check if the digits decreased | |
if not (digit >= lastDigit) then | |
digitsDecrease = true | |
break -- could just return false here | |
end | |
-- mark pairs, if the pair already exists current digit is guarenteed to be part of a larger group | |
if digit == lastDigit then | |
-- hoo boy | |
-- if the validPairs[digit] is false we have already determined that this is a group larger than 2 | |
-- if the validPairs[digit] is true this is a group of digits larger than 2, set to false | |
-- if the validPairs[digit] is nil this pair has not been seen, set to true. | |
if validPairs[digit] ~= false then | |
if validPairs[digit] == true then | |
validPairs[digit] = false | |
elseif validPairs[digit] == nil then | |
validPairs[digit] = true | |
end | |
end | |
end | |
lastDigit = digit | |
end | |
-- if we have a valid pair set the flag | |
for _, isValid in pairs(validPairs) do | |
if isValid then | |
containsPair = true | |
break | |
end | |
end | |
return ( | |
isSixDigit and | |
containsPair and | |
not digitsDecrease | |
) | |
end | |
-- count valid answers | |
local validAnswers = 0 | |
for i = lowest, highest do | |
if isValid(i) then | |
validAnswers = validAnswers + 1 | |
end | |
end | |
print("Number of valid passwords:") | |
print("\t"..validAnswers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment