Monday, June 19, 2017

TopCoderSolutions


Problem Statement
SMS messages are short messages sent between mobile phones. The maximum length of a single message is 160 characters, so it is often necessary to abbreviate words.
You are given a String text, and your task is to translate it to SMS language according to the following rules:
Remove all punctuation symbols ('.', ',', '?' and '!').
Replace all uppercase letters with their lowercase equivalents.
Replace all occurrences of "and" with '&'.
Replace all occurrences of "ate" with '8'.
Replace all occurrences of "at" with '@'.
Replace all occurrences of "you" with 'U'.
All quotes are for clarity only. The rules must be applied in the order they appear in the list. For example, "I HATE rats, and you?" will be translated to "i h8 r@s & U".
Return the resulting translation as a String.

Definition
   
Class: SMSLanguage
Method: translate
Parameters: String
Returns: String
Method signature: String translate(String text)
(be sure your method is public)
 

Constraints
- text will contain between 1 and 50 characters, inclusive.
- text will contain only letters ('a'-'z', 'A'-'Z'), the characters ',', '.', '!', '?', and spaces (' ').

Examples
0)
   
"I HATE rats, and you?"
Returns: "i h8 r@s & U"
The example from the problem statement.
1)
   
"What is the weather like today?"
Returns: "wh@ is the we@her like today"
2)
   
"It is not too late to.."
Returns: "it is not too l8 to"
3)
   
"this text is already in sms language"
Returns: "this text is already in sms language"

public class SMSLanguage {
public  String translate(String text){
String s1 = text.replaceAll("\\.", "").
replaceAll("\\!", "").
replaceAll("\\?", "").
replaceAll("\\,", "");

String s2 = s1.toLowerCase().
replaceAll("you", "U").
replaceAll("and", "&").
replaceAll("ate", "8")
.replaceAll("at", "@");

return s2;

}
}
*********************************************************************************

Problem Statement
   
Some texts contain hidden messages. In the context of this problem, the hidden message of a text is composed of the first letter from each word in the text, in the order they appear.

Given a String text, consisting of only lowercase letters and spaces, return the hidden message. A word is a maximal sequence of consecutive letters. There may be multiple spaces between words. Also, text may contain only spaces.


Definition
   
Class: HiddenMessage
Method: getMessage
Parameters: String
Returns: String
Method signature: String getMessage(String text)
(be sure your method is public)
    

Constraints
- text will contain between 1 and 50 characters, inclusive.
- Each character of text will be either a lowercase letter ('a'-'z'), or a space (' ').

Examples
0)
   
"compete online design event rating"
Returns: "coder"
Taking the first letter from each word yields the return "coder".
1)
   
"  c    o d     e      r    "
Returns: "coder"
Watch out for the leading spaces.
2)
   
"round  elimination during  onsite  contest"
Returns: "redoc"
"coder" written backwards.
3)
   
" "
Returns: ""
Since there are no words here, the empty string must be returned.

import java.util.StringTokenizer;

public class HiddenMessage {
public static void main(String[] args) {
System.out.println(getMessage("  c   od  e r"));
}

public static String getMessageOld(String text) {
String param[] = text.split(" ");
String res = "";

for (String r : param) {
if (r.length() > 0)
r = r.substring(0, 1);

res = res + r;
}
return res;
}
public static String getMessage(String text) {
String res = "";
StringTokenizer st = new  StringTokenizer(text);
while(st.hasMoreTokens()){
res = res+ st.nextToken().charAt(0);
}
return res;
}

}
*********************************************************************************
Problem Statement
   
You are working for the financial institution TopBank, and you have been tasked with writing a module that will take an initial account balance, along with a list of that day's transactions, and return the ending balance for the day.

Each transaction will be either a credit, which adds funds to the account, or a debit, which removes funds from the account. If a debit exceeds the available funds at the time, then the account balance will go negative. You will be given an int startingBalance, the initial account balance. You will also be given a String[] transactions, the list of transactions for the day. Each element of transactions will be in the form "type amount" (quotes added for clarity). Each type will be 'C' or 'D', for credit or debit, respectively. Each amount will be an integer between 1 and 1000000, inclusive, with no leading zeros. You are to return an int representing the ending balance after processing all of the transactions.


Definition
   
Class: AccountBalance
Method: processTransactions
Parameters: int, String[]
Returns: int
Method signature: int processTransactions(int startingBalance, String[] transactions)
(be sure your method is public)
    

Constraints
- startingBalance will be between 0 and 1000000, inclusive.
- transactions will have between 0 and 50 elements, inclusive.
- Each element of transactions will be formatted as "type amount" (quotes added for clarity).
- Each type will be 'C' or 'D'.
- Each amount will represent an integer between 1 and 1000000, inclusive, with no leading zeros.

Examples
0)
   
100
{"C 1000", "D 500", "D 350"}
Returns: 250
This person had 100 dollars, got their paycheck, then went shopping at two different stores. 100 + 1000 - 500 - 350 = 250.
1)
   
100
{}
Returns: 100
With no transactions, the balance doesn't change by the end of the day.
2)
   
100
{"D 50", "D 20", "D 40"}
Returns: -10
Uh oh! This person's account is overdrawn.
3)
   
53874
{"D 1234", "C 987", "D 2345", "C 654", "D 6789", "D 34567"}
Returns: 10580


public class AccountBalance {

public static int processTransactions(int startingBalance, String[] transactions) {

for (String trans : transactions) {
String param[] = trans.split(" ");
String TransType = param[0];

if (TransType.equalsIgnoreCase("C")) {
startingBalance = startingBalance + Integer.valueOf(param[1]);
}

else if (TransType.equalsIgnoreCase("D")) {
startingBalance = startingBalance - Integer.valueOf(param[1]);
}
}

return startingBalance;

}

}

*********************************************************************************

Java Interview Question

1. Difference between replace() and replaceAll() ?
2. Should we use StringTokenizer  or Split()

Thursday, June 15, 2017

What is a ConcurrentModificationException can anyone explain this to me in depth.

If any one ask you what is a ConcurrentModificationException ?
The straight forward answer is "It is thrown only when you are trying to iterate through a collection like list/map and at the same time you are making changes to the collection" 
then ConcurrentModificationException   will be thrown.

humm that's its
Are you willing to know whats happening behind the scenes, if interested continue reading.

Every collection in Java List/Map maintains a transient variable modCount.
modCount is the count howmany times the structure of the collection List/Map has been changes.

Every entry to List or every put operation on Map will increment the modCount by one.




There is one more variable expectedModCount 
expectedModCount which is initialized to the modCount while the iterator is created.

Later on, during every iteration, the iterator verifies if the expectedModCount is same as the modCount of the collection it is iterating over. A mismatch means that the collection
has been modified during the life cycle of the iterator and a ConcurrentModificationException is thrown.






Note 
If you have a Map and you are just changing the value of the Map this will not result in the ConcurrentModificationException as the structure of the Map is not changes

Where as if you are trying to update both the key and value of a Map then in this case ConcurrentModificationException will be thrown.

while (it1.hasNext()) 
{
 String key = it1.next();
   if (key.equals("3")) {
myMap.put(key + "new", "new3");  //Line 1
myMap.put(key, "new3");  //Line 2
    }


}


In above code Line 1 will result in a ConcurrentModificationException as the structure of the map is being changes

Line 2 will not result in ConcurrentModificationException  as the structure of the Map is not changed

What is the reason behind “non-static method cannot be referenced from a static context”

We have seen this is a very common interview question
"“non-static method cannot be referenced from a static context" but most of us does't have clear understanding about why is that soo.

Lets understand this concept.

1. First what do we understand by static : Static variable/methods means these will be loaded/creates   at the time of creation of class. So we got to know static variable/method will be created in memory when the class is loaded and these static variable and method will hold some default values in it.

2.One more this these static variable and method can be accessed using the class name itself, no need to created the object for that.

Above two points i guess every one knows.

Now whats the pain in “non-static method cannot be referenced from a static context"

lets see when the static method and non static methods are created in memory.

Static methods are created when the class is loaded.
Non static methods are created when object for that class is creates.

So if static method will hold reference of non static , and static methods are created when the class is loaded , and the non static will only be created only when  object of the class is created.
So all the calls associated withing static block are not fulfilled.
As is contains ref to a non static block of code, which only be populated when the object for the class is created.

Which leads to the contradiction and can raise ambiguity.

Hope you got my point. :-)

Thursday, June 8, 2017

Beyond Compare Script from command line

You can call Beyond Compare 3 in scripting mode with a /silent flag to have it run automatically and generate a report without showing a window. I would recommend creating the report initially without the silent flag, as it will suppress all messages and errors. Once you are confident the report will run as expected, then simply add /silent to the command line call.

BC3's scripting mode is run with:

C:\Users\Abhishek>"C:\Program Files\Beyond Compare 4\bcompare.exe" "@D:\bcscript
.txt" "D:\1" "D:\2" "D:\bcreport.html"

Where bcscript.txt would be a text file containing a few commands:
load "%1" "%2"
expand all
folder-report layout:side-by-side options:display-mismatches output-to:"%3"

Tuesday, March 14, 2017

Wait not working in selenium 3.0

Add the following to maven pom.xml:
<dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>21.0</version>
</dependency>

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...