Am I a Special N-bonacci Number? The N-bonacci sequence, originally invented by @DJMcMayhem in this question, is a sequence generated by starting with the integers 0 and 1, and then adding the previous N numbers to generate the next number.  The special N-bonacci sequence is an N-bonacci sequence beginning with a pair of numbers other than 0 and 1, which will be named X and Y.  If N is greater than the number of terms already in the sequence, simply add all available terms.

So for example the normal fibonacci sequence has an N of 2 (takes the previous two items), and an X and Y of 0 and 1, or 1 and 1, depending on who you ask.

Your Task:

You are to write a program or function that checks whether an inputted integer (A) is part of the special N-bonacci sequence generated by the next three integers (using the second input as N, and the third and fourth as X and Y).  Ensure that you handle the special case of N=1.

Input:

Four non-negative integers, A, N, X, and Y.

Output:

A truthy/falsy value that indicates whether A is part of the N-bonacci sequence generated by the N, X, and Y inputs.

Test Cases:

Input:    Output:
13,2,0,1->truthy
12,3,1,4->falsy
4,5,0,1-->truthy
8,1,8,9-->truthy
9,1,8,9-->truthy

12,5,0,1->falsy  [0,1]>[0,1,1]>[0,1,1,2]>[0,1,1,2,4]>[0,1,1,2,4,8]>[0,1,1,2,4,8,16]>etc.

Scoring:

This is code-golf, so the lowest score in bytes wins.

05AB1E, 18 bytes

[DR²£O©‚˜³®>‹#]³QZ

Try it online!

Uses: [X,Y], N, A

I feel like some unintended functionality made that harder than it needed to be.

There's no greater-than-or-equal-to, never noticed that before.

And #³ didn't work, and required a ], for +1 bytes #]³.


Solve the Rotation puzzle On some old Nokia phones, there was a variation of the fifteen puzzle called Rotation. In this variation, instead of sliding one tile at a time, you rotated four tiles at a time in one direction.

In this game, you'd start out with a board like this:

4 9 2
3 5 7
8 1 6

And by rotating the lower-left block twice clockwise and the upper-left block once clockwise, you'd get this:

4 9 2
8 3 7
1 5 6

4 9 2
1 8 7
3 5 6

1 4 2
8 9 7
3 5 6

and the 1 tile would be in the top-left corner where it's supposed to be. Eventually, after a few more moves, you'd end up with:

1 2 3
4 5 6
7 8 9

which is the "original" configuration.

Your task is to build a program that will take as input a 3x3 grid of numbers from 1 to 9 (in any format you choose) and return as output a sequence of moves representing the moves you must take to return the board back to its original configuration (again, in any format you choose). The legal moves are defined as moving the [top/bottom]-[left/right] block of 4 tiles [clockwise/counterclockwise].

Your program must be able to solve all possible 3x3 grids (all permutations are solvable).

The shortest code to do this wins.

GolfScript, 39/83 bytes

# Optimized for size:

{.4rand.p.2/+>`{?1420344440`=}+$..$>}do

# Optimized for speed:

6,(7++:t;~{.(1=.@7=9=+4\-rand+..2/+@.@>:s^[3s=0s=2s=4s=1s=]+s|.)9<\t>|}do.$>30764`*

Speed vs size

The size-optimized version randomly chooses clockwise rotations until the desired permutation is achieved. This is sufficient, since a counterclockwise rotation is equivalent to three consecutive clockwise rotations of the same square.

The speed-optimized version does the same, except for the following:

If the number 1 is in the upper left corner, it doesn't rotate the upper left square anymore.
If the number 9 is in the lower right corner, it doesn't rotate the lower right square anymore.
The steps for swapping positions 7 and 8 are hardcoded, so there are two positions that allow the loop to break.

Aside from changing the algorithm, the speed-optimized version achieves the rotation in a straightforward manner, while the size-optimed version uses GolfScript's built-in sort by mapping. It also hardcodes the final state (for comparison) instead of sorting the state in every iteration.

The speed-optimized version requires fewer iterations and every iteration is much faster by itself.

Benchmarks

I have used the following code to randomize the positions of the numbers and perform test runs, uncommenting the line corresponding to the version to be tested:

[{[
    0:c;10,1>{;2 32?rand}$
    #{c):c;.4rand.2/+>`{?1420344440`=}+$..$>}do
    #6,(7++:t;{.(1=.@7=9=+4\-rand+..2/+@.@>:s^[3s=0s=2s=4s=1s=]+s|.)9<\t>|}do.$>30764`*
],c+}\~*]

$.0='Min: '\+puts .-1='Max: '\+puts ..{+}*\,/'Avg: '\+puts .,2/='Med: '\+

The output shows the minimum and maximum number of steps it took to order the numbers, the the average and the median of all runs, as well as the elapsed time in seconds:

$ TIME='\n%e s' time golfscript rotation-test-size.gs <<< 100
Min: 4652
Max: 2187030
Avg: 346668
Med: 216888

21500.10 s
$
$ TIME='\n%e s' time golfscript rotation-test-speed.gs <<< 1000
Min: 26
Max: 23963
Avg: 3036
Med: 2150

202.62 s

On my machine (Intel Core i7-3770), the mean execution time of the size-optimized version was 3.58 minutes. The mean execution time of the speed-optimized version was 0.20 seconds. Thus, the speed-optimized version is approximately 1075 times faster.

The speed-optimized version yields 114 times less rotations. Performing each rotation is 9.4 times slower, which is mainly due to how the state is updated.

I/O

The output consists of 3-bit numbers. The MSB is set for counterclockwise rotations, the middle bit is set for lower squares and the LSB is set for right squares. Thus, 0 (4) is the upper left square, 1 (5) the upper right one, 2 (6) the lower left and 3 (7) the lower right one.

The speed-optimized version prints all rotations on a single line. The size-optimized version prints one rotation per line, followed by the final position of the numbers.

For the speed-optimized version, the input has to yield an array containing the numbers from 1 to 9 when evaluated. For the size-optimized version, the input has to be a string without final newline; it does not get evaluated.

Example runs:

$ echo -n '253169748' | golfscript rotation-size.gs
3
0
123456789
$ golfscript rotation-speed.gs <<< '[5 4 7 1 2 9 3 8 6]'
2210300121312212222212211121122211122221211111122211211222112230764

Size-optimized code

{               #
  .             # Duplicate the state.
  4rand         # Push a randomly chosen integers between 0 and 3.
  .p            # Print that integer.
  .2/+          # Add 1 to it if it is grater than one. Possible results: 0, 1, 3, 4
  >`            # Slice the state at the above index.
  {             # Push a code block doing the following:
    ?           # Get the index of the element of the iteration in the sliced state.
    1420344440` # Push the string "14020344440".
    =           # Retrieve the element at the position of the computed index.
  }+            # Concatenate the code block with the sliced state.
  $             # Sort the state according to the above code block. See below.
  ..$>          # Push two copies of the state, sort the second and compare the arrays.
}do             # If the state is not sorted, repeat the loop.

Updating the state is achieved in the following fashion:

Rotation 2 yields the integer 3 after adding 1. If the state is “123456789”, slicing the state yields “456789”.

Right before executing “$”, the topmost elements of the stack are:

[ 1 2 3 4 5 6 7 8 9 ] { [ 4 5 6 7 8 9 ] ? "1420344440" = }

“$” executes the block once for every element of the array to be sorted, after pushing the element itself.

The index of 1 in “[ 4 5 6 7 8 9 ]” is -1 (not present), so the last element of "1420344440" is pushed. This yields 48, the ASCII code corresponding to the character 0. For 2 and 3, 48 gets pushed as well.

The integers pushed for 4, 5, 6, 7, 8 and 9 are 49, 52, 50, 48, 51 and 52.

After sorting, the first element of the state will be one of the elements yielding 48; the last will be one of those yielding 52. The built-in sort is unstable in general, but I've verified empirically that it is stable in this particular case.

The result is “[ 1 2 3 7 4 6 8 5 9 ]”, which corresponds to a clockwise rotation of the lower left square.

Speed-optimized code

6,(7++:t;       # Save [ 1 2 3 4 5 7 ] in variable “t” and discard it.
~               # Interpret the input string.
{               #
  :s            # Duplicate the current state.
  (1=           # Unshift the first element and push 1 if it is equal to 1 and 0 otherwise.
  .@            # Duplicate the boolean and rotate the unshifted array on top of it.
  7=9=          # Push 1 if the eighth element of “s” is equal to 9 and 0 otherwise.
  +4\-          # Add the booleans and subtract their sum from 4.
  rand          # Push a randomly chosen integers between 0 and the result from above.
  +.            # Add this integer to the first boolean and duplicate it for the output.
  .2/+          # Add 1 to the result if it is grater than one. Possible results: 0, 1, 3, 4
  @.            # Rotate the state on top of the stack and duplicate it.
  @>:s          # Slice the state at the integer from above and save the result in “s”.
  ^             # Compute the symmetric difference of state and sliced state.
  [             # Apply a clockwise rotation to the sliced array:
    3s=         # The fourth element becomes the first.
    0s=         # The first element becomes the second.
    2s=         # The third element remains the same.
    4s=         # The fifth element becomes the fourth.
    1s=         # The second element becomes the fifth.
  ]             # Collect the results into an array.
  +             # Concatenate with array of elements preceding the slice.
  s|            # Perform set union to add the remaining elements of “s”.
  .             # Duplicate the updated state.
  )9<           # Pop the last element; push 0 if it is equal to 9 and 1 otherwise.
  \t            # Swap the popped state on top and push [ 1 2 3 4 5 7 ].
  >             # Push 0 if the state begins with [ 1 2 3 4 5 6 ] and 1 otherwise.
  |             # Take the logical OR of the booleans.
}do             # If the resulting boolean is 1, repeat the loop.
.$              # Duplicate the state and sort it.
>30764`*        # If the state was not sorted, 7 and 8 are swapped, so push "30764".

Observe that the rotations 3, 0, 7, 6 and 4 swap the elements in positions 7 and 8, without altering the positions of the remaining seven elements.


Who will win the election? This is a challenge in which two people, 1 and 2, are running for office. People deterministically vote in certain ways in the world of 1 and 2, which can allow for the candidates to figure out the results before the election.

NOTE: this is not meant to refer to any outside elections or other political events.

Two people are running for office. We'll call these people 1 and 2. Because they both want to know if they will win the election, they decide to use their knowledge of people and some code to figure out what the result will be. Due to the want to minimize government spending, the code needs to be a short as possible.

Your task: Given a string of people based on how they are voting, output who wins the election.

There are five kinds of people in the fun and exciting world of 1 and 2:

A: people who will definitely vote for 1.
B: people who will definitely vote for 2.
X: people who will vote for whoever the person to their left will vote for. If there is no person to their left, then they vote for whoever the person at their right will vote for. If it is not clear who the person to their right is voting for, then they do not vote.
Y: people will vote the opposite of the person to their left. If there is no person to their left, then they vote opposite of whoever is at their right. If it is not clear who the person to their right is voting for, then they do not vote.
N: people who do not vote.

This is evaluated from left to right.

Example:

Whoever is being "evaluated" is in lowercase, for clarity.

Input: `XXAYAN`
        xX      Votes for whoever their friend is voting for. Their friend has not decided yet, so it is unclear, so they do not vote.
        Xx      Person to left is voting "none" so votes "none."
          a     Votes for 1
          Ay    Since person on left is voting for 1, votes for 2.
            a   Votes for 1
             n  Does not vote

Final poll:

2 people voted for 1
1 people voted for 2
3 people did not vote

1 has the most votes, so 1 wins!

Test cases:

You may use other characters or values as input and output, as long as they are distinct. (For example: numbers instead of letters, different letters, lowercase letters, truthy/falsy or positive/negative (for output), etc.)

Input -> Output

"AAAA" -> 1
"BBBB" -> 2
"BBAXY" -> 2
"BAXYBNXBAYXBN" -> 2
"XXAYAN" -> 1
"AAAABXXXX" -> 2
"AXNXXXXAYB" -> 1
"NANNY" -> 1
"XA" -> 1
"YAB" -> 2
"XY" -> anything (do not need to handle test cases with no victor)
"AB" -> anything (do not need to handle test cases with no victor)

Java 8, 153 141 135 131 129 bytes

a->{int l=a.length,t,r=0,i=-1;for(;++i<l;r+=(t=a[i]=a[i]>4?t<3?t^3:3:a[i]>3?t:a[i])>2?0:3-t*2)t=a[i>0?i-1:i<l-1?i+1:i];return r;}

Uses an integer array as input with A=1, B=2, N=3, X=4, Y=5 and outputs a positive integer (>= 1) if A wins, a negative integer (<= -1) if B wins, or 0 if it's a draw.
-18 bytes thanks to @OlivierGrégoire.
Try it online.
Explanation:
a->{                      // Method with int-array parameter and boolean return-type
  int l=a.length,         //  Length of the input-array
      t,                  //  Temp integer, uninitialized
      r=0,                //  Result-integer, starting at 0
  i=-1;for(;++i<l         //  Loop `i` in the range [0, l):
           ;              //    After every iteration:
            r+=           //     Increase the result by:
             (t=a[i]=     //       Change `i`'th item in the array to:
                 a[i]>4?  //        If the `i`'th item is a 5:
                  t<3?    //         If `t` is 1 or 2:
                   t^3    //          Use `t` Bitwise-XOR 3 to invert it
                          //          (1 becomes 2; 2 becomes 1)
                  :       //         Else (`t` is 3, 4, or 5 instead):
                   3      //          Set it to 3
                 :a[i]>3? //        Else-if the `i`'th item is a 4:
                  t       //         Set it to `t`
                 :        //        Else (the `i`'th item is a 1, 2 or 3):
                  a[i])   //         Leave it unchanged
             )>2?         //      And if this new `i`'th value is 3, 4, or 5:
              0           //       Leave the result the same by increasing it with 0
             :            //      Else (it's 1 or 2 instead):
              3-t*2;      //       Increase it by 3 minus two times the `i`'th value
                          //       (which is 1 for 1; and -1 for 2)
         t=               //   Set `t` to:
           a[i>0?         //    If `i` is not the first item:
              i-1         //     Set `t` to the previous (`i-1`'th) value
             :i<l-1?      //    Else-if `i` is not the last item:
              i+1         //     Set `t` to the next (`i+1`'th) value
             :            //    Else (`i` is the first or last item):
              i];         //     Set `t` to the current item itself
  return r;}              //  Return the result
                          //  (positive if A wins; negative if B wins; 0 if it's draw)


Output the first 200 primes using TeX Write a plain TeX program that lists the first two hundred primes (in base-10 notation). Including external files/resources is not permitted. The output may be to the terminal, the log file, or the actual dvi/pdf file, at your option, but should be easily readable to a human; in particular, there must be some delimiter (comma, space, newline,...) between consecutive primes. e-TeX and pdfTeX primitives are permitted. See this answer for a starting place.

Hard-coding the result is permitted, although I do not expect such an answer to win.

The answer with the lowest byte count wins.

176 bytes (plain TeX without e-TeX or pdfTeX)

\let\n\newcount\n~\n\j\n\k2~3\loop\ifnum~<1224{\let\x.\j3\loop\ifnum\j<~\k~\divide\k\j\multiply\k\j\ifnum\k=~\let\x!\fi\advance\j2\repeat\ifx\x., \the~\fi}\advance~2\repeat\end

Algorithm

The algorithm is quite simple. It outputs the first prime number 2 and goes from the next prime number 3 to the 200th prime number 1223.
Each number i is tested, if the odd number is divisible by 3 up to i-1 without even numbers (thanks Howard for the removal of the even numbers).

There is much room for optimizations of the run-time, e.g.:

The inner loop can be aborted, when the first divisor is found, see the comments.
The divisions only need to be done up to sqrt(i).

The result is a paragraph with comma separated numbers:

Ungolfed version

% assign some count registers with short names
\newcount\i
\newcount\j
\newcount\k
% Output first prime number 2
2%
% Start loop with second prime number 3
\i=3 %
\loop
\ifnum\i<1224 % 1223 is 200th prime number
  {% group with curly braces because of the nested \loop
    \let\x=. % \x is changed, if \i is not prime
    % Test for all 2 <= j < i: trunc(i/j)*j == i
    % If true, then j is divisor of i and i is not prime
    \j=3
    \loop
    \ifnum\j<\i
      \k=\i
      \divide\k by \j
      \multiply\k by \j
      \ifnum\k=\i
        \let\x=! % \i is not prime
        % Optimization to break the loop:
        %   \let\iterate\empty
        % Then also \x can be removed: If the loop is not aborted,
        % then \iterate will have the meaning \relax and the
        % test "\ifx\x." can be replaced by "\ifx\iterate\relax".
      \fi
      \advance\j by 2
    \repeat
    \ifx\x.
      , \the\i % output prime number
    \fi
  }%
  \advance\i by 2 % test next odd number
\repeat
\end % end of job

Variant: Output in protocol file, 195 bytes

\let\n\newcount\n~\n\j\n\k~2\def\w{\wlog{\the~}}\w~3\loop\ifnum~<1224{\let\x.\j3\loop\ifnum\j<~\k~\divide\k\j\multiply\k\j\ifnum\k=~\let\x!\fi\advance\j2\repeat\ifx\x.\w\fi}\advance~2\repeat\end

The result is written to the .log file:

This is TeX, Version 3.1415926 (TeX Live 2013) (format=tex 2013.5.21)  11 MAR 2014 18:33
**test
(./test.tex
~=\count26
\j=\count27
\k=\count28
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229
233
239
241
251
257
263
269
271
277
281
283
293
307
311
313
317
331
337
347
349
353
359
367
373
379
383
389
397
401
409
419
421
431
433
439
443
449
457
461
463
467
479
487
491
499
503
509
521
523
541
547
557
563
569
571
577
587
593
599
601
607
613
617
619
631
641
643
647
653
659
661
673
677
683
691
701
709
719
727
733
739
743
751
757
761
769
773
787
797
809
811
821
823
827
829
839
853
857
859
863
877
881
883
887
907
911
919
929
937
941
947
953
967
971
977
983
991
997
1009
1013
1019
1021
1031
1033
1039
1049
1051
1061
1063
1069
1087
1091
1093
1097
1103
1109
1117
1123
1129
1151
1153
1163
1171
1181
1187
1193
1201
1213
1217
1223
 )
No pages of output.

Variant: Counting prime numbers, 197 bytes

The following variant also counts the prime numbers to get rid of the "hard-coded" 200th prime number. (I have added this variant at the end, because the question would also allow to hard-code all prime numbers.)

\let\a\advance\let\n\newcount\n\p\n~\n\j\n\k2\p1~3\loop\ifnum\p<200{\let\x.\j3\loop\ifnum\j<~\k~\divide\k\j\multiply\k\j\ifnum\k=~\let\x!\fi\a\j2\repeat\ifx\x., \the~\global\a\p1\fi}\a~2\repeat\end


Closest Woodall Prime A Woodall Prime is a prime which can be calculated, given a positive integer n, with n * 2^n - 1.

Your task is to, given a integer k, generate a Woodall Prime with k digits. If no such Woodall Prime exists, you must generate a Woodall Prime with the closest amount of digits. If two primes exist with the same digit count difference, you may use either.

You may assume that there exists no two Woodall Primes with the same amount of digits.

There is no time complexity limit, and you must be able to handle at least the first ten Woodall Primes (you can see them in the OEIS link at the start of the question)

You may write a full program or a function, and you may print or return the output.

Examples:

1 -> 7
4 -> 383
0 -> 7
-100 -> 7
7 -> 383 or 32212254719 (you may pick either of these)
8 -> 32212254719

As this is code-golf, that shortest code wins!

(there are only nine Woodall Primes on the linked OEIS sequence, so you might want to look at this for more Woodall Primes: https://oeis.org/A002234)

Brachylog, 28 26 bytes
:K≜+ℕ~lṗ.+₁~×[İ,J]h:2^₍J≜∧

Try it online!
This is too slow for TIO for inputs bigger than 4.
Explanation
:K                             The list [Input, K]
  ≜                            Assign a value to K (0, then 1, then -1, then 2, etc.)
   +ℕ                          Input + K >= 0
     ~l .                      Output is a number of length (Input + K)
       ṗ.                      Output must be a prime number
         +₁                    Output + 1...
           ~×[İ,J]             ... = İ × J, İ being an integer...
                  h:2^₍J       ... and J = 2^İ
                         ≜∧    Check that it is possible to find a value for İ that satisfies
                                 all of those constraints. If not, go back to the beginning
                                 and try another value for K through backtracking.

We use a common trick in Brachylog for "find the closest X to Y": labeling a completely free variable (which we do when we use ≜ on the list [Input, K] will label it with this pattern: 0, 1, -1, 2, -2, 3, .... Therefore, when backtracking if the value Input + K doesn't work as the number of digits, the next choice we will try will be the next possible closest choice.


Generalise perfect numbers Let \$\sigma(n)\$ represent the divisor sum of \$n\$ and \$\sigma^m(n)\$ represent the repeated application of the divisor function \$m\$ times.
Perfect numbers are numbers whose divisor sum equals their double or \$\sigma(n) = 2n\$. For example, \$\sigma(6) = 12 = 2\times6\$
Superperfect numbers are numbers whose twice iterated divisor sum equals their double. For example, \$\sigma^2(16) = \sigma(\sigma(16)) = \sigma(31) = 32 = 2\times16\$
\$m\$-superperfect numbers are numbers such that \$\sigma^m(n) = 2n\$ for \$m \ge 1\$. For \$m \ge 3\$, there are no such numbers.
\$(m,k)\$-perfect numbers are numbers such that \$\sigma^m(n) = kn\$. For example, \$\sigma^3(12) = 120 = 12\times10\$, so \$12\$ is a \$(3,10)\$-perfect number.
You are to choose one of the following three tasks to do:

Take three positive integers \$n, m, k\$ and output the \$n\$th \$(m,k)\$-perfect number (0 or 1 indexed, your choice)
Take three positive integers \$n, m, k\$ and output the first \$n\$ \$(m,k)\$-perfect numbers
Take two positive integers \$m, k\$ and output all \$(m,k)\$-perfect numbers

You may assume that the inputs will never represent an impossible sequence (e.g. \$m = 5, k = 2\$) and that the sequences are all infinite in length. You may take input in any convenient method.
Note that methods that count up starting from either \$m\$ or \$k\$ are not valid, as they fail for \$(4,4)\$-perfect numbers, the smallest of which is \$2\$ (credit to Carl Schildkraut for finding this)
This is code-golf so the shortest code in bytes wins.

Test cases
This lists the first few outputs\${}^*\$ for example inputs of \$(m, k)\$
m, k -> out
3, 10 -> 12, 156, 32704, ...
2, 2 -> 2, 4, 16, 64, 4096, 65536, ...
1, 2 -> 6, 28, 496, 8128, ...
4, 48 -> 160, 455, 5920, ...
3, 28 -> 4480, ...
3, 16 -> 294, 6882, ...
1, 4 -> 30240, 32760, ...
4, 4 -> 2, ...

\${}^*\$: Aka, the outputs I could get from my generating program without timing out on TIO

PowerShell, 95 92 87 bytes
-8 bytes thanks to mazzy!
This takes two parameters, m and k, and calculates all (m,k) perfect numbers (up to the maximum for a 64-bit signed integer).

param($m,$k)for(;$n=++$x){1..$m|%{$a=0;1..$n|%{$a+=$_*!($n%$_)};$n=$a}
,$x*!($a-$k*$x)}

Try it online!


Self-Interpreting Interpreter Based on a comment by George Edison to this question, write the smallest self-interpreting interpreter.

You may use the language of your choosing.
Empty languages do not count.  Your program must be at least two characters long.
The program does not need to interpret the entire language, just a Turing-complete subset of language features (that contains the interpreter).
Quines don't count.
Do not use your language's built-in eval function or equivalent. Same goes for apply, etc.


Build a Mastermind engine For reference to the game of Mastermind: Solving Mastermind in 6 or less moves

In the version of Mastermind used in this problem, the operating string is a 4-digit number, from 0000 to 9999, represented as either numbers from 0 to 9999 or strings of consecutive digits "0000" to "9999" in input.

Your task is to build a function that will take two numbers/strings secret and guess as input, and return two numbers A and B, the number of red and white pegs respectively.

The shortest code in any language to do this wins.

J: 40 26 29 22

=,&(+/)(~:#[)e.&~.~:#]

change: don't laminate, but work truly dyadically, eliminating need for explicit ranks ("1), lamination(,:) and between (/)
change: don't count duplicate characters twice
change: Strings are more efficient as they don't need parsing

This verb takes a left and right argument a string from '0000' to '9999'.
It takes care of doubles and excludes exact matches from checking correct numbers but wrong place.

Test cases:

NB. Give the beast a name
mm=: =,&(+/)(~:#[)e.&~.~:#]
NB. make 6 by 4 arrays of the inputs
secret =: (, ;. _2) '1254 1234 5441 5441 5441 5441 '
guess  =: (, ;. _2) '1342 1111 1234 4531 4441 5441 '

NB. Apply the verb on each pair of secret/guess
'1111' mm '1231'
2 0

NB. A whole bunch of test cases with formatting and printing of the inputs:
secret ([,' ',(":@mm),' ',])"1 guess

NB. output:
1254 1 2 1342
1234 1 0 1111
5441 0 2 1234
5441 1 2 4531
5441 3 0 4441
5441 4 0 5441

A little bit of explanation, reading from right to left:

NB.   ExactMatch: checks where digits correspond:
ExactMatch =: =

NB.   GoodDigitWrongPlace: Copies non-matched numbers from both arguments (left and right
NB.   pairs of parentheses, and checks them for same elements(e.), after eliminating
NB.   doubles in both (&~.)
GoodDigitWrongPlace =: (~: # [) (e.&~.) (~: # ])

NB.   Piecing the conditions together, after summing the booleans:
mm =: ExactMatch ,&(+/) GoodDigitWrongPlace


Convert Gemtext to HTML Gemtext is a very simple markup format used by the alternative web protocol Gemini. Write a Gemtext to HTML converter.
From the Wiki:

A line of text is a paragraph, to be wrapped by the client. It is is
independent from the  lines coming before or after it.
A list item starts with an asterisk and a space. Again, the rest of
the line is the line item, to be wrapped by the client.
A heading starts with one, two, or three number signs and a space. The
rest of the line is the heading.
A link is never an inline link like it is for HTML: it’s simply a line
starting with an equal-sign and a greater-than sign: “=>”, a space, an
URI, and some text. It could be formatted like a list item, or like a
paragraph. Relative URIs are explicitly allowed.
Example:
# This is a heading
This is the first paragraph.
* a list item
* another list item
This is the second paragraph.
=> http://example.org/ Absolute URI
=> //example.org/ No scheme URI
=> /robots.txt Just a path URI
=> GemText a page link

This should produce this HTML tree (just the equivalent tree, not the exact formatting):
EDIT you don't need the
 tags to produce valid HTML

This is a heading

This is the first paragraph.

a list item

another list item

This is the second paragraph.

Absolute URI
No scheme URI
Just a path URI
a page link

All text must pass through. All of <>"& should be converted to HTML entities, even if they don't confuse browsers, to be safe
EDIT: For the sake of this question, you don't have to do 2nd and 3rd level headings
This is code-golf so the shortest code in bytes wins


The real treasure was the numbers we made along the way Your task is to write a program, function or snippet (yes, snippets are allowed) that simply outputs an integer. However, you must be able to separate your submission into prefixes that also produce distinct integers. You cannot use any bytes that have appeared in previous prefixes. For example, we can have the prefixes:

1         # 1    (Now we can't use 1)
1-6       # -5   (Now we can't use - or 6)
1-6/3     # -1   (Now we can't use / or 3)
1-6/3+0xA # 9    Final submission

Rules

Your goal is to create to try and create the most unique integers, while keeping them close to zero.

The scoring system is ((number of unique integers)**3)/(sum of absolute values), where the higher your score, the better. The above example scores \$(4^3)/(1+\lvert-5\rvert+\lvert-1\rvert+9) = 64/16 = 4\$.

There should be at least two unique integers (no dividing by zero!)
Please format your answer similar to:

# Language, \$(4^{3})/16 = 4\$

   1-6/3+0xA (the full program)

Mention if your submission is composed of snippets that evaluate to a value, functions or full programs.
List each of the prefixes and (optionally) an explanation for how they work.

TI-BASIC (TI-84+ CE), \$238^3/14161 = 952.0\$

118-length("+×/ABCDEFGHIJK...

The 256 bytes in TI-BASIC break down thusly:

240 bytes are one-byte tokens that can be quoted
11 are the start of two-byte tokens
2 are unused
The remaining 3 are the ",→, and newline characters which break strings.

The string contains all 237 allowable bytes in the first category not already in 118-length(.

The program calculates 238 distinct integers, ranging from 118 down to -119. The score is therefore $$ \frac{238^3}{\sum_{n = -119}^{118} |n|} = 952.$$


Anonymize names - sort of Edit: There will be a bonus of -20 for random masking

Hello fellow Whistleblowers and carriers of secret knowledge.

I am due to an interview by mail and I - of course - cannot say specific names in full length. But as I want to disclose it in a rather not-so-obvious-way I need your help.

I will provide these names in the form of

  "evil_company_that_makes_me_shiver"

but surely I do not want to spell it out completely. Your task to help me and the whole world is that you provide a nice program that turns the above into

"ev**************************"

or

"**il************************"

or even

"****_c**********************"

I think you get it. But there is one flaw: I want to disclose the name in total, so I need to pass the number of occurrences and the word itself to the script and it will disclose the letters bit by bit. An example could be

~$ ./whistle NSA 3
> "N**"
> "**A"
> "*S*"

or

~$ ./whistle nuclear 3
> "nu*****"
> "***lea*"
> "**c***r"

or

~$ ./whistle nuclear 2
> "nuc****"
> "***lear"

I hope you can help me and as we know that size matters the shortest code wins. Help make this world a better place!

GolfScript, 26 charaters
Since no specific way of disclosure was specified I decided to go for the shortest:
:f,\`{{\)f%.!@42if}%\;n}+%

You may experiment with this code online.
Example:
> "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 7
******G******N******U*****
*****F******M******T******
****E******L******S******Z
***D******K******R******Y*
**C******J******Q******X**
*B******I******P******W***
A******H******O******V****

Commented code:
:f           # Save the second input to variable f
,            # Makes the array [0 1 2 .... f-1]
\`{          # \´{}+% builds a code block where
             # first the input string is pushed (done
             # via the + operator and afterwards the whole
             # block is applied to above array, i.e.
             # For each line 0, 1, ...
             #   Here, the stack contains the line number (counter)
             #   and the string
  {          #   {}% -> map to each character of the string
             #     Stack contains counter and current character
    \)f%     #     Increase the counter by one and calculate modulo f
    .        #     Duplicate counter (will be used for the if below)
    !        #     and test for zero
             #     I.e. if counter==0
    @        #       Then Current character
    42       #       Else 42 (which is '*')
    if       #
  }%         #   The mapping operation masked most of the characters
  \;         #   Discard the counter
  n          #   Add newline
}+%


Simulate a Rubik's cube A Rubik's cube has 6 colors: red, orange, yellow, white, blue, and green. Red and orange, yellow and white, and blue and green faces are on opposite sides.

Net of a solved Rubik's cube looks like this:

 Y
BRGO
 W

And the tiles look like this:

      Y Y Y
      Y Y Y
      Y Y Y
B B B R R R G G G O O O
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W

Challenge

Given rotations, reversed rotations, or double rotations output what a solved cube will transform to, as ASCII art or as an image (whitespaces aren't necessary, may or may not exist, trailing whitespaces are allowed.).

Input will be rotation (and optional modifier). Rotation notation goes like: U(p), L(eft), F(ront), R(ight), B(ack), D(own); 2 (double), ' or i (inverse).

All normal rotations will be 90° clockwise, inverse ones will be counterclockwise.

Explanation about clockwiseness: Imagine the cube as you're looking at the red face, and the yellow face is at the top. Then rotate the cube so that the face that the program will rotate will face you. This is the way clockwiseness will work. (Except back face, you will rotate the cube horizontally in that case.)

Input

Input will be a list of moves.

Output

An ASCII art that represents the cube or an image of the net of the cube.

Examples

Input:  (empty)

Output:

      Y Y Y
      Y Y Y
      Y Y Y
B B B R R R G G G O O O
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W

Input: U (up)

Output:

      Y Y Y
      Y Y Y
      Y Y Y
R R R G G G O O O B B B
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W

Input: U' or Ui (inverse up)

Output:

      Y Y Y
      Y Y Y
      Y Y Y
O O O B B B R R R G G G
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W

Input: U2 (double up)

Output:

      Y Y Y
      Y Y Y
      Y Y Y
G G G O O O B B B R R R
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W

Input: L' (inversed left)

Output:

      R Y Y
      R Y Y
      R Y Y
B B B W R R G G G O O Y
B B B W R R G G G O O Y
B B B W R R G G G O O Y
      O W W
      O W W
      O W W

Input: R (right)

Output:

      Y Y R
      Y Y R
      Y Y R
B B B R R W G G G Y O O
B B B R R W G G G Y O O
B B B R R W G G G Y O O
      W W O
      W W O
      W W O

Input: U2 L' D (double up, inverse left, down)

Output:

      O Y Y
      R Y Y
      R Y Y
G B B W O O B B B R R Y
G B B W R R G G G O O Y
O O Y G B B W R R G G G
      R O O
      W W W
      W W W

Rules

No loopholes allowed.
This is code-golf, so shortest code in bytes solving the problem wins.

Ruby, 370 339 305 bytes
Latest edit: a few bytes saved by rearrangement of the plotting formulas and removal of unnecessary brackets. A massive saving by rewriting the generation of the cube - I never knew Ruby had a builtin for Cartesian Products!
->s{q=[-66,0,71].product [-87,0,89],[-79,0,82]
s.map{|c|m="LDBRUF".index c[0];e=m/3*2-1
c.sub(/[i']/,"33").chars{q.map{|j|j[m%=3]*e>0&&(j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)}}}
t=[" "*12]*9*$/
q.map{|r|a,b,c=r.map{|i|i<=>0}
3.times{|i|r[i]!=0&&t[56+[a*3-a*c-d=b*13,a-d*3+d*c,3-d-c*3+c*a][i]]=r[i].abs.chr}}
t}

Anonymous function.
Accepts an array of strings, each representing one face turn (a single string with spaces between each face turn is an additional 6 bytes.)
Returns a 9x12 rectangular string.
Brief explanation
This is closely based on a concept from my answer to this question, which in turn was based on a similar concept by Jan Dvorak.
The first line generates a 27 element array, representing the 27 cubies. Each cubie is represented by a 3 dimensional vector in which the sign represents its current position and the magnitude of each coordinate represents the ascii code for the colour of the sticker.
Example move: for R, for each cubie check if the x coordinate is >0 and if so rotate 90 degrees by swapping the y and z coordinates and swapping the sign of one of them.
Take a 9x12 array of spaces and plot the cube into it. For each cubie and axis we check if the sticker exists (coordinate in that axis nonzero), and work out where it is to go. Then we take the coordinate and perform .abs.chr to change the number into the required character and plot it.
Ungolfed in test program (per 339 byte edit)
f=->s{

  q=(0..26).map{|i|                         #Build an array of 27 cubies
    [[-66,0,71][i%3],                       #x coordinate B.G
     [-87,0,89][i/3%3],                     #y coordinate Y.W
     [-79,0,82][i/9]]                       #z coordinate O.R
  }

  s.map{|c|                                 #For each move in the input array
    m="LDBRUF".index(c[0]);e=m/3*2-1        #m=face to move. e=-1 for LDB, +1 for RUF.
    c.sub(/[i']/,"33").chars{               #Substitute "i" and "'" for "33" so chars in string = clockwise 1/4 turns required. For each char...
      q.map{|j|j[m%=3]*e>0&&                #...and each cubie, m%3 tells the relevant axis. if coordinate*e>1 rotate the cubie 1/4 turn.
        (j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)} #Swap other two axes and change sign of one. e performs sign change if necessary for LDB.
    }
  }

  t=[" "*12]*9*$/                           #Make an array of 9 strings of 12 spaces, then make a single string by joining them with newlines
  q.map{|r|                                 #For each cubie
    a,b,c=r.map{|i|i<=>0}                   #make a normalised (-1,0,1) copy of each coordinate.
    d=b*13                                  #13 chars per line, d will be useful for plotting to the correct line of the output.
    3.times{|i|                             #For each of the 3 coordinates of the cubie
      r[i]!=0&&                             #if zero, sticker doesn't exist (edges and centres have <3 stickers.) If not zero plot the sticker.
      t[[56-d+a*3-a*c,                      #Calculate position on plot for x (L/R faces),
         56-d*3+d*c+a,                      #Calculate position on plot for y (D/U faces),
         59-d-c*3+c*a][i]]=                 #Calculate position on plot for z (B/F faces). Select the correct axis.
      r[i].abs.chr                          #Convert the coordinate to a character and assign to the correct space on the output plot.
    }
  }
t}                                          #Return the output string.

puts f[gets.chomp.split]

Output
Checkerboard
U2 D2 F2 B2 L2 R2
   YWY
   WYW
   YWY
BGBRORGBGORO
GBGOROBGBROR
BGBRORGBGORO
   WYW
   YWY
   WYW

6-spot
U D' R L' F B' U D'
   RRR
   RYR
   RRR
WWWGGGYYYBBB
WBWGRGYGYBOB
WWWGGGYYYBBB
   OOO
   OWO
   OOO

Testcase
U2 L' D
   OYY
   RYY
   RYY
GBBWOOBBBRRY
GBBWRRGGGOOY
OOYGBBWRRGGG
   ROO
   WWW
   WWW


Compare char to other chars in javascript In my answer, I have this code:

s.match(/[AEIOU]/)

This seems too verbose to check if a string is one of A, E, I, O, or U.

I tried:

"AEIOU".includes(s)

But that's 1 byte longer. Can I do this in a shorter way?

Try /[AEIOU]/.test(s)

Body must be at least 30 characters; you entered 21


Spanish ID card control character calculator This is a very very simple algorithm, that I am sure can be solved in many many different languages. In Spain ID cards (known as DNI) consist of 8 numbers and a control character. The control character is calculated with the following algorithm: divide the number by 23, take the remainder of the operation and replace it with a character according to this table:

0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22
T  R  W  A  G  M  Y  F  P  D  X  B  N  J  Z  S  Q  V  H  L  C  K  E

If the DNI belongs to a foreign person living in Spain, the first digit is changed to X, Y or Z and it is called an NIE. In this case, the following substitutions are made before calculating the control character:

X Y Z
0 1 2

There are a lot of calculators online that help you get the control character, but, how short can you write that code? Write an algorithm (program or function) that receives a string with the DNI number (that will always consist of 8 alphanumeric characters) and returns just the single control character calculated and nothing more (a trailing newline is accepted).

Notes:

The DNI is always written in uppercase, but in your algorithm you can choose the input and output to be upper- or lowercase, just be consistent.
In real life, some NIEs issued before 2008 have 8 digits after the X, Y or Z, but for the purposes of this game, you can consider they have 7 digits as they have nowadays.
You can consider that the input string will always have 8 characters, but if they are not in the "8 digits" format nor the "[XYZ] plus 7 digits" format, you must return an error (of your choice) or just throw an exception.

Test cases:

00000010 -> X (HRM Juan Carlos I's DNI number)
01234567 -> L
98765432 -> M
69696969 -> T
42424242 -> Y
Z5555555 -> W (Z=2)
Y0000369 -> S (Y=1)
A1234567 -> <Error code or exception>
1231XX12 -> <Error code or exception>

This is code-golf, so may the shortest code for each language win!

Python 3, 83 bytes

lambda n:'TRWAGMYFPDXBNJZSQVHLCKE'[int([n,str(ord(n[0])%4)+n[1:]][n[0]in'XYZ'])%23]

Try it online!

-5 thanks to AlixEinsenhardt (from 99 to 94). -1 thanks to JonathanAllan.


"Write" a simple calculator without writing a single line of code It's very easy:

Create a program without writing a single line of code. The code may only consist of existing Stack Overflow questions and answers.

The program should create two random numbers and output the numbers

added to,
subtracted from,
multiplied with and
divided by

each other.

Rules

You must include links to the questions/answers you used in your answer.
You may not modify the code you find, with the following exceptions:

You may rename variables, functions, and methods. (This doesn't mean you can change a method invocation, by changing, say scanner.nextInt() to scanner.nextLine() and claiming that you're changing a method name. The change must be in the definition or reference to the same entity.). The solution should still work if variables, functions or methods would be renamed again.
You may adjust indentation appropriately.
You can assume that the proper modules are loaded for the code snippets to work. (e.g., import statements for Java and Python, using statements for C# and C++, and their equivalents in all languages) If the code snippet includes the imports for you, you can move them to the top of the code.
If the language requires the code to be in some kind of method body to execute (e.g., public static void main(String[] args) for Java, static int Main(string[] args) for C#, and so on), you can wrap your code in the appropriate method. But the contents of that main method must remain unmodified.
You must supply an explicit list of any variable/method/function/class renamings performed.
You can't take snippets of snippets (meaning if you take a code block from a post, you take the whole thing)
Provide a brief description of what the code does for people who aren't intimate with the language you're using.
You must use snippets posted before this challenge was started.

Popularity contest, so the most upvotes wins!

Deadline

I will accept the the submission that has the most votes around the end of August, 6.

J, 7 questions/answers, none about J
echo a%b[echo a*b[echo a-b[echo a+b[b=:?2147483647 [a=:?2147483647

It's a pretty damn cheap way to do it, I'm not gonna lie. Here are the SO answers I used:

echo
This answer

+, -, * and %
This question

?
This answer

[
This answer

= and :
This community wiki question

2147483647
This answer

foo
This answer

I renamed variable foo as a and b in the code.


4-way intersection generator Here is an ASCII-art of a 4-way intersection:
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |
-----+-----+-----
     |     |
- - -|     |- - -
     |     |
-----+-----+-----
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |

(Note how the horizontal roads are 3 rows tall, while the vertical roads are 5 columns wide. This is for aesthetic reasons, because of the rectangular font.)
Your challenge is to produce this ASCII art. However, as I'm sure you all know, not every intersection has a road travelling off in every single direction. This particular intersection goes NESW, but some intersections might go, for example, NW:
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |
-----+-----+
     |     |
- - -|     |
     |     |
-----+-----+

Or it might go SWE:
-----+-----+-----
     |     |
- - -|     |- - -
     |     |
-----+-----+-----
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |

Or it may even go E, just a single direction (although you can hardly call this an intersection, but try to avoid being overly pedantic):
     +-----+-----
     |     |
     |     |- - -
     |     |
     +-----+-----

You need to write a program or function that can easily generate any of these combinations. More specifically, your challenge is to write a program or function that takes a string of directions, consisting of NESW, as input, and outputs or returns this ASCII art of an intersection with roads pointing in those directions. These directions may appear in any order, but the input will not contain any characters except for N, E, S, or W. If you like, you may request inputs to be lowercase instead, but you must specify this in your answer. You may also assume that all inputs will contain at least one direction.
The last example had leading spaces on each line, because there is no road going west. If you do not have a road going west, these leading spaces are optional. This:
+-----+-----
|     |
|     |- - -
|     |
+-----+-----

Would also be an acceptable output. Similarly, if N or S is gone, empty lines in there place are optional. One trailing newline is allowed, and trailing spaces are allowed as long as the output is visually the same.
You may take input and output in any reasonable format, such as STDIN/STDOUT, command line args, files, function arguments/return values, etc.
As usual, this is code-golf, so try to get the shortest possible answer in whatever language you happen to use!
Sample IO:
NESW:

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

NS:

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

S:

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

EW:

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

SE:
+-----+-----
|     |
|     |- - -
|     |
+-----+-----
|  |  |
|     |
|  |  |
|     |
|  |  |

Javascript (ES6), 190 187 185 bytes

This is an attempt to build this ASCII art character per character by iterating on a 17x15 matrix. Therefore, the output is always made of 15 rows of 17 columns with the intersection of the roads centered in the middle.

p=>eval("for(y=15,s='';y--;s+=`\n`)for(x=17;x--;)s+=' |-+'[+[a=y>4,b=y<10,c=x>4,d=x<12].every((c,i)=>c|p.search('SNEW'[i])+1)&&!((z=x-8||y&1|a&b)&&z*z-9)+2*!((z=y-7||x&1|c&d)&&z*z-4)]")

Ungolfed and commented

for(y = 15, s = ''; y--; s += `\n`)   // iterate on y, from 14 to 0 / append line feeds
  for(x = 17; x--;)                   // iterate on x, from 16 to 0
    s += ' |-+' [                     // append next character to string
      +[ a = y > 4,                   // a = outside South area?
         b = y < 10,                  // b = outside North area?
         c = x > 4,                   // c = outside East area?
         d = x < 12 ]                 // d = outside West area?
      .every((c, i) =>                // for each area, see if either:
        c |                           //   - we're currently outside it
        p.search('SNEW' [i]) + 1      //   - or it's an allowed area (p = function param.)
      )                               // if all tests pass, add a:
      &&                              //   - vertical bar (encoded as 1) if:
      !((z = x - 8 || y & 1 | a & b)  //     - x=8, y is even and we're not in the middle
      && z * z - 9)                   //     - OR x=5 OR x=11 (<=> (x-8)*(x-8) = 9)
      + 2 *                           //   - horizontal bar (encoded as 2) if:
      !((z = y - 7 || x & 1 | c & d)  //     - y=7, x is even and we're not in the middle
      && z * z - 4)                   //     - OR y=5 OR y=9 (<=> (y-7)*(y-7) = 4)
    ]                                 // (vertical + horizontal = 3, which leads to '+')

Matrix

Below is the matrix with the coordinates used in the code.

Demo

The following snippet allows to try any road configuration.

let f =
p=>eval("for(y=15,s='';y--;s+=`\n`)for(x=17;x--;)s+=' |-+'[+[a=y>4,b=y<10,c=x>4,d=x<12].every((c,i)=>c|p.search('SNEW'[i])+1)&&!((z=x-8||y&1|a&b)&&z*z-9)+2*!((z=y-7||x&1|c&d)&&z*z-4)]")

function update() {
  document.getElementById("o").innerHTML = f(document.getElementById("s").value);
}
update();
<input id="s" size=4 value="NSEW" oninput="update()">


Arbitrary Clock Time Calculator Create a routine to calculate the position of each unit of a clock with an arbitrary number of units (minutes, hours, half-days, days, years, parsecs, quarter-quells, etc), where each unit can be equally sub-divided into an arbitrary number of sub-units; after n base units have elapsed.

Basically, figure out what a clock would show after n seconds given user defined lengths for minutes, hours, days, etc.

For example, after 86,400 seconds on a clock that has 60 seconds in a minute, 60 minutes in an hour, 12 hours per half day, 2 half days per day, and 365 days in a year; you get the following:

clockFunction(86400,[60,60,12,2,365]) = 0,0,0,0,1

(Standard Clock)

clockFunction(86400,[60,60,12,2]) = 0,0,0,0

(Standard Clock - Rolling Over)

clockFunction(7430201,[100,100,10,10,3,12]) = 1,2,3,4,1,2

(French Republican Calendar [sec / min, min / hr, hrs / day, days / wk, wks / mo, mo / yr])

clockFunction(2443332,[60,60,24,365]) = 12,42,6,28

(Standard Clock - Donnie Darko)

clockFunction(63570500940,[60,60,12,2,365,10000]) = 0, 29, 4, 1, 294, 2015

(Standard Clock - Back to the Future)

Shortest code that works wins!

Clarifications:

All Units are integer
All Units are greater than 0

Dyalog APL, 9 7 5 bytes

⌽⊤⍨∘⌽

This is a dyadic function train that expects seconds and lengths as left and right arguments. It is equivalent to the following, train-less function:

{⌽⍺⊤⍨⌽⍵}

Verify all test cases at once on TryAPL.

How it works

    ⌽ Reverse the right argument...
   ∘    and...
 ⊤⍨     perform mixed base encoding on the left argument with those bases.
⌽     Reverse the order of the result.


Tips for golfing in The Shakespeare Programming Language What general tips do you have for golfing in The Shakespeare Programming Language? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to SPL (e.g. "remove comments" is not an answer).

Please post one tip per answer.

(Well... since this is my adopted language 1, I feel like I'm obliged to add something here)

Use short variable names

Yeah, yeah, yeah, that's pretty standard to code-golf, you just use one-letter-length variable names, no news here. Or is there? Because the chaps that created SPL were wacky enough not to allow any name for their language's variables: they must come from Shakesperian plays which, in terms of character length, is a pain in the royal tush - but, if you're coding in SPL, you already know that. So, my advice would be to use characters with short names, like Ajax, Ford, Page or Puck, instead of The Archbishop of Canterbury, per instance.

That's all I got, I'm afraid.

1- since my Java skills are equivalent of those of a newborn.


Throwback Friday: Renumber my ZX spectrum BASIC listing The first programming language I was exposed to was Sinclair BASIC.  Like many BASIC dialects, it requires all source code lines to be numbered.

As a result, use of the GO TO command was idiomatic and jumps execution to the given line number (no labels).

Also there is a related GO SUB command which can be used as a rudimentary function call.  Again, execution jumps to the given line number, but when a RETURN command is reached, execution jumps back to the next instruction after the GO SUB.

Similarly the RUN command will restart program execution at the given line.

Anyone who has spent any time in a line-numbered BASIC interpreter will have learned to use a numbering scheme with gaps in it.  This is so that it is easier to insert new lines of code.  However even then, you may still find yourself needing to insert new lines in between consecutively numbered lines.

Given a line-numbered BASIC listing as input, output the same program but renumbered such that the line numbers start at 10 and increment by steps of 10.  The input listing may have GO TO or GO SUB commands, so the numbers associated with these must also be adjusted.

GO TO and GO SUB commands are either on their own lines or at the end of IF THEN lines.  Its safe to say ^(\d+) .*GO (TO|SUB) (\d+)$ is sufficient to match such lines.  These commands in quotes should be ignored.
RUN commands will always be on their own lines.  In this case a line number is optional.  If it is missing, then the interpreter simply starts at the top of the program.
If a GO TO, GO SUB or RUN command references a non-existent line, then it will instead jump to the next defined line.  Your entry needs to deal with this and ensure any such line references are fixed so they point to the correct line.  Behaviour may be undefined if a line number after the end of the program is given in one of these commands.
Line numbers will always be positive integers 1 to 9999 (as per the manual).  This means that input programs will never have more than 999 lines.
Input lines will always be numbered in numerically ascending order.
For the purposes of this challenge, input listings will only contain printable ASCII.  You don't need to worry about the ZX character set.  Having said that, if your entry is actually written in ZX BASIC or appropriate z80 assembly/machine code (and there are emulators out there), then you may choose for your input to be encoded in the ZX character set instead.
You may not use any renumber libraries or utilities that are specifically tailored for this purpose.

Example Input:

1 REM "A rearranged guessing game"
2 INPUT A: CLS
3 INPUT "Guess the number ", B
10 IF A=B THEN PRINT "Correct": STOP
100 IF A<B THEN GO SUB 125
120 IF A>B THEN GO SUB 122
121 GO TO 3
125 PRINT "Try again"
126 RETURN
127 REM "An example of GO TO 7 and GO SUB 13 in quotes"

Example Output:

10 REM "A rearranged guessing game"
20 INPUT A: CLS
30 INPUT "Guess the number ", B
40 IF A=B THEN PRINT "Correct": STOP
50 IF A<B THEN GO SUB 80
60 IF A>B THEN GO SUB 80
70 GO TO 30
80 PRINT "Try again"
90 RETURN
100 REM "An example of GO TO 7 and GO SUB 13 in quotes"

I wanted to link to a ZX BASIC manual.  The best I could find seems to be http://www.worldofspectrum.org/ZXBasicManual/index.html but this seems to be a dead link.  The wayback machine has a copy though.

JavaScript (ES6) 177

Edit Added the (costly) scan for the next valid line number

l=>l.split`
`.map((x,i)=>([,n,t]=x.match(/(\d+)(.*)/),l[n]=10*-~i,t),l=[]).map((x,i)=>10*-~i+x.replace(/(UN |GO TO |UB )(\d+)$/,(a,b,c)=>(l.some((v,i)=>i<c?0:a=b+v),a))).join`
`

TEST

f=l=>
  l.split`\n`
  .map((x,i)=>([,n,t]=x.match(/(\d+)(.*)/),l[n]=10*-~i,t),l=[])
  .map((x,i)=>10*-~i+x.replace(/(UN |GO TO |UB )(\d+)$/,(a,b,c)=>(l.some((v,i)=>i<c?0:a=b+v),a)))
  .join`\n`

//TEST
console.log=x=>O.textContent+=x+'\n'

test=`1 REM "A rearranged guessing game"
2 INPUT A: CLS
3 INPUT "Guess the number ", B
10 IF A=B THEN PRINT "Correct": STOP
100 IF AB THEN GO SUB 122
121 GO TO 3
125 PRINT "Try again"
126 RETURN`
console.log(test+'\n\n'+f(test))


Print a list of iPhones Write the shortest program that prints, in order, a complete list of iPhone iterations, according to this site:

iPhone
iPhone 3G
iPhone 3GS
iPhone 4
iPhone 4S
iPhone 5
iPhone 5c
iPhone 5s
iPhone 6
iPhone 6 Plus
iPhone 6s
iPhone 6s Plus
iPhone SE
iPhone 7
iPhone 7 Plus
iPhone 8
iPhone 8 Plus
iPhone X
iPhone XR
iPhone XS
iPhone XS Max
iPhone 11
iPhone 11 Pro
iPhone 11 Pro Max

Output should be printed exactly as specified, though trailing newlines are allowed (as well as additional whitespace at the end of each line).

This is code golf, so the shortest answer in bytes, per language, wins.

Canvas, 77 76 73 bytes

¶＋∔ｉＦ╴qV1┼#│»ｌN↶:╋KＡRV／＋├6<∔ZK＠≠≡Ｚｅ３ｈ}s×⁴＊⁵GZX─?ep┼Q‟-ｓ｛iPhone ×|∙ Plus╋］

Try it here!

-3G-3GS-4-4S-5-5c-5s-6-6|-6s-6s|-SE-7-7|-8-8|-X-XR-XS-XS Max-11-11 Pro-11 Pro Max compressed, split on -, | replaced with ' Plus', and 'iPhone ' prepended.


Create a function for transposing musical chords Your mission is to create a function for transposing music chords.

Copied from SO with permission of the original asker, I just really wanted to see what you guys could do with this one:

Since I don't expect everyone to be a musician here, I'll try to explain how it works in music theory. I hope I don't forget something. If yes, musicians, please, correct me.

1) The simple chords

The simple chords are almost as simple as an alphabet and it goes like this:

  C, C#, D, D#, E, F, F#, G, G#, A, A# B

From B it loops all over again to C. Therefore, If the original chord is E and we want to transpose +1, the resulting chord is F. If we transpose +4, the resulting chord is G#.

2) Expanded chords

They work almost like the simple chords, but contain a few more characters, which can safely be ignored when transposing. For example:

  Cmi, C#7, Dsus7, Emi, Fsus4, F#mi, G ...

So again, as with the simple chords, if we transpose Dsus7 + 3 = Fsus7

3) Non-root bass tone

A problem arises when the bass plays a different tone than the chord root tone. This is marked by a slash after the chord and also needs to be transposed. Examples:

  C/G, Dmi/A, F#sus7/A#

As with examples 1 and 2, everything is the same, but the part after the slash needs transpose too, therefore:

C/G + 5 = F/C

F#sus7/A# + 1 = Gsus7/B

I think this should be all, unless I forgot something.

So basically, imagine you have a javascript variable called chord and the transpose value transpose. What code would transpose the chord?

Example:

var chord = 'F#sus7/C#';
var transpose = 3; // remember this value also may be negative, like "-4"
... code here ...
var result; // expected result = 'Asus7/E';

original question here: https://stackoverflow.com/questions/7936843/how-do-i-transpose-music-chords-using-javascript (note that he's asking for JS, for this challenge I don't care what language its in)

OK, within the limitations of the question as asked and not catering for a lot of things you'd need to allow for if using with real music (flats being the most obvious):

function t(c,a) {
  var s=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],i;
  return c.replace(/[A-G]#?/g,function(m){return s[(i=(s.indexOf(m)+a)%s.length)<0?i+s.length:i];});
}

This is my first attempt at code-golf, so I hope I've taken the right approach. Following is the readable version that I originally posted at stackoverflow.com:

function transposeChord(chord, amount) {
  var scale = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
  return chord.replace(/[CDEFGAB]#?/g,
                       function(match) {
                         var i = (scale.indexOf(match) + amount) % scale.length;
                         return scale[ i < 0 ? i + scale.length : i ];
                       });
}


Average of your code Inspired by this
Task
Your task is to output the average character of your code.
What is an average character?
Say we have a string golf().
We then take the ASCII value of each separate symbol, so our string is 103 111 108 102 40 41, and calculate the average of those values, rounded to an integer. In our case the average is 505 / 6 = 84.1666... = rounded to 84. That value is printed out as an ASCII character, in our case T.
Rules
You must take no input and must not read the source code directly, while outputting the average character of its source code. Integers are rounded by function floor(x+0.5). Empty programs are not allowed. This is code-golf, so lowest byte count wins!

///, 1 byte
A

Try it online!
As it’s 1 byte, simply outputting the source code gives the average. /// just outputs the source code unchanged if it doesn’t contain any / characters, so almost any ASCII character works in place of A


Exploring the xorspace The xorspace of a set of integers is the set of all integers that can be obtained by combining the starting integers with the usual bitwise xor operator (^). For example, the xorspace of (8, 4) is (0, 4, 8, 12): 0 is 4^4, 12 is 4^8, and no other numbers can be reached. Note that the starting numbers are always included, by this definition (for example, 4 is 4^4^4).

Your goal is to write the shortest program that takes a list of non-negative integers as input, and outputs the number of elements in their xorspace.

Standard loopholes are forbidden.
Input and output can be in any of the usual formats. Input is guaranteed to be valid, non-empty, and without duplicates.
Your code should be able to process all test cases in less than a day.

Test cases

Input: 0
Output: 1

Input: 6
Output: 2

Input: 8 4
Ouput: 4

Input: 0 256
Output: 2

Input: 256 259 3
Output: 4

Input: 60 62 94 101 115
Output: 32

Input: 60 62 94 101 115 40 91
Output: 32

Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
Output: 64

Input: 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384
Output: 32768

MATL, 11 bytes

t"G!Z~Ghu]n

Try it online!

The last test case doesn't run in the online interpreter because of memory limitations, but runs offline in less than 2 seconds on a modern computer.

Explanation

For input of size n, this does the following:

Initiallize result to input.
Repeat n times:

Apply bitwise XOR to all pair of entries from current result and input.
Attach input values to the result.
Deduplicate.

The output is the number of elements of the final result.

Commented code.

t      % Implicit input: row vector. Duplicate
"      % For each (i.e. do as many times as the input size)
  G!   %   Push input as a column vector
  Z~   %   Bitwise XOR with broadcast, i.e. for all pairs of entries of the
       %   two arguments. The first argument is the accumulated result
       %   from the previous iteration, the second is the input vector
  G    %   Push input again
  h    %   Postpend
  u    %   Unique values. Gives a row vector
]      % End
n      % Number of entries. Implicitly display

Example

The intermediate results (steps 2.1 and 2.3) for input [256 259 3] are:

First iteration: [256 259 3] with [256 259 3]: computing all pairs of bitwise-XOR gives the matrix

  0   3 259
  3   0 256
259 256   0

Attaching [256 259 3] and deduplicating

0 3 259 256

Second iteration: current result [0 3 259 256] with [256 259 3]. After deduplicating this again gives

0 3 259 256

Third iteration: again

0 3 259 256

So the output is 4 (number of entries of result).


Integer triangles with perimeter less than n Definition

An "integer triangle" is one with integer coordinates. For example the following triangle is an integer triangle:

(0, 0), (0, 1), (1, 2) with perimeter 1 + sqrt(2) + sqrt(5) ≈ 4.650.

Task

The goal of this challenge is to count all integer triangles (up to congruence) with perimeter less than n.

Input and Output

The argument will be given as an integer, and the output should be the number of triangles with perimeter strictly less than the argument.

Examples

The smallest integer triangle by perimeter is congruent to

(0, 0), (0, 1), (1, 0) which has perimeter 2 + sqrt(2) ≈ 3.414

The next smallest are:

(0, 0), (0, 1), (1, 2) with perimeter 1 + sqrt(2) + sqrt(5) ≈ 4.650,
(0, 0), (0, 2), (1, 1) with perimeter 2 + 2sqrt(2)          ≈ 4.828,
(0, 0), (0, 2), (1, 0) with perimeter 3 + sqrt(5)           ≈ 5.236, and
(0, 0), (1, 2), (2, 1) with perimeter sqrt(2) + 2sqrt(5)    ≈ 5.886

Test cases:

a(1) = 0
a(2) = 0
a(3) = 0
a(4) = 1
a(5) = 3
a(6) = 5
a(7) = 11
a(8) = 18
a(9) = 29
a(10) = 44
a(12) = 94
a(20) = 738
a(30) = 3756
a(40) = 11875

I have coordinates for each of the triangles in this Gist.

Warnings

Notice that two non-congruent triangles can have the same perimeter:

(0, 0), (0, 3), (3, 0) and (0, 0), (0, 1), (3, 4) both have perimeter 6 + 3sqrt(2).

Also keep in mind that the inequality is strict; the 3-4-5 pythagorean triangle should be counted by a(13), not a(12).

Scoring

This is code-golf—the shortest code wins!

Jelly, 28 27 25 23 bytes

pḶŒcÆḊÐfḅı;I$€AṢ€QS€<¹S

Try it online!

How it works

pḶŒcÆḊÐfḅı;I$€AṢ€QS€<¹S  Main link. Argument: n

 Ḷ                       Unlength; yield [0,...,n-1].
p                        Take the Cartesian product of [1,...,n] and [0,...,n-1].
  Œc                     Take all combinations of the resulting pairs.
                         The result are of the form [[a, b], [c, d]].
    ÆḊÐf                 Filter by determinant; keep only pairs of pairs for which
                         the determinant (ad - bc) is non-zero, i.e., those such
                         that [0, 0], [a, b], and [c, d] are not collinear.
        ḅı               Convert each pair [a, b] from base i (imaginary unit) to
                         integer, mapping it to ai + b.
             €           For each pair of complex numbers [p, q]:
          ;I$              append their forward differences, yielding [p, q, p-q].
              A          Take the absolute value of each resulting complex number.
               Ṣ€        Sort each resulting array of side lengths.
                 Q       Unique; remove duplicates.
                  S€     Take the sum of each array, computing the perimeters.
                    <¹   Compare them with n.
                      S  Take the sum of the resulting Booleans.


Find the average of a word Inspired by this chat message

Your task will be to take a word and find the average position of its letters on the keyboard as a letter.

Keyboard Layout

Since layouts vary from keyboard to keyboard, we will be using a standard based of of my own keyboard in this question.

The keyboard has 3 rows, the top row from left to right contains the keys

QWERTYUIOP

The second row contains the letters

ASDFGHJKL

The final row contains

ZXCVBNM

Each letter is 1 unit horizontal from its neighbor to the left.  This means that W is 1 away from Q and E is 1 away from W and so on.

The keys at the beginning of each row have the positions:

Q : 0,0
A : 1/3,1
Z : 2/3,2

This means that the rows are separated one unit vertically and the bottom two rows are shifted by a third from the row above them.

You should take a word as input and output the letter that is closest to the average position of the letters in its word.  The average of a set of vectors is

(average x value, average y value)

When two keys are equidistant from the average you may output either as the "closest" key.

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

Example solution

Let's calculate the average of APL.

We convert each letter to a vector

A -> (1/3,1)
P -> (9,0)
L -> (8 1/3,1)

We add these up the three vectors to get (17 2/3, 2). We then divide each coordinate by 3 (The number of letters in the word) to get (5 8/9, 2/3).

The closest letter to (5 8/9, 2/3) is J at (6 1/3,1) so our result is J.

Test Cases

APL  -> J
TEXT -> R
PPCG -> J
QQQQ -> Q
ZZZZ -> Z
PPPP -> P
MMMM -> M
QQSS -> A or W

Python 3, 130 bytes

lambda w,d={'QAZWSXEDCRFVTGBYHNUJMIKOOLPP'[i]:i%3*1j+i/3for i in range(28)}:min(d,key=lambda c:abs(d[c]-sum(map(d.get,w))/len(w)))

Try it online!

d={'QAZWSXEDCRFVTGBYHNUJMIKOOLPP'[i]:i%3*1j+i/3for i in range(28)} constructs the mapping from letters to points (represented as complex numbers, (x+y*1j)).

As for the lambda body, sum(map(d.get,w))/len(w) computes the average position of word w, and putting that in min(d,key=lambda c:abs(d[c]-…)) finds the closest letter to that position. (For complex numbers, abs(A-B) corresponds to the Euclidean distance between (A.real, A.imag) and (B.real, B.imag).)


Who was president of the USA? Challenge

Write a program that takes as input a day from April 30, 1789 to August 21, 2019 and returns as output who was president of the USA that day.

Notes

For the list of US presidents, the format of their names, and the period of their presidency, see below:

April 30, 1789 - March 4, 1797          George Washington
March 4, 1797 - March 4, 1801           John Adams
March 4, 1801 - March 4, 1809           Thomas Jefferson
March 4, 1809 - March 4, 1817           James Madison
March 4, 1817 - March 4, 1825           James Monroe
March 4, 1825 - March 4, 1829           John Quincy Adams
March 4, 1829 - March 4, 1837           Andrew Jackson
March 4, 1837 - March 4, 1841           Martin Van Buren
March 4, 1841 - April 4, 1841           William Henry Harrison
April 4, 1841 - March 4, 1845           John Tyler
March 4, 1845 - March 4, 1849           James K. Polk
March 4, 1849 - July 9, 1850            Zachary Taylor
July 9, 1850 - March 4, 1853            Millard Fillmore
March 4, 1853 - March 4, 1857           Franklin Pierce
March 4, 1857 - March 4, 1861           James Buchanan
March 4, 1861 - April 15, 1865          Abraham Lincoln
April 15, 1865 - March 4, 1869          Andrew Johnson
March 4, 1869 - March 4, 1877           Ulysses S. Grant
March 4, 1877 - March 4, 1881           Rutherford B. Hayes
March 4, 1881 - September 19, 1881      James A. Garfield
September 19, 1881 - March 4, 1885      Chester A. Arthur
March 4, 1885 - March 4, 1889           Grover Cleveland
March 4, 1889 - March 4, 1893           Benjamin Harrison
March 4, 1893 - March 4, 1897           Grover Cleveland
March 4, 1897 - September 14, 1901      William McKinley
September 14, 1901 - March 4, 1909      Theodore Roosevelt
March 4, 1909 - March 4, 1913           William Howard Taft
March 4, 1913 - March 4, 1921           Woodrow Wilson
March 4, 1921 - August 2, 1923          Warren G. Harding
August 2, 1923 - March 4, 1929          Calvin Coolidge
March 4, 1929 - March 4, 1933           Herbert Hoover
March 4, 1933 - April 12, 1945          Franklin D. Roosevelt
April 12, 1945 - January 20, 1953       Harry S. Truman
January 20, 1953 - January 20, 1961     Dwight D. Eisenhower
January 20, 1961 - November 22, 1963    John F. Kennedy
November 22, 1963 - January 20, 1969    Lyndon B. Johnson
January 20, 1969 - August 9, 1974       Richard Nixon
August 9, 1974 - January 20, 1977       Gerald Ford
January 20, 1977 - January 20, 1981     Jimmy Carter
January 20, 1981 - January 20, 1989     Ronald Reagan
January 20, 1989 - January 20, 1993     George H. W. Bush
January 20, 1993 - January 20, 2001     Bill Clinton
January 20, 2001 - January 20, 2009     George W. Bush
January 20, 2009 - January 20, 2017     Barack Obama
January 20, 2017 - Incumbent            Donald Trump

A presidency is intended as first day included and last day excluded. For example, "March 4, 1861 - April 15, 1865; Abraham Lincoln" means that Lincoln was president from March 4, 1861 to April 14, 1865.

This is code-golf, the shortest program in each language wins.

Example

Input: "February 7, 1865" Output: "Abraham Lincoln"

PHP, 936 bytes

for($a=explode('-',gzinflate(base64_decode('dVTRbtswDPwV/YANKXZq+zFJ1wRts3VZtgB7Y2Mm1ipLAO0089+PtNIuHbAnAzySd+RRNkVZ6XxSJUsMdES1g66x/tgHn5iiKnSms+Q+NF7Nami7xJTajLFtE1ro1D0eDkidZJe6itnQYqfWUNsYNsV1OHgKyNHJ9G/rryfr98M7wyT2mfma8KzuYf8SG2Wx0Rqot179AK/mJ0JB8qhpZ52z0KoVehrUCoguEhjP38i2g0OS2PRK1kOqnoJ7kXAk/wn7BrjJFgYXJH2qdaHLZM0UQLW6428bSCaZZmPFHYF/cSzsySLtR+B68PmJG3oQNTdR7eyZoGG1jzx8cCMw1bnJ3wdntVH+TdT03Q1dx62+pWrJZD0jRaTYnPoG6RBY2DzlwQeUPZbmin/GRUAHi66OUGXKZNFg1yMJOKO+OcmgZdzLksIrIwuHr+jAj0VRxhz9L2h50KsFV9n/ii4n9GbNev9gvcMhMZUWDXJIGGrepNqE0EldL1j10dBwlqVv4SCgiWS7EGoKZ8VJo4hqcrkCloVeLWURVPMtC5RpPtxkAe6VhS9CcLY+ogCRaIX0jNQzkQzA8ewfU2/TD/pyccoksoFB/NjSqRVvKz4GY6rk9myPTS9Vn2yHvgnnsSs7L+h4h3epekDvsZZd3GTGTEzyOPg6ePHw3fyKzZeajZWDrNVn+3sMFzlPVPKrJXB8jmy9BIvY37btoBb8TkbWMrJugpfUDcJxlFrGxpd3v0rVLuUr7RqGqjjFnNfPZlovf4OJ1ua64C2b47HRHIifqvryDC1w1EQtfwA=')));$d=$a[+$i++];)date(Ymd,strtotime($argn))>$d?$m=$a[$i++]:die($m);echo'Donald Trump';

Try it online!

Tests:
Try it online!

The code for tests is the same logic but a little bit different to replace the die(...) with return... so I can loop over tests.

I have created a string having start date of presidency minus 1 day in format of YYYYMMDD and name of president in it, separated by -. Example: 17890429-George Washington-17970303-John Adams-18010303-Thomas Jefferson-...

This string is compressed using gzdeflate and also the compressed output is converted to base-64 so all characters are printable ASCII and I can post them here or use them in TIO.

In the script, the string is split by - and looped over. For each loop iteration:

$d is set to current iteration value (which is the president's start date -1 day) and the loop variable ($i) is increased by one.
If input date is larger than $d, then $m is set to next iteration value (which is the president name for $d) and the loop variable ($i) is increased by one again. This allows the loop to get president names but jump over them in iterations.
If input date is not larger than $d, then that means the previous iteration was the correct president, so $m is printed using die function, this will stop the whole program after printing the name.

At the end, if the loop is finished (which means no die was called), the last president's name is printed, since we know non of previous presidents have got a match (so basically anything after January 19, 2017) prints last president's name, even if it is January 1, 3999.


Evaluate CDF of Student-t distribution The goal of this codegolf is evaluating the cumulative distribution function of the student-t probability distribution. This is not trivial since there is no closed form and the function is dependent of two variables v and x. The distribution function is

For getting the CDF you could integrate this function from -inf to x. As you can see the evaluation of this function relies much on integration as you'd also have to evaluate nontrivial values of the gamma function.

Details

You can can write a program or function that accepts a two numbers xand v as input, where x is the position (must at least accept floats from -10 upto 10) at which the CDF is evaluated and v is the number of degrees of freedom. v is a positive integer (range 1 upto 1450) but it must be possible to set it to infinity (for v=inf the student-t distribution is equal to the normal distribution). But you can specify that e.g. v = -1 should denote infinity. The output consists must be a number between 0 and 1 and must have an accuracy of at least 4 decimal places.
If your language does not support runtime inputs or arguments on program call you may assume that both arguments are stored in variables (or another 'memory unit')

Restrictions

You may not use special functions like the gamma function or probability distribution functions as well as numerical integration functions or libraries (as long as you do not include their source in your code which counts for the score) etc. The idea is using only basic math functions. I tried to make a list of what I consider as 'basic' but there might be others I forgot - if so please comment.

Explicitly allowed are

+ - / *
% (modulo)
! (factorial for integers only)
&& || xor != e.t.c. (logical operators)
<< >> ^ e.t.c. (bitshift and bitwise operators)
** pow (powerfunction for floats like a^b including sqrt or and other roots)
sin cos tan arcsin arccos arctan arctan2
ln lb log(a,b)
rand() (generating pseudorandom numbers of UNIFORM distribution)

Scoring

Lowest number of bytes wins.

Entry

Please explain how your code works.
Please show the output of your program for at least 5 different arguments. Among those should be the following three. For your own values please also provide 'exact' values (like from wolframalpha or what ever you prefer).

x = 0      v= (any)  (should return 0.5000)
x = 3.078  v= 1      (should return 0.9000
x = 2.5    v= 23     (should return 0.9900)

If possible, it would be great if you could provide some fancy plots of the values calculated with your program (the code for plotting does not count for the score).

(from Wikipedia):

BBC BASIC, 155 ASCII characters, tokenised filesize 140
Download emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html
  a=1s=.000003INPUTx,v
  IFv<1v=9999
  FORw=1TOv-1a=w/a
  NEXTb=SGN(x)*s*a/SQR(v)IFv MOD2b=b/PI ELSEb=b/2
  f=.5FORz=0TOABS(x)STEPs
  f+=b/(1+z*z/v)^(v/2+.5)NEXTPRINTf

The code is in two parts. The first calculates the coefficient that is independent of x. and stores it in b. The algorithm is a bit like a continued fraction, but a mathematician would probably call it a simple quotient of two products. It's based on a formula from the Wikipedia page in the question, which is similar to a factorial but has the product (v-1)(v-3)... divided by the product (v-2)(v-4)... This is possible because we are only interested in half-integral values of the gamma function (arbitrary values of the gamma function would be a lot harder.) Using this formula we never have to calculate either gamma function, so we avoid large numbers. The largest intermediate value is approximately the square root of v.
The second is a straightforward integration from 0 to x by summation. It is known that f(0) is 0.5 so we start from there and work outwards. the sign and magnitude of b are modified before the loop, in order to be able to give the final answer directly.
Pretty version, ungolfed
This contains a few extra lines to add colour and to plot the data. The range x=0 to endpoint, and f(x)=0.5 to 1 is shown. Also v is modified to 2^v to be able to show the full range of v values without exceeding the limits on colour. In order to speed the drawing up, there are two less digits in s than in the golfed version. Even so, there is only one discrepancy when compared with http://www.wolframalpha.com/input/?i=student+t-distribution+probability: 0.8130575 rounds up to 0.8131. The golfed version give the correct answer (0.8130) for this and all the other cases below.
  a=1                              :REM accumulator for gamma series
  s=.0001                          :REM step size for x integration
  INPUTx,v
  IFv<1 v=9999                     :REM if v<1, set v to a value that gives results indistinguishable from infinity
  GCOLv                            :REM pick a colour
  v=2^v                            :REM for the pretty version, modify v to 2^v
  FORw=1TOv-1
    a=w/a                          :REM calculate series as per Wikipedia
  NEXT
  b=a/SQR(v)                       :REM divide a by the necessary values...
  IFv MOD2 b=b/PI ELSE b=b/2       :REM to give the coefficient, per Wikipedia

  b*=SGN(x)*s                      :REM modify according to sign and step size
  f=.5                             :REM initialise f(x)=.5 at x=0
  FORz=0TO ABS(x) STEPs
    f+=b/(1+z*z/v)^(v/2+.5)        :REM perform integration as simple "barchart" sum
    PLOT69,z*100+200,(f-.5)*1600   :REM plot a point
  NEXT
  PRINT f


Generalized Gematria Calculator Create a bidirectional Gematria calculator, for any given sequence of Unicode characters as the alphabet.

Gematri-What?

Gematria is a system of assigning numerical values to symbols, developed by ancient Greeks and adopted by ancient Jews. It is in a way like ASCII or Unicode, it's just non-linear... See the following table (full table is available in the link above):

Index     Letter   Letter name  Value
--------------------------
  0         א         "Alef"     1
  1         ב         "Bet"      2

           ...

  8         ט         "Tet"      9
  9         י         "Yud"      10
 10         כ         "Kaf"      20

           ...

 17         צ        "Tsady"     90
 18         '        "Kuf"       100
 19         ר        "Resh"      200

           ...

The names of letters are not important, only their index in the "Array" of the alphabet and the respective numerical value. The Hebrew alphabet only has 22 letters (not including "final" letters), so the maximum available value is 400.

If we borrow this system to the English alphabet (A-Z) we will end up with A=1, B=2... L=30... U=300... Z=800.

Two things we need to know.

One of the most important features in this system is calculating the "Gematria Value" of a word, by summing up its letters' values. (Some say there is a mystical connection between words, or phrases (when the value of space is zero) - that share the same Gematria Value).
Any non-negative Integer can be represented in symbols. For example (and let's stay with the English alphabet for now) the value of 32 is LB (L=30 + B=2). The value of 1024 is ZTKD (800+200+20+4. Note that ZSSKD is also 1024, but that's not a legal representation, since it can be compacted).

The Challenge

Write a program / a function / a code snippet in your language-of-choice, which is first set up with an alphabet (see API below) and then accept an argument. That argument may be an Integer, or a word/phrase. If it's an Integer - your program should output/return its representation in the alphabet symbols - the most compacted one (see (2) above). If it is a word or a phrase, your program should output/return the Gematria Value (by summing up symbols' values, not counting whitespaces, see (1) above).

API

Your program/function should accept 3 arguments. You can get them from STDIN, or as function arguments, you can even assume they are variables which initialized programmatically prior to your function invocation.

First argument - the first character (in Unicode) of the alphabet.
Second argument - the last character (in Unicode) of the alphabet.
Third argument - An Integer, to be represented in symbols, OR a
phrase which is  created by the given alphabet.

Output / Return Value: Depending on the third argument, as explained above.

Assumptions

First two arguments will always be one character long each, and the second will always be grater than the first.
The sequence (first until last, inclusive) will never include any of the values 30-39 (which represent the digits 0-9), otherwise it will make the third argument ambiguous. EDIT: It won't contain space as well, since in phrases spaces are counted as zeros.
The third argument, in case it's a phrase, may only contain spaces and letters of the given alphabet. Empty string is not a valid input (you can assume it's not empty). In case it's an Integer, you can assume it's a positive Integer.

Examples

Input                Output

A Z CODE GOLF        175
a s 512              sssssjb
A B 7                BBBA
≐ ⊐ ≤≫ ≥            1700

Scoring

Score = upvotes - length/100.0

Your code should be short, but more-importantly popular. Negative scores can also play along. The winner will be the answer with highest score in a week from now, 2014-11-29 19:20:00 UTC.

Java 7, Score = Upvotes - 3.97

Yay!!! Java!!! The world's favourite golfing language in the world. What, you can actually golf in java??? Well, it's kind of like using a bulldozer to putt.

a is expected to contain the first character. b is expected to contain the last character. c is expected to have the input string.

Here is the function golfed:

int d=0;try{d=Integer.parseInt(c);}catch(Exception e){}int l=b-a+1;char[]f=new char[l];int[]g=new int[l];int h=1;int i=1;g[0]=1;f[0]=a;int j;for(j=1;j<b-a+1;){g[j]=(h+=i);f[j]=(char)(f[j++-1]+1);i*=h==10*i?10:1;}if(d==0){h=0;for(char k:c.toCharArray()){for(j=0;j<l;j++){if(f[j]==k){h+=g[j];}}}System.out.println(h);}else{c="";for(j=l;j>0;){if(g[--j]<=d){c+=f[j];d-=g[j++];}}System.out.println(c);}

Here it is indented with structure code:

public class G{

    public static void main(String[] args){
        new G(args);
    }

    public G(String[] args){
        a = args[0].charAt(0);
        b = args[1].charAt(0);
        for (int i = 2; i < args.length; i++){
            c += args[i];
        }
        function();
    }

    char a;

    char b;

    String c = "";

    void function(){
        int d=0;
        try{
            d=Integer.parseInt(c);
        }catch(Exception e){}
        int l=b-a+1;
        char[]f=new char[l];
        int[]g=new int[l];
        int h=1;
        int i=1;
        g[0]=1;
        f[0]=a;
        int j;
        for(j=1;j<b-a+1;){
            g[j]=(h+=i);
            f[j]=(char)(f[j++-1]+1);
            i*=h==10*i?10:1;
        }
        if(d==0){
            h=0;
            for(char k:c.toCharArray()){
                for(j=0;j<l;j++){
                    if(f[j]==k){
                        h+=g[j];
                    }
                }
            }
            System.out.println(h);
        }else{
            c="";
            for(j=l;j>0;){
                if(g[--j]<=d){
                    c+=f[j];
                    d-=g[j++];
                }
            }
            System.out.println(c);
        }
    }
}

Here it is completely expanded:

public class Generator{

    public static void main(String[] args){
        beginning = args[0].charAt(0);
        end = args[1].charAt(0);
        for (int i = 2; i < args.length; i++){
            phrase += args[i];
        }
        function();
    }

    static char beginning;

    static char end;

    static String phrase = "";

    static void function(){
        int convertTo = 0;
        try{
             convertTo = Integer.parseInt(phrase);
        } catch (Exception e){}
        char[] alphabet = new char[end - beginning + 1];
        int[] values = new int[alphabet.length];
        int value = 1;
        int base = 1;
        values[0] = 1;
        alphabet[0] = beginning;
        int i;
        for (i = 1; i < values.length;){
            values[i] = (value += base);
            alphabet[i] = (char)(alphabet[i++-1]+1);
            base*=value==10*base?10:1;
        }
        if(convertTo==0){
            value = 0;
            for (char character : phrase.toCharArray()){
                for (i = 0; i < alphabet.length;i++){
                    if (alphabet[i] == character){
                        value += values[i];
                    }
                }
            }
            System.out.println(value);

        } else {
            phrase = "";
            for (i = values.length;i > 0;){
                if (values[--i] <= convertTo){
                    phrase += alphabet[i];
                    convertTo -= values[i++];
                }
            }
            System.out.println(phrase);

        }
    }
}


Bringing a pair of integers to equality This was inspired by a math problem I saw somewhere on the internet but do not remember where (UPDATE: The original problem was found on the math riddles subreddit with a proof provided that it is possible, also see this Math SE post), asking for a proof if the following process is possible for any arbitrary pair of integers (from what I remember, it was possible for any given pair):

Given a pair of integers, j and k, double one of them and add one to the other, resulting in a pair of new integers, i.e., (j, k) -> (j+1, k*2) or (j*2, k+1). Then repeat this process with those integers, with the objective of having the pair of integers be equal.

These given examples are not necessarily optimal but show how this process can be done on any integers, positive, negative or zero:

(2, 5) -> (3, 10) -> (6, 11) -> (12, 12)

(5, 6) -> (6, 12) -> (7, 24) -> (14, 25) -> (28, 26) -> (56, 27) -> (112, 28) -> (113, 56) -> (226, 57) -> (227, 114) -> (228, 228)

(0, 2) -> (1, 4) -> (2, 5) -> (3, 10) -> (6, 11) -> (12, 12)

(-4, 0) -> (-3, 0) -> (-2, 0) -> (-1, 0) -> (0, 0)

(3, -1) -> (6, 0) -> (12, 1) -> (13, 2) -> (14, 4) -> (15, 8) -> (16, 16)

(-4, -3) -> (-8, -2) -> (-16, -1) -> (-32, 0) -> (-31, 0) -> ... -> (0, 0)

Challenge

Create a program that given two integers, outputs the list of steps required to make those integers equal by repeatedly incrementing one and doubling the other

Specifications

The solution does not have to be optimal but it must solve in a finite number of steps for any arbitrary pair
Input must be two integers
Output may be any reasonable output that clearly denotes the resulting integers of each step, for example:

a string with two distinct delimiters (any symbol, whitespace, etc), one for each integer in a pair and one for each pair

e.g., input j, k: 2, 5 -> output: 3,10;6,11;12,12

a list of lists of integers

e.g. input j, k: 2, 5 -> output: [[3, 10], [6, 11], [12, 12]]

If the input is a pair of equal numbers, you may output anything as long as it's consistent with other nontrivial answers

for example

if input [2, 5] has output [[3, 10], [6, 11], [12, 12]], which does not include the input pair, then input [4, 4] should output nothing.
if input [2, 5] has output [[2, 5], [3, 10], [6, 11], [12, 12]], which does include the input pair, then input [4, 4] should output [[4, 4]].

Standard IO methods apply and standard loopholes banned
This is code golf so shortest answer in bytes wins

JavaScript (ES6), 111 90 83 bytes

f=(a,b,p=q=[],u=[...p,[a,b]])=>a-b?f(...(q=[[a*2,b+1,u],[a+1,b*2,u],...q]).pop()):u

Try it online!
Commented
f = (                       // f = recursive function taking:
  a, b,                     //   (a, b) = input integers
  p =                       //   p[] = current path
  q = [],                   //   q[] = queue
  u = [...p, [a, b]]        //   u[] = updated path with [a, b] appended to it
) =>                        //
  a - b ?                   // if a is not yet equal to b:
    f(...                   //   recursive call, using spread syntax:
      (q = [                //     prepend the next 2 possible moves in the queue:
        [a * 2, b + 1, u],  //       a * 2, b + 1
        [a + 1, b * 2, u],  //       a + 1, b * 2
        ...q                //
      ]).pop()              //     use the move on the top of the queue
    )                       //   end of recursive call
  :                         // else:
    u                       //   success: return the (updated) path


Calculate the cube root of a number The goal of this code golf is to create a program or function that calculates and outputs the cube root of a number that's given as input.
The rules:

No external resources
No use of built-in cube root functions.
No use of methods/operators that can raise a number to a power (that includes square root, 4th root, etc.).
Your function/program must be able to accept floating-point numbers and negative numbers as input.
If the cube root is a floating-point number, then round it to 4 numbers after the decimal point.
This is a code golf, the shortest code in bytes wins.

Test cases:

27 --> 3
64 --> 4
1  --> 1
18.609625 --> 2.65
3652264 --> 154
0.001 --> 0.1
7  --> 1.9129

You can use all test cases above to test negative numbers (-27 --> -3, -64 --> -4 ...)

Haskell - 35

c n=(iterate(\x->(x+n/x/x)/2)n)!!99

Example runs:

c 27  =>  3.0
c 64  =>  4.0
c 1  =>  1.0
c 18.609625  =>  2.6500000000000004  # only first 4 digits are important, right?
c 3652264  =>  154.0
c 0.001  =>  0.1
c 7  =>  1.9129311827723892
c (-27)  =>  -3.0
c (-64)  =>  -4.0

Moreover, if you import Data.Complex, it even works on complex numbers, it returns one of the roots of the number (there are 3):

c (18:+26)  =>  3.0 :+ 1.0

The :+ operator should be read as 'plus i times'


Produce Dürer's magic square The challenge

Output an array or string representation of Dürer's famous magic square:

that is,

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

Some properties of this square, which can perhaps be exploited, are:

It contains each integer from 1 to 16 exactly once
The sum of each column or row, as well as the the sum of each of the two diagonals, is the same. This is the defining property of a magic square. The sum is the magic constant of the square.
In addition, for this particular square, the sum of each of the four quadrants also equals the magic constant, as do the sum of the center four squares and the sum of the corner four squares.

Rules

Bultins that generate magic squares are not allowed (such as Matlab's magic or Mathematica's MagicSquare). Any other builtin can be used.

The code can be a program or a function.

There is no input.

The numbers must be in base 10. The output format is flexible as usual. Some possibilities are:

A nested array (either function output, or its string representation, with or without separators, any type of matching brackets):

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

A 2D array:

{16, 3, 2, 13; 5, 10, 11, 8; 9, 6, 7, 12; 4, 15, 14, 1}

An array of four strings, or a string consisting of four lines. The numbers may be right-aligned

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

or left-aligned

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

A string with two different separators for row and column, such as

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

The output format should clearly differentiate rows and columns. For example, it is not allowed to output a flat array, or a string with all numbers separated by spaces.

Code golf. Shortest wins.

Pyth, 18 bytes

c4.PC"H#ût"_S16

Run the code.

c4.PC"H#ût"_S16

    C"H#ût"       Convert the packed string to the number 1122196781940
  .P       _S16   Take that-numbered permutation of the reversed range [16,15,...,1]
c4                Chop into piece of length 4

Reversing the range was meant to lower the permutation index, since the output starts with 16, but I think it only broke even.

This beat out a more boring strategy of converting the table directly to base 17 and then a string (link) for 20 bytes:

c4jC"úz(ás¸H"17


Maximum Hamming distance among a list of padded strings The Hamming distance between two strings of equal length is the number of positions at which the corresponding characters are different. If the strings are not of equal length, the Hamming distance is not defined.

Challenge

Write a program or function that finds the largest Hamming distance from among all pairs of strings from a list of strings, padded as required according to the rules described below.

The characters will be from within a-zA-Z0-9.

The strings may not be equal in length, so for each comparison the shorter string has to be padded as follows:

wrap the string from the beginning as many times as needed to match the required length
change the cases of the letters each odd time wrapping (1st, 3rd, 5th, etc.)
leave things outside a-zA-Z unchanged when wrapping

For example, let's say you need to pad the 5 character string ab9Cd so that it ends up with 18 characters. You would end up with:

ab9CdAB9cDab9CdAB9
     ^^^^^     ^^^

with ^ added underneath the 1st and 3rd wraps to highlight to case changes.

Input/Output

Input/output format is flexible. You can assume the input has at least two strings, and that all strings will have at least one character.

The output is an integer.

Rules

This is code-golf. Standard rules apply.

Test cases

[ "a", "b" ] => 1
[ "a", "b", "c" ] => 1
[ "a", "a", "c" ] => 1
[ "abc", "abcd" ] => 1
[ "abc12D5", "abC34d3", "ABC14dabc23DAbC89d"] => 17
[ "a", "Aaa", "AaaA", "aAaAa", "aaaaaaaaaaaaaa", "AAaAA", "aAa" ] => 8
["AacaAc", "Aab"] => 2

Reference implementation

I tested the examples with (completely ungolfed) R code that you can try here to compare any other examples you might try out with your code.


Find the sum of closest distances For this task your code should take two sorted arrays of integers X and Y as input.  It should compute the sum of the absolute distances between each integer in X and its closest number in Y.

Examples:

X = (1 5,9)
Y = (3,4,7)

The distance is 2 + 1 + 2.

X = (1,2,3)
Y = (0,8)

The distance is 1 + 2 + 3.

Your code can take input in any way that is convenient.

The main restriction is that your code must run in linear time in the sum of the length of the two arrays.. (You can assume that adding two integers takes constant time.)

Haskell, 70 64 bytes

a%b=abs$a-b
x@(a:b)#y@(c:d)|e:_<-d,a%c>a%e=x#d|1>0=a%c+b#y
_#_=0

Try it online!

Explanation

First we define (%) to be the absolute difference between two numbers.  Then we define (#) to be the interesting function. In the first line we match when both lists are non-empty:

x@(a:b)#(c:d:e)

On our first case from here we bind d to e:_ with e:_<-d.  This ensures that d is non-empty and sets it's first element to e.

Then if the second element of \$Y\$ (e) is closer than the first (c) to the first element of \$X\$ (a), we return x#d removing the first element of \$Y\$ and calling again with the same \$X\$.

If we match the pattern but don't pass the condition we do:

a%c+b#y

Which, removes the first item of \$X\$ and adds the absolute difference of it from the first element of \$X\$ to the remaining result.

Lastly if we don't match the pattern we return \$0\$.  Not matching the pattern means that \$X\$ must be empty because \$Y\$ cannot be empty.

This algorithm has order notation \$O(|X|+|Y|)\$.

Haskell, 34 bytes

Here's how I would do it in \$O(\left|X\right|\times\left|Y\right|)\$ time:

x#y=sum[minimum$abs.(z-)<$>y|z<-x]

Try it online!