Wednesday, 14 June 2017

Noble integers in an array
Given an array, find a Noble integer in it.
Noble Integer
An integer x is said to be Noble in an array if the number of integers greater than x is equal to x. If there are many Noble integers, return any of them. If there is no, then return -1.
      
private static int findNobleInteger(int[] array) {
           int noble = -1;
           /**Sort the array. */
           Arrays.sort(array);

           int length  = array.length;
           for (int i = 0; i < length; i++) {
                if (array[i] == array[i+1]) {
                     continue;
                }
                /**Check wheter the small number count is greater than number.*/                
                if(array[i]<length-i) {
                     noble = array[i];
                     break;
                }
           }
           return noble;
}

Saturday, 10 June 2017

The purpose of software tests

Software testing is a process of executing a program or application with the intent of finding the software bugs. It can also be stated as the process of validating and verifying that a software program or application or product: Meets the business and technical requirements that guided its design and development.

What are software tests?
A software test is a piece of software, which executes another piece of software. It validates if that code results in the expected state (state testing) or executes the expected sequence of events (behavior testing).

Software unit tests help the developer to verify that the logic of a piece of the program is correct.

Running tests automatically helps to identify software regressions introduced by changes in the source code. Having high test coverage of code allows us to continue developing features without having to perform lots of manual tests.

Testing terminology
1. Code (or application) under test
The code which is tested is typically called the code under test. If we are testing an application, this is called the application under test.

2. Test fixture
A test fixture is a fixed state in code which is tested used as input for a test. Another way to describe this is a test precondition.

For example, a test fixture might be a fixed string, which is used as input for a method. The test would validate if the method behaves correctly with this input.

3. Unit tests and unit testing
A unit test is a piece of code written by a developer that executes a specific functionality in the code to be tested and asserts a certain behavior or state.

The percentage of code which is tested by unit tests is typically called test coverage.

A unit test targets a small unit of code, e.g., a method or a class. External dependencies should be removed from unit tests, e.g., by replacing the dependency with a test implementation or a (mock) object created by a test framework.

Unit tests are not suitable for testing complex user interface or component interaction. For this, we should develop integration tests.

4. Integration tests
An integration test aims to test the behavior of a component or the integration between a set of components. The term functional test is sometimes used as synonym for integration test. Integration tests check that the whole system works as intended; therefore they are reducing the need for intensive manual tests.

These kinds of tests allow you to translate user stories into a test suite. The test would resemble an expected user interaction with the application.

5. Behavior vs. state testing
A test is a behavior test (also called interaction test) if it checks if certain methods were called with the correct input parameters. A behavior test does not validate the result of a method call.

State testing is about validating the result. Behavior testing is about testing the behavior of the application under test.

While testing algorithms or system functionality, in most cases you may want to test state and not interactions. A typical test setup uses mocks or stubs of related classes to abstract the interactions with these other classes away afterwards you test the state or the behavior depending on your need.

6. Performance tests
Performance tests are used to benchmark software components repeatedly. Their purpose is to ensure that the code under test runs fast enough even if it’s under high load.

Testing frameworks for Java
There are several testing frameworks available for Java. The most popular ones are JUnit and TestNG

Where should the test be located?
Typical, unit tests are created in a separate project or separate source folder to keep the test code separate from the real code. The standard convention from the Maven and Gradle build tools is to use:

src/main/java - for Java classes

src/test/java - for test classes

Which part of the software should be tested?
It is a highly controversial topic as some developers believe every statement in code should be tested.

In any case, we should write software tests for the critical and complex parts of application. If we introduce new features a solid test suite also protects us against regression in existing code.

In general, it is safe to ignore trivial code (useless to write tests for getter and setter methods). Writing tests for these statements is time consuming and pointless, as you would be testing the Java virtual machine. The JVM itself already has test cases for this. If you are developing end user applications you are safe to assume that a field assignment works in Java.

If we start developing tests for an existing code base without any tests, it is good practice to start writing tests for code in which most of the errors happened in the past. This way we can focus on the critical parts of our application.

Thursday, 8 June 2017

Subset Sum Problem | Dynamic Programming

Given an array of non-negative integers, and a value sum, determine if there is a subset of the given set with a sum equal to given sum and find out that subset.

Examples:
Input:
array [] = {3, 12, 4, 12, 5, 2}
sum = 7
Output:
true


package com.dp;
public class SubsetSumProblem {

     private static boolean isSumSubsetExist(int[] array, int sum) {
           int col = sum+1;
           int row = array.length+1;
           boolean[][] dp = new boolean[row][col];
          
           for(int i=0;i<row;i++) {
                dp[i][0] = true;
           }
          
           for(int i=1;i<col;i++) {
                dp[0][i] = false;
           }
          
           for (int i = 1; i < row; i++) {
                int value = array[i-1];
                /* Create DP. */
                for (int j = 1; j < col; j++) {
                     if(j<value) {
                           dp[i][j] = dp[i-1][j];
                     } else {
                           dp[i][j] = dp[i-1][j-value];
                     }
                }
           }
          
           /** Print the elements set. */
           printElements(dp, array, row, col);
          
           return dp[row-1][col-1];
     }
    
     private static void printElements(boolean[][] dp, int[] array, int row, int col) {
           int i = row-1; int j = col-1;
          
           while(i>0 && j>=0) {
                int value = array[i-1];
                if(j-value>=0 && dp[i-1][j-value]) {
                     i = i -1;
                     j = j-value;
                     System.out.println(value);
                } else {
                     i--;
                }   
           }
     }

     /**
      * Driver Method
      * @param args
      */
     public static void main(String[] args) {
           int[] array = {3, 12, 4, 12, 5, 2};
           int sum = 7;
           boolean isExist = isSumSubsetExist(array,sum);
           System.out.println(isExist);
     }
}

Friday, 26 May 2017

Mediator pattern

Mediator pattern defines an object that encapsulates how a set of objects interact.

Participants
Mediator - defines the interface for communication between Colleague objects.

ConcreteMediator - implements the Mediator interface.
Implements the communication and transfer the messages between the colleague objects.

ConcreteColleague - communicates with other Colleagues through its.

Before Mediator Design Pattern

 After Mediator Design Pattern


                                                            

Chat application

package designpattern.mediator;

public interface IChatMediator {
    public void sendMessage(IUser from, IUser to, String msg);

    void addUser(IUser user);
}

import java.util.ArrayList;
import java.util.List;
public class ChatMediator implements IChatMediator {
      private List<IUser> users;

      public ChatMediator() {
            this.users=new ArrayList<>();
      }

      @Override
      public void addUser(IUser user) {
            this.users.add(user);
      }

      @Override
      public void sendMessage(IUser from, IUser to, String msg) {
            to.receive(from,msg);
      }
}

public abstract class IUser {
      protected IChatMediator mediator;
      protected String name;

      public IUser(IChatMediator med, String name){
            this.mediator=med;
            this.name=name;
      }

      public abstract void send(IUser to, String msg);

      public abstract void receive(IUser from,String msg);
}

public class User extends IUser {
      public User(ChatMediator med, String name) {
            super(med, name);
      }

      @Override
      public void send(IUser to, String msg) {
            System.out.println(this.name+": Sending Message="+msg);
            mediator.sendMessage(this, to,msg);
      }
     
      @Override
      public void receive(IUser from, String msg) {
            System.out.println("Delivered from "+from.name+" to "+this.name);
      }
}

public class ChatClient {
      public static void main(String[] args) {
            ChatMediator mediator = new ChatMediator();
            IUser john = new User(mediator, "john");
            IUser micheal = new User(mediator, "micheal");
           
            mediator.addUser(john);
            mediator.addUser(micheal);
           
            john.send(micheal, "hello micheal!");
           
            micheal.send(john, "hello john!");
      }
}

Output:
john: Sending Message=hello micheal!
Delivered from john to micheal
micheal: Sending Message=hello john!
Delivered from micheal to john

Mediator Pattern usage in JDK

Java Message Service (JMS) uses Mediator pattern along with Observer pattern to allow applications to subscribe and publish data to other applications.

java.util.Timer class schedule (i.e scheduleAtFixedRate) methods.

Java Concurrency Executor execute() method.

java.lang.reflect.Method invoke() method.
Related Posts Plugin for WordPress, Blogger...