Thursday, 26 November 2015

Pythagorean Triplets


A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2. Such a triple is commonly written (a, b, c), and a well-known example is (3, 4, 5). If (a, b, c) is a Pythagorean triple, then so is (ka, kb, kc) for any positive integer k. A primitive Pythagorean triple is one in which a, b and c are coprime. A right triangle whose sides form a Pythagorean triple is called a Pythagorean triangle.


Finding all the triplets  for c2<= n :

public class PythagoreanTriplet {
        static int count = 0;
public static void main(String[] args) {
Long start = System.currentTimeMillis();
                //time comparison for various number of inputs 
//int n = 100000000;//total time in ms=1118847
//int n = 10000000;//total time in ms=36031
//int n = 1000000;//total time in ms=2122
//int n = 100000;//total time in ms=66
//int n = 10000;//total time in ms=20
//int n = 1000;//total time in ms=2
//int n = 100;//total time in ms=1

int n = 1000;
List<Integer> listOfSquraes = new ArrayList<>();
for (int i = 1;; i++) {
int sqr = i*i;
if(sqr > n){
break;
} else {
listOfSquraes.add(sqr);
}
}
int  k =listOfSquraes.size();
for (int i = 0; i<k; i++) {
findPythagoreanTriplet(listOfSquraes.get(i), listOfSquraes,k);
}
Long end = System.currentTimeMillis();
System.out.println("total triplets found=" + count + " and total time in ms=" + (end-start));
}

public static void findPythagoreanTriplet(int sumRequired,List<Integer> list, int size){
for (int i = 1; i < size; i++) {
for (int j = i+1; j < size; j++) {
int sum  = list.get(i) + list.get(j);
int diff = sumRequired-sum;
if(diff == 0){
count++;
System.out.println("("+(int)Math.sqrt(list.get(i)) + "," + (int)Math.sqrt(list.get(j)) + "," + (int)Math.sqrt(sumRequired)+")");
}
}
}
}
}

Output

(3,4,5)
(6,8,10)
(5,12,13)
(9,12,15)
(8,15,17)
(12,16,20)
(7,24,25)
(15,20,25)
(10,24,26)
(20,21,29)
(18,24,30)

total triplets found=11 and total time in ms=2

Time complexity though O(n3) which we can reduce with the improving the search to O(nlogn) , so overall complexity would reduce to O(n2logn).

Sunday, 22 November 2015

Installing MongoDB on MacOS X



MongoDB Version : 3.0.7

Mac OS X Version : 10.10.4

Following are step by step installation of the mongodb on the Mac OS :

Start with the Terminal 1 :

1. Get the latest MongoDB from the downloads MongoDB

2. Go to Downloads folder  -- >  cd ~ Downloads/

3.  sudo mv mongodb-osx-x86_64-3.0.7.tgz  /Users/sachin/Documents/software/mongodb [cd ~ is /Users/sachin ]

4. cd ~ Documents/software/mongodb

5. tar xzf mongodb-osx-x86_64-3.0.7.tgz

6. By default MongoDB stores the data  in the /data/db folder , so  we require to create the data and to provide proper permission to it :

  a) sudo mkdir -p /data/db
  b) whoami
      sachin
  c) sudo chown sachin /data/db

7. Adding mongo db to $PATH  : 
  a)  cd ~
  b) pwd 
      /Users/sachin
 c)  vim .bash_profile
 d) export PATH=$PATH:/Users/sachin/Documents/software/mongodb/mongodb-osx-x86_64-3.0.7/bin

8) Starting the MongoDB :

a) Go to new Terminal 2
b) mongod    (it starts the mongo service)

9) Go to Terminal 3 :
a) mongo

MongoDB shell version: 3.0.7

connecting to: test

An Alternate to manually starting the mongoDB using the background job as following : 

10 ) Auto starting the Mongodb  using job : 

a)  sudo vim /Library/LaunchDaemons/mongodb.plist

b)  insert the following text and save the file : 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>mongodb</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Users/sachin/Documents/software/mongodb/mongodb-osx-x86_64-3.0.7/bin/mongod</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>WorkingDirectory</key>
  <string>/usr/local/mongodb</string>
  <key>StandardErrorPath</key>
  <string>/var/log/mongodb/error.log</string>
  <key>StandardOutPath</key>
  <string>/var/log/mongodb/output.log</string>
</dict>
</plist>

c) Load the above mentioned job in the background :

sudo launchctl load /Library/LaunchDaemons/mongodb.plist






Welcome and Enjoy the MongoDB world !!!!!

Saturday, 21 November 2015

Generating multiple log file using log4j

It is a good practise to separate out the application log and error log for your application. With a distinguish error logs , monitoring of the project becomes easy and debugging process becomes easy.

Usually in application log, we write many useful information depending upon what the default logging level is set. 

With the latest development in Log4J , the set of built-in levels includes TRACE, DEBUG, INFO, WARN, ERROR, and FATAL. 

If you want to create two different files , one for application and one for errors log, following configuration is required to add in the log4j.properties file kept in the classpath : 
----------------------------------------------------------
# Root logger option
log4j.rootLogger=INFO, app, error

# application log file
log4j.appender.app=org.apache.log4j.RollingFileAppender
log4j.appender.app.File=${catalina.home}/logs/application.log
log4j.appender.app.MaxFileSize=10MB
log4j.appender.app.MaxBackupIndex=10
log4j.appender.app.layout=org.apache.log4j.PatternLayout
log4j.appender.app.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n


#error logs
log4j.appender.error=org.apache.log4j.RollingFileAppender
log4j.appender.error.File=${catalina.home}/logs/error.log
log4j.appender.error.MaxFileSize=10MB
log4j.appender.error.MaxBackupIndex=10
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n
log4j.appender.error.Threshold=ERROR
-----------------------------------------------------

File path is used here is the default set value of the tomcat catalina home , if you are using some other application server , then you can use the ${SERVER_HOME} path  or whatever the path , you would like to add.

Above configuration generates two files : 

1 . application.log which contains all the logging information  of INFO and upper level  of logging levels.
2. error.log file only contains ERROR logging level information, so whatever you want keep in the error logs .

Java is Pass by Value or Pass by Reference !!!!


In the Java , there is no concept of pointers and objects are  stated to have passed by value. In case of primitives only values can be passed to a method and in case of java objects , it is said to be pass by reference value.

I think correct term should be termed as  Pass by reference value instead of Pass by Value.

Behind the scene its the passing of the value of the reference bit by bit in the method  so its not passing the reference. Following example would validate the  above facts  :


public class Name
{
String name;

Name(String name){
this.name = name;
}

public static void changeNameReference(Name oldname){
oldname = new Name("John");
}
public static void modifyNameReference(Name oldname){
oldname.name = "Brock";
}

public static void main (String[] args) throws java.lang.Exception
{
Name newname = new Name("Rock");
System.out.println("#1.Original name= " + newname.name + " and system hashcode=" + System.identityHashCode(newname));
changeNameReference(newname);
System.out.println("#2.After changeNameReference method call name= " + newname.name + " and system hashcode=" + System.identityHashCode(newname));
modifyNameReference(newname);
System.out.println("#3.After modifyNameReference method call name= " + newname.name + " and system hashcode=" + System.identityHashCode(newname));

}

}

Output : 
-----------------------------------------------------------------------
#1.Original name= Rock and system hashcode=582216281
#2.After changeNameReference method call name= Rock and system hashcode=582216281
#3.After modifyNameReference method call name= Brock and system hashcode=582216281

------------------------------------------------------------------------

Following points by points to keep understand the above example :

1. Note the Point#1 and # 2 having the same value of the object even though object is passed into the method changeNameReference   which assigning the new reference to the object but original object remain intact.

2. In the point#3 , when a new value is assigned to the  argument object to the method  modifyNameReference , its changed the value of the original object with the  new value "Brock"

3. Value of the object is being passed bit by bit but reference remain same in the Heap memory

4. Note the system hash code value  they are same, so object reference is same  in the heap memory.If reference would have passed then definitely the value system hashcode  would have changed.

Note that Class instance and Array  are the objects in java, so passing the reference value in any method would not affect the reference of the object.


Palindrome



palindrome is a word, phrasenumber, or other sequence of characters which reads the same backward or forward. Allowances may be made for adjustments to capital letters, punctuation, and word dividers. Famous examples include "A man, a plan, a canal, Panama!", "Amor, Roma", "race car", "stack cats", "step on no pets", "taco cat", "put it up", "Was it a car or a cat I saw?" and "No 'x' in Nixon"


Java code to validate the Palindrome is as follow : 

/*
 * @sachin
 */
public class Palindrome {
public static boolean isPalindrome(String input) throws Exception{
if(input == null || input.isEmpty()) {
throw new Exception("Invalid input");
}
String str = input.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
boolean isPalindrome = true;
int i = 0;
int j = str.length();
for(i=0; i< j;i++){
if(str.charAt(i) == str.charAt(j-1)){
j--;
continue;
} else {
isPalindrome = false;
}
}
return isPalindrome;
}
public static void main(String[] args) {
try {
System.out.println("isValidPalindrome=" + isPalindrome("No 'x' in Nixon"));
                        System.out.println("isValidPalindrome=" + isPalindrome("12321"));
                        System.out.println("isValidPalindrome=" + isPalindrome("sachin"));
} catch (Exception e) {
e.printStackTrace();
}
}

}

Output

true
true
false