• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
AmzBee

Calculating average mode without creating too much garbage...

4 posts in this topic

Hey everyone, I'm currently working on some behaviours for non playable characters in a game, and I need to find a reliable and fast method for finding the mode specific average of a set of values. This is not really a mathematics specific question rather a performance once, see the code must be per-formant in various situations where creating things like hash tables or anything else that creates orphan garbage to an extent that has potential to slow the game down to a crawl.

 

So far, I've found 4 different approaches to the issue as follows:

 

static int ModeA(int[] items)
{
    var groups = items.GroupBy(t => t);
    int maxCount = groups.Max(g => g.Count());
    return groups.First(g => g.Count() == maxCount).Key;
}
 
static int ModeB(IEnumerable<int> items)
{
    int maxVal = 0, maxCount = 0, curCount;
    var iter = items.GetEnumerator();
    while (iter.MoveNext())
    {
        curCount = items.Count(t => t == iter.Current);
        if (curCount > maxCount)
        {
            maxVal = iter.Current;
            maxCount = curCount;
        }
    }
    return maxVal;
}
 
static int ModeC(int[] items)
{
    int maxVal, maxCount, curCount;
    for (int i = maxVal = curCount = maxCount = 0; i < items.Length; i++)
    {
        var curVal = items[i];
        if ((curCount = items.Count(t => t == curVal)) > maxCount)
        {
            maxVal = curVal;
            maxCount = curCount;
        }
    }
    return maxVal;
}
 
static int ModeD(int[] items)
{
    int maxVal = 0, maxCount = 0, curCount = 0, curVal = 0, i = 0, j = 0;
    for (i = 0, j = 0; i < items.Length; i++, curCount = 0)
    {
        curVal = items[i]; 
 
        for (j = 0; j < items.Length; j++)
            if (items[j] == curVal) 
                curCount++;
 
        if (curCount > maxCount)
        {
            maxVal = curVal;
            maxCount = curCount;
        }
    }
    return maxVal;
}

 

 

And here is what I get performance wise if I ask each function to return the mode for 10,000 elements (timed with the Stopwatch class):

 

Method A Took: 00:00:00.0112893.
Method B Took: 00:00:02.9916290.
Method C Took: 00:00:02.3635998.
Method D Took: 00:00:00.5677500.
 
Hopefully you'll already be able to see my problem, method A is obviously the fastest but method D is more favourable (at least from what I can see as it doesn't create an enumerable collection like A and B do). In the real-time scenario I'll only be throwing a maximum of 300 elements at this method, which gives me something more reasonable:
 
Method A Took: 00:00:00.0087793.
Method B Took: 00:00:00.0039755.
Method C Took: 00:00:00.0026175.
Method D Took: 00:00:00.0007191.
 
And if I repeat this test within a loop a few times, the results change slightly:

Method A Took: 00:00:00.0000429.
Method B Took: 00:00:00.0027317.
Method C Took: 00:00:00.0021401.
Method D Took: 00:00:00.0005269.
 
Again obviously method A is the fastest, but in this 2rd test only after iteration. So my question is am I being too obsessed over this when I could just go with method A and sod GC, or is method D truly better even though I never see that much improvement after iteration and on larger arrays it struggles.
 
Thanks everyone for any feedback on the subject.
 
Aimee
Edited by AmzBee
0

Share this post


Link to post
Share on other sites

OK maybe I am definately looking too far into this lol, I've found another method that's even faster than method A, except it does what I was trying to avoid by using a dictionary as follows:

 

static Dictionary<int, int> table = new Dictionary<int, int>();

static int ModeE(int[] items)
{
    table.Clear();
    for (int i = 0; i < items.Length; i++)
    {
        var item = items[i];
        if (!table.ContainsKey(item)) table.Add(item, 0);
        table[item]++;
    }
    return table.First(t => t.Value == table.Max(u => u.Value)).Key;
}

 

Does anyone see anything here that I'm missing that could cause unwanted garbage?

 

Aimee

Edited by AmzBee
0

Share this post


Link to post
Share on other sites
You can pass a capacity value to the dictionary constructor, so that it doesn't have to allocate more memory as you add values into it. items.Length would be a reasonable value to use if you only use the dictionary once - otherwise, just pick a fairly large number.
 
But really, you don't need to allocate any memory for this. Sort the items, then iterate through them, looking for the longest consecutive run of identical values.
items.Sort(); // equal numbers are now contiguous in the array
int currTotal = 1;
int currentNumber = items[0];

// Initial state, having only considered one value
int modeValue = currentNumber;
int modeTotal = currTotal ;

// now look at the others
for (int i=1; i<items.Length; ++i)
{
    if (items[i] == items[i-1])
    {
        // One more of the same number
        currTotal++;

        // Biggest count so far? This will be our mode, until we find a bigger count.
        if (currTotal > modeTotal)
        {
            modeValue = currentNumber;
            modeTotal = currTotal;
        }
    }
    else
    {
        // This is a new number.
        // Only found one of them so far
        currTotal = 1;        
        currentNumber = items[i];
        // Never need to change the modeValue here as we always have an existing value with a count of at least 1
    }
}
There might be a bug or two in there as it's untested code, but hopefully you get the idea. The sorting operation means you only ever have to remember 2 values at a time, keeping hold of the largest, and since 2 is a constant you don't need any dynamic storage.
1

Share this post


Link to post
Share on other sites

Do any of those functions work correctly? If there's a tie for the most popular value don't you have to take the mean of the tied values?

 

EDIT: Apparently not, although that makes the data multimodal... and you probably want to report all the modes of a data set in that case...

Edited by Paradigm Shifter
0

Share this post


Link to post
Share on other sites
You're thinking of the median. Taking the mean of each candidate for the mode would be meaningless since you're not necessarily working with interval or ratio data.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0