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

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 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();
	}
}

Maven error Annotations are not supported in -source 1.3

The Error

Are you using annotations in your project?

If so, you will get this error if you try to do mvn compile or mvn install.

You may have also seen this if you are building your project on eclipse as well.

The solution

The default maven relies on JDK 1.3 for its building the project and you might be using a JDK above 1.3. Also, JDK 1.3 does not implement annotations.

The solution is to tell the maven the current non-1.3 JDK you are using on you pom.xml file.


<project>
.
.

  <build> 
    <plugins> 
      <plugin> 
        <artifactId>maven-compiler-plugin</artifactId> 
        <version>2.3.2</version> 
        <configuration> 
          <source>1.8</source> 
          <target>1.8</target> 
        </configuration> 
      </plugin> 
     </plugins> 
   </build> 
</project>

For the source and target you will provide your current JDK you are using.

Running maven project in eclipse step by step

If you have java web project that is maven based, and you want to run the project in eclipse here are the steps.

Mind you this is for the project which is already a maven project, say you did it through terminal or you got it from other repository and you want to run it locally through eclipse.

Assumed -> you have setup the webserver like tomcat on eclipse.

1. Go to Eclipse Run->Run Configuration

2. Double click on M2 Maven Build

3. On the base directory: insert ${project_loc}

4. On the goals: insert tomcat:run and the select and apply

5. Right click on the project and select configure->Convert to Maven Project

configure build path

configure build path

6. Again right click on the project and select Maven->Update Project

update-project

7. For further pulling the dependencies from maven to eclipse, right click on it->properties->Deployment Assembly

8 Click on Add button and select Java build path entries and select Maven Dependencies

9. Now, your dependencies should be pulled all is ready for testing. Go to project menu and click on build project. This will be inactive if Build Automatically is selected.

10. Then to test, right click on one of your servlet and select run as and click on the server option. If all went good, you should be able to see the output from your servlet on the browser.

The above simple steps would allow you to convert the Java web project into maven project in eclipse.

See: How to change directory structure for maven

See: Resolving classpath problem in eclipse

Importing packages to eclipse added by maven to java web project

If eclipse is having a hard time acknowledging the packages you got through maven, here are the step by step fix for it..

1. Go to your projects root, where the pom.xml resides

2. issue mvn eclipse:clean

3. issue mvn eclipse:eclipse

4. this could be optional, on eclipse go to the project, right click on it and select build project

resources can not be added

eclipse j2ee error There are No resources that can be added or removed from the server

Eclipse showing There are No resources that can be added or removed from the server when adding project

If you are trying to test the java web application (j2ee) on your local machine with built in eclipse support and getting error, then it is related to project facet.

Here is how you can solve the error There are No resources that can be added or removed from the server coming from eclipse

1. right click on your web project in eclispe

2. Select properties
properties

3. Select Project facets
project-facets

4. Select Dynamic Web Module
select-dynamic-web-module

5. Click on apply and then click on OK

This will solve the problem.

See also: How to resolve class pass error when working with maven

testing k complementary pairs algorithm with junit

This is the test class for the java solution of the k-complementary problem listed here


package algorithm;

import static org.junit.Assert.assertArrayEquals;

import org.junit.Before;
import org.junit.Test;

/**
 * Testing KComplementary algorithm
 * 
 * @author Kaleb Woldearegay
 *
 */
public class KComplementaryTest {
	
	private KComplementary kComplementary;
	
	@Before
	public void initiate() {
		this.kComplementary = new KComplementary();
	}
	
	
	@Test
	public void test1() {
		Integer[][] expectedResult = new Integer[][]{{1,9},{5,5},{9,1}};
		int[] test = new int[]{1,5,9};
		
		assertArrayEquals(this.kComplementary.getKComplementaryPairs(10,  test), expectedResult);
	}
	
	@Test
	public void test2() {
		Integer[][] expectedResult = new Integer[][]{{5,7},{7,5}};
		int[] test = new int[]{3,5,7};
		
		assertArrayEquals(this.kComplementary.getKComplementaryPairs(12,  test), expectedResult);
	}
	
	@Test
	public void test3() {
		Integer[][] expectedResult = new Integer[][]{{-1,1},{0,0},{1,-1}};
		int[] test = new int[]{5,-1,0,-2,3, 1};
		
		assertArrayEquals(this.kComplementary.getKComplementaryPairs(0,  test), expectedResult);
	}

}

See more algorithm solutions by clicking Here