Sunday 21 July 2013

Determine if any anagram of a string can be a palindrome.

The Problem : 

      Given a string containing only lowercase alphabets, determine whether an anagram of this string can be a palindrome. Output YES if an anagram which is a palindrome exists and NO otherwise. The length of the string can vary between 1 and 100000, both inclusive.

Examples :

Input String : aab
Output : YES
Explanation : aba is an anagram which is a palindrome

Input String : babb
Output : NO
Explanation : No anagram of "babb" exist which is a palindrome

Input String : a
Output : YES
Explanation : a is itself a palindrome

Input String :bbabaaa
Output : YES
Explanation aabbbaa is an anagram which is a palindrome


The Solution : 

      A brute force way of solving this would be to generate all anagrams of the given string and then check whether any of them is a palindrome. But a string of length n (of distinct characters) can have n! different anagrams. Thus this method is not feasible even for small values of n (5!=120, 10!=3628800). A faster solution is thus needed.

      Lets look at an even length string. For this to be a palindrome the first half of the string must match the second half. So each characters in the first half of the string must also be present in the second half. Hence, there must be an even number of occurrences of each character in the string. (Note that here we say even occurrences of each character and not 2 occurrences. Why?. Consider the case where we have 4 occurrences of character 'a'. This means two of them can lie in the first half and the other two in the second half, hence an even number of occurrences is acceptable).

      Now lets take the case of an odd length string. Here the middle character of the string can be anything. Only the former part of the string (before the middle character) must match the latter part(after the middle character). So the middle character does not need a matching character, but the rest of the characters must occur in pairs (i.e. each character other than the middle must occur an even number of times in the string).

Now, for the problem at hand.

Case 1: Even length string 
   
      If each character of the string occurs an even number of times then we can make a palindrome out of it by rearranging the characters. For each character in the first half there shall exist a matching one in the second half. So we just need to count the occurrence of each character. If each character occurs an even number of times we can print YES.

Case 2: Odd length string

      Here, in a palindrome, all characters must have a matching pair except the middle one. So each character must occur an even number of times except one. So in a random string if all characters except one occur an even number of times, then these characters can be arranged in the first and second halves of the string. Now for the character that occurs an odd number of times. Suppose it occurs 5 times. Then 4 occurrences of this can be included in the first and second halves of the palindrome and the remaining one occurrence will become the middle character.
       Note that if, in a string, we had more than one character occurring an odd number of times the we could not have created a palindrome out of it.

So the logic becomes :

If string is of even length, check if all characters occur an even number of times, if they do print YES else print NO.

If string is of odd length, check if all but one characters occur an even number of times, one character must occur odd number of times, if these conditions satisfy print YES else print NO.


The Implementation:

      Here we need to count the occurrence of only 26 lowercase alphabets. So take an array of length 26. The count of 'a' will stored at the zeroth positions, 'b' at the first position and so on. Initialize this array with 0's. Lets call this array a[].

      Now a naive implementation would be to simply go through the string and increment the corresponding position in the array. At the end go through the array to check if the requirements defined in the logic are met. There is however a better solution where we need not traverse the array to get the solution.

      We take a flag variable to indicate the number of characters which occur odd number of times in the string. Every time we encounter a character we shall toggle the corresponding position in the array. Since the initial value of the position was 0, the first time it is toggled, it will become 1. On the next toggle it will become zero. Hence, a value 1 indicates the first occurrence and a value zero indicates the second occurrence. So every time a position becomes 1 increment the flag, and every time it becomes zero decrement the flag.

      So at any point during the traversal of the string the flag will indicate the number of characters whose occurrence count till this point is odd. Lets see this with an example.

Lets take the string ababb. A dry run is shown in the following table

Position   Character           array a[]                flag
   0               a           a[0]=1,others 0                   1    (till this point a-odd)
   1               b           a[1]=1,a[0]=1,others 0       2    (till this point a-odd, b-odd)
   2               a        a[0]=0,a[1]=1,others 0        1    (till this point b-odd)
   3               b a[1]=0,others 0                   0    (till this point none-odd)
   4               b a[1]=1,others 0                   1    (till this point b-odd)


The toggle can be implemented by using the XOR operator " ^ ".

Now to display the result, the following steps are followed :

1. Find length of string
2. If even then if flag=0 print YES esle print NO
3. If odd then if flag=1 print YES else print NO

The Code (in C): 

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
   int a[26],i,flag=0,len=0;
   char str[100001],*ptr=NULL;
   for(i=0;i<26;i++)
   a[i]&=0;
   scanf("%s",str);   //the input
   ptr=str;
   while(*ptr)   //traversing the string
   {
      len++;   //counting the length
      a[*ptr-97]^=1;   //toggle the position for if ptr points to a the a[*ptr-97] translates to a[0]
      if(a[*ptr-97])   //if position became 1
         flag++;
      else   //if position became 0
         flag--;
      ptr++;
   }
   if(len&1)   //if string is of odd length
   {
      if(flag==1)
         printf("YES");
      else
         printf("NO");
   }
   else   //if string is of even length

   {
      if(flag==0)
         printf("YES");
      else
         printf("NO");
   }
   return 0;
}

      Note that if in the problem it was not specified that the contents of the string are lowercase alphabets, then we could take the array to be of length 256 to take into account all the ASCII characters.

Saturday 20 July 2013

Capture Screenshot/Part of Java GUI

      In this post we shall see how to capture a screenshot with java. Also, we shall see how to capture the GUI (complete with the frame or partial e.g. a graph displayed in a panel) thrown by a Java Program. This may be useful in the case when we have to take a print out of, say, a graph or an image which is displayed on the Graphical User Interface(GUI).

Part 1 : The Screenshot

      To do this we shall make use of the Robot, BufferedImage and ImageIO classes. A brief description of how the classes are used follows :

Robot :  The Robot class has a function called createScreenCapture() which take as parameter a Rectangle object. The Rectangle object specifies the portion of the screen to capture (through coordinates). It returns a BufferedImage object. For taking a screenshot the rectangle must cover the entire screen. We can get the screen size by using the Toolkit.getDefaultToolkit().getScreenSize() method.

BufferedImage :  This class is used to describe an image. We shall store the return value from the call to the createScreenCapture() method of the Robot class in a BufferedImage object. Then this will be used to write a file containing the image using the ImageIO class.

ImageIO : It has a static method called write() which takes three parameters : the image(BufferedImage object), the format of the file to write(e.g. png) and the name of the file.


The CODE : 

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
class ScreenCapture {
   public static void main(String args[]) {
      try {
         Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
         BufferedImage capture = new Robot().createScreenCapture(screenRect);
         ImageIO.write(capture, "png", new File("d:\\screencapture.png"));
      }catch (Exception ex) {
         System.out.println(ex);
      }
   }
}


Part 2 : Cpturing Java GUI

      Now, we shall try to capture the GUI displayed by a Java Swing/AWT program. This can be useful when we have to print the whole layout displayed by a program or print a portion of it (say a graph or an image displayed on it). To do this we shall make use of the BufferedImage and the ImageIO classes. The following points explain the process :

1. Instantiate a BufferedImage object (called capture in our example) using the three argument contructor. The arguments passed are the a) width - width of the created image b) height - height of the created image c) imageType - type of the created image.
2. Call the components paint method(the component whose contents are to be captured). Pass as argument capture.getGraphics(). When the getGraphics() method is called on a component, it returns the component's graphics context, which lets you draw on a component. When this is passed as argument to paint method, the contents of the component calling the paint method(pnl2 in our case) are drawn on the object whose Graphic context is passed as argument.
3. Lastly we use the ImageIO.write() method to write the BufferedImage object to a file.


The CODE : 

Here we display a simple frame with two panels and capture the contents of pnl2 in an image.

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
public class CapturePanelInFrame extends JFrame {
   JPanel pnl1,pnl2;
   JLabel lab1,lab2;
   public CapturePanelInFrame() {   //Creating the GUI
      pnl1=new JPanel();
      pnl2=new JPanel();
      pnl1.setBackground(Color.blue);
      pnl2.setBackground(Color.green);
      lab1=new JLabel("This is the Label in Panel1");
      lab2=new JLabel("This is the Label in Panel2");
      pnl1.add(lab1);
      pnl2.add(lab2);
      setLayout(new GridLayout(2,1));
      add(pnl1);
      add(pnl2);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(400,200);
      setVisible(true);
      captureit(pnl2);
   }
   private void captureit(JComponent comp) {
      Rectangle rec = comp.getBounds(); // Getting the size of Component
      BufferedImage capture = new BufferedImage(rec.width, rec.height,BufferedImage.TYPE_INT_ARGB);
      comp.paint(capture.getGraphics());//capturing the components content in the capture object
      try {
         ImageIO.write(capture, "png", new File("capturepnl.png")); //writing the captued image to a file
      } catch (Exception e) {
         System.out.println(e);
      }
   }
   public static void main(String args[])
   {
      new CapturePanelInFrame();
   }
}


      Note that we pass the component to be captured to the captureit() method. So if we need to display the whole frame that is to be displayed, we can simply pass the JFrame object.

Saturday 6 July 2013

Open browser with proxy settings set from Java code

      In this post we aim to to write a java application which lets the user click a button to open a browser with its proxy settings set. To open an application from java we can use the exec method of the java Runtime class. So one can simply open a browser from java code. But the second part of the problem states that its proxy settings must be set to a specific value. In order to achieve this we shall make use of Google Chrome's switches. A detailed description of the entire process is given below.

Google Chrome Switches : 

      The Chrome Browser allows the use of command line flags (or "switches") that the browser accepts in order to enable particular features or modify otherwise default functionality. To use these switches we need to modify the target of an application. This can be done as follows.

Step 1 : Create a shortcut of the chrome.exe file. (To create a shortcut right click on the chrome.exe application, go to the Send To submenu and click on Desktop(create shortcut) item. This will create a shortcut of the application on your desktop).

Step 2 : Right click on the shortcut and click on Properties.

Step 3 : Append the following flag to the target text box value --proxy-server=127.0.0.1:8080. Here 127.0.0.1, 8080 are the IP and port of the proxy server (You may change these to reflect your own proxy server). With this flag the target must now look like chrome.exe --proxy-server=127.0.0.1:8080. Note that there is a space between chrome.exe and the flag.

Step 4 : Click on Apply and close the Properties window.

      Now  if you open the shortcut it will start the browser with its proxy setting set. Note that if an instance of the chrome browser is already opened then the proxy settings wont be used, so you must close any running instances of the browser before opening the shortcut. These proxy settings will not be shown in the proxy settings accessible through the settings tab of chrome. So in order to verify you can set the proxy to any random free ip-port address and open the shortcut. If the proxy settings were indeed set, opening any website in the browser will show you the following error : Unable to connect to the proxy server. (for this check you may use 127.0.0.1:8080 as proxy settings provided you do not have a proxy set up on your machine).

      So if we are able to somehow open this shortcut from our java code we are set. We shall do exactly this with the exec method of the  Runtime class.


The Runtime class :

      The Runtime Class in java encapsulates the runtime environment. You can get a reference to the current Runtime object by calling the Runtime.getRuntime() method. Once a reference to the current runtime object is obtained we can call the exec method to execute a specific command. This command must open the shortcut of the browser that we had created earlier. The following command accomplishes this  :

cmd /c start /d \"d:\" chrome.lnk

      Note that here d: is the path of where our application is and chrome.lnk is the name of the application.  This means that I had kept the shortcut in my d: drive. So you can change the path to reflect the location of your shortcut file. (The name is chrome .lnk because the shortcuts in windows have the extension lnk).


The CODE!

Following is the complete code that does the above :

public class OpenBrowser {
   public static void main(String[] args) {
      try {
         Process process = Runtime.getRuntime().exec("cmd /c start /d \"d:\" chrome.lnk");
      }
      catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}


Now the incorporation of the above method into an application where a click on a button triggers the above task is trivial.

Warning : Note that Google states the following on its chromium page
"It is important to note that using these switches is not supported or recommended. They should only be used for temporary cases and may break in the future."
So use this solution at your own risk :)