Tuesday, May 2, 2017

Tricky double problem


In one of the interview I was asked how to eliminate tricky double in an array.I have not heard about tricky double.

Tricky double means
" 1, 2, 8, 9, 1, 2 , 3, 2 " . In this example what we notice is that 1, 2 is a  tricky double. However 2 is repeated twice it is not a tricky double.



Now in the above example we need to eliminate 1, 2 from the array. I tried to look for solutions online. However I was not able to find any solution.

I was able to solve this problem

Steps involved

1. Convert the integer to Alphabets . This can be achieved by adding 64 and converting ascii character     to string
2. Append the string characters in increments of 2

   " 1, 2, 8, 9, 1, 2 , 3, 2 " would be  " AB,HI,AB,CB"
3. Add the new set of strings to an array.
4. Eliminate duplicates
5. Convert the string value to integer


function trickyDouble(arr)
{
    var exists =[], 
         outArray =[],
         cur,
         double;
         dupcheck ={},
         str="",
         arr2="";
         //Loop to add 2 consecutive values and convert the numbers to characters
         //Note we are adding 64 
         for(i=0;i<=arr.length-1;i+=2)
         {
             cur=arr[i];
             //Converts integervalues to alphabets
             //String.fromCharCode uysed to convert character based on the ascci value
             double=String.fromCharCode(64+arr[i]) + String.fromCharCode(64+arr[i+1])
             exists.push(double);
         }
         //Elimenate duplicates
         for(j=0;j<=exists.length-1;j++)
         {
              if(!dupcheck[exists[j]])
               {
                 dupcheck[exists[j]]=true;
                str=str+exists[j];
               }
         }
         //Spread operator converts string to an array of characters
          arr2 = [...str]
          for(k=0;k<=arr2.length-1;k++)
         {
           //convert the character value to number
           //note we are subtracting 64
              outArray.push(arr2[k].charCodeAt()-64)
         }
        ///Convert all the character array to numbers
 
return outArray;
}

No comments:

Post a Comment