skip to Main Content

How can I compress strings such that :

  • input is lowercase alphanumeric and the dot character
  • output must be alphanumeric mixed case only

The input is short and has no repetition

2

Answers


  1. Something like this could work if I understand it correctly:

    const compressString = (input) => {
        if (!/^[a-z0-9.]+$/.test(input)) {
            throw new Error("Invalid input: must be lowercase alphanumeric and dots only");
        }
    
        const dotReplacement = 'Z';
    
        const result = input.replace(/./g, dotReplacement).toUpperCase();
    
        return result;
    }
    
    const input = "example.string";
    const compressed = compressString(input);
    console.log(compressed);
    
    

    To be honest this is probably very basic example but you can use it as start I guess.

    Login or Signup to reply.
  2. Your input can contain 37 different characters (lowercase letters, digits, dot), which can be expressed with 6 bits per character.

    Your output can contain 62 different characters (upper- and lowercase letters and digits), which suggests a base62 encoding.

    const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
    function compress(input) {
      input = input.toUpperCase();
      var int = 0;
      for (var i = 0; i < input.length; i++) {
        code = input.charCodeAt(i) - 48;
        if (code === -2) code = 50 // special value for .
        int = (int << 6) + code;
      }
      var res = "";
      while (int > 0) {
        res = alphabet[int % 62] + res;
        int = Math.floor(int / 62);
      }
      return res;
    }
    Input: <input onchange="out.value = compress(this.value)"><br>
    Output: <input id="out" readonly/>

    A corresponding decoding function can also be written.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search