Java 8 coding challenge : Jarvis and Seven Segments

All over the world, peoples are working on energy solution. It would be a tough time for our next generation to survive if we don’t think about solution. Tony stark is working on a new project and wants to display his project using “seven segment display – concept”. Tony Stark gave Jarvis a task to find a number from his Favorite list of number for which the energy consumption is lowest.

(Assuming that for a digit to represent Tony stark is using 7 bulbs and only those bulbs light up which are required to represent a number and rest other would be completely off.)

Help Jarvis and conserve energy.

Seven segment display – https://en.wikipedia.org/wiki/Seven-segment_display

enter image description here

Input:
First line will contain the number of test cases and for every test case first line will contain length of favorite list and the second line for a test case will contain n numbers

Output:
For every test case print the answer. If there exist more than 1 numbers for which same number of bulbs are required than output the number which occurs first in the Favorite list.

Constraints:
Test cases< 10
A[i] < 10^6
Size of list < 10^5

SAMPLE INPUT
1
5
1 2 3 4 5
SAMPLE OUTPUT
1
Explanation

Number 1 needs only two bulbs to represent.

Code:

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
 
 
 
 
public class Solution {
 
 
 public static void main(String args[]) throws IOException{
 InputReader in=new InputReader(System.in);
 PrintWriter out=new PrintWriter(System.out);
 int T=in.readInt();
 
 while(T-->0){
 long N=in.readLong();
 long min=222222222;
 long minnum=0;
 while(N-->0){
 long num=in.readCount();
 long count=in.getcount();
 if(count<min){
 min=count;
 minnum=num;
 }
 }
 out.println(minnum);
 out.flush();
 
 }
 
 out.close();
 
 }
}
 
class InputReader{
 InputStream in;
 int[] segment={6,2,5,5,4,5,6,3,7,6};
 long count=0;
 InputReader(InputStream in){
 this.in=in;
 }
 
 public long getcount(){
 return count;
 }
 private int read() throws IOException{
 return in.read();
 }
 
 
 
 public char readChar() throws IOException{
 int n=read();
 while(isWhiteSpace(n)){
 n=read();
 }
 return (char)n;
 }
 
 public int readInt() throws IOException{
 int number=0;
 int n=read();
 while(isWhiteSpace(n)){
 n=read();
 }
 while(!isWhiteSpace(n)){
 int integer=n-'0';
 number*=10;
 number+=integer;
 n=read();
 }
 return number;
 }
 
 public long readCount() throws IOException{
 long number=0;
 count=0;
 int n=read();
 while(isWhiteSpace(n)){
 n=read();
 }
 while(!isWhiteSpace(n)){
 int integer=n-'0';
 count+=segment[integer];
 number*=10;
 number+=integer;
 n=read();
 }
 return number;
 }
 
 
 public long readLong() throws IOException{
 long number=0;
 int n=read();
 while(isWhiteSpace(n)){
 n=read();
 }
 while(!isWhiteSpace(n)){
 int integer=n-'0';
 number*=10;
 number+=integer;
 n=read();
 }
 return number;
 }
 
 private boolean isWhiteSpace(int n){
 if(n=='\n'||n=='\r'||n=='\t'||n==' '||n==-1){
 return true;
 }else{
 return false;
 }
 
 }
 }

Java 8 coding challenge: Addition ain’t simple

Jack is awesome. His friends call him little Einstein. To test him, his friends gave him a string. They told him to add the string with its reverse string and follow these rules:

  1. Every ith character of string will be added to every ith character of reverse string.
  2. Both string will contain only lower case alphabets(a-z).
  3. Eg:- a+a=b,a+c=d,z+a=a (Refer to sample test cases for more details)

Input:

First line contains a value N denoting number of test cases. Next N lines contains string str.

Output:

For every string str output the string that Jack’s friends wants from him.

Constraints

1 <= N <= 10

1 <= str <= 10^5

SAMPLE INPUT
4
hello
codeapocalypse
programming
world
SAMPLE OUTPUT
wqxqw
hhtdmqrrqmdthh
wfxtebetxfw
aajaa

Code:

import java.io.*;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
 

public class AdditionAintSimple {
 static class Print {
 private final BufferedWriter bw;
 
 public Print() {
 this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
 }
 
 public void print(Object object) throws IOException {
 bw.append("" + object);
 }
 
 public void println(Object object) throws IOException {
 print(object);
 bw.append("\n");
 }
 
 public void close() throws IOException {
 bw.close();
 }
 }
 
 static class Reader
 {
 final private int BUFFER_SIZE = 1 << 16;
 private DataInputStream din;
 private byte[] buffer;
 private int bufferPointer, bytesRead;
 
 public Reader()
 {
 din = new DataInputStream(System.in);
 buffer = new byte[BUFFER_SIZE];
 bufferPointer = bytesRead = 0;
 }
 
 public Reader(String file_name) throws IOException
 {
 din = new DataInputStream(new FileInputStream(file_name));
 buffer = new byte[BUFFER_SIZE];
 bufferPointer = bytesRead = 0;
 }
 
 public String readLine() throws IOException
 {
 byte[] buf = new byte[100000]; // line length
 int cnt = 0, c;
 while ((c = read()) != -1)
 {
 if (c == '\n')
 break;
 buf[cnt++] = (byte) c;
 }
 return new String(buf, 0, cnt);
 }
 
 public int nextInt() throws IOException
 {
 int ret = 0;
 byte c = read();
 while (c <= ' ')
 c = read();
 boolean neg = (c == '-');
 if (neg)
 c = read();
 do
 {
 ret = ret * 10 + c - '0';
 } while ((c = read()) >= '0' && c <= '9');
 
 if (neg)
 return -ret;
 return ret;
 }
 
 public long nextLong() throws IOException
 {
 long ret = 0;
 byte c = read();
 while (c <= ' ')
 c = read();
 boolean neg = (c == '-');
 if (neg)
 c = read();
 do {
 ret = ret * 10 + c - '0';
 }
 while ((c = read()) >= '0' && c <= '9');
 if (neg)
 return -ret;
 return ret;
 }
 
 public double nextDouble() throws IOException
 {
 double ret = 0, div = 1;
 byte c = read();
 while (c <= ' ')
 c = read();
 boolean neg = (c == '-');
 if (neg)
 c = read();
 
 do {
 ret = ret * 10 + c - '0';
 }
 while ((c = read()) >= '0' && c <= '9');
 
 if (c == '.')
 {
 while ((c = read()) >= '0' && c <= '9')
 {
 ret += (c - '0') / (div *= 10);
 }
 }
 
 if (neg)
 return -ret;
 return ret;
 }
 
 private void fillBuffer() throws IOException
 {
 bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
 if (bytesRead == -1)
 buffer[0] = -1;
 }
 
 private byte read() throws IOException
 {
 if (bufferPointer == bytesRead)
 fillBuffer();
 return buffer[bufferPointer++];
 }
 
 public void close() throws IOException
 {
 if (din == null)
 return;
 din.close();
 }
 }
 
 public static void main(String[] args) throws Exception{
 Reader rd = new Reader();
 Print pr = new Print();
 
 int t = rd.nextInt();
 String ip;
 
 
 int len;
 
 while(t-->0) {
 ip = rd.readLine();
 len = ip.length();
 char op[] = new char[len];
 
 for (int i = 0; i < len; i++) {
 op[i] = (char) ((( ip.charAt(i) + ip.charAt(len - i - 1) - 193) % 26)+97);
 }
 pr.println(String.valueOf(op));
 }
 pr.close();
 }
}

Java 8 Coding Challenge: COUNT NUMBERS

Your task is pretty simple , given a string S , find the total count of numbers present in the digit.

Input

The first line contains T , the number of test cases. The first line of each and every testc ase will contain a integer N , the length of the string . The second line of each and every test case will contain a string S of length N.

Output

For each and every testcase , output the total count of numbers present in the string.

Constraints

  1. 0<T<200
  2. 0<N<10000
SAMPLE INPUT
1
26
sadw96aeafae4awdw2wd100awd
SAMPLE OUTPUT
4
Explanation

For the first test case , the string given is “sadw96aeafae4awdw2wd100awd”. There are total of 4 numbers in the string – [96,4,2,100]. So , we output 4.

Code

import java.io.BufferedReader;
import java.io.InputStreamReader;
 
class TestClass {
 public static void main(String args[] ) throws Exception {
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 int T = Integer.parseInt(br.readLine());
 
 boolean bit=false;
 int count=0,i=0,j=0,N=0;
 char c='.';
 String ST = "";
 
 for (i=0; i<T; i++)
 {
 count=0;
 N = Integer.parseInt(br.readLine());
 ST = br.readLine();
 
 for(j=0; j<N; j++)
 {
 c = ST.charAt(j);
 if(c>47 && c<58)
 bit=true;
 else
 { if(bit)
 { bit=false;
 count++;
 }
 }
 }
 if(bit)
 { bit=false;
 count++;
 }
 System.out.println(count);
 }
 }
}

Higher order infrastructure

2017-03-11 17_30_38-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

2017-03-11 17_31_50-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

Developer need not to worry about the underlying infrastructure, all he/she has to look into is the services running on them and the stack they write.

You do not have to worry about where your code is running. Which leads to faster rollouts, faster releases, faster deployments. Even rollbacks have become piece of cake with having docker on your infrastructure.

2017-03-11 17_35_15-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

If there is any change in your service all you have to do is change the YAML (yet another markup language) file and you will have a completely new service in minutes.  Docker was build for scalabilty and high availability.

It is very easy to load balance your services in docker, scale up and scale down as per your requirements.

The most basic application that is demoed by docker, is the following cat and dog polling polygot application.

2017-03-11 17_43_31-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png2017-03-11 17_43_44-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

Each part of this application will be written and maintained by a different team. Add it will just get collaborated by docker.

2017-03-11 17_47_59-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

The above are the components required to get the docker application up and running.

2017-03-11 17_51_39-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

2017-03-11 17_51_54-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

2017-03-11 17_52_45-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

Docker swarm is a docker cluster manager that we can run our docker commands on and they will be executed on the whole cluster instead of just one machine.

The following is a docker swarm architecture:

2017-03-11 17_54_34-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

Containers provide an elegant solution for those looking to design and deploy applications at scale. While Docker provides the actual containerizing technology, many other projects assist in developing the tools needed for appropriate bootstrapping and communication in the deployment environment.

One of the core technologies that many Docker environments rely on is service discovery. Service discovery allows an application or component to discover information about their environment and neighbors. This is usually implemented as a distributed key-value store, which can also serve as a more general location to dictate configuration details. Configuring a service discovery tool allows you to separate your runtime configuration from the actual container, which allows you to reuse the same image in a number of environments.

The basic idea behind service discovery is that any new instance of an application should be able to programmatically identify the details of its current environment. This is required in order for the new instance to be able to “plug in” to the existing application environment without manual intervention. Service discovery tools are generally implemented as a globally accessible registry that stores information about the instances or services that are currently operating. Most of the time, in order to make this configuration fault tolerant and scalable, the registry is distributed among the available hosts in the infrastructure.

While the primary purpose of service discovery platforms is to serve connection details to link components together, they can be used more generally to store any type of configuration. Many deployments leverage this ability by writing their configuration data to the discovery tool. If the containers are configured so that they know to look for these details, they can modify their behavior based on what they find.

How Does Service Discovery Work?

Each service discovery tool provides an API that components can use to set or retrieve data. Because of this, for each component, the service discovery address must either be hard-coded into the application/container itself, or provided as an option at runtime. Typically the discovery service is implemented as a key-value store accessible using standard http methods.

The way a service discovery portal works is that each service, as it comes online, registers itself with the discovery tool. It records whatever information a related component might need in order to consume the service it provides. For instance, a MySQL database may register the IP address and port where the daemon is running, and optionally the username and credentials needed to sign in.

When a consumer of that service comes online, it is able to query the service discovery registry for information at a predefined endpoint. It can then interact with the components it needs based on the information it finds. One good example of this is a load balancer. It can find every backend server that it needs to feed traffic to by querying the service discovery portal and adjusting its configuration accordingly.

This takes the configuration details out of the containers themselves. One of the benefits of this is that it makes the component containers more flexible and less bound to a specific configuration. Another benefit is that it makes it simple to make your components react to new instances of a related service, allowing dynamic reconfiguration.

What Are Some Common Service Discovery Tools?

Now that we’ve discussed some of the general features of service discovery tools and globally distributed key-value stores, we can mention a few of the projects that relate to these concepts.

Some of the most common service discovery tools are:

  • etcd: This tool was created by the makers of CoreOS to provide service discovery and globally distributed configuration to both containers and the host systems themselves. It implements an http API and has a command line client available on each host machine.
  • consul: This service discovery platform has many advanced features that make it stand out including configurable health checks, ACL functionality, HAProxy configuration, etc.
  • zookeeper: This example is a bit older than the previous two, providing a more mature platform at the expense of some newer features.

Some other projects that expand basic service discovery are:

  • crypt: Crypt allows components to protect the information they write using public key encryption. The components that are meant to read the data can be given the decryption key. All other parties will be unable to read the data.
  • confd: Confd is a project aimed at allowing dynamic reconfiguration of arbitrary applications based on changes in the service discovery portal. The system involves a tool to watch relevant endpoints for changes, a templating system to build new configuration files based on the information gathered, and the ability to reload affected applications.
  • vulcand: Vulcand serves as a load balancer for groups of components. It is etcd aware and modifies its configuration based on changes detected in the store.
  • marathon: While marathon is mainly a scheduler (covered later), it also implements a basic ability to reload HAProxy when changes are made to the available services it should be balancing between.
  • frontrunner: This project hooks into marathon to provide a more robust solution for updating HAProxy.
  • synapse: This project introduces an embedded HAProxy instance that can route traffic to components.
  • nerve: Nerve is used in conjunction with synapse to provide health checks for individual component instances. If the component becomes unavailable, nerve updates synapse to bring the component out of rotation.

2017-03-11 18_01_52-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player2017-03-11 18_02_10-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player2017-03-11 18_02_27-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player

The command above is used to create a consul machine droplet in digital ocean.

2017-03-11 18_05_06-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

Use the above command to create docker swarm master which will attach to the consul.

2017-03-11 18_09_42-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

In docker swarm you can define your strategies in a very fine grain style.

2017-03-11 18_11_51-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

2017-03-11 18_12_38-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player2017-03-11 18_13_17-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player

2017-03-11 18_17_14-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player2017-03-11 18_17_32-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player2017-03-11 18_18_19-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player

To scale up all you have to type is docker-compose scale <your-service-name> and you are done.

auto-scaling will2017-03-11 18_28_03-GOTO2016•Higher-Download-From-YTPak.com.mp4 - VLC media player.png

Auto-scalng will need a monitoring service to be plugged in.

Java 8 coding challenge: Count Divisors

Problem:

You have been given 3 integers l, r and k. Find how many numbers between l and r (both inclusive) are divisible by k. You do not need to print these numbers, you just have to find their count.

Input Format
The first and only line of input contains 3 space separated integers l, r and k.

Output Format
Print the required answer on a single line.

Constraints
1lr10001≤l≤r≤1000
1k10001≤k≤1000

SAMPLE INPUT
1 10 1
SAMPLE OUTPUT
10

Code:

/* IMPORTANT: Multiple classes and nested static classes are supported */
 
/*
 * uncomment this if you want to read input.
//imports for BufferedReader
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
//import for Scanner and other utility classes
import java.util.*;
*/
import java.util.Scanner;
 
class TestClass {
 public static void main(String args[] ) throws Exception {
 Scanner sc = new Scanner(System.in);
 
 int l = sc.nextInt();
 int r = sc.nextInt();
 int k = sc.nextInt();
 
 sc.close();
 int count = 0;
 if(l == r && l%k != 0) {
 System.out.println(0);
 System.exit(0);
 }
 
 while (l <= r) {
 if(l % k == 0) {
 break;
 }
 l++;
 }
 
 count = (r - l) / k + 1;
 System.out.println(count);
 }
}

Java 8 coding challenge: Magical Word

Problem:

Dhananjay has recently learned about ASCII values.He is very fond of experimenting. With his knowledge of ASCII values and character he has developed a special word and named it Dhananjay’s Magical word.

A word which consist of alphabets whose ASCII values is a prime number is an Dhananjay’s Magical word. An alphabet is Dhananjay’s Magical alphabet if its ASCII value is prime.

Dhananjay’s nature is to boast about the things he know or have learnt about. So just to defame his friends he gives few string to his friends and ask them to convert it to Dhananjay’s Magical word. None of his friends would like to get insulted. Help them to convert the given strings to Dhananjay’s Magical Word.

Rules for converting:

1.Each character should be replaced by the nearest Dhananjay’s Magical alphabet.

2.If the character is equidistant with 2 Magical alphabets. The one with lower ASCII value will be considered as its replacement.

Input format:

First line of input contains an integer T number of test cases. Each test case contains an integer N (denoting the length of the string) and a string S.

Output Format:

For each test case, print Dhananjay’s Magical Word in a new line.

Constraints:

1 <= T <= 100

1 <= |S| <= 500

SAMPLE INPUT
1
6
AFREEN
SAMPLE OUTPUT
CGSCCO
Explanation

ASCII values of alphabets in AFREEN are 65, 70, 82, 69 ,69 and 78 respectively which are converted to CGSCCO with ASCII values 67, 71, 83, 67, 67, 79 respectively. All such ASCII values are prime numbers.

Code:

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
 

public class MagicalWord {
 static class Print {
 private final BufferedWriter bw;
 
 public Print() {
 this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
 }
 
 public void print(Object object) throws IOException {
 bw.append("" + object);
 }
 
 public void println(Object object) throws IOException {
 print(object);
 bw.append("\n");
 }
 
 public void close() throws IOException {
 bw.close();
 }
 }
 static class Reader {
 final private int BUFFER_SIZE = 1 << 16;
 private DataInputStream din;
 private byte[] buffer;
 private int bufferPointer, bytesRead;
 
 public Reader() {
 din = new DataInputStream(System.in);
 buffer = new byte[BUFFER_SIZE];
 bufferPointer = bytesRead = 0;
 }
 
 public String readLine() throws IOException {
 byte[] buf = new byte[100000]; // line length
 int cnt = 0, c;
 while ((c = read()) != -1) {
 if (c == '\n')
 break;
 buf[cnt++] = (byte) c;
 }
 return new String(buf, 0, cnt);
 }
 
 public int nextInt() throws IOException {
 int ret = 0;
 byte c = read();
 while (c <= ' ')
 c = read();
 boolean neg = (c == '-');
 if (neg)
 c = read();
 do {
 ret = ret * 10 + c - '0';
 } while ((c = read()) >= '0' && c <= '9');
 
 if (neg)
 return -ret;
 return ret;
 }
 
 private void fillBuffer() throws IOException {
 bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
 if (bytesRead == -1)
 buffer[0] = -1;
 }
 
 private byte read() throws IOException {
 if (bufferPointer == bytesRead)
 fillBuffer();
 return buffer[bufferPointer++];
 }
 
 public void close() throws IOException {
 if (din == null)
 return;
 din.close();
 }
 }
 
 public static void main(String[] args) throws Exception{
 Print pr = new Print();
 Reader rd = new Reader();
 
 
 Map<Character,Character> map = new HashMap<>();
 map.put('A','C');
 map.put('B','C');
 map.put('C','C');
 map.put('D','C');
 map.put('E','C');
 map.put('F','G');
 map.put('G','G');
 map.put('H','G');
 map.put('I','I');
 map.put('J','I');
 map.put('K','I');
 map.put('L','I');
 map.put('M','O');
 map.put('N','O');
 map.put('O','O');
 map.put('P','O');
 map.put('Q','O');
 map.put('R','S');
 map.put('S','S');
 map.put('T','S');
 map.put('U','S');
 map.put('V','S');
 map.put('W','Y');
 map.put('X','Y');
 map.put('Y','Y');
 map.put('Z','Y');
 map.put('a','a');
 map.put('b','a');
 map.put('c','a');
 map.put('d','e');
 map.put('e','e');
 map.put('f','e');
 map.put('g','g');
 map.put('h','g');
 map.put('i','g');
 map.put('j','k');
 map.put('k','k');
 map.put('l','k');
 map.put('m','m');
 map.put('n','m');
 map.put('o','m');
 map.put('p','q');
 map.put('q','q');
 map.put('r','q');
 map.put('s','q');
 map.put('t','q');
 map.put('u','q');
 map.put('v','q');
 map.put('w','q');
 map.put('x','q');
 map.put('y','q');
 map.put('z','q');
 
 map.put('\0','C');
 map.put('!','C');
 map.put('"','C');
 map.put('#','C');
 map.put('$','C');
 map.put('%','C');
 map.put('&','C');
 map.put('\'','C');
 map.put('(','C');
 map.put(')','C');
 map.put('*','C');
 map.put('+','C');
 map.put(',','C');
 map.put('-','C');
 map.put('.','C');
 map.put('/','C');
 map.put(':','C');
 map.put(';','C');
 map.put('<','C');
 map.put('=','C');
 map.put('>','C');
 map.put('?','C');
 map.put('@','C');
 map.put('[','Y');
 map.put('\\','Y');
 map.put(']','Y');
 map.put('^','a');
 map.put('_','a');
 map.put('`','a');
 map.put('{','q');
 map.put('|','q');
 map.put('}','q');
 map.put('~','q');
 
 map.put('0','C');
 map.put('1','C');
 map.put('2','C');
 map.put('3','C');
 map.put('4','C');
 map.put('5','C');
 map.put('6','C');
 map.put('7','C');
 map.put('8','C');
 map.put('9','C');
 
 int t = rd.nextInt();
 while(t-->0){
 int len = rd.nextInt();
 StringBuilder ip= new StringBuilder(rd.readLine());
 char op[] = new char[len];
 for(int i=0;i<len;i++){
 op[i] = map.get(ip.charAt(i));
 }
 pr.println(String.valueOf(op));
 }
 pr.close();
 }
 
}

Java 8 Coding challenge: Factorial!

Problem:

You have been given a positive integer N. You need to find and print the Factorial of this number. The Factorial of a positive integer N refers to the product of all number in the range from 1 to N.

Input Format:
The first and only line of the input contains a single integer N denoting the number whose factorial you need to find.

Output Format
Output a single line denoting the factorial of the number N.

Constraints
1≤N≤101≤N≤10
SAMPLE INPUT
2
SAMPLE OUTPUT
2

Code:

import java.util.*;
 
 
class TestClass {
 public static void main(String args[] ) throws Exception {
 
 try (Scanner input = new Scanner(System.in)) {
 
 int fatorial = input.nextInt();
 
 int total=fatorial;
 
 for(int i=fatorial-1;i>=1;i--){
 total = total * i;
 }
 
 System.out.println(total);
 
 
 } catch (Throwable e) {
 e.printStackTrace();
 }
 
 }
}

 

Java 8 coding challenge: Roy and Profile Picture

Problem:

Roy wants to change his profile picture on Facebook. Now Facebook has some restriction over the dimension of picture that we can upload.
Minimum dimension of the picture can be L x L, where L is the length of the side of square.

Now Roy has N photos of various dimensions.
Dimension of a photo is denoted as W x H
where W – width of the photo and H – Height of the photo

When any photo is uploaded following events may occur:

[1] If any of the width or height is less than L, user is prompted to upload another one. Print “UPLOAD ANOTHER” in this case.
[2] If width and height, both are large enough and
(a) if the photo is already square then it is accepted. Print “ACCEPTED” in this case.
(b) else user is prompted to crop it. Print “CROP IT” in this case.

(quotes are only for clarification)

Given L, N, W and H as input, print appropriate text as output.

Input:
First line contains L.
Second line contains N, number of photos.
Following N lines each contains two space separated integers W and H.

Output:
Print appropriate text for each photo in a new line.

Constraints:
1 <= L,W,H <= 10000
1 <= N <= 1000

SAMPLE INPUT
180
3
640 480
120 300
180 180
SAMPLE OUTPUT
CROP IT
UPLOAD ANOTHER
ACCEPTED

 Java code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
class TestClass {
 public static void main(String args[] ) throws Exception {
 try{
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 String line = br.readLine();
 int L = Integer.parseInt(line);
 line = br.readLine();
 int N = Integer.parseInt(line);
 int X[][]=new int[N][2];
 for(int i=0;i<N;i++){
 String input=br.readLine();
 String[] tokens = input.split(" ");
 X[i][0]=Integer.parseInt(tokens[0]);
 X[i][1]=Integer.parseInt(tokens[1]); 
 }
 for(int i=0;i<N;i++){
 if(X[i][0]<L||X[i][1]<L){
 System.out.println("UPLOAD ANOTHER");
 }
 else if(X[i][0]>=L&&X[i][1]>=L){
 if(X[i][0]==X[i][1])
 System.out.println("ACCEPTED");
 else
 System.out.println("CROP IT");
 }
 }
 }
 catch(Exception e){
 System.out.println(e);
 }
 
 
 
 }
}

Java

for(int x[]: nums) {
Notice how x is declared. It is a reference to a one-dimensional array of integers. This is
necessary because each iteration of the for obtains the next array in nums, beginning with
the array specified by nums[0]. The inner for loop then cycles through each of these arrays,
displaying the values of each element.

Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program. Each is examined here.
NOTE In addition to the jump statements discussed here, Java supports one other way that you can change your program’s flow of execution: through exception handling. Exception handling provides a structured method by which run-time errors can be trapped and handled by your program. It is supported by the keywords try, catch, throw, throws, and finally.

Using break as a Form of Goto
In addition to its uses with the switch statement and loops, the break statement can also be
employed by itself to provide a “civilized” form of the goto statement. Java does not have a
goto statement because it provides a way to branch in an arbitrary and unstructured
manner. This usually makes goto-ridden code hard to understand and hard to maintain. It
also prohibits certain compiler optimizations. There are, however, a few places where the
goto is a valuable and legitimate construct for flow control. For example, the goto can be
useful when you are exiting from a deeply nested set of loops. To handle such situations,
Java defines an expanded form of the break statement. By using this form of break, you can,
for example, break out of one or more blocks of code. These blocks need not be part of a
loop or a switch. They can be any block. Further, you can specify precisely where execution
will resume, because this form of break works with a label. As you will see, break gives you
the benefits of a goto without its problems.

Most often, label is the name of a label that identifies a block of code. This can be a standalone
block of code but it can also be a block that is the target of another statement. When
this form of break executes, control is transferred out of the named block. The labeled
block must enclose the break statement, but it does not need to be the immediately
enclosing block. This means, for example, that you can use a labeled break statement to
exit from a set of nested blocks. But you cannot use break to transfer control out of a block
that does not enclose the break statement.
To name a block, put a label at the start of it. A label is any valid Java identifier followed by
a colon. Once you have labeled a block, you can then use this label as the target of a break
statement. Doing so causes execution to resume at the end of the labeled block. For example,
the following program shows three nested blocks, each with its own label. The break statement
causes execution to jump forward, past the end of the block labeled second, skipping the two
println( ) statements.
// Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println(“Before the break.”);
if(t) break second; // break out of second block
System.out.println(“This won’t execute”);
}
System.out.println(“This won’t execute”);
}
System.out.println(“This is after second block.”);
}
}
}

// Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(” ” + (i * j));
}
}
System.out.println();
}
}

Box b1 = new Box();
Box b2 = b1;
// …
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
REMEMBER When you assign one object reference variable to another object reference variable, you are
not creating a copy of the object, you are only making a copy of the reference.

Sometimes an object will need to perform some action when it is destroyed. For example,
if an object is holding some non-Java resource such as a file handle or character font, then
you might want to make sure these resources are freed before an object is destroyed. To
handle such situations, Java provides a mechanism called finalization. By using finalization,
you can define specific actions that will occur when an object is just about to be reclaimed
by the garbage collector.
To add a finalizer to a class, you simply define the finalize( ) method. The Java run time
calls that method whenever it is about to recycle an object of that class. Inside the finalize( )
method, you will specify those actions that must be performed before an object is destroyed.
The garbage collector runs periodically, checking for objects that are no longer referenced
by any running state or indirectly through other referenced objects. Right before an asset is
freed, the Java run time calls the finalize( ) method on the object.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}

It is important to understand that finalize( ) is only called just prior to garbage collection.
It is not called when an object goes out-of-scope, for example. This means that you cannot
know when—or even if—finalize( ) will be executed. Therefore, your program should
provide other means of releasing system resources, etc., used by the object. It must not
rely on finalize( ) for normal program operation.
NOTE If you are familiar with C++, then you know that C++ allows you to define a destructor for a class,
which is called when an object goes out-of-scope. Java does not support this idea or provide for
destructors. The finalize( ) method only approximates the function of a destructor. As you get more
experienced with Java, you will see that the need for destructor functions is minimal because of
Java’s garbage collection subsystem.