Check whether a number can be dialed on a phone keypad without diagonal moves












3












$begingroup$


I'm trying to write/come up with an algorithm for a phone keypad traversal.



Let's say I have a rook on a keypad. The rook can traverse only horizontally and vertically. My code has to input a phone number and check whether the rook is able to dial it (shouldn't go diagonally) and return a boolean based on the result.



enter image description here



Example: A phone number "4632871" is termed as "true" since the rook can traverse without going diagonally whereas "4853267" is termed as "false"



Below is my code implementation:






var data = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];

function rookTraversal(arr, phoneNumber) {

var arrIndex = ,
numArray = ;

var number = phoneNumber.split('');

for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
arrIndex.push([i, j]);
}
}

arrIndex = arrIndex.map((item, index) => ({
[index + 1]: item,
}));

number.forEach((item) => {
numArray.push(arrIndex[item - 1]);
});

let numArrayKeys = numArray.reduce((acc, x) => [...acc, Object.values(x).map((y) => y)], );

for (let i = 1; i < numArrayKeys.length; i++) {
var x1 = numArrayKeys[i - 1][0][0];
var y1 = numArrayKeys[i - 1][0][1];
var x2 = numArrayKeys[i][0][0];
var y2 = numArrayKeys[i][0][1];

if (x1 !== x2 && y1 !== y2) {
return false;
}
}

return true;
}


console.log(rookTraversal(data, '4631782'));
console.log(rookTraversal(data, '4853267'));





Is there a way to optimize this piece of code?










share|improve this question









New contributor




a2441918 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    3












    $begingroup$


    I'm trying to write/come up with an algorithm for a phone keypad traversal.



    Let's say I have a rook on a keypad. The rook can traverse only horizontally and vertically. My code has to input a phone number and check whether the rook is able to dial it (shouldn't go diagonally) and return a boolean based on the result.



    enter image description here



    Example: A phone number "4632871" is termed as "true" since the rook can traverse without going diagonally whereas "4853267" is termed as "false"



    Below is my code implementation:






    var data = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
    ];

    function rookTraversal(arr, phoneNumber) {

    var arrIndex = ,
    numArray = ;

    var number = phoneNumber.split('');

    for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr.length; j++) {
    arrIndex.push([i, j]);
    }
    }

    arrIndex = arrIndex.map((item, index) => ({
    [index + 1]: item,
    }));

    number.forEach((item) => {
    numArray.push(arrIndex[item - 1]);
    });

    let numArrayKeys = numArray.reduce((acc, x) => [...acc, Object.values(x).map((y) => y)], );

    for (let i = 1; i < numArrayKeys.length; i++) {
    var x1 = numArrayKeys[i - 1][0][0];
    var y1 = numArrayKeys[i - 1][0][1];
    var x2 = numArrayKeys[i][0][0];
    var y2 = numArrayKeys[i][0][1];

    if (x1 !== x2 && y1 !== y2) {
    return false;
    }
    }

    return true;
    }


    console.log(rookTraversal(data, '4631782'));
    console.log(rookTraversal(data, '4853267'));





    Is there a way to optimize this piece of code?










    share|improve this question









    New contributor




    a2441918 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      3












      3








      3





      $begingroup$


      I'm trying to write/come up with an algorithm for a phone keypad traversal.



      Let's say I have a rook on a keypad. The rook can traverse only horizontally and vertically. My code has to input a phone number and check whether the rook is able to dial it (shouldn't go diagonally) and return a boolean based on the result.



      enter image description here



      Example: A phone number "4632871" is termed as "true" since the rook can traverse without going diagonally whereas "4853267" is termed as "false"



      Below is my code implementation:






      var data = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
      ];

      function rookTraversal(arr, phoneNumber) {

      var arrIndex = ,
      numArray = ;

      var number = phoneNumber.split('');

      for (var i = 0; i < arr.length; i++) {
      for (var j = 0; j < arr.length; j++) {
      arrIndex.push([i, j]);
      }
      }

      arrIndex = arrIndex.map((item, index) => ({
      [index + 1]: item,
      }));

      number.forEach((item) => {
      numArray.push(arrIndex[item - 1]);
      });

      let numArrayKeys = numArray.reduce((acc, x) => [...acc, Object.values(x).map((y) => y)], );

      for (let i = 1; i < numArrayKeys.length; i++) {
      var x1 = numArrayKeys[i - 1][0][0];
      var y1 = numArrayKeys[i - 1][0][1];
      var x2 = numArrayKeys[i][0][0];
      var y2 = numArrayKeys[i][0][1];

      if (x1 !== x2 && y1 !== y2) {
      return false;
      }
      }

      return true;
      }


      console.log(rookTraversal(data, '4631782'));
      console.log(rookTraversal(data, '4853267'));





      Is there a way to optimize this piece of code?










      share|improve this question









      New contributor




      a2441918 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I'm trying to write/come up with an algorithm for a phone keypad traversal.



      Let's say I have a rook on a keypad. The rook can traverse only horizontally and vertically. My code has to input a phone number and check whether the rook is able to dial it (shouldn't go diagonally) and return a boolean based on the result.



      enter image description here



      Example: A phone number "4632871" is termed as "true" since the rook can traverse without going diagonally whereas "4853267" is termed as "false"



      Below is my code implementation:






      var data = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
      ];

      function rookTraversal(arr, phoneNumber) {

      var arrIndex = ,
      numArray = ;

      var number = phoneNumber.split('');

      for (var i = 0; i < arr.length; i++) {
      for (var j = 0; j < arr.length; j++) {
      arrIndex.push([i, j]);
      }
      }

      arrIndex = arrIndex.map((item, index) => ({
      [index + 1]: item,
      }));

      number.forEach((item) => {
      numArray.push(arrIndex[item - 1]);
      });

      let numArrayKeys = numArray.reduce((acc, x) => [...acc, Object.values(x).map((y) => y)], );

      for (let i = 1; i < numArrayKeys.length; i++) {
      var x1 = numArrayKeys[i - 1][0][0];
      var y1 = numArrayKeys[i - 1][0][1];
      var x2 = numArrayKeys[i][0][0];
      var y2 = numArrayKeys[i][0][1];

      if (x1 !== x2 && y1 !== y2) {
      return false;
      }
      }

      return true;
      }


      console.log(rookTraversal(data, '4631782'));
      console.log(rookTraversal(data, '4853267'));





      Is there a way to optimize this piece of code?






      var data = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
      ];

      function rookTraversal(arr, phoneNumber) {

      var arrIndex = ,
      numArray = ;

      var number = phoneNumber.split('');

      for (var i = 0; i < arr.length; i++) {
      for (var j = 0; j < arr.length; j++) {
      arrIndex.push([i, j]);
      }
      }

      arrIndex = arrIndex.map((item, index) => ({
      [index + 1]: item,
      }));

      number.forEach((item) => {
      numArray.push(arrIndex[item - 1]);
      });

      let numArrayKeys = numArray.reduce((acc, x) => [...acc, Object.values(x).map((y) => y)], );

      for (let i = 1; i < numArrayKeys.length; i++) {
      var x1 = numArrayKeys[i - 1][0][0];
      var y1 = numArrayKeys[i - 1][0][1];
      var x2 = numArrayKeys[i][0][0];
      var y2 = numArrayKeys[i][0][1];

      if (x1 !== x2 && y1 !== y2) {
      return false;
      }
      }

      return true;
      }


      console.log(rookTraversal(data, '4631782'));
      console.log(rookTraversal(data, '4853267'));





      var data = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
      ];

      function rookTraversal(arr, phoneNumber) {

      var arrIndex = ,
      numArray = ;

      var number = phoneNumber.split('');

      for (var i = 0; i < arr.length; i++) {
      for (var j = 0; j < arr.length; j++) {
      arrIndex.push([i, j]);
      }
      }

      arrIndex = arrIndex.map((item, index) => ({
      [index + 1]: item,
      }));

      number.forEach((item) => {
      numArray.push(arrIndex[item - 1]);
      });

      let numArrayKeys = numArray.reduce((acc, x) => [...acc, Object.values(x).map((y) => y)], );

      for (let i = 1; i < numArrayKeys.length; i++) {
      var x1 = numArrayKeys[i - 1][0][0];
      var y1 = numArrayKeys[i - 1][0][1];
      var x2 = numArrayKeys[i][0][0];
      var y2 = numArrayKeys[i][0][1];

      if (x1 !== x2 && y1 !== y2) {
      return false;
      }
      }

      return true;
      }


      console.log(rookTraversal(data, '4631782'));
      console.log(rookTraversal(data, '4853267'));






      javascript






      share|improve this question









      New contributor




      a2441918 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      a2441918 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 1 hour ago









      200_success

      129k15153415




      129k15153415






      New contributor




      a2441918 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 7 hours ago









      a2441918a2441918

      1161




      1161




      New contributor




      a2441918 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      a2441918 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      a2441918 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          1 Answer
          1






          active

          oldest

          votes


















          1












          $begingroup$

          There are a lot of different traits you could optimize for. I like to optimize for lines of code, so I'll try that.



          You can simplify the testing by building a "graph" (2-dimensional array) of reachable numbers. Each row and column index is a phone digit. If the value at (i,j) is true, then j is reachable from i.



          To do this, take all the numbers in each digit's row/column and create an array where those indexes have a value of 1.



          The reachability graph looks like this:



          enter image description here



          The digit 6 can reach 3,4,5,6,9 and you can see that reachable[6][x] is true for x=3,4,5,6 or 9.



          Then simply run through the list of numbers and test if reachable[current][next] is true.



          I've assumed the rook can dial repeated numbers like 3333. If no, you can test for that in the graph creation or during reachability testing.






          function rookTraversal(rows, phoneNumber) { 
          var cols=rows[0].map((col, i) => rows.map(row => row[i])),
          digits=phoneNumber.match(/(d)/g),
          reachable=;
          for (var row = 0; row < rows.length; row++) {
          for (var col = 0; col < cols.length; col++) {
          reachable[ rows[row][col] ] = rows[row].concat(cols[col]).reduce( (map, value) => { map[value]=1; return map }, );
          }
          }
          // console.log({reachable,digits});
          for (var i=0; i<digits.length-1; ++i) if (! reachable[ digits[i] ][ digits[i+1] ]) return false;
          return true;
          }

          var data = [
          [1, 2, 3],
          [4, 5, 6],
          [7, 8, 9],
          ];

          console.log(rookTraversal(data, '4631782'));
          console.log(rookTraversal(data, '4853267'));








          share|improve this answer











          $endgroup$













            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });






            a2441918 is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212873%2fcheck-whether-a-number-can-be-dialed-on-a-phone-keypad-without-diagonal-moves%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1












            $begingroup$

            There are a lot of different traits you could optimize for. I like to optimize for lines of code, so I'll try that.



            You can simplify the testing by building a "graph" (2-dimensional array) of reachable numbers. Each row and column index is a phone digit. If the value at (i,j) is true, then j is reachable from i.



            To do this, take all the numbers in each digit's row/column and create an array where those indexes have a value of 1.



            The reachability graph looks like this:



            enter image description here



            The digit 6 can reach 3,4,5,6,9 and you can see that reachable[6][x] is true for x=3,4,5,6 or 9.



            Then simply run through the list of numbers and test if reachable[current][next] is true.



            I've assumed the rook can dial repeated numbers like 3333. If no, you can test for that in the graph creation or during reachability testing.






            function rookTraversal(rows, phoneNumber) { 
            var cols=rows[0].map((col, i) => rows.map(row => row[i])),
            digits=phoneNumber.match(/(d)/g),
            reachable=;
            for (var row = 0; row < rows.length; row++) {
            for (var col = 0; col < cols.length; col++) {
            reachable[ rows[row][col] ] = rows[row].concat(cols[col]).reduce( (map, value) => { map[value]=1; return map }, );
            }
            }
            // console.log({reachable,digits});
            for (var i=0; i<digits.length-1; ++i) if (! reachable[ digits[i] ][ digits[i+1] ]) return false;
            return true;
            }

            var data = [
            [1, 2, 3],
            [4, 5, 6],
            [7, 8, 9],
            ];

            console.log(rookTraversal(data, '4631782'));
            console.log(rookTraversal(data, '4853267'));








            share|improve this answer











            $endgroup$


















              1












              $begingroup$

              There are a lot of different traits you could optimize for. I like to optimize for lines of code, so I'll try that.



              You can simplify the testing by building a "graph" (2-dimensional array) of reachable numbers. Each row and column index is a phone digit. If the value at (i,j) is true, then j is reachable from i.



              To do this, take all the numbers in each digit's row/column and create an array where those indexes have a value of 1.



              The reachability graph looks like this:



              enter image description here



              The digit 6 can reach 3,4,5,6,9 and you can see that reachable[6][x] is true for x=3,4,5,6 or 9.



              Then simply run through the list of numbers and test if reachable[current][next] is true.



              I've assumed the rook can dial repeated numbers like 3333. If no, you can test for that in the graph creation or during reachability testing.






              function rookTraversal(rows, phoneNumber) { 
              var cols=rows[0].map((col, i) => rows.map(row => row[i])),
              digits=phoneNumber.match(/(d)/g),
              reachable=;
              for (var row = 0; row < rows.length; row++) {
              for (var col = 0; col < cols.length; col++) {
              reachable[ rows[row][col] ] = rows[row].concat(cols[col]).reduce( (map, value) => { map[value]=1; return map }, );
              }
              }
              // console.log({reachable,digits});
              for (var i=0; i<digits.length-1; ++i) if (! reachable[ digits[i] ][ digits[i+1] ]) return false;
              return true;
              }

              var data = [
              [1, 2, 3],
              [4, 5, 6],
              [7, 8, 9],
              ];

              console.log(rookTraversal(data, '4631782'));
              console.log(rookTraversal(data, '4853267'));








              share|improve this answer











              $endgroup$
















                1












                1








                1





                $begingroup$

                There are a lot of different traits you could optimize for. I like to optimize for lines of code, so I'll try that.



                You can simplify the testing by building a "graph" (2-dimensional array) of reachable numbers. Each row and column index is a phone digit. If the value at (i,j) is true, then j is reachable from i.



                To do this, take all the numbers in each digit's row/column and create an array where those indexes have a value of 1.



                The reachability graph looks like this:



                enter image description here



                The digit 6 can reach 3,4,5,6,9 and you can see that reachable[6][x] is true for x=3,4,5,6 or 9.



                Then simply run through the list of numbers and test if reachable[current][next] is true.



                I've assumed the rook can dial repeated numbers like 3333. If no, you can test for that in the graph creation or during reachability testing.






                function rookTraversal(rows, phoneNumber) { 
                var cols=rows[0].map((col, i) => rows.map(row => row[i])),
                digits=phoneNumber.match(/(d)/g),
                reachable=;
                for (var row = 0; row < rows.length; row++) {
                for (var col = 0; col < cols.length; col++) {
                reachable[ rows[row][col] ] = rows[row].concat(cols[col]).reduce( (map, value) => { map[value]=1; return map }, );
                }
                }
                // console.log({reachable,digits});
                for (var i=0; i<digits.length-1; ++i) if (! reachable[ digits[i] ][ digits[i+1] ]) return false;
                return true;
                }

                var data = [
                [1, 2, 3],
                [4, 5, 6],
                [7, 8, 9],
                ];

                console.log(rookTraversal(data, '4631782'));
                console.log(rookTraversal(data, '4853267'));








                share|improve this answer











                $endgroup$



                There are a lot of different traits you could optimize for. I like to optimize for lines of code, so I'll try that.



                You can simplify the testing by building a "graph" (2-dimensional array) of reachable numbers. Each row and column index is a phone digit. If the value at (i,j) is true, then j is reachable from i.



                To do this, take all the numbers in each digit's row/column and create an array where those indexes have a value of 1.



                The reachability graph looks like this:



                enter image description here



                The digit 6 can reach 3,4,5,6,9 and you can see that reachable[6][x] is true for x=3,4,5,6 or 9.



                Then simply run through the list of numbers and test if reachable[current][next] is true.



                I've assumed the rook can dial repeated numbers like 3333. If no, you can test for that in the graph creation or during reachability testing.






                function rookTraversal(rows, phoneNumber) { 
                var cols=rows[0].map((col, i) => rows.map(row => row[i])),
                digits=phoneNumber.match(/(d)/g),
                reachable=;
                for (var row = 0; row < rows.length; row++) {
                for (var col = 0; col < cols.length; col++) {
                reachable[ rows[row][col] ] = rows[row].concat(cols[col]).reduce( (map, value) => { map[value]=1; return map }, );
                }
                }
                // console.log({reachable,digits});
                for (var i=0; i<digits.length-1; ++i) if (! reachable[ digits[i] ][ digits[i+1] ]) return false;
                return true;
                }

                var data = [
                [1, 2, 3],
                [4, 5, 6],
                [7, 8, 9],
                ];

                console.log(rookTraversal(data, '4631782'));
                console.log(rookTraversal(data, '4853267'));








                function rookTraversal(rows, phoneNumber) { 
                var cols=rows[0].map((col, i) => rows.map(row => row[i])),
                digits=phoneNumber.match(/(d)/g),
                reachable=;
                for (var row = 0; row < rows.length; row++) {
                for (var col = 0; col < cols.length; col++) {
                reachable[ rows[row][col] ] = rows[row].concat(cols[col]).reduce( (map, value) => { map[value]=1; return map }, );
                }
                }
                // console.log({reachable,digits});
                for (var i=0; i<digits.length-1; ++i) if (! reachable[ digits[i] ][ digits[i+1] ]) return false;
                return true;
                }

                var data = [
                [1, 2, 3],
                [4, 5, 6],
                [7, 8, 9],
                ];

                console.log(rookTraversal(data, '4631782'));
                console.log(rookTraversal(data, '4853267'));





                function rookTraversal(rows, phoneNumber) { 
                var cols=rows[0].map((col, i) => rows.map(row => row[i])),
                digits=phoneNumber.match(/(d)/g),
                reachable=;
                for (var row = 0; row < rows.length; row++) {
                for (var col = 0; col < cols.length; col++) {
                reachable[ rows[row][col] ] = rows[row].concat(cols[col]).reduce( (map, value) => { map[value]=1; return map }, );
                }
                }
                // console.log({reachable,digits});
                for (var i=0; i<digits.length-1; ++i) if (! reachable[ digits[i] ][ digits[i+1] ]) return false;
                return true;
                }

                var data = [
                [1, 2, 3],
                [4, 5, 6],
                [7, 8, 9],
                ];

                console.log(rookTraversal(data, '4631782'));
                console.log(rookTraversal(data, '4853267'));






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 6 hours ago

























                answered 6 hours ago









                Oh My GoodnessOh My Goodness

                39817




                39817






















                    a2441918 is a new contributor. Be nice, and check out our Code of Conduct.










                    draft saved

                    draft discarded


















                    a2441918 is a new contributor. Be nice, and check out our Code of Conduct.













                    a2441918 is a new contributor. Be nice, and check out our Code of Conduct.












                    a2441918 is a new contributor. Be nice, and check out our Code of Conduct.
















                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212873%2fcheck-whether-a-number-can-be-dialed-on-a-phone-keypad-without-diagonal-moves%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to reconfigure Docker Trusted Registry 2.x.x to use CEPH FS mount instead of NFS and other traditional...

                    is 'sed' thread safe

                    How to make a Squid Proxy server?