AS3: Sort Two Fields - sorting

PLEASE NEED HELP
This is what I'm doing:
var my_array_W:Array = new Array();
my_array_W.push({cor:Acorrect, tem:AnewTime, tab: "TB_A", nom:Aoseasnnombre});
my_array_W.push({cor:Bcorrect, tem:BnewTime, tab: "TB_B", nom:Boseasnnombre});
my_array_W.push({cor:Ccorrect, tem:CnewTime, tab: "TB_C", nom:Coseasnnombre});
my_array_W.push({cor:Dcorrect, tem:DnewTime, tab: "TB_D", nom:Doseasnnombre});
my_array_W.push({cor:Ecorrect, tem:EnewTime, tab: "TB_E", nom:Eoseasnnombre});
my_array_W.push({cor:Fcorrect, tem:FnewTime, tab: "TB_F", nom:Foseasnnombre});
This Output:
[tab] | [cor] | [tem]
TB_A 3 8.6877651541
TB_B 4 12.9287651344
TB_C 1 6199.334999999999923
TB_D 4 33.6526718521
TB_E 4 31.90468496844
TB_F 1 6.334999999923
So then I sort:
my_array_W.sortOn("tem", Array.NUMERIC);
my_array_W.sortOn("cor", Array.NUMERIC | Array.DESCENDING);
And Geting this T_T :
[tab] | [cor] | [tem]
TB_E 4 31.90468496844
TB_D 4 33.6526718521
TB_B 4 12.9287651344
TB_A 3 8.6877651541
TB_F 1 31.90468496844
TB_C 1 6199.334999999999923
I just wanna sort a Winner Table by Time(the less) and Correct(the high)
So the Winner is the One who make more correct answers in less time.
I really try so hard to get a sort like this:
[tab] | [cor] | [tem]
TB_B 4 12.9287651344
TB_E 4 31.90468496844
TB_D 4 33.6526718521
TB_A 3 8.6877651541
TB_F 1 6.334999999923
TB_C 1 6199.334999999999923
But couldn't achieve it

Your mistake is that you sort it 2 times. The second time does not additionally sort the sorted, it just sorts the whole Array anew. What you need is to use the Array.sort(...) method with a compareFunction argument:
my_array_W.sort(sortItems);
// Should return -1 if A < B, 0 if A == B, or 1 if A > B.
function sortItems(A:Object, B:Object):Number
{
// First, the main criteria.
if (A.cor > B.cor) return -1;
if (A.cor < B.cor) return 1;
// If A.cor == B.cor, then secondary criteria.
if (A.tem < B.tem) return -1;
if (A.tem > B.tem) return 1;
// Items seem to be equal.
return 0;
}

#Organis was so close.
But Finally I do the trick :D
With this line
my_array_W.sortOn(['cor', 'tem'],[ Array.NUMERIC | Array.DESCENDING, Array.NUMERIC ]);
I get the result I was looking for
Thanks

In your case you have to write a costume sorter function. to do that check my example:
Your first data:
var arr:Array = [];
arr.push({cor:4,tem:13});
arr.push({cor:3,tem:12});
arr.push({cor:2,tem:1});
arr.push({cor:3,tem:16});
arr.push({cor:1,tem:11});
The sorting function and sort result for sample one based on tem:
arr.sort(scrollSorter);
function temSorter(a,b):int
{
if(a.tem<b.tem)
return 1 ;//To pass a forward
else(a.tem>b.tem)
return -1;//To pass a backward
return 0;//a and b are same.
}
And the result is:
The result is this:
[
{
"cor": 3,
"tem": 16
},
{
"cor": 4,
"tem": 13
},
{
"cor": 3,
"tem": 12
},
{
"cor": 1,
"tem": 11
},
{
"cor": 2,
"tem": 1
}
]
Now the sample based on something close you need:
arr.sort(scrollSorter);
function userScoreCalculator(a):Number
{
return a.cor/a.tem;
}
function winnerSorter(a,b):int
{
var aScore:Number = userScoreCalculator(a);
var bScore:Number = userScoreCalculator(b);
if(aScore<bScore)
return 1 ;
else(aScore>bScore)
return -1
return 0
}
And the result is:
[
{
"cor": 2,
"tem": 1
},
{
"cor": 4,
"tem": 13
},
{
"cor": 3,
"tem": 12
},
{
"cor": 3,
"tem": 16
},
{
"cor": 1,
"tem": 11
}
]
Than means the person with score of 2 is winner because he made it in only 1 second. but other players are close to gather in tem parameter, so the next winner is the person with highest score. it comes from the userScoreCalculator() output. the higher output of that function is the winner.
Now take your time and change the userScoreCalculator() function to show the winner.
https://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7fa4.html

Related

Inline::Python tunneling mode

My raku Inline::Python code module unexpectedly prints output even when the rs_str method is disabled.
use Inline::Python;
role Series {
has $args;
has $!py = Inline::Python.new;
has $.po; #each instance has own Python Series obj
method TWEAK {
my $py-str = qq{
class RakuSeries:
def __init__(self):
self.series = pd.Series($args)
#`[
def rs_str(self):
return(str(self.series))
#]
};
$!py.run($py-str);
$!po = $!py.call('__main__', 'RakuSeries');
}
method Str {
$!po.rs_str()
}
}
say ~Series.new( args => "[1, 3, 5, 6, 8]" );
>>>
0 1
1 3
2 5
3 6
4 8
Name: anon, dtype: int64
Is this a special tunnelling mode?
Poisson d'Avril
April Fool
першоквітневий дурень
Aprilscherz

Sort table in lua as multible groups

I need to sort a list _rolls to have both the users rolls and ranks taken into considerations.
_rolls = {
{Username="User1", Roll=50, RankPrio=1},
{Username="User2", Roll=2, RankPrio=3},
{Username="User4", Roll=10, RankPrio=2},
{Username="User5", Roll=9, RankPrio=2},
{Username="User3", Roll=32, RankPrio=2}
}
I want the list to be sorted like
_rolls = {
{Username="User2", Roll=2, RankPrio=3},
{Username="User3", Roll=32, RankPrio=2},
{Username="User4", Roll=10, RankPrio=2},
{Username="User5", Roll=9, RankPrio=2},
{Username="User1", Roll=50, RankPrio=1}
}
i know i can use this to sort by Rolls but i cant see a way to do both.
table.sort(_rolls, function(a,b) return a.Roll < b.Roll end)
You just need to write the comparison function so that it compares the Roll fields when the RankPrio fields compare equal:
_rolls = {
{Username="User1", Roll=50, RankPrio=1},
{Username="User2", Roll=2, RankPrio=3},
{Username="User4", Roll=10, RankPrio=2},
{Username="User5", Roll=9, RankPrio=2},
{Username="User3", Roll=32, RankPrio=2}
}
table.sort(_rolls,
function (a, b)
if a.RankPrio == b.RankPrio then
return b.Roll < a.Roll
else return b.RankPrio < a.RankPrio
end
end)
> table.inspect(_rolls)
1 =
RankPrio = 3
Username = User2
Roll = 2
2 =
RankPrio = 2
Username = User3
Roll = 32
3 =
RankPrio = 2
Username = User4
Roll = 10
4 =
RankPrio = 2
Username = User5
Roll = 9
5 =
RankPrio = 1
Username = User1
Roll = 50

Multi-level counter iteration

I'm stuck on creating an algorithm as follows. I know this shouldn't be too difficult, but I simply can't get my head around it, and can't find the right description of this kind of pattern.
Basically I need a multi-level counter, where when a combination exist in the database, the next value is tried by incrementing from the right.
1 1 1 - Start position. Does this exist in database? YES -> Extract this and go to next
1 1 2 - Does this exist in database? YES -> Extract this and go to next
1 1 3 - Does this exist in database? YES -> Extract this and go to next
1 1 4 - Does this exist in database? NO -> Reset level 1, move to level 2
1 2 1 - Does this exist in database? YES -> Extract this and go to next
1 2 2 - Does this exist in database? NO -> Reset level 2 and 1, move to level 3
2 1 1 - Does this exist in database? YES -> Extract this and go to next
2 1 2 - Does this exist in database? YES -> Extract this and go to next
2 1 3 - Does this exist in database? NO -> Reset level 1 and increment level 2
2 2 1 - Does this exist in database? YES -> Extract this and go to next
2 2 2 - Does this exist in database? YES -> Extract this and go to next
2 2 3 - Does this exist in database? YES -> Extract this and go to next
2 3 1 - Does this exist in database? NO -> Extract this and go to next
3 1 1 - Does this exist in database? NO -> Extract this and go to next
3 2 1 - Does this exist in database? NO -> End, as all increments tried
There could be more than three levels, though.
In practice, each value like 1, 2, etc is actually a $value1, $value2, etc. containing a runtime string being matched against an XML document. So it's not just a case of pulling out every combination already existing in the database.
Assuming, the length of the DB key is known upfront, here's one way how it can be implemented. I'm using TypeScript but similar code can be written in your favorite language.
First, I declare some type definitions for convenience.
export type Digits = number[];
export type DbRecord = number;
Then I initialize fakeDb object which works as a mock data source. The function I wrote will work against this object. This object's keys are representing the the database records' keys (of type string). The values are simple numbers (intentionally sequential); they represent the database records themselves.
export const fakeDb: { [ dbRecordKey: string ]: DbRecord } = {
'111': 1,
'112': 2,
'113': 3,
'211': 4,
'212': 5,
'221': 6,
'311': 7,
};
Next, you can see the fun part, which is the function that uses counterDigits array of "digits" to increment depending on whether the record presence or absence.
Please, do NOT think this is the production-ready code! A) there are unnecessary console.log() invocations which only exist for demo purposes. B) it's a good idea to not read a whole lot of DbRecords from the database into memory, but rather use yield/return or some kind of buffer or stream.
export function readDbRecordsViaCounter(): DbRecord[] {
const foundDbRecords: DbRecord[] = [];
const counterDigits: Digits = [1, 1, 1];
let currentDigitIndex = counterDigits.length - 1;
do {
console.log(`-------`);
if (recordExistsFor(counterDigits)) {
foundDbRecords.push(extract(counterDigits));
currentDigitIndex = counterDigits.length - 1;
counterDigits[currentDigitIndex] += 1;
} else {
currentDigitIndex--;
for (let priorDigitIndex = currentDigitIndex + 1; priorDigitIndex < counterDigits.length; priorDigitIndex++) {
counterDigits[priorDigitIndex] = 1;
}
if (currentDigitIndex < 0) {
console.log(`------- (no more records expected -- ran out of counter's range)`);
return foundDbRecords;
}
counterDigits[currentDigitIndex] += 1;
}
console.log(`next key to try: ${ getKey(counterDigits) }`);
} while (true);
}
The remainings are some "helper" functions for constructing a string key from a digits array, and accessing the fake database.
export function recordExistsFor(digits: Digits): boolean {
const keyToSearch = getKey(digits);
const result = Object.getOwnPropertyNames(fakeDb).some(key => key === keyToSearch);
console.log(`key=${ keyToSearch } => recordExists=${ result }`);
return result;
}
export function extract(digits: Digits): DbRecord {
const keyToSearch = getKey(digits);
const result = fakeDb[keyToSearch];
console.log(`key=${ keyToSearch } => extractedValue=${ result }`);
return result;
}
export function getKey(digits: Digits): string {
return digits.join('');
}
Now, if you run the function like this:
const dbRecords = readDbRecordsViaCounter();
console.log(`\n\nDb Record List: ${ dbRecords }`);
you should see the following output that tells you about the iteration steps; as well as reports the final result in the very end.
-------
key=111 => recordExists=true
key=111 => extractedValue=1
next key to try: 112
-------
key=112 => recordExists=true
key=112 => extractedValue=2
next key to try: 113
-------
key=113 => recordExists=true
key=113 => extractedValue=3
next key to try: 114
-------
key=114 => recordExists=false
next key to try: 121
-------
key=121 => recordExists=false
next key to try: 211
-------
key=211 => recordExists=true
key=211 => extractedValue=4
next key to try: 212
-------
key=212 => recordExists=true
key=212 => extractedValue=5
next key to try: 213
-------
key=213 => recordExists=false
next key to try: 221
-------
key=221 => recordExists=true
key=221 => extractedValue=6
next key to try: 222
-------
key=222 => recordExists=false
next key to try: 231
-------
key=231 => recordExists=false
next key to try: 311
-------
key=311 => recordExists=true
key=311 => extractedValue=7
next key to try: 312
-------
key=312 => recordExists=false
next key to try: 321
-------
key=321 => recordExists=false
next key to try: 411
-------
key=411 => recordExists=false
------- (no more records expected -- ran out of counter's range)
Db Record List: 1,2,3,4,5,6,7
It is strongly recommended to read the code. If you want me to describe the approach or any specific detail(s) -- let me know. Hope, it helps.

Grouping data in mapReduce

I have a csv file which I have loaded into hadoop. Data sample is below.
name | shop | balance
tom | shop a | -500
john | shop b | 200
jane | shop c | 5000
Results:
bad 1
normal 1
wealthy 1
I have to get the balance for each person and then put them into groups(bad(<0), normal(1 to 500), good(>500)
I'm not 100% sure how to put the groups into mapReduce. Do I put it in the reducer? or mapper?
Splitting the csv file(mapper):
String[] tokens = value.toString().split(",");
Sting balance = tokens[3];
Creating groups:
String[] category = new String[3];
category[0] = "Bad"
category[1] = "Normal"
category[2] = "Good"
I also have this if/else statement:
if (bal =< 500){
//put into cat 0
} else if ( bal >= 501 && bal <=1500){
// put into cat 1
} else {
//put into cat 2
}
Thanks in advance.
A simple way to implement this would be:
Map:
map() {
if (bal <= 0) { //or 500, or whatever
emit (bad, 1);
} else if (bal <= 500) { // or 1500, or whatever
emit (normal, 1);
} else {
emit (good, 1);
}
}
Reduce (and combiner, as well):
reduce(key, values) {
int count = 0;
while (values.hasNext()) {
count += values.next();
}
emit (key, count);
}
It's exactly the same as the word count example, where, in your case, you have three words (categories): bad, normal, good.

tcl array to ruby hash parser

I have a file outputted from a TCL script, which has a TCL syntax'ed array, as below.
set data(item1) {
xyz {
a { one two three 1 2 3}
b { three one two 3 2 4}
}
lmn {
z { "something" 1 2 3}
d { "samething" 3 2 4}
}
};
set data(item2) {
xyz {
ss { 100 }
sd { "sdss" 200 300}
}
lmn {
ee { "xdf" 1 "2dsd" 3}
pp { "dd" "fsdf" 3 2 4}
}
};
Now I need to read this file in a Ruby program and build them into a Hash of Hashes, similar to something below, before I start consuming the required data:
data = {
'item1' => {
'xyz' => {
'a' => %w{one two three 1 2 3},
'b' => %w{three one two 3 2 4}
},
'lmn' => {
'z' => %w{something 1 2 3},
'd' => %w{samething 3 2 4}
}
},
'item2' => {
'xyz' => {
'ss' => %w{100 },
'sd' => %w{sdss 200 300}
},
'lmn' => {
'ee' => %w{xdf 1 2dsd 3},
'pp' => %w{dd fsdf 3 2 4}
}
}
}
Is there any Ruby utility or method that I can use for this purpose?
Thanks in advance for your support.
No. You will have to build a parser. Take a look at treetop.
It will help a lot to have some early basic knowledge of compilers like compiling phases (lexical analyzer and syntax analyzer, you don't need semantic analyzer for this project).
Also, some basic understanding of grammars will help, since is pre-requisite for compilers - but most likely you will stumble upon grammars while trying to figure out compilers.

Resources