Saturday, 29 October 2016

Longest Repeating Subsequence

Find length of the longest repeating subsequence such that the two subsequences don’t have same string character at same position, i.e., any k’th character in the two subsequences shouldn’t have the same index in the original string.

This problem can be solved using the Longest Common Subsequence problem. LRS(str, str) where str is the input string with the restriction that when both the characters are same, they shouldn’t be on the same index in the two strings.


package amazon.dp;

public classLongestRptSubseq {

     private static int getLRS(String string) {
          
           char[] charArray = string.toCharArray();
           int len = charArray.length;
          
           int[][] dp = new int[len+1][len+1];
          
           for(int i=1;i<=len;i++) {
               
                for (int j=1;j<=len;j++) {

                     // If characters match and indexes are not same
                     if (charArray[i-1] == charArray[j-1] && i!=j) {
                           dp[i][j] =  1 + dp[i-1][j-1];
                          
                     } else {
                           // If characters do not match
                           dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
                     }
                }
           }
          
           return dp[len-1][len-1];
     }

     public static voidmain(String[] args) {
           String string = "amazonazom";
           int len = getLRS(string);
           System.out.println("Longest Repeating Subsequence "+len);
     }
}

Count number of ways to cover a distance

Count total number of ways to cover the distance with 1, 2 and 3 steps.

Recursion solution time complexity is exponential i.e. O(3n).

Since same sub problems are solved again, this problem has overlapping sub problems property. So min square sum problem has both properties of a dynamic programming problem.


public class MaxStepsCount {

     /** Dynamic Programming. */
     private static int getMaxWaysDP(int distance) {

           int[] count = new int[distance+1];
           count[0] = 1;
           count[1] = 1;
           count[2] = 2;

           /** Memorize the Sub-problem in bottom up manner*/
           for (int i=3; i<=distance; i++) {
                count[i] = count[i-1] + count[i-2] + count[i-3];               
           }
           return count[distance];
     }


     /** Recursion Approach. */
     private static int getMaxWaysRecur(intdistance) {
           if(distance<0) {
                return 0;
           } else if(distance==0) {
                return 1;
           }
           return getMaxWaysRecur(distance-1)+getMaxWaysRecur(distance-2)
                     +getMaxWaysRecur(distance-3);
     }

     public static void main(String[] args) {
           // Steps pf 1, 2 and 3.
           int distance = 10;

           /** Recursion Approach. */
           int ways = getMaxWaysRecur(distance);
           System.out.println(ways);

           /** Dynamic Programming. */
           ways = getMaxWaysDP(distance);
           System.out.println(ways);
     }
}

Sunday, 23 October 2016

How to get the file last modified date in Java?

In Java, File.lastModified() can be used to get the file’s last modified time stamp.

This method will returns the time in milliseconds (long value), we can format it with SimpleDateFormat to make it readable format.

importjava.io.File;
importjava.text.SimpleDateFormat;

public classFileLastModifiedDate {
     public static voidmain(String[] args) {

           File file = new File("C:\\HaxLogs.txt");

           System.out.println("Last modified stamp: " + file.lastModified());

           SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

           System.out.println("Formatted date: " + sdf.format(file.lastModified()));
     }
}

Saturday, 22 October 2016

Listing all drives with type, total space and free space in Java



importjava.io.File;

importjavax.swing.filechooser.FileSystemView;

public class DrivesLists {
  
   public static voidmain(String[] args) {

      FileSystemView fsv = FileSystemView.getFileSystemView();

      File[] drives = File.listRoots();

      if (drives != null && drives.length > 0) {

         for (File drive : drives) {
            System.out.print("Drive name: "+drive);
            System.out.print(",\tType: "+fsv.getSystemTypeDescription(drive));
            System.out.print(",\tTotal space: "+drive.getTotalSpace());
            System.out.print(",\tFree space: "+drive.getFreeSpace());
            System.out.println();
         }
      }
   }
}

Insert 100000 records in database with minimum time?

Using PreparedStatement batch

1. Create DB connection.
2. Create query for prepared statement.
3. setAutoCommit false.
4. Prepare stamen and add it to batch.
5. If batch size is multiple of 2000 then commit the database.
6. Repeat step 4 and 5 till the complete data is loaded.
7. close connection.

public static intuploadFilesData(List<CallDetailDTO> list) {
          
           connection = getConnection();
          
           String query = Constants.INSERT_PREFIX + Constants.TABLE_ROWS + Constants.PREPARED_STMT_VALUE;

           int count = 0;

           try {
                connection.setAutoCommit(false);
               
                PreparedStatement ps = connection.prepareStatement(query);

                for (CallDetailDTO dto: list) {
                     ps.setString (1,dto.getPartyNumberA());
                     ps.setString (2,dto.getPartyNumberB());
                     ps.setString (3,dto.getCallDate());
                     ps.setString (4,dto.getCallTime());
                     ps.setString (5,dto.getDuration());
                     ps.setString (6,dto.getCellId());
                     ps.setString (7,dto.getLastCellId());
                     ps.setString (8,dto.getCallType());
                     ps.setString (9,dto.getImei());
                     ps.setString (10,dto.getImsi());
                     ps.setString (11,dto.getPpPo());
                     ps.setString (12,dto.getSmsCentre());
                     ps.setString (13,dto.getRoamingNwCied());
                     ps.setString (14,dto.getSheetName());

                     ps.addBatch();

                     if(++count % Constants.BATCH_SIZE == 0) {
                           ps.executeBatch();
                           connection.commit();
                     }
                }
                ps.executeBatch();
                connection.commit();
                ps.close();
                connection.close();
           } catch (SQLException e) {
                System.out.println("SQLException:"+e.getMessage());
           }

           return count;
     }
Related Posts Plugin for WordPress, Blogger...