Friday, September 12, 2008

remove first element from list in Haskell

Hello All~

As you are aware, I am presently reading the beautiful book "The Haskell Road to Logic Maths and Programming" and another book called the "black Swan - The Impact of the highly Improbable" by Nassim Nicholas Taleb. As I have just started reading it yesterday, I will include my views on the book in the coming days.
However what I plan to do today is solve the exercise 1.10 from the haskell book, so here is the problem with my explanation.
Problem: Define a function removeFst that removes the first occurrence of an integer m, from a list of integers. If m does not occur in the list, the list remains unchanged.
For example let us consider the list [1,2,3,4,5,6,2], so if we call the program thus


removeFst 2 [1,2,3,4,5,6,2]


We should get the list [1,3,4,5,6,2] as return. Only the first occurrence of 2 is removed, any other 2 in the list is left unchanged.
I will present 2 solutions.
Solution 1: removes the first occurrence of 2.
Solution 2: removes all occurrences of 2.

Solution 1:

--Test for an empty list, if an empty list throw error.
removeFst n []=error "The list is empty "
--Cover the condition in case there is only 1 element in the array
removeFst n [x]|n==x=[] --Case n==x, show a blank array as output
|otherwise=[x]
--Handle the usual case, in case x==n, we return the tail else
--create a new array and append x recursively.
removeFst n (x:xs)|n==x=xs
|otherwise=x:removeFst n xs


Solution 2:

--Test for an empty list, if an empty list throw error.
removeFst n []=error "The list is empty "
--Cover the condition in case there is only 1 element in the array
removeFst n [x]|n==x=[] --Case n==x, show a blank array as output
|otherwise=[x]
--Handle the usual case, in case x==n, we return the tail else
--create a new array and append x recursively.
removeFst n (x:xs)|n==x=removeFst n xs --Do nothing and move to the next element
|otherwise=x:removeFst n xs


Wednesday, September 10, 2008

Find if a number is prime or not.

Hello Friends~

I am presently reading a beautiful book, "The Haskell Road To Logic Maths and Programming" by Kees Doets and Jan Van Eijck. I would highly recommend this book to any serious student of Computer Science. I plan to talk on prime numbers as that's what I read yesterday.
Here's a brief background on prime numbers. Well a prime number is a number that does not have factors other than itself and 1. For example lets take a number 7, as the number 7 does not get cleanly divided by any number except 1 and 7 hence it is a prime. Similarly the number 8, is divided cleanly by 2 and 4 hence it is not a prime.

Some applications of prime number are in the field of RSA encryption.

There are many ways to find if a given number is prime or not. One commonly used way is to run a for loop starting from 2 up-till the number/2+1, in case of a clean division we declare that the number is not a prime. This method works great for small numbers, but just imagine the amount of work that needs to be done to find if a very large number is a prime number or not.

We will state 2 propositions and write a small java program based on the proposition to find if a given number is prime number.
Let us define a number L(n)>1 as the least natural number that divides n.
Proposition 1:
for L(n) > 1 L(n) is a prime.
We will prove this proposition through a process called contradiction.

Let p=L(n).
In case p is not a prime, we can factor it such that:
a*c=p; which follows a > 1 and c < p.
Hence the least possible number dividing n must naturally be a prime.

Proposition 2:
for n>1 and n is not a prime, (L(n))^2<=n

So let's prove this one as well.
Let p=L(n).
As p is a factor of n, it follows.
a*p=n. for some number a such that
a > = p ----------------1
as p is the least natural number dividing n.
Multiplying both sides of 1> by p, we get
a.p >= p^2; substituting a.p=n and p^2=(L(n))^2 we get
Which basically means that the square of the least prime factor of a number is always less than or equal to the number.

Here's is the java implementation, enjoy:


package algos;

public class IsPrime {

public static boolean isPrime(int number)
{
boolean flag=true;
for(int i=2; i <= number; i++)
{
if(number%i==0)
{
flag=false;
break;
}

if((i*i)>=number)
{
flag=true;
break;
}


}
return flag;

}


public static void main(String[] args) {
System.out.println(isPrime(23));
}
}

Monday, September 8, 2008

Find Letter frequency in a sentence

Hello ALL~

I was reading this beautiful book on python at http://greenteapress.com out there I came across a python implementation for finding out the word frequency in a given sentence. You might naturally ask, why do frequency analysis? Well the reasons are many, but the primary usage may be in the field of compression, if we know which letter has the maximum freq in a file we can devise efficient encoding techniques to compress a given file.

So let's cut out the talk here goes the implementation.


package dictionary;

import java.util.Map;
import java.util.TreeMap;

public class LetterFrequency {

private Map map=new TreeMap ();
private String feed;
public LetterFrequency(String feed)
{
this.feed=feed;
}

public Map findFrequency()
{
char feedChar;
Integer freq;
for(int i=0; i<feed.length(); i++)
{
feedChar=feed.charAt(i);
freq=map.get(feedChar);
map.put(feedChar, freq==null?1:freq+1);
}
return map;
}

public static void main(String[] args) {
LetterFrequency frequency=new LetterFrequency("Vivek Ramaswamy");
System.out.println("LetterFrequency "+ frequency.findFrequency());
}

}

Monday, September 1, 2008

Date manipulation in perl.

Hello~

I ran across, a small problem while coding in Perl the other day.
I wanted yesterdays, date to do some calculations. The way I went about it was as follows:



use Time::localtime;
$tm=localtime;
$yesterdaysDate=sprintf("%04d-%02d-%02d",$tm->year+1900, ($tm->mon)+1, ($tm->mday)-1);



This is what I am trying to accomplish here, I create a reference to an object that holds date related data like year, month, day etc.
The above code, gets yesterdays date by: ($tm->mday)-1, which basically negates 1 day from todays date. So if it is say 30th August today, the variable will hold the date component as 29th.

All looks hunky and dory here, but looking a bit more carefully we realize there is a big bug; What happens at the start of every month, also the start of every year.

Say, today is 1st January 2009.
The variable $yesterdaysDate after negation, will hold the following info, 2007-1-0, which is meaningless, what we wanted was, 2006-12-31.

So what is the solution, there are basically 2 solutions:

One the really hard one involving tons of if else loop, checking for all boundary condition, I will not discuss this solution. In my opinion everyone can figure it out.
The second solution uses a concept called epoch time. It is the time in seconds that have passed since some reference day in the year 1970.
This is how we modify the above program to make it function correctly.


use Time::localtime;
$yesterday = time() - (24 * 60 * 60 );
$tm=localtime($yesterday);
$yesterdaysDate=sprintf("%04d-%02d-%02d",$tm->year+1900, ($tm->mon)+1, ($tm->mday));



As you can see, that has been done here is that we use a function time(), from perl base lib, which return to us the number of epoch seconds that have passed till now. Once we get that, all we do to get yesterdays date is to negate (24*60*60) seconds from it and pass this as the in parameter to the localtime() function. This fixes all the issues that I put forth in the start of the post.