HackerRank: Sherlock and The Beast

Problem Statement

Sherlock Holmes suspects his archenemy, Professor Moriarty, is once again plotting something diabolical. Sherlock’s companion, Dr. Watson, suggests Moriarty may be responsible for MI6’s recent issues with their supercomputer, The Beast.

Shortly after resolving to investigate, Sherlock receives a note from Moriarty boasting about infecting The Beastwith a virus; however, he also gives him a clue—a number, NN. Sherlock determines the key to removing the virus is to find the largest Decent Number having NN digits.

A Decent Number has the following properties:

  1. Its digits can only be 3‘s and/or 5‘s.
  2. The number of 3‘s it contains is divisible by 5.
  3. The number of 5‘s it contains is divisible by 3.
  4. If there are more than one such number, we pick the largest one.

Moriarty’s virus shows a clock counting down to The Beast‘s destruction, and time is running out fast. Your task is to help Sherlock find the key before The Beast is destroyed!

Constraints
1T201≤T≤20
1N1000001≤N≤100000

Input Format

The first line is an integer, TT, denoting the number of test cases.

The TT subsequent lines each contain an integer, NN, detailing the number of digits in the number.

Output Format

Print the largest Decent Number having NN digits; if no such number exists, tell Sherlock by printing -1.

Sample Input

4
1
3
5
11

Sample Output

-1
555
33333
55555533333

Explanation

For N=1, there is no decent number having 1 digit (so we print 1−1).
For N=3, 555 is the only possible number. The number 5 appears three times in this number, so our count of 5‘s is evenly divisible by 3 (Decent Number Property 3).
For N=5, 33333 is the only possible number. The number 3 appears five times in this number, so our count of 3‘s is evenly divisible by 5 (Decent Number Property 2).
For N=11, 55555533333 and all permutations of these digits are valid numbers; among them, the given number is the largest one.

Solution:

2D Array: Hour Glass problem solution

Problem Statement:

You are given a 2D array with dimensions 6*6. An hourglass in an array is defined as a portion shaped like this:

a b c
  d
e f g

For example, if we create an hourglass using the number 1 within an array full of zeros, it may look like this:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

Actually, there are many hourglasses in the array above. The three topmost hourglasses are the following:

1 1 1     1 1 0     1 0 0
  1         0         0
1 1 1     1 1 0     1 0 0

The sum of an hourglass is the sum of all the numbers within it. The sum for the hourglasses above are 7, 4, and 2, respectively.

In this problem, you have to print the largest sum among all the hourglasses in the array.

Note: If you have already solved the problem “Java 2D array” in the data structures chapter of the Java domain, you may skip this challenge.

Input Format

There will be exactly 6 lines of input, each containing 6 integers separated by spaces. Each integer will be between -9 and 9, inclusively.

Output Format

Print the answer to this problem on a single line.

Sample Input

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

Sample Output

19

Explanation

The hourglass possessing the largest sum is:

2 4 4
  2
1 2 4

Solution:

HackerRank: Sparse Arrays

Problem Statement

There are N strings. Each string’s length is no more than 2020 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.

Input Format

The first line contains N, the number of strings.
The next N lines each contain a string.
The N+2nd line contains Q, the number of queries.
The following Q lines each contain a query string.

Constraints

1N1000
1Q1000
1lengtof anstring20

Sample Input

4
aba
baba
aba
xzxb
3
aba
xzxb
ab

Sample Output

2
1
0

Explanation

Here, “aba” occurs twice, in the first and third string. The string “xzxb” occurs once in the fourth string, and “ab” does not occur at all.

Solution

Code to merge list of PDFs using Itext Library

Here is the code to merge and output a single pdf from a set of PDFs in a folder.

In order to run and get the output just pass the folder path in the main method and the output will be saved in the same folder as the files.

Please share comments…:)

Unable to find valid certification path to requested target

Most of you must be familiar with the below exception message:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

When trying to open an SSL connection to a host using Java.

Sample Code(source):

What this usually means is that the server is using a test certificate (possibly generated using keytool) rather than a certificate from a well known commercial Certification Authority such as Verisign or GoDaddy.

Web browsers display warning dialogs in this case, but since JSSE cannot assume an interactive user is present it just throws an exception by default.

To bypass this issue and be able to get the contents of a HTTPS url here is the steps:

First: use the below class code to install the required certificates(Source):

I was testing this on wikipedia.org, which is on https, thus facing the https issue.
You can modify the same as per requirement.

Next, set the following arguments while running JVM(source):

-Djavax.net.ssl.trustStore=<local path to certs>/jssecacerts

Next use the below code to get the contents(Source):

Easy Rules: Java™ rules engine

Easy Rules is a Java rules engine inspired by an article called Should I use a Rules Engine? by Martin Fowler in which he says:

You can build a simple rules engine yourself. All you need is to create a bunch of objects with conditions and actions, store them in a collection, and run through them to evaluate the conditions and execute the actions.

Core features

  • Lightweight library and easy to learn API
  • POJO based development with annotation programming model
  • Useful abstractions to define business rules and apply them easily with Java
  • The ability to create composite rules from primitive ones
  • Dynamic rule configuration at runtime using JMX

Example

Hello World tutorial

This tutorial shows how to use Easy Rules in a very simple application. The goal is to ask the user if he is a friend of duke and says ‘Hello duke’s friend!’ only if he replies ‘yes’.

Based on this requirement, the rule is pretty straightforward :

  • The condition is that the user input must be equal to ‘yes’
  • The action is to say ‘Hello duke’s friend!’ to the user

First, let’s create a rule class:

@Rule(name = "Hello World rule",
    description = "Say Hello to duke's friends only")
public class HelloWorldRule {

    /**
     * The user input which represents the data
     * that the rule will operate on.
     */
    private String input;

    @Condition
    public boolean checkInput() {
        //The rule should be applied only if
        //the user's response is yes (duke friend)
        return input.equalsIgnoreCase("yes");
    }

    @Action
    public void sayHelloToDukeFriend() throws Exception {
        //When rule conditions are satisfied,
        //prints 'Hello duke's friend!' to the console
        System.out.println("Hello duke's friend!");
    }

    public void setInput(String input) {
        this.input = input;
    }

}

Then, we have to register an instance of this rule in a Easy Rules engine and launch the tutorial with the following class:

public class Launcher {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Are you a friend of duke?[yes/no]:");
        String input = scanner.nextLine();

        /**
         * Declare the rule
         */
        HelloWorldRule helloWorldRule = new HelloWorldRule();

        /**
         * Set business data to operate on
         */
        helloWorldRule.setInput(input.trim());

        /**
         * Create a rules engine and register the business rule
         */
        RulesEngine rulesEngine = aNewRulesEngine().build();

        rulesEngine.registerRule(helloWorldRule);

        /**
         * Fire rules
         */
        rulesEngine.fireRules();

    }
}

You would get the following output:

Are you a friend of duke? [yes/no]:
yes
INFO: Rule 'Hello World rule' triggered.
Hello duke's friend!
INFO: Rule 'Hello World rule' performed successfully.

Source

How to fix: Unsupported major.minor version xy.z error?

Occasionally in certain new environments using some libraries, we face the following Exception:

java.lang.UnsupportedClassVersionError: test_hello_world :
 Unsupported major.minor version 51.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
       .........................................

The problem here is about versions; some version of Java may be old or too new.

The version number shown describes the version of the JRE the class file is compatible with.

The reported major numbers are:

J2SE 8 = 52,
J2SE 7 = 51,
J2SE 6.0 = 50,
J2SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45

(Source: wiki)

To fix the actual problem you should try to either run the Java code with a newer version of Java JRE or specify the target parameter to the Java compiler to instruct the compiler to create code compatible with earlier Java versions.

With newer versions of the Java compiler you are likely to get a warning about the bootstrap class path not being set. More information about this error is available in blog post New javac warning for setting an older source without bootclasspath.

Source

How to read a properties file in a web application

Let’s consider that you have a war file named SampleApp.war which has a properties file named MyApp.properties at it’s root

SampleApp.war
   |- myApp.properties
   |- WEB-INF
     |- classes
       |- org
          |- myApp
          |- MyPropertiesReader.class


Here root folder in war is equivalent to Source Folder in Netbeans.
That means you have to keep your properties file in default package of your Source Files folder.
Let’s assume that you want to read the property named “abc” present in the properties file:


myApp.properties:

abc=some value
xyz=some other value

Let’s consider that the class org.myApp. MyPropertiesReader present in your application wants to read the property. Here’s the code for the same:

package org.myapp;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MyPropertiesReader {

    public MyPropertiesReader() {
    }

    public void doSomeOperation() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("myApp.properties");
        Properties properties = new Properties();
        System.out.println("InputStream is: " + inputStream);
        properties.load(inputStream);
        String propValue = properties.getProperty("abc");
        System.out.println("Property value is: " + propValue);
    }
}

Now suppose the properties file is not at the root of the application, but inside a folder (let’s name it config) in the web application, something like:

SampleApp.war
   |- config
    |- myApp.properties   
   |- WEB-INF
    |- classes
      |- org
         |- myApp
           |- MyPropertiesReader.class

There will just be one line change in the above code:

public void doSomeOperation() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("config/myApp.properties");
        Properties properties = new Properties();
        System.out.println("InputStream is: " + inputStream);
        properties.load(inputStream);
        String propValue = properties.getProperty("abc");
        System.out.println("Property value is: " + propValue);
    }

 

Source