Write a program to print all permutations of a given string with repetition. (Repetition of characters is allowed).

Given a string of length n, print all permutation of the given string. Repetition of characters is allowed

   Case 1
      Input:   A
      output: A
     
  Case 2
      Input: AB
      output:
                AA
                AB
                BA
                BB
  Case 3
      Input:  ABC
      output:
                AAA
                AAB
                AAC
                ABA
                ABB
                ABC
                ACA
                ACB
                ACC
                BAA
                BAB
                BAC
                BBA
                BBB
                BBC
                BCA
                BCB
                BCC
                CAA
                CAB
                CAC
                CBA
                CBB
                CBC
                CCA
                CCB
                CCC

Algorithm:


How many permutations is possible?

  Lets see how many permutation is possible for given n character String.
  
In string "AB", n is 2
In string "ABC", n is 3
From above permutations displayed, we can see relation as n^n.
So for "AB", total permutations are 2^2 = 4.
For "ABC", total permutations are 3^3 = 27.

How to print all permutation?

  It is very easy, Lets take an example of String "ABC"
 
  We will take recursive approach. In this approach important thing is base case.
  We will try to make each permutation by adding characters one by one to the temporary String 
  that need to be printed.
 
  As our string is of length 3, so we will add the characters to the temporary string that needs 
  to be printed till the length is 3 as permutation string length will be 3.
 
  So base case is, when the length of our temporary string that needs to be printed is 3, 
  print and return.
 
  Now, how we will form temporary string is, 
      
       add first character of string to temporary string and check the length of 
       temporary string which is less then 3, true, so call function again,
       tempString = "A"
     

      add first character of string to temporary string and check the length of
      temporary string which is less then 3, true, so call function again,
      tempString = "AA"
     

      add first character of string to temporary string and check the length of
      temporary string which is less then 3, false, so print and return
      tempString = "AAA"
     

      1st permutation is AAA
      after returning from printing 1st permutation, tempString will be again "AA"
     
      Now appending "B" to "AA" will make our 2nd permutation that is "AAB", print and return.
      Now appending "C" to "AA" will make our 3rd permutation that is "AAC", print and return.
     
      from this we can see, that keeping "AA" common and adding "A", "B", "C" that is 
      each character of String, we are getting permutation.
      if we continue the same for 2nd position and then for 1st position of temporary string then 
      we will get all our permutations.

Java Program to print permutation of string with repetition


package javabypatel;

public class StringPermutationWithRepetition {

 public static void main(String[] args) {
  printPermutationOfStrings("ABC");
 }
 
 private static void printPermutationOfStrings(String str){
  printPermutation(str, "");
 }
 
 private static void printPermutation(String str, String stringToPrint){
  if(stringToPrint.length()==str.length()){
   System.out.println(stringToPrint);
   return;
  }
  for (int i = 0; i < str.length(); i++) {
   printPermutation(str, stringToPrint + str.charAt(i));
  }
 }
}

Due to Immutable nature of String class, every time we create a different String literal a new object of String is created, In above approach, we append character to String variable "stringToPrint" and new String object is created. So to avoid creating new String in each append here, we should use array or some mutable datatype like StringBuffer here. Let's see the better approach below,

Optimized Approach:


package javabypatel;

import java.util.Arrays;

public class StringPermutationWithRepetition {

    public void printCombination(int n, String str, char[] arr) {
        if (n == arr.length) {
            System.out.println(Arrays.toString(arr));
            return;
        }

        for (int i=0; i < str.length(); i++) {
            arr[n] = str.charAt(i);
            printCombination(n+1, str, arr);
        }
    }

    public static void main(String[] args) {
        StringPermutationWithRepetition obj = new StringPermutationWithRepetition();
        String str = "AB";
        obj.printCombination(0, str, new char[str.length()]);
    }
}

You may also like to see


Write a program to print all permutations of a given string without repetition. (Repetition of characters is not allowed).

Print all combinations/permutations of a string of length k that can be formed from a set of n characters.

Print all subsets of a given set.

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

What is Websocket? How Websocket works? Program on updating total count of connected Clients.

What is Websocket?


Websocket is bi-directional communication protocol over web that helps client to server and server to client communication on single TCP connection and on same port.

What is the use of Websocket and how it is helpful?
How things works before Websocket ?


For communication on web, HTTP is the standard protocol that is used.


HTTP is stateless protocol. It means,
    1. Client Request connection
    2. Connection established
    3. Client sends a request.
    4. Server gives response.
    5. Connection closed

Now client and server are independent and unaware of each other.
If client want to communicate again then it has to again go with above steps,
Also, request is always initiated by client and server can't initiate communication.


So, if Server has to say something to the client then how to achieve that?


First of all, why server want to communicate with the client, Lets see below example,
   1. Say, Jayesh requested for fare information of Flight number MH 198 from Mumbai 
       to Ahmedabad. 
   2. Server responded to Jayesh "Price is 5000 INR."
   3. Jayesh is thinking whether to book a flight at 5000 INR and then finally after 5 minutes,
        he made a mind to book it.
   4. Now after filling long form of passenger list and other flight information, 
       when Jayesh pressed the "Book" button, he found that now Flight price is 6000 INR, 
       how this happen??????????
   5. Jayesh is frustrated and thinking why server not notified him before filling the long form 
       on passenger list.

Ideally, Server should notify Jayesh that flight price is changed, please refresh the page. 
But how the server will know that to which all clients he need to inform and top of all, Server doesn't know any information on client.
This is possible only if server is capable of identifying client that, "who all client are connected to server and notify them on updates".

As communication happens over HTTP, Before Websocket, Server notify to the client using below techniques,

1. Polling


In this technique,
  1. Client requests a webpage from a server using regular HTTP request.
  2. The requested webpage executes JavaScript which requests for updates from the server at 
       regular intervals (say 1 seconds).
  3. The server checks for updates and responds back, just like normal HTTP response.

In Polling, client continuously polls server at regular intervals, asking is there any updates for client?

Disadvantage: if there is no updates, then unnecessarily client sends request to server and it hits server performance.

2. Long Polling


In this technique, 
  1. A client requests a webpage from a server using regular HTTP request.
  2. The requested webpage executes JavaScript which requests for updates from the server.
  3. Now if server does not has any updates, then server does not immediately responds telling 
      "no update" instead waits until there's new information available.
      When there's update available, the server responds with the updated information that help 
      client  on information say price has changed.
  4. The client receives updated price information and immediately sends another request 
       to the server, re-starting the process.

Disadvantage: Server like Tomcat would spawned thread to handle for each request, that reserve resources, till its done. So the traffic is smaller, but eats resources fast (also block resources).

Websocket overcome issues present in Polling and Long Polling.
One limitation with Websocket is that it is only supported with HTML 5 compliant  browsers.

Lets see a sample application on updating total count of connected clients using WebSockets, AngularJS and Java.


Client Side HTML and Javascript

index.html
<!DOCTYPE html>
<html>
 <head>
 
  <title>Websocket Example</title>  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
  <script src="app.js"></script>  
 
 </head>
 <body  data-ng-app="websocketDemoApp" style="margin:0px;">  
  
  <div data-ng-controller="appController">
   
   <label style="font-size: 20px; font-weight: bold;">Messages from Websocket Communication : </label>
   <pre>{{ websocketMessage }}</pre><br>
   
   <label style="font-size: 20px; font-weight: bold;">Connected Clients : </label>
   <label style="font-size: 40px; font-weight: bold;">{{ numberOfUsersConnected }}</label>
   
  </div>
  
 </body>
</html> 
app.js
'use strict';
var module = angular.module('websocketDemoApp', [ ]);

angular.module('websocketDemoApp').controller("appController", ['$scope', function($scope) {

 $scope.websocketMessage = "";
 
 $scope.getURLWithOutProtocalFromCurrentContext = function() {
  var hostName = window.location.host;
  var currentPath = window.location.pathname;
  return hostName + currentPath;
 };
 
 var urlWithOutProtocol = $scope.getURLWithOutProtocalFromCurrentContext();
 var wsUri = "ws://" + urlWithOutProtocol +"endpoint";
 var websocket = new WebSocket(wsUri);
 
 websocket.onopen = function(evt) {
  console.log("connection established");
  
  $scope.$apply(function(){
   $scope.websocketMessage = $scope.websocketMessage + "Connection to Websocket has established." + "\n";
        });
  
 };
 
 websocket.onmessage = function(evt) {
  console.log("message received: "+evt.data);
  var jsonResponse = JSON.parse(evt.data);
  
  $scope.$apply(function(){
   
   if(jsonResponse.count!=null || !angular.isUndefined(jsonResponse.count))
    $scope.numberOfUsersConnected = jsonResponse.count;
   
   if(jsonResponse.message!=null || !angular.isUndefined(jsonResponse.message))
    $scope.websocketMessage = $scope.websocketMessage + "Data Received: " +jsonResponse.message + "\n";
   
   
  });
 };
 
 websocket.onerror = function(evt) {
  console.log('websocket error: ' + jsonResponse);
  $scope.websocketMessage = $scope.websocketMessage + "There is some error while establishing connection to web socket." + "\n";
 };
 
 websocket.onclose = function(){
  $scope.websocketMessage = $scope.websocketMessage + "Web Socket connection is closed now..." + "\n";
    };
 
}]);


Server Side Java Code

ServerPush.java
package com.websocket.test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/endpoint")
public class ServerPush {
 private static Map<Object, Session> mapConnections = new HashMap<Object, Session>();

 public ServerPush() {
  //Starting notifier to push data to client at 1 minute interval
  new NotifierExample();
 }

 //This method is called when websocket connection is established or open.
 @OnOpen
 public void start(Session session) {
  mapConnections.put(session.getId(), session);
  String json = "{ \"count\" : \""+mapConnections.size()+"\"}"; 
  broadcastToAll(json);
 }

 @OnMessage
 public void echoTextMessage(Session session, String msg, boolean last) {
  String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
  broadcastToAll(json);
 }
 
 //This method is called when websocket connection is closed or when browser tab is closed. 
 @OnClose
 public void end(Session session, CloseReason reason) {
  mapConnections.remove(session.getId());
  String json = "{ \"count\" : \""+mapConnections.size()+"\"}"; 
  broadcastToAll(json);
 }

 //For sending data to single connected client for one to one communication between client and server.
 public static void broadcast(String key, String message) {
  Session session = mapConnections.get(key);
  if(session!=null){
   try {
    session.getBasicRemote().sendText(message);
   } catch (IOException e) {
    try {
     session.close();
    } catch (IOException e1) {
     // Ignore
    }
   }
  }
 }

 //For sending data to all the connected clients
 public static void broadcastToAll(String message) {
  for(Session session : mapConnections.values()){
   if(session!=null){
    try {
     session.getBasicRemote().sendText(message);
    } catch (IOException e) {
     try {
      session.close();
     } catch (IOException e1) {
      // Ignore
     }
    }
   }
  }
 }

}

NotifierExample.java
package com.websocket.test;

import java.util.Timer;
import java.util.TimerTask;

public class NotifierExample extends TimerTask{

 //After every 60 seconds, server will push the data to all connected clients.
 public NotifierExample() {
     Timer timer = new Timer();
     timer.schedule(this, 5000, 60000);
 }
 
 @Override
 public void run() {
  String json = "{ \"message\" : \"Database table is updated, Please refresh to get updated records.\"}";
  ServerPush.broadcastToAll(json);
 }
}


Note: ServerPush.java use classes from websocket jar, So make sure you have websocker-api.jar present in tomcat lib folder, if not then download using below dependency,

    javax.websocket
    javax.websocket-api
    1.0


After setup, Run the application in Tomcat.
  1.  Open browser and try to access application "http://localhost:8080/AppName"
  2.  Now, open firefox browser and try to access application "http://localhost:8080/AppName"
In the browser you will observe that as and when number of connected clients increase, 
the server pushes the total connected client count information on browser as well without explicit request from client

Output:



Number Range Spinner in Angular JS

Using JQuery Datatable in AngularJS application.

Download binary file AngularJS + REST service

Configure Angular2 + Webpack + Maven Sample


Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

TRIE datastructure explanation and simplified dictionary implementation in Java.

What is TRIE datastructure?


Trie is the data structure very similar to Binary Tree.
Trie datastructure stores the data in particular fashion, so that retrieval of data became much faster and helps in performance.
The name "TRIE" is coined from the word retrieve.

What are TRIE data structure usage or applications?


1. Dictionary Suggestions OR Autocomplete dictionary

Retrieving data stored in Trie data structure is very fast, so it is most suited for application where retrieval are more frequently performed like Phone directory where contact searching operation is used frequently.

2. Searching Contact from Mobile Contact list OR Phone Directory
Auto suggestion of words while searching for anything in dictionary is very common.
If we search for word "tiny", then it auto suggest words starting with same characters like "tine", "tin", "tinny" etc.

Auto suggestion is very useful and Trie plays a nice role there, Lets see real time use.
If say, Person doesn't know the complete spelling of the some word but know few, then rest of words starting with few characters can be auto suggested using TRIE data structure.

How TRIE datastructure works?


Each word of a English language is made using 26 alphabets. Trie data structure uses this property as a base for storing words.
 

A word can be started (first character of a word) from either a, either b, either c .... or either z.
So there are total 26 possibilities, from which first character of a word will be started.

Second character can also be started from either a, either b, either c .... or either z. 
So there are total 26 possibilities, from which second character of a word will be started.
 

Same for Third character and so on.

So for storing a word, we need to take an array(container) of size 26 and initially all the characters are blank as there are no words and it will look as shown below,


Lets see how a word "hello" and "him" is stored, 

1. "hello"
    "hello" starts from "h", So we will mark the position "h" as filled, which represents the use of
     "h". 

      After placing first character, for 2nd character again there are 26 possibilities, So from "h",
      again there is array of size 26, for storing 2nd character.



      Second character is "e", So from "h", we will move to "e" and mark "e" in 2nd array as used.
      After "e", 3rd character is "l", So mark the position "l" as used in respective array.

      Repeat the above steps for all the characters of a word and Trie will look like below.



2. "him"
    "him" starts from "h", So we will mark the position "h" as filled, but "h" is already filled by
      word "hello"which indicates that there exist some other word starting with "h".
     
      Using the same position "h" as a reference, Now, for 2nd character "i",

      We will move to "i" and mark position "i" in 2nd array as used.
      This signifies, that there exist 2 words starting with "he" and "hi".
     
       Now comes 3rd character "m" after "i", Now, we need to start new 26 array alphabet set again,
       which will hold the series starting from "hi".
      
       So mark the position "m" as used in respective array.

      After storing "hello" and "him",
Trie will look like below.

 
NOTE:
When we store the last character of a word, we need to mark that position as "END" to signify that this is the end of one word.
So that, while reading we will come to know that there exist some word which starts at "h" and ends at character "o" in case of "hello".



See figure below for more words.



Lets see java implementation of TRIE data structure.


TRIE Container class
package javabypatel.trie;

public class TrieContainer{
 public boolean isEnd;
 public TrieContainer[] series = new TrieContainer[26];
} 
TRIE Operation class

Operation it supports are,
  1.   Insert word in TRIE datastructure, 
  2.  Search word exist in TRIE datastructure, 
  3.  Print all the words present in TRIE datastructure.
package javabypatel.trie;

public class Trie {

 public static void main(String[] args) {
  TrieContainer start = new TrieContainer();
  
  storeWords(start, "hello");
  storeWords(start, "hallo");
  storeWords(start, "hell");
  storeWords(start, "teg");
  storeWords(start, "tag");
  
  printWordStrings(start,"");
  
  System.out.println("\n"+isWordPresent(start, "teg"));
 }

 private static void storeWords(TrieContainer start, String word){
  for (int j = 0; j < word.length(); j++) {
   char character = word.charAt(j);

   //In series, check the position of character, 
   //if it is already filled then check the series of filled Trie object.
   //if it is not filled then create new TrieContainer object and place it at correct position, and check 
   //if it is end of the word, then mark isEnd = true or else false;  
   if(start.series[character-97]!=null){
    if(word.length()-1 == j){ //if word is found till last character, then mark the end as true.
     start.series[character-97].isEnd = true;
    }
    start = start.series[character-97];
   }else{
    TrieContainer trie = new TrieContainer();
    trie.isEnd = (word.length()-1 == j ? true:false);
    start.series[character-97] = trie;
    start = start.series[character-97];
   }
  }  
 }
 
 private static boolean isWordPresent(TrieContainer start, String word){
  boolean isFound = true;
  for (int i = 0; i < word.length(); i++) {
   char character = word.charAt(i);

   //if at character position TrieContainer object is present then character is found and 
   //start looking for next character is word. 
   if(start.series[character-97]!=null){
    if(word.length()-1 != i){
     start = start.series[character-97];
    }else{
     if(!start.series[character-97].isEnd){
      isFound = false;
     }
    }
   }else{
    isFound = false;
    break;
   }
  }
  return isFound;
 }

 private static void printWordStrings(TrieContainer start, String toPrint) {
  if(start==null){
   return;
  }
  if(start.isEnd){
   System.out.println(toPrint);
  }

  for (int i = 0; i < start.series.length; i++) {
   TrieContainer t = start.series[i];
   if(t!=null){
    printWordStrings(t, toPrint + (char)(97+i));
   }
  }
 }
}


Place N Queens on N×N chess board such that no two Queens attack each other.

0/1 Knapsack Problem solved using Iterative and Dynamic Programming

Stock Buy Sell to Maximize Profit.

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted

Count trailing zeros in factorial of a number.

How to Detect loop in linked list.

Tower Of Hanoi Program in Java.

Print Matrix Diagonally OR Diagonal order of Matrix.

Transpose of Matrix Inplace

Implement Queue using One Stack in Java (Recursive Implementation)

SOAP Vs REST Web Service, when to use SOAP, When to use REST.


Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.

How to enable or allow remote access to PostgreSQL database server.

For enabling remote access to PostgreSQL database server,
Remote access to PostgreSQL database
There are 2 main PostgreSQL configuration files that need to be changed to allow remote connections.
1. postgresql.conf
2. pg_hba.conf

postgresql.conf


It will be located in PostgreSQL installed directory,

In Linux, You may find file at location below,
  1. /var/lib/pgsql/data/
  2. /etc/postgresql/9.1/main/
In Windows, You may find file at location below,
  1. C:/ProgramData/PostgreSQL/9.3/postgresql.conf

For exact location of "postgresql.conf" file, run the below command in psql command prompt.
SHOW config_file;
Open the file and search for "listen_addresses" and set listen_addresses parameter to,
listen_addresses = '*'

pg_hba.conf


It will be located in several directory, depending on how postgresql is installed

In Linux, You may find file at location below,
  1. /home,
  2. /var/lib/pgsql, 
  3. /var/lib/postgresql/[version]/, 
  4. /opt/postgres/  
  5. /etc/postgresql/[version]/main/
In Windows, You may find file at location below,
  1. C:/ProgramData/PostgreSQL/9.3/pg_hba.conf
For exact location of "pg_hba.conf" file, run the below command in psql command prompt.
SHOW hba_file; 

If you want PostgreSQL to accept incoming connection from any IP address then add entry like below,
 host             all             all             0.0.0.0/0             md5 

If you want PostgreSQL to accept incoming connection from particular IP address, say 192.168.82.2 then add entry in pg_hba.conf file like below,
host             all             all            192.168.82.2/24       md5 

Reload Configuration


After the changes are done, you have to reload the configuration as a superuser. run below command,
SELECT pg_reload_conf(); 
Done.

If PostgreSQL is still not accepting remote connection then try restarting the PostgreSQL service like below.

In Linux, If your PostgreSQL service name is "postgresql" then execute below command
service postgresql restart
In Windows, You can find service at
Start Menu ---> Search "Run" ---> Type "Services.msc" ---> Search "PosgreSQL"  
 ---> Right click and select Restart Service.

Explain SQL Injection with example?

When to use Builder design pattern

How Recursion works internally with example

Difference between process and thread

Burning Rope Puzzle - Measure 45 Minutes

Union and Intersection of Two Sorted Arrays

Merge two sorted arrays in Java

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Convert Integer to Roman numeral in Java

Converting Integers to Roman Numerals equivalent in Java

In this post we will see how to convert Integer to Roman numeral in Java. We will also look into Java program to convert integer to roman numerals.

Let's understand what is the Input and the expected output.

Input : 99
Output: XCIX

Input : 81
Output: LXXXI

Input : 0



Output: not defined

Integer to Roman numbers from 1 to 100 chart
Integer to Roman numbers chart

Algorithm

STEP 1:
Note down all Unique characters where Roman numbers deviated from usual Pattern and put them in map.

Take an example, 
Roman equivalent of '1' is 'I'. So we will add this in map, 
map.put(1, "I"); Now no need to add Roman equivalent of '2' as it can be formed from equivalent of '1' 
(taking 'I' twice), 
Same for 3 (taking 'I' thrice).

This is not the case with Roman equivalent of '4', it has different pattern and not the ('IIII'), 
so add it in map. map.put(4, "IV");

Note: 
Unique patterns noted here are to support integers from 1 to 399 as program only support till 399.
 
Map map = new LinkedHashMap();
map.put(100, "C");
map.put(90, "XC");
map.put(50, "L");
map.put(40, "XL");
map.put(10, "X");
map.put(9, "IX");
map.put(5, "V");
map.put(4, "IV");
map.put(1, "I");


If we want program to support more integers then identify patterns where Roman numbers have unusual patterns after 399 and add it in map.

STEP 2:
For converting Integer to Roman equivalent, we will start comparing given Integer with largest number in map,

Eg:
  Map map = new LinkedHashMap();
  map.put(100, "C");
  map.put(90, "XC");
  map.put(50, "L");
  map.put(40, "XL");
  map.put(10, "X");
  map.put(9, "IX");
  map.put(5, "V");
  map.put(4, "IV");
  map.put(1, "I");

check how many times given number(say 153) has 100 in it(1 time, So pick "C" and remove 100 from 153, remaining number is 53),
100: Divide 153/100 = 1 time in 153 (remaining number is 153 - 100 = 53), remaining number is 153%100 = 53

then check how many time remaining number(53) has 90 in it(0 time),
90: 53/90 = 0 time in 53 (remaining number 53), remaining number is 53%90 = 53

then check how many time remaining number(53) has 50 in it(1 time, So pick "L" and remove 50 from 53, remaining number is 3),
50: 53/50 = 1 time in 53 (remaining number is  53 - 50 = 3), remaining number is 53 % 50 = 3

then check how many time remaining number(3) has 40 in it(0 time),
40: 3/40 = 0 time in 40 (remaining number 3), remaining number is 3%40 = 3

then check how many time remaining number(3) has 10 in it(0 time),
10: 3/10 = 0 time in 10 (remaining number 3), remaining number is 3%10 = 3

then check how many time remaining number(3) has 9 in it(0 time),
9: 3/9 = 0 time in 9 (remaining number 3), remaining number is 3%9 = 3

then check how many time remaining number(3) has 5 in it(0 time),
5: 3/5 = 0 time in 5 (remaining number 3), remaining number is 3%5 = 3

then check how many time remaining number(3) has 4 in it(0 time),
4: 3/4 = 0 time in 4 (remaining number 3), remaining number is 3%4 = 3

then check how many time remaining number has(3) 1 in it(3 time, So pick "I"*3 = "III" and remove 1 thrice from 3, remaining number is 0),
1: 3/1 = 3 time in 1 (remaining number is 3 - (1+1+1) = 0), remaining number is 3%1 = 0

We reach 0, no more number present, Stop here are return "CLIII"



Convert Integer to Roman numerals Java Program

package com.javabypatel;

import java.util.LinkedHashMap;
import java.util.Map;

public class IntegerToRomanNumber {

 public static void main(String[] args) {
  System.out.println(getRomanEquivalentOfInteger(399));
 }
 
 private static String getRomanEquivalentOfInteger(int number){
  if(number<=0){
   return "not defined";
  }

  //Noting down all Unique characters where Roman numbers deviated from usual Pattern.
  //unique patterns noted here are to support integers from 1 to 399 as program only support till 399.
  //if we want program to support more integers then identify patterns where Roman numbers have unusual patterns after 399 and add it in map.
  Map<Integer, String> map = new LinkedHashMap<Integer, String>();
  map.put(100, "C");
  map.put(90, "XC");
  map.put(50, "L");
  map.put(40, "XL");
  map.put(10, "X");
  map.put(9, "IX");
  map.put(5, "V");
  map.put(4, "IV");
  map.put(1, "I");
 
  String romanEqui="";
  
  // Iterate map, check how many times given number has 100 in it, then check how many time remaining number has 90 in it and so on.
  // or we can also say, is number divisible by 100, remaining number is divisible by 90 and so on.
  // if number is 153, then first will see how many time number has 100 in it, which is 1 time.
  // 100 - 1 time in 150 (remaining number is 150 - 100 = 53) OR 153/100 = 1 remaining 153%100 = 53
  // 90  - 0 time in  53 (remaining number is  53 -  90 = 0)  OR  53/90 = 0 remaining   53 % 90 = 53 (we only need to find perfectly divisible numbers.)  
  // 50  - 1 time in  53 (remaining number is  53 -  50 = 3)  OR  53/50 = 1 remaining   53 % 50 = 3
  // 40  - 0 time in   3 (remaining number is   3 -  40 = 0)  OR   3/40 = 0 remaining    3 % 40 = 3
  // 10  - 0 time in   3 (remaining number is   3 -  10 = 0)  OR   3/10 = 0 remaining    3 % 10 = 3
  // 9   - 0 time in   3 (remaining number is   3 -   9 = 0)  OR    3/9 = 0 remaining    3 %  9 = 3
  // 5   - 0 time in   3 (remaining number is   3 -   5 = 0)  OR    3/5 = 0 remaining    3 %  5 = 3
  // 4   - 0 time in   3 (remaining number is   3 -   4 = 0)  OR    3/4 = 0 remaining    3 %  4 = 3
  // 1   - 3 time in   3 (remaining number is   3 -   1 = 0)  OR    3/1 = 3 remaining    3 %  1 = 0
  for (Map.Entry<Integer, String> entry : map.entrySet()) {
   int key = entry.getKey();
   if(number/key!=0){
    for (int i = 0; i < (number/key); i++) {
     romanEqui = romanEqui + map.get(key);
    }
    number = number % key;
   }   
  } 
  return romanEqui;
 }
}




Another approach

package com.javabypatel;

public class RomanEquivalent {
    public static void main(String[] args) {
        System.out.println(romanEquivalent(4));
    }

    //Another Solution - This method works for first 50 numbers, can be extended by extending uniqueNumber and arrSymbol
    static String romanEquivalent(int number) {
        int[] uniqueNumber = new int[] {1, 4, 5, 9, 10, 40, 50};
        String[] arrSymbol = new String[]{"I", "IV", "V", "IX", "X", "XL", "L"};

        int size = uniqueNumber.length - 1;
        StringBuffer result = new StringBuffer();

        while (number > 0) {
            int count = number / uniqueNumber[size];
            while (count > 0) {
                result.append(arrSymbol[size]);
                count--;
            }
            number = number % uniqueNumber[size];
            size--;
        }
        return result.toString();
    }
}

You may also like to see


Factorial of Big Number using Recursion in Java

Get Level/Height of node in binary tree

Implement Queue using One Stack in Java (Recursive Implementation)

Rotate matrix by 90 degree

Top 25 Multithreading Interview Questions in Java

Find the element that appears once others appears THRICE.

Merge two sorted arrays in Java

Union and Intersection of Two Sorted Arrays

Find all pairs of elements from array whose sum equals to given number K.

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted.

Find Largest and Second Largest number in array

How Binary search Algorithm works in Java


Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Find the element that appears once in a sorted array, where all elements appear twice(one after one) except one element appears only once.

Find the element that appears only once in a sorted array.
Given a sorted array in which all elements appear twice (one after one) and one element appears only once.
Find that element in O(Log n) complexity.

Input: arr[] = {1, 1, 2, 2, 3, 4, 4} Output: 3

Input: arr[] = {1, 1, 2, 2, 3, 3, 4}
 Output: 4

Input: arr[] = {1}
Output: 1 

Using JQuery Datatable with AngularJS

Datatables - AngularJS
using jquery datatable with angularjs example
Using JQuery Datatable with AngularJS

Datatables


DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool for rendering data in tables with features like,
  1. Searching record/row in table.
  2. Sorting columns.
  3. Pagination etc.
More details on Datatables: https://www.datatables.net/