The shortest code to tell if a number is even or odd One of my colleagues proposed us a challenge: to write the shortest C/C++ program to determine if a number is even or odd.

These are the requirements:

Get a number from keyboard, at run-time (not from command line)
Output the string pari if the number is even
Output the string dispari if the number is odd
We can assume that the input is legal
We can assume that the machine has a i386 architecture
Code preprocessing is not allowed (e.g.: use #defines)
[edit after comments] The code can be considered valid if it compiles with gcc 4.x

This is the best attempt we had so far (file test.c, 50B):

main(i){scanf("%d",&i);puts("dispari"+3*(~i&1));}

Do you think we can go further?

(*): "dispari" is the italian for odd and "pari" is the italian for even

47 bytes (2 less)

main(i){scanf("%d",&i);puts("dispari"-~i%2*3);}

For a positive i, ~i is negative, so ~i%2 is 0 or -1.


How Shuffled is this Sequence? Given a sequence \$S\$ with length \$n\$ of exactly one each of whole numbers from \$1\$ to \$n\$, your task is to return a number \$\sigma\$ indicating how shuffled it is.

Definition of shuffledness

Humans perceive shuffling randomness locally [Citation Needed], so the shuffledness of a sequence is based on the ability to find various patterns within each sliding window \$W\$ of 5 consecutive elements of the sequence (\$W = \{S_x, S_{x+1},  S_{x+2}, S_{x+3}, S_{x+4}\}\$ for some \$x\$- these will overlap, as each \$x\$ that is at least \$4\$ less than \$n\$ is considered). For each window of 5 elements, add a point for each test of the following that fails: (Note the 1-indexing due to the use of mathematical notation)

Apply the following tests to the whole window:

\$W\$ is monotonic
\$W\$ is in ascending order
Some permutation of \$W\$ is a run of sequential integers (e.g. 1, 2, 3, 4, 5)
For all \$W_i\$ where \$i>1\$, \$W_i = W_{i-1}+k\$ for some integer \$k\$.

This corresponds to regular linear intervals

For all \$W_i\$ where \$i>1\$, \$W_i = W_{i-1}+ax+k\$ for some integers \$k, a\$, where \$x=i\$.

This corresponds to regular quadratic intervals (which could also be linear)

Apply the same tests for subwindows where 1 or 2 elements have been removed (if any one of those reduced windows passes a particular test, this step passes. Only count one failure when a test fails for all reduced windows.
Apply the same tests for windows with some pair of adjacent elements optionally swapped (this step will pass if all tests passed for the whole unmodified window) Replace test 3 with the following:

\$W\$ is an ascending or descending sequence of sequential integers (e.g. 5, 4, 3, 2, 1)

Notes

Ascending sequential sequences will pass every test for all windows and therefore be scored as \$0\$
Descending sequential sequences will pass all tests except the "ascending" one for all windows and will therefore be scored as \$3(n-4)\$
The naive maximum shuffledness is \$15(n-4)\$

Examples

[1, 5, 3, 2, 4]

All elements:

Passes test 3
Fails all other tests (+4)

Elements removed:

Passes tests 1, 2, 5 with [1, 2, 4] (remove 5 and 3)
Passes test 3 with [5, 3, 2, 4] (remove 1)
Fails test 4 (+1)

Elements swapped:

Fails all tests (+5)

Test 3 fails because it requires the elements to be in order for this case only

\$\therefore \sigma = 10\$

[1, 2, 4, 3, 5]

All elements:

Passes test 3
Fails all other tests (+4)

Elements removed:

All tests pass with [1, 2, 3] (remove 4, 5)

Elements swapped:

Passes all tests (swap 4, 3)

\$\therefore \sigma = 4\$

[3, 6, 9, 12, 15]  (a sliding window)

All elements:

Passes tests 1, 2, 4, 5
Fails test 3 (+1)

Elements removed: same (+1)
Elements swapped: same (+1) (no swap)
\$\therefore \sigma = 3\$

[8, 12, 13, 11, 6] (a sliding window)

All elements:

Passes test 5 (\$a=-3, k=4\$)
Fails all other tests (+4)

Elements removed:

Passes tests 1, 2, 5 with [8, 12, 13] (remove 11, 6)
Passes test 3 with [12, 13, 11] (remove 8, 6)
Fails test 4 (+1)

Elements swapped: same as all elements (+4) (no swap)
\$\therefore \sigma = 9\$

[2, 4, 6, 1, 3, 5] (whole sequence)

First window: ([2, 4, 6, 1, 3])

All elements: Fails all tests (+5)
Elements removed:

Passes tests 1, 2, 4, 5 with [2, 4, 6]
Passes test 3 with [2, 1, 3]

Elements swapped: Fails all tests (+5)

Second window: ([4, 6, 1, 3, 5])

All elements: Fails all tests (+5)
Elements removed:

Passes tests 1, 2, 4, 5 with [1, 3, 5]
Passes test 3 with [4, 6, 5]

Elements swapped: Fails all tests (+5)

\$\therefore \sigma = 20\$

Rules and such

Standard IO rules, loopholes, etc
You must handle sequences of up to 1000 elements long
You may assume \$S\$ is at least 5 elements long
No validation necessary. You may assume that all inputs contain exactly one each of every whole number from \$1\$ to \$n\$
Shortest code wins!

Jelly, 71 65 bytes

J4Ṭ;-+ʋ€ịṭ@Wẋ¥€3ṭœcJ;2/Ṣṭ,`Ɗ€€ƲḊ,UṢƑ€o\ƲI,I$E€ƊIỊẠƊ3ƭ€€€»/€¬µ5ƤFS

Try it online!

A monadic link taking a list if integers and returning an integer. I’m sure this can be shortened further.

Explanation

...µ5Ƥ   | Run the main chain (below) for each 5-integer-long infix of the list
      F  | Flatten list
       S | Sum

Main chain

This generates the lists for the each set of tests. To deal with the variation in test 3, there are 3 copies made of each innermost list. For the first and second sets of tests, the last copy of each innermost list is sorted, while for the third set of tests it is not.

Main chain part 1 (generates swapped lists for third set of tests)

J                | Sequence along list [1,2,3,4,5]
 4    ʋ€         | Do the following as a dyad for each of 1,2,3,4 with 1,2,3,4,5 as the right argument:
  Ṭ              | - Convert to logical list with 1 at the relevant index [[1],[0,1],[0,0,1],[0,0,0,1]]
   ;-            | - Concatenate -1 to this
     +           | - Add (to [1,2,3,4,5])
        ị        | Index into original list
         ṭ@      | Tack onto end the original list
           Wẋ¥€3 | Repeat each inner list 3 times

Main chain part 2 (generates lists for first and second sets of tests)

ṭ             Ʋ  | Tack output of part 1 onto the following:
 œcJ             | - Combinations of lengths 1,2,3,4,5
    ;2/          | - Pairwise reduce using concatenation
           Ɗ€€   | - Following as a monad for each innermost list:
       Ṣ         |   - Sort
        ṭ,`      |   - Tacked onto the list paired with itself
               Ḋ | - Remove first (i.e. the combinations of lengths 1 and 2)

Main chain part 3 (runs the tests)

                   3ƭ€€€     | For each innermost list, do one of the following three in turn:
       Ʋ                     | - Tests 1 and 2
,U                           |   - Pair with reversed list
  ṢƑ€                        |   - Check whether each invariant if sorted
     o\                      |   - Cumulative or
              Ɗ              | - Tests 4 and 5
        I                    |   - Increments (test 4)
         ,I$                 |   - Paired with increments of increments (test 5)
            E€               |   - Check if all equal for each of these
                  Ɗ          | - Test 3
               I             |   - Increments
                Ị            |   - Absolute value <= 1
                 Ạ           |   - All
                        »/€  | Reduce each using max - picks the best results for each test for each set of tests
                           ¬ | Not (vectorises)


Code Golfinator-3000 As everyone knows, adding inator-3000 to the end of any noun makes it way cooler. But what else can make a word cooler?

Given an ASCII string as input, output the coolness of the word.

Calculating the coolness

There are 4 elements to calculating the coolness of a word.

The word itself. The base score is the number of capital letters multiplied by 1000
The end number. A number at the end of the word (such as burninator-3000) is added to the base score, but if the number is more than 4 digits, they're being too greedy and the number should be ignored.
The connector. A space before the end number adds 1000, while a hyphen adds 2000, any other symbol, or no symbol at all, has no effect.
The suffix. If the word ends in ator, double the final score. If it ends in inator, triple the score. These are case insensitive.

So for example Burninator-3000 can be calculated as follows:

1 Capital letter - Base Score: 1000
(1000(base) + 3000(number) + 2000(hyphen)) * 3(suffix) = 18000

Testcases

Burninator-3000 -> 18000
Burnator3000 -> 8000
BurNinator 100 -> 9300
BuRnInAtOr-7253 -> 42759
burn -> 0
burn- -> 0
bUrn-1 -> 3001
inator-7 -> 6021
ator 56 -> 2112
burninators 1000 -> 2000
burn_1000 -> 1000
BURNINATOR-9999 -> 65997
burninator 99999 -> 3000
burninator_99999 -> 0
Code Golfinator-3000 -> 21000
inator ator hello world-1000 -> 3000
javaiscool_99999 -> 0
hypen-ated -> 0
1000 -> 1000
-1000 -> 3000
10000 -> 0
-10000 -> 2000
BURN1N470R-3000 -> 11000

Scoring

This is code-golf, so fewest bytes in each language wins!


Write a line in program that looks useless Write some program (the size doesn't matter), and put a line that looks useless, but it's actually not - if it would be removed, the program would crash, or do something wrong. Feel free to mark the line that looks unused by a comment, or mention it your code description, like in example below (of course, in this example, the line is actually not needed, it's just an example).

int main(void) {
    /* The line below is actually needed. */
    2 + 2;

    return 0;
}

As this is popularity contest, the solution with highest number of votes wins.

C

int main(int argc, char **argv) {
    switch(argc) {
        case 2:
            ;
            int allowed = 0;
        case 3:
            argc--;
            break;
        default:
            argc = 3;
    }
    return 0;
}

Won't compile if we remove the single ;.

EDIT:

Solution below:

   This happens because a case statement is just a label, and, as such, must be followed by a statement (which the standard refers to as a "specifier for actions to be performed", which rules out declarations). To prevent this, we prefix the declaration with a ;, a null statement. Specifications for the case label can be found here at page 142 (131 in-document)


Assembly Language Quine Write the shortest possible assembly-language quine.

Use any ISA you want, unless it has a print-quine instruction or equivalent.  Examples include x86, MIPS, SPARC, MMIX, IBM BAL, MIX, VAX, JVM, ARM, etc.

You may link against the C standard library's _printf function (or the Java equivalent for JVM bytecode) for I/O.

Length will be judged both on instruction count and size of the data segment.  Solutions must contain at least two instructions.

The quine should print the assembly code, not the assembled machine code.

x86 Linux, AT&T syntax: 244

push $10
push $34
push $s
push $34
push $37
push $37
push $s
call printf
mov $0,%ebx
mov $1,%eax
int $128
s:.ascii "push $10
push $34
push $s
push $34
push $37
push $37
push $s
call printf
mov $0,%cebx
mov $1,%ceax
int $128
s:.ascii %c%s%c%c"

(I compiled it with this: gcc -nostartfiles -lc quine.S -o quine)


Cardinal Numbers in Standard American English Let n be any integer between 1 and 999,999 inclusive. Your challenge is to write a complete program which using stdin or command-line arguments takes in n and outputs the number of times the letter "o" is needed to write all cardinal numbers in standard American English between 1 and n. You can assume that n will always be an integer within the above given range.

You can just use all lowercase letters as I do below. So we count all "o". No need to worry about uppercase "O".

Here is a quick review of how to write English numerals in American English.

one two three four ... nine ten eleven twelve thirteen fourteen ... nineteen twenty
twenty-one twenty-two ... twenty-nine thirty ... forty ... fifty ... sixty ...
seventy ... eighty ... ninety ... one hundred ... two hundred ... three hundred ...
nine hundred ... one thousand ... two thousand ... nine thousand ... ten thousand ...
eleven thousand ... ninety-nine thousand ... one hundred thousand ...
two hundred thousand ... nine hundred ninety-nine thousand nine hundred ninety nine.

The hyphen for two digit numbers doesn't matter.

The commas don't matter of course. I excluded them above.

Separation between hundreds and tens doesn't matter because we are only counting the letter "o" so 110 can be written as "one hundred ten", or "one hundred and ten". I excluded the "and" above.

For this challenge "hundred" and "thousand" must be preceded by "one" instead of "a" when being used at the beginning of the number. So 1111 must be "one thousand one hundred eleven" instead of "a thousand one hundred eleven".

Here are some more random numerals to clarify.

219873 = two hundred nineteen thousand eight hundred seventy three
615023 = six hundred fifteen thousand twenty three
617610 = six hundred seventeen thousand six hundred ten
423716 = four hundred twenty-three thousand seven hundred sixteen
386031 = three hundred eighty-six thousand thirty one

Here are some samples for what your code should return.

./mycount 1
1

There's only "one" to write so we need only a single "o".

./mycount 10
3

We only need three o's namely in "one", "two", and "four".

./mycount 101
41

Your code must be self-contained and must not connect to the internet, download any files, perform any query, etc. I can already see somebody using google or mathematica with wolfram alpha to do this.

True code-golf. The shortest code in any language wins. Please post your code with some test cases. In the case of ties, I pick the one with the highest upvotes after waiting at least for two weeks. So everyone feel free to upvote any solutions you like.

Happy coding!

R - 54

sum(nchar(gsub("[^o]","",english::english(1:scan()))))

I get 41 for n=101. I hope someone can confirm.


Chotchkies Restaurant Because there isn't enough xkcd on PPCG...

Challenge

The challenge is the same as above - given a menu and a total price, you need to find what the customer ordered.

The menu will be supplied as a text file in the format:

Name:Price
Name:Price

The path to the menu file and the total price should be supplied via argv or STDIN.
If you wish, the menu may be supplied via STDIN/argv (instead of newlines, separate each item by commas).

The output should be a list of values. If there are multiple answers, output all of them.

Example

Menu:

Burger:12.60
Pepsi:3.50
Lobster Thermidore:33.10
Ice Cream:23.00

Total Price: 68.70

The output is:

Burger
Lobster Thermidore
Ice Cream

Winning

The fastest code given an undisclosed problem wins. The speed will be taken five times and averaged.

Python 2 - Naive implementation - 224

Well, let's start with "the most naive algorithm" as some kind of reference solution:

import itertools

path = input()
total = input()

with open(path) as f:
    menu = map(lambda l: l.split(':'), f.read().split('\n'))

names, prices = zip(*menu)
prices = map(float, prices)

for i in range(len(menu)):
    for comb in itertools.combinations(range(len(menu)), i):
        if sum(prices[c] for c in comb) == total:
            for i in comb:
                print names[i]

Input:

"data.txt"
68.70

Output:

Burger
Lobster Thermidore
Ice Cream

Complexity:

O(2^N * N)

--> exponential in the number of menu items N (of course)

Edit:

To reflect the new winning criterion I golfed it down quite a bit:

from itertools import*
S=str.split
f,t=S(input())
m=[S(l,':')for l in S(open(f).read(),'\n')]
R=range(len(m))
F=float
for i in R:
 for C in combinations(R,i):
  if sum(F(m[c][1])for c in C)==F(t):
   for j in C:print m[j][0]

The input format changed to data.txt 68.70 (both on one line separated with a whitespace).


Simulate a random walk Context

In this challenge, a random walk is a stochastic process in which a particle at a position with integer coordinates (or a drunk man) moves at each integer time step (that is, at t = 1, 2, 3, ...) by taking a step of size 1 to any of its neighbouring positions, with the direction of the step being aligned with the axis, but chosen randomly

For example, in one dimension, we may have the following table of positions at the given times, starting at t = 0 with the initial condition p = 2:

----------
| t |  p |
----------
| 0 |  2 |
----------
| 1 |  3 |
----------
| 2 |  2 |
----------
| 3 |  3 |
----------
| 4 |  2 |
----------
| 5 |  1 |
----------
| 6 |  0 |
----------
| 7 | -1 |
----------
| 8 |  0 |
----------
| 9 | -1 |
----------
   ...

Task

Your task is to simulate a random walk in n dimensions from a supplied starting point, until the drunk man arrives at the origin for the first time, i.e. when we reach the point with coordinates [0,0,...,0] for the first time. If we start at the origin, nothing has to be done because we already arrived.

In the example above, the program would have stopped at t = 6.

You can take whatever probability distribution you want over the possible directions to go, so long as, for any position and any direction, there is a non-zero probability of that direction being picked.

Notice that your program must work for an arbitrary dimension, even though in practice, for higher dimensions it will not stop in a reasonable amount of time.

Input

Any initial position with integer coordinates, of any positive size (so 1 or more). You can infer the dimensions of the random walk from the size of the input or you can take the dimension as an extra input. If you do, assume the dimension given matches the size of the initial position.

Input of initial position can be in any sensible format, including:

a list of integers
one input coordinate per function argument

Your program should work for any n, even though in practice it will time out for n >= 3 unless you are incredibly lucky :)

Output

You should return or print any of the following:

all the intermediate positions occupied by the particle until the end of the random walk
all the intermediate steps taken by the particle until the end of the random walk

The intermediate positions can be displayed in any human-readable way, as long as no two different positions are displayed the same way. Same applies to intermediate steps taken.

Test cases

These should finish on TIO often:

[3]
[1, 0]
[0, -2]
[1, 1]
[-1,1]
[0]
[0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]

These will probably timeout, but that is fine as long as your program runs:

[1, 0, 0, 0]
[0, 0, 3, 0, -2, 100]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

You can check this reference program where I set the seed so that you can see it terminating for a random walk of 3 dimensions.

This is code-golf so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

Jelly,  13  12 bytes

LXṬ,N$X+µẸÐ¿

A monadic Link accepting a list of integers which yields a list of lists of integers.

Try it online!

How?

LXṬ,N$X+µẸÐ¿ - Link: list of integers, p (length d)
          Ð¿ - collect up while...
         Ẹ   - ...condition: any? (when we reach [0]*d this does not hold
        µ    - ...do: the monadic chain - i.e. f(v); initially v=p:
L            -   length (of v) = d
 X           -   random integer (in range [1,d])
  Ṭ          -   untruth     e.g. 4 -> [0,0,0,1]
     $       -   last two links as a monad:
    N        -     negate              [0,0,0,-1]
   ,         -     pair                [[0,0,0,1],[0,0,0,-1]]
      X      -   random choice         [0,0,0,1] OR [0,0,0,-1]
       +     -   add (to v)  e.g. [0,0,0,-1] + [4,2,3,2,5] = [4,2,3,1,5]


How many significant figures? Given a number as input, determine how many significant figures it has. This number will should be taken as a string because you have to do some special formatting. You'll see what I mean soon (I think).

A digit is a sig-fig if at least one of the following apply:

Non-zero digits are always significant.
Any zeros between two significant digits are significant.
final zero or trailing zeros in the decimal portion only are significant.
all digits are significant if nothing follows the decimal place.
when there are only zeroes, all but the last zero are considered leading zeroes

Input

A string or string array of the number. It might have a decimal point at the end without a digit after it. It might not have a decimal point at all.

Output

How many sig-figs there are.

Examples

1.240 -> 4
0. -> 1
83900 -> 3
83900.0 -> 6
0.025 -> 2
0.0250 -> 3
2.5 -> 2
970. -> 3
0.00 -> 1

Retina, 29 27 bytes

Saved 2 bytes thanks to @MartinEnder

^0\.0*.|^\d(\d*?)0+$
1$1
\d

Try it online! | Test suite


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

Please post one tip per answer.

Should be answers to respective challenges (if they exist). Note that some of these code samples might alerady be answers somewhere else.

If you just want to print undefined, use this 4-byte, 1-char program.

Infinite loop (6 bytes, 2 chars).

ℹ⏩

Cat (owned by Conor O'Brien) (15 bytes, 5 chars).

⏫⏪⏬⏫⏩

This program should output the 8 phases of the moon, but it doesn't seem to work (61 bytes, 16 chars).

⏪⏬⏩

Hypothenuse (27 bytes, 7 chars).

➕


Piles and Piles of Pebbles My job is stacking pebbles into triangular piles. I've only been doing this for a century and it is already pretty boring. The worst part is that I label every pile. I know how to decompose pebbles into piles of maximal size, but I want to minimize the number of piles. Can you help?

Task

Given an integer, decompose it into the minimum number of triangular numbers, and output that minimum number.

Triangular Numbers

A triangular number is a number which can be expressed as the sum of the first n natural numbers, for some value n. Thus the first few triangular numbers are

1 3 6 10 15 21 28 36 45 55 66 78 91 105

Example

As an example, let's say the input is 9. It is not a triangular number, so it cannot be expressed as the sum of 1 triangular number. Thus the minimum number of triangular numbers is 2, which can be obtained with [6,3], yielding the correct output of 2.

As another example, let's say the input is 12. The most obvious solution is to use a greedy algorithm and remove the largest triangular number at a time, yielding [10,1,1] and an output of 3. However, there is a better solution: [6,6], yielding the correct output of 2.

Test Cases

in out
1 1
2 2
3 1
4 2
5 3
6 1
7 2
8 3
9 2
10 1
11 2
12 2
13 2
14 3
15 1
16 2
17 3
18 2
19 3
20 2
100 2
101 2
5050 1

Rules

The input integer is between 1 and the maximum integer of your language.
I can emulate any language with my pebbles, and I want your code as small as possible because I have nothing but pebbles to keep track of it. Thus this is code-golf, so the shortest code in each language wins.

Retina, 57 49 bytes

.+
$*
(^1|1\1)+$
1
(^1|1\1)+(1(?(2)\2))+$
2
11+
3

Try it online! Based on my answer to Three triangular numbers. Change the third line to ^(^1|1\1)*$ to support zero input. Edit: Saved 8 (but probably should be more) bytes thanks to @MartinEnder.


JAxH obfuscated method, not text A JAPH is a grand tradition of making a program that prints "Just another Perl hacker,". We already have a question about JAPH on this site but they seem more concerned with hiding the text, but JAPH has always been more about hiding the method by which it does what it does. Therefore I challenge you to show off your favorite language's cool features, and don't worry too much about hiding the text (unless you want to).

Here's mine, in Perl, which shouldn't be to hard for an experienced velociraptor to understand, but may be interesting for others.

(*STORE,*TIESCALAR)=map{eval"sub{$_}"}qw'map{print&&sleep$|}split//,pop bless\$|++';tie$t,main;$t="Just another Perl hacker,\n"

Judged subjectively on votes by you guys, lets see some mind-benders!

C

Must be compiled to 32bit. On 64bit machines use gcc -m32 or such.

#include <stdlib.h>

int main() {
    char *c = "echo Just another C hacker";
    int foo=123; //unused                          /* Warning: there's a
    int k=(int)1                                    * (long) system
    //now for the fun part!                         * of chinese boxes
    //behold:                                       * in this code. */
    +0;
    -1;
    ((int(*)(char *))k)(c);
}

Disclaimer: not my idea. I found it years ago hidden in some piece of code. Seriously. Theirs was even better, I forgot several little details. But the gist is there.

When you see it, you'll sh*t bricks.


AWK -vn=, 9
a[$1]++<n

This is so competitive with the golfing-language answers, I feel like I might have misunderstood the question - did I?
The limit n is passed as a variable at the command line with -vn=<value>. The array is read from STDIN.
Try it online!


Check if a pattern appears in a DNA sequence In a project I am working on, I am checking to see if certain DNA sequences appear in certain genes in E. coli. I have written a program in Java that performs the below features. However, since I wrote my program in Java, the universe needs to be corrected and rid of verbosity by having you write your code in as few bytes as possible.
My program took a DNA sequences and a regex as input (for this challenge, order doesn't matter). The DNA sequence contains only the letters A, C, G, and T. It will be determined if the DNA sequence contains any subsequences that follow the regex, and the output of the program will be the one-indexed location(s) of the first character of each matching subsequence in the DNA sequence in your choice of format. If there is no such location, you may output any reasonable indicator of this.
The regex I used had the following specifications.

A, C, G, and T match to themselves.
N matches to any of A, C, G, and T
(X/Y) means that at the current location in the sequence, the next character(s) in the sequence match X or Y (note that X and Y can be multiple characters long, and that there can be multiple slashes; for example, (AA/AG/GA) matches to AA, AG or GG; however, X and Y must have the same length)

You may assume that the DNA sequence is longer than any sequence that follows the specifications of the regex, and that both the DNA and the regex are valid.

Test cases
Here, the DNA sequence is first, and the regex is second.
AAAAAAAAAA
AAA
==> 1 2 3 4 5 6 7 8

ACGTAATGAA
A(A/C)(T/G/A)
==> 1 5

GGGGCAGCAGCTGACTA
C(NA/AN)
==> 5 8 15

ACGTTAGTTAGCGTGATCGTG
CGTNA
==> 2 12

This is code-golf. The shortest answer in bytes wins. Standard rules apply.

Python 3, 125 bytes

import re,sys
a=sys.argv
s=re.sub
print([i+1 for i in range(len(a[1]))if re.match(s('N','[ACGT]',s('/','|',a[2])),a[1][i:])])


Does the start equal the end? The Task
In this challenge, your task is to write a program or function which takes in a String and outputs a truthy or falsey value based on whether the first character and the last character of the input String are equal.
Input
You may take input in any way reasonable way. However, assuming that the input is  present in a predefined variable is not allowed. Reading from a file, console, command line, input field etc., or taking input as a function argument is allowed.
Output
You may output in any reasonable format, except for assigning the result to a variable. Writing to a file, console, command line, modal box, function return statements etc. is allowed.
Additional Rules

The input can be empty String as well, for which you should return a falsey value.

Single-Char Input Strings should have a truthy result.

Your program should be case-sensitive. helloH should output a falsey value.

You can only have a single Truthy value and a single Falsey value. For example, outputting false for an Input String and 0 for another input String  as Falsey values is not allowed.

Standard loopholes are not allowed.

Test Cases
Input    ->    Output

"10h01"        Truthy
"Nothing"      Falsey
"Acccca"       Falsey
"wow!"         Falsey
"wow"          Truthy
"H"            Truthy
""             Falsey

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

Python 3, 23 bytes

s=input()
s[0]!=s[-1]<e

Output is via exit code, so 0 (success) is truthy and 1 (failure) is falsy. If this is acceptable, a byte can be saved.

Try it online!

How it works

First of all, if s is an empty string, s[0] will raise an IndexError, causing the program to fail.

For non-empty s, if the first and last characters are equal, s[0]!=s[-1] will evaluate to False, so the program exits cleanly and immediately.

Finally, if the characters are different, s[0]!=s[-1] will evaluate to True, causing the compairson s[-1]<e to be performed. Since e is undefined, that raises a NameError.

If backwards compatibility with Python 2 is not desired,

s[0]!=s[-1]<3

works as well, since comparing a string with an integer raises a TypeError.


Code Golf: Your own horizontal pet ASCII snake Very heavily inspired by this challenge Code Golf: Your own pet ASCII snake - I thought making it horizontal would add an extra layer of complexity.

An example horizontal snake:

            0 0
  0        0 0 000
00 0     00       000 0      0
    000 0            0 0   00
       0                000

And the rules are:

Exactly 5 lines of characters are printed
Each line is exactly 30 characters long, consisting of a combination of spaces and the character you choose to draw your snake with
Your snake starts on line 3
The next line to be used for drawing your snake must be randomly chosen from your current line, one line above (if you're not already on line 1) or one line below (if you're not already on line 5).

These choices must be equally weighted. So if you are on line 1, you have a 50% chance to stay on line 1 and a 50% chance to move to line 2. If you are on line 2, you have a 33% chance to move to line 1, a 33% chance to stay on line 2 or a 33% chance to move to line 3

Your snake does not need to visit every single line.

JavaScript (ES6), 98 bytes
Saved 7 bytes thanks to @KevinCruijssen
Returns an array of 5 strings.
f=(y=2,a=[...'  0  '])=>a[0][29]?a:f(y+=(Math.random()*(y%4?3:2)|0)-!!y,a.map((v,i)=>v+=i-y&&' '))

Try it online!
Commented
f = (                       // given:
  y = 2,                    //   y = current line (0-indexed)
  a = [...'  0  ']          //   a[] = array of 5 lines
) =>                        //
  a[0][29] ?                // if all columns have been processed:
    a                       //   stop recursion and return a[]
  :                         // else:
    f(                      //   do a recursive call with:
      y += (                //     the updated value of y, to which we add -1, 0 or 1:
        Math.random() *     //       pick a random value in [0,1)
        (y % 4 ?            //         if y is neither 0 or 4:
          3                 //             multiply it by 3
        :                   //           else:
          2                 //             multiply it by 2
        ) | 0               //       force an integer value
      ) - !!y,              //     subtract either 0 or 1
      a.map((v, i) =>       //     for each value v at position i in a[]:
        v += i - y && ' '   //       append either '0' if i = y or a space otherwise
      )                     //     end of map()
    )                       //   end of recursive call


Generate list of numbers and their negative counterparts A recent SO question asks for a convenient one-liner to generate a list of numbers and their negative counterparts in Python.

Given two integers \$1≤a≤b\$, generate all the integers \$x\$ such that \$a≤|x|≤b\$. The result may be printed or returned in any order or structure, as putting the result into a list and sorting it, yields [-b,1-b,2-b,…,-a,a,a+1,a+2,…,b]

Examples

\$a=6,b=9\$ gives [6,-6,7,-7,8,-8,9,-9] or [6,7,8,9,-9,-8,-7,-6] or [-8,7,-9,-7,9,8,-6,6] or [[6,-6],[7,-7],[8,-8],[9,-9]] or [[6,7,8,9],[-6,-7,-8,-9]] etc.

\$a=6,b=6\$ gives [6,-6] or [-6,6] or [[6,-6]] or [[6],[-6]] etc.

Python 2, 33 bytes

def f(a,b):print-a,a;a<b<f(a+1,b)

Try it online!

A recursive function that prints in a two-column format. Based on ideas from Surculose Sputum.

In Python 3, we'd need 2 more bytes for print() needing parens.

Python 2, 37 bytes

lambda a,b:range(a,b+1)+range(-b,1-a)

Try it online!

Unfortunately for this challenge, Python's ranges are exclusive, so we have to add 1 to both upper endpoints.


Scan dactylic hexameter in a unique puzzle As a terrible Latin student for several years I have learned to hate many things about Latin.  However there is one thing I love.

Latin scansion.

Scansion is the act of determining the meter of a particular line of poetry.  For Latin this means demarcating each syllable in the line as "light" or "heavy".

In Latin scansion has many of rules.  However unlike English Latin scansion is fairly regular and often requires no knowledge of Latin vocabulary or grammar to be performed.  For this problem we will be using simplified subset of those rules (real Latin does not have a neat spec).

Before you begin the scansion you must elide. Elision is the dropping syllables between words to ease pronunciation. (e.g. "he is" -> "he's"). Unlike English, Latin elision follows very nice rules.

The final vowel of a word ending with a vowel is omitted if the next word begins with a vowel.

NAUTA EST -> NAUTEST
The same goes for words ending in a vowel followed by "m".

FIDUM AGRICOLAM -> FIDAGRICOLAM
Word-initial "h" followed by a vowel counts as a single vowel for elision purposes and is always dropped when elided.

MULTAE HORAE -> MULTORAE

or

MULTAM HORAM -> MULTORAM

After elision we can begin scansion.  Scansion is done to a specific meter.  The meter for this challenge is dactylic hexameter.  Dactylic hexameter has six "feet" each foot consists of two or three syllables.  Syllables can be either long or short depending on the vowel.  Each of the first five feet will be either a dactyl, a long syllable followed by two short ones, or a spondee, two long syllables. And the last foot will be a long followed by an anceps (short or long, for this problem you will not have to determine which).

A vowel in latin can be either short or long
An "i" sandwiched between two vowels (e.g. eiectum) is a consonant. (i.e. a "j")
An "i" beginning a word followed by a vowel (e.g Iactus) is also a consonant
A "u" after a "q" is also a consonant (i.e. a "v")
Diphthongs (ae, au, ei, eu, oe, and ui) are made up of two vowels but count as one vowel and are always long
A vowel with two or more consonants between it and the next vowel is always long
For the previous rule an "l" or an "r" after a "b","c","d","g","p", or "t" does not count as a consonant
"x" counts as two consonants
"ch", "ph", "th", and "qu" count as one consonant
The syllable "que" at the end of a word (after elision) is always short
If a vowel is not forced by one of the previous rules it can be either long or short this will depend on the meter

Your task will be to take a line of latin and produce the scansion of it.  You will take in the line as string via standard input and output a string representing the final scansion.

The input will contain only spaces and characters A-Z.

To represent the scansion you will output all of the syllables with | demarcating the separation of feet.  A long syllable will be represented by a - while a short syllable will be marked by a v and an anceps (the last syllable of every line) will be marked by a x.  If there are multiple solutions as there often will be you may output anyone of them.

Test Cases

The start of Virgil's Aeneid.

 ARMA VIRUMQUE CANO TROIAE QUI PRIMUS AB ORIS     -> -vv|-vv|--|--|-vv|-x (or -vv|-vv|--|-vv|--|-x)
 ITALIAM FATO PROFUGUS LAVINIAQUE VENIT           -> -vv|--|-vv|-vv|-vv|-x
 LITORA MULTUM ILLE ET TERRIS IACTATUS ET ALTO    -> -vv|--|--|--|-vv|-x
 VI SUPERUM SAEVAE MEMOREM IUNONIS OB IRAM        -> -vv|--|-vv|--|-vv|-x (or -vv|--|-vv|-vv|--|-x)
 MULTA QUOQUE ET BELLO PASSUS DUM CONDERET URBEM  -> -vv|--|--|--|-vv|-x
 INFERRETQUE DEOS LATIO GENUS UNDE LATINUM        -> --|-vv|-vv|-vv|-vv|-x
 ALBANIQUE PATRES ATQUE ALTAE MOENIA ROMAE        -> --|-vv|--|--|-vv|-x

Further stipulations

In the proper fashion of Latin poetry all answers must begin with an invocation to the muses.

Latin has only two one letter words "e" and "a".  You may assume that no other one letter words will appear as input.

sed, 402 392 374 359 363 334 333 bytes

  “Sing, goddess, the anger of Peleus’ son Achilleus
  and its devastation, which put pains thousandfold upon the Achians,
  hurled in their multitudes to the house of Hades strong souls
  of heroes, but gave their bodies to be the delicate feasting
  of dogs, of all birds, and the will of Zeus was accomplished
  since that time when first there stood in division of conflict
  Atreus’ son the lord of men and brilliant Achilleus.”

— Homer (The Iliad); confused why this quote is here? check the rules.

sed -E 's/[AEIOU]M? H?([AEIOU])/\1/g;s/X/cc/g;s/(^|[ AEIOU])I([AEIOU])/\1c\2/g;s/QUE( |$)/cv/g;s/A[EU]|E[IU]|OE|UI/-/g;s/[CPT]H|[BCDGPT][LR]|QU|[^-vAEIOU ]/c/g;s/ //g;s/ucc+/-/g;s/c//g;s/^[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u].$/-\1|-\2|-\3|-\4|-\5|-x/;s/[uv]/-/g;s/---/-vv/g'

Not exactly golfed, but this implements all the given rules in the form of regular expressions, which sed just runs one-by-one to reach the solution. This handles each line independently, so can process an entire multi-line input.

Usage:

printf 'ARMA VIRUMQUE CANO TROIAE QUI PRIMUS AB ORIS
ITALIAM FATO PROFUGUS LAVINIAQUE VENIT
LITORA MULTUM ILLE ET TERRIS IACTATUS ET ALTO
VI SUPERUM SAEVAE MEMOREM IUNONIS OB IRAM
MULTA QUOQUE ET BELLO PASSUS DUM CONDERET URBEM
INFERRETQUE DEOS LATIO GENUS UNDE LATINUM
ALBANIQUE PATRES ATQUE ALTAE MOENIA ROMAE' | sed -E '<...>';

Breakdown:

sed -E "
# Apply Elision
 s/[AEIOU]M? H?([AEIOU])/\1/g;

# Convert into vowels (u, v or -) and consonants (c) according to the rules given
 s/X/cc/g;
 s/(^|[ AEIOU])I([AEIOU])/\1c\2/g;
 s/QUE( |\$)/cv/g;
 s/A[EU]|E[IU]|OE|UI/-/g;
 s/[CPT]H|[BCDGPT][LR]|QU|[^-vAEIOU ]/c/g;
 s/[A-Z]/u/g; # all remaining vowels are unknown

# Remove all spaces
 s/ //g;

# A vowel followed by 2 consonants before the next vowel is long
# (and we don't care if the last vowel is long or short)
 s/ucc+/-/g;

# Remove all consonants
 s/c//g;

# Look for a matching dactylic hexameter and insert pipe separators
 s/^\
[-u]([-u]|[vu]{2})\
[-u]([-u]|[vu]{2})\
[-u]([-u]|[vu]{2})\
[-u]([-u]|[vu]{2})\
[-u]([-u]|[vu]{2})\
[-u].\$/-\1|-\2|-\3|-\4|-\5|-x/;

# Substitute identified feet with the necessary long/short vowels
 s/[uv]/-/g;
 s/---/-vv/g
"

Results for test cases:

-vv|-vv|--|--|-vv|-x
-vv|-vv|--|-vv|-vv|-x
-vv|--|--|--|-vv|-x
-vv|--|-vv|-vv|--|-x
-vv|--|--|--|-vv|-x
--|-vv|-vv|-vv|-vv|-x
--|-vv|--|--|-vv|-x


Write numbers as a difference of Nth powers Challenge
There are many numbers which can be expressed as the difference of two squares, or as the difference of two cubes, or maybe even higher powers. Talking about squares, there are various ways of writing a number, say 75, as the difference of 2 squares. You can write:
75 = (10)^2 - (5)^2
   = (14)^2 - (11)^2
   = (38)^2 - (37)^2

So let's talk about the challenge. Firstly, the user enters a number and then he enters a value for n. You need to display all the ways in which that number can be written in the form of aⁿ - bⁿ.
Input and Output
The input will be the number and the value of n. Your output shall have all such pairs of 'a' and 'b' such that the above-stated condition is met. The first number in the pair must be larger than the second. Please note that a, b, n and the input number are all positive integers, and n > 1.
Examples
50, 2 -> (none)

32, 2 -> (9,7), (6, 2)

7, 3 -> (2,1)

665, 6 -> (3, 2)

81, 4 -> (none)

Scoring
This is code-golf , so the shortest code wins!

Jelly, 8 bytes

p*ƓIFẹ+d

This is a monadic link that takes the number as argument and reads n from STDIN.

Try it online!

How it works

p*ƓIFẹ+d  Main link. Argument: k

p         Cartesian product; yield all pairs [b, a] with b and a in [1, ..., k].
  Ɠ       Get; read an integer n from STDIN.
 *        Power; map each [b, a] to [b**n, a**n].
   I      Increments; map each [b**n, a**n] to [a**n-b**n].
    F     Flatten the resulting list of singleton arrays.
     ẹ    Every; find all indices of k in the list we built.
      +   Add k to the indices to correct the offset.
       d  Divmod; map each index j to [j/k, j%k].


Find the nth digit of Euler's number Challenge

Given a positive integer n, you must calculate the nth digit of \$e\$, where \$e\$ is Euler's number (2.71828...).

The format of the output can be a number or a string (e.g., 3 or '3')

Example

# e = 2.71828...

nthDigit(3) => 8
nthDigit(1) => 7
nthDigit(4) => 2

Shortest code wins.

Python 2, 34 32 bytes

Solution provided by @l4m2
-2 bytes thanks to @xnor

lambda n:`(100**n+1)**100**n`[n]

Try it online!

Very,  very slow.

Verification up to \$166\$ digits. The idea for this verification comes from @l4m2: calculates \$x^{100^n}\$ by calculating x=x**10 repeatedly (\$2n\$ times), each time truncating \$x\$ to a few left most digits (the TIO link uses \$500\$ digits). By changing the truncation to round down or up, we obtain the lower and upper bound for the result. If the lower and upper bound agree to \$n\$ leftmost digits, we know that the exact calculation will also result in those \$n\$ digits.

I have verified that this solution works up to \$n = 333\$, using MAX_DIGITS = 1000.

How

This solution uses the following well known approximation of \$e\$:
$$ e = \lim_{x \to \infty} \left(1 + \frac{1}{x} \right)^{x}$$
Substituting \$x = 100^n\$, we have:
$$ e = \lim_{n \to \infty} \left(1 + \frac{1}{100^n} \right)^{100^n} = \lim_{n \to \infty} \frac{\left(100^n + 1 \right)^{100^n}}{\left(100^n\right)^{100^n}}$$
Since the denominator is a power of \$10\$, we can ignore it entirely.

According to this analysis on Math SE, the worst case error of this approximation is:
$$ \Delta < \frac{3}{x} = \frac{3}{100^n}$$
which means roughly that every time \$n\$ increases by \$1\$, we gains 2 digits of precision.


Patience, young "Padovan" Everyone knows the Fibonacci sequence:
You take a square, attach an equal square to it, then repeatedly attach a square whose side length is equal to the largest side length of the resulting rectangle.
The result is a beautiful spiral of squares whose sequence of numbers is the Fibonacci sequence:

But, what if we didn't want to use squares?

If we use equilateral triangles—instead of squares—in a similar fashion, we get an equally beautiful spiral of triangles and a new sequence:  the Padovan sequence, aka A000931:

Task:

Given a positive integer, \$N\$, output \$a_N\$, the \$N\$th term in the Padovan sequence OR the first \$N\$ terms.

Assume that the first three terms of the sequence are all \$1\$.  Thus, the sequence will start as follows:
$$
1,1,1,2,2,3,...
$$

Input:

Any positive integer \$N\ge0\$
Invalid input does not have to be taken into account

Output:

The \$N\$th term in the Padovan sequence OR the first \$N\$ terms of the Padovan sequence.
If the first \$N\$ terms are printed out, the output can be whatever is convenient (list/array, multi-line string, etc.)
Can be either \$0\$-indexed or \$1\$-indexed

Test Cases:
(0-indexed, \$N\$th term)

Input | Output
--------------
0     | 1
1     | 1
2     | 1
4     | 2
6     | 4
14    | 37
20    | 200
33    | 7739

(1-indexed, first \$N\$ terms)

Input | Output
--------------
1     | 1
3     | 1,1,1
4     | 1,1,1,2
7     | 1,1,1,2,2,3,4
10    | 1,1,1,2,2,3,4,5,7,9
12    | 1,1,1,2,2,3,4,5,7,9,12,16

Rules:

This is code-golf: the fewer bytes, the better!
Standard loopholes are forbidden.

Jelly, 10 bytes

9s3’Ẓæ*³FṀ

Try it online!

1-indexed. Computes the largest element of: $$\begin{bmatrix}0&0&1 \\ 1&0&1 \\ 0&1&0\end{bmatrix}^n$$
where the binary matrix is conveniently computed as: $$\begin{bmatrix}\mathsf{isprime}(0)&\mathsf{isprime}(1)&\mathsf{isprime}(2) \\ \mathsf{isprime}(3)&\mathsf{isprime}(4)&\mathsf{isprime}(5) \\ \mathsf{isprime}(6)&\mathsf{isprime}(7)&\mathsf{isprime}(8)\end{bmatrix}$$

(this is a total coincidence.)

9s3         [[1,2,3],[4,5,6],[7,8,9]]    9 split 3
   ’        [[0,1,2],[3,4,5],[6,7,8]]    decrease
    Ẓ       [[0,0,1],[1,0,1],[0,1,0]]    isprime
     æ*³    [[0,0,1],[1,0,1],[0,1,0]]^n  matrix power by input
        FṀ                               flatten, maximum


Leap for Leap Seconds! Since today marks the occasion of the 26th leap second ever to occur, your challenge will be to output the date and time of every leap second in GMT or UTC that has occurred so far, as well as the one to occur today.

Input

There is no input.

Output

1972-06-30 23:59:60
1972-12-31 23:59:60
1973-12-31 23:59:60
1974-12-31 23:59:60
1975-12-31 23:59:60
1976-12-31 23:59:60
1977-12-31 23:59:60
1978-12-31 23:59:60
1979-12-31 23:59:60
1981-06-30 23:59:60
1982-06-30 23:59:60
1983-06-30 23:59:60
1985-06-30 23:59:60
1987-12-31 23:59:60
1989-12-31 23:59:60
1990-12-31 23:59:60
1992-06-30 23:59:60
1993-06-30 23:59:60
1994-06-30 23:59:60
1995-12-31 23:59:60
1997-06-30 23:59:60
1998-12-31 23:59:60
2005-12-31 23:59:60
2008-12-31 23:59:60
2012-06-30 23:59:60
2015-06-30 23:59:60

Rules

Since I doubt there are many built-ins that allow leap-seconds, I'll allow them.

Standard loopholes are disallowed.

Shortest code wins.

Date format must have a zero-padded month and a 4-digit year, as well as military time and a space separating the time from the date. Putting UTC at the end is optional. Your choice of dashes or slashes.

EDIT: Yep as predicted, this became an encoding challenge. If only encoding could fix the leap second problem, ...then all our code would be much more practical. Maybe we need some ideas for more fun challenges with practical uses?

R, 78 75 bytes

Built-ins, you say? Well...

message(paste(as.Date(.leap.seconds)-1,"23:59:60\n"),"2015-06-30 23:59:60")

R has an automatic variable .leap.seconds which contains the date and time of each leap second insertion, given in the system's local time. As of R version 3.2.0, this does not include today, so I've added that manually.

Ungolfed + explanation:

# Convert the datetime values to UTC dates. These will be a day past the
# expected output, so we can subtract 1 to get what we want.
dates <- as.Date(.leap.second) - 1

# Paste the UTC time and a newline onto the end of each date
datetimes <- paste(dates, "23:59:60\n")

# Print each time, including today, on its own line
message(datetimes, "2015-06-30 23:59:60")

You can try it online!


Print the amount of ones in a binary number without using bitwise operators Description

Given a number, print the amount of 1s it has in binary representation.

Input

A number >= 0 in base 10 that won't exceed the highest number your language is able to handle.

Output

The amount of 1s in binary representation.

Winning condition

The shortest code wins.

Disallowed

Bitwise operators. Other operators, like addition and multiplication, are allowed.
Built-in base conversion functions.

Examples

Input:     Ouput:

56432      8

Input:     Output:

45781254   11

Input:     Output:

0          0

APL, 9 12 characters
+/2|⌊⎕÷2*⍳32

This assumes that the interpreter uses 32-bit integers, and that ⎕IO is set to 0 (meaning that monadic ⍳ begins with 0, rather than 1). I used the 32-bit version of Dyalog APL.
Explanation, from right to left:

⍳32 generates a vector of the first 32 integers (as explained before, because ⎕IO is 0, this vector begins with 0).
* is the power function. In this case, it generates 2 to the power of each element of the vector supplied as its right argument.
÷ is the divided-by function. It gives us ⎕ (evaluated user input) divided by each element of the vector to its right (each power of two).
⌊ floors each element of the argument to its right.
2| gives us the remainder of each element of to its right divided by 2.
/ reduces (folds) its right argument using the function to its left, +.

Not quite 9 characters anymore. :(
Old, rule-breaking version:

+/⎕⊤⍨32/2

Explanation, from right to left:

32/2: Replicate 2, 32 times.
⍨ commutes the dyadic function to its left, which in this case is ⊤ (i.e., X⊤⍨Y is equivalent to Y⊤X).
⊤ is the encode function. It encodes the integer to its right in the base given to its left. Note that, because of the commute operator, the right and left arguments are switched. The base is repeated for the number of digits required, hence 32/2.
⎕ is a niladic function that accepts user input and evaluates it.
+/ reduces (folds) its right argument using +. (We add up the 0's and 1's.)


Constrained integer partition Challenge
In this challenge, all numbers are in \$\mathbb{N}_0\$.
Create a function or program that, when given a number \$N\$ and a tuple of \$k\$ numbers \$(n_i)\$ (all ≤ \$N\$), returns the number of ways \$N\$ can be written as a sum of \$k\$ integers (\$x_1 + x_2 + ... + x_k\$) such that \$n_i \le x_i \le N\$.
The input format is not fixed. You can read and parse strings, take two parameters as int and int[], etc.
This is a variation of the classical Integer Partition problem.
Test Cases
\$N=4, n=(0, 0, 2) \implies 6\$ (2+0+2, 1+1+2, 0+2+2, 1+0+3, 0+1+3, 0+0+4)
\$N=121, n=(7, 16, 21, 36, 21, 20) \implies 1\$ (7+16+21+36+21+20)
This is code-golf, so the lowest byte count for each language wins!

Jelly, 5 bytes
rŒp§ċ

A dyadic Link accepting the lower bound tuple on the left and the total on the right which yields the count.
Try it online!
How?
rŒp§ċ - Link: T, N       e.g. [2,1,3], 5
r     - inclusive range       [[2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
 Œp   - Cartesian product     [[2,1,1],[2,1,2],[2,1,3],[2,1,4],[2,1,5],[2,2,1],...,[5,5,4],[5,5,5]]
   §  - sums                  [ 4,      5,      6,      7,      8,      5,     ..., 14,     15]
    ċ - count (Ns)            2


Pokemon GO Evolution Cost Calculator Tired of always wondering how many more Pokémon you need to catch to get those high-tier evolutions? Wonder no more! Now you will write a complete program or function to calculate it for you!

The Challenge:

As input, your program will receive a list of the costs in candy to evolve a Pokémon to the next tier. (This list may be separated by any delimiter of your choosing, or as function arguments). Your program will then return or print the number of Pokémon that must be caught, including the one that will be evolved, to evolve through all the tiers given.

How do you calculate this? Like so:
1. Add up all the candy costs: 12 + 50 = 62
2. Subtract 3 candies from the total, this being from the one Pokémon you keep for evolving: 62 - 3 = 59
3. Divide this number by 4 (3 for catching, 1 for giving it to the Professor), always taking the ceil() of the result: ceil(59/4) = 15
4. Finally, add 1 to this total to get the total number of Pokémon you must catch, 16!

Example Input -> Output:

[4] -> 2
[50] -> 13
[12, 50] -> 16
[25, 100] -> 32
[19, 35, 5, 200] -> 65

Winning:

The app has already taken up most of the space on your phone, so your program needs to be as short as possible. The complete program or function with the smallest byte count will be accepted in two weeks! (with any ties being settled by the earliest submitted entry!)

Jelly, 5 4 bytes
S:4‘

Try it online!
Sum, integer divide : by 4 and increment ‘.


Return the last color of the input in Manufactoria This puzzle is the next in my series of Manufactoria challenges.

Background

Manufactoria is a game / two-dimensional programming language.  The player must create programs that will manipulate a queue to arrive at the desired output.  It is easy to learn but hard to master, so it lends itself to creating a wide variety of challenges.  If you don't know what I am talking about, I advise that you play the first few tutorial levels of the game.

Challenge

Your challenge is to create a machine that will return the very last element of the input string.  To make this even more challenging, the input string can be any combination of all four colors.

The official custom level to be used is found here:

http://pleasingfungus.com/Manufactoria/?ctm=Last_in_Line!;IN:_a_series_of_colors_OUT:_the_very_last_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3;0;

This week's challenge is mostly focused on the idea of compression. I chose this challenge to require a huge mess of conveyor belts. The fact that all four colors appear in the input means that it is very hard to store information.

Although I did not attempt compression, my first working prototype had 114 parts and fit into the 13x13 space with almost no room to spare.

Scoring

The goal of this challenge is to use a few parts as possible.  The score is the number of parts placed, and the lowest score wins.

Although there are only 8 test cases, your creation should be able to theoretically function under any test case.  The test cases provided are for debugging purposes.

Examples

in:  byrgyrbyrrgry
out: y
in:  ggryybrryr
out: r
in:         #don't you love degenerate cases?
out:
in:  gyrbrygbrygbyrb
out: b


Fastest python code to find a set of winning words in this game This is a word game from a set of activity cards for children.  Below the rules is code to find the best triplet using /usr/share/dict/words.  I thought it was an interesting optimization problem, and am wondering if people can find improvements.

Rules

Choose one letter from each of the sets below.
Choose a word using the letters chosen (and any others).
Score the word.

Each letter from the chosen set gets the number shown with the set (repeats included).
AEIOU count 0
All other letters are -2

Repeat steps 1-3 above (no reusing letters in step 1) twice more.
Final score is the sum of the three word scores.

Sets

(set 1 scores 1 point, set 2 scores 2 points, etc.)

LTN
RDS
GBM
CHP
FWV
YKJ
QXZ

Code:

from itertools import permutations
import numpy as np

points = {'LTN' : 1,
          'RDS' : 2,
          'GBM' : 3,
          'CHP' : 4,
          'FWV' : 5,
          'YKJ' : 6,
          'QXZ' : 7}

def tonum(word):
    word_array = np.zeros(26, dtype=np.int)
    for l in word:
        word_array[ord(l) - ord('A')] += 1
    return word_array.reshape((26, 1))

def to_score_array(letters):
    score_array = np.zeros(26, dtype=np.int) - 2
    for v in 'AEIOU':
        score_array[ord(v) - ord('A')] = 0
    for idx, l in enumerate(letters):
        score_array[ord(l) - ord('A')] = idx + 1
    return np.matrix(score_array.reshape(1, 26))

def find_best_words():
    wlist = [l.strip().upper() for l in open('/usr/share/dict/words') if l[0].lower() == l[0]]
    wlist = [l for l in wlist if len(l) > 4]
    orig = [l for l in wlist]
    for rep in 'AEIOU':
        wlist = [l.replace(rep, '') for l in wlist]
    wlist = np.hstack([tonum(w) for w in wlist])

    best = 0
    ct = 0
    bestwords = ()
    for c1 in ['LTN']:
        for c2 in permutations('RDS'):
            for c3 in permutations('GBM'):
                for c4 in permutations('CHP'):
                    for c5 in permutations('FWV'):
                        for c6 in permutations('YJK'):
                            for c7 in permutations('QZX'):
                                vals = [to_score_array(''.join(s)) for s in zip(c1, c2, c3, c4, c5, c6, c7)]
                                ct += 1
                                print ct, 6**6
                                scores1 = (vals[0] * wlist).A.flatten()
                                scores2 = (vals[1] * wlist).A.flatten()
                                scores3 = (vals[2] * wlist).A.flatten()
                                m1 = max(scores1)
                                m2 = max(scores2)
                                m3 = max(scores3)
                                if m1 + m2 + m3 > best:
                                    print orig[scores1.argmax()], orig[scores2.argmax()], orig[scores3.argmax()], m1 + m2 + m3
                                    best = m1 + m2 + m3
                                    bestwords = (orig[scores1.argmax()], orig[scores2.argmax()], orig[scores3.argmax()])
    return bestwords, best

if __name__ == '__main__':
    import timeit
    print timeit.timeit('print find_best_words()', 'from __main__ import find_best_words', number=1)

The matrix version is what I came up with after writing one in pure python (using dictionaries and scoring each word independently), and another in numpy but using indexing rather than matrix multiplication.

The next optimization would be to remove the vowels from the scoring entirely (and use a modified ord() function), but I wonder if there are even faster approaches.

EDIT: added timeit.timeit code

EDIT: I'm adding a bounty, which I'll give to whichever improvement I most like (or possibly multiple answers, but I'll have to accrue some more reputation if that's the case).

Here's an idea - you can avoid checking lots of words by noticing that most words have awful scores.  Say you have found a pretty good scoring play that gets you 50 points.  Then any play with more than 50 points must have a word of at least ceil(51/3)=17 points.  So any word that can't possibly generate 17 points can be ignored.

Here's some code that does the above.  We compute the best possible score for each word in the dictionary, and store it in an array indexed by score.  Then we use that array to check only words that have the required minimum score.

from itertools import permutations
import time

S={'A':0,'E':0,'I':0,'O':0,'U':0,
   'L':1,'T':1,'N':1,
   'R':2,'D':2,'S':2,
   'G':3,'B':3,'M':3,
   'C':4,'H':4,'P':4,
   'F':5,'W':5,'V':5,
   'Y':6,'K':6,'J':6,
   'Q':7,'X':7,'Z':7,
   }

def best_word(min, s):
    global score_to_words
    best_score = 0
    best_word = ''
    for i in xrange(min, 100):
        for w in score_to_words[i]:
            score = (-2*len(w)+2*(w.count('A')+w.count('E')+w.count('I')+w.count('O')+w.count('U')) +
                      3*w.count(s[0])+4*w.count(s[1])+5*w.count(s[2])+6*w.count(s[3])+7*w.count(s[4])+
                      8*w.count(s[5])+9*w.count(s[6]))
            if score > best_score:
                best_score = score
                best_word = w
    return (best_score, best_word)

def load_words():
    global score_to_words
    wlist = [l.strip().upper() for l in open('/usr/share/dict/words') if l[0].lower() == l[0]]
    score_to_words = [[] for i in xrange(100)]
    for w in wlist: score_to_words[sum(S[c] for c in w)].append(w)
    for i in xrange(100):
        if score_to_words[i]: print i, len(score_to_words[i])

def find_best_words():
    load_words()
    best = 0
    bestwords = ()
    for c1 in permutations('LTN'):
        for c2 in permutations('RDS'):
            for c3 in permutations('GBM'):
            print time.ctime(),c1,c2,c3
                for c4 in permutations('CHP'):
                    for c5 in permutations('FWV'):
                        for c6 in permutations('YJK'):
                            for c7 in permutations('QZX'):
                                sets = zip(c1, c2, c3, c4, c5, c6, c7)
                                (s1, w1) = best_word((best + 3) / 3, sets[0])
                                (s2, w2) = best_word((best - s1 + 2) / 2, sets[1])
                                (s3, w3) = best_word(best - s1 - s2 + 1, sets[2])
                                score = s1 + s2 + s3
                                if score > best:
                                    best = score
                                    bestwords = (w1, w2, w3)
                                    print score, w1, w2, w3
    return bestwords, best

if __name__ == '__main__':
    import timeit
    print timeit.timeit('print find_best_words()', 'from __main__ import find_best_words', number=1)

The minimum score gets rapidly up to 100, which means we need only consider 33+ point words, which is a very small fraction of the overall total (my /usr/share/dict/words has 208662 valid words, only 1723 of which are 33+ points = 0.8%).  Runs in about half an hour on my machine and generates:

(('MAXILLOPREMAXILLARY', 'KNICKKNACKED', 'ZIGZAGWISE'), 101)


Determine the Winner of a Game of Australian Football In Australian Football, goals are worth 6 points and behinds are worth 1 point. Scores may include the number of goals and behinds, as well as the total score. Given the number of goals and behinds for two different teams, determine which team won the game.
Take four integers g1, b1, g2, b2 as input, and output two distinct values for whether the first team or the second team inputted won. Input format is flexible, but input order must allow it to be obvious which team is first. For example, g1, g2, b1, b2 would be allowed, but b1, g2, g1, b2 would not.
Test Cases
Test cases will use true for the first team winning and false for the second team winning. Input is in the format (g1,b1),(g2,b2).
(1,0),(0,1)        true
(2,0),(0,11)       true
(10,8),(11,1)      true
(0,0),(1,0)        false
(100,100),(117,0)  false
(7,7),(5,12)       true
(2,0),(0,13)       false

As an example, for input (10,8),(11,1), team 1 scored 10 goals and 8 behinds, for a total of \$10*6+8*1=68\$ points, while team 2 scored \$11*6+1*1=67\$ points, so team 1 wins.
No input will be a draw - your program's behavior on draw input does not matter.

Jelly, 3 bytes
ḅ6M

A monadic Link accepting a list of lists of integers, [[g1,b1],[g2,b2]], which yields a list [1] or [2].
(Draws would yield [1,2])
...Or a full program printing 1 or 2.
Try it online! Or see the test-suite.
How?
ḅ6M - Link: list of lists of integers, X
 6  - literal six
ḅ   - convert (X) from base 6 (vectorises)
  M - maximal indices


Compute 30000 Digits of Pi (π), as Fast as Possible Compute 30000 digits of the mathematical constant π, with the fastest code.

Implement in any computer programming language that I can run in my 64 bit Linux machine. You should provide your compiler optimization options if any. I am ready to install a new compiler or language runtime to run your code, given that I am not spending any money.

The code that finishes calculation and prints the output in the shortest time wins! I will measure the running time with the time command.

note 1: The program should be single threaded.
note 2: With 3.14, the number of digits is 3; with 3.1415, 5, and so on.
note 3: Hard coding π is not allowed.
note 4: Now you can use any number form in your code, not only integer.
note 5: Your output, which should be in decimal digits, need not contain the .. Just print out the numbers.
note 6: Your last digit should not be rounded up. If the next digit after the last is 5 or more, you should round up your last digit still leave the last digit as is.

Since this question was marked as duplicate, to this question. I should explain that this is a 'fastest-code' question not 'code-golf' and thus not a dupliate. The 'code-golf' answers are not well suited as an answer to this question; they are not the 'fastest'.

Python 2 (Spigot Algorithm)

This is just Jeremy Gibbon's algorithm implemented in python. Definitely will be faster once someone else implements this in another language. Other methods might be faster too since I started working on this when the rules stated that I could only use integers. I originally tried doing this without string conversion and joining, but it was actually slower..

def p():
 q,r,t,j=1,180,60,2
 while True:
    u,y=3*(3*j+1)*(3*j+2),(q*(27*j-12)+5*r)//(5*t);yield y;q,r,t,j=10*q*j*(2*j-1),10*u*(q*(5*j-2)+r-y*t),t*u,j+1
p=p()
print''.join(str(p.next())for x in[1]*30000)

Completes on my work machine in about 53 seconds.


m-nomial coefficient While the binomial coefficient are the coefficients of \$(1+x)^n\$, m-nomial coefficients are the coefficients of \$(1+x+x^2+...+x^{m-1})^n\$.
For example, \$m(3,5,6)\$ is the coefficient of \$x^6\$ in the expansion of \$(1+x+x^2)^5\$.
Write a program/function that takes 3 numbers as input and outputs the corresponding m-nomial coefficient.
Details

Input can be taken via any reasonable method.
Everything out of range is \$0\$, for example \$m(2,0,-1) = m(2,5,6) = 0\$
The first argument will be positive.
The second argument will not be negative.
All three arguments will be integers.

Testcases
Inputs:
[1,0,0]
[2,5,6]
[3,5,6]
[4,5,-1]

Outputs:
1
0
45
0

Scoring
This is code-golf. Shortest solution in bytes wins.

Perl, 63 60 59 57 bytes

Includes +2 for -pa

Give input parameters on STDIN

mnomial.pl <<< "3 5 6"

#!/usr/bin/perl -pa
$_=/-/^($_--,1x$F[2])=~/^(1{0,$_}){$F[1]}$(??{++$;})/+$

As a perl programmer I just know that every problem is really a regex in disguise...

Explanation:

m(3,5,6) can be seen as the number of ways you can get 6 by adding 5 integers in the range [0..2]. You can write a regex matching such a partition using:

1 x 6 = /^(1{0,2}){5}$/

However once a single solution is found the regex stops. We need to fail the found solution to get the regex to backtrack to the next solution and count the failures. In perl this can be done by extending the regex at runtime with something that is sure to fail, e.g. by demanding that something comes after the end of the string:

 1 x 6 = /^(1{0,2}){5}$(??{++$n})/

$n will count the number of failed attempts

My solution is basically this with two modifications:

Output the counter in such a way that you get 0 instead of the empty string if there is no valid partition and the counter never gets incremented
If the third argument is negative it would work if negative string lengths existed, but 1 x -5 is the empty string and 0 can be written exactly one way as sum of zeros, so that would output 1 instead of 0. I xor with the result of /-/to change the 1 back to 0

Without the need to handle a negative third argument this 49 byte solution would be good enough (give one parameter of m(x,y,z) on each line of STDIN in order y \n z \n x \n):

#!/usr/bin/perl -pa
$_=(1x<>)=~/^(1{0,@{[<>-1]}}){@F}$(??{++$;})/+$


Sum of indices of second least significant bit This is a pure code-golf question.

Input: A non-negative integer n

Output: Sum of the indices of the second least significant set bit in the binary representation of the integers 0...n. If the number doesn't have two set bits then the contribution to the sum should be zero.

Your code should be runnable on a standard linux machine using free software and shouldn't take more than n+1 seconds to run.

Sample answers for n from 0..20

0 0 0 1 1 3 5 6 6 9 12 13 16 18 20 21 21 25 29 30

Here is some sample ungolfed python code.

def get_2nd_least_bit(x):
    sum = 0
    for i in range(0,x.bit_length()):
        sum += (x >> i) & 1
        if sum == 2 :
            return i
    return 0
for x in xrange(20):
    print sum(get_2nd_least_bit(i) for i in xrange(x+1)),


Check type of an integer You will receive an integer less than 2000000000 and bigger than -2000000000 and you have to test what type(s) of number this is out of:
Factorial
Square
Cube
Prime
Composite
Triangular
Positive
Negative

Here is a definition  of all the different types of numbers:
Factorial - A number That is equal to the product of all positive integers less than the a certain positive integer - 5×4×3×2×1 = 120
Square - A number that is the product of two identical integers - 5×5 = 25
Cube - A number that is the product of three identical integers - −5×−5×−5 = -125
Prime - A number that has only two divisors (1 and 0 are not) - 3
Composite - A number that has more than two divisors (also not 1 or 0) - 4
Triangular - A number that is equal the sum of all positive integers less than the a certain positive integer - 5+4+3+2+1 = 15
Positive - A number larger than 0 (not 0) - 7
Negative - A number less than 0 (not 0) - −7
Test Cases
-8 = ["Cube","Negative"]
-2 = ["Negative"]
-1 = ["Cube","Negative"]
 0 = ["Cube", "Square", "Triangular"]
 1 = ["Cube","Factorial","Positive","Square","Triangular"]
 2 = ["Factorial","Positive","Prime"]
 3 = ["Positive","Prime","Triangular"]
 4 = ["Composite","Positive","Square"]
 5 = ["Positive","Prime"]
 6 = ["Composite","Factorial","Positive","Triangular"]
 7 = ["Positive","Prime"]
 8 = ["Composite","Cube","Positive"]
 9 = ["Composite","Positive","Square"]
10 = ["Composite","Positive","Triangular"]
11 = ["Positive","Prime"]
12 = ["Composite","Positive"]

Note: The Order of the Result Does Not Matter and it can be expressed with words (Does Not Have To Be A List)
Remember, this is a code golf so the smallest answer in bytes is what I'm looking for

APL (Dyalog Extended), 130 119 bytesSBCS

Anonymous tacit prefix function.

((∊∘⎕A⊂⊢)'FactorialSquareTriangularCubePositiveNegativePrimeComposite')/⍨{⍵∊¨(⊂∘!,×⍨⍮+\)⍳|⍵},(|∊⍳∘|*3⍨),<,>,1∘⍭,0∘⍭∧1∘<

Try it online!

(…)/⍨ filters the list of strings on the left by the bit mask on the right:

 (…)'Fac…ite' apply the following tacit function to the long string:

  ∊∘⎕A element-wise membership of the uppercase alphabet

  ⊂ partitions (i.e. True begins a new partition)

  ⊢ the unmodified argument

The last 46 bytes return a bit vector indicating [Factorial, Square, Triangular, Cube, Positive, Negative, Prime, Composite]:

{⍵∊¨(⊂∘!,×⍨⍮+\)⍳|⍵},(|∊⍳∘|*3⍨),<,>,1∘⍭,0∘⍭∧1∘<

Try it online!

{…} the first three bits (factorial, square, triangular) come from this anonymous lambda:

 ⍵∊¨(…)… is the argument a member of each of the following three lists?

  ⊂∘! the enclosed factorials

  , followed by

  ×⍨ the squares (lit. the multiplication selfies)

  ⍮ juxtaposed with

  +\ the running sum

 ⍳ of the integers one through

 |⍵ the absolute value of the argument

(…) the next bit (cube) comes from the following tacit function:

 | is the absolute value of the argument

 ∊ a member of

 ⍳∘| the integers 1 through the absolute value of the argument

 * raised to the power of

 3⍨ three

< the next bit is simply whether it is positive (zero is less than)

> the next bit is simply whether it is negative (zero is more than)

1∘⍭ the next bit is whether it is prime

0∘⍭ the final bit is whether it is non-prime

∧

1∘< one is less than it


Number of Straight-Chain Alk*nes of given length A straight-chain alk*ne is defined as a sequence of carbon atoms connected by single (alkane), double (alkene), or triple bonds (alkyne), (implicit hydrogens are used.) Carbon atoms can only form 4 bonds, so no carbon atom may be forced to have more than four bonds. A straight-chain alk*ne can be represented as a list of its carbon-carbon bonds.

These are some examples of valid straight-chain alk*nes:

[]       CH4              Methane
[1]      CH3-CH3          Ethane
[2]      CH2=CH2          Ethene
[3]      CH≡CH            Ethyne
[1,1]    CH3-CH2-CH3      Propane
[1,2]    CH3-CH=CH2       Propene
[1,3]    CH3-C≡CH         Propyne
[2,1]    CH2=CH-CH3       Propene
[2,2]    CH2=C=CH2        Allene (Propadiene)
[3,1]    CH≡C-CH3         Propyne
[1,1,1]  CH3-CH2-CH2-CH3  Butane
...

While these are not, as at least one carbon atom would have more than 4 bonds:

[2,3]
[3,2]
[3,3]
...

Your task is to create a program/function that, given a positive integer n, outputs/returns the number of valid straight-chain alk*nes of exactly n carbon atoms in length. This is OEIS A077998.

Specifications/Clarifications

You must handle 1 correctly by returning 1.
Alk*nes like [1,2] and [2,1] are considered distinct.
Output is the length of a list of all the possible alk*nes of a given length.
You do not have to handle 0 correctly.

Test Cases:

1 => 1
2 => 3
3 => 6
4 => 14

This is code golf, so lowest byte count wins!

MATL, 10 bytes
7K5vBiY^1)

Try it online!
Explanation
This uses the characterization found in OEIS

a(n) is the top left entry of the n-th power of the 3 X 3 matrix [1, 1, 1; 1, 0, 0; 1, 0, 1]

7    % Push 7
K    % Push 4
5    % Push 5
v    % Concatenate all numbers into a column vector: [7; 4; 5]
B    % Convert to binary: gives 3×3 matrix [1, 1, 1; 1, 0, 0; 1, 0, 1]
i    % Input n
Y^   % Matrix power
1)   % Take the first element of the resulting matrix, i.e. its upper-left corner.
     % Implicitly display


Communistic Substring Normalization If a string T of length K appears K or more times in a string S, then it is potentially communistic. For example, 10 in 10/10 is potentially communistic, for it appears 2 times and is of length 2. Note that these substrings cannot overlap.

A communistic transformation is one that takes this string T and moves each character ti of T to the i occurrence of T in S. So, for the previous example, the communistic transformation would yield 1/0; the first char of 10 replaces 10 the first time 10 is found, and 0 the second time.

A communistic normalization is a function that takes all such strings T with K ≥ 2 and performs a communistic transformation on them.

Some specifics on the algorithm:

Perform communistic transformations on the longest valid strings T first. Favor the first occurrences of T.
Then, perform communistic transformations on the next-longest strings, then the next-next-longest... etc.
Repeat until no such strings exist in the string.

Note that some strings, such as the "Hello, Hello" example in the test cases, can be interpreted two different ways.  You can use ell for T, but you can also use llo.  In this case, your code can choose either option.  The shown test case uses llo, but you may get a different and equally valid output.

Your task is to implement communistic normalization. The input will only ever consist of printable ASCII characters (0x20 to 0x7E, space to tilde). You may write a program or function to solve this task; the input may be taken as a line from STDIN, string/character array argument, argument from ARGV, etc.

Test cases

'123' -> '123'
'111' -> '111'
'1111' -> '11'
'ABAB' -> 'AB'
'111111111' -> '111'
'asdasdasd' -> 'asd'
'10/10' -> '1/0'
'100/100+100' -> '1/0+0'
'   +   +   ' -> ' + '
'Hello, hello, dear fellow!' -> 'Hel he, dear feow!' OR 'Heo hl, dear flow!'
'11122333/11122333/11122333' -> '112/13' OR '132/23'

'ababab1ababab' -> 'a1bab'
'1ab2ab3ab4ab5ab6' -> '1a2b3a4b5ab6'

Worked out test case

Format is 'string', 'substring', at each step of replacement.  Replaced bits are bracketed.

'11[122]333/11[122]333/11[122]333', '122'
'111[333]/112[333]/112[333]', '333'
'1113/11[23]/11[23]', '23'
'11[13]/112/1[13]', '13'
'1[11]/[11]2/13', '11'
'1[/1]12[/1]3', '/1'
'112/13', ''

Another test case:

'Hello, hello, dear fellow!', 'llo'
'Hel, hel, dear feow!', 'l,'
'Hel he, dear feow!', ''

Reference code (Python)

You may find this useful to visualize the algorithm.

#!/usr/bin/env python

import re

def repeater(string):
    def repeating_substring(substring):
        return (string.count(substring) == len(substring)) and string.count(substring) > 1

    return repeating_substring

def get_substrings(string):
    j = 1
    a = set()
    while True:
        for i in range(len(string) - j+1):
            a.add(string[i:i+j])
        if j == len(string):
            break
        j += 1
    return list(a)

def replace_each_instance(string, substring):
    assert `string`+',', `substring`
    for i in substring:
        string = re.sub(re.escape(substring), i, string, 1)

    return string

def main(s):
    repeats = repeater(s)
    repeating_substr = filter(repeater(s), get_substrings(s))

    while repeating_substr:
        repeating_substr.sort(lambda x,y: cmp(len(y), len(x)))
        s = replace_each_instance(s, repeating_substr[0])
        repeating_substr = filter(repeater(s), get_substrings(s))

    return s

assert main('123') == '123'
assert main('111') == '111'
assert main('1111') == '11'
assert main('ABAB') == 'AB'
assert main('111111111') == '111'
assert main('asdasdasd') == 'asd'
assert main('10/10') == '1/0'
assert main('100/100+100') == '1/0+0'
assert main('   +   +   ') == ' + '
assert main('Hello, hello, dear fellow!') == 'Hel he, dear feow!'
assert main('11122333/11122333/11122333') == '112/13'

Thanks to @ConorO'Brien for posting the original idea of this challenge.

JavaScript (ES6), 121 bytes
f=(s,j=2,o,m=s.match(`(.{${j}})(.*\\1){${(j-1)}}`))=>m?f(s,j+1,s.split(m[1]).map((e,i)=>e+(m[1][i]||'')).join``):o?f(o):s

Recursively matches the pattern:
(.{2})(.*\1){1}  //2 characters, repeated 1 time
(.{3})(.*\1){2}  //3 characters, repeated 2 times
(.{4})(.*\1){3}  //4 characters, repeated 3 times
etc.

… until the pattern isn't found.  (This guarantees that the longest string is handled first.)
It then performs the "communistic transformations" on the last-found pattern, by splitting on the match, and joining on each of the match's characters.  (map is used for this purpose.  Too bad join doesn't take a callback.)
It finally recurses on this new string until it is no longer communistic.
Test cases:

f=(s,j=2,o,m=s.match(`(.{${j}})(.*\\1){${(j-1)}}`))=>m?f(s,j+1,s.split(m[1]).map((e,i)=>e+(m[1][i]||'')).join``):o?f(o):s

console.log(f('123'));  //123
console.log(f('111'));  //111
console.log(f('1111')); //11
console.log(f('ABAB')); //AB
console.log(f('111111111')); //111
console.log(f('asdasdasd')); //asd
console.log(f('10/10')); //1/0
console.log(f('100/100+100')); //1/0+0
console.log(f('   +   +   ')); // +
console.log(f('Hello, hello, dear fellow!')); //Heo hl, dear flow!
console.log(f('11122333/11122333/11122333')); //132/23


Find the sum of the divisors of N Write a program that displays on the screen the sum of the divisors of a number (1 ≤ N ≤ 100) entered by the user in the range of 1 to N.

This is OEIS A000203.

Examples:

Input: 7

7 / 1 = 7
7 / 7 = 1

7 + 1 = 8

Output: 8

Input: 15

15 / 1 = 15
15 / 3 = 5
15 / 5 = 3
15 / 15 = 1

15 + 5 + 3 + 1 = 24

Output: 24

Input: 20

20 / 1 = 20
20 / 2 = 10
20 / 4 = 5
20 / 5 = 4
20 / 10 = 2
20 / 20 = 1

20 + 10 + 5 + 4 + 2 + 1 = 42

Output: 42

Input: 1

1 / 1 = 1

Output: 1

Input: 5

5 / 1 = 5
5 / 5 = 1

5 + 1 = 6

Output: 6

05AB1E, 2 bytes
ÑO

Try it online!
How?
Ñ    Divisors
 O   Sum


Correct way to add numbers to get lots of 8's Inspired by this question which was further inspired by this one, write a program which takes two integers and adds them in a unique way, by performing an OR operation on the segments used to display them in a 7-segment display.  For reference, the digits are represented in the following way:

 _        _   _         _    _   _    _    _
| |   |   _|  _|  |_|  |_   |_    |  |_|  |_|
|_|   |  |_   _|    |   _|  |_|   |  |_|   _|

Note that the 1 uses the two segments on the right, not the left.  There are two special characters that can be produced this way which are not numbers.  See the addition table below:

  | 0 1 2 3 4 5 6 7 8 9
--+--------------------
0 | 0 0 8 8 8 8 8 0 8 8
1 | 0 1 a 3 4 9 8 7 8 9
2 | 8 a 2 a 8 8 8 a 8 8
3 | 8 3 a 3 9 9 8 3 8 9
4 | 8 4 8 9 4 9 8 Q 8 9
5 | 8 9 8 9 9 5 6 9 8 9
6 | 8 8 8 8 8 6 6 8 8 8
7 | 0 7 a 3 Q 9 8 7 8 9
8 | 8 8 8 8 8 8 8 8 8 8
9 | 8 9 8 9 9 9 8 9 8 9

Useful observations:

Any digit plus itself equals itself
8 plus any digit equals 8
2 plus 1, 3, or 7 equals the letter 'a' (must be lower-case)
4 plus 7 equals either 'q' or 'Q', your choice
Numbers should be right-aligned, so the digits should be added from right to left.  If one number has more digits than the other, the extra digits at the beginning should be unchanged.  There are no leading 0's, unless the number is exactly 0.
All numbers will be 0 or greater.  You don't need to handle a '-' sign.  (Mainly because there's no good fit for the sum of a '-' and a '1' or '7'.)

Your program should accept 2 integers in any format you choose, and output a string containing their "sum" when calculated in this manner.  This is code-golf, so your program should be as small as possible.

Examples:

Input: 12345, 123.  Output: 12389
Input: 88888, 42.  Output: 88888
Input: 0, 23.  Output: 28
Input: 120, 240.  Output: a80
Input: 270, 42.  Output: 2Q8 (or 2q8)
Input: 1234567890, 1234567890.  Output: 1234567890

Bash + Common Linux utilities, 80

s=~0my3[_p^?{}s
h()(tr 0-9 $s<<<$1|xxd -p)
dc -e$[0x`h $1`|0x`h $2`]P|tr $s 0-9aQ

Note the ^? in the source should be replaced with an ASCII 0x7f character.
The string s is each 7 segment digit 0-9, a, Q encoded with each segment corresponding to a bit of an ASCII char.
The h() function transliterates the input number from decimal to the encoding specified by s, then outputs the result as a raw hex string.
The two resulting raw hex strings are ORed together using regular bash arithmetic, then output by dc's P command as a bytestream.  This bytestream is then transliterated back to decimal + a + Q and output.
Note also that when using the <<< bash herestring construct in function h() a newline is implicitly appended to the redirected string.  This doesn't matter - it is simply translated to 0x0a at the end of each hex string; when the two hex numbers are ORed together, the result is still 0x0a in the last char which doesn't get transliterated and thus simply translates back to a newline which is output after the result.
Test output:
$ for testcase in \
> "12345 123" \
> "88888 42" \
> "0 23" \
> "1234 56789" \
> "4 7"; do
> ./7segadd.sh $testcase
> done
12389
88888
28
58a89
Q
$


N-dimensional Circles! Write a program that takes two numbers as its input. The first one is the number of dimensions - 0 for a dot, 1 for a straight line, 2 for a circle, 3 for a sphere. The second number is the radius of the object, or, if it's 1-dimensional, the number itself. Output 0 for 0 dimensions. The output is the length/area/volume of the object.

If we call the first number n, the second one r, and the output x, we get that:

for n = 0, x = 1
for n = 1, x = 2×r
for n = 2, x = r2×π
for n = 3, x = (4/3)×r3×π
and so on... if you want, though.

Notes:

Cases when one or both numbers are negative, or when the first number is not whole, don't need to be covered.
The program must not read from any file and the only input are those two numbers.
The output should use only numerals (e.g. not "14*pi"), and should be accurate to at least two decimal digits.
As for n = 0, you can output 0 if it makes the code shorter.
Extra swag for an answer covering even 4 and more-dimensional "spheres"!
It's code-golf, so the shortest answer in bytes wins!

Examples:

 1 1 -> 2

 2 3 -> 28,27

 3 1 -> 4,19

 3 4,5 -> 381,70

 1 9.379 -> 18.758

 0 48 -> 1

Mathematica, 18 bytes, up to ~168.15 trillion dimensions

Pi^(a=.5#)/a!#2^#&

Anonymous function. Takes two numbers as input, and returns an inexact number as output. Works with any number of dimensions. Outputs 1. for n = 0. Uses the formula from Volume of an n-ball on Wikipedia.

Explanation

We are attempting to compute πn/2/Γ(n/2 + 1)·Rn, or N[Pi^(n/2)/Gamma[n/2 + 1] R^n] in Mathematica. In our case, # (first argument) is n and #2 (second argument) is R. This leaves us with N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &, which can be golfed as follows:

N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &
Pi^(.5#)/Gamma[.5# + 1] #2^# &    (* replace exact with approximate numbers*)
Pi^(.5#)/(.5#)! #2^# &            (* n! == Gamma[n + 1] *)
Pi^(a=.5#)/a! #2^# &              (* replace repeated .5# *)
Pi^(a=.5#)/a!#2^#&                (* remove whitespace *)

and thus, our original program.


Generate any random integer Your program/function should

output exactly one integer
output any integer with positive probability
output an integer greater than 1.000.000 or less than -1.000.000 with at least with 50% probability.

Example outputs (all must be possible):

59875669123
12
-42
-4640055890
0
2014
12
24
-7190464664658648640055894646646586486400558904644646646586486400558904646649001

Clarifications:

A trailing line break is permitted.
Leading zeros aren't allowed.
-0 is permitted.

Shortest code wins.

Java, 133 149

void f(){String s=x(2)<1?"-":"";for(s+=x(9)+1;x(50)>0;s+=x(10));System.out.print(x(9)<1?0:s);}int x(int i){return new java.util.Random().nextInt(i);}

Example outputs

-8288612864831065123773
0
660850844164689214
-92190983694570102879284616600593698307556468079819964903404819
3264

Ungolfed

void f() {
    String s = x(2)<1 ? "-" : "";       // start with optional negative sign
    s+=x(9)+1;                          // add a random non-zero digit
    for(; x(50)>0; )                    // with a 98% probability...
        s+=x(10)                        // append a random digit
    System.out.print(x(9)<1 ? 0 : s);   // 10% chance of printing 0 instead
}

int x(int i) {
    return new java.util.Random().nextInt(i);
}

Old answer (before rule change)

void f(){if(Math.random()<.5)System.out.print('-');do System.out.print(new java.util.Random().nextInt(10));while(Math.random()>.02);}


Natural Pi #2 - River Goal

Given an string with a train of hashes, calculate its total length and divide by the distance from start to finish.

Simulation

What are we simulating? According to this paper, the ratio of the length of a river to the distance between start and end is approximately Pi! (This may have been disproved empirically, but I could find the data and for this challenge we'll assume it is true).

How are we simulating this?

Take a string input of whitespace and hashes
Each hash will have two others adjacent to it

With the exception of the first and last hash which will have only 1

Each character lies on a lattice point (x, y)
x is the character's index in its line

eg c is the 4th character in 0123c567

y is the character's line number

eg c is on the 3rd line:

      0line
      1line
      2line
      3c...

Sum the distances between adjacent hashes, call it S
Take the distance between the first and last hashes, call it D
Return S/D

Specification

Input

Flexible, take input in any of the standard ways (eg function parameter,STDIN) and in any standard format (eg String, Binary)

Output

Flexible, give output in any of the standard ways (eg return, print)
White space, trailing and leading white space is acceptable
Accuracy, please provide at least 4 decimal places of accuracy (ie 3.1416)

Scoring

Shortest code wins!

Test Cases

These are my approximations of the rivers. My approximations might be poor or these my be poor sample of the river population. Also, I did this calculations by hand; I could have miss calculated.

Yellow River

        ### ####
       #   #    #
       #       #          #
       #       #         #
       #       #        #
      #         #      #
##   #          # #####
  ##  #          #
    ##

1.6519

Nile River

         #
         #
          #
           #
           #
          #
         #
        #
        #  #
        # # #
         #  #
            #
          ##
         #
         #
        #
        #
       #
       #
       #
       #
   #  #
  # ##
  #
  #
   #
    #
     #
     #
      #
     #
    #
     #
      #

1.5498

Mississippi River

 ###
#   #
     #
     #
    #
   #
  #
  #
  #
   #
    #
     #
      #
       #
        #
        #
        #
         #
          #
           #
          #
       ###
      #
       #
      #
     #
    #
    #
    #
    #
     #
      ##
        #
        #
         ##
           ##
             ##
               #
              #
             #
            #
           #
          #
         #
        #
        #
        #
        #
        #
       #
      #
     #
      #
       #
        ####
            #
             #

1.5257

TL;DR

These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't waste ammo! There are nine challenges total.

MATL, 48 44 42 37 33 bytes

Quite a few bytes saved thanks to rahnema1's idea (Octave answer) of collapsing two convolutions into one

t5BQ4B&vX^Z+*ssGt3Y6Z+1=*&fdwdYy/

This takes the input as a binary matrix, with ; as row separator. 1 corresponds to hash and 0 to space.

Try it online! Or verify all test cases.

Here's a format converter that takes inputs as 2D char arrays (again, with ; as separator) and produces string representations of the corresponding binary matrices.

Explanation

This was fun! The code uses three two 2D-convolutions, each for a different purpose:

To detect vertical and horizontal neighbours, which contribute a distance of 1, the required mask would be

0 1 0
1 0 1
0 1 0

But we only want each pair of neighbours to be detected once. So we take half the mask (and the last row of zeros can be removed):

0 1 0
1 0 0

Similarly, to detect diagonal neighbours, which contribute a distance of sqrt(2), the mask would be

1 0 1
0 0 0
1 0 1

but by the same reasoning as above it becomes

1 0 1
0 0 0

If this mask is multiplied by sqrt(2) and added to the first, the two convolutions can be replaced by one convolution with the combined mask

sqrt(2) 1  sqrt(2)
1       0        0

Start and end points are, by definition, the points with only one neighbour. To detect them we convolve with

1 1 1
1 0 1
1 1 1

and see which points give 1 as result.

To produce the combined mask of item 1 it's shorter to generate its square and then take the square root. The mask in item 2 is a predefined literal.

t     % Take input matrix implicitly. Duplicate
5B    % 5 in binary: [1 0 1]
Q     % Add 1; [2 1 2]
4B    % 4 in binary: [1 0 0]
&v    % Concatenate vertically
X^    % Square root of each entry
Z+    % 2D convolution, maintaining size
*     % Multiply, to only keep results corresponding to 1 in the input
ss    % Sum of all matrix entries. This gives total distance
Gt    % Push input again. Duplicate
3Y6   % Predefined literal. This gives third mask
Z+    % 2D convolution, maintaining size
1=    % Values different than 1 are set to 0
*     % Multiply, to only keep results corresponding to 1 in the input
&f    % Push array of row indices and array of column indices of nonzeros
d     % Difference. This is the horizontal difference between start and end
wd    % Swap, difference. This is the vertical difference between start and end
Yy    % Hypothenuse. This gives total distance in straight line
/     % Divide. Display implicitly


Is there a smaller tautogram checker? I got into code-golfing recently and tried to write the smallest tautogram checker.
A tautogram is a sentence in which all words start with the same letter, for example: Flowers flourish from France.
Given a sentence as input, determine whether it is a tautogram.
Test Cases
Flowers flourish from France
    True

This is not a Tautogram
    False

I came up with this python code (because it is my main language):
print(True if len(list(set([x.upper()[0] for x in __import__('sys').argv[1:]]))) == 1 else False)

Usage:
python3 tautogram.py Flowers flourish from France
# True
python3 tautogram.py This is not a Tautogram
# False

The sentence may contain commas and periods, but no other special characters, only upper and lower case letters and spaces.
Its size is 98 bytes. Is there a smaller solution in any language?

05AB1E, 5 bytes

l#€нË

Try it online!

l      # Lowercase input.
 #     # Split on spaces.
  €н   # a[0] of each.
    Ë  # All equal?

Did this on mobile excuse the no explanation.


Alternatively shift columns and rows of a 2D array Objective
Given a 2D array of any size, write a program or function to shift alternatively the columns and rows
Example
a b c d e
f g h i j
k l m n o

All elements in the first column shift down one row, the second column shift up one row, the third shift down one row and so on, wrapping when they reach the edge.
k g m i o
a l c n e
f b h d j

All elements in the first row shift to the right, the second to to the left, the third to the right etc., wrapping when they reach the edge.
o k g m i
l c n e a
j f b h d

I will follow the tradition of selecting the shortest working code as the best answer

MATL, 13 bytes
,!tZy:oEq2&YS

Try it online!
Explanation
,        % Do twice
  !      %   Transpose. Takes input implicitly the first time
  t      %   Duplicate
  Zy     %   Size. Gives a vector with numbers of rows and of columns
  :      %   Range from 1 to the first entry of the vector (number of rows)
  o      %   Parity: gives 0 or 1 for eacn entry
  Eq     %   Times 2, minus 1: transforms 0 into -1
  2      %   Push 2
  &YS    %   Circularly shift along the second dimension. This shifts the
         %   first row by 1 (that is, to the right), the second by -1 (to
         %   the left), etc.
         % End (implicit). Display (implicit)


A loose spellchecker John Doe used to be one of the fastest QWERTY keyboard typists in the world, but a recent head injury caused by a stampeding herd of downgoats has critically hampered his ability to type accurately. In a desperate effort to retain his reputation as a typing prodigy, he has tasked us with the creation of a spellchecker - well, sort of. This spellchecker's rigged so that John Doe can worry less about accuracy and more about speed.
Challenge
Here's the keyboard you'll be using. NOTE: non-spacebar keys are separated by 2 spaces, with the unshifted key followed by the shifted key.
`~   1!  2@  3#  4$  5%  6^  7&  8*  9(  0)  -_  =+
Tab  qQ  wW  eE  rR  tT  yY  uU  iI  oO  pP  [{  ]}  \|
     aA  sS  dD  fF  gG  hH  jJ  kK  lL  ;:  '"  enter
     zZ  xX  cC  vV  bB  nN  mM  ,<  .>  /?
             [    SPACEBAR    ]

Notice how I have arranged the keys to line up properly. This is crucial for this challenge to work.
Write a full program/function that, given 2 strings of equal length containing only characters from the above keyboard, outputs a truthy/falsy value according to the following:

If all characters' keys are at most 1 away (horizontally, vertically, or diagonally) from the characters' keys at the same index in string 2, then output truthily.

Example using a: Any characters in aAqQsSzZwWxX or \t (tab key) would return truthily.

Special cases: \n (enter key) would return truthily for any character in [{]}\|'" or \n. Spaces (spacebar key) would return truthily for any character in xXcCvVbBnNmM,< or spaces.

Otherwise, output falsily.
Note: Tabs and newlines will be actual representations instead of their escaped equivalents (\t and \n).

This is code-golf; shortest code wins.
Example test cases
String1     String2        Output
---------------------------------
asdf        QWeR        => true
cat         gsl         => false
12345       qWeRty      => true
John Doe    Jonh Deo    => false

JavaScript (ES6), 287 bytes

(a,b)=>[...a].map((l,i)=>{p=k[g="indexOf"](l);q=k[g](o=b[i]);r=r?l==s|o==s?~m[g](l)&&~m[g](o):(x=(p%28/2|0)-(q%28/2|0))<2&x>-2&(y=(p/28|0)-(q/28|0))<2&y>-2:0},r=k=`\`~1!2@3#4$5%6^7&8*9(0)-_=+  \t qQwWeErRtTyYuUiIoOpP[{]}\\|  aAsSdDfFgGhHjJkKlL;:'"
     zZ${m="xXcCvVbBnNmM,<"}.>/?`,m+=s=" ")|r

Explanation

Returns 1 for true and 0 for false.

Note that the \t should be a literal tab character.

(a,b)=>
  [...a].map((l,i)=>{               // for each character l at index i in word A
      p=k[g="indexOf"](l);          // p = index of l in k
      q=k[g](o=b[i]);               // o = letter in word B, q = index of o in k
      r=r?                          // if r
        l==s|o==s?                  // if l or o is a space
          ~m[g](l)&&~m[g](o)        // check the space-matching characters for l and o
        :
          (x=(p%28/2|0)-(q%28/2|0)) // X distance between letters A and B
            <2&x>-2&                // if distance is 2 or greater, r = 0
          (y=(p/28|0)-(q/28|0))     // Y distance between letters A and B
            <2&y>-2                 // if distance is 2 or greater, r = 0
      :0                            // do nothing if r == 0
    },
    r=                              // r = result

    // Keyboard string, each row is 28 characters long, using spaces as padding
    k=`\`~1!2@3#4$5%6^7&8*9(0)-_=+  \t qQwWeErRtTyYuUiIoOpP[{]}\\|  aAsSdDfFgGhHjJkKlL;:'"
     zZ${m="xXcCvVbBnNmM,<"}.>/?`,

    m+=                             // m = list of characters that are adjacent to space
    s=" "                           // add space to the list, s = space character
  )
  |r                                // return r

Test

var solution = (a,b)=>[...a].map((l,i)=>{p=k[g="indexOf"](l);q=k[g](o=b[i]);r=r?l==s|o==s?~m[g](l)&&~m[g](o):(x=(p%28/2|0)-(q%28/2|0))<2&x>-2&(y=(p/28|0)-(q/28|0))<2&y>-2:0},r=k=`\`~1!2@3#4$5%6^7&8*9(0)-_=+  \t qQwWeErRtTyYuUiIoOpP[{]}\\|  aAsSdDfFgGhHjJkKlL;:'"
     zZ${m="xXcCvVbBnNmM,<"}.>/?`,m+=s=" ")|r
A = <input type="text" id="A" value="John Doe" />

B = <input type="text" id="B" value="Jonh Deo" />

<button onclick="result.textContent=solution(A.value,B.value)">Go</button>


Traverse all numbers with only one bit flip per step You can count 0, 1, 2, 3, 4.
But to get from 3 to 4 you have to change 3 bits at once.
Given a number of bits, how can you go through all numbers once,
but change at each step only 1! bit.

Here is an example for 3 bits:

000 100 110 010 011 111 101 001

so the output is:

0 1 3 2 6 7 5 4

Rules:

given a number of bits n, return a list of 2^n unique numbers
between to consecutive numbers only one bit is different
the shorter the code the better

Python 3:

for i in range(2**n):i^i//2

(Doh. Overlooked that this solutions is already known. Would delete it if stackexchange allowed it)


How many Latin Squares? A Latin Square is a square of size n × n containing numbers 1 to n inclusive. Each number occurs once in each row and column.

An example of a 3 × 3 Latin Square is:

[[1, 2, 3],
 [3, 1, 2],
 [2, 3, 1]]

Another is:

[[3, 1, 2],
 [2, 3, 1],
 [1, 2, 3]]

Given an integer input n where n > 0, determine how many Latin Squares there are with a size n  × n, where the possible values are anything from 1 to n inclusive.

Examples:

1 -> 1
2 -> 2
3 -> 12
4 -> 576
5 -> 161280
6 -> 812851200
7 -> 61479419904000
11 -> 776966836171770144107444346734230682311065600000

This is OEIS sequence A002860. It has a Wikipedia article here.

Answers are only required to support inputs up to 6, due to anything above that being greater than 232. However, while this is not strictly enforceable, your algorithm must work for all inputs.

Jelly, 8 bytes

Œ!ṗµfZ€L

Brute force solution. Inputs 5 and higher will time out on TIO.

Try it online!

How it works

Œ!ṗµfZ€L  Main link. Argument: n

Œ!        Generate all permutations of R := [1, ..., n].
  ṗ       Take the n-th Cartesian power, yielding the array A of all n×n matrices
          whose rows are permutations of R.
   µ      New chain. Argument: A
     Z€   Zip each; transpose each matrix in A, yielding the array B of all n×n
          matrices whose columns are permutations of R.
    f     Filter; keep only matrices that appear in A and B.
       L  Compute the length, counting the kept matrices.


Write a Sine-Deriving Machine The Challenge

Your challenge is to write a program that evaluates the following function:

f(x, t) = d^x / dt^x (sin t)

That is, the x-th derivative of sin t. In case you aren't familiar with calculus, here is a table of derivatives for the sine function:

...

f(-1, t) = -cos t

f(0, t) = sin t

f(1, t) = cos t

f(2, t)= -sin  t

...

The sequence repeats these 4 functions.

The Inputs

Your program should take in an integer to be used as the x value in the function, and a float to be used at the t value in the function.

Your program may use radians or degrees for the sine function.

The Output

Your program should output the value of f(x, t) given the integer x and float t.

Scoring

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

Python, 42 bytes

from math import*
lambda x,n:sin(x+pi/2*n)

Uses the fact that differentiating shifts the function by pi/2 left.