digitalmars.D.learn - Sum and other algorithm functions
- Namal (6/6) Sep 10 2015 Hello,
- anonymous (4/13) Sep 10 2015 First you slice the first/last 3, then you sum them.
- Andrea Fontana (15/21) Sep 10 2015 In this case, you can simply slice array using a[0..3] or
Hello, how can I define the range for the sum function which I want to sum up? For instance how do I sum up the first 3 elements of an array int[] a = [1,2,3,4,5,6,7,8,9]; or the last 3?
Sep 10 2015
On Thursday 10 September 2015 15:48, Namal wrote:Hello, how can I define the range for the sum function which I want to sum up? For instance how do I sum up the first 3 elements of an array int[] a = [1,2,3,4,5,6,7,8,9]; or the last 3?First you slice the first/last 3, then you sum them. first 3: a[0 .. 3].sum last 3: a[$ - 3 .. $].sum
Sep 10 2015
On Thursday, 10 September 2015 at 13:48:16 UTC, Namal wrote:Hello, how can I define the range for the sum function which I want to sum up? For instance how do I sum up the first 3 elements of an array int[] a = [1,2,3,4,5,6,7,8,9]; or the last 3?In this case, you can simply slice array using a[0..3] or a[$-3..$]. If you have a range you can use take() and/or drop() void main() { int[] a = [1,2,3,4,5,6]; writeln(a[0..3]); writeln(a[$-3..$]); writeln(a.take(3)); writeln(a.drop(a.length-3)); }
Sep 10 2015