Dihedral group D4 composition with custom labels The dihedral group \$D_4\$ is the symmetry group of the square, that is the moves that transform a square to itself via rotations and reflections. It consists of 8 elements: rotations by 0, 90, 180, and 270 degrees, and reflections across the horizontal, vertical, and two diagonal axes.

The images are all from this lovely page by Larry Riddle.

This challenge is about composing these moves: given two moves, output the move that's equivalent to doing them one after another. For instance, doing move 7 followed by move 4 is the same as doing move 5.

Note that switching the order to move 4 then move 7 produces move 6 instead.

The results are tabulated below; this is the Cayley table of the group \$D_4\$. So for example, inputs \$7, 4\$ should produce output \$5\$.

\begin{array}{*{20}{c}}
   {} & {\begin{array}{*{20}{c}}
   1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\
\end{array} }  \\
   {\begin{array}{*{20}{c}}
   1  \\
   2  \\
   3  \\
   4  \\
   5  \\
   6  \\
   7   \\
   8   \\
\end{array} } & {\boxed{\begin{array}{*{20}{c}}
   1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\
   2 & 3 & 4 & 1 & 8 & 7 & 5 & 6\\
   3 & 4 & 1 & 2 & 6 & 5 & 8 & 7\\
   4 & 1 & 2 & 3 & 7 & 8 & 6 & 5\\
   5 & 7 & 6 & 8 & 1 & 3 & 2 & 4\\
   6 & 8 & 5 & 7 & 3 & 1 & 4 & 2\\
   7 & 6 & 8 & 5 & 4 & 2 & 1 & 3\\
   8 & 5 & 7 & 6 & 2 & 4 & 3 & 1\\
\end{array} }}  \\
\end{array}

Challenge

Your goal is to implement this operation in as few bytes as possible, but in addition to the code, you also choose the labels that represent the moves 1 through 8. The labels must be 8 distinct numbers from 0 to 255, or the 8 one-byte characters their code points represent.

Your code will be given two of the labels from the 8 you've chosen, and must output the label that corresponds to their composition in the dihedral group \$D_4\$.

Example

Say you've chosen the characters C, O, M, P, U, T, E, R for moves 1 through 8 respectively. Then, your code should implement this table.

\begin{array}{*{20}{c}}
   {} & {\begin{array}{*{20}{c}}
   \, C  \, & \, O \, & M \, & P \, & U \, & \, T \, &  \, E \,  &  R \, \\
\end{array} }  \\
   {\begin{array}{*{20}{c}}
   C  \\
   O  \\
   M  \\
   P  \\
   U  \\
   T  \\
   E   \\
   R   \\
\end{array} } & {\boxed{\begin{array}{*{20}{c}}
   C & O & M & P & U & T & E & R \\
   O & M & P & C & R & E & U & T\\
   M & P & C & O & T & U & R & E\\
   P & C & O & M & E & R & T & U\\
   U & E & T & R & C & M & O & P\\
   T & R & U & E & M & C & P & O\\
   E & T & R & U & P & O & C & M\\
   R & U & E & T & O & P & M & C\\
\end{array} }}  \\
\end{array}

Given inputs E and P, you should output U. Your inputs will always be two of the letters C, O, M, P, U, T, E, R, and your output should always be one of these letters.

Text table for copying

1 2 3 4 5 6 7 8
2 3 4 1 8 7 5 6
3 4 1 2 6 5 8 7
4 1 2 3 7 8 6 5
5 7 6 8 1 3 2 4
6 8 5 7 3 1 4 2
7 6 8 5 4 2 1 3
8 5 7 6 2 4 3 1

Ruby, 18 bytes

->a,b{a+b*~0**a&7}

Ungolfed

->a,b{ (a+b*(-1)**a) % 8}
# for operator precedence reasons,
#-1 is represented as ~0 in the golfed version

Try it online!

Uses the following coding numbers 0 to 7

In order native to the code:

Native     Effect                    Codes per
Code                                 Question
0          rotate 0 anticlockwise    1C
1 /        flip in y=x               7E
2 /|       rotate 90 anticlockwise   2O
3 /|/      flip in x axis            5U
4 /|/|     rotate 180 anticlockwise  3M
5 /|/|/    flip in y=-x              8R
6 /|/|/|   rotate 270 anticlockwise  4P
7 /|/|/|/  flip in y axis            6T

In order per the question

Native     Effect                    Codes per
Code                                 Question
0          rotate 0 anticlockwise    1C
2 /|       rotate 90 anticlockwise   2O
4 /|/|     rotate 180 anticlockwise  3M
6 /|/|/|   rotate 270 anticlockwise  4P
3 /|/      flip in x axis            5U
7 /|/|/|/  flip in y axis            6T
1 /        flip in y=x               7E
5 /|/|/    flip in y=-x              8R

Explanation

/ represents a flip in the line y=x and | represents a flip in the y axis.

It is possible to generate any of the symmetries of the group D4 by alternately flipping in these two lines For example / followed by | gives /| which is a rotation of 90 degrees anticlockwise.

The total number of consecutive flips gives a very convenient representation for arithmetic manipulation.

If the first move is a rotation, we can simply add the number of flips:

Rotate 90 degrees   +  Rotate 180 degrees = Rotate 270 degrees
/|                     /|/|                 /|/|/|

Rotate 90 degress   +  Flip in y=x        = Flip in x axis
/|                    /                     /|/

If the first move is a reflection, we find we have some identical reflections / and | symbols next to each other. As reflection is self inverse we can cancel out these flips one by one. So we need to subtract one move from the other

Flip in x axis     +  Flip in y=x        = Rotate 90 degrees
/|/                   /                    /|/ / (cancels to) /|

Flip in x axis     +  Rotate 90 degrees  = Flip in y=x
/|/                   /|                   /|/ /| (cancels to ) /


Reverse a string while maintaining the capitalization in the same places The goal here is to simply reverse a string, with one twist:
Keep the capitalization in the same places.

Example Input 1: Hello, Midnightas
Example Output 1: SathginDim ,olleh

Example Input 2: .Q
Exmaple Output 2: q.

Rules:

Output to STDOUT, input from STDIN
The winner will be picked 13th of July on GMT+3 12:00 (One week)
The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters.
Any punctuation ending up in a position where there was an upper-case letter must be ignored.

Python, 71 bytes
lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1]))

Try it online
-3 bytes from Ruud, plus the inspiration for 2 more.
-4 more bytes from FryAmTheEggman


Score a hand of Hearts Hearts is a trick-taking card game for 4 players. Each trick is taken by the player who played the highest card of the leading suit. At the end of each hand, the players incur a penalty score depending on the penalty cards they have taken; the task is to determine the scores under Microsoft Hearts rules.

Input

Input is 4 lists (or delimited string, array, etc.) showing the penalty cards taken by each of the 4 players. The penalty cards are

2♥, 3♥, 4♥, 5♥, 6♥, 7♥, 8♥, 9♥, 10♥, J♥, Q♥, K♥, A♥, Q♠

which we shall represent as

2,  3,  4,   5,  6,  7,  8,  9,  10,  11, 12,  13,  1,  0

respectively.

Output

Output is the 4 penalty points incurred by the 4 players (list, string, array etc.). Scoring is as follows:

Each heart (♥, represented by integers 1 to 13 inclusive) incurs 1 point
The queen of spades (Q♠, represented by 0) incurs 13 points
Exception: if a player has taken all of the penalty cards (called shooting the moon), then he incurs 0 points, while all other players incur 26 points.

Test cases

[2, 8, 7, 1], [3, 4], [], [9, 5, 6, 0, 10, 11, 12, 13]     -->  4,  2,  0, 20
[0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [], [], [1]   --> 25,  0,  0,  1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0], [], [], [] -->  0, 26, 26, 26

Shortest code in bytes wins.

R, 85 77 74 bytes

function(x,z=sapply(x,function(x)sum(x>0)+any(x<1)*13))abs(z-any(z>25)*26)

Unnamed function that takes an R-list as input. Works by counting the number of elements >0 and adds 13 if any element within each vector is <1 (i.e. queen of spades) and store as z.

If any element in z is >25, return 26-z, else return z.

Try it on R-fiddle


Calculate the Number, Divisors Edition Inspired by this question over on Math.
Let the prime factorization of a number, n, be represented as: \$P(n) = 2^a\times3^b\times5^c\times\cdots\$. Then the number of divisors of n can be represented as \$D(n) = (a+1)\times(b+1)\times(c+1)\times\cdots\$. Thus, we can easily say that the number of divisors of \$2n\$ is \$D(2n) =  (a+2)\times(b+1)\times(c+1)\times\cdots\$,
the number of divisors of \$3n\$ is \$D(3n) =  (a+1)\times(b+2)\times(c+1)\times\cdots\$,
and so on.
Challenge
Write a program or function that uses these properties to calculate \$n\$, given certain divisor inputs.
Input
A set of integers, let's call them \$w, x, y, z\$, with all of the following definitions:

all inputs are greater than 1 -- \$w, x, y, z > 1\$
\$x\$ and \$z\$ are distinct -- \$x\ne z\$
\$x\$ and \$z\$ are prime -- \$P(x)=x, D(x)=2, P(z)=z \text{ and } D(z)=2\$
\$w\$ is the number of divisors of \$xn\$ -- \$D(xn)=w\$
\$y\$ is the number of divisors of \$zn\$ -- \$D(zn)=y\$

For the problem given in the linked question, an input example could be \$(28, 2, 30, 3)\$. This translates to \$D(2n)=28\$ and \$D(3n)=30\$, with \$n=864\$.
Output
A single integer, \$n\$, that satisfies the above definitions and input restrictions.  If multiple numbers fit the definitions, output the smallest. If no such integer is possible, output a falsey value.
Examples:
(w, x, y, z) => output

(28, 2, 30, 3) => 864
(4, 2, 4, 5) => 3
(12, 5, 12, 23) => 12
(14, 3, 20, 7) => 0 (or some other falsey value)
(45, 13, 60, 11) => 1872
(45, 29, 60, 53) => 4176

Rules:

Standard code-golf rules and loophole restrictions apply.
Standard input/output rules apply.
Input numbers can be in any order - please specify in your answer which order you're using.
Input numbers can be in any suitable format: space-separated, an array, separate function or command-line arguments, etc. - your choice.
Similarly, if output to STDOUT, surrounding whitespace, trailing newline, etc. are all optional.
Input parsing and output formatting are not the interesting features of this challenge.
In the interests of sane complexity and integer overflows, the challenge number \$n\$ will have restrictions such that \$1 < n < 100000\$ -- i.e., you don't need to worry about possible answers outside this range.

Related

Count the divisors of a number
Give the smallest number that has N divisors
Divisor sum from prime-power factorization

Jelly, 17 16 bytes

×€ȷ5R¤ÆDL€€Z=Ḅi3

This is a brute force solution that tries all possible values up to 100,000. Try it online!

Non-competing version

The latest version of Jelly has a bug fix that allows to golf down the above code to 15 bytes.

ȷ5R×€³ÆDL€€=Ḅi3

Try it online!

How it works

×€ȷ5R¤ÆDL€€Z=Ḅi3  Main link. Left input: x,z. Right input: w,y

     ¤            Combine the two atoms to the left into a niladic chain.
  ȷ5              Yield 100,000 (1e5).
    R             Apply range. Yields [1, ..., 100,000].
x€                Multiply each r in the range by x and z.
                  This yields [[x, ..., 100,000x], [z, ..., 100,000z]].
      ÆD          Compute the divisors of each resulting integer.
        L€€       Apply length to each list of divisors.
                  This counts the divisors of each integer in the 2D array.
           Z      Zip; group the divisors of kx and kz in pairs.
            =     Compare each [divisors(kx), divisors(kz)] with [w, y].
                  This yields a pair of Booleans.
             Ḅ    Convert each Boolean pair from binary to integer.
              i3  Find the first index of 3. Yields 0 for not found.


Chopping Unicode Bytes Introduction
Each Unicode codepoint can be represented as a sequence of up to 4 bytes. Because of this, it is possible to interpret some 2, 3, or 4-byte characters as multiple 1-byte characters. (See here for a UTF-8 to bytes converter).
Challenge
Given a UTF-8 character, output it split into a sequence of 1-byte characters. If the character is 1-byte already, return it unchanged.

Your program must take one, and exactly one, UTF-8 character as input. You may use any input method you wish, as long as it has been decided on meta that is is a valid method. You cannot take input as a bytearray or series of bytes; then the challenge would just be converting hex to ASCII.
Your program must output one or more ASCII 1-byte characters. Again, any output method is allowed as long as it has been marked valid on meta. Edit: As per the conversation in the comments, output should be in Code Page 850.

Note: see this post for valid I/O methods.
Example I/O

܀ (0x700)
▄Ç (0xdc 0x80)
a (0x61)
a (0x61)
聂 (0x8042)
Þüé (0xe8 0x81 0x82)

Rules
This is code-golf, so shortest answer in bytes wins!

C# (Visual C# Interactive Compiler), 73 85 bytes

a=>Encoding.UTF8.GetBytes(a).Select(b=>Encoding.GetEncoding(850).GetString(new[]{b}))

Try it online!

+12 bytes to use the updated code page


Swap indices and values The task

Write a program or function whose input is a list/array X of integers, and whose output is a list of sets of integers Y, such that for each element e in each set Y[i], X[e] = i, and such that the total number of elements in the sets in Y equals the number of elements in X.

(This is basically the same operation as reversing a hashtable/dictionary, except applied to arrays instead.)

Examples

These examples assume 1-based indexing, but you can use 0-based indexing instead if you prefer.

X             Y
[4]           [{},{},{},{1}]
[1,2,3]       [{1},{2},{3}]
[2,2,2]       [{},{1,2,3}]
[5,5,6,6]     [{},{},{},{},{1,2},{3,4}]
[6,6,5,5]     [{},{},{},{},{3,4},{1,2}]

Clarifications

You may represent a set as a list, if you wish. If you do so, the order of its elements does not matter, but you may not repeat elements.
You can use any reasonable unambiguous I/O format; for example, you could separate elements of a set with spaces, and the sets themselves with newlines.
Y should be finitely long, and at least long enough to have all elements of X as array indexes. It may, however, be longer than the maximal element of X (the extra elements would be empty sets).
The elements of X will all be valid array indices, i.e. non-negative integers if you use 0-based indexing, or positive integers if you use 1-based indexing.

Victory condition

As a code-golf challenge, shorter is better.

MATL, 8 bytes

tn:IXQ&D

Input is a column vector, with ; as separator (for example [2;2;2]). Output is the string representation of a cell array of row vectors (for example {[]; [1 2 3]}). A row vector of a single element is the same as a number (so {1; 2; 3} would be output instead of {[1]; [2]; [3]}).

Try it online! Or verify all test cases.

Explanation

t     % Implicit input, say x. Duplicate
n     % Number of elements, say N
:     % Range: [1 2 ... N]
IXQ   % accumarray(x, [1 2 ... N], [], @(x){sort(x).'})
&D    % String representation

Most of the work is done by Matlab's higher-order function accumarray, which groups elements in the second input according to matching values in the first, and applies a specified function to each group. The function in this case is @(x){sort(x).'}, which outputs the sorted elements in each group and causes the results for all groups to be packed in a cell array.


Enhanced Builder Pattern, verified at compile time Question: can you design a Builder Pattern API which verifies at compile time that every field is set exactly once?

To be eligible, the size of the compiler output should not be exponential in the number of fields. The best solution will be the shortest implementation for a class of 22 fields.

Example of a possible surface API in java

Given an class for immutable data structure such as this one:

public class Human {
  private final String name;
  private final Int age;
  private final Double money;

  public Human(String name, Int age, Double money) {
    this.name = name;
    this.age = age;
    this.money = money;
  }

  public String getName() { return name; }
  public Int getAge() { return age; }
  public Double getMoney() { return money; }
}

The goal is to design an API to construct instances this Humain class with the following requirements, checked at compile time (the code in example is just a possible design, you can come up with anything that is equivalent in term of functionally):

Possible to set parameters in any order:

Human h = HumanBuilder().withName("n").withMoney(0.15).withAge(1).build();
Human g = HumanBuilder().withName("n").withAge(1).withMoney(0.15).build();

Possible to set parameters in different places of the code:

// Given appropriate takesCareOfTheMan & takesCareOfTheMoney methods
Human h = takesCareOfTheMan(takesCareOfTheMoney(HumanBuilder())).build();
Human g = takesCareOfTheMoney(takesCareOfTheMan(HumanBuilder())).build();

Impossible to set the same parameter twice:

// This should not compile:
// Human h = HumanBuilder().withName("n").withAge(1).withAge(2).withMoney(0.15).build();

Impossible to omit a parameter:

// This should not compile:
// Human h = HumanBuilder().withName("n").withMoney(0.15).build();

How about something like this, in Haskell:

{-# LANGUAGE GADTs, DataKinds, KindSignatures, StandaloneDeriving #-}
module Builder ( Human', Human, mkHuman, unHuman
               , withName, withAge, withMoney
               ) where

data Optional (b :: Bool) (a :: *) where
    Missing :: Optional False a
    Present :: a -> Optional True a
deriving instance (Show a) => Show (Optional b a)

data Human' b1 b2 b3 where
    MkHuman :: Optional b1 String -> Optional b2 Int -> Optional b3 Double -> Human' b1 b2 b3
deriving instance Show (Human' b1 b2 b3)

type Human = Human' True True True

mkHuman :: Human' False False False
mkHuman = MkHuman Missing Missing Missing

unHuman :: Human -> (String, Int, Double)
unHuman (MkHuman (Present name) (Present age) (Present money)) = (name, age, money)

withName :: String -> Human' False b2 b3 -> Human' True b2 b3
withName name (MkHuman _ age money) = MkHuman (Present name) age money

withAge :: Int -> Human' b1 False b3 -> Human' b1 True b3
withAge age (MkHuman name _ money) = MkHuman name (Present age) money

withMoney :: Double -> Human' b1 b2 False -> Human' b1 b2 True
withMoney money (MkHuman name age _) = MkHuman name age (Present money)

Example usage:

h1, h2 :: Human
h1 = withName "n" . withMoney 0.15 . withAge 1 $ mkHuman
h2 = withName "n" . withAge 1 . withMoney 0.15 $ mkHuman

takesCareOfTheName :: Human' False b2 b3 -> Human' True b2 b3
takesCareOfTheName = withName "John"

-- This doesn't typecheck
h3 :: Human
h3 = withName "newName" h1

-- Neither does this
h4 :: Human
h4 = withName "n" . withAge 1 $ mkHuman


Write a Blade Templating Engine Blade is a PHP templating engine. For this challenge, you only need to implement a modified version one feature -- text replacement.

Challenge Description

Given an input file and a map of keys to their replacements, write an interpreter that reads through the file to find double open braces ({{) followed by a key, followed by double closing braces (}}). Whitespace inside the braces should be ignored, unless it is inside of the key.

Requirements

If a key is not found in the map, your program should exit without outputting anything

Keys must be nestable. See the examples for a valid nesting example.

Keys may contain any character, but cannot start or end with a space. Whitespace should be trimmed from the start and end of the key.

Example input/output

Input blade file:

Hello, {{user_{{username }}}}! It is { NICE } to meet you!
My name is {{     my n@m3}}!

Input map:

{
'user_Joe': 'Joseph, user #1234',
'username': 'Joe',
'my n@m3': 'Henry'
}

Expected output:

Hello, Joseph, user#1234! It is { NICE } to meet you!
My name is Henry!

Marking:

Feel free to hard code input/output and exclude it from your byte count. However, if you implement the following features, take the corresponding value away from your byte count.

Read filename of blade template from stdin or arguments: 15 bytes

Read variable mapping as JSON from stdin or arguments: 20 bytes

Read variable mapping in any other format from stdin or arguments: 12 bytes

Bonus

Allow calculations (+, -, *, /, %, etc) in your blade script. Example input file:

{{a + b}}

Input map:

{ 'a': 1, 'b': 4 }

Expected output:

5

Perl: 105 - 15 - 20 = 70

perl -MJSON -pE'sub f{$_[0]=~s#{{\s*((.*?(?R)?.*?)+)\s*}}#$h->{f($1)}#reg};BEGIN{$h=from_json shift};$_=f$_' 'JSON' <input

Usage: the JSON is given as a command line argument. The template source is passed in STDIN. Example:

$ perl ... '{"user_Joe":"Joseph, user #1234","username":"Joe","my n@m3":"Henry"}'
>Hello, {{user_{{username }}}}! It is { NICE } to meet you!
>My name is {{     my n@m3}}!

(where lines beginning with > are pasted/typed/piped in)

Restrictions:

can't do arithmetic.
keys cannot span multiple lines.
requires the JSON Perl module to be installed (non-standard).
requires a new-ish perl (tested on Perl5 v20, but should work on at least v16 or v14).

I am not sure about the scoring rules, so I excluded perl·, the quotes for the code, and included an extra space and two quotes needed to pass the JSON on the command line.

Explanation:

Perl regexes can be recursive, but substitutions can't. To overcome this, we first define a regex that matches keys that might contain keys again: {{\s* ((.*? (?R)? .*?)+) \s*}}. Here, (?R) recurses into the whole pattern. The key does not have to contain a template tag, so the recursion is optional. In that case, the pattern is a non-greedy “match anything”: .*?.*?. This will terminate given a double closing braces. Usually braces are metacharacters in regexes, e.g. a{10,20} (match 10 to 20 "a"s). Fortunately, the regex compiler recognizes that these braces are not used as quantifiers.

Once we have matched the (possibly recursive) tag contents, we pass it to the function f which again applies the substitution to this content. The result is then used as a key in a hash reference $h, which replaces the tag contents. This is done non-destructively /r and globally /g.

The $h hash reference is defined in the BEGIN phase to the json-decoded value of the first command line argument. Since the sub f definition and the BEGIN block are done before the main execution, the actual script is perl -pE'$_=f$_', which applies our substitution function f to each line.

Voilà, a template engine is born :)


Find the sum of all numbers below n that are a multiple of some set of numbers Almost equivalent to Project Euler's first question:

  If we list all the natural numbers below 10 that are multiples of 3 or
  5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below 1000.

Challenge:

Given a positive integer N and a set of at least one positive integer A, output the sum of all positive integers less than N that are multiples of at least one member of A.

For example, for the Project Euler case, the input would be:

1000
3
5

Test cases:

Input : 50, [2]
Output: 600

Input : 10, [3, 5]
Output: 23

Input : 28, [4, 2]
Output: 182

Input : 19, [7, 5]
Output: 51

Input : 50, [2, 3, 5]
Output: 857

Jelly, 6 bytes

ḍþṖḅTS

Try it online!

How it works

ḍþṖḅTS  Main link. Left argument: D (array). Right argument: n (integer)

ḍþ       Divisible table; test each k in [1, ..., n] for divisibility by all
        integers d in D.
  Ṗ     Pop; discard the last Boolean array, which corresponds to n.
   ḅ    Unbase; convert the Boolean arrays of base n to integer. This yields a
        non-zero value (truthy) and and only if the corresponding integer k is
        divisible by at least one d in D.
    T   Truth; yield the array of all indices of truthy elements.
     S  Compute their sum.


How do I ask a teller for money at the bank? I need to go to the bank and withdraw some money.  I need to withdraw $30, $22 to pay my roommate for the internet and $8 for laundry.  Since neither of these can make change, I need my $30 to be split into two partitions of the two sizes.  That means when the teller asks me how I want my $30 I am going to have to make a request.  I could tell them I want it in a twenty, a fiver, and five ones.  But I want to make my request as simple as possible as to avoid having to repeat myself.  To make my request simpler I could ask that my cash contain a twenty and at least 2 ones because the 8 is implied by the total, but better yet I could simply request that one of the bills I receive be a one dollar bill (If you are not convinced of this just try to make 29 dollars without making 8).

So that's all fine and dandy but I need to do this calculation every time I go to the bank so I thought I would write a program to do this (have you write a program to do this for me).

Your program or function should take a list of integers representing all the payments I need to make and a set of integers representing the denominations of bills available at the bank, and you must output the smallest list of denominations such that every way to make the total that includes that list of denominations can be cleanly divided into the list of payments.

Extra rules

You may assume that the denomination list will always contain a 1 or you may add it to each list yourself.
Some inputs will have multiple minimal solutions. In these cases you may output either one.

This is code-golf so answers will be scored in bytes with less bytes being better.

Test Cases

Payments, denominations    -> requests
{22,8}    {1,2,5,10,20,50} -> {1} or {2}
{2,1,2}   {1,5}            -> {1}
{20,10}   {1,2,5,10,20,50} -> {}
{1,1,1,1} {1,2}            -> {1,1,1}
{20,6}    {1,4,5}          -> {1}
{2,6}     {1,2,7}          -> {2}
{22, 11}  {1, 3, 30, 50}   -> {1, 3}
{44, 22}  {1, 3, 30, 50}   -> {1, 3, 3, 30}

JavaScript (ES6), 485 476 bytes

Alright ... this is a monster. :-(
But it's a rather fast monster that solves all test cases almost instantly.

I may attempt some more advanced golfing later, but I've already spent far too much time on it.

f=(b,a,L=[...a])=>L.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).sort((a,b)=>a[b.length]||-1).find(L=>(Y=G(U(b)-U(L),L.sort((a,b)=>a-b)),Y[0]&&!Y.some(a=>P(b.map(a=>G(a,[]))).every(b=>b+''!=a))),U=a=>~~eval(a.join`+`),P=(e,C=[],R=[])=>e[0].map(v=>R=(c=v.map((x,i)=>x+(C[i]|0)),e[1])?[...P(e.slice(1),c),...R]:[c,...R])&&R,G=(n,l)=>(S=[],g=(n,l)=>n?a.map(x=>x<l[0]|x>n||g(n-x,[x,...l])):S=[l.map(v=>s[a.indexOf(v)]++,s=[...a].fill(0))&&s,...S])(n,l)&&S)||f(b,a,[...a,...L])

Test cases

f=(b,a,L=[...a])=>L.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).sort((a,b)=>a[b.length]||-1).find(L=>(Y=G(U(b)-U(L),L.sort((a,b)=>a-b)),Y[0]&&!Y.some(a=>P(b.map(a=>G(a,[]))).every(b=>b+''!=a))),U=a=>~~eval(a.join`+`),P=(e,C=[],R=[])=>e[0].map(v=>R=(c=v.map((x,i)=>x+(C[i]|0)),e[1])?[...P(e.slice(1),c),...R]:[c,...R])&&R,G=(n,l)=>(S=[],g=(n,l)=>n?a.map(x=>x<l[0]|x>n||g(n-x,[x,...l])):S=[l.map(v=>s[a.indexOf(v)]++,s=[...a].fill(0))&&s,...S])(n,l)&&S)||f(b,a,[...a,...L])

console.log(JSON.stringify(f([22,8], [1,2,5,10,20,50])))
console.log(JSON.stringify(f([2,1,2], [1,5])))
console.log(JSON.stringify(f([20,10], [1,2,5,10,20,50])))
console.log(JSON.stringify(f([1,1,1,1], [1,2])))
console.log(JSON.stringify(f([20,6], [1,4,5])))
console.log(JSON.stringify(f([2,6], [1,2,7])))
console.log(JSON.stringify(f([22,11], [1,3,30,50])))
console.log(JSON.stringify(f([44,22], [1,3,30,50])))

How?

NB: This is not matching the current version anymore, but is much easier to read that way.

// b = list of payments, a = list of bills,
// L = list from which the requested bills are chosen
f = (b, a, L = [...a]) => (
  // U = helper function that computes the sum of an array
  U = a => ~~eval(a.join`+`),

  // P = function that computes the summed Cartesian products of arrays of integers
  // e.g. P([[[1,2],[3,4]], [[10,20],[30,40]]]) --> [[33,44], [13,24], [31,42], [11,22]]
  P = (e, C = [], R = []) => e[0].map(v => R =
    (c = v.map((x, i) => x + (C[i] | 0)), e[1]) ? [...P(e.slice(1), c), ...R] : [c, ...R]
  ) && R,

  // G = function that takes a target amount and a list of requested bills and returns
  // all combinations that contain the requested bills and add up to this amount;
  // each combination is translated into a list of number of bills such as [2,0,0,1,0]
  G = (n, l) => (
    S = [],
    g = (n, l) => n ?
      a.map(x => x < l[0] | x > n || g(n - x, [x, ...l])) :
      S = [l.map(v => s[a.indexOf(v)]++, s = [...a].fill(0)) && s, ...S]
  )(n, l) && S,

  // compute X = list of possible bill combinations to process all payments
  X = P(b.map(a => G(a, []))),

  // compute the powerset of L and sort it from shortest to longest list
  L.reduce((a, x) => [...a, ...a.map(y => [x, ...y])], [[]])
  .sort((a, b) => a[b.length] || -1)

  .find(L => (
    // compute Y = list of possible combinations to reach the total amount,
    // using the requested bills
    Y = G(U(b) - U(L), L.sort((a, b) => a - b)),

    // exit if Y is not empty and all combinations in Y allow to generate all payments
    Y[0] && !Y.some(a => X.every(b => b + '' != a)))
  )

  // if no solution was found, enlarge the set of requested bills and try again
  || f(b, a, [...a, ...L])
)


Why don't you grow up? Why don't you grow up?

In the past week a meme involving the young actor Aaron Bailey became trending in most Brazilian social networks. Entitled "why don't you grow up" it consists in repeating a sentence replacing its vowels with is (it's a bit more complicated than that, I'll explain below). As I want to be a cool guy I decided to write a program that mimimifies a given string.

Challenge

The challenge consists of mimimifying a string, following the rules:

ão and õe should be replaced with im.
ca, ka, que, ke, qui, ki, co ,ko, cu, and ku should be replaced with ki.
ça, ce, çe, ci, çi, ço, and çu should be replaced with ci.
ga, gue, gui, go, and gu should be replaced with gui.
ja, ge, je, gi, ji, jo, and ju should be replaced with ji
You can assume that qua, quo, quu, gua, guo, and guu, will never appear, only a and o can have tildes and if they do they'll be followed by o and e, repsectively (ão, õe).
The only time us are allowed in output strings is gui, besides that case all other vowels present should be is.
In all other circumstances all vowels must be replaced with is.
Other than tilde all other accents may be ignored.
Two or more is in a row are not allowed, you should replace them with only one (Piauiense -> Pinsi)

Examples

Input

Por que você só fala assim?

Output

pir ki vici si fili issim?

Input

Que horas são?

Output

ki hiris sim?

Input

Óculos sem lente pode ser armação

Output

ikilis sim linti pidi sir irmicim

Input

Ganha o código com menos bytes

Output

guinhi i kidigui kim minis bytis

Rules

The vowels are a, e, i, o, and u.
You can see the full list of possible accents here.
code-golf: the shortest code in bytes wins. Check meta if counting bytes is awkward in your language.
Standard loopholes are forbidden
Your output must be consistent in case: all upper/all lower.
You may assume the input to be in whichever encoding you want but if you do you must specify it.

Happy golfing!/Hippy guilfing!

Retina, 150 bytes
[ÀÁÂàáâ]
a
[ÉÊéê]
e
Í|í
i
[ÓÔóô]
o
[ÚÜúü]
u
T`L`l
ão|õe
im
[ck][aou]|qu[ei]|ke
ki
ç[aeiou]|ce
ci
g[aou]|gue
gui
j[aeou]|g[ei]
ji
(gu)i|[aeou]
$1i
ii
i

Try it online!
This is my first Retina program, so there's probably a lot of improvements to make. Suggestions are welcome.
Thanks to Martin for correcting some mistakes and for some golfing suggestions.
Explanation
I'm going to break up the explanation into 3 sections, to make it easier on me.
Section 1: Preprocessing
[ÀÁÂàáâ]
a
[ÉÊéê]
e
Í|í
i
[ÓÔóô]
o
[ÚÜúü]
u
T`L`l

The first 5 rules replace any accented vowel with the corresponding unaccented version. It's shorter to list out the matches in character classes (or, in the third case, as two options) than to use the culture-invariance and case-insentivity options each time. The last rule converts all ASCII letters to lowercase.
Section 2: Mimimification
ão|õe
im
[ck][aou]|qu[ei]|ke
ki
ç[aeiou]|ce
ci
g[aou]|gue
gui
j[aeou]|g[ei]
ji

These rules simply apply the substitutions specified.
Section 3: Cleanup
(gu)i|[aeou]
$1i
i+
i

The first rule matches any vowel except for the u in gui, and replaces them with is. The second rule removes repeated is.


Map of Islands (and a river) Introduction

For many centuries, there has been a certain river that has never been mapped. The Guild of Cartographers want to produce a map of the river, however, they have never managed to succeed -- for some reason, all the cartographers they have sent to map the river have been eaten by wild animals in the area. A different approach is required.

Input Description

The area is a rectangular grid of cells of length m and width n. The cell in the bottom left would be 0,0, and the cell in the top right would be m-1,n-1. m and n are provided in the input as a tuple m,n.

By using long distance geographical sounding techniques the location of islands around the river have been identified. The size of the islands (i.e. how many cells the island occupies) have also been identified but the shape has not. We supply this information in a tuple s,x,y where s is the size of the island, and x and y are the x and y positions of one particular cell of that island. Each tuple in the input is space separated, so here is an example input:

7,7 2,0,0 2,3,1 2,6,1 2,4,3 2,2,4 8,0,6 1,2,6 3,4,6

To illustrate more clearly, here are is the input on a graph:

 y 6|8 1 3
   5|
   4|  2
   3|    2
   2|
   1|   2  2
   0|2
     =======
     0123456
     x

Output Description

Output a map using ASCII characters to represent parts of the area. Each cell will either be # (land) or . (water). The map should follow these rules:

Definition. An island is a orthogonally contiguous group of land cells that is bounded entirely by river cells and/or the border of the area.
Definition. A river is an orthogonally contiguous group of water cells that is bounded entirely by land cells and/or the border of the area, and does not contain "lakes" (2x2 areas of water cells).
Rule. The map shall contain exactly one river.
Rule. Each numbered cell in the input shall be part of an island containing exactly s cells.
Rule. Every island in the map shall contain exactly one of the numbered cells in the input.
Rule. There exists a single unique map for every input.

Here is the output of the example input:

#.#.##.
#....#.
#.##...
##..##.
###....
...##.#
##....#

Here is another input and output.

Input:

5,5 3,0,1 1,4,1 2,0,4 2,2,4 2,4,4

Output:

#.#.#
#.#.#
.....
###.#
.....

C + PicoSAT, 2345 995 952 bytes

#include<picosat.h>
#define f(i,a)for(i=a;i;i--)
#define g(a)picosat_add(E,a)
#define b calloc(z+1,sizeof z)
#define e(a,q)if(a)A[q]^A[p]?l[q]++||(j[++k]=q):s[q]||(i[q]=p,u(q));
z,F,v,k,n,h,p,q,r,C,*x,*A,*i,*l,*s,*j,*m;u(p){s[m[++n]=p]=1;e(p%F-1,p-1)e(p%F,p+1)e(p>F,p-F)e(p<=F*v-F,p+F)}t(){f(q,k)l[j[q]]=0;f(q,n)s[m[q]]=0;k=n=0;i[p]=-1;u(p);}main(){void*E=picosat_init();if(scanf("%d,%d",&F,&v)-2)abort();z=F*v;for(x=b;scanf("%d,%d,%d",&r,&p,&q)==3;g(p),g(0))x[p=F-p+q*F]=r;f(p,F*v-F)if(p%F)g(p),g(p+1),g(p+F),g(p+F+1),g(0);for(A=b,i=b,l=b,s=b,j=b,m=b;!C;){picosat_sat(E,C=h=-1);f(p,F*v)A[p]=picosat_deref(E,p)>0,i[p]=0;f(p,F*v)if(x[p])if(i[q=p]){for(g(-q);i[q]+1;)q=i[q],g(-q);g(C=0);}else if(t(),r=n-x[p]){f(q,r<0?k:n)g(r<0?j[q]:-m[q]);g(C=0);}f(p,F*v)if(!i[p])if(t(),A[p]){g(-++z);f(q,k)g(j[q]);g(C=0);f(q,n)g(-m[q]),g(z),g(0);}else{C&=h++;f(q,k)g(-j[q]);g(++z);g(++z);g(0);f(q,F*v)g(s[q]-z),g(q),g(0);}}f(p,F*v)putchar(A[p]?35:46),p%F-1||puts("");}

Try it online!

(Warning: this TIO link is a 30 kilobyte URL that contains a minified copy of PicoSAT 965, so you might not be able to load it in some browsers, but it loads in at least Firefox and Chrome.)

How it works

We initialize the SAT solver with a variable for each cell (land or water), and only the following constraints:

Every numbered cell is land.
Every 2×2 rectangle has at least one land.

The rest of the constraints are difficult to encode directly into SAT, so instead we run the solver to get a model, run a sequence of depth-first searches to find the connected regions of this model, and add additional constraints as follows:

For every numbered cell in a land region that’s too big, add a constraint that there should be at least one water cell among the current land cells in that region.
For every numbered cell in a land region that’s too small, add a constraint that there should be at least one land cell among the current water cells bordering that region.
For every numbered cell in the same land region as another numbered cell, add a constraint that there should be at least one water cell along the path of current land cells between them (found by walking the parent pointers left over from the depth-first search).
For every land region including no numbered cells, add constraints that either

all of those current land cells should be water, or
at least one of the current water cells bordering that region should be land.

For every water region, add constraints that either

all of those current water cells should be land, or
every cell other than those current water cells should be land, or
at least one of the current land cells bordering that region should be water.

Taking advantage of the incremental interface to the PicoSAT library, we can immediately rerun the solver including the added constraints, preserving all the previous inferences made by the solver.  PicoSAT gives us a new model, and we continue iterating the above steps until the solution is valid.

This is remarkably effective; it solves 15×15 and 20×20 instances in a tiny fraction of a second.

(Thanks to Lopsy for suggesting this idea of interactively constraining connected regions in an incremental SAT solver, a while back.)

Some larger test cases from puzzle-nurikabe.com

A random page of 15×15 hard puzzles (5057541, 5122197, 5383030, 6275294, 6646970, 6944232):

15,15 1,5,1 3,9,1 5,4,2 1,6,2 2,11,2 2,2,3 3,9,3 2,4,4 1,10,4 5,12,4 3,1,5 1,3,5 3,8,5 1,13,5 5,5,6 1,12,6 1,2,8 2,9,8 1,1,9 2,6,9 6,11,9 3,13,9 5,2,10 2,4,10 4,10,10 1,5,11 2,12,11 2,3,12 2,8,12 5,10,12 1,5,13 1,9,13 1,6,14 1,8,14
15,15 4,2,0 2,5,0 1,3,1 2,14,2 1,3,3 2,11,3 1,13,3 1,5,4 11,7,4 1,9,4 1,4,5 1,8,5 2,10,5 12,14,5 3,5,6 1,4,7 2,10,7 3,9,8 4,0,9 1,4,9 1,6,9 3,10,9 1,5,10 1,7,10 8,9,10 1,1,11 10,3,11 2,11,11 6,0,12 1,11,13 2,9,14 1,12,14
15,15 2,2,0 8,10,0 2,3,1 2,14,2 2,3,3 3,5,3 3,9,3 2,11,3 5,13,3 6,0,4 3,7,4 3,3,5 2,11,5 2,6,6 1,8,6 1,4,7 2,10,7 1,6,8 2,8,8 5,3,9 2,11,9 2,7,10 7,14,10 2,1,11 4,3,11 2,5,11 1,9,11 2,11,11 2,0,12 4,6,13 1,11,13 3,4,14 1,12,14
15,15 2,0,0 2,4,0 3,6,1 2,10,1 1,13,1 2,5,2 2,12,2 3,0,3 2,2,3 4,7,3 2,9,3 1,14,3 1,4,4 1,8,4 2,12,5 4,2,6 3,4,6 1,14,6 7,7,7 1,10,8 2,12,8 3,2,9 2,14,9 2,0,10 2,6,10 1,10,10 2,5,11 4,7,11 2,12,11 1,14,11 3,2,12 3,9,12 1,1,13 2,4,13 3,8,13 2,10,14 5,14,14
15,15 1,3,0 1,14,0 3,7,1 3,10,1 2,13,1 3,1,2 4,5,2 2,12,3 3,3,4 1,8,4 1,1,5 3,5,5 1,9,5 5,13,5 3,3,6 1,8,6 2,2,7 2,12,7 1,6,8 1,8,8 2,11,8 2,1,9 4,5,9 2,9,9 2,13,9 2,6,10 4,11,10 1,2,11 3,9,12 2,13,12 3,1,13 2,4,13 3,7,13 1,0,14
15,15 2,8,0 2,4,1 2,7,1 1,10,1 6,4,3 1,1,4 12,5,4 3,11,4 5,13,4 3,10,5 3,0,6 1,6,6 2,8,6 4,13,7 2,3,8 1,6,8 3,8,8 2,14,8 2,4,9 5,1,10 4,3,10 1,9,10 6,13,10 3,8,11 1,10,11 3,4,13 2,7,13 3,10,13 1,6,14 1,14,14

A random page of 20×20 normal puzzles (536628, 3757659):

20,20 1,0,0 3,2,0 2,6,0 1,13,0 3,9,1 3,15,1 2,7,2 3,13,2 3,0,3 2,3,3 3,18,3 3,5,4 2,9,4 2,11,4 2,16,4 1,0,5 2,7,5 1,10,5 1,19,5 3,2,6 1,11,6 2,17,6 2,0,7 3,4,7 5,6,7 2,9,7 4,13,7 3,15,7 1,3,8 1,10,8 1,14,9 2,18,9 3,1,10 2,4,10 1,8,10 1,10,10 3,12,10 3,16,10 1,9,11 1,17,11 2,19,11 2,0,12 2,2,12 1,4,12 4,6,12 2,13,12 2,15,12 1,14,13 2,17,13 1,3,14 2,5,14 4,7,14 2,15,14 3,0,15 1,2,15 2,13,15 3,18,15 3,7,16 7,10,16 1,17,16 2,0,17 2,3,17 2,5,17 3,11,17 3,15,17 1,0,19 1,2,19 1,4,19 2,6,19 5,8,19 1,11,19 1,13,19 3,15,19 2,18,19
20,20 1,0,0 1,4,0 5,8,0 1,17,0 1,19,0 2,17,2 3,6,3 2,10,3 2,12,3 4,14,3 6,0,4 3,4,4 4,7,4 1,11,4 1,18,4 1,6,5 3,12,5 4,15,5 4,4,6 2,16,6 2,19,6 6,0,7 3,10,7 2,12,8 2,17,8 3,3,9 2,5,9 4,8,9 2,10,9 3,0,10 1,2,10 5,14,10 2,16,10 2,19,10 7,7,11 3,12,12 2,17,12 2,2,13 4,4,13 3,6,13 4,14,13 3,0,14 1,3,14 1,5,14 3,16,14 1,2,15 1,9,15 2,11,15 5,13,15 3,19,15 1,4,16 3,6,16 1,3,17 1,12,17 1,14,17 1,16,17 6,0,19 2,2,19 3,5,19 2,7,19 5,9,19 1,11,19 2,13,19 1,15,19 4,17,19


Find minimal set of rows to retain all unique values in each column Given a matrix, the goal is to ensure all the values in each column occur at least once, while at the same time doing so requiring the least possible amount of rows. Fastest solution wins.

Note: a value in one column (e.g. 1) is considered different from the same value in another column.

Expected output: an array/list/series of row indices that retain all unique values across all columns.

Example data:

import numpy as np
import pandas as pd

np.random.seed(42)

num_rows = 10000
num_cols = 200
max_uniq_values = 10

data = pd.DataFrame({i: np.random.randint(0, max_uniq_values, num_rows)
                     for i in range(num_cols)})
# or python
# data = [np.random.randint(0, max_uniq_values, num_rows).tolist()
#         for i in range(num_cols)]

Minimal example (num_rows=5, num_cols=2, max_uniq_values=4)

Input:

    | 0  1
  --------
  0 | 1  1
  1 | 2  2
  2 | 3  4
  3 | 3  3
  4 | 4  4

Expected output:

[0, 1, 3, 4]

Additionally:

Benchmark will happen on a 2015 Macbook Pro with CPU Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz.
Restricted to use 1 core.
External libraries allowed
Blind test will be done on 10 random seeds (the same ones for each solution)

Python3 + PuLP library

This is equivalent to a set covering problem (where the elements are column/value pairs) which can be transformed into an integer linear programming problem.

from pulp import *

def opt(mat):
    num_rows = len(mat)
    covering_rows = {}
    for row_nr, vals in enumerate(mat):
        for pair in enumerate(vals):
            covering_rows.setdefault(pair, []).append(row_nr)
    prob = LpProblem("Minimal Covering Set of Rows", LpMinimize)
    vars = LpVariable.dicts("R", range(num_rows), 0, 1, LpInteger)
    prob += lpSum([vars[i] for i in range(num_rows)])
    for rowlist in covering_rows.values():
        prob += lpSum([vars[r] for r in rowlist]) >= 1
    prob.solve()
    assert prob.status==LpStatusOptimal, "Couldn't solve"
    return [r for r in range(num_rows) if value(vars[r])==1]

On debian, the relevant package is called python3-pulp.

The function handles matrices with 20 columns and 100 rows in about one minute on weak hardware. The best way to substantially improve the speed is probably to use a better solver, which the PuLP library allows by adding an argument to the solve method call.


Gluttonous Colluding Numbers Here's an easy one, with just enough complexity to make golfing non-trivial.
Input

A list of non-negative numbers representing people waiting in line for Thanksgiving dessert.  The first (leftmost) number is first in line, and the list can contain repeats (think of each number as a person's first name):

Note: Pie not part of actual input.

        (
         )
    __..---..__
,-='  /  |  \  `=-.
:--..___________..--;   6 4 3 1 2 3 0
\.,_____________,./

A non-empty subset of that list, representing a group of colluding friends who will "chat and cut" to skip ahead in line.  All colluders will move just behind the friend already closest to the front of the line, but otherwise retain their relative positions.  Everyone they skip past will also retain their relative position.

Output
The new list, after a successful (possibly multi-way) chat and cut.  For example, in the list above, for a friend group of 0 2 4, the output would be:
6 4 2 0 3 1 3

If the friend group was 4 3, the output would be:
6 4 3 3 1 2 0

Notes
This is code golf with standard site rules.

A single colluder x in the colluder list makes everyone in line with that number a colluder.
The list of people waiting may contain repeats.
The colluder list will not contain repeats.
The colluder list may not be sorted.
The colluder list will have between 2 and U items, where U is the number of unique elements in the queuer list.

Test Cases
The format is:

People in line.
List of colluders.
Output.

5 4 3 2 1 0
3 1
5 4 3 1 2 0

1 2 1 3 1 9
1 9
1 1 1 9 2 3

1 2 3 4 5
4 5
1 2 3 4 5

7 6 1 5 2 4 3
4 5 6
7 6 5 4 1 2 3

7 6 1 5 2 4 3
1 2 3
7 6 1 2 3 5 4

7 6 1 5 2 4 3
3 6
7 6 3 1 5 2 4

1 2 3 4
1 2 3 4
1 2 3 4

1 2 3 4 5 4
5 4
1 2 3 4 5 4

J, 12 bytes
-1 thanks to FrownyFrog!
[/:OR\@e.-e.

Try it online!
For 6 4 3 1 2 3 0 and 0 2 4:
[/:OR\@e.-e.
   OR        OR …
     \       each prefix of …
      @e.    the bitmask of friends, or:
   OR\@e.    after the first friend? (0 1 1 1 1 1 1)
          e. the bitmask of friends  (0 1 0 0 1 0 1)
         -   minus                   (0 0 1 1 0 1 0)
[/:          (stable) sort the people based on the list
                                     (6 4 3 1 2 3 0)


3... 2... 1... Crash off! Your task is to write a full program that will continue to count down from 10 every time it is run.

The first time you run the program, it should print 10.
The next time, it should output 9.
The next time, it should output 8, and so on.
Instead of printing 0, the program should crash. You do not have to handle the program running any more times after that.
Any facilities used for storage may be assumed to be empty before the first execution of the program.

Here's an example implementation in Python 3:

try:f=open("a","r+");v=int(f.read())
except:f=open("a","w");v=10
1/v
print(v)
f.seek(0)
f.write(str(v-1))

This is code-golf, so the shortest answer (measured in bytes) wins.

Perl on Linux, 17 bytes

I thought it might be interesting to create a program that doesn't maintain any state itself, and doesn't modify its own source code; in other words, it actually checks how often it's been run by asking the OS. The question says "Any facilities used for storage may be assumed to be empty before the first execution of the program.", and thus we'd want to start from a completely blank OS. As such, I'd better explain just how you go about doing that, as otherwise testing the program is difficult.

There are actually two ways to set up for running the program. Either way, the minimal OS for the purpose would be running nothing but a shell (to enable us to run Perl in turn), and the simplest possible shell at that (so that it doesn't do anything fancy that makes the OS non-blank). /bin/dash is a good choice here, as it was intended as a minimal shell for system recovery. Then, we need to start Linux in such a way that it's running nothing but dash. We can either do this by rebooting the computer with init=/bin/dash on the Linux command line so that it starts nothing besides dash, or (much more conveniently) creating a Linux container using unshare -Urfp /bin/dash in a terminal (unshare doesn't actually create a blank OS, but it does simulate one; notably, the inside of the container thinks it's root, dash thinks it's init, etc., just as would happen on an actual blank OS). Disclaimer: I haven't actually tested this on bare metal yet, only inside unshare, but it should work both ways in theory.

Finally, once we've got that set up, we simply have to look at the PID; as we're on a blank system, the init system (here, the shell) will have PID 1, so the executions of Perl will have PIDs from 2 up to 12 inclusive. So our program looks like this:

say 12-$$||die

Here's a sample run:

$ unshare -Urfp /bin/dash
# perl -E 'say 12-$$||die'
10
# perl -E 'say 12-$$||die'
9
# perl -E 'say 12-$$||die'
8
# perl -E 'say 12-$$||die'
7
# perl -E 'say 12-$$||die'
6
# perl -E 'say 12-$$||die'
5
# perl -E 'say 12-$$||die'
4
# perl -E 'say 12-$$||die'
3
# perl -E 'say 12-$$||die'
2
# perl -E 'say 12-$$||die'
1
# perl -E 'say 12-$$||die'
Died at -e line 1.
#


n-queens problem, displaying more than one solution available as some of you may know, n-queens problem is a set of algorithm puzzle that given a 'n x n' where n is the board size of a (let's say) chessboard, and the main goal is for the n queens (where n is the number of the queens) not be able to 'attack' one another in the board.

now I have a set of console code where user can input the board size (with an exception of less than 4x4), and the program will display one solution for the board size inputted. here's the code sample in C++:

#include <windows.h>
#include <iostream>
#include <string>

using namespace std;

class point
{
public:
int x, y;
point() { x = y = 0; }
void set( int a, int b ) { x = a; y = b; }
};

class nQueens
{
public:
void solve( int c )
{
    _count = c;
    int len = (c + 1) * (c + 1);
    _queens = new bool[len]; memset( _queens, 0, len );
    _cl = new bool[c]; memset( _cl, 0, c );
    _ln = new bool[c]; memset( _ln, 0, c );
    point pt; pt.set( rand() % c, rand() % c );
    putQueens( pt, c );
    displayBoard();
    delete [] _queens; delete [] _ln; delete [] _cl;
}

private:
void displayBoard()
{
    system( "cls" );
    const string t = "+---+", q = "| Q |", s = "|   |";
    COORD c = { 0, 0 };
    HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );
    for (int y = 0, cy = 0; y < _count; ++y)
    {
        int yy = y * _count;
        for ( int x = 0; x < _count; x++ )
        {
            SetConsoleCursorPosition( h, c ); cout << t;
            c.Y++; SetConsoleCursorPosition( h, c );
            if (_queens[x + yy]) cout << q; else cout << s;
            c.Y++; SetConsoleCursorPosition( h, c );
            cout << t; c.Y = cy; c.X += 4;
        }
        cy += 2; c.X = 0; c.Y = cy;
    }
}

bool checkD( int x, int y, int a, int b )
{
    if ( x < 0 || y < 0 || x >= _count || y >= _count ) return true;
    if ( _queens[x + y * _count] ) return false;
    if ( checkD( x + a, y + b, a, b ) ) return true;
    return false;
}

bool check( int x, int y )
{
    if ( _ln[y] || _cl[x] )        return false;
    if ( !checkD( x, y, -1, -1 ) ) return false;
    if ( !checkD( x, y,  1, -1 ) ) return false;
    if ( !checkD( x, y, -1,  1 ) ) return false;
    if ( !checkD( x, y,  1,  1 ) ) return false;
    return true;
}

bool putQueens( point pt, int cnt )
{
    int it = _count;
    while (it)
    {
        if ( !cnt ) return true;
        if ( check( pt.x, pt.y ) )
        {
            _queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = true;
            point tmp = pt;
            if ( ++tmp.x >= _count ) tmp.x = 0;
            if ( ++tmp.y >= _count ) tmp.y = 0;
            if ( putQueens( tmp, cnt - 1 ) ) return true;
            _queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = false;
        }
        if ( ++pt.x >= _count ) pt.x = 0;
        it--;
    }
    return false;
}

int          _count;
bool*        _queens, *_ln, *_cl;
};

int main( int argc, char* argv[] )
{
nQueens n; int nq;
while( true )
{
    system( "cls" );
    cout << "Enter board size bigger than 3 (0 - 3 to QUIT): "; cin >> nq;
    if ( nq < 4 ) return 0;
    n.solve( nq ); cout << endl << endl;
    system( "pause" );
}
return  0;
}

now, as the code only display one solution only, where 4x4 should have more than one solution available, your challenge is to make the code to be able to display more than one solution should it's possible, and displaying the 'graphic' solution (console is recommended). C++ is recommended, but other programming language is more than welcome. Good luck!


Randomly Misspell a Word Inspired by this CR question (please don't kill me for browsing CR)

Spec

The probabilities of misspelling a word are:

1/3 of the time don't change the output
1/3 of the time remove a random character
1/3 of the time duplicate a random character

The chance for removing/duplicating a given character in the input should be the same for all chars.

If two consecutive characters are the same (case-sensitive), the probability of one of them being modified should be the same as if they are one character. I.e. the outputs for AA (which are AA or A or AAA) should all have the same probability.

The input will only contain of letters for simplicity.

Examples

First line is input, following lines are all possible misspellings. Each line should have the same probability of being output, the input is excluded in the examples but it should still have a 1/3 probability of output.

foo

fo
oo
ffoo
fooo

PPCG

PPC
PPG
PCG
PPPCG
PPCCG
PPCGG

Pip, 38 27 bytes

a@:`(.)\1*`YRR#aa@y@0X:RR3a

This was fun--got to use Pip's regex and mutable string capabilities, which I hadn't pulled out in a while. Takes input via command-line argument.

Explanation:

a@:`(.)\1*`                  Split a into runs of identical chars using regex match
           YRR#a             Yank randrange(len(a)) into y (randomly choosing one such run)
                a@y@0        Take the first character of that run
                     X:RR3   Modify in place, string-multiplying by randrange(3):
                               If RR3 is 0, character is deleted
                               If RR3 is 1, no change
                               If RR3 is 2, character is duplicated
                          a  Output the modified a

Try it online!


When does (x == x+2)? The challenge: Define x in such a way that the expression (x == x+2) would evaluate to true.

I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.

I intend to accept a C solution, but other languages can get my vote.

Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming int is 32bit 2's complement) is OK.
Simple - should be small, use basic language features.
Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. Update: Avoiding the preprocessor is interesting.
Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.

The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

The C preprocessor. #define x 2|0 was suggested, but there are many other possibilities.
Floating point. Large numbers, infinity or NaN all work.
Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.

The rest don't work with C:
Operator overloading - A + that doesn't add or a == that always returns true.
Making x a function call (some languages allow it without the x() syntax). Then it can return something else each time.
A one-bit data type. Then x == x+2 (mod 2).
Changing 2 - some language let you assign 0 to it.

Fortran IV:

2=0

After this every constant 2 in the program is zero. Trust me, I have done this (ok, 25 years ago)


Random word-sentence-story generator This question got me nostalgic: Build a word generator!
In the '80s I wrote a simple word generator in under 42kB (code and working memory) that would take a collection of strings and use them to create new words and phrases.
Your task is to recreate this program in as few bytes as possible, with a few minor updates.
Your program will take the input and ensure that there are two spaces after each sentence. Each sentence should end with a full-stop (.). There must not be three consecutive spaces anywhere in the text. Line breaks should be replaced by a single space. There should only be two spaces after a sentence and nowhere else.
Record the number of times each character triplet appears. If you're using regex to break up the text /\X/ is a good way to match a Unicode glyph (could be multiple codepoints, not necessarily a single codepoint). For the purposes of counting, assume that there are two spaces at the start of the text and two spaces at the end.
Hopefully, you now have some good data to work with! Randomly select a triplet where the first two characters are both spaces. For example, if the only two matching triplets are [' ', ' ', 'I'] => 3 and [' ', ' ', 'A'] => 7 there should be a 30% chance of selecting I and a 70% chance of selecting A. Shift the characters along and randomly select one of the next triplets. If A was the first character selected the next triplets might be [' ', 'A', 'n'] => 2, [' ', 'A', 't'] => 2 and [' ', 'A', 's'] => 3. Randomly select one using the correct weightings and so on. Repeat until the last two characters are both spaces, then output the string generated if it's 100 characters or longer. If the output is less than 100 characters, repeat the process again, adding to the existing string until it is at least 100 characters long.
You should end up with output something like below, which looks almost like the input language. As my test input I used the first chapter of Charles Dickens' A Tale of Two Cities but you can use any text you feel like. Please provide a link to your input text (preferably not copyrighted) and a sample of the output.

In harithe dir, in hadede Fards fouses, by we aws, mand by nouse St. Merty exce, he th at ing ithe inceir farce, a Capir bod day, one defor ond rodmane of the ce witsethe after seas a pleark parison a prion to eves hund Parglairty the beere tielaires, and wrece to ente comses itic plaw andozene hich tat andiver, a he pent wer thneople, the werseved froads se sebron theire mands inge Woodmage larestown ther Ligh, sed and was the withaved broce pers. Brity-fired of bust a din humakings th, incre pas of the amonoblis the a kne Chrooteres, to offle ound lies yeargland this thing by on the goil ituarivesdozen, moolurd instive the whe only a king was thelfe one divery. Und the intren a king thiging ors, and he tow, afty out pas musears, thot he in aces, it it Fran, tho the blets be anglaters ouseticiodmand whimeng was by the primed tord a ce a dirience.

TL;DR
Build sentences from test input by analysing the frequency of the character triplets, and using those frequencies to randomly select each character in sequence.
You can pre-format your text to make sure it matches the input requirements. It doesn't have to contribute to your byte-count.
If your language can't cope with Unicode at all, limit the input to ASCII characters. Ideally, your program should be able to cope with combining marks (accents and the like) if they are encoded separately but it doesn't have to. It shouldn't affect the output much, although it's possible you might get weird output in rare cases. e.g. if é is encoded as two codepoints, e+combining acute accent, it SHOULD (but doesn't HAVE to) treat it as a single glyph.

Ruby, 88 bytes
Port from the Python answer by @Blue with a few modifications because it's still the shortest way to do things in Ruby as well...
->s{o=e='  ';(s[x=rand(s.size-2),2]==o[-2,2]?o+=s[x+2]:0)while o.size<100||o[-2,2]!=e;o}

Alternate version using selection and sampling, 99 bytes
->s{o=e='  ';o+=s[(0..s.size-2).select{|i|s[i,2]==o[-2,2]}.sample+2]while o.size<100||o[-2,2]!=e;o}


Spell out numbers in French There was a challenge to convert a number to its numeral in English, but that was too straightforward. Given a number 0–100, your task is to output the corresponding numeral in French. The French numeral system has a more complex logic behind it compared to the English one:

Number  Numeral
---------------
 0      zéro (note the accent)
 1      un
 2      deux
 3      trois
 4      quatre
 5      cinq
 6      six
 7      sept
 8      huit
 9      neuf
10      dix
11      onze
12      douze
13      treize
14      quatorze
15      quinze
16      seize
17      dix-sept (literally ten seven)
18      dix-huit
19      dix-neuf
20      vingt
21      vingt et un (no hyphens)
22      vingt-deux
...
30      trente
...
40      quarante
...
50      cinquante
...
60      soixante
...
70      soixante-dix (literally sixty ten)
71      soixante et onze
...
80      quatre-vingts (note the s; literally four twenties)
81      quatre-vingt-un (note the hyphens)
...
90      quatre-vingt-dix
91      quatre-vingt-onze
...
99      quatre-vingt-dix-neuf (4*20+10+9)
100     cent

For a complete list, follow http://quizlet.com/996950/ (http://www.webcitation.org/6RNppaJx0).
Further rules/explanations

There will always be a hyphen between words EXCEPT when the number ends in 1.
When the number ends in 1, the word et (meaning and) is added before the un or onze. (31 = trente et un)
However, 81 and 91 are formatted the same as the other numbers. (81 = quatre-vingt-un)
At 60, the system switches from base 10 to base 20.
There are some minor discrepancies across the web about this; refer to the list linked above for questions.
Loopholes that are forbidden by default are not allowed.
Using an external source such as a website, as well as any libraries, APIs, functions, or the like that convert numbers to numerals or translate to French are not allowed.
This is code-golf, so the answer with the fewest bytes wins.
If available, please link to an online compiler to allow for easy testing of your code.

Input

Input shall be taken from however your language takes input. (STDIN, command line, etc.)
Input will be a single string, consisting of a whole number between 0 and 100 inclusive (leading zeroes optional).
You can assume the input will always be well-formed.

Output

The result shall be output to the most convenient method for your language. (STDOUT, dialog box, etc.)
Case does not matter in the output.

Examples
Test your code against these:

Input  Output
-------------
0      zéro
18     dix-huit
51     cinquante et un
80     quatre-vingts
91     quatre-vingt-onze
99     quatre-vingt-dix-neuf

JavaScript (ES6) 318 321
Edit Bug fix (managing leading 0s) and golfed more
Credit for the camel case trick @Core1024
With input/output via popup
alert((n=prompt(),w='ZéroUnDeuxTroisQuatreCinqSixSeptHuitNeufDixOnzeDouzeTreizeQuatorzeQuinzeSeizeDix-septDix-huitDix-neufVingtTrenteQuaranteCinquanteSoixante'.match(/[A-Z][^A-Z]+/g),
u=n%10,s=u-1|n>80?d='-':' et ',n>99?'Cent':n<21?w[n|0]:n<70?w[18+n/10|0]+(u?s+w[u]:''):(n<80?w[24]:w[4]+d+w[20])+(n-80?s+w[n%20]:'s')))

As a testable function
F=n=>(
  w='ZéroUnDeuxTroisQuatreCinqSixSeptHuitNeufDixOnzeDouzeTreizeQuatorzeQuinzeSeizeDix-septDix-huitDix-neufVingtTrenteQuaranteCinquanteSoixante'
  .match(/[A-Z][^A-Z]+/g),
  u=n%10,s=u-1|n>80?d='-':' et ',
  n>99?'Cent':
  n<21?w[n|0]:
  n<70?w[18+n/10|0]+(u?s+w[u]:''):
  (n<80?w[24]:w[4]+d+w[20])+(n-80?s+w[n%20]:'s')
)

To Test In FireFox console or FireBug
for (i = 0; i < 100; console.log(r),i+= 10)
  for (j=0, r=''; j < 10; j++)
    r+=(i+j)+':'+F(i+j+'')+", "; // specific: input is a string
F('100')

Test Output

0:Zéro, 1:Un, 2:Deux, 3:Trois, 4:Quatre, 5:Cinq, 6:Six, 7:Sept, 8:Huit, 9:Neuf,
10:Dix, 11:Onze, 12:Douze, 13:Treize, 14:Quatorze, 15:Quinze, 16:Seize, 17:Dix-sept, 18:Dix-huit, 19:Dix-neuf,
20:Vingt, 21:Vingt et Un, 22:Vingt-Deux, 23:Vingt-Trois, 24:Vingt-Quatre, 25:Vingt-Cinq, 26:Vingt-Six, 27:Vingt-Sept, 28:Vingt-Huit, 29:Vingt-Neuf,
30:Trente, 31:Trente et Un, 32:Trente-Deux, 33:Trente-Trois, 34:Trente-Quatre, 35:Trente-Cinq, 36:Trente-Six, 37:Trente-Sept, 38:Trente-Huit, 39:Trente-Neuf,
40:Quarante, 41:Quarante et Un, 42:Quarante-Deux, 43:Quarante-Trois, 44:Quarante-Quatre, 45:Quarante-Cinq, 46:Quarante-Six, 47:Quarante-Sept, 48:Quarante-Huit, 49:Quarante-Neuf,
50:Cinquante, 51:Cinquante et Un, 52:Cinquante-Deux, 53:Cinquante-Trois, 54:Cinquante-Quatre, 55:Cinquante-Cinq, 56:Cinquante-Six, 57:Cinquante-Sept, 58:Cinquante-Huit, 59:Cinquante-Neuf,
60:Soixante, 61:Soixante et Un, 62:Soixante-Deux, 63:Soixante-Trois, 64:Soixante-Quatre, 65:Soixante-Cinq, 66:Soixante-Six, 67:Soixante-Sept, 68:Soixante-Huit, 69:Soixante-Neuf,
70:Soixante-Dix, 71:Soixante et Onze, 72:Soixante-Douze, 73:Soixante-Treize, 74:Soixante-Quatorze, 75:Soixante-Quinze, 76:Soixante-Seize, 77:Soixante-Dix-sept, 78:Soixante-Dix-huit, 79:Soixante-Dix-neuf,
80:Quatre-Vingts, 81:Quatre-Vingt-Un, 82:Quatre-Vingt-Deux, 83:Quatre-Vingt-Trois, 84:Quatre-Vingt-Quatre, 85:Quatre-Vingt-Cinq, 86:Quatre-Vingt-Six, 87:Quatre-Vingt-Sept, 88:Quatre-Vingt-Huit, 89:Quatre-Vingt-Neuf,
90:Quatre-Vingt-Dix, 91:Quatre-Vingt-Onze, 92:Quatre-Vingt-Douze, 93:Quatre-Vingt-Treize, 94:Quatre-Vingt-Quatorze, 95:Quatre-Vingt-Quinze, 96:Quatre-Vingt-Seize, 97:Quatre-Vingt-Dix-sept, 98:Quatre-Vingt-Dix-huit, 99:Quatre-Vingt-Dix-neuf,
"Cent"


Stream of Letters to Words Given a string containing only letters (case-insensitive), split it into words of uniformly random lengths, using the distribution below, with the exception of the last word, which can be of any valid length (1-10). Your output is these words, as a space-separated string ("test te tests"), an array of strings (["test","te","tests"]), or any other similar output format.
Word Length Distribution
Word Length - Fractional Chance / 72 - Rounded Percentage
1 - 2 / 72 - 2.78%
2 - 14 / 72 - 19.44%
3 - 16 / 72 - 22.22%
4 - 12 / 72 - 16.67%
5 - 8 / 72 - 11.11%
6 - 6 / 72 - 8.33%
7 - 5 / 72 - 6.94%
8 - 4 / 72 - 5.56%
9 - 3 / 72 - 4.17%
10 - 2 / 72 - 2.78%

Your odds do not need to match exactly - they can be off by 1/144th, or .69%, in either direction (but obviously they still must sum up to 72/72 or 100%).
Data roughly guessed from the fourth page, first figure of this paper.
Test Cases with Sample Output
Behavior on very short (length < 11) test cases is undefined.
Note that I created these by hand, so they may or may not follow the uniform distribution above.
abcdefghijklmnopqrstuvwxyz
abcd efgh i jklmnopq rs tu vwx yz

thequickbrownfoxjumpedoverthelazydog
t heq uick brown fo xj ump edo vert helazydog

ascuyoiuawerknbadhcviuahsiduferbfalskdjhvlkcjhaiusdyfajsefbksdbfkalsjcuyasjehflkjhfalksdblhsgdfasudyfekjfalksdjfhlkasefyuiaydskfjashdflkasdhfksd
asc uyoi uawer k nb a dhcviua hsid ufe r bfa lskd jhv lkcj haius dy faj se fbks dbfkals jcuyasjehf lkjh falk sd blhsgdf asudyfekjf alk sdjfhlk asefyu iaydskfja shdflk as dhf ksd

This is code-golf, so shortest answer in bytes wins.

Jelly, 28 bytes

“¤Œæ×¿®¬©¥¤‘Jẋ"$FẋLẊ‘1¦+\Ṭœṗ

A monadic link taking a list and returning a list of lists.

Try it online! (the footer separates the resulting list of lists with spaces)

How?

Uses all the percentages in the distribution rounded to their nearest integer (thus being within the 0.69% allowed thresholds).

“¤Œæ×¿®¬©¥¤‘Jẋ"$FẋLẊ‘1¦+\Ṭœṗ - Link: list (of characters), s
“¤Œæ×¿®¬©¥¤‘                 - code page indexes = [3,19,22,17,11,8,7,6,4,3]
               $             - last two links as a monad:
            J                -   range of length = [1, 2, 3, 4, 5,6,7,8,9,10]
              "              -   zip with:
             ẋ               -     repeat list = [[1,1,1],...,[9,9,9,9],[10,10,10]]
                F            - flatten (into one list of length 100)
                  L          - length of s
                 ẋ           - repeat list (one list of length 100*length(s) with the
                             -              correct distribution of integer lengths)
                   Ẋ         - shuffle
                      ¦      - sparse application of:
                    ‘        -   increment
                     1       -   to indexes: 1 (offset indexes for the partition below)
                        \    - cumulative reduce by:
                       +     -   addition (e.g. [4,4,7,1,...] -> [4,8,15,16,...])
                         Ṭ   - untruth (yield a list with 1s at those indexes (1 indexed)
                          œṗ - partition s at truthy indexes (note: excess ignored)


Jelly, 11 10 bytes

Saved 1 byte thanks to @Dennis

ȷḶ×⁽q£:ȷ5Ḃ

Try it online!

How?

I first noticed that the pattern alternates between runs of length 4 and length 3, skipping the length-4 step every few runs. This led me to look for a number which could be divided into the current index, then taken mod 2 and floored—i.e. retrieving the least significant bit—to give the bit at that index in the series. After much trial and error, I found that 3.41845 does exactly that, but multiplying by its approximate reciprocal (.29253) is a byte shorter.

ȷḶ×⁽q£:ȷ5Ḃ    Main link. Arguments: none
ȷ             Yield 1e3, i.e. 1000.
 Ḷ            Lowered range; yield [0, 1, 2, ..., 999].
  ×⁽q£        Multiply each item by 29253.
      :ȷ5     Floor-divide each item by 1e5, i.e. 100000.
         Ḃ    Take each item mod 2.


There are known knowns Former US Secretary of Defense, Donald Rumsfeld, famously popularized the phrase "known knowns." Here we're going to distill his remarks into a four-line stanza.

Specifically, output this text:

known knowns
known unknowns
unknown knowns
unknown unknowns

Capitalization doesn't matter (for example, Known unKnowns is fine), and a single trailing newline is acceptable, but no other formatting changes are allowed. That means a single space between the words, and either LF (59 bytes) or CR/LF (62 bytes) between the lines.

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.

Python 2, 54 52 bytes

-2 bytes thanks to xnor

k='unknowns'
for i in 8,6,2,0:print k[i/3:7],k[i%3:]

Try it online!

The results from the / and % will be [[2, 2], [2, 0], [0, 2], [0, 0]] that will be the starting indexes, removing the un when 2, keeping the string unaltered when 0


Most destructive "forgot-to-enter-insert-mode" sequence in Vim Pretend you have an arbitrary text file (which you may choose).

Give the sequence of keystrokes that is most destructive (*) if it was intended to be inserted to the text, but instead was entered in normal mode (i.e. i/a was not pressed). You may not enter visual mode and not quit Vim.

Destructive is defined as follows: The ratio of changed/deleted characters by the number of necessary keystrokes.
You get bonus points if your changes cannot be undone by a fixed number of undos.

Example: Input file without line breaks. Input sequence: dfs.


Overflow-Proof Buffer Background

Programmers these days can't seem to keep their buffers straight! A common source of error is trying to use an array index that is too large for the buffer. Your task is to implement a buffer where large indices are reduced to a size that the buffer can handle. Because I decide exactly what's best for everyone, you will implement this buffer to my precise specifications.

Overview

You have a insert-only buffer that grows in size as elements are added to it. The buffer is zero-indexed, and also indexed modulo its current size. The special rule for this challenge is this:

To insert an item at index i means to compute j, j = i % buffer.length() and insert the new item after the jth item in the list.

The only special case is if the buffer is empty, as arithmetic modulo zero doesn't work. Thus, if the buffer is currently empty, the new item will be index 0.

If the buffer has only one item, then you are always inserting after the 0th item. This is just one instance of the general case.

If the buffer contains 6 items: [4, 9, 14, 8, 5, 2] and you are told to insert a new item 10 at index 15, you find that 15 % 6 == 3, and then insert the new 10 after the 8 at index 3 which gives a resulting buffer of  [4, 9, 14, 8, 10, 5, 2]

Problem

Write a function or program that takes in an ordered list of positive integers, and positive integer indices at which to insert them.

Start with an empty buffer, and add the specified integers to the buffer at the corresponding indices.

Output the ordered list of integers that are in the buffer after all the specified insertions have been made.

This is a code-golf challenge, so shortest code wins.

Input guidelines

You may take the input lists however you see fit. Examples:

List of pairs: [ [1,1], [2,4], [3,9], [4,16], [5,25]...]
Item list and index list: [1, 2, 3, 4, 5...], [1, 4, 9, 16, 25]
Flattened: [1, 1, 2, 4, 3, 9, 4, 16, 5, 25 ...]
etc.

You may assume the input always contains at least one item and corresponding index.

Test cases

Squares case from above:

[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64)] -> [1, 2, 8, 7, 6, 5, 4, 3]

I generated these randomly:

[(11, 9), (13, 14)] -> [11, 13]
[(1, 18), (11, 7), (3, 35), (16, 22)] -> [1, 11, 16, 3]
[(3, 16), (16, 37), (0, 28), (18, 24)] -> [3, 18, 0, 16]
[(7, 26), (8, 20), (11, 39), (1, 23), (17, 27)] -> [7, 8, 11, 1, 17]
[(15, 35), (17, 7), (16, 15), (1, 13), (2, 6), (11, 34)] -> [15, 17, 1, 2, 16, 11]
[(2, 13), (1, 20), (16, 25), (8, 21), (5, 2), (16, 37), (3, 0)] -> [2, 3, 8, 1, 16, 5, 16]
[(6, 20), (15, 15), (12, 26), (10, 27), (17, 13), (7, 18), (4, 16)] -> [6, 10, 17, 12, 7, 4, 15]
[(18, 9), (5, 34), (15, 4), (12, 29), (2, 5), (7, 0), (7, 10), (16, 38)] -> [18, 7, 15, 2, 16, 5, 7, 12]
[(0, 12), (12, 0), (4, 16), (15, 12), (6, 28), (8, 10), (11, 24), (0, 25)] -> [0, 11, 8, 6, 15, 0, 4, 12]
[(6, 12), (14, 13), (10, 33), (11, 35), (1, 3), (0, 28), (15, 27), (8, 10), (1, 2)] -> [6, 14, 10, 1, 11, 8, 15, 0, 1]
[(2, 29), (19, 30), (18, 17), (13, 3), (0, 21), (19, 19), (11, 13), (12, 31), (3, 25)] -> [2, 13, 3, 11, 0, 12, 19, 18, 19]

Python3 reference implementation

def f(inputs):
    # `inputs` is a list of pairs
    buff = []
    for item, index in inputs:
        if len(buff) == 0:
            buff.insert(0, item)
        else:
            insert_after = index % len(buff)
            buff.insert(insert_after+1, item)
    return buff

Perl, 37 bytes

35 bytes of code + 2 bytes for -lp flags.

splice@F,1+<>%(@F||1),0,$_}{$_="@F"

Try it online!

The implementation is quite straight forward, splice inserts in array @F at index 1+<>%(@F||1) (note that @F||1 handles the case of the array being empty).

Just a few words about the (seemingly) unmatched braces }{ (because I had a comment about it, and I think it's quite weird for people who don't know Perl), and it's a quite common trick in Perl golfings:
-p flag surrounds the code with (roughly) while(<>){ CODE } continue { print }, (the continue is executed after each iteration). So with those unmatched }{, I change my code to while(<>) { CODE}{ } continue { print }. So it creates an empty block right after my code (but that's not a problem), and the continue is executed only once, after the while (ie. when the all the input has been read).


Sorting out redundant text from screen scraper application You are writing a screen scraper application monitoring a text-only chat window. Text is added at the bottom of the window.

The application takes screenshot of the chat window. If a change has occurred since last screenshot (new_screenshot != old_screenshot), the screenshot is saved.

After X time, all images are merged to one image, where the oldest image is on the top. This large image is send to a server for OCR, and a string of text is returned.

Challenge: Sort out redundant text.

Example: Chat window is 5 lines high and is initially empty. The solution must work with empty and not-empty initial chat window. More than one line can be added at each screenshot.

Input to algorithm:

1 Lorem ipsum dolor sit amet,
1 Lorem ipsum dolor sit amet,
2 consectetur adipiscing elit
1 Lorem ipsum dolor sit amet,
2 consectetur adipiscing elit
3 Mauris porttitor enim sed tincidunt interdum.
1 Lorem ipsum dolor sit amet,
2 consectetur adipiscing elit
3 Mauris porttitor enim sed tincidunt interdum.
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
1 Lorem ipsum dolor sit amet,
2 consectetur adipiscing elit
3 Mauris porttitor enim sed tincidunt interdum.
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
5 Nam aliquet velit vel elementum tristique.
2 consectetur adipiscing elit
3 Mauris porttitor enim sed tincidunt interdum.
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
5 Nam aliquet velit vel elementum tristique.
6 Donec ac tincidunt urna.
3 Mauris porttitor enim sed tincidunt interdum.
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
5 Nam aliquet velit vel elementum tristique.
6 Donec ac tincidunt urna.
7 Proin pretium, metus non porttitor lobortis, tortor sem rhoncus urna
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
5 Nam aliquet velit vel elementum tristique.
6 Donec ac tincidunt urna.
7 Proin pretium, metus non porttitor lobortis, tortor sem rhoncus urna
8 quis finibus leo lorem sed lacus.
5 Nam aliquet velit vel elementum tristique.
6 Donec ac tincidunt urna.
7 Proin pretium, metus non porttitor lobortis, tortor sem rhoncus urna
8 quis finibus leo lorem sed lacus.
1 Lorem ipsum dolor sit amet,

Expected result:

1 Lorem ipsum dolor sit amet,
2 consectetur adipiscing elit
3 Mauris porttitor enim sed tincidunt interdum.
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
5 Nam aliquet velit vel elementum tristique.
6 Donec ac tincidunt urna.
7 Proin pretium, metus non porttitor lobortis, tortor sem rhoncus urna
8 quis finibus leo lorem sed lacus.
1 Lorem ipsum dolor sit amet,

UPDATE: I forgot an important detail in the original challenge: The same line can come multiple times, but never two times in a row so just deduplicating is not enough.

Japt -R, 11 bytes
This passes the test case but the spec still isn't clear enough
·ò¨ mÌò¦ mg

Try it


Convert number to comma separated number Given a number, say, -2982342342363.23425785 convert it to -2,982,342,342,363.23425785.

Extra points for not using look-behind
Extra points for not using regular expressions.

Java, 50 chars

String C(double d){return String.format("%,f",d);}

Works as specified in most locales.  Does the correct thing in all locales :)

Edit:

If you really want commas no matter the default locale, do:

String C(double d){return String.format(java.util.Locale.US,"%,f",d);}

which is 70 characters (60 if you've already imported java.util.*).


Golff y Côd - Treiglad Read this yng Nghymraeg

Challenge

Given a word in Welsh, output all of the possible mutated forms of the word.

Mutations

A mutation is a change of the first letter of a word when following certain words or in certain grammatical contexts.

In Welsh, the following are considered "consonants":

b c ch d dd f ff g ng h l ll m n p ph r rh s t th

Note that multiple character consonants such as ch, ng and rh are counted as one letter in Welsh, and therefore one consonant.

The other letters in the Welsh alphabet are vowels, listed below:

a e i o u w y

See below, all of the mutations with the original letter on the left and the resulting mutated letters on the right:

Original | Mutations
---------+---------------
p        | b mh ph
t        | d nh th
c        | g ngh ch
b        | f m
d        | dd n
g        | [no letter] ng
m        | f
ll       | l
rh       | r

Here, [no letter] means that the g is removed from the start of the word.

Note that there are some consonants which do not mutate:

ch
dd
f
ff
j
l
n
ng
ph
r
s
th

Vowels may also be found at the start of words but do not mutate:

a
e
i
o
u
w
y

Examples

Input: dydd

Output:

dydd
ddydd
nydd

Input: pobl

Output:

pobl
bobl
mhobl
phobl

Input: gwernymynydd

Output:

gwernymynydd
wernymynydd
ngwernymynydd

Input: ffrindiau

Output:

ffrindiau

Input: enw

Output:

enw

Input: theatr

Output:

theatr

On the request of ArtOfCode ;)

Input: llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch

Output:

llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch
lanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch

Rules

The input will only ever be one word.

There will always be more letters after the leading consonant in your input.

Winning

The shortest code in bytes wins.

JavaScript (ES6), 180 bytes

x=>x.replace(/^([cpt](?!h)|d(?!d)|[bgm]|ll|rh)(.+)/,(_,y,z)=>({p:"b mh ph",t:"d nh th",c:"g ngh ch",b:"f m",d:"dd n",g:" ng",m:"f"}[y]||y[0]).split` `.map(b=>a.push(b+z)),a=[x])&&a

Outputs as an array of strings. This is my first try, so it's almost certainly not optimal.

Try it out

f=x=>x.replace(/^([cpt](?!h)|d(?!d)|[bgm]|ll|rh)(.+)/,(_,y,z)=>({p:"b mh ph",t:"d nh th",c:"g ngh ch",b:"f m",d:"dd n",g:" ng",m:"f"}[y]||y[0]).split` `.map(b=>a.push(b+z)),a=[x])&&a
<input id=A value="pobl"><button onclick="B.innerHTML=f(A.value).join('
')">Run</button>


Translate a Glypho program Given an input of any valid Glypho program,
output its "human-readable" counterpart.

Glypho is an interesting esolang idea:

  The instruction reference is given here. For each instruction, the characters
  abcd represent the symbols composing each instruction. a refers to the first
  unique symbol, b refers to the second unique symbol, etc.

aaaa ..... n NOP - no operation; do nothing
aaab ..... i Input - push input onto top of stack
aaba ..... > Rot - pops top stack element and pushes to bottom of stack
aabb ..... \ Swap - swaps top two stack elements
aabc ..... 1 Push - pushes a 1 onto the top of stack (creates new element)
abaa ..... < RRot - pops bottom element and pushes to top of stack
abab ..... d Dup - Duplicates top stack element
abac ..... + Add - pops top two elements and pushes their sum
abba ..... [ L-brace - skip to matching ] if top stack element is 0
abbb ..... o Output - pops and outputs top stack element
abbc ..... * Multiply - pops top two elements and pushes their product
abca ..... e Execute - Pops four elements and interprets them as an instruction
abcb ..... - Negate - pops value from stack, pushes -(value)
abcc ..... ! Pop - pops and discards top stack element
abcd ..... ] R-brace - skip back to matching [

  (credit: Brian Thompson aka
  Wildhalcyon)

So, for example, PPCG would represent the Push instruction—PPCG matches
the pattern aabc, where a represents P, b represents C, and c
represents G.

The input will be a single string consisting of only printable ASCII
characters. It will always have a length divisible by four (duh).

The output is each group of four characters in the input string replaced by
which instruction they designate. Use the single-letter instruction names (the
ones right after the five dots in the table quoted above).

Since this is code-golf, the shortest code in bytes will win.

Test cases:

In                                Out
------------------------------------------------
Programming Puzzles & Code Golof  ]!]!]]]+
nananananananana batman!          dddd]]
;;;;;;;:;;:;;;::                  ni>\
llamas sleep                      1-*
8488133190003453                  <[oe
<empty string>                    <empty string>

Pyth, 37 35 34 bytes
The code contains unprintable characters, so here is the xxd hexdump:
0000000: 5663 7a34 7040 2e22 216f d78c 40bf d4f0  Vcz4p@."!o..@...
0000010: 38d6 7dfe 7312 3ff8 ea22 6958 4e7b 4e55  8.}.s.?.."iXN{NU
0000020: 5433                                     T3

Here's a printable version at 36 bytes:
Vcz4p@"ni >\\1   <d+[o*e-!]"iXN{NUT3

Try it online. Test suite.
Explanation
Vcz4p@."…"iXN{NUT3       implicit: z = input
  z                      input
 c 4                     split to 4-character blocks
V                        loop over that in N
           X               replace...
            N                in current part
             {N              unique chars in current part, in order
               UT            with numbers 0-9
          i      3         interpret as base 3
     @                     take that item of
      ."…"                   string "ni >\\1   <d+[o*e-!]"
    p                      and print without newline


Total number of cells in R numeric dataframe Problem statement

The task is to write the shortest R statement to count the cells (rows * cols) in an instance of the R type numeric data.frame. For example, the data.frame which would be displayed as

  a    b  c
1 1 2000 NA
2 2 2000 NA
3 3 2000 1
4 4 2000 Inf

has 12 cells.

Input

The data.frame is supplied in variable x. You may assume that it contains only numbers, boolean, NA, Inf (no strings and factors).

Test cases

Example code to construct your own data.frame:

x <- merge(data.frame(a = 1:100),
    merge(data.frame(b = 2000:2012),
    data.frame(c = c(NA, 10, Inf, 30))))

The expected output is 15600.

Appendix

Curious if someone can beat my solution :-) I don't want to take the fun from you so I will not reveal it now, I will only show you md5sum of my solution so that you later trust me in case you invent the same :-)

d4f70d015c52fdd942e46bd7ef2824b5

My best two attempts so far only got me down to 11 characters. I'd love to see fewer than @Spacedman's 10!

>sum( `[<-`(x,,,1) )
[1] 15600

>sum(!(F&x))
[1] 15600

Got it!

sum(x^0)
[1] 15600


Determine the cyclical shift your program is in Write a program that outputs the number 0.

That's a bit trivial, isn't it?

Let the length of your program be \$S\$. Write a program that outputs the number 0. When your program is cyclically shifted \$i < S\$ bytes left, it should output \$i\$. To cyclically shift a string \$i\$ bytes left means to move the last \$i\$ bytes (including newlines) to the front, without changing the order.

For example, if your code is ABCD, then ABCD should output 0; DABC should output 1; CDAB should output 2; BCDA should output 3.

Rules

Your program must be at least 3 bytes long.
"Output" represents any acceptable output: on the stack, to STDOUT, as a return value, as an exit code, etc.
Your program is to not take any form of input.
This is code-golf, so shortest code wins.

brainfuck, 3 bytes

.++

Try it online!

how it works: it's really simple, actually. The internal memory is initialized at 0 so we output (with .) the original cell and we get 0. By shifting the program, we are shifting memory increments (done with +) to before the output, so each byte shifted corresponds to one more increment, and hence we increase the counter.


Making octogonal words Last Thursday user @SpookyGengar delighted us with his/her first challenge about Making Squared Words. What if we double the number of sides?

The challenge

Take a string as input in any reasonable format you need (string, char array...) and output an octogonal representation of the input (also in any reasonable format: string, list of strings, char matrix...) as in the next examples:

Input: golf
Output:

   golf
  o    l
 l      o
f        g
l        o
o        l
g        f
 o      l
  l    o
   flog

Input: HelloWorld
Output:

         HelloWorld
        e          l
       l            r
      l              o
     o                W
    W                  o
   o                    l
  r                      l
 l                        e
d                          H
l                          e
r                          l
o                          l
W                          o
o                          W
l                          o
l                          r
e                          l
H                          d
 e                        l
  l                      r
   l                    o
    o                  W
     W                o
      o              l
       r            l
        l          e
         dlroWolleH

Input: a
Output:

a

Input: ab
Output:

 ab
b  a
a  b
 ba

Input: code golf
Output:

        code golf
       o         l
      d           o
     e             g

   g                 e
  o                   d
 l                     o
f                       c
l                       o
o                       d
g                       e

e                       g
d                       o
o                       l
c                       f
 o                     l
  d                   o
   e                 g

     g             e
      o           d
       l         o
        flog edoc

Notes

Input will consist only of printable ASCII characters.
Leading and/or trailing whitespaces and newlines allowed as long as the octogonal shape is maintained.
This is code-golf, so may the sortest program/function for each language win!

Charcoal, 16 bytes (10 bytes noncompeting)

Ｆ⁸«✂θ⁰±¹↷¹Ａ⮌θθ»θ

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

Ｆ⁸«                 Repeat for each side of the octagon
   ✂θ⁰±    ¹        Print the input except the last character
        ↷¹          Rotate 45° clockwise
          Ａ⮌θθ      Reverse the input string
              »θ    Print the input again, to handle the length 1 case

Alternative length 1 fix, also 16 bytes: Verbose version.

ＰθＦ⁸«✂θ⁰±¹↷¹Ａ⮌θθ

A Charcoal bugfix means that the following 10-byte code now works: Verbose version.

Ｆ⁴«θ←↘⮌θ↖⟲


A nasty little memory leak Below Python code generates memory leak.

Challenge: Fix the memory leak with minimal changes to the code as measured by Levenshtein distance to the original code. You may only change the code before t is initialised. When the del t line is removed the modified program should print I'm still alive! every second.

PS: I already know the answer (found it after several hours of debugging). This is not the programming help question! Hopefully this would be interesting to folks.

import threading, time

# this class takes callback and calls it every 1 sec
class MyTimer:
    def __init__(self, callback):
        self.callback = callback
        self.th = threading.Thread(target=self.run,daemon=True)
        self.th.start()
    def run(self):
        while(True):
            self.callback()
            time.sleep(1)

class TestMyTimer:
    def __init__(self):
        self.timer = MyTimer(self.is_alive)
    def is_alive(self):
        print("I'm still alive")

# test code for MyTimer
t = TestMyTimer()
del t

# just to be sure to collect all dead objects
import gc
gc.collect()

# if you are still seeing messages then we have memory leak!
time.sleep(60)

Here's repl.it to play with this code online.

Taking inspiration from the comments and from the question, just by adding 3 characters I "fixed" the memory leak.

Granted, I broke everything else at the same time

import threading, time

# this class takes callback and calls it every 1 sec
class MyTimer:
    def __init__(self, callback):
        self.callback = callback
        self.th = threading.Thread(target=self.run,daemon=True)
        self.th.start()
    def run(self):
        while(True):
            self.callback()
            time.sleep(1)

class TestMyTimer:
    def __init__(self):
        self.timer = MyTimer(self.is_alive)
    def is_alive(self):
        print("I'm still alive")

# test code for MyTimer
#t = TestMyTimer()
#del t

# just to be sure to collect all dead objects
import gc
#gc.collect()

# if you are still seeing messages then we have memory leak!
time.sleep(60)

Edit: The challenge has now been properly updated :)


I Rot-13 the source code, you Rot-19 the output! This is alternate of a rip-off of a rip-off of a rip-off of a  rip-off of a rip-off of a rip-off. Go upvote those!
Your task, if you accept it, is to write a program/function that outputs/returns its input/args. But again, The tricky part is that if I rot-13 your source code, the output must be returned rot-19.
Your code will be only rotated once.
Examples
Let's say your source code is ABC and the input is xyz.
Code ABC should return xyz.
Code NOP(rotated) should return -./ (Rot-19).
Details

If your language has a custom codepage, apply rot13 to the bytes in the printable ASCII range in your code, and do not modify the rest. The input and output will be in pure printable ASCII.
The input only contains ASCII character.
use printable ASCII table for rotating
rot-13 means to forward 13 positions in ASCII table
Same applied to rot-19, which forward 19 positions instead.

Rules

Input can be taken in any convenient format.
Output can be in any convenient format as well.
Standard Loopholes are forbidden.

scoring
This is code-golf so the answer with the fewest amount of bytes wins.
Extra scoring rule
If there's somehow, a non-esolang appeared as a valid answer, it may considered as a better answer.
Example: python, C++, java script etc.
If you are confused with Rot
Here is a encoder to get some idea with.
Use full ACSII Table for this question’s requirement.
Use printable ASCII Table (33 ~126) for rotation!

Space are 32 in ASCII, which count as unprintable!

JavaScript (Node.js), 50 bytes

a=>01+"$25hYYXeya=>z!`TcyV01yV~$'zv,'|&&z|xx-$"&&a

Try it online!
Both versions are a function which takes a string as input and returns a string.
ROT13 code:
nJK=>8/1?Buffer(nJK).map(c=>(c-14)%94+33)+'':1/33n

Explanation
Hides tricky characters used in the ROT19 logic inside a string. The quotes map to / characters so it's just a matter of finding where to put them to make it work.


My triangle needs more nodes Consider the standard equilateral triangle, with nodes labeled using barycentric coordinates:

We can turn this 3 node triangle into a 6 node triangle by adding a new line of 3 vertices (one more than was present on a side of the original 3 node triangle), remove any internal edges (but not internal nodes) and re-normalize the coordinates:

Repeating the process to go from a 6 node triangle to a 10 node triangle, add a line of 4 vertices (again, one more than was present on a side of the original 6 node triangle), remove any internal edges (but not internal nodes) and re-normalize the coordinates:

This process can be repeated indefinitely. The goal of this challenge is given an integer N representing how many times this process has been performed, output all the nodes for the associated triangle in barycentric coordinates.

Input

Your program/function should take as input a single non-negative integer N representing how many times this process has been applied. Note that for N=0, you should output the original triangle with 3 nodes.

The input may come from any source (function parameter, stdio, etc.).

Output

Your program/function should output all the nodes in normalized barycentric coordinates. The order of the nodes does not matter.
A number can be specified as a fraction (fraction reduction not required) or a floating point number. You may also output "scaled" vectors to specify a node. For example, all 3 of the following outputs are equivalent and allowed:

0.5,0.5,0

1/2,2/4,0

[1,1,0]/2

If using floating point output, your output should be accurate to within 1%. The output may be to any sink desired (stdio, return value, return parameter, etc.). Note that even though the barycentric coordinates are uniquely determined by only 2 numbers per node, you should output all 3 numbers per node.

Examples

Example cases are formatted as:

N
x0,y0,z0
x1,y1,z1
x2,y2,z2
...

where the first line is the input N, and all following lines form a node x,y,z which should be in the output exactly once. All numbers are given as approximate floating point numbers.

0
1,0,0
0,1,0
0,0,1

1
1,0,0
0,1,0
0,0,1
0.5,0,0.5
0.5,0.5,0
0,0.5,0.5

2
1,0,0
0,1,0
0,0,1
0.667,0,0.333
0.667,0.333,0
0.333,0,0.667
0.333,0.333,0.333
0.333,0.667,0
0,0.333,0.667
0,0.667,0.333

3
1,0,0
0.75,0,0.25
0.75,0.25,0
0.5,0,0.5
0.5,0.25,0.25
0.5,0.5,0
0.25,0,0.75
0.25,0.25,0.5
0.25,0.5,0.25
0.25,0.75,0
0,0,1
0,0.25,0.75
0,0.5,0.5
0,0.75,0.25
0,1,0

Scoring

This is code golf; shortest code in bytes wins. Standard loopholes apply. You may use any built-ins desired.

CJam (22 bytes)

{):X),3m*{:+X=},Xdff/}

This is an anonymous block (function) which takes N on the stack and leaves an array of arrays of doubles on the stack. Online demo

Dissection

{         e# Define a block
  ):X     e# Let X=N+1 be the number of segments per edge
  ),3m*   e# Generate all triplets of integers in [0, X] (inclusive)
  {:+X=}, e# Filter to those triplets which sum to X
  Xdff/   e# Normalise
}