String encoder to fixed size output

I got a task where I need to write a encoder with these requirements:

I have no experience with crypto(?) or encoding algorithms so I have no clue how to get this job done. The libs I found online doesn't allow to set the output size since it's based on input size.

Any help is strongly appreciated, I'm lost here

Upvotes: 2

Views: 1578

Answers (2)

georg
georg

Reputation: 215029

Here's a simple approach:

  • convert the input to a string and extend to 9 digits by adding zeros to the left as necessary
  • encode each group of 3 digits using base32 encoding, which gives you max two letters/digits per group. You can use .toString(32) while testing, but I guess the interviewer expects you to create your own function
  • pad each group to the length 2 and concatenate

Example:

 1234567 -> 001234567 -> 001 234 567 -> 1 7a hn -> 017ahn

Good luck!

Upvotes: 1

The Bomb Squad
The Bomb Squad

Reputation: 4337

I got excited when I saw this, so I made an answer that at least does what the question requires :D

The encoding works through base conversion logic and conversion of those numbers to text. I used an array of length 6 to store the data on encoding to ensure that it will always be 6 chars(and not less)

The decoding works through just adding it back respecting the powers so it adds back in full value

I hope it's an answer you're looking for because I love this question :D

//a homemade answer :D
//first time I saw a question like that, I hope I get stuff like this in college ngl
function encode(num){
  let alphabet=[]
  for(let i=48;i<127;i++){
    alphabet.push(String.fromCharCode(i))
  }
  //alphabet is filled with encoding text :D
  let arr=[0,0,0,0,0,0] //for fixed 6 digits
  let pow=0; let pow1=1
  let length=alphabet.length
  while(num>0){
    let subtraction=(num%Math.pow(length,pow1))
    num-=subtraction
    arr[pow]=subtraction/Math.pow(length,pow)
    pow++; pow1++
  }
  return arr.reverse()
  .map(a=>String.fromCharCode(a+48)) //offset of 48 for nice chars
  .join('') //like a base conversion basically
}

function decode(string){
  let num=0; let length=127-48 //length really is the number of base(79 in this case)
  string=string.split('').reverse().join('')
  for(let i=0;i<string.length;i++){
    let int=string.charCodeAt(i)-48 //-48 remembering the offset
    num+=int*Math.pow(length,i)
  }
  return num
}



var int=12348291
console.log('encoded num:',encode(int))
console.log('decoded string:',decode(encode(int)))
console.log('they are reversible?',decode(encode(int))==int)

Upvotes: 2

Related Questions