What would be the best and most efficient way to sort a Java Vector in JAVAME.
My object has five properties, and I would like to sort by a property called price which is of type double. In my Vector I will have a maximum of 150 items. A sample code would be appreciated.
Thanx for your time.
Use Collections.sort(List<T> vector, Comparator<T> c) method. If there is no such method in Java ME, just copy it from Java SE. It uses merge sort algorithm, so it will not be much to copy.
import java.lang.reflect.Field;
import java.util.*;
public class Sorter {
public static List sort(List list, String fieldName, boolean asc) {
Comparator c = new FieldComparator(fieldName, asc);
Collections.sort(list, c);
return list;
}
public static int compareNumbers(Number n1, Number n2) {
double d1 = n1.doubleValue();
double d2 = n2.doubleValue();
if (d1 < d2) {
return -1;
}
if (d2 < d1) {
return 1;
}
return 0;
}
public static int compareDates(Date d1, Date d2) {
long l1 = d1.getTime();
long l2 = d2.getTime();
if (l1 < l2) {
return -1;
}
if (l2 < l1) {
return 1;
}
return 0;
}
public static int compareStrings(String s1, String s2) {
return s1.compareTo(s2);
}
public static Object getFieldValue(Object obj, String fn) {
try {
Class clazz = obj.getClass();
Field f = null;
try {
f = clazz.getDeclaredField(fn);
} catch (Exception e) {}
while (f == null && clazz.getSuperclass() != null) {
clazz = clazz.getSuperclass();
try {
f = clazz.getDeclaredField(fn);
} catch (Exception e) {}
}//while
if (f != null) {
f.setAccessible(true);
return f.get(obj);
}
} catch (IllegalAccessException e) {}
return null;
}
protected static class FieldComparator implements Comparator {
String fieldName;
int asc;
protected FieldComparator(String fieldName, boolean asc) {
this.fieldName = fieldName;
this.asc = asc ? 1 : -1;
}
public int compare(Object o1, Object o2) {
if (o1 == null) {
if (o2 == null) {
return 0;
} else {
return -1 * asc;
}
}
if (o2 == null) {
return asc;
}
//compare fields
Object fieldValue1 = getFieldValue(o1, fieldName);
Object fieldValue2 = getFieldValue(o2, fieldName);
if (fieldValue1 == null) {
if (fieldValue2 == null) {
return 0;
} else {
return -1 * asc;
}
}
if (fieldValue2 == null) {
return asc;
}
//both field values aren't nulls
if (fieldValue1 instanceof Number && fieldValue2 instanceof Number) {
return compareNumbers((Number) fieldValue1, (Number) fieldValue2) * asc;
} else if (fieldValue1 instanceof Date && fieldValue2 instanceof Date) {
return compareDates((Date) fieldValue1, (Date) fieldValue2) * asc;
} else {
return compareStrings(fieldValue1.toString(), fieldValue2.toString()) * asc;
}
}
}
public static void main(String[] args) {
ArrayList source = new ArrayList();
source.add(new TestNumber(5));
source.add(new TestNumber(1));
source.add(new TestNumber(4));
source.add(new TestNumber(2));
source.add(new TestNumber(3));
List dest = sort(source, "value", true);
out(dest);
source = new ArrayList();
source.add(new TestString("cc"));
source.add(new TestString("dd"));
source.add(new TestString("bb"));
source.add(new TestString("ee"));
source.add(new TestString("aa"));
dest = sort(source, "value", false);
out(dest);
}
private static class TestNumber {
private int value;
public TestNumber(int v) {
value = v;
}
public String toString() {
return "" + value;
}
}
private static class TestString {
private String value;
public TestString(String v) {
value = v;
}
public String toString() {
return "" + value;
}
}
private static void out(List list) {
for (Object obj : list) {
System.out.println("" + obj.toString());
}
System.out.println("----------------------------");
}
}
Adjusted code from JavaSE:
public static void sort(List<YourObject> list) {
Object[] a = list.toArray();
sort(a);
ListIterator<YourObject> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((YourObject)a[j]);
}
}
public static void sort(YourObject[] a) {
YourObject[] aux = (YourObject[])a.clone();
mergeSort(aux, a, 0, a.length, 0);
}
private static void mergeSort(YourObject[] src,
YourObject[] dest,
int low,
int high,
int off) {
int length = high - low;
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i=low; i<high; i++)
for (int j=i; j>low &&
dest[j-1].getPrice()-dest[j].getPrice()>0; j--)
swap(dest, j, j-1);
return;
}
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (src[mid-1].getPrice()-src[mid].getPrice() <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// Merge sorted halves (now in src) into dest
for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && src[p].getPrice()-src[q].getPrice()<=0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
}
Related
I have generated a minheap to this file but I think something I have missed but I can't identify what are the things I have missed. I have missed something on --private void bubbleDown() { }-- section but I can't find what are the things missed by me.
private int default_size = 100; // how big the heap should be
private T[] array;
private int size;
public Heap() {
#SuppressWarnings("unchecked")
T[] tmp = (T[]) (new Comparable[default_size]);
array = tmp;
size = 0;
}
boolean isRoot(int index) { return (index == 0); }
int leftChild(int index) { return 2 * index + 1; }
int parent(int index) { return (index - 1) / 2; }
int rightChild(int index) { return 2 * index + 2; }
T myParent(int index) { return array[parent(index)]; }
T myLeftChild(int index) { return array[leftChild(index)]; }
T myRightChild(int index) { return array[rightChild(index)]; }
boolean hasLeftChild(int i) { return leftChild(i) < size-1; }
boolean hasRightChild(int i){ return rightChild(i) < size-1; }
private void swap(int a, int b) {
T tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
public boolean isEmpty() { return (size == 0); }
/* adding heap */
public void add(T value) {
if(size == default_size) throw new IllegalStateException("Full array");
array[size++] = value;
bubbleUp();
}
public void bubbleUp() {
if(size == 0) throw new IllegalStateException("Shape error");
int index = size - 1;
while(!isRoot(index)) {
if(myParent(index).compareTo(array[index]) <= 0) break;
/* else part */
swap(parent(index), index);
index = parent(index);
}
}
/* removing */
public T remove() {
if(isEmpty()) return null;
T res = array[0]; /* root */
array[0] = array[size-1];
size --;
bubbleDown();
return res;
}
// i think this section having wrong something
private void bubbleDown() {
int parent = 0;
int leftChild = 2*parent + 1;
int rightChild = 2*parent + 2;
int choice = compareAndPick(leftChild, rightChild);
while (choice != -1)
{
swap(choice, parent);
parent = choice;
choice = compareAndPick(2*choice+1, 2*choice+2);
}
}
private int compareAndPick(int leftChild, int rightChild)
{
if (leftChild >= default_size || array[leftChild] == null) return -1;
if (array[leftChild].compareTo(array[rightChild]) <= 0 || (array[rightChild] == null))
return leftChild;
return rightChild;
}
public void show() {
for(int i=0; i<size; i++)
System.out.print(array[i] + " ");
System.out.println("=======");
}
public static void main(String [] args) {
Heap<Integer> heap = new Heap<Integer>();
for(int i=0; i<10; i++) {
heap.add((Integer)(int)(Math.random() * 100));
heap.show();
}
System.out.println("You should see sorted numbers");
while(!heap.isEmpty()) {
System.out.print(heap.remove());
System.out.print(" ");
heap.show();
}
System.out.println();
}
}
this code used generics and min heap functions.. i need to identify what is the wrong thing did by me on bubbleDown() section
Explanation
The bubbleDown() method is not a different way to insert a node and move it to it's correct position in the Heap. When bubbleDown() is called it's job is to Heapify the Binary Tree from any state. So your attempt to write the method just by changing the condition from the bubbleUp() method isn't gonna help you.
Extra
Here is a video that can give you the idea of how bubbleDown is supposed to work.
I am trying to create a simple pagination routine for values held in an ArrayList. Basically what I want to do is render the first five elements in the ArrayList at first go. And then when users click on Next (increment by another 5) and Previous (decrease by 5).
My logic looks like this:
class foo
{
private static final int defaultStep = 5;
private int moveCounter;
private List<String> values;
public foo()
{
values = new ArrayList<String>();
values.add("Fiber Channel");
values.add("Copper Channel");
...
}
private void pageNext()
{
if (moveCounter > -1 && moveCounter < values.size())
{
int currentIndex = (moveCounter + 1);
renderValues(currentIndex, false);
}
}
private void pagePrevious()
{
if (moveCounter > -1 && moveCounter <= values.size())
{
renderValues(moveCounter-1, true);
}
}
private void renderValues(int startIndex, boolean isPreviousCall)
{
if (startIndex > -1)
{
StringBuilder html = new StringBuilder();
List<String> valuesToRender = new ArrayList<String>();
int checkSteps = 1;
while (startIndex < values.size())
{
valuesToRender.add(values.get(startIndex));
if (checkSteps == defaultStep) break;
startIndex++;
checkSteps++;
}
moveCounter = startIndex;
//TODO: Build html String
...
}
}
}
I have an issue with pagePrevious call, can you guys help me build the valuesToRender 5-steps up values array before adding the value to render to the valuesToRender array.
I tried doing something like this also:
for (int start = startIndex, end = values.size() - 1; start < end; start++, end--)
{
if (isPreviousCall) valuesToRender.add(values.get(end));
else valuesToRender.add(values.get(start));
if (checkSteps == defaultStep) break;
checkSteps++;
}
But this doesn't seems to work neither. Can you guys spot and help me fix this issue.
Thanks Guys.
Based on "pscuderi" solution here
I've built a wrapping class that can be helpful for someone looking for this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PaginatedList<T> {
private static final int DEFAULT_PAGE_SIZE = 10;
private List<T> list;
private List<List<T>> listOfPages;
private int pageSize = DEFAULT_PAGE_SIZE;
private int currentPage = 0;
public PaginatedList(List<T> list) {
this.list = list;
initPages();
}
public PaginatedList(List<T> list, int pageSize) {
this.list = list;
this.pageSize = pageSize;
initPages();
}
public List<T> getPage(int pageNumber) {
if (listOfPages == null ||
pageNumber > listOfPages.size() ||
pageNumber < 1) {
return Collections.emptyList();
}
currentPage = pageNumber;
List<T> page = listOfPages.get(--pageNumber);
return page;
}
public int numberOfPages() {
if (listOfPages == null) {
return 0;
}
return listOfPages.size();
}
public List<T> nextPage() {
List<T> page = getPage(++currentPage);
return page;
}
public List<T> previousPage() {
List<T> page = getPage(--currentPage);
return page;
}
public void initPages() {
if (list == null || listOfPages != null) {
return;
}
if (pageSize <= 0 || pageSize > list.size()) {
pageSize = list.size();
}
int numOfPages = (int) Math.ceil((double) list.size() / (double) pageSize);
listOfPages = new ArrayList<List<T>>(numOfPages);
for (int pageNum = 0; pageNum < numOfPages;) {
int from = pageNum * pageSize;
int to = Math.min(++pageNum * pageSize, list.size());
listOfPages.add(list.subList(from, to));
}
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 62; i++) {
list.add(i);
}
PaginatedList<Integer> paginatedList = new PaginatedList<Integer>(list);
while (true) {
List<Integer> page = paginatedList.nextPage();
if (page == null || page.isEmpty()) {
break;
}
for (Integer value : page) {
System.out.println(value);
}
System.out.println("------------");
}
}
}
Change
if (moveCounter > -1 && moveCounter <= archive.size())
{
renderValues(moveCounter-1, true);
}
to
if (moveCounter > 0 && moveCounter <= archive.size())
{
renderValues(moveCounter-1, true);
}
I would do it like this:
I'm not sure what renderValues does, and whether we have to substract 1 or maybe defaultStep from the upper bound of the moveCounter.
private void pageMove (int step)
{
moveCounter = moveCounter + step;
if (moveCounter < 0) moveCounter = 0;
if (moveCounter > values.size ()) moveCounter = values.size ();
renderValues (currentIndex, false);
}
private void pageNext ()
{
pageMove (defaultStep);
}
private void pagePrevious ()
{
pageMove (-defaultStep);
}
The first 3 lines could be packed into two big ternary experssions like so:
mc = ((mc + s) < 0) ? 0 : ((mc + s) > vs) ? vs : (mc + s);
but the 3 lines solution is better to follow.
Here is a simple java function for pagination. Note that the page starts from 0 (first page)
public List<Object> pagedResponse(List<Object> allItems, int page, int limit){
int totalItems = allItems.size();
int fromIndex = page*limit;
int toIndex = fromIndex+limit;
if(fromIndex <= totalItems) {
if(toIndex > totalItems){
toIndex = totalItems;
}
return allItems.subList(fromIndex, toIndex);
}else {
return Collections.emptyList();
}
}
The algorithm:
Uses a PQ that supports change priority operations.
Assume all the ADTs work correctly.
Example problem: Find the shortest path of operations to get from integer x to integer y using the following operations and weights; add/subtract 1 : 1, multiply/divide by 2 : 5, square : 10.
Tested against other types of graphs and inputs, sometimes it gets the shortest path, sometimes it gets a suboptimal, sometimes it times out.
import java.util.*;
/**
* Represents a graph of vertices.
*/
public interface AStarGraph<Vertex> {
List<WeightedEdge<Vertex>> neighbors(Vertex v);
double estimatedDistanceToGoal(Vertex s, Vertex goal);
}
public interface ShortestPathsSolver<Vertex> {
SolverOutcome outcome();
List<Vertex> solution();
double solutionWeight();
int numStatesExplored();
double explorationTime();
}
public interface ExtrinsicMinPQ<T> {
/* Inserts an item with the given priority value. */
void add(T item, double priority);
/* Returns true if the PQ contains the given item. */
boolean contains(T item);
/* Returns the minimum item. */
T getSmallest();
/* Removes and returns the minimum item. */
T removeSmallest();
/* Changes the priority of the given item. Behavior undefined if the item doesn't exist. */
void changePriority(T item, double priority);
/* Returns the number of itemToPriority in the PQ. */
int size();
}
public enum SolverOutcome {
SOLVED, TIMEOUT, UNSOLVABLE
}
public class ArrayHeapMinPQ<T> implements ExtrinsicMinPQ<T> {
private ArrayList<PriorityNode> heap;
int count;
private HashMap<T, PriorityNode> items;
public ArrayHeapMinPQ() {
heap = new ArrayList<>();
heap.add(0, new PriorityNode(null, Double.NEGATIVE_INFINITY));
count = 0; // For convenient math
items = new HashMap<>();
}
#Override
public void add(T item, double priority) {
if(contains(item)){
throw new IllegalArgumentException();
}
PriorityNode pn = new PriorityNode(item, priority);
if(count == 0){
heap.add(1, pn);
count++;
}else{
heap.add(count+1, pn);
swim(count+1);
count++;
}
items.put(item, pn);
}
private void swap(int i, int j){
Collections.swap(heap, i, j);
}
private void swim(int i){
while(i > 1){
PriorityNode cur = heap.get(i);
if((cur.compareTo(heap.get(i/2)) >= 0)){
break;
}
swap(i, i/2);
i = i/2;
}
}
private void sink(int k){
while (2*k <= size()-1) {
if(2*k+1 <= size()-1) {
if (heap.get(2 * k).compareTo(heap.get(2 * k + 1)) < 0) {
if (heap.get(k).compareTo(heap.get(2 * k)) > 0) {
swap(k, 2 * k);
k = 2 * k;
continue;
}
} else if(heap.get(k).compareTo(heap.get(2*k+1)) > 0){
swap(2*k+1, k);
k = 2*k +1;
continue;}
}
else if (heap.get(k).compareTo(heap.get(2 * k)) > 0) {
swap(k, 2 * k);
k = 2 * k;
continue;}
break;
}
}
#Override
public int size(){
return heap.size();
}
public PriorityNode getRoot(){
return heap.get(1);
}
#Override
public boolean contains(T item) {
return items.containsKey(item);}
#Override
public T getSmallest() {
if(heap.size() == 0){
throw new NoSuchElementException();
}
return getRoot().getItem();
}
#Override
public T removeSmallest() {
if(heap.size() == 1){
throw new NoSuchElementException();
}
T item = heap.get(1).item;
swap(1, size()-1);
heap.remove(size()-1);
if(size() > 1){
sink(1);
}
items.remove(item);
count--;
return item;
}
public boolean isEmpty(){
return heap.size() == 1;
}
public int getCount() {
return count;
}
#Override
public void changePriority(T T, double priority) {
if(heap.size() == 0){
throw new NoSuchElementException();
}
PriorityNode tochange = items.get(T);
double prioritysearch = tochange.getPriority();
double currprior = getRoot().getPriority();
int left = 0;
int right = 0;
if((prioritysearch != currprior)){
if (currprior > prioritysearch){
add(T, priority);
return;
}
left = heapTraverse(prioritysearch, tochange, 2);
right = heapTraverse(prioritysearch, tochange, 3);
}
if(left == -1 && right == -1){
throw new NoSuchElementException();
}
else if(left > 0){
PriorityNode toChange = heap.get(left);
toChange.setPriority(priority);
if(priority < heap.get(left/2).getPriority()){
swim(left);
}else
sink(left);
}
else {
PriorityNode toChange = heap.get(right);
toChange.setPriority(priority);
if (priority < heap.get(right / 2).getPriority()) {
swim(right);
} else
sink(right);
}
}
private int heapTraverse(double priority, PriorityNode node, int index){
if(index > heap.size()-1){
return -1;
}
PriorityNode curr = heap.get(index);
double currprior = curr.getPriority();
if(currprior == priority && node.equals(curr)){
return index;
} else if(currprior > priority){
return -1;
}else{
if(heapTraverse(priority, node, index*2) == -1){
return heapTraverse(priority, node, index*2 +1);}
else {return heapTraverse(priority, node, index*2);}
}
}
private class PriorityNode implements Comparable<PriorityNode> {
private T item;
private double priority;
PriorityNode(T e, double p) {
this.item = e;
this.priority = p;
}
T getItem() {
return item;
}
double getPriority() {
return priority;
}
void setPriority(double priority) {
this.priority = priority;
}
#Override
public int compareTo(PriorityNode other) {
if (other == null) {
return -1;
}
return Double.compare(this.getPriority(), other.getPriority());
}
#Override
public boolean equals(Object o) {
if( o == null) {
throw new NullPointerException();
}
if (o.getClass() != this.getClass()) {
return false;
} else {
return ((PriorityNode) o).getItem().equals(getItem());
}
}
#Override
public int hashCode() {
return item.hashCode();
}
}
public class WeightedEdge<Vertex> {
private Vertex v;
private Vertex w;
private double weight;
public WeightedEdge(Vertex v, Vertex w, double weight) {
this.v = v;
this.w = w;
this.weight = weight;
}
public Vertex from() {
return v;
}
public Vertex to() {
return w;
}
public double weight() {
return weight;
}
}
public class SolutionPrinter {
/** Summarizes the result of the search made by this solver without actually
* printing the solution itself (if any).
*/
public static <Vertex> void summarizeOutcome(ShortestPathsSolver<Vertex> solver) {
summarizeSolution(solver, "", false);
}
/** Summarizes the result of the search made by this solver and also
* prints each vertex of the solution, connected by the given delimiter,
* e.g. delimiter = "," would return all states separated by commas.
*/
public static <Vertex> void summarizeSolution(ShortestPathsSolver<Vertex> solver,
String delimiter) {
summarizeSolution(solver, delimiter, true);
}
private static <Vertex> String solutionString(ShortestPathsSolver<Vertex> solver,
String delimiter) {
List<String> solutionVertices = new ArrayList<>();
for (Vertex v : solver.solution()) {
solutionVertices.add(v.toString());
}
return String.join(delimiter, solutionVertices);
}
private static <Vertex> void summarizeSolution(ShortestPathsSolver<Vertex> solver,
String delimiter, boolean printSolution) {
System.out.println("Total states explored in " + solver.explorationTime()
+ "s: " + solver.numStatesExplored());
if (solver.outcome() == SolverOutcome.SOLVED) {
List<Vertex> solution = solver.solution();
System.out.println("Search was successful.");
System.out.println("Solution was of length " + solution.size()
+ ", and had total weight " + solver.solutionWeight() + ":");
if (printSolution) {
System.out.println(solutionString(solver, delimiter));
}
} else if (solver.outcome() == SolverOutcome.TIMEOUT) {
System.out.println("Search timed out, considered " + solver.numStatesExplored()
+ " vertices before timing out.");
} else { // (solver.outcome() == SolverOutcome.UNSOLVABLE)
System.out.println("Search determined that the goal is unreachable from source.");
}
}
}
public class AStarSolver implements ShortestPathsSolver {
private final AStarGraph<Vertex> graph;
private Vertex source;
private Vertex dest;
private SolverOutcome result;
private HashMap<Vertex, Double> distTo = new HashMap<>();
private ArrayHeapMinPQ<Vertex> fringe = new ArrayHeapMinPQ<>();
private HashMap<Vertex, WeightedEdge<Vertex>> edgeTo = new HashMap<>(); // answers the question which vertex to ge to this vertex
private double solutionweight;
private List<Vertex> solution;
private ArrayList<Vertex> marked = new ArrayList<>();
private double timetosolve;
private int numofstates = 0;
public AStarSolver(AStarGraph<Vertex> input, Vertex start, Vertex end, double timeout ){
graph = input;
source = start;
dest = end;
if(start.equals(end)){
solutionweight = 0;
solution = List.of(start);
result = SolverOutcome.SOLVED;
numofstates = 0;
timetosolve = 0;
return;
}
fringe.add(start, 0.0);
distTo.put(start, 0.0);
while (!fringe.isEmpty()) {
Vertex src = fringe.removeSmallest();
numofstates++;
marked.add(src);
List<WeightedEdge<Vertex>> neighbors = graph.neighbors(src);
for(WeightedEdge<Vertex> e: neighbors){
double heur = graph.estimatedDistanceToGoal(e.to(), dest);
if ((heur == Double.POSITIVE_INFINITY || marked.contains(e.to())) && !e.to().equals(dest)) {
continue;
}
double distFr = distTo.get(e.from()) + e.weight();
if(!distTo.containsKey(e.to())){
distTo.put(e.to(), distFr);
}
if (!fringe.contains(e.to())) {
fringe.add(e.to(), distFr + heur);
edgeTo.put(e.to(), e);
}
if (distTo.get(e.to()) > distFr) {
fringe.changePriority(e.to(), heur + distFr);
edgeTo.put(e.to(), e);
distTo.put(e.to(), distFr);
}
if (e.to().equals(dest)) {
solutionweight = distTo.get(e.to());
solution = pathTracer(e);
timetosolve = sw.elapsedTime();
result = SolverOutcome.SOLVED;
return;
}
if (e.to().equals(dest)) {
solutionweight = distTo.get(e.to());
solution = pathTracer(e);
timetosolve = sw.elapsedTime();
result = SolverOutcome.SOLVED;
return;
}
}
if (timeout < sw.elapsedTime()){
result = SolverOutcome.TIMEOUT;
return;
}
}
result = SolverOutcome.UNSOLVABLE;
solution = List.of();
}
private List<Vertex> pathTracer(WeightedEdge<Vertex> e) {
ArrayList<Vertex> path = new ArrayList<>();
path.add(e.to());
path.add(e.from());
while (!e.from().equals(source)) {
e = edgeTo.get(e.from());
path.add(e.from());
}
Collections.reverse(path);
return path;
}
#Override
public SolverOutcome outcome() {
return result;
}
#Override
public List solution() {
return solution;
}
#Override
public double solutionWeight() {
return solutionweight;
}
#Override
public int numStatesExplored() {
return numofstates;
}
#Override
public double explorationTime() {
return timetosolve;
}
public class IntegerHopGraph implements AStarGraph<Integer> {
#Override
public List<WeightedEdge<Integer>> neighbors(Integer v) {
ArrayList<WeightedEdge<Integer>> neighbors = new ArrayList<>();
neighbors.add(new WeightedEdge<>(v, v * v, 10));
neighbors.add(new WeightedEdge<>(v, v * 2, 5));
neighbors.add(new WeightedEdge<>(v, v / 2, 5));
neighbors.add(new WeightedEdge<>(v, v - 1, 1));
neighbors.add(new WeightedEdge<>(v, v + 1, 1));
return neighbors;
}
#Override
public double estimatedDistanceToGoal(Integer s, Integer goal) {
// possibly fun challenge: Try to find an admissible heuristic that
// speeds up your search. This is tough!
return 0;
}
}
public class DemoIntegerHopPuzzleSolution {
public static void main(String[] args) {
int start = 17;
int goal = 111;
IntegerHopGraph ahg = new IntegerHopGraph();
ShortestPathsSolver<Integer> solver = new AStarSolver<>(ahg, start, goal, 10);
SolutionPrinter.summarizeSolution(solver, " => ");
}
}
}
To get from x = 11, to y = 117 the algorithm gives this result:
Total states explored in 0.019s: 110
Search was successful.
Solution was of length 7, and had total weight 19.0:
17 => 16 => 15 => 225 => 224 => 223 => 111
The correct result should is:
Total states explored in 0.018s: 338 <--- may vary.
Search was successful.
Solution was of length 6, and had total weight 18.0:
17 => 16 => 15 => 225 => 112 => 111
Thanks for all the help guys but I figured it out. My algorithm terminates prematurely. It stops when it sees the finish, not when it is on the top of the heap like it should.
I came across a post showing how to arrange char array by alphabet order.
seeing this can be done, I want to output the alphabetical order of each character of the input string, in order of the characters of the input string.
I'm a bit stuck. I can get the string reordered alphabetically, but I don't know what to do next.
example is 'monkey' to '354216'
because 'ekmnoy' e is alphabetically first from the set of given characters so e = 1 , k is the second alpha char when sorted so k = 2, and so on.
if you cannot understand I can provide more example to make things clear out.
Code
String str = "airport";
Character[] chars = new Character[str.length()];
for (int z = 0; z < chars.length; z++) {
chars[z] = str.charAt(z);
}
Arrays.sort(chars, new Comparator<Character>() {
public int compare(Character c1, Character c2) {
int cmp = Character.compare(
Character.toLowerCase(c1.charValue()),
Character.toLowerCase(c2.charValue()));
if (cmp != 0) {
return cmp;
}
return Character.compare(c1.charValue(), c2.charValue());
}
});
StringBuilder sb = new StringBuilder(chars.length);
for (char c : chars) {
sb.append(c);
}
str = sb.toString();
System.out.println(sb);
Output
aioprrt
expected output
Orange -> aegnOr
561432 - 123456
Monkey -> ekMnoy
354216 -> 123456
I dont know what you want to do with double characters, but if you add this few lines to your code at the end you are getting the right result. Iterate over the sorted String and replace the charakters in the original String with their indices in the sorted String.
String originalStr = "airport";
for(int i = 0; i<str.length(); i++) {
originalStr = originalStr.replace(str.charAt(i), String.valueOf(i+1).charAt(0));
}
System.out.println(originalStr);
Output: 1254357
If you want to get the output: 1254367 use replaceFirst:
originalStr = originalStr.replaceFirst(String.valueOf(str.charAt(i)), String.valueOf(i+1));
Input:Orange
Output:561432
Input:Monkey
Output:354216
The whole code:
String str = "airport";
String originalStr = str; //creat a backup of str because you change it in your code
Character[] chars = str.toCharArray();
Arrays.sort(chars, new Comparator<Character>() {
public int compare(Character c1, Character c2) {
int cmp = Character.compare(
Character.toLowerCase(c1.charValue()),
Character.toLowerCase(c2.charValue()));
if (cmp != 0) {
return cmp;
}
return Character.compare(c1.charValue(), c2.charValue());
}
});
str = String.valueOf(chars);
System.out.println(str);
//Iterate over the sorted String and replace the charakters in the original String with their indices in the sorted String
for(int i = 0; i<str.length(); i++) {
originalStr = originalStr.replaceFirst(String.valueOf(str.charAt(i)), String.valueOf(i+1));
}
System.out.println(originalStr);
Once you have arranged the characters in order (in a different array from the original) then create a third array by walking the original string and choosing the index of each character from te sorted string.
input: edcba
sorted: abcde
index: 01234
Pseudocode...
for( int i = 0; i < input.length(); i++ ) {
index[i] = sorted.indexOf(input[i]);
}
Result should be 43210 with the given input.
Note that strings with more than 10 characters will result in ambiguous output, which can be handled by inserting spaces in the output. Example:
abcdefghijk ->
012345678910
You can use this below code:
package Test;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Arrange {
public static void main(String[] args) {
String str = "money";
List<Test> strs=new LinkedList<Test>();
List<Test> final_result=new LinkedList<Test>();
for(int i=0;i<str.length();i++)
{
Test t=new Test(i, ""+str.charAt(i), 0);
strs.add(t);
}
Collections.sort(strs,new Comparator<Test>() {
#Override
public int compare(Test o1, Test o2) {
return (o1.getS().compareToIgnoreCase(o2.getS()));
}
});
Integer i=1;
for (Test st : strs) {
st.setJ(i);
final_result.add(st);
i++;
}
Collections.sort(final_result,new Comparator<Test>() {
#Override
public int compare(Test o1, Test o2) {
return (o1.getI().compareTo(o2.getI()));
}
});
for (Test test : final_result) {
System.out.println(test.getJ());
}
}
}
class Test{
private Integer i;
private String s;
private Integer j;
public Test() {
// TODO Auto-generated constructor stub
}
public Test(Integer i, String s, Integer j) {
super();
this.i = i;
this.s = s;
this.j = j;
}
public Integer getI() {
return i;
}
public void setI(Integer i) {
this.i = i;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public Integer getJ() {
return j;
}
public void setJ(Integer j) {
this.j = j;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((i == null) ? 0 : i.hashCode());
result = prime * result + ((j == null) ? 0 : j.hashCode());
result = prime * result + ((s == null) ? 0 : s.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Test other = (Test) obj;
if (i == null) {
if (other.i != null)
return false;
} else if (!i.equals(other.i))
return false;
if (j == null) {
if (other.j != null)
return false;
} else if (!j.equals(other.j))
return false;
if (s == null) {
if (other.s != null)
return false;
} else if (!s.equals(other.s))
return false;
return true;
}
}
I have this code for a heap tree and I'm stuck with the iterators.
I need in-order, pre-order and post-order iterators, but I have no idea how to do it.
If someone has an idea or example please help.
class Numbers implements Comparable<Numbers> {
private int value;
public Numbers(int value) {
this.value = value;
}
public String toString() {
return Integer.toString(value);
}
public int getValue() {
return this.value;
}
public int compareTo(Numbers o) {
int tmp = o.getValue();
if (value > tmp)
return 1;
if (value < tmp)
return -1;
return 0;
}
}
class BinaryHeapIsFull extends Exception {
BinaryHeapIsFull() {
super("There is no more place in the heap!");
}
}
public class BinaryHeap<E extends Comparable> {
E[] elements;
int count;
public BinaryHeap(int maxSize) {
elements = (E[]) new Comparable[maxSize];
this.count = 0;
}
public void enqueue(E elem) throws BinaryHeapIsFull {
if (count == elements.length)
throw new BinaryHeapIsFull();
int i = count++;
while (i > 0 && elements[(i - 1) / 2].compareTo(elem) == 1) {
elements[i] = elements[(i - 1) / 2];
i = (i - 1) / 2;
}
elements[i] = elem;
}
public E findMin() {
return elements[0];
}
public E dequeueMin() {
if (count == 0)
return null;
E result = elements[0];
E last = elements[--count];
int i = 0;
while (2 * i + 1 <= count) {
int child = 2 * i + 1;
if (child < count
&& elements[child + 1].compareTo(elements[child]) == -1)
child++;
if (last.compareTo(elements[child]) == -1
|| last.compareTo(elements[child]) == 0)
break;
elements[i] = elements[child];
i = child;
}
elements[i] = last;
return result;
}
public String toString() {
String print = "";
for (int i = 0; i < count; i++)
print += elements[i].toString() + " ";
return print;
}
public void sort() {
int a = count;
for (int i = 0; i < a; i++) {
System.out.print(findMin() + " ");
dequeueMin();
}
}
public static void main(String[] args) throws BinaryHeapIsFull {
BinaryHeap<Numbers> b = new BinaryHeap<Numbers>(10);
b.enqueue(new Numbers(6));
System.out.println(b.toString());
b.enqueue(new Numbers(3));
System.out.println(b.toString());
b.enqueue(new Numbers(4));
System.out.println(b.toString());
b.enqueue(new Numbers(1));
System.out.println(b.toString());
b.enqueue(new Numbers(5));
System.out.println(b.toString());
b.enqueue(new Numbers(0));
System.out.println(b.toString());
b.enqueue(new Numbers(2));
System.out.println(b.toString());
b.dequeueMin();
System.out.println(b.toString());
b.dequeueMin();
System.out.println(b.toString());
System.out.println(b.findMin());
b.sort();
}
}
I'd start with three classes, one for each case, that implements the Iterator interface. Give those iterators an instance of your binary heap and let them do their thing.
public class BinaryHeapPreOrderIterator implements Iterator {
// constructor and methods for Iterator here.
}