On Friday, 4 September 2015 at 07:27:54 UTC, Namal wrote:
On Friday, 4 September 2015 at 01:55:13 UTC, deed wrote:
On Friday, 4 September 2015 at 01:31:28 UTC, Namal wrote:
How can I get just the maximum element? Do I need to give a range for it?

Use max? http://dlang.org/phobos/std_algorithm_comparison.html#max

Sorry, I don't understand the syntax yet. How do I tell max to search all elements?
You can search all elements by using reduce
http://dlang.org/phobos/std_algorithm_iteration.html#reduce

I mean, why does sort(myarray) is legit and max(myarray) isn't.
I don't know why, other than that is the current design in Phobos.


import std.algorithm, std.range, std.array, std.string, std.stdio,
std.conv;

int[] arr1 = [1, 2, 30];
//arr1.max.writeln;         // Doesn't work, as you say
arr1.reduce!max.writeln;    // This does. Prints 30.

int[] arr2 = [4, 5, 6];
int[][] arr = [arr1, arr2];
arr.reduce!max.writeln; // Returns either arr1 or arr2. Element by // element comparison until one is greatest.
                            // Prints arr2, since 1 < 4.
arr.joiner.reduce!max.writeln; // Flattens arr1 and arr2 to one arr and
                            // finds max. Prints 30.

//For your example:
auto f = File("filename", "r");
auto numbers = f            // 1 2 3\n4 5 6
    .byLine                 // ["1 2 3", "4 5 6"]
    .map!(a => a.split)     // [["1", "2", "3"], ["4", "5", "6"]]
    .map!(a => a.to!(int[]))// [[1, 2, 3], [4, 5, 6]]
.array; // Allocates and puts the elements into an
                            // int[][] for reuse of state.

numbers                     // [[1, 2, 3], [4, 5, 6]]
    .map!(reduce!max)       // [3, 6]
    .writeln;               // prints [3, 6]

numbers                     // [[1, 2, 3], [4, 5, 6]]
    .joiner                 // [1, 2, 3, 4, 5, 6]
    .reduce!max             // 6
    .writeln;               // prints 6

Reply via email to