Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Crack caesard encoded sentences.
// By find which letter is E.
// E is letter the most used in french.
function crack(caesarCode) {
const matrix = {};
const caesarCodeArray = caesarCode.toUpperCase().split('')
caesarCodeArray.filter(e => e !== " ").forEach(e => {
if(matrix[e]) {
matrix[e] += 1
} else {
matrix[e] = 1
}
})
console.log('matrix', matrix)
const maxValue = Object.values(matrix).sort((a, b) => b - a)[0]
console.log('maxValue', maxValue)
const E = Object.keys(matrix).find(e => matrix[e] === maxValue)
// console.log('E === ', E)
const alpha = [...'ABCDEFGHIJKLMNOPQRSTUVWXYZ']
const decalage = alpha.indexOf(E) - alpha.indexOf('E')
// console.log('decalage', decalage)
let alphaShifted = alpha.slice(decalage, alpha.length)
alphaShifted.push(...alpha.slice(0, decalage))
// console.log('alphaShifted', alphaShifted)
const answer = caesarCodeArray.reduce((acc, curr) => {
if (!alpha.includes(curr)) {
return acc + curr
}
return acc + alpha[alphaShifted.indexOf(curr)]
}, '')
return answer
}
console.log(
crack("Cv tfuv Tvjri vjk le tyzwwivdvek srjv jli le uvtrcrxv uv c'rcgyrsvk (uvgcrtvdvek uvj cvkkivj gclj cfze urej c'rcgyrsvk), zc j'rxzk u'lev jlsjkzklkzfe dfefrcgyrsvkzhlv, t'vjk-r-uziv hl'lev dvdv cvkkiv e'vjk ivdgcrtvv hlv gri lev jvlcv rlkiv (kflaflij zuvekzhlv gfli le dvdv dvjjrxv). Cv uvtrcrxv cv gclj jflmvek lkzczjv vjk uv kifzj cvkkivj.")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment