N-queen-and-equine quine There is a variant of the well-known N-queens problem which involves queens and knights and is said to be "considerably more difficult" 1. The problem statement is as follows:

  You must place an equal number of knights ♞ and queens ♛ on a chessboard
  such that no piece attacks any other piece. What is the maximum number
  of pieces you can so place on the board, and how many different ways
  can you do it?

In this code-golf challenge, you will be given an input n between 3 and 32 (in a way that is the most suitable for your language). For a given n, there might be zero or more solutions to the above problem. In case there is no solution, you must output/return nothing (nil, empty string, false, ...). Otherwise, you must give two results:

A solution board (see below) for size n where it is not possible to add a queen or a knight chess piece without having any piece being under attack. There must be an equal number of queens and knights.
The source of a program to be run which accepts no input and gives (i) another solution (or nothing) for the same size n, in the same format, as well as (ii) another program for the next solution (and so on...).

Note that:

The sequence of programs must never return the same board twice, must cover all possible solutions for the problem of size n and eventually has to terminate (producing no output).
You can either return two values, return one and print the other, or print the two return values.
However, if you print both the board and the next program, the board must not be considered to be a part of the next program (I'd recommend printing the board in comment, or use both standard output and error streams).
The program-as-a-return-value must be a string, not a closure.

Board format

A board is a square of size n.
A board cell can be empty, a queen or a knight.
You must choose distinct values for each kind of cells (i.e. you can use other symbols than Q, N when printing the board).
If you return a non-string board, it must be an ordered collection of the n2 values of the board (e.g. matrix, vector or list in row/column-major order, ...).
If you print the board, you can either print it squared, or as a line.
For example, a solution board of size 4 can be printed as follows (spaces not required; symbols at your discretion):

Q - - -
- - - -
- - - -
- - N -

If you feel so, you can also output:

♛ · · ·
· · · ·
· · · ·
· · ♞ ·

... but this is sufficient:

Q-------------N-

It does not matter if you iterate through cells in a row-major or column-major order, because there are symmetrical solutions.
For example, the solutions for n=4 are:

Q------N--------
Q----------N----
Q------------N--
Q-------------N-
-Q----------N---
-Q------------N-
-Q-------------N
--Q---------N---
--Q----------N--
--Q------------N
---QN-----------
---Q----N-------
---Q---------N--
---Q----------N-
---NQ-----------
----Q------N----
----Q----------N
N------Q--------
-------QN-------
-------Q----N---
---N----Q-------
-------NQ-------
--------Q------N
N----------Q----
----N------Q----
-----------QN---
-N----------Q---
--N---------Q---
-------N----Q---
-----------NQ---
N------------Q--
--N----------Q--
---N---------Q--
N-------------Q-
-N------------Q-
---N----------Q-
-N-------------Q
--N------------Q
----N----------Q
--------N------Q

You can also look at the solutions for n=5 as matrices; the boards contains #, q and n symbols, which are empty cells of different kinds (see my answer below).
I count 2836 boards for n=6, like in Sleafar's answer (I introduced a bug when reducing byte count, but it is fixed now).

Many thanks to Sleafar for finding not one but two bugs in my code.

Score

Shortest code in bytes win.

We measure the size of the first program, the one which accepts n.

1. Queens and Knights, by Roger K.W. Hui (beware! contains a solution)

Common Lisp, 737

self-answer

(lambda(n &aux(d 1))#2=(catch'$(let((s(* n n))(c d))(labels((R(w % @ b ! &aux r h v a)(loop for u from % below s do(setf h(mod u n)v(floor u n)a #4=(aref b u))(when(< 0(logand a w)4)(and(= 6 w)!(throw'! t))(let((b(copy-seq b))(o 5))(loop for(K D)on'(-1 -2 -1 2 1 -2 1 2)for y =(+ K v)for x =(+(or D -1)h)for u =(and(< -1 y n)(< -1 x n)(+(* y n)x))if u do #1=(if(< #4#4)(setf #4#(logand #4#o(if(= w o)3 0)))))(#8=dotimes(y N)(#8#(x N)(let((u(+(* y n)x))(o 6))(if(or(= x h)(= y v)(=(abs(- h x))(abs(- v y))))#1#))))(setf #4#w r(or(cond((= w 5)(R 6 @ U b !))((R 5 @ U b())t)((catch'!(R 5 0 0 b t))t)(t(and(=(decf c)0)(incf d)(or(format t"~%(lambda(&aux(n ~A)(d ~A))~%~S)"n d'#2#)(throw'$ B)))t))r)))))r))(R 5 0 0(fill(make-array s)3)())))))

Example

Paste the above in the REPL, which returns a function object:

#<FUNCTION (LAMBDA (N &AUX (D 1))) {1006D1010B}>

Call it (the star is bound to the last returned value):

QN> (funcall * 4)

This prints the following to the standard output:

(lambda(&aux(n 4)(d 2))
#1=(CATCH '$
 (LET ((S (* N N)) (C D))
   (LABELS ((R (W % @ B ! &AUX R H V A)
              (LOOP FOR U FROM % BELOW S
                    DO (SETF H (MOD U N)
                             V (FLOOR U N)
                             A #2=(AREF B U)) (WHEN (< 0 (LOGAND A W) 4)
                                                (AND (= 6 W) !
                                                     (THROW '! T))
                                                (LET ((B (COPY-SEQ B))
                                                      (O 5))
                                                  (LOOP FOR (K D) ON '(-1
                                                                       -2
                                                                       -1 2
                                                                       1 -2
                                                                       1 2)
                                                        FOR Y = (+ K V)
                                                        FOR X = (+
                                                                 (OR D -1)
                                                                 H)
                                                        FOR U = (AND
                                                                 (< -1 Y N)
                                                                 (< -1 X N)
                                                                 (+ (* Y N)
                                                                    X))
                                                        IF U
                                                        DO #3=(IF (< #2# 4)
                                                                  (SETF #2#
                                                                          (LOGAND
                                                                           #2#
                                                                           O
                                                                           (IF (=
                                                                                W
                                                                                O)
                                                                               3
                                                                               0)))))
                                                  (DOTIMES (Y N)
                                                    (DOTIMES (X N)
                                                      (LET ((U
                                                             (+ (* Y N) X))
                                                            (O 6))
                                                        (IF (OR (= X H)
                                                                (= Y V)
                                                                (=
                                                                 (ABS
                                                                  (- H X))
                                                                 (ABS
                                                                  (- V
                                                                     Y))))
                                                            #3#))))
                                                  (SETF #2# W
                                                        R
                                                          (OR
                                                           (COND
                                                            ((= W 5)
                                                             (R 6 @ U B !))
                                                            ((R 5 @ U B
                                                                NIL)
                                                             T)
                                                            ((CATCH '!
                                                               (R 5 0 0 B
                                                                  T))
                                                             T)
                                                            (T
                                                             (AND
                                                              (= (DECF C)
                                                                 0)
                                                              (INCF D)
                                                              (OR
                                                               (FORMAT T
                                                                       "~%(lambda(&aux(n ~A)(d ~A))~%~S)"
                                                                       N D
                                                                       '#1#)
                                                               (THROW '$
                                                                 B)))
                                                             T))
                                                           R)))))
              R))
     (R 5 0 0 (FILL (MAKE-ARRAY S) 3) NIL)))))

Also, the value returned by this function is:

#(5 0 0 0 0 0 0 6 0 0 0 2 0 2 0 0)

... which is an array literal. Number 5 represents queens, 6 is for knights and anything else stands for an empty cell, except there are more informations stored internally. If we copy-paste the returned function to the repl, we obtain a new function.

#<FUNCTION (LAMBDA (&AUX (N 4) (D 2))) {100819148B}>

And we can call it to, without arguments:

QN> (funcall * )

This call returns a new solution #(5 0 0 0 0 0 0 2 0 0 0 6 0 0 2 0) and the source of another function (not shown here). In case the original function or the last generated one does not find a solution, nothing is printed and nothing is returned.

Internal values

|----------+--------+---------+--------+-----------------|
|          | Binary | Decimal | Symbol | Meaning         |
|----------+--------+---------+--------+-----------------|
| Empty    |    000 |       0 | -      | safe for none   |
|          |    001 |       1 | q      | safe for queen  |
|          |    010 |       2 | n      | safe for knight |
|          |    011 |       3 | #      | safe for both   |
|----------+--------+---------+--------+-----------------|
| Occupied |    101 |       5 | Q      | a queen         |
|          |    110 |       6 | K      | a knight        |
|----------+--------+---------+--------+-----------------|

I used to generate too few solutions. Now, I propagate what cell is safe for a queen and for a knight, independently. For example, here is an output for n=5 with pretty-printing:

Q - - - -
- - - n N
- q - n n
- # n - n
- n # # -

When we placed the queen Q, positions that are a knight-move away from this queen are still safe for queens and denoted q. Likewise, knights that are reachable only by queens are safe for other knights.
Values are bitwise and-ed to represent the possible moves and some cells are reachable by no kind of piece.

More precisely, here is the sequence of boards leading to the following solution (from left to right), where free cells are gradually constrained with different values:

# # # # # #     q - - - q #     - - - - - #     - - - - - #     - - - - - n
# # # # # #     - - Q - - -     - - Q - - -     - - Q - - -     - - Q - - -
# # # # # #     q - - - q #     q - - - - -     Q - - - - -     Q - - - - -
# # # # # #     - q - q - #     - q - - - n     - - - - - n     - - - - - n
# # # # # #     # # - # # -     n n - n N -     - - - n N -     - - - - N -
# # # # # #     # # - # # #     # # - n n n     - # - - n n     - n - - n N

Non-quine approach

Ungolfed, commented version

(defun queens-and-knights
    (n    ; size of problem
     fn   ; function called for each solution

     ;; AUX parameters are like LET* bindings but shorter.
     &aux
       ;; total number of cells in a board
       (s (* n n)))

  (labels
      ;; Define recursive function R
      ((R (w      ; what piece to place: 5=queen, 6=knight
           %      ; min position for piece of type W
           @      ; min position for the other kind of piece
           b      ; current board
           !      ; T iff we are in "check" mode (see below)
           &aux
           r      ; result of this function: will be "true" iff we can
                  ; place at least one piece of type W on the board b
           h      ; current horizontal position
           v      ; current vertical position
           a      ; current piece at position (h,v)
           )

         (loop
            ;; only consider position U starting from position %,
            ;; because any other position below % was already visited
            ;; at a higher level of recursion (e.g. the second queen
            ;; we place is being placed in a recursive call, and we
            ;; don't visit position before the first queen).
            for u from % below s

            do
              (setf h (mod u n)         ; Intialize H, V and A
                    v (floor u n)       ;
                    a (aref b u))       ;

            ;; Apply an AND mask to current value A in the board
            ;; with the type of chess piece W. In order to consider
            ;; position U as "safe", the result of the bitwise AND
            ;; must be below 4 (empty cell) and non-null.
              (when (< 0 (logand a w) 4)

                ;; WE FOUND A SAFE PLACE TO PUT PIECE W

                (when (and ! (= 6 w))
                  ;; In "check" mode, when we place a knight, we knwo
                  ;; that the check is successful. In other words, it
                  ;; is possible to place an additional queen and
                  ;; knight in some board up the call stack. Instead
                  ;; of updating the board we can directly exit from
                  ;; here (that gave a major speed improvement since
                  ;; we do this a lot). Here we do a non-local exit to
                  ;; the catch named "!".
                  (throw '! t))

                ;; We make a copy of current board b and bind it to the
                ;; same symbol b. This allocates a lot of memory
                ;; compared to the previous approach where I used a
                ;; single board and an "undo" list, but it is shorter
                ;; both in code size and in runtime.
                (let ((b (copy-seq b)))

                  ;; Propagate knights' constraints
                  (loop
                     ;; O is the other kind of piece, i.e. queen here
                     ;; because be propagate knights. This is used as
                     ;; a mask to remove knights pieces as possible
                     ;; choices.
                     with o = 5

                     ;; The list below is arranged so that two
                     ;; consecutive numbers form a knight-move. The ON
                     ;; iteration keyword descend sublist by sublist,
                     ;; i.e. (-1 -2), (-2 -1), (-1 2), ..., (2 NIL). We
                     ;; destructure each list being iterated as (K D),
                     ;; and when D is NIL, we use value -1.
                     for (K D) on '(-1 -2 -1 2 1 -2 1 2)

                     ;; Compute position X, Y and index U in board,
                     ;; while checking that the position is inside the
                     ;; board.
                     for y = (+ K v)
                     for x = (+ (or D -1) h)
                     for u = (and (< -1 y n)
                                  (< -1 x n)
                                  (+(* y n)x))

                     ;; if U is a valid position...
                     if u
                     do
                     ;; The reader variable #1# is affected to the
                     ;; following expression and reused below for
                     ;; queens. That's why the expression is not
                     ;; specific to knights. The trick here is to
                     ;; use the symbols with different lexical
                     ;; bindings.
                       #1=(when (< (aref b u) 4) ; empty?
                            (setf (aref b u)

                                  (logand
                                   ;; Bitwise AND of current value ...
                                   (aref b u)

                                   ;; ... with o: position U is not a
                                   ;; safe place for W (inverse of O)
                                   ;; anymore, because if we put a W
                                   ;; there, it would attack our
                                   ;; current cell (H,V).
                                   o

                                   ;; ... and with zero (unsafe for
                                   ;; all) if our piece W is also a
                                   ;; knight (resp. queen). Indeed, we
                                   ;; cannot put anything at position
                                   ;; U because we are attacking it.
                                   (if (= w o) 3 0)))))

                  ;; Propagate queens' constraints
                  (dotimes (y N)
                    (dotimes (x N)
                      (let ((u(+(* y n)x))(o 6))
                        (if (or (= x h)
                                (= y v)
                                (= (abs(- h x)) (abs(- v y))))

                            ;; Same code as above #1=(if ...)
                            #1#))))

                  (setf
                   ;; Place piece
                   (aref b u) w

                   ;; Set result value
                   r (or (cond
                           ;; Queen? Try to place a Knight and maybe
                           ;; other queens. The result is true only if
                           ;; the recursive call is.
                           ((= w 5) (R 6 @ U b !))

                           ;; Not a queen, so all below concern
                           ;; knights: we always return T because
                           ;; we found a safe position.
                           ;; But we still need to know if
                           ;; board B is an actual solution and
                           ;; call FN if it is.
                           ;; ------------------------------------

                           ;; Can be place a queen too? then current
                           ;; board is not a solution.
                           ((R 5 @ U b()) t)

                           ;; Try to place a queen and a knight
                           ;; without constraining the min positions
                           ;; (% and @); this is the "check" mode that
                           ;; is represented by the last argument to
                           ;; R, set to T here. If it throws true,
                           ;; then board B is a duplicate of a
                           ;; previous one, except that it is missing
                           ;; pieces due to constraints % and @. The
                           ;; "check" mode is a fix to a bug where we
                           ;; reported as solutions boards where there
                           ;; was still room for other pieces.
                           ((catch'!(R 5 0 0 b t)) t)

                           ;; Default case: we could not add one more
                           ;; layer of pieces, and so current board B
                           ;; is a solution. Call function FN.
                           (t (funcall fn b) t))

                         ;; R keeps being true if it already was for
                         ;; another position.
                         r)))))

         ;; Return result R
         r))

    ;; Start search with a queen and an empty board.
    (R 5 0 0 (fill (make-array s) 3)  nil)))

Duplicates and bugs

My very first solution outputted duplicate solutions. In order to solve it, I introduced two counters for queens and knights. The counter for queens (resp. knights) keep track of the first position in the board where a queen (resp. knight) exists: I add a queen (resp. a knight) only at positions that follow that minimal position.

That methods prevents me from revisiting solutions that were already found in previous iterations, because I iterate with an increasing queen (resp. knight) position.

However, Sleafar noticed that there were solutions for which there could be room for queens and knights, which is against the rules. For a while I though I had to revert to a normal search and store all the known solutions to prevent duplicates, which felt too costly (both in terms of bytes and memory usage).

Instead, here is what I do now: when a potential solution board is found, I try to add exactly one queen and one knight, without taking into account the counters (i.e. for all cells on the board). If this is possible, then current board is a duplicate of a previous one, and I reject the solution.

Tests

|---+---------+------------+--------------|
| N |  boards |    seconds |        bytes |
|---+---------+------------+--------------|
| 3 |       0 |          0 |        32768 |
| 4 |      40 |          0 |       360416 |
| 5 |     172 |          0 |      3440016 |
| 6 |    2836 |   0.085907 |     61251584 |
| 7 |   23876 |   1.265178 |    869666288 |
| 8 |  383586 |  24.991300 |  17235142848 |
| 9 | 6064506 | 524.982987 | 359952648832 |
|---+---------+------------+--------------|

Quine-ification

I had different ideas to make successive quines.
The easiest one is probably to generate all solutions first as a list of strings and write sequential quines which pop from that list at each generation. However this did not seem to be shorter than current approach.
Alternatively, I tried to rewrite the recursive code with a custom stack and dump all the state variables each time I find a solution; the goal is that the next step can be processed as a continuation of current step.
 Maybe this would be better suited for a stack based language.
The current one is quite simple and rely on Common Lisp reader variables, which are always fun to use.


Dividing Divisive Divisors Given a positive integer \$n\$ you can always find a tuple \$(k_1,k_2,...,k_m)\$ of integers \$k_i \geqslant 2\$ such that \$k_1 \cdot k_2 \cdot ... \cdot k_m = n\$ and $$k_1 | k_2 \text{ , } k_2 | k_3 \text{ , } \ldots \text{ , }k_{m-1}|k_m.$$
Here \$a|b\$ means \$b\$ is a multiple of \$a\$, say "a divides b". If \$n>1\$ all entries \$k_i\$ must be at least \$2\$. For \$n=1\$ we have no such factor and therefore we get an empty tuple.
In case you're curious where this comes from: This decomposition is known as invariant factor decomposition in number theory and it is used in the classification of finitely generated
Abelian groups.
Challenge
Given \$n\$ output all such tuples \$(k_1,k_2,...,k_m)\$ for the given \$n\$ exactly once, in whatever order you like. The standard sequence output formats are allowed.
Examples
  1: () (empty tuple)
  2: (2)
  3: (3)
  4: (2,2), (4)
  5: (5)
  6: (6)
  7: (7)
  8: (2,2,2), (2,4), (8)
  9: (3,3), (9)
 10: (10)
 11: (11)
 12: (2,6), (12)
108: (2,54), (3,3,12), (3,6,6), (3,36), (6,18), (108)

Related: http://oeis.org/A000688, List all multiplicative partitions of n

Haskell, 66 62 60 bytes

f n=[n|n>1]:[k:l:m|k<-[2..n],l:m<-f$div n k,mod(gcd n l)k<1]

Try it online!


Rotation-safe Latin squares A Latin square is a square that has no repeated symbols in either the X or Y columns.  For example:

ABCD
DABC
CDAB
BCDA

is one such square.  Notice how every column and row contains a permutation of the same 4 letters.

However, our Latin square has a problem:  If I were to rotate the second row (DABC) 1 to the left, I'd end up with ABCD, which is identical to the permutation above it.  If it is impossible to rotate any 1 column/row and obtain another column/row, then we consider the square to be rotation safe.

For example:

ABCD
BDAC
CADB
DCBA

is rotation safe.  The grid has the following properties:

Point [0,N] uses the Nth symbol
Point [0,N] and [N,0] are always the same symbol.  (I'd like to also say that [x,y] and [y,x] are also always the same letter, but I can't prove it)

Your task is to print out 1 rotation-safe Latin square, when passed N.  I don't care if you output letters, numbers, a list, or a 2D array.  If you use numbers, the top column and row must be 0,1,2,3,... (in that order).  If you use letters, then it must be A,B,C,D,....

For example, if your input was 4, you should either print:

0,1,2,3            0,1,2,3
1,3,0,2     or     1,0,3,2
2,0,3,1            2,3,1,0
3,2,1,0            3,2,0,1

There are no rotation-safe Latin squares of size less than 4.  I don't care what your program does if N is less than 4.  For the curious, the number of rotation-safe squares is (starting at 4):  2,5,5906,(too long to calculate)

This is a code-golf, so try to make answers as short as possible in your favorite language!

Pyth - 29 bytes
Brute force.
hf&!@JsCBTsm.>RdJStQ.A{IMJ^.p

Does not finish online even for n=4, but you can try it out locally, or run this modified version online for one more byte.


Build an Electrical Grid The Challenge

There are N cities aligned in a straight line. The i-th city is located A[i] kilometers to the right of the origin. No two cities will be in the same place.

You are going to build an electrical grid with some power plants. Power plants must be built inside a city. However, you are only allowed to build K (< N) power plants, so there will be some cities with no power plants in them. For each city with no power plants, you must build a cable between it and the nearest city that has a power plant.

For example, if there are three cities located at 0, 1, 2, and only the city at 0 has a power plant, you need to build two cables, one from 2 to 0(2km) and the other from 1 to 0(1km), which have a total length of 3km.

Given K and positions of cities (A), you should compute the minimum kilometers of cable you need to build the grid.

Example Testcases

K = 1, A = [0, 2, 4, 6, 8] : 12
# build power plant in the city at position 4, total length = 4 + 2 + 0 + 2 + 4 = 12

K = 3, A = [0, 1, 10, 11, 20, 21, 22, 30, 32] : 23
# build power plants in cities at positions 0, 10 and 22

K = 5, A = [0, 1, 3, 6, 8, 11, 14] : 3
# build power plants in all cities except those at positions 0, 3

K = 6, A = [0, 1, 3, 6, 8, 14, 15, 18, 29, 30, 38, 41, 45, 46, 49, 58, 66, 72, 83, 84] : 49

Specifications

You should implement a function or a program, which takes a positive integer K and a list of integers A in any form, and output/return an integer representing the answer.
A is sorted in ascending order, and all elements are non-negative integers.
A[0] = 0, and A[N-1] will be no more than 1000N.
Note that the output will be in magnitude of 1000N2, so in larger cases, you may need 64-bit integers in some languages.
Multithreading is not allowed (I will set the affinity of your program to only 1 core when judging). Compiler optimizations (such as -O2 in C) are allowed.

Scoring

I will time your code on my computer (Ubuntu 16.04 with Intel i7-3770S processor) with different size of testcases. Specifically, I will generate some testcases with N = floor(2x/5) where x is a positive integer.Your score will be the x value of the smallest testcase that your program uses more than 10 seconds or 1 GiB of memory, or doesn't give a correct answer.

The answer with highest score wins. If two answers get the same score, the earlier answer wins.

All programs will be judged by the same set of testcases.
Feel free to post your own scorings. Explanations of your algorithm are encouraged.

Bonus

This is my C++ program, it scores 108. You can verify the SHA-256 digest 9a87fa183bad1e3a83d2df326682598796a216b3a4262c32f71dfb06df12935d by the whole code segment (without footer) in the link.

The algorithm combines binary search and Knuth's optimization to find the correct penalty of each plant to get the desired number. The complexity is O(N log N log A[N-1]). I was surprised that the program got a higher score than the O(N log A[N−1]) solution by Anders Kaseorg. It's probably due to the fact that the log case in Knuth's optimization won't usually occur.

Note that this challenge is the same as IOI 2000 Post Office. The original constraints are N <= 300 and K <= 30, though.

Rust, score = 104

This is an implementation of the algorithm noted by Grønlund et al. (2017) at the end of §3.3.1, though I had to follow a long citation chain and fill in some missing details.  It runs in O(N log A[N − 1]) time.

Compile with rustc -O. Input format is K on the first line, followed by the entries of A, one entry per line, all on stdin.

(Note: I’m submitting this an hour after the bounty deadline, but I expect the last version I submitted before the bounty deadline, which ran in O(N log N log A[N − 1]) time, to score about 94.)

use std::cmp::min;
use std::io::{self, BufRead};
use std::iter::{once, Cloned};
use std::num::Wrapping;
use std::ops::Range;
use std::slice;
use std::time::Instant;
use std::u64;

type Cost = u64;
const INF: Cost = u64::MAX;

trait ColsTrait<Col>: Clone {
    type Iter: Iterator<Item = Col>;
    fn len(&self) -> usize;
    fn iter(&self) -> Self::Iter;
    fn slice(&self, range: Range<usize>) -> Self;
}

impl<'a, Col: Clone> ColsTrait<Col> for &'a [Col] {
    type Iter = Cloned<slice::Iter<'a, Col>>;
    fn len(&self) -> usize {
        (*self).len()
    }
    fn iter(&self) -> Self::Iter {
        (*self).iter().cloned()
    }
    fn slice(&self, range: Range<usize>) -> Self {
        unsafe { self.get_unchecked(range) }
    }
}

impl ColsTrait<usize> for Range<usize> {
    type Iter = Range<usize>;
    fn len(&self) -> usize {
        self.end - self.start
    }
    fn iter(&self) -> Range<usize> {
        self.clone()
    }
    fn slice(&self, range: Range<usize>) -> Self {
        Range {
            start: self.start + range.start,
            end: self.start + range.end,
        }
    }
}

fn smawk<Col: Copy, Cols: ColsTrait<Col>, Key: Ord, F: Copy + Fn(usize, Col) -> Key>(
    n: usize,
    shift: u32,
    cols: Cols,
    f: F,
) -> Vec<usize> {
    if n == 0 {
        Vec::new()
    } else if cols.len() > n {
        let mut s = Vec::with_capacity(n);
        let mut sk = Vec::with_capacity(n);
        for (jk, j) in cols.iter().enumerate() {
            while match s.last() {
                Some(&l) => f(!(!(s.len() - 1) << shift), j) <= f(!(!(s.len() - 1) << shift), l),
                None => false,
            } {
                s.pop();
                sk.pop();
            }
            if s.len() < n {
                s.push(j);
                sk.push(jk);
            }
        }
        smawk1(
            n,
            shift,
            cols,
            f,
            smawk(n / 2, shift + 1, &s[..], f)
                .into_iter()
                .map(|h| unsafe { *sk.get_unchecked(h) }),
        )
    } else {
        smawk1(
            n,
            shift,
            cols.clone(),
            f,
            smawk(n / 2, shift + 1, cols, f).into_iter(),
        )
    }
}

fn smawk1<
    Col: Copy,
    Cols: ColsTrait<Col>,
    Key: Ord,
    F: Fn(usize, Col) -> Key,
    Iter: Iterator<Item = usize>,
>(
    n: usize,
    shift: u32,
    cols: Cols,
    f: F,
    iter: Iter,
) -> Vec<usize> {
    let mut out = Vec::with_capacity(n);
    let mut range = 0..0;
    for (i, k) in iter.enumerate() {
        range.end = k + 1;
        out.push(
            range
                .clone()
                .zip(cols.slice(range.clone()).iter())
                .min_by_key(|&(_, col)| f(!(!(2 * i) << shift), col))
                .unwrap()
                .0,
        );
        out.push(k);
        range.start = k;
    }
    if n % 2 == 1 {
        range.end = cols.len();
        out.push(
            range
                .clone()
                .zip(cols.slice(range.clone()).iter())
                .min_by_key(|&(_, col)| f(!(!(n - 1) << shift), col))
                .unwrap()
                .0,
        );
    }
    out
}

fn solve(k: usize, a: &[Cost]) -> Cost {
    if k >= a.len() {
        return 0;
    }
    let sa = once(Wrapping(0))
        .chain(a.iter().scan(Wrapping(0), |s, &x| {
            *s += Wrapping(x);
            Some(*s)
        }))
        .collect::<Vec<_>>();
    let c = |i: usize, j: usize| {
        let h = (i - j) / 2;
        unsafe {
            (sa.get_unchecked(i) - sa.get_unchecked(i - h) - sa.get_unchecked(j + h)
                + sa.get_unchecked(j))
                .0
        }
    };
    let cost1 = c(a.len(), 0);
    if k == 1 {
        return cost1;
    }
    let cost2 = (1..a.len()).map(|j| c(j, 0) + c(a.len(), j)).min().unwrap();
    let mut low = 0;
    let mut high = cost1 - cost2;
    let mut ret = INF;
    while low <= high {
        let penalty = low + (high - low) / 2;
        let mut out = vec![(INF, 0); a.len() + 1];
        out[0] = (0, 0);
        let mut begin = 0;
        let mut chunk = 1;
        loop {
            let r = min(a.len() + 1 - begin, 2 * chunk);
            let edge = begin + chunk;
            let (out0, out1) = out.split_at_mut(edge);
            let f = |i: usize, j: usize| {
                let h = (edge + i - j) / 2;
                let &(cost, count) = unsafe { out0.get_unchecked(j) };
                (
                    cost.saturating_add(
                        unsafe {
                            sa.get_unchecked(edge + i) - sa.get_unchecked(edge + i - h)
                                - sa.get_unchecked(j + h)
                                + sa.get_unchecked(j)
                        }.0 + penalty,
                    ),
                    count + 1,
                )
            };
            for ((i, j), o) in smawk(r - chunk, 0, begin..edge, &f)
                .into_iter()
                .enumerate()
                .zip(out1.iter_mut())
            {
                *o = min(f(i, begin + j), *o);
            }
            let x = unsafe { out1.get_unchecked(r - 1 - chunk) };
            if let Some(j) = (edge..begin + r - 1).find(|&j| &f(r - 1 - chunk, j) <= x) {
                begin = j;
                chunk = 1;
            } else if r == a.len() + 1 - begin {
                break;
            } else {
                chunk *= 2;
            }
        }
        let &(cost, count) = unsafe { out.get_unchecked(a.len()) };
        if count > k {
            low = penalty + 1;
        } else {
            ret = cost.wrapping_sub(k as Cost * penalty);
            if count == k {
                return ret;
            }
            high = penalty - 1;
        }
    }
    ret
}

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let k = lines.next().unwrap().unwrap().parse().unwrap();
    let a = lines
        .map(|s| s.unwrap().parse().unwrap())
        .collect::<Vec<_>>();
    let start = Instant::now();
    let cost = solve(k, &a);
    let time = start.elapsed();
    println!(
        "cost: {}\ntime: {}.{:09} sec",
        cost,
        time.as_secs(),
        time.subsec_nanos()
    );
}

Try it online!

Rust, pretest score = 73

Compile with rustc -O.  Input format is K on the first line, followed by the entries of A, one entry per line, all on stdin.

use std::io::{self, BufRead};
use std::iter::once;
use std::num::Wrapping;
use std::time::Instant;
use std::u64;

type Cost = u64;
const INF: Cost = u64::MAX;

fn smawk<Col: Clone, Key: Ord, F: Clone + Fn(usize, &Col) -> Key>(
    n: usize,
    shift: u32,
    cols: &[Col],
    f: F,
) -> Vec<usize> {
    if n == 0 {
        Vec::new()
    } else if cols.len() > n {
        let mut s = Vec::with_capacity(n);
        let mut sk = Vec::with_capacity(n);
        for (jk, j) in cols.iter().enumerate() {
            while match s.last() {
                Some(l) => f(!(!(s.len() - 1) << shift), j) <= f(!(!(s.len() - 1) << shift), l),
                None => false,
            } {
                s.pop();
                sk.pop();
            }
            if s.len() < n {
                s.push(j.clone());
                sk.push(jk);
            }
        }
        smawk1(
            n,
            shift,
            cols,
            f.clone(),
            smawk(n / 2, shift + 1, &s, f)
                .into_iter()
                .map(|h| unsafe { *sk.get_unchecked(h) }),
        )
    } else {
        smawk1(
            n,
            shift,
            cols,
            f.clone(),
            smawk(n / 2, shift + 1, &cols, f).into_iter(),
        )
    }
}

fn smawk1<Col: Clone, Key: Ord, F: Clone + Fn(usize, &Col) -> Key, Iter: Iterator<Item = usize>>(
    n: usize,
    shift: u32,
    cols: &[Col],
    f: F,
    iter: Iter,
) -> Vec<usize> {
    let mut out = Vec::with_capacity(n);
    let mut range = 0..0;
    for (i, k) in iter.enumerate() {
        range.end = k + 1;
        out.push(
            range
                .clone()
                .zip(unsafe { cols.get_unchecked(range.clone()) })
                .min_by_key(|&(_, col)| f(!(!(2 * i) << shift), col))
                .unwrap()
                .0,
        );
        out.push(k);
        range.start = k;
    }
    if n % 2 == 1 {
        range.end = cols.len();
        out.push(
            range
                .clone()
                .zip(unsafe { cols.get_unchecked(range.clone()) })
                .min_by_key(|&(_, col)| f(!(!(n - 1) << shift), col))
                .unwrap()
                .0,
        );
    }
    out
}

fn solve(k: usize, a: &[Cost]) -> Cost {
    let mut cost = vec![INF; a.len() + 1 - k];
    let sa = once(Wrapping(0))
        .chain(a.iter().scan(Wrapping(0), |s, &x| {
            *s += Wrapping(x);
            Some(*s)
        }))
        .collect::<Vec<_>>();
    cost[0] = 0;
    let cols = (0..a.len() + 1 - k).collect::<Vec<_>>();
    for m in 0..k {
        cost = {
            let f = |i: usize, &j: &usize| {
                if i + 1 >= j {
                    let h = (i + 1 - j) / 2;
                    unsafe {
                        cost.get_unchecked(j).saturating_add(
                            (sa.get_unchecked(i + m + 1) - sa.get_unchecked(i + m + 1 - h)
                                - sa.get_unchecked(j + m + h)
                                + sa.get_unchecked(j + m))
                                .0,
                        )
                    }
                } else {
                    INF
                }
            };
            smawk(a.len() + 1 - k, 0, &cols, &f)
                .into_iter()
                .enumerate()
                .map(|(i, j)| f(i, &j))
                .collect()
        };
    }
    cost[a.len() - k]
}

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let k = lines.next().unwrap().unwrap().parse().unwrap();
    let a = lines
        .map(|s| s.unwrap().parse().unwrap())
        .collect::<Vec<_>>();
    let start = Instant::now();
    let cost = solve(k, &a);
    let time = start.elapsed();
    println!(
        "cost: {}\ntime: {}.{:09} sec",
        cost,
        time.as_secs(),
        time.subsec_nanos()
    );
}

Try it online!


Simulating Crashing Cars Introduction

I have some ASCII cars that have velocity and direction. Their velocity is represented by their number. If a car is <> then it has stopped. For example:

<>
1>
2>
3>

After one second, I get

<>
 1>
  2>
   3>

After two, I get

<>
  1>
    2>
      3>

If two cars are too close, they crash.

1> <1
1> <2

After a second, this becomes

 ###
 ##

If two cars intersect, they become hashtags were they would be.

If one car is fast enough to 'hop' over the other, it does not result in a crash.

3><1   2><1   4><>

becomes

 <13>   ###     <>4>

If a car goes left off-screen, it disappears (unless there's a crash). There is no way for a car to go right off-screen.

 <11>
<1  1>
1    1>
      1>

Challenge

Based on the given car physics, you must create a program that can time-step one second into the future. The input will be cars with spaces and a maximum velocity of 5 (matching regex (<[1-5]|[1-5]>|<>| )+). The simulation will happen on one line, however that line has no fixed size.

Test cases

<> 1> 2> 3> 4> 5>
<>  1>  2>  3>  4>  5>

1><1   1> <1   1>  <1
 ##     ###     1><1

2><2   2> <2   2>  <2   2>   <2   2>    <2
<22>    ###      ##       ###       2><2

<22>  <1 3>   <2
    ###     ##

<><>     1><>     2><>     3><>     4><>     5><>
<><>      ###       ##       ###      <>4>     <> 5>

<><1 <2 <3 <4 <5
###<2<3<4<5

Scoring

This is code-golf, so code with the smallest number of bytes wins!

JavaScript (ES6), 140 bytes

s=>[...s.replace(/\S./g,([a,b],i)=>r[r[i+=+b?-b:~~a]=r[i]?C:a,++i]=r[i]?C:b,r=[],C='#')&&r].map((c,i)=>c?r[i-1]==C|r[i+1]==C?C:c:' ').join``

Try it online!
Commented
s =>                      // given the input string s
  [ ...s.replace(         // search in s ...
    /\S./g,               //   ... all substrings consisting of 2 non-whitespace characters
    ([a, b], i) =>        //   let a be the 1st character, b the 2nd one and i the position
      r[                  //   update r[]:
        r[i +=            //     apply the car velocity to i:
          +b ? -b         //       if b is a digit, then move b cells backwards
                  : ~~a   //       else: use a to move forwards (or don't move at all)
        ] = r[i] ? C : a, //     if r[i] is set, overwrite it with '#'; otherwise, insert a
        ++i               //     increment i for the 2nd character
      ] = r[i] ? C : b,   //     if r[i] is set, overwrite it with '#'; otherwise, insert b
      r = [],             //   initialize r[] to an empty array
      C = '#'             //   define C as the 'crash' character
  ) && r ]                // end of replace(); return a fully iterable copy of r[]
  .map((c, i) =>          // for each entry c at position i in this array:
    c ?                   //   if c is defined:
      r[i - 1] == C |     //     if either the previous
      r[i + 1] == C ?     //     or the next cell is '#' (in the original array):
        C                 //       replace the current cell with '#'
      :                   //     else:
        c                 //       let c unchanged
    :                     //   else:
      ' '                 //     insert a space
  ).join``                // end of map(); join the result


Draw some mountain peaks Write a program or function that draws a mountain range, where each subsequent larger mountain peak is "behind" the ones in front, and alternates which side is visible.

This is a mountain range of size 1

/\

This is a mountain range of size 2

 /\
/\ \

This is a mountain range of size 3

  /\
 / /\
/ /\ \

This is a mountain range of size 4

   /\
  /\ \
 / /\ \
/ /\ \ \

This is a mountain range of size 5

    /\
   / /\
  / /\ \
 / / /\ \
/ / /\ \ \

And so on.

Input

A single positive integer in any convenient format, n > 0.

Output

An ASCII-art representation of the mountain range, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the peaks line up appropriately.

Rules

Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Charcoal, 16 bytes

ＮλＦλ«Ｐ↘⁻λι←↙¹‖Ｔ→

Try it online!

How?

Ｎλ inputs the size of the largest mountain into λ. Ｆλ« runs a loop over values of ι from 0 through λ-1. (The closing » is implied at the end of the program.)

Inside the loop, Ｐ↘⁻λι calculates λ-ι and draws, without moving the cursor afterward, a line of that length going southeast. Based on its direction, this line will consist of \ characters. ← moves one step to the west, and ↙¹ draws a line of length 1 going southwest (made of /). Finally, ‖Ｔ→ horizontally reflects the drawing, transforming characters as appropriate: \ becomes / and / becomes \.

Adding the dump instruction Ｄ at the beginning of the loop (try it) allows us to see the progression:

    /\
   /
  /
 /
/
    /\
   /\ \
  /    \
 /      \
/        \
    /\
   / /\
  / /\ \
 / /    \
/ /      \
    /\
   /\ \
  / /\ \
 / /\ \ \
/ /    \ \
    /\
   / /\
  / /\ \
 / / /\ \
/ / /\ \ \


Calculate the number of trailing zeros in n! Write a function which takes n as a parameter, and returns the number of trailing zeros in n!.

Input Constraints

0 <= n <= 10^100

Output Constraints

Should be return the result in less than 10 seconds.

Test Input

1
213
45678
1234567
78943533
4567894123
121233112233112231233112323123

Test Output

0
51
11416
308638
19735878
1141973522
30308278058278057808278080759

Shortest code by character count wins.

Python 50 47 Characters

n=input()
x=5
s=0
while n/x:s+=n/x;x*=5
print s


Rock Around the Clock In as few Unicode characters as possible, print the following (144 characters):

1, 2, 3 o'clock, 4 o'clock rock,
5, 6, 7 o'clock, 8 o'clock rock,
9, 10, 11 o'clock, 12 o'clock rock,
We're gonna rock around the clock tonight.

You must not use any numbers in your code, except the digit 1.

Javascript - 140 132

k=1,s=", ",t=" o'clock",x="";while(k<11)x+=k+++s+k+++s+k+++t+s+k+++t+" rock,\n";alert(x+"We're gonna rock around the clock tonight.")

The fact, that 11 is made out of two 1's let me pass the rules I guess.

Explanation

The k+++s is equal to (k++)+s, so it adds k first to x, then increments k and then it adds s to x. This process will be done three times before it adds the last sentence.


Separating the _____ from the _____ There are two types of people in this world: users and admins. Let's find out who the real admins are.
The task is simple:
If the script is run with elevation, print 'True' and only 'True' (only trailing newlines permitted as extra). If the script is run as an unelevated user, print 'False' and only 'False', exceptions granted for trailing new lines.
The code can be run on any operating system which is currently available free of charge, or on any CPU architecture as a code insertion OR it can run on Windows 10.
The selected operating system must have at least 3 privilege levels, and should return 'True' for any execution of code above the default user privilege level.
I couldn't find any tags for this, so please if you have suggestions, name them. Good luck!

Python 3, 32 bytes
-13 bytes thanks to @Arnauld
-1 byte thanks to @Dingus

import os
print(os.getuid()<1e3)

Try it online!


Is my prison secure? Your challenge is given an input of a prison layout to work out whether any of the prisoners can escape.

Input

Input may be in any reasonable format such as a string, array, array of arrays etc. The input will consist of three characters, in this case #, P and space. The input will not necessarily contain all three characters.

#: A wall
P: A prisoner
space: An empty space

An example input will look like:

#####
#   #
# P #
#   #
#####

Output

A truthy/falsey value of whether or not the prison is secure. The prison is only secure if it can hold all of the prisoners. If any prisoner can escape it is not secure.

A prisoner can escape if they are not fully enclosed by a wall. A diagonal joining is fully enclosed.

Test cases

############# Truthy
# P #  P#   #
#   #   # P #
#############

############# Truthy
# P    P    #
#   #   # P #
#############

############# Falsey
# P #  P#   #
#   #   # P #
########## ##

####          Truthy
#   #
 #   #
  # P ####
  ####

P             Falsey

###           Falsey
# #
# #
### P

Snails, 13 bytes

!(t\P(o\ ),o~

Try it online!

Prints 0 for insecure prisons and the size of the input's bounding box for secure prisons.

The idea is to ensure that we can't find a path from a P to an out of bounds cell (~) moving only orthogonally (o) through spaces. The t is a teleport so that regardless where we attempt the match it tries all possible starting positions to find a P.


A Most Excellent Code Golf Adventure You dudes, the Most Excellent Adventure is a home brew roleplaying game system based on the Bill & Ted Films, plays gnarly air guitar riff.

In this game system, when you draw from your dice pool (you have between 1 and 12 ten-sided dice, with faces labelled 0-9) you need to connect the results as a phone number on your phone pad:

Here one person has rolled 4, 2, 8, 3, 8, and 2, dialling 3-2-2-4-8-8. The other 7, 4, 6, 3, 9, and 4, only dialling 4-4-7 or 3-6-9. And the longest number wins.

Bill and Ted want to play this game on their telephone kiosk, but haven't the first clue about programming. As Station isn't around, they want you to program it. The kiosk had access to all programming languages and OSs past and future (causality forbids you using any future technology... No imaginary python 7 !)

Your input is two numbers between 1 and 12, representing the number of dice player 1 and player 2 have respectively. The output is the result for each player, and the length of the largest number they could dial.

Input: 8 10
Output:

Player 1 rolled 1 2 3 4 5 6 7 8 with longest dialable number of 8.
Player 2 rolled 8 8 8 2 3 1 4 0 3 3 with longest dialable number of 10.

Numbers can be reordered and pressing the same key twice counts as two digits (which is why the above sequence 8 8 8 2 3 1 4 10 3 3 makes a six digit number not a 4 digit number)

Also, as you're programming this in a telephone kiosk you can only access 0-9, a-z, the * and a # keys in your code. Letters are accessed by repeated typing, much like on a mobile phone. Every other key must be input in the kiosk as its ASCII code in hex like so: #0a the upshot is when scoring your submission, these keys "cost" three times as many.[Unclear / Incorrect?]

For instance to type ~ you press the hash key once, the 7 and then 3 three times to cycle through the digits 3de. This gives the code #7e which corresponds to ~. When you upload you code here you can just type the ~, and count it as five characters.

The keypad looks a little like this:

For instance If your code had print() that would cost 15 for the print (7p 7pqr 4ghi 6mn 8t) plus 6 for the () (#28 #29).

This is code golf as Bill and Ted will get bored otherwise. Let the coding commence plays gnarly air guitar riff.

VBScript - 1668 telephone keypresses (was 1708)

My entry is golfed a bit more - I realized (doh!) that the variable names should be characters that require less telephone keypresses (a,d,g,j,etc).

This program produces the output exactly as shown and takes the input as command line parameters.  If line endings are 1 byte there is no advantage to using : to put it all on one line (#0a vs #3a).  Run it with cscript script.vbs 8 10 replacing 8 and 10 with whatever values you want - it tries every combination in order to get the maximum string so it is SLOW.

I just have one question: if you needed a two numbers beside each other that were both on the same key isn't it a bit ambiguous.  Wouldn't the text a=e (22#333333) be the same keypresses as a>d (22#333333)?  How do you differentiate where the character boundaries are?  I didn't specifically check for every possible occurance of where things on the same key are beside themselves and I don't know what I would have done if I did notice it...

sub b(d,m)
p=true
a=len(m)
for g=1to a-1
p=p and instr(split("7890*1245*123456*2356*124578*123456789*235689*45780*4567890*56890","*")(mid(m,g,1)),mid(m,g+1,1))>0
next
if p and t<a then t=a
if d=""then exit sub
a=len(d)
for g=1to a
w=""
if g>1then w=left(d,g-1)
p=""
if g<a then p=mid(d,g+1)
b w+p,m+mid(d,g,1)
next
end sub
randomize
set m=wscript.arguments
for e=1to 2
d=""
j="Player "+cstr(e)+" rolled"
for t=1to mid(10000+m.item(0)*100+m.item(1),e*2,2)
w=cstr(int(rnd()*10))
j=j+" "+w
d=d+w
next
j=j+" with longest dialable number of"
t=0
b d,""
wscript.echo j+" "+cstr(t)
next

Ok, I am finally ready to score my entry - that of course means no more changes to it because of how long it takes to transform it to a score.  The transformed phone input is:

77777888222#20222#2833#2222266#29#02277#333887777888333#02222#3335555333666#2866#29#02233336666777
7#2044#3331886666#2022#2331#02277#33377#202266633#20444466677777887777#2877777775555444488#28#2278
90*1245*123456*2356*124578*123456789*235689*45780*4567890*56890#22#22222#22*#22#29#2866444433#2866
#2222244#222221#29#29#2222266444433#2866#2222244#22221#222221#29#29#33330#02266633399988#022444433
33#2077#202266633#2088#3222222#2088444333666#2088#33322#02244443333#2033#333#22#2288444333666#2033
3999444488#2077777888222#02222#3335555333666#2833#29#022333366667777#2044#3331886666#2022#02299#33
3#22#22#02244443333#2044#3333188444333666#2099#3335555333333388#2833#2222244#2331#29#02277#333#22#
22#02244443333#2044#3222222#2088444333666#2077#33366444433#2833#2222244#22221#29#022222#2099#22227
7#2222266#222266444433#2833#2222244#222221#29#02266633399988#02233366633#2077777888222#02277772266
633666666444499999333#0227777733388#2066#33399777772222777744447788#233322777744888663336668877777
#022333366667777#20333#3331886666#202#02233#333#22#22#02255#333#22#5055552299993337777#20#22#22222
22277777887777#28333#29#2222#22#20777766665555555533333#22#022333366667777#2088#3331886666#2066444
433#2810000#222266#233344448833366#280#29*100#222266#233344448833366#281#29#22222333*2#222222#29#0
2299#333222277777887777#28444466688#28777766633#28#29*10#29#29#02255#33355#2222#22#20#22#222299#02
233#33333#222299#02266633399988#02255#33355#2222#22#2099444488444#2055556666666443337777788#203344
44225555222225555333#20666888662223337777#2066663333#22#02288#3330#022222#2033#22222#22#22#0229977
7772222777744447788#233333322224446666#2055#2222#22#20#22#2222222277777887777#2888#29#022666333999
88


Clockwise matrix rotation The title pretty much describes it all. Given as input a \$n \times m\$ matrix and an integer \$i\$ create a complete function/program that returns the matrix \$i\$ times clockwise rotated by \$90^\circ\$.

Rules:

as matrix you can use any convenient representation you like e.g. a list of lists etc...
matrix values can be positive and/or negative integer numbers
\$n\$ and \$m\$ are of course always positive integers between 1 and 10
\$i\$ can be any valid integer which belongs in the following range: \${0...10^5}\$
Standard code-golf rules & winning criteria apply but no "winning" answer will be chosen.

EDIT: I had to edit the initial question because for some programming languages it takes too long to compute the result for \$i\in\{0...10^7\}\$. There is a workaround to it but since it's a code-golf just make sure that it simply runs successfully for at least \$i\in\{0...10^5\}\$.

Some test cases:

==== example 1 ====
Input:
5
[[1, 3, 2, 30,],
 [4, 9, 7, 10,],
 [6, 8, 5, 25 ]]

Expected Output:
[[ 6  4  1],
 [ 8  9  3],
 [ 5  7  2],
 [25 10 30]]

==== example 2 ====
Input:
100
[[1]]

Expected Output:
[[1]]

==== example 3 ====
Input:
15
[[150,    3,  2],
 [  4, -940,  7],
 [  6, 8000,  5]]

Expected Output:
[[   2    7    5],
 [   3 -940 8000],
 [ 150    4    6]]

==== example 4 ====
Input:
40001
[[1, 3, 9]]

Expected Output:
[[1],
 [3],
 [9]]
```

APL (Dyalog Unicode), 7 bytes

⌽∘⍉⍣⎕⊢⎕

Try it online!

⎕ prompt for matrix expression from stdin

⊢ yield that

⎕ prompt for \$i\$ expression from stdin

⍣ do the following that many times

⍉ transpose

∘ and then

⌽ mirror


There, I broke it (with scissors) Challenge

Given a string describing a cutting rule and another string, cut parts out of the second string using the rule described by the first string.

Both strings will consist of letters a-z or A-Z, whichever one you choose (they don't have to be represented the same way). The way the second string is to be modified is described below:

Algorithm

Take the first string and imagine filling in the gaps between non-adjacent (increasing) letters with =; for example, abcfg => abc==fg. Then, line up the two strings and return all characters from the first string that aren't above an equal sign. For example, given abcfg and qrstuvw as inputs:

qrstuvw - Modify
abc==fg - Modifier

qrs--vw -> qrsvw

If the modifier is shorter after filling with equal signs, all trailing characters in the second string should be included. If the modifier is longer, the trailing characters are ignored.

The modifier isn't guaranteed to be sorted.

Test Cases

abcfg, qrstuvw -> qrsvw
abqrs, qwertyuiopasdfghjklzxcvbnm -> qwjklzxcvbnm
za, qr -> qr
azazaz, qwertyuioplkjhgfdsazxcvbnmnbvcxzasdfghjklpoiuytrewq -> qmn

Reference Implementation (used to generate test cases) -> TIO

Rules

Standard Loopholes Apply
You may take input as two strings, two lists of characters, a matrix of characters, etc. (any other reasonable format is acceptable)
You may output as a string or a list of characters (or some other standard format for strings)
This is code-golf, so the shortest answer in bytes in each language is declared the winner for its language. No answer will be accepted.
Either string may be empty.

Happy Golfing!

Inspired by Kevin Cruijssen's recent two challenges, "There, I fixed it (with tape/rope)"

JavaScript (ES6), 81 80 bytes
Takes input in currying syntax (modify)(modifier).

s=>g=([c,...a],d=i=0,x=s[k=parseInt(c,36),i+=c?d&&(k-d+26)%26:1])=>x?x+g(a,k):''

Try it online!
Commented
s =>                       // outer function, taking the string s to modify
  g = (                    // recursive inner function g(), taking:
    [c, ...a],             //   c = current modifier character; a[] = remaining characters
    d = i = 0,             //   d = code of previous modifier character; i = pointer in s
    x = s[                 //   x = i-th character of s
      k = parseInt(c, 36), //     k = code of the current modifier character in [10..35]
      i += c ?             //     update i; if c is defined:
        d &&               //       if d = 0, let i unchanged
        (k - d + 26) % 26  //       otherwise, add the difference between k and d (mod 26)
      :                    //     else:
        1                  //       just pick the next character by adding 1
    ]                      //   end of character lookup in s
  ) =>                     //
    x ?                    // if x is defined:
      x + g(a, k)          //   append x and do a recursive call to g()
    :                      // else:
      ''                   //   stop recursion


Has my milk expired? Aww, man, this expiry date doesn't write the months with letters! I can't tell if it's expiring on March 10th or October 3rd... Wait, no, never mind, the year says 2012. (alley-oops half-used brick of cheese into the trash can like a pro)

So let's suppose for a moment that you're too busy to try to reason out when this jar of marinara is supposed to expire. You just want the Cliff Notes version: how likely is it that it's past due? Let's write some code!

You know that the manufacturers print the date as an ordered triple of integers, in one of three formats:

YEAR  MONTH DAY
MONTH DAY   YEAR
DAY   MONTH YEAR

And you know that some dates can only be interpreted in one or two ways, not all three: the 55 in 55-11-5 has to be a year, meaning this particular box of Twinkies expired November 5th, 1955. The year is sometimes given in four digits and not two, which can rule out some options. When it's two digits, though, 50..99 means 1950..1999 and 0..49 means 2000..2049.

Your job is to write a program or function that takes an array of integers which is a valid date in at least one of the interpretations above, and outputs a percent chance it is still good. The percent chance is simply the percentage of valid interpretations of the date that are on or later than today's date.

The array of integers will be your language's [Int] type of length three if it is an argument to a function, and given as either dash-, slash-, or space-separated (you get to pick) integers if used as input on STDIN to a full program.*

"Today's date" can be today's actual date, as obtained through a date function, or the date given in an extra argument to function or extra paramater in STDIN. It may be in Unix epoch seconds, another year-month-day triple entered in one of the three ways above, or another more convenient fashion.

Let's have some examples! The expiry date input will be in the dash-separated style, and assume for the examples below that today's date is July 5th, 2006.

14-12-14 - Both valid interpretations for this (DMY and YMD) are equivalent, December 14, 2014. The output is 100 because this product is definitely still good.
8-2-2006 - The last number is a year, for sure, since it has four digits. This could be either February 8th (expired) or August 2nd (still good). The output is 50.
6-7-5 - This could be anything! The "July 5th, 2006" interpretation is still good (for one day only), but the remaining two are both in 2005 and should be tossed as quickly as possible. The output is 33.
6-5-7 - Here, two out of three interpretations are safe. You can round your decimal up or down, so 66 or 67 are both okay.
12-31-99 - Okay, this one is unambiguously from the turn of the century (years from 50 to 99 are 19XX, and 31 can't possibly be a month). A big fat 0, and you really should clean out your fridge more often.

You can safely assume that any input which does not meet the standards above is not privy to the output rules above.

No web requests or standard loopholes. Date handling libraries are allowed. This is code golf: may the shortest program win.

* If you are using brainfuck or some similarly datatype-handicapped language, you can assume the ASCII values of the first three characters in input are the integers for the date. This excludes the four-digit year logic, sure, but I think we would be too astounded by seeing a solution to this in Brainfuck to slight you for it.

Ruby, 115 characters

f=->a,t{[a,a.rotate(~s=r=0),a.reverse].map{|x,*y|(t>Time.gm(x<100?x+2e3-100*x/=50:x,*y)||r+=100
s+=1)rescue p}
r/s}

This defines a function f that takes two arguments: an array containing the input, and "today's" date.

Examples:

f[[14,12,14], Time.new]
100
f[[8,2,2006], Time.new]
0
f[[8,2,2006], Time.new(2006, 7, 5)]
50
f[[6,7,5], Time.new(2006, 7, 5)]
33


Golf me a polygonal loader Codidact post, CGCC Sandbox, Codidact Sandbox
Given three positive integers as input, animate an ascii-art polygonal loading symbol on the screen.
Intro
You will be given three inputs, \$n\$, \$l\$, and \$d\$...
\$n\$ (one of \$3\$, \$4\$, \$6\$, or \$8\$), is the number of sides of a polygon:
                           * * *
                          *     *
                * * *    *       *
               *     *   *       *
  *    * * *  *       *  *       *
 * *   *   *   *     *    *     *
* * *  * * *    * * *      * * *

\$l\$ is the side length to use. (The above all use \$l = 3\$, the minimum possible value).
You may use any printable ASCII character other than space instead of *.
\$d\$ is the load length and is less than the perimeter.
The task is to create a loading animation as follows:

Make the first frame of the animation by starting at any one of the topmost corners and drawing the perimeter until its length is \$d\$.
Make the next frame by shifting this partial perimeter by 1 clockwise.
Repeat step 2 ad-infinitum.

For example, \$n=3,l=3,d=4\$ would result in the following steps:
  *                          *       *        *
   *  ->    *  ->  *    ->  *   ->  * *  ->  * *  -> . . .
  * *    * * *    * * *    * *     *            *

Example
Here is a solution made by Hakerh400: Try It Online!
Further details(important):

You are guaranteed that \$n∊(3,4,6,8)\$
You are guaranteed that \$l≥3.\$
You are guaranteed that \$d<(l-1)×n.\$
There must be a delay of at least 0.1 s between each step. You can have a delay of up to 10 seconds.
Your language is allowed to output a list of steps infinitely if and only if it cannot clear the screen or do something similar.
If so, there must be at least 2 newlines between each step.
This is not graphical-output.

Scoring
This is code-golf. Shortest answer in each language wins.


Calculate e^x and ln(x) Given a floating point x (x<100), return e^x and ln(x). The first 6 decimal places of the number have to be right, but any others after do not have to be correct.

You cannot have any "magic" constants explicitly stated (e.x. a=1.35914 since 1.35914*2 ~= e), but you can calculate them. Only use +, -, *, and / for arithmetic operators.

If x is less than or equal to 0, output ERROR instead of the intended value of ln(x).

Test Cases:

input: 2
output: 7.389056 0.693147
input: 0.25
output: 1.284025 -1.386294
input: 2.718281828
output: 15.154262 0.999999  (for this to output correctly, don't round to 6 places)
input: -0.1
output: 0.904837 ERROR

Shortest code wins.

PHP 109 107 bytes

<?for($g=1e4;--$g;$l=$y/$g+abs($y=$x>1?1-1/$x:$x-1)*$l)$e=1+$e/$g*$x.=fgets(STDIN);echo"$e ",$x>0?$l:ERROR;

 is a fairly straight-forward calculation. I use a nested form of the sum of inverse factorials, which not only increases the convergence rate, but also allows for exponentiation at the same time:

 is slightly more complicated. All convergent series seem to work for  or , but not both (Newton's iteration does not have this limitation, but requires the calculation of  each step). This isn't really a problem, though, given the log identity:

This means that if, for example, the iteration you're using only works on  and , you can use the multiplicative inverse of  and negate the result. Because I was using a nested identity for , I also chose to use a nested identity for :

 where

Or equivalently, as demonstrated by Paul Walls' implementation:

I define the  case as  (which is necessarily negative), using the absolute value for the inner product, and then allowing a bare  value in the fraction to correct the sign.

Sample I/O:

$ echo 2 | php exp_ln.php
7.3890560989307 0.69314718055995

$ echo 0.25 | php exp_ln.php
1.2840254166877 -1.3862943611199

$ echo 2.718281828 | php exp_ln.php
15.154262234523 0.99999999983113

$ echo -0.1 | php exp_ln.php
0.90483741803596 ERROR

Perl 95 93 89 bytes

$e=1+$e/$?*($x.=<>),$l=$_/$?+$l*abs,$_=$x>1?1-1/$x:$x-1while--$?;print"$e ",$x>0?$l:ERROR

Nearly identical to the PHP solution above, with a slightly larger iteration (65535 down to 0).

Edits:

Both 2 byte improvements due to Paul Walls.
Four more bytes saved in Perl by (ab)using $?, which is stored internally as an unsigned short, and by using $_ to save parentheses in abs.


Recamán's duplicates Recamán's Sequence is defined as follows:

\$a_n=\begin{cases}0\quad\quad\quad\quad\text{if n = 0}\\a_{n-1}-n\quad\text{if }a_{n-1}-n>0\text{ and is not already in the sequence,}\\a_{n-1}+n\quad\text{otherwise}\end{cases}\$

or in pseudo-code:

a(0) = 0,
if (a(n - 1) - n) > 0 and it is not
   already included in the sequence,
     a(n) = a(n - 1) - n
else
     a(n) = a(n - 1) + n.

The first numbers are (OEIS A005132):

0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24, 8, 25, 43, 62, 42, 63, 41, 18, 42

If you study this sequence, you'll notice that there are duplicates, for instance a(20) = a(24) = 42 (0-indexed). We'll call a number a duplicate if there is at least one identical number in front of it in the sequence.

Challenge:

Take an integer input k, and output either the first k duplicate numbers in the order they are found as duplicates in Recamán's Sequence, or only the k'th number.

This first duplicated numbers are:

42, 43, 78, 79, 153, 154, 155, 156, 157, 152, 265, 261, 262, 135, 136, 269, 453, 454, 257, 258, 259, 260, 261, 262

A few things to note:

a(n) does not count as a duplicate if there are no identical numbers in a(0) ... a(n-1), even if a(n+m)==a(n).
42 will be before 43, since its duplicate occurs before 43's duplicate
The sequence is not sorted
There are duplicate elements in this sequence too. For instance the 12th and the 23rd numbers are both 262 (0-indexed).

Test cases (0-indexed)

k      Output
    0      42
    9     152
   12     262
   23     262
  944    5197
  945   10023
10000   62114

This is code-golf, so the shortest code in each language wins!

Explanations are encouraged!

Wolfram Language (Mathematica), 88 85 76 bytes

(For[i=k=j=p=0,k<#,i~FreeQ~p||k++,i=i|p;p+=If[p>++j&&FreeQ[i,p-j],-j,j]];p)&

Try it online!

1-indexed.

Explanation

For[

For loop.

i=k=j=p=0

Start with i (\$=\{a_1, a_2, \ldots\}\$), k (number of duplicates found), j (\$=n\$), p(\$=a_{n-1}\$) equal to 0.

k<#

Repeat while k is less than the input.

i=i|p

Append p to i using the head Alternatives (a golfier version of List in this case).

p+=If[p>++j&&FreeQ[i,p-j],-j,j]

Increment j. If p is greater than j (i.e. \$a_{n-1} > n\$) and p-j is not in i (i.e. \$a_{n-1} - n\$ is new), then increment p by -j. Otherwise, increment p by j.

i~FreeQ~p||k++

Each iteration, increment k if p is not in i (the || (= or) short-circuits otherwise).

... ;p

Return p.


Draw some ASCII-boxes Take two lists of non-negative integers, and output an ASCII-box as it's defined below.

Corners and intersections are pluses: + (ASCII-code 43)
Vertical lines are bars | (ASCII-code 124)
Horizontal lines are minuses - (ASCII-code 45)

The first input list specifies the number of minuses between each plus sign, in the horizontal direction.

The second input list specifies the number of bars between each plus sign, in the vertical direction.

It's easier to explain with a few examples:

0    // No minuses between each + sign
0    // No bars between + signs

++
++

------------------
1 2   // First a single minus, then two minuses
1 2   // First  one bar, then two bars

+-+--+
| |  |
+-+--+
| |  |
| |  |
+-+--+

------------------
1 0 3 0 2 0
2 1 0 0

+-++---++--++
| ||   ||  ||
| ||   ||  ||
+-++---++--++
| ||   ||  ||
+-++---++--++
+-++---++--++
+-++---++--++

Clarifications:

Input order and format are optional
Only the boxes should be printed/displayed, but a trailing space or newlines are accepted.
You may optionally add 1 to all input values if that's more convenient. The second example would then be: 2 3; 2 3.

This is code golf, so the shortest code in bytes win.

Python 2, 117 Bytes

def f(h,v):r="+"+"+".join("-"*i for i in h)+"+\n";print r+r.join(("|"+"|".join(" "*i for i in h)+"|\n")*i for i in v)+r

Try it on ideone.

Not expecting too much from this. Really simple, just uses python joins and string multiplication to pull everything together.


Draw a random hexa-glyph The above image is called a hexa-glyph.  Hexa-glyphs are some cool patterns I made up while doodling during my DiffEq class.  Here's how you make one:

Consider the following set of points, shaped like a regular hexagram.  The inner hexagon is what will contain the final glyph, while the outer 6 points form a star and are where we will start drawing our lines.

From the outer six points, randomly select a pair.  For efficiency, there should be at least one other point between the two selected points (otherwise, it would have no effect on the final figure).  Then, from each of the two points, cast a ray towards the other.  This ray is blocked by previous lines.

Repeat this process until all 9 edges have been formed, as shown in the next few images.

Here is an example of rays being blocked.  The ends of the ray segment are still visible, but the middle portion is occluded by the first two segments we drew.

These two rays are also "blocked," but this doesn't cause any visible difference because they are blocked by the same other line.

Fast-forwarding until all 9 lines are drawn.  If you want a more detailed explanation of these skipped steps, I can expound.

Finally, remove the points of the star.  To make it look prettier, the thick dots are also removed.

The challenge

You challenge is to output a visual representation of a random hexa-glyph.  This is code-golf, fewest bytes wins.

All possible hexa-glyphs should appear with some positive probability. Different hexa-glyphs are generated by changing the order in which the 9 edges are drawn.
Furthermore, all images output by your program must be valid hexa-glyphs. Certain patterns (like a complete outline of the inner hexagon) cannot possibly appear as a hexa-glyph, and so you program mustn't output these.
The output should be a graphical image (printed to screen or file).
The hexagon must be regular, but can appear in any orientation.
Reflections / rotations are not considered unique.  (This might make requirement 1 easier to follow).

Mathematica, 273 268 264 242 bytes

c=CirclePoints;b@_=k=1>0;Graphics[Line/@Cases[Append[Join@@({c@6,{3^.5/2,-Pi/6}~c~6}),{0,0}][[b@#=!k;#]]&/@TakeWhile[#,t=k;(r=t;t=b@#;r)&]&/@Join@@RandomSample[{#,Reverse@#}&/@Partition[Range@12,3,2,1]~Join~Array[{2#,13,2#+6}&,3]],{_,__}]]

The  renders as a superscript T in Mathematica and is a postfix transpose operator.

Sorting out the bugs in this took forever... towards the end I hacked a few things together to make it work, so this is definitely suboptimal. I also wonder whether it might be better overall to implement the spec more literally via the lines across the outer hexagon and let Mathematica's geometry functions handle the intersections.

Note that this is a full program and if you want to run the code multiple times within a single REPL session you'll have to prefix it with Clear[b].

Here are the results of 20 runs:

Explanation

This solution doesn't make use of the outer star points at all. Instead it works directly with the points that are part of the hexaglyph and lines that cover three of them at a time.

Let's label the points:

1 starts on a slightly weird corner but this is due to the (also somewhat weird) default behaviour of CirclePoints. Starting the hexagon from there turned out cheapest.

Now we want to find the relevant lines through three of those points which correspond to connected points of the outer star. The ones around the hexagon are of course just 3 adjacent points (modulo 12), starting from an odd number. The ones across the centre consist of an even number n, 13 and n+6.

Representations of these lines (in the form of lists of three points are generated by the following code):

Partition[Range@12,3,2,1]~Join~Array[{2#,13,2#+6}&,3]

The Partition generates the lines around the hexagon and the Array the lines through the centre. To process both beams, we map this function over the list of lines:

{#,Reverse@#}&

Now we shuffle these with RandomSample to process them in a random order. Join @@ flattens the list of pairs so that we have a list of beams.

Short intermission: to keep track of which points are already blocked we use a lookup function b, which is initialised to True for all values by b@_=k=1>0;. When processing a beam we keep all points until the first point that has b[n] == False (including that one):

TakeWhile[#,t=k;(r=t;t=b@#;r)&]&

I feel like this is the most golfable part right now... the use of two temporary variables to play Mastermind seems really expensive. Anyway, the result of this gives us the points in a line we're allowed to draw. Now this function is mapped over each of those points:

Append[Join@@({c@6,{3^.5/2,-Pi/6}~c~6}),{0,0}][[b@#=!k;#]]&

The first part generates the list of all 13 points using the interleaved results of two calls to CirclePoints (with different radii for the edge centres and the corners of the hexagon). Note the b@#=!k which now sets the lookup table's value for the current point to False so that no further beam can pass through it. Finally, the value is used as an index into the list of coordinates to get the correct 2D point.

Cases[...,{_,__}]

This discards all single-element lists, because they would render as individual (and visible) points. Finally we render the result:

Graphics[Line/@...]


Are These Scores Possible? Background
In the sport of Table Tennis (aka Ping-Pong or Whiff Whaff), two opponents play a sequence of rounds, where each round consists of players hitting a ball back and forth until one player (may or may not be the server) gains a point.
Table Tennis has some official rules that make for a good game, but we will use a different set of rules for a better challenge.
The modified rules are as follows:

The score is announced directly before each serve as a pair (current server's score, other player's score).
Person A serves for 5 points, then Person B serves for 5 points, then back to A. Hence, A serves whenever the total score A+B is 0-4 mod 10.
After each serve, either A scores a point or B scores a point. A and B both start with 0 points.
For simplicity, games never end.

Following is an example game:
(A starts serving, so the scores are read as (A,B))
0,0; A scores a point
1,0; B scores a point
1,1; A scores a point
2,1; A scores a point
3,1; A scores a point
(B is now serving, so the scores are read as (B,A))
1,4; A scores a point
1,5; B scores a point
2,5; B scores a point
3,5; B scores a point
4,5; B scores a point
(A is now serving, so the scores are read as (A,B))
5,5; B scores a point
5,6 …
(game continues)

Task
Given a pair of unique score readouts, determine if they can be announced in the same game.
Your program/function may take input as any reasonable way equivalent to an ordered pair of numbers.
The output can follow your language's convention for truthy/falsey or use any two distinct values to represent true/false.
Examples
Given (4,5), (1,4), the output should be truthy. The example game is one where this score set occurs.
Given (4,2), (3,5), the output should be falsey. They occur at point totals 6 and 8 respectively, so B is serving in both readouts, so both are reported as (B,A). It is impossible for B's score to decrease from 4 to 3 while A's score increases from 2 to 5, so this situation is impossible.
Given (3,1), (1,5), the output should be truthy. (3,1) is reported as (A,B), while (1,5) is reported as (B,A), so the game can transition from (3,1) to (1,5) if A scores 2 points.
Test Cases
Truthy:
(4,5), (1,4)
(3,1), (1,5)
(0,0), (0,1)
(0,0), (45,54)
(6,9), (11,9)

Falsey:
(12,5), (11,6)
(4,2), (3,5)
(3,3), (5,2)
(2,1), (4,1)
(17,29), (17,24)

Python 2, 58 bytes

lambda a,b,A,B:(A-a)*(B-b)<(a-b)*(A-B)*((a+b)/5+(A+B)/5&1)

Try it online!
Outputs True/False reversed
59 bytes

lambda a,b,A,B:A*B+a*(b-A-B)<(b-a)*[A,B][(a+b)/5+(A+B)/5&1]

Try it online!
59 bytes

lambda a,b,A,B:A*B+b*a<[A*b+B*a,a*A+b*B][(a+b)/5+(A+B)/5&1]

Try it online!
62 bytes

a,b,A,B=input()
if(a+b)/5+(A+B)/5&1:a,b=b,a
print(A-a)*(B-b)<0

Try it online!


Watch the bookie win When you roll a die, you have a 6:1 chance of any given option.

There's a bookmaker taking bets on die rolls. He owns £20 at the start of the game.

The bookmaker offers odds of 4:1, but gamblers take it, because there's money on offer.

There are 10 gamblers. A, B, C, D, E, F, G, H, I, and J. Each gambler owns 10 pounds sterling.

Each round, the 10 gamblers each bet £1 on a die roll, if they have any money left.

If they win their bet, £4 is transferred from the bookmaker to the gambler.
If they lose, £1 is transferred from the gambler to the bookmaker.

The game ends in either of these conditions:

The bookmaker runs out of money, or is in debt.
All of the gamblers have run out of money.

We should see the result presented as a series of tables, like so:

Turn 1
Roll: 2

|                | Bookie | A  | B  | C  | D  | E  | F  | G  | H  | I  | J  |
| Start money    | 20     | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 |
| Bet            | n/a    | 1  | 3  | 2  | 1  | 2  | 4  | 6  | 5  | 2  | 4  |
| Balance change | -2     | -1 | -1 | +3 | -1 | +3 | -1 | -1 | -1 | +3 | -1 |
| End money      | 18     | 9  | 9  | 13 | 9  | 13 | 9  | 9  | 9  | 13 | 9  |

Turn 2
Roll: 4

|                | Bookie | A  | B  | C  | D  | E  | F  | G  | H  | I  | J  |
| Start money    | 18     | 9  | 9  | 13 | 9  | 13 | 9  | 9  | 9  | 13 | 3  |
| Bet            | n/a    | 1  | 2  | 3  | 4  | 5  | 6  | 1  | 2  | 3  | 4  |
| Balance change | +2     | -1 | -1 | -1 | +3 | -1 | -1 | -1 | -1 | -1 | +3 |
| End money      | 20     | 8  | 8  | 12 | 8  | 12 | 8  | 8  | 8  | 12 | 12 |

When a gambler runs out of money, they can't bet any more. Their bet is 0.

turn 20
roll: 5

|                | Bookie | A  | B  | C  | D  | E  | F  | G  | H  | I  | J  |
| Start money    | 180    | 3  | 1  | 12 | 4  | 0  | 1  | 3  | 6  | 23 | 1  |
| Bet            | n/a    | 1  | 2  | 3  | 4  | 0  | 6  | 1  | 2  | 3  | 4  |
| Balance change | +2     | -1 | -1 | -1 | +3 | 0  | -1 | -1 | -1 | -1 | +3 |
| End money      | 20     | 8  | 8  | 12 | 8  | 0  | 8  | 8  | 8  | 12 | 12 |

Write some code to model this game, and display the results in a table:

Use any language
The gamblers can change their bet each turn, always bet on the same number, all bet on the same number. As long as each turn they bet on one number from 1 to 6.
The die roll must be a random integer from 1 to 6. Use a typical, vernacular definition of random.
The end money from one turn is the start money of the next turn.
The balance change for the bookie is the sum of the other balance changes.
Each turn your program should output:

Which turn we are on
The resulting die roll
The starting balance, die roll, balance change, and ending balance for the bookie and all ten gamblers, as an ascii table.

Attempt to do so in the fewest bytes.

JavaScript (Node.js), 548 516 511 485 453 397 396 392 372 325 323 260 bytes

f=(i=!(b=20,p=10))=>b*p>0?`T:${++i} R:${(r=0|Math.random()*6)+1}
|   |Book|A |B |C |D |E |F |G |H |I |J |
|Stt${(d=(n,s)=>`|${n}`.padEnd(5)+`|${s}`.padEnd(3).repeat(10)+`|
`)(b,p)}|Bet${d('n/a',1)}|Chg${d(u=r?'+10':-40,v=r?-1:'+4')}|End`+d(b+=+u,p+=+v)+f(i):''

Try it online!

-32 something bytes by shortening row labels. Also fixed the dice roll being 0-5, not 1-6
-5 bytes by compacting output format
-26 bytes because padding
-32 bytes because whitespace is the devil
-56 bytes thanks to ASCII-only and Luis Felipe in chat
-1 byte because return x doesn't need to be on a new line
-4 bytes thanks to some small refactors from ASCII-only
-20 bytes thanks to more collaboration in chat and some changes by Kevin Cruijssen
-47 bytes because y was the devil and ASCII-only performed an exorcism
-2 bytes because ASCII-only is a golfing machine
-63 bytes thanks to the work of several people in the comments

The golf I took was calculated, but man am I bad at golf.

Almost looks like python rather than JS because where possible I used newlines in place of semicolons for readability.

All gamblers always bet on 1, so we only need to store 1 gambler balance (p), the bookie's balance is b.

Explanation time

I need to rewrite the explanation to match the 260 byte version, but check the revision history for the lengthy explanation of the 323 byte version.


Display words using 7-segment display My first ever Programming Puzzles & Code Golf is the Seven-Slash Display. Here is my first Challenge, also based on 7-segment display.
I often think about, besides numbers, what kind of letters I can display using a simple 7 segment display. Turns out a lot of letters can be displayed. In fact, all but the letters K, M, V, W, X can be displayed using a single 7-segment display. This is because you can display either lower case or the upper case of a letter. e.g.
"abcdef" can be displayed as
 _     _     _  _
!_!!_ !   _!!_ !_
! !!_!!_ !_!!_ !

Note that each character is a 3x3 matrix made up of ! and _.
Of course, the 7-segment display can be used to display numbers and symbols:
 _     _  _  _           _  _     _
  ! _ !_ !_ !      _!  !!_ !_!!  !_!!_!
  !    _!!_ !_!   !_!  ! _!!  !_ ! ! _!

Some letters can have both upper and lower case:
 _                 _
!   _ !_!!_   !   ! ! _ ! !
!_ !_ ! !! !  !  !!_!!_!!_!!_!

Here are the full set of characters:
 _     _  _     _  _  _  _  _                       _
! !  ! _! _!!_!!_ !_   !!_!!_!    _ !_     _     _  _!
!_!  !!_  _!  ! _!!_!  !!_! _!   !_ ! !  !!_!!_!   !

 _     _     _  _  _                 _  _  _     _           _
!_!!_ !   _!!_ !_ !  !_!  !  !!   _ ! !!_!!_! _ !_ !_ ! !!_! _!
! !!_!!_ !_!!_ !  !_!! !  !!_!!_ ! !!_!!    !!   _!!_ !_! _!!_

Pay attention that there are a white space( ), a dash(-) and a question mark(?). The letter I, O and Z are the same as numbers 1, 0 and 2 respectively.
In this challenge, you will write a program or a function to display a string using 7-segment display format above.
Rules

You can write a program or a function

This is code-golf, the shortest code in bytes wins

Your program or function should take input from STDIN or as a parameter. And outputs a string to STDOUT or as a string in 3 lines without leading space but terminated with newline. Handle upper/lower case of CHIOU properly.

You may optionally print trailing white spaces

You must follow the format above. Using underscore _ and exclamation mark ! to form your 7-segment display.

You must support white space( ), dash(-) and question mark (?)

If the string contain unsupported character (k, m, v, w, x), a single error character (3 horizon line, see example) is displayed. Besides the 5 unsupported characters, you can assume the input is made up of only supported character set.

I opted to not have a letter for lowercase L (l) due to confusions but if you are so inclined, you can display it like a 1 either to the right or left.

Examples
$./a.out Start
 _     _
!_ !_ !_! _ !_
 _!!_ ! !!  !_
$./a.out "7-seg dIsplay"
 _     _  _  _           _  _     _
  ! _ !_ !_ !      _!  !!_ !_!!  !_!!_!
  !    _!!_ !_!   !_!  ! _!!  !_ ! ! _!
$./a.out "0123456789 chiou-?"
 _     _  _     _  _  _  _  _                       _
! !  ! _! _!!_!!_ !_   !!_!!_!    _ !_     _     _  _!
!_!  !!_  _!  ! _!!_!  !!_! _!   !_ ! !  !!_!!_!   !
$./a.out "ABCDEFGHIJLNOPQRSTUZ"
 _     _     _  _  _                 _  _  _     _        _
!_!!_ !   _!!_ !_ !  !_!  !  !!   _ ! !!_!!_! _ !_ !_ ! ! _!
! !!_!!_ !_!!_ !  !_!! !  !!_!!_ ! !!_!!    !!   _!!_ !_!!_
$./a.out "abcdefghijlnopqrstuz"
 _           _  _  _                    _  _     _        _
!_!!_  _  _!!_ !_ !  !_      !!   _  _ !_!!_! _ !_ !_     _!
! !!_!!_ !_!!_ !  !_!! !  !!_!!_ ! !!_!!    !!   _!!_ !_!!_
$./a.out "Bad Form"
 _
 _
 _
$./a.out "Hello"
    _
!_!!_ !  !   _
! !!_ !_ !_ !_!
$./a.out "World"
 _
 _
 _

CJam, 123 114 112 110 bytes

Qq_eu";=KMVWX":T&"@"@?" -chiou"Tereu{i"^A^W^G;^Þ¯     ^Þ^Û9³·^É¿»
^@
^P
^Ü^Ò½7¦^_¶´§=   ^O^V&5^U¯¼¹^T³6/"=i2b9Ue[3/"!_!"f.{S?}.+}/N*

The above uses caret notation, since the code contains unprintable characters. One of them is a null byte (^@), which means that this code can only be executed from the command line.

At the cost of only two more bytes (for a total of 112), we can fix this.

Qq_eu";=KMVWX":T&"@"@?" -chiou"Tereu{i"AWG{ÞïIÞÛyó÷Éÿû
@
P
ÜÒýwæ_öôç}IOVfuUïüùTóvo"=i448+2b1>3/"!_!"f.{S?}.+}/N*

This time, all characters are printable. Try it online in the CJam interpreter.

Example run

$ LANG=en_US
$ xxd -ps -r > 7seg.cjam <<< 51715f6575223b3d4b4d565758223a5426224022403f22202d6368696f752254657265757b69220117073b9eaf099e9b39b3b789bfbb0a000a100a9c92bd37a61fb6b4a73d090f16263515afbcb914b3362f223d6932623955655b332f22215f2122662e7b533f7d2e2b7d2f4e2a
$ wc -c 7seg.cjam
110 7seg.cjam
$ echo -n '0123456789 chiou-?' | cjam 7seg.cjam; echo
 _     _  _     _  _  _  _  _                       _
! !  ! _! _!!_!!_ !_   !!_!!_!    _ !_     _     _  _!
!_!  !!_  _!  ! _!!_!  !!_! _!   !_ ! !  !!_!!_!   !
$ echo -n 'ABCDEFGHIJLNOPQRSTUYZ' | cjam 7seg.cjam; echo
 _     _     _  _  _                 _  _  _     _           _
!_!!_ !   _!!_ !_ !  !_!  !  !!   _ ! !!_!!_! _ !_ !_ ! !!_! _!
! !!_!!_ !_!!_ !  !_!! !  !!_!!_ ! !!_!!    !!   _!!_ !_! _!!_
$ echo -n 'World' | cjam 7seg.cjam; echo
 _
 _
 _

Idea (printable version)

Each character can be shown on the 9-segment display

!_!
!_!
!_!

by replacing some of its characters characters with spaces.

We can turn a specific character into an integer by replacing each shown segment, in natural reading order, with a 1, each not shown segment with a 0 and considering the result binary digits.

The first and third segment are never shown, so this will produce integers in the ranges [0,64) and [128,192).

We can encode each of these integers as a single byte, but half of them will result in unprintable characters. Thus, we add 64 to each integer before casting to character, which makes sure the code points are in the ranges [64,128) and [192,256).

The only unprintable character in these two ranges is DEL (code point 127), which corresponds to the following, unsued display configuration:

!_!
!_!

We can reverse the above encoding by adding 448 == 512 - 64 to each code point, converting to base 2 and removing the first binary digit.

All that's left to to find an efficient way of associating these encoded segmenets with their corresponding ASCII characters.

If we map the characters of " -chiou" to the characters of ";=KMVWX" and convert the entire input to uppercase, we can simply store encoding for all characters between 0 (code point 48) and Z (code point 90), giving a range of 43.

Array indexing is modular in CJam, so if A is a string of length 43, A86=, A43= and A0= all yield the same results. The character with code point 86 is V, so we simply store the encoded segments of V - Z and 0 - U, in order.

In the actual code, we select the at sign as "bad form" character, replace the entire input with the string "@" if it contains a forbidden letter and reverse the steps from above.

Code (printable version)

Q            e# Push an empty array for posterior concatenation.
q            e# Read from STDIN.
_eu          e# Copy the input and convert is to uppercase.
";=KMVWX":T& e# Intersect the result with with T := ";=KMVWX".
"@"@?        e# Select "@" if truthy and the input if falsy.
" -chiou"Ter e# Perform transliteration.
eu           e# Convert everything to uppercase.
{            e# For each character in the modified input:
  i          e#   Push its code point.
  "…"=       e#   Select the corresponding character from the string.
  i448+      e#   Push that character's code point and add 448.
  2b1>       e#   Convert to base 2 and discard the first digit.
  3/         e#   Group into triplets of digits (rows).
  "!_!"      e#   Push that string.
  f.{        e#   For each group of digits:
    S?       e#     Select the corresponding char of "!_!" for 1 and " " for 0.
  }          e#
  .+         e#   Concatenate along the rows with the previous results.
}/           e#
N*           e# Join, separating by linefeeds.


Count to 20 with Words! Using the following length-separated lists of words:
https://github.com/Magic Octopus Urn/wordListsByLength
Print 1 word from each list of length n  from 1 all the way up to 20, here's a valid example:
a
an
and
hand
hands
handle
handles
abandons
abandoned
understand
outstanding
newfoundland
understanding
characteristic
characteristics
characterization
characterizations
characteristically
characterologically
chemotherapeutically

Alternatively (array):
['a', 'an', 'and', 'hand', 'hands', 'handle', 'handles', 'abandons', 'abandoned', 'understand', 'outstanding', 'newfoundland', 'understanding', 'characteristic', 'characteristics', 'characterization', 'characterizations', 'characteristically', 'characterologically', 'chemotherapeutically']

Alternatively (any printable non-alphabetic separator other than \n):
a:an:and:hand:hands:handle:handles:abandons:abandoned:understand:outstanding:newfoundland:understanding:characteristic:characteristics:characterization:characterizations:characteristically:characterologically:chemotherapeutically

Rules

You may choose your own 20 words.
The words must be from the github page provided, more specifically:

1 from 1.txt, 1 from 2.txt, etc...
Note, files above 20.txt exist, but you do not need any words above 20 characters.

Valid separators are ASCII-printable non-alphabetical characters (even numbers, don't care).
Lowercase or uppercase only, pick one, stick with it; no title-case allowed.
Please don't use a 100% copy of my example 20 words...

You can, but that's no fun.
They are likely suboptimal anyways...

If you DON'T want to use the separated files, and need a full list:

Use unsorted.txt, this is all n.txt files in one, sorted alphabetically.

Note, you CANNOT directly read from the URL, it is a common loophole.
This is code-golf, lowest byte-count will be the winner.

For reference, the output is 229 bytes, so anything that gets under that beats hardcoding.

Possible meta-tag-discussion:
user-driven where the user gets to customize their outputs from a list of possibilities?

Python 2, 145 bytes

print'i am now tiny @ @s##s#ed#act#acts#@#@s#@ed#@ing#arguments#accusation#accusations#advertisings'.replace('#',' counter').replace('@','check')

Try it online!

Prints these words, separated by spaces:

i
am
now
tiny
check
checks
counter
counters
countered
counteract
counteracts
countercheck
counterchecks
counterchecked
counterchecking
counterarguments
counteraccusation
counteraccusations
counteradvertisings


Generalized integer casting in Python Background

I have a string in Python which I want to convert to an integer. Normally, I would just use int:

>>> int("123")
123

Unfortunately, this method is not very robust, as it only accepts strings that match -?[0-9]+ (after removing any leading or trailing whitespace). For example, it can't handle input with a decimal point:

>>> int("123.45")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123.45'

And it certainly can't handle this:

>>> int("123abc?!")

On the other hand, exactly this behavior can be had without any fuss in Perl, PHP, and even the humble QBasic:

INT(VAL("123abc"))   ' 123

Question

Here's my shortest effort at this "generalized int" in Python. It's 50 bytes, assuming that the original string is in s and the result should end up in i:

n="";i=0
for c in s:
 n+=c
 try:i=int(n)
 except:0

Fairly straightforward, but the try/except bit is ugly and long. Is there any way to shorten it?

Details

Answers need to do all of the following:

Start with a string in s; end with its integer value in i.
The integer is the first run of digits in the string. Everything after that is ignored, including other digits if they come after non-digits.
Leading zeros in the input are valid.
Any string that does not start with a valid integer has a value of 0.

The following features are preferred, though not required:

A single - sign immediately before the digits makes the integer negative.
Ignores whitespace before and after the number.
Works equally well in Python 2 or 3.

(Note: my code above meets all of these criteria.)

Test cases

"0123"   -> 123
"123abc" -> 123
"123.45" -> 123
"abc123" -> 0
"-123"   -> -123 (or 0 if negatives not handled)
"-1-2"   -> -1 (or 0 if negatives not handled)
"--1"    -> 0
""       -> 0

Python 2, 47, 46
It's not as short as using regex, but I thought it was entertainingly obscure.
i=int(('0%sx'%s)[:~len(s.lstrip(str(1<<68)))])

-1 due to KSab – str with some large integer works better than the repr operator since it does not put an L on the end.


Add N numbers without using + or - Given N integers, output the sum of those integers.
Input
You may take the integers in any reasonable format, including:

stdin
arguments
an array or list

Rules

Your code must not include the characters + or -.

Standard loopholes apply. Take note of Abusing native number types to trivialize a problem.

This is code-golf. The shortest code in each language wins, which means that I will not be accepting an answer.

Testcases
n=2, 1, 2 -> 3
n=2, 2, 2 -> 4
n=2, 9, 10 -> 19
n=2, 7, 7 -> 14
n=2, 8, 8 -> 16
n=2, -5, 3 -> -2
n=2, -64, -64 -> -128
n=2, -3, 0 -> -3
n=2, 0, 3 -> 3
n=2, 0, 0 -> 0
n=2, -1, -1 -> -2
n=2, -315, -83 -> -398
n=2, 439, 927 -> 1366
n=3, 1, 2, 3 -> 6
n=3, 2, 2, 5 -> 9
n=3, 0, 9, 10 -> 19
n=3, 7, 0, 7 -> 14
n=3, 8, 8, 0 -> 16
n=3, -5, 3, -2 -> -4
n=3, -64, -64, 16 -> -112
n=3, -3, 0, 0 -> -3
n=3, 0, 3, 0 -> 3
n=3, 0, 0, 0 -> 0
n=3, -1, -1, -1 -> -3
n=3, -315, -83, -34 -> -432
n=3, 439, 927, 143 -> 1509
n=17, -74, 78, 41, 43, -20, -72, 89, -78, -12, -5, 34, -41, 91, -43, -23, 7, -44 -> -29

Testcases with partial sums that exceed 8 bits are only required if your integer type supports each partial sum (if any) and the final result. As a special case, n=2, -64, -64 -> -128 is only required if your integer type can represent -128.
Testcases involving negative integers are only required if your language natively supports negative integers.

Wolfram Language (Mathematica), 2 bytes

Tr finds the trace of the matrix or tensor list

Tr

Try it online!


Fifty Shades of Grey Boys and girls are excited to see Fifty Shades of Grey on the silver screen, we just want to code without being bothered, so here's a challenge to pick our brain.

You have to:

Print on the screen fifty squares filled each with a different shade of grey
If your language of choice lacks image processing capabilities, you could output an image file
Squares must be visible, at least 20 x 20 pixels
You cannot use random numbers unless you make sure each shade is unique.
You cannot connect to any service over any network
You cannot read any files in your program.
You cannot use any libraries out of the standard libraries of your language of choice.

This is code golf so shortest code wins.