Pretty Print Polynomials Introduction

Humans are a remarkable species, but we can be very awkward to understand sometimes—especially for computers.
In particular, we seem to like writing polynomials in a very convoluted fashion with seemingly arbitrary rules.

What is the shortest program you can write to format a polynomial correctly using these rules?

Challenge

Input

  A list of integers between -1000 and 1000 (inclusive), representing the coefficients of a polynomial, with the last entry being the coefficient of x^0 (the constant), the second last being the coefficient of x^1, etc.

Output

  A string representing this polynomial in the correctly formatted mathematical notation of humans.

Rules:

The sign on the leading coefficient is only shown if it is negative.

Right: -x^2+3

Wrong: +x^2+3

Components with coefficient of 0 are not printed (except for the corner case where all coefficients are 0*).

Right: x^5-x^2+3

Wrong: x^5+0x^4+0x^3-x^2+0x+3

Coefficients -1 and +1 are to be displayed without the 1, unless they are the constant.

Right: x^5-x^2+1

Wrong: 1x^5-1x^2+1

The exponent is only shown if it is greater than 1 and the variable is only shown if the exponent is greater than 0.

Right: 3x^3-7x^2+2x+1

Wrong: 3x^3-7x^2+2x^1+1x^0

*Corner case: while zero values usually result in not printing that component, if all coefficients are zero the constant 0 should be printed.

Right: 0

Wrong: 0x+0

Wrong: (nothing)

This is code-golf so the winner will be the program with the fewest bytes.

Example Input and Output

Input:                  Output:
      [0]                      0
      [0,0]                    0
      [0,-1,35,0]             -x^2+35x
      [5,1,7,-9]               5x^3+x^2+7x-9
      [100,0,0,-1]             100x^3-1
      [931,21,-11,1]           931x^3+21x^2-11x+1

I look forward to seeing your solutions. Have fun!

EDIT:

You can surround operations by whitespace if you wish. So 3x+5 and 3x + 5 are both fine. 3x+ 5 and 3x +5 are not.
If you want to produce actual exponent characters (say in Tex) that is allowed as it is even closer to how humans write.
Coefficients must appear without any decimals e.g. 9x^2 is correct, 9.0x^2 is not.

Retina 0.8.2, 56 bytes

(?=( \S+)+)
x^$#1
\b0x.\d+

\b1x
x
x.1
x
 0

 -
-

+

Try it online! Link includes test cases. Explanation:

(?=( \S+)+)
x^$#1

Insert all of the powers of x, including x^1 but not x^0.

\b0x.\d+

Delete all powers of x with zero coefficients, but not a trailing 0 (yet).

\b1x
x

Delete a multiplier of 1 (but not a constant 1).

x.1
x

Delete the ^1 of x^1.

 0

Delete a constant 0 unless it is the only thing left.

 -
-

Delete the space before a -.

+

Change any remaining spaces to +s.


Pentomino 6x10 solution normalizer As you most probably now, there are 2339 solutions to pentomino puzzle in a 6x10 grid. There are different labeling schemes for the 12 pentominoes, two of them are shown on the image below:

Image credit: Wikipedia

For the purposes of the current task we will say that a normalized pentomino solution is a solution that uses the second labeling scheme (Conway’s).

Example:

O O O O O S S S Z Z
P P R R S S W W Z V
P P P R R W W Z Z V
U U X R T W Y V V V
U X X X T Y Y Y Y Q
U U X T T T Q Q Q Q

The piece with 5 squares in a row is denoted with letters O, according to the scheme. The same is true for all pieces.

Task:

Given a solution to the 6x10 pentomino in which the pieces are labeled with a random sheme, normalize it so that all pieces are labeled in Conway’s labeling scheme. You need to recognize the pieces and mark each square of a particular piece with the symbol of the piece.

Input:

The solution to be normalized, in any format that is convenient for you, for example:

A multiline string
A list of strings
A list of lists of characters

and so on

Output:

The same solution (all the pieces positions and orientation preserved), but each piece labeled according to Conway’s labeling scheme.
Note: The output MUST be PRINTED as a 6x10 grid of characters. Leading and trailing newlines and spaces are permitted. You can also print a space between the characters (but not empty lines), as in the example above.

Test cases:

1.
Input:

6623338888
6222344478
66A234BB70
1AAA94B770
11A99BB700
1199555550

Output:

UURTTTQQQQ
URRRTVVVSQ
UUXRTVZZSY
PXXXWVZSSY
PPXWWZZSYY
PPWWOOOOOY

2.
Input:

45ookkkk00
455ooogk00
4a55gggdd0
4aaa3gnnd.
4am333ndd.
mmmm3nn...

Output:

OWSSQQQQPP
OWWSSSRQPP
OTWWRRRUUP
OTTTXRZZUV
OTYXXXZUUV
YYYYXZZVVV

Winning criteria:

The shortest solution in bytes in each language wins. Don’t be discouraged by the golfing languages. Explanations of the algorithms and implementations are welcome.

APL (Dyalog Classic), 54 53 50 bytes

⍴⍴{'OXRYTPZQUWSV'[⌊5÷⍨⍋⍋,{×/+⌿↑|(⊢-+/÷≢)⍸⍵}¨⍵=⊂⍵]}

Try it online!

Compute an invariant for each pentomino in the input: measure (∆x,∆y) from each of its squares to its centre of gravity, take abs(∆x) and abs(∆y), sum the x components and separately the y components, and multiply the two sums. This gives 12 distinct results. Then, find the index of each pentomino's invariant in the sorted collection of all invariants. Replace 0 with 'O', 1 with 'X', 2 with 'R', etc.


Build an ASCII Fibonacci Clock Someone built a really fancy clock using Fibonacci numbers, which looks really nice but is fairly unusable. Just the way we like it! Let's recreate this.

The clock is made up of 5 sections corresponding to the first five Fibonacci numbers, starting from 1 (i.e. 1, 1, 2, 3, 5):

ccbeeeee
ccaeeeee
dddeeeee
dddeeeee
dddeeeee

The clock is capable of displaying the 12-hour time in increments of 5 minutes. Here is how that works. Consider the time 7:20. The hour 7 can be decomposed into the given Fibonacci numbers as

7 = 2 + 5

There are also 4 units of five minutes. The 4 can be decomposed as

4 = 2 + 1 + 1

Now the hours are shown in red, the minute chunks in green, and if a number is used for both hours and minutes it's shown in blue. If a number isn't used at all, it remains white. So the above would be shown as:

BBGRRRRR
BBGRRRRR
WWWRRRRR
WWWRRRRR
WWWRRRRR

But wait, there's more. The above decompositions aren't the only possibilities. One can also write 7 = 3 + 2 + 1 + 1 and 4 = 3 + 1, which would give one of

GGRWWWWW          GGBWWWWW
GGBWWWWW          GGRWWWWW
BBBWWWWW    or    BBBWWWWW
BBBWWWWW          BBBWWWWW
BBBWWWWW          BBBWWWWW

depending on which 1 is chosen. Of course there are other combinations as well. The clock chooses from all valid decompositions at random.

As I said... this might not win a usability award, but it sure is nice to look at.

The Challenge

Your task is to implement such a clock. Your program (or function) should print an ASCII representation of the current time (rounded down to the last multiple of 5 minutes) as described above to STDOUT or closest alternative. You may choose to read the time in any common format as input or obtain it with standard library functions. You must not assume that the current/given time is divisible by 5 minutes.

Your solution must choose randomly from all possible representations of the current time. That is each representation must be printed with non-zero probability.

Midnight and noon should be treated as 0:00 (as opposed to 12:00).

You may optionally print a single trailing newline character.

You may use any four distinct printable ASCII characters (character codes 0x20 to 0xFE) in place of RGBW. Please state your choice in your answer and use it consistently.

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

Python 2, 194 182 bytes

from random import*
h=m=H,M=input()
while[h,m]!=[H,M/5]:
 h=m=0;s=[]
 for n in 1,1,2,3,5:c=randint(0,3);h+=c%2*n;m+=c/2*n;s=zip(*(["WRGB"[c]*n]*n+s)[::-1])
for L in s:print"".join(L)

The algorithm is just rejection sampling, so it keeps generating clocks until it gets one that's right. The clock is built by starting with nothing, then doing "add a square above and rotate clockwise" 5 times.

Takes two comma-separated integers via STDIN.

>>> ================================ RESTART ================================
>>>
7,17
BBBWWWWW
BBRWWWWW
RRRWWWWW
RRRWWWWW
RRRWWWWW
>>> ================================ RESTART ================================
>>>
7,17
GGBRRRRR
GGRRRRRR
WWWRRRRR
WWWRRRRR
WWWRRRRR


Confuse the Word spell checker! Your task is to make a program that will take an input of a word of any length, in the Calibri font. This word will be made out of letter characters that are found on a normal QWERTY keyboard. There will be no accents or any other characters (i.e punctuation, numbers etc).

So, the original characters are:

  A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

The program will then scramble it to change the characters so they look similar or exactly the same, which would probably confuse a spell checker by flagging it, but it would confuse me as it looks the same as the normal word, with the unchanged character.

An example of this is the Unicode character U+0430, Cyrillic small letter a ("а"), can look identical to Unicode character U+0061, Latin small letter a, ("a") which is the lowercase "a" used in English.

Another example is the Russian letters а, с, е, о, р, х and у have optical counterparts in the basic Latin alphabet and look close or identical to a, c, e, o, p, x and y.

Rules:

The program has to work out similar characters. This means that they cannot be stored in any form. This means that Unicode value or the character itself.
This is a code golf - the shortest answer wins!
You have to post the ungolfed version too to avoid cheating that can't be detected when its golfed!
You can use any function or program to do this, as long as words are not stored there either.
You must use UTF-8. Other inputs and outputs are banned. This is so that I am actually able to read what you are outputting, and what I am inputting, so I do not have a random mass of squares, question marks and ❮ther rand❮m punctuati❮n!
It has to work with any word that I input.

A working example (Copy and paste this into word and insert a space after, it should flag the second one and not the first one.)

Halim
Hаlim

Some helpful info is here

Good Luck! Begin

JavaScript, 71 characters

function f(s){return "\u202E"+s.split("").reverse().join("")+"\u202C";}

Try it out on JSFiddle.

By the way, this would be a good bit shorter in CoffeeScript (53 characters)

f=(s)->"\u202E#{s.split('').reverse().join ''}\u202C"

EDIT: I just noticed that UTF-8 requirement. That's going to be tough in JavaScript. :-/


First spiral, then diagonal Given a positive input number \$n\$, construct a spiral of numbers from \$1\$ to \$n^2\$, with \$1\$ in the top-left, spiraling inward clockwise. Take the sum of the diagonals (if \$n\$ is odd, the middle number \$n^2\$ is counted twice) and output that number.
Example for \$n = 1\$:
1

(1) + (1) = 2

Example for \$n = 2\$:
1 2
4 3

(1+3) + (4+2) = 4 + 6 = 10

Example for \$n = 4\$:
 1  2  3 4
12 13 14 5
11 16 15 6
10  9  8 7

(1+13+15+7) + (10+16+14+4) = 36 + 44 = 80

Example of \$n = 5\$:
 1  2  3  4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

(1+17+25+21+9) + (13+23+25+19+5) = 73 + 85 = 158

Further rules and clarifications

This is OEIS A059924 and there are some closed-form solutions on that page.
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 or 1-index, as I am here in my examples, 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.

R, 43 34 bytes

function(n)(8*n^3-3*n^2+4*n+3)%/%6

Try it online!

The OEIS page lists the following formula for a(n):

(16*n^3 - 6*n^2 + 8*n + 3 - 3*(-1)^n)/12

However, I skipped right over that to get to the PROG section where the following PARI code is found:

floor((16*n^3 - 6*n^2 + 8*n + 3 - 3*(-1^n))/12))

Naturally, +3-3*(-1^n) is the same as +6 so we can simplify the linked formula, first by reducing it to

(16*n^3-6*n^2+8*n+6)/12 -> (8*n^3-3*n^2+4*n+3)/6

and using %/%, integer division, rather than / to eliminate the need for floor.


using a Markov Chain, because this question itself as input text for example Create a Markov Chain generator, which generates (and outputs) an Order 4 text chain. It must be able to support all plain text formatting used on this question, so be sure to check for punctuation (parentheses count for example, but HTML doesn't need to be accounted for fortunately)! You could even use this question itself as input if you're so inclined. There must be a defined input variable (or something analogous to such, I am aware certain popular esoteric languages do not really have variables per se.)

Your generator also should start sentences with a capital letter, and end with ".", "!", or "?", according to how often those respective characters appear in the input text.

You must also include a way to change the amount of text which should be output, so the only two things that are really configurable are the amount to output and the input string. It should stick with an Order 4 chain, because those happen to be funniest when it all comes down to it really.

Oh and, if your generators happen to create something particularly funny, please feel free to include it in your post for the lulz.

The title of this question was generated using a Markov Chain.

Perl, 108 chars
What, no answers?  Here's a quick Perl solution:
$/=$,;$_=<>;push@$1,$2while/(?=(....)(.))/sg;print+($m)=/(....)/s;print while($m.=($_=$$m[rand@$m]))=~s/.//s

And this is what I got the first time I fed the question text through it:

Create a defined. There must also inclined. There must be sure to be according a Markov Chain.

(The average output length should approximately match the input length, so such a short output is quite untypical.  On the other hand, the output length is roughly exponentially distributed, so both very short and very long outputs are quite possible.)


Conjugate permutations A permutation of size n is a reordering of the first n positive integers.  (meaning each integer appears once and exactly once).  Permutations can be treated like functions that change the order of a list of items of size n.  For example

(4 1 2 3) ["a", "b", "c", "d"] = ["d", "a", "b", "c"]

Thus permutations can be composed like functions.

(4 1 2 3)(2 1 3 4) = (4 2 1 3)

This brings about a lot of interesting properties.   Today we are focusing on conjugacy.  Permutations y and x (both of size n) are conjugates iff there are permutations g and g-1 (also of size n) such that

x = gyg-1

and gg-1 is equal to the identity permutation (the first n numbers in proper order).

Your task is to take two permutations of the same size via standard input methods and decide whether they are conjugates.  You should output one of two consistent values, one if they are conjugates and the other if they are not.

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

There are lots of theorems about conjugate permutations that are at your disposal, so good luck and happy golfing.

You may take input as an ordered container of values (either 1-n or 0-n) representing the permutation like above, or as a function that takes a ordered container and performs the permutation.  If you choose to take function you should take it as an argument rather than have it at a predefined name.

Test Cases

(1) (1) -> True
(1 2) (2 1) -> False
(2 1) (2 1) -> True
(4 1 3 2) (4 2 1 3) -> True
(3 2 1 4) (4 3 2 1) -> False
(2 1 3 4 5 7 6) (1 3 2 5 4 6 7) -> True

Python 2, 87 bytes

f=lambda P,k:k<1or len({sum([x==eval('L['*k+'x'+']'*k)for x in L])for L in P})&f(P,k-1)

Try it online!

Takes input with P as a pair of both permutations and k their length. Outputs 1 for conjugates and 0 not.

This uses the result:

  Two permutations x and y are conjugate exactly if their k-th powers xk and yk have an equal number of fixed points for every k from 0 to n.

Two conjugate permutations satisfy this because their k-th powers are also conjugate, and conjugacy preserves the count of fixed points.

It's less obvious that any two non-conjugate permutations always differ. In particular, conjugacy is determined by the sorted list of cycle lengths, and these can be recovered from the counts of fixed points. One way to show this is with linear algebra, though it might be overkill.

Let X be the permutation matrix for x. Then, the number of fixed points of xk is Tr(Xk). These traces are the power sum symmetric polynomials of the eigenvalues of Xk with multiplicity. These polynomials for k from 0 to n let us recover the corresponding elementary symmetric polynomials of these eigenvalues, and therefore the characteristic polynomial and so the eigenvalues themselves.

Since these eigenvalues are roots of unity corresponding to the cycles of x, from these we can recover the cycle sizes and their multiplicities. So, our "signature" identifies the permutation up to conjugation.


Generate number in reverse polish notation Your task is to write a function which accepts a number N and creates a string of Reverse Polish Notation which will generate that number. Valid operations are:

1-9: Push number onto stack. Only 1-9 are allowed.
+-*/%: take two numbers from top of stack and apply arithmetic operation,
    pushing the result.
d: duplicate - push a copy of the top of the stack

That's all. For - / and % which are order dependent, the operand which was pushed first goes first. ie 63/ = 2 63- = 3 and 64% = 2

Entries are judged not by brevity of code, but by the size of the generated strings. The smaller the better. I also want to encourage pushing smaller numbers rather than bigger ones. The score for a number is calculated like so:

For any number pushed, add that number to the score.
For every operand (+-*/%d) add 1.

Your final score is the sum of your score for all numbers 0 to 10,000 inclusive. Lets go ahead and limit total running time to two minutes for all 10k, on a reasonable machine, to avoid too much brute forcing.

If you can do it only pushing 1s, go ahead and subtract 10% from your score.

Score 199503, Java solution

import java.util.HashMap;
import java.util.HashSet;

public class RPN {

    public static void main(String[] args) {
        // Loop to calculate total over all 10001 numbers as defined in puzzle
        int total = 0;
        System.out.println("n\tscore\trpn");
        for (int k = 0; k <= 10000; k++) {
            final String rpn = findRPN(k);
            final int scr = calcScore(rpn);
            System.out.println(k + "\t" + scr + "\t" + rpn);
            total += scr;
        }
        System.out.println("TOTAL: " + total);
    }

    // simple scoring calculator for a given rpn representation (ignores 10% bonus)
    private static int calcScore(String rpn) {
        int score = 0;
        for (char ch : rpn.toCharArray()) {
            if (Character.isDigit(ch)) {
                score += ch - '0';
            } else {
                score++;
            }
        }
        return score;
    }

    // hashmap caching intermediate results and all results for 0<=n<=10000
    final static int max = 6000000;
    final static HashMap<Integer, String> rpns = new HashMap<Integer, String>();

    // maximum score expected for numbers 0<=n<=10000
    final static int maxScore = 26;

    private static void preCalculate() {
        // hashmap which contains all numbers with a given score
        final HashMap<Integer, HashSet<Integer>> perScore = new HashMap<Integer, HashSet<Integer>>();

        // numbers are build by combining those with lower score
        for (int sc = 1; sc <= maxScore; sc++) {
            final HashSet<Integer> currentScore = new HashSet<Integer>();
            perScore.put(sc, currentScore);

            // 1-9 can be reached directly by pushing
            if (sc < 10 && !rpns.containsKey(sc)) {
                rpns.put(sc, Integer.toString(sc));
                currentScore.add(sc);
            }

            if (sc > 2) {
                // score is increased by 2 if appending "d+" or "d*" to an existing rpn
                for (int n : perScore.get(sc - 2)) {
                    String rpn_n = rpns.get(n);
                    consider(n * 2, currentScore, rpn_n, "d+");
                    consider(n * (long)n, currentScore, rpn_n, "d*");
                }
            }

            // another possibility to get score sc is to take two operands
            // with scores sc1 and sc2 and add another operator
            // with the requirement that sc1 + sc2 + 1 = sc
            for (int sc2 = 1; sc2 <= sc - 2; sc2++) {
                int sc1 = sc - sc2 - 1;
                HashSet<Integer> l1 = perScore.get(sc1);
                HashSet<Integer> l2 = perScore.get(sc2);

                // try all combinations of operators from list 1 and list 2
                // with each operator + - * / and %
                for (int n : l1) {
                    String rpn_n = rpns.get(n);
                    for (int m : l2) {
                        String prefix = rpn_n + rpns.get(m);

                        // Commutative operators - only need to consider them once
                        if (n < m) {
                            consider(n + m, currentScore, prefix, "+");
                            consider(n * (long)m, currentScore, prefix, "*");
                        }

                        // Non-commutative operators.
                        consider(n - m, currentScore, prefix, "-");
                        // div and mod only possible if m!=0
                        if (m != 0) {
                            consider(n / m, currentScore, prefix, "/");
                            consider(n % m, currentScore, prefix, "%");
                        }
                    }
                }
            }
        }
    }

    private static void consider(long value, HashSet<Integer> currentScore, String prefix, String suffix) {
        if (value < -max || value > max) return;
        Integer r = Integer.valueOf((int)value);
        if (!rpns.containsKey(r)) {
            rpns.put(r, prefix + suffix);
            currentScore.add(r);
        }
    }

    private static String findRPN(int number) {
        if (rpns.isEmpty()) {
            preCalculate();
        }

        // if number is negative try 1(-n+1)-
        if (number < 0) {
            return "1" + findRPN(-number + 1) + "-";
        }

        // if number not in precalculated list try number/2
        if (!rpns.containsKey(number)) {
            if (number % 2 == 0) {
                return findRPN(number / 2) + "d+";
            } else {
                return findRPN(number / 2) + "d+1+";
            }
        }

        // otherwise use cached result
        return rpns.get(number);
    }
}

The solution is pretty much optimized to get a good score within the defined range of numbers (i.e. 0 to 10000). It sacrifices non-optimal solutions outside the range for (hopefully) optimal representations within. Nevertheless it will still work for other numbers too.

I think the score given by that solution is very close to optimal although I'm not able to prove it.

Output:

n   score   rpn
0   3   11-
1   1   1
2   2   2
3   3   3
4   4   4
5   5   5
6   5   3d+
7   7   7
8   6   4d+
9   5   3d*
10  7   5d+
11  8   3d*2+
12  7   3d+d+
...
9990    19  5d+d*d*3d*-1-
9991    17  5d+d*d*3d*-
9992    18  5d*d+d*2-d+d+
9993    19  5d+d*d*3d+-1-
9994    17  5d+d*d*3d+-
9995    17  5d+d*d*5-
9996    16  5d+d*d*4-
9997    15  5d+d*d*3-
9998    14  5d+d*d*2-
9999    13  5d+d*d*1-
10000   11  5d+d*d*
TOTAL: 199503


Choosing Languages for Golfing What are some tips for choosing the right language to golf?
What factors affect the language to be chosen?

Here are some example problem types:

Problems that require I/O solution, either console or file
Problems that require parsing
Problems that requires you to write your solution as a function definition
Math problems
Problem dealing with prime numbers
Solving number puzzles
Performing numerical methods
String processing
Array processing
Tricky 2D array problems
Computational geometry
Recursion
2D graphics
3D graphics
Audio
Networking / web
Parallel processing

Don't simply say things like "Use GolfScript|J" because you like them.

Putting my two cents in on array programming languages, J and APL in particular.

K/Kona, Q, and Nial fall in this category too, but they generally have the same benefits and criticisms. Use discretion. I will use J examples below, mostly because these are ASCII and thus easy to type--remember than APL characters count as single bytes, so don't let that be your problem with the language as choice for golfing.

Math problems
Solving number puzzles
Performing numerical methods
Tricky 2D array problems

These two are very good math and data-manipulation languages, because they toss arrays around a high level, and a lot of looping is done implicitly, by saying, e.g. add ten to each of 3, 4, and 5 (10 + 3 4 5) or sum each row of an array (+/"1 arr--the looping is in the "1).

Problem dealing with prime numbers

With prime number problems in particular, J has fast and short builtin primitives, as do some dialects of APL. (Edit: I'm thinking of Nars2000, which is part dialect and part completely different implementation. APL has no builtin for primes.) N-th prime (p:), no. of primes up to (_1&p:), factoring (q:), GCD and LCM (+. and *.), and so on, there's a lot there. However, in practice, the question will often specify that you have to cook your own prime implementations, so these don't see too much use. There are still neat and fancy ways of getting the prime stuff you need, it just becomes a little less cut-and-paste.

String processing
Array processing

Array and string processing is a bit of a mixed bag: if it's something that APL/J is good at or has a primitive or common idiom for, it's nearly trivial; if it's something that's very sequential and not very parallelizable, you're going to have a bad time. Anything in between is up in the air, though usually they will respond favourably.

Problems that require I/O solution, either console or file
Problems that requires you to write your solution as a function definition

IO is weird. APL has a single-character input expression, but with J you have to spend at least 8 to read in a number: ".1!:1]1. Output is a little less verbose, but you're still looking at 6 or 7 characters wasted, in practice. J in particular really likes it a lot if you can take in the input as arguments to a function, instead of having to muck around with IO itself.

In practice, with J and APL, usually the solution is written as a function that you invoke at the console. With APL, you can basically just put in variable names for your arguments and wrap the expression you were working with in curly braces and call it a day.

But with J, there's a bit of an overhead for defining functions explicitly--3 :'...', and you have to escape any strings inside--so what is usually done is something called tacit programming: you program at the function level, combining primitives in a manner not unlike that of Haskell. This can be both a blessing and a curse, because you don't have to spend as many characters referring to your arguments, but it's easy to drown in parentheses and end up losing tens of characters trying to hack your otherwise short and clever solution into something that works.

Problems that require parsing
Computational geometry

I don't have experience with golfing these particular problems, but I will say this: in the end, array programming languages are very good at piping and transforming lots of data in the same way. If you can turn the problem into an exercise in number shuffling, you can make it an APL/J problem, no sweat.

That said, not everything is an APL/J problem. Unlike Golfscript, APL and J just happened to be good for golfing, alongside their other benefits ;)


Same word when missing letters Idea

From a given word dictionary (containing only plain letters, i.e: no accent or other special chars), with a given fixed word length, find every same when a given number letters are missing.

For sample: un--ed could match: united, untied or unused

  Using my dictionnary: /usr/share/dict/american-english, searching for same 6 letters words, having 2 letters missing let me find:

  19242 different possible combination (shapes),
  The most matching shape is -a-ing, that will match saving, gaming, hating and more than 80 other words
  There is 11209 matching shapes for which only two words match, like -hre-d that would only match shrewd or thread.

The goal of this challenge is to write the most efficient algorithm (and implement them in any language) for

extract all given fixed length words from a dictionnary
find all possible multiple words that could be match same shape containing a given fixed number of missing letter.
Sort and present output from the most matching shape to the less matching shape.

There are 3 variables:

Dictionnary file name (could be STDIN)
Fixed words length
Number of missing chars

This could be transmitted in any way you may find usefull.

Samples

A quick sample could better explain: Searching for same shape of 18 letters, having 2 missing letters give only one match:

same /usr/share/dict/american-english 18 2
electrocardiogra--: electrocardiograms,electrocardiograph

or

same /usr/share/dict/american-english 8 2
17: --ddling: coddling,cuddling,diddling,fiddling,fuddling,huddling,meddling,middling,muddling,paddling,peddling,piddling,puddling,riddling,saddling,toddling,waddling
17: -us-iest: bushiest,cushiest,duskiest,dustiest,fussiest,fustiest,gushiest,gustiest,huskiest,lustiest,mushiest,muskiest,mussiest,mustiest,pushiest,pussiest,rustiest
16: --tching: batching,bitching,botching,catching,ditching,fetching,hatching,hitching,latching,matching,notching,patching,pitching,retching,watching,witching
15: sta--ing: stabbing,stabling,stacking,staffing,staining,stalking,stalling,stamping,standing,stapling,starling,starring,starting,starving,stashing
15: --ttered: battered,bettered,buttered,fettered,guttered,lettered,littered,mattered,muttered,pattered,pottered,puttered,tattered,tittered,tottered
...
 2: -e-onate: detonate,resonate
 2: c-mmune-: communed,communes
 2: trou-le-: troubled,troubles
 2: l-t-rals: laterals,literals
 2: sp-ci-us: spacious,specious
 2: -oardi-g: boarding,hoarding
 2: pre-ide-: presided,presides
 2: blen-he-: blenched,blenches
 2: sw-llin-: swelling,swilling
 2: p-uc-ing: plucking,pouching

or

  The shape ---l- match hello and world as well as 297 other words.:

same /usr/share/dict/american-english 5 4 |
    sed -ne '/hello/{s/^ *\([0-9]*: [a-z-]*\):.*,world,.*$/\1/p}'
299: ---l-

Test file

For testing, I've posted this 62861 length extract from my dict file in plain ascii, useable from jsfiddle, jsbin or even from your filesystem (because of the directive access-control-allow-origin) ( sample: @edc65 answer, with score count ).

Ranking

This is a fastest algorithm challenge.

The goal of this is to find quickest way for building shape, making comparissions and sorting list.

But the natural speed of language have to not be matter. So if a solution using bash is slower, but simplier, using more efficient algorithm than another c based solution, the simplier (maybe slower) have to win.

The score is the number of logical steps required by the whole job, using any dictionary file (my personal english dictionary: wc -l /usr/share/dict/american-english -> 99171) and different combinations of word length and number of missing letters.

The lowest score win.

C++11

Excuse the variable names.

Calculates hamming distance between each pair of words then tries replacing characters in words with '-', and calculates hamming distance between the word with '-' and the words without (that had a low enough hamming distance). See comments for details.

#include <algorithm>
#include <cassert>
#include <cstdio>
#include <fstream>
#include <ios>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>

// Calculates hamming distance between a and b, both of which are length m
inline int fries(const std::string &a, const std::string &b, int m){
    int c = 0;
    for(int i = 0; i < m; ++i)
        a[i]==b[i] || ++c;
    return c;
}
using namespace std;

int main(int eggs, char **bagels){
    ios_base::sync_with_stdio(false);
    // make sure proper number of arguments are passed
    assert(eggs == 4);

    int m, k;
    // read in m (word length) and k (number of '-'s)
    sscanf(bagels[2], "%i", &m);
    sscanf(bagels[3], "%i", &k);

    // bacon will store all words that are of length m
    vector<string> bacon;
    bacon.reserve(500000);

    // Save only words that are of length m
    ifstream milk(bagels[1]);
    {
        string toast;
        while(getline(milk, toast))
            if(toast.length() == m)
                bacon.push_back(toast);
    }

    // ham[i] will store the indices of strings with a hamming distance from bacon[i] that is at most k
    vector<vector<int>> ham(bacon.size());

    // Calculate hamming distance, if <=k, add to ham.
    for(int i = 0, sz = bacon.size(); i < sz; ++i){
        // Uses i+1 to ensure each PAIR is only checked once
        for(int j = i+1; j < sz; ++j){
            unsigned strip = fries(bacon[i], bacon[j], m);
            if(strip && strip <= k)
                ham[i].push_back(j);
        }
    }

    // cereal[string], where string is the matching shape, and the vector is a vector of indices of strings that are matched by string
    map<string, vector<int>> cereal;
    for(int i = 0, sz = ham.size(); i < sz; ++i){
        // skip words that are not similar enough to other words
        if(ham[i].size() == 0) continue;

        // Iterate through all versions of bacon[i] with k '-'s
        // THIS ONLY ITERATES THROUGH COMBINATIONS NOT PERMUTATIONS
        vector<bool> cream(m);
        fill(cream.begin()+k,cream.end(),true);
        do{
            std::string juice = bacon[i];
            // Add in '-'s
            for(int i = 0; i < m; ++i){
                if(!cream[i]) juice[i] = '-';
            }
            // Ensure that this pattern has not yet been processed
            if(!cereal.count(juice)){
                // For each of the words with hamming distance<=k, check hamming distance with the matching shape
                // If hamming distance == k, then it matches, so save to cereal
                for(int j = 0, ssz = ham[i].size(); j < ssz; ++j){
                    if(fries(juice, bacon[ham[i][j]], m) == k)
                        cereal[juice].push_back(ham[i][j]);
                }
                // In the case that there ARE matches, put the index of the original string at the end
                if(cereal.count(juice))
                    cereal[juice].push_back(i);
            }
        }while(next_permutation(cream.begin(), cream.end()));
    }
    // Sorts all the matching shapes by number of matches
    vector<pair<string, vector<int>>> orange_juice;
    copy(cereal.begin(), cereal.end(), back_inserter(orange_juice));
    sort(orange_juice.begin(), orange_juice.end(), [](const pair<string, vector<int>> &a, const pair<string, vector<int>> &b){
        return a.second.size() > b.second.size();
    });
    // Iterate through sorted matching shapes, print
    for(auto cake:orange_juice){
        // bacon[cake.second.back()] is the original string from which the pattern was derived
        cout << cake.second.size() << ": " << cake.first << ": " << bacon[cake.second.back()];
        // do not print original string twice
        cake.second.pop_back();
        // print other strings
        for(auto coffee:cake.second){
            cout << "," << bacon[coffee];
        }
        cout << "\n";
    }
    return 0;
}


How many times, are they multiples? You are given three parameters: start(int), end(int) and list(of int);

Make a function that returns the amount of times all the numbers between start and end are multiples of the elements in the list.
example:

start = 15; end = 18; list = [2, 4, 3];
15 => 1 (is multiple of 3)
16 => 2 (is multiple of 2 and 4)
17 => 0
18 => 2 (is multiple of 2 and 3)
result = 5

The function should accept two positive integer numbers and an array of integers as parameters, returning the total integer number. Assume that start is less <= end.

examples:

Multiple(1, 10, [1, 2]); => 15
Multiple(1, 800, [7, 8]); => 214
Multiple(301, 5000,[13, 5]); => 1301

The shortest solution is the victor!!! May he odds be ever in your favor...

05AB1E, 5 bytes
ŸÑ˜åO

Try it online!

Explanation
Ÿ       - the numbers between start and end
 Ñ      - get their divisors
  ˜     - deep flatten this list
   å    - find the instances of the elements in the list in these divisors
    O   - Sum this


Remove repeated words from a string Remove all repeating words from an inputted sentence.

Input will be something like cat dog cat dog bird dog Snake snake Snake and the output should be cat dog bird Snake snake. There will always be a single space separating words.

Output order must be the same as input. (Refer to the example)

You don't need to handle punctuation but capital letter handling is required.

CJam, 7 chars

qS/_&S*

Can probably be much shorter... but whatever I've almost never used CJam. ^.^

q reads input, S/ splits on spaces, _& duplicates and applies a setwise AND (therefore getting rid of duplicates), and S* re-joins on space.

Online interpreter link


Follow a linked list For this challenge, a linked list looks like this:
[1, 2, 4, 0, 6, 1, 3, 1]

You'll notice there's no data; each item in the list is just a reference to the index of the next one. Your task is to write a program or function which will follow a linked list like this forever, outputting each item as it is encountered. For example, for the above input:
[1, 2, 4, 6, 3, 0, 1, ...]

Input and output can be represented in any reasonable manner. All numbers in the input will be valid indices in the list, and you can choose if it's 0- or 1-indexed. The output will be infinite, and as long as your program would theoretically give a correct result given infinite time and resources it's valid.
Test cases:
Zero indexed, using lists.
[0]         -> [0, 0, ...]
[1, 0]      -> [1, 0, 1, ...]
[0, 1, 2]   -> [0, 0, ...]
[2, 1, 0]   -> [2, 0, 2, ...]
[4]         -> (does not need to be handled)

convey, 36 29 bytes
v<<<<,{
\~./."
>"`=>!
 >!0<"}

Try it online!

{ gets the input, that will get looped around in the upper two rows, while outputting downwards the length \, its indices /. and a copy of itself ". It will only continue after ~. (batch) if n elements reach ~., whereas n will be the length.

We then take ! n copies of the current index i (starting with 0) and compare = them to the indices of the list. This returns either 1 or 0. We take the correspondent element of the copied list so many times, effectively filtering the others out. The next index then gets copied to the output "} and waits for the next iteration.


Tips for golfing in Visual Basic .NET This page is not for Visual Basic Tips

Visual Basic .NET (VB.NET) is an multi-paradigm dialect of basic that was developed and released by Microsoft in 2002 as a replacement for Visual Basic. The current version of VB.Net as of Feb 2018 is Visual Basic .NET 15.0.
Unlike Visual Basic (VB), Visual Basic .NET (VB.NET) is fully integrated with the Microsoft .NET Framework giving it access to a far wider range of classes to access. Additionally, the bit width of integers and longs in VB.NET are 32 and 64 bits, respectively - twice that available to VB.

Some helpful links

MSDN Visual Basic .NET Guide

Visual Basic .NET Wiki

TIO - Visual Basic .NET (.NET Core)

TIO - Visual Basic .NET (Mono)

Dim Variables implicitly as variants

VB.NET is capable of assuming object type at compile time - with numerics being dimmed into 32-bit spaces this means that

Module M
Sub Main
Dim i As Byte
Dim j As Short
Dim k As Integer
Dim l As Long
For i=128To 2^8-1 Step 64
For j=2^7*i To 2^15-1 Step 64^2
For k=2^16*j To 2^31-1 Step 2^24
For l=2^31*k To 2^62-1 Step 2^48
Console.Write(i & j & k & l)
Next
Next
Next
Next
End Sub
End Module

Try it online! (266 bytes)

May be trimmed down by dimming i, j, k as variants, (note that because the default numeric type of a variant is a 32 Bit Integer l must still be dimmed as a Long as it shall hold a 64 bit value)

Module M
Sub Main
Dim i,j,k,l As Long
For i=128To 2^8-1 Step 64
For j=2^7*i To 2^15-1 Step 64^2
For k=2^16*j To 2^31-1 Step 2^24
For l=2^31*k To 2^62-1 Step 2^48
Console.Write(i &j &k &l)
Next
Next
Next
Next
End Sub
End Module

Try it online! (226 bytes)

or even further to 218  bytes by combining Next statements

Module M
Sub Main
Dim i,j,k,l As Long
For i=128To 2^8-1 Step 64
For j=2^7*i To 2^15-1 Step 64^2
For k=2^16*j To 2^31-1 Step 8^8
For l=2^31*k To 2^62-1 Step 2^48
Console.Write(i &j &k &l)
Next l,k,j,i
End Sub
End Module

Try it online! (218 bytes)
For a total savings of 40 bytes without impacting the output.


Randomize points on a disc I read about circles somewhere, and just now learned about discs (it's actually a pretty common concept) and thought about codegolf.

Your task is to randomize a point/several points on a disc with the radius 1.

Rules:

All points must have an equal probability to be generated
Floating point coordinates must be used; the minimum requirement is two decimals (e.g. the points (0.12, -0.45) or (0.00, -1.00) are valid)
You get -20 bytes if your program actually displays the bounding circle and the point(s) generated in it. Coordinates still has to be valid but not displayed, and the image generated has to be at least 201 by 201 pixels in size
You get -5 bytes if your program takes the number of points to be generated as input on stdin
If you decide not to plot the bounding circle and the point(s), your program has to output the point(s) generated on the format (x, y) or (x,y) on stdout
If you decide to take the number of generated points as input, but not to plot it - your program has to output all the randomized points on the format stated above with or without one space in between

Shortest submission in bytes wins!

CJam, 28 27 bytes

PP+mr_mc\ms]1.mrmqf*"(,)".\

This solution is not rejection-based. I'm generating the points in polar coordinates, but with a non-uniform distribution of the radii to achieve a uniform density of the points.

Test it here.

Explanation

PP+     e# Push 2π.
mr_     e# Get a random float between 0 and 2π, make a copy.
mc\     e# Take the cosine of one copy and swap with the other.
ms]     e# Take the sine of the other copy and wrap them in an array.
        e# This gives us a uniform point on the unit circle.
1.mr    e# Get a random float between 0 and 1.
mq      e# Take the square root. This is the random radius.
f*      e# Multiply x and y by this radius.
"(,)".\ e# Put the resulting numbers in the required format.

Why does it work? Consider a narrow annulus of radius r and (small) width dr. The area is approximately 2π*r*dr (if the annulus is narrow, the inner and outer circumference are almost identical, and the curvature can be ignored, such that the area can be treated as that of a rectangle with side lengths of the circumference and the width of the annulus). So the area increases linearly with the radius. This means that we also want a linear distribution of the random radii, in order to achieve a constant density (at twice the radius, there is twice as much area to fill, so we want twice as many points there).

How do we generate a linear random distribution from 0 to 1? Let's look at the discrete case first. Say, we have a desired distribution of 4 values, like {0.1, 0.4, 0.2, 0.3} (i.e. we want 1 to be 4 times as common as 0, and twice as common as 2; we want 3 three times as common as 0):

How can pick one of the four values with the desired distribution? We can stack them up, pick a uniformly random value between 0 and 1 on the y-axis and pick the segment at that point:

There's a different way to visualise this picking though. We could instead replace each value of the distribution with the accumulation of the values up to that point:

And now we treat the top line of this chart as a function f(x) = y and invert it to get a function g(y) = f-1(y) = x, which we can apply to a uniformly random value in y ∈ [0,1]:

Cool, so how can make use of this to generate a linear distribution of radii? This is the distribution we want:

The first step is to accumulate the values of the distribution. But the distribution is continuous, so instead of summing over all previous values, we take an integral from 0 to r. We can easily solve that analytically: ∫0r r dr = 1/2 r2. However, we want this to be normalised, i.e. to multiply it by a constant such that this gives 1 for the maximum value of r, so what we really want is r2:

And finally, we invert this to get a function we can apply to a uniform value in [0,1], which we can again do analytically: it's just r = √y, where y is the random value:

This is a fairly useful technique that can often be used to generate simple distributions exactly (it works for any distribution, but for complicated ones the last two steps may have to be solved numerically). However, I wouldn't use it in this particular case in production code, because the square root, sine and cosine are prohibitively expensive: using a rejection-based algorithm is on average much faster, because it only needs addition and multiplication.


Calculate a tip using the smallest number of coins Most tip calculator apps simply take a flat percentage of the meal price.  So, for example, if your meal is $23.45, you can leave a 15% tip = $3.52, or a more generous 20% tip = $4.69.

Convenient enough for credit card users.  But not so if you prefer to leave cash tips, in which case these oddball cent amounts get in the way.  So let's modify the idea to be more convenient for cash users.

Your assignment

Write, in as few bytes as possible, a program or function that takes as input:

Price of the meal
Minimum tip percentage
Maximum tip percentage

And output any tip amount within the range [price * min_percentage / 100, price * max_percentage / 100] that minimizes the number of bills/banknotes and coins required.

Assume the US monetary denominations of 1¢, 5¢, 10¢, 25¢, $1, $5, $10, $20, $50, and $100.

Example

Here is a non-golfed example program in Python:

import math
import sys

# Do the math in cents so we can use integer arithmetic
DENOMINATIONS = [10000, 5000, 2000, 1000, 500, 100, 25, 10, 5, 1]

def count_bills_and_coins(amount_cents):
    # Use the Greedy method, which works on this set of denominations.
    result = 0
    for denomination in DENOMINATIONS:
        num_coins, amount_cents = divmod(amount_cents, denomination)
        result += num_coins
    return result

def optimize_tip(meal_price, min_tip_percent, max_tip_percent):
    min_tip_cents = int(math.ceil(meal_price * min_tip_percent))
    max_tip_cents = int(math.floor(meal_price * max_tip_percent))
    best_tip_cents = None
    best_coins = float('inf')
    for tip_cents in range(min_tip_cents, max_tip_cents + 1):
        num_coins = count_bills_and_coins(tip_cents)
        if num_coins < best_coins:
            best_tip_cents = tip_cents
            best_coins = num_coins
    return best_tip_cents / 100.0

# Get inputs from command-line
meal_price = float(sys.argv[1])
min_tip_percent = float(sys.argv[2])
max_tip_percent = float(sys.argv[3])
print('{:.2f}'.format(optimize_tip(meal_price, min_tip_percent, max_tip_percent)))

Some sample input and output:

~$ python tipcalc.py 23.45 15 20
4.00
~$ python tipcalc.py 23.45 15 17
3.55
~$ python tipcalc.py 59.99 15 25
10.00
~$ python tipcalc.py 8.00 13 20
1.05

JavaScript (ES6), 93 bytes

(x,m,M)=>(g=(t,c=1e4)=>t>x*M?0:t<x*m?[...'1343397439'].some(d=>g(t+(c/=-~d/2)))*r:r=t)(0)/100

Try it online!

How?

We recursively compute a sum of bill/coin values until it falls within the acceptable range, always trying the highest value first.

This is guaranteed to use the minimum amount of bills and coins because for any solution \$\{b_0,\dots,b_n\}\$ returned by this algorithm:

all terms \$b_0\$ to \$b_n\$ are required, otherwise the algorithm would have selected \$\{b_0,\dots,b_{k-1},x\}\$ with \$x \ge b_k\$ for some \$0 \le k < n\$
for any \$0 \le k < n\$ and any \$x \le b_n\$, \$\{b_0,\dots,b_{k-1},b_k-x,b_{k+1},\dots,b_n\}\$ cannot be a solution, otherwise \$\{b_0,\dots,b_{n-1}\}\$ would have been selected
there may exist some \$0 < x < b_n\$ such that \$\{b_0,\dots,b_{n-1},x\}\$ is also valid, but that would not use less bills/coins than the selected solution

The bill/coin values \$c_n\$ expressed in cents are computed with:

$$\begin{cases}c_0=10000\\c_{n+1}=\dfrac{c_n}{(d_n+1)/2}\end{cases}$$

where \$(d_0,\dots,d_9) = (1,3,4,3,3,9,7,4,3,9)\$.

 n | c(n)  | d(n) | k = (d(n)+1)/2 | c(n+1) = c(n)/k
---+-------+------+----------------+-----------------
 0 | 10000 |   1  | (1+1)/2 = 1    |      10000
 1 | 10000 |   3  | (3+1)/2 = 2    |       5000
 2 |  5000 |   4  | (4+1)/2 = 2.5  |       2000
 3 |  2000 |   3  | (3+1)/2 = 2    |       1000
 4 |  1000 |   3  | (3+1)/2 = 2    |        500
 5 |   500 |   9  | (9+1)/2 = 5    |        100
 6 |   100 |   7  | (7+1)/2 = 4    |         25
 7 |    25 |   4  | (4+1)/2 = 2.5  |         10
 8 |    10 |   3  | (3+1)/2 = 2    |          5
 9 |     5 |   9  | (9+1)/2 = 5    |          1


Answer to Vote Ratio This question is inspired by the fact that I love seeing questions with equal vote and answer counts...

So here's a simple stack-exchange-api challenge for y'all:

Challenge:

Given a codegolf.stackexchange question id, output the ratio between the question's votes and number of answers (e.g. votes/answers).

Specifics:

You may access the internet, but you may only access stackexchange.com and its various sub-domains. You may not use URL shorteners.
You may take input and give output in any standard format.
You must output the ratio as a decimal number in base 10, with at least 4 {accurate} digits after the decimal (zeros may be truncated).
If the question is unanswered, your program may produce undefined behavior.
You should use the score of the question as the vote-count, see here.

This is code-golf, least bytes in each language wins for that language, least bytes overall wins overall.

Here is a sample program in Python 3 + requests:

import requests
import json

id = input("id> ")
url = "https://api.stackexchange.com/2.2/questions/" + id + "?site=codegolf"
content = requests.get(url).text
question = json.loads(content)["items"][0]

print(float(question["score"]) / question["answer_count"])

JavaScript (ES6), 103 102 bytes
Needs to be run from the root level of api.stackexchange.com. Returns a Promise object containing the result.
n=>fetch(`questions/${n}?site=codegolf`).then(r=>r.json()).then(({items:[j]})=>j.score/j.answer_count)

1 byte saved thanks to kamoroso94.

If requiring that it be run from a specific path is allowed then that becomes 92 90 bytes.
n=>fetch(n+`?site=codegolf`).then(r=>r.json()).then(({items:[j]})=>j.score/j.answer_count)

Try it
Full URL added to enable it to work here.

f=
n=>fetch(`//api.stackexchange.com/questions/${n}?site=codegolf`).then(r=>r.json()).then(({items:[j]})=>j.score/j.answer_count)
onchange=_=>f(+i.value).then(t=>o.innerText=t)
<input id=i type=number><pre id=o>


Finding Programs in the Primes Let's assign the numbers 0 through 94 to the 95 printable ASCII characters:
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
Space is 0, ! is 1, and so on until ~ is 94. We'll also assign 95 to tab (\t) and 96 to newline (\n).
Now consider the infinite string whose Nth character is the character above that the Nth prime number, modulo 97, has been assigned to. We'll call this string S.
For example, the first prime number is 2, and 2 mod 97 is 2, and 2 is assigned to ", so the first character of S is ". Similarly, the 30th prime number is 113, and 113 mod 97 is 16, and 16 is assigned to 0, so the 30th character of S is 0.
The first 1000 characters of S are as follows:
"#%'+-137=?EIKOU[]cgiosy $&*,0>BHJTV\bflrt~
#%1=ACGMOY_ekmswy"046:HNXZ^dlrx|!)-5?AKMSW]eiko{"&.28DFX^hntv|%+139?CEQ[]agmo{  $,6>HPV\`hnrz~+5ACMOSU_mqsw$(*.BFNX`djp~!'-5;GKQS]_eoq{}"48:>DJRX^tv
'17=EQU[aciu    026<>DHJNZ\b#)/7ISaegkqy}   $0:<@BFLXdlx~!'/3;?MQWY]ceku(.24LPR\hjt|!'-?EIKWamu$28<>BDNZ`fxz)+AGOUY[_gmwy"0:@LNRT^jl|~#')3;Meiow&(,4DFJRX^bnp%+-37=KQUW]agsy    ,06BJPTn
)15;=CYegw  ".<FHLTZ`dfjpx|~#-/9AES]ikquw&48>FLPbjtz
'1=KOU[]y{$,0>BJV\hlr%/1A[_amsw"(04<RTXZf!#)/59?AMQ]_ik{},2FV^bdhj
'39CEIOQWacoy{$28<BJPVfrtx%+/7AIOUkqs}*.4FHR`dfp~!);?EGKQS_cw,8:>DJLRhjp
%139EUW[aosu&>HNPZ\fhrxz#%/5=[egqy  (:@LXZlrv|!35?MSWY]uw"(8@FL^nptz|!'17COacim &>BDHNP\`n+5;GU[eqsw}$*46:HNTX^`jl|'/AEKWY_ek&,:>FPXdvz|
7CIK[agu    ,0NTZ`hnrt
%)+1GMOSegkwy   "<BHLT^~-/59;?AKY_cku{.24:X\dntz!'37=?EIOQ[]ms&*6D`fz~/7=AGU[akmw"*46@HT^vx|#)-5GQW]_eo{}&,28@FPVX^djt|39OQcgoy6>PTV`fhnr#+7IY_ams} (*0:HLdfvx!#-AEGKScioq},48>\^hjptz
'-1=CKW[iu  6<HNPfn
)/=ACIS[aek(6@BNXZjl~5GM]ouw(,24>FPV\dhnpz|'+179EIWims&*28<DHV\`nz~
=AY_eq}*046:LR^

Stack Exchange turns tabs into spaces, so here's a PasteBin with the tabs intact.
Challenge
Find a substring of S that is a valid program in your language of choice that outputs the first M prime numbers, one per line, in order, for some positive integer M.
For example, 2 is a substring of S (it occurs in multiple places but any will do), and 2 is a valid CJam program whose output is
2

which is the first M = 1 prime numbers, one per line, in order.
Similarly, the string 2N3N5 may be a substring of S somewhere, and 2N3N5 is a valid CJam program that outputs
2
3
5

which is the first M = 3 prime numbers, one per line, in order.
Scoring
The submission with the highest M wins. Tie breaker goes to the submission posted first.
Details

There should be no additional output besides the single primes on each line, except for an optional trailing newline after the last line. There is no input.

The substring may be any length as long as it's finite.

The substring may occur anywhere within S. (And S may contain it in multiple places.)

The program must be a full-fledged program. You may not assume it is run in a REPL environment.

The program must run and terminate in a finite amount of time without errors.

"Newline" may be interpreted as any common newline representation necessary for your system/interpreter/etc. Just treat it as one character.

You must give the index of S where your substring starts, as well as the length of the substring if not the substring itself. You may not only show that the substring must exist.
Related: Looking for programs in a huge Boggle board


Prove DeMorgan's laws Using the the ten inferences of the Natural Deduction System prove DeMorgan's laws.
The Rules of Natural Deduction

Negation Introduction: {(P → Q), (P → ¬Q)} ⊢ ¬P

Negation Elimination:  {(¬P → Q), (¬P → ¬Q)} ⊢ P

And Introduction:      {P, Q} ⊢ P ʌ Q

And Elimination:       P ʌ Q ⊢ {P, Q}

Or Introduction:       P ⊢ {(P ∨ Q),(Q ∨ P)}

Or Elimination:        {(P ∨ Q), (P → R), (Q → R)} ⊢ R

Iff Introduction:      {(P → Q), (Q → P)} ⊢ (P ≡ Q)

Iff Elimination:       (P ≡ Q) ⊢ {(P → Q), (Q → P)}

If Introduction:       (P ⊢ Q) ⊢ (P → Q)

If Elimination:        {(P → Q), P} ⊢ Q

Proof structure
Each statement in your proof must be the result of one of the ten rules applied to some previously derived propositions (no circular logic) or an assumption (described below).  Each rule operates across some propositions on the left hand side of the ⊢ (logical consequence operator) and creates any number of propositions from the right hand side.  The If Introduction works slightly differently from the rest of the operators (described in detail below).  It operates across one statement that is the logical consequent of another.
Example 1
You have the following statements:
{(P → R), Q}
You may use And Introduction to make:
(P → R) ʌ Q
Example 2
You have the following statements:
{(P → R), P}
You may use If Elimination to make:
R
Example 3
You have the following statements:
(P ʌ Q)
You may use And Elimination to make:
P
or to make:
Q
Assumption Propagation
You may at any point assume any statement you wish.  Any statement derived from these assumptions will be "reliant" on them.  Statements will also be reliant on the assumptions their parent statements rely on.  The only way to eliminate assumptions is by If Introduction.  For If introduction you start with a Statement Q that is reliant on a statement P and end with (P → Q).  The new statement is reliant on every assumption Q relies on except for assumption P.  Your final statement should rely on no assumptions.
Specifics and scoring
You will construct one proof for each of DeMorgan's two laws using only the 10 inferences of the Natural Deduction Calculus.
The two rules are:
¬(P ∨ Q) ≡ ¬P ʌ ¬Q

¬(P ʌ Q) ≡ ¬P ∨ ¬Q

Your score is the number of inferences used plus the number of assumptions made.  Your final statement should not rely on any assumptions (i.e. should be a theorem).
You are free to format your proof as you see fit.
You may carry over any Lemmas from one proof to another at no cost to score.
Example Proof
I will prove that (P and not(P)) implies Q
(Each bullet point is +1 point)

Assume not (Q)

Assume (P and not(P))

Using And Elim on (P and not(P)) derive {P, not(P)}

Use And Introduction on P and not(Q) to derive (P and not(Q))

Use And Elim on the statement just derived to make P

The new P proposition is different from the other one we derive earlier.  Namely it is reliant on the assumptions not(Q) and (P and not(P)).  Whereas the original statement was reliant only on (P and not(P)).  This allows us to do:

If Introduction on P introducing not(Q) implies P (still reliant on the (P and not(P)) assumption)

Use And Introduction on not(P) and not(Q) (from step 3) to derive (not(P) and not(Q))

Use And Elim on the statement just derived to make not(P)
(now reliant on not(Q))

If Introduction on the new not(P) introducing not(Q) implies not(P)

We will now use negation elimination on not(Q) implies not(P) and not(Q) implies P to derive Q

This Q is reliant only on the assumption (P and not(P)) so we can finish the proof with

If Introduction on Q to derive (P and not(P)) implies Q

This proof scores a total of 11.

Score: 81
Each line should be worth 1 point. The De Morgan's laws are found at statements (3) and (6). Labels in brackets denote the previous statement(s) a line depends on if they are not immediately preceding.
(a) assume P {
    (aa) P ^ P
    (ab) P
    (ac) P v Q
} (a1) P -> P
  (a2) P -> P v Q
(1) assume ~P ^ ~Q {
    (1a) assume P v Q {
        (1aa) assume Q {
            (1aaa) assume ~P {
                (1aaaa) Q ^ Q [1aa]
                (1aaab) Q
                (1aaac) ~Q [1]
            } (1aaa1) ~P -> Q
              (1aaa2) ~P -> ~Q
            (1aab) P
        } (1aa1) Q -> P
        P [1a, a1, 1aa1]
        ~P [1]
    } (1a1) P v Q -> P
      (1a2) P v Q -> ~P
    (1b) ~(P v Q)
} (11) ~P ^ ~Q -> ~(P v Q)
(2) assume ~(P v Q) {
    (2a) ~(P v Q) ^ ~(P v Q)
    (2b) assume P {
        (2aa) ~(P v Q) [2a]
    } (2b1) P -> ~(P v Q)
    (2c) ~P [a2, 2b1]
    (2d) assume Q {
        (2da) ~(P v Q) [2a]
        (2db) P v Q
    } (2d1) Q -> ~(P v Q)
      (2d2) Q -> P v Q
    (2e) ~Q
    (2f) ~P ^ ~Q
} (21) ~(P v Q) -> ~P ^ ~Q
(3) ~(P v Q) == ~P ^ ~Q [11, 21]
(4) assume ~P v ~Q {
    (4a) assume ~P {
        (4aa) assume P ^ Q {
            (4aaa) P
            (4aab) ~P ^ ~P [4a]
            (4aac) ~P
        } (4aa1) P ^ Q -> P
          (4aa2) P ^ Q -> ~P
        (4ab) ~(P ^ Q)
    } (4a1) ~P -> ~(P ^ Q)
    (4b) assume ~Q {
        (4ba) assume P ^ Q {
            (4baa) Q
            (4bab) ~Q ^ ~Q [4b]
            (4bac) ~Q
        } (4ba1) P ^ Q -> Q
          (4ba2) P ^ Q -> ~Q
        (4bb) ~(P ^ Q)
    } (4b1) ~P -> ~(P ^ Q)
    (4c) ~(P ^ Q) [4, 4a1, 4b1]
} (41) ~P v ~Q -> ~(P ^ Q)
(5) assume ~(P ^ Q) {
    (5a) assume ~(~P v ~Q) {
        (5aa) ~(~P v ~Q) ^ ~(P ^ Q) [5, 5a]
        (5ab) assume ~P {
            (5aba) ~P v ~Q
            (5abb) ~(~P v ~Q) [5aa]
        } (5ab1) ~P -> ~P v ~Q
          (5ab2) ~P -> ~(~P v ~Q)
        (5ac) P
        (5ad) assume ~Q {
            (5ada) ~P v ~Q
            (5adb) ~(~P v ~Q) [5aa]
        } (5ad1) ~Q -> ~P v ~Q
          (5ad2) ~Q -> ~(~P v ~Q)
        (5ae) Q
        (5af) P ^ Q [5ac, 5ae]
        (5ag) ~(P ^ Q) [5aa]
    } (5a1) ~(~P v ~Q) -> P ^ Q
      (5a2) ~(~P v ~Q) -> ~(P ^ Q)
    (5b) ~P v ~Q
} (51) ~(P ^ Q) -> ~P v ~Q
(6) ~(P ^ Q) == ~P v ~Q [41, 51]


Minimal Rotate-Right-Double numbers in base n Task

For a given base \$n \ge 3\$, find the smallest positive integer \$m\$, when written in base \$n\$ and rotated right once, equals \$2m\$. The base-\$n\$ representation of \$m\$ cannot have leading zeroes.

The corresponding OEIS sequence is A087502, and its base-\$n\$ representation is A158877 (this one stops at \$n=11\$ because the answer for \$n=12\$ has a digit higher than 9). The OEIS page has some information about how to calculate the number:

  a(n) is the smallest integer of the form x*(n^d-1)/(2n-1) for integer x and d, where 1 < x < n and d > 1. x is the last digit and d is the number of digits of a(n) in base n.

  Maple code:

A087502 := proc(n) local d, a; d := 1; a := n; while a>=n do
  d := d+1; a := denom((2^d-1)/(2*n-1)); od;
return(max(2, a)*(n^d-1)/(2*n-1)); end proc;

You may output the result as a single integer or a list of base-10 or base-\$n\$ digits.

Examples and test cases

For \$ n = 3 \$, the answer is \$ m = 32 \$. \$ n = 4 \$ should give \$ m = 18 \$.

$$
m = 32_{10} = 1012_3 \rightarrow 2m = 64_{10} = 2101_3 \\
m = 18_{10} = 102_4 \rightarrow 2m = 36_{10} = 210_4
$$

n = 3
m = 32
m (base n) = 1012 or [1,0,1,2]
------------------------------
n = 4
m = 18
m (base n) = 102 or [1,0,2]
------------------------------
n = 10
m = 105263157894736842
m (base n) = 105263157894736842 or [1,0,5,2,6,3,1,5,7,8,9,4,7,3,6,8,4,2]
------------------------------
n = 33
m = 237184
m (base n) = 6jqd or [6,19,26,13]
------------------------------
n = 72
m = 340355112965862493
m (base n) = [6,39,19,45,58,65,32,52,26,13]

More I/O examples can be found on OEIS.

Scoring and winning criterion

Standard code-golf rules apply. Shortest solution in bytes wins.

Python 2, 77 76 70 bytes

f=lambda n,m=1,i=1:i<m and f(n,m,i*n)or(m+m%n*i)/n-m*2and f(n,m+1)or m

Try it online!

Input: base n
Output: The smallest integer m satisfies the requirement.

Saved 6 bytes thanks to @Bubbler!

This is a brute-force search that starts at m = 1 and works its way up. Will run out of recursion limit if the actual solution is too large.

For each m, i keeps track of the current power of n, which is increased until i>m.


Calculate the day number of the year Seems like we do not have this one yet, so here we go:

The Challenge

Write a program or function that takes a date as input and outputs the day number of the year. You may not use any builtins for that!

Rules

As usual you may write a full program or a function.
The format of the input is up to you, but it has to contain a year, a month and a day. Make clear which one your solution uses!
No date-related builtins allowed! You gotta do the work by yourself. Builtins which are not related to date operations are fine.
Base for the calcultion is the gregorian calendar.
You have to take account of leap-years.
You only need to handle years in the range [1, 9999]
Standard loopholes are forbidden.
Lowest byte count wins!

Testcases

Input format here is YYYY/MM/DD

2016/07/05 -> 187
2000/03/28 -> 88
0666/06/06 -> 157
6789/10/11 -> 284
0004/04/04 -> 95
1337/07/13 -> 194

Happy Coding!

JavaScript ES6, 81 69 bytes

(y,m,d)=>d+parseInt("03479cehkmpr"[--m],36)+m*28-(y%(y%25?4:16)&&m>1)

Assuming months are 1-based, otherwise I could save 2 bytes.

Edit: Saved 12 bytes using @user81655's tip.


The powerful connection Introduction

There is a plantation defined by one big square-board like this one:

The numbers inside each small square represents its area's value/cash/...

The farmer needs help to find the N squares that connected (it means all N squares should have at least one shared border) give him the greatest value.

For example:

If N=1, then the output must be 140.

If N=6, then..

..the output must be 315.

Challenge

Your program/function must take the the matrix's values and the number N as input/arguments and must output the powerful connection's value.

Since this is code-golf, the shortest answer in bytes wins!

Examples

Input:

10 -7 11 7 3 31
33 31 2 5 121 15
22 -8 12 10 -19 43
12 -4 54 77 -7 -21
2 8 6 -70 109 1
140 3 -98 6 13 20
6

Output: 315

Input:

35 -7
-8 36
2

Output: 29

JavaScript (ES6), 190 bytes

(m,n)=>m.map((a,r)=>a.map((_,c)=>f(r,c,[0],0)),o=f=(x,y,s,t)=>s[n]?o>t?0:o=t:s.indexOf(w=x+","+y)<0&&m[y]&&(v=m[y][x])<1/0&&f(x+1,y,s=[...s,w],t+=v)+f(x,y+1,s,t)+f(x-1,y,s,t)+f(x,y-1,s,t))|o

Explanation

Takes the matrix as an array of arrays.

Starts from each square then uses a recursive function to test every possible combination. This is a brute-force approach, but it finishes almost instantly for the first test case on my machine.

(m,n)=>
  m.map((a,r)=>                 // for each row
    a.map((_,c)=>               // for each column
      f(r,c,[0],0)              // start checking paths from the coordinate of the square
    ),
    o=                          // o = output number (max total)
    f=(x,y,s,t)=>               // recursive function f, x & y = current square, t = total
                                // s = array of used squares (starts as [0] so length = +1)
      s[n]?                     // if we have used n squares
        o>t?0:o=t               // set o to max of o and t
      :s.indexOf(w=x+","+y)<0&& // if the square has not been used yet
      m[y]&&(v=m[y][x])<1/0&&   // and the square is not out of bounds
                                // ( if value of square is less than Infinity )

        // Check each adjacent square
        f(x+1,y,
          s=[...s,w],           // clone and add this square to s
          t+=v                  // add the value of this square to the total
        )
        +f(x,y+1,s,t)
        +f(x-1,y,s,t)
        +f(x,y-1,s,t)
  )
  |o                            // return output

Test

var solution = (m,n)=>m.map((a,r)=>a.map((_,c)=>f(r,c,[0],0)),o=f=(x,y,s,t)=>s[n]?o>t?0:o=t:s.indexOf(w=x+","+y)<0&&m[y]&&(v=m[y][x])<1/0&&f(x+1,y,s=[...s,w],t+=v)+f(x,y+1,s,t)+f(x-1,y,s,t)+f(x,y-1,s,t))|o
<textarea rows="7" cols="40" id="Matrix">10 -7 11 7 3 31
33 31 2 5 121 15
22 -8 12 10 -19 43
12 -4 54 77 -7 -21
2 8 6 -70 109 1
140 3 -98 6 13 20</textarea>

N = <input type="number" id="N" value="6" />

<button onclick="result.textContent=solution(Matrix.value.split('\n').map(x=>x.split(' ').map(z=>+z)),N.value)">Go</button>


Tips for golfing in Pike Pike is a dynamically typed interpreted scripting language, heavily influenced by C, which typically compiles to C99 with a few #defines. (It even has a preprocessor!)

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

Abuse mixed.

Pike is unfortunately not exactly identical to C; for instance the type of a list of strings is array(string), not char[][] or even string[].

Any time you need a type declarator and it's not int, mixed (the "any" type, which gets promoted to the actual type of the RHS at runtime) is liable to be shorter.

A function that takes a list of ints and sorts it, then returns it, for a whopping 41 bytes:

array(int)s(array(int)l){return sort(l);}

Or, the type-inferencing version, which is 31 bytes:

mixed s(mixed l){return sort(l);}

My answer to Manage Trash So uses a lot of mixed.


Programming Dichotomies (Literally) Consider a question written in plain English whose answer involves two reasonably accurate (but potentially clever) words or phrases that can be separated by the word 'and':

Q: What are the two sides of a coin? A: heads and tails
Q: What are the best ways to travel? A: airplane and jetpack
Q: Why is a raven like a writing desk? A: because there is a 'b' in both and an 'n' in neither

Goal
Write a program which, when run normally, outputs such a question.
When every other character is removed from the program starting with the second character and the result is re-run, the output should be whatever is to the left of the 'and' in the answer.
When every other character is removed from the program starting with the first character and the result is re-run, the output should be whatever is to the right of the 'and' in the answer.
(The 'and' itself is not output.)
Example
If the program is
A1B2C3D4E5F6G7H8I9

and its output is
What are the two sides of a coin?

Then the output of ABCDEFGHIshould be heads, and the output of 123456789 should be tails.
Rules about questions and answers

You may use my example questions but I encourage you to make up your own.
The question and the two answer parts:

must all be distinct
should be common grammatical meaningful English
may only contain printable ASCII (hex 20 to 7E)

Ideally the question will be capitalized and punctuated (but the answers do not need to be).
The question must be at least 30 character long and have entropy above or equal to 3.5. (Type in string, hit calculate, look for last H(X).)
The two answer parts (not including the [space]and[space] between them) must each have at least 5 characters with entropy above or equal to 2.
The word 'and' may appear in either answer part.

Rules about code

None of the 3 code snippets may:

contain comments or anything else traditionally ignored by the compiler/interpreter (don't worry about putting an extra semicolon or two in, but if you think it's a comment it probably is)
exit the program in mid-execution

The code may contain any characters, including Unicode and non-printable ASCII.
It may have an odd or even number of characters.
Output goes to stdout or a file or whatever seems reasonable. There is no input.

Scoring
Since I wan't to encourage golfed answers but I want to encourage clever answers even more, the scoring will be something in between code-golf and popularity contest:
Score = (upvotes - downvotes) - floor((bytes in code that outputs question) / 3)
The highest score wins.
(Use http://mothereff.in/byte-counter as a byte counter.)

Javascript (148 bytes)

Creates some nonsense literals, with the side effect of creating an alert* for the question. (the splits doing similar, but creating alerts* for each of the answers).

"';"+alert( 'What is the ideal breakfast???')+/ " ;apl=e"rbta(k"esnc"r.armebplleadc ee g g s(" ) + " \/)k;e"/+ ",t'hceo 'c)a;kye= ailse rat (lpi)e "

Splits:

";+lr('hti h da rafs??)/";p="baken".replace   (    /ke/ ,'co');y=alert(p)

and

'"aet Wa steielbekat?'+  alert("scrambled eggs")+"\);"+"the cake is a lie"

Question: What is the ideal breakfast???

Answers: bacon and scrambled eggs


Number of palindrome splits In this task you will take as input a non-negative integer \$n\$, and output the number of pairs of non-negative integers \$a,b\$ such that both are palindromes*, \$a \leq b\$, and \$a+b = n\$.  For example if \$n\$ is \$22\$ then the valid pairs are

\$
\begin{array}{c|c}
a & b  \\
\hline
0 & 22 \\
11 & 11 \\
\end{array}
\$

So the output is \$2\$.

As another example, if \$n\$ is \$145\$  then the valid pairs are

\$
\begin{array}{c|c}
a & b \\
\hline
4 & 141 \\
44 & 101 \\
\end{array}
\$

So the output is 2.

Your submission should be a program or function.  Answers will be scored in bytes with fewer bytes being the goal.

Test Cases

\$
\begin{array}{c|c c|c}
\mathrm{Input} & \mathrm{Output} & \mathrm{Input} & \mathrm{Output} \\
\hline
0 & 1  & 12 & 5\\
1 & 1  & 13 & 4\\
2 & 2  & 14 & 4\\
3 & 2  & 15 & 3\\
4 & 3  & 16 & 3\\
5 & 3  & 17 & 2\\
6 & 4  & 18 & 2\\
7 & 4  & 19 & 1\\
8 & 5  & 20 & 1\\
9 & 5  & 21 & 0\\
10 & 5 & 22 & 2\\
11 & 5 & 23 & 1\\
\end{array}
\$

OEIS A260254

* In base 10

Jelly, 9 bytes

ŻŒḂ€ḋṚ$HĊ

A monadic Link accepting a non-negative integer which yields a non-negative integer.

Try it online!

How?

Counts all pairs without the \$a\leq b\$ restriction, halves and rounds up. Note that the halved count is only a fraction if \$\frac n 2\$ is a palindrome and in such cases we want to count this \$a=b\$ pair.

ŻŒḂ€ḋṚ$HĊ - Link: integer, n    e.g. 22
Ż         - zero-range               [0,1,2,...,9,10,11,12,...,21,22]
   €      - for each:
 ŒḂ       -   is palindrome (digits) [1,1,1,...,1,0,1,0,...0,1]
      $   - last two links as a monad:
     Ṛ    -   reverse                [1,0,...,0,1,0,1,...,1,1,1]
    ḋ     -   dot-product           3  (=1×1+1×0+...+1×0+1×1+0×1+...+0×1+1×1)
       H  - halve                   1.5
        Ċ - ceil                    2


Can you find the villain's password? Background
You work for the police force as a programmer.
A villain has planted a bomb in the city, luckily the police force has captured both him and the bomb. The bomb is really complicated to disarm, however it has a password input to disarm it.
The villain, being cocky, has told you that there was no way you'd find the password as you'd take X time to brute force it. You notice that the keyboard can only input english letters (lower and upper case) and digits.
Task
Assuming you can try Y passwords per second, and that the brute force character order would be a-z A-Z 0-9, you are to create either a full program or a function that takes as input both X (in seconds) and Y (passwords/second) and outputs the villain's password.
X can be a float but Y will always be an integer.
(X*Y should always be an integer)
Your code has to solve the problem using math instead of relying on trying several options or creating huge arrays and simply indexing them with X*Y.
Example in JS
var c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var b=62;
function num(x){
    var n=0;
    while(x>=0){
        x-=Math.pow(b,++n);
    }
    return n;
}
function reduce(x, n){
    while(--n>0){
        x-=Math.pow(b,n);
    }
    return x;
}
function pass(x, y){
    x=x*y;
    x--;
    var p=[];
    var n=num(x);
    x = reduce(x, n);
    do{
        var t=x%b;
        x=(x-t)/b;
        p.unshift(t);
    }while(x>0);
    return ("a".repeat(n)+p.map(f=>c[f]).join``).substr(-n);
}

Assuming my code is correct here are some example outputs.
(If there are any errors please tell me so that I can correct them)
pass(0.000, 1000); // "" or anything that won't be mistaken for a password
pass(0.001, 1000); // "a"
pass(0.002, 1000); // "b"
pass(0.027, 1000); // "A"

//A password that would take a year to brute force at 1000 passwords/second
pass(3600*24*365, 1000) // "HzmZmr"

My code is awful and ungolfed but it's only to serve as an example. Since this is code-golf shortest answer in bytes wins.

Jelly, 9 bytes

×ḃ62ịØWŒs

Try it online!

How?

×ḃ62ịØWŒs - Main link: X, Y
×         - multiply X by Y
 ḃ62      - convert to bijective base 62 (uses modulo arithmetic under the hood)
    ị     - index into (1-based)
     ØW   - word yield -> "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"
       Œs - swap case


Help me sort my socks! I have a pile of clean socks that I want to sort into pairs. Unfortunately, I can only take socks from either end of the pile, not the middle. Further, I can only remove socks from the pile a matching pair at a time. My strategy is to first split the pile into one or more smaller piles. I think some examples will make this clear. I'll represent each sock as a positive integer (matching integers indicate equal socks).

If the initial pile of socks is

1 2 3 3 2 1

then I don't have to do any splitting. I can remove both 1 socks, then both 2 socks, then both 3 socks.

If instead the initial pile is

1 2 3 2 3 1

then I have to split it first because I won't be able to pair all the socks by just removing them from the end. One possibility is to split it into the two piles

1 2 3 and 2 3 1

Now I can remove the 1 socks, leaving 2 3 and 2 3, followed by the 3 socks, leaving 2 and 2, and finally the 2 socks.

Your Job

Given the initial pile of socks, write a program that will split it into smaller piles that will allow me to sort the socks. Your program should split the pile into the fewest number of piles possible (if there are multiple best solutions, you need only find one).

The input will be given as a list, delimited string, or other convenient form. It will contain only integers between 1 and some maximum value n, with each integer occurring exactly twice.

The output should consist of the input list split into smaller lists, given in any convenient form.

Examples

Input             Sample Output
1 1               1 1
1 2 1 2           1; 2 1 2
1 3 2 4 3 2 1 4   1 3 2; 4 3 2 1 4
1 2 3 4 3 4 1 2   1; 2 3; 4 3 4 1 2
1 1 2 2 3 3       1 1 2; 2 3 3
4 3 4 2 2 1 1 3   4 3 4 2; 2 1 1 3

Note that this isn't the only allowed output for most of these inputs. For the second case, for example, the outputs 1 2; 1 2 or 1 2 1; 2 would also be accepted.

Thanks to Sp3000 for some test suggestions!

I hate spending a long time sorting my clothes, so make your code as short as possible. Shortest answer in bytes wins!

Notes

I don't want to have to look behind a sock to see if its matching pair is there, so taking both socks in a pair from the same end is not allowed. E.g. if the pile is 1 1 2 2 then you wouldn't be able to leave it as one pile and take both 1 socks from the left end.

Pyth, 25 bytes

hf!u #-R.-F{BhMs_BMGGT)./

Test suite

Explanation:

hf!u #-R.-F{BhMs_BMGGT)./
                       ./    Form all partitions (implicitly) of the input.
 f                           Filter the permutations on
   u                 T)      Run the following function on the partition
                             until it reaches a fixed point:
                _BMG         Bifurcate the lists on reversal
               s             Concatenate
             hM              Take the first element of each list.
                             These elements are all the ones on the ends of lists.
           {B                Bifurcate on deduplication
        .-F                  Bagwise subtraction.
                             Only elements repeated in ends of lists remain.
      -R            G        Remove these elements from each list.
   ' #'                      Filter out empty lists.
  !                          Negate. Only an empty list as fixed point succeeds.
h                            Output the first successful partition.


Get as close to pi as you can Your job is to write a program to find the closest number to PI.

Let me clarify.

You will first choose a number type. Let us say you choose Integer (in an actual answer, you cannot). Your program would then have to generate an integer that is closed to PI. For Integers, this would be 3. Not 4; 3.

For every allowed number type, there will be one and only one closest number, as you will see.

Select your number type. It should only be able to represent rational numbers. You can not make up your own number types. Float or Double is recommended.
Your program will generate a number ctp for "close to PI" (I am just calling it that; you don't have to). 223/71 < ctp < 22/7 must be true (this is why you can't choose Integers). Also, ctp must be the closet number to PI in its number type (although see bonus).
No importing libraries for mathematical functions, operations, etc... (although types are allowed as long, as it obeys #1).
You must somehow output ctp.
You also may not hard code any number (in any type) that uses at least half the precision of your chosen number type.

Bonus: If you use a data type with a precision that depends on machine resources, and it still generates the most accurate approximation possible for any given machine, you can take the pith root of your score.
Note: If you code may actually exhaust machine resources, put a warning in. That way people know to use virtual machines to check it (or just check it with their minds).

This is code golf, so shortest program in bytes wins!

Note: The point of this challenge is not just to be another pi calculation challenge. You have to work at the limits of your number type, where all calculations can have detrimental rounding errors. You are doing maximum-precision computing. This is not the same as just outputting a large number of digits.

C++ 158 chars
#include<iostream>
#include<iomanip>
int main(){double p=0;for(long long l=1;l>0;l+=2){p+=(double)4/l;l+=2;p-=(double)4/l;}std::cout<<std::setprecision(30)<<p;}

Simply calculates pi by brute force until my computer can't store the number to divide 4 by.
I got to 3.1415926535792384 before I killed it. The highlighted part is what is off; it should have been 3.1415926535897932.  Eventually, it would have got there.


Interpreter for number theory, modulo n A sentence of number theory (for our purposes) is a sequence of the following symbols:

0 and ' (successor) - successor means +1, so 0'''' = 0 + 1 + 1 + 1 + 1 = 4

+ (addition) and * (multiplication)

= (equal to)

( and ) (parentheses)

the logical operator nand (a nand b is not (a and b))

forall (the universal quantifier)

v0, v1, v2, etc. (variables)
Here is an example of a sentence:

forall v1 (forall v2 (forall v3 (not (v1*v1*v1 + v2*v2*v2 = v3*v3*v3))))

Here not x is shorthand for x nand x -- the actual sentence would use (v1*v1*v1 + v2*v2*v2 = v3*v3*v3) nand (v1*v1*v1 + v2*v2*v2 = v3*v3*v3), because x nand x = not (x and x) = not x.
This states that for every combination of three natural numbers v1, v2, and v3, it is not the case that v13 + v23 = v33 (which would be true because of Fermat's Last Theorem, except for the fact that it would get 0^3+0^3=0^3).
Unfortunately, as proved by Gödel, it is not possible to determine whether or not a sentence in number theory is true.
It is possible, however, if we restrict the set of natural numbers to a finite set.
So, this challenge is to determine whether or not a sentence of number theory is true, when taken modulo n, for some positive integer n. For example, the sentence
forall v0 (v0 * v0 * v0 = v0)

(the statement that for all numbers x, x3 = x)
Is not true for ordinary arithmetic (e.g. 23 = 8 ≠ 2), but is true when taken modulo 3:
0 * 0 * 0 ≡ 0 (mod 3)
1 * 1 * 1 ≡ 1 (mod 3)
2 * 2 * 2 ≡ 8 ≡ 2 (mod 3)

Input and output format
The input is a sentence and positive integer n in any "reasonable" format. Here are some example of reasonable formats for the sentence forall v0 (v0 * v0 * v0 = v0) in number theory modulo 3:
("forall v0 (v0 * v0 * v0 = v0)", 3)
"3:forall v0 (((v0 * v0) * v0) = v0)"
"(forall v0)(((v0 * v0) * v0) = v0) mod 3"
[3, "forall", "v0", "(", "(", "(", "v0", "*", "v0", ")", "*", "v0", ")", "=", "v0", ")"]
(3, [8, 9, 5, 5, 5, 9, 3, 9, 6, 3, 9, 6, 4, 9, 6]) (the sentence above, but with each symbol replaced with a unique number)
"f v0 = * * v0 v0 v0 v0"
[3, ["forall", "v0", ["=", ["*", "v0", ["*", "v0", "v0"]], "v0"]]]
"3.v0((v0 * (v0 * v0)) = v0)"

Input can be from stdin, a command line argument, a file, etc.
The program can have any two distinct outputs for whether the sentence is true or not, e.g. it could output yes if it's true and no if it's not.
You do not need to support one variable being the subject of a forall twice, e.g. (forall v0 (v0 = 0)) nand (forall v0 (v0 = 0)). You can assume that your input has valid syntax.
Test cases
forall v0 (v0 * v0 * v0 = v0) mod 3
true

forall v0 (v0 * v0 * v0 = v0) mod 4
false (2 * 2 * 2 = 8 ≡ 0 mod 4)

forall v0 (v0 = 0) mod 1
true (all numbers are 0 modulo 1)

0 = 0 mod 8
true

0''' = 0 mod 3
true

0''' = 0 mod 4
false

forall v0 (v0' = v0') mod 1428374
true

forall v0 (v0 = 0) nand forall v1 (v1 = 0) mod 2
true (this is False nand False, which is true)

forall v0 ((v0 = 0 nand v0 = 0) nand ((forall v1 (v0 * v1 = 0' nand v0 * v1 = 0') nand forall v2 (v0 * v2 = 0' nand v0 * v2 = 0')) nand (forall v3 (v0 * v3 = 0' nand v0 * v3 = 0') nand forall v4 (v0 * v4 = 0' nand v0 * v4 = 0')))) mod 7
true
(equivalent to "forall v0 (v0 =/= 0 implies exists v1 (v0 * v1 = 0)), which states that every number has a multiplicative inverse modulo n, which is only true if n is 1 or prime)

forall v0 ((v0 = 0 nand v0 = 0) nand ((forall v1 (v0 * v1 = 0' nand v0 * v1 = 0') nand forall v2 (v0 * v2 = 0' nand v0 * v2 = 0')) nand (forall v3 (v0 * v3 = 0' nand v0 * v3 = 0') nand forall v4 (v0 * v4 = 0' nand v0 * v4 = 0')))) mod 4
false

This is code-golf, so try to make your program as short as possible!

Python 2, 252 236 bytes

def g(n,s):
 if str(s)==s:return s.replace("'","+1")
 o,l,r=map(g,[n]*3,s);return['all((%s)for %s in range(%d))'%(r,l,n),'not((%s)*(%s))'%(l,r),'(%s)%%%d==(%s)%%%d'%(l,n,r,n),'(%s)%s(%s)'%(l,o,r)]['fn=+'.find(o)]
print eval(g(*input()))

Try it online!

Takes input as the nested prefix-syntax, with f instead of forall and n instead of nand:

[3, ["f", "v0", ["=", ["*", "v0", ["*", "v0", "v0"]], "v0"]]]


Do you need a cup holder? You're going to replicate the 90's cup holder joke software.

Here's what's it did, and you have to do:

Display the message Do you need a cup holder?
If the user confirms, enter an infinite loop that keeps opening the CDROM drive.
If the user doesn't confirm, silently exit.

You may display the message using either a console message (confirmation is y, decline is n), or display a message window with the two options "Yes" and "No". You can assume the default (or most common) CDROM drive (D: on Windows, /cdrom on linux etc.). Standard loopholes (except built-ins) are forbidden. No additional input nor output may be involved. If your PC has no physical drive, or another "style" of tray, make sure the program is valid.

code-golf, so shortest program in bytes wins.

Trivia: The loop is there to prevent anyone from closing the drive. On desktop drives, the re-open command will be sent while the drive is closing, therefore staying open and not "spilling the coffee".

Bash, 115 69 68 66 bytes

This was written on Mac OS X but it should work on other BSD-based systems as well.

echo Do you need a cup holder?;sed 1q|grep y&&yes drutil\ eject|sh

We echo the prompt, get input with set 1q, and determine whether the user confirmed with grep y. If the user said y, we pipe the infinite output of yes with the string drutil eject to the shell, which will continuously eject the disk tray.

Saved 50 bytes thanks to Digital Trauma!


Loop without 'looping' A question similar to this has been asked a couple of years ago, but this one is even trickier.

The challenge is simple. Write a program (in your language of choice) that repeatedly executes code without using any repetition structures such as while, for, do while, foreach or goto (So for all you nitpickers, you can't use a loop). However, recursion is not allowed, in the function calling itself sense (see definition below). That would make this challenge far too easy.

There is no restriction on what needs to be executed in the loop, but post an explanation with your answer so that others can understand exactly what is being implemented.

For those who may be hung up on definitions, the definition of a loop for this question is:

A programming language statement which allows code to be repeatedly executed.

And the definition of recursion for this question will be your standard recursive function definition:

A function that calls itself.

Winner will be the answer that has the most upvotes on July 16th at 10 AM eastern time. Good luck!

UPDATE:

To calm confusion that is still being expressed this may help:

Rules as stated above:

Don't use loops or goto
Functions cannot call themselves
Do whatever you want in the 'loop'

If you want to implement something and the rules don't explicitly disallow it, go ahead and do it. Many answers have already bent the rules.

Ruby

def method_missing(meth,*args)
  puts 'Banana'
  send(meth.next)
end

def also
  puts "Orange you glad I didn't say banana?"
end

ahem

Demo

Clears its throat, prints "Banana" 3070 times, and also puts "Orange you glad I didn't say banana?".

This uses Ruby's ridiculous just-in-time method definition functionality to define every method that lies alphabetically between the words 'ahem' and 'also' ("ahem", "ahen", "aheo", "ahep", "aheq", "aher", "ahes", "ahet", "aheu", "ahev"...) to first print Banana and then call the next in the list.


Ternary-if Converter In Java/.NET/C/JavaScript/etc. you can use ternary-ifs to shorten if-statements.

For example (in Java):

// there is a String `s` and an int `i`
if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";

Can be shortened with a ternary-if to:

s=i<0?"Neg":i>0?"Pos":"Neut";

Challenge:

Input: A regular if-else (possible with nesting) that sets a single variable.

Output: The converted ternary-if.

Challenge rules:

You can assume all if-else cases are possible without brackets (so each if/else-if/else block has a single body).
You can assume there won't be any spaces, tabs, or new-lines, except for a single space after each else (including at else if).
You can assume the variable names used are always a single lowercase letter ([a-z]).
The values given to the variables can be one of:

Strings (without spaces/tabs/new-lines), which will be surrounded by double-quotes (i.e. "Test", "SomeString", "Example_string", etc.). You can assume the strings will never contain the substrings if or else, nor will it contain spaces, tabs, newlines, (escaped) double-quotes, or the character =. It can contain the characters ><(){}[];?:!&|, but will be in the printable ASCII range only (['!' (33), '~' (126)]).
Integers (i.e. 0, 123, -55, etc.)
Decimals (i.e. 0.0, 0.123, -55.55, etc.)

The values won't ever be mixed. So all variables assigned are integers, and not some are integers and some are strings.
The conditions within parenthesis can contain the following characters =<>!+-/*%&|[], a-z, 0-9. You can assume there won't be any inner parenthesis, and you can also assume there won't be any (confusing) fields of more than one character used (like if(if<0)).
You can assume there won't be any short-cuts like i*=10 instead of i=i*10.
You won't have to handle dangling else cases, so all if can be paired up with an else. I.e. if(a)if(b)r=0;else r=1; isn't a possible input-case. if(a)if(b)r=0;else r=1;else r=2; or if(a&&b)r=0;else if(a&&!b)r=1;else r=-1; are however.
I/O is flexible. Input and Output can be a string, list of characters, read from STDIN, output to STDOUT, etc. Your call.
All ternaries will have a right associativity, as is the standard in most languages (but not in for example PHP).

General rules:

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

Test cases:

Input:   if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";
Output:  s=i<0?"Neg":i>0?"Pos":"Neut";

Input:   if(i%2<1)r=10;else r=20;
Output:  r=i%2<1?10:20;

Input:   if(n<10)if(m<0)i=0;else i=10;else if(m<0)i=-1;else i=1;
Output:  i=n<10?m<0?0:10:m<0?-1:1;

Input:   if(i==1)i=0.0;else i=0.25;
Output:  i=i==1?0.0:0.25;

Input:   if(!a)if(b)r=0;else r=1;else r=2;
Output:  r=!a?b?0:1:2;

Input:   if(a)if(b)r=0;else r=1;else if(c)r=2;else r=3;
Output:  r=a?b?0:1:c?2:3;

Input:   if(a&&b)r=0;else if(a&&!b)r=1;else r=-1;
Output:  r=a&&b?0:a&&!b?1:-1;

Input:   if(i[0]>0)if(j>0)if(q>0)r="q";else r="j";else r="i";else r="other";
Output:  r=i[0]>0?j>0?q>0?"q":"j":"i":"other";

Input:   if(i>0)r="i";else if(j>0)r="j";else if(q>0)r="q";else r="other";
Output:  r=i>0?"i":j>0?"j":q>0?"q":"other";

Input:   if(a>0)if(a<2)x="one";else if(a<3)x="two";else if(a<4)x="three";else x="other";else x="other";
Output:  x=a>0?a<2?"one":a<3?"two":a<4?"three":"other":"other";

Input:   if(b[0]<=b[1])q=5;else if(b[0]==null)q=0;else q=-10;
Output:  q=b[0]<=b[1]?5:b[0]==null?0:-10;

Python 2, 126 121 120 114 100 bytes

lambda s:findall(' (.=)',s)[0]+sub('if.(.*?)\)(.=)?',r'\1?',sub('.{5} (.=)?',':',s))
from re import*

Try it online!

Saved:

-1 byte, thanks to Kevin Cruijssen


Minimum 1's to get 1-expression for n Background

Challenge is inspired by this question.

The 1-expression is a formula that in which you add and multiply the number 1 any number of times. Parenthesis is allowed, but concatenating 1's (e.g. 11) is not allowed.

Here is an example to get the 1-expression for \$19\$:

(1+1)*(1+1)*(1+1+1+1)+1+1+1 = 19

Total number of \$1\$'s is \$11\$ but there is shorter than this:

(1+1)*(1+1+1)*(1+1+1)+1 = 19

Total number of \$1\$'s is \$9\$.

Program

Given a positive integer n output the minimum 1's to get the 1-expression for n.

Notes:

For reference, the sequence is A005245.
This is code-golf so shortest answer in each language wins!

Test cases

Input -> Output | 1-Expression
1 -> 1 | 1
6 -> 5 | (1+1+1)*(1+1)
22 -> 10 | (1+1)*((1+1+1+1+1)*(1+1)+1)
77 -> 14 | (1+1)*(1+1)*((1+1+1)*(1+1+1)*(1+1)+1)+1
214 -> 18 | ((((1+1+1)*(1+1)*(1+1)+1)*(1+1)*(1+1)+1)*(1+1)+1)*(1+1)
2018 -> 23 | (((1+1+1)*(1+1)+1)*(1+1+1)*(1+1+1)*(1+1)*(1+1)*(1+1)*(1+1)+1)*(1+1)

Wolfram Language (Mathematica), 76 71 bytes

If[#<2,1,Min[#+Reverse@#&/@{#0/@Range[#-1],#0/@Most@Rest@Divisors@#}]]&

Try it online!

The recursive approach: define f[n] to be the minimum of f[k]+f[n-k]over all k less than n, and f[d] + f[n/d]over all divisors of n (other than 1 and n itself).


Element-wise string multiplication Inspired by this challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.

How does it work?

Given two strings (for example split and isbn) you will first, truncate the longer one such that they have equal length and then determine their ASCII codes:

split -> spli -> [115, 112, 108, 105]
isbn  -> isbn -> [105, 115,  98, 110]

The next step will be to map them to the range [0..94] by subtracting 32 of each code:

[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115,  98, 110] -> [73, 83, 66, 78]

Now you will multiply them element-wise modulo 95 (to stay in the printable range):

[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]

Add 32 to get back to the range [32..126]:

[74, 85, 76, 89] -> [106, 117, 108, 121]

And the final step is to map them back to ASCII characters:

[106, 117, 108, 121] -> "july"

Rules

You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
The input may consist of one or two empty strings
The input will be characters in the printable range ([32..126])
The output is either printed to the console or you return a string
The output is allowed to have trailing whitespaces

Test cases

"isbn", "split"                  -> "july"
"", ""                           -> ""
"", "I don't matter"             -> ""
"             ", "Me neither :(" -> "             "
"but I do!", "!!!!!!!!!"         -> "but I do!"
'quotes', '""""""'               -> 'ck_iKg'
"wood", "hungry"                 -> "yarn"
"tray", "gzip"                   -> "jazz"
"industry", "bond"               -> "drop"
"public", "toll"                 -> "fall"
"roll", "dublin"                 -> "ball"
"GX!", "GX!"                     -> "!!!"
"4 lll 4", "4 lll 4"             -> "4 lll 4"
"M>>M", "M>>M"                   -> ">MM>"

Note: The quotes are just for readability, in the 6th test case I used ' instead of ".

MATL, 12 bytes

c32-p95\32+c

Try it online!

Explanation

c      % Implicitly input cell array of 2 strings. Convert to 2-row char matrix.
       % This pads the shorter string with spaces
32-    % Subtract 32, element-wise. Each char is interpreted as its ASCII code.
       % Note that padding spaces will give 0.
p      % Product of each column. Since (padding) spaces have been mapped to 0, the
       % product effectively eliminates those colums. So the effect is the same as
       % if string length had been limited by the shorter one
95\    % Modulo 95, element-wise
32+    % Add 32, element-wise
c      % Convert to char. Implicitly display


Javascript left-pad golf Introduction

In the wake of the left-pad npm package fallout, let's have a code golf for implementing left-pad.

The left-pad function consists of 2 default arguments and 1 additional argument, in the form string, length, (padchar). If the padchar is not given, this is standardized to a space character. Let's take an example with two arguments:

left_pad("abc", 6)

First, we observe the length of the string, which is 3. After this, we need to pad this string in the left until the length of the full string has reached the length given in the function. In this case 6. Since the padchar is not given, we need to pad this with spaces:

   abc

This is a string with 3 spaces and the initial string, resulting into a string with length 6. Here is an example with the padchar given:

left_pad("abc", 6, "-")

We just do the same as the example above, but replace the spaces with the padchar. In this case, the hyphen:

---abc

The Task

Given the string, length, and maybe the additional argument padchar, output the left-padded string. You can assume that the length number is equal or greater than the length of the string. The padchar will always consist of 1 character.

Test cases

left_pad("string", length, ("padchar")) === "left-padded string"

left_pad("foo", 5) === "  foo"
left_pad("foobar", 6) === "foobar"
left_pad("1", 2, "0") === "01"
left_pad("1", 2, "-") === "-1"

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

Pyth, 13 11 bytes

+*.xwd-Qlzz

Try it here.

Takes input from STDIN as the string on the first line, length on the second line, and padding char optionally on a third line.