Sorting algortithm with index in java - java

I have a set of values for srting algorithm. I have successfully sorted them out. But I also want to have the index for each element after sorting. For example like :
Array = [95, 53, 24, 10]
Output after sorting should be like :
10 at index 3, 24 at index 2, 53 at index 1 and 95 at index 0
I have used the following logic for sorting. But unable to get the indexes
for (int p = 0; p < ((list.size()) - 1); p++) {
int min = p;
count++;
for(int q=p+1; q<list.size();q++) {
if(doubleArray[q] < doubleArray[min]) {
min = q;
}
}
double smallNumber = doubleArray[p];
doubleArray[p] = doubleArray[min];
doubleArray[min] = smallNumber;
}

As this is probably homework, just some ideas:
before sorting, create a copy of your initial array
after sorting, iterate the original array, and then find the index of each value in the sorted array, and print that
the tricky part is dealing with values that show up repeatedly. but that is something that depends on your exact requirements.
Alternatively, you could look into introducing a helpful data structure, such as a Pair<Integer, Integer> class. The first entry represents the value, the second one an index. Then you can define your own "sorting" on that class.

As previously suggested, I would also recommend using an additional Item class which stores the item on which you want to sort and the initial index:
public class Item<T extends Comparable<T>> implements Comparable<Item<T>> {
public final T item;
public final int index;
public Item(T item, int index) {
if (item == null)
throw new NullPointerException("the given item is null!");
this.item = item;
this.index = index;
}
#Override
public int compareTo(Item<T> t) {
if (t == null)
return 1;
return item.compareTo(t.item);
}
}
When you need to sort the array of doubles, you first create an ArrayList containing the Items which store the doubles of the input array and the initial index. Since the Item class implements the Comparable interface, you can use Collections.sort for sorting (which will be faster than your bubblesort implementation):
public static void sort(Integer... array) {
List<Item<Integer>> copy = new ArrayList<Item<Integer>>(array.length);
// copy the input array
for (int i = 0; i < array.length; ++i)
copy.add(new Item<Integer>(array[i], i));
Collections.sort(copy);
for (Item<Integer> t : copy)
System.out.println(t.item + " at index " + t.index);
}

Try this:
Create a Pair class like
class Pair {
int val;
int index;
}
sort it by valuez
index will keep the initial index

I would suggest below approach:
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class trial
{
public static void main(String[] args)
{
List<Integer> aList = Arrays.asList(95, 53, 24, 10);
Map<Integer, Integer> aMap = new HashMap<>();
int index = 0;
for( Integer aInteger : aList )
{
aMap.put(aInteger, index);
index++;
}
SortedSet<Integer> keys = new TreeSet<>(aMap.keySet());
for( Integer key : keys )
{
Integer value = aMap.get(key);
System.out.println(key + " at index " + value);
}
}
}

Here you find the old index and shorted value
Map<Integer, Integer> map1 = numbers.stream().collect(Collectors.toMap(i -> i, i -> numbers.indexOf(i))). entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
//output {10=3, 24=2, 53=1, 95=0}

I have just tried the following and it worked.
int[] index = {0,1,2,3}
for (int p=0;p<((list.size())-1);p++)
{
int min = p;
count++;
for(int q=p+1; q<list.size();q++)
{
if(doubleArray[q]< doubleArray[min])
{
min = q;
}
}
double smallNumber = doubleArray[p];
doubleArray[p] = doubleArray[min];
doubleArray[min] = smallNumber;
store = index[p];
index[p] = index[min];
index[min] = store;
}
}
and it worked.

Related

How can I sort a list based on another list values in Java [duplicate]

I've seen several other questions similiar to this one but I haven't really been able to find anything that resolves my problem.
My use case is this: user has a list of items initially (listA). They reorder the items and want to persist that order (listB), however, due to restrictions I'm unable persist the order on the backend so I have to sort listA after I retrieve it.
So basically, I have 2 ArrayLists (listA and listB). One with the specific order the lists should be in (listB) and the other has the list of items (listA). I want to sort listA based on listB.
Using Java 8:
Collections.sort(listToSort,
Comparator.comparing(item -> listWithOrder.indexOf(item)));
or better:
listToSort.sort(Comparator.comparingInt(listWithOrder::indexOf));
Collections.sort(listB, new Comparator<Item>() {
public int compare(Item left, Item right) {
return Integer.compare(listA.indexOf(left), listA.indexOf(right));
}
});
This is quite inefficient, though, and you should probably create a Map<Item, Integer> from listA to lookup the positions of the items faster.
Guava has a ready-to-use comparator for doing that: Ordering.explicit()
Let's say you have a listB list that defines the order in which you want to sort listA. This is just an example, but it demonstrates an order that is defined by a list, and not the natural order of the datatype:
List<String> listB = Arrays.asList("Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday");
Now, let's say that listA needs to be sorted according to this ordering. It's a List<Item>, and Item has a public String getWeekday() method.
Create a Map<String, Integer> that maps the values of everything in listB to something that can be sorted easily, such as the index, i.e. "Sunday" => 0, ..., "Saturday" => 6. This will provide a quick and easy lookup.
Map<String, Integer> weekdayOrder = new HashMap<String, Integer>();
for (int i = 0; i < listB.size(); i++)
{
String weekday = listB.get(i);
weekdayOrder.put(weekday, i);
}
Then you can create your custom Comparator<Item> that uses the Map to create an order:
public class ItemWeekdayComparator implements Comparator<Item>
{
private Map<String, Integer> sortOrder;
public ItemWeekdayComparator(Map<String, Integer> sortOrder)
{
this.sortOrder = sortOrder;
}
#Override
public int compare(Item i1, Item i2)
{
Integer weekdayPos1 = sortOrder.get(i1.getWeekday());
if (weekdayPos1 == null)
{
throw new IllegalArgumentException("Bad weekday encountered: " +
i1.getWeekday());
}
Integer weekdayPos2 = sortOrder.get(i2.getWeekday());
if (weekdayPos2 == null)
{
throw new IllegalArgumentException("Bad weekday encountered: " +
i2.getWeekday());
}
return weekdayPos1.compareTo(weekdayPos2);
}
}
Then you can sort listA using your custom Comparator.
Collections.sort(listA, new ItemWeekdayComparator(weekdayOrder));
Speed improvement on JB Nizet's answer (from the suggestion he made himself). With this method:
Sorting a 1000 items list 100 times improves speed 10 times on my
unit tests.
Sorting a 10000 items list 100 times improves speed 140 times (265 ms for the whole batch instead of 37 seconds) on my
unit tests.
This method will also work when both lists are not identical:
/**
* Sorts list objectsToOrder based on the order of orderedObjects.
*
* Make sure these objects have good equals() and hashCode() methods or
* that they reference the same objects.
*/
public static void sortList(List<?> objectsToOrder, List<?> orderedObjects) {
HashMap<Object, Integer> indexMap = new HashMap<>();
int index = 0;
for (Object object : orderedObjects) {
indexMap.put(object, index);
index++;
}
Collections.sort(objectsToOrder, new Comparator<Object>() {
public int compare(Object left, Object right) {
Integer leftIndex = indexMap.get(left);
Integer rightIndex = indexMap.get(right);
if (leftIndex == null) {
return -1;
}
if (rightIndex == null) {
return 1;
}
return Integer.compare(leftIndex, rightIndex);
}
});
}
Problem : sorting a list of Pojo on the basis of one of the field's all possible values present in another list.
Take a look at this solution, may be this is what you are trying to achieve:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Employee> listToSort = new ArrayList<>();
listToSort.add(new Employee("a", "age11"));
listToSort.add(new Employee("c", "age33"));
listToSort.add(new Employee("b", "age22"));
listToSort.add(new Employee("a", "age111"));
listToSort.add(new Employee("c", "age3"));
listToSort.add(new Employee("b", "age2"));
listToSort.add(new Employee("a", "age1"));
List<String> listWithOrder = new ArrayList<>();
listWithOrder.add("a");
listWithOrder.add("b");
listWithOrder.add("c");
Collections.sort(listToSort, Comparator.comparing(item ->
listWithOrder.indexOf(item.getName())));
System.out.println(listToSort);
}
}
class Employee {
String name;
String age;
public Employee(String name, String age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
#Override
public String toString() {
return "[name=" + name + ", age=" + age + "]";
}
}
O U T P U T
[[name=a, age=age11], [name=a, age=age111], [name=a, age=age1], [name=b, age=age22], [name=b, age=age2], [name=c, age=age33], [name=c, age=age3]]
Here is a solution that increases the time complexity by 2n, but accomplishes what you want. It also doesn't care if the List R you want to sort contains Comparable elements so long as the other List L you use to sort them by is uniformly Comparable.
public class HeavyPair<L extends Comparable<L>, R> implements Comparable<HeavyPair<L, ?>> {
public final L left;
public final R right;
public HeavyPair(L left, R right) {
this.left = left;
this.right = right;
}
public compareTo(HeavyPair<L, ?> o) {
return this.left.compareTo(o.left);
}
public static <L extends Comparable<L>, R> List<R> sort(List<L> weights, List<R> toSort) {
assert(weights.size() == toSort.size());
List<R> output = new ArrayList<>(toSort.size());
List<HeavyPair<L, R>> workHorse = new ArrayList<>(toSort.size());
for(int i = 0; i < toSort.size(); i++) {
workHorse.add(new HeavyPair(weights.get(i), toSort.get(i)))
}
Collections.sort(workHorse);
for(int i = 0; i < workHorse.size(); i++) {
output.add(workHorse.get(i).right);
}
return output;
}
}
Excuse any terrible practices I used while writing this code, though. I was in a rush.
Just call HeavyPair.sort(listB, listA);
Edit: Fixed this line return this.left.compareTo(o.left);. Now it actually works.
Here is an example of how to sort a list and then make the changes in another list according to the changes exactly made to first array list. This trick will never fails and ensures the mapping between the items in list. The size of both list must be same to use this trick.
ArrayList<String> listA = new ArrayList<String>();
ArrayList<String> listB = new ArrayList<String>();
int j = 0;
// list of returns of the compare method which will be used to manipulate
// the another comparator according to the sorting of previous listA
ArrayList<Integer> sortingMethodReturns = new ArrayList<Integer>();
public void addItemstoLists() {
listA.add("Value of Z");
listA.add("Value of C");
listA.add("Value of F");
listA.add("Value of A");
listA.add("Value of Y");
listB.add("this is the value of Z");
listB.add("this is the value off C");
listB.add("this is the value off F");
listB.add("this is the value off A");
listB.add("this is the value off Y");
Collections.sort(listA, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
// TODO Auto-generated method stub
int returning = lhs.compareTo(rhs);
sortingMethodReturns.add(returning);
return returning;
}
});
// now sort the list B according to the changes made with the order of
// items in listA
Collections.sort(listB, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
// TODO Auto-generated method stub
// comparator method will sort the second list also according to
// the changes made with list a
int returning = sortingMethodReturns.get(j);
j++;
return returning;
}
});
}
try this for java 8:
listB.sort((left, right) -> Integer.compare(list.indexOf(left), list.indexOf(right)));
or
listB.sort(Comparator.comparingInt(item -> list.indexOf(item)));
import java.util.Comparator;
import java.util.List;
public class ListComparator implements Comparator<String> {
private final List<String> orderedList;
private boolean appendFirst;
public ListComparator(List<String> orderedList, boolean appendFirst) {
this.orderedList = orderedList;
this.appendFirst = appendFirst;
}
#Override
public int compare(String o1, String o2) {
if (orderedList.contains(o1) && orderedList.contains(o2))
return orderedList.indexOf(o1) - orderedList.indexOf(o2);
else if (orderedList.contains(o1))
return (appendFirst) ? 1 : -1;
else if (orderedList.contains(o2))
return (appendFirst) ? -1 : 1;
return 0;
}
}
You can use this generic comparator to sort list based on the the other list.
For example, when appendFirst is false below will be the output.
Ordered list: [a, b]
Un-ordered List: [d, a, b, c, e]
Output:
[a, b, d, c, e]
One way of doing this is looping through listB and adding the items to a temporary list if listA contains them:
List<?> tempList = new ArrayList<?>();
for(Object o : listB) {
if(listA.contains(o)) {
tempList.add(o);
}
}
listA.removeAll(listB);
tempList.addAll(listA);
return tempList;
Not completely clear what you want, but if this is the situation:
A:[c,b,a]
B:[2,1,0]
And you want to load them both and then produce:
C:[a,b,c]
Then maybe this?
List c = new ArrayList(b.size());
for(int i=0;i<b.size();i++) {
c.set(b.get(i),a.get(i));
}
that requires an extra copy, but I think to to it in place is a lot less efficient, and all kinds of not clear:
for(int i=0;i<b.size();i++){
int from = b.get(i);
if(from == i) continue;
T tmp = a.get(i);
a.set(i,a.get(from));
a.set(from,tmp);
b.set(b.lastIndexOf(i),from);
}
Note I didn't test either, maybe got a sign flipped.
Another solution that may work depending on your setting is not storing instances in listB but instead indices from listA. This could be done by wrapping listA inside a custom sorted list like so:
public static class SortedDependingList<E> extends AbstractList<E> implements List<E>{
private final List<E> dependingList;
private final List<Integer> indices;
public SortedDependingList(List<E> dependingList) {
super();
this.dependingList = dependingList;
indices = new ArrayList<>();
}
#Override
public boolean add(E e) {
int index = dependingList.indexOf(e);
if (index != -1) {
return addSorted(index);
}
return false;
}
/**
* Adds to this list the element of the depending list at the given
* original index.
* #param index The index of the element to add.
*
*/
public boolean addByIndex(int index){
if (index < 0 || index >= this.dependingList.size()) {
throw new IllegalArgumentException();
}
return addSorted(index);
}
/**
* Returns true if this list contains the element at the
* index of the depending list.
*/
public boolean containsIndex(int index){
int i = Collections.binarySearch(indices, index);
return i >= 0;
}
private boolean addSorted(int index){
int insertIndex = Collections.binarySearch(indices, index);
if (insertIndex < 0){
insertIndex = -insertIndex-1;
this.indices.add(insertIndex, index);
return true;
}
return false;
}
#Override
public E get(int index) {
return dependingList.get(indices.get(index));
}
#Override
public int size() {
return indices.size();
}
}
Then you can use this custom list as follows:
public static void main(String[] args) {
class SomeClass{
int index;
public SomeClass(int index) {
super();
this.index = index;
}
#Override
public String toString() {
return ""+index;
}
}
List<SomeClass> listA = new ArrayList<>();
for (int i = 0; i < 100; i++) {
listA.add(new SomeClass(i));
}
SortedDependingList<SomeClass> listB = new SortedDependingList<>(listA);
Random rand = new Random();
// add elements by index:
for (int i = 0; i < 5; i++) {
int index = rand.nextInt(listA.size());
listB.addByIndex(index);
}
System.out.println(listB);
// add elements by identity:
for (int i = 0; i < 5; i++) {
int index = rand.nextInt(listA.size());
SomeClass o = listA.get(index);
listB.add(o);
}
System.out.println(listB);
}
Of course, this custom list will only be valid as long as the elements in the original list do not change. If changes are possible, you would need to somehow listen for changes to the original list and update the indices inside the custom list.
Note also, that the SortedDependingList does currently not allow to add an element from listA a second time - in this respect it actually works like a set of elements from listA because this is usually what you want in such a setting.
The preferred way to add something to SortedDependingList is by already knowing the index of an element and adding it by calling sortedList.addByIndex(index);
If the two lists are guaranteed to contain the same elements, just in a different order, you can use List<T> listA = new ArrayList<>(listB) and this will be O(n) time complexity. Otherwise, I see a lot of answers here using Collections.sort(), however there is an alternative method which is guaranteed O(2n) runtime, which should theoretically be faster than sort's worst time complexity of O(nlog(n)), at the cost of 2n storage
Set<T> validItems = new HashSet<>(listB);
listA.clear();
listB.forEach(item -> {
if(validItems.contains(item)) {
listA.add(item);
}
});
List<String> listA;
Comparator<B> comparator = Comparator.comparing(e -> listA.indexOf(e.getValue()));
//call your comparator inside your list to be sorted
listB.stream().sorted(comparator)..
Like Tim Herold wrote, if the object references should be the same, you can just copy listB to listA, either:
listA = new ArrayList(listB);
Or this if you don't want to change the List that listA refers to:
listA.clear();
listA.addAll(listB);
If the references are not the same but there is some equivalence relationship between objects in listA and listB, you could sort listA using a custom Comparator that finds the object in listB and uses its index in listB as the sort key. The naive implementation that brute force searches listB would not be the best performance-wise, but would be functionally sufficient.
IMO, you need to persist something else. May be not the full listB, but something. May be just the indexes of the items that the user changed.
Try this. The code below is general purpose for a scenario where listA is a list of Objects since you did not indicate a particular type.
Object[] orderedArray = new Object[listA.size()];
for(int index = 0; index < listB.size(); index ++){
int position = listB.get(index); //this may have to be cast as an int
orderedArray[position] = listA.get(index);
}
//if you receive UnsupportedOperationException when running listA.clear()
//you should replace the line with listA = new List<Object>()
//using your actual implementation of the List interface
listA.clear();
listA.addAll(orderedArray);
Just encountered the same problem.
I have a list of ordered keys, and I need to order the objects in a list according to the order of the keys.
My lists are long enough to make the solutions with time complexity of N^2 unusable.
My solution:
<K, T> List<T> sortByOrder(List<K> orderedKeys, List<T> objectsToOrder, Function<T, K> keyExtractor) {
AtomicInteger ind = new AtomicInteger(0);
Map<K, Integer> keyToIndex = orderedKeys.stream().collect(Collectors.toMap(k -> k, k -> ind.getAndIncrement(), (oldK, newK) -> oldK));
SortedMap<Integer, T> indexToObj = new TreeMap<>();
objectsToOrder.forEach(obj -> indexToObj.put(keyToIndex.get(keyExtractor.apply(obj)), obj));
return new ArrayList<>(indexToObj.values());
}
The time complexity is O(N * Log(N)).
The solution assumes that all the objects in the list to sort have distinct keys. If not then just replace SortedMap<Integer, T> indexToObj by SortedMap<Integer, List<T>> indexToObjList.
To avoid having a very inefficient look up, you should index the items in listB and then sort listA based on it.
Map<Item, Integer> index = IntStream.range(0, listB.size()).boxed()
.collect(Collectors.toMap(listB::get, x -> x));
listA.sort((e1, e2) -> Integer.compare(index.get(c1), index.get(c2));
So for me the requirement was to sort originalList with orderedList. originalList always contains all element from orderedList, but not vice versa. No new elements.
fun <T> List<T>.sort(orderedList: List<T>): List<T> {
return if (size == orderedList.size) {
orderedList
} else {
var keepIndexCount = 0
mapIndexed { index, item ->
if (orderedList.contains(item)) {
orderedList[index - keepIndexCount]
} else {
keepIndexCount++
item
}
}
}}
P.S. my case was that I have list that user can sort by drag and drop, but some items might be filtered out, so we preserve hidden items position.
If you want to do it manually. Solution based on bubble sort (same length required):
public void sortAbasedOnB(String[] listA, double[] listB) {
for (int i = 0; i < listB.length - 1; i++) {
for (int j = listB.length - 1; j > i; j--) {
if (listB[j] < listB[j - 1]){
double tempD = listB[j - 1];
listB[j - 1] = listB[j];
listB[j] = tempD;
String tempS = listA[j - 1];
listA[j - 1] = listA[j];
listA[j] = tempS;
}
}
}
}
If the object references should be the same, you can initialize listA new.
listA = new ArrayList(listB)
In Java there are set of classes which can be useful to sort lists or arrays. Most of the following examples will use lists but the same concept can be applied for arrays. A example will show this.
We can use this by creating a list of Integers and sort these using the Collections.sort(). The Collections (Java Doc) class (part of the Java Collection Framework) provides a list of static methods which we can use when working with collections such as list, set and the like. So in a nutshell, we can sort a list by simply calling: java.util.Collections.sort(the list) as shown in the following example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class example {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<Integer>();
ints.add(4);
ints.add(3);
ints.add(7);
ints.add(5);
Collections.sort(ints);
System.out.println(ints);
}
}
The above class creates a list of four integers and, using the collection sort method, sorts this list (in one line of code) without us having to worry about the sorting algorithm.

Java: Create unique List from an existing List keeping index numbers constant

I have two ArrayLists.
List of dates
List of respective data.
Both are synchronized. I sometimes have more than one data on a same date. I need to create two lists: unique dates and the data (averaged) respectively. So far, I have tried the following methods
int i = 1;
for(int it =0; it < predatetime.size() - 1; it++){
//Compare each element with the next one
if(predatetime.get(it+1) == predatetime.get(it)){
i++;
weight = preweight.get(it+1) + weight;
//If equal, add weights and increment a divisor for averaging
}
else { //if not equal, add to the new lists
if(it == predatetime.size() - 2){ //if the last element is not equal to its previous one, just add it to the list
newDateTime.add(predatetime.get(it+1));
newWeight.add(preweight.get(it+1));
break;
}
weight = weight / i;
newDateTime.add(predatetime.get(it));
newWeight.add(weight);
weight = preweight.get(it+1); //re-initialize variables
i = 1;
}
if(it == predatetime.size() - 2){
weight = weight / i;
newDateTime.add(predatetime.get(it));
newWeight.add(weight);
}
}
There are a lot of problems with this code.
If the list has only one element, it fails. (I know I can write 2 more lines to care of this). Is there a better way to do this?
I know there are similar questions on this website, but still I'm unable to resolve the problem.
This is the full solution
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
public class CustomList {
public static void main(String[] args) {
ArrayList<String> date = new ArrayList<>();
date.add("1");
date.add("2");
date.add("2");
date.add("3");
System.out.println(date);
ArrayList<Integer> value = new ArrayList<>();
value.add(1);
value.add(2);
value.add(4);
value.add(3);
System.out.println(value);
new MyCls().createList(date, value);
}
}
class MyCls {
ArrayList uniqueDate = new ArrayList<String>();
ArrayList averageValue = new ArrayList<Integer>();
LinkedHashMap store = new LinkedHashMap<String, CountEntry>();
class CountEntry {
int value;
int count;
CountEntry() {
}
CountEntry(int v, int c) {
value = v;
count = c;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
public void createList(ArrayList<String> date, ArrayList<Integer> value) {
for (int i = 0; i < date.size(); i++) {
CountEntry tmp = (CountEntry) store.get(date.get(i));
if (tmp == null) {
store.put(date.get(i), new CountEntry(value.get(i), 1));
} else {
int tmpVal = tmp.getValue();
int tmpCount = tmp.getCount();
store.put(date.get(i), new CountEntry(value.get(i) + tmpVal, ++tmpCount));
}
}
ArrayList<String> uniqueDate = new ArrayList<String>(store.keySet());
ArrayList<CountEntry> tempAvgList = new ArrayList<CountEntry>(store.values());
for (CountEntry ce : tempAvgList) {
averageValue.add(ce.getValue() / ce.getCount());
}
System.out.println("Output");
System.out.println(uniqueDate);
System.out.println(averageValue);
}
}
/*
OUTPUT Snap:
[1, 2, 2, 3]
[1, 2, 4, 3]
Output
[1, 2, 3]
[1, 3, 3]
*/
If you try to make your list elements unique why you not try to convert the list to set collection
Set<Foo> foo = new HashSet<Foo>(myList);
Why not create a Map instead with the dates as the key and have the value as a list. This will allow you to keep the dates unique, at the same allow you to have your data as a list.
Map<String, ArrayList<myData>> myMap = new HashMap<String, ArrayList<myData>>();
Then you can just find if your key exists, if it does add it to the array list by using the key to identify the correct list. If it doesnt exist it, add it to the map
Thanks to #Rambler and #JulianGurung, I created a HashMap and it works
HashMap<Integer, Float> hm = new HashMap<Integer,Float>();
int occurance = 0;
float weight = 0;
hm.put(predatetime.get(0), 0f); //initialize with the first value
for(Map.Entry m : hm.entrySet()){
for( int it = 0; it < predatetime.size(); it++){
if(m.getKey() == predatetime.get(it)){
weight = (Float) m.getValue() + preweight.get(it); //Sum all the same data in order to avg later
hm.put(predatetime.get(it), weight);
occurance++;
}
else{ //if it is not equal, add the new element to the map
hm.put(predatetime.get(it), preweight.get(it));
}
}
weight = weight / occurance;
hm.put((Integer) m.getKey(), weight);
weight = 0;
occurance = 0;
}

How to create combinations of values in Java?

I have the following map: Map<Integer,String[]> map = new HashMap<Integer,String[]>();
The keys are integers and the values are arrays (could also be replaced by lists).
Now, I would like to get all possible combinations of the values among the keys. For example, let's say the map contains the following entries:
key 1: "test1", "stackoverflow"
key 2: "test2", "wow"
key 3: "new"
The combinations consists of
("test1","test2","new")
("test1","wow","new")
("stackoverflow", "test2", "new")
("stackoverflow", "wow", "new")
For this I imagine a method boolean hasNext() which returns true if there is a next pair and a second method which just returns the next set of values (if any).
How can this be done? The map could also be replaced by an other data structure.
The algorithm is essentially almost the same as the increment algorithm for decimal numbers ("x -> x+1").
Here the iterator class:
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.TreeSet;
public class CombinationsIterator implements Iterator<String[]> {
// Immutable fields
private final int combinationLength;
private final String[][] values;
private final int[] maxIndexes;
// Mutable fields
private final int[] currentIndexes;
private boolean hasNext;
public CombinationsIterator(final Map<Integer,String[]> map) {
combinationLength = map.size();
values = new String[combinationLength][];
maxIndexes = new int[combinationLength];
currentIndexes = new int[combinationLength];
if (combinationLength == 0) {
hasNext = false;
return;
}
hasNext = true;
// Reorganize the map to array.
// Map is not actually needed and would unnecessarily complicate the algorithm.
int valuesIndex = 0;
for (final int key : new TreeSet<>(map.keySet())) {
values[valuesIndex++] = map.get(key);
}
// Fill in the arrays of max indexes and current indexes.
for (int i = 0; i < combinationLength; ++i) {
if (values[i].length == 0) {
// Set hasNext to false if at least one of the value-arrays is empty.
// Stop the loop as the behavior of the iterator is already defined in this case:
// the iterator will just return no combinations.
hasNext = false;
return;
}
maxIndexes[i] = values[i].length - 1;
currentIndexes[i] = 0;
}
}
#Override
public boolean hasNext() {
return hasNext;
}
#Override
public String[] next() {
if (!hasNext) {
throw new NoSuchElementException("No more combinations are available");
}
final String[] combination = getCombinationByCurrentIndexes();
nextIndexesCombination();
return combination;
}
private String[] getCombinationByCurrentIndexes() {
final String[] combination = new String[combinationLength];
for (int i = 0; i < combinationLength; ++i) {
combination[i] = values[i][currentIndexes[i]];
}
return combination;
}
private void nextIndexesCombination() {
// A slightly modified "increment number by one" algorithm.
// This loop seems more natural, but it would return combinations in a different order than in your example:
// for (int i = 0; i < combinationLength; ++i) {
// This loop returns combinations in the order which matches your example:
for (int i = combinationLength - 1; i >= 0; --i) {
if (currentIndexes[i] < maxIndexes[i]) {
// Increment the current index
++currentIndexes[i];
return;
} else {
// Current index at max:
// reset it to zero and "carry" to the next index
currentIndexes[i] = 0;
}
}
// If we are here, then all current indexes are at max, and there are no more combinations
hasNext = false;
}
#Override
public void remove() {
throw new UnsupportedOperationException("Remove operation is not supported");
}
}
Here the sample usage:
final Map<Integer,String[]> map = new HashMap<Integer,String[]>();
map.put(1, new String[]{"test1", "stackoverflow"});
map.put(2, new String[]{"test2", "wow"});
map.put(3, new String[]{"new"});
final CombinationsIterator iterator = new CombinationsIterator(map);
while (iterator.hasNext()) {
System.out.println(
org.apache.commons.lang3.ArrayUtils.toString(iterator.next())
);
}
It prints exactly what's specified in your example.
P.S. The map is actually not needed; it could be replaced by a simple array of arrays (or list of lists). The constructor would then get a bit simpler:
public CombinationsIterator(final String[][] array) {
combinationLength = array.length;
values = array;
// ...
// Reorganize the map to array - THIS CAN BE REMOVED.
I took this as a challenge to see whether the new Java 8 APIs help with these kind of problems. So here's my solution for the problem:
public class CombinatorIterator implements Iterator<Collection<String>> {
private final String[][] arrays;
private final int[] indices;
private final int total;
private int counter;
public CombinatorIterator(Collection<String[]> input) {
arrays = input.toArray(new String[input.size()][]);
indices = new int[arrays.length];
total = Arrays.stream(arrays).mapToInt(arr -> arr.length)
.reduce((x, y) -> x * y).orElse(0);
counter = 0;
}
#Override
public boolean hasNext() {
return counter < total;
}
#Override
public Collection<String> next() {
List<String> nextValue = IntStream.range(0, arrays.length)
.mapToObj(i -> arrays[i][indices[i]]).collect(Collectors.toList());
//rolling carry over the indices
for (int j = 0;
j < arrays.length && ++indices[j] == arrays[j].length; j++) {
indices[j] = 0;
}
counter++;
return nextValue;
}
}
Note that I don't use a map as an input as the map keys actually don't play any role here. You can use map.values() though to pass in the input for the iterator. With the following test code:
List<String[]> input = Arrays.asList(
new String[] {"such", "nice", "question"},
new String[] {"much", "iterator"},
new String[] {"very", "wow"}
);
Iterator<Collection<String>> it = new CombinatorIterator(input);
it.forEachRemaining(System.out::println);
the output will be:
[such, much, very]
[nice, much, very]
[question, much, very]
[such, iterator, very]
[nice, iterator, very]
[question, iterator, very]
[such, much, wow]
[nice, much, wow]
[question, much, wow]
[such, iterator, wow]
[nice, iterator, wow]
[question, iterator, wow]

Comparator to get the maximum value in Linked List with exclude the first element of the Linked List from the comparison

I am trying to extract the maximum value from the LinkedList,but with one condition that I want the first element of the LinkedList being out of the comparison and without relying on the values stored inside the first element.
Can I use the index of the LinkedList or whatever to exclude the first element through the comparison.
This is what I have done but I do not know how implement this condition:
import java.util.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class HelloWorld{
public static void main(String args[]) {
// create a linked list
LinkedList<HashMap<Integer, Integer>> PathList = new LinkedList<HashMap<Integer, Integer>>();
Integer n = new Integer(0);
// add elements to the linked list
for(int i=1; i<4; i++){
HashMap<Integer, Integer> PMap = new HashMap<Integer, Integer>();
PMap.put(1,0);
PMap.put(2,i);
PMap.put(3,2*i);
PathList.add(n,PMap);
n++;
}
Iterator x = PathList.listIterator(0);
// print list with the iterator
while (x.hasNext()) {
HashMap<Integer, Integer> PMap = new HashMap<Integer, Integer>();
PMap = (HashMap<Integer, Integer>)x.next();
System.out.println(PMap.get(3));
}
Comparator<HashMap> cmp = new Comparator<HashMap>() {
#Override
public int compare(HashMap hm1, HashMap hm2) {
return new Integer((Integer)hm1.get(3)).compareTo(new Integer((Integer)hm2.get(3)));
}
};
System.out.println("Max value in this element " + Collections.max(PathList,cmp));
}
}
You can create a sublist from the original list (it is just a view, it doesn't copy all the elements).
So you can change:
System.out.println("Max value in this element " + Collections.max(PathList,cmp));
To:
LinkedList<HashMap<Integer, Integer>> pathListWithoutFirst = PathList.subList(1, PathList.size());
System.out.println("Max value in this element " + Collections.max(pathListWithoutFirst, cmp));
Aside from Collections.max, you can do the implementation your own like this-
public int getMaxValue(LinkedList<Integer> list){
int max = Integer.MIN_VALUE;
/* We used i = 1 below to exclude first element as your needs.
But to include all elements, use i = 0 */
for(int i = 1; i < list.size(); i++){
if(list.get(i) > max){
max = list.get(i);
}
}
return max;
}
Note that calling the above method with zero or one item in the list will return the Integer.MIN_VALUE which is -2147483648.

How to make generic Counting Sort Method?

Okay I am a pretty beginner java coder, and I am doing an assignment where I am stuck. I need to create a generic method (sort) that sorts a Type array according to frequency, basically, I am taking the CountingSort Algorithm and making it a generic method. This is where I am lost. I can't seem to figure out how to do this.
Here is a link to my instructions,
https://classes.cs.siue.edu/pluginfile.php/7068/mod_assign/intro/150mp08.pdf
Code:
Driver Class
package mp08;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Lists array = new Lists();
array.populateLists();
System.out.println("Original Int List: \n");
array.sort(Lists.intList);
System.out.println("Sorted Int List: \n");
}
}
Lists Class
package mp08;
import java.util.Arrays;
import java.util.Random;
public class Lists {
public static Integer[] intList;
public static Integer[] sortedintList;
public static Integer[] frequency;
public static Character[] charList;
public static Character[] sortedcharList;
public static int MAX_SIZE = 101;
public static int lengthInt;
public static int lengthChar;
public Lists(){
this.intList = new Integer[MAX_SIZE];
this.sortedintList = new Integer[MAX_SIZE];
this.charList = new Character[MAX_SIZE];
this.sortedcharList = new Character[MAX_SIZE];
this.frequency = new Integer[MAX_SIZE];
this.lengthInt = 0;
this.lengthChar = 0;
}
//Makes random integer for populated lists method.
public int randomInt(int min, int max){
Random rand = new Random();
int randomNum = rand.nextInt((max-min)+1)+min;
return randomNum;
}
//Makes random character for populated lists method.
public char randomChar(){
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = alphabet.length();
Random rand = new Random();
char randomLet = alphabet.charAt(rand.nextInt(N));
return randomLet;
}
//Populates intList and charList with random values.
public void populateLists(){
for (int i = 0; i < MAX_SIZE; i++) {
intList[i] = randomInt(1,100);
lengthInt++;
}
for (int i = 0; i < MAX_SIZE; i++) {
charList[i] = randomChar();
lengthChar++;
}
}
//Returns sorted array
public Integer[] sorted(){
return intList;
}
public static <T> void sort(T[] array) {
// array to be sorted in, this array is necessary
// when we sort object datatypes, if we don't,
// we can sort directly into the input array
Integer[] aux = new Integer[array.length];
// find the smallest and the largest value
int min = 1;
int max = 101;
// init array of frequencies
int[] counts = new int[max - min + 1];
// init the frequencies
for (int i = 0; i < array.length; i++) {
counts[array[i] - min]++;
}
// recalculate the array - create the array of occurence
counts[0]--;
for (int i = 1; i < counts.length; i++) {
counts[i] = counts[i] + counts[i-1];
}
/*
Sort the array right to the left
1) Look up in the array of occurences the last occurence of the given value
2) Place it into the sorted array
3) Decrement the index of the last occurence of the given value
4) Continue with the previous value of the input array (goto set1),
terminate if all values were already sorted
*/
for (int i = array.length - 1; i >= 0; i--) {
aux[counts[array[i] - min]--] = array[i];
}
}
public static void main(String[] args) {
Integer [] unsorted = {5,3,0,2,4,1,0,5,2,3,1,4};
System.out.println("Before: " + Arrays.toString(unsorted));
Integer [] sorted = sort(unsorted);
System.out.println("After: " + Arrays.toString(sorted));
}
}
I obviously have not finished my driver class yet and I would appreciate any help I can get!
There's no generic way for any Comparable type to get its ordinal number. Sometimes such numbers do not exist at all (for example, String is Comparable, but you cannot map any String to the integer number). I can propose two solutions.
First one is to store counts not in the array, but in TreeMap instead creating new entries on demand (using Java-8 syntax for brevity):
public static <T extends Comparable<T>> void sort(T[] array) {
Map<T, Integer> counts = new TreeMap<>();
for(T t : array) {
counts.merge(t, 1, Integer::sum);
}
int i=0;
for(Map.Entry<T, Integer> entry : counts.entrySet()) {
for(int j=0; j<entry.getValue(); j++)
array[i++] = entry.getKey();
}
}
public static void main(String[] args) {
Integer[] data = { 5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4 };
System.out.println("Before: " + Arrays.toString(data));
sort(data);
System.out.println("After: " + Arrays.toString(data));
Character[] chars = { 'A', 'Z', 'B', 'D', 'F' };
System.out.println("Before: " + Arrays.toString(chars));
sort(chars);
System.out.println("After: " + Arrays.toString(chars));
}
Such solution looks clean, but probably not very optimal (though its advantage is that it does not care whether all numbers are from 1 to 100 or not).
Another possible solution is to create some additional interface which defines ordering for given type:
public interface Ordering<T> {
int toOrdinal(T obj);
T toObject(int ordinal);
}
public class IntegerOrdering implements Ordering<Integer> {
#Override
public int toOrdinal(Integer obj) {
return obj;
}
#Override
public Integer toObject(int ordinal) {
return ordinal;
}
}
public class CharacterOrdering implements Ordering<Character> {
#Override
public int toOrdinal(Character obj) {
return obj;
}
#Override
public Character toObject(int ordinal) {
return (char)ordinal;
}
}
Now you may make your sort method accepting the ordering parameter:
public static <T> void sort(T[] array, Ordering<T> ordering) { ... }
Every time you need to get counts array index by T object, just call ordering.toOrdinal(object). Every time you need to get object by array index, just use ordering.toObject(index). So, for example, instead of
counts[array[i] - min]++;
Use
counts[ordering.toOrdinal(array[i]) - min]++;
And call the sorting method like this:
sort(characterArray, new CharacterOrdering());
sort(integerArray, new IntegerOrdering());

Categories