# HackerRank : OpenBracket CodeSprint – Viral Advertising

HackerLand Enterprise is adopting a new viral advertising strategy. When they launch a new product, they advertise it to exactly people on social media.

On the first day, half of those people (i.e., ) like the advertisement and each person shares it with of their friends; the remaining people (i.e., ) delete the advertisement because it doesn’t interest them. So, at the beginning of the second day, people receive the advertisement.

On the second day, half of the people who received the advertisement share it with new friends. So, at the beginning of the third day, people receive the advertisement. The diagram below depicts the advertisement’s virality over the first three days (green denotes a person that likes the advertisement and red denotes a person that disliked and deleted it):

Assume that at the beginning of the day, people received the advertisement, people like and share it with new friends, and people dislike and delete it. At the beginning of the day, people receive the advertisement.

Given an integer, , find and print the total number of people who liked HackerLand Enterprise’s advertisementduring first days.

It is guaranteed that no two people have any friends in common and, after a person shares the advertisement with a friend, the friend always sees it the next day.

Input Format

A single integer, , denoting a number of days.

Output Format

Print the number of people who liked the advertisement during first days.

Sample Input

3


Sample Output

9


Explanation

This example is depicted by the diagram at the top of the challenge. people liked the advertisement on the first day, people liked the advertisement on the second day and people liked the advertisement on the third day, so the answer is 2+3+4=9.

Solution

At each level the number of advertisements are being multiplied by 3
and then half of them are passing to the next level.
So Basically it is following the formula (n*3)/2.

when n=2
count= ( 2*3)/2  =  3

when n=3
count= ( 3*3)/2  =  4

when n=4
count= ( 4*3)/2  =  6

---------------------
We just have to add these numbers to t times( which is the input from user ),
to get the final solution.

# How to View MultiRow messages in RedMi Mobiles

Its been a problem from quiet long to view the multi row whatsapp(or other messangers) messages in Xiomi or Redmi Mobiles from quite some time, well not now. You can view the messages on your messangers without opening the messanger.

Well, use your two fingers simultaneously to drag down the notification drawer and bamm.. you can view messages without opening messanger.

# HackerRank : Week of Code 24 – XOR Matrix

Consider a zero-indexed matrix with rows and columns, where each row is filled gradually. Given the first row of the matrix, you can generate the elements in the subsequent rows using the following formula:

Each row is generated one by one, from the second row through the last row. Given the first row of the matrix, find and print the elements of the last row as a single line of space-separated integers.

Note: The operator denotes bitwise XOR.

Input Format

The first line contains two space-separated integers denoting the respective values of (the number of columns in the matrix) and (the number of rows in the matrix).
The second line contains space-separated integers denoting the respective values of the elements in the matrix’s first row.

Constraints

Output Format

Print space-separated integers denoting the respective values of the elements in the last row of the matrix.

Sample Input

4 2
6 7 1 3


Sample Output

1 6 2 5


Explanation

We use the formula given above to calculate the values in the last row of the matrix:

We then print each value (in order) as a single line of space-separated integers.

Solution

Working on the Solution

# HackerRank : Week of Code 24 – Simplified Chess Engine

Chess is a very popular game played by hundreds of millions of people. Nowadays, we have chess engines such asStockfish and Komodo to help us analyze games. These engines are very powerful pieces of well-developed software that use intelligent ideas and algorithms to analyze positions and sequences of moves, as well as find tactical ideas. Consider the following simplified version of chess:

• Board: It’s played on a board between two players named Black and White.
• Pieces and Movement:
• White initially has pieces and Black initially has pieces.
• There are no Kings and no Pawns on the board. Each player has exactly one Queen, at most two Rooks, and at most two minor pieces (i.e., a Bishop and/or Knight).
• Each piece’s possible moves are the same as in classical chess, and each move made by any player counts as a single move.
• There is no draw when positions are repeated as there is in classical chess.
• Objective: The goal of the game is to capture the opponent’s Queen without losing your own.

Given and the layout of pieces for games of simplified chess, implement a very basic (in comparison to the real ones) engine for our simplified version of chess with the ability to determine whether or not White can win in moves (regardless of how Black plays) if White always moves first. For each game, print YES on a new line if White can win under the specified conditions; otherwise, print NO.

Input Format

The first line contains a single integer, , denoting the number of simplified chess games. The subsequent lines define each game in the following format:

• The first line contains three space-separated integers denoting the respective values of (the number of White pieces), (the number of Black pieces), and (the maximum number of moves we want to know if White can win in).
• The subsequent lines describe each chesspiece in the format t c r, where is a character denoting the type of piece (where is Queen, is Knight, is Bishop, and is Rook), and and denote the respective column and row on the board where the figure is placed (where and ). These inputs are given as follows:
• Each of the subsequent lines denotes the type and location of a White piece on the board.
• Each of the subsequent lines denotes the type and location of a Black piece on the board.

Constraints

• It is guaranteed that the locations of all pieces given as input are distinct.
• Each player initially has exactly one Queen, at most two Rooks and at most two minor pieces.

Output Format

For each of the games of simplified chess, print whether or not White can win in moves on a new line. If it’s possible, print YES; otherwise, print NO.

Sample Input

1
2 1 1
N B 2
Q B 1
Q A 4


Sample Output

YES


Explanation

We play games of simplified chess, where the initial piece layout is as follows:

White is the next to move, and they can win the game in move by taking their Knight to and capturing Black’s Queen. Because it took move to win and , we print YES on a new line.

Solution

Working on the Solution. In case you want any suggestions or the completed code,

public static void main(String[] args) {

Scanner scan= new Scanner(System.in);

int g= scan.nextInt();
int w=scan.nextInt();
int b= scan.nextInt();
int m= scan.nextInt();
scan.nextLine();
int blackQueenRow=0;
int blackQueenColumn=0;

Map <String, ArrayList> mapBlack=  new HashMap<String, ArrayList>();
Map <String, ArrayList> mapWhite= new HashMap<String, ArrayList>();

for(int i=0;i<w;i++)
{
ArrayList bList= new ArrayList();
String pawn = scan.next(), c = scan.next(),  r = scan.next();
pawn=pawn+i;

int column=0;

switch (c) {
case "A":
column=1;
break;
case "B":
column=2;
break;
case "C":
column=3;
break;
case "D":
column=4;
break;
}

board[Integer.parseInt(r)-1][column-1]=pawn;
mapWhite.put(pawn,bList);
}

for(int j=0;j<b;j++)
{
ArrayList wList= new ArrayList();
String pawn = scan.next(), c = scan.next(), r = scan.next();

int column=0;

switch (c) {
case "A":
column=1;
break;
case "B":
column=2;
break;
case "C":
column=3;
break;
case "D":
column=4;
break;
}

if(pawn.equals("Q"))
{
blackQueenRow=column-1;
blackQueenColumn=Integer.parseInt(r)-1;
}

pawn=pawn+j;

board[Integer.parseInt(r)-1][column-1]=pawn;
mapBlack.put(pawn,wList);
}

/*

System.out.println(mapBlack);
System.out.println(mapWhite);
*/

/*		for(int i=0;i<4;i++)
{
for(int j=0;j0;mm--)
{
for (Entry<String, ArrayList> entry : mapWhite.entrySet())
{
String key=entry.getKey();
ArrayList wList= entry.getValue();

String pType= String.valueOf(key.charAt(0));
isMate=(checkMate(pType, wList.get(0), wList.get(1), blackQueenRow, blackQueenColumn));
if(isMate==true)
break;
}
}

if(isMate==true)
System.out.println("YES");
else
System.out.println("NO");

}


# HackerRank : Week of Code 24 – Happy Ladybugs

Happy Ladybugs is a board game having the following properties:

• The board is represented by a string, , of length . The character of the string, , denotes the cell of the board.
• If is an underscore (i.e., _), it means the cell of the board is empty.
• If is an uppercase English alphabetic letter (i.e., A through Z), it means the cell contains a ladybug of color .
• String will not contain any other characters.
• A ladybug is happy only when its left or right adjacent cell (i.e., ) is occupied by another ladybug having the same color.
• In a single move, you can move a ladybug from its current position to any empty cell.

Given the values of and for games of Happy Ladybugs, determine if it’s possible to make all the ladybugs happy. For each game, print YES on a new line if all the ladybugs can be made happy through some number of moves; otherwise, print NO to indicate that no number of moves will result in all the ladybugs being happy.

Input Format

The first line contains an integer, , denoting the number of games. The subsequent lines describes a Happy Ladybugs game in the following format:

1. The first line contains an integer, , denoting the number of cells on the board.
2. The second line contains a string, , describing the cells of the board.

Constraints

• It is guaranteed that string consists of underscores and uppercase English alphabetic letters (i.e., _ and Athrough Z).

Output Format

For each game, print YES on a new line if it is possible to make all the ladybugs happy; otherwise, print NO.

Sample Input

4
7
RBY_YBR
6
X_Y__X
2
__
6
B_RRBR


Sample Output

YES
NO
YES
YES


Explanation

The first three games of Happy Ladybugs are explained below:

1. Initial board:

After the first move:

After the second move:

After the third move:

Now all the ladybugs are happy, so we print YES on a new line.
2. There is no way to make the ladybug having color Y happy, so we print NO on a new line.
3. There are no unhappy ladybugs, so we print YES on a new line.

Solution

Hint: there seems to be nested conditions to check all the scenarios.
My Approach:

I have created one utility function to check if the string contains all same
characters.

In my main I have written below logical conditions to check :

If string length is 1 & character is Underscore, then output is YES.
If string consists of all same characters, then output is YES.
ELSE:

I have constructed a map and store occurrences of each character and checked
below conditions:

if any character is present only one time other than underscore then output is NO
else, traverse the string and check if there is some character which has no similar
and if there is not even any underscore in the string, then output is NO.

Code for the Solution:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

public class Solution {
public static boolean isSame(String str) {
boolean isSame = true;

for (int i = 1; i < str.length() - 1; i++) {
if (str.charAt(i) != str.charAt(i - 1)) {
isSame = false;
break;
}
}
return isSame;
}

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

int t = scan.nextInt();

for (int i = 0; i < t; i++) {

int n = scan.nextInt();
scan.nextLine();
String str = scan.nextLine();

// only one underscore
if (str.length() == 1 && str.charAt(0) == '_') {
System.out.println("YES");
}
// all same
else if (isSame(str)) {
System.out.println("YES");
} else {

// construct map

Map map = new HashMap();
for (int j = 0; j < n; j++) {
String s = String.valueOf(str.charAt(j));
if (map.containsKey(s)) {
int val = map.get(s);
val++;
map.remove(s);
map.put(String.valueOf(s), val);
} else {
map.put(String.valueOf(s), 1);
}

}

// System.out.println(map);

int flag = 0;
for (Entry string : map.entrySet()) {

if (flag == 1)
break;
String key = string.getKey();
int value = string.getValue();

// underscore is there but any char is only one

if (value == 1
&& !string.getKey().equals(String.valueOf('_'))) {
System.out.println("NO");
flag = 1;
break;
} else {
for (int g = 1; g < n - 1; g++) {
if (str.charAt(g) == str.charAt(g - 1)
|| str.charAt(g) == str.charAt(g + 1)) {
} else {
if (str.contains(String.valueOf('_'))) {

} else {
if (map.size() == 1) {
} else {
System.out.println("NO");
flag = 1;
break;
}

}
}
}
}

}
if (flag == 0)
System.out.println("YES");

}

} // for closes

}
}



# HackerRank : Week of Code 24 – Apple and Orange

Sam’s house has an apple tree and an orange tree that yield an abundance of fruit. In the diagram below, the red region denotes his house, where is the start point and is the end point. The apple tree is to the left of his house, and the orange tree is to its right. You can assume the trees are located on a single point, where the apple tree is at point and the orange tree is at point .

When a fruit falls from its tree, it lands units of distance from its tree of origin along the -axis. A negative value of means the fruit fell units to the tree’s left, and a positive value of means it falls units to the tree’s right.

Given the value of for apples and oranges, can you determine how many apples and oranges will fall on Sam’s house (i.e., in the inclusive range )? Print the number of apples that fall on Sam’s house as your first line of output, then print the number of oranges that fall on Sam’s house as your second line of output.

Input Format

The first line contains two space-separated integers denoting the respective values of and .
The second line contains two space-separated integers denoting the respective values of and .
The third line contains two space-separated integers denoting the respective values of and .
The fourth line contains space-separated integers denoting the respective distances that each apple falls from point .
The fifth line contains space-separated integers denoting the respective distances that each orange falls from point .

Constraints

Output Format

Print two lines of output:

1. On the first line, print the number of apples that fall on Sam’s house.
2. On the second line, print the number of oranges that fall on Sam’s house.

Sample Input

7 11
5 15
3 2
-2 2 1
5 -6


Sample Output

1
1


Explanation

The first orange falls at position .
The second orange falls at position .
The third orange falls at position .
The first apple falls at position .
The second apple falls at position .
Only one fruit (the second orange) falls within the region between and , so we print as our first line of output.
Only the second apple falls within the region between and , so we print as our second line of output.

Solution


The Solution is pretty simple. We have to just add the x cordinate of each tree
with the fruit cordinate and check whether it falls in the range of the
house ( inclusively).



# CodeChef : October Challenge 2016 – Chef and Keyboard

Chef is a well known programmer. He owns a brand new Android phone of screen size of dimension n × m. Chef wants to design a program for painting the screen. He figured out c colors, which he will use to paint the screen. He wants to paint some rectangular section of pixels of the screen each with different color. Also Chef would like to use all of his c colors in painting.

Can you help Chef in finding number of different dimensions of rectangular section he can paint? In other words, find number of pairs x, y such that Chef can paint a rectangular section of dimension x × y on the screen. Please note that Chef uses a fix orientation of his phone and is not allowed to rotate it.

### Input

First line of the input contains an integer T denoting the number of test cases. T test cases follow.

Only line of each test case contains three space separated integers n, m, c.

### Output

For each test case, output a single line containing the answer for the test case.

### Constraints

• 1T100
• 1n, m106
• 1c106

• Subtask #1: (40 points) 1n, m100, 1c104
• Subtask #2: (60 points) original constraints

### Example

Input:
2
4 6 12
3 3 10

Output:
3
0


### Explanation

Test case 1. Possible pairs of dimensions are (2, 6), (3, 4) and (4, 3). Note that the rectangular section of dimension (1, 12) can’t be painted as it can’t fit into the screen, because 12 > 6.

Test case 2. There does not exist any rectangle of desired dimensions which can have 10 different pixels painted.

### Solution

Will be uploading the algo once the competition is over.

# HackerRank : Moody’s Analytics University Hackathon – Asterisk Expressions

In Mathematics, exponentiation has higher operator precedence than multiplication. This means that any exponentiation in the expression must be evaluated first before before any multiplication. For the purposes of this challenge, exponentiation is left-associative, which is different than you would normally evaluate it. This means that is evaluated as and not as .

In Python, the exponentiation operator is denoted by a double asterisk (**). For example, is expressed as a**k. To express multiplication, we use a single asterisk operator, *. For example, we express as a*b.

An expression, , consisting of decimal digits and asterisks is valid if and only if it forms a valid mathematical expression when each double-asterisk (i.e., **) is replaced with a math exponentiation sign. For example,2**4*5**3 is a valid expression translating to , while *2**3, 2***3, 4*5**, and 4**2* are invalid as they do not translate to valid mathematical expressions.

Given expressions consisting of decimal digits and asterisks, parse each expression and determine its validity. If an expression is valid, print its evaluated value modulo on a new line; if it’s invalid, print Syntax Errorinstead.

Input Format

The first line contains a single integer, , denoting the number of expressions.
Each line of the subsequent lines contains a single string, , denoting an expression.

Constraints

• There are at most consecutive digits in an expression.
• Consecutive sequences of digits in an expression will never start with .
• Each expression consists of decimal digits (i.e., through ) and asterisks (*) only.

Output Format

For each expression, , print its answer on a new line. If is valid, the answer is the evaluated expression ; otherwise, it’s Syntax Error.

Sample Input

Sample Input 0

1
3*2**3**2*5


Sample Output 0

960


Explanation 0
We have expression to evaluate. Because exponentiation has higher operator precedence than multiplication, and because exponentiation is left-associative here, the expression evaluates to . Thus, we print on a new line.

Sample Input 1

1
3***4


Sample Output 1

Syntax Error


Explanation 1
We have expression to evaluate. Because this expression contains three consecutive asterisks, it cannot be evaluated as a mathematical expression. Thus, we print Syntax Error on a new line.

Solution

Only 1st and 2nd test cases are passing as of now. Trying to debug other corner cases and solve them.



public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */	Scanner scan= new Scanner(System.in);

int n=scan.nextInt();
scan.nextLine();

for (int i = 0; i < n; i++) {
String str= scan.nextLine();

if(str.charAt(0)=='*' || str.contains("***") || str.charAt(str.length()-1)=='*')
System.out.println("Syntax Error");

else if( str.contains("*0*") || str.charAt(0)=='0' || str.charAt(str.length()-1)=='0')
{
System.out.println("0");
break;
}

else
{
char a[]= str.toCharArray();

Stack  st= new Stack();

st.push(String.valueOf(str.charAt(0)));

for(i=2;i<str.length();i++)
{

if(str.charAt(i)!='*' && str.charAt(i-1)=='*' && str.charAt(i-2)!='*' )
{
int initial=i;

while(initial!=str.length()-1 )
{

if(str.charAt(initial+1)=='*')
break;
else
initial++;
}

String sub=str.substring(i,initial+1);
i=initial;
st.push(sub);

}

if(str.charAt(i)!='*'  && str.charAt(i-1)=='*' && str.charAt(i-2)=='*' )
{
int initial=i;

while(initial!=str.length()-1 )
{

if(str.charAt(initial+1)=='*')
break;
else
initial++;
}

String sub=str.substring(i,initial+1);
i=initial;

int pop= Integer.parseInt(st.pop());
int b= Integer.parseInt(sub);
int mul=  (int) Math.pow(pop, b);
st.push(String.valueOf(mul));
}

if(str.charAt(i)=='*')
{

}

}

int f=1;
for (String string : st) {
f=f* Integer.parseInt(string);
}
System.out.println(f);

}
}

}



# HackerRank : Moody’s Analytics University Hackathon – Small Risk Trading

A company can make at most of available trades. Each available trade has the following properties:

• : A floating-point number denoting the trade’s probability of being profitable.
• : A floating-point number denoting the trade’s potential profit.
• : A floating-point number denoting the trade’s potential loss, which has a probability of .

Given the values of , , and , , and for each trade , find and print the maximum expected amount of money the company can make by performing at most of the trades.

Input Format

The first line contains two space-separated integers denoting the respective values of (the number of trades available) and (the maximum number of trades allowed).
The second line contains space-separated floating-point numbers describing the respective values of , where each denotes the probability that the transaction will result in a profit.
The third line contains space-separated floating-point numbers describing the respective values of , where each denotes the possible profit of the transaction.
The fourth line contains space-separated floating-point numbers describing the respective values of , where each denotes the possible loss of the transaction.

Constraints

• All , , and are floating-point numbers scaled to exactly one decimal place (i.e., format).

Output Format

Print the maximum expected amount of money that can be made by performing at most of the available trades. Scale your answer to exactly decimal places (i.e., format).

Sample Input 0

4 2
0.5 0.5 0.5 0.5
4.0 1.0 2.0 3.0
4.0 0.5 1.0 1.0


Sample Output 0

1.50


Explanation 0
There are transactions available and we can perform at most of them. We also know that the probability that each transaction results in a profit is . If the third and the fourth transactions are performed, the expected amount of money made from these transactions is: ; because this is greater than all the other possibilities we could calculate, we print as our answer (recall that we must scale our answer to two decimal places).

Sample Input 1

2 2
0.9 0.5
1.0 0.5
100.0 0.4


Sample Output 1

0.05


Explanation 1
There are transactions available and we can perform at most of them. The probability that the first transaction is profitable is , while the probability that the second transaction is profitable is . We can maximize our potential profit by only performing the second transaction, which has an expected value of ; thus, we print as our answer.

Solution

Thanks to Maxxy for suggesting the approach here.
The approach to solution is :

Store probability of profits(p) in a List.
Similarly store potential profits(x) and potential loss(y) in two other array lists.

Now traverse the lists and store corresponding profits ( calculated as per the formula given
in description).