Programming chrestomathy: wealthiest customer

mipri mipri at minimaltype.com
Tue Mar 9 05:06:03 UTC 2021


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



More information about the Digitalmars-d mailing list