Sorting Arraylist by an object variable - sorting

Any ideas on how to apply Collections.sort method to sort my arraylist by priority of each grocItem object within the itemData ArrayList?
public class GroceryProgram {
private final static int GROC_SIZE = 6;
private final List<ItemData> itemData = new ArrayList<ItemData>();
private void setUpList() {
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < GROC_SIZE; i++) {
System.out.print("\nEnter item name (" + i + ") : ");
String name = keyboard.next();
System.out.print("\nEnter the price of item (" + i + ") : ");
double cost = keyboard.nextDouble();
System.out.print("\nEnter Priority Number (" + i + ") : ");
int priority = keyboard.nextInt();
ItemData grocItem = new ItemData(name, cost, priority);
itemData.add(grocItem); // add grocery items to itemData ArrayList
Collections.sort(grocItem);
for (Int priority : priority) {
System.out.println(integer);

Call sort() with a Comparator. For example, a Comparator in ascending-order of priority could look like this.
Collections.sort( items, new Comparator<ItemData>() {
public int compare (ItemData o1, ItemData o2) {
int comp = o1.getPriority() - o2.getPriority();
return comp;
}
});
PS: 'itemData' is bad variable naming -- it would refer to a single item, not a list. 'groceryItems', 'stockItems' or 'itemList' would be better.
Variable names should enable you to speak in meaningful, clear, concise English about your software.
Hope this helps.

Could you use Collections.sort(List list, Comparator c) to deal with this? You could simply do the following :
Collections.sort(itemData, new Comparator() {
public int compare(Object o1, Object o2) {
// Return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
}
}

You can use custom comparator as below:
Collections.sort(itemData ,new PriorityComparator());
//print sorted arraylist,it will print the data in ascending order (low priority->high priority).feel free to modify if you want to go for descending order
System.out.println(itemData );
PriorityComparator class definition:
private static class PriorityComparator implements Comparator{
#Override
public int compare(ItemData object1, ItemData object2) {
return (object1.priority< object2.priority) ? -1: (object1.priority> object2.priority) ? 1:0 ;
}
}
Reference:
how-to-sort-arraylist-in-java-example
I hope it will be helpful !!

Related

Subset sum with positive and negative integers

I've to implement a variation of the subset sum problem, my input will be positive and negative decimal, also I will need to know the subset, knowing that exists unfortunately it's not enough.
I've tried the algorithms found on wikipedia, but I can't make them work with negative numbers, and also I can't find the way to obtain the subset if it exists.
Could anyone point me where I could find some pseudo-code, documentation or implementation, for this algorithm.
I wrote the code in Java
it checks all the possibilities
import java.util.*;
public class StackOverFlow {
public static <T> Set<Set<T>> powerSet(Set<T> originalSet) {
Set<Set<T>> sets = new HashSet<Set<T>>();
if (originalSet.isEmpty()) {
sets.add(new HashSet<T>());
return sets;
}
List<T> list = new ArrayList<T>(originalSet);
T head = list.get(0);
Set<T> rest = new HashSet<T>(list.subList(1, list.size()));
for (Set<T> set : powerSet(rest)) {
Set<T> newSet = new HashSet<T>();
newSet.add(head);
newSet.addAll(set);
sets.add(newSet);
sets.add(set);
}
return sets;
}
public static int sumSet(Set<Integer> set){
int sum =0;
for (Integer s : set) {
sum += s;
}
return sum;
}
public static void main(String[] args) {
Set<Integer> mySet = new HashSet<Integer>();
mySet.add(-1);
mySet.add(2);
mySet.add(3);
int mySum = 4;
for (Set<Integer> s : powerSet(mySet)) {
if(mySum == sumSet(s))
System.out.println(s + " = " + sumSet(s));
}
}
}
I hope it helps

ArrayList Comparator compareTo

I have an arraylist of Processes in which i want to sort them according to their arrival time the problem is that I can't seem to code my Comparator well. Below is my code:
ArrayList<Process> pArray = new ArrayList<>();
for(int x = 0; x<processTable.getRowCount(); x++){
int pID = Integer.parseInt(processTable.getValueAt(x,0).toString());
int aT = Integer.parseInt(processTable.getValueAt(x,1).toString());
int bT = Integer.parseInt(processTable.getValueAt(x,2).toString());
Process temp = new Process(bT, aT, pID);
totalBT += bT;
pArray.add(temp);
}
//sort by arrival time
Collections.sort(pArray, new Comparator<Process>(){
int compare(Process o1, Process o2) {
return o1.getAt() - o2.getAt();
}
boolean equals(Process obj) {
}
});
try{
System.out.print("ha");
pArray = doRR(new Integer(rr1Q.getValue().toString()), pArray, totalBT);
}catch(InterruptedException ie){
System.out.println("Process ended due to interruption");
}
The following error pops up:
compare(Process,Process) in <anonymous my.CpuGui.CpuGui$ButtonHandler$1> cannot implement compare(T,T) in Comparator
int compare(Process o1, Process o2) {
Can anyone explain what it says?
I'm not sure the error message is verbatim what I would expect, but your compare method cannot reduce the visibility of the method defined in the interface.
Declare compare as public and it should work (after you get rid of the pointless and erroneous equals method of course).
Collections.sort(pArray, new Comparator<Process>(){
public int compare(Process o1, Process o2) {
return o1.getAt() - o2.getAt();
}
});

Keyword Search for ListField in Blackberry

I am creating a ListField. in each row of I am adding a image and 3 labelfield.
Can any one tell me how to create a keywordfilterField for this...
Thanks in advance
I am new to blackberry.
Little code will help me alot
This is my code for creating a custom list
class CustomListField extends ListField implements ListFieldCallback
{
String type;
int DISPLAY_WIDTH = Display.getWidth();
int DISPLAY_HEIGHT = Display.getHeight();
Vector mItems = new Vector();
Vector mine = new Vector();
Vector three= new Vector();
// SizedVFM mListManager = new SizedVFM(DISPLAY_WIDTH, DISPLAY_HEIGHT - 40);
Bitmap searchresult = Bitmap.getBitmapResource("res/searchresult.png");
HorizontalFieldManager hfManager;
Bitmap image ,image1;
int z = this.getRowHeight();
CustomListField(String text1,String text2,String type)
{
for (int i = 1; i < 31; i++)
{
mItems.addElement(text1 +String.valueOf(i));
mine.addElement(" "+text2);
three.addElement("31");
}
this.type=type;
this.setRowHeight((2*z));
this.setCallback(this);
this.setSize(20);
//mListManager.add(mListField);
//add(mListManager);
}
public void drawListRow(ListField field, Graphics g, int i, int y, int w)
{
// Draw the text.
image = Bitmap.getBitmapResource("res/searchresult.png");
String text = (String) get(field, i);
String mytext = (String)mine.elementAt(i);
String urtext=(String)three.elementAt(i);
g.drawBitmap(0, y, image.getWidth(),image.getHeight(), image, 0, 0);
g.drawText(text, image.getWidth(), y, 0, w);
g.setColor(Color.GRAY);
g.drawText(mytext, image.getWidth(), y+getFont().getHeight(), 0, w);
g.drawText(urtext,Graphics.getScreenWidth()*7/8,y,0,w);
if (i != 0)
{
g.drawLine(0, y, w, y);
}
}
public Object get(ListField listField, int index)
{
return mItems.elementAt(index);
}
public int getPreferredWidth(ListField listField)
{
return DISPLAY_WIDTH;
}
public int indexOfList(ListField listField, String prefix, int start)
{
return 0;
}
protected boolean touchEvent(TouchEvent message)
{
// If click, process Field changed
if ( message.getEvent() == TouchEvent.CLICK )
{
if(type.equals("Stops"))
UiApplication.getUiApplication().pushScreen(new SearchScreen("Services"));
else if(type.equals("Services"))
UiApplication.getUiApplication().pushScreen(new SearchScreen("Stops"));
return true;
}
return super.touchEvent(message);
}
}
The problem with KeywordFilterField is that it uses internally its own ListField, so I think it is going to be difficult to customize. If you wanted to use it as it is provided, you'll have to use it as follows:
//KeywordFilterField contains a ListField to display and a search edit field to type in the words
KeywordFilterField keywordFilterField = new KeywordFilterField();
//Instantiate the sorted collection:
CustomList cl = new CustomList(mItems);
//Pass the custom collection
keywordFilterField.setSourceList(cl, cl);
//Now you have to add two fields: first the list itself
myManager.add(keywordFilterField);
//And the search field, probably you'd want it at top:
myScreen.setTitle(keywordFilterField.getKeywordField());
You'll have to implement a custom sortable collection to hold the items you wan't to display:
class CustomList extends SortedReadableList implements KeywordProvider {
//In constructor, call super constructor with a comparator of <yourClass>
public CustomList(Vector elements)
{
super(new <yourClass>Comparator()); //pass comparator to sort
loadFrom(elements.elements());
}
//Interface implementation
public String[] getKeywords( Object element )
{
if(element instanceof <yourClass> )
{
return StringUtilities.stringToWords(element.toString());
}
return null;
}
void addElement(Object element)
{
doAdd(element);
}
//...
}
You have a full demo available inside the JDE samples folder. It is called keywordfilterdemo.
To use a custom list like the one you posted, you'll probably have to code a lot of stuff, like a custom EditField to type in the keywords receiving events on every typed character, linked to a search on a sortered collection (maybe you could use a SortedReadableList for this) which will select in your ListField the first search result returned by this collection.

Lossless hierarchical run length encoding

I want to summarize rather than compress in a similar manner to run length encoding but in a nested sense.
For instance, I want : ABCBCABCBCDEEF to become: (2A(2BC))D(2E)F
I am not concerned that an option is picked between two identical possible nestings E.g.
ABBABBABBABA could be (3ABB)ABA or A(3BBA)BA which are of the same compressed length, despite having different structures.
However I do want the choice to be MOST greedy. For instance:
ABCDABCDCDCDCD would pick (2ABCD)(3CD) - of length six in original symbols which is less than ABCDAB(4CD) which is length 8 in original symbols.
In terms of background I have some repeating patterns that I want to summarize. So that the data is more digestible. I don't want to disrupt the logical order of the data as it is important. but I do want to summarize it , by saying, symbol A times 3 occurrences, followed by symbols XYZ for 20 occurrences etc. and this can be displayed in a nested sense visually.
Welcome ideas.
I'm pretty sure this isn't the best approach, and depending on the length of the patterns, might have a running time and memory usage that won't work, but here's some code.
You can paste the following code into LINQPad and run it, and it should produce the following output:
ABCBCABCBCDEEF = (2A(2BC))D(2E)F
ABBABBABBABA = (3A(2B))ABA
ABCDABCDCDCDCD = (2ABCD)(3CD)
As you can see, the middle example encoded ABB as A(2B) instead of ABB, you would have to make that judgment yourself, if single-symbol sequences like that should be encoded as a repeated symbol or not, or if a specific threshold (like 3 or more) should be used.
Basically, the code runs like this:
For each position in the sequence, try to find the longest match (actually, it doesn't, it takes the first 2+ match it finds, I left the rest as an exercise for you since I have to leave my computer for a few hours now)
It then tries to encode that sequence, the one that repeats, recursively, and spits out a X*seq type of object
If it can't find a repeating sequence, it spits out the single symbol at that location
It then skips what it encoded, and continues from #1
Anyway, here's the code:
void Main()
{
string[] examples = new[]
{
"ABCBCABCBCDEEF",
"ABBABBABBABA",
"ABCDABCDCDCDCD",
};
foreach (string example in examples)
{
StringBuilder sb = new StringBuilder();
foreach (var r in Encode(example))
sb.Append(r.ToString());
Debug.WriteLine(example + " = " + sb.ToString());
}
}
public static IEnumerable<Repeat<T>> Encode<T>(IEnumerable<T> values)
{
return Encode<T>(values, EqualityComparer<T>.Default);
}
public static IEnumerable<Repeat<T>> Encode<T>(IEnumerable<T> values, IEqualityComparer<T> comparer)
{
List<T> sequence = new List<T>(values);
int index = 0;
while (index < sequence.Count)
{
var bestSequence = FindBestSequence<T>(sequence, index, comparer);
if (bestSequence == null || bestSequence.Length < 1)
throw new InvalidOperationException("Unable to find sequence at position " + index);
yield return bestSequence;
index += bestSequence.Length;
}
}
private static Repeat<T> FindBestSequence<T>(IList<T> sequence, int startIndex, IEqualityComparer<T> comparer)
{
int sequenceLength = 1;
while (startIndex + sequenceLength * 2 <= sequence.Count)
{
if (comparer.Equals(sequence[startIndex], sequence[startIndex + sequenceLength]))
{
bool atLeast2Repeats = true;
for (int index = 0; index < sequenceLength; index++)
{
if (!comparer.Equals(sequence[startIndex + index], sequence[startIndex + sequenceLength + index]))
{
atLeast2Repeats = false;
break;
}
}
if (atLeast2Repeats)
{
int count = 2;
while (startIndex + sequenceLength * (count + 1) <= sequence.Count)
{
bool anotherRepeat = true;
for (int index = 0; index < sequenceLength; index++)
{
if (!comparer.Equals(sequence[startIndex + index], sequence[startIndex + sequenceLength * count + index]))
{
anotherRepeat = false;
break;
}
}
if (anotherRepeat)
count++;
else
break;
}
List<T> oneSequence = Enumerable.Range(0, sequenceLength).Select(i => sequence[startIndex + i]).ToList();
var repeatedSequence = Encode<T>(oneSequence, comparer).ToArray();
return new SequenceRepeat<T>(count, repeatedSequence);
}
}
sequenceLength++;
}
// fall back, we could not find anything that repeated at all
return new SingleSymbol<T>(sequence[startIndex]);
}
public abstract class Repeat<T>
{
public int Count { get; private set; }
protected Repeat(int count)
{
Count = count;
}
public abstract int Length
{
get;
}
}
public class SingleSymbol<T> : Repeat<T>
{
public T Value { get; private set; }
public SingleSymbol(T value)
: base(1)
{
Value = value;
}
public override string ToString()
{
return string.Format("{0}", Value);
}
public override int Length
{
get
{
return Count;
}
}
}
public class SequenceRepeat<T> : Repeat<T>
{
public Repeat<T>[] Values { get; private set; }
public SequenceRepeat(int count, Repeat<T>[] values)
: base(count)
{
Values = values;
}
public override string ToString()
{
return string.Format("({0}{1})", Count, string.Join("", Values.Select(v => v.ToString())));
}
public override int Length
{
get
{
int oneLength = 0;
foreach (var value in Values)
oneLength += value.Length;
return Count * oneLength;
}
}
}
public class GroupRepeat<T> : Repeat<T>
{
public Repeat<T> Group { get; private set; }
public GroupRepeat(int count, Repeat<T> group)
: base(count)
{
Group = group;
}
public override string ToString()
{
return string.Format("({0}{1})", Count, Group);
}
public override int Length
{
get
{
return Count * Group.Length;
}
}
}
Looking at the problem theoretically, it seems similar to the problem of finding the smallest context free grammar which generates (only) the string, except in this case the non-terminals can only be used in direct sequence after each other, so e.g.
ABCBCABCBCDEEF
s->ttDuuF
t->Avv
v->BC
u->E
ABABCDABABCD
s->ABtt
t->ABCD
Of course, this depends on how you define "smallest", but if you count terminals on the right side of rules, it should be the same as the "length in original symbols" after doing the nested run-length encoding.
The problem of the smallest grammar is known to be hard, and is a well-studied problem. I don't know how much the "direct sequence" part adds to or subtracts from the complexity.

Partition/split/section IEnumerable<T> into IEnumerable<IEnumerable<T>> based on a function using LINQ?

I'd like to split a sequence in C# to a sequence of sequences using LINQ. I've done some investigation, and the closest SO article I've found that is slightly related is this.
However, this question only asks how to partition the original sequence based upon a constant value. I would like to partition my sequence based on an operation.
Specifically, I have a list of objects which contain a decimal property.
public class ExampleClass
{
public decimal TheValue { get; set; }
}
Let's say I have a sequence of ExampleClass, and the corresponding sequence of values of TheValue is:
{0,1,2,3,1,1,4,6,7,0,1,0,2,3,5,7,6,5,4,3,2,1}
I'd like to partition the original sequence into an IEnumerable<IEnumerable<ExampleClass>> with values of TheValue resembling:
{{0,1,2,3}, {1,1,4,6,7}, {0,1}, {0,2,3,5,7}, {6,5,4,3,2,1}}
I'm just lost on how this would be implemented. SO, can you help?
I have a seriously ugly solution right now, but have a "feeling" that LINQ will increase the elegance of my code.
Okay, I think we can do this...
public static IEnumerable<IEnumerable<TElement>>
PartitionMontonically<TElement, TKey>
(this IEnumerable<TElement> source,
Func<TElement, TKey> selector)
{
// TODO: Argument validation and custom comparisons
Comparer<TKey> keyComparer = Comparer<TKey>.Default;
using (var iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
yield break;
}
TKey currentKey = selector(iterator.Current);
List<TElement> currentList = new List<TElement> { iterator.Current };
int sign = 0;
while (iterator.MoveNext())
{
TElement element = iterator.Current;
TKey key = selector(element);
int nextSign = Math.Sign(keyComparer.Compare(currentKey, key));
// Haven't decided a direction yet
if (sign == 0)
{
sign = nextSign;
currentList.Add(element);
}
// Same direction or no change
else if (sign == nextSign || nextSign == 0)
{
currentList.Add(element);
}
else // Change in direction: yield current list and start a new one
{
yield return currentList;
currentList = new List<TElement> { element };
sign = 0;
}
currentKey = key;
}
yield return currentList;
}
}
Completely untested, but I think it might work...
alternatively with linq operators and some abuse of .net closures by reference.
public static IEnumerable<IEnumerable<T>> Monotonic<T>(this IEnumerable<T> enumerable)
{
var comparator = Comparer<T>.Default;
int i = 0;
T last = default(T);
return enumerable.GroupBy((value) => { i = comparator.Compare(value, last) > 0 ? i : i+1; last = value; return i; }).Select((group) => group.Select((_) => _));
}
Taken from some random utility code for partitioning IEnumerable's into a makeshift table for logging. If I recall properly, the odd ending Select is to prevent ambiguity when the input is an enumeration of strings.
Here's a custom LINQ operator which splits a sequence according to just about any criteria. Its parameters are:
xs: the input element sequence.
func: a function which accepts the "current" input element and a state object, and returns as a tuple:
a bool stating whether the input sequence should be split before the "current" element; and
a state object which will be passed to the next invocation of func.
initialState: the state object that gets passed to func on its first invocation.
Here it is, along with a helper class (required because yield return apparently cannot be nested):
public static IEnumerable<IEnumerable<T>> Split<T, TState>(
this IEnumerable<T> xs,
Func<T, TState, Tuple<bool, TState>> func,
TState initialState)
{
using (var splitter = new Splitter<T, TState>(xs, func, initialState))
{
while (splitter.HasNext)
{
yield return splitter.GetNext();
}
}
}
internal sealed class Splitter<T, TState> : IDisposable
{
public Splitter(IEnumerable<T> xs,
Func<T, TState, Tuple<bool, TState>> func,
TState initialState)
{
this.xs = xs.GetEnumerator();
this.func = func;
this.state = initialState;
this.hasNext = this.xs.MoveNext();
}
private readonly IEnumerator<T> xs;
private readonly Func<T, TState, Tuple<bool, TState>> func;
private bool hasNext;
private TState state;
public bool HasNext { get { return hasNext; } }
public IEnumerable<T> GetNext()
{
while (hasNext)
{
Tuple<bool, TState> decision = func(xs.Current, state);
state = decision.Item2;
if (decision.Item1) yield break;
yield return xs.Current;
hasNext = xs.MoveNext();
}
}
public void Dispose() { xs.Dispose(); }
}
Note: Here are some of the design decisions that went into the Split method:
It should make only a single pass over the sequence.
State is made explicit so that it's possible to keep side effects out of func.

Resources