1. 7

  2. 3

    k solution:

    {x@<(+/`i$')'x}{x@<x}@" "\:


                          " "\: /split by spaces
                   {x@<x}@      /string sort
    {   (      )'x}             /for each
           `i$'                 /    cast each char to integer
         +/                     /    sum
     x@<                        /sort by these
    1. 1

      This is missing the part where ties by weight are broken by ordinary string order.

      1. 1

        This is what the initial string sorting is for. < seems to preserve order in the case of ties.

    2. 1

      Haskell solution (requires the packages sort and extra):

      import Data.Sort (sortOn)
      import Data.Tuple.Extra ((&&&))
      weightSort :: String -> String
      weightSort = unwords . sortOn (sum . map (read . pure) &&& id) . words
      1. 1

        Here’s a Rust transliteration of the Haskell, made entirely for curiosity (this isn’t a great example of idiomatic Rust): Rust Playground.

      2. 1

        Python solution:

        def sort_by_weight(inputline):
            return " ".join(sorted(inputline.split(), 
                                   key=lambda i: (sum(int(j) for j in i), i) ))

        And in D, for good measure. I like how easy it is to literally translate Python into D:

        import std;
        auto sort_by_weight(string inputline) {
          return inputline.split
            .schwartzSort!(x => tuple(x.map!(i => int(i - '0')).sum, x)).join(" ");

        Btw, “kata” is a Japanese loanword. For the plural, just add s, “katas”.

        1. 1

          @raymii pop_back on an empty string is undefined[1] so your solution would probably behave correctly most of the time on empty string as input but might just crash too

          [1] https://en.cppreference.com/w/cpp/string/basic_string/pop_back

          1. 1

            Thanks for noticing! In the last paragraph the complete code does a check for input.empty() and returns “” if true, so the pop back shouldn’t happen, or I might miss something.

          2. 1

            Fun little exercise. Here’s a Perl solution that works for the test input: https://pastebin.com/yiesqUbg

            1. 1

              Cool! I love how Perl looks like a shell script bus is a real language as well. I also did this kata in Python and faster than in C++. Not being as familiar with the standard library and strong typing cost most of the time.