Pages

Sunday 28 February 2016

How to Convert String to Int without using Integer.parseInt() method: Code With Example

As integer can be positive and negative, here two cases arise.

Use cases#
Case#1: If string is positive
If user inputs  "12312", then it should give output 12312 as an int number

Case#2: If string is negative
If user inputs "-47939", then it should give output -47939 as an int number.

Case#3: If string contains alphabetic character like "12ab6", it should print an error.

Approach#
We will traverse the character array as we know String is the array of character.

Step#1: int_value = 0;

Step#2: Traverse the Character array from right to left.

Step#3: Find the place_value of the Character because the ASCII value is different of character to string.

Step#4: Multiplying the place value by 10 each time and add to sum.
              int_value = int_value + place_value * 10;


import java.text.ParseException;
public class IntegerParser {

     public static int parseInt(String str) throws ParseException {
           int i = 0, number = 0;
           boolean isNegative = false;
           char[] value = str.toCharArray();
           if(value[0] == '-') {
                isNegative = true;
                i = 1;
           }

           while(i < value.length) {
                char ch = value[i++];
                int place_value = ch - '0';
                if(place_value>=0 && place_value<=9) {
                     number *= 10;
                     number += (ch - '0');
                } else {
                    System.out.println("Wrong input format!!");
                    throw newParseException("String to int parse",-1);
                }
           }
           if(isNegative) {
                number = -number;
           }
           return number;
     }


     public static void main (String args[]) throws ParseException {
           String  convertingString="1243";
           int integer = parseInt(convertingString);
           System.out.println(integer);

           convertingString="-1243";
           integer = parseInt(convertingString);
           System.out.println(integer);
          
           convertingString="-12a43";
           integer = parseInt(convertingString);
           System.out.println(integer);

     }
}

Output:
1243
-1243
Wrong input format!!
Exception in thread "main" java.text.ParseException: String to int parse
     at IntegerParser.parseInt(IntegerParser.java:39)
     at IntegerParser.main(IntegerParser.java:17)



For suggestions/doubts, please put your comments.

Friday 26 February 2016

What is the difference between thin and thick client?

The thin vs. thick distinction usually refers to how much processing or "business logic" is done on the client.

Thin client:
Basically, a thin client is a web based application and most of the processing is done on the server side.

Example:
Web browser is the classic example of thin client. It can be the client application for anyone's server application.

The client can be generic like a web browser, and since most of the logic takes places on the central server, it's much easier to push updates out to the clients.

Advantage of thin clients is they make fewer demands on the client machine, which can be anything from a computer to a smart phone to a household device like a blender or TV set top box.

Thick client:
A thick client is more like a standalone application, which run on the client machine and communicates with the server less frequently.

With thick client, there won't be much processing via the network. In a way, it will be a much faster option if your network is slow or congested.

Example:
A virus scanner is a good example. It downloads new virus definitions from the server, but then runs its scan on the client machine without further communication to the server.

Advantage of thick clients is that the performance isn't tied to the load on the server, and the speed of the network connection.


Swapping of two numbers without using third variable

Approach#1.
Addition and Subtraction Method

Integer a, b
read a and b
a= a+b;
b=a-b;
a=a-b;

Problem:
Incorrect result when sum of numbers will exceed the Integer range.


Approach#2. 
Multiplication and Division Method

Integer a, b
read a and b
a=a*b;
b=a/b;
a=a/b;

Problems:
1. If the value of a*b exceeds the range of integer.
2. If the value of a or b is zero then it will give wrong results.

Approach#3.
XOR Method

Integer a , b
read a and b
a=a^b;
b=a^b;
a=a^b;

Best approach to solve this problem without any pitfalls.



Thursday 18 February 2016

5 Class Design Principles in Java

[S.O.L.I.D.]
The 5 Class Design Principles

S.O.L.I.D is the acronym for five basic principles of object-oriented programming to design a class.

Single responsibility
Open-closed
Liskov substitution
Interface segregation and
Dependency inversion.

S.O.L.I.D principles help us to create a system that is easy to maintain and extend over time. Well designed and written classes can speed up the coding process by leaps and bounds, while reducing the number of bugs in comparison.

Classes are the building blocks of System. If these blocks are not strong, your building (i.e. System) is going to face the tough time in future.

If Classes are not so well-written, can lead to very difficult situations when the application scope goes up or application faces certain design issues either in production or maintenance.

It is part of an overall strategy of agile and Adaptive Software Development.

S
Single responsibility principle
“a class should have only a single responsibility” (i.e. only one potential change in the software's specification should be able to affect the specification of the class)
O
Open/closed principle
“software entities … should be open for extension, but closed for modification.”

L
Liskov substitution principle

“objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”

I
Interface segregation principle

“many client-specific interfaces are better than one general-purpose interface.”
D
Dependency inversion principle

one should “Depend upon Abstractions. Do not depend upon concretions.”


Introduced by Michael Feathers for the "first five principles" named by Robert C. Martin in the early 2000s.

Tuesday 16 February 2016

Find the element repeated more than n/2 times

There is an array (of size N) with an element repeated more than N/2 number of time and the rest of the element in the array can also be repeated but only one element is repeated more than N/2 times. Find the number.

Approach#1
Keep the count of each number in a hash map.
Extra space required for this approach.

Approach#2
Simplest, sort the array and the number at n/2+1th index is the required number.
Time complexity to sort array is: O (nlogn).

Approach#3
Moore’s Voting Algorithm
1. Define two variables majority_elem to keep track of majority element and counter (count).
2. Initially we set the first element of the array as the majority element.
3. Traverse the array:
a. If the current element == majority_elem
Increment count
    else
Decrement count

b. If count becomes zero,
Set count = 1
Set majority_elem = current element.
4. Print majority_elem.

array = [1, 2, 3, 4, 5, 5, 5, 5, 5 ]
majority_elem = items[0]
count = 1

for i ß0 to end {
if (items[i] == majority_elem) {
          count += 1;
            } else {
          count -= 1
            }

           if (count == 0) {
                majority_elem = items[i];
                count = 1;
            }
}
print(majority_elem)

Note:  For boundary condition, Check that the occurrence of element is more than n/2.


Intuition behind the algorithm:
Suppose that you were to have a roomful of people each holding one element of the array. Whenever two people find each other where neither is holding the same array element as the other, the two of them sit down. Eventually, at the very end, if anyone is left standing, there's a chance that they're in the majority, and you can just check that element. As long as one element occurs with frequency at least N/2, you can guarantee that this approach will always find the majority element. 

Find the start index of 1 in infinite length sorted array of 0s and 1s

Given an infinite size array with only 0s and 1s and sorted. Find the transition point where 0s end or 1s start.

Approach#1
We cannot apply the Simple Binary as the length of Array is not given.
So we need to apply the linear search.
Complexity: O(n) where n may be infinite.

Approach#2
Use Binomial theorem to find the index (simulate the Binary Search).

1. At first check the 2^i the index i=0,1,2,....
2. If '1' occurs at some point of index [example say 32 i.e. 2^5]
3. Apply binary search between 2^4 and 2^5. (Now we have two indexes to apply Binary search).

Complexity: O(logn).

Pseudo code:

array[1....inf]

preIdx = 0;
index=1;

while(array[index]!=1) {
           preIdx = index;
           index *= 2;
}

return binarySearch(array, value, preIdx, index); 

Thursday 11 February 2016

Check Oddity

Check Oddity
Write the precise code to check the number is Odd or not.

Approach#1
Check the module 2 of number is Zero. If it Zero, number is Odd.

public boolean oddOrNot(int num) {
     return num % 2 == 1;
}

Problem: It will not return the correct result for the negative number.

Approach#2
If number is positive/negative, Subtract 2/-2 from number respectively until the number result is Zero or one.

public boolean oddOrNot(intnum) {
     int s = 0;
     if(num>0) {
           s = 2;
     } else {
           s = -2;
     }
     while(num>1) {
           num = num – s;
     }
     if(num==0) {
           return false;
     } else {
           return true;
     }
}

Complexity of given approach is O(num).

Approach#3

Example:Number = 10
Binary representation of 10 = 1010
Binary representation of 1   = 0001
Logical AND of both numbers = 0000.

A number will be Odd iff last bit of binary representation is 1.

public boolean oddOrNot(intnum) {
    return (num & 1) != 0;
}

This is highly optimized code. Since, Arithmetic and Logical operations are much faster compared to division and multiplication.