Finding Max Value of Column in Multi-Dimesional Array
9il
ilyayaroshenko at gmail.com
Fri Jul 5 01:41:38 UTC 2019
On Friday, 5 July 2019 at 00:54:15 UTC, Samir wrote:
> Is there a cleaner way of finding the maximum value of say the
> third column in a multi-dimensional array than this?
> int[][] p = [[1,2,3,4], [9,0,5,4], [0,6,2,1]];
> writeln([p[0][2], p[1][2], p[2][2]].max);
>
> I've tried the following
> writeln([0, 1, 2].map!(p[a][2]).max);
>
> but get an "Error: undefined identifier a" error.
>
> I know there doesn't seem to be much of a difference between
> two examples but my real-world array is more complex which is
> why I'm looking for a more scalable option.
>
> Thanks
> Samir
Hi Samir,
You may want to take a look into mir-algorithm [1] library.
It contains ndsilce package [2] to work with multidimensional
data.
The following example can be run online [3]:
------
/+dub.sdl:
dependency "mir-algorithm" version="~>3.4.4"
+/
import mir.algorithm.iteration: reduce;
import mir.ndslice: fuse, map, byDim;
import mir.utility: max;
import std.stdio: writeln;
void main()
{
// create 2D matrix type of Slice!(int*, 2);
auto matrix = [[1,2,3,4], [9,0,5,4], [0,6,2,1]].fuse;
matrix
.byDim!1 // by columns
.map!(c => int.min.reduce!max(c))
.writeln; // [9, 6, 5, 4]
}
------
1. https://github.com/libmir/mir-algorithm
2. http://mir-algorithm.libmir.org/mir_ndslice.html
3. https://run.dlang.io/is/OW6zvF
More information about the Digitalmars-d-learn
mailing list