Learn Java so Far so Good Java 1D Array

code_puzzleHi, I am happy to announce, that my learn Java journey at the Hacker Rank is going very nice. Today I was very happy to solve the code puzzle named Java 1D Array (Part 2) and this puzzle has already 39.64% success rate. And it category Data Structure Challenges most of the code puzzles has more than 90% of success rate. So far, so good, I have in Java 313 points and 2067 rank :). I have to say that Java is cool. I am solving Hacker Rank puzzles in Java 7 and today I decided to start to prepare for certifications but I will be learning for certifications in Java 8. Below you can see solution of mentioned above code puzzle. The nice thing in this code is showing how to build algorithm that play simple game. And how to make strategy by using Stack class. I am not algorithm expert but I like this way to solve this kind of issues. What do you think? Is it correct? Thanks for reading!

import java.io.*;
import java.util.*;
import java.util.Collections;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        for(int i = 0; i < t; ++i){
            int n = sc.nextInt();
            int m = sc.nextInt();
            int[] arr = new int[n];
            boolean win = false;
            for(int j = 0; j < n; ++j){
                arr[j] = sc.nextInt();
            }
            int c = 0;
            int move = 0;
            Stack<Integer> strategy = new Stack<Integer>();
            strategy.push(0);
            while(strategy.size() > 0){
                move = strategy.pop();
                if (move >= n-1){
                    win = true;
                    break;
                }
                if (arr[move] == 0 && move+m < n && arr[move+m] == 0 || move+m >= n){
                    strategy.push(move+m);
                    ++c;
                    int minm = move+m;
                    if (minm > 0 && minm < n){
                        while (arr[minm] == 0 && minm > 0 && arr[minm - 1] == 0){
                            --minm;
                        }
                        strategy.push(minm);
                        ++c;
                    }
                }
                if (arr[move] == 0 && move+1 < n && arr[move+1] == 0 || move+1 >= n){
                    strategy.push(move+1);
                    ++c;
                }
                if (c > 10*n) break; // how deep the rabbit whole is? :)
            }
            System.out.println(win ? "YES" : "NO");
        }
    }
}

Enjoy!

p ;).

Leave a Reply

Your email address will not be published. Required fields are marked *

*