text:
Binary Numbers Magic Trick
The challenge is simply; output the following six 2D integer arrays:
[[ 1, 11, 21, 31, 41, 51],
 [ 3, 13, 23, 33, 43, 53],
 [ 5, 15, 25, 35, 45, 55],
 [ 7, 17, 27, 37, 47, 57],
 [ 9, 19, 29, 39, 49, 59]]

[[ 2, 11, 22, 31, 42, 51],
 [ 3, 14, 23, 34, 43, 54],
 [ 6, 15, 26, 35, 46, 55],
 [ 7, 18, 27, 38, 47, 58],
 [10, 19, 30, 39, 50, 59]]

[[ 4, 13, 22, 31, 44, 53],
 [ 5, 14, 23, 36, 45, 54],
 [ 6, 15, 28, 37, 46, 55],
 [ 7, 20, 29, 38, 47, 60],
 [12, 21, 30, 39, 52]]

[[ 8, 13, 26, 31, 44, 57],
 [ 9, 14, 27, 40, 45, 58],
 [10, 15, 28, 41, 46, 59],
 [11, 24, 29, 42, 47, 60],
 [12, 25, 30, 43, 56]]

[[16, 21, 26, 31, 52, 57],
 [17, 22, 27, 48, 53, 58],
 [18, 23, 28, 49, 54, 59],
 [19, 24, 29, 50, 55, 60],
 [20, 25, 30, 51, 56]]

[[32, 37, 42, 47, 52, 57],
 [33, 38, 43, 48, 53, 58],
 [34, 39, 44, 49, 54, 59],
 [35, 40, 45, 50, 55, 60],
 [36, 41, 46, 51, 56]]

What are these 2D integer arrays? These are the numbers used in a magic trick with cards containing these numbers:

The magic trick asks someone to think of a number in the range [1, 60], and give the one performing the magic trick all the cards which contain this number. The one performing the magic trick can then sum the top-left numbers (all a power of 2) of the given cards to get to the number the person was thinking of. Some additional explanation of why this works can be found here.
Challenge rules:

You can output the six 2D integer arrays in any reasonable format. Can be printed with delimiters; can be a 3D integer array containing the six 2D integer arrays; can be a string-list of lines; etc.
You are allowed to fill the bottom right position of the last four cards with a negative value in the range [-60, -1] or character '*' instead of leaving it out to make the 2D integer arrays rectangular matrices (no, you are not allowed to fill them with 0 or a non-integer like null/undefined as alternative, with the exception of * since a star is also used in the actual cards).
The order of the numbers in the matrices is mandatory. Although it doesn't matter for the physical magic trick, I see this challenge mainly as a matrix-kolmogorov-complexity one, hence the restriction on order.
The order of the matrices themselves in the output list can be in any order, since it's clear from the top-left card which matrix is which.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.

Related. (As in, it's referring to the same magic trick, but not really useful to get inspiration from for this challenge I think. That challenge asks to output a truthy/falsey value whether number n appears on the k'th card; where my challenge is a KC-challenge to output the six matrices.)

@DigitalTrauma Hm, I'm not so sure if this is really a duplicate, because your challenge is [tag:ascii-art] (not tagged as such, but it is), while this one allows you to output the array in a way more lenient format (not just four essentially identical ways). I can't vote to reopen, though, because I have a hammer.

@EriktheOutgolfer Woops.. Forgot I have a hammer as well >.> Sometimes being able to close/open hammer is pretty annoying.. It had 2 votes already though, so with yours and mine in addition there were 4 open votes. But if someone wants to close it again I don't mind. They are indeed very similar, although his challenge is indeed an [ascii-art] challenge with strict (MD5) output rules, where mine are very flexible (and the rows/columns are swapped, and range is [1,60] instead of [1,63]; pretty minor differences, but still).

Looks like you didn't try to VTRO with an attitude of "this is my precious challenge!!!" at least... :P

@EriktheOutgolfer No, that was indeed not my intention. :) If I knew about his challenge I probably wouldn't have posted mine in the Sandbox. But since it's already here I can see your earlier point, and I indeed see quite a bit of differences (although also just as many similarities) between the two challenges. If I would be like "my previous challenge :(" I would had already opened it as soon as the close-vote came in. ;P But I could understand it. Now that I'm remembered my vote is a hammer I'll leave it to others to open-vote it next time..

I too forgot about the hammer.  I still think this is close enough to vote to dup, though I'll defer to the wisdom of the community if it is reopened.

Not related to the challenge, but to the magic trick: other versions of those cards scramble the numbers (with the power of two in some convenient spot) so that how it works is less obvious. Unfortunately, this makes it a little more likely the chooser will miss a card, so the magician may want to have some patter ready in case that happens.

MATL, 12 11 bytes
-1 byte thanks to the master himself:)
60:B"@fQ6eq

Explanation:
60:           % create a vector [1,2,3,...,60]
   B          % convert to binary matrix (each row corresponds to one number)
    "         % loop over the columns and execute following commands:
     @f       % "find" all the nonzero entries and list their indices
       Q      % increment everything
        6e    % reshape and pad with a zero at the end
          q   % decrement (reverts the increment and makes a -1 out of the zero
              % close loop (]) implicitly
              % display the entries implicitly

Try it online!

Perl 6, 63 46 bytes
say grep(*+&2**$_,^61)[$_,*+5...*for ^5]for ^6

Try it online!
Outputs as 2D arrays on multiple lines, with the last array of each one cut off if necessary.

Python 2, 76 bytes
r=range;print[[[i for i in r(61)if i&2**k][j::5]for j in r(5)]for k in r(6)]

Try it online!
The method here is to create a list of all possible numbers r(61) and then whittle that down to the list of numbers for a card i&2**k.
Then, by using list slicing, that 1D list of numbers is rearranged to the correct 6x5 card size [card nums][j::5]for j in r(5).
Then, this generator is just repeated for 6 cards for k in r(6).

While I could not find any solutions less than 76 bytes, here are two others that are also 76 bytes:
r=range;print[[[i for i in r(61)if i&1<<k][j::5]for j in r(5)]for k in r(6)]

Try it online!
This next one is inspired by Jonathan Allan.
k=32
while k:print[[i for i in range(61)if i&k][j::5]for j in range(5)];k/=2

Try it online!
Any comments are greatly appreciated.

Charcoal, 26 bytes
Ｅ⁶Ｅ⁵⪫Ｅ⁶§⁺§⪪Φ⁶¹＆πＸ²ι⁵ν⟦*⟧λ

Try it online! Link is to verbose version of code. I tried calculating the entries directly but this was already 27 bytes before adjusting for the * in the bottom right. Outputs each row joined with spaces and a blank line between cards. Explanation:
Ｅ⁶                          Loop over 6 cards
  Ｅ⁵                        Loop over 5 rows
     Ｅ⁶                     Loop over 6 columns
           Φ⁶¹              Filter over 0..60 where
               π            Current value
              ＆             Bitwise And
                 ²          Literal 2
                Ｘ           Raised to power
                  ι         Card index
          ⪪        ⁵        Split into groups of 5
         §          ν       Indexed by column
        ⁺                   Concatenated with
                      *     Literal string `*`
                     ⟦ ⟧    Wrapped in an array
       §                λ   Indexed by row
    ⪫                       Joined with spaces
                            Implicitly print

I added that rule about * for fun after I saw the stars on the actual cards. Was wondering if there would be any languages using it, but I'm glad to see at least one did. :) Nice answer!

@KevinCruijssen Charcoal doesn't have a transpose operator, and the golfiest transpose requires a rectangular array of known size, so I need to add something to make up the size, and * is at least as short as anything else would be.

I don't think this is 26 bytes...

@Tvde1 Charcoal, like many of the esolangs on this site, uses a custom code page. Characters from that page cost 1 byte, while other characters cost up to 4 bytes.

05AB1E, 16 bytes
60L2вíƶ0ζε0K5ô®ζ

Try it online!
Explanation
60L                 # push [1 ... 60]
   2в               # convert each to a list of binary digits
     í              # reverse each
      ƶ             # multiply each by its 1-based index
       0ζ           # transpose with 0 as filler
         ε          # apply to each list
          0K        # remove zeroes
            5ô      # split into groups of 5
              ®ζ    # zip using -1 as filler

05AB1E, 17 bytes
6F60ÝNoôāÈÏ˜5ô®ζ,

Try it online!
Explanation
6F                  # for N in [0 ... 5] do
  60Ý               # push [0 ... 60]
     Noô            # split into groups of 2^N numbers
        āÈÏ         # keep every other group
           ˜        # flatten
            5ô      # split into groups of 5
              ®ζ    # transpose with -1 as filler
                ,   # print

Python 2, 82 80 78 74 bytes
i=1
exec"print zip(*zip(*[(n for n in range(61)+[-1]if n&i)]*5));i*=2;"*6

Try it online!
-4 bytes, thanks to Jonathan Allan

Nice. The iter keyword is redundant here since a generator will do the job just as well.

@JonathanAllan Cool, thanks :D

Husk, 13 bytes
ṠMöTC5Wnünḣ60

Try it online!
Explanation
          ḣ60  Range [1..60]
        ü      Uniquify using equality predicate
         n     bitwise AND: [1,2,4,8,16,32]
 M             For each number x in this list,
Ṡ     W        take the indices of elements of [1..60]
       n       that have nonzero bitwise AND with x,
    C5         cut that list into chunks of length 5
  öT           and transpose it.

Japt, 14 bytes
6Æ60õ f&2pX)ó5

Try it
6Æ              Create a range from 0 to 5 (inclusive) and map each X into
  60õ             Elements in the range [1..60]
      f             Where
       &2pX)          The number bitwise AND with X is not 0
  ó5              Split into 5 arrays, where each array contains every 5th element

-Q flag is just for formatting purposes

C (gcc), 95 bytes
i,j,k;f(int o[][5][6]){for(i=6;i;)for(o[--i][4][5]=j=k=-1;j<60;)++j&1<<i?o[i][++k%5][k/5]=j:0;}

Try it online!
Returns the matrices as a 3D int array in o.
The last 4 matrices have -1 as their last value.
Saved 2 bytes thanks to Kevin Cruijssen.
Saved 7 8 bytes thanks to Arnauld.

You can save 2 bytes by changing o[i][4][5]=-1;for(j=k=0; to for(o[i][4][5]=-1,j=k=0; so the brackets can be removed. Nice answer btw, +1 from me.

95 bytes

(Note that I'm not 100% sure if passing a 3D array already allocated with the correct dimensions is allowed. But I'll let regular C golfers provide a better insight about that.)

@Arnauld I was thinking about that, but decided against it.

better to leave out #include to show that it works without it

JavaScript (ES6),  90  88 bytes
_=>[1,2,4,8,16,32].map(n=>(g=i=>i<60?g(++i,i&n?m[y%5]=[...m[y++%5]||[],i]:0):m)(y=m=[]))

Try it online!
Commented
_ =>                        // anonymous function taking no argument
  [1, 2, 4, 8, 16, 32]      // list of powers of 2, from 2**0 to 2**5
  .map(n =>                 // for each entry n in this list:
    ( g = i =>              //   g = recursive function taking a counter i
      i < 60 ?              //     if i is less than 60:
        g(                  //       recursive call:
          ++i,              //         increment i
          i & n ?           //         if a bitwise AND between i and n is non-zero:
            m[y % 5] =      //           update m[y % 5]:
            [ ...m[y++ % 5] //             prepend all previous values; increment y
              || [],        //             or prepend nothing if it was undefined so far
              i             //             append i
            ]               //           end of update
          :                 //         else:
            0               //           do nothing
        )                   //       end of recursive call
      :                     //     else:
        m                   //       return m[]
    )(y = m = [])           //   initial call to g with i = y = m = []
                            //   (i and y being coerced to 0)
  )                         // end of map()

Python 2, 73 bytes
Inspiration taken from both TFeld's and The Matt's.
k=32
while k:print zip(*zip(*[(i for i in range(61)+[-1]if i&k)]*5));k/=2

Try it online!

Wolfram Language (Mathematica), 88 bytes
Transpose@Partition[#~Append~-1,5]&/@Last@Reap[Sow[,NumberExpand[,2]]~Do~{,60},Except@0]

I took the liberty of adding a TIO link (based on @J42161217's answer). +1 from me.

91 bytes?: Transpose@Partition[#~Append~-1,5]&/@Last@Reap[Do[Sow[k,k~NumberExpand~2],{k,60}],Except@0]

@Mr.Xcoder Thanks.  I've used this ~ trick in one more place and replaced the variable k by Null.  Sorry, no time to add a tio link.

Jelly, 13 bytes
60&ƇⱮs€5LÐṂZ€

A niladic Link which yields a list of (6) lists of lists of integers. (It outputs the using the default option of having no * or negative filler.)
Try it online!
How?
Each matrix contains, in column-major order, the numbers up to \$60\$ which share the single set-bit with the top-left (minimal) number.
This program first makes all \$60\$ possible ordered lists of numbers in \$[1,60]\$ which share any set-bit(s) with their index number. It then splits each into chunks of \$5\$ and keeps only those with minimal length - which will be the ones where the index has only a single set-bit (and hence also being its minimal value). Finally it transposes each to put them into column-major order.
60&ƇⱮs€5LÐṂZ€ - Link: no arguments
60            - set the left argument to 60
    Ɱ         - map across ([1..60]) with:  (i.e. [f(60,x) for x in [1..60]])
   Ƈ          -   filter keep if:  (N.B. 0 is falsey, while non-zeros are truthy)
  &           -     bitwise AND
      €       - for each:
     s 5      -   split into chunks of five
         ÐṂ   - keep those with minimal:
        L     -   length
           Z€ - transpose each

Lots of 15s without realising the "minimal by length when split into fives" trick:
5Ż2*Ɱ60&ƇⱮs€5Z€
6µ’2*60&Ƈ)s€5Z€
60&ƇⱮ`LÞḣ6s€5Z€

...and, while attempting to find shorter, I got another 13 without needing the trick at all:
60B€Uz0Ts5ZƊ€

CJam (18 bytes)
6{61{2A#&},5/zp}fA

Online demo. This is a full program which outputs to stdout.
Dissection
6{             }fA    # for A = 0 to 5
  61{2A#&},           #   filter [0,61) by whether bit 2^A is set
           5/z        #   break into chunks of 5 and transpose to get 5 lists
              p       #   print

R, 73 bytes
`!`=as.raw;lapply(0:5,function(i)matrix(c((a=1:60)[(!a&!2^i)>0],-1),5,6))

I am not entirely sure if I have met the requirement for order, since R by default fills matrices by column, so the order such that it appears physically on the cards is the same as the way matrices are allocated in R.
Try it online!

The output looks good. And if R fills matrices by columns before row instead of row before column like almost all other languages, it just means it's a good programming language to use for this challenge I guess. :)

T-SQL, (1,168 1,139 bytes)
I just wanted to know I could do it.
Optimised version
 WITH g AS(SELECT 1 AS n UNION ALL SELECT n+1 FROM g WHERE n+1<61),B as(SELECT cast(cast(n&32 as bit)as CHAR(1))+cast(cast(n&16 as bit)as CHAR(1))+cast(cast(n&8 as bit)as CHAR(1))+cast(cast(n&4 as bit)as CHAR(1))+cast(cast(n&2 as bit)as CHAR(1))+cast(cast(n&1 as bit)as CHAR(1))as b FROM g),P as(SELECT * from (values(1), (2), (4), (8), (16), (32)) as Q(p)),S as(select distinct p,p+(substring(b,6,1)*1)*(case when p=1 then 0 else 1 end)+(substring(b,5,1)*2)*(case when p=2 then 0 else 1 end)+(substring(b,4,1)*4)*(case when p=4 then 0 else 1 end)+(substring(b,3,1)*8)*(case when p=8 then 0 else 1 end)+(substring(b,2,1)*16)*(case when p=16 then 0 else 1 end)+(substring(b,1,1)*32)*(case when p=32 then 0 else 1 end)as e from P cross apply B),D as(select * from S where e>=p and e<61),R as(select p,(row_number()over(partition by p order by cast(e as int)))%5 as r,e from D),H as(select k.p,'['+stuff((select','+cast(l.e as varchar)from R l where l.p=k.p and l.r=k.r for xml path('')),1,1,'')+']'as s from R k group by k.p,k.r)select stuff((select','+cast(x.s as varchar)from H x where x.p=z.p for xml path('')),1,1,'')from H z group by z.p

Online demo
Try it online!
Verbose version - with notes as SQL comments
WITH gen -- numbers 1 to 60
AS (
    SELECT 1 AS num
    UNION ALL
    SELECT num+1 FROM gen WHERE num+1<=60
),
BINARIES -- string representations of binaries 000001 through 111111
as (
SELECT
    +cast( cast(num & 32 as bit) as CHAR(1))
    +cast( cast(num & 16 as bit)  as CHAR(1))
    +cast( cast(num & 8 as bit)  as CHAR(1))
    +cast( cast(num & 4 as bit)  as CHAR(1))
    +cast( cast(num & 2 as bit)   as CHAR(1))
    +cast(cast(num & 1 as bit)  as CHAR(1)) as binry FROM gen
),
POWERS -- first 6 powers of 2
as (
SELECT * from (values(1), (2), (4), (8), (16), (32)) as Q(powr)
),
SETELEMENTS -- cross apply the six powers of 2 against the binaries
-- returns 2 cols. col 1 = the power of 2 in question.
-- col 2 is calculated as that power of 2 plus the sum of each power of 2 other than the current row's power value,
-- but only where a given power of 2 is switched "on" in the binary string,
-- ie. where the first digit in the string represents 32, the second represents 16 and so on.
-- That is, if the binary is 100100 then the number will be
-- the sum of (32 x 1) + (16 x 0) + (8 x 0) + (4 x 1) + (2 x 0) + (1 x 0)
-- but if the current row's power is 32 or 4, then just that number (32 or 4) is excluded from the sum.
-- rows are distinct.
as (
select distinct powr,
powr+
 (substring(binry,6,1) * 1) * (case when powr = 1 then 0 else 1 end)
 +(substring(binry,5,1) * 2) * (case when powr = 2 then 0 else 1 end)
 +(substring(binry,4,1) * 4) * (case when powr = 4 then 0 else 1 end)
 +(substring(binry,3,1) * 8) * (case when powr = 8 then 0 else 1 end)
 +(substring(binry,2,1) * 16) * (case when powr = 16 then 0 else 1 end)
 +(substring(binry,1,1) * 32) * (case when powr = 32 then 0 else 1 end) as elt
from POWERS cross apply BINARIES
),
DISTINCTELEMENTS -- purge calculated numbers smaller than the power of 2 or greater than 60
as (
select * from SETELEMENTS where elt >= powr and elt < 61
)--,
,
ROWNUMBERED -- for each power, number the rows repeatedly from 0 through 5, then back to 0 through 5 again, etc
as (
select powr, (row_number() over (partition by powr order by cast(elt as int)))%5 as r, elt  from DISTINCTELEMENTS
),
GROUPEDSETS -- for each row number, within each power, aggregate the numbers as a comma-delimited list and wrap in square brackets - the inner arrays
as (
select r1.powr, '['+stuff((select ',' + cast(r2.elt as varchar) from ROWNUMBERED r2 where r2.powr = r1.powr and r2.r = r1.r for xml path('')),1,1,'')+']' as s
from ROWNUMBERED r1
group by r1.powr,r1.r
)
select -- now aggregate all the inner arrays per power
stuff((select ',' + cast(g2.s as varchar) from GROUPEDSETS g2 where g2.powr = g1.powr for xml path('')),1,1,'')
from GROUPEDSETS g1
group by g1.powr

Voila!
Note 1: Some of the logic pertains to rendering square brackets and commas.
Note 2: Newer versions of SQLServer have more compact approaches to creating comma-delimited lists. (This was created on SQL Server 2016.)
Note 3: Arrays for a given card are not sorted (which is ok per the spec). Numbers within an array are correctly sorted. In this case, each "card" of the question, renders its arrays on a separate row in the results.
Shorter to hard-code arrays?
Yes.
Byte me.

Jeez, wouldn't it be shorter to just hardcode the result?

Haha. Neither as fun, nor extensible.

I do not fully understand -- are you saying that your solution only works by chance or are you convinced you followed the specifications correctly?

@JonathanFrech - I did not explicitly code for the ordering of the numbers, although there may be an implicit condition in the language resulting in a guaranteed order. They render in correct ascending order. Separately, after posting, I realised I had misunderstood how the data were to be presented (in striped arrays per card, rather than one single set per card) - so have yet to solve that problem. As such, the result currently renders the correct numbers, in ascending order, within each of the 6 expected sets - see the linked sql fiddle. Still to do: break the sets into 5 subsets each.

I appreciate your effort but if your solution is not correct, please fix it or delete your post. We generally do not allow for invalid answers to linger.

@JonathanFrech fixed.

:| "viola" is a musical instrument

It'll be violins soon

Wolfram Language (Mathematica), 99 bytes
Transpose@Partition[#~FromDigits~2&/@Last@GatherBy[{0,1}~Tuples~6,#[[-k]]&],5]~Table~{k,6}/. 61->-1

Try it online!

You can save a few char by: doing Transpose@ instead of Transpose[...]; padding to 30 entries before partitioning; using Table[...,{k,6}] to avoid needing k=#.

@Bruno Le Floch Table may save one byte. Did you try transpose@? Because it doesn't work if you watch carefully. I'm afk but will golf later

Sorry, Transpose@ works after you move PadRight inside Partition.  Another comment is that the question does not seem to allow "" for the placeholder; you can replace it by -1 without losing any byte.

Jelly, 13 bytes
60B€Uz0µTs5Z)

Try it online!
Loosely based on flawr’s MATL answer. A niladic link which outputs a list of lists as required.

Red, 108 107 bytes
n: 32 until[b: collect[repeat k 60[if n and k = n[keep k]]]loop 5[print
extract b 5 b: next b]1 > n: n / 2]

Try it online!

APL+WIN, 65 62 bytes
v←∊+\¨n,¨29⍴¨1↓¨(n⍴¨1),¨1+n←2*0,⍳5⋄((v=61)/v)←¯1⋄1 3 2⍉6 6 5⍴v

Try it online! Courtesy of Dyalog Classic

C# (Visual C# Interactive Compiler), 112 bytes
_=>" ".Select(x=>Enumerable.Range(1,60).Where(l=>(l&x)>0).Select((a,b)=>new{a,b}).GroupBy(i=>i.b%5,i=>i.a))

Try it online!

MATLAB, 155 bytes
cellfun(@disp,cellfun(@(x)x-repmat(62,5,6).*(x>60),cellfun(@(x)reshape(find(x,30),[5 6]),mat2cell(dec2bin(1:62)-48,62,ones(1,6)),'Uniform',0),'Uniform',0))

This could be shorter as multiple lines but I wanted to do it in one line of code.

Could you perhaps add a TIO link with test code, so I can verify the output?

05AB1E, 14 bytes
žOε60LDNo&ĀÏ5ι

Try it online!

Why the žO instead of just 6L? I know you're not using them in your map, but I'm curious why you've used aeiouy to create a list with 6 values. xD Nice answer, btw!

@KevinCruijssen No particular reason, I just thought it was funnier than 6L, 6и, 5Ý, 5°, or 9!.

It certainly caught my eye, that's for sure. ;)

@KevinCruijssen I just realized тœ, ₅œ, ₁œ,  also work, those are pretty cool too (:

₆b would work as well ;)


text:
Alphabetical Justice Warrior
Introduction:
Aaron is a young game developer. He recently joined the development team of a game where the players select their character from a predefined set, aka "heroes". Unfortunately, the names of the existing heroes are not evenly distributed throughout the alphabet. For example, there are 6 heroes that have a name starting with C, but only 5 starting with A or B. Since the game will continue to add new heroes, and Aaron has a saying in how to name those, he is determined to try "smoothening" the distribution of hero names.
Of course, he cannot simply mathematically generate names as gap fillers, because those suggestions would be unpronounceable and thus rejected right away. Therefore, instead of calculating a name, Aaron opted to go with "just" a helper for his creative process that helps him to focus on the right things to do:
He will calculate the "distance" between each two names following each other in alphabetical order, and then print the top ten biggest gaps between two names. This way Aaron can try to focus on finding a name that comes in between those two, so he'll eventually create a smoother equidistant descend throughout the alphabet as the list of heroes continues to grow.
The Challenge
For a given list of names, generate the entries' keys that consist of only the uppercase form of the letters [A-Za-z]. Calculate a distance between each two alphabetically adjacent keys.
The first key is additionally compared to the first possible key "A", the last to the last possible key "ZZZZZZZZZZZZ".
Print the top ten (or all if there are less) biggest gaps in descending order with both names as given by the input and a measurement for the size of the gap. The "given name" of the borders is an empty string.
Input data
The list of names. Conditions as follows:
Entries:

The entries are guaranteed to only contain printable ASCII characters (sorry Björn NUL LF)
The characters may have any case ("Tim", to be treated same as "TIM")
The entries have different lengths ("Anna", "Jon")
The entries are guaranteed to not contain commas, so you can use that as safe delimiter for your outputs
The entries do contain other characters such as spaces or dots, which do not change the key as stated above ("Mr. T", to be treated same as "MRT")
The entries are guaranteed to give keys within 1 to 12 (inclusive) letters (entries won't be "" or "-.-.-. -.--.-" or "Gandalf the White")
The entries explicitly may contain single quotes ' and double quotes ", in case this is important for escaping

List:

The entries are not guaranteed to come in any particular order (e. g.
"Eve", "Dr. Best", "Dracula", keys sorted "DRACULA", "DRBEST", "EVE")
The list is guaranteed to have at least one entry
The list is guaranteed to have only entries with distinct keys
The list will not (and must not!) contain any entries that will give the keys "A" or "ZZZZZZZZZZZZ"

Example
This was done in Excel. I limited the maximum length of 7 letters though for practical reasons (see notes), but the point should be clear.
List: ["Tim", "Mr. T", "Anna", "Jon", "Eve", "Dr. Best", "Timo", "Dracula"]
Keys: ["TIM", "MRT", "ANNA", "JON", "EVE", "DRBEST", "TIMO", "DRACULA"]
Ordered: ["ANNA", "DRACULA", "DRBEST", "EVE", "JON", "MRT", "TIM", "TIMO"]
Values: [595765044, 1808568406, 1809137970, 2255435604, 4096878669, 5305375503, 7884458676, 7884753921]
Distances: [1212803362, 569564, 446297634, 1841443065, 1208496834, 2579083173, 295245]
Distance from "ANNA" to "A": 208344555
Distance from "TIMO" to "ZZZZZZZ": 2575894526

Output (padding added for clarity, see "Rules #4"):
[    Mr. T,      Tim, 2579083173 ]
[     Timo,         , 2575894526 ]
[      Eve,      Jon, 1841443065 ]
[     Anna,  Dracula, 1212803362 ]
[      Jon,    Mr. T, 1208496834 ]
[ Dr. Best,      Eve,  446297634 ]
[         ,     Anna,  208344555 ]
[  Dracula, Dr. Best,     569564 ]
[      Tim,     Timo,     295245 ]

Interpretation: Aaron should focus on finding a name in the middle between "Mr. T" and "Tim". Welcome Pyrion, splitting 2579083173 into 1261829394 + 1317253779, while sounding absolutely badass! This is not part of the challenge however, only the top ten pairs and their distance should be output.
Rules

Ex falso sequitur quodlibet. If the input data does not conform to the rules set above, the program may do whatever, including crashing.
You are free to chose your method of measurement for the distance, but it has to ensure the following: AAA and AAC are further apart than AAA and AAB. AAA is closer to AAB than to ABA. AA comes after A (so basically: all possible names are ordered lexicographically). This means the distance in the output could differ per answer, but the order of the pairs are strict.
Range and precision of the gaps is arbitrary, as long as you have a non-zero distance between "AAAAA AAAAA AA" and "AAAAA AAAAA AB".
The output has to contain the names as given (not the keys) and the distance. The precise formatting is up to you, as long as it's clear what belongs together. Name1,Name2,Distance is a safe bet.
As mentioned earlier, if there are more than ten results, only output the top ten.
The borders of "A" and "ZZZZZZZZZZZZ" are empty strings in the output.

Winner

Code golf, shortest code by bytes wins.

Notes

The example above was done in Excel and uses a base 27 number system. It was limited to 7 letters, because for 12, the upper bound would be 27^13 - 1 = 4,052,555,153,018,976,266 which exceeds Excel's internal number range. If you were to add a test-link for your code which times out for 12 letter keys, feel free to use a smaller value so your program can be verified in the test-link.
I am aware that the "measurement of the gap size" may vary depending on the algorithm. Some might not even have "one number" to sum it up. Try your best to find something conveying that finding a name between "Mr. T" and "Tim" helps a lot more than between "Mr. T" and "Jon" on our road to more equidistant names.
This is my first posting here, feel free to comment if I need to add or clarify something. I've been looking at other content and hope I did everything right.
The problem is derived from an actual problem I had to solve lately and I thought it might be a fun one to post it here.

Comments are not for extended discussion; this conversation has been moved to chat.

Perl 6, 136 bytes
{$!=$;$/=1;(|.sort(&h),'').map({~$!,~($!=$_),-$/+($/=(sort('A'..'Z'x 12)....&h||'Z'x 12))}).sort(-*[2])[lazy ^10]}
my&h={S:g/<:!L>//.uc}

Try it online!
This is an anonymous code block that takes a list of strings and returns a list of lists. This uses a brute forcey method which takes far too long to attempt 12 letter names, so here is a link to a version with only 3 letter names.
Explanation:
my&h={              }  # Helper function.
      S:g/<:!L>//      # This removes non-alpha characters
                 .uc   # Convert to uppercase

{              # Actual code block
  $!=$;        # Initialise the "first" element as an empty string
  $/=1;        # With value 1
  (|.sort(&h)  # Sort the input by the helper function
   ,'')        # And add the last string as an empty string
  .map({       # Map each value to
    ~$!,          # The previous name
    ~($!=$_),     # The current name
    -$/           # The negative of the previous value
       +($/=(     # Plus the new value, which is:
             sort('A'..'Z'x 12)     # From the lexographically sorted list of names
             ...                    # Get the sublist up to
                .&h                 # The current name
                   ||'Z'x 12        # Or the last name if the current is empty
        ))   # And get the length of the list
   }).sort(      # Sort each list
     *[2]        # By the third element
   )[lazy ^10]   # And get the first 10 or less items

Haha, I didn't even think about "brute forcing" it, but I like the idea. If that's shorter, why not... One question though: the order of elements seems to be correct, but it does not seem to output the second element per tuple? I'd expect (value aside) (gfd, qwe, #) (bcv, gfd, #) (uyt, zde, #) ... and your output is (gfd #) (bcv #) (uyt #) .... So it seems right, but the second half of the pair is missing.

@LWChris Ah, sorry. I removed a pair of brackets to golf it, but turned out to break that. This should be fixed now

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Enumerate Derangements
Given some positive integer \$n\$ generate all derangements of \$n\$ objects.
Details

A derangement is a permutation with no fixed point. (This means in every derangement number \$i\$ cannot be in the \$i\$-th entry).
The output should consist of derangements of the numbers \$(1,2,\ldots,n)\$ (or alternatively \$(0,1,2,\ldots,n-1)\$).
You can alternatively always print derangements of \$(n,n-1,\ldots,1)\$ (or \$(n-1,n-2,\ldots,1,0)\$ respectively) but you have to specify so.
The output has to be deterministic, that is whenever the program is called with some given \$n\$ as input, the output should be the same (which includes that the order of the derangements must remain the same), and the complete output must be done within a finite amount of time every time (it is not sufficient to do so with probability 1).
You can assume that \$ n \geqslant  2\$
For some given \$n\$ you can either generate all derangements or alternatively you can take another integer \$k\$ that serves as index and print the \$k\$-th derangement (in the order you chose).

Examples
Note that the order of the derangements does not have to be the same as listed here:
n=2: (2,1)
n=3: (2,3,1),(3,1,2)
n=4: (2,1,4,3),(2,3,4,1),(2,4,1,3), (3,1,4,2),(3,4,1,2),(3,4,2,1), (4,1,2,3),(4,3,1,2),(4,3,2,1)

OEIS A000166 counts the number of derangements.

Can we submit a generator?

@Fatalize Yes I think this would be similar enough to the other two mentioned methods (or do you think there is a strong argument against it?).

@Fatalize Actually it seems returning a generator instead of a list is possible by default.

Jelly, 6 bytes
Œ!=ÐṂR

A monadic Link accepting a positive integer which yields a list of lists of integers.
Try it online!
How?
Œ!=ÐṂR - Link: integer, n
Œ!     - all permutations of (implicit range of [1..n])
     R - range of [1..n]
   ÐṂ  - filter keep those which are minimal by:
  =    -   equals? (vectorises)
       -   ... i.e. keep only those permutations that evaluate as [0,0,0,...,0]

Brachylog, 9 bytes
⟦kpiᶠ≠ᵐhᵐ

Try it online!
This is a generator that outputs one derangement of [0, …, n-1] given n.
If we wrap it in a ᶠ - findall metapredicate, we get all possible generations of derangements by the generator.
Explanation
⟦           The range [0, …, Input]
 k          Remove the last element
  p         Take a permutation of the range [0, …, Input - 1]
   iᶠ       Take all pair of Element-index: [[Elem0, 0],…,[ElemN-1, N-1]]
     ≠ᵐ     Each pair must contain different values
       hᵐ   The output is the head of each pair

JavaScript (V8), 85 bytes
A recursive function printing all 0-based derangements.
f=(n,p=[],i,k=n)=>k--?f(n,p,i,k,k^i&&!p.includes(k)&&f(n,[...p,k],-~i)):i^n||print(p)

Try it online!
Commented
f = (                   // f is a recursive function taking:
  n,                    //   n   = input
  p = [],               //   p[] = current permutation
  i,                    //   i   = current position in the permutation
  k = n                 //   k   = next value to try
) =>                    //         (a decrementing counter initialized to n)
  k-- ?                 // decrement k; if it was not equal to 0:
    f(                  //   do a recursive call:
      n, p, i, k,       //     leave all parameters unchanged
      k ^ i &&          //     if k is not equal to the position
      !p.includes(k) && //     and k does not yet appear in p[]:
        f(              //       do another recursive call:
          n,            //         leave n unchanged
          [...p, k],    //         append k to p
          -~i           //         increment i
                        //         implicitly restart with k = n
        )               //       end of inner recursive call
    )                   //   end of outer recursive call
  :                     // else:
    i ^ n ||            //   if the derangement is complete:
      print(p)          //     print it

Ruby, 55 bytes
->n{[*0...n].permutation.select{|x|x.all?{|i|i!=x[i]}}}

Try it online!
Generates all 0-based derangements

05AB1E, 9 bytes
Lœʒāø€Ë_P

Try it online!
Explanation
L           # push [1 ... input]
 œ          # get all permutations of that list
  ʒ         # filter, keep only lists that satisfy
   āø       # elements zipped with their 1-based index
     €Ë_P   # are all not equal

Wolfram Language (Mathematica), 55 bytes
Select[Permutations[s=Range@#],FreeQ[Ordering@#-s,0]&]&

Try it online!

Japt, 8 bytes
0-based
o á fÈe¦

Try it (Footer increments all elements for easier comparison with the test cases)
o á fÈe¦     :Implicit input of integer
o            :Range [0,input)
  á          :Permutations
    f        :Filter
     È       :By passing each through this function
      e      :  Every element of the permutation
       ¦     :  Does not equal its 0-based index

Python 2, 102 bytes
lambda n:[p for p in permutations(range(n))if all(i-j for i,j in enumerate(p))]
from itertools import*

Try it online!
0-based indexing, list of tuples.
Non-itertools-based solution:
Python 2, 107 bytes
n=input()
for i in range(n**n):
 t=[];c=1
 for j in range(n):c*=j!=i%n not in t;t+=[i%n];i/=n
 if c:print t

Try it online!
0-based indexing, lines of lists, full program.
Note: This solution, even though it doesn't import the itertools library, isn't much longer than the other one which does import it, because most of the bulk here is building the permutations. The derangement check is really about 7 additional bytes! The reason is that the check is done on the fly as part of the building of each permutation. This isn't true for the other solution, where you have to check if each permutation returned by the itertools.permutations function is in fact a derangement, and, of course, the mapping itself takes a lot of bytes.

Perl 5 -MList::Util=none -n, 100 89 bytes
$"=',';@b=1..$_;map{%k=$q=0;say if none{++$q==$_||$k{$_}++}/\d+/g}glob join$",("{@b}")x@b

Try it online!

MATL, 11 bytes
:tY@tb-!AY)

This generates all derangements in lexicographical order.
Try it online!
Explanation with example
Consider input 3.
:     % Implicit input n. Range [1 2 ... n]
      % STACK: [1 2 3]
t     % Duplicate
      % STACK: [1 2 3], [1 2 3]
Y@    % All permutations, in lexicographical order, as rows of a matrix
      % STACK: [1 2 3], [1 2 3; 1 3 2; ··· ; 3 2 1]
t     % Duplicate
      % STACK: [1 2 3], [1 2 3; 1 3 2; ··· ; 3 2 1], [1 2 3; 1 3 2; ··· ; 3 2 1]
b     % Bubble up: moves third-topmost element in stack to the top
      % STACK: [1 2 3; 1 3 2; ··· ; 3 2 1], [1 2 3; 1 3 2; ··· ; 3 1 2; 3 2 1], [1 2 3]
-     % Subtract, element-wise with broadcast
      % STACK: [1 2 3; 1 3 2; ··· ; 3 2 1], [0 0 0; 0 1 -1; ··· ; 2 -1 -1; 2 0 -2]
!A    % True for rows containining only nonzero elements
      % STACK: [1 2 3; 1 3 2; ··· ; 3 1 2; 3 2 1], [false false ··· true false]
Y)    % Use logical mask as a row index. Implicit display
      % STACK: [2 3 1; 3 1 2]

Haskell, 58 bytes
f n|r<-[1..n]=[l|l<-mapM(\i->filter(/=i)r)r,all(`elem`l)r]

Try it online!
60 bytes
f n|r<-[1..n]=foldr(\i m->[x:l|l<-m,x<-r,all(/=x)$i:l])[[]]r

Try it online!

J, 26 bytes
i.(]#~0~:*/@(-|:))i.@!A.i.

Try it online!
i. (] #~ 0 ~: */@(- |:)) i.@! A. i.
i. (                   )            NB. 0..input
   (                   ) i.@! A. i. NB. x A. y returns the
                                    NB. x-th perm of y
                                    NB. i.@! returns
                                    NB. 0..input!. Combined
                                    NB. it produces all perms
                                    NB. of y
    ] #~ 0 ~: */@(- |:)             NB. those 2 are passed as
                                    NB. left and right args
                                    NB. to this
    ] #~                            NB. filter the right arg ]
                                    NB. (all perms) by:
         0 ~:                       NB. where 0 is not equal to...
              */@                   NB. the product of the
                                    NB. rows of...
                 (- |:)             NB. the left arg minus
                                    NB. the transpose of
                                    NB. the right arg, which
                                    NB. will only contain 0
                                    NB. for perms that have
                                    NB. a fixed point

R, 81 80 bytes
function(n)unique(Filter(function(x)all(1:n%in%x&1:n-x),combn(rep(1:n,n),n,,F)))

Try it online!
Returns a list containing all derangements. Highly inefficient, as it generates \$ n^2\choose n\$ possible values as the size-n combinations of [1..n] repeated n times, then filters for permutations 1:n%in%x and derangements, 1:n-x.
R + gtools, 62 bytes
function(n,y=gtools::permutations(n,n))y[!colSums(t(y)==1:n),]

Try it online!
Much more efficient, returns a matrix where each row is a derangement.

Gaia, 10 bytes
┅f⟨:ċ=†ỵ⟩⁇

Try it online!
┅		| push [1 2 ... n]
 f		| push permutations
  ⟨	⟩⁇	| filter where result of following is truthy
   :ċ		| dup, push [1 2 ... n]
     =†ỵ	| there is no fixed point

C++ (gcc), 207 196 bytes
-5 bytes by ceilingcat
-6 bytes by Roman Odaisky
#include<regex>
#define v std::vector
auto p(int n){v<v<int>>r;v<int>m(n);int i=n;for(;m[i]=--i;);w:for(;std::next_permutation(&m[0],&m[n]);r.push_back(m))for(i=n;i--;)if(m[i]==i)goto w;return r;}

Try it online!

You can do much better if you use an output parameter, particularly if it’s an std::array so it’s pre-sized — 145 bytes

@RomanOdaisky: nice idea, but how I understand the rules of code golf, you'll have to take the preallocation code into your byte count.

@movatica A gray area, I think the code is more likely valid than invalid. It will happily write the correct results somewhere, and it’s the caller’s responsibility of reading the output. Note that STL algorithms such as std::copy likewise entrust the caller with providing adequate space for the output.

@RomanOdaisky: STL behaviour is indeed a valid argument.

Python 3.8 (pre-release), 96 bytes
lambda n:(p for i in range(n**n)if len({*(p:=[j for k in range(n)for j in{i//n**k%n}-{k}])})==n)

Try it online!

Perl 6, 49 37 bytes
Edit: After some back and forth with Phil H, we've whittled it down to only 37 bytes:
(^*).permutations.grep:{all @_ Z-^@_}

Try it online!
By using the Whatever at the beginning, we can avoid the brackets (saves 2 chars).  Next use a the Z metaoperator with - which takes each element of a permutation (e.g. 2,3,1) and subtracts 0,1,2 in order.  If any of them are 0 (falsy) then the all junction fails.

Original solution was (Try it online!)
{permutations($_).grep:{none (for $_ {$++==$_})}}

Good start, you can make the filter shorter with Z on != for -7 bytes: https://tio.run/##K0gtyjH7n1upoJamYKvwv7ogtSi3tCSxJDM/r1hDJV5TL70otcCq2j4xJ0fBIV4hStFWIU7bIb629r81V3EiSJuGkSacaYxgmgCZ/wE

@PhilH I knew there has to be a way to integrate the zip operator but I couldn't quite figure it out. Nice

PhilH using that strategy, can still knock another 3 by killing parentheses: https://tio.run/##K0gtyjH7n1upoJamYKvwv7ogtSi3tCSxJDM/r1hDJV5TL70otcCqOs4hXrGuziG@tva/NVdxIki5hpEmnGmMYJoAmf8B

PhilH that last one doesn't work. For all but n=2 more than just one element will be rejected

Of course, forgot the requirement... removed

Marginal improvement using Whatever star (39 b), but still seems suboptimal: https://tio.run/##K0gtyjH7n1upoJamYKvwXyNOS1OvILUot7QksSQzP69YL70otcCqOjEnR8EhXiFKVyFO2yG@9r81V3EiSI@GkSacaYxgmgCZ/wE

PhilH: space isn't needed after the operator and you don't need to nummify the array, because the range operator takes care of that: https://tio.run/##K0gtyjH7n1upoJamYKvwXyNOS1OvILUot7QksSQzP69YL70otcCqOjEnR8EhXiFKN84hvva/NVdxIkiHhpEmnGmMYJoAmf8B (I'll update the answer when I'm not on mobile)

C++ (gcc), 133 bytes
I think this has grown different enough from the other submission to merit a separate answer. Finally a use for index[array] inside-out syntax!
#include<regex>
[](int n,auto&r){int i=n;for(;i[*r]=--i;);for(;std::next_permutation(*r,*r+n);)for(i=n;i--?(r[1][i]=i[*r])-i:!++r;);}

Try it online!

Haskell, 76 bytes
n&x=[x++[i]|i<-[1..n],notElem i x,i/=length x+1]
d n=iterate(>>=(n&))[[]]!!n

Python 2, 82 bytes
f=lambda n,i=0:i/n*[[]]or[[x]+l for l in f(n,i+1)for x in range(n)if~-(x in[i]+l)]

Try it online!
88 bytes as program:
M=[],
r=range(input())
for i in r:M=[l+[x]for l in M for x in r if~-(x in[i]+l)]
print M

Try it online!
93 bytes using itertools:
from itertools import*
r=range(input())
print[p for p in permutations(r)if all(map(cmp,p,r))]

Try it online!

Charcoal, 44 28 bytes
crossed out 44 is still regular 44
ＮθＩΦＥＸθθＥθ﹪÷ιＸθλθ⬤ι‹⁼μλ⁼¹№ιλ

Try it online! Link is to verbose version of code. Loosely based on @EricTheOutgolfer's non-itertools answer. Explanation:
Ｎθ                              Input `n`
     Ｘθθ                        `n` raised to power `n`
    Ｅ                           Mapped over implicit range
         θ                      `n`
        Ｅ                       Mapped over implicit range
            ι                   Outer loop index
           ÷                    Integer divided by
             Ｘθ                 `n` raised to power
               λ                Inner loop index
          ﹪     θ               Modulo `n`
   Φ                            Filtered where
                  ι             Current base conversion result
                 ⬤              All digits satisfy
                         №ιλ    Count of that digit
                       ⁼¹       Equals literal 1
                   ‹            And not
                    ⁼μλ         Digit equals its position
  Ｉ                             Cast to string
                                Implicitly print

C (gcc), 187 180 bytes

Saved seven bytes thanks to ceilingcat.

*D,E;r(a,n,g,e){e=g=0;if(!a--){for(;e|=D[g]==g,g<E;g++)for(n=g;n--;)e|=D[n]==D[g];for(g*=e;g<E;)printf("%d ",D[g++]);e||puts("");}for(;g<E;r(a))D[a]=g++;}y(_){int M[E=_];D=M;r(_);}

Try it online!

Pyth, 12 bytes
f*F.e-bkT.PU

Try it online!
           UQ # [implicit Q=input] range(0,Q)
         .P  Q# [implicit Q=input] all permutations of length Q
f             # filter that on lambda T:
   .e   T     #   enumerated map over T: lambda b (=element), k (=index):
     -bk      #     b-k
 *F           # multiply all together

The filter works like this: if any element is at its original spot, (element-index) will be 0 and the whole product will be 0, and thus falsey.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Upside-Down Pyramid Addition...REVERSED!
Upside-Down Pyramid Addition is the process of taking a list of numbers and consecutively adding them together until you reach one number.
When given the numbers 2, 1, 1 the following process occurs:
 2   1   1
   3   2
     5

This ends in the number 5.

YOUR TASK
Given the right side of an Upside-Down Pyramid (Ascending), write a program or function that will return the original list.
New Extra Challenge: Try doing this in less than O(n^2)
EXAMPLE
f([5, 2, 1]) => [2, 1, 1]
f([84,42,21,10,2]) => [4,7,3,8,2]

NOTE: The Upside-Down Pyramid will never be empty and will always consist of positive integers ONLY.

Welcome to PP&CG!  This challenge is decent, though it could be improved.  I'd recommend posting your challenges in the Sandbox first to improve the post before it's put on main.

Do the input and output have to be in the order given (top to bottom and left to right respectively), or can either or both be reversed?

The input will go from bottom to top. The output must be from left to right

Free insight that I can't find a language it's shorter in: $$f([a,b,c,d,e]) = \begin{bmatrix} 1&-4&6&-4&1 \ 0&1&-3&3&-1 \ 0&0&1&-2&1 \ 0&0&0&1&-1 \ 0&0&0&0&1 \end{bmatrix} \cdot \begin{bmatrix}a\b\c\d\e\end{bmatrix} $$

Just FYI, this is the same as the CodeWars kata.

@ggorlen i know. I’m the one who made the kata :)

Try doing this in less than O(n) surely it's impossible to allocate a n-sized array or change O(n) items in it faster than O(n) complexity?

Suggested test case: 1 => 1

@someone fixed, thanks for catching that, I meant quadratic time, not linear.

JavaScript (ES6),  62 58 49  46 bytes
Saved 3 bytes thanks to @Oliver
Returns the list as a comma-separated string.
f=a=>+a||f(a.map(n=>a-(a=n),a=a.shift()))+[,a]

Try it online!
Commented
f = a =>              // f = recursive function taking the input list a[]
  +a                  // if a[] consists of a single positive integer:
                      //   stop recursion and return this integer
  ||                  // else:
    f(                //   do a recursive call to f:
      a.map(n =>      //     for each value n in a[]:
        a - (a = n),  //       yield the difference between the previous value and n
                      //       and update a to n
        a = a.shift() //       start by removing the first element and saving it in a
                      //       (because of the recursion, it's important here to reuse
                      //       a variable which is defined in the scope of f)
      )               //     end of map()
    )                 //   end of recursive call
    + [, a]           //   append the last entry from a[]

@Oliver, yes

Haskell, 22 bytes
foldl(flip$scanr(-))[]

Try it online!

Haskell, 42 bytes
f[]=[]
f a=f(zipWith(-)a$tail a)++[last a]

Try it online!

TI-BASIC, 54 bytes
Ans→L₁:dim(L₁→dim(L₂:While 1-Ans:L₁(Ans→L₂(Ans:-ΔList(L₁→L₁:dim(Ans:End:L₁(Ans→L₂(Ans:L₂

Input is the list of the right side of the triangle in Ans, as is described in the challenge.
Output is the top row of said triangle.
Examples:
{5,2,1
         {5 2 1}
prgmCDGF19
         {2 1 1}
{84,42,21,10,2
 {84 42 21 10 2}
prgmCDGF19
     {4 7 3 8 2}

Explanation:
This solution abuses the fact that the triangle formed using the right side of the triangle as the start ends up being the change in each element.
In other words,
2 1 1
 3 2
  5

becomes:
5 2 1
 3 1
  2

Thus, the resulting list is the right side of this new triangle, which can be formed by setting the last element to the index of its parent list's length in the resulting list.
Ans→L₁          ;store the input list in L₁
dim(L₁→dim(L₂   ;set the length of L₂ to the length of L₁
While 1-Ans     ;while the L₁'s length is not 1
L₁(Ans→L₂(Ans   ;set the last element of L₁ to the corresponding index in L₂
-ΔList(L₁→L₁    ;get the change in each element, then negate
                ; (elements are in descending order so the change in each
                ;  element will be negative)
                ; and store the resulting list in L₁
dim(Ans         ;leave the length of L₁ in "Ans"
End
L₁(Ans→L₂(Ans   ;set the element again
                ; (needed for final step)
L₂              ;leave L₂ in "Ans"
                ;implicit print of "Ans"

Note:  TI-BASIC is a tokenized language.  Character count does not equal byte count.

MathGolf, 14 11 bytes
xÆ‼├│?;∟;]x

Try it online!
Explanation
x             reverse int/array/string
 Æ     ∟      do while true without popping using 5 operators
  ‼           apply next 2 operators to TOS
   ├          pop from left of list
    │         get differences of list
     ?        rot3
      ;       discard TOS (removes rest from ├ command)
              loop ends here
        ;     discard TOS (removes empty array from stack)
         ]    wrap stack in array
          x   reverse array

Jelly, 6 bytes
ṚIƬZḢṚ

A monadic Link accepting a list of integers which yields a list of integers.
Try it online!
How?
Builds the whole triangle then extracts the required elements.
ṚIƬZḢṚ - Link: list of integers          e.g.  [84,42,21,10,2]
Ṛ      - reverse                               [2,10,21,42,84]
  Ƭ    - collect & apply until a fixed point:
 I     -   incremental differences            [[2,10,21,42,84],[8,11,21,42],[3,10,21],[7,11],[4],[]]
   Z   - transpose                            [[2,8,3,7,4],[10,11,10,11],[21,21,21],[42,42],[84]]
    Ḣ  - head                                  [2,8,3,7,4]
     Ṛ - reverse                               [4,7,3,8,2]

Had an almost identical solution but with Us instead of Ṛ!

IƬUZḢA would work with the given question too; I wonder if there is a byte save somewhere...

ạƝƬZṪ€ works too but is again a six.

Yep, I noticed that variant; I'm less hopeful now.

I just posted a 5-byter, but it's a bit different than your approach regarding the part  after the pyramid construction.

@EriktheOutgolfer Ah ha, that'll do it.

Python 2, 56 bytes
f=lambda a:a and f([l-r for l,r in zip(a,a[1:])])+a[-1:]

A recursive function accepting a list of positive integers which returns a list of non-negative integers.
Try it online!

Jelly, 5 bytes
_ƝƬa/

Try it online!
We can assume the whole pyramid is positive, so we can use a && operation instead of a "right" operation.

Pari/GP, 36 bytes
Based on @Lynn's comment:

Free insight that I can't find a language it's shorter in:
  $$f([a,b,c,d,e]) = \begin{bmatrix} 1&-4&6&-4&1 \\ 0&1&-3&3&-1 \\ 0&0&1&-2&1 \\ 0&0&0&1&-1 \\ 0&0&0&0&1 \end{bmatrix} \cdot \begin{bmatrix}a\\b\\c\\d\\e\end{bmatrix}$$

Pari/GP has a built-in for the Pascal matrix, and its inverse is exactly the matrix we need:
$$\begin{bmatrix} 1&0&0&0&0 \\ 1&1&0&0&0 \\ 1&2&1&0&0 \\ 1&3&3&1&0 \\ 1&4&6&4&1 \end{bmatrix}^{-1} = \begin{bmatrix} 1&0&0&0&0 \\ -1&1&0&0&0 \\ 1&-2&1&0&0 \\ -1&3&-3&1&0 \\ 1&-4&6&-4&1 \end{bmatrix}$$
a->r=Vecrev;r(r(a)/matpascal(#a-1)~)

Try it online!

R, 69 67 bytes
function(n,x=sum(n|1):1-1,`[`=outer)(x[x,choose]*(-1)^x[x,"+"])%*%n

Try it online!
Returns a column vector.
-2 bytes thanks to Kirill L.
Also based on Lynn's comment:

Free insight that I can't find a language it's shorter in:
  $$f([a,b,c,d,e]) = \begin{bmatrix} 1&-4&6&-4&1 \\ 0&1&-3&3&-1 \\ 0&0&1&-2&1 \\ 0&0&0&1&-1 \\ 0&0&0&0&1 \end{bmatrix} \cdot \begin{bmatrix}a\\b\\c\\d\\e\end{bmatrix}$$

It's longer than the other R answer, but it was an interesting approach to take and try to golf.

R, 55 63 55 53 bytes
x=scan();for(i in sum(1|x):1){F[i]=x[i];x=-diff(x)};F

Try it online!
-2 bytes thanks to Giuseppe.

Javascript (ES6), 127 bytes
f=a=>{for(e=[a],a=[a[l=a.length-1]],i=0;i<l;i++){for(e.push(g=[]),j=-1;j<l;)g.push(e[i][j]-e[i][++j]);r.unshift(g[j])}return r}

Original code
function f(a){
  var e=[a];
  var r=[a[a.length-1]];
  for (var i=1;i<a.length;i++){
    var g=[];
    for (var j=0;j<a.length;j++){
      g.push(e[i-1][j-1]-e[i-1][j]);
    }
    e.push(g);
    r.unshift(g[j-1]);
  }
  return r;
}

Oh, I lost like... a lot... to the previous answer...

Perl 6, 37 bytes
{[R,]($_,{@(.[]Z-.skip)}...1)[*;*-1]}

Try it online!
Repeatedly reduces by elementwise subtraction, and then returns the last number of each list in reverse.
Explanation:
{                                  }  # Anonymous code block
      $_,               ...   # Create a sequence starting from the input
         {             }      # Where each element is
            .[]Z-.skip          # Each element minus the next element
          @(          )         # Arrayified
                           1  # Until the list has one element left
 [R,]                                # Reverse the sequence
     (                     )[*;   ]  # For every list
                               *-1   # Take the last element

05AB1E, 12 11 bytes
R.¥.Γ¥}¨ζнR

Port of @JonathanAllan's Jelly answer, although I'm jelly about Jelly's more convenient builtins in this case. ;)
-1 byte thanks to @Emigna.
Try it online or verify all test cases.
Explanation:
R            # Reverse the (implicit) input-list
             #  i.e. [16,7,4,3] → [3,4,7,16]
 .¥          # Undelta it (with leading 0)
             #  → [0,3,7,14,30]
   .Γ }      # Continue until the result no longer changes, and collect all steps:
     ¥       #  Get the deltas / forward differences of the current list
             #  → [[3,4,7,16],[1,3,9],[2,6],[4],[]]
       ¨     # Remove the trailing empty list
             #  → [[3,4,7,16],[1,3,9],[2,6],[4]]
        ζ    # Zip/transpose; swapping rows/column (with space as default filler)
             #  → [[3,1,2,4],[4,3,6," "],[7,9," "," "],[16," "," "," "]]
         н   # Only leave the first inner list
             #  → [3,1,2,4]
          R  # Revert it back
             #  → [4,2,1,3]
             # (after which it's output implicitly as result)

You can save a byte with R.¥.Γ¥}¨ by starting from the list whose delta is the input.

@Emigna Ah, undelta into a loop with deltas to save a byte on the prepend. :) Thanks!

Wolfram Language (Mathematica), 57 bytes
(r=Reverse)[#&@@@Most@NestList[Differences,r@#,Tr[1^#]]]&

Try it online!

Python 2, 78 bytes
lambda n,*a:R(lambda r,v:R(lambda x,w:x+[w-x[-1]],r,[v]),a,[n])[::-1]
R=reduce

Try it online!

Japt, 11 9 bytes
Nc¡=äa
yÌ

Try it
2 bytes saved thanks to Oliver.
12 11 bytes
_äa}hUÊN yÌ

Try it
1 byte saved thanks to Oliver.

9 bytes and 10 bytes

@Oliver, not thinking to use y(f) is bad enough, but completely forgetting the newline is unforgivable! Will update shortly. Thanks :)

C# (Visual C# Interactive Compiler), 164 bytes
a=>{int x=a.Length;var l=new int[x][];for(int i=0;i<x;i++){l[i]=new int[x];l[i][0]=a[i];for(int j=0;j<i;j++)l[i][j+1]=l[i-1][j]-l[i][j];}return l.Last().Reverse();}

Try it online!

151 bytes

APL+WIN, 34 or 28 bytes
v←⊂⌽⎕⋄1↓⌽↑¨⍎∊'v',(∊⍴¨v)⍴⊂',-2-/¨v'

Try it online! Courtesy of Dyalog Classic
Prompts for right side vector.
or implementing @Lynn's approach:
0⍕⌽(⌹⍉n∘.!n←0,⍳¯1+⍴n)+.×⌽n←⎕

Try it online!Courtesy of Dyalog Classic
Prompts for right side vector.

Charcoal, 19 bytes
Ｆθ«ＰＩ§θ±¹↑ＵＭθ⁻§θ⊖λκ

Try it online! Link is to verbose version of code. Explanation:
Ｆθ«

Loop once for each term in the original list.
ＰＩ§θ±¹↑

Print the last term in the list, but move the cursor to the beginning of the previous line, so that the terms are output in reverse order.
ＵＭθ⁻§θ⊖λκ

Compute the deltas, inserting a dummy value at the beginning so that we can use an operation that doesn't change the length of the list.

Attache, 29 bytes
{y.=Delta@-_If[_,$@y'_@-1,y]}

Try it online!
Simply iterates the Delta function until its empty. Much shorter than the very verbose PeriodicSteps solution...

C, 76 bytes
i=0;int*f(int*a,int n){for(;i<n;a[i++]=a[i]-a[i+1]);if(!n)return a;f(a,n-1);}

input : (*a = pointer to array, n = last element's index of that array)
output : return int* = output
Explanation
going from right side to up, as the last elements are same in both input and output the loop inside function simply finds next higher numbers in the triangle gradually reaching to the top leaving the answer intact in the end.
ungolfed(from C++)
#include <iostream>
#define SIZE_F 5

int*recFind(int*a, int n) {
    int i = 0;
    while (i < n)
        a[i++] = a[i] - a[i+1];
    if (!n) return a;
        recFind(a, n - 1);
}
int main()
{
    int first[SIZE_F],*n;
    for (int i = 0; i < SIZE_F; i++)
        std::cin >> first[i];

    n = recFind(first, SIZE_F - 1);//size - 1
    for (int i = 0; i < SIZE_F; i++)
        std::cout << n[i];
}

Julia 0.6, 44 bytes
x->reverse([(j=x[end];x=-diff(x);j)for i=x])

Try it online!
Same iterative principle as my R answer.
Julia 0.6, 55 bytes
x->inv([binomial(i,j)for i=(l=length(x)-1:-1:0),j=l])*x

Try it online!
@Lynn's algorithm (inverse of Pascal matrix multiplied by input).


text:
Type-check an expression
Given an infix expression, determine whether all constants are of the same type.
Operators will consist only of these dyadic operators: +-/*
Your program or function should take a valid expression string as input, and output a truthy value if the constants in the expression are of the same time, and a falsey value otherwise.
The expression will consist solely of constants, and may contain any of the following types:

String, of the form "String" (Always double quotes, can be empty, no escape characters, may contain any ASCII text)
Integer, of the form 14 (Always positive or zero)
Float, of the form 7.3f (Always positive or zero, always has a decimal component, eg 14.0f)
Byte, of the form 0x42 (0-255, Always 2 hexadecimal characters)
Boolean, of the form true (true or false, case insensitive)

The expression will not contain parentheses, as order of operation doesn't affect type when no type coercion is present.
A lone constant with no operators is a valid expression.
An empty expression is not a valid expression.
You may assume that the expression string contains no whitespace outside of string literals.
Note: Alternatively you may assume that there will always be spaces between constants and operators, as seen in the testcases. If you make this assumption, please specify as such in your answer
You do not have to handle invalid expressions such as 1 +.
Scoring
This is code-golf, so fewest bytes wins!
Test cases
(Whitespace added for readability)
2 + 3
True

"Hello" / "World"
True

true * false
True

"Hello" + 4
False

"Hello" + "4"
True

3 + 2.4f / 8
False

0xff * 0xff
True

0xff + 2
False

6
True

" " + ""
True

"4 + false" + "word"
True

Does "case insensitive" for Boolean values mean that we have to support all cases? Or that we can decide which case to use?

@Arnauld must support all cases

@JonathanAllan my interpretation was that we had to handle any mixture of cases (e.g. truE+fALSe). If not I can save two bytes in my solution.

JavaScript (ES6),  79 77  75 bytes
Saved 2 bytes thanks to @ExpiredData
Expects whitespace around operators. Returns a Boolean value.
s=>![/".*?"/g,/0x../g,/\S+f/g,/\d/,/e/i].filter(e=>s!=(s=s.split(e)+''))[1]

Try it online!
How?

We remove all strings, using /".*?"/g
We remove all bytes, using /0x../g
We remove all floats, using /\S+f/g
We look for a remaining digit with /\d/; if we do find one, there must be at least one integer
We look for a remaining "e" or "E" with /e/i; if we do find one, there must be at least one Boolean value

All removed expressions are actually replaced with a comma, which is harmless.
We filter out the regular expressions causing no change to the input string and test whether less than two of them remain at the end of the process.

true and false are marked as being case insensitive, I think that means you need to make your regex ignore case when searching for these t and s (I could be wrong though).

@JonathanAllan I've put a temporary fix and asked the OP.

75 bytes

@ExpiredData Nice. :) Thanks!

Perl 5 -p, 73 bytes
for$f(qw/".*?" \d+.\d+f 0x.. ....?e \d+/){s/$f//gi&&last}$_=/^[+\/* -]*$/

Try it online!
How?
Attempt to remove strings, floats, hex, boolean, and integers, in that order.  Stop as soon as something is removed.  After stopping, check to see if the remaining string consists only of operators and whitespace.  It if does, the trype check is true; if not, it's false.
First attempt: Perl 5 -MList::Util=all -p, 99 bytes
s/".*?"/!/g;for$f(qw/! \d+ \d+\.\d+f 0x[0-9a-f]{2} (true|false)/){$\||=all{/^$f$/i}/[^+\/* -]+/g}}{

Try it online!

$_=/^[+\/* -]*$/ may be changed by $_=!y#-+/* ##c, and ....?e by .*e

otherwise in one regex, 63 bytes

58 bytes assuming there will always be spaces between constants and operators

Jelly, 30 23 bytes
ṣ”"ŒœḢYŒlḲŒœḢeþ@“.e¶x”E

Try it online!
A monadic link that takes a string as input and returns 1 for true and 0 for false (Jelly’s boolean values). Expects whitespace around operators.
I’ve added a few new test cases to the TIO including one with three operators and one with mixed case for booleans.
Explanation
ṣ”"                     | Split input at double-quotes
   Œœ                   | Split into two lists, one of odd indices and one even. The even indices will have the contents of the quoted bits in the input (if any)
     Ḣ                  | Keep only the odd-indexed items
      Y                 | Join with newlines (so now all quoted strings in input are a single newline)
       Œl               | Convert to lower case (so that booleans are case insensitive)
         Ḳ              | Split at spaces
          ŒœḢ           | As before just take odd indices
             eþ@“.e¶x”  | Check for each section which they contain of .e¶x (respectively floats, booleans, strings and hex; integers will have none of these)
                      E | Check each section is equal (will return true for single section)

C# (Visual C# Interactive Compiler), 113 111 109 bytes
n=>@""".*?"" 0x.. \S+f \d e|E".Split().Single(x=>n!=(n=System.Text.RegularExpressions.Regex.Replace(n,x,"")))

Port of Arnauld's javascript answer. Is 72 bytes with the flag /u:System.Text.RegularExpressions.Regex.
Try it online!

108 bytes

05AB1E, 50 24 bytes
'"¡āÉÏ»lð¡āÉÏε".e
x"Så}Ë

-26 bytes by making a port of  @NickKennedy's Jelly answer, so make sure to upvote him!!
Expects input with spaces at the operands.
Try it online or verify all (plus some more) test cases.
Explanation:
'"¡         '# Split the (implicit) input-string by '"'
   āÉÏ       # Only keep all values at 0-based even indices
      »      # Join them by newlines
       l     # Converted to lowercase (for `true`/`false`)
ð¡           # Split by spaces (NOTE: `#` cannot be used here, since inputs without
             # operands wouldn't be wrapped inside a list)
  āÉÏ        # Keep all values at 0-based even indices again
     ε".e
     x"Så}   # Check for each item for each of [".","e","\n","x"] if it's in the item
          Ë  # Check if all inner lists are the same
             # (which is output implicitly as result)

Japt -!, 36 bytes
`".*?" 0x.. %S+f %d e|E`¸è@UÀ(U=rXÃÉ

Try it

33 bytes?

Python 2, 102 bytes
import re
def f(s):
	m=map(eval,re.split('[*+-/]',s))
	return all(map(lambda t:type(t)==type(m[0]),m))

Try it online!
Not entirely sure how to represent some of these types in Python. For example, 0xff and 2 are both treated as integers. And 2.4f isn't a valid type in Python, I think. Capitalized True and False for testing Booleans.
Edit: Grammar

Will fail the last test case

...and (as it stands) the true * false one.

It passes for "True * False". I can try to make it work with lower case, but I figured since bools are always capitalized in python it would be sufficient.

Currently this does not fulfill the challenge criteria. Namely: It does not handle booleans case insensitively, it errors on floats, and it incorrectly returns true when given an expression consisting of bytes and integers

Stax, 26 bytes
ïd"┬Z\¡►L!8$lm╗╕╤☻ú≡╝ò6Å>^

Run and debug it
This program expects spaces around the operators.  In general, it works by applying a few transformations to the input such that the maximum character for each expression type is distinct.
Unpacked, ungolfed, and commented, it looks like this.
i           suppress automatic evaluation of input
'"/2::'s*   replace quoted strings with 's'
.\d'9R      replace all digits with '9'
.ez|t       replace 'e' with 'z'
j2::        split on spaces, and discard alternating groups (operators)
{|Mm        calculate the maximum character in each remaining group
:u          resulting array contains exactly one distinct value

Run this one

Haskell, 140 Bytes
r(a:t)|a=='"'=a:r(tail$snd$span(/=a)t)|elem a"+-*/"=r t|0<1=a:r t
r n=n
f x|z<-[last$'i':(filter(`elem`t)"fex\"")|t<-words$r x]=all(==z!!0)z

f x=let z=...in ... can be f x|z<-...=....

JavaScript: 69 bytes.
a=>{b=a.split(/\+|\-|\*|\//);return typeof eval(b[0])==typeof eval(b[1])}

Remarks

eval is a dangerous operation.
I used bad JavaScript practices in the process, like implicit globals and auto-semicolons.

Explanation

b = ... sets the variable b to the array created by splitting a based on the dyadic operations
return ... returns true if the types of the return values of eval match, false otherwise.

Don't worry about good practices here. In our daily jobs we are not doing things seen here. ☺ Your code could be reduced to a=>typeof eval((b=a.split(/\+|\-|\*|\//))[0])==typeof eval(b[1]), but unfortunately its glitches would stay: 1) Integers, floats and hexadecimal will all result “number” while the requirement asks to find them different. 2) Your solution should also handle expressions with fewer or more than 2 constants.

On code golf, it would be worrying if you hadn't used bad practices ;)

Does it handle string with symbol +?


text:
Maximizing by swapping
Input
An integer n in the range 100 to 10^18 and an integer k in the range 1 to 18, inclusive.
The swap operation
A swap chooses two digits at different positions and exchanges their positions, as long as the swap does not result in a leading zero. For example if we start with the integer 12345 we can perform one swap to make it 12543.
Task
Output the largest number you can get after exactly k swaps.
Examples
n = 1283, k = 2. Output: 8312
n = 510, k = 1. Output: 501
n = 501, k = 2. Output: 501
n = 999, k = 3. Output: 999
n = 12345678987654321, k = 1. Output: 92345678187654321

What is it with these [code-golf] + [restricted-time] challenges lately.. They are complete opposites imho. Anyway, as for the actual challenge, if we are to output huge test cases with k=18 and n between $10^{17}$ and $10^{18}$ within 10 seconds, you may want to add some test cases for those.

@KevinCruijssen It's a combination I really like :) Basically the challenge is to write compact code that is not too naive/brute force.  I will try to add some more test cases.If anyone comes up with any first, please post them in the comments and I will add them to the question.

Also, a test case where k is larger than the length of n would be good as well, since we have to do exactly k swaps instead of up to k swaps. Can't really think of a good test case for this, but I think we might need to do an inefficient swap first sometimes in order to get to the maximum in exactly k swaps.

May we take n as a string?

@attinat Yes you can.

What should we do with n=200, k=1?

@H.PWiz I guess we should swap the zeros. An invalid input (IMO) would be n=20, k=1.

@Arnauld I was about to ask why n=20, k=1 is invalid, but I now see the "as long as the swap does not result in a leading zero". And here I thought I was close to a solution.. xD You know, this would actually be a pretty good challenge I would upvote since we have to exactly k swaps (which is quite a bit harder than up to k swaps), if it weren't for the time-restriction. PS: I'm not one of the downvotes btw despite my first two comments, but I'm also not upvoting either.

Can we take input n as a list of digits?

@KevinCruijssen Yes you can.

@KevinCruijssen I don't mind removing the time restriction if it makes people generally happier.

@Arnauld Your suggested input is invalid because it doesn't satisfy n>=100

I succumbed to peer pressure and removed [tag:restricted-time]

So this is basically the first k iterations of a sorting algorithm?

@MagicOctopusUrn Not necessary, since n=501, k=2 would become 510 in the first iteration, but then should be swapped back to 501 as our result.

@KevinCruijssen I feel like that should've been explained better in the question, instead of by you on a comment ._. It confused both me and ovs.

@MagicOctopusUrn Well, that's the difference between up to k swaps (which is pretty easy) and exactly k swaps (which is pretty tricky and is what this challenge is asking).

@KevinCruijssen They aren't off topic, right? https://codegolf.stackexchange.com/questions/133618/extreme-fibonacci

Python 3, 194 190 196 193 175 164 162 bytes
def f(n,k):
 for i in range(len(n)-1):
  y=max(n[i:]);j=n[::-1].index(y)
  if(y>n[i])*k:n[i],n[~j]=y,n[i];k-=1
 if len(n)-len({*n})<k%2:n[-2:]=n[:-3:-1]
 return n

Try it online!
Pretty tough to golf this challenge in a real world language - I like it :)
After golfing down to 190 bytes (and below..), I found some cases where the algorithm would not find the maximum possible value. Bugfixing forced me back up to 196 193 bytes :/
... then I found some ways to better handle branching on k and went down below 180 :)
After the comment from Chas Brown, switching from integer to list I/O saved 28 bytes! (And more golfing another 2..)
Then, another bug: the algorithm incorrectly handles remaining swaps, if there are equal digits present. The fix cost 19 bytes.
Algorithm:

For each digit, starting from the leftmost one, swap it with the rightmost maximum digit, if that one is bigger. First line of the for-loop finds the maximum and its index. Second line does the swap.
If there are k' swaps left, swap two equal digits, or the two rightmost k' times. I.e. if  there are two equal digits present, or if k' is even, no more swaps have to be done. Else, just swap the last two digits once.

The bug I needed to fix: f(899,1)=989, but should be 998. If there are multiple candidates to swap, use the rightmost one for the biggest effect. This is now taken care of by looking for the index in reverse. Takes up a lot of bytes for index calculation though :/

Hi and welcome, movatica! For the input 9881,1 you return 9818; but you should return 9881. (Also, you can take n as a string of digits already, and return a list of digits as well; as noted in the comments; so that should give you some breathing space! :)).

Hi @ChasBrown and thanx for the warm welcome :) You're right about the bug, this is because of how i handle possible swaps... I'm thinking of a way around. The removal of string/list handling will indeed save a lot of bytes.

162 bytes by tweaking that last if clause a bit: len(n)-len({*n}) must be 0 and k%2 must be 1, which is the condition len(n)-len({*n})<k%2.

Jelly, 16 bytes
JŒ!nJ$S⁼ɗƇ2ị⁸Ṁµ¡

Try it online!
A dyadic Link accepting a list of digits (as non-negative integers) on the left and a non-negative integer on the right which yields a list of digits.
How?
JŒ!nJ$S⁼ɗƇ2ị⁸Ṁµ¡ - Link: L, n
              µ¡ - repeat the monad to the left n times -- i.e. f(f(f(...(L)...))):
J                -   range of length
 Œ!              -   all permutations
         Ƈ       -   filter keep if:
        ɗ 2      -     last three links as a dyad with right argument 2
     $           -       last two links as a monad:
    J            -         range of length
   n             -         not equal? (vectorises)
      S          -       sum
       ⁼         -       equal?
           ị     -   index into (vectorises):
            ⁸    -     chain's left argument, L
             Ṁ   -   maximum

20 byte version which is fine within the previous time-constraint since \$\binom{18}2=\frac{18\times 17}2=153\$
JŒcœṖḢ;Ḣ€ṚżƊƊFɗ€⁸Ṁµ¡

Try it online!
How?
JŒcœṖḢ;Ḣ€ṚżƊƊFɗ€⁸Ṁµ¡ - Link: L, n
                  µ¡ - repeat the monad to the left n times -- i.e. f(f(f(...(L)...))):
J                    -   range of length
 Œc                  -   all (length(L)-choose-2) pairs: [[1,2],[1,3],[1,4],...,[2,3],[2,4],...]
               €     -   for each (such pair, P):
              ɗ ⁸    -     last three links as a dyad, with right argument L:
   œṖ                -       partition (L) at indexes (P) - call this X
            Ɗ        -       last three links as a monad - i.e. f(X):
     Ḣ               -         head (of X) (the items up to but not including the first to swap)
           Ɗ         -         last three links as a monad - i.e. f(X):
       Ḣ€            -           head each (actually removes them too) (the items to swap)
         Ṛ           -           reverse
          ż          -           zip with (the altered X)
      ;              -         concatenate
             F       -       flatten
                 Ṁ   -   maximum

Python 2, 185 177 173 166 164 161 152 bytes
def f(a,k):exec"i=0;j=L=len(a)-1\nwhile i<L>0<a[i]==max(a[i:]):i+=1\nwhile a[j]<max(a[i:]):j-=1\nj-=i==j<=L<len(set(a));a[i],a[j]=a[j],a[i];"*k;return a

Try it online!
Takes a list of digits and an integer k; returns a list of digits.
j-=i==j<=L<len(set(a))

uses a bunch of shortcuts, and is the same as:
if i==j:                     # if i==j, then the list is already sorted
    if len(a)-1<len(set(a)): # since len(a)>=len(set(a)) is *always* True,
                             # this means len(a)==len(set(a), i.e,
                             # a has no duplicated digits,
        j = i-1              # so do a swap with the rightmost digits

Python 2, 113 bytes
f=lambda l,k,E=enumerate:l*0**k or f(max(l[:i]+[y]+l[i+1:j]+[x]+l[j+1:]for(i,x)in E(l)for j,y in E(l)if i<j),k-1)

Try it online!
Greedily does the best swap at each step, found by testing all possible swaps and taking the maximum.

PowerShell, 162 bytes
$f={param($s,$k)if($k--){$s=if($s.length-le2){&$f($s[1]+$s[0])$k}else{($m=($s|% t*y|sort)[-1])+(&$f(($s-replace"(?<!$m.*)$m",$s[0])|% s*g 1)($k+=$s[0]-eq$m))}}$s}

Try it online!
The Recursive Function. Less golfed:
$f={
    param($s,$k)
    if($k--){
        $s=if($s.length-le2){
            &$f ($s[1]+$s[0]) $k
        }
        else{
            $max=($s|% t*y|sort)[-1]
            $k+=$s[0]-eq$max
            $s=$s-replace"(?<!$max.*)$max",$s[0]
            $s=$s|% subString 1
            $max+(&$f $s $k)
        }
    }
    $s
}

Alternative, 169 bytes
param($s,$k)1..$k|%{do{if($s.length-le2){$s=-join$s[1,0]
$r=0}else{$m+=($c=($s|% t*y|sort)[-1])
$r=$s[0]-eq$c
$s=($s-replace"(?<!$c.*)$c",$s[0])|% s*g 1}}while($r)}$m+$s