Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

product function #9971

Open
dlangBugzillaToGithub opened this issue May 3, 2013 · 0 comments
Open

product function #9971

dlangBugzillaToGithub opened this issue May 3, 2013 · 0 comments

Comments

@dlangBugzillaToGithub
Copy link

bearophile_hugs reported this on 2013-05-03T16:41:41Z

Transfered from https://issues.dlang.org/show_bug.cgi?id=10024

Description

I suggest to add a product() function to Phobos, similar to sum().

This benchnarking code shows an algorithm better than the naive one when it's used on bigints:


import std.stdio, std.bigint, std.algorithm, std.random;

T product1(T)(T[] seq) {
    typeof(return) result = 1;
    foreach (s; seq)
        result *= s;
    return result;
}

T product2(T)(T[] seq) { // faster
    if (seq.length < 50) {
        typeof(return) result = 1;
        foreach (s; seq)
            result *= s;
        return result;
    } else {
        immutable mid = seq.length / 2;
        return product2(seq[0 .. mid]) * product2(seq[mid .. $]);
    }
}

void main() {
    BigInt[2 ^^ 16] items;
    foreach (i, ref b; items)
        b = i + 1;
    items[].randomShuffle;

    //auto r = items.product1;
    auto r = items.product2;
    //r.writeln;
}


What about T == InputRange?
@LightBender LightBender removed the P4 label Dec 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants