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 pleased to solve the code puzzle named Java 1D Array (Part 2), and this puzzle already has a 39.64% success rate. And its category of Data Structure Challenges, most of the code puzzles have more than a 90% success rate. So far, so good. I have 313 points in Java and a 2067 rank :). I have to say that Java is cool. I am solving Hacker Rank puzzles in Java 7, I decided to start to prepare for certifications, but I will be learning for certifications in Java 8. Below you can see the solution to mentioned above code puzzle. The nice thing about this code is showing how to build an algorithm that plays a simple game. And how to make a strategy by using the Stack class. I am not an algorithm expert, but I like this way of solving this issue. 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 hole is? :)
            }
            System.out.println(win ? "YES" : "NO");
        }
    }
}

Enjoy!

p ;).

Leave a Reply

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

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.