HackerRank: CodeWhiz.java March 2016: Java Singleton

Problem

“The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.”
Wikipedia: Singleton Pattern


Complete the Singleton class in your editor which contains the following components:

  1. A private Singleton non parameterized constructor.
  2. A public String instance variable named strstr.
  3. Write a static method named getSingleInstance that returns the single instance of theSingleton class.

Once submitted, our hidden Solution class will check your code by taking a String as input and then using yourSingleton class to print a line.

Input Format

You will not be handling any input in this challenge.

Output Format

You will not be producing any output in this challenge.

Sample Input

hello world

Sample Output

Hello I am a singleton! Let me say hello world to you

Solution

Automated script to renew IP config on network issues

I had been facing an issue recently in my system that the network connection often got lost and the network icon would start showing the yellow icon indicating that no internet connection is available even though the system is connected to the network.

To solve this I had to run the command

IPCONFIG /RENEW

I had to do this every time and many times would realize that the system had been offline for a while.

Started becoming a bummer to me when others needed to access to my system.

I implemented this script and fired it on startup. It performs a simple task

  • Check if google.com is reachable
  • If Not then run IPCONFIG command
  • if the state is not changed even after this command. that means that your system is actually down. therefore stop retrying

Here is the script:

HackerRank: Cavity Map

Problem

You are given a square map of size n×nn×n. Each cell of the map has a value denoting its depth. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has strictly smaller depth. Two cells are adjacent if they have a common side (edge).

You need to find all the cavities on the map and depict them with the uppercase character X.

Input Format

The first line contains an integer, nn, denoting the size of the map. Each of the following nn lines contains nnpositive digits without spaces. Each digit (1-9) denotes the depth of the appropriate area.

Constraints
1n1001≤n≤100

Output Format

Output nn lines, denoting the resulting map. Each cavity should be replaced with character X.

Sample Input

4
1112
1912
1892
1234

Sample Output

1112
1X12
18X2
1234

Explanation

The two cells with the depth of 9 fulfill all the conditions of the Cavity definition and have been replaced by X.

Solution

HackerRank: The Grid Search

Problem

Given a 2D array of digits, try to find the occurrence of a given 2D pattern of digits. For example, consider the following 2D matrix:

1234567890  
0987654321  
1111111111  
1111111111  
2222222222  

Assume we need to look for the following 2D pattern:

876543  
111111  
111111

If we scan through the original array, we observe that the 2D pattern begins at the second row and the third column of the larger grid (the 8 in the second row and third column of the larger grid is the top-left corner of the pattern we are searching for).

So, a 2D pattern of P digits is said to be present in a larger grid G, if the latter contains a contiguous, rectangular 2D grid of digits matching with the pattern P, similar to the example shown above.

Input Format
The first line contains an integer, T, which is the number of test cases. T test cases follow, each having a structure as described below:
The first line contains two space-separated integers, R and C, indicating the number of rows and columns in the grid G, respectively.
This is followed by R lines, each with a string of C digits, which represent the grid G.
The following line contains two space-separated integers, r and c, indicating the number of rows and columns in the pattern grid P.
This is followed by r lines, each with a string of c digits, which represent the pattern P.

Constraints
1T5
1R,r,C,c1000
1rR
1cC

Test Case Generation
Each individual test case has been generated by first specifying the size (R and C) of the large 2D matrix, and then randomly generating the digits in it. A limited number of digits in the larger matrix may be changed by the problem setter (no more than 5% of the total number of digits in the matrix). So the larger 2D matrix is almost-random. The pattern matrix has been manually-curated by the problem setter.

Output Format
Display ‘YES’ or ‘NO’, depending on whether (or not) you find that the larger grid GG contains the rectangular pattern PP. The evaluation will be case sensitive.

Sample Input

2
10 10
7283455864
6731158619
8988242643
3830589324
2229505813
5633845374
6473530293
7053106601
0834282956
4607924137
3 4
9505
3845
3530
15 15
400453592126560
114213133098692
474386082879648
522356951189169
887109450487496
252802633388782
502771484966748
075975207693780
511799789562806
404007454272504
549043809916080
962410809534811
445893523733475
768705303214174
650629270887160
2 2
99
99

Sample Output

YES
NO

Explanation

The first test in the input file is:

10 10
7283455864
6731158619
8988242643
3830589324
2229505813
5633845374
6473530293
7053106601
0834282956
4607924137
3 4
9505
3845
3530

As one may see, the given 2D grid is indeed present in the larger grid, as marked in bold below.

7283455864  
6731158619  
8988242643  
3830589324  
2229505813  
5633845374  
6473530293  
7053106601  
0834282956  
4607924137  

The second test in the input file is:

15 15
400453592126560
114213133098692
474386082879648
522356951189169
887109450487496
252802633388782
502771484966748
075975207693780
511799789562806
404007454272504
549043809916080
962410809534811
445893523733475
768705303214174
650629270887160
2 2
99
99

The search pattern is:

99
99

This cannot be found in the larger grid.

Solution

HackerRank: Chocolate Feast

Problem

Little Bob loves chocolate, and he goes to a store with $N$N in his pocket. The price of each chocolate is $C$C. The store offers a discount: for every MM wrappers he gives to the store, he gets one chocolate for free. How many chocolates does Bob get to eat?

Input Format:
The first line contains the number of test cases, TT.
TT lines follow, each of which contains three integers, NN, CC, and MM.

Output Format:
Print the total number of chocolates Bob eats.

Constraints:
1T10001≤T≤1000
2N1052≤N≤105
1CN1≤C≤N
2MN2≤M≤N

Sample input

3
10 2 5
12 4 4
6 2 2

Sample Output

6
3
5

Explanation
In the first case, he can buy 5 chocolates with $10 and exchange the 5 wrappers to get one more chocolate. Thus, the total number of chocolates is 6.

In the second case, he can buy 3 chocolates for $12. However, it takes 4 wrappers to get one more chocolate. He can’t avail the offer and hence the total number of chocolates remains 3.

In the third case, he can buy 3 chocolates for $6. Now he can exchange 2 of the 3 wrappers and get 1 additional piece of chocolate. Now he can use his 1 unused wrapper and the 1 wrapper of the new piece of chocolate to get one more piece of chocolate. So the total is 5.

Solution

HackerRank: Encryption

Problem

An English text needs to be encrypted using the following encryption scheme.
First, the spaces are removed from the text. Let LL be the length of this text.
Then, characters are written into a grid, whose rows and columns have the following constraints:

  • LrowscolumnL⌊L⌋≤rows≤column≤⌈L⌉, where x⌊x⌋ is floor function and x⌈x⌉ is ceil function

For example, the sentence if man was meant to stay on the ground god would have given us roots after removing spaces is 5454 characters long, so it is written in the form of a grid with 7 rows and 8 columns.

ifmanwas  
meanttos          
tayonthe  
groundgo  
dwouldha  
vegivenu  
sroots
  • Ensure that rows×columnsLrows×columns≥L
  • If multiple grids satisfy the above conditions, choose the one with the minimum area, i.e. rows×columnsrows×columns.

The encoded message is obtained by displaying the characters in a column, inserting a space, and then displaying the next column and inserting a space, and so on. For example, the encoded message for the above rectangle is:

imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau

You will be given a message in English with no spaces between the words. The maximum message length can be8181 characters. Print the encoded message.

Here are some more examples:

Sample Input:

haveaniceday

Sample Output:

hae and via ecy

Sample Input:

feedthedog    

Sample Output:

fto ehg ee dd

Sample Input:

chillout

Sample Output:

clu hlt io

Solution

 

How to get current datetime on Windows command line for using in a filename?

Lets say you want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, Code_2008-10-14_2257.zip

In a windows console(CMD), the following command helps you get what you need

@echo off
For /f "tokens=2-4 delims=/ " %a in ('date /t') do (set mydate=%c-%a-%b)
For /f "tokens=1-2 delims=/:" %a in ('time /t') do (set mytime=%a-%b)
echo %mydate%_%mytime%
@echo on

echo "Testing 123" >> "testFile_%mydate%_%mytime%.txt"

This would output the filename appended with the desired time format.

Source

Util Method to get all attributes printed in System.out.println()

This small util override is to allow developers to view all instance variable values as a CSV format in Java. It is similar to the one seen as var_dump in PHP:

    @Override
    public String toString() {
        Field[] fields = this.getClass().getDeclaredFields();
        StringBuilder sbNote = new StringBuilder();
        sbNote.append("{");
        for (int i = 0; i < fields.length; i++) {
            try {
                sbNote.append(fields[i].getName() + " - " + fields[i].get(this)+", ");
            } catch (java.lang.IllegalAccessException e) {
                System.out.println(e);
            }
        }
        sbNote.append("}");
        return sbNote.toString();
    }

override the toString() method to the above code to get a comma separated description enclosed in {}

Another useful library is the Apache commons –

public String toString() {
       return ToStringBuilder.reflectionToString(this);
}