How would I convert this code to Generics? - java

I am in desperate need of help here. I am to migrate this existing code to generics and I've really hit a wall. Any help would be greatly appreciated.
The existing code is an algorithm library and is accompanied by some classes with constructors for vehicles (i.e Bike.Java).
I've tried alot of different things but I just can't seem to figure it out. I'd love some insight.
public class Algo
{
/**
* Copies all objects from src to tgt, for which the predicate pred holds.
*
* #param src source list
* #param tgt target list
* #param pred unary predicate
*/
static public
void copyIf(List src, List tgt, UnaryPredicate pred)
{
for (Object obj : src)
{
if (pred.test(obj)) tgt.add(obj);
}
}
/**
* Copies all objects from src to tgt that are greater than yardstick.
*
* #param src source
* #param tgt target
* #param yardstick determines if objects in src should be copied to tgt.
*/
static public
void copyIfGreaterThan(List src, List tgt, final Comparable yardstick)
{
copyIf(src, tgt, new UnaryPredicate() {
public boolean test(Object o)
{
return yardstick.compareTo(o) < 0;
}
});
}
/**
* Finds a maximum object in lst.
*
* #param lst a list containing non-null references
* #return a maximum object in lst
*/
static public
Comparable findMax(List lst)
{
assert lst != null;
Comparable max = null;
Iterator iter = lst.iterator();
// handle first element
if (iter.hasNext())
max = (Comparable) iter.next();
// handle remaining elements
while (iter.hasNext())
{
assert max != null;
Comparable cand = (Comparable) iter.next();
if (max.compareTo(cand) < 0)
max = cand;
}
return max;
}
/**
* Adds the smaller of lhs and rhs to dst.
*
* #param lhs left hand side object
* #param rhs right hand side object
* #param dst destination list
*/
static public
void storeMin(Comparable lhs, Comparable rhs, List dst)
{
Comparable min = lhs;
if (min.compareTo(rhs) > 0) min = rhs;
dst.add(min);
}
/**
* swaps the elements at a and b in lst.
*
* #param lst a list
* #param a first location in lst
* #param b second location in lst
*/
static private
void swap(ArrayList objs, int a, int b)
{
Object tmp = objs.get(a);
objs.set(a, objs.get(b));
objs.set(b, tmp);
}
/**
* Sorts the elements in lst.
*
* #param lst an array list containing non-null references
*/
static public
void selectionSort(ArrayList lst)
{
for (int i = 0; i < lst.size(); ++i)
{
int min = i;
Comparable minobj = (Comparable) lst.get(min);
for (int j = i+1; j < lst.size(); ++j)
{
if (minobj.compareTo(lst.get(j)) > 0)
{
min = j;
minobj = (Comparable) lst.get(min);
}
}
swap(lst, min, i);
}
}
}

Since Java 8 you could do it like that:
public static <T> List<T> copyIf(List<T> src, Predicate<T> predicate){
return src.stream().filter(predicate).collect(Collectors.toList());
}
public static <T> List<T> copyIfGreaterThan(List<T> src, Comparable<T> yardstick) {
return copyIf(src, t -> (yardstick.compareTo(t) < 0));
}
For more infos about generics see:
https://docs.oracle.com/javase/tutorial/java/generics/types.html
For more infos on streams see e.g.
https://www.tutorialspoint.com/java8/java8_streams.htm

Related

Permutation Iterator in java

I want a class, that take in a possitive integer and produce a iterator that let me iterate through all possible of permutation of a list of possitive numbers under the positive integer.
eg. permulator p = paermulator(3)
p.next() -> [0,1,2]
p.next() -> [0,2,1]
p.next() -> [1,0,2]
p.next() -> [1,2,0]
...
which is 6 possible permutations in this case.
I have designed a class, but it is incredibly slow, I want to make iterate faster.
This is my design:
(I am doing it pruely for that sake that it seems possible. )
package Mathematica.complexity;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Tthis will be a class that demonstrate what we call:
* a factorial complexity algorithm
* it's going to print all the possible permutations of some sort of collection
* in java.
* <br>
* A recursive data structure that resembles the process of permutating.
* #author dashie
*
*/
public class FactorialComplexity implements Iterator<List<Integer>>
{
private List<Integer> G_Data;
// sub recursive structure of the class.
private FactorialComplexity G_next = null;
private int G_ChoosenIndex = 0;
private boolean G_canProduceNextElement= true;
public static void main(String[] args)
{
}
public FactorialComplexity(int NumbersofElements)
{
if(NumbersofElements <0)throw new AssertionError();
this.G_Data = new LinkedList<>();
for(int i =0; i< NumbersofElements;i++)this.G_Data.add(i);
this.prepareSubStructure();
}
protected FactorialComplexity(List<Integer> argIn)
{
this.G_Data = argIn;
this.prepareSubStructure();
}
/**
* Using the internal index to return the current element it is
* pointing at.
* <br></b>I doesn't increment the internal pointer. </b>
* #return
*/
public Integer getChoosenElement()
{
//if(this.G_Data.size() == 0)return null;
return this.G_Data.get(this.G_ChoosenIndex);
}
/**
* This function serves for the iterator.
* #return
*/
public List<Integer> getPermutation()
{
// two of the base case.
if(this.G_Data.size()==0)
{
return new LinkedList<>();
}
if(this.G_Data.size()==1)
{
List<Integer> temp = new LinkedList<>();
temp.add(this.G_Data.get(0));
return temp;
}
return this.getPermutation_part1(new LinkedList<Integer>());
}
private List<Integer> getPermutation_part1(List<Integer> argIn)
{
argIn.add(getChoosenElement());
argIn.addAll(this.G_next.getPermutation());
return argIn;
}
/**
* <ol>
* <li>If the sub-structure has next element, increment the sub structure.
* <li>If not, increment the index in this instance and recreate sub structure.
* <li>be careful about the base case please.
* </ol>
*
* #return
* if this, including sub structure should be incremented.
*
*/
protected boolean increment()
{
if(this.G_next!= null)
{
boolean temp = this.G_next.increment();
int pointer = this.G_ChoosenIndex;
if(this.G_ChoosenIndex+1<this.G_Data.size())
{
if(temp)
{
this.G_ChoosenIndex++;
this.prepareSubStructure();
}
return false;
}
else
{
return (this.G_ChoosenIndex+1 == this.G_Data.size())&&temp;
}
}
else
{
//empty means not choice can make.
return true;
}
}
#Override
/**
* All the nodes are at its last index.
*/
public boolean hasNext()
{
if(!this.G_canProduceNextElement)return false;
if(this.isAllPointingAtLastIndex())this.G_canProduceNextElement=false;
return true;
}
/**
* This index in this class instance and
* all its sub structure are pointing at the last index?
* #return
*/
boolean isAllPointingAtLastIndex()
{
if(this.G_Data.size()<=1)
{
return true;
}
return this.G_ChoosenIndex+1
==
this.G_Data.size()&&this.G_next.isAllPointingAtLastIndex();
}
#Override
public List<Integer> next()
{
List<Integer> result = this.getPermutation();
this.increment();
return result;
}
public String toString()
{
String s = new String();
s+= this.G_Data+":"+this.G_ChoosenIndex+"->";
if(this.G_next!= null)s+= this.G_next.toString();
return s;
}
/**
* <ol>
* <li>Base case: the list in this instant is empty.
* <li>Make a copy of the local collection, excluding the
* element the pointer is pointing to
* <li>Make connect the this object to its sub structure and recurse.
* </ol>
*/
protected void prepareSubStructure()
{
if(this.G_Data.size() == 0)return;
List<Integer> temp = new LinkedList<>();
temp.addAll(this.G_Data);
temp.remove(this.G_ChoosenIndex);
this.G_next = new FactorialComplexity(temp);
this.G_next.prepareSubStructure();
}
public static int factorial(int n)
{
if(n<0)return 0;
if(n<=1)return 1;
return n*factorial(n-1);
}
}
To summarize:
The class is recursive like a linked list, each node contains the an index that indicate the element it is pointing at and a list of all the element got passed from the previouse node.
How Naive is this approach? How can I make it faster?
This is a better solution, inspired by https://stackoverflow.com/a/10117424/312172
To achieve, instead of getting a list of elements that are jumbled, we focus on the choices we make when deducting elements from the list.
give the function a size, and a number that is smaller than factorial(size); it will return a sequence of choices we need to make to get the permutation.
for example:
getTheIndexOfSelection(100,5)-> for a list of 5 elements, we want the 100th permutation.
it should output: [4, 0, 2, 0, 0]
it means, remove the element at index 4, for the list that got removed, remove element at 0 ....
if the list is[1,2,3,4,5]; this will be the procujure:
[1,2,3,4,5] remove index 4 -> 5
[1,2,3,4] remove index 0 -> 1
[2,3,4] remove index 2 -> 4
[2,3] rovmove index 0 -> 2
[3] remove index 0 -> 3
all the element we removed sequentially is the permutation.
/**
* Feed this function a number, it gives you a sequence of choices
* to make a permutation.
* <br>
* if this return [0,0,0,0]
* it means remove element at 0, and then remove again... until
* reaches the end.
* #return
*
* #param
* len: the length of the list
* n: the number that got match to a certain permutation.
*/
public static int[] getTheIndexOfSelection(int n, int size)
{
int[] lst = new int[size];
return getTheIndexOfSelection( n, size, 0, lst);
}
private static int[] getTheIndexOfSelection(int n, int size, int index, int[] lst)
{
if(size==1)
{
int[] result = {0}; // a list of one element, you can only choose the one that is in it
// which is at index 0;
return result;
}
if(n >= factorial(size))return null; // This is not possible to do.
size-=1;
int firstchoice = n/factorial(size);
lst[index] = firstchoice;
n = n-firstchoice*factorial(size);
if(size>1)return getTheIndexOfSelection(n ,size, index+1, lst);
return lst;
}
This is a better solution because:
The speed really depends on the factorial function, assume factorial is super fast, this will be o(n).
It matches numbers to permutation, making the expandable for things like map and iterator.
It is not the full solution, the part that is left to solve do is pretty much trivial by now.
An implementation using Heap's Algorithm. It compute next permutations on the fly. And have only one array copying
import java.util.Arrays;
import java.util.Iterator;
class Permutator<E> implements Iterator<E[]>{
E[] arr1 = null;
E[] arr2 = null;
int size;
int[] stack = null;
int index = 0;
public Permutator( E[] arr ){
if( arr.length > 0 ){
arr1 = arr;
size = arr1.length;
arr2 = Arrays.copyOf(arr1, size);
stack = new int[size];
Arrays.fill(stack, 0);
}
}
#Override
public boolean hasNext() {
return (null != arr1 && arr1.length > 0);
}
#Override
public E[] next() {
// start computing.
// We will return original array as value of last permutation.
// This is to make "hasNext() " implementation easy.
updateValue();
return arr2;
}
protected void updateValue(){
boolean bret = false;
for( ; index < size ; ){
if( stack[index] < index ){
if( index %2 == 0 ){
swap(0, index);
}else{
swap(stack[index], index);
}
stack[index]++;
index = 0;
bret = true;
break;
}else{
stack[index] = 0;
index++;
}
}
if( !bret ){
// No more permutation available.
// Set the original array as return value.
// Also set arr1 = null , so that hasNext() will return false for next test
arr2 = arr1;
arr1 = null;
}
}
private void swap (final int i, final int j) {
E temp = arr2[i];
arr2[i] = arr2 [j];
arr2[j] = temp;
}
}
Usage:
public static void main(String[] args) {
Permutator<Integer> perm = new Permutator<Integer>(new Integer[]{1,2,3, 4, 5});
int count = 0;
while(perm.hasNext()){
System.out.println(Arrays.toString(perm.next()));
count++;
}
System.out.println("total: " + count);
}

Algorithm on an ordered collection of strings

I have an assessment to do and I'm not good at programming. I can search for the algorithms and see how they are done, but in my case I have ordered collection of strings and somehow I have to use the get method.
I have these two classes that must not be changed:
public class SearchTest {
/**
* Test program for the Search class.
* Put whatever tests you like in the body of the method.
* #param args the command line arguments
* #throws java.io.IOException of error reading the input
*/
public static void main(String[] args) throws IOException {
// Don't change this line
final Search search = new Search();
// You can set this to any of the text files in the data folder
final FileStrings strings = new FileStrings("data/small.txt");
// add your tests here
System.out.println(search.longestWord(strings));
}
}
and
public class FileStrings implements StringList {
/** Underlying list of elements */
private final ArrayList<String> elements;
/** Number of calls to get() since the last call to resetCount() */
private int count;
/**
* Create a list containing the lines of a text file.
* #param fileName name of a text file of strings, in order
* #throws java.io.IOException on input error
*/
public FileStrings(String fileName) throws IOException {
elements = new ArrayList<>();
try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = input.readLine()) != null) {
elements.add(line);
}
}
count = 0;
}
/**
* Returns the number of elements in this list.
* This method takes constant time.
* #return the number of elements in this list
*/
#Override
public int size() {
return elements.size();
}
/**
* Returns the element at the specified position in this list.
* This method takes constant time.
* #param i position in the list, between 0 and size()-1
* #return the element at the position i
*/
#Override
public String get(int i) {
count++;
return elements.get(i);
}
/**
* Reset the count field.
*/
public void resetCount() {
count = 0;
}
/**
* Getter for count.
* #return number of calls to get() since the last resetCount()
*/
public int getCount() {
return count;
}
}
And my first task is to find the longest word from the given file list.
This is my attempt(I know it's wrong, but can't follow examples, because the solutions I see use the array directly):
public class Search {
/**
* Returns the index of the longest string in the list.
* If there are several string of this length, the
* indexed returned is the that of the first.
* #param a list of strings, in ascending order
* #return position of an entry with the longest string in the list
*/
public int longestWord(StringList a) {
int i=0;
int longestWord=0;
String nextWord=a.get(i+1);
String previousWord=a.get(i);
while (i < a.size() ) {
if (nextWord.length()>previousWord.length()){
longestWord = i;
}
i = i + 1;
}
return longestWord;
}
The result should be "14", the world "because" is the 15th word and is the longest. I hope you can help me with this!
list of words
public class Search {
/**
* Returns the index of the longest string in the list.
* If there are several string of this length, the
* indexed returned is the that of the first.
* #param a list of strings, in ascending order
* #return position of an entry with the longest string in the list
*/
public int longestWord(StringList a) {
int length=a.get(0).length();
int i=0;
int longestWord=0;
while (i<a.size()){
if (a.get(i).length()>length){
length=a.get(i).length();
longestWord=i;
}
i = i + 1;
}
return longestWord;
}
managed to do it :P

Determine phone number prefix with Trie in Java

I am trying to create a fast search function to determine the prefix of a phone number.
I am loading prefix data from database into memory as TreeMap, where key is prefix and value is an object containing information about this prefix(country etc).
This is how TreeMap is populated:
private static TreeMap<String, PrefixData> prefixMap = new TreeMap<>();
//EXAMPLE of DB query
try {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection(dbURL, dbUser, dbPass);
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM countries_prefixes");
//Looping resultset
while (rs.next()) {
//TODO Review fields that must be stored in memory
String country = rs.getString("name");
//Populating map with data object (keeping nr prefix as key and object as value)
prefixMap.put(rs.getString("country_prefix"), new PrefixData(country));
}
rs.close();
stmt.close();
connection.close();
} catch (ClassNotFoundException | SQLException e) {
System.out.println(e.toString());
}
Lets say I have phone numbers I want to check:
37251845632;
35844021546;
34651478966
etc ...
Some prefixes are 1 digit long, some 2 digits long, some 3 digits long and so on...
So I created a loop, that works:
//TODO Try some other search methods (Tries)
//array for prefix length priority
int[] sequence = {3, 4, 2, 1, 5, 6};
//Performing search from the map
for (int i = 0; i < sequence.length; i++) {
//Extracting prefix from phone nr
String prefix = phoneNr.substring(1, sequence[i] + 1);
if (prefixMap.containsKey(prefix)) {
PrefixData pdata = prefixMap.get(prefix);
System.out.println(String.format("Found matching key [%s] in TreeMap", prefix));
System.out.println(String.format("[NAME: %s] [REGEX: %s] ", pdata.getCountryName(), pdata.getNrRegex()));
//Validate number format with regex
if (pdata.getNrRegex().trim() != null && !pdata.getNrRegex().trim().isEmpty()) {
System.out.println("Regex for number validation is present!");
if (phoneNr.matches(pdata.getNrRegex().replaceAll("^/|/$", ""))) {
System.out.println("NUMBER IS VALID!");
} else {
System.out.println("INVALID NUMBER!");
}
}
return pdata;
}
}
return null;
}
Now the loop works well, but it is slow. I've heard something about Tries, which is faster, but I don't understand how to implement this in my scenario.
Any help is appreciated!
As I said, the loop works, but this is not a nice way to achieve my goal.
So I did a little bit of research and came up with solution that is using prefix tree (Trie) implementation.
Little reading what Trie is can be found here.
And now the Trie implementation part. I knew that it would be faster to find a code that is already written and tested, so I found Google implementation here. And Vladimir Kroz's implementation here.
Made some minor modifications and this is the solution. I will provide both solutions:
Prefixmap interface
package tiesImpl;
/**
* Maps string prefixes to values. For example, if you {#code put("foo", 1)},
* {#code get("foobar")} returns {#code 1}. Prohibits null values.
*
* <p>Use instead of iterating over a series of string prefixes calling
* {#code String.startsWith(prefix)}.
*
* #author crazybob#google.com (Bob Lee)
* #param <T>
*/
public interface PrefixMap<T> {
/**
* Maps prefix to value.
*
* #param prefix
* #param value
* #return The previous value stored for this prefix, or null if none.
* #throws IllegalArgumentException if prefix is an empty string.
*/
T put(CharSequence prefix, T value);
/**
* Finds a prefix that matches {#code s} and returns the mapped value.
*
* If multiple prefixes in the map match {#code s}, the longest match wins.
*
* #param s
* #return value for prefix matching {#code s} or {#code null} if none match.
*/
T get(CharSequence s);
}
PrefixTrie class
package tiesImpl;
/*
* Copyright (C) 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Trie implementation supporting CharSequences as prefixes.
*
* Prefixes are sequences of characters, and the set of allowed characters is
* specified as a range of sequential characters. By default, any seven-bit
* character may appear in a prefix, and so the trie is a 128-ary tree.
*
* #author crazybob#google.com (Bob Lee)
* #author mharris#google.com (Matthew Harris)
* #param <T>
*/
public class PrefixTrie<T> implements PrefixMap<T> {
// The set of allowed characters in prefixes is given by a range of
// consecutive characters. rangeOffset denotes the beginning of the range,
// and rangeSize gives the number of characters in the range, which is used as
// the number of children of each node.
private final char rangeOffset;
private final int rangeSize;
private final Node<T> root;
/**
* Constructs a trie for holding strings of seven-bit characters.
*/
public PrefixTrie() {
rangeOffset = '\0';
rangeSize = 128;
root = new Node<>(rangeSize);
}
/**
* Constructs a trie for holding strings of characters.
*
* The set of characters allowed in prefixes is given by the range
* [rangeOffset, lastCharInRange], inclusive.
*
* #param firstCharInRange
* #param lastCharInRange
*/
public PrefixTrie(char firstCharInRange, char lastCharInRange) {
this.rangeOffset = firstCharInRange;
this.rangeSize = lastCharInRange - firstCharInRange + 1;
if (rangeSize <= 0) {
throw new IllegalArgumentException("Char range must include some chars");
}
root = new Node<>(rangeSize);
}
/**
* {#inheritDoc}
*
* #param prefix
* #param value
* #throws IllegalArgumentException if prefix contains a character outside
* the range of legal prefix characters.
*/
#Override
public T put(CharSequence prefix, T value) {
if (value == null) {
throw new NullPointerException();
}
Node<T> current = root;
for (int i = 0; i < prefix.length(); i++) {
int nodeIndex = prefix.charAt(i) - rangeOffset;
try {
Node<T> next = current.next[nodeIndex];
if (next == null) {
next = current.next[nodeIndex] = new Node<>(rangeSize);
}
current = next;
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException(
"'" + prefix.charAt(i) + "' is not a legal prefix character.");
}
}
T oldValue = current.value;
current.value = value;
return oldValue;
}
/**
* {#inheritDoc}
* #param s
*/
#Override
public T get(CharSequence s) {
Node<T> deepestWithValue = root;
Node<T> current = root;
for (int i = 0; i < s.length(); i++) {
int nodeIndex = s.charAt(i) - rangeOffset;
if (nodeIndex < 0 || rangeSize <= nodeIndex) {
return null;
}
current = current.next[nodeIndex];
if (current == null) {
break;
}
if (current.value != null) {
deepestWithValue = current;
}
}
return deepestWithValue.value;
}
/**
* Returns a Map containing the same data as this structure.
*
* This implementation constructs and populates an entirely new map rather
* than providing a map view on the trie, so this is mostly useful for
* debugging.
*
* #return A Map mapping each prefix to its corresponding value.
*/
public Map<String, T> toMap() {
Map<String, T> map = newLinkedHashMap();
addEntries(root, new StringBuilder(), map);
return map;
}
/**
* Adds to the given map all entries at or below the given node.
*
* #param node
* #param builder A StringBuilder containing the prefix for the given node.
* #param map
*/
private void addEntries(Node<T> node,
StringBuilder builder,
Map<String, T> map) {
if (node.value != null) {
map.put(builder.toString(), node.value);
}
for (int i = 0; i < node.next.length; i++) {
Node<T> next = node.next[i];
if (next != null) {
builder.append((char) (i + rangeOffset));
addEntries(next, builder, map);
builder.deleteCharAt(builder.length() - 1);
}
}
}
private static class Node<T> {
T value;
final Node<T>[] next;
#SuppressWarnings("unchecked")
Node(int numChildren) {
next = new Node[numChildren];
}
}
/**
* Creates a {#code LinkedHashMap} instance.
*
* #param <K>
* #param <V>
* #return a newly-created, initially-empty {#code LinkedHashMap}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<>();
}
}
Vladimir Kroz implementation: Trie class
package tiesImpl;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Prefix table based on Trie structure. Allows to perform incremental lookup
* and match based on search key prefixes (classic example - determine phone
* area code for given phone number)
*
* #param <V> a type of value object to be stored along with prefix (e.g when
* key is a country name, the value could be a name of the country)
*
* #author Vladimir Kroz
* https://vkroz.wordpress.com/2012/03/23/prefix-table-trie-implementation-in-java/
*/
public class Trie<V> {
Entry<V> entry;
char key;
Map<Character, Trie<V>> children;
public Trie() {
this.children = new HashMap<>(10);
entry = new Entry<>();
}
/**
* non-public, used by _put()
*/
Trie(char key) {
this.children = new HashMap<>(10);
this.key = key;
entry = new Entry<>();
}
public void put(String key, V value) {
_put(new StringBuffer(key), new StringBuffer(""), value);
}
void _put(StringBuffer remainder, StringBuffer prefix, V value) {
if (remainder.length() > 0) {
char keyElement = remainder.charAt(0);
Trie<V> t = null;
try {
t = children.get(keyElement);
} catch (IndexOutOfBoundsException e) {
}
if (t == null) {
t = new Trie<>(keyElement);
children.put(keyElement, t);
}
prefix.append(remainder.charAt(0));
t._put(remainder.deleteCharAt(0), prefix, value);
} else {
this.entry.value = value;
this.entry.prefix = prefix.toString();
}
}
/**
* Retrieves element from prefix table matching as a prefix to provided
* key. E.g. if key is "37251656565" and prefix table has node "372" then
* this call will return the value of "372"
*
* #param key a string which starts with prefix to be searched in the table
* (e.g. phone number)
* #return an Object associated with matching prefix (i.e if key is a phone
* number it may return a corresponding country name)
*/
public V get(String key) {
return _get(new StringBuffer(key), 0);
}
/**
* Returns true if key has matching prefix in the table
*
* #param key
* #return
*/
public boolean hasPrefix(String key) {
return this.get(key) != null;
}
V _get(StringBuffer key, int level) {
if (key.length() > 0) {
Trie<V> t = children.get(key.charAt(0));
if (t != null) {
//FYI: modified code to return deepest with value instead of returning null if prefix doesn't have corresponding value.
V result = t._get(key.deleteCharAt(0), ++level);
return result == null ? entry.value : result;
} else {
return (level > 0) ? entry.value : null;
}
} else {
return entry.value;
}
}
#Override
//For debugging
public String toString() {
Iterator<Character> it = children.keySet().iterator();
StringBuffer childs = new StringBuffer();
while (it.hasNext()) {
Character _key = it.next();
childs.append(String.format("\n%s\n",
//Adding a tab to the beginning of every line to create a visual tree
String.format("%s: %s", _key, children.get(_key)).replaceAll("(?m)(^)", "\t")));
}
return String.format("Trie [entry=%s, children=%s]", entry, childs);
}
static public class Entry<V> {
String prefix;
V value;
public Entry() {
}
public Entry(String p, V v) {
prefix = p;
value = v;
}
public String prefix() {
return prefix;
}
public V value() {
return value;
}
#Override
public String toString() {
return "Entry [prefix=" + prefix + ", value=" + value + "]";
}
}
}
And finally the Testing part
package tiesImpl;
/**
* Class for testing different implementations of prefix tree (Trie).
*
* #author lkallas
*/
public class TriesTest {
private static final PrefixTrie<String> googleTrie = new PrefixTrie<>();
private static final Trie<String> krozTrie = new Trie<>();
public static void main(String[] args) {
//Inserting prefixes to Google implementation of Trie
googleTrie.put("7", "Russia");
googleTrie.put("77", "Abkhazia");
googleTrie.put("746", "Some unknown country");
//Inserting prefixes to Vladimir Kroz implementation of Trie
krozTrie.put("7", "Russia");
krozTrie.put("77", "Abkhazia");
krozTrie.put("746", "Some unknown country");
System.out.println("Google version of get: " + googleTrie.get("745878787"));
System.out.println("Vladimir Kroz version of get: " + krozTrie.get("745878787"));
}
}
Hope that this answer is somewhat helpful to others also!
Cheers!

LinkedList : Collections.max() throwing NoSuchElementException

I am not iterating the LinkedList by any means like scanner or other methods, I am using Collections.max() to get maximum number from the LinkedList.
I have read on Stack Overflow that this exception is thrown due to iterator or scanner or tokenizer, but I am using none of them.
import java.io.*;
import java.util.*;
class TLG {
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LinkedList<Integer> first = new LinkedList<Integer>();
LinkedList<Integer> second = new LinkedList<Integer>();
int cases = Integer.parseInt(br.readLine());
for(int i=1;i<=cases;i++) {
String score = br.readLine();
int number1 = Integer.parseInt(score.split(" ")[0]);
int number2 = Integer.parseInt(score.split(" ")[1]);
int diff = number1 - number2;
if(diff > 0){
first.add(diff);
}
else {
second.add(java.lang.Math.abs(diff));
}
}
Integer max1 = Collections.max(first); // Getting Exception here
Integer max2 = Collections.max(second); // Getting Exception here
if(max1 > max2) {
System.out.println(1+" "+max1);
}
else {
System.out.println(2+" "+max2);
}
}
}
/**
* Returns the maximum element of the given collection, according to the
* <i>natural ordering</i> of its elements. All elements in the
* collection must implement the <tt>Comparable</tt> interface.
* Furthermore, all elements in the collection must be <i>mutually
* comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a
* <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
* <tt>e2</tt> in the collection).<p>
*
* This method iterates over the entire collection, hence it requires
* time proportional to the size of the collection.
*
* #param coll the collection whose maximum element is to be determined.
* #return the maximum element of the given collection, according
* to the <i>natural ordering</i> of its elements.
* #throws ClassCastException if the collection contains elements that are
* not <i>mutually comparable</i> (for example, strings and
* integers).
* #throws NoSuchElementException if the collection is empty. <---------------
* #see Comparable
*/
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
you are calling Collections.max() with empty list.
You are not checking against Empty case: So Collections.max() will throw NoSuchElementException
First check if any of the Lists is Empty (then you know the max and which list is providing it)
Integer max;
int list;
if (first.isEmpty()) {
max = Collections.max(second);
list = 2;
} else if (second.isEmpty()) {
max = Collections.max(first);
list = 1;
} else {
Integer max1 = Collections.max(first);
Integer max2 = Collections.max(second);
if (max1 > max2) {
max = max1;
list = 1;
} else {
max = max2;
list = 2;
}
}
System.out.println(list + " " + max);

Java implement priority queue using binary heap errors

I have a homework problem as follows:
Created HeapPriorityQueue that will implement Priority queue
import java.util.Arrays;
public class HeapPriorityQueue<K,V extends Comparable<K>> implements PriorityQueue<K, V> {
private static final int DEFAULT_CAPACITY = 10;
protected K[] array;
protected int size;
/**
* Constructs a new BinaryHeap.
*/
#SuppressWarnings("unchecked")
public HeapPriorityQueue() {
// Java doesn't allow construction of arrays of placeholder data types
array = (K[])new Comparable[DEFAULT_CAPACITY];
size = 0;
}
/**
* Adds a value to the min-heap.
*/
public void add(K value) {
// grow array if needed
if (size >= array.length - 1) {
array = this.resize();
}
// place element into heap at bottom
size++;
int index = size;
array[index] = value;
bubbleUp();
}
/**
* Returns true if the heap has no elements; false otherwise.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns (but does not remove) the minimum element in the heap.
*/
public K peek() {
if (this.isEmpty()) {
throw new InvalidKeyException("Invalid Key");
}
return array[1];
}
/**
* Removes and returns the minimum element in the heap.
*/
public K remove() {
// what do want return?
K result = peek();
// get rid of the last leaf/decrement
array[1] = array[size];
array[size] = null;
size--;
bubbleDown();
return result;
}
/**
* Returns a String representation of BinaryHeap with values stored with
* heap structure and order properties.
*/
public String toString() {
return Arrays.toString(array);
}
/**
* Performs the "bubble down" operation to place the element that is at the
* root of the heap in its correct place so that the heap maintains the
* min-heap order property.
*/
protected void bubbleDown() {
int index = 1;
// bubble down
while (hasLeftChild(index)) {
// which of my children is smaller?
int smallerChild = leftIndex(index);
// bubble with the smaller child, if I have a smaller child
if (hasRightChild(index)
&& array[leftIndex(index)].compareTo(array[rightIndex(index)]) > 0) {
smallerChild = rightIndex(index);
}
if (array[index].compareTo(array[smallerChild]) > 0) {
swap(index, smallerChild);
} else {
// otherwise, get outta here!
break;
}
// make sure to update loop counter/index of where last el is put
index = smallerChild;
}
}
/**
* Performs the "bubble up" operation to place a newly inserted element
* (i.e. the element that is at the size index) in its correct place so
* that the heap maintains the min-heap order property.
*/
protected void bubbleUp() {
int index = this.size;
while (hasParent(index)
&& (parent(index).compareTo(array[index]) > 0)) {
// parent/child are out of order; swap them
swap(index, parentIndex(index));
index = parentIndex(index);
}
}
protected boolean hasParent(int i) {
return i > 1;
}
protected int leftIndex(int i) {
return i * 2;
}
protected int rightIndex(int i) {
return i * 2 + 1;
}
protected boolean hasLeftChild(int i) {
return leftIndex(i) <= size;
}
protected boolean hasRightChild(int i) {
return rightIndex(i) <= size;
}
protected K parent(int i) {
return array[parentIndex(i)];
}
protected int parentIndex(int i) {
return i / 2;
}
protected K[] resize() {
return Arrays.copyOf(array, array.length * 2);
}
protected void swap(int index1, int index2) {
K tmp = array[index1];
array[index1] = array[index2];
array[index2] = tmp;
}
#Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Entry<K, V> max() throws EmptyPriorityQueueException {
// TODO Auto-generated method stub
return null;
}
#Override
public Entry<K, V> insert(K key, V value) throws InvalidKeyException {
// TODO Auto-generated method stub
return null;
}
#Override
public Entry<K, V> extractMax() throws EmptyPriorityQueueException {
// TODO Auto-generated method stub
return null;
}
}
this should implement this PriorityQueue
/**
* Interface for the priority queue ADT
*
* K is the key of the entry stored in the priority queue and denotes the priority of the entry.
*
* V is the auxillary data of the entry
* #author bryann
*
*/
public interface PriorityQueue<K extends Comparable<K>,V> {
/**
* Returns the number of items in the priority queue
*
* #return number of items in the priority queue
*/
public int size();
/**
* Returns whether the priority queue is empty.
*
* #return true if the priority queue is empty. Otherwise, false.
*/
public boolean isEmpty();
/**
* Returns but does not remove an entry with maximum priority key
*
* #return entry that has the highest priority key
* #throws EmptyPriorityQueueException
*/
public Entry<K,V> max() throws EmptyPriorityQueueException;
/**
* Inserts a key-value pair and returns the entry created.
*
* #param key priority key of the entry to be inserted
* #param value value of the entry to be inserted
* #return entry that was inserted into the priority queue
* #throws InvalidKeyException
*/
public Entry<K,V> insert(K key, V value) throws InvalidKeyException;
/**
* Removes and returns an entry with maximum priority key
*
* #return entry that has the highest priority key
* #throws EmptyPriorityQueueException
*/
public Entry<K,V> extractMax() throws EmptyPriorityQueueException;
}
while the Driver class is this
public class HeapPriorityQueueDriver {
public static void main(String[] args) {
PriorityQueue<Integer, String> queue = new HeapPriorityQueue<Integer, String>();
queue.insert(0, "Zero");
queue.insert(10, "Ten");
queue.insert(1, "One");
queue.insert(5, "Five");
queue.insert(3, "Three");
queue.insert(7, "Seven");
queue.insert(9, "Nine");
while(!queue.isEmpty()) {
System.out.println(queue.extractMax());
} // end while
} // end main
}
the problems I get are
Bound mismatch: The type String is not a valid substitute for the bounded parameter <V extends Comparable<K>> of the type HeapPriorityQueue<K,V> HeapPriorityQueueDriver.java /MP7/src/simon/mp7 line 6
Java Problem
Bound mismatch: The type K is not a valid substitute for the bounded parameter <K extends Comparable<K>> of the type Entry<K,V> HeapPriorityQueue.java /MP7/src/simon/mp7 line 199
Java Problem
Bound mismatch: The type K is not a valid substitute for the bounded parameter <K extends Comparable<K>> of the type Entry<K,V> HeapPriorityQueue.java /MP7/src/simon/mp7 line 193
Java Problem
Bound mismatch: The type K is not a valid substitute for the bounded parameter <K extends Comparable<K>> of the type Entry<K,V> HeapPriorityQueue.java /MP7/src/simon/mp7 line 187
Java Problem
The method compareTo(K) is undefined for the type K HeapPriorityQueue.java /MP7/src/simon/mp7 line 126
Java Problem
The method compareTo(K) is undefined for the type K HeapPriorityQueue.java /MP7/src/simon/mp7 line 104
Java Problem
The method compareTo(K) is undefined for the type K HeapPriorityQueue.java /MP7/src/simon/mp7 line 100
Java Problem
Bound mismatch: The type K is not a valid substitute for the bounded parameter <K extends Comparable<K>> of the type PriorityQueue<K,V> HeapPriorityQueue.java /MP7/src/simon/mp7 line 5
the message in the console is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Bound mismatch: The type String is not a valid substitute for the bounded parameter <V extends Comparable<K>> of the type HeapPriorityQueue<K,V>
at simon.mp7.HeapPriorityQueueDriver.main(HeapPriorityQueueDriver.java:6)
You declare HeapPriorityQueue<K,V extends Comparable<K>>, but you try to use it as:
PriorityQueue<Integer, String> queue = new HeapPriorityQueue<Integer, String>();
But String doesn't extends Comparable<Integer> so it gives you compilation error.

Categories