2D array traversal to get distinct 7 digit number combos

匆匆过客 提交于 2019-12-11 07:54:24

问题


I ran into a tricky question from an interview prep book which goes.. You have a 3 by 3 matrix containing integers 1 to 9 as shown below

 1 2 3
 4 5 6
 7 8 9

How do you get unique 7 digit number combos with the first numbers all starting with 4 (matrix[1][0]). The traversal is meant to be like that of a rook on a chess board.. 1 way either horizontally or vertically...(Having 4125874 is valid 7 digit combo btw).

I tried writing some code and doing regular 2D matrix traversal with a boolean visited flag here to get an answer and storing each combo in a hashSet to ensure uniqueness but I am stuck. Any kind comments, hints and code revisions to get me code working would be appreciated.

class Ideone
{

    void dfs(int[][] matrix, boolean visited) //considered dfs with a boolean visited flag but I am stuck. I want to make my solution recursive
    {
        boolean visited =  false;

    }

    public static HashSet<String> get7DigitCombo(int[][] matrix)
    {
        String result = "";
        int[][] cache =  matrix.clone();
        Set<String> comboSet =  new HashSet<String>();
        boolean visited =  false;

        int resultStart = matrix[1][0];

        for(int row = 1; row < matrix.length; row++)
        {
            for(int col = 0; col < matrix[0].length; col++)
            {
                if (visited == false & result.length < 7)
                {
                    result += "" + (matrix[row + 1][col] || matrix[row -1][col] || matrix[row][col+1] || matrix[row][col-1]);
                }

            }
        }

        comboSet.add(result);
        return comboSet;
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        int[][] matrix =  {{1, 2, 3},
                          {4, 5, 6}, 
                          {7, 8, 9},
                          };

        HashSet<String> comboSet =  get7DigitCombo(matrix);

        System.out.print(comboSet);
    }
}

回答1:


The following mcve demonstrates recursively getting neighbors and accumulating then into unique combinations.
The code is documented with comments:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Ideone
{
    private static final int SIZE = 7;     //size of combo 

    private static int[][] directions = {  //represents moving directions 
            {-1, 0},  //up
            { 0,-1},  //left
            { 0, 1},  //right
            { 1, 0}   //down
    };

    public static void main (String[] args) throws java.lang.Exception
    {
        int[][] matrix =  {{1, 2, 3},
                {4, 5, 6},
                {7, 8, 9},
        };
        Set<String> comboSet =  get7DigitCombo(matrix);
        System.out.print(comboSet.size());
    }

    public static Set<String> get7DigitCombo(int[][] matrix)
    {
        Set<String> comboSet =  new HashSet<>();

        get7DigitCombo(1, 0, matrix, String.valueOf(matrix[1][0]), comboSet);
        return comboSet;
    }

     //recursively get all neighbors. generate combos by appending each neighbor 
    //combo represents a single combination. combos accumulates combination 
    static void get7DigitCombo(int row, int col, int[][] matrix, String combo, Set<String> combos){

        if(combo !=null && combo.length() == SIZE) { //when combo reached the right size, add it  
            //System.out.println(combo);
            combos.add(combo);
            return;
        }

        //get and iterate over all adjacent neighbors 
        for(int[] neighbor : getNeighbors(row, col, matrix)){
            get7DigitCombo(neighbor[0], neighbor[1], matrix, combo+neighbor[2], combos);
        }
    }

    //return list of adjacent neighbors. each neighbor is represented by
    //int[3]: row, column, value
    private static List<int[]> getNeighbors(int row, int col, int[][] matrix) {

        List<int[]> neighbors = new ArrayList<>();
        for(int[] dir : directions){
            int newRow = row + dir[0] ; int newCol = col + dir[1];
            if(isValidAddress(newRow, newCol, matrix)) {
                neighbors.add( new int[]{newRow,newCol, matrix[newRow][newCol]});
            }
        }
        return neighbors;
    }

    private static boolean isValidAddress(int row, int col, int[][] matrix) {

        if(row < 0 || col < 0) return false;
        if(row >= matrix.length || col >= matrix[row].length) return false;
        return true;
    }
} 



回答2:


This is a pacman problem. You must look for or define the neighbors of each matrix value. Then cross the matrix fallowing the neighbors of each matrix value. It usually resolves with recursive functions. I think you code must be change from the ground using a different approach.



来源:https://stackoverflow.com/questions/54973940/2d-array-traversal-to-get-distinct-7-digit-number-combos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!