Package distribution While at work I spotted a nice and simple challenge.
The job was to stock products in cargo units with a certain capability.
Since an order can have various batches, coming in sequence from the production, we usually make a list of the pieces of those batches distributed in each cargo to make sure nothing is lost during the process.
For example if we had this production sheet:
 _____________
|ord: xxx     |
|_____________|
| A | 30 pcs  |
| B | 38 pcs  |
| C | 12 pcs  |
 —————————————

and our cargo could contain 12 pieces we would make this list:
A | 12 12  6-
B | -6 12 12  8-
C | -4  8//

where x- indicates that x pieces will be stocked with -y pieces of the next line and z// indicates that after those z pieces there's a different order, thus nothing more we can add, and the last cargo is complete.
Task
In this challenge you have to take a production sheet and a cargo capacity and output the distributed list.
Specifications
Production sheet is taken in the form of a sequence of numbers representing the batches amounts.
You have to output just the distributed amounts, we don't care about the additional signs - // mentioned above.
Every batch must be distributed separately, so the output is a list of lists which you can represent in any reasonable format, just specify it and be consistent.
It's guarantee that:

each batch has at least one piece
cargo units can contain at least one piece
an order( input list ) has at least one batch

So you have to handle only positive integers( >0 ).
input:
a list of numbers representing the production sheet and a number representing the cargo capacity, each positive integers, in any reasonable method / order.
output:
the distributed list in form of a list of lists of numbers in any convenient method.

No extraneous numbers can appear in the output.
Order of obtained lists must be preserved.

Test cases
 [30, 38, 12], 12 => [[12,12,6],[6,12,12,8],[4,8]]
 [1],1 => [[1]]
 [2],1 => [[1,1]]
 [1],2 => [[1]]
 [1,12,34],20 => [[1],[12],[7,20,7]]
 [5],1 => [[1,1,1,1,1]]
 [5],5 => [[5]]
 [300,120],84 => [[84,84,84,48],[36,84]]
 [1,2,3,4,5],6 => [[1],[2],[3],[4],[2,3]]
 [2,5,16,38,32,38,38,34,8,30,31,9,12],15 => [[2],[5],[8,8],[7,15,15,1],[14,15,3],[12,15,11],[4,15,15,4],[11,15,8],[7,1],[14,15,1],[14,15,2],[9],[4,8]]

Rules

Input/output can be given by any convenient method.
You can print it to STDOUT, return it as a function result or error message/s.
Either a full program or a function are acceptable.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Sandbox


Output all the white or black squares of a chessboard Introduction
This is how a chessboard looks like.

You can see that a1 is a dark square. However, b1 is a light square.
The Task
The challenge is, given dark, light or both, output all the dark, light or all squares with a separator (like a whitespace or a newline). The order of all the squares does not matter.
Test cases
Input: dark
Output: a1 a3 a5 a7 b2 b4 b6 b8
        c1 c3 c5 c7 d2 d4 d6 d8
        e1 e3 e5 e7 f2 f4 f6 f8
        g1 g3 g5 g7 h2 h4 h6 h8

Input: light
Output: a2 a4 a6 a8 b1 b3 b5 b7
        c2 c4 c6 c8 d1 d3 d5 d7
        e2 e4 e6 e8 f1 f3 f5 f7
        g2 g4 g6 g8 h1 h3 h5 h7

Input: both
Output: a1 a2 a3 a4 a5 a6 a7 a8
        b1 b2 b3 b4 b5 b6 b7 b8
        c1 c2 c3 c4 c5 c6 c7 c8
        d1 d2 d3 d4 d5 d6 d7 d8
        e1 e2 e3 e4 e5 e6 e7 e8
        f1 f2 f3 f4 f5 f6 f7 f8
        g1 g2 g3 g4 g5 g6 g7 g8
        h1 h2 h3 h4 h5 h6 h7 h8

Note: I have prettified the output but this is not necessary.
This is code-golf, so the submission with the least amount of bytes wins!

Pyth, 22 21 bytes
-1 byte by @Sp3000
fn%Chz3%sCMT2sM*<G8S8

Under the function %Chz3, dark hashes to 1, light to 0, and both to 2. If we take the parity of the sum of the ords of a chess square (that is, a1 -> [97, 33] -> (97 + 33)%2 = 0, dark squares go to 0, and light to 1. This allows us to filter by inequality.
fn%Chz3%sCMT2sM*<G8S8      implicit: z=input
               *           Cartesian product of
                <G8          first 8 letters in G (alphabet)
                   S8        with [1,...,8] implicitly stringified
             sM*<G8S8      ['a1','a2,...,'a8','b1'...'h8']
f          T               Filter that by gives truthy result to lambda T:
        sCMT                   The sum of the ords of the chars in T,
       %    2                  modulo 2
 n                            does not equal
   Chz                          ord of the first char in z,
  %   3                         modulo 3
                            Implicitly print the list.

Try it here.


Animate Jacob's ASCII Ladder You may have seen Jacob's Ladder in children's science museums. If you're not familiar with what they look like, there are several images and video examples on the Wikimedia Commons. The challenge today is to create an animated ASCII version of the electrical gadget. In the end, it should look something like this:

Ladder Construction

Here is the basic shape of a ladder with a height (H) of 6:

6   \            /
5    \          /
4     \        /
3      \      /
2       \    /
1        \  /
0         ¯¯

The numbers on the left simply indicate row number for this example and should not be included in the output. We'll refer to a given row by it's number (R). Row 0 is the bottom ¯¯. Each row 1 through H is comprised of four parts:

A space  (U+0020) repeated (H - R) times
A back slash \ (U+005C)
A space  (U+0020) repeated (2 * R) times
A forward slash / (U+002F)

Row 0 is identical except both the slashes are replaced with a macron ¯ (U+00AF). Trailing whitespace at the end of each line or below the ladder is OK. Leading whitespace is not.

Arc Construction

Once the ladder is constructed, you can create arcs between the left and right side. One arc is entirely within a row and replaces the spaces between the leading \ and trailing /. Therefore, row 2 will have 4 characters in its arc, row 3 will have 6, and so forth. Each arc is composed using the following rules:

The only allowable characters are _/¯\ (U+005F, U+002F, U+00AF, U+005C)
In order to ensure a smooth appearance, any ¯ or / must be followed by a ¯ or \
In order to ensure a smooth appearance, any _ or \ must be followed by a _ or /
The two rules above apply to the edges of the ladder as well
The three rules above effectively mean that the first character in the arc must be _ or / and the last character must be _ or \ (\¯\_// is invalid on both ends but \_/¯\/ is OK)
There must be a non-zero chance for each allowable character to occur at a given point
Each arc is independent from every other arc

Animation

The life of a single arc is created by starting it at row 1 and "moving" it up one row at a time until it reaches the top. I.E., first generate an arc at row 1, then set it back to spaces and generate an arc at row 2, and so forth. Given a number of arcs to show (N), show the complete life of that many arcs one at a time using the following guidelines:

Only one arc should be "alive" at any one time. The next arc cannot start until the current one reaches the top and then extinguishes.
Each row of the arc's life should be shown for exactly one frame
There should one frame of just the basic ladder (with no arcs) before a new arc starts (optional before the first arc)
The animation should show the full life of N arcs. If N=0, it should animate random arcs forever until stopped.
If N>0, you may still loop the animation forever but it must be a loop of the same arcs over and over. (The example GIF at the top of this post has H=6 and N=3 but it loops forever.)
The animation should occur in-place. That is, each frame should completely overwrite the next frame and be in the same location.
The length of each frame can be whatever you want but make it watchable by a human (I.E., use your common sense: 0.01s/frame and 30s/frame are both unacceptable.)

Input / Output

Input and Output can be in any standard format
You can export a GIF, write text to the screen, output a single file for each frame, or any other reasonable means
Standard loopholes are forbidden
The height of the ladder H will be a positive integer
The number of arcs to show N will be a non-negative integer
Both H and N are taken as inputs in any order you choose (Please include the order in your answer)

Winning Condition

This is code-golf so the shortest code wins.

Sandbox

Python 2, 287 271 270 276 275 bytes

import time,random
r,n=input()
c=n*-~r or-r
while c:
 c-=1;L=[list(' '*i+'\\'+'  '*(r-i)+'/')for i in range(r)];x=c%-~r;time.sleep(1);y=x+1;exec"L[x][y]=random.choice('\xaf/\_'[L[x][y-1]in'\_'::2][y==2*r-x:]);y+=1;"*2*(r-x)
 for l in['']*99+L+[' '*r+'\xaf'*2]:print''.join(l)

Try it online!

Does not clear the screen on tio, but works in a console.

Gif of it running:


Tic-tac-toe with only crosses Introduction
Everyone knows the game tic-tac-toe, but in this challenge, we are going to introduce a little twist. We are only going to use crosses. The first person who places three crosses in a row loses. An interesting fact is that the maximum amount of crosses before someone loses, is equal to 6:
X X -
X - X
- X X

That means that for a 3 x 3 board, the maximum amount is 6. So for N = 3, we need to output 6.
Another example, for N = 4, or a 4 x 4 board:
X X - X
X X - X
- - - -
X X - X

This is an optimal solution, you can see that the maximum amount of crosses is equal to 9. An optimal solution for a 12 x 12 board is:
X - X - X - X X - X X -
X X - X X - - - X X - X
- X - X - X X - - - X X
X - - - X X - X X - X -
- X X - - - X - - - - X
X X - X X - X - X X - -
- - X X - X - X X - X X
X - - - - X - - - X X -
- X - X X - X X - - - X
X X - - - X X - X - X -
X - X X - - - X X - X X
- X X - X X - X - X - X

This results in 74.
The task
The task is simple, given an integer greater than 0, output the maximum amount of crosses that can be placed with no three X's adjacent in a line along a row, column or diagonally.
Test cases
N     Output
1     1
2     4
3     6
4     9
5     16
6     20
7     26
8     36
9     42

More information can be found at https://oeis.org/A181018.
Rules

This is code-golf, so the submission with the least amount of bytes wins!
You may provide a function or a program.

CJam (58 56 bytes)

2q~:Xm*{7Yb#W=}:F,Xm*{ee{~0a@*\+}%zS*F},_Wf%:z&Mf*1fb:e>

This is incredibly slow and uses a lot of memory, but that's code-golf for you.

Dissection

2q~:Xm*        e# Read input into X and find Cartesian product {0,1}^X
{7Yb#W=}:F,    e# Filter with a predicate F which rejects arrays with a 111
Xm*            e# Take the Cartesian product possible_rows^X to get possible grids
{              e# Filter out grids with an anti-diagonal 111 by...
  ee{~0a@*\+}% e#   prepending [0]*i to the ith row
  zS*F         e#   transposing, joining on a non-1, and applying F
},
_Wf%:z         e# Copy the filtered arrays and map a 90 degree rotation
&              e# Intersect. The rotation maps horizontal to vertical and
               e# anti-diagonal to diagonal, so this gets down to valid grids
Mf*            e# Flatten each grid
1fb            e# Count its 1s
:e>            e# Select the maximum

The number of valid rows is a tribonacci number and is \$\Theta(a^X)\$ where \$a\$ is the tribonacci constant, \$1.83928675\ldots\$. The number of grids generated in the Cartesian product is \$\Theta(a^{X^2})\$; the second filter will reduce the number somewhat, but the intersection is still probably \$\Theta(a^{X^4})\$.

An "efficient" approach ("merely" \$O(X a^{3X})\$) uses dynamic programming. Ungolfed in Java:

public class A181018 {
    public static void main(String[] args) {
        for (int i = 1; i < 14; i++) {
            System.out.format("%d:\t%d\n", i, calc(i));
        }
    }

    private static int calc(int n) {
        if (n < 0) throw new IllegalArgumentException("n");
        if (n < 3) return n * n;

        // Dynamic programming approach: given two rows, we can enumerate the possible third row.
        // sc[i + rows.length * j] is the greatest score achievable with a board ending in rows[i], rows[j].
        int[] rows = buildRows(n);
        byte[] sc = new byte[rows.length * rows.length];
        for (int j = 0, k = 0; j < rows.length; j++) {
            int qsc = Integer.bitCount(rows[j]);
            for (int i = 0; i < rows.length; i++) sc[k++] = (byte)(qsc + Integer.bitCount(rows[i]));
        }

        int max = 0;
        for (int h = 2; h < n; h++) {
            byte[] nsc = new byte[rows.length * rows.length];
            for (int i = 0; i < rows.length; i++) {
                int p = rows[i];
                for (int j = 0; j < rows.length; j++) {
                    int q = rows[j];
                    // The rows which follow p,q cannot intersect with a certain mask.
                    int mask = (p & q) | ((p << 2) & (q << 1)) | ((p >> 2) & (q >> 1));
                    for (int k = 0; k < rows.length; k++) {
                        int r = rows[k];
                        if ((r & mask) != 0) continue;

                        int pqrsc = (sc[i + rows.length * j] & 0xff) + Integer.bitCount(r);
                        int off = j + rows.length * k;
                        if (pqrsc > nsc[off]) nsc[off] = (byte)pqrsc;
                        if (pqrsc > max) max = pqrsc;
                    }
                }
            }

            sc = nsc;
        }

        return max;
    }

    private static int[] buildRows(int n) {
        // Array length is a tribonacci number.
        int c = 1;
        for (int a = 0, b = 1, i = 0; i < n; i++) c = a + (a = b) + (b = c);

        int[] rows = new int[c];
        int i = 0, j = 1, val;
        while ((val = rows[i]) < (1 << (n - 1))) {
            if (val > 0) rows[j++] = val * 2;
            if ((val & 3) != 3) rows[j++] = val * 2 + 1;
            i++;
        }

        return rows;
    }
}


Follow incomplete directions A friend of yours has given you directions to the best restaurant in town. It's a series of left and right turns. Unfortunately, they forgot to mention for how long you need to go straight ahead between those turns. Luckily you have a street map with all the restaurants on it. Maybe you can figure out which restaurant they meant?

Input

The map is given as a rectangular grid of ASCII characters. . is a road, # is a building, A to Z are the various restaurants. You start in the top left corner, going east. Example:

.....A
.#.###
B....C
##.#.#
D....E
##F###

Your friend's instructions will be given as a (potentially empty) string or list of characters containing Ls and Rs.

Output

You can walk any path that corresponds to the left and right turns in the input string, provided that you take at least one step forward before each of them, as well as at the end. In particular this means if the string starts with R you cannot go south immediately in the left-most column. It also means you can't turn around 180° on the spot.

You cannot walk through buildings or restaurants except the one you reach at the end. You may assume that the top left corner is a ..

You should output all the restaurants that can be reached with your friend's instructions, as a string or list.

You may assume that the instructions will lead to at least one restaurant. E.g. a single L would be invalid for the above map.

Some examples for the above map:

<empty> A
R       F
RR      B,D
RL      C,E
RLRL    E
RLLR    C
RLLL    B
RLRR    D
RLRRRR  A,C
RLLLRLL B

Note in particular that R doesn't reach B.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Standard code-golf rules apply.

Additional Test Cases

Here is a larger map, courtesy of Conor O'Brien (which I modified a bit):

.......Y..........................######
.####.....#.##....##..######....#.###.##
B.........#.##.#..##....##...##.#.#P...#
.#.#####..#.##..#.##....##.#....#.####.#
.#.#...C..#.##...G##..#.##.#....#.#....#
.#.#.#.#..#.####.###.#..##.#....#.#.NO.#
.#.#A#.#..#.##...F###...##.#.##.#......#
.#.###....#.##....##....##.#....###....#
.#.....##...##....##...D##........###R.#
.#.##..##...##E...##..######....####...#
.....X....#.#.....................##S.T#
###########.###########M############...#
#................................###.#.#
#.#########.########.######.#.######.#.#
#......V#.....######.IJ...........##.#.#
#########.###......ZH############L##.#.#
#########.##########.###############.#.#
####K##...##########.#....#..........#.#
####....########U......##...#######Q.#.#
#####################################W.#

And here are a few selected lists of directions and their expected results:

<empty>                                 Y
RR                                      B
RLL                                     Y
RLRR                                    B,C,X
RLLLRRR                                 G
RLRLRLRL                                I,Z
RLLRRRLRRLRR                            C,D,F,G,Y
RLRRLLRLLLRL                            B,C,Y
RLLRRLRRRLLLL                           F,M,N,O,Y
RLRRLLLRRRRLLLL                         F,M,Y
RLRRLRRRRRRRRRR                         E,F,Y
RLRRRLLLRLLRRLL                         M,N,O
RLLRRLRRLRLRLRRLLR                      E,U
RLRLLRLRRLRRRRRLRL                      F,G,I,Z
RLLRRLLRLLRRRLRRLLRR                    W
RLLLRRRLRRLLLLLRLLLLLL                  D,G,X
RLRLLRLRRLRLRRRLRLLLRR                  B,C,E,J,X
RLRLRLLLLRLRRRRRRLRLRRLR                Y
RLRLRRRLRLLLLRLRRLLLLRLLRRL             E,M,X
RLRLLLRRRLLLRLLRLLRLRRLRLRR             B,E,F,K
RLRRRLLLLLLLLLLLLLLLRRRRLLL             A,B

Bonus question: is there an input that results in only I or only U? If so, what's the shortest such path?

Perl, 150 149 146 145 141 140 138 136 135 133 130 126 125 124

Added +7 for -F -Xn0i

An initial attempt.

Run with the map on STDIN and the directions after the -i option, e.g.

perl -F -Xn0iRL incomplete.pl
.....A
.#.###
B....C
##.#.#
D....E
##F###

Close STDIN with ^D or ^Z or whatever works on your operating system.

incomplete.pl:

%P=0;$^I=~s``{%;=!/
/;%P=map{$_|=$F[$^H=$_+=(1,@+,-1,"-@+")[$d&3]]=~/(\w)|#|^$/*~!\$;{$1}}(%P)x@F}$d-=B&$'^u`eg;print%

Replace the ^H by the literal control character to get the given score

Bonus question:

There is no input that results in only I
The shortest input that results in only U is RLLRRLLRLRLRRLRRLRLRLRRLLR
The longest input needed to result in a unique set is RLLRRRLRLRLLLRRLRLLLLLRRRLLRRRLLLLLLLRRLRRRR which gives B O R


Make America(n Maps) Great Again New Bonus! (See below)

The cartography team of U.S. Republican presidential hopeful Ben Carson is having some trouble with their maps (image via Washington Post):

The problem is they don't have the Right Tool For The Job™. They need the most compact and reliable program possible, so they never have to worry about making maps again. That's why they hired you. You need to take this map and output it again with the desired coloring:

  By Theshibboleth [GFDL (http://www.gnu.org/copyleft/fdl.html) or
  CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0/)], via
  Wikimedia Commons

If you don't know where all the states are (because you are not an American...or you are an American), here is a map with all the names (Washington D.C. is not required for this challenge):

  "Map of USA with state names 2". Licensed under CC BY-SA 3.0 via
  Wikimedia Commons -
  https://commons.wikimedia.org/wiki/File:Map_of_USA_with_state_names_2.svg#/media/File:Map_of_USA_with_state_names_2.svg

For example if the input is Ohio, Indiana, Illinois;New York, New Jersey, Florida, you output:

The blank map image is available in SVG and PNG formats. For your convenience, here is a list of all 50 states in alphabetical order

This is a code-golf and graphical-output challenge. Output must be as a SVG or image file. Simply displaying the output on the screen is not enough. Input must be taken from STDIN or by reading a text file. I am flexible with how you format the input, although it should contain the full names of each state, with red (Republican) states listed first and blue (Democratic) states second. Any two distinct shades of red and blue are acceptable for the coloring. Of course, you can have the blank map image in the same folder as your program with whatever file name you want.

Accuracy Criteria

If your output is a raster file, it must be at least 800px by 495px, and the lines should not deviate from the result of scaling up the SVG to the same size by more than 1.5 pixels. If your output is a vector file, the lines should not deviate from the SVG by more than 1.5 pixels when both are scaled to 800px by 495px.

Bonus!

Ben is trying to cut down dependence on foreign libraries, and is now offering a -50% bonus to anyone who uses only a raster graphics version of the map as input and creates their own algorithm for region detection. Ultimately, it is my judgment that determines whether your approach counts as "writing your own" algorithm.

Good Luck!

Processing,  425 bytes (259 bytes + 1 +165 byte file)

Code:

size(959,593);String[]a=loadStrings("a"),b=loadStrings("b");PShape m=loadShape("M.svg");m.disableStyle();for(int i=0;i<51;i++){fill(255);int r=0;for(String j:a){if(j.isEmpty())r++;if(j.contains(b[i]))fill(r>0?#0000FF:#FF0000);}shape(m.getChild(i));}save("m");

Blank map should be named "M.svg" and stored in a folder called /data (all other files are in the same folder as the program.)

Input File ("a"):

Mississippi
California
Connecticut

Delaware
Florida
Wyoming
Hawaii

Key File ("b"): http://pastebin.com/0pNufAH9

Output ("m.tif"):

Ok, here is my try at my own challenge. Some notes:

The output map looks different from the input map in the following ways

The input map had grey filling on a transparent background. The output has white filling on a gray background. I think this should be allowed, because white, gray, and transparency are all neutral.
The output map is missing the lines around Hawaii and Alaska that the input had. Once again, I think this is ok because the lines are not a significant part of the map.

The program uses an external file to hold keys. According to this meta post, I just need to add 1 byte for one additional file.

If anyone has any discrepancies with my self-adjudication of my code, feel free to leave a comment.

Also, if anyone is curious about trying this challenge in Processing, it supports both reading SVG files into PShape's, as well as parsing SVG files as XML.


Inverse-quotes-quine, inverted (pt. 2) Based on a comment by Jo King on my previous question (called 'Inverse-quotes-quine'), I present this new question. The rules are similar, but just, the opposite:

If your program is run normally, all of the code not in the speech marks (" - double quotes) should be printed.
If your program is wrapped in double quotes (in turn inverting the speech marks), the code that is normally n̶o̶t̶ in quotes should be printed.

E.g:

Let's say you have the following code:

fancyStuff("myCode"); "I like".isGreat();

If I run it, I would expect an output of:

fancyStuff(
);
.isGreat();

However, if I wrapped it in quotes, I would get:

"fancyStuff("myCode"); "I like".isGreat();"

When this code is run, the expected output would be:

myCode
I like

Obviously, the above example is not a functional response in any language. Your job is to write the code that performs in this way.

Rules

Standard loopholes apply.
The printed values, in both quoted and unquoted forms, must be non-empty, or consist solely of whitespace. This also means that all programs must include at least one set of quotes.
However, trailing/preceeding whitespace is allowed.
The quoted and unquoted strings must print different results.
No looking at your own code, required file names, etc.
Unmatched quotes are disallowed
If there are multiple strings, they can either be printed as newlines (as in the example), or in some other human-readable way - no arrays or objects
This is code-golf, so shortest answer in bytes wins.

Python 2, 32 bytes

''*2;print"''*2;print"''*2;print

Try it online!

Based on my initial solution for the other variant of this puzzle.


GolfScript, 39 characters
35,{2+'6 * 9 = '54@base{.9>7*+48+}%n+}/

Result can be seen here.


Test if a string can be made with substrings! Given a string s and an array/list l, determine whether or not s can be made with parts from l.

For example, if the string is "Hello, world!" and the list is [' world!', 'Hello,'], then the program/function should return a truthy value, because you can arrange the list to form the string. The following list would also return a truthy value: ['l', 'He', 'o, wor', 'd!']. Just imagine the 'l' filling in where it needs to in he string. So yes, you may repeat elements of the list to form the string. If it cannot form the string, it should return a falsy value. Standard methods of IO, standard loopholes apply.

Test cases:

Input (In the form of s, l)
Output (1 if possible, 0 if impossible)

"Hello, world!", ["l", "He", "o, wor", "d!"]
1

"la lal al ", ["la", " l", "al "]
1

"this is a string", ["this should return falsy"]
0

"thi is a string", ["this", "i i", " a", " string"]
0

"aaaaa", ["aa"]
0

"foo bar foobar", ["foo", "bar", " ", "spam"]
1

"ababab", ["a","ba","ab"]
1

"", ["The string can be constructed with nothing!"]
1

Brachylog, 8 bytes
~c¬{∋¬∈}

Try it online!
This is really slow. Took about 37 seconds for the "Hello, world!" test case on my PC, and timed-out on TIO.
This takes the string through the Input variable and the list through the Output variable
Explanation
             String = ?, List = .

             It is possible to find…
~c           …a deconcatenation of ?…
  ¬{   }     …such that it is impossible…
    ∋¬∈      …that an element of that deconcatenation is not an element of .


A sequence of sums of integers that aren't in the sequence Background

Consider a sequence defined as follows:

The first element is 0;
The second element is 4;
From the third element onwards, its value can be calculated by:

Taking the set of integers from 0 up to the previous element of the sequence (inclusive or exclusive, it doesn't matter);
Removing any integers that have already appeared earlier in the sequence from the set;
Adding together the remaining elements of the set; that's the value you want.

Interestingly, this sequence doesn't seem to be on OEIS yet.

The task

Write a program or function which takes an integer n as input, and outputs the nth element of the sequence.

Test cases

The first few elements of the sequence are:

0
4
6 (1+2+3)
11 (1+2+3+5)
45 (1+2+3+5+7+8+9+10)
969 (1+2+3+5+7…10+12…44)
468930 (1+2+3+5+7…10+12…44+46…968)

Clarifications

Your program should in theory be able to handle arbitrary n if run on a variant of your language that has unboundedly large integers and access to an unlimited amount of memory. (Languages without bignums are unlikely to be able to get much beyond 468930, but that's no excuse to hardcode the answers.)
You may choose either 0-based or 1-based indexing for the sequence (e.g. it's up to you whether n=1 returns the first element, n=2 the second element, and so on; or whether n=0 returns the first element, n=1 the second element, and so on).
There are no requirements on the algorithm you use, nor on its efficiency; you may implement the definition of the sequence directly (even though it's really inefficient), and you may also implement a different algorithm which leads to the same results.

Victory condition

This is code-golf, so the shortest correct program, measured in bytes, wins.

Jelly, 13 12 9 bytes

rSạo4¥ð@¡

Uses 0-based indexing.

Try it online!

How it works

rSạo4¥ð@¡  Main link. No arguments. Implicit argument: 0

      ð    Collect everything to the left into a chain and start a new, dyadic one.
           The arity of the first chain is unknown at this point, as it isn't
           prefixed by ø, µ, or ð.
       @   Swap the arguments of the first chain. Swapping  arguments is only
           implemented for dyadic links, so this makes the chain dyadic.
        ¡  Read an integer n from STDIN and execute the chain n times. Taking the
           argument swap into account, the chain is executed first with 0 as left
           and right argument, then with the previous right argument as left
           argument and the previous return value as right argument.
           The return value of the last call is the return value of the quicklink
           and becomes the implicit output.

           Let's call the left argument x and the right argument y.
r            Range; yield [x, ..., y].
 S           Compute the sum of all integers in the range.
     ¥       Convert the two atoms to the left into a dyadic chain, and call that
             chain with arguments x and y.
   o4          Take the logical OR of x and 4, replacing a 0 with 4 and leaving
               positive integers untouched.
  ạ          Take the absolute difference of the sum to the left and the result of
             the logical OR to the right.


Cycle my input please Input

A string s of printable ASCII characters, newlines, and spaces (0x20 ( ) to 0x7E (~)), and a non-negative integer n.

Challenge

To write a program that outputs either another program, or s depending on n. If n = 1, Then your code should output code which outputs s. If n = 2, Your code should output code which outputs code which outputs s and so on.

All outputted code should be in the same language as the language of the original submission.

Test Cases

Format: s, n -> output
Assuming your submission is written in JavaScript:

No cycles, 0 -> No cycles
Hello, 1 -> console.log("Hello");
Cycle!, 3 -> console.log("console.log(\"console.log(\\\"Cycle!\\\")\")");
:), 3 -> console.log("console.log('console.log(`:)`)')");

Scoring

This is code-golf, so aim for shortest code in bytes.

Additional Rules

I/O format is flexible
Default rules and standard loopholes apply.
The output of your submission must be valid.
You can use any language, even if it was created after this challenge, as long as it wasn't created for the purpose of this challenge
This isn't a polyglot challenge. A JavaScript submission shouldn't output Ruby code.
Input is guaranteed to be valid as defined in the Input section

Validation

Here's a quick tip to test your answers:
For n=0, output=s
For n=1, eval(output)=s
For n=2, eval(eval(output))=s
Where n and s are inputs

R, 43 bytes

f=function(s,n)"if"(n,function()f(s,n-1),s)

Try it online!

Returns a zero-argument function that recursively calls f with n set to n-1. n successive function applications returns s.


Reverse Engineer Polling Statistics Introduction

Given a set of percentages of choices in a poll, calculate the minimum number of voters there must be in the poll to generate those statistics.

Example: What is your favorite pet?

Dog: 44.4%
Cat: 44.4%
Mouse: 11.1%

Output: 9 (minimum possible # of voters)

Specs

Here are the requirements for your program/function:

You are given an array of percentage values as input (on stdin, as function argument, etc.)
Each percentage value is a number rounded to one decimal place (e.g., 44.4 44.4 11.1).
Calculate the minimum possible number of voters in the poll whose results would yield those exact percentages when rounded to one decimal place (on stdout, or function return value).
Bonus: -15 characters if you can solve in a "non-trivial" way (i.e., doesn't involve iterating through every possible # of voters until you find the first one that works)

Example

>./pollreverse 44.4 44.4 11.1
9
>./pollreverse 26.7 53.3 20.0
15
>./pollreverse 48.4 13.7 21.6 6.5 9.8
153
>./pollreverse 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 99.6
2000
>./pollreverse 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 98.7
667
>./pollreverse 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 98.7
2000
>./pollreverse 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 97.8
401

Scoring

This is code-golf, so shortest possible characters wins.  Any bonuses are further subtracted from the total character count.


Integer square root of integer Problem:

In your choice of language, write the shortest function that returns the floor of the square root of an unsigned 64-bit integer.

Test cases:

Your function must work correctly for all inputs, but here are a few which help illustrate the idea:

               INPUT ⟶ OUTPUT

                   0 ⟶  0
                   1 ⟶  1
                   2 ⟶  1
                   3 ⟶  1
                   4 ⟶  2
                   8 ⟶  2
                   9 ⟶  3
                  15 ⟶  3
                  16 ⟶  4
               65535 ⟶ 255
               65536 ⟶ 256
18446744073709551615 ⟶ 4294967295

Rules:

You can name your function anything you like. (Unnamed, anonymous, or lambda functions are fine, as long as they are somehow callable.)
Character count is what matters most in this challenge, but runtime is also important. I'm sure you could scan upwards iteratively for the answer in O(√n) time with a very small character count, but O(log(n)) time would really be better (that is, assuming an input value of n, not a bit-length of n).
You will probably want to implement the function using purely integer and/or boolean artithmetic. However, if you really want to use floating-point calculations, then that is fine so long as you call no library functions. So, simply saying return (n>0)?(uint32_t)sqrtl(n):-1; in C is off limits even though it would produce the correct result. If you're using floating-point arithmetic, you may use *, /, +, -, and exponentiation (e.g., ** or ^ if it's a built-in operator in your language of choice, but only exponentiation of powers not less than 1). This restriction is to prevent "cheating" by calling sqrt() or a variant or raising a value to the ½ power.
If you're using floating-point operations (see #3), you aren't required that the return type be integer; only that that the return value is an integer, e.g., floor(sqrt(n)), and be able to hold any unsigned 32-bit value.
If you're using C/C++, you may assume the existence of unsigned 64-bit and 32-bit integer types, e.g., uint64_t and uint32_t as defined in stdint.h. Otherwise, just make sure your integer type is capable of holding any 64-bit unsigned integer.
If your langauge does not support 64-bit integers (for example, Brainfuck apparently only has 8-bit integer support), then do your best with that and state the limitation in your answer title. That said, if you can figure out how to encode a 64-bit integer and correctly obtain the square root of it using 8-bit primitive arithmetic, then more power to you!
Have fun and get creative!

CJam, 17 (or 10) bytes

{_1.5#\/i}

Try it online by verifying the test cases:

[0 1 2 3 4 8 9 15 16 65535 65536 18446744073709551615]{_1.5#\/i}%N*

It won't pass the last test case because of rounding issues, but since 18446744073709551615 isn't an Integer in CJam (it's a Big Integer), we're still good, right?

If not, the following (and slightly longer) code will correct those errors:

{__1.5#\/i_2#@>-}

Not the shortest solution anymore, but faaast.

How it works

__    " Duplicate the integer twice. ";
1.5#  " Raise to power 1.5. Note that, since 1.5 > 1, this doesn't break the rules. ";
\     " Swap the result with the original integer. ";
/     " Divide. ";
i     " Cast to integer. ";
_2#   " Push square of a copy. ";
@     " Rotate the orginal integer on top of the stack. ";
>-    " If the square root has been rounded up, subtract 1. ";


Smallest unseen, but no sharing digits! Challenge

Here at PPCG, we sure do like our sequences, so here's a fun another one.

Let's define a(n) as being the smallest non-negative integer X that is not equal to any a(k) (0 < k < n), and a(n-1) and X do not share any decimal digits. a(0) = 0

Given an input n > 0, output such a(n).

For example, for input n = 13, we have a(13) = 20, since a(12) = 11 and 20 is the smallest non-negative integer we haven't seen yet that doesn't share any decimal digits with 11.

Sequence

Here are the first 20 terms to get you started. This is sequence A067581 on OEIS.

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 22, 11, 20, 13, 24, 15, 23, 14, 25

Rules

The input and output can be assumed to fit in your language's native integer type.
The input and output can be given in any convenient format.
You can choose to either 0-index, as I am here in my examples, or 1-index for your submission. Please state which you're doing.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Python 2, 85 bytes

-1 byte thanks to Dead Possum

n=0,
exec"i=0\nwhile set(`i`)&set(`n[-1]`)or i in n:i+=1\nn+=i,;"*input()
print n[-1]

Try it online!


One Bad Ternary Operator Deserves Another Today's Daily WTF quotes the following line of code...

FailSafe==0?'No technical alarms':((FailSafe&1)!=0&&(FailSafe&2)!=0&&(FailSafe&4)!=0&&(FailSafe&8)!=0?'Detection zones staying in a given state; Bad visibility;
Initialization; Bad configuration':((FailSafe&1)!=0&&(FailSafe&2)!=0&&(FailSafe&4)!=0?'Detection zones staying in a given state; Bad visibility; Initialization':
((FailSafe&1)!=0&&(FailSafe&2)!=0&&(FailSafe&8)!=0?'Detection zones staying in a given state; Bad visibility; Bad configuration':((FailSafe&1)!=0&&(FailSafe&4)!=0&&
(FailSafe&8)!=0?'Detection zones staying in a given state; Initialization; Bad configuration':((FailSafe&2)!=0&&(FailSafe&4)!=0&&(FailSafe&8)!=0?'Bad visibility;
Initialization; Bad configuration':((FailSafe&1)!=0&&(FailSafe&2)!=0?'Detection zones staying in a given state; Bad visibility':((FailSafe&1)!=0&&(FailSafe&4)!=0?'Detection
zones staying in a given state; Initialization':((FailSafe&1)!=0&&(FailSafe&8)!=0?'Detection zones staying in a given state; Bad configuration':((FailSafe&2)!=0&&
(FailSafe&4)!=0?'Bad visibility; Initialization':((FailSafe&2)!=0&&(FailSafe&8)!=0?'Bad visibility; Bad configuration':((FailSafe&4)!=0&&(FailSafe&8)!=0?'Initialization; Bad
configuration':((FailSafe&1)!=0?'Detection zones staying in a given state':((FailSafe&2)!=0?'Bad visibility':((FailSafe&4)!=0?'Initialization':((FailSafe&8)!=0?'Bad
configuration':'Unknown')))))))))))))))

Write some code that takes an integer value named FailSafe and returns the same string that the above code would produce from the same integer value.

The challenge is to rewrite that line, so "boilerplate" code is free, including any code that loads an integer value and outputs the string. Only the code that performs the above transformation from an integer to a string counts.
You may use a different name to "FailSafe" if you wish, as long as your chosen identifier has the same golf score.
No calling external resources to perform the lookup.
Normal code-golf rules apply.

Ruby, 210 characters
Similar to @Jan Dvorak's solution but a bit more functional and a bit shorter.
f=FailSafe
e=[f&1,f&2,f&4,f&8,1-f].zip(["Detection zones staying in a given state","Bad visibility","Initialization","Bad configuration","No technical alarms"]).map{|a,b|a>0&&b}-[!0]
e[0]||="Unknown"
e.join"; "


What's assignable to what? related

What's assignable to what?

In this challenge you will be given two types, A and B and determine if A is assignable to B, B is assignable to A, or neither.

The Type System

(I will use t to represent any type)

Basic Types

Basic types are represented by a single capital letter, such as X. They are basically classes.

X is assignable to Y if Y is either the same as, or a parent class of X.

Intersection Types

Intersection types are represented by intersect<X, Y>, and can have any number of types between the <'s (e.g. intersect<X, Y, Z, D, E>).

t is assignable to intersect<X1, X2... Xn> if t is assignable to all X.
intersect<X1, X2... Xn> is assignable to t if any X is assignable to t.

Union Types

Union types are represented by union<X, Y> and can have any number of types between the <'s (e.g. union<X, Y, Z, D, E>).

t is assignable to union<X1, X2... Xn> if t is assignable to any X.
union<X1, X2... Xn> is assignable to t if all X are assignable to t.

Input

You will receive as input:

The class hierarchy. You may choose the method of input for the class hierarchy. You can input a representation of a tree, or each type with a list of its parents, or anything else that accurately represents the class hierarchy.
Two types (input is flexible, as long as the notation is consistent you may receive these types however you like).

Output

You will output one of three consistent and distinct values, call them X, Y, and Z. Given two types A and B, output X if A is assignable to B, output Y if B is assignable to A and output Z otherwise (If A is assignable to B and B is assignable to A, you may output X, Y, both, or a fourth value).

Test Cases

Format:

# of types
[type, parents...]
[type, parents...]
Type a
Type b

2
[A,B]
[B]
A
B
--
A is assignable to B

3
[A,B,C]
[B,C]
[C]
intersect<A,C>
A
--
A is assignable to intersect<A,C>

3
[A,B,C]
[B,C]
[C]
union<A,C>
A
--
A is assignable to union<A,C>

3
[A,B,C]
[B,C]
[C]
intersect<B,C>
A
--
A is assignable to intersect<B,C>

3
[A,B,C]
[X,Y,Z]
[T,U,V]
intersect<union<A,T,X>,intersect<A,B>,Y>
intersect<T,C,X>
--
intersect<T,C,X> and intersect<union<A,T,X>,intersect<A,B>,Y> are not assignable to each other

1
[A]
A
A
--
A is assignable to A

3
[A,B,C]
[X,Y,Z]
[T,U,V]
intersect<A,intersect<A,B>,Y>
intersect<T,C,X>
--
intersect<T,C,X> and intersect<A,intersect<A,B>,Y> are not assignable to each other

2
[A]
[B]
A
B
--
B and A are not assignable to each other

3
[A,B,C]
[X,Y,Z]
[T,U,V]
intersect<union<A,X>,intersect<A,B>,Y>
intersect<T,C,X>
--
intersect<T,C,X> and intersect<union<A,X>,intersect<A,B>,Y> are not assignable to each other

Here is a link to a working ungolfed Java solution you can use for testing (it takes input in the same way as the test cases)

This is code-golf, so least bytes in each language wins for that language!

Python 3, 177 bytes

c is a dictionary of the parents of each type, a and b are the two expression to check. Types are represented by strings, while intersects and unions are represented by lists with of expressions, with the first element set to 0for intersect and 1 for union

Returns 0 if they are not assignable to each other, 1 if a is assignable to b, 2 if b is assignable to a and 3 if both are assignable to each other

lambda c,a,b:y(a,b,c)+2*y(b,a,c)
y=lambda a,b,c:(b in c[a]or a==b if b[0]in c else[all,any][b[0]](y(a,x,c)for x in b[1:]))if a[0]in c else[any,all][a[0]](y(x,b,c)for x in a[1:])

Try it online!


Prime counting function Introduction
The Prime Counting Function, also known as the Pi function \$\pi(x)\$, returns the amount of primes less than or equal to x.
Challenge
Your program will take an integer x which you can assume to be positive, and output a single integer equal to the amount of primes less than or equal to x. This is a code-golf challenge, so the winner will be the program with the fewest bytes.
You may use any language of your choosing provided that it existed before this challenge went up, but if the language has a built-in prime-counting function or a primality checking function (such as Mathematica), that function cannot be used in your code.
Example Inputs
Input:
1
Output:
0
Input:
2
Output:
1
Input:
5
Output:
3
A000720 - OEIS

05AB1E, 3 bytes

!fg

This assumes that factorization built-ins are allowed. Try it online!

How it works

!    Compute the factorial of the input.
 f   Determine its unique prime factors.
  g  Get the length of the resulting list.


Find the nth base-b digit of (b^k-1)^-2 Task
Your task is simple. Write a program or function which takes three positive integer arguments \$n\$, \$k\$, and \$b\$ in any order, such that \$2 ≤ b ≤ 36\$, and returns or outputs the nth (1-indexed) base-\$b\$ digit after the decimal point of the rational number (\$b^k-1)^{-2}\$.
The output must be correct for \$n\$ and \$b^k\$ up to the largest integer value your language of choice can natively represent. This will most likely mean that you cannot depend on built-in floating point representations to exactly represent the base-\$b\$ expansion of the number.
Fortunately, this class of numbers has a rather nice property [Spoiler Alert!]: https://www.youtube.com/watch?v=daro6K6mym8
Rules

Base conversion built-ins are permitted.
Built-in spigot functions capable of indexing digits of exactly represented real numbers are forbidden.
The digits for base \$b\$ are the first \$b\$ symbols in the string 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ or alternately 0123456789abcdefghijklmnopqrstuvwxyz. Your choice.

Winning
This is code golf. Shortest solution in bytes wins.
Test Cases
(You need not be able to correctly handle all of these if \$n\$ or \$b^k\$ overflows your integer datatype.)
Input (n,k,b)               Output
9846658,3,31                5
789234652,4,10              4
4294967295,17,2             1
4294967254,72,15            B
137894695266,3,30           H
184467440737095595,6,26     L
184467440737095514,999,36   T

APL (Dyalog Extended), 31 bytes

(⎕D,⎕A)⊃⍨⊃⎕⌽¯1⌽,⍉⎕(⊣⊤⍳⍤*~*-2⍨)⎕

Try it online!
A full program that takes numbers from stdin in the order of k, b, n. n being 1-based cost me 3 bytes ¯1⌽.
How it works
The main mathematical trick is well explained in Neil's answer. The gist is that the repeating part of the base-b representation consists of length-k base-b digits of 0..b^k-1, except b^k-2.
This answer implements it very literally: list all repeating base-b digits, cyclically fetch nth digit from it, and convert it to 0-9A-Z. Cyclic indexing uses ngn's trick.
⎕(...)⎕     ⍝ Take k (the right) and b (the left) from stdin
  ⍳⍤*~*-2⍨  ⍝ Create a list of 0..b^k-1, and remove the number b^k-2
  ⊣⊤        ⍝ Convert these numbers into base-b digits into columns
,⍉          ⍝ Transpose and flatten to get the repeating base-b digits
⊃⎕⌽¯1⌽      ⍝ Take n from stdin and get the nth digit cyclically
(⎕D,⎕A)⊃⍨   ⍝ Convert the number to the corresponding char in 0-9A-Z


Python 3, 69 68 bytes

-1 byte thanks to @WheatWizard

i=0
for c in input():
 i+=c==';'
 if'#'==c:print(end=chr(i%127));i=0

Try it online!


Implement an Over function Over is a higher-order function in multiple languages such as APL (⍥). It takes 2 functions and 2 values as arguments, applies the first function to both values, then applies the second to their result. For example, using ⍥ to represent Over:
1 ²⍥+ 2

We would first calculate ² of each argument: 1² = 1 and 2² = 4. We then apply + to these, yielding 5.
You are to take as input:

A black box function, \$f\$, which takes an integer as input and returns an integer
A black box function, \$g\$, which takes 2 integers as input and returns a single integer
2 integers, \$a\$ and \$b\$.

You should then return the result of \$g(f(a), f(b))\$.
If you have a builtin specifically for this (e.g. APL's ⍥, Husk's ¤ etc.), consider including a non-builtin answer as well. It might even get you an upvote :)
You may input and output in the most convenient format for your language, and in any convenient method, including taking \$a\$ and \$b\$ as a pair/list/tuple [a, b]
For the sake of simplicity, you can assume that the black-box function will always input and output integers within your language's integer domain, and that \$a\$, \$b\$  and the output will be with your language's integer domain.
This is code-golf, so the shortest code in bytes wins
Test cases
f
g
a, b -> out

f(x) = x²
g(x,y) = x - y
-2, 2 -> 0

f(x) = φ(x)     (Euler totient function)
g(x,y) = 2x + y
5, 9 -> 14

f(x) = x³-x²-x-1
g(x,y) = y⁴-x³-y²-x
-1, -1 -> 22

f(x) = x
g(x,y) = x / y   (Integer division)
-25, 5 -> -5

Haskell, 12 bytes

f?g=(.f).g.f

Try it online!
Haskell was made for this.
Let's unpack it:
(f?g) x y =
(((.f).g.f) x) y =
(.f)(g (f x)) y =
((g (f x)).f) y =
g (f x) (f y)

If you're wondering what happens if we make this further pointfree in f and g, we can express (?) as:
\f->((.f).).(.f)
(.).(.).flip(.)<*>flip(.)

The flipped version of ? that's invoked as g?f is a little nicer:
((.).flip(.)<*>).(.)

(I used pointfree.io for these.)
Test cases copied from Unrelated String.

Haskell, 10 bytes

(.map).(.)

Try it online!
If the input [x,y] is a two-element list, and the binary function g accepts its two arguments as such a list. The main function takes is arguments as g then `f.


Classic Proof Fallacy The Background

So, we all know the classic proof that goes like this:

a = b
a² = ab
a² - b² = ab - b²
(a-b)(a+b) = b(a-b)
(a+b) = b
b+b = b
2b = b
2 = 1   (Ha ha!)
Of course, the mistake is that you can't divide by 0. Since a = b, a - b = 0, so there was a hidden division by 0.

The Challenge

You have to replicate this proof. First, declare two integers a and b (it doesn't matter what you call them) that equal. Then declare aMod and bMod to be modifiable versions of a and b and initially equal to a and b, respectively. You must multiply them both by a, then subtract b*b from both of them. You must then divide by a - b and then divide them by b (or a) to get. Then, print out aMod and bMod with an equal sign between them.

The Underhanded

Of course, since you declared a and b to equal, a - b = 0, and dividing by 0 causes an error. So you must creatively fake it. Also, because you are trying to replicate the proof, the result on all the operations on aMod and bMod must not equal when printed. They don't have to equal exactly 2 and 1, just two numbers that don't equal.

Here is an example:

#include <iostream>
#define subtract(a, b) a - b

using namespace std;
int main()
{
    int a = 4, b = 4;
    int a_2 = a, b_2 = b;

    a_2 *= a;
    b_2 *= b;

    a_2 -= b * b;
    b_2 -= b * b;

    a_2 = a_2 / subtract(a, b);
    b_2 = b_2 / subtract(-b, -a); // a - b == (-b) - (-a)

    a_2 /= a;
    b_2 /= a;

    cout << a_2 << " = " << b_2 << " because I did the same operations on both of them.";

    return 0;
}

Maybe not the best one, but it illustrates the point.

Bonus Underhanded

Instead of printing the equals sign, you can print out just the two variables (aMod and bMod), and then have code that appears to compare the two variables for equality but in actuality lies that they equal (and prints some form of true).

Remember, this is a popularity contest, so highest number of upvotes wins.
Also, a new version of mathematics called Mathematics 2.0 has made use of standard loopholes automatically invalidate a proof.

JavaScript
var a=3,b=3,a2=3,b2=3
[a2,b2]=[a2*a,b2*a]
[a2,b2]=[a2-b*b,b2-b*b]
[a2,b2]=[a2/(a-b),b2/(a-b)]
console.log([a2/a,b2/a])

Output:
[1, NaN]

Note that 0/0 = NaN
Hint

 Try add some semicolons.
 This program is actually var a=3,b=3,a2=3,b2=3[a2,b2]=...=[a2/(a-b),b2/(a-b)];console.log([a2/a,b2/a]).
 And the NaN is [3/0,undefined/0]/3.


Tips for golfing in LiveScript What general tips do you have for golfing in LiveScript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to LiveScript (e.g. "remove comments" is not an answer). Please post one tip per answer.

Take advantage of curried functions and Prelude.ls

If the function is already curried, it can be much shorter overall. Also, Prelude.ls is the standard library, and its functions are often very useful. This means, unless otherwise specified, this library is 100% allowed. Examples:

f=->[1 to &0].reduce (*) # space required
f=->product [1 to &0]

s=(.reduce (+))
s=sum                    # better yet, avoid defining this when possible

d=(.map (*2))
d=map (*2)               # Sometimes even shorter than native methods

r=->&0.reduce (-&1-)
r=->fold1 (-&1-),&0      # Equal if starting value is required.

a.=sort!
a=sort a                 # sometimes the same length

a.=sort ->&1.length-&0.length # space before arrow required
a.=sort over (-),(.length)    # slightly more functional
a=sortBy (.length)            # specific builtin, always prefer CamelCase


Help me compress this song in my country we have a children's song which goes like this:
Priletela muha na zid, muha na zid, muha na zid.
Priletela muha na zid,
muha na zid.

Pralatala maha na zad, maha na zad, maha na zad.
Pralatala maha na zad,
maha na zad.

Preletele mehe ne zed, mehe ne zed, mehe ne zed.
Preletele mehe ne zed,
mehe ne zed.

Prilitili mihi ni zid, mihi ni zid, mihi ni zid.
Prilitili mihi ni zid,
mihi ni zid.

Prolotolo moho no zod, moho no zod, moho no zod.
Prolotolo moho no zod,
moho no zod.

Prulutulu muhu nu zud, muhu nu zud, muhu nu zud.
Prulutulu muhu nu zud,
muhu nu zud.

As you can see, it contains a bit of redundant information. So I was wondering if it could be compressed a bit.
This is code golf — shortest code wins.

05AB1E, 54 52 bytes
Thanks to Kevin Cruijssen for -2 bytes!
T"ÿ, 0, 0.
ÿ,
0.
"T.•ý‹¨ΣªßˆTδ}vØ#•.ª'x¡‡žMv=žMyÞ‡}?

Try it online!
Commented:
T                         # push 10
 "ÿ, 0, 0.\nÿ,\n0.\n"     # push string literal "10, 0, 0.\n10,\n0.\n"
  T                       # push 10 again
   .•ý‹¨ΣªßˆTδ}vØ#•       # push compressed string "priletela xmuha na zid"
    .ª                    # sentence case => "Priletela xmuha na zid"
      ‛x¡                 # split on 'x'  => ["Priletela ", "muha na zid"]
         ‡                # replace every digit of 10 with the corresponding list entry in the string literal
                          # this is the first verse
          žM              # push the vowels "aeiou"
            v      }      # for y in vowels:
             =            #   print the last verse without removing it from the stack
              žM          #   push the vowels
                yÞ        #   the infinite list of the vowel y
                  ‡       #   replace every vowel with y
                    ?     # print the last verse without a trailing newline

more obfuscated and a lot slower 52-byter:
•nöðrb•ØTz… ,
«ÅвJT.•ý‹¨ΣªßˆTδ}vØ#•.ª'x¡‡žMv=žMyÞ‡}?

Don’t try it online!
•nöðrb•              # push compressed integer 211262272027
       Ø             # push the 211262272028th prime 5996494318979 (slow)
        Tz           # push 1/10
          … ,\n      # push string " ,\n"
               «     # concatenate to "0.1 ,\n"
                Åв   # convert the prime into that custom base
                  J  # join from list of chars into a string
                     # this generates the same string as T"ÿ, 0, 0.\nÿ,\n0.\n" above


Electoral votes from state name Given a the name of a state of the United States as a string (with case), return the number of votes the state has in the Electoral College. Write a full program or function, and take input and output through any default I/O method.

A list of all inputs and outputs (source):

[['Alabama', 9], ['Alaska', 3], ['Arizona', 11], ['Arkansas', 6], ['California', 55], ['Colorado', 9], ['Connecticut', 7], ['Delaware', 3], ['Florida', 29], ['Georgia', 16], ['Hawaii', 4], ['Idaho', 4], ['Illinois', 20], ['Indiana', 11], ['Iowa', 6], ['Kansas', 6], ['Kentucky', 8], ['Louisiana', 8], ['Maine', 4], ['Maryland', 10], ['Massachusetts', 11], ['Michigan', 16], ['Minnesota', 10], ['Mississippi', 6], ['Missouri', 10], ['Montana', 3], ['Nebraska', 5], ['Nevada', 6], ['New Hampshire', 4], ['New Jersey', 14], ['New Mexico', 5], ['New York', 29], ['North Carolina', 15], ['North Dakota', 3], ['Ohio', 18], ['Oklahoma', 7], ['Oregon', 7], ['Pennsylvania', 20], ['Rhode Island', 4], ['South Carolina', 9], ['South Dakota', 3], ['Tennessee', 11], ['Texas', 38], ['Utah', 6], ['Vermont', 3], ['Virginia', 13], ['Washington', 12], ['West Virginia', 5], ['Wisconsin', 10], ['Wyoming', 3]]

Any other input is undefined behavior. This is code-golf, so the shortest solution in bytes wins.

Hint: You probably shouldn't store all of the state names.

If you're solving this challenge with a builtin, please also write a solution without, for the sake of an interesting answer.

Python 3, 137 bytes

lambda s:b"2F$&#+*&4#(#'*&$++&''0+)-/ &)$# #(0*W% *&4)$= ,   %.# = %#$"[sum(b'!!E$/!5.!!!&#"!!1_&!!$#<!./'[ord(c)%32]-32for c in s)-4]-32

Although not required by the challenge, this accepts case-insensitive state names. I computed parts of this hash function with GPerf.


Is the matrix centrosymmetric... and so is the code? Defintion

A centrosymmetric matrix is a square matrix that is symmetric about its center. More rigorously, a matrix \$A\$ of size \$n \times n\$ is centrosymmetric if, for any \$i,\: j \in ([1, n] \cap \mathbb{Z})\$ the following relation is satisfied:
$$A_{i,\:j}=A_{n+1-i,\:n+1-j}$$

Examples of such matrices

Here is an illustration of the symmetry of a matrices like these (borrowed from the aforementioned Wikipedia article):

An even-side-length (\$4\times 4\$) centrosymmetric matrix:

$$\left(\begin{matrix}
1 & 2 & 3 & 4 \\
5 & 6 & 7 & 8 \\
8 & 7 & 6 & 5 \\
4 & 3 & 2 & 1\end{matrix}\right)$$

And an odd-side-length (\$3\times 3\$) one:

$$\left(\begin{matrix}
1 & 2 & 3 \\
5 & 6 & 5 \\
3 & 2 & 1\end{matrix}\right)$$

Task and Specs

Given a square matrix of size at least \$2\$, output one of two distinct and consistent values, deciding whether the matrix is centrosymmetric or not. You can assume that the matrix will consist entirely of positive integers.

However, your code must also be centrosymmetric. That is, it must be a program / function (or equivalents) consisting of \$n\$ lines, each of which containing \$n\$ bytes in your language's encoding, and must satisfy the definition given above, but with bytes instead of positive integers. Your submission's score will be the value of \$n\$, with a lower \$n\$ being better.

You can take input and provide output through any standard method and in any reasonable format, while taking note that these loopholes are forbidden by default. You may (optionally) choose to take the size, \$n\$, as input too (unless you take input as a 1D list, in which case you may only take \$n^2\$ as additional input).

Test cases

Truthy:

[[1, 2], [2, 1]]
[[1, 2, 3], [5, 6, 5], [3, 2, 1]]
[[10, 5, 30], [2, 6, 2], [30, 5, 10]]
[[100, 100, 100], [100, 50, 100], [100, 100, 100]]
[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]]
[[3, 4, 5, 6, 7], [5, 6, 7, 8, 9], [3, 2, 10, 2, 3], [9, 8, 7, 6, 5], [7, 6, 5, 4, 3]]

Falsy:

[[1, 2], [1, 2]]
[[1, 2, 10], [5, 6, 5], [11, 2, 1]]
[[14, 5, 32], [2, 6, 2], [30, 5, 16]]
[[19, 19, 19], [40, 50, 4], [19, 19, 19]]
[[1, 2, 20, 4], [7, 6, 7, 8], [8, 7, 6, 6], [3, 3, 2, 1]]
[[3, 4, 5, 6, 7], [5, 6, 7, 8, 9], [4, 5, 10, 4, 5], [5, 6, 7, 8, 9], [3, 4, 5, 6, 7]]

JavaScript (ES6), size 12 11 9

All versions return false for centrosymmetric or true for non-centrosymmetric.

1-dimensional array + length, size 9 (89 bytes)

Takes input in currying syntax (length)(array), where array is 1-dimensional.

w=>a=> //
a.some //
(v=>v- //
a[--w])//
/////////
//)]w--[a
// -v>=v(
// emos.a
// >=a>=w

Try it online!

Matrix + width, size 11 (131 bytes)

Takes input in currying syntax (width)(matrix).

/**/w=>a=>a
.some(r=>r.
some(v=>v-a
[y][w-++x],
x=!y--),y=w
);'*/'/*';)
w=y,)--y!=x
,]x++-w[]y[
a-v>=v(emos
.r>=r(emos.
a>=a>=w/**/

Try it online!

Payload

w => a => a.some(r => r.some(v => v - a[y][w - ++x], x = !y--), y = w)

Container

/**/CODE;'*/'/*';EDOC/**/

Matrix only, size 12 (155 bytes)

This is my original solution, which computes the width of the matrix by itself.

/**/a=>a[w=a
.length-1,s=
'some']((r,y
)=>r[s]((v,x
)=>v-a[w-y][
w-x]))////*/
/*////))]x-w
[]y-w[a-v>=)
x,v((]s[r>=)
y,r((]'emos'
=s,1-htgnel.
a=w[a>=a/**/

Try it online!

How?

We need a few critical tokens that cannot be split:

some
length
)=>

Line-feeds may be inserted almost anywhere else.

The unrolled payload code reads as:

a => a[w = a.length - 1, s = 'some']((r, y) => r[s]((v, x) => v - a[w - y][w - x]))

and is wrapped inside the following structure:

/**/CODE////*/

which, once reversed, becomes a valid block comment:

/*////EDOC/**/


Minus, Plus, Times, Exponentiation? This is a CMC (chat mini challenge) that I posted in our chatroom, The Ninteenth Byte, a bit ago.

The Challenge

Given a positive integer x, depending on the last 2 bits of x, do the following:

x & 3 == 0: 0
x & 3 == 1: x + x
x & 3 == 2: x * x
x & 3 == 3: x ^ x (exponentiation)

Input/Output

Single Integer -> Single Integer

A trailing newline is permitted in the output. No other whitespace is permitted.

Testcases

input       output
    1            2
    2            4
    3           27
    4            0
    5           10
    6           36
    7       823543
    8            0
    9           18
   10          100
   11 285311670611
   12            0

This is a code-golf challenge, so the shortest code wins!

Jelly, 8 bytes

ị“+×*_”v

Try it online!

How it works

Firstly, notice that x&3 is equivalent to x%4, where % is modulo. Then, since Jelly uses modular indexing (a[n] == a[n+len(a)]), so we don't even need to deal with that.

Then:

If x%4==0, return x_x (subtraction) (for consistency);
If x%4==1, return x+x;
If x%4==2, return x×x(multiplication);
If x%4==3, return x*x(exponentiation)

Note that Jelly uses 1-indexing, so the subtraction "_" is moved to the end.

ị“+×*_”v  example input: 10
ị“+×*_”   index 10 of the string “+×*_”, which gives "×"
       v  evaluate the above as a Jelly expression,
          with 10 as the argument, meaning "10×" is the
          expression evaluated. The dyad "×" takes the
          second argument from the only argument, effectively
          performing the function to itself.


Compiling English for your Boss Your boss has recently learned of this interesting programming language called English. He has had this "revolutionary" idea, he wants to code with you to double code production rates! Since he is not a tech savvy, he wants you to write a compiler for it so that he can code too!

Now, you are an evil lazy programmer and obviously will not write a program to compile this ridiculously complex language. Instead, you are going to make sure there is always an error in your boss's code, so that he never gets to the actual compilation and is stuck fixing grammar errors instead of coding.

The challenge is to write a program that can be run from the terminal, and accepts a file path as an argument. The program has to:

modify the file input by introducing a typo.
Pretend to fail compilation due to encountering the typo you introduced.
Running the program on copies of the same file should not introduce the same typo twice in a row.

To illustrate the challenge, running your program on this file:

Take an array as input.
Sort the array.
Output the array.

should output something along the lines of

Error on line 1:
'Take an arqay as input.'
         ^
arqay is not a valid identifier.

and the file that you told the program to compile should now look like:

Take an arqay as input.
Sort the array.
Output the array.

Here are some more details on the specs of the program:

Your program is allowed to assume that swapping any character in the program your boss inputs for a different random character will cause a grammar error.
Your program should not use non alphabetical characters to create errors in your bosses code. Your boss would never use a number or symbol, and he would find out that something is afoot.
Your program should only introduce errors to the words in your boss's program. Do not change the spaces in the sentences, or the punctuation.
Your program should not alter the case of the program your boss tries to compile, meaning errors like arQay are invalid. This prevents errors like take instead of Take happening, or Array instead of array.
Your program should output the error by first stating what line the error is at:

Error on line <insert line number here>:

It should then print out the line with the error inside ' symbols. On the next line it should place a ^ symbol under the word with the error, and finally it should have some text describing the error (this part is up to you, you can say whatever you want there as long as it describes an error).

You can assume that the input file exists and it is not empty.
You can also assume the input file has no grammatical errors before you add one.

Bonuses:

-60 bytes if the errors your code introduces are not completely random, but typo-based as in this question.

-60 bytes for at least 5 different error messages, randomly alternating.

-60 bytes if your program has a 1 in 100 chance or less to output some demotivational message to your boss.

EDIT: The byte count of the messages do not count towards your score.
(Thanks to Martin Büttner for this good idea)

This is code-golf, shortest byte count wins. Please do not golf the error message content, your boss wont be happy if he can't understand the error messages, and will ask you to fix them for him.

TI-BASIC, 77 - 34 (error text) = 43
In case he wants to do in on his TI-83/84 calculator ;)
As standard for functions, file string should be in Ans so it can return and display the output.
Ans->Str1:If 1=inString(Ans,"A
Then:"B
Else:"A
End:Disp "ERROR ON LINE 1","'"+Ans+sub(Str1,2,-1+length(Str1))+"'"," ^ INVALID

Note that many tokens are one byte.


Generating BF-code with single purpose I'd like to see you create code (in any programming language) that output working BF (Brain***k) code. Your program have a single character input on stdin. The input should be one digit ("0", "1", "2", "3", "4", "5", "6", "7", "8" or "9").

Your code should output BF-code that when interpreted with a normal BF-interpreter outputs a 5*5 ascii version of the digit. The generated BF-code should not accept any input. The resulting output from the generated BF-code should be exactly this:

Input: '0'

Output BF-code that when interpreted generates the following output:

.---.
|  /|
| / |
|/  |
'---'

Input: '1'

Output BF-code that when interpreted generates the following output:

 .
/|
 |
 |
 '

Input: '2'

Output BF-code that when interpreted generates the following output:

.---.
    |
.---'
|
'---'

Input: '3'

Output BF-code that when interpreted generates the following output:

.---.
    |
 ---|
    |
'---'

Input: '4'

Output BF-code that when interpreted generates the following output:

.   .
|   |
'---|
    |
    '

Input: '5'

Output BF-code that when interpreted generates the following output:

.---
|
'---.
    |
'---'

Input: '6'

Output BF-code that when interpreted generates the following output:

.---
|
|---.
|   |
'---'

Input: '7'

Output BF-code that when interpreted generates the following output:

----.
   /
  /
 /
'

Input: '8'

Output BF-code that when interpreted generates the following output:

.---.
|   |
|---|
|   |
'---'

Input: '9'

Output BF-code that when interpreted generates the following output:

.---.
|   |
'---|
    |
'---'

The output from your code must be 10 different BF sourcecodes, one for each digit you input. Your program should not output all 10 BF in one run, it must ask for a digit and output BF code for that and only that ascii representation.

The BF-code requirements:

cell size: 8bit unsigned.
Overflow is undefined.
Array size: Max 30000 bytes (not circled)
It can contain other characters than [],.+-<>, but they should all be ignored. It is only - the standard BF code without any extensions that counts.
The EOF return 0
Linefeed is chr(10)

The winning answer will be the one that scores that lowest code using this formula:

your code in number of bytes * 5 + sum of the 10 generated BF codes

So keep in mind that you need to generate GOLF'd BF-code to score better.

Edit/Add (2011-08-25): You may omit or supply trailing spaces, as long as the digits displays the ASCII representation on a 80 column output, so the limit is 80 chars rows. Honor to the answers to generates exactly 5*5 output for all digits.


2-dimensional hue graph of array The Question

Given a two dimensional array, o[][], create a 2-dimensional graph such that o[xCoordinate][yCoordinate] is the hue of the point at (xCoordinate, yCoordinate), and the value and saturation are always 100. Let the hue go from -50 to 50, where -50 and 50 are 0 and 100 respectively.

Rules

You may use any language you wish
Lowest bytes wins
Include seperate byte amount for points taken off from extra

Extra

If you want extra points (or, less actually) you can include a snippit of code in the same language such that o[x][y] is equal to sin x · cos y, in less than 25 bytes more than your original snippit. Extra points removes 10 bytes from your score.

Example Language: 89 [79] (Extra: 113)

Mathematica: 68
Graphics@Raster@Reverse[List@@Hue[#/100]~ColorConvert~"RGB"&/@#&/@o]

Still figuring out the extra.


Build the Trinity Hall Prime Based on this challenge and this Math.SE question. Idea originally come from a Numberphile video. The goal is to reproduce the logic of Professor McKee when he builds this prime.
Your task is to build the Trinity Hall Prime, at a much lower scale. You are given a single number N greater than 2, representing the length of the prime we need.
Rules

N is decomposed into a rectangle W(idth) x H(eight). W and H must be close, so 12 is 4x3 and 16 is 4x4 with W >= H
The first line got only 8's
The next lines have 8's in the outer and 1's in the middle
Each lines have 2 more 1's and 2 less 8's than the previous, except if W is odd, then the second line have only one 1 in the middle
Once you got your emblem, find the first prime greater than the emblem.
2 <= N <= 16
This is ascii-art, so newlines must be part of the output.
This is code-golf, so shortest code, in bytes, wins.

Test cases:
I   Emblem    O
================
2   88        89

3   888       907

4   88        88
    11        19

6   888       888
    818       827

8   8888      8888
    8118      8133

9   888       888
    818       818
    111       159

10  88888     88888
    88188     88213

16  8888      8888
    8118      8118
    1111      1111
    1111      1159

Python 3, 194 bytes

n=int(input())
R=range
w=n//max(i*(i*i<=n>1>n%i)for i in R(1,n))
m=0
for i in R(n):m=m*10+1+7*(abs(i%w*2-w+1)//2*w>i-w)
while any(m%p<1for p in R(2,m)):m+=1
m=str(m)
while m:print(m[:w]);m=m[w:]

Try it online!

too slow for most inputs, especially x > 8

-6 bytes thanks to Jonathan Frech
-98 bytes thanks to Leaky Nun


Determine if an Array contains something other than 2 Take an array which consists of numbers or arrays, output if it only contains 2s.
Output should be a truthy or falsey value (Sorry if this destroys answers)
Truthy Test Cases
[2]
[2,2]
[[2],[2,2],2]
[]
[[],[]]

Falsey Test Cases
[1]
[22]
[2,2,2,1]
[[1,2],2]

Standard Loopholes Are forbidden.
Default IO rules apply.
Code-golf, Fewest bytes wins!

Python 2, 43 40 bytes

f=lambda l:l>=[]and all(map(f,l))or l==2

Try it online!

At time of posting this answer, it was still allowed per this meta consensus to output via throwing an error / not throwing an error. Therefore this answer at 26 bytes was valid:

f=lambda l:l==2or map(f,l)

Try it online!


Quixels - Quantum Pixels Introduction

A quixel is a quantum pixel. Similar to a classical pixel, it is represented with 3 integer values (Red, Green, Blue). However, quixels are in a super position of these 3 states instead of a combination. This super position only lasts until the quixel is observed at which point it collapses to one of three classical pixels; RGB(255,0,0), RGB(0,255,0) and RGB(0,0,255).

Specification

Representation

Each quixel is represented as an array of 3 integers between 0 and 255, r, g and b respectively.

Super Positions

Each quixel is in a super position between the Red, Blue and Green states represented by R, G and B respectively.

Observation

When each quixel is observed it collapses into one of the three states. The probability of each classical state is R = (r + 1) / (r + g + b +3), G = (g + 1) / (r + g + b + 3) and B = (b + 1) / (r + g + b + 3). This way each classical state always as a non-zero probability of showing up.

Input

The function or program should take a image of quixels. How it does this is flexible. A filename, using a multi-dimensional array, etc are all acceptable.

Output

The function or program should produce an image of classical pixels. The data structure for this produced image is also flexible. Note that all of the pixels should be one of these three: RGB(255,0,0), RGB(0,255,0) and RGB(0,0,255)
The output should not be deterministic; these are quantum pixels! The same input should result in different outputs.
If your language has no way of generating a random number, you can take random bytes as input

Scoring

This is code-golf so fewest bytes win.

Images

Mona Lisa by Leonardo da Vinci

Starry Night by Vincent van Gogh

Persistence of Memory by Salvador Dali

Teddy Roosevelt VS. Bigfoot by SharpWriter

Dyalog APL, 23 21 19 bytes

Takes table of (R, G, B) triplets.
Inspired by miles' algorithm
Returns table of indices into {(255, 0, 0), (0, 255, 0), (0, 0, 255)}. Horribly wasteful.
(?∘≢⊃⊢)¨(⊂⍳3)/¨⍨1+⊢

(
 ?∘≢ random index
 ⊃ selects
 ⊢ from
)¨ each of
(
 ⊂ the entire
 ⍳3 first three indices
)/¨⍨ replicated by each of
1+⊢ the incremented triplets
TryAPL!

Old version
Returns table of 0-based indices into {(255, 0, 0), (0, 255, 0), (0, 0, 255)}
{+/(?0)≥+\(1+⍵)÷3++/⍵}¨

{...}¨ for each quixel in the table, find the:
 +/ the sum of (i.e. count of truths of)
 (?0)≥ a random 0 < number < 1 being greater than or equal to
 +\ the cumulative sum of
 (1+⍵)÷ the incremented RGB values divided by
 3+ three plus
 +/⍵ the sum of the quixel
Note: Dyalog APL lets you chose between the Lehmer linear congruential generator, the Mersenne Twister, and the Operating System's RNG¹ ².
For example, the image:
┌──────────┬──────────┬───────────┬───────────┬─────────┐
│52 241 198│148 111 45│197 165 180│9 137 120  │46 62 75 │
├──────────┼──────────┼───────────┼───────────┼─────────┤
│81 218 104│0 0 255   │0 255 0    │181 202 116│122 89 76│
├──────────┼──────────┼───────────┼───────────┼─────────┤
│181 61 34 │84 7 27   │233 220 249│39 184 160 │255 0 0  │
└──────────┴──────────┴───────────┴───────────┴─────────┘

can give
┌─┬─┬─┬─┬─┐
│1│0│2│2│1│
├─┼─┼─┼─┼─┤
│2│2│1│1│2│
├─┼─┼─┼─┼─┤
│0│2│1│2│0│
└─┴─┴─┴─┴─┘

Notice how the three "pure" quixels collapsed to their respective colors.
TryAPL online!


Make a Math Competition Grader I enjoy participating in math competitions run by Mu Alpha Theta, a mathematics honor society in the United States. At competitions, I take a 30-question multiple choice test. There are five choices per question, labeled A through E.

My score on a test is four points for each correct answer, zero points for a question left blank, and negative one points for each wrong answer.

Write a program that grades a test according to the above scoring system. There should be two components to the input: an answer key followed by responses. Questions left blank are to be inputted as blank spaces. The first input must contain only the letters A-E (or a-e, your choice), and it can be assumed that there is no whitespace in the input. The second input must only contain blank spaces and the letters A-E (or a-e). Inputs not implementing 30-question tests must print Invalid test as output.

The output should be the grade or Invalid test.

Bonus

If your program prints the number right, number left blank, and number wrong after the final score as (aR bB cW), take off 20 bytes.

Sample input

CABBDCABECDBACDBEAACADDBBBEDDA    //answer key
CABEDDABDC BACDBBAADE  CBBEDDA    //responses

Sample output

No bonus

73

Bonus

73 (20R 3B 7W)

Standard rules apply. Shortest code in bytes wins.

Pyth, 53 51

?&!-sJ.z+d<G5&FqR30lMJ+sm?qFd4_1CJ/eJd"Invalid test

Try it online

The checks are done by seeing if the entire input contains any characters when all of the spaces and a-e are removed, and by checking if both strings have length 30.

The score calculation is done by zipping the two lines together, then by mapping each pair to: (letters are equal) ? 4 : -1. Then simply summing the values, and adding the number of spaces in the second line back to the score.


Brute-force the switchboard The other day, our team went to an escape room. One of the puzzles involved a board of six mechanical switches where you had to find the correct combination of on and off in order to unlock a box, somewhat like this:

-v-v-v-
-v-v-v-

Being developers, we decided it would be more efficient to try every single one of 2^6=64 combinations than actually solve the puzzle. So we assigned some poor guy to do some binary counting:

-v-v-v-
-v-v-v-

-v-v-v-
-v-v-^-

-v-v-v-
-v-^-v-

-v-v-v-
-v-^-^-

and so on.

The challenge
Write a program that, given the switches all in off position as a string formatted as above, generates all combinations of on and off in any order.

You can write either a full program or a function. Thus, your program can either take in input through stdin, a file, or as a single string argument, and either return or print the output. If returned, the output may be in a list/array/etc. rather than a single string. If the output is a single string, the boards should be separated by newlines (trailing newlines are allowed.)

The input strings will match the regex r'((-v)+-)(\n(-v)+-)*' and represent one board with all switches off. This means no zero case, and switches are left-aligned. Each row might not have the same number of switches.

Each output board should be of the exact same format as the input, except that the v's may be replaced by ^'s as required. The output boards can be separated by any number of newlines.

Since runtime is naturally O(2^n) in the number of switches, your code will not be tested on any more than 10 switches in any arrangement.

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

Sample inputs and outputs

Input:

-v-

Possible output:

-v-
-^-

Input:

-v-
-v-

Possible output:

-^-
-^-
-^-
-v-

-v-
-^-

-v-
-v-

Since it's extremely tedious to check your answer for bigger numbers of switches, here's a Python script as a sanity check tool. (I've included a currently commented-out snippet to generate expected output from a given input file in case you want more test cases.) It's quite a bit less flexible in terms of input and output than the spec, unfortunately; put the input string in a file named 'input' and the newline-separated output (sorry, no list formatting) in a file named 'output' in the same directory and run python3 sanitycheck.py.

Haskell, 25 24 23 17 bytes

mapM$min"^v".pure

Try it online!

-1 byte thanks to @H.PWiz

-1 byte thanks to @nimi

Returns a list of strings. The TIO has 2 extra bytes for the function declaration - I've seen other people leave it off when they write the function pointfree so I'm doing the same unless told otherwise.

Previous Answer (25 bytes)

g 'v'="v^"
g x=[x]
mapM g

The explanations are all for the previous answer, which works pretty much the same way, except I inlined the definition of g. The way g works now is by using lexical comparison to substitute ^v for v and keep everything else the same.

Interestingly, this works for arbitrary switchboards:

>>> mapM g "-----^-----"
  ["-----v-----", "-----^-----"]

Explanation (Short)

g 'v'="v^" -- for 'v', choose between 'v' or '^'
g x=[x]    -- for any other character, choose just that character
mapM g     -- find all ways to choose characters using g on the given input

Explanation (Long)

mapM is a pretty scary function for those not familiar with Haskell. But it's not hard to understand in this context. By making it act on Strings (which in Haskell are lists of characters), I've specialized it to its definition for lists. So in this context, its type signature is

mapM :: (a -> [b]) -> [a] -> [[b]]
--      ^^^^^^^^^^                  arg 1: a function from any a to a list of b
--                    ^^^           arg 2: a list of a
--                           ^^^^^ return: a list of list of b

It is actually even more specialized in my usage of it - a and b are both Char - so we can see the type signature as

mapM :: (Char -> String) -> String -> [String]

Let's quickly look at what g does before explaining how mapM works.

g :: Char -> String
g 'v' = "v^"
g  x  = [x]

g uses pattern matching to convert the Char 'v' into the string "v^"; everything else gets converted to a singleton string (remember, strings are just lists of Chars, so we can put x in a singleton list). Testing on the REPL, we find this is the case

>>> g 'a'
  "a"
>>> g 'b'
  "b"
>>> g 'v'
  "v^"

Note that g has the right type to be an argument of mapM (unsurprisingly!).

We'll explore how mapM works by giving it g and the argument

"-v-\n-v-"

as input.

mapM first maps g over the String, and because g converts Chars to Strings, this gives us a list of Strings

["-", "v^", "-", "\n", "-", "v^", "-"]

While this is the correct output type, mapM does slightly more. You can think of it as forming all Strings that you could create from this list if you had to pick a single character from each String in it (in order).

So for the first element, you have no choice other than to pick the Char '-'. For the second element, you can choose between 'v' and '^', so on and so forth.

It's roughly equivalent to this python code:

result = []
for x1 in "-":
  for x2 in "v^":
    for x3 in "-":
      ...
        result.append(''.join([x1, x2, x3, x4, x5, x6, x7]))

Except that since Haskell separates between Chars and Strings, when it puts the Chars into a list, it doesn't need to join them.

So the final output is

["-v-\n-v-", "-v-\n-^", "-^-\n-v-", "-^-\n-^-"]

as desired.


Element names above 118 IUPAC in their insufferable wisdom have created a systematic element name for any newly created element. This is the temporary name of an element until they finally make up their minds about an actual name. It works like so: each digit of an element number is assigned a prefix based on its value. The prefixes are concatenated with ‘ium’ at the end. When this is done and if you get double i’s (ii) or triple n’s (nnn), replace them with single i’s and double n’s. The symbol for the element is the first letter of each prefix used concatenated and result capitalized. The prefixes used are below.

0 nil       5 pent
1 un        6 hex
2 bi        7 sept
3 tri       8 oct
4 quad      9 enn

So for this golf, your code needs to generate both the element name and its symbol for a given positive integer. So if your code was given 137, it should print to stdout or return both untriseptium and Uts. It should be valid from at least 118 to 558. Any higher is valid if it doesn't increase your code's length.

Python example showing the method:

def elename(n):
    '''Return name and symbol of new element for given element number.'''
    prefixes=['nil','un','bi','tri','quad','pent','hex','sept','oct','enn']
    nmeFixes, symFixes = [], []

    while n:  # each digit of element number is assigned a prefix
        n, i = divmod(n, 10)
        pf = prefixes[i]

        symFixes.append(pf[0])  # symbol uses only first letter of prefix
        nmeFixes.append(pf)

    # loop assembled prefixes in reverse order
    nmeFixes.reverse()
    symFixes.reverse()

    nmeFixes.append('ium')  # suffix
    name = ''.join(nmeFixes)
    symb = ''.join(symFixes).capitalize()

    # apply rule about too many n's or i's
    name = name.replace('nnn','nn')  # can happen with -90-
    name = name.replace('ii','i')  # -2ium or -3ium

    return name, symb

Eric Towers wins with cadmium bytes!

Python 3, Unhexseptium (167) bytes

h=x='';r=str.replace
for i in input():s=r('nubtqphsoeinirueeecnl  ianxptn    dt t'[int(i)::10],' ','');h+=s;x+=s[0]
print(r(r(h+'ium\n','ii','i'),'nnn','nn')+x.title())

These are the results when the program is run on every number from 1 to 999 (inclusive)


Implement the Fibonacci-quine A Quine is a program which outputs its source when run.

In this challenge, You should make a Fibonacci-quine, a variant of the quine.

What is a Fibonacci-quine?

A Fibonacci-quine is a program, which outputs a modification of the source by the following rule:

The initial source should be ...2.... In other words, the source should contain 2. (Why 2? If it was 1, Nobody would know if it was the first 1 or the second, Even the program itself)

When run, You should output the source, but only the specific number (In this stage, 2) changed to the next number of the fibonacci sequence. For example, ...3.... Same goes for the output, and the output of the output, etc. You may support integers for up to 2^32-1. For integers over that limit, the next output is on your choice.

  OP's note

  I would really like to see a creative solution for this. I couldn't think of a single solution for this, since Both of the two important aspects of the challenge, fibonacci and quine, is not easy. I'll be waiting then!

Mathematica, 61 bytes

ToString[#0 /. v:2 :> RuleCondition[Round[GoldenRatio v]]] &

Note that there is a trailing space. This is a function quine, i.e. the above code evaluates to an unnamed function which, if called returns the code itself as a string (with 2 changed to the next Fibonacci number).

This was suprisingly tricky to get to work. The basic idea is to take the function itself (with #0) and replace a number in that function with the next one using /. v:2 :> nextFib[v]. However, nextFib wouldn't get evaluated at this stage so we wouldn't really end up with the new number in the source code. After searching around for a while to figure out how to force immediate evaluation, I found this great post on Mathematica.SE. The "standard" technique uses a With block which forces evaluation, but the second answer by WReach contains a shorter alternative using the undocumented built-in RuleCondition which also forces evaluation.

The way we compute the next Fibonacci number is by making use of the fact that the ratio of consecutive numbers is roughly the golden ratio 1.618... and this is accurate up to rounding. So we don't need to keep track of the last two numbers and can simply do Round[GoldenRatio v]. This will never lose precision since Mathematica's GoldenRation is a symbolic value and therefore Round can always compute an accurate result.

In summary:

... #0 ... &

An unnamed function, where #0 refers to the function object itself.

... /. v:2 :> ...

Find a 2 in the expression tree of the function (this 2 of course only matches itself), call it v and replace it with...

... RuleCondition[Round[GoldenRatio v]]

... the next Fibonacci number.

ToString[...]

And convert the resulting expression tree to its string representation.


Multiply with restricted operations There's a 500 rep unofficial bounty for beating the current best answer.

Goal

Your goal is to multiply two numbers using only a very limited set of arithmetic operations and variable assignment.

Addition x,y -> x+y
Reciprocal x -> 1/x (not division x,y -> x/y)
Negation x -> -x (not subtraction x,y -> x-y, though you can do it as two operations x + (-y))
The constant 1 (no other constants allowed, except as produced by operations from 1)
Variable assignment [variable] = [expression]

Scoring: The values start in variables a and b. Your goal is to save their product a*b into the variable c using as few operations as possible. Each operation and assignment +, -, /, = costs a point (equivalently, each use of (1), (2), (3), or (4)). Constants 1 are free. The fewest-point solution wins. Tiebreak is earliest post.

Allowance: Your expression has to be arithmetically correct for "random" reals a and b. It can fail on a measure-zero subset of R2, i.e. a set that has no area if plotted in the a-b Cartesian plane. (This is likely to be needed due to reciprocals of expressions that might be 0 like 1/a.)

Grammar:

This is an atomic-code-golf. No other operations may be used. In particular, this means no functions, conditionals, loops, or non-numerical data types. Here's a grammar for the allowed operations (possibilities are separated by |). A program is a sequence of <statement>s, where a <statement> is given as following.

<statement>: <variable> = <expr>
<variable>: a | b | c | [string of letters of your choice]
<expr>: <arith_expr> | <variable> | <constant>
<arith_expr>: <addition_expr> | <reciprocal_expr> | <negation_expr>
<addition_expr>: <expr> + <expr>
<reciprocal_expr>: 1/(<expr>)
<negation_expr>: -<expr>
<constant>: 1

You don't actually have to post code in this exact grammar, as long as it's clear what you're doing and your operation count is right. For example, you can write a-b for a+(-b) and count it as two operations, or define macros for brevity.

(There was a previous question Multiply without Multiply, but it allowed a much looser set of operations.)

22 operations

itx = 1/(1+a+b)     #4
nx = -1/(itx+itx)   #4
c = -( 1/(itx + itx + 1/(1+nx)) + 1/(1/(a+nx) + 1/(b+nx)) ) #14

Try it online!

The ops are 10 additions, 7 inverses, 2 negations, and 3 assignments.

So, how did I get this? I started with the promising-looking template of the sum of two double-decker fractions, a motif that had appeared in many previous attempts.

c = 1/(1/x + 1/y)  +  1/(1/z + 1/w)

When we restrict the sum to x+y+z+w=0, a beautiful cancellations occur, giving:

c = (x+z)*(y+z)/(x+y),

which contains a product. (It's often easier to get t*u/v rather than t*u because the first has degree 1.)

There's a more symmetric way to think about this expression. With the restriction x+y+z+w=0, their values are specified by three parameters p,q,r of their pairwise sums.

 p = x+y
-p = z+w
 q = x+z
-q = y+w
 r = x+w
-r = y+z

and we have c=-q*r/p. The sum p is distinguished as being in the denominator by corresponding to the pairs (x,y) and (z,w) of variables that are in the same fraction.

This is a nice expression for c in p,q,r, but the double-decker fraction is in x,y,z,w so we must express the former in terms of the latter:

x = ( p + q + r)/2
y = ( p - q - r)/2
z = (-p + q - r)/2
w = (-p - q + r)/2

Now, we want to choose p,q,r so that c=-q*r/p equals a*b. One choice is:

p = -4
q = 2*a
r = 2*b

Then, the doubled values for q and r are conveniently halved in:

x = -2 + a + b
y = -2 - a - b
z =  2 + a - b
w =  2 - a + b

Saving 2 as a variable t and plugging these into the equation for c gives a 24-op solution.

#24 ops
t = 1+1   #2
c = 1/(1/(-t+a+b) + 1/-(t+a+b))  +  1/(1/(-b+t+a) + 1/(-a+b+t)) #1, 10, 1, 10

There's 12 additions, 6 inverses, 4 negations, and 2 assignments.

A lot of ops are spent expressing x,y,z,w in terms of 1,a,b. To save ops, instead express x in p,q,r (and thus a,b,1) and then write y,z,w in terms of x.

y = -x + p
z = -x + q
w = -x + r

Choosing

p = 1
q = a
r = b

and expressing c with a negation as c=-q*r/p, we get

x = (1+a+b)/2
y = -x + 1
z = -x + a
w = -x + b

Unfortunately, halving in x is costly. It needs to be done by inverting, adding the result to itself, and inverting again. We also negate to produce nx for -x, since that's what y,z,w use. This gives us the 23-op solution:

#23 ops
itx = 1/(1+a+b)     #4
nx = -1/(itx+itx)   #4
c = -( 1/(1/(-nx) + 1/(1+nx))  +  1/(1/(a+nx) + 1/(b+nx)) ) #15

itx is 1/(2*x) and nx is -x. A final optimization of expressing 1/x as itx+itx instead of the templated1/(-nx) cuts a character and brings the solution down to 22 ops.


Is it a new highscore? Challenge:

In the language of your choice, write a program that generates a leaderboard with random scores and outputs it, then take a new score as input and check if it can be placed in the leaderboard, and output which place it is in.

Specifications:

You must generate a list of 50 "random" scores, in descending order and output it
The "random" scores will range from 0 to 255
If 2 scores are the same, it doesn't matter which is placed first in the descending order
If the input score isn't higher than any of the scores in the list, output 0 or a falsy statement. (the input will be 0 to 255, no need to check)
If the score IS higher than a score in the list, output the position it would take in the leaderboards.
Generate and output the leaderboards/list first in descending order, before taking input.

Example I/O:

Random list:  (the three dots are so I don't have to add 50 line text here. You should output each score. 12 is the 50th place)

201
192
178
174
...
...
12

Input:

180

Output:

3

(because this score would place no.3 in the leaderboards)

Input 2:

7

Output 2:

0

(because it is lower than everything on the leaderboard)

This is a code-golf so shortest code wins.

Python 2, 102 bytes

from random import*
lambda n,l=[randint(0,255)for i in[0]*50]:(l,[sorted(l+[n]).index(n),0][n>max(l)])

Try it online!


Draw a Permutation Path Imagine the following diagrams as sets of vertical criss-crossing tubes.

1 2    1 2    1 2 3 4
\ /    \ /    \ / \ /
 X      |      |   |
/ \    / \    / \ / \
2 1    1 2   |   X   |
              \ / \ /
               X   X
              / \ / \
              3 1 4 2

In the leftmost diagram, the 1 and 2 slide down their respective slashes, cross at the X, and come out at opposite sides from where they started.

It's the same idea in the middle diagram, but the | signifies that the paths do not cross, so nothing changes.

The rightmost diagram shows a more complex tube routing that permutes 1 2 3 4 into 3 1 4 2.

Goal

Your goal in this code golf challenge is to draw these "tube routing diagrams" given a permutation such as 3 1 4 2. The shortest program in bytes will win.

Details

Input comes from stdin as any permutation of the numbers from 1 to n separated by spaces, where n is a positive integer. You may assume all input is well formed.
The routing diagram output goes to stdout.

"Dropping" the numbers 1 through n in order into the top of the diagram should result in the input permutation coming out at the bottom. (Top and bottom are always layers of slashes.)
The diagram does not need to be optimally small. It may be as many levels as necessary as long as it is correct.
The diagram should only contain the characters \/ X| as well as newlines (no numbers).
| should always be used on the outermost intersections since using X wouldn't make sense.
A few leading or trailing spaces is fine as long as the diagram is all lined up correctly.

Examples

An input of 3 1 4 2 might produce (same as above)

 \ / \ /
  |   |
 / \ / \
|   X   |
 \ / \ /
  X   X
 / \ / \

An input of 1 might produce

 \
  |
 /
|
 \
  |
 /

An input of 3 2 1 might produce

 \ / \
  X   |
 / \ /
|   X
 \ / \
  X   |
 / \ /

An input of 2 1 3 4 6 5 might produce

\ / \ / \ /
 X   |   X
/ \ / \ / \

Python, 290

def g(o,u=1):
 s=['|']*o
 for i in range(o,n-1,2):v=r[i+1]in a[:a.index(r[i])]*u;s+=['|X'[v]];r[i:i+2]=r[i:i+2][::1-2*v]
 print'  '*(1-o)+'   '.join(s+['|']*(o^n%2))*u+'\n'*u+(' / \\'*n)[2*o:][:n*2]
a=map(int,raw_input().split())
n=len(a)
r=range(1,n+1)
o=1
g(1,0)
g(0)
while r!=a:g(o);o^=1

I went for a fairly basic approach, but it turned out a bit longer than I was hoping. It considers the list in pairs and decides whether or not to swap each pair. This is repeated for every intersecting row until the list matches the input.

Example:

$ python path.py
5 3 8 1 4 9 2 7 6
 \ / \ / \ / \ / \
  |   |   |   X   |
 / \ / \ / \ / \ /
|   X   X   X   X
 \ / \ / \ / \ / \
  X   X   X   X   |
 / \ / \ / \ / \ /
|   X   X   |   X
 \ / \ / \ / \ / \
  X   X   X   |   |
 / \ / \ / \ / \ /
|   |   |   X   |
 \ / \ / \ / \ / \


Calculate the relativistic velocity In special relativity, the velocity of a moving object relative to another object that is moving in the opposite direction is given by the formula:
\begin{align}s = \frac{v+u}{1+vu/c^2}.\end{align}
s = ( v + u ) / ( 1 + v * u / c ^ 2)

In this formula, \$v\$ and \$u\$ are the magnitudes of the velocities of the objects, and \$c\$ is the speed of light (which is approximately \$3.0 \times 10^8 \,\mathrm m/\mathrm s\$, a close enough approximation for this challenge).
For example, if one object was moving at v = 50,000 m/s, and another object was moving at u = 60,000 m/s, the velocity of each object relative to the other would be approximately s = 110,000 m/s. This is what you would expect under Galilean relativity (where velocities simply add). However, if v = 50,000,000 m/s and u = 60,000,000 m/s, the relative velocity would be approximately 106,451,613 m/s, which is significantly different than the 110,000,000 m/s predicted by Galilean relativity.
The Challenge
Given two integers v and u such that 0 <= v,u < c, calculate the relativistic additive velocity, using the above formula, with c = 300000000. Output must be either a decimal value or a reduced fraction. The output must be within 0.001 of the actual value for a decimal value, or exact for a fraction.
Test Cases
Format: v, u -> exact fraction (float approximation)
50000, 60000 -> 3300000000000/30000001 (109999.99633333346)
50000000, 60000000 -> 3300000000/31 (106451612.90322581)
20, 30 -> 7500000000000000/150000000000001 (49.999999999999666)
0, 20051 -> 20051 (20051.0)
299999999, 299999999 -> 53999999820000000000000000/179999999400000001 (300000000.0)
20000, 2000000 -> 4545000000000/2250001 (2019999.1022226212)
2000000, 2000000 -> 90000000000/22501 (3999822.2301231055)
1, 500000 -> 90000180000000000/180000000001 (500000.9999972222)
1, 50000000 -> 90000001800000000/1800000001 (50000000.972222224)
200000000, 100000000 -> 2700000000/11 (245454545.45454547)

Mathematica, 17 bytes

+##/(1+##/9*^16)&

An unnamed function taking two integers and returning an exact fraction.

Explanation

This uses two nice tricks with the argument sequence ##, which allows me to avoid referencing the individual arguments u and v separately. ## expands to a sequence of all arguments, which is sort of an "unwrapped list". Here is a simple example:

{x, ##, y}&[u, v]

gives

{x, u, v, y}

The same works inside arbitrary functions (since {...} is just shorthand for List[...]):

f[x, ##, y]&[u, v]

gives

f[x, u, v, y]

Now we can also hand ## to operators which will first treat them as a single operand as far as the operator is concerned. Then the operator will be expanded to its full form f[...], and only then is the sequence expanded. In this case +## is Plus[##] which is Plus[u, v], i.e. the numerator we want.

In the denominator on the other hand, ## appears as the left-hand operator of /. The reason this multiplies u and v is rather subtle. / is implemented in terms of Times:

FullForm[a/b]
(* Times[a, Power[b, -1]] *)

So when a is ##, it gets expanded afterwards and we end up with

Times[u, v, Power[9*^16, -1]]

Here, *^ is just Mathematica's operator for scientific notation.