Thursday 29 June 2017

Ping an IP address in Java | Java Networking

We can ping an IP address using java.net.InetAddress.isReachable() method.

This example is by using ProcessBuilder class, Process class. ProcessBuilder class is used to create operating system processes and ProcessBuilder.start() starts the sub-process which will execute the ping command.
package com.java.networking;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class PingIP {
    
     static void runOSCommands(ArrayList<String> commandList) throws Exception {
           /** creating the sub process, execute system command. */
           ProcessBuilder build = new ProcessBuilder(commandList);
          
           Process process = build.start();

           /** to read the output. */
           BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
           BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
          
           String s = null;
           System.out.println("Ping result: ");
          
           while((s = input.readLine()) != null) {
                System.out.println(s);
           }
          
           System.out.println("Print error (if any): ");
           while((s = error.readLine()) != null) {
                System.out.println(s);
           }
     }

     public static void main(String args[]) throws Exception {
          
           /** Initialize the command list. */
           ArrayList<String> commandList = new ArrayList<String>();

           commandList.add("ping");
           commandList.add("www.google.com");
          
           runOSCommands(commandList);
     }
}
Ping result:
Pinging www.google.com [74.125.68.104] with 32 bytes of data:
Reply from 74.125.68.104: bytes=32 time=403ms TTL=45
Reply from 74.125.68.104: bytes=32 time=341ms TTL=45
Reply from 74.125.68.104: bytes=32 time=359ms TTL=45
Reply from 74.125.68.104: bytes=32 time=329ms TTL=45

Ping statistics for 74.125.68.104:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 329ms, Maximum = 403ms, Average = 358ms

To Maximize the Probability of Red Marble

You have 50 red balls and 50 blue balls, you have to place these balls in two containers in such a way that probability of a person picking up a red ball from any container is maximum.

1. For container 1,
You should have to place one red marble into 1st Container. By this when we select this Container 1 P(Red|C1) will be 1.

2.  For container 2,
Rest all marbles should have to place into 2nd container. By this when we select this Container 2 P(Red|C2) will be 49/99.

Here, P(C1) = P(C2) = 1/2 as there is only 2 containers.

So answer will be P(Red) = P(C1)*P(Red|C1) + P(C2)*(Red|C2)
                                                  P(Red) = (1/2)*(1) + (1/2)*(49/99)
                                                  P(Red) = 0.747474.

Proof of above given solution using the Java code:
public class MaximizeRedBallProbability {
     /**
      * This is the code which maximize the probability.
      * @param red
      * @param blue
      * @return probability
      */
     private static double getProbability(int red, int blue) {
           double max=0;
           int maxRed = 0;
           int maxBlue = 0;
          
           for (int i = 1; i < red; i++) {
                for (int j = 0; j < blue; j++) {
                     double prb = (0.5*i)/(i+j) + (0.5*(50-i))/(100-i-j);
                    
                     if (prb>max) {
                           max = prb;
                       maxRed=i;
                       maxBlue=j;
                     }
                }
           }
           System.out.println("Container 1, Red balls: "+maxRed +" Blue balls : "+maxBlue);
           System.out.println("Container 2, Red balls: "+(red-maxRed) +" Blue balls : "+(blue-maxBlue));
           return max;
     }
    
     /** Driver Method. */
     public static void main(String[] args) {
           int red = 50;
           int blue = 50;
           double p = getProbability(red,blue);
           System.out.println("Maximum probability of RED ball "+p);
     }
}
Output: 7474747474747475

                                                  

Wednesday 28 June 2017

Search an element in an unsorted array using minimum number of comparisons

Given an array and an element, search the element x in the array using minimum number of comparisons.

/**This is generic algorithm which takes 2n+1
 * comparisons(worst case) to search element. */
private static int searchElementUsingGenericAlgo(int[] array, int value) {
     int idx = -1;
     int length = array.length;
     for (int i = 0;i<length; i++) { /* n+1 comparisons. */
           if(value == array[i]) { /* n comparisons. */
                idx = i;
                break;
           }
     }
     return idx;
}
This algorithm is developed to return the element index in 2n+1 comparison in the worst case.

Approach:
To avoid the comparison that is taking place in the loop.

Algorithm:
1. Check that the last element in the array is equal to searched element.
   a. YES, element index is found, return the index.
   b. NO, Take back up of last element and put the searched element on last index of array.
2. Search for element with Infinite loop (without termination condition) and break when the element is found
   a. If element is found on last index, this is the element put by us to terminate the search and this signals that element not found in the array.
   b. If element found other than last index, set the backup to last index and return the index.

public class MinComparison {

     /**This algorithm is developed to return the
      * element index in n+1 comparison in the worst case.
      * Approach: To avoid the comparison that is taking place in the loop.
      * Steps:
      * 1. Check that the last element in the array is equal to searched element.
      *     a. YES, element index is found, return the index.
      *    b. NO, Take back up of last element and put the searched element on last index of array.
      * 2. Search for element with Infinite loop(without termination condition) and break when the element is found
      *    a. If element is found on last index, this is the element put by us to terminate
      *       the search and this signals that element not found in the array.
      *    b. If element found other than last index, set the backup to last index and return the index.
      **/
     private static int searchElement(int[] array, int value) {
           int idx = -1;

           int length = array.length;
           int backup = array[length-1];

           if(backup==value) {
                return (length-1);
           }

           array[length-1] = value;

           for (int i = 0;; i++) {
                if(value == array[i]) { /* n comparisons. */
                     idx = i;
                     break;
                }
           }

           if(idx==length-1) { /* 1 comparison. */
                idx = -1;
           }
           return idx;
     }
    
     public static void main(String[] args) {
           int value = 1;
           int [] array = {4, 6, 1, 5, 8};

           int index = searchElement(array, value);
           System.out.println("Element index in array "+index);
     }
}

This algorithm is developed to return the element index in n+1 comparison in the worst case.


Related Posts Plugin for WordPress, Blogger...