Tuesday, 1 March 2016

Increment a number by one without using addition operator

Write a program to increment a number by one without using operators like ‘+’, ‘-‘, ‘*’, ‘/’, ‘++’, ‘–‘ …etc.

Examples:
Input: 20
Output: 21

We can achieve the functionality using bitwise operators.

Approach#
To increment the bit, we need to add 1 in binary representation. However addition is not allowed.
So we can check the each bit and flip it using bitwise operators.

Step#1 Flip all the set bits until we find a 0. (Alternate to Carry forward in addition)
Step#2 Flip the rightmost 0 bit (Add the new value at right side).

Bitwise representation of 20 is 10100.

public class IncrementByOne {
     public static void main(String[] args) {
           int value = 20;
           value = increment(20);
           System.out.println(value);
     }

     static intincrement(int number) {
           int one = 1;

           /* Flip all the set bits until we find a 0 */
           while((number & one)!=0 ) {
                number = number^one;
                one <<= 1;
           }

           /* flip the rightmost 0 bit */
           number = number^one;
           return number;
     }
}
Output:
21

Sunday, 28 February 2016

Dependency Lookup


The Dependency Lookup is an approach where we get the resource after demand. Various ways to get the resource are mentioned below:

Using new keyword
ClassA obj = new ClassAImpl(); 

Static factory method
ClassA  obj = ClassA.getClassA(); 

Using JNDI (Java Naming Directory Interface) :
Context ctx = new InitialContext();
Context environmentCtx = (Context) ctx.lookup ("java:comp/env"); 
ClassA obj = (ClassA)environmentCtx.lookup("ClassA "); 

Problems of Dependency Lookup
Tight coupling: The dependency lookup approach makes the code tightly coupled. If resource is changed, we need to perform a lot of modification in the code.

Not easy for testing: This approach creates a lot of problems while testing the application especially in black box testing.

Dependency Injection (DI) is a design pattern that removes the dependency from the code so that it can be easy to manage and test the application. It makes our programming code loosely coupled.

This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.

The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container.


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

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. 
Related Posts Plugin for WordPress, Blogger...