JavaRush /Java Blog /Random EN /Conquering CodeWars (Solving the 4kyu problem)

Conquering CodeWars (Solving the 4kyu problem)

Published in the Random EN group
Hi all! This is not a success story, but I have to say a few words about myself. I started learning Java in February of this year (on our beloved CodeGymConquest of CodeWars (We solve the problem 4kyu) - 1 of course ), and at some point I realized that I needed more GOLD practices. This is how I stumbled upon CodeWars. In order to register there, you must complete a test task, which I could not successfully solve in February, but when I returned in April, I broke through this wall. Everyone starts at rank 8kyu, the highest 1kyu. When I started, I immediately started solving 7kyu, which I successfully did, then in a couple of days I solved a couple more tasks of ranks 6kyu -7kyu and one 5kyu. Thus successfully received 6kyu. And then it started.... I wanted to climb higher, but tasks 5-3kyu increase their complexity in some geometric progression (there is no talk about 1 and 2 at all😬). However, I continued in the end with a couple of 5, 4 and one 3 jumped to the rank of 5kyu, where I am now. PS The most pleasant thing on CodeWars is that after solving a task, you can see how others solved it (and the guys are tough there). In general, try it. I will not give a link, they will think that advertising) Let's move on to dessert, solve an interesting 4Kyu problem (although I would rate it as 5kyu). Condition: Everyone knows about the game Sudoku , where we must fill the 9x9 matrix with numbers from 1 to 9. At the same time, the numbers should not be repeated in each row and column, and the numbers should not be repeated in 3x3 squares (Look at Wikipedia :)) / We must write a method that will check the matrix for correct filling in which case return true. If the matrix contains 0, then this element is considered empty, respectively, false. (The link to this kata , I can send the task to the PM) Solution: The solution will have to be divided into three blocks otherwise, the code will not be displayed correctly (taught by bitter experience)
public class SudokuSolutionValidator {
    public static void main(String[] args) {
        int[][] matrix = {
                        {5, 3, 4,  6, 7, 8,  9, 1, 2},
                        {6, 7, 2,  1, 9, 5,  3, 4, 8},
                        {1, 9, 8,  3, 4, 2,  5, 6, 7},
                        {8, 5, 9,  7, 6, 1,  4, 2, 3},
                        {4, 2, 6,  8, 5, 3,  7, 9, 1},
                        {7, 1, 3,  9, 2, 4,  8, 5, 6},
                        {9, 6, 1,  5, 3, 7,  2, 8, 4},
                        {2, 8, 7,  4, 1, 9,  6, 3, 5},
                        {3, 4, 5,  2, 8, 6,  1, 7, 9}};
        System.out.println(validSolution(matrix));
    }

    public static boolean validSolution(int[][] matrix) {
//  Проверяем нашу матрицу на наличие 0
        for (int[] array : matrix) {
            for (int element : array) {
                if (element == 0) return false;
            }
        }
        if ((checkVerticalAndHorizontal(matrix))&&(check3v3squares(matrix)))
            return true;
        else return false;
    }

//   В методе checkVerticalAndHorizontal() проверим на правильность заполнения
//   наши строки и столбцы
    private static boolean checkVerticalAndHorizontal (int[][] matrix) {

//  4 переменные, преднаmeaning которых вы узнает ниже)
        int vertical = 0;
        int horizontal = 0;
        int horizontalCount = 0;
        int verticalCount = 0;

        for (int i = 0; i < 9; i++) {
            for (int j = 1; j < 10; j++) {

                for (int k = 0; k < 9; k++) {
                    if (matrix[i][k] == j) {
                        horizontalCount++;
//  В данном случае, мы проверяли наличие повторов в строках,
//  Если вы уберете break (выход из цикла "k"), и раскомментируйте
//  code ниже, вы увидите Howого числа не хватает, а Howой элемент дублируется дважды и более
//  System.out.println("matrix[i][k] = " + matrix[i][k] + "meaning element = " + j+"_______"+ "индекс element в строке "+k);
                        break;
                    }
                }


                for (int k = 0; k < 9; k++) {
//  А тут проверяем столбцы. Как вы понимаете, наличие
//  ошибки в строке свидетельствует об ошибке в столбце :D
                    if (matrix[k][i] == j) {
                        verticalCount++;
//              элемент совпал +, элемент не совпал 0.
//              еще раз повторюсь, break нужен для того, чтобы не ловить повторы.
                        break;
                    }
                }
//  Далее закомментирована метка, которая служит навигатором по циклам
//               System.out.println("______________________");

            }
            if (horizontalCount == 9) horizontal++;
            if (verticalCount == 9) vertical++;
            horizontalCount = 0;
            verticalCount = 0;
//  Две конструкции if выше How раз и реализуют мою основную идею проверки столбцов и строк,
//  а именно при переборе всех значений (от 1 до 9) в циклах k мы проверям соответствует ли
//  строка и столбец заданному условию or нет.
        }
//  если наши переменные vertical и horizontal равны 9 каждая,
//  значит со столбцами и строками проблем нет.
        if ((vertical == 9)&&(horizontal==9)) return true;
        else return false;
    }

//  В методе check3v3squares() переходим к сладкому, проверка квадратов 3на3
    private static boolean check3v3squares(int[][] matrix) {

        int transitionDown = 0;
        int transitionRight = 0;
        int lastCount = 0;
//  По квадратам будем двигаться вниз, дойдя до низа на шаг влево.
//  По достижению правого нижнего квадрата выходим из цикла. ( в сумме 9 квадратов (3на3), соответственно
//  внешний круг должен содержать 9 итераций)

        for ( int x = 0; x<9; x++) {
            if(transitionDown == 9) {
                transitionRight +=3;
                transitionDown = 0;
            }
//  В циклах ниже я реализовали движение по квадратам 3х3 и их проверку.
//  Переменная key нужна для того, чтобы избежать повторной проверки одного
//  и того же числа (тоесть при наличии 2 одинаковых чисел, мы увеличиваем счетчик на 1, а не 2)
            for (int k = 1; k < 10; k++) {
                int key = 0;
                for (int i = 0; i < 3; i++) {
                        for (int j = 0; j < 3; j++) {
                        if ((k == matrix[i+transitionDown][j+transitionRight])&&(key!=k)) {
                            lastCount++;
                            key = k;
                        }
                    }
                }
            }
            transitionDown += 3;
        }
//  Счетчик lastCount должен вернуть число 81, если оно меньше, то не обошлось без повторов
        if(lastCount == 81) return true;
        else return false;
    }
}
It turned out to put the whole code :) Do not judge strictly, it will be better in the future. One of these days I will try to find and post another interesting puzzle :) Thank you for reading :) Another article from me: Creating a "Magic Square"Conquest of CodeWars (We solve the problem 4kyu) - 2
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION