Skip to content

Instantly share code, notes, and snippets.

@HunterLarco
Last active August 24, 2020 20:10
Show Gist options
  • Save HunterLarco/7e52328b6cf5ba5365dca79bb11ecccf to your computer and use it in GitHub Desktop.
Save HunterLarco/7e52328b6cf5ba5365dca79bb11ecccf to your computer and use it in GitHub Desktop.
function computeRopeCosts(password, additionsNeeded, removalsNeeded) {
let ropes = []
let lastChar;
let lastCharIndex;
for (let i = 0; i < password.length; ++i) {
const char = password[i];
if (char != lastChar) {
if (lastChar && i - lastCharIndex >= 3) {
ropes.push(i - lastCharIndex)
}
lastChar = char
lastCharIndex = i
}
}
if (lastChar && password.length - lastCharIndex >= 3) {
ropes.push(password.length - lastCharIndex)
}
ropes = ropes.map(count => {
if (count - 2 <= removalsNeeded) {
removalsNeeded -= count - 2
return count - 2
} else {
return count
}
})
ropes = ropes.map(count => {
if (removalsNeeded > 0) {
if (count % 3 == 0) {
--removalsNeeded
return count - 1
}
} else if (additionsNeeded > 0) {
if (count % 3 == 0 || count % 3 == 1) {
--additionsNeeded
return count - 2
}
}
return count
})
ropes = ropes.filter(count => count >= 3)
let additions = 0
let modifications = 0
let removals = 0
for (let count of ropes) {
modifications += Math.floor(count / 3)
}
return { additions, modifications, removals }
}
function CheckStrongPassword(password) {
let digits = 0
let lowercase = 0
let uppercase = 0
for (const char of password) {
if (char.match(/^[a-z]$/)) {
++lowercase
} else if (char.match(/^[A-Z]$/)) {
++uppercase
} else if (char.match(/^[0-9]$/)) {
++digits
}
}
const additionsNeeded = Math.max(0, 6 - password.length)
const removalsNeeded = Math.max(0, password.length - 20)
// Regardless of everything else, we always have to make enough modifications
// or additions to match the char type requirements.
let minMidAdds = (digits == 0) + (lowercase == 0) + (uppercase == 0)
minMidAdds = Math.max(0, minMidAdds - additionsNeeded)
console.log('additionsNeeded', additionsNeeded)
console.log('removalsNeeded', removalsNeeded)
console.log('minMidAdds', minMidAdds)
const { additions, modifications, removals } =
computeRopeCosts(password, additionsNeeded, removalsNeeded)
console.log(additions, modifications, removals)
return additions + modifications + removals
+ Math.max(0, removalsNeeded - removals)
+ Math.max(0, additionsNeeded - additions)
+ Math.max(0, minMidAdds - (additions + modifications))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment