ID:1639923
 
(See the best response by Pirion.)
Hi guys,

Part of a system I'm working on takes two lists and needs to look at them returning a value.
Each list has items and an amount, and they cancel each other out until 0 or a list has be fully read

List['Apples'] = 100
List['Pears'] = 10

Now, this part needs to take people lists and compare them, while doing stuff. So


A.List['Apples'] = 100
A.List['Pears'] = 10

B.List['Apples'] = 70
B.List['Pears'] = 50

Now, the first thing I've come up with (At work not at home with DM) is something like the following.
for(a_Item in A.List)
var/a_amount = A.list[a_Item]
for(b_Item in B.List)
var/b_amount = B.List[b_Item]
var/overage = Process(a_amount,b_amount)


Apples and Pears have different 'values' so Apples are two Pears for example, Process returns either 0, or a positive number if List A's item is more than List B and also subtracts from a_List,b_List amounts.
If there is still apples left (in this case 30), It needs to compare the rest of the Apples (30) against the next item in b_list.
It plagued me all day how to do this efficiently.
I've thought about while() looping through the lists.
while(i ++ stuffs)
a_Amount = A.List[a.List[i]] //Is there a better way to call the values?
b_Amount = b.List[b.list[i]]
if(Proccess(a_Amount,b_Amount)
b_amount = b.list[b.list[i++]]


I'm guessing this would be slightly better, but what if there are still Apples left after. Then I need to enclose that in a while loop as well.

I hope I'm missing a simpler way to do this.



Best response
So from what I am reading:

There are two lists.
The list items have amounts.
Each list item has a specific value.
You want to view the delta.

//define your index.
var/list/index = list("apple" = 2, "pear" = 1)

//Treat each list as its own problem, and reuse!
proc/viewListValue(list/a)
. = 0
for(var/item in a)
. += a[item] * index[item]

//compare the results
proc/viewDelta(list/a, list/b)
var/a_value = viewListValue(a)
var/b_value = viewListValue(b)
. = abs(a_value - b_value) //abs makes it positive.


For the test:
mob/verb/test()
var/list/a_list = list("apple" = 100, "pear" = 10)
var/list/b_list = list("apple" = 50, "pear" = 200)
src << "The comparison of a to b is '[viewDelta(a_list, b_list)]'."

Outputs: The comparison of a to b is '90'.

If I over-simplified, please clarify a little more. Thanks!