Three Indistinguishable Dice Given three dice rolls (integer values from 1-6) in sorted order (so as to be indistinguishable), convert them to the sum of two fair dice with an identical distribution.

The answer for three to one is summing them all, modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die).

It's easy to do this for three-to-one, by summing them all modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die).  Your challenge is to do the same for three-to-two.

Inspired by standupmath's The Three Indistinguishable Dice Puzzle. A follow-up "solution" video was also posted, but arguing about "elegance" of one way or another is a bit subjective. Counting characters isn't. :D

Instructions

Write a program or function that accepts three sorted integers/digits, 1-6, and outputs or returns a single integer, 2-12, such that, for the 216 possible inputs, the outputs are distributed as:

 222222
 333333333333
 444444444444444444
 555555555555555555555555
 666666666666666666666666666666
 777777777777777777777777777777777777
 888888888888888888888888888888
 999999999999999999999999
 AAAAAAAAAAAAAAAAAA
 BBBBBBBBBBBB
 CCCCCC

(I've used hex to keep to single characters; decimal output is fine)

Because the dice are indistinguishable, there is no intrinsic order to them, hence the sorted input. You cannot simply "drop the third" because that would be ambiguous.

Details

Score is the length of the program in bytes
The program can be a function that's called somehow, or executable script that reads from stdin, or whatever's convienent.
No "rerolling" by getting entropy from another source

Example (and test)

Rather than doing any sort of probabilistic testing, it's easy enough to rip through the 216 (6³) cases of all the three dice and assert that your function returns each value as many times as it should. It will be called with identical parameters (e.g. the cases 1, 2, 3 and 3, 2, 1, ... are presumed indistinguishable and are (arbitrarily) converted to 1, 2, 3).

An example answer (extremely brute-force and inefficient) and test suite is provided below in Python. Hopefully the test bits are clear enough to port to your language of choice, though doing stdin/stdout would be a bit different. The testing code is just for testing and not scored (though if you want to provide it for other users of your language or I/O method, that might be useful).

# 6x6 lists of numbers with digits sorted
LUT = [
    [[124], [133, 166], [346], [223, 355], [256], [115, 445]],
    [[233, 266], [125], [224, 455], [134], [116, 446], [356]],
    [[126], [111, 333, 555, 225], [234], [144, 366], [456], [135]],
    [[112, 244], [235], [334, 466], [145], [226, 556], [136]],
    [[146], [122, 155], [236], [113, 344], [245], [335, 566]],
    [[246], [123], [114, 336], [345], [222, 444, 666, 255], [156]],
]

def three2two(rolls):
    look_for = int('{}{}{}'.format(*sorted(rolls)))
    for i in range(6):
        for j in range(6):
            if look_for in LUT[i][j]:
                return i + j + 2

# fair distribution of the sum of two dice multiplied by 6 (because each should be hit 6x)
expected_counts = {
    2: 6,   12: 6,
    3: 12,  11: 12,
    4: 18,  10: 18,
    5: 24,   9: 24,
    6: 30,   8: 30,
    7: 36,
}

d = [1, 2, 3, 4, 5, 6]
for i in d:
    for j in d:
        for k in d:
            ijk = sorted([i, j, k])
            result = three2two(ijk)
            expected_counts[result] -= 1

for key in expected_counts:
    assert expected_counts[key] == 0


Numbers divisible by the sum and product of their digits Take a positive integer X. This number is part of the sequence we are interested in if the sum of all digits of X is a divisor of X, and if the product of all digits of X is a divisor of X.
For example, 135 is such a number because 1 + 3 + 5 = 9 which divides 135 = 9 * 15 and 1 * 3 * 5 = 15 which also divides 135.
This is sequence A038186 in the OEIS.
Your task: given an integer N, output the Nth positive integer with such properties.
Inputs and outputs

Numbers may be 0-indexed or 1-indexed; please indicate which one your answer use.

The input may be taken through STDIN, as a function argument, or anything similar.

The output may be printed to STDOUT, returned from a function, or anything similar.

Test cases
The test cases below are 1-indexed.
Input        Output

1            1
5            5
10           12
20           312
42           6912
50           11313

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

05AB1E, 13 12 bytes

Thanks to Emigna for saving a byte!

µNNSONSP‚ÖP½

Explanation:

µ          ½   # Get the nth number for which the following holds:
  NSO          #   The sum of digits of the current number
     NSP       #   And the products of digits of the current number
 N      ‚ÖP    #   Divides the current number
               # If the nth number has been reached, quit and implicitly print N

Uses the CP-1252 encoding. Try it online!


Solve the Secretary Problem The Secretary Problem is a famous problem described as thus:

You need a new secretary
You have N applicants that you can interview one at a time
You are able to score each applicant after the interview.  Your scoring system will never give two applicants the same score
After you interview an applicant, you must give an immediate "yes" or "no"
You want the applicant with the highest score

The solution is to interview the first floor(N/e) applicants, and then accept the first applicant that has a higher score than all of the previous applicants.   If none of the applicants are higher, then return the last applicant.  Interestingly enough, this gives the top applicant 1/e percent of the time.  e refers to Euler's number.  To get the value of e, you can use a builtin, log, or hardcode it to at least 5 decimal points.
Input:
An non-empty array of unique non-negative integers no more than 2^31-1.
Output:
An integer representing the chosen candidate.  To be clear the algorithm is:

Find the maximum element in the first floor(N/e) elements of the array.
Iterate through the remaining elements, and return the first element that is higher than the maximum found on step 1.
If none of the elements are higher, than return the last element.

For example, say your array was [2,7,4,3,9,20], so N = 6 and floor(N/e) = 2.  The first 2 elements of the array is [2,7].  The max of [2,7] is 7.  The remaining elements are [4,3,9,20].  The first element that is greater than 7 is 9, so we return 9.
Test Cases:
[0]         => 0
[100]       => 100
[100, 45]   => 100
[0, 1]      => 0
[45, 100]   => 45
[1, 4, 5]   => 4
[1, 5, 4]   => 5
[5, 4, 1]   => 1
[5, 1, 4]   => 4
[4, 1, 5]   => 5
[56, 7, 37, 73, 90, 59, 65, 61, 29, 16, 47, 77, 60, 8, 1, 76, 36, 68, 34, 17, 23, 26, 12, 82, 52, 88, 45, 89, 94, 81, 3, 24, 43, 55, 38, 33, 15, 92, 79, 87, 14, 75, 41, 98, 31, 58, 53, 72, 39, 30, 2, 0, 49, 99, 28, 50, 80, 91, 83, 27, 64, 71, 93, 95, 11, 21, 6, 66, 51, 85, 48, 62, 22, 74, 69, 63, 86, 57, 97, 32, 84, 4, 18, 46, 20, 42, 25, 35, 9, 10, 19, 40, 54, 67, 70, 5, 44, 13, 78, 96]
=> 98
[10, 68, 52, 48, 81, 39, 85, 54, 3, 21, 31, 59, 28, 64, 42, 90, 79, 12, 63, 41, 58, 57, 13, 43, 74, 76, 94, 51, 99, 67, 49, 14, 6, 96, 18, 17, 32, 73, 56, 7, 16, 60, 61, 26, 86, 72, 20, 62, 4, 83, 15, 55, 70, 29, 23, 35, 77, 98, 92, 22, 38, 5, 50, 82, 1, 84, 93, 97, 65, 37, 45, 71, 25, 11, 19, 75, 78, 44, 46, 2, 53, 36, 0, 47, 88, 24, 80, 66, 87, 40, 69, 27, 9, 8, 91, 89, 34, 33, 95, 30]
=> 30

Your solution must be O(n), where n is the length of the array.  If your language has a builtin that finds the maximum of an array, you can assume that the function takes O(n) (and hopefully it does).
Standard loopholes apply, and this is a code-golf, so the make the shortest answer in your favorite language!

Jelly, 13 bytes

L:Øe³ḣȯ-Ṁ<i1ị

Definitely an O(n) algorithm, hopefully an O(n) implementation. Try it online!

How it works

L:Øe³ḣȯ-Ṁ<i1ị  Main link. Argument: A (list of scores)

L              Get the length of A.
 :Øe           Divide the length by e, flooring the result.
    ³ḣ         Retrieve the that many scores from the beginning of A.
      ȯ-       Logical OR; replace an empty list with -1.
        Ṁ      Compute the maximum of those scores.
         <     Compare each score in A with that maximum.
          i1   Find the first index of 1 (0 if not found).
            ị  Retrieve the element of A at that index (the last one if 0).


Piet, 612 codels
Takes n from standard input. Outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Check out this NPiet trace, which shows the program calculating the solution for an input value of 99.
I'm not sure whether I'd ever heard of Pell's equation before this challenge, so I got all of the following from Wikipedia; specifically, these sections of three articles:

Pell's equation § Fundamental solution via continued fractions
Methods of computing square roots § Continued fraction expansion
Continued fraction § Infinite continued fractions and convergents

Basically, what we do is this:

Get \$n\$ from standard input.
Find \$\lfloor\sqrt n\rfloor\$ by incrementing a counter until its square exceeds \$n\$, then decrement it once. (This is the first loop you can see in the trace, at top left.)
Set up some variables for calculating \$x\$ and \$y\$ from the continued fraction of \$\sqrt n\$.
Check whether \$x\$ and \$y\$ fit Pell's equation yet. If they do, output the values (this is the downwards branch about 2/3 of the way across) and then exit (by running into the red block at far left).
If not, iteratively update the variables and go back to step 4. (This is the wide loop out to the right, back across the bottom, and rejoining not quite halfway across.)

I frankly have no idea whether or not a brute-force approach would be shorter, and I'm not about to try it! Okay, so I tried it.


Add an array with itself Your challenge today is to take an array, split it into chunks, and add those chunks.

Here's how this works: Your program or function will be given an array of integers a and a chunk size L. The array should be split into arrays of size L, if the array length is not divisible by L then the array should have 0's appended to it so that it is evenly divisible. Once the array is chunked, all chunks are to be added together element-wise. The resulting array is then output.

You can assume L is greater than 0, and that a is nonempty. You cannot make the assumption that a's contents are positive.

Here's an example:

[1,2,3,4,5,6,7,8], 3 => [1,2,3]+[4,5,6]+[7,8,0] =>  [1+4+7,2+5+8,3+6+0] => [12,15,9]

Test cases:

Array                           Length   Output
[1]                             1        [1]
[1]                             3        [1,0,0]
[0]                             3        [0,0,0]
[1,2]                           3        [1,2,0]
[1,2]                           1        [3]
[-1,1]                          2        [-1,1]
[-7,4,-12,1,5,-3,12,0,14,-2]    4        [12,-1,0,1]
[1,2,3,4,5,6,7,8,9]             3        [12,15,18]

This is code-golf, fewest bytes wins!

Python 3, 67 65 42 bytes

Uses the fact that the sum of an empty array is 0

lambda x,y:[sum(x[i::y])for i in range(y)]

Try it online!


Lolololololololololololol Let us take a break from the brain-wrecking questions and answer some of the simpler ones
You have recently read something extremely funny, and want to express your laughter to the world! But how can you?
Task
You have to display the string:
Lolololololololololololololololololololololololololololololololololololololololololololololololololololololololol...
...to STDOUT.
The string should be of infinite length, or will constantly be printed until the end of time.
It is just as simple!
But remember, this is code-golf, so the source code must be as short as possible!
Note: Some languages may throw errors since excecution  can be timed out, or for other reasons. That is okay! It can be weird when you laugh forever!

Good luck!

Python 3, 32 bytes

x='L'
while[print(end=x)]:x='ol'

Try it online!
In Python 3, the print function by default has end='\n' to put a newline after what you print. Rather than changing that to the empty string, we stick the value x that we want to be printed there, and don't provide any value to be printed.
We stick the printing in the while loop condition. Since print returns None by default but this is Falsey and won't continue the loop, we wrap it in a singleton list to make it Truthy.
I had tried to stick an infinite iterator into print like print(*iter(...),sep=''), but it looks like Python will consume the whole iterable first and never actually print.


Score Tarzan's Olympic Vine-Swinging Routine Olympic vine-swingers perform their routines in standard trees.  In particular, Standard Tree n has vertices for 0 up through n-1 and edges linking each nonzero vertex a to the vertex n % a below it.  So, for example, Standard Tree 5 looks like this:

3
|
2   4
 \ /
  1
  |
  0

because the remainder when 5 is divided by 3 is 2, the remainder when 5 is divided by 2 or by 4 is 1, and the remainder when 5 is divided by 1 is 0.

This year, Tarzan will be defending his gold with new routines, each of which begins at vertex n - 1, swings to vertex n - 2, continues to vertex n - 3, etc., until finally he dismounts to vertex 0.

The score for a routine is the sum of the scores for each swing (including the dismount), and the score for a swing is the distance within the tree between its start and end points.  Thus, Tarzan's routine on Standard Tree 5 has a score of 6:

a swing from 4 to 3 scores three points (down, up, up),
a swing from 3 to 2 scores one point (down),
a swing from 2 to 1 scores one point (down), and
a dismount from 1 to 0 scores one point (down).

Write a program or function that, given a positive integer n, computes the score of Tarzan's routine on Standard Tree n.  Sample inputs and outputs:

 1 ->  0
 2 ->  1
 3 ->  2
 4 ->  6
 5 ->  6
 6 -> 12
 7 -> 12
 8 -> 18
 9 -> 22
10 -> 32
11 -> 24
12 -> 34
13 -> 34
14 -> 36
15 -> 44
16 -> 58
17 -> 50
18 -> 64
19 -> 60
20 -> 66
21 -> 78
22 -> 88
23 -> 68
24 -> 82

Rules and code scoring are as usual for code-golf.

C, 98 97 bytes

F(i){int c[i],t=i-2,n=0,p;for(;++n<i;)for(p=c[n]=n;p=i%p;c[p]=n)t+=c[p]<n-1;return i>2?t*2:i-1;}

This calculates the distance between each pair of points with the following formula:

Add the distance from the root to node A
Add the distance from the root to node B
Subtract 2* the length of the common root of A and B

This has the advantage that when applied to all pairs, it's the same as:

Add 2* the distance from the root to each node
Subtract 2* the length of the common root of each node pair
Subtract the distance from the root to the first node
Subtract the distance from the root to the last node

To make the logic simpler, we assume we're going from node 0 to node n-1, rather than n-1 to 0 as the question states. The distance from the root node to node 0 is obviously 0 (they're the same). And we can see that for (most) trees, the distance from the last node to the root is 2:

                    n+1 % n = 1  for all n > 1
and:                  n % 1 = 0  for all n >= 0
therefore:  n % (n % (n-1)) = 0  for all n > 2

This means we have some special cases (n<2) but we can account for those easily enough.

Breakdown:

F(i){                               // Types default to int
    int c[i],                       // Buffer for storing paths
        t=i-2,                      // Running total score
        n=0,                        // Loop index
        p;                          // Inner loop variable
    for(;++n<i;)                    // Loop through all node pairs (n-1, n)
        for(p=c[n]=n;p=i%p;c[p]=n)  //  Recurse from current node (n) to root
            t+=c[p]<n-1;            //   Increase total unless this is a common
                                    //   node with the previous path
    return i>2?   :i-1;             // Account for special cases at 1 and 2
               t*2                  // For non-special cases, multiply total by 2
}

Thanks @feersum for 1 byte saved

Bonus: Trees!

I wrote a quick-and-dirty program to see what these trees look like. Here's some of the results:

6:

5 4
| |
1 2 3
 \|/
  0

8:

  5
  |
7 3   6
|  \ /
1   2   4
'--\|/--'
    0

13:

   08
    |
11 05   10 09 07
 |   \ /    |  |
02   03    04 06 12
 '-----\  /---'--'
        01
         |
        00

19:

   12
    |
   07   14
     \ /
     05    15 11
       \  /    |
17      04    08 16 13 10
 |       '-\  /--'   |  |
02          03      06 09 18
 '---------\ |/-----'--'--'
            01
             |
            00

49:

                         31
                          |
           30            18   36
            |              \ /
           19   38 27      13    39 29    32
             \ /    |        \  /    |     |
   26        11    22 44      10    20 40 17   34
    |         '-\  /--'        '-\  /--'    \ /
47 23   46       05               09        15    45 43 41 37 33 25    35 28
 |   \ /          '--------------\ |/-------'-----'   |  |  |  |  |     |  |
02   03                           04                 06 08 12 16 24 48 14 21 42
 '----'--------------------------\ |/----------------'--'--'--'--'--'    \ |/
                                  01                                      07
                                   '-----------------\  /-----------------'
                                                      00


Sylvester's sequence Sylvester's sequence, OEIS A000058, is an integer sequence defined as follows:
Each member is the product of all previous members plus one.  The first member of the sequence is 2.
Task
Create the smallest program possible that takes an n and calculates the nth term of Sylvester's Sequence.  Standard input, output and loopholes apply.
Since the result grows very quickly you are not expected to take any term of which the result would cause an overflow in your chosen language.
Test Cases
You may use either zero or one indexing. (Here I use zero indexing)
>>0
2
>>1
3
>>2
7
>>3
43
>>4
1807

Brain-Flak, 76 68 58 52 46 bytes

<>(()())<>{({}[()])<>({({}[()])({})}{}())<>}<>

Try it online!

Uses this relationship instead:

which is derived from this relationship modified from that provided in the sequence:

a(n+1) = a(n) * (a(n) - 1) + 1.

Explanation

For a documentation of what each command does, please visit the GitHub page.

There are two stacks in Brain-Flak, which I shall name as Stack 1 and Stack 2 respectively.

The input is stored in Stack 1.

<>(()())<>             Store 2 in Stack 2.

{                      while(Stack_1 != 0){
  ({}[()])                 Stack_1 <- Stack_1 - 1;
  <>                       Switch stack.
  ({({}[()])({})}{}())     Generate the next number in Stack 2.
  <>                       Switch back to Stack 1.
}

<>                     Switch to Stack 2, implicitly print.

For the generation algorithm:

({({}[()])({})}{}())      Top <- (Top + Top + (Top-1) + (Top-1) + ... + 0) + 1

(                  )      Push the sum of the numbers evaluated in the process:

 {            }               while(Top != 0){
  ({}[()])                        Pop Top, push Top-1    (added to sum)
          ({})                    Pop again, push again  (added to sum)
                              }

               {}             Top of stack is now zero, pop it.
                 ()           Evaluates to 1 (added to sum).

Alternative 46-byte version

This uses only one stack.

({}<(()())>){({}<({({}[()])({})}{}())>[()])}{}

Try it online!


Convert to ASCII Agrippa Numbers Challenge

Given a natural number, output it in the ASCII form of Agrippa's number system.

Description

I like odd alphabets and numeral systems. My favorite numeral system is one given by Heinrich Cornelius Agrippa. It gives a succinct way to write numbers in the range [0,9999], where single digits are written as follows:

Larger numbers less than 10^4 are a combination of single digits, but rotated/horizontally-mirrored on a single central bar as follows:

[0° mirrored, 10's  ] | [0°,            1's  ]
[180°,        1000's] | [180° mirrored, 100's]

Here are a few examples:

The ASCII equivalents are:

Ones:
  0  1  2  3  4  5  6  7  8  9
  |  |- |_ |\ |/ |~ || |^ |v |]
  |  |  |  |  |  |  |  |  |  |

Tens:
  0  1  2  3  4  5  6  7  8  9
  | -| _| /| \| ~| || ^| v| [|
  |  |  |  |  |  |  |  |  |  |

Hundreds:
  0  1  2  3  4  5  6  7  8  9
  |  |  |  |  |  |  |  |  |  |
  |  |_ |- |/ |\ |~ || |v |^ |]

Thousands:
  0  1  2  3  4  5  6  7  8  9
  |  |  |  |  |  |  |  |  |  |
  | _| -| \| /| ~| || v| ^| [|

 1510:  1511:  1471:  1486:  3421:
 -|     -|-    ^|-    v||    _|-
 _|~    _|~    _|\    -|\    \|\

Numbers larger than 9999 are broken up into sections of 4 digits (with leading zeros added to get a multiple of four) and each is converted. For example:

314159: (0031 4159)
         /|-  ~|]
          |   /|_

Rules

Your answer may be a function or full program
The input is a positive integer
Entries must support inputs over 10^8
Each four digit section takes exactly six characters
Sections of four are separated by a single space
Trailing newline is optional
Up to two trailing spaces per line are allowed
I will not accept my own answer
Score is in bytes, lowest score wins!

Haskell, 310 bytes

Defining reverse (as I did: r) is one byte shorter than importing Data.List and using it just once
Defining z=0:z and (!)=(!!).(++z) is the shortest way yet that I've found to return 0 for out of bounds
I've checked and quickChecked the take4s function, but it still feels like magic to me

Here's the code:

l=lines"    \n--__\n__--\n\\//\\\n/\\\\/\n~~~~\n||||\n^^vv\nvv^^\n][]["
d x|x<1=[]|1<2=mod x 10:d(div x 10)
(&)=(!!)
z=(0::Int):z
(!)=(&).(++z)
t a=[[a!q|q<-[p..p+3]]|p<-[0,4..length a-1]]
g[c,d,b,a]=[[l&b&1,'|',l&a&0,' '],[l&d&3,'|',l&c&2,' ']]
r[]=[]
r(x:y)=r y++[x]
f=unlines.foldl1(zipWith(++)).map g.r.t.d

Less golfed:

import Data.List (reverse)

dict = lines "    \n--__\n__--\n\\//\\\n/\\\\/\n~~~~\n||||\n^^vv\nvv^^\n][]["

-- Note that (digits x) returns the digits of x in little-endian order
digits x  | x < 1     = []
          | otherwise = mod x 10 : digits (div x 10)

-- Note: zeros needs the type signature, because otherwise it won't match [Int] (inferred from (!!))
zeros = (0::Int) : zeros

-- list ! position gives the element at the position, or 0 for out of bounds
(!) = (!!) . (++zeros)

-- This partitions the digits into groups of four, padded right
take4s a = [[a!q | q <-[p..p+3]] | p <- [0,4..length a - 1]]

convertOne[c,d,b,a] = [[dict !! b !! 1, '|', dict !! a !! 0, ' '], [dict !! d !! 3, '|', dict !! c !! 2, ' ']]

f = unlines . foldl1(zipWith (++)) . map convertOne . reverse . take4s . digits

Tests (escape characters removed):

mapM_ print $ lines $ f 1510
-|
_|~

mapM_ print $ lines $ f 1511
-|-
_|~

mapM_ print $ lines $ f 1471
^|-
_|\

mapM_ print $ lines $ f 1486
v||
_|\

mapM_ print $ lines $ f 3421
_|-
\|\

mapM_ print $ lines $ f 1234567891011121314
_|\ ||^ -|  -|_ -|/
 |_ /|~ ^|] _|_ _|/

mapM_ print $ lines $ f 1024628340621757567
 |_ _|v  || ^|~ ||^
 |_ /|| \|\ -|_ v|~


How likely is this mutation? In my previous bioinformatics challenge, I asked you to mutate a DNA sequence. This time, I'd like you to evaluate how likely a mutation, or a series of mutations, is.
The two types of substitutions are transitions and transversions, and due to the chemical structure of DNA bases, transitions are more likely to occur than transversions. A transition is when a base is turned into one of the same size (purine -> purine or pyrimidine -> pyrimidine), and a transversion involves two bases of different sizes (purine <-> pyrimidine). Following Kimura's model, postulated in 1980, we can define a as the probability of a transition occurring for each unit of time, and b as the probability of a transversion occurring.
See diagram below. A and G are purines, C and T are pyrimidines.

Although the exact values of a and b change from organism to organism (and even between different areas in an organism's genome), we can set a=0.25 and b=0.1 for this challenge.
Given two DNA strings of same length as input, I would like you to calculate how likely it would be for string B to be a mutated version of string A. This is code golf, so fewest bytes wins!
Test cases:
Input String A | Input string B | Output probability
tgcctatc       | tgcctata       |  0.1
aggttcctt      | gggttcctt      |  0.25
aactgg         | aaccgg         |  0.25
atgccct        | atcgcct        |  0.01
tatcactaag     | tgtcaatgag     |  0.00625
ctcctgggca     | cttttgcgca     |  0.00625
ctgtgtgct      | cagagagca      |  0.0001
atcgctttca     | ttggctttca     |  0.01
attcac         | taagcg         |  0.000001
attttcattg     | attttttacg     |  0.000625

Specifications:

The input DNA strings can be as strings of characters, binary or numerical.
We will assume that all of the mutations are independent events.
The output can be in plain notation (0.00015) or scientific (\$1.5\times10^{-4}\$).

If you have any questions or require more specifications, send them my way in the comments!

Jelly, 9 bytes
^ị“½¥¢‘İP

Try it online!
Takes input as 2376 instead of acgt respectively. The Footer does this for you
-1 byte thanks to Jonathan Allan!
How it works
^ị“½¥¢‘İP - Main link. Takes the first input on the left and the second on the right
^         - XOR the corresponding elements
  “½¥¢‘   - Yield [10, 4, 1]
 ị        - Index into this array, 1-indexed and modularly
       İ  - Take the inverse of each
        P - Take the product

Why this works

Characters
As integers
XOR
1-index into [10,4,1]
Inverse

aa
2, 2
\$0\$
\$1\$
\$1\$

cc
3, 3
\$0\$
\$1\$
\$1\$

gg
7, 7
\$0\$
\$1\$
\$1\$

tt
6, 6
\$0\$
\$1\$
\$1\$

ac
2, 3
\$1\$
\$10\$
\$0.1\$

ag
2, 7
\$5\$
\$4\$
\$0.25\$

at
2, 6
\$4\$
\$10\$
\$0.1\$

cg
3, 7
\$4\$
\$10\$
\$0.1\$

ct
3, 6
\$5\$
\$4\$
\$0.25\$

gt
7, 6
\$1\$
\$10\$
\$0.1\$


How wavy is an array? A wave of power \$k\$ is an infinite array that looks like \$1,2,\dots,k,k-1,\dots,1,\dots,k,\dots,1,\dots\$, and so on.
For example, a wave of power 3 starts with \$1,2,3,2,1,2,3,2,1,...\$, and repeats indefinitely. A wave of power 1 is an infinite array of ones. They happen to be beautifully expressed as $$w_k[t] = k - |(t - 1)\bmod(2k - 2) - k + 1|\text{, 1-indexed}$$
In this challenge, all waves are trimmed to their first \$n\$ elements, where \$n\$ is the length of the input array.
A decomposition of an array into waves is an array of coefficients of length \$n\$ such that the original array equals the sum of the waves multiplied by their corresponding coefficients. Formally, if the original array is \$A\$, the decomposition is an array \$B\$  such that for any \$i\$  (\$1 \le i \le n\$) the following equality holds:
$$A[i] = \sum_{j=1}^\infty B[j] \cdot w_j[i]\text{, 1-indexed}$$
The waviness of an array is the index of the last non-zero value in its decomposition into waves.
The task is, given a positive integer array of length \$n\$, to calculate its waviness. Note that the decomposition can still include non-integer and negative numbers.
Test cases
All test cases below are 1-indexed. Your solution may use 0-indexing instead.
[1, 1, 1] -> 1                 (decomposition: [1, 0, 0])
[1, 2, 1] -> 2                 (decomposition: [0, 1, 0])
[1, 2, 3] -> 3                 (decomposition: [0, 0, 1])
[1, 1, 2] -> 3                 (decomposition: [1, -0.5, 0.5])
[1, 3, 3, 3, 1] -> 3           (decomposition: [-1, 1, 1, 0, 0])
[1, 2, 2, 4] -> 4              (decomposition: [0, 0.5, -0.5, 1]
[4, 6, 9, 1, 4, 3, 5] -> 7     (decomposition: [2, -0.5, 5, -5, 6.5, -1, -3]
[4, 6, 9, 1, 4, 3, 5, 7] -> 8  (decomposition: [2, -0.5, 5, -5, 6.5, -1, -10.5, 7.5])

This is tagged code-golf an uncommon justification, so the shortest answer wins.

JavaScript (ES6),  172 171  169 bytes
The output is 0-indexed.

a=>a.map((_,i)=>(D=m=>+m||m.reduce((s,[v],i)=>s+(i&1?-v:v)*D(m.map(([,...r])=>r).filter(_=>i--)),0))(a.map((v,y)=>a.map((_,x)=>x-i?x-~-Math.abs(y%(2*x)-x):v)))&&(j=i))|j

Try it online!
How?
This is essentially an implementation of Cramer's rule, except that the denominator is not computed.
Given the input vector of length \$n\$, we define \$W_n\$ as the matrix holding the waves, stored column-wise.
Example:
$$W_5=\begin{pmatrix}
1&1&1&1&1\\
1&2&2&2&2\\
1&1&3&3&3\\
1&2&2&4&4\\
1&1&1&3&5\end{pmatrix}$$
We compute all values \$v_i=\det(M_i)\$ with \$0\le i<n\$, where \$M_i\$ is the matrix formed by replacing the \$i\$-th column of \$W_n\$ with the input vector.
Example:
For the 5th test case and \$i=3\$, this gives:
$$v_3=\det(M_3)=\begin{vmatrix}
1&1&1&\color{red}1&1\\
1&2&2&\color{red}3&2\\
1&1&3&\color{red}3&3\\
1&2&2&\color{red}3&4\\
1&1&1&\color{red}1&5\end{vmatrix}=0$$
We return the highest index \$j\$ such that \$v_j\neq0\$.
Commented
The helper function \$D\$ uses Laplace expansion to compute the determinant:
D = m =>                     // m[] = matrix
  +m ||                      // if the matrix is a singleton, return it
  m.reduce((s, [v], i) =>    // otherwise, for each value v at (0, i):
    s                        //   take the previous sum s
    + (i & 1 ? -v : v)       //   based on the parity of i, add either v or -v
    * D(                     //   multiplied by the result of a recursive call:
      m.map(([, ...r]) => r) //     pass m[] with the 1st column removed
      .filter(_ => i--)      //     and the i-th row removed
    ),                       //   end of recursive call
    0                        //   start with sum = 0
  )                          // end of reduce()

The matrix \$M_i\$ is computed with:
a.map((v, y) =>         // for each value v at position y in the input vector a[]:
  a.map((_, x) =>       //   for each value at position x in the input vector a[]:
    x - i ?             //     if this is not the i-th column:
      x -               //       compute the wave of power x+1 at position y:
      ~-Math.abs(       //         x - (|y mod (2*x) - x| - 1)
        y % (2 * x) - x //         (where y mod 0 is coerced to 0)
      )                 //
    :                   //     else:
      v                 //       append the value a[y] of the input vector
  )                     //   end of inner map()
)                       // end of outer map()


Abbreviate that US state! Given one of the 50 U.S. state names on the left as input, output its two-letter postal code as shown to the right:

Alabama         AL
Alaska          AK
Arizona         AZ
Arkansas        AR
California      CA
Colorado        CO
Connecticut     CT
Delaware        DE
Florida         FL
Georgia         GA
Hawaii          HI
Idaho           ID
Illinois        IL
Indiana         IN
Iowa            IA
Kansas          KS
Kentucky        KY
Louisiana       LA
Maine           ME
Maryland        MD
Massachusetts   MA
Michigan        MI
Minnesota       MN
Mississippi     MS
Missouri        MO
Montana         MT
Nebraska        NE
Nevada          NV
New Hampshire   NH
New Jersey      NJ
New Mexico      NM
New York        NY
North Carolina  NC
North Dakota    ND
Ohio            OH
Oklahoma        OK
Oregon          OR
Pennsylvania    PA
Rhode Island    RI
South Carolina  SC
South Dakota    SD
Tennessee       TN
Texas           TX
Utah            UT
Vermont         VT
Virginia        VA
Washington      WA
West Virginia   WV
Wisconsin       WI
Wyoming         WY

Rules

Input and output are both case sensitive. You many not output e.g. Al for Alabama.
You may assume the input is one of the 50 state names shown above.
You may not access the internet or use built-in state data (looking at you, Mathematica).

Separate lists of inputs and outputs can be found in this snippet (please don't run it, it's just for compressing the post):

Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming

AL
AK
AZ
AR
CA
CO
CT
DE
FL
GA
HI
ID
IL
IN
IA
KS
KY
LA
ME
MD
MA
MI
MN
MS
MO
MT
NE
NV
NH
NJ
NM
NY
NC
ND
OH
OK
OR
PA
RI
SC
SD
TN
TX
UT
VT
VA
WA
WV
WI
WY

(Non-scoring) Brownie points if you can also take District of Columbia as input and produce DC, Virgin Islands, etc etc.

Scoring

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

(Originally proposed by ETHProductions)

Javascript, 137 135 134 132 113 110 108 101 99 94 93 92 90 bytes
This is originally based on HP Williams solution, with some improvements outside the regex, and a couple of tweaks within it, plus a couple of bytes from Primo.
s=>s[0]+
  /.$/.exec(s.toUpperCase()
    .match`.* .|.*Z|...S.S?|T..|M[I-T]+|[AFINOUW][^O]V?|.*`
  )

(Linebreaks for readability only)
Commentary for the regex:
.*( .|z)|      // Two-or-three word states, plus Arizona
...s.s?|       // Mississippi, Missouri, Massachussetts, Alaska, and (non-harmfully) Kansas
M[i-t]+|       // Montana, Minnesota, Michigan
[AFINOUW][^o]v?|  // All the other first-two-letter states, avoiding Iowa/Connecticut/Louisiana, plus Nevada
T..|           // Tennessee, Texas
.+             // Everything else is first-and-last

Alternative regex's (same length):
/...(a$|z|s.s?|.* .)|M[i-t]+|T..|[AFINOUW].v?|.*/
/.*( .|z)|...s.s?|Te.|M[i-t]+|[^GHKMPVo]{2}v?|.*/
/.*( .|z)|...s.s?|M[i-t]+|[^GHKMPVo]{2}[vnx]?|.*/

History
92
s=>s[0]+
/.*( .|z)|...s.s?|T..|M[i-t]+|[AFINOUW][^o]v?|.*/
.exec(s)[0].slice(-1).toUpperCase()

94
s=>s[0]+/.*( .|z)|...s.s?|M[io]n?t?|[AFIOUWN][^o]v?|T..|.*/
.exec(s)[0].slice(-1).toUpperCase()

99
s=>s[0]+/.*( .|z|l.*k)|T..|M.ss.s?|M[io]n?t?|[AFIOUWN][^o]v?|.*/
.exec(s)[0].slice(-1).toUpperCase()

101
s=>s[0]+/.+[A-Zz]|Nev?|.*sk|M.ss.s?|M[io]n?t?|[AFIOUW][^o]|Te.|.+/
.exec(s)[0].slice(-1).toUpperCase()

108
 s=>s[0]+/MI(N|SSO|S)|[CDGHKLPV].*|.* .|.*[XZV]|.*?N[NTE]|.*(SK|D$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)

110
s=>s[0]+/MI(N|SSO|S)|[CGHKLPV].*|.* .|.*[XZV]|.*?N[NTE]|.*(SK|[ED]$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)

113
s=>s[0]+/^MI(N|SSO|S)|^[CGHKLPV].*|.*?( .|[XZV])|.*?N[NTE]|.*(SK|[ED]$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)

132
s=>(S=s.toUpperCase(),' ._SSO_^MI[NS]_^[CGHKLPV].*_.V_N[TNE]_SK_[ED]$_WA_Z_X_..'
.split`_`.some(p=>s=S.match(p)),S[0]+s[0].slice(-1))

134
s=>' ._SSO_^MI[NS]_^[CGHKLPV].*_.V_N[TNE]_SK_E$_D$_WA_Z_X_..'.split`_`
.map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s

135
s=>' ._SSO_^MI[NS]_LASK_^[CGHKLPV].*_NT_EN_[DE]$_WA_.[XVZ]_..'.split`_`
.map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s

137
s=>' ._OWA_SSO_ONT_^MI[NS]_LASK_^[CGHKLPV].*_EN_[DE]$_.[XVZ]_..'.split`_`.
map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s


Determine if a move exists in a Bejeweled/match 3 game Background
In Bejeweled and similar games, the player must swap any two adjacent gems (no diagonals) in an 8x8 grid of gems in order to match three of the same color in a row. The gems can be matched horizontally or vertically. Gameplay continues until there no move exists that can be made resulting in three in a row, at which point the game is over.
Task
The goal is to write a program that determines whether a game of Bejeweled is not over yet. In other words, it must check to see if there is a possible move that makes at least three in a row. There can be more than three gems in a row and it is still a valid move.
Input
Your program must accept via standard input an 8x8 representation of a Bejeweled grid. Each of the seven gem colors will be represented by a digit from 1 to 7. Each line will contain one row, and 8 lines, each consisting of 8 digits, will be input. See the examples. You can assume that the input will always follow this format, and will never already contain three in a row.
Output
The program must then output (to standard output) yes or no depending on whether or not at least one valid move exists that would result in three or more gems in a row. Your program must not output anything other than a single instance of either yes or no.
Rules
Your program must not use any external files or resources, command-line arguments, or require a certain file name. The program with the least number of bytes in its source code wins.
Examples
Input:
12314131
13224145
54762673
61716653
61341144
23453774
27645426
75575656

Output: yes
Input:
35261546
76421754
15743271
62135642
35617653
64565476
54427254
15635465

Output: no
See MT0's answer below for additional test cases.

Original Solution: JavaScript - 261 255 228 227 179 153 Characters
/(\d)(\1(\d|.{6}|.{9})|(\d|.{6}|.{9})\1|.{7}\1(.|.{9})|(.|.{9})\1.{7}|(.{7,9}|.{17})\1.{8}|.{8}\1(.{7,9}|.{17}))\1/.test(s.replace(/\n/g,'A'))?'yes':'no'

Assuming that the string to test is in the variable s (to make it a function f then add f=s=> to the beginning of the code or, otherwise, to take input from a prompt then replace s with prompt()).
Outputs is to the console.
3rd Solution: JavaScript (ECMAScript 6) - 178 Characters
p=x=>parseInt(x,36);for(t="2313ab1b8a2a78188h9haj9j8iaiir9r",i=v=0;s[i];i++)for(j=0;t[j];v|=s[i]==s[i+a]&s[i]==s[i+b]&i%9<8&(b>3|(i+b-a)%9<8))a=p(t[j++]),b=p(t[j++]);v?'yes':'no'

I took the 2nd solution, below, (which uses regular expressions to check for characters in certain configurations) and reworked it to just check the string for identical characters in the same configurations without using regular expressions.
The Base-36 string "2313ab1b8a2a78188h9haj9j8iaiir9r" gives pairs of offsets to check - i.e. the pair 23 results in the check if ith character is identical to the (i+2)th character and the (i+3)th character (the equivalent of the regular expression (.).\1\1 - with some additional checks to ensure that the non-identical character is not a newline).
2nd Solution: JavaScript (ECMAScript 6) - 204 Characters
p=x=>parseInt(x,18);g=a=>a?a>1?"(.|\\n){"+a+"}":".":"";f=(x,a,b)=>RegExp("(.)"+g(a)+"\\1"+g(b)+"\\1").test(x);for(t="10907160789879h8",i=v=0;t[i];v|=f(s,x,y)||f(s,y,x))x=p(t[i++]),y=p(t[i++]);v?'yes':'no'

Builds multiple regular expressions (see below for more details) using pairs of values taken from the  Base-18 string 10907160789879h8 and takes the OR of all the tests. To reduce it further you can note that the regular expressions come in pairs where one is the "reverse" of the other (ignoring the Regular Expressions for 3-in-a-row horizontally and vertically as the OP states they will never be present - if you want to add those tests back in the append 0088 to the Base-18 string).
Explanation
Start with 16 regular expressions covering all the possible configurations of valid moves:
REs=[
    /(\d)\1\1/,                 // 3-in-a-row horizontally
    /(\d).\1\1/,                // 3-in-a-row horizontally after left-most shifts right
    /(\d)\1.\1/,                // 3-in-a-row horizontally after right-most shifts left
    /(\d)(?:.|\n){9}\1\1/,  // 3-in-a-row horizontally after left-most shifts down
    /(\d)(?:.|\n){7}\1.\1/, // 3-in-a-row horizontally after middle shifts down
    /(\d)(?:.|\n){6}\1\1/,  // 3-in-a-row horizontally after right-most shifts down
    /(\d)\1(?:.|\n){6}\1/,  // 3-in-a-row horizontally after left-most shifts up
    /(\d).\1(?:.|\n){7}\1/, // 3-in-a-row horizontally after middle shifts up
    /(\d)\1(?:.|\n){9}\1/,  // 3-in-a-row horizontally after right-most shifts up
    /(\d)(?:.|\n){7,9}\1(?:.|\n){8}\1/, // 3-in-a-row vertically (with optional top shifting left or right)
    /(\d)(?:.|\n){7}\1(?:.|\n){9}\1/,   // 3-in-a-row vertically after middle shifts right
    /(\d)(?:.|\n){9}\1(?:.|\n){7}\1/,   // 3-in-a-row vertically after middle shifts left
    /(\d)(?:.|\n){8}\1(?:.|\n){7}\1/,   // 3-in-a-row vertically after bottom shifts right
    /(\d)(?:.|\n){8}\1(?:.|\n){9}\1/,   // 3-in-a-row vertically after bottom shifts left
    /(\d)(?:.|\n){17}\1(?:.|\n){8}\1/,  // 3-in-a-row vertically after top shifts down
    /(\d)(?:.|\n){8}\1(?:.|\n){17}\1/,  // 3-in-a-row vertically after bottom shifts up
];

(Note: the regexs for 3-in-a-row horizontally (0th) and vertically (part of the 9th) are irrelevant as the OP states that inputs matching these will never be present.)
Testing each of those against the input will determine if a valid move of that configuration can be found.
However, the regular expressions can be combined to give these 6:
/(\d)(?:.|(?:.|\n){9}|(?:.|\n){6})?\1\1/            // Tests 0,1,3,5
/(\d)\1(?:.|(?:.|\n){9}|(?:.|\n){6})?\1/            // Tests 0,2,6,8
/(\d)(?:.|\n){7}\1(?:.|(?:.|\n){9})\1/              // Tests 4,10
/(\d)(?:.|(?:.|\n){9})\1(?:.|\n){7}\1/              // Tests 7,11
/(\d)(?:(?:.|\n){7,9}|(?:.|\n){17})\1(?:.|\n){8}\1/ // Tests 9,14
/(\d)(?:.|\n){8}\1(?:(?:.|\n){7,9}|(?:.|\n){17})\1/ // Tests 9a,12,13,15

These can then be combined into a single regular expression:
/(\d)(?:.|(?:.|\n){9}|(?:.|\n){6})?\1\1|(\d)\2(?:.|(?:.|\n){9}|(?:.|\n){6})?\2|(\d)(?:.|\n){7}\3(?:.|(?:.|\n){9})\3|(\d)(?:.|(?:.|\n){9})\4(?:.|\n){7}\4|(\d)(?:(?:.|\n){7,9}|(?:.|\n){17})\5(?:.|\n){8}\5|(\d)(?:.|\n){8}\6(?:(?:.|\n){7,9}|(?:.|\n){17})\6/

Which just needs to be tested against the input.
Test Cases
Some test cases which other people might find useful (doesn't comply with the input format of using only digits 1-7 but that's easily corrected and is only an 8x4 grid - since that is the minimum required for a test of all the valid inputs).
In the format of a map from input string to which of the 16 regular expressions above it matches.
Tests={
    "12345678\n34567812\n56781234\n78123456": -1, // No Match
    "12345678\n34969912\n56781234\n78123456": 1,    // 3-in-a-row horizontally after left-most shifts right
    "12345678\n34567812\n59989234\n78123456": 2,    // 3-in-a-row horizontally after right-most shifts left
    "12345978\n34567899\n56781234\n78123456": 3,    // 3-in-a-row horizontally after left-most shifts down
    "12345978\n34569892\n56781234\n78123456": 4,    // 3-in-a-row horizontally after middle shifts down
    "12345678\n34967812\n99781234\n78123456": 5,    // 3-in-a-row horizontally after right-most shifts down
    "12399678\n34967812\n56781234\n78123456": 6,    // 3-in-a-row horizontally after left-most shifts up
    "12345678\n34597912\n56789234\n78123456": 7,    // 3-in-a-row horizontally after middle shifts up
    "12345998\n34567819\n56781234\n78123456": 8,    // 3-in-a-row horizontally after right-most shifts up
    "12945678\n34597812\n56791234\n78123456": 9,    // 3-in-a-row vertically after top shifts right
    "12349678\n34597812\n56791234\n78123456": 9,    // 3-in-a-row vertically after top shifts left
    "12345978\n34569812\n56781934\n78123456": 10,   // 3-in-a-row vertically after middle shifts right
    "92345678\n39567812\n96781234\n78123456": 11,   // 3-in-a-row vertically after middle shifts left
    "12945678\n34967812\n59781234\n78123456": 12,   // 3-in-a-row vertically after bottom shifts right
    "12349678\n34569812\n56781934\n78123456": 13,   // 3-in-a-row vertically after bottom shifts left
    "12395678\n34567812\n56791234\n78193456": 14,   // 3-in-a-row vertically after top shifts down
    "12345698\n34567892\n56781234\n78123496": 15,   // 3-in-a-row vertically after bottom shifts up
    "12345678\n34567899\n96781234\n78123456": -1,   // No match - Matches (.)\1.\1 but not 3 in a row
    "12345679\n99567812\n56781234\n78123456": -1,   // No match - Matches (.).\1\1 but not 3 in a row
};

Edit 1
Replace \ds with . - saves 6 characters.
Edit 2
Replace (?:.|\n) with [\s\S] and removed extra non-capturing groups and updated back references (as suggested by m-buettner) and added in yes/no output.
Edit 3

Added ECMAScript 6 solution to build the individual Regular Expressions from a Base-18 string.
Removed the tests for 3-in-a-row horizontally (as suggested by m-buettner).

Edit 4
Added another (shorter) solution and two more non-matching tests cases.
Edit 5

Shortened original solution by replacing newlines with a non-numeric character (as suggested by VadimR).

Edit 6

Shortened original solution by combining bits of the regular expression (as suggested by VadimR).


Solve a quadratic equation using Vieta's formulas Exposition

Your mathematics teacher is a big fan of Vieta's formulas, and he believes that you should use them to solve quadratic equations. Given the equation

ax^2 + bx + c = 0

the product of its roots is c/a, and their sum is -b/a. When all of a, b and c are nonzero integers, assuming the roots are rational numbers, it's enough to try all possible numbers in the form

r1 = ±s/t

where s is a divisor of abs(c), and t is a divisor of abs(a). For each such r1, plug it into ax^2 + bx + c, and see whether the result is 0. If yes, then r1 is a root. The second root is -b/a-r1 or (c/a)/r1 - you can choose whatever formula you like.

Your teacher decided to give you many exercises, and he expects you to describe how you used Vieta's formulas to solve each one. Each exercise looks like this (example):

9x^2+12x+4=0

Write a subroutine or a program that gets an exercise as input, and outputs your alleged "solving process" to appease your teacher.

Input

Since you will feed the exercise to your program manually, format it in any convenient form. For example, use space-separated values on stdin:

9 12 4

or call a function with 3 parameters:

SolveExercise(9, 12, 4);

or parse the exercise literally:

9x^2+12x+4=0

Your output should be formatted as described below. Use the standard output device or return it as a string from your subroutine.

Output (example)

x = 1? 9x^2+12x+4 = 25
x = 2? 9x^2+12x+4 = 64
x = 1/3? 9x^2+12x+4 = 9
x = 2/3? 9x^2+12x+4 = 16
... (as many or as few failed attempts as you like)
x = -2/3? 9x^2+12x+4 = 0
r1 = -2/3
r2 = -12/9-(-2/3) = -2/3

Alternatively, the last line can be:

r2 = 4/9/(-2/3) = -2/3

Some additional notes:

The minimum number of line-breaks in the output is as described in the example (trailing line-break is not required). Additional line-breaks are permitted.
All coefficients in input are integers in the range [-9999...9999], none can be equal to 0
All roots are rational numbers, and should be output as such - e.g. 0.66666667 is not equal to 2/3 and so is incorrect
In the final expressions for r1 and r2, integers should be output as such, e.g. -99/1 is unacceptable, and should be output as -99; in other places in the output, denominator equal to ±1 is acceptable
Reduced form for rational numbers is not required - e.g. 2/4 is a good substitute for 1/2, even though it's ugly, even for roots r1 and r2
Parentheses in the output are sometimes required by rules of mathematics, e.g. in the expression 12/9/(2/3). When precedence rules of mathematics permit omission of parentheses, they are not required, e.g. -12/9--2/3. Superfluous parentheses are permitted: 4-(2) is OK, even though it's ugly
There should be at least one case (input) for which your program tries 3 or more non-integer values for r1; however, it's allowed to "guess the right answer" almost always on the first try
All trial values for r1 must be rational numbers ±s/t, where s and t are constrained as described above

Test cases

Input

x^2-x-2=0

or

1 -1 -2

Possible output

x=1? x^2-x-2=-2
x=-1? x^2-x-2=0
r1=-1
r2=-2/1/-1=2

Input

-x^2+2x-1=0

or

-1, 2x, -1

Possible output

x=1? -x^2+2x-1=0
r1=1
r2=-2/-1-1=1

Input

7x^2-316x+924=0

or

X(7, -316, 924);

Possible output (a divisor of 924 is 42, which solves the equation by "luck")

x=42? 7x^2-316x+924=0
r1=42
r2=316/7-42=22/7

Input

6x^2-35x-6=0

or

[6 -35 -6]

Possible output (even though your program may "know" that 6 is a root, it decides to show some failed trials)

x=1/2? 6x^2-35x-6=-88/4
x=1/3? 6x^2-35x-6=-153/9
x=3/2? 6x^2-35x-6=-180/4
x=6/1? 6x^2-35x-6=0
r1=6
r2=35/6-6=-1/6

Alternative versions for the last line:

r2=--35/6-6=-1/6
r2=-6/6/6=-1/6

Impossible input (no rational solutions)

x^2+5x+1=0

Impossible input (zero coefficient)

x^2-1=0

Python - 202 200 bytes
2 bytes saved thanks to @FryAmTheEggman.
from fractions import*;f=Fraction
lambda a,b,c:"\n".join(["x=%s?%dx^2+%dx+%d=%s"%(i,a,b,c,a*i*i+b*i+c)for i in[f(1,a),f(-1,a),f(c,a)]]+["r%d=%s"%((3-i)/2,f(i*(b*b-4*a*c)**.5-b)/f(2*a))for i in[1,-1]])


Forecast Palindromic Dates Palindromic dates are dates that appear as palindromes: the string of digits can be read the same way backwards as forwards. For the North American date format (MM/DD/YYYY), the next few palindromic dates are:

02/02/2020

12/02/2021

03/02/2030

The Challenge

Create a function that returns all palindromic dates in a consistent, common date format (of your choosing) that fall within a range of dates (edit: including the range itself).

Rules

To qualify as a palindrome, only the numeric characters of the date should be
checked.
The date can be in any common format (MM/DD/YYYY, DD-MM-YYYY), as
long as it uses two digits for both the month and day and four for
the year, and it uses a character to separate parts of the date. The output must preserve seperating characters (/, -, etc.). Your function only needs to handle one distinct date format. Please include the format in your answer.
If there are more than one dates returned, they should be comma or
new-line separated.
Shortest answer wins!

Example

date_palindrome('05/02/2050', '12/12/2060')
>>>['05/02/2050', '06/02/2060']

MATL, 24 23 bytes
YOZ}&:"@23XOtt47>)tP=?8M

Accepts  input in the form of an array of string {lower, upper} where the date format is 'MM/DD/YYYY'. Output is in the format MM/DD/YYYY as well.
Try it Online
Explanation
        % Implicitly grab the two inputs
YO      % Convert to serial date format
Z}      % Push them onto the stack separately
&:      % Create an array from [lower...upper] incrementing 1 day
"       % For each day
  @23XO % Get the string version of the date (mm/dd/yyyy)
  tt    % Duplicate twice
  47>)  % Get the numeric parts
  tP=   % Compare numeric part with the flipped version of the numeric part
  ?8M   % If they are the same push it to the stack
        % Implicitly display stack contents


Find if a list is an ABC-triple Three positive integers A, B, C are ABC-triple if they are coprime,
with A < B and satisfying the relation : A + B = C
Examples :

1, 8, 9 is an ABC-triple since they are coprime, 1 < 8 and 1 + 8 = 9
6, 8, 14 is not because they are not coprime
7, 5, 12 is not because 7 > 5

You can see this Frits Beukers 2005 presentation for more details about ABC-triples.
Input/Output
Three integers, decimal written. May be separated values or
list. Output had to be a truthy/falsy value whether the three
integers are an ABC-triple.
Note: It is important to respect integers order in the list, for example: 1, 8, 9 is not considered as the same list as 9, 1, 8 or any other combination. So first is an ABC-triple and second is not.
Thus A is the first element of the list, B the second and C the third.
Test cases
Each of the following lists should output a truthy value
[1, 8, 9]
[2, 3, 5]
[2, 6436341, 6436343]
[4, 121, 125]
[121, 48234375, 48234496]

Each of the following lists should output a falsey value
[1, 1, 2]
[1, 2, 5]
[1, 9, 8]
[4, 12872682, 12872686]
[6, 8, 14]
[7, 5, 12]

Haskell, 48 38 29 bytes

-10 bytes due to TFeld's gcd trick!
-7 bytes thanks to HPWiz for improving the co-primality test and spotting a superfluous space!
-2 bytes thanks to nimi for suggesting an infix-operator!
(a!b)c=a<b&&a+b==c&&gcd a b<2

Try it online!
Explanation
The first two conditions a < b and a + b == c are fairly obvious, the third one uses that \$\gcd(a,b) = \gcd(a,c) = \gcd(b,c)\$:
Writing \$\gcd(a,c) = U \cdot a + V \cdot c\$ using Bézout's identity and substituting \$c = a + b\$ gives:
$$
U \cdot a + V \cdot (a + b) = (U + V) \cdot a + V \cdot b
$$
Since the \$\gcd\$ is the minimal positive solution to that identity it follows that \$\gcd(a,b) = \gcd(a,c)\$. The other case is symmetric.


New Order #2: Turn My Way Introduction (may be ignored)

Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers. This is the second challenge in this series. The first challenge can be found here.

In this challenge, we use Gray codes to rearrage the natural numbers. A Gray code, or "reflected binary code" is a binary encoding in such a way that two successive values differ in only one bit. A practical application of this encoding is to use it in rotary encoders, hence my reference to "Turn My Way".

Note that this encoding leaves some degree of freedom. For example, following binary 1100, there are four possible following codes: 1101, 1110, 1000 and 0100. This is why I will define \$a(n)\$ as the smallest, not previously used value that differs only one character in binary encoding. This sequence corresponds with A163252.

Since this is a "pure sequence" challenge, the task is to output \$a(n)\$ for a given \$n\$ as input, where \$a(n)\$ is A163252.

Task

Given an integer input \$n\$, output \$a(n)\$ in integer format (not in binary format).

\$a(n)\$ is defined as the least positive integer not occurring earlier in the sequence such that \$a(n-1)\$ and \$a(n)\$ differ in only one bit when written in binary.

Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 3\$, etc. Please mention this in your answer if you choose to use this.

Test cases

Input | Output
--------------
1     | 1
5     | 4
20    | 18
50    | 48
123   | 121
1234  | 1333
3000  | 3030
9999  | 9997

Rules

Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
Invalid input (0, floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour. In A163252, \$a(0)\$ is defined as 0. For this challenge, we will ignore this.
Default I/O rules apply.
Default loopholes are forbidden.
This is code-golf, so the shortest answers in bytes wins

Final note

See the following related (but not equal) PP&CG questions:

Finding the next Gray code (input and output in binary)
Generate the all Gray codes of length n

JavaScript (ES6), 65 bytes
1-indexed.

n=>{for(o=p=[k=1];o[k]|~-(i=p^k)&i?k++:k=o[p=k]=!!n--;);return p}

Try it online!
Commented
n => {                  // n = index of requested term
  for(                  // for loop:
    o =                 //   o = storage object for the terms of the sequence
    p =                 //   p = last term found in the sequence
      [k = 1];          //   k = current term
    o[k] |              //   if k was already encountered
    ~-(i = p ^ k) & i ? //   or (p XOR k) has more than 1 bit set:
      k++               //     increment k
    :                   //   else:
      k = o[p = k]      //     set o[k], set p to k
        = !!n--;        //     stop if n is equal to 0 or set k to 1; decrement n
  );                    // end of for()
  return p              // return p
}                       // end


Write a Program that Writes a function BUT in a different language! Write the shortest program that takes one input (n) from STDIN (or equivalent) and outputs a simple incrementing function with one argument (x) that returns x + n but the function must be in a different language. Pretty simple!

This is code-golf, normal rules apply, shortest program wins.

Example: ><> to Python (Ungolfed)

!v"def i(x):"a"    return x+"ir!
 >l?!;o

Input:

3

Output:

def i(x):
    return x+3

EDIT: Anonymous functions and lambda expressions are allowed!

GS2 → K, 2 bytes

•+

This prints a tacit, monadic function. The source code uses the CP437 encoding. Try it online!

Test run

$ xxd -c 2 -g 1 sum-func.gs2
00000000: 07 2b  .+
$ printf 42 | gs2 sum-func.gs2
42+
$ kona
K Console - Enter \ for help

  (42+) 69
111
  f : 42+
42+
  f 69
111

How it works

GS2

GS2 automatically reads from STDIN and pushes the input on the stack.
• indicates that the next byte is a singleton string literal.
Before exiting, GS2 prints all stack items.

K

Left argument currying is automatic in K.

Here, n+ turns the dyadic function + into a monadic function by setting its left argument to n.


Find the shortest representation of a number in Modular SNUSP Background

Many esoteric programming languages don't have numbers built in at literals, so you have to calculate them at runtime; and in many of these cases, the number representation can be quite interesting. We've already had a challenge about representing numbers for Underload. This challenge is about representing numbers in Modular SNUSP. (Note that you don't need to learn SNUSP in order to complete this challenge – all the information you need is in the specification – but you might find the background interesting.)

The task

For the purpose of this challenge, a Modular SNUSP number is a string formed out of the characters @, +, and =, except that the last character is a #, and that the penultimate character must be + or = (it cannot be @). For example, valid numbers include @+#, ==#, and @@+@=#; examples of invalid numbers include +=, @@#, and +?+#.

The value of a Modular SNUSP number is calculated recursively as follows:

# has a value of 0 (this is the base case).
If the number has the form =x, for any string x, its value is equal to the value of x.
If the number has the form +x, for any string x, its value is equal to the value of x, plus 1.
If the number has the form @cx, for any single character c and any string x, its value is equal to the value of x, plus the value of cx.

For this challenge, you must write a program that takes a nonnegative integer as input, and outputs a string that's the shortest possible Modular SNUSP number that has a value equal to the input.

Clarifications

It's entirely possible that there will be more than one string with the same value, and in particular, for some integers there will be a tie for the shortest Modular SNUSP number with that value. In such a case, you may output any of the numbers involved wit the tie.
There's no restriction on the algorithm you use to find the number; for example, brute-forcing strings and evaluating them is a legal tactic, but so is doing something cleverer to reduce the search space.
As usual on PPCG, your submission may be either a full program or a function (pick whichever is more concise in your language).
This isn't a problem about handling input and output formats, so you can use any reasonable means to input a nonnegative integer and output a string. There's a full guide on meta, but the most commonly used legal methods include function arguments/returns, command line arguments, and standard input/standard output.

Test cases

Here are the shortest representations of the first few numbers:

0: #
1: +#
2: ++#
3: +++# or @++#
4: ++++# or +@++# or @=++#
5: @+++# or @@++#
6: +@+++# or +@@++# or @=+++# or @=@++# or @@=++#
7: @++++# or @+@++#
8: @@+++# or @@@++#
9: +@@+++# or +@@@++# or @+++++# or @++@++# or @+@=++# or @@=+++# or @@=@++#
10: @=@+++# or @=@@++# or @@@=++# (this is a fairly important test case to check, as all the possible answers include =)
11: @+@+++# or @+@@++# or @@++++# or @@+@++#
12: +@+@+++# or +@+@@++# or +@@++++# or +@@+@++# or @=+@+++# or @=+@@++# or @=@=+++# or @=@=@++# or @=@@=++# or @@=++++# or @@=+@++# or @@=@=++#
13: @@@+++# or @@@@++#
14: +@@@+++# or +@@@@++# or @=@++++# or @=@+@++# or @@+++++# or @@++@++# or @@+@=++#
15: @+@++++# or @+@+@++# or @@=@+++# or @@=@@++# or @@@=+++# or @@@=@++#

As a larger test case, the output from input 40 should be @@@=@@+++#, @@@=@@@++#, @@@@=@+++#, or @@@@=@@++#.

Victory condition

As a code-golf challenge, the winner is the shortest entry, measured in bytes.

Oracle SQL 11.2, 341 262 bytes

WITH e AS(SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4),n(s,v,p,c,i)AS(SELECT'#',0,0,e,1 FROM e UNION ALL SELECT c||s,DECODE(c,'+',1,'@',p,0)+v,v,e,i+1 FROM n,e WHERE i<11)CYCLE s SET y TO 1 DEFAULT 0 SELECT s FROM n WHERE:1=v AND rownum=1;

Old version

WITH e AS(SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4),n(s,v,p,c) AS(SELECT'#',0,0,e FROM e UNION ALL SELECT s||c,CASE c WHEN'+'THEN 1 WHEN'='THEN 0 WHEN'@'THEN p ELSE 0 END+v,v,e FROM n,e WHERE LENGTH(s)<10)CYCLE s SET y TO 1 DEFAULT 0 SELECT MIN(REVERSE(s))KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s))FROM n WHERE v=:1;

:1 the number to represent in Modular SNUSP

Un-golfed :

WITH e AS (SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4),
n(s,v,p,c,i) AS
(
  SELECT '#',0,0,e,1 FROM e
  UNION ALL
  SELECT s||c
       , DECODE(c,'+',1,'@',p,0)+v
       , v
       , e
       , i+1
  FROM n,e
  WHERE i<11
) CYCLE s SET y TO 1 DEFAULT 0
SELECT s FROM n WHERE:1=v AND rownum=1;

First create a view with 3 lines, one for each symbol used to represent numbers, minus # which is only used at the end of the string :

SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4;

Then the recursive view n generates every string possible with those 3 symbols, concatenates them to # and evaluates them.

The parameters are :

s : the Modular SNUSP representation of the number being evaluated
  v : the decimal value of s computed by the previous iteration
  p : v computed by the i-2 iteration
  c : the next symbol to concatenate to s
  i : the length of s, only needed to get rid of two LENGTH() for golfing purpose

DECODE(c,'+',1,'@',p,0)+v

If the last symbol is + then add 1
If it is @ add the value of the i-2 iteration
Else the symbol is either # or =. v is initialised with 0 in the init part of the recursive view, so the new v is equal to the previous v in either case.

WHERE i<11

Every string possible with the 3 symbols is computed, this part insure that the request does not run until the big crunch.

CYCLE s SET y TO 1 DEFAULT 0

Since there is no rule to the construction of the strings, duplicates are bound to arise. Being in a recursive view Oracle interprets those duplicates as cycles and throw an error if the case is not explicitly taken care of.

SELECT s FROM n WHERE:1=v AND rownum=1;

Returns the first Modular SNUSP representation that evaluate to the decimal number entered as parameter :1

In my tests that first line is always one of the shortest representations.

In the case your database would not act in the same way, then that last clause should be replaced with

SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY i)FROM n WHERE:1=v


Where should I put my restaurant? You are the owner of a restaurant. You are opening in a new area in Cartesia where there is only one main road, known as the y-axis. You want to place your restaurant such that you minimize the total distance from your restaurant and each of the houses in that area.

Input:

The input will be

n, the number of houses
house1
house2
house3
...
houseN

where each house is a coordinate in the form x y. Each unit represents one kilometer.

You can take input as a string or provide a function that takes the input, in whatever format you choose, as its arguments.

Output:
The y-coordinate of your restaurant (remember, it will be located on the y-axis). Actually, it will be located on the side of the road, but the difference is negligible.

Essentially, if nth house is h_n and D is the distance function, then you want to find k such that D(h_0, (0, k)) + D(h_1, (0, k)) + D(h_2, (0, k)) + ... + D(h_n, (0, k)) is minimized.

Note that distance is calculated as though the customer travels in an exactly straight line from their house to the restaurant. That is the distance from (x, y) to your restaurant is sqrt(x^2 + (y - k)^2).

The output should be accurate to at least 2 decimal places.

Output can be printed as a string or can be returned from the function.

Example input/output:

Input:
2
5.7 3.2
8.9 8.1
Output:
5.113013698630137

The total distance in this example is about 15.4003 kilometers.

This is code golf -- shortest code wins.

P.S. I'm also interested in a mathematical solution that isn't just brute force. It won't win the code golf but it'll get some upvotes. Here is how I did the example problem:

Let point A be located at A(5.7, 3.2) and B at B(8.9, 8.1). Let the solution point at (0, k) be C. Reflect A over the y-axis to make A' at (-5.7, 3.2). The distance from A' to C is equal to the distance from A to C. Therefore, the problem can be reduced to the point C such that A'C + CB is minimized. Obviously, this would be the point C that lies on the line A'B.

I don't know if this would generalize well to 3 or more points.

C, 315 302 bytes
t,i;double o,w,h,x,y,k,a,b,c;double g(N,S)double N,S[][2];{for(t=0;t<N;t++)k+=S[t][1];k/=N;for(i=0;i<9;i++){o=w=h=0;for(t=0;t<N;t++)x=S[t][0],y=S[t][1],a=y-k,c=k*k-2*k*y+x*x+y*y,o+=-a/sqrt(x*x+a*a),w+=x*x/pow(c,1.5),h+=3*x*x*a/pow(c,2.5);a=h/2;b=w-h*k;c=o-w*k+a*k*k;k=(-b+sqrt(b*b-4*a*c))/h;}return k;}

This is far from pretty, and it's not short either. I figured since I'm not going to win the length contest, I can try to win the (theoretical) accuracy contest! The code is probably an order of magnitude or two faster than the bruteforce solution, and relies on a bit of mathematical tomfoolery.
We define a function g(N,S) which takes as input the number of houses, N, and an array of houses S[][2].
Here it is unraveled, with a test case:
t,i;
double o,w,h,x,y,k,a,b,c;
double g(N,S)double N,S[][2];{
    /* Initially, let k hold the geometric mean of given y-values */
    for(t=0;t<N;t++)
        k+=S[t][1];
    k/=N;

    /* We approximate 9 times to ensure accuracy */
    for(i=0;i<9;i++){
        o=w=h=0;
        for(t=0;t<N;t++)
            /* Here, we are making running totals of partial derivatives */
            /* o is the first, w the second, and h the third*/
            x=S[t][0],
            y=S[t][1],
            a=y-k,
            c=k*k-2*k*y+x*x+y*y,
            o+=-a/sqrt(x*x+a*a),
            w+=x*x/pow(c,1.5),
            h+=3*x*x*a/pow(c,2.5);
        /* We now use these derivatives to find a (hopefully) closer k */
        a=h/2;
        b=w-h*k;
        c=o-w*k+a*k*k;
        k=(-b+sqrt(b*b-4*a*c))/h;
    }
    return k;
}
/* Our testing code */
int main(int argc, char** argv) {
    double test[2][2] = {
        {5.7, 3.2},
        {8.9, 8.1}
    };
    printf("%.20lf\n", g(2, test));
    return 0;
}

Which outputs:
5.11301369863013732697

Warning: Knowledge of some calculus may be required for a complete understanding!
So, let's talk about the math.
We know the distance from our desired point (0, k) and a house i:

And thus the total distance D from n houses can be defined as follows:

What we would like to do is minimize this function by taking a derivative with respect to k and setting it equal to 0. Let's try it. We know that the derivatives of D can be described as follows:

But the first partial derivative of each Di is pretty bad...

Unfortunately, even with n == 2, setting these derivatives to 0 and solving for k becomes disastrous very quickly. We need a more robust method, even if it requires some approximation.
Enter Taylor Polynomials.
If we know the value of D(k0) as well as all of D's derivatives at k0, we can rewrite D as a Taylor Series:

Now, this formula's got a bunch of stuff in it, and its derivatives can get pretty unwieldy, but we now have a polynomial approximation of D!
Doing a little bit of calculus, we find the next two derivatives of D by evaluating the derivatives of Di, just as before:

By truncation and evaluating the derivatives, we may now approximate D as a 3rd degree polynomial of the form:

Where A, B, C, D are simply real numbers.
Now this we can minimize. When we take a derivative and set it equal to 0, we will end up with an equation of the form:

Doing the calculus and substitutions, we come up with these formulas for a, b, and c:

Now our problem gives us 2 solutions given by the quadratic formula:

The entire formula for k would be a massive burden to write out, so we do it in pieces here and in the code.
Since we know that the higher k will always result in the minimum distance of our approximate D (I have a truly marvelous proof of this, which the margin of this paper is insufficient to contain...) we do not even have to consider the smaller of the solutions.
One final problem remains. For accuracy purposes, it is necessary that we begin with a k0 that is at least in the ballpark of where we expect the answer to be. For this purpose, my code chooses the geometric mean of the y-values of every house.
As a fail-safe, we repeat the entire problem again 9 times, replacing k0 with k at every iteration, to ensure accuracy.
I haven't done the math about how many iterations and how many derivatives are truly necessary, but I've opted to err on the side of caution until I can confirm accuracy.
If you made it through that with me, thank you so much! I hope you understood, and if you spot any mistakes (of which there are likely many, I'm very tired), please let me know!


Smallest Hamming distance to a palindrome containing a substring This was inspired by a now removed CS.SE question.

Task

Given two non-empty input strings A and B, output the smallest distance from A to a palindrome that contains B as a substring. Distance is defined by the number of character replacements (Hamming distance).

Restrictions

Sensible input: a palindrome exists. This means |A| ≥ |B|.
A and B contain only lower ASCII characters, lowercase and uppercase are distinct (as are all other characters).
If your language cannot deal with ASCII characters, you may use integers (or some other reasonable data type) as well, and you may choose to limit the range to 128 elements.
You may take input from stdin, function arguments, command line arguments, etc.
You may give the result on stdout, return value, etc.
You do not need to give a working palindrome, the smallest distance to one is sufficient.

Examples

A                   B            Output
thilloaoyreot       hello        4 (thelloaolleht)
benjonson           stack        9 (stackcats)
neversaynever!      odd          9 (neveroddoreven)
ppcggcpp            gg           0 (ppcggcpp)
stars               tat          1 (stats)

Scoring

This is code golf, shortest code in bytes wins.

Pyth, 19 bytes

hSmsnVQd/#z_I#^+Qzl

Demonstration

Extreme brute force approach. Generate all strings of the appropriate length with characters in either string, filter for palindromes and for containing the second input, map to hamming distance from first string, output smallest.

Explanation:

hSmsnVQd/#z_I#^+Qzl
hSmsnVQd/#z_I#^+QzlQ     Variable introduction
                         Q = string A, z = string B.
               +Qz       Concatenate A and B
              ^   lQ     Form every string of length equal to len(A)using
                         characters from the concatenation.
             #           Filter on
           _I            Invariance under reversal (palindrome)
         #               Filter on
        / z              Nonzero occurences of B
  m                      Map to
    nV                   !=, vectorized over
      Qd                 A and the map input
   s                     Sum (gives the hamming weight)
hS                       Min


Determine if a substructure is present in a chemical structure using SMILES string (substructure fingerprint) A SMILES (Simplified molecular-input line-entry system) string is a string that represents a chemical structure using ASCII characters. For example, water (\$H_2O\$) can be written in SMILES as H-O-H.

However, for simplicity, the single bonds (-) and hydrogen atoms (H) are frequently omitted. Thus, a molecules with only single bonds like n-pentane (\$CH_3CH_2CH_2CH_2CH_3\$) can be represented as simply CCCCC, and ethanol (\$CH_3CH_2OH\$) as CCO or OCC (which atom you start from does not matter).

n-pentane:

ethanol:

In SMILES, double bonds are represented with = and triple bonds with #. So ethene:

can be represented as C=C, and hydrogen cyanide:

can be represented as C#N or N#C.

SMILES uses parentheses when representing branching:

Bromochlorodifluoromethane can be represented as FC(Br)(Cl)F, BrC(F)(F)Cl, C(F)(Cl)(F)Br, etc.

For rings, atoms that close rings are numbered:

First strip the H and start from any C. Going round the ring, we get CCCCCC. Since the first and last C are bonded, we write C1CCCCC1.

Use this tool: https://pubchem.ncbi.nlm.nih.gov/edit3/index.html to try drawing your own structures and convert them to SMILES, or vice versa.

Task

Your program shall receive two SMILES string. The first one is a molecule, the second is a substructure (portion of a molecule). The program should return true if the substructure is found in the molecule and false if not. For simplicity, only above explanation of SMILES will be used (no need to consider stereochemistry like cis-trans, or aromaticity) and the only atoms will be:

O
C
N
F

Also, the substructure do not contain H.

Examples

CCCC C
true

CCCC CC
true

CCCC F
false

C1CCCCC1 CC
true

C1CCCCC1 C=C
false

COC(C1)CCCC1C#N C(C)(C)C // substructure is a C connected to 3 other Cs
true

COC(C1)CCCCC1#N COC1CC(CCC1)C#N // SMILES strings representing the same molecule
true

OC(CC1)CCC1CC(N)C(O)=O CCCCO
true

OC(CC1)CCC1CC(N)C(O)=O NCCO
true

OC(CC1)CCC1CC(N)C(O)=O COC
false

Shortest code wins. Refrain from using external libraries.

Mathematica, 31 bytes
MoleculeContainsQ@@Molecule/@#&

Takes input as a list of 2 strings (the source and the pattern molecules).
As you could guess, this checks if the first molecule (parsed via Molecule) contains the second one by using the MoleculeContainsQ function.
This doesn't seem to work in the online interpreter on TIO; I'm not sure what I am doing wrong. It works on my local machine, though. Of course, this is not using an external library: it's completely built-in functionality!


Cheat at Rock-Paper-Scissors-Lizard-Spock When playing Rock-Paper-Scissors-Lizard-Spock, your robot reflexes let you see your opponent's throw before they make it. You just need to choose a throw that beats theirs, in as few bytes as possible of course.

There's always two winning throws, and either one will work.

Input    -> Possible outputs
------------------------------
Rock     -> Spock or Paper
Spock    -> Paper or Lizard
Paper    -> Lizard or Scissors
Lizard   -> Scissors or Rock
Scissors -> Rock or Spock

Take a string as input, and output one of the strings that beats it. Strings must be exactly as given, with capitalization. List of characters may substitute for strings.

Perl 6, 36 30 bytes

{<Spock Lizard Rock>[.comb%4]}

Try it online!

Gets each output based on the length of the input modulo 4. I think this is probably the optimal strategy.


Angle between the hands on a clock Given the time in 24 hour format (2359 = 11:59pm) return the angle between the minute and hour hands on a standard clock (on the face plane, so don't just output 0).

Angles are to be returned in the unit of your choice, should be the smallest possible, and should be a positive number (negative angle converted to a positive value), i.e. you will never have an answer greater than 180 degrees or pi radians.

Some examples to check against (in degrees)

0000 = 0.0
0010 = 55.0
0020 = 110.0
0030 = 165.0
0040 = 140.0
0050 = 85.0
0150 = 115.0
0240 = 160.0
0725 = 72.5
1020 = 170.0
1350 = 115.0
1725 = 12.5

Note: There are a few that have rounding errors, I'm not sure how that should be handled; if we should force consistency across all values.

Haskell - 78 characters

q[h,i,m,n]=abs$((600*h+60*i-110*m-11*n-312)`mod`720)-360
c s=q$map fromEnum s

Note: My "unit of choice" is the "half-degree", of which there are 720 to the circle. With these units, the answer to the problem is always integral! :-)

Ex.:

> map c $ words "0000 0001 0010 0630 0633 2325 2345 2355 2359"
[0,11,110,30,3,335,165,55,11]
> map c $ words "0930 1845 0315 1742 2359"
[210,135,15,162,11]


Do two numbers contain unique powers of 2 Break two numbers up into their powers of 2, if they share any, return a falsey value. Otherwise, return a truthy value.

If one input is 0, the answer will always be truthy.
if one input is 255, the answer will be falsey if the other is not 0.

Example

Given 5 and 3

5 = 2⁰ + 2²
3 = 2⁰ + 2¹

Both share 2⁰, return falsey.

Given 8 and 17

8  = 2³
17 = 2⁰ + 2⁴

Neither share any powers, return truthy.

I/O

Input and output can be through any standard means

Input will always be two integers in the range 0 <= n <= 255

Output should be one truthy or falsey value

Test Cases

Truthy:
1, 2
3, 4
2, 4
8, 17
248, 7

Falsey:
1, 3
6, 4
8, 8

Standard Loopholes apply.

This is code-golf, so fewest bytes wins!

Actually, 2 bytes

&Y

Try it online!

Explanation:

&Y
&   bitwise AND
 Y  boolean negation


Kids shuffling cards Shuffling a deck of cards is hard for kids, so they must figure out ways to get a reasonable well shuffled deck as simply as possible.

One way to do this that gives reasonably good results is:

Take the top card out and insert it a random place in the deck
Take the bottom card out and insert it in a random place in the deck
Continue until you believe it's good enough.

Note that you shall never insert a card in the top or bottom spot, it should be placed somewhere in the deck.

Instead of shuffling cards, we'll shuffle alphanumerical characters: 0-9, A-J, a-j, q-z and Q-Z.

Start with the string shown below and shuffle the characters the way it's described above. You can choose if you want to continue shuffling infinitely or shuffle the cards 100 rounds (100 cards from the top and 100 cards from the bottom).

0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ

The challenge is to display the characters being shuffled. Each "shuffle" (take out and insert card) shall take between 0.25 and 0.35 seconds.

The gif below shows an example output:

This is code-golf so the shortest code in bytes wins.

"Why don't you have a-t instead of a-j, q-z?" Because this shall illustrate suits of cards, not just characters. And yes, there are 5 suits.

Note: I have decided to stop using the check mark on code-golf-challenges. Relevant meta posts here and here.

JavaScript (ES6), 192 188 185 bytes

document.write('<pre id=o>')
s='ABCDEFGHIJQRSTUVWXYZ'
a=[0,...123456789+s.toLowerCase()+s]
setInterval('o.innerText=a.join``;a.splice(Math.random(s^=1)*48+1,0,s?a.pop():a.shift())',250)

Edit: Saved 4 bytes thanks to @L.Serné. Saved 3 bytes thanks to @Arnauld.


Find elements in an array computing a given function value Problem Description

Given:

a function \$f(a, b, c, d, e) = \frac{a \times b}c + \frac de\$
an array \$x = [x_1, x_2, x_3, x_4, ..., x_n]\$ of non-distinct integers
a target value \$k\$

What is the most efficient way, in terms of worst-case \$n\$, to find 5 distinct indices \$x_a, x_b, x_c, x_d, x_e\$ from \$x\$ such that \$f(x[x_a], x[x_b], x[x_c], x[x_d], x[x_e]) = k\$?

Example solutions

Example 1 (single solution):

\$x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], k = 5\$

Solution 1:

\$[1, 4, 2, 9, 3]\$ as \$f(x[1], x[4], x[2], x[9], x[3])\$ evaluates to \$5\$.

Example 2 (multiple solutions):

\$x = [0, -1, 1, -1, 0, -1, 0, 1], k = 0\$

Solution 2 (of many solutions):

\$[1, 2, 3, 5, 7]\$ OR \$[0, 1, 2, 4, 7]\$

Example 3 (no solution):

\$x = [0, -1, 1, -1, 0, -1, 0, 1], k = 8\$

Solution 3:

\$-1\$ (no solution)

Example 4 (intermediary floats):

\$x = [2, 3, 5, 4, 5, 1], k = 2\$

Solution 4:

\$[2, 3, 5, 4, 5]\$

Python3, O(n^3 log n)
from math import gcd
from functools import reduce

def lcm(x,y):
    return x//gcd(x,y)*y

def label(l):
    res=[(v,i) for i,v in enumerate(l)]
    res.sort()
    return res

def sortcombine(l):
    l.sort()
    res=[]
    oldval=None
    for val,how in l:
        if val==oldval:
            res[-1][1].append(how)
        else:
            oldval=val
            res.append((val,[how]))
    return res

def getabc(L,xl):
    N=len(xl)
    res=[]
    lasta=None
    for ai in range(N):
        a,al=xl[ai]
        if a==lasta:
            continue
        lasta=a
        lastb=None
        for bi in range(ai+1,N):
            b,bl=xl[bi]
            if b==lastb:
                continue
            lastb=b
            lastc=None
            for c,cl in xl:
                if c in [0,lastc] or cl in [al,bl]:
                    continue
                lastc=c
                res.append((L//c*a*b,(al,bl,cl)))
    return sortcombine(res)

def getde(L,xl):
    res=[]
    xl.reverse()
    lastd=None
    for d,dl in xl:
        if lastd==d:
            continue
        lastd=d
        laste=None
        for e,el in xl:
            if e in [0,laste] or el==dl:
                continue
            laste=e
            res.append((L//e*d,(dl,el)))
    return sortcombine(res)

def solve(l,k):
    xl=label(l)
    L=reduce(lcm,[v for v in l if v!=0],1)
    k*=L
    abc=getabc(L,xl)
    de=getde(L,xl)
    i=0
    j=len(de)-1
    while i<len(abc) and j>=0:
        v1,ls1=abc[i]
        v2,ls2=de[j]
        s=v1+v2
        if s==k:
            for l1 in ls1:
                s=set(l1)
                for l2 in ls2:
                    if s.isdisjoint(l2):
                        return list(l1+l2)
            i+=1
            j-=1
        elif s<k:
            i+=1
        else:
            j-=1
    return None

Try it online!
Multiply the equation by the LCM of the x values to avoid floating point or fractions.
Find all possible values of ab/c (using ab=ba but that's only for a factor of 1/2) and d/e, sort them and try to add them to the wanted result. The sorting means we don't have to try all combinations.
There are O(n^3) possible values for ab/c, sorting them gives the log. The other steps are faster than that.
The while loop may be repeated O(n^3) times, but the case s==k can only occur O(n^2) times. If we don't find a solution and stop in this case, then the sizes of ls1 and ls2 (number of ways to obtain the corresponding value) must be in O(n) resp. O(1) (except in the case when the value is 0, but luckily that doesn't happen O(n) times).


Alien Name Generator Task

Write a function to generate names of aliens and their worlds, so that the output is of the form:

Greetings Earthfolk, I am ____ of the planet _____.

"Rules"

Best space-sounding-ness to code length wins.

The more diversity the better.

Dictionaries/look-up tables count towards code length.

Random number generators definitely allowed, other libraries less so.

Provide examples of the output.

APL (72)

Not entirely serious, but I couldn't resist. The names are generated from a subset of the APL charset. The names are between 5 and 14 characters long.

{'Greetings Earthfolk, I am'⍺'of the planet'⍵}/{⎕AV[186+{?25}¨⍳4+?9]}¨⍬⍬

Example output:

Greetings Earthfolk, I am  ⌹⍒|⍟∩⊤∩⍉⊂⊥⌽  of the planet  ∩⌹⍱⍎∪≢⊂∩
Greetings Earthfolk, I am  ⍕≡|⍕⍋!⍟⌹  of the planet  ⊂⊤⊤⌽⍟⊖⍱⊤⊤⍟⊥
Greetings Earthfolk, I am  ≢⍉⊂⍫⊂  of the planet  ⍋⌽!⍟⍉⊂∪≢


Generate cyclic numbers in decimal The formula on the wiki article for cyclic numbers can be used to generate cyclic numbers in any base. Using this formula, or any other appropriate formula, compute the first ten cyclic numbers in base 10. (The numbers cannot simply be stored and read out, even if the encoding is obscure or novel.)

Repeated cyclic numbers, for example 142857142857, should be avoided if possible.

Output can include 0. if desired, but it is not required. Each number to be delimited by line, space, comma, etc.

The program which is the shortest and which follows the rules as closely as possible will be declared the winner.

GolfScript (30 29 chars)

As xxd output:

0000000: 2207 1113 171d 2f3b 3d61 6d22 7b2e 2831  "...../;=am"{.(1
0000010: 305c 3f2e 402f 2b60 283b 6e7d 25         0\?.@/+`(;n}%

This illustrates the importance of making codegolf problems take input so that the results can't be effectively hard-coded.


Could you please tell me the time? You know that your language's clock/time API's are broken and they are not reliable at all.

So you are not allowed to use any built-in API to access system time/date.

But you also know that your language's ability to perform date math, and retaining a date/time value in a variable are correct.

Write a program that prints the current date/time without calling any date/time/clock API's.  For example DateTime.Now, GetDate() and similar functions are not allowed.

The answer with most upvotes wins.

In case of a tie, the answer with more precision wins (that is, accurate up to seconds, then milliseconds, then microseconds, and so on).

Java

Almost all of the current solutions assume that local/remote computer is not lying about a current time (would you believe T-600 as well?) .
Key point in time calculation is trusting a pure nature. This Android app asks user to take photo of the sky and it's predicting current time with outstanding precision:

public void onActivityResult(int requestCode, int resultCode, Intent data)
{
   if (resultCode == RESULT_OK)
   {
      Uri selectedImageUri = data.getData();
      this.imageView.setImageURI(selectedImageUri);

      TimeGuesser guesser = new TimeGuesser(this);
      String result = guesser.guessTimeFromImage(selectedImageUri);
      this.textView.setText(result);
   }
}

public class TimeGuesser {

    private Context context;
    public TimeGuesser(Context context)
    {
        super();
        this.context = context;
    }

    public String guessTimeFromImage(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.context.getContentResolver(), uri);
        } catch (IOException e) {
            return "There is no sky. Everyone's going to die";
        }

        float brightness = getBrightness(bitmap);

        if (brightness < 90.0)
        {
            return "It's sooo late";
        } else {
            return "It's sooo early";
        }
    }

    private float getBrightness(Bitmap bitmap)
    {
        float R, G, B;
        R = G = B = 0.0f;
        int pixelColor;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int size = width * height;

        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                pixelColor = bitmap.getPixel(x, y);
                R += Color.red(pixelColor);
                G += Color.green(pixelColor);
                B += Color.blue(pixelColor);
            }
        }

        R /= size;
        G /= size;
        B /= size;

        float brightness =  (0.2126f*R ) + (0.7152f*G) + (0.0722f*B);
        return brightness;
    }
}

Results:


Duplicate the KOOS Jr. Scoring interval algorithm Inspired from a real problem; we were looking at this table and said "Hey, now that's a good codegolf problem."

The KOOS Jr. scores converts from a raw number to a percentile score given this table:

Raw summed score  Interval score
(0-28)            (0 to 100 scale)
 0                100.000
 1                 91.975
 2                 84.600
 3                 79.914
 4                 76.332
 5                 73.342
 6                 70.704
 7                 68.284
 8                 65.994
 9                 63.776
10                 61.583
11                 59.381
12                 57.140
13                 54.840
14                 52.465
15                 50.012
16                 47.487
17                 44.905
18                 42.281
19                 39.625
20                 36.931
21                 34.174
22                 31.307
23                 28.251
24                 24.875
25                 20.941
26                 15.939
27                  8.291
28                  0.000

Provide a program, function, expression, or source file generator* that given the input raw number returns the interval score number. You may accept your input as a string or number and may produce your output as a string or number. Trailing zeros after the decimal point may be included or omitted. You may not however use scaled integers: 1 must really return 91.975 not 91975.

*source file generator must output a valid source file for some language you specify; just outputting the table is not allowed.

05AB1E, 59 bytes

•G‚Œιã¶&‡Vc–QΩ`ååI~(Ìö{3.ùSÿ{Ćι¯TærÆcï`₃āÀ}ªHÕ¶η•4ô.¥R3°/Iè

Try it online!

Explanation

•G‚Œιã¶&‡Vc–QΩååI~(Ìö{3.ùSÿ{Ćι¯TærÆcï₃āÀ}ªHÕ¶η• is a compressed version of the input constructed by:

multiplying each element in the input by 1000
reversing the resulting list
calculating deltas
joining to a single base-10 number
compressing to base-255

The rest of the code is then:

4ô          # split in pieces of 4
  .¥        # undelta
    R       # reverse
     3°/    # divide each by 1000
        Iè  # index into list with input


Obtaining ordering of cards You are given a deck containing n cards.  While holding the deck:

Take the top card off the deck and set it on the table
Take the next card off the top and put it on the bottom of the deck in your hand.
Continue steps 1 and 2 until all cards are on the table.  This is a round.
Pick up the deck from the table and repeat steps 1-3 until the deck is in the original order.

Write a program to determine how many rounds it will take to put a deck back into the original order.

I found some answers online that had answers online for comparing and I cannot get the same answers. Either they are wrong or I am completely wrong. I went through a few examples of my own got these answers:

5 cards:
    order: 12345

1: 24531
2: 43152
3: 35214
4: 51423
5: 12345   <-- 5 rounds

6 cards:

order: 123456

1: 462531
2: 516324
3: 341265
4: 254613
5: 635142
6: 123456   <-- 6 rounds

Answers I found online were:

Problem: http://www.velocityreviews.com/forums/t641157-solution-needed-urgent.html

Answer: http://www.velocityreviews.com/forums/t641157-p2-solution-needed-urgent.html   <-- last post

I found another solution that has the same solution as mine but not sure on any solutions credibility:

http://entrepidea.com/algorithm/algo/shuffleCards.pdf

I was wondering if anyone has done this problem before and would be able to confirm which answers are correct. I need something to test against to see if my program is giving the correct output. THANKS!

Python
def game(a):
    deck = range(1,a+1)
    #store the deck
    origDeck = []
    #copy the deck
    origDeck.extend(deck)
    table =[]
    ans = 0
    while 1:
        while len(deck) > 0:
            table.append(deck.pop(0))
            if len(deck) == 0:
                break
            deck.append(deck.pop(0))
        table.reverse()
        deck,table=table,deck
        ans+=1
        #this is the condition that exits the infinite loop
        if deck==origDeck:
            break
    print ans

Calling game(n) prints the number of rounds for n cards. The code can be easily changed to allow for printing the deck between rounds (add print deck before if deck==origDeck).

Tests (1 through 50):
1: 1
2: 2
3: 3
4: 2
5: 5
6: 6
7: 5
8: 4
9: 6
10: 6
11: 15
12: 12
13: 12
14: 30
15: 15
16: 4
17: 17
18: 18
19: 10
20: 20
21: 21
22: 14
23: 24
24: 90
25: 63
26: 26
27: 27
28: 18
29: 66
30: 12
31: 210
32: 12
33: 33
34: 90
35: 35
36: 30
37: 110
38: 120
39: 120
40: 26
41: 41
42: 42
43: 105
44: 30
45: 45
46: 30
47: 60
48: 48
49: 120
50: 50

31 produces a peculiar output; it goes through 210 rounds.
It appears that primes have large cycles. For example, 97 has the largest cycle under 100: 6435.


Write a chicken interpreter! You have to write an interpreter for a cool language called Chicken!

You should read a Chicken program from a file, standard input, program or function arguments, or whatever is most convenient for your language, as well as input to the program.

You should print or return the result of interpreting the program according to the Chicken language specification.

More description about the language.

Chicken Program Overview

Chicken operates on a single stack, which composes its entire memory model. As instructions are executed, the program will push and pop values from the stack, but there are also instructions that allow the program to modify other parts of the stack at will.

There are three segments in the stack:

The registers, at indices 0 and 1. Index 0 is a reference to the stack itself, and index 1 is a reference to the user input. Mostly used for instruction 6 (see below).
The loaded code: for each line of code there is cell in this segment that contains the number of "chicken"s in the line. This is padded with a 0 (opcode for terminate program) at the end.
The actual program stack, where values are pushed/popped as the program runs. Note that the segments are not isolated, which means that it is possible to create self-modifying code or execute code from this segment of the stack space.

The Chicken ISA

Chicken's instruction set is based around the number of times the word "chicken" appears on each line of the program. An empty line terminates the program and prints the topmost value in the stack.

The Chicken instruction set, by number of "chicken"s per line:

Push the literal string "chicken" to the stack
Add top two stack values as natural numbers and push the result.
Subtract top two values as natural numbers and push the result.
Multiply top two values as natural numbers and push the result.
Compare two top values for equality, push 1 if they are equal and 0 otherwise.
Look at the next instruction to determine which source to load from: 0 loads from stack, 1 loads from user input. Top of stack points to address/index to load from the given source; load that value and push it onto stack. Since this is a double wide instruction, the instruction pointer skips the instruction used to determine the source.
Top of stack points to address/index to store to. The value below that will be popped and stored in the stack at the given index.
Top of stack is a relative offset to jump to. If the value below that is truthy, then the program jumps by the offset.
Interprets the top of the stack as ascii and pushes the corresponding character.
(10 + N) Pushes the literal number n-10 onto the stack.

Example

Assume the program is:

chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
(an empty line)

(A cat program. Note that the empty line is required because of the preceding line having 6 "chicken".)

Input provided to Chicken program

Chicken

Output

Chicken

The Chicken.js reference implementation.

Error detection

The interpreter should leave an error and terminate when any word not "chicken" is present in the source.

Good luck!

Javascript ES6, 398 bytes
By far the longest golf I have ever done, I'm sure this can be improved but my brain doesn't recognize anything other than chicken at this point.
(a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}

I will edit the explanation in when my brain starts functioning again. Here's a slightly ungolfed version for now.
Outputs a falsey value (0) for everything which isn't chicken
(a,b)=>{
    for(c='chicken',s=[j=0,b,...A=a.split`
    `.map(m=>m.split(c).length-1)],i=A.length+2; // loop init
    j<A.length; // loop condition
    ( // everything else
        [
            _=>s[++i]=c,
            _=>s[--i]=s[i]+s[i+1],
            _=>s[--i]=s[i]-s[i+1],
            _=>s[--i]=s[i]*s[i+1],
            _=>s[--i]=s[i]==s[i+1],
            _=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],
            _=>s[s[i--]]=s[i--],
            _=>j+=s[--i]?s[--i+2]:0,
            _=>s[i]=String.fromCharCode(s[i])
        ][s[j+2]-1]
        ||(_=>s[++i]=s[j+1]-10)
    )(j++)
);
return /[^chicken \n]\w/g.test(a)?0:s[i]}

Try it here

f=
  (a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}

i.innerHTML = f(`chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
`, 'Hello world!')
<pre id=i>


How many squares, cubes, fourth powers, etc. do I need to sum to n? You are given a nonnegative integer n and an integer p >= 2. You need to add some p-th powers (p=2 means squares, p=3 means cubes) together to get n. This is always for any nonnegative n, but you don't know many p-th powers (of any positive integer) you'll need.

This is your task: find the minimum number of p-th powers that can sum to n.

Examples

>>> min_powers(7, 2)
4                       # you need at least four squares to add to 7
                        # Example: (2)^2 + (1)^2 + (1)^2 + (1)^2 = 4 + 1 + 1 + 1 = 7
>>> min_powers(4, 2)
1                       # you need at least one square to add to 4
                        # Example: (2)^2 = 4
>>> min_powers(7, 3)
7                       # you need at least seven cubes to add to 7
                        # Example: 7*(1)^3 = 7
>>> min_powers(23, 3)
9                       # you need at least nine cubes to add to 23
                        # Example: 2*(2)^3 + 7*(1)^2 = 2*8 + 7*1 = 23

A related Wikipedia article on this problem, Waring's problem.

Rules

Your code must be a program or a function.
Input is two integers n and p in any order. You can assume all inputs are valid (n is any positive integer, p >= 2
Output is an integer representing the number of powers needed to sum to n.
This is code golf, so the shortest program wins., not necessarily the most efficient.
Any and all built-ins are allowed.

As always, if the problem is unclear, please let me know. Good luck and good golfing!

Mathematica 61 50 bytes
With 11 bytes saved by LegionMammal978.
When restricted to powers of counting numbers, this problem is straightforward (in Mathematica).  When extended to include powers of integers, it's a nightmare.
(k=0;While[PowersRepresentations[#,++k,#2]=={}];k)&

Test Cases
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[7, 2]
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[4, 2]
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[7, 3]
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[23, 3]

4
1
7
9

PowersRepresentationsp[n,k,p] finds all the cases in which n can be expressed as a sum of k positive integers raised to the p-th power.

For example,
PowersRepresentations[1729, 2, 3]

{{1, 12}, {9, 10}}

Checking,
1^3 + 12^3

1729

9^3 + 10^3

1729