Friday, February 13, 2015

Fibonacci Series

This is very popular basic question often asked from beginners to check their recursive algorithm knowledge. This it will lead to some performance question, not much hard , but to how to improve, with testing memorization concept.

Fibonacci series is a number series where each number is built with the sum of the following two numbers.
F_n = F_{n-1} + F_{n-2},\!\,

1, 1, 2,3, 5, 8, 13 ......

Or
 0, 1, 1, 2, 3, 5, 8, 13 .....

This can be done using recursive algorithm as below.

------------------------------------------------------------------------
public static Integer fibR(Integer number) {

if (number == 1 || number == 2) {
return 1;
}
return fibR(number - 1) + fibR(number - 2);
}

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

This has some small issue, where recursion will have duplicate calls to calculate same fibonacci value.
Image result for fibonacci recursion

eg: If we calculate Fibonacci(5) , or value of Fibonacci series at 5 th position, we need Fibonacci values from Fibonacci(0)  to Fibonacci(5)
But with recursive way , except for Fibonacci(5) , all values are called repetitively. This is a waste.

So what we need to do. There the question of memorization will come to action.
That is, if we can have the memory of the values we have already calculated, then we can reuse them, without recalculating.

So we need to functionality to be made.
1. Keep the calculated Fibonacci values in memory
2. Before calculating new value, check whether value is calculated and need to have a retrieving mechanism of stored value.

Note : recursive algorithm is calling all the nodes, until get the leaf node
(  depending on your definition of Fibonacci series , series will defines as fib(0) , fib(1), fib(2).... or fib(1), fib(2), fib(3)...   )
So in both cases leaf nodes will be fib(0) , fib(1),  or fib(1), fib(2) respectively.
calculation happens from bottom to top after calling to create each node.
So Recursive algorithm is bottom up.

Next when come to memorization , I have create in top down approach.

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

public static Integer fibM(Integer number) {
HashMap cache = new HashMap();
cache.put(1, 1);
cache.put(2, 1);

if (number == 1 || number == 2) {
return 1;
}

// for memorization, we go from top to bottom - fib(1) to fib(n)
for (Integer i = 3; i <= number; i++) {
cache.put(i, cache.get(i - 1) + cache.get(i - 2));
}

return cache.get(number);
}

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

I have used a HashMap to cache the calculated values and finally return the Fibonacci  value.

Thursday, February 12, 2015

Reverse Number and Check Number is Palindrome

I have explained previously about finding a Armstrong number. There we used modulus and division operators.
Same way we can reverse a given number, and one step ahead can check whether it is Palindrome.

what is Palindrome number ?
If any number equals its reverse number, we call them palindrome number.

So checking Palindrome we need to reverse the number.

So first look at reversing number.

--------------------------------------------------------------------------------
 public static int reverseNumber(int number){
        int reverseNumber = 0;
        int remainder = 0;
        do{
            remainder = number%10;
            reverseNumber = reverseNumber*10 + remainder;
            number = number/10;
         
        }while(number > 0);
     
        return reverseNumber;
    }

-----------------------------------------------------------------------
We use modulus to get the last digit of the number and rest of the numbers exclusive of last digit by division.

To check the palindrome ,  we can use this functionality.
Note: I have done using do while loop ,but this can be done using while loop as we have used in Armstrong number scenario.
So benefit i will use Palindrome number check with while loop.


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

public static boolean isPalindrome(int number) {
int palindromeNumber = number; // copied number into variable
int reverseNumber = 0;

while (palindromeNumber != 0) {
int remainder = palindromeNumber % 10;
reverseNumber = reverseNumber * 10 + remainder;
palindromeNumber = palindromeNumber / 10;
}

// original number equals reverse number , then it's Palindrome.
if (number == reverseNumber) {
return true;
}
return false;
}

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



Wednesday, February 11, 2015

Find Armstrong Number

I thought of sharing this little question with you all. This is very simple question, but which will put your analytical and technical approach in test.
First place Amstrong number , for those who have never heard this, it's a very wonderful arithmetic art or classic we observe with base ten (we are normally using our number is base 10 format,it can be any format - this is also known as Narcissistic Number).

Amstrong number is any number , where sum of its own digits raised to the power of number of digits.

eg : If we take three digit number, Amstrong number , where sum of cubic value of each digit number equals to the number.
If get a number xyz then ,
 eg:  xyz = x^3 + y^3 + z^3

For further explain, let's take Amstrong number 153

153 = 1^3 + 5^3 + 3^3 = 1 +125 +27 = 153

See how nice  is that.

We continue example with 3 digit number, and extend the program for any number.

So it's very simple arithmetic operation to check whether a number is Armstrong ,
1. break number in to digit
2. get the sum of  cubic  value of each number.

So when come to the  implementation of the logic step 1 is where you will be tested, break the number in to digits. Obviously step 2 has very little where  getting sum of each cubic value- very simple and straight forwards writing of same arithmetic operation in any language.

How to break the number in to digits.

You can come up with various solutions. Convert to String and make substrings of size one, convert to char array , but any operation relate with strings and characters will have high cost and some implementation logic.

But we can use division and modulus operator to achieve this. Below code snippet will show you the method to check whether number is Armstrong.

public class ArmstrongNumber {

/*
* @return true if number is Armstrong number or return false
*/
// how to create the logic.
// we need to get the each digit of the number one by one
// get the cubic value, value to the power three
// and get the sum of all cubic value
//
// how to get digit by digit
// we can have so many approaches
// simple arithmetic way is to use modulus to break to digits
// and division to break the number exclusive of modulus , like taking
// substring except last character
public static boolean isArmStrong(int number) {
int result = 0;
int orig = number;
while (number != 0) {
int remainder = number % 10;
result = result + remainder * remainder * remainder;
number = number / 10;
}
// number is Armstrong return true
if (orig == result) {
return true;
}

return false;
}

public static void main(String[] args) {
int number = 153;
System.out.println("Number " + number + " is Amstrong ="
+ isArmStrong(number));

}

}


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

If I am going to explain further

Modulus operator is used to break the number in to digits. In base ten , if we need to break number in to digits all we need to do is , get the modulus by ten where you can get the last number.
So from modulus we can the last number.
Now problem , how to break the remaining part and continue to get the last digit.

int remainder = number % 10;

It's very simple, as same as getting the modulus of ten to get the last digit, if we get the division value of that number from 10, then we get the remaining part of the number(two digits to right side) - which is obviously to the right side of the number.

number = number / 10;

Two simple operation to break then number.
We continue to replace the number with division value itself, until number becomes zero - where no number to divide (number has been reduced to one digit)

while (number != 0)


Same arithmetic logic can be used to check whether number in Palindrome and reverse a given number.


So above program is designed to only to 3 digits number, but the concept has been implemented. Only thing is to get the power to number of digits.
So how we can find the number of digits in any number.
We have mathematical solution.

If we take any number any base, we take the log value of the number in the same base we get one less of the number of digits in the number.

So as we discussed for base ten, we get the number of digits as, or in simple length of the number.

int length = (int)(Math.log10(n)+1);

taking the power of number , you can few ways

Math.pow(remainder, length); // where length is the power - this takes double values as input and returns double

BigInteger.valueOf(3).pow(length)  // BigInteger has pow() method which needs and instance.

any way I have done the example using "int" values and code looks like below

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

public static boolean isArmStrong(int number) {
int result = 0;
int orig = number;
int length = (int)(Math.log10(number)+1);
while (number != 0) {
int remainder = number % 10;
result = result + (int)Math.pow(remainder, length);
number = number / 10;
}
// number is Armstrong return true
if (orig == result) {
return true;
}

return false;
}

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




Tuesday, February 10, 2015

WebSphere End to End War deployment

Once you install and configured websphere with new profile, you can start deploy war files.
Start new profile.
from websphere customization tool box, you can see the servers
here in my case server2 -- AppSrv02

start server

https://localhost:9044/ibm/console/
https://localhost:9044/ibm/console/login.do?action=secure
(above port=9061 - port will be increase by one for each profile creation.)
will load login page for admin
user name and password = admin/admin

1. Increase heap size

"webshere application server"  under server--> server types-->



select "server1"

select "Process definition" under "Server Infastructure"


select "Java Virtual Machine"  under additional properties.

Step 04 (Set Initial heap size & Maximum heap size àApply àSave),
Don’t give your system’s complete RAM size as Max heap size.  Ex, if your system is having 5120 RAM don’t give MAX heap size as “4096”. Give it as “2048”


In my case I have 4GB ram with left some 2BG, i would rather give some 1000 plus value, you can increase this later. 



make sure you apply the changes and save them (save for the configuration file.)












Config Websphere

Unzip websphere to c:\
it will have folder structure like

C:\ibm-websphere\WebSphere\AppServer\profiles\AppSrv01\firststeps

Then go to above "firsteps"  folder and run the bat file in command prompt."firststeps.bat run"

C:\ibm-websphere\WebSphere\AppServer\profiles\AppSrv01\firststeps>firststeps.bat run

it will give you below screen.


take your browser and got to
https://localhost:9043/ibm/console

https://localhost:9043/ibm/console/logon.jsp

username and password = admin/admin

successful login will load admin console.




Create New Profile
-----------------

Click "webSphere customization Toolbox" in application server console menu, same console where you have start and stop server.



this will give following window



















click "create" and select "Application server"
























select "Next"
























select "Advance"


























Select "Next" - with default settings all deploy options
You will configuration window, where you can give name for the profile.

I have given default name "AppSrv02"





















click "Next"

Give server name, Node name and host name























Give user name and password, with enable administrative security.
Then you will get security Certificate Part 1
if you like you can use that. I do not , just click Next






















after that you will receive (Part 2) , showing all configuration values.Click "Next"



Next you will get Port values. Click Next
Give Web Server definitions
You can use default values
Then you will get Web server definition (part 2) , click Next
Finally the  --> Profile Summary.

click "create"
It will create the profile with given details and show you with profile creation summary.


You can start new profile with given window option or by going to location
C:\ibm-websphere\WebSphere\AppServer\profiles\AppSrv02\firststeps


WebSphere start error

when you start websphere for first time, you may have unzipped the folder to direct to C;\  in windows and would have tried to start firststep.bat

C:\ibm-websphere\WebSphere\AppServer\profiles\AppSrv01\firststeps

this would have given error  something like "cannot find the path specified."

This happens cause , due to little mistake in unzipping the websphere. check whether you zipped folder has duplicated "ibm-websphere"  directory.
which results as

C:\ibm-websphere\ibm-websphere\WebSphere\AppServer\profiles\AppSrv01\firststeps

Showed in bold steps.

So make sure when unzip , give to C;\ itself  , rather than giving a extract folder.

Monday, January 19, 2015

Error in packaging Spring security example in Mkyong site


Link for code
http://www.mkyong.com/spring-security/spring-security-custom-login-form-annotation-example/

There are few errors
--------
misspelled of scope in a dependency as ''provider" and exclusion of "web.xml"

I have done the correction is 2 steps.
1. correction of the scope attribute
2. correction for exclusion of web.xml - where this will be looked and the example is done excluding web.xml  - added plugin to ignore web.xml


So again two corrections
--------------
1.

javax.servlet
javax.servlet-api
${javax.servlet.version}
provided


Below is the full trace of the error.

2.

org.apache.maven.plugins
maven-war-plugin
2.3

false



===========

C:\code\Examples\SpringSecurity\Mkyoung\spring-security-helloworld-annotation>mv
n package
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for
com.mkyong:spring-security-helloworld-annotation:war:1.0-SNAPSHOT
[WARNING] 'dependencies.dependency.scope' for javax.servlet:javax.servlet-api:ja
r must be one of [provided, compile, runtime, test, system] but is 'provider'. @
 line 41, column 11
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten t
he stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support buildin
g such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringSecurity Hello World XML 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ spring-s
ecurity-helloworld-annotation ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ spring-securi
ty-helloworld-annotation ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. b
uild is platform dependent!
[INFO] Compiling 2 source files to C:\code\Examples\SpringSecurity\Mkyoung\sprin
g-security-helloworld-annotation\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] \code\Examples\SpringSecurity\Mkyoung\spring-security-helloworld-annotat
ion\src\main\java\com\mkyong\config\core\SpringMvcInitializer.java:[7,7] error:
cannot access ServletException
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.450s
[INFO] Finished at: Mon Jan 19 15:20:27 IST 2015
[INFO] Final Memory: 10M/75M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.
3.2:compile (default-compile) on project spring-security-helloworld-annotation:
Compilation failure
[ERROR] \code\Examples\SpringSecurity\Mkyoung\spring-security-helloworld-annotat
ion\src\main\java\com\mkyong\config\core\SpringMvcInitializer.java:[7,7] error:
cannot access ServletException
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
ch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureExc
eption
C:\code\Examples\SpringSecurity\Mkyoung\spring-security-helloworld-annotation>

==========


Errors in POM

1. dependency ' javax.servlet"  scope is mispelled as "provider"  --> should be "provided"


=====
Error after correcting scope

============

[INFO]
[INFO] --- maven-war-plugin:2.1.1:war (default-war) @ spring-security-helloworld-annotation ---
[INFO] Packaging webapp
[INFO] Assembling webapp [spring-security-helloworld-annotation] in [C:\code\Examples\SpringSecurity\Mkyoung\spring-security-helloworld-anno
tation\target\SpringSecurityHelloWorld]
[INFO] Processing war project
[INFO] Copying webapp resources [C:\code\Examples\SpringSecurity\Mkyoung\spring-security-helloworld-annotation\src\main\webapp]
[INFO] Webapp assembled in [1123 msecs]
[INFO] Building war: C:\code\Examples\SpringSecurity\Mkyoung\spring-security-helloworld-annotation\target\SpringSecurityHelloWorld.war
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.401s
[INFO] Finished at: Mon Jan 19 15:50:57 IST 2015
[INFO] Final Memory: 13M/109M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-war) on project spring-security-helloworld-annot
ation: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

==============