www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Programming chrestomathy: wealthiest customer

reply mipri <mipri minimaltype.com> writes:
This is a fun video: https://www.youtube.com/watch?v=MKb4WD6mioE
Which includes three separate C++ solutions to a simple
(four letters in APL) problem, his preferred C++ solution
being:

   // C++17 Solution
   int maximumWealth(vector<vector<int>>& accounts) {
       return std::transform_reduce(
           accounts.cbegin(),
           accounts.cend(),
           0,
           [](auto a, auto b) { return std::max(a, b); },
           [](auto const& row) { return std::reduce(row.cbegin(), 
row.cend()); });
   }

Although what he thinks the C++ is trying to be is this Rust:

   pub fn maximum_wealth(accounts: Vec<Vec<i32>>) -> i32 {
       accounts.iter()
               .map(|x| x.iter().sum())
               .max()
               .unwrap()
   }


But D is very competitive here:

   int maximumWealth(const int[][] accounts) {
       import std.algorithm : map, sum, maxElement;
       return accounts.map!sum.maxElement;
   }

Or, aping the APL:

   int maximumWealth(const int[][] accounts) {
       import std.algorithm : fold, map;
       return accounts.map!(fold!"a+b").fold!"a.max(b)";
   }


That's it. I like this RosettaCode stuff and happened across
the video. He does include D in some other similar videos, like
https://www.youtube.com/watch?v=pDbDtGn1PXk&t=278s
Mar 08 2021
parent FeepingCreature <feepingcreature gmail.com> writes:
On Tuesday, 9 March 2021 at 05:06:03 UTC, mipri wrote:
 But D is very competitive here:

   int maximumWealth(const int[][] accounts) {
       import std.algorithm : map, sum, maxElement;
       return accounts.map!sum.maxElement;
   }

 Or, aping the APL:

   int maximumWealth(const int[][] accounts) {
       import std.algorithm : fold, map;
       return accounts.map!(fold!"a+b").fold!"a.max(b)";
   }
Golf! import std; alias maximumWealth = pipe!(map!sum, maxElement); unittest { assert([[2, 10], [11]].maximumWealth == 12); }
Mar 08 2021