Sunday 31 March 2019

Can You Access? HackerRank Java Solution

Problem:-

You are given a class Solution and an inner class Inner.Private. The main method of class Solution takes an integer  as input. The powerof2 in class Inner.Private checks whether a number is a power of . You have to call the method powerof2 of the class Inner.Private from the main method of the class Solution.
Constraints 
Sample Input
8
Sample Output
8 is power of 2
An instance of class: Solution.Inner.Private has been created

Solution:-

import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.regex.*;
import java.security.*;


public class Solution {

    public static void main(String[] args) throws Exception {
        DoNotTerminate.forbidExit();    

        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int num = Integer.parseInt(br.readLine().trim());
            Object o;// Must be used to hold the reference of the instance of the class Solution.Inner.Private
o = new Inner().new Private();
System.out.println(num + " is " + ((Solution.Inner.Private)o).powerof2(num));
        System.out.println("An instance of class: " + o.getClass().getCanonicalName() + " has been created");
        
        }//end of try
        
        catch (DoNotTerminate.ExitTrappedException e) {
            System.out.println("Unsuccessful Termination!!");
        }
    }//end of main
    static class Inner{
        private class Private{
            private String powerof2(int num){
                return ((num&num-1)==0)?"power of 2":"not a power of 2";
            }
        }
    }//end of Inner
    
}//end of Solution

class DoNotTerminate { //This class prevents exit(0)
    
public static class ExitTrappedException extends SecurityException {

        private static final long serialVersionUID = 1L;
}
public static void forbidExit() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
}   
    

Java Varargs - Simple Addition

Problem:-

You are given a class Solution and its main method in the editor. 
Your task is to create the class Add and the required methods so that the code prints the sum of the numbers passed to the function add.
Note: Your add method in the Add class must print the sum as given in the Sample Output
Input Format
There are six lines of input, each containing an integer.
Output Format
There will be only four lines of output. Each line contains the sum of the integers passed as the parameters to add in the mainmethod.
Sample Input
1
2
3
4
5
6
Sample Output
1+2=3
1+2+3=6
1+2+3+4+5=15
1+2+3+4+5+6=21

Solution:-

import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Add {
public void add(int... intArgs) {
int sum = 0;
String separator = "";
for (int i : intArgs) {
sum += i;
System.out.print(separator + i);
separator = "+";
}
System.out.println("=" + sum);
}
}


public class Solution {

public static void main(String[] args) {
try{
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            int n1=Integer.parseInt(br.readLine());
            int n2=Integer.parseInt(br.readLine());
            int n3=Integer.parseInt(br.readLine());
            int n4=Integer.parseInt(br.readLine());
            int n5=Integer.parseInt(br.readLine());
            int n6=Integer.parseInt(br.readLine());
            Add ob=new Add();
            ob.add(n1,n2);
            ob.add(n1,n2,n3);
            ob.add(n1,n2,n3,n4,n5); 
            ob.add(n1,n2,n3,n4,n5,n6);
            Method[] methods=Add.class.getDeclaredMethods();
            Set<String> set=new HashSet<>();
            boolean overload=false;
            for(int i=0;i<methods.length;i++)
            {
                if(set.contains(methods[i].getName()))
                {
                    overload=true;
                    break;
                }
                set.add(methods[i].getName());
                
            }
            if(overload)
            {
                throw new Exception("Overloading not allowed");
            }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        
    
    

}

Java Iterator HackerRank Solution

Problem:-

Java Iterator class can help you to iterate through every element in a collection. Here is a simple example:
import java.util.*;
public class Example{

    public static void main(String []args){
        ArrayList mylist = new ArrayList();
        mylist.add("Hello");
        mylist.add("Java");
        mylist.add("4");
        Iterator it = mylist.iterator();
        while(it.hasNext()){
            Object element = it.next();
            System.out.println((String)element);
        }
    }
}
In this problem you need to complete a method func. The method takes an ArrayList as input. In that ArrayList there is one or more integer numbers, then there is a special string "###", after that there are one or more other strings. A sample ArrayListmay look like this:
element[0]=>42
element[1]=>10
element[2]=>"###"
element[3]=>"Hello"
element[4]=>"Java"
You have to modify the func method by editing at most 2 lines so that the code only prints the elements after the special string "###". For the sample above the output will be:
Hello
Java
Note: The stdin doesn't contain the string "###", it is added in the main method.
To restore the original code in the editor, click the top left icon on the editor and create a new buffer.

Solution:-

import java.util.*;
public class Main{
    
static Iterator func(ArrayList mylist){
Iterator it=mylist.iterator();
while(it.hasNext()){
Object element = it.next();
if(element instanceof String && ("###".equals((String)element)))

            break;
        }
return it;
}
@SuppressWarnings({ "unchecked" })
public static void main(String []args){
ArrayList mylist = new ArrayList();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
for(int i = 0;i<n;i++){
mylist.add(sc.nextInt());
}
mylist.add("###");
for(int i=0;i<m;i++){
mylist.add(sc.next());
}
Iterator it=func(mylist);
while(it.hasNext()){
Object element = it.next();
System.out.println((String)element);
}
}
}

Saturday 30 March 2019

Java Priority Queue HackerRank Solution

Problem:-

In computer science, a priority queue is an abstract data type which is like a regular queue, but where additionally each element has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority. - Wikipedia

In this problem we will test your knowledge on Java Priority Queue.
There are a number of students in a school who wait to be served. Two types of events, ENTER and SERVED, can take place which are described below.
  • ENTER: A student with some priority enters the queue to be served.
  • SERVED: The student with the highest priority is served (removed) from the queue.
A unique id is assigned to each student entering the queue. The queue serves the students based on the following criteria (priority criteria):
  1. The student having the highest Cumulative Grade Point Average (CGPA) is served first.
  2. Any students having the same CGPA will be served by name in ascending case-sensitive alphabetical order.
  3. Any students having the same CGPA and name will be served in ascending order of the id.
Create the following two classes:
  • The Student class should implement:
    • The constructor Student(int id, String name, double cgpa).
    • The method int getID() to return the id of the student.
    • The method String getName() to return the name of the student.
    • The method double getCGPA() to return the CGPA of the student.
  • The Priorities class should implement the method List<Student> getStudents(List<String> events) to process all the given events and return all the students yet to be served in the priority order.
Input Format
The first line contains an integer, , describing the total number of events. Each of the  subsequent lines will be of the following two forms:
  • ENTER name CGPA id: The student to be inserted into the priority queue.
  • SERVED: The highest priority student in the queue was served.
The locked stub code in the editor reads the input and tests the correctness of the Student and Priorities classes implementation.
Constraints
Output Format
The locked stub code prints the names of the students yet to be served in the priority order. If there are no such student, then the code prints EMPTY.
Sample Input 0
12
ENTER John 3.75 50
ENTER Mark 3.8 24
ENTER Shafaet 3.7 35
SERVED
SERVED
ENTER Samiha 3.85 36
SERVED
ENTER Ashley 3.9 42
ENTER Maria 3.6 46
ENTER Anik 3.95 49
ENTER Dan 3.95 50
SERVED
Sample Output 0
Dan
Ashley
Shafaet
Maria
Explanation 0
In this case, the number of events is 12. Let the name of the queue be Q.
  • John is added to Q. So, it contains (John, 3.75, 50).
  • Mark is added to Q. So, it contains (John, 3.75, 50) and (Mark, 3.8, 24).
  • Shafaet is added to Q. So, it contains (John, 3.75, 50), (Mark, 3.8, 24), and (Shafaet, 3.7, 35).
  • Mark is served as he has the highest CGPA. So, Q contains (John, 3.75, 50) and (Shafaet, 3.7, 35).
  • John is served next as he has the highest CGPA. So, Q contains (Shafaet, 3.7, 35).
  • Samiha is added to Q. So, it contains (Shafaet, 3.7, 35) and (Samiha, 3.85, 36).
  • Samiha is served as she has the highest CGPA. So, Q contains (Shafaet, 3.7, 35).
  • Now, four more students are added to Q. So, it contains (Shafaet, 3.7, 35), (Ashley, 3.9, 42), (Maria, 3.6, 46), (Anik, 3.95, 49), and (Dan, 3.95, 50).
  • Anik is served because though both Anil and Dan have the highest CGPA but Anik comes first when sorted in alphabetic order. So, Q contains (Dan, 3.95, 50), (Ashley, 3.9, 42), (Shafaet, 3.7, 35), and (Maria, 3.6, 46).
As all events are completed, the name of each of the remaining students is printed on a new line.

Solution:-

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.*;
class Student implements Comparable<Student>{
String name = new String();
double cgpa;
int id;
public Student(String name,double cgpa,int id)
{
this.name = name;
this.cgpa = cgpa;
this.id = id;
}
public String getName(){
return this.name;
}
public int compareTo(Student s)
{
if(cgpa == s.cgpa)
{
if(name.compareTo(s.name) == 0)
{
if(id == s.id)
return 0;
else if (id > s.id)
return 1;
else
return -1;
}
else
return name.compareTo(s.name);
}
else if(cgpa > s.cgpa)
return -1;
else
return 1;
}
}

class Priorities{
public ArrayList<Student> getStudents(List<String> events)
{
int n = events.size();
PriorityQueue<Student> pq = new PriorityQueue<Student>();
for(String i:events)
{
String[] s = new String[4];
s = i.split("\\s");
if(s.length>1)
{
pq.add(new Student(s[1],Double.valueOf(s[2]),Integer.valueOf(s[3])));
}
else
{
pq.poll();
}
}
while(pq.size()>1)
{
System.out.println(pq.poll().name);
}
return new ArrayList<Student>(pq);
}
}

public class Solution {
private final static Scanner scan = new Scanner(System.in);
private final static Priorities priorities = new Priorities();
public static void main(String[] args) {
int totalEvents = Integer.parseInt(scan.nextLine());
List<String> events = new ArrayList<>();
while (totalEvents-- != 0) {
String event = scan.nextLine();
events.add(event);
}
List<Student> students = priorities.getStudents(events);
if (students.isEmpty()) {
System.out.println("EMPTY");
} else {
for (Student st: students) {
System.out.println(st.getName());
}
}
}
}

Error While embed the video in Your website page

Error:- Refused to display '<URL>' in a frame because it set 'X-Frame-Options' to 'sameorigin Solution:- if ...