Find all possible interpretations of an array of digits

This post is solution to a problem with the same title on geeksforgeeks.

I did not like the original solution posted on the site because:

  1. Using a data structures like TREE makes it complex
  2. Traversing operations are costly, if not linear
  3. And, it’s a simple problem. Why make it complicated?

My solution: Fewer lines of code, One Loop, most importantly Linear time #swag, Hashmap FTW!

You can use switch-case too if you wish to.

// Find all possible interpretations of an array of digits
// geeksforgeeks.org/find-all-possible-interpretations/

function interpret( arr ){
  for(var i=0; i<arr.length; i++){
    console.log(  printResult(arr[i]) );

    //digits do not exceed 2, therefore, this is enough
    if( i < arr.length-2 ) {
      console.log(  printResult ( arr[i]+ " " + arr[i+1] ) );
    }
  }
}


function printResult ( num ) {
  // instead of this map, you can use switch case to return the equivalent value
  var map = {
    "1"  : "a",
    "2"  : "b",
    "3"  : "c",
    "4"  : "d",
    "5"  : "e",
    "6"  : "f",
    // ...
    // ...
    // ...
    "26" : "z"
  };

  if(num in map){
    return map[num];
  }
  return "";
}

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s