Riffle shuffle a string - Cops Robbers post

A riffle shuffle is a way of shuffling cards where the deck is split into 2 roughly equal sections and the sections are riffled into each other in small groups. This is how to riffle shuffle a string:

Split the string into equal sections.
Reverse the strings, and starting from the start of each string.
Put runs of a uniformly random length between 1 and the number of characters left in the current string into the final string
Then remove these characters from the string.
Repeat for the other half, until both halves are empty.

An example

"Hello World!"      Output string = ""
"Hello ", "World!"  ""
"Hell", "World!"    " o"
"Hell", "World"     " o!"
"Hel", "World"      " o!l"
"Hel", "Wo"         " o!ldlr"
"H", "Wo"           " o!ldlrle"
"H", ""             " o!ldlrleoW"
"", ""              " o!ldlrleoWH"

The final product from Hello World! could be o!ldlrleoWH and that is what you would output.

Cops

Your task is to make a program (or function) that will riffle shuffle a string. If the inputted string is of odd length, just split it into two uneven length strings with a relative length of +1 and +0 (abc => [ab, c] or [a, bc]). You may take input in the normal fashion and produce output in the normal fashion.

Your Cops submission will consist of 4 things

The language you used
The length of your program in bytes
Your program, riffle shuffled.
Anything else you want to add

You are aiming to keep your code from being uncracked by the Robbers for 7 days. After that period, your program is safe and you should edit in your original program. Your submission may still be cracked until you reveal your solution. The shortest, safe solution will be the winner!

Python 3, 154 bytes (list of chars -> list of chars) (function) Cracked

[=o;]1-::[]:s[i,]1-::[]s:[i=R,L;2//)i(nel=s
:)i(r fed
*tropmi modR+L+o nruter
]:s[L,R=R,L;]s:[L=+o;))L(nel,1(tnidnar=s:R dna L elihw
]nar morf

I doubt this will be too hard to crack, especially since riffling once is rather ineffective (you can see entire program components in the output...). This is mostly just to get things rolling. There might be some whitespace (including newlines) that I didn't copy correctly. The SHA-384 hash of my  intended solution is
5924530418bf8cd603c25da04ea308b124fdddfc61e7060d78b35e50ead69a7fbde9200b5ee16635cc0ee9df9c954fa1.


Apportionment paradox Given:

A natural number S.
A list of N rational weights W that sum to 1.

Return a list L of N non-negative integers, such that:

(1) sum(L) = S
(2) sum((S⋅W_i - L_i)^2) is minimal

In other words, approximate S⋅W_is with integers as closely as possible.

Examples:

1 [0.4 0.3 0.3] = [1 0 0]
3 [0 1 0] = [0 3 0]
4 [0.3 0.4 0.3] = [1 2 1]
5 [0.3 0.4 0.3] = [2 2 1] or [1 2 2] but not [1 3 1]
21 [0.3 0.2 0.5] = [6 4 11]
5 [0.1 0.2 0.3 0.4] = [1 1 1 2] or [0 1 2 2]
4 [0.11 0.3 0.59] = [1 1 2]
10 [0.47 0.47 0.06] = [5 5 0]
10 [0.43 0.43 0.14] = [4 4 2]
11 [0.43 0.43 0.14] = [5 5 1]

Rules:

You can use any input format at all, or just provide a function that accepts the input as arguments.

Background:

This problem comes up when displaying S of different types of items in different proportions Wi with regard to the types.

Another example of this problem is proportional political representation, see the apportionment paradox. The last two test cases are known as Alabama paradox.

  As a statistician, I recognised this problem as equivalent to a
  problem encountered in identifying sample sizes when conducting a
  stratified sample. In that situation, we want to make the proportion
  of each stratum in the sample equal to the proportion of each stratum
  in the population.
  — @tomi


11 = (1+2+3+4+5) - (1+2+3) + (6) - (4) Given a positive integer N, your task is to return the number of steps required by the following algorithm to reach N:

Find the smallest triangular number Ti such that Ti ≥ N. Build the corresponding list L = [ 1, 2, ..., i ].
While the sum of the terms of L is greater than N, remove the first term from the list.
If the sum of the terms of L is now less than N, increment i and append it to the list. Go on with step #2.

We stop as soon as N is reached. Only the first step is systematically executed. Steps #2 and #3 may not be processed at all.

Examples

Below is an example for N = 11:

So the expected output for N = 11 is 4.

Other examples:

N = 5 - We start with T3 = 1 + 2 + 3 = 6, followed by 2 + 3 = 5. Expected output: 2.
N = 10 - Only the first step is required because 10 is a triangular number: T4 = 1 + 2 + 3 + 4 = 10. Expected output: 1.

First 100 values

Below are the results for 1 ≤ N ≤ 100:

  1,  2,  1,  4,  2,  1,  2, 10,  2,  1,  4,  2,  6,  2,  1, 22,  8,  2, 10,  2,
  1,  2, 12,  6,  2,  4,  2,  1, 16,  2, 18, 50,  2,  6,  2,  1, 22,  6,  2,  4,
 26,  2, 28,  2,  1,  8, 30, 16,  2,  6,  4,  2, 36,  2,  1,  2,  4, 12, 40,  2,
 42, 14,  2,108,  2,  1, 46,  2,  6,  4, 50,  2, 52, 18,  2,  4,  2,  1, 56, 12,
  2, 20, 60,  4,  2, 22, 10,  2, 66,  2,  1,  4, 10, 24,  2, 40, 72,  8,  2,  6

Rules

You may write either a full program or a function, that either prints or returns the result.
You're required to process any N ≤ 65536 in less than one minute on mid-range hardware.
Given enough time, your program/function should theoretically work for any value of N that is natively supported by your language. If it doesn't, please explain why in your answer.
This is code golf, so the shortest answer in bytes wins!

Mathematica, 79 bytes

Min[2#/(d=Divisors@#~Cases~_?OddQ)+d]-2⌊(2#)^.5+.5⌋+⌈Sqrt[8#+1]~Mod~1⌉&

Explanation

I couldn't be bothered to implement the algorithm in the challenge, so I wanted to look for a shortcut to the solution. While I found one, unfortunately it doesn't beat the Mathematica answer that does implement the algorithm. That said, I'm sure this isn't optimally golfed yet, and there might be other languages who can benefit from this approach or some of the insights gained in the process.

So I claim that the sequence we're supposed to compute is:

f(n) = 2*(A212652(n) - A002024(n)) + 1 + A023532(n-1)

Alternatively, it's f(n) = 1 if n is a triangular number and f(n) = 2*(A212652(n) - A002024(n) + 1) otherwise.

In the first expression, A023532 simply encodes these two different cases. The other two sequences (plus 1) are the difference between the the largest integer k in the longest decomposition of n into consecutive integers (k-i+1) + (k-i+2) + ... + k = n and the largest integer j so that 1 + 2 + ... + j < n.

In somewhat simpler words, here is how we find the answer for non-triangular numbers: first, find the largest triangular number Tj which is less than n. Then j is the penultimate integer that gets added during step 1 (because after adding j+1 we will have exceeded n). Then decompose n into as many (or as small) consecutive integers as possible and call the maximum among these numbers k. The result is simply 2*(k-j). The intuitive reason for this is that the maximum in the decomposition grows by 1 every other step and we stop when we reach k.

We need to show four things to prove that this works:

f(n) = 1 for triangular numbers. This is trivially the case, because the first step simply iterates through all triangular numbers. If we hit n exactly during this process we're done and there was only one step to compute.
For all other numbers, we always end after a deletion step, never after an insertion step. That means all other f(n) are even.
In each insertion step after the first, we only add a single number. This guarantees that we'll reach a decomposition including k after k-j pairs of steps.
The final decomposition of n that we obtain is always the longest possible decomposition of n into consecutive integers, or in other words, it's always the decomposition of n with the lowest maximum among the summed numbers. In other words, the last number we add to the sum is always A212652(n).

We've already shown why (1) is true. Next, we prove that we can't end on an insertion step except the initial one (which doesn't happen for non-triangular numbers).

Suppose we ended on an insertion step, reaching n after adding a value p to the sum. That means that before this insertion step, the value was n-p (or less if we added multiple values at once). But this insertion step was preceded by a deletion step (since we couldn't have hit n during step 1). The last value q we removed during this deletion step was necessarily less than p due to the way the algorithm works. But that means before we removed q we had n-p+q (or less) which is less than n. But that's a contradiction, because we would have had to stop removing integers when we hit n-p+q instead of removing another q. This proves point (2) above. So now we know that we always end on a deletion step and that therefore all non-triangular numbers have even outputs.

Next we prove (3), that each insertion step can only insert one value. This is essentially a corollary of (2). We have shown that after adding one value we cannot hit n exactly and since the prove was using an inequality, we also cannot end up below n (since then n-p+q would still be less than n and we shouldn't have removed that many values in the first place). So whenever we add a single value, we're guaranteed to exceed n because we went below n by removing a smaller value. Hence, we know that the upper end of the sum grows by 1 every other step. We know the initial value of this upper end (it's the smallest m such that Tm > n). Now we just need to figure out this upper end once we've reached the final sum. Then the number of steps is simply twice the difference (plus 1).

To do this, we prove (4), that the final sum is always the decomposition of n into as many integers as possible, or the decomposition where the maximum in that decomposition is minimal (i.e. it's the earliest possible decomposition). We'll again do this by contradiction (the wording in this part could be a bit more rigorous, but I've already spent way too much time on this...).

Say the earliest/longest possible decomposition of n is some a + (a+1) + ... (b-1) + b, a ≤ b, and say the algorithm skips it. That means at the time that b gets added, a must no longer be part of the sum. If a was part of the sum s, then we'd have n ≤ s at that moment. So either the sum only contains the values from a to b, which equals n and we stop (hence we didn't skip this decomposition), or there is at least one value less than a in the sum, win which case n < s and that value would get removed until we hit the exact sum (again, the decomposition wasn't skipped). So we'd have to get rid of a before adding b. But that means we'd have to reach a situation in which a is the smallest component of the sum, and the largest isn't b yet. However, at that point we can't remove a, because the sum is clearly less than n (since b is missing), so we're required to add values first until we add b and hit n exactly. This proves (4).

So taking these things together: we know that the first pair of steps gives us a maximum value of A002024(n). We know that the maximum value of the final decomposition is A212652(n). And we know that this maximum is incremented once in every pair of steps. Hence, the final expression is 2*(A212652(n) - A002024(n) + 1). This formula almost works for triangular numbers, except that for those we only need 1 step instead of 2, which is why we correct the result with the indicator function of the triangular numbers (or its inverse, whichever is more convenient).

Finally, as for the implementation. For the former sequence, I'm using the formula MIN(odd d|n; n/d + (d-1)/2) from OEIS. It turns out to save a few bytes if we take the factor of 2 into this expression to get MIN(odd d|n; 2n/d + d-1), because that -1 then cancels with the +1 in my first version of f(n) which directly encodes the two cases for triangular and non-triangular numbers. In the code, this is:

Min[2#/(d=Divisors@#~Cases~_?OddQ)+d]

For the latter sequence (1, 2, 2, 3, 3, 3, ...), we can use a simple closed form:

⌊(2#)^.5+.5⌋

And finally, the inverse indicator function of the triangular numbers is 0 whenever 8n+1 is a perfect square. This can be expressed in Mathematica as

⌈Sqrt[8#+1]~Mod~1⌉

There are a lot of ways to express these last two sequences and to shift some constant offset between them, so I'm sure this is not an optimal implementation yet, but I hope this might give others a starting point to look into new approaches in their own languages.

Since I went to all this trouble, here is a plot of the sequence up to n = 1000 (I could also compute 100k in a couple of seconds, but it doesn't really show any additional insights):

It might be interesting to look into the variations about those very straight lines, but I'll leave that to someone else...


When will I have a binary car? I noticed that my car's odometer was at 101101 when I got to work today. Which is a cool number because it's binary (and a palindrome, but that's not important). Now, I want to know when the next time I'll have a binary odometer reading. I can't read the odometer while I'm driving, because that would be dangerous, so it'll have to be binary either when I get to work or get home.

There's really bad traffic on the way to and from my office, so I have to take a different route each day.

For the purposes of this challenge, a day is a round trip and starts with my commute to work.

You'll need to take the initial reading of the odometer and a 10 element sequence representing the amount of miles each way. This sequence should be repeated until you get to a binary odometer reading. You should then output the number of days it takes until we get to a binary reading.

Both the milage for the route and the odometer reading will be positive integers. The count of days will either be x or x.5, so your output of the day count needs to support floating point for half days. If the day count is an integer, you don't need to output the .0. The odometer will always eventually reach a binary state.

Any form of input/output is acceptable and standard loopholes are disallowed.

Test cases:

101101, [27, 27, 27, 27, 27, 27, 27, 27, 27, 27] == 165.0
1, [13, 25, 3, 4, 10, 8, 92, 3, 3, 100] == 22.5
2, [2, 3, 1, 2, 7, 6, 10, 92, 3, 7] == 2.0

Javascript, 68 63 61 60 52 bytes

5 bytes off thanks @ETHproductions. 2 3 11!! bytes off thanks @NotthatCharles.

f=(i,a,m=0)=>/[^01]/.test(i+=a[m++%10])?f(i,a,m):m/2

Test here.


Avoid the evil integers! You are developing some code to generate ID numbers. Policy requires that no ID numbers include the digit sequence 666.

Create a function (or your language's equivalent) which takes a positive integer parameter and returns the next integer that does not include 666 when that integer is expressed in decimal. (60606 is fine, 66600 is not.)

Your code must not use a loop that adds one until it finds a result that fits the rules.

f(1) returns 2.
f(665) returns 667.
f(665999999) returns 667000000 without having looped a million times.
(Following examples added since the question was first posed.)
f(666666666) also returns 667000000.
f(66600) returns 66700.
f(456667) returns 456670.

UPDATE:
Replacing 666 with 667 won't work if there's more than one 666 in the input.

Python, no string manipulation

def f(n):
    n += 1
    p = 1
    m = n
    while m:
        if m % 1000 == 666:
            n += p - n % p
        p *= 10
        m /= 10
    return n

Works by finding powers of 10, p, where 666 appears, and adding p - n % p to n which replaces 666xxxxx with 66700000.


One Ring to rule them all. One String to contain them all Objectives: Output a String which contains every positive integer strictly below 1000.

The obvious answer would be to concatenate every one of them, and that would create a String of 2890 characters (thanks manatwork), to avoid this kind of easy answer, the length of the string must be under 1500 characters.
Here is a straightforward Java code which outputs a 1200 chars String.

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

import static org.junit.Assert.assertTrue;

/**
 * Created with IntelliJ IDEA.
 * User: fab
 * Date: 05/11/13
 * Time: 09:53
 * To change this template use File | Settings | File Templates.
 */
public class AStringToContainThemAll {

    @Test
    public void testsubStrings() throws Exception {
        String a = generateNewString();
        boolean cool = true;
        for (int i = 0; i < 1000; i++) {
            assertTrue(a.contains(Integer.toString(i)));
        }
    }

    private String generateNewString() {
        List<Integer> myTree = new ArrayList<Integer>();
        String finalString = new String("100");
        for (int i = 10; i < 1000; i++) {
            myTree.add(i);
        }
        while (myTree.size() > 0) {
            if (finalString.contains(Integer.toString(myTree.get(0)))) {
                myTree.remove(0);
            } else {
                String substringLong = finalString.substring(finalString.length() - 2, finalString.length());
                boolean found = false;
                loop:
                for (Integer integer : myTree) {
                    if (integer.toString().startsWith(substringLong) && !finalString.contains(integer.toString())) {
                        finalString = finalString.concat(integer.toString().substring(2, 3));
                        myTree.remove(integer);
                        found = true;
                        break loop;
                    }
                }
                if(! found){
                    finalString = finalString.concat(myTree.get(0).toString());
                    myTree.remove(0);
                }
            }

        }
        return finalString;
    }
}

Shortest code win, bonus point for the shortest String!


Greek Syllabication (Simplified) INTRO

Let's say you write a passage and you are close to the end of the line wanting to write down a large word. In most languages, you just leave some blank and move to the next line, like a sir.

  Example - English:

blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah   blah this man is      unaccountable

But if you are (un)lucky enough to be Greek, when you are close to terminate a line, you cannot just move to the next one. Everything must look nice and in balance, so you SEPARATE the word

  Example - Greek:

μπλα μπλα μπλα μπλα μπλα μπλα μπλα μπλα μπλα μπλα μπλα μπλα αυτός ο άνδρας είναι ανεξή-
γητος

Of course this separation is not done randomly, but instead there is a complicated set of rules, as to how & when to separate, which is actually an entire learning chapter back in primary school that every kid hates.

OBJECTIVE

You are given a greek word (just a string of greek letters). You need to do a greek syllabication, i.e. separate the greek word in syllabes, according to the set of rules given below, so that the user will have the option to separate the word in the end of the line correctly.

Examples:
1) αγαπη (love) = α-γα-πη
2) ακροπολη (acropolis) = α-κρο-πο-λη
3) βασικα (basically) = βα-σι-κα

ALPHABET & SIMPLIFIED RULES

consonants: β,γ,δ,ζ,θ,κ,λ,μ,ν,ξ,π,ρ,σ,τ,φ,χ,ψ

vowels: α,ε,η,ι,ο,υ,ω

rule 0) Every vowel defines a different syllable, unless rule 4

rule 1) When there is consonant between two vowels, it goes with the second vowel
(ex. γ --> α-γα-πη)

rule 2) When there are two consonants between two vowels, they go with the second vowel, if there is a greek word starting from these two consonants (we assume that that's always the case in our exercise)
(ex. βλ --> βι-βλι-ο)

rule 3) When we have 3 consonants between two vowels-->same as rule 2

rule 4) Following configurations are considered as "one letter" and are never separated: ει, οι, υι, αι, ου, μπ, ντ, γκ, τσ, τζ
(ex. α-γκυ-ρα)

rule 5) Always separate same consonants
(ex. αλ-λη)

YOUR TASK

Your code should take as input string (or some other format you wish) a greek word and return the same word, with dashes in between, determining the points where the word can be separated, i.e. do a greek syllabication.

TestCases:

[πολη (city)] --> [πο-λη]
[τρεχω (run)] --> [τρε-χω]
[αναβαση (climbing)] --> [α-να-βα-ση]
[οαση (oasis)] --> [ο-α-ση]
[ουρα (tail)] --> [ου-ρα]
[μπαινω (enter)] --> [μπαι-νω]
[εχθροι (enemies)] --> [ε-χθροι]
[ελλαδα (greece)] --> [ελ-λα-δα]
[τυροπιτα (cheese pie)] --> [τυ-ρο-πι-τα]
[αρρωστη (sick)] --> [αρ-ρω-στη]

Shortest code wins, but every effort is appreciated :)

Haskell, 222 201 bytes

s""=[]
s x|c?"ειοιυιαιου"=(a++c):s d|h:e:f:g<-b,e==f=(a++[h,e]):s(f:g)|e:f<-b=(a++[e]):s f|2>1=[a]where(a,b)=break(`elem`"αεηιουω")x;(c,d)=splitAt 2 b
i?(x:y:z)=i==[x,y]||i?z
i?""=1>2

Try it online!


Crop ASCII Art Challenge ASCII art is fun. Modern text editors are very good at manipulating text. Are modern programming languages up to the task?

One common task in ASCII art manipulation is to crop text to a rectangle between two characters. This is the task you must implement in this challenge.

Details

Your program will take 3 inputs:

the first is the 'start' character of the block - marking the top-left corner
the second is the 'end' character of the block - marking the bottom-right corner
the third is some form of multiline text, either a string, or list of strings, or filename, or whatever

The result will be multiline text (again, in any of the above formats) cropped to the rectangle between the given inputs. Note that the first two inputs may not be unique.

Edge cases

Boxes must always have volume at least 2. Thus these:

()     (
       )

are boxes but these:

)(     )      (
       (     )

are not (with start=( and end=)).

The input will only contain one box. Thus the start and end characters must only occur once, unless they are the same character in which case they must occur exactly twice.

Additionally each line in the input must be at least as long as the distance from the start of a line to the right edge of the box in the input.

Your program does not need to handle invalid inputs; they may result in undefined behavior.

Rules

Typical code-golf rules apply. Shortest code wins.

Examples

Sunny-day: start: ( end: ) input:

This is some text
. (but this text
  is in a box  ).
So only it is important.

Output:

(but this text
is in a box  )

Note the stripping of horizontal space as well. ASCII art crops are 2d.

Rainy-day: start: ( end: ) input:

This is some text (
But is that even  )
really a box?

Output:

(
)

Same start/end: start: / end: / input:

Oh, I get how this could be useful
 /----------------------------\
 | All this text is in a box! |
 \----------------------------/

Output:

/----------------------------\
| All this text is in a box! |
\----------------------------/

Invalid input: start: ( end: ) input:

Boxes are rectangular ( so this has
0 volume ) which is illegal.

Invalid input 2: start: ( end: ) input:

(The lines must already be square
so this line that is too short
relative to this end, is illegal)

Vim, 16, 12 bytes/keystrokes

#<C-v>Nj*yggVGp

Try it online! in the V interpreter

  Modern text editors are very good at manipulating text. Are modern programming languages up to the task?

I bet old text editors are even better! :D

Even though it doesn't necessarily have to, this answer does work with both of the given "invalid" inputs, outputting

 rectangular (
) which is ill

and

(The lines must already be square
so this line that is too short
relative to this end, is illegal)

Explanation:

#               " Move backward to the previous occurrence of the word (or in this case, character) under the cursor
 <C-v>          " Start a visual block selection
      N         " Go to the next occurrence of the last searched term (guaranteed to be line 1)
       j        " Move down a line
        *       " Move forward to the next occurrence of the character under the cursor
         y      " Yank (copy) the whole visually selected block
          gg    " Go to line 1
            VG  " Select every line
              p " And paste what we last copied over it, deleting the whole buffer and replacing it with the block


Sum the time durations Challenge

Write the shortest code that can sum all the time durations that appear in the stdin. The program must only consider the strings that match with one of the following patterns and ignore the rest.

    HH:MM:SS     (it will be interpreted as HH hours, MM minutes and SS seconds)
    H:MM:SS      (it will be interpreted as H hours, MM minutes and SS seconds)
    MM:SS        (it will be interpreted as MM minutes, SS seconds)
    M:SS         (it will be interpreted as M minutes, SS seconds)

examples of strings that match with the enumerated patterns:

    12:00:01
    2:03:22
    00:53
    9:13

The output should be of the form

    HHh MMm SSs      (that means HH hours, MM minutes and SS seconds with non-zero-padding)

Example

STDIN

  View the Welcome video.
    Video: 10:37 min.
  View the video introduction to the course.
    Video: 3:30 min.
  View the video of how to use the Lesson Overview.
    Video: 9:13 min.
  View the video overview of how to use the Epsilen system to share your work.
    Video: 03:15 min.
  View the video to learn about the State of Texas Assessment of Academic Readiness (STAAR).
    Video: 1:05:26 min.

STDOUT

  1h 32m 1s

Javascript ES6, 138 chars

Function, 139

Takes string as an argument and writes output to console:

f=s=>(r=0,s.replace(/(\d\d?):(\d\d)(:(\d\d))?/g,(m,a,b,x,c)=>r+=x?+c+b*60+a*3600:+b+a*60),console.log("%dh %dm %ds",r/3600,r%3600/60,r%60))

Program, 138

prompt(r=0).replace(/(\d\d?):(\d\d)(:(\d\d))?/g,(m,a,b,x,c)=>r+=x?+c+b*60+a*3600:+b+a*60),console.log("%dh %dm %ds",r/3600,r%3600/60,r%60)

Test for function

f("View the Welcome video.\n\
Video: 10:37 min.\n\
View the video introduction to the course.\n\
Video: 3:30 min. View the video of how to use the Lesson Overview.\n\
Video: 9:13 min.\n\
View the video overview of how to use the Epsilen system to share your work.\n\
Video: 03:15 min.\n\
View the video to learn about the State of Texas Assessment of Academic Readiness (STAAR).\n\
Video: 1:05:26 min.")

Output

"1h 32m 1s"


Sums of digits 1 through 7 Challenge
Given a positive integer N that is 28 or above, output a list of numbers summing to N that uses each digit 1 through 7 exactly once. You can give as a program or function.
The digits can appear by themselves or concatenated, as long as you use each of them once without repeats. For example,[12, 34, 56, 7] is valid, as is [1, 27, 6, 4, 35] and [1234, 567], but not [123, 34567] or [3, 2, 1476]. The order that the numbers are listed does not matter.
If N cannot be made with 1-7, return or output nothing.
Other information

This is code golf, so the shortest code in bytes by Thursday the 15th of October wins.

Ask any questions in the comments.

Anything I do not specify in the challenge is up to you.

Standard loopholes are disallowed.

Examples
These may clear any confusion up:
Input
28

Output
[1, 2, 3, 4, 5, 6, 7]

Input
100

Output
[56, 7, 4, 31, 2]

Input
1234567

Output
[1234567]

Input
29

Output
Nothing, 29 is invalid.
Input
1891

Output
[1234, 657]

Input
370

Output
[15, 342, 7, 6]

I'll make more if needed.
Here's a pastebin of all of the possible numbers created with these seven numbers, courtesy of FryAmTheEggman.

Pyth, 18 14 bytes

hfqSjkTjkS7./Q

Thanks to @isaacg for golfing off 2 bytes and paving the way for 2 more.

The code will crash if it should produce no output, which causes no output to be produced.

This will work for small-ish inputs if you're patient enough, and for larger ones if given enough time and memory.

To verify that the code works as intended, you can replace the 7 with a 3 for sums of digits 1 through 3. Click here for a test suite.

Example runs

$ time pyth/pyth.py -c 'hfqSjkTjkS7./Q' <<< 28
(1, 2, 3, 4, 5, 6, 7)

real    4m34.634s
user    4m34.751s
sys     0m0.101s
$ time pyth/pyth.py -c 'hfqSjkTjkS7./Q' <<< 29 2>/dev/null

real    9m5.819s
user    9m6.069s
sys     0m0.093s

How it works

           ./Q    Compute all integer partitions of the input.
 f                Filter the integer partitions:
    jkT             Join the integers with empty separator.
   S                Sort the characters of the resulting string.
      jkS7          Join [1, ..., 7] with empty separator.
  q                 Check both results for equality.
                  Keep the partition of `q' returned True.
h                 Retrieve the first element of the filtered list.
                  For a non-empty list, this retrieves the solution.
                  For the empty list, it causes an error and produces no output.


Pizza, Pizza, Deep Dish Pizza! April 5th is National Deep DIsh Pizza Day, the theme of this challenge. Given a positive integer n (n is greater than 0), create an ASCII deep dish pizza. Actual deep dish pizza shown:

As you can see, there is a layer of crust on the bottom and surrounding the rest of the pizza.

How to make the pizza

The crust is made of two layers. The first layer will be n tall and n*3 long. Length is the number of characters (including spaces) in the highest line. So given n is 1, the first layer would look like this:

\_/  1 character tall
 3 characters long

If n is two:

\    /   2 characters tall
 \__/
  6 characters long

Now for the second layer of the crust. It will go outside the first, inner crust so therefore, it will be n+2 characters tall and (n*3)+6) characters long. Given n is one:

\       /  3 characters tall
 \     /
  \___/
   9 characters long (3 underscores, 3 slashes on either side)

If n is two:

\          / 4 characters high
 \        /
  \      /
   \____/
    12 characters long

You would then match up the two highest pairs of \/ with each other for the inner and outer crust. In n is 1:

\ \   / /
 \ \_/ /
  \___/

If done correctly, it would look like a V without the tops with a one character difference between each layer. Speaking of tops, the crust will be joined together by a pair of /\, separated by a line of underscores (n*3)+2 long to complete the crust and pizza.

Examples

If n is 1:

/\_____/\
\ \   / /
 \ \_/ /
  \___/

n is 2:

/\________/\
\ \      / /
 \ \    / /
  \ \__/ /
   \____/

n is 3:

/\___________/\
\ \         / /
 \ \       / /
  \ \     / /
   \ \___/ /
    \_____/

Winning Criterion

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

JavaScript (ES6), 136 bytes

f=
n=>"/\\"+(r=s=>s[0][0].repeat(n-1)+s)`_`+r`_`+r`___/\\
`+r` `.replace(/ /g,"$`\\ \\$`   $'$'$'/ /\n")+r` \\ \\`+r`_/ /
`+r`  \\`+r`___/`
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>

The whole pizza is very repetitious so the r function (designed as a tagged template literal) repeats the first character of its input n times. This handles the top and bottom two lines of the pizza. The middle is repeated by replacing a string of blanks; the $` and $' subsitutions automatically correspond to increasing and decreasing numbers of blanks thus positioning the \ \ and / / appropriately.


Every prime bit must alternate A program is bit primed if bits in prime positions must alternate between zero and one, starting with one.

For example, this is a template for a bit primed program with [0..47] bits.

..10.1.0 ...1.0.. .1.0...1 .....0.1 .....0.. .1.0...1
01234567 89012345 67890123 45678901 23456789 01234567

Create a bit primed program that takes as input a string and checks if the string is bit primed. The string will be in ASCII and it will be a maximum of 1000 chars.

Rules

For the purposes of this challenge, the bit string for ABCD is

01000001 01000010 01000011 01000100

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


String generator based on a wildcard Your task, if you accept it, is to make a string generator that generates strings based on a wildcard.

You can make a function or a full program that receives 1 argument and sends to the standard output/console a string that matches.

Wildcard characters and sequences:

* produces 0 or more random characters
? produces exactly 1 random character
[] detonates a group and produces any one of the characters from the group, exactly once.
[]* produces at least 0 of the characters from that group
[]? produces any one of the characters from that group, at most once
[]{n} produces n characters in that group
Anything else is a literal string

The supported characters to return are a-z, A-Z and 0-9.
Casing doesn't matter.

You can do whatever you want with invalid input.

Examples:

f('a[d-f]{3}') //return 'addd', 'adde', 'addf' ...

f('a*') //returns 'a' or anything starting with 'a'

f('[bt]est') //returns 'best', 'test'

Scoring:

Shortest code in bytes wins.
-10% bonus if you support symbols
-10% bonus if you implement multiple matches, inside each group (e.g.: [ae,c-d,0-5])
-20% bonus if you implement negated group (e.g.: [^a-f] returns anything that doesn't start with a-f)
-10% if you support at least 3 regex character classes (e.g.: \d,\s,\D)
Standard loopholes are not allowed!

Any doubts, feel free to ask in a comment.

Python 3, 511 bytes - 10% = 459.9
It's early morning over here so golfing mode hasn't quite kicked into my system yet, but it was a really fun-looking problem so I thought I'd try it anyway.

from random import*
C=0
r=input()
i=0
S=""
Q=""
while i<len(r):
 c=r[i]
 if i<len(r)-1:d=r[i+1]
 if"]"==c:
  C=0
  if d not in"*?{":S+=choice(Q)
 elif"["==c:C=1;Q=""
 elif"*"==c:
  while random()>.2:S+=choice(Q)
 elif"?"==c:S+=choice(Q)*randint(0,1)
 elif"{"==c:
  a=""
  while r[i+1]!="}":a+=r[i+1];i+=1
  S+="".join(choice(Q)for _ in range(int(a)))
 elif"}"!=c:
  if"-"==d:Q+="".join(chr(x)for x in range(ord(c),ord(r[i+2])+1));i+=2
  else:
   Q=C*Q+c
   if not C and d not in"*?{":S+=choice(Q)
 i+=1
print(S)

I'm claiming the "multiple matches, inside each group" bonus. You can try it out like so:
[abA-C0]*


Build a typing speed test / measuring CPM The Rules
It's time to build a typing speed test in your language of choice!
1. You provide a file with a dictionary of choice (every 'word' in it must be newline delimited). Pipe it in via stdin or provide it's name as a command line argument.

a
able
about
above
absence
...

2. Pick 10 random words from the file (no duplicates must be allowed) and print them out in the following manner:

-> direct
-> ground
-> next
-> five
...

3. Start measuring the time spent from now on!
4. Let the user type all of the ten words as fast as possible (ended with a carriage return). Print OK when you have a match, print WRONG when we have a typing mistake (or the word was already succesfully typed in this run).
5. Stop the clocks! Now print the CPM (Caracters per minute) benchmark, which is calculated as follows: (sum of the characters of the chosen words / time spent typing (seconds)) * 60. Round to the nearest integer and reproduce the following (sample) output:

--> You have scored 344 CPM!

A sample run

-> settle
-> side
-> open
-> minister
-> risk
-> color
-> ship
-> same
-> size
-> sword
settle
OK
side
OK
open
OK
# ...................... some lines snipped ......................
word
WRONG
sword
OK
--> You have scored 298 CPM!

The winner
This is code colf, the shortest entry (in source code character count) wins, have fun!

Bash - 217 212 199 196 chars

Not gonna win but it was fun

declare -A W
for w in `shuf -n10`;do C+=$w;echo -\> $w;W[$w]=OK;done
SECONDS=0
for((;${#W[*]};));do read r;echo ${W[$r]-WRONG};unset W[$r];done
echo --\> You have scored $((60*${#C}/SECONDS)) CPM!

Under 200 chars now!

Takes wordlist file as an argument
Now takes word list on standard input. Paste it in the terminal and press ^D

Implemented suggestion from manatwork


Syllables in a Number Make a program/function which takes in an integer from 0 to 999999999999 (inclusive) as input and returns how many syllables it has when spoken in English. Make your code short.

Specification

A billion is a thousand million, a trillion is a million million, etc.
A million has three syllables -- it's mill-ee-on, as opposed to mill-yon. Pronounce all -illions like this.
Numbers like 1115 are 'one thousand, one hundred and fifteen'. The 'and' counts as a syllable.
0 is zero. That's two syllables.

I know the specification seems mishmash in terms of which standards are used (British or American, mainly) -- it's what I and everyone I know use. I would change it so it's consistent, but someone's already answered...

Test Cases

> 0
2
(zero)

> 100
3
(one hundred)

> 1000001
6
(one million and one)

> 1001000001
10
(one billon, one million and one)

> 7
2
(seven)

> 28
3
(twenty-eight)

> 78
4
(seventy-eight)

> 11
3
(eleven)

> 1111
10
(one thousand, one hundred and eleven)

> 999999999999
36
(nine hundred and ninety-nine billion, nine hundred and ninety-nine million, nine hundred and ninety-nine thousand, nine hundred and ninety-nine)

Python 2, 232 bytes

def f(a):o=map(int,format(a,",").split(","));print(a%100>0)*(a>1000)+sum((k%100>0)*(k/100>0)for k in o[:-1])+sum((k>99)*2+`k`.count('7')+(k/10%10>0)+3-`k+1000`.count('0')for k in o)+sum((0<o[~k])*(5-k)*k/2for k in range(len(o)))or 2

Try it online!

This still has some potential for golfing, maybe in a lambda.
The function splits the input into groups of three digits, each of which have a certain number of syllables. Luckily, every digit is 1 syllable except for 7. Every tens-place adds an extra 1 syllable to the number of syllables of the digit except for 1, which adds 0 (-teen or ten).

Ungolfed:

def f(k):
    a=k
    if a==0:return 2
    o=[]
    while a>0:
        o.append(a%1000)
        a/=1000
    o=o[::-1]
    return \
int(o[-1]%100>0 and len(o)>1)        +len('+1 if first group of three have "and"'[0:0])+\
sum(\
  [int(k%100>0 and k/100>0)        +len('+1 if rest have "and"'[0:0])\
for k in o[:-1]])+
sum(\
  [int(k>99)*2                      +len('have "hundred"'[0:0])\
  +str(k).count('7')               +len('+1 for "se-ven"'[0:0])\
  +(k/10%10>0)                    +len('+1 for "-ty" e.g. nine-ty'[0:0])\
  +3-str(k+1000).count('0')        +len('+1 for each number'[0:0])\
for k in o])+\
sum(\
  [int(o[-(k+1)]>0)*([0,2,3,3][k])  +len('add 2 if "thousand", add 3 if "million", add 3 if "billion"'[0:0])\
for k in range(len(o))])

-12 bytes thanks to @Mr.Xcoder


Hardcoding the Cops and Robbers (Cops) This is a cops-and-robbers challenge. The robbers' thread is here.

An interesting question to think about is the following:

  If I have a sequence of numbers how many of them do I have to provide before it is clear what sequence I am talking about?

For example if I want to talk about the positive integers in order starting from \$1\$, I could say \$1,2,3, \dots\$, but is that really enough?

I have one way of answering this question, and being a code-golfer it involves code-golf.  You have provided enough terms of a sequence if the shortest code that produces those terms produces all the terms of the sequence.  If we think about this in terms of code-golf, this would mean you have provided enough test cases such that the shortest code that passes the test-cases does the desired task.

Challenge

This challenge is a cops-and-robbers challenge.  In which cops will be presenting test-cases and robbers will have to find a shorter way to spoof the test-cases other than the intended sequence. Cops will present the following things:

A piece of code that takes a non-negative integer as input and produces an integer as output.    This code will define your sequence. Your code does not need to support 0 as an input, opting to instead take 1 as the smallest input.  It should be clear if this is the case in your answer.
Any relevant platform or language requirements that might affect the output, for example the size of longint.
A number \$n\$, along with the first \$n\$ terms of the sequence as calculated by the code.  These will act as "test-cases".

You are encouraged to explain what your sequence does and link OEIS if it exists, however it is your code that defines the sequence not the description.

Robbers will be finding a program in the same language that is shorter than the one presented and passes all the test cases (produces the same output for the first \$n\$ inputs as the cop's code). The robber's code must also differ in output from the cop's program for some number larger than \$n\$.

Cops must be able to crack their own answers before submitting them.

After one week a cop may reveal their crack and mark their answer as Safe.  Answers marked as such can no longer be cracked.

Scoring

Cops answers will be scored by the number of bytes with fewer bytes being better. Cracked answers score an infinite score.

cQuents, 4 bytes (Cracked)

"::$

Try it online!

Here are eight (n=8) cases:

1 1
2 12
3 123
4 1234
5 12345
6 123456
7 1234567
8 12345678

Code explanation:

"      Stringify sequence (join on "", remove it and see what happens)
 ::    Given input n, output all items in the sequence up to and including n
   $   Each item in the sequence equals the index

So the sequence is 1,2,3,4,5 ..., it is joined on "" so it becomes 12345 ..., and :: means that it prints up to the input.


Automatic house-builder Automatic house building nanobots have been fabricated, and it's your job to code them.

Here is the house created by input 7 4 2

  /-----/|
 /     / |
|-----|  |
|     |  |
|     | /
|_____|/

The input is a string containing the house's dimensions.

7 is the width.

|_____|

---7---

4 is the height.

|
|
|
|

2 is the depth

 /
/

Given this input, can you create the house?

Your code must be as small as possible so that it can fit in the robots.

Notes

The smallest dimensions you will be given as input are 3 2 2. Your program can do anything with dimensions that are smaller than 3 2 2.

Testcases

3 2 10

          /-/|
         / / |
        / / /
       / / /
      / / /
     / / /
    / / /
   / / /
  / / /
 / / /
|-| /
|_|/

Python 2, 128 bytes

w,h,d=input();i=d
while-i<h:c='|/'[i>0];print' '*i+c+'- _'[(d>i!=0)+(h+i<2)]*(w-2)+c+' '*min(d-i,h-1,w+1,h-1+i)+'/|'[d-i<h];i-=1

Prints row by row. The row indices i count down from d to -h+1.


Single Digit Representations of Natural Numbers Task

Write a program/function that when given a positive integer \$n\$ and a digit \$d\$ which is not 0 outputs a way to represent \$n\$ using only addition, subtraction, multiplication, exponentiation, division, concatenation, parenthesis and the digit \$d\$.

Examples

n =  6, d = 1  =>  (1 + 1) * (1 + 1 + 1)
n =  6, d = 1  =>  1 + 1 + 1 + 1 + 1 + 1
n = 10, d = 1  =>  1 || 1 - 1
n = 12, d = 1  =>  1 || (1 + 1)
n = 64, d = 2  =>  2 ^ (2 + 2 + 2)
n =  1, d = 9  =>  9 / 9

Note: In the examples || represents concatenation

Output Format

Concatenation must be explicit with a separate operator
Output can be a string, list of operations and numbers or a list of lists in place of brackets.
You may choose the precedence of the operators but it must be consistent for all outputs produced by your program/function
Output may be in polish, reverse polish or infix notation but it must be consistent for all outputs produced by your program/function.
You can use custom symbols for representing the digits and operations but the symbols used for representing the digits and operations should be distinct.

Scoring

This is code-challenge, Your score will be

100*B + S

Where B is the number of bytes in the program/function, and S is the sum of the number of times the digit \$d\$ appears in the representation of \$n\$ with the digit \$d\$ as returned by your program/function for all \$n \le 1000\$ and all \$d\$ from 1 to 9

Lowest score wins

Example: if your program is abcd and all representation of \$n\$ returned by your program has 5 occurrences of \$d\$ then its score will be (4 * 100) + (5 * 1000 * 9) = 45400

Rules

Your program/function should run deterministically, so that it always returns the same representation for a given \$n\$ and \$d\$ (and hence always gets the same score).
Your answer must include not only your submission, but also the code you used to calculate the S part of its score. This need not be written in the same language as your submission, and will not be counted towards its byte count. You are encouraged to make it readable.
Your answer must include the precedence of the operators needed to evaluate the outputs produced by your program/function
You must actually run your test program and calculate/verify your score before submitting your entry. If your submission runs too slowly for you to verify its score then it is not qualified to compete, even if you know what its score would be in principle.

Inspired by this video

Python 3, 210 bytes · 100 + 59045 digits = 80045

def f(n,d):
 m={d:d},
 while{n}-{*m[0]}:m={z:(p[x],o,q[y])for p,q in zip(m,m[::-1])for x in p for y in q for z,o in zip([x+y,x-y,x*y,y<9and x**y,x%y<1and x//y,int(f"{x}{y}")],"+-*^/|")if z>0},*m
 return m[0][n]

Try it online!

Scoring

Scoring goes much faster using this modified version that solves 1 through 1000 all at once:

def f_gen(d):
 m={d:d},
 while 1:yield from m[0].items();m={z:(p[x],o,q[y])for p,q in zip(m,m[::-1])for x in p for y in q for z,o in zip([x+y,x-y,x*y,y<9and x**y,x%y<1and x//y,int(f"{x}{y}")],"+-*^/|")if z>0},*m

def size(expr):
    return 1 if isinstance(expr, int) else size(expr[0]) + size(expr[2])

score = 0
for d in range(1, 10):
    s = set(range(1, 1001))
    for n, expr in f_gen(d):
        if n in s:
            s -= {n}
            score += size(expr)
            print(n, expr)
            if not s:
                break
print(score)


Finish a symmetrical map You are given one-quarter of a map that is symmetrical over the x- and y-axes as input. The program should print the complete map.
The map can contain the following characters: -+/\|., and they should be turned as expected. The in data is always rectangular and small.
Example
$ cat in
+---
|./.
|/..

$ ./solution < in
+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+

Shortest code wins.

Canvas, 5 4 bytes
║Ｑ↷↷

First Canvas answer, so let's start with an easy one. :)
-1 byte thanks to @dzaima.
The slashes are automatically converted when mirroring or rotating in Canvas.
Could have been 1 byte ╬ (Try it online), but unfortunately it also transforms the dots . to single quotes ' when mirroring horizontally.
Try it online.
Explanation:

         # (Take the multi-line input implicitly as canvas object)
║        # Palindromize the canvas object (without overlap)
 Ｑ      # Output it with a trailing newline (without popping)
  ↷↷    # Rotated the canvas object that's still on the stack by 90 degrees twice
         # (and output it implicitly as well at the end)


Contaminated Squares Introduction
Let's observe the following square, consisting only of the digits 0 - 9:
1034
4167
8414
3542

The outer shell of this square is:
1034
4  7
8  4
3542

It contains zeros, so we need to peel off the outer shell, leaving:
16
41

The outer shell of this square is:
16
41

It does not contain any zeros and is therefore a non-contaminated square. So basically, the definition of a non-contaminated square is when the outer shell of the square contains no zeros.
The Task
Given a square of digits (containing only non-negative integers) in any reasonable format, output the largest non-contaminated square by constantly peeling off the outer shell, in any reasonable format.
Test cases
Test case 1:
Input         Output

1234          1234
2345          2345
3456          3456
4567          4567

Test case 2:
Input         Output

123           123
204           204
346           346

Test case 3:
Input         Output

101           1
010
101

Test case 4:
Input         Output

000           (none)
000
000

This is code-golf, so the submission with the least amount of bytes wins!

JavaScript, 105 97 bytes
Saved 8 bytes thanks to @Patrick Roberts!
l=a=>a.slice(1,-1)
p=a=>l(a).map(l)
c=a=>a.join``.replace(/[^0]/g,"")
s=a=>c(p(a))<c(a)?s(p(a)):a

Defines function s, which returns a 2D array of integers when provided a 2D array of integers as input.
How it Works

function l: given an array a, returns a copy without its first and last indexes.

function p: given a 2D array a, calls l to remove the first and last row, then for each remaining row calls l to remove the fist and last column. This performs the onion peeling.

function c: given a 2D array a, returns a string that only contains the 0s in the stringified form of a.

function s: given a 2D array a, calls c on the peeled form of the array given by p, and on the array itself. Compares these strings lexicographically to determine if the peeled form has less 0s than the original. If it does, then the original is contaminated, so call s recursively on the peeled form. Otherwise return the original.


Analyze overhanded shuffles Rod is moderating a card game between two players: George and Tim. Currently, Tim is shuffling the cards. Rod suspects that Tim is trying to cheat, so he needs your help to check that the shuffle is fair.

Tim is doing the overhanded shuffle: he cuts a pile of cards from the bottom of the deck, then cuts various parts from the top of the pile onto the top of the deck, and repeats the process a few times.

Rod is eagle-eyed and can see exactly how many cards Tim is cutting each time, however he can't calculate and keep track of the cards as fast as Tim is shuffling. This is where you come in: Rod would like you to write a program or function that gets the detailed shuffling information and determines whether the shuffle is fair, weak or a trick.

If after shuffling, less than 25 pairs of adjacent cards remain adjacent (in the same order), then the shuffle is fair and the game can go on.
If at least 25 (but not all) pairs of adjacent cards remain adjacent, then the shuffle is weak and Rod will bonk Tim over the head and ask him to shuffle some more.
If all the cards remain in the same position at the end, then Tim is obviously cheating and Rod will whack him with a large trout.

This is code golf, so the shortest code wins.

Input:

You will get a series of numbers between 0 and 52 (both exclusive) separated by space, on several lines, where each line represents a round of shuffling that begins and ends with all the cards piled together.

On each line, the first number is the number of cards Tim cuts from the bottom of the deck, and each subsequent number is a number of cards he drops from his hand onto the top of the deck. If any cards remain after the last number on a line, you should assume that Tim puts them on top of the deck.

The input is guaranteed to be valid. There is at least one line of numbers, and each line contains at least 2 numbers. The first number on each line is not smaller than the sum of all the other numbers on the same line. A trailing newline is optional, you may assume that the input has one or that it doesn't have one.

Output:

Your program should print/return "fair" if the shuffle is fair, "weak" if the shuffle is weak and "trick" if Tim is keeping all the cards in the same order. A trailing newline is optional.

Example:

The deck is assumed to have 52 cards, but for demonstration purposes, I'll use a smaller deck of 10 cards.

Input:

5 3 1
4 2 2

Initial deck, viewed from the top: 0 1 2 3 4 5 6 7 8 9
5 ➜ 0 1 2 3 4 (5 6 7 8 9 in hand)
3 ➜ 5 6 7 0 1 2 3 4 (8 9 in hand)
1 ➜ 8 5 6 7 0 1 2 3 4 (9 in hand)
end of line ➜ 9 8 5 6 7 0 1 2 3 4
4 ➜ 9 8 5 6 7 0 (1 2 3 4 in hand)
2 ➜ 1 2 9 8 5 6 7 0 (3 4 in hand)
2 ➜ 3 4 1 2 9 8 5 6 7 0
4 pairs remain adjacent: (3 4) (1 2) (5 6) (6 7)

Test cases:

43 5 5 5 5 5 5 5 5
43 5 5 5 5 5 5 5 5
43 5 5 5 5 5 5 5 5

Output: fair

43 5 5 5 5 5 5 5 5
43 5 5 5 5 5 5 5 5
43 5 5 5 5 5 5 5

Output: weak

29 24
19 18
38 2 1 8 13 6 4
47 15 16 5 2 1 7
34 22 9 3
44 9 10 11 3 1 7
33 18 4 2 3 3

Output: fair

24 6 12 4
25 3 19
36 4 25 2
19 11 1 3
15 9 3
37 5 27

Output: weak

26 13
26 13
26 13
26 13

Output: trick

50 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

Output: weak

50 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
50 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

Output: trick

50 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
49 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

Output: fair

Requirements:

If you write a function, it can either read from the standard input or receive the input as a single string parameter. Also, the function can either print out the output or return it.
The program must be runnable in Linux using freely available software.
The source code must use only ASCII characters.
No standard loopholes.

CJam, 76 75 bytes

52,qN/{[~](52\-@/(\e_@{/(@+\e_}/\+}/2ew::m2f/0-,_!\26>-"weak trick fair"S/=

Try it online in the CJam interpreter.


Using Symbols for Letters Input: A single word as a string (matches [a-zA-Z]+).  If the input doesn't follow these guidelines, print "Error" (but no error should be thrown)

Output: The NATO pronunciation of the word.  Print out a space separated list of the NATO word that matches each letter of the input word.  Trailing white space is acceptable.

Restrictions:
Your source code must contain each ASCII character from 32 (space) to 126 (tilde) in that order, excluding numbers and letters.  You may have anything you like mingled in between the required characters, but the required characters must be there and in order. (If ABC were the required characters, YA8iBC3 or C6ABn#C would be valid, but A7CRT or 8mdB9AC would not be).

Standard loopholes and built-ins for generating the NATO pronunciation are not allowed.

References:
The NATO pronunciation is as follows: Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliet Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey Xray Yankee Zulu.

The required symbols (in order) are as follows: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Test cases: (The quotation marks won't be part of input, but are included to show whitespace)

"a"            => Alpha
"Z"            => Zulu
"twig"         => Tango Whiskey India Golf
"PPCG"         => Papa Papa Charlie Golf
"camelCase"    => Charlie Alpha Mike Echo Lima Charlie Alpha Sierra Echo
"Quebec"       => Quebec Uniform Echo Bravo Echo Charlie
""             => Error
" "            => Error
"()"           => Error
"twig "        => Error
" PPCG"        => Error
"one+two"      => Error
"Queen bee"    => Error

This is a code-golf, so the shortest code in your favorite language wins!

JavaScript (ES6), 268
An anonymous function

i=>[...i].every(c=>(c=parseInt(c,36))>9?o+="AlphaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu".match(/[A-Z][^A-Z]+/g)[c-10]+' ':0,o='',!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~")?o:'Error'


Playing the Name Game Write a program to play the name game.

Input

Your program should accept a single name as input from the user in some way (e.g read from standard input or as a command-line argument). You can assume that the name is a single word consisting of an upper case letter followed by one or more lower case letters.

Output

Your program must print the rhyme for the given name, as explained in the song, by filling out the following template:

(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!

Here, (X) is the original name, and (Y) is the name in lower case with any initial consonants removed.

There is one exception, however. If the original name began with m, f or b, it should be written without this letter on the corresponding line. E.g. if the name was Bob, the "b" line should end with bo-ob. Note that in this case, any other consonants are kept, so for Fred it's fo-red, not fo-ed.

Examples

Shirley:

Shirley, Shirley, bo-birley
Banana-fana fo-firley
Fee-fi-mo-mirley
Shirley!

Arnold:

Arnold, Arnold, bo-barnold
Banana-fana fo-farnold
Fee-fi-mo-marnold
Arnold!

Bob:

Bob, Bob, bo-ob
Banana-fana fo-fob
Fee-fi-mo-mob
Bob!

Fred:

Fred, Fred, bo-bed
Banana-fana fo-red
Fee-fi-mo-med
Fred!

Scoring

Shortest code wins.

vi, 118 115

Y2PA,<ESC>Ypj~Y2PIbo-b<c-o>wBanana-fana fo-f<c-o>wFee-fi-mo-m<c-o>2$!<ESC>HJJ:%s/\vo-(([bfm])\2([^aeiou]*))?([bfm]?)[^aeiou]*/o-\3\4
ZZ

The code includes 5 control characters, which I've put in brackets. Each only counts as a single character towards the character count.

EDIT: Moving the first join (J) to later and changing the paste-before (P) to a paste-after (p) saved me 1 character. Also, not capturing the o- in the regex saved me 2 more characters.


Find the needle in the haystack Given a rectangular haystack of size at least 2x2 composed of all the same printable ASCII characters, output the location (counting from the top-left) of the needle which is a different character.

For example, if the following haystack is input:

#####
###N#
#####
#####

The output should be 3,1 when zero-indexed (what I'll be using in this challenge) or 4,2 when one-indexed.

The haystack can be composed of any printable ASCII character:

^^^
^^^
^N^
^^^
^^^
^^^

output: 1,2

and the needle will be any other printable ASCII character:

jjjjjj
j@jjjj
jjjjjj

output 1,1

It's also possible to have a needle in the corner:

Z8
88

output 0,0

88
8Z

output 1,1

or to have the needle at the edge:

>>>>>>>>>>
>>>>>>>>>:
>>>>>>>>>>

output 9,1

Rules and Clarifications

Input and output can be given by any convenient method. This means you can take input as a list of list of characters, as a single string, etc.
You can print the result to STDOUT or return it as a function result. Please state in your submission what order the output is in (i.e., horizontal then vertical, as used in the challenge, or vice versa).
Either a full program or a function are acceptable.
You do not get to pick which characters to use. That's the challenge.
The haystack is guaranteed to be at least 2x2 in size, so it's unambiguous which is the needle and which is the hay.
There is only ever one needle in the input, and it's only ever one character in size.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

R, 49 47 44 bytes

function(m,`?`=which)m==names(?table(m)<2)?T

Try it online!

Takes input as a matrix, returns 1-indexed coordinates


Implement the Universal Machine emulator The goal is to write a full program that emulates the Universal Machine from ICFP 2006 with the shortest code. The Universal Machine has a very simple instruction set explained here. The emulator has to read a filename from command-line argument, and run the file as the program, so your language has to support command-line arguments and stdin/out in some way. The emulator has to complete the sandmark within a reasonable time (not decades).
Here's a short explanation of the instruction set:

  The machine has eight registers each holding an 32-bit unsigned integer.
  The machine holds an indexed set of arrays of 32-bit unsigned integer cells.
  Shortly speaking, the allocation instruction returns an opaque 32-bit uint which is the handle to the created array, which has a static size, and holds 32-bit uint elements.
  The 0'th array denotes the program. It is loaded from a big-endian file on startup.
  There is also an Instruction Pointer which points to a cell in the 0 array.
  On each step, an instruction is read from the cell the Pointer points to, and the Pointer is inceremented before anything is done.
  The 4 most significant bits represent the opcode.
  If the opcode is 13, then the next 3 bits represent the register, and the other 25 represent the number that is written into the said register.
  Otherwise the 9 least significant bits represent three registers, say, A, B, and C, where C is represented by the 3 least significant bits.
  Then depending on the opcode, the following happens:
  0. A = B unless C == 0
  1. A = B[C]
  2. A[B] = C
  3. A = B + C
  4. A = B * C
  5. A = B / C
  6. A = ~(B & C)
  7. The emulator exits
  8. B = allocate(C)
  9. deallocate(C)
  10. output a character from C to stdout
  11. input a character from stdin into C
  12. copy the array B into the 0 array and set the Pointer to C

I have written a needlessly complex but totally fast implementation (ab)using x86_64 jitted assembly (the fun starts in emit()), which would for sure help you if you misunderstand some of the Machine's aspects.

PHP: 443 416  384 bytes

<?php @eval(ereg_replace('[U-Z]','$\0',strtr('for(Y=[unpack("N*",join(file($argv[1])))];;A|=0){{W=Y[V=0][++U]
C&&A=B
A=Y[B][C+1]
Y[A][B+1]=C
A=B+C
A=B*C
A=bcdiv(PB),PC))*1
A=~B|~C
die
B=++Z
unset(Y[C])
echo chr(C)
C=fgetc(STDIN);C=ord(C)-(C=="")
Y[0]=Y[B|0];U=C
X[W>>25&7]=W&33554431;}}',['
'=>';}if((W>>28&15)==V++){',A=>'X[W>>6&7]',B=>'X[W>>3&7]',C=>'X[W&7]',P=>'sprintf("%u",'])));

*Revamped again*. It's as small as I can possibly get it now. I kept some variables down the far end of the alphabet so that the regex that inserts the $ signs doesn't mangle the STDIN constant, so here's a little glossary:

U: instruction pointer
V: index of opcode that's currently being tested
W: current instruction word
X: the 8 general purpose registers
Y: main memory (each block is 1-based, since that's how unpack() returns arrays)
Z: id of next free memory block (will eventually overflow, but the sandmark only uses ~92 million)
A,B,C are the registers of the current instruction as in the spec

Unsigned division is a subtle nuisance (the *1 is needed to ensure that large numbers cast back to the correct int) but the rest of the arithmetic is easy to keep 32-bit by ORing the arithmetic register with 0 (A|=0) after each instruction.

I found this project really interesting but striving to minimize the character count made it slow and inelegant, so I also made a simple (not golfed) Java version, that can complete the sandmark in a few minutes instead of taking all day:

import java.io.*;
import java.util.HashMap;

public class UniversalMachine {
    public static void main(String[] args) throws IOException {
        if (args.length == 0) {
            System.err.println("Program not specified.");
            System.exit(1);
        }

        int[] program;
        try (RandomAccessFile raf = new RandomAccessFile(args[0], "r")) {
            program = new int[(int)(raf.length() / 4)];
            for (int i = 0; i < program.length; i++) {
                program[i] = raf.readInt();
            }
        }

        HashMap<Integer,int[]> memory = new HashMap<>();
        memory.put(0, program);
        int nextMemKey = 1;

        int[] R = new int[8]; // Registers
        int IP = 0; // Execution Finger (Instruction Pointer)

        loop: for (;;) {
            int ins = program[IP++];
            int op = ins >>> 28;
            if (op == 13) { // Orthography
                int A = (ins >> 25) & 7;
                int num = ins & 0x01FF_FFFF;
                R[A] = num;
            } else {
                final int A = (ins >> 6) & 7;
                final int B = (ins >> 3) & 7;
                final int C = (ins >> 0) & 7;
                switch (op) {
                case 0: // Conditional Move
                    if (R[C] != 0) R[A] = R[B];
                    break;
                case 1: // Array Index
                    R[A] = memory.get(R[B])[R[C]];
                    break;
                case 2: // Array Amendment
                    memory.get(R[A])[R[B]] = R[C];
                    break;
                case 3: // Addition
                    R[A] = R[B] + R[C];
                    break;
                case 4: // Multiplication
                    R[A] = R[B] * R[C];
                    break;
                case 5: // Division
                    R[A] = (int)((R[B] & 0xFFFF_FFFFL) / (R[C] & 0xFFFF_FFFFL));
                    break;
                case 6: // Not-And
                    R[A] = ~(R[B] & R[C]);
                    break;
                case 7: // Halt
                    break loop;
                case 8: // Allocation
                    // note: must use C before setting B, as they may be the same reg
                    memory.put(nextMemKey, new int[R[C]]);
                    R[B] = nextMemKey++;
                    break;
                case 9: // Abandonment
                    memory.remove(R[C]);
                    break;
                case 10: // Output
                    System.out.print((char)R[C]);
                    break;
                case 11: // Input
                    R[C] = System.in.read();
                    break;
                case 12: // Load Program
                    IP = R[C];
                    if (R[B] != 0) {
                        memory.put(0, program = memory.get(R[B]).clone());
                    }
                    break;
                }
            }
        }
    }
}


Rank a list of scores with "skips" Given a list of scores (non-negative integers) pre-sorted from greatest to least:

[ 10, 10, 6,  6,  4,  0]

Assign each score an integer rank, beginning with 1 and ascending, such that equal scores have the same rank (i.e. they are tied):

[ 1, 1, 3, 3, 5, 6 ]

In the case of ties, ranks are "skipped," e.g. since the first and second-greatest scores (10 and 10) are tied, they both have rank 1, and rank 2 is "skipped," so the third-greatest score (6) has rank 3.

Output a list of non-descending ranks corresponding to the input scores.

Examples

In:  10 10  6  6  4  0
Out:  1  1  3  3  5  6

In:  10  9  8
Out:  1  2  3

In:   0  0  0
Out:  1  1  1

In:  16 15 15 12 11 11 10  9  9  9  8  2  2  2  0
Out:  1  2  2  4  5  5  7  8  8  8 11 12 12 12 15

Input

Assume all scores will be between 0 and 1,000 inclusive, and the input will have no more than 500 scores. Input can be in whatever format is convenient for your language of choice (including but not limited to STDIN, arguments to a function, an array already stored in a variable, etc.).

Output

Return or store in a variable the resulting ordered list of ranks, or write it to STDOUT in a human-readable way (e.g. 1 2 3, [1,2,3], 1\n2\n3\n, and { 1, 2, 3 } are all fine; 123 is not, for want of a delimiter). The input scores may be stored/printed along with their corresponding output ranks, but that's not required.

Restrictions

You may use any standard library your language offers. Standard loopholes apply.

Winning conditions

This is code-golf, so the smallest program (in bytes) wins. In case of a tie, the answer with the most votes wins.

Notes

This is based on a Ruby question on SO that generated some interesting answers, including one very short one. I encourage you to come up with your own solutions before looking there.

T-SQL (40)

SELECT RANK()OVER(ORDER BY B DESC)
FROM @

Assume @ is a table containing the scores as rows.


Almost Illegal Strings, Mark II (Cops) Edit 2020-11-06: This challenge has been edited with new provisions to encourage participation. The edits have been bolded for emphasis.

Welcome to a cops and robbers version of Find an Illegal String.
An illegal string is "a string of characters that cannot appear in any legal program in your programming language of choice" (from the linked post).
For this challenge, we will define an almost illegal string, which is a string of characters that is very hard, but not impossible, to include in a valid program.
The Cops' Challenge

Choose a programming language, and choose an 'almost illegal string' - this is a sequence of characters that is very hard to include in a valid program without causing it to error.
Write a program that contains the 'almost illegal string' as a contiguous substring that does not error.
 Optionally, you may also specify a set of banned characters. These are characters that do not appear in your program, except in the 'almost illegal string'. (Therefore: banned characters can still appear inside the almost illegal string)

That's it! You will reveal the programming language, the almost illegal string, and the set of banned characters, and challenge robbers to write a program that contains the illegal string but does not error.
For the purposes of this challenge, we define 'does not error' as:

Your program exits with exit code 0.
Your program does not print any output to standard error.
Your program may print anything to standard output, if you wish, but it does not have to.
If (and only if) your language always prints output to standard error regardless of the program, such as debugging or timing information, you may instead design a program that only outputs this to standard error. If you are making use of this clause, mention it in your cop post.

The Robbers' Challenge
Find an uncracked answer. Write a program in the language specified that contains as a contiguous substring the almost illegal string specified and does not error. Your program may not use any character in the set of banned characters, unless it is part of the almost illegal string. Your program does not need to be exactly what the cop had in mind. Post an answer to the robber's thread and leave a comment on the cops' answer to crack it.
Clarifications

If your cop answer requires a specific operating environment or version, you must specify this in your answer.
The cop's almost illegal string that they reveal is to be interpreted with respect to the standard encoding for the language's interpreter. For most programs, this will be UTF8.
Solutions should not take any input (via standard input, argv, or any other source) and may assume no such input is given.
Solutions must terminate in a finite amount of time. This means entering an infinite loop and getting killed by TIO's 60 second timeout is not a valid solution.
Cops should make sure if their almost illegal string contains leading or trailing newlines that it is very clear it does so. Robbers should carefully note any leading or trailing newlines in a cop's post.

Formatting hint
The clearest way to include leading or trailing newlines is to use the backtick syntax for your post:
```

foo

```

Renders as:

foo

To remove any ambiguity, explicitly mention the leading/trailing newlines in your post.
Scoring
After 10 days without a crack, a cop can mark their answer as safe and reveal their solution. Once the cop has revealed their solution, it is no longer able to be cracked.
Cops are scored based on the length (in bytes) of their almost illegal string in their safe answer(s), with lower being better.
Robbers are scored by the number of answers they crack, with higher being better.

Example
Python 3, 5 bytes
Illegal string:
"'1/0

Banned characters:
#'

Python 3, cracks example's answer
Program:
""" "'1/0 """

The idea is that we can just comment out the string, since " is not banned.

Python 2, 5 bytes (cracked by tsh)

bin()

Try it online!
Banned: all characters except alphanumeric characters
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

So, you're allowed the above characters and nothing else (in addition to bin() itself).
(This idea isn't mine, I remember it from an earlier challenge, but I don't remember who deserves credit for it.)


Count the contiguous submatrices Migrated from chat
Given two non-empty non-negative integer matrices A and B, answer the number of times A occurs as a contiguous, possibly overlapping, submatrix in B.
Examples/Rules
0. There may not be any submatrices
A:
[[3,1],
 [1,4]]
B:
[[1,4],
 [3,1]]
Answer:
0
1. Submatrices must be contiguous
A:
[[1,4],
 [3,1]]
B:
[[3,1,4,0,5],
 [6,3,1,0,4],
 [5,6,3,0,1]]
Answer:
1 (marked in bold)
2. Submatrices may overlap
A:
[[1,4],
 [3,1]]
B:
[[3,1,4,5],
 [6,3,1,4],
 [5,6,3,1]]
Answer:
2 (marked in bold and in italic respectively)
3. A (sub)matrix may be size 1-by-1 and up
A:
[[3]]
B:
[[3,1,4,5],
 [6,3,1,4],
 [5,6,3,1]]
Answer:
3 (marked in bold)
4. Matrices may be any shape
A:
[[3,1,3]]
[[3,1,3,1,3,1,3,1,3]]
Answer:
4 (two bold, two italic)

Brachylog (v2), 10 bytes

{{s\s\}ᵈ}ᶜ

Try it online!

I like how clear and straightforward this program is in Brachylog; unfortunately, it's not that short byte-wise because the metapredicate syntax takes up three bytes and has to be used twice in this program.

Explanation

{{s\s\}ᵈ}ᶜ
  s         Contiguous subset of rows
   \s\      Contiguous subset of columns (i.e. transpose, subset rows, transpose)
 {    }ᵈ    The operation above transforms the first input to the second input
{       }ᶜ  Count the number of ways in which this is possible


A bracket amphitheater Specification
Write the shortest possible code in any language that does the following:
It takes two arguments, x and y, and generates x + y lines of text.
The first x lines should consist of y nested pairs of square brackets separated by a space surrounding a single digit, which cycles from 1 to 9, then 0 to 9, etc. from line to line.
The following y lines have the letter X in place of the digit and successively replace the innermost remaining pair of square brackets with spaces. The last line only contains the X, surrounded by spaces.
All output is ASCII.
You may choose to output a final newline (following a space), but you may also choose not to.
You may use either CR, CRLF, or LF as newline sequences.
The last line must contain an appropriate number of spaces following the central X.
The only valid inputs are positive integers. Zero is not a valid input.
You’re free to impose a reasonable, technically-driven limit on input size, even if the problem is solvable without. For instance, if there’s some function available for 16 bit integers that isn’t for bigints for some reason, and using it makes your program shorter, that’s a valid reason for a input size constraint.
Your code may reject invalid input or simply behave in any way on invalid input.
Examples
Example with x = 12, y = 8:
[ [ [ [ [ [ [ [ 1 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 2 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 3 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 4 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 5 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 6 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 7 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 8 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 9 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 0 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 1 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 2 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [   X   ] ] ] ] ] ] ]
[ [ [ [ [ [     X     ] ] ] ] ] ]
[ [ [ [ [       X       ] ] ] ] ]
[ [ [ [         X         ] ] ] ]
[ [ [           X           ] ] ]
[ [             X             ] ]
[               X               ]
                X

Example with x = 5, y = 1
[ 1 ]
[ 2 ]
[ 3 ]
[ 4 ]
[ 5 ]
  X

Example with x = 1, y = 10:
[ [ [ [ [ [ [ [ [ [ 1 ] ] ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ [   X   ] ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [     X     ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [       X       ] ] ] ] ] ] ]
[ [ [ [ [ [         X         ] ] ] ] ] ]
[ [ [ [ [           X           ] ] ] ] ]
[ [ [ [             X             ] ] ] ]
[ [ [               X               ] ] ]
[ [                 X                 ] ]
[                   X                   ]
                    X

Jelly,  33  27 bytes
-1 thanks to caird coinheringaahing (use of ))
Ø[j
%⁵Ç¡);”XÇ¡⁶i”];C$$¦ƬḊ¤G

A full program that accepts \$x\$ and \$y\$ and prints the result.
Try it online!
How?
Ø[j - Link 1, wrap in []: a
Ø[  - list of characters = ['[', ']']
  j - join (with a) = ['[', a, ']']

%⁵Ç¡);”XÇ¡⁶i”];C$$¦ƬḊ¤G - Main Link: x, y
    )                   - for each (v in [1..x]):
 ⁵                      -   ten
%                       -   (v) modulo (10)
   ¡                    -   repeat (y times):
  Ç                     -     call last Link (1) as a monad
                     ¤  - nilad followed by link(s) as a nilad:
      ”X                -   character = 'X'
         ¡              -   repeat (y times):
        Ç               -     call last Link (1) as a monad
                   Ƭ    -   loop until no change, collecting up inputs:
                  ¦     -     sparse application...
                 $      -     ...to (1-based) indices: last two links as a monad:
           i”]          -       first index of character ']' (call this i)
                $       -       last two links as a monad:
               C        -         complement -> 1-i
              ;         -         concatenate -> [i, 1-i]
          ⁶             -     ...of: space character (replaces innermost [] with spaces)
                    Ḋ   -   dequeue (remove the leading one with all []s present)
     ;                  - concatenate
                      G - format as a grid
                        - implicit print


Efficient Robot Movement Disclaimer: The story told within this question is entirely fictional, and invented solely for the purpose of providing an intro.

My boss has gotten a new toy robot, and he wants me to help program it.  He wants to be able to enter simple arrow instructions to get it to move.  These instructions are: ^ (for move forward) < (for turn left), and > (for turn right).  However, now that I've programmed the robot, he wants additional functionality.  He wants me to transform any sequence of arrows he inputs, so that rather than having the robot take the path indicated, it moves to the desired location, indicated by the place it would end up if it had taken the inputted path, as efficiently as possible.  I appeal to you, the members of PP&CG, to help me with this task.

Your Task:

Write a program or function to convert a string made up of arrows into a string that will get to the location indicated by the input as quickly as possible.  Turning takes exactly as long as moving backwards or forwards.

Input:

A string of arrows, as indicated above.  If you wish, different characters may be substituted for the arrows, but be sure to include the fact that you do so in your answer.  All test cases use the arrows normally.

Output:

A string of arrows (or your equivalent characters), that take the robot to the desired destination as efficiently as possible.

Test Cases:

Note that the solutions offered are only possibilities, and that other solutions may be valid.

>^<<^^>^^    -> ^^<^
^^^^>^^^^    -> ^^^^>^^^^
>>>^^^^^^    -> <^^^^^^
>^>^>^>^     -> (empty string)
^<^^<^^<^^^^ -> >^^>^

Scoring:

The robot's memory is limited, so your program must have the lowest byte count possible.

Retina, 103 74 71 bytes

<
>>>
+`(>(\^*>){3})\^
^$1
+`\^(>\^*>)\^
$1
>>(\^*)>(\^+)
<$2<$1
<?>*$

Try it online! Link includes test cases. Explanation:

<
>>>

Turn left turns into triple right turns.

+`(>(\^*>){3})\^
^$1

Reduce all turns modulo 4.

+`\^(>\^*>)\^
$1

Cancel out movements in opposite directions.

>>(\^*)>(\^+)
<$2<$1

Turn a triple right turn back into a left turn. This also handles the case of >>^>^ which needs to become <^<^.

<?>*$

Delete unnecessary trailing turns.


Find patterns in numbers based on the similarity of characters? Task

The task is to write a script that accepts a number from 1 to 20 inclusive. It will then check if the number has a character that is found in every number that was entered before it. If the number has a character in common it will ask for another number. However if the number does not have a character in common with any of the previous numbers the program will halt

You are given the following array which is named as numbers

{"one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"}

Example runs

Say the following number is given

1

There are no previous numbers so it shares a character will every previous number. So the program will ask for another number, let the following number be given

3

one and three both share the character "e" so this is a valid number. So we given another number, let the following number be given

4

four does not share the "e" common to both one and three so this breaks the pattern so the program now stops

Here is another run with just the output of the program shown

5
15
17
3
7
8
2

This script also had the pattern of numbers with the letter "e"  which caused "two" to break the pattern

Python 2, 48 46 bytes

Saved two bytes thanks to @ovs!

s=set(''.join(l))
while s:s&=set(l[input()-1])

Try it online!

Renamed numbers to l. If that's not okay then add 10 bytes for l=numbers.


Count Like a Babylonian Challenge

Given an ASCII representation of a Babylonian number as input, output the number in Western Arabic numerals.

Babylonian Numeral System

How did the Babylonians count? Interestingly, they used a Base 60 system with an element of a Base 10 system. Let's first consider the unit column of the system:

The Babylonians had only three symbols: T (or, if you can render it: ) which represented 1, and < (or, if you can render it: ) which represented 10, and \ (or, if you render it: ) which represented zero.

Note: Technically, \ (or ) isn't zero (because the Babylonians did not have a notion of 'zero'). 'Zero' was invented later, so \ was a placeholder symbol added later to prevent ambiguity. However, for the purposes of this challenge, it's enough to consider \ as zero

So, in each column you just add up the value of the symbols, e.g.:

<<< = 30
<<<<TTTTTT = 46
TTTTTTTTT = 9
\ = 0

There will never be more than five < or more than nine T in each column. \ will always appear alone in the column.

Now, we need to extend this to adding more columns. This works exactly the same as any other base sixty, where you multiply the value of the rightmost column by \$60^0\$, the one to the left by \$60^1\$, the one to the left by \$60^2\$ and so on. You then add up the value of each to get the value of the number.

Columns will be separated by spaces to prevent ambiguity.

Some examples:

<< <TT = 20*60 + 12*1 = 1212
<<<TT \ TTTT = 32*60^2 + 0*60 + 4*1 = 115204

Rules

You are free to accept either ASCII input (T<\) or Unicode input ()
The inputted number will always be under \$10^7\$
The <s will always be to the left of the Ts in each column
\ will always appear alone in a column

Winning

Shortest code in bytes wins.

JavaScript (ES6), 44 bytes

Takes input as an array of ASCII characters.

a=>a.map(c=>k+=c<1?k*59:c<'?'?10:c<{},k=0)|k

Try it online!

How?

The Babylonian Numeral System can be seen as a 4-instruction language working with a single register -- let's call it the accumulator.

Starting with \$k=0\$, each character \$c\$ in the input array \$a\$ modifies the accumulator \$k\$ as follows:

space: multiply \$k\$ by \$60\$ (implemented as: add \$59k\$ to \$k\$)
<: add \$10\$ to \$k\$
T: increment \$k\$
\: do nothing; this is the NOP instruction of this language (implemented as: add \$0\$ to \$k\$)


List array elements which can be summed from other elements Consider an array of unique integers, with an arbitrary length greater than 2. It is sometimes possible to express elements of the array as the sum of at least two other elements. For example, if our array is [2, 3, 1], we can express 3 as the sum 2+1. However, we can't express either 2 or 1 as the sum of other elements.
Additionally, each integer in the list may only be used once in each sum. For example, with [1, 2, 5] we can't express 5 as 2+2+1 (or 1+1+1+2 etc.) as we can only use each element once per sum.
Your program should take such array as input, via any convenient method, and output the elements of the input that are expressible as the sum of other elements. The output may be in any order, as may the input.
This is code-golf, so aim to make your code as short as possible, time / space complexity be damned.
Test cases
input -> output
[2, 3, 1] -> [3]
[8, 2, 1, 4] -> []
[7, 2, 1, 4] -> [7]
[7, 2, 1, 4, 6] -> [6, 7]
[0, 1, -1] -> [0]
[4, 2, -2, 0] -> [2, 0]
[0, 1, 2] -> []

Explanation for the last test case and result: For the purposes of this problem statement, zero cannot be considered the sum of a resulting empty list. Zero can only be in the resulting list IFF two or more other elements of the input list can be added to sum to it.
In other words, do not assume that if 0 is in the input, it should always be in the output - you cannot choose an empty subset to cover it. The problem statement explicitly states that any element in the resulting list must be the sum of other elements.

Jelly, 9 bytes
ɓḟŒPḊ§iµƇ

Try it online!
Essentially, we go over each element, x, of the input, L, and keep it if:

We remove x from the input, call that L'
We then get all non-empty subsets of L', and get the sums of each
Finally, if x is in these sums, we keep it

If 0 is not considered the sum of the empty list, then +1 byte
How it works
ɓḟŒPḊ§iµƇ - Main link. Takes a list L on the left
ɓ      µ  - Group the links between ɓ and µ into a dyad f(L, x):
 ḟ        -   Remove x from L, L'
  ŒP      -   Powerset of L'
    Ḋ     -   Remove the leading empty array
     §    -   Sums of each
      i   -   Index of x, or 0 if not present
        Ƈ - For each element, x, of L, keep it if f(L, x) is true


Traveling Pumpkin Problem Background:
Jack is a pumpkin that enjoys spooking the citizens of the villages near his pumpkin patch every Halloween.  However, every year after someone lights the candle inside of him, he has a limited amount of time to spook everyone before the candle burns out, thus being unable to spook any more villagers because nobody can see him.  In past years, he has only been able to spook a small amount of villages due to his poor decision making, but now that he has you to help him, he will be able to spook as many villages as possible!
Task:
Given a list of village locations and a candle lifespan, output the maximum number of villages Jack can visit.  You do not have to print the path itself.
Input:
The lifespan of the candle and a list of village locations in a Cartesian coordinate system.  The pumpkin patch Jack originates from will always be at 0,0.  You may format the input in anyway you wish.  To simplify Jack's movements, he can only move horizontally, vertically, or diagonally, meaning his candle will either lose 1 or 1.5 (he takes a bit longer diagonally) units of life every move.  The candle burns out when the lifespan is less than or equal to 0.
Output:
An integer equal to the maximum number of villages Jack can visit before the candle burns out.
Rules:
This is code-golf, so shortest code in bytes wins.  Standard loopholes are not allowed.
Test cases:
// Format [lifespan] [list of village coordinates] -> [maximum visit-able villages]

4 -1,0 1,0 2,0 3,0 4,0 5,0 -> 3
4 1,1 2,2 3,3 -> 2
5 1,1 2,1 3,1 4,1 5,0 5,1 -> 4

Jelly, 30 29 27 25 bytes
_AṢæ..
0,0ṭṚç2\+\<S
Œ!ç€Ṁ

Try it online!
Apparently Jelly's dot product just ignores a list size mismatch and doesn't multiply the extra elements of the other array, just adds them. Shaves off 2 bytes.
Explanation
_AṢæ..              Helper link to calculate distance. Arguments: a, b
_                     subtract the vertices from each other
 A                    take absolute values of axes
  Ṣ                   sort the axes
   æ..                dot product with [0.5]

0,0ṭṚç2\+\<S        Helper link to calculate max cities. Arguments: perm, max
0,0                   create pair [0,0]
   ṭ                  append that to the permutation
    Ṛ                 reverse the permutation (gets the [0,0] to the beginning)
     ç2\              find distances of each pair using the previous link
        +\            find all partial sums
          <           see if each sum was less than the max
           S          sum to count cases where it was

Œ!ç€Ṁ               Main link. Arguments: cities, max
Œ!                    get permutations of cities
  ç€                  find max cities for each permutation using the previous link
    Ṁ                 take the maximum


Turn Your Program into a Snake! ...or "snakes but not too long".

Inspired by this challenge and this comment.

Task

Write a program or a function that takes no input and outputs its own source code formatted as a snake according
to the rules below:

If your code has any whitespace, it will not be output; it will just be skipped.
There will be one character on each column in the output.
The first character in the code is placed on the first column of line x.
The second character is placed on the second column of either line x, x-1, or x+1. More generally, the nth character (excluding whitespace) goes to the nth column on a line that is one above, one below, or the same as the line on which the previous character went.
The character on the highest line will be on the first line in the output; that is, there are no extraneous leading lines. A single, empty trailing line is allowed.

For example, if the code was from python import snake, the output should look like:

      th
     y  o       s  ke
f  mp    ni po t na
 ro        m  r

or

                    e
                   k
f                 a
 r               n
  om    o im    s
    p  h n  po t
     yt       r

All valid forms of snake should have a nonzero probability of occurring. Your program's source code should contain at least two non-whitespace characters.

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

05AB1E, 47 bytes

4"D34çýSDεXD<X>ŸΩU}W-úζ»"D34çýSDεXD<X>ŸΩU}W-úζ»

Try it online!


Generate *all* coprime tuples Given integers k and n, generate a sequence of n unique k-tuples of pairwise coprime integers. Every such tuple must occur once eventually, that is, for any existing k-tuple of pairwise coprime integers, some n will eventually generate it.
The output may be printed or evaluated in any list/tuple-like form.
Definitions

Two numbers a and b are coprime if gcd(a, b) = 1, i.e. they share no common divisor other than 1.
A tuple of k numbers (a1, a2, ..., ak) is pairwise coprime if every pair of numbers in the tuple is coprime.

Examples
 k =  1, n =  5 -> [[1],[2],[3],[4],[5]]
 k =  2, n =  7 -> [[2,1],[3,1],[3,2],[4,1],[4,3],[5,1],[5,2]]
 k =  3, n = 10 -> [[3,2,1],[4,3,1],[5,2,1],[5,3,1],[5,3,2],[5,4,1],[5,4,3],[6,5,1],[7,2,1],[7,3,1]]
 k =  4, n =  2 -> [[5,3,2,1],[5,4,3,1]]
 k =  5, n =  0 -> []

Notes

Standard code golf rules, shortest code wins.
k is assumed to be positive, and n non-negative.
The numbers within each tuple must be positive, distinct, and may appear in any order.
Uniqueness is up to ordering: e.g. (1,2,3) is the same as (1,3,2).
Good luck and have fun!

05AB1E, 13 bytes

I think it has been 389 days since I last posted something here haha. There is definitely some golfing potential left in this program.

Code

Uses the 05AB1E-encoding.

∞æ¹ùʒPy.¿Q}²£

Try it online!

Explanation

It is worth noting that for two numbers \$n, m \in \mathbb{Z}^+\$ that:

$$
\tag{1} \label{1}
\gcd(n, m) \cdot \text{lcm}(n, m) = n \cdot m
$$

This means that for two numbers \$n, m \in \mathbb{Z}^+\$ where the \$\gcd(n, m) = 1\$, we can conclude that the \$\text{lcm}(n, m) = n \cdot m\$.

Furthermore, the \$\gcd\$ function is a multiplicative function, which means that if \$n_1\$ and \$n_2\$ are relatively prime, then:

$$
\gcd(n_1 \cdot n_2, m) = \gcd(n_1, m) \cdot \gcd(n_2, m)
$$

From this, we obtain the fact that:

$$
\tag{2} \label{2}
\gcd(a, bc) = 1 \iff \gcd(a, b) = 1 \wedge \gcd(a, c) = 1
$$

Let us denote a \$k\$-tuple of positive integers as \$S = \{x_1, x_2, \dots, x_k\}\$. A set \$S\$ is pairwise coprime, if and only if:

$$
\tag{3} \label{3}
\forall a, b \in S \wedge a \not = b \rightarrow \gcd(a, b) = 1
$$

Using Equations \$\eqref{1}, \eqref{2}\$ and \$\eqref{3}\$, we can conclude that a set \$S = \{x_1, x_2, \dots, x_k\}\$ is pairwise coprime, if and only if:

$$
\text{lcm}(x_1, x_2, \dots, x_k) = \prod_{x \in S} x
$$

Code Explanation

∞æ¹ùʒPy.¿Q}²£

∞æ              # Powerset of the infinite list [1, ..., ∞].
  ¹ù            # Keep only lists of length k.
    ʒ     }     # Filter. Keep lists where the
     P          #   product of the list
         Q      #   is equal to
      y.¿       #   the least common multiple of the list
           ²£   # Retrieve the first n elements.


Calculate a Pedigree A little genetics lesson

When you only have access to someone's visible traits or phenotype, a pedigree of their family history is often used to figure out the actual genetic information or, genotype of each family member.

When dealing with simple dominance as we will be, a simple pedigree chart will be enough to figure out the alleles, or the version of the genes that they have, of each person. In simple dominance a person with a dominant allele (denoted with a capital letter) will always have the trait that that version represents, no matter the other allele. It takes two recessive alleles (denoted with a lowercase letter) to have that version expressed. In other words the dominant allele always masks the recessive version of that gene. Here is an example of a pedigree chart:

Each row here is a generation. Circles are female, males squares, horizontal  lines are marriage, vertical lines children. Pretty simple. Black means recessive phenotype, white, dominant. Starting from the top, (assume the alleles are A and a), we know person 2 has aa, homozygous recessive because that is the only possible option for the recessive phenotype. Now even though person one could be either Aa or AA to be dominant phenotype, because he has a recessive child, he must be Aa, or heterozygous. You can do this for all the other people. In the event you don't have any information that enables you to figure out the second allele, it can be done like so: A_.

Your Task

You will receive a pedigree chart in the form of a list of generations like [GenI, GenII, etc.] in any sane format.
Each generation will be a list of strings, each string representing a person.
The people are made up of three parts - an ID, their phenotype, and their "connections".
Their ID is a single printable ascii character that is unique in the entire tree other than A or a. (No, there won't be more than 95 people in the chart).
Their phenotype is one of A or a, A being the dominant allele, and a being recessive.
Their connections are a sequence of ID's of other people that they have connections with.
A connection in the same generation is marriage, in different generations is child and parent.
The connections are repeated on both sides (i.e. the husband has say he is a husband of wife, and wife says she is husband of wife).
You have to figure out the genotypes of everyone as much as possible.
Return the same list, except instead of people, put their genotypes in the same position.
The genotype has to be outputted in order so Aa instead of aA.
A little leeway on the input format is fine.
This is code-golf so shortest answer in bytes wins.

Examples

[["0A1234", "1a0234"], ["2A01", "3a01", "4A015678",
"5a4678"], ["6a45", "7A45","8A45"]] (The one above)   ->

[["Aa", "aa"], ["Aa", "aa", "Aa", "aa"], ["aa", "Aa", "Aa"]]

[["0A12", "1A02"], ["2A301", "3a2"]]    ->

[["A_", "A_"], ["A_", "aa"]]

Bonus

-30 bytes if you deal with incomplete and co-dominance also. On the detection of three phenotypes instead of two in the entire chart, apply incomplete/co dominance to your algorithm.

05AB1E, 39 bytes
εNUε'aåi„aaë¯.øX<X>‚è˜y2£lSδåPài„Aaë„A_

Port of my Java answer.
Try it online or verify all test cases.
Explanation:

ε                     # Map over the rows of the (implicit) input-list:
 NU                   #  Store the outer-map index in variable `X`
   ε                  #  Map over the strings `y` of the current row:
    'aåi             '#   If the current string contains an "a":
        „aa           #    Push string "aa"
       ë              #   Else (it contains an "A" instead):
        ¯.ø           #    Surround the (implicit) input-list with two empty lists
                      #    (05AB1E has automatic wrap-around when indexing lists,
                      #     so this is to prevent that)
           X<X>‚      #    Push `X-1` and `X+1` and pair them together
                è     #    Index both into the list to get (potential) parent and child rows
                 ˜    #    Flatten it to a single list
        y             #    Push the current string we're mapping again
         2£           #    Only leave the first 2 characters (its id and the letter "A")
           l          #    Lowercase the "A" to "a"
            S         #    And convert it to a list of characters: [id, "A"]
             δå       #    Check in each string whether it contains the id and "A"
               P      #    Check for each whether it contained BOTH the id AND "A"
                ài    #    If a child/parent is found for which this is truthy:
                  „Aa #     Push string "Aa"
                 ë    #    Else:
                  „A_ #     Push string "A_"
                      # (after which the mapped result is output implicitly)


Evaluate an expression of ternary operators Consider a grammar over the alphabet {0, 1, ?, :} defined by the production rule

  s → 0 ┃ 1 ┃ 0 ? s : s ┃ 1 ? s : s

Given a string generated from s, parse it as an expression where ?: is right-associative (for example, a?B?X:Y:c?d:e?f:g means a?(B?X:Y):(c?d:(e?f:g))) and evaluate it with the following semantics:

eval(0) = 0
eval(1) = 1
eval(0?a:b) = eval(b)
eval(1?a:b) = eval(a)

If the result is 0, output some fixed value; if the output is 1, output a different fixed value. Specify your chosen output values (e.g. 0/1, or False/True) in your answer.

Test cases

0 -> 0
1 -> 1
0?0:1 -> 1
0?1:0 -> 0
1?0:1 -> 0
1?1:0 -> 1
0?1?0:1:1 -> 1
1?0?1:1:1 -> 1
1?0:1?0:1?1:1 -> 0
1?1?1:0?1?0:0:0:0 -> 1
1?0:1?0?1:1?1:0:1?1?1:1:1?0:1 -> 0
1?1?1:0?0?1:1:0?1:0:1?1?0?0:0:1?1:0:0?1?0:1:1?0:1 -> 1
0?0?1?0?0:1:0?0:0:0?0?1:1:1?0:1:0?0?0?1:0:0?1:1:1?1?0:1:1 -> 0

Rules

You may not use language built-ins that interpret strings as code in some programming language and run it (such as JavaScript/Perl/Ruby/Python’s eval).
That said, your code doesn’t actually have to parse and then evaluate the input string. You can take any approach the achieves equivalent results and doesn’t violate the previous rule.
Your program will be checked against perl -le 'print eval<>'.
The shortest code (in bytes) wins.

Retina, 23 bytes

r-1=+`0\?.:|1\?(.):.
$1

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

It's fairly simple actually. The input is reduced to the result by repeatedly (+) evaluating ternaries that contain only literals. To make sure this is done right-associatively, we look for matches from right to left (r) and replace only the last match we find (-1=).

The regex itself either matches 0\?.: and removes it (leaving only the stuff after :) or 1\?.:. and replaces it with the value after the ?.