Monday 17 July 2017

Java | Reverse a String without using String class function


package com.java.tricks;
import java.lang.reflect.Field;
public class ReverseString {

     /**
      * This method is used to reverse string without using any string class method.
      */
     private static void reverseString(String value) {
           try {
               
                /** to access the private value[] array of String class. */
                Field field = String.class.getDeclaredField("value");

                /** Grant the access to access the field value. */
                field.setAccessible(true);

                /** Access the value array from the String class. */
                char[] array = (char[]) field.get(value);
                int i = 0; int j = array.length-1;

                /** Reverse the array values to reverse it. */
                while(i<j) {
                     char temp = array[i];
                     array[i] = array[j];
                     array[j] = temp;
                     i++; j--;
                }
               
                /** Set the reversed array into the String Object. */
                field.set(value, array);
           } catch (NoSuchFieldException | SecurityException |
                     IllegalArgumentException | IllegalAccessException e) {
                System.err.println(e.getCause());
           }
     }

     /**
      * Driver method to reverse a String.
      */
     public static void main(String[] args) {
           String value = "geeksforgeeks";
           System.out.println(value);
           reverseString(value);
           System.out.println(value);
     }
}

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

                                                  
Related Posts Plugin for WordPress, Blogger...