Saturday, July 16, 2011

File IO and bit counting

I made this problem up to practice doing file IO, bit manipulation, and using data structures.

Problem:
1. Generate a file where each line is a random integer
2. Read the file
3. For each line count the number of set bits (1's) in the integer, and order the output in ascending order of most bits set.

Example:
File=
4
1
6
2
1
5
1
7
0
6


Output should be this:
-------------
Ones=0
0
-------------
-------------
Ones=1
4
1
2
1
1
-------------
-------------
Ones=2
6
5
6
-------------
-------------
Ones=3
7
-------------

Solution


In Main
       int[] arr = getRandomArray(10);
       String fileName = "D:/Test/BitManip.txt";
       FileIO.Write(fileName, arr);
       FileIO.OrderByNum1s(fileName);

In FileIO.java
public class FileIO {

    public static void Write(String fileName, int[] arr)
    {
        try
        {
           BufferedWriter bw = new BufferedWriter(new FileWriter(new File(fileName)));
           for(int i = 0; i < arr.length; i++)
           {
               bw.append(String.valueOf(arr[i]));
               bw.newLine();
           }
           bw.close();
        }
        catch(IOException io)
        {
            System.out.println(io);
        }
       
    }
    public static void OrderByNum1s(String fileName)
    {
        try
        {
            BufferedReader br = new BufferedReader(new FileReader(new File(fileName)));
            Integer i = 0;
            TreeMap<Integer, ArrayList<Integer>> tree = new TreeMap<Integer, ArrayList<Integer>>();
            String input = null;
            while((input = br.readLine()) != null)
            {
                i = Integer.parseInt(input);
                int count = countOnes(i);
                if(!tree.containsKey(count))
                {
                    ArrayList<Integer> numList = new ArrayList<Integer>();
                    numList.add(i);
                    tree.put(count, numList);
                }
                else
                {
                    tree.get(count).add(i);
                }
                   
            }
            br.close();
            ArrayList<Integer> ints = new ArrayList<Integer>();
            for(Map.Entry<Integer, ArrayList<Integer>> entry : tree.entrySet())
            {
                System.out.printf("-------------\nOnes=%d\n", entry.getKey());
                for(Integer k : entry.getValue())
                    System.out.println(k);
                System.out.printf("-------------\n");
            }
           
        }
        catch(IOException io)
        {
            System.out.println(io);
        }
    }
    private static int countOnes(Integer i)
    {
        int count = 0;
        for(int j = 0; j < Integer.SIZE; j++)
        {
            int bitmask = 1<<j;
            if((bitmask & i.intValue()) == bitmask)
                count++;
        }
        return count;
    }
}
 

No comments:

Post a Comment

There was an error in this gadget