collections.sort compare selectItem - sorting

i have a Problem and i hope you can help me,
i have a list of SelectItem to ordern
the inital order is:
geschieden
ledig
unbekannt
verheiratet
verwitwet
and i will the list like:
ledig
verheiratet
geschieden
verwitwet
unbekannt
i have the method implementiert but i don t have the right order:
public List getFamilienstandSelectItems()
{
List getFamilienstandSelectItems =TK_Familienstand_DS_Values.getInstance().getSelectItems();
Collections.sort(getFamilienstandSelectItems , new Comparator<SelectItem>()
{
public int compare(SelectItem s1, SelectItem s2)
{
if (s1.getLabel()=="ledig")
{
return 0;}
else if (s1.getLabel()=="verheiratet" )
{ return 0;}
else if (s2.getLabel()=="geschieden" )
{ return 1;}
else if (s2.getLabel()=="unbekannt" )
{ return -1;}
else if (s2.getLabel()=="verwitwet " )
{ return 0;}
else return 1;
} });
return getFamilienstandSelectItems;
}
and the result of this method:
ledig
verheiratet
geschieden
unbekannt
verwitwet
something is missing??
thank you

The compare method should tell us, of the two items that I'm comparing right now, which one should come first? Negative numbers means that the second item should come first, 0 means that they are equal and positive numbers means that the first item should come first.
So give each item type a number and create a function
public int getPriority(SelectItem item) {
// Give higher values to the items that should come first
}
and then do something like this in your compare method
public int compare(SelectItem s1, SelectItem s2) {
return Integer.compare(getPriority(s1),getPriority(s2));
}

Related

Sort a list of Flutter widgets using my own compare function

I'm building a TODO application using Flutter.
What I need to do is to sort tasks stored in List using my own compare method (completed tasks must be at the bottom).
The list I need to sort:
var taskWidgets = List<Widget>();
Elements of taskWidgets list are TaskCard class objects
class TaskCard extends StatefulWidget {
My compare method:
int compareTasks(TaskCard a, TaskCard b) {
if (a.state._checked == b.state._checked) {
return 0;
}
if (a.state._checked && !b.state._checked) {
return 1;
}
return -1;
}
This is how I sort my list:
taskWidgets.sort(compareTasks);
After doing all that I get the following error:
type '(TaskCard, TaskCard) => int' is not a subtype of type '((Widget, Widget) => int)?'
I tried to change compare function
int compareTasks(Widget a, Widget b) {
if (a.state._checked == b.state._checked) {
return 0;
}
if (a.state._checked && !b.state._checked) {
return 1;
}
return -1;
}
But then I got another error
lib/main.dart:98:11: Error: The getter 'state' isn't defined for the class 'Widget'.
- 'Widget' is from 'package:flutter/src/widgets/framework.dart' ('../../AppData/flutter/packages/flutter/lib/src/widgets/framework.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'state'.
if (a.state._checked == b.state._checked) {
So all in all, the question is:
How do I properly sort a List of TaskCard objects using my own compare function?
in the case you know all taskWidgets elements are of the type TaskCard you can change taskWidgets to be of type List<TaskCard> in order to make your first compare method work.
if you want to keep your list of type List<Widget>, you need to manualy check if your widgets are of type Taskcard, and take in to consideration the case in which they aren't:
int compareTasks(Widget a, Widget b) {
if (!(a is TaskCard)) {
return -1; // if a is not of type Taskcard, make it go before b
}
if (!(b is TaskCard)) {
return 1; // if a is a TaskCard and b is not Taskcard, make b go before a
}
TaskCard taskA = a as TaskCard;
TaskCard taskB = b as TaskCard;
if (taskA.state._checked == taskB.state._checked) {
return 0;
}
if (taskA.state._checked && !taskB.state._checked) {
return 1;
}
return -1;
}

Compare most recent values from multiple BehaviorSubjects

Say I have this:
isMatchedCountLessThanTotalCountMessage(){
// I want to implement this
// "returns" a string asynchronously
}
getMatchedEventsCount() {
return this.dcs.matchCount.asObservable();
}
getTotalEventsCount() {
return this.dcs.totalCount.asObservable();
}
matchedCount and totalCount are like so:
public matchCount = new BehaviorSubject<number>(0);
public totalCount = new BehaviorSubject<number>(0);
these Observables fire integers as values change. Anytime a value is fired from either one, I want to compare the two most recent values from both, how do I do that?
What I want to do is return a boolean from the method
so I can display in the HTML:
<div>{{(isMatchedCountLessThanTotalCountMessage() | async)}}</div>
I think Observable.zip might do the trick:
isMatchedCountLessThanTotalCountMessage(){
return Observable.zip(
this.getMatchedEventsCount(),
this.getTotalEventsCount()
)
.subscribe(function(v){
const intA = v[0];
const intB = v[1];
if(intA > intB)
// but I don't know how to send a message the HTML from here
});
}
You can easily use .map() function to transform the data you want:
isMatchedCountLessThanTotalCountMessage() {
return Observable.combineLatest(
this.getMatchedEventsCount(),
this.getTotalEventsCount(),
)
.map(([intA, intB]) => {
return intA > intB ? '(results ARE filtered)' : '(results are not filtered)'
})
}
This works, although we might be able to use something other than Observable.zip.
isMatchedCountLessThanTotalCount() {
return Observable.create(obs => {
return Observable.zip(
this.getMatchedEventsCount(),
this.getTotalEventsCount()
)
.subscribe(v => {
if ((v[1] - v[0]) > 0) {
obs.next('(results ARE filtered)')
}
else {
obs.next('(results are not filtered)');
}
});
});
}
and there is actually a simpler way to do that using what's called a "projection function":
isMatchedCountLessThanTotalCount() {
return Observable.combineLatest(
this.getMatchedEventsCount(),
this.getTotalEventsCount(),
function (one, two) {
if ((two - one) > 0) {
return '(results ARE filtered)'
}
return '(results are not filtered)';
}
)
}
Observable.combineLatest() is similar to Observable.zip() but will fire upon the first new value, it doesn't wait for new values to come from all observables.

Two sum data structure problems

I built a data structure for two sum question. In this data structure I built add and find method.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example:
add(1); add(3); add(5);
find(4) // return true
find(7) // return false
the following is my code, so what is wrong with this code?
http://www.lintcode.com/en/problem/two-sum-data-structure-design/
this is the test website, some cases could not be passed
public class TwoSum {
private List<Integer> sets;
TwoSum() {
this.sets = new ArrayList<Integer>();
}
// Add the number to an internal data structure.
public void add(int number) {
// Write your code here
this.sets.add(number);
}
// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
// Write your code here
Collections.sort(sets);
for (int i = 0; i < sets.size(); i++) {
if (sets.get(i) > value) break;
for (int j = i + 1; j < sets.size(); j++) {
if (sets.get(i) + sets.get(j) == value) {
return true;
}
}
}
return false;
}
}
There does not seem to be anything wrong with your code.
However a coding challenge could possibly require a more performant solution. (You check every item against every item, which would take O(N^2)).
The best solution to implement find, is using a HashMap, which would take O(N). It's explained more in detail here.

LINQ ToList() causes all records to be the last one off a coroutine

I seem to have an misunderstanding because the following code works correctly if I don't append the ToList() command:
IEnumerable<ProcessorInfo> query = (
from n in InfoGet(EMachineInfoDepth.LogicalProcessor)
select n
)
.ToList();
InfoGet looks like this:
internal static IEnumerable<ProcessorInfo> InfoGet(EMachineInfoDepth depth)
{
ProcessorInfo result = new ProcessorInfo();
// loop through all workgroups
foreach (Workgroup wg in workgroups_S)
{
result.Workgroup = wg;
if (depth >= EMachineInfoDepth.NUMANode)
{
// loop through all NUMANodes
foreach (NUMANode node in wg.NUMANodes)
{
result.NUMANode = node;
if (depth >= EMachineInfoDepth.CPU)
{
// loop through all CPUs
foreach (CPU cpu in node.CPUs)
{
result.CPU = cpu;
if (depth >= EMachineInfoDepth.Core)
{
// loop through all Cores
foreach (Core core in cpu.Cores)
{
result.Core = core;
if (depth >= EMachineInfoDepth.LogicalProcessor)
{
// loop through all LogicalProcessors
foreach (LogicalProcessor lp in core.LogicalProcessors)
{
result.LogicalProc = lp;
yield return result;
}
}
else
{
yield return result;
}
}
}
else
{
yield return result;
}
}
}
else
{
yield return result;
}
}
}
else
{
yield return result;
}
}
}
With ToList() I get the correct count, but all records equal the final element in the sequence. While I get that this could be a variable scope error in my complex coroutine, as in all iterations see the final value, why does the code work without ToList()?
My question is: what am I misunderstanding?
Problem is, you're returning reference to the same variable all the time:
ProcessorInfo result = new ProcessorInfo();
That's the only place you're actually creating new ProcessorInfo object. You only change it's properties values later, but return still the same object.
You should consider adding copy constructor into your ProcessorInfo() class, and replace every yield return result; call with yield return new ProcessorInfo(result);. That would be the easiest way to make it work.
Update
It could look like it works e.g. when you've saved some variable state somewhere during loop:
foreach(var item in query)
{
itemsList.Add(item);
propertyList.Add(item.IntProperty);
}
After that call itemsList will contain incorrect data, while propertyList will be just fine.

What does ExpressionVisitor.Visit<T> Do?

Before someone shouts out the answer, please read the question through.
What is the purpose of the method in .NET 4.0's ExpressionVisitor:
public static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor)
My first guess as to the purpose of this method was that it would visit each node in each tree specified by the nodes parameter and rewrite the tree using the result of the elementVisitor function.
This does not appear to be the case. Actually this method appears to do a little more than nothing, unless I'm missing something here, which I strongly suspect I am...
I tried to use this method in my code and when things didn't work out as expected, I reflectored the method and found:
public static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor)
{
T[] list = null;
int index = 0;
int count = nodes.Count;
while (index < count)
{
T objA = elementVisitor(nodes[index]);
if (list != null)
{
list[index] = objA;
}
else if (!object.ReferenceEquals(objA, nodes[index]))
{
list = new T[count];
for (int i = 0; i < index; i++)
{
list[i] = nodes[i];
}
list[index] = objA;
}
index++;
}
if (list == null)
{
return nodes;
}
return new TrueReadOnlyCollection<T>(list);
}
So where would someone actually go about using this method? What am I missing here?
Thanks.
It looks to me like a convenience method to apply an aribitrary transform function to an expression tree, and return the resulting transformed tree, or the original tree if there is no change.
I can't see how this is any different of a pattern that a standard expression visitor, other than except for using a visitor type, it uses a function.
As for usage:
Expression<Func<int, int, int>> addLambdaExpression= (a, b) => a + b;
// Change add to subtract
Func<Expression, Expression> changeToSubtract = e =>
{
if (e is BinaryExpression)
{
return Expression.Subtract((e as BinaryExpression).Left,
(e as BinaryExpression).Right);
}
else
{
return e;
}
};
var nodes = new Expression[] { addLambdaExpression.Body }.ToList().AsReadOnly();
var subtractExpression = ExpressionVisitor.Visit(nodes, changeToSubtract);
You don't explain how you expected it to behave and why therefore you think it does little more than nothing.

Resources