[FORMULA AI]: product of all list members

Discussion and development of scenarios and campaigns for the game.

Moderator: Forum Moderators

Post Reply
amir
Posts: 25
Joined: August 24th, 2008, 10:43 am

[FORMULA AI]: product of all list members

Post by amir »

hi,
im trying to write custom ai behaviour using formula ai and im stuck with a problem that seems to be rather profane, but causes me a serious headache:

how can i get the product of all members of a list?
e.g: i want [2,4,3] to result to 24 (that would be the result of 2*4*3).

im using wesnoth 1.6.5 from svn.

thx,
amir
amir
Posts: 25
Joined: August 24th, 2008, 10:43 am

Re: [FORMULA AI]: product of all list members

Post by amir »

seems not to be profan after all... is it?
not even a hint?

thx,
amir
User avatar
solsword
Code Contributor
Posts: 291
Joined: January 12th, 2009, 10:21 pm
Location: Santa Cruz, CA
Contact:

Re: [FORMULA AI]: product of all list members

Post by solsword »

Hm... profane isn't the right word there. Perhaps arcane? In any case, you might do well to post this over in the Coder's Corner, as that sub-forum has the highest concentration of people knowledgeable about the formula AI.

I know very little about the formula, AI, but looking at the list of built-in functions, I don't see 'reduce', so it seems like you'll have to write a recursive function to do your job. Something along the lines of:

Code: Select all

[function]
    name=list_product
    inputs=list
    formula="if(size(list)==0, 1, head(list)*list_product(list[1:]))"
[/function]
Of course, I don't know if slicing (the "[1:]" in the proposed function above) is supported in the FAI, but there doesn't seem to be a built-in function that does it, and there's got to be *some* way of doing it... right?

I guess if that doesn't work one could construct a 'tail' function like this:

Code: Select all

[function]
    name=tail
    inputs=list
    formula="filter(list, index_of(item, list) != 0), 'item')"
[/function]
Unfortunately, this version of 'tail' doesn't work if there are repeated values in the list. So if slicing doesn't work, and your list might have the same value twice, you'll need to construct a more complicated function that takes that into account. But if slicing is impossible in the formula AI, you should probably just bring up the fact that at least a tail() function should exist!
The Knights of the Silver Spire campaign.

http://www.cs.hmc.edu/~pmawhorter - my website.

Teamcolors for everyone! PM me for a teamcolored version of your sprite, or you can do it yourself. If you just happen to like magenta, no hard feelings?
AI
Developer
Posts: 2396
Joined: January 31st, 2008, 8:38 pm

Re: [FORMULA AI]: product of all list members

Post by AI »

In 1.7.6, reduce( [2,4,3], a*b ) will do the trick.
amir
Posts: 25
Joined: August 24th, 2008, 10:43 am

Re: [FORMULA AI]: product of all list members

Post by amir »

thx a lot to the both of u. i guess ill rather do it with 1.7.6.

amir
Post Reply