Check if two strings are anagrams or not

Are the two strings or phrases anagrams or not algorithm

First thing first, What is anagram?

Anagrams are phrases/words of which one can be created from the other with rearrangement of characters.

Examples of anagram strings:

Debit card and bad credit
George Bush and He Bugs Gore

Now, given two strings, how would do find if the strings are anagrams or not.

The approach I used is a follows:

1. remove the space out of the strings
2. compare the length of strings, if they don’t match, they ain’t anagrams
3. sort the characters of each string
4. check character by character and see if they match till the end

This is approach I used with o(nlogn) because of the sorting part. All the others can be done in o(n)

A java solution for anagram algorithm

No Persistence provider for EntityManager named Hibernate error

No Persistence provider for EntityManager named

If you are working on hibernate, then there are two ways to provide the configuration to it. Either you would be using hibernate.cfg.xml or persistence.xml

In both cases, hibernate would be using the information like the connection string information and classes associated with tables.

If you are using persistence.xml and you are getting No Persistence provider for EntityManager named error, then there the following would be an issue and here is how you solve those.
Continue reading No Persistence provider for EntityManager named Hibernate error

missing numbers in billion records

Finding missing numbers from billion sequential number list file

You are given a billion numbers but some are missing

This is interesting algorithm question. With my first attempt I have tried it with o(n**2) which needs improvement of course.

Do you know how to find complementary numbers in given array?

The question in detail

You are given a randomly listed billion numbers, from 1 to billion that is. And there are a couple of numbers missing from this list.

The task is to find those missing numbers from a billion list, and you are given a very limited memory resource – you can assume storage is not an issue.

How I proceed with this solution

Continue reading Finding missing numbers from billion sequential number list file

apache error

Java Tomcat error: can not access a member of class with modifiers

Class org.apache.catalina.core.DefaultInstanceManager can not access a member of class with modifiers “” sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)

If you are on tomcat/or anyother webserver for J2EE and getting this error, then the most probable servlet you have would look like this


package package;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

class MyServletClass extends HttpServlet {
...
...
...
}

The fix:

You have missed the class modifier public

public class MyServletClass

Should solve the problem

pass all the jars in classpath when compiling java

How to pass multiple jar files while using javac – compiling java classes

If you have single jar file, you can pass as: lets assume you are compiling file.java

javac path/to/file.java -classpath "path/to/jar/file.jar" -d classpath

But how about if you have multiple jar files to be included in the class path?

If you are on windows you can list the jar files separated by semi colon(;) and in unix you can pass with colon(:)

javac path/to/java/file.java -classpath "file1.jar:file2.jar:dir/*"

The last example is for unix environment but you can apply it to windows with proper path and semicolon

find and replace in vi vim

Search and replace in vim

Find and replace text strings in vim file

It is one of the most frequent task you might do while working on vim.

Here are some of the most used ones

1. Find and search a single string and replace the first occurrence only
:s/search/replace/g

The above code would search for “search” and replaces it with “replace” and it would do it only once

2. Find all occurrences of the string and replace those
:%s/search/replace/g

In this case all strings in the file with “search” would be replaced by “replace”

3. Find and ask for confirmation before changing it
:%s/search/replace/gc

It would do the usual task but this time it would ask for confirmation before it changes it.

You can do search and replace in vi or vim using the above command being on vim. Don’t forget to be out of the update mode otherwise you would just be writing the above commands.

find complementary numbers

Find K Complementary numbers from array Java implementation

Find K complementary numbers from the given array

This is another approach to the problem that I have done it here. On that post, a good deal of visitors pointed out that it is actually o(n*n) not o(n) as I claimed.

Yes, the naive usage of Hashmap for holding the numbers has soared the performance and I have changed the approach as follows.

To remind the k complementary problem and its solution, you are given array of numbers and a number k of which you are going to find numbers that give k complementary. The following is an example of it.

The problem is, given numbers like 7, 1, 5, 6, 9, 3, 11, -1 and given number 10, write a script that would print numbers that would add to 10. In the example, it would be like
7 and 3, 1 and 9, -1 and 11.

Thanks Reda and mtrad for your correction.


package algorithm;

import java.util.ArrayList;
import java.util.List;

/**
 * Algorithm to find the pairs making the K complementary in O(n) complexity
 * 
 * @author http://gullele.com
 */
public class KComplementary2 {
	
	public static void main(String[] args) {
		KComplementary2 kcomp = new KComplementary2();
		int[] numbers = new int[]{7, 1, 5, 6, 9, 3, 11, -1};
		
		for (Integer number : kcomp.getKComplementaryPairs(10, numbers)) {
			System.out.println(" Pairs are "+ number + " and " + (10-number));
		}
	}
	
	public KComplementary2() {}
	
	/**
	 * An algorithm to find the pair from the given array that would sum up the given K
	 * 
	 * @note - the algorithm would be done in o(n)+o(nlogn). First it will run through the whole 
	 * numbers and creates a temporary list of pairs in HashMap with 
	 * (value, sum-value). 
	 * @param sum
	 * @param listOfIntegers
	 * @return
	 */
	public List getKComplementaryPairs(int sum, int[] listOfIntegers) {
		
		/*
		 * The algorithm works using front and last pointers on ascendingly sorted array. The front would be 
		 * instantiated with 0 and last with length-1; if the arr[front]+arr[last] == sum, then pick
		 * the numbers and add them to the pair array.
		 * if their sum is greater than sum, it means time to check the  second higher number that is lower
		 * than the current highest number. And the reverse would hold true if the sum is less than the sum
		 * time to move to the next higher number from the lower side.
		 */
		if (listOfIntegers == null || listOfIntegers.length == 0) {
			return null;
		}
		
		//quick sort the array 
		quickSort(0, listOfIntegers.length-1, listOfIntegers);
		
		int[] sortedArray = listOfIntegers;
		
		//holder for the complementary pairs
		List pairs = new ArrayList();
		int frontPointer = 0;
		int lastPointer = sortedArray.length-1;
		
		while (frontPointer < lastPointer) {
			int currentSum = sortedArray[frontPointer] + sortedArray[lastPointer];
			if (currentSum == sum) {
				/*
				 * Since sum is found, increment front and decrement last pointer
				 * Only one number is required to be hold, the other can be found 
				 * from sum-number since complementary 
				 */
				pairs.add(sortedArray[frontPointer]);//adding is o(1)
				frontPointer++;
				lastPointer--;
			} else if (currentSum > sum) {
				lastPointer--;
			} else {
				frontPointer++;
			}
		}
		
		return pairs;
	}
	
	/**
	 * sort the numbers. I have used quick sort here. QuickSort is nlogn in average case 
	 * well, in worst case it still would be n**2 though :(
	 * @param numbers
	 * @return sorted array numbers.
	 */
	public void quickSort(int lowerIndex, int higherIndex, int[] numbers) {
		/*
		 * Recursively inarray sort. Start from arbitrary value to compare from and recursively sort its 
		 * left and right.
		 */
		int pivot = lowerIndex+(higherIndex-lowerIndex)/2;
		int lower = lowerIndex;
		int higher = higherIndex;
		
		while (lower < higher) {
			while (numbers[lower] < numbers[pivot]) {
				lower++;
			}
			while (numbers[higher] > numbers[pivot]) {
				higher--;
			}
			
			//swap those needed to be on the left on those on the right.
			if (lower <= higher) {
				int temp = numbers[lower];
				numbers[lower] = numbers[higher];
				numbers[higher] = temp;
				lower++;
				higher--;
			}
		}
		if (lowerIndex < higher) {
			quickSort(lowerIndex, higher, numbers);
		}
		
		if (lower < higherIndex) {
			quickSort(lower, higherIndex, numbers);
		}
	}
}

Love algorithms? See how you would solve the following

Can you find the three numbers that would sum to T from given array?

From a file of billion numbers, find missing numbers with limited memory

Find longest palindrom from sequence of characters

Given the string, find the longest palindrom you can form from it


/**
 * @author gullele.com
 */
public class LongestPalindrom {
	public static void main(String[] args) {
		LongestPalindrom longest = new LongestPalindrom();
		System.out.println(longest.longest("zzbmbmbdmm"));
	}
	
	public String longest(String string) {
		if (string.length() == 0 || string == null) {
			return "";
		}
		

		StringBuffer palindrom = new StringBuffer();
		Map charBag = new HashMap();
		for (Character c : string.toCharArray()) {
			int totalChar = charBag.get(c) != null ? charBag.get(c) : 0;
			if ((totalChar + 1) % 2 == 0) {
				palindrom.append(c);
				palindrom = palindrom.insert(0, c);
				charBag.remove(c);
				continue;
			}
			charBag.put(c, ++totalChar);
		}
		
		if (charBag.size() > 0) {
			Iterator it = charBag.entrySet().iterator();
			Map.Entry pair = (Map.Entry)it.next();
			String c = pair.getKey().toString();
			palindrom.insert(palindrom.length()/2, c);
		}
		return palindrom.toString();
	}
}

Allow or deny access

Allow or Restrict sudo access to Users in linux

On collaborative work, you would give access to others who would be helping you out on the code or system admin stuff.

The question would be, how limited can you go with granting access to the users?

The first thing would be adding the user to the sudoers list, lets say you have created a new user named tom and you want to grant sudo access to this user

You can edit the sudoers file with whatever editor you are using. But the most recommended way would be using visudo


sudo visudo 

Grant all the access to user

If you want to give the world access to the user, then add the following line and save the file


tom ALL=(ALL) ALL

tom is the user you want to grant permissions and the first ALL is for the host and the ALL in the bracket is referring to other accounts the user sudouser can act as and the final ALL would be for list of commands – in this case tom has every access provided.

Grant only some commands

Lets say you want to give tom an access of copy and renaming a file


tom ALL=/bin/cp,/bin/mv

The above command would tell the system the user tom has access to cp and mv only. You might need to check the correct binary to cp and mv using which command. That is which cp would tell you the right path to the binary of the cp.

Allow the user everything but installing new softwares using apt-get

Ok, so you might want to give every access to the user but you want to limit installing new softwares using apt-get


tom ALL=ALL,!/usr/bin/apt-get

Here tom can do everything but not apt-get. If you add the ! in front of the command, it means don’t allow.

So using the combinations of the above you can reach the level where you can grant and deny any command for the user of interest

Add scrollbar to mysql result in terminal

MySQL command line scrollbar

MySQL command line provides a full fledged application that allows interaction with mysql engine so easy.

In MySQL command one thing that would annoy is when there is larger result set and scrolling is static or not even accessible.

If you have larger result coming from mysql and you want to scroll through the result on mysql terminal?

You might ask

How to add scrollbar to mysql result in mysql command line?

Reading larger result set in mysql command

Or have you asked how to scroll on results of terminal mysql?

Solution

Go to your terminal and do


mysql> pager less

This would allow you to have that feeling of being on vim

See how to configure LAMP on Amazon here