Skip to content

Instantly share code, notes, and snippets.

@Keped
Created July 25, 2024 20:30
Show Gist options
  • Save Keped/a37069ae00d2f9739e955643d0ad080c to your computer and use it in GitHub Desktop.
Save Keped/a37069ae00d2f9739e955643d0ad080c to your computer and use it in GitHub Desktop.
/*
Encrypted Words
You've devised a simple encryption method for alphabetic strings that shuffles the characters in such a way that the resulting string is hard to quickly read, but is easy to convert back into the original string.
When you encrypt a string S, you start with an initially-empty resulting string R and append characters to it as follows:
Append the middle character of S (if S has even length, then we define the middle character as the left-most of the two central characters)
Append the encrypted version of the substring of S that's to the left of the middle character (if non-empty)
Append the encrypted version of the substring of S that's to the right of the middle character (if non-empty)
For example, to encrypt the string "abc", we first take "b", and then append the encrypted version of "a" (which is just "a") and the encrypted version of "c" (which is just "c") to get "bac".
If we encrypt "abcxcba" we'll get "xbacbca". That is, we take "x" and then append the encrypted version "abc" and then append the encrypted version of "cba".
Input
S contains only lower-case alphabetic characters
1 <= |S| <= 10,000
Output
Return string R, the encrypted version of S.
Example 1
S = "abc"
R = "bac"
Example 2
S = "abcd"
R = "bacd"
Example 3
S = "abcxcba"
R = "xbacbca"
Example 4
S = "facebook"
R = "eafcobok"
*/
function encript(s, mid){
let enc = s[mid]
if(s[mid-1] ){
enc+= s[mid-1]
}
if(s[mid+1]){
enc+= s[mid+1]
}
return enc
}
function splitMergeEnc(s, mid){
let h1 = ""
let h2 = ""
if(mid >= 1){
h1+=recursiveEnc(s.slice(0,mid))
console.log("TT1",h1)
}
if(mid + 1 < s.length){
h2+=recursiveEnc(s.slice(mid+1))
console.log("TT2",h2)
}
console.log(mid, h1, h2)
return h1+ h2
}
function recursiveEnc(s){
if(s.length<2) {
console.log("s",s)
return s
}
let modifier = 1 -(s.length % 2)
const mid = Math.floor(s.length/2) - modifier
console.log(`s: ${s}`,s[mid],`mid: ${mid}`)
if(s.length <= 3) {
return encript(s,mid)
}
return s[mid] + splitMergeEnc(s, mid)
}
console.log(recursiveEnc("facebook"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment