Pristine and Unique Code Bowling Your challenge is simple: write as long of a pristine program as possible in the language of your choice using only unique bytes. (The full definition of a pristine program, copied from that link, is at the bottom of this question.)
That's right, no strings attached. Your code doesn't have to do anything at all, just run without erroring, meet the requirements for a pristine program (linked above), and include no duplicate bytes in the encoding you use.
For the purposes of the above explanation and linked definition of "pristine program", an error is defined as anything that causes the program to either entirely fail to run or to terminate with a nonzero exit code after a finite amount of time.
As this is code-bowling, longest, not shortest, code wins (measured by byte count). The maximum theoretically possible score is 256, as there are 256 distinct bytes possible. In case of a tie, the first answer at the highest score wins.

Here's the full definition of a pristine program, copied from the above link:

Let's define a pristine program as a program that does not have any errors itself but will error if you modify it by removing any contiguous substring of N characters, where 1 <= N < program length.
For example, the three character Python 2 program
`8`

is a pristine program because all the programs resulting from removing substrings of length 1 cause errors (syntax errors in fact, but any type of error will do):
8`
``
`8

and also all the programs resulting from removing substrings of length 2 cause errors:
`
`

If, for example,  `8 had been a non-erroring program then `8` would not be pristine because all the results of substring removal must error.

Haskell, 39 45 50 52 60 bytes

main=do{(\	陸 ⵙ�商ߜ 新->pure fst)LT
EQ[]3
2$1}

Identifier main has to have type IO a for some type a. When the program is executed, the computation main is performed, and its result is discarded. In this case its type is IO ((a,b)->a).

The result is an application of the function (λ a b c d e f → return fst),
a six-argument constant function returning the function fst (which gives the first element of a 2-tuple), injected into the IO monad. The six arguments are LT (enum for less than), EQ (enum for equality), empty list [], 3, 2 and 1.

What would be spaces are replaced with unique characters that count as spaces: a tab, a non-breaking space, a formfeed, vertical tab, OGHAM SPACE MARK, regular space, newline and carriage return. If any of these are missing, there will be a mismatch in the number of arguments. The parameter names are chosen as three or four byte UTF-8 characters, 陸ⵙ商ߜ新, carefully choosing characters that don't result in duplicate bytes.

Thanks to @BMO for his valuable contributions.

Hex dump:

00000000: 6d61 696e 3d64 6f7b 285c f0a4 b6b8 09ef  main=do{(\......
00000010: a793 c2a0 e2b5 990c e595 860b df9c e19a  ................
00000020: 80e6 96b0 2d3e 7075 7265 2066 7374 294c  ....->pure fst)L
00000030: 540a 4551 5b5d 330d 3224 317d            T.EQ[]3.2$1}

Try it online!


Cyclically Equivalent Words Cyclic Equivalence

Let L be a list of pairs of letters, for example [(a,b), (a,c)]. We call L a list of commutators. Two words are cyclically equivalent over L, if one can be transformed into the other using the following operations:

Cyclic shift: pop a letter from the beginning, and push it to the end.
Commutator swap: if the word begins with two letters that appear in L in either order, swap those letters.

For example, the words acabd and dcaba are cyclically equivalent over L, since we have the sequence of operations acabd -> caabd -> aabdc -> abdca -> badca -> adcab -> dcaba. However, the words acabd and acdab are not cyclically equivalent, since the letters b, c and d cannot be swapped with each other, so they can occur only in the order cbd, dcb or bdc in words that are cyclically equivalent to acbad.

The Challenge

You are given as input two words, and a list of commutators. You program should output a truth-y value (True, 1, etc.) if the words are cyclically equivalent over the list, and a false-y value (False, 0, etc.) otherwise. You don't have to output a sequence of operations in the positive case. The shortest answer (in bytes) is the winner.

Test Cases

[(a,b), (a,c)] acabd dcaba -> True
[(a,b), (a,c)] acabd acdab -> False
[(a,b), (a,d), (b,c), (b,d)] cdaddccabbdcddcababaaabbcbdccaccacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda -> True
[(a,b), (a,d), (b,c), (b,d)] cdaddccabbdcddcababaaabbcbdcccacacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda -> False

Clarifications

You can write either a function or a STDIN-to-STDOUT program.
The list of commutators can be given as a comma-separated string, a list of length-two strings, or a list of pairs of characters.
You can assume that the input words only contain alphanumeric ASCII symbols.
Your program should be able to process inputs of length 100 in a matter of seconds.
Standard loopholes are disallowed.

Python 413
Pretty efficient, although it does sacrifice a small amount of speed for length, such as calculating things every pass of a small for loop rather than precalculating it. I̶t̶ ̶s̶t̶i̶l̶l̶ ̶o̶u̶t̶p̶u̶t̶s̶ ̶a̶l̶l̶ ̶t̶h̶e̶ ̶t̶e̶s̶t̶ ̶c̶a̶s̶e̶s̶ ̶i̶n̶ ̶w̶e̶l̶l̶ ̶u̶n̶d̶e̶r̶ ̶a̶ ̶s̶e̶c̶o̶n̶d̶.̶
Edit:
I had to fix a bug which now makes it significantly less efficient for larger inputs.
X,Y,L=input();S=sorted;T=type
def E(s,c):
 l=[[]]
 for h in s:
    if h==c:l+=[h]
    elif all(h!=[b,a][j]for a,b in L for j,n in[(0,a),(1,b)]if n==c):
     if T(l[-1])==str:l+=[[]]
     l[-1]=S(l[-1]+[h])
 if T(l[0])==T(l[-1])!=str:return[l[0]+l[-1]]+l[1:-1]+[len(l[-1])]
 return l+[0]
print any(0==cmp(*[[E(s,c)for c in S(set(s))]for s in [X[j:]+X[:j],Y[i:]+Y[:i]]])for i in range(len(Y))for j in range(len(X)))

Test Cases
"acb", "abc", [('a','b')]
True (0 ms)

'acabd','dcaba',[('a','b'),('a','c')]
True (1 ms)

'acabd','acdab',[('a','b'),('a','c')]
False (2 ms)

'cdaddccabbdcddcababaaabbcbdccaccacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc','ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda',[('a','b'), ('a','d'), ('b','c'), ('b','d')]
True (62 ms)

'cdaddccabbdcddcababaaabbcbdcccacacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc','ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda',[('a','b'), ('a','d'), ('b','c'), ('b','d')]
False (6963 ms)

The basic algorithm does the following. For each letter, L, present, loop through the string constructing a list; anytime it encounters L it appends it to the list, any group of adjacent letters which can not be switched with L it appends to the list sorted, letters which can be switched with L are ignored.
For example when considering 'acabd' with the pairs [('a','b'),('a','c')], we would construct:
a : a, a, [d]
b : [c], b, [d] *
c : c, [b,d]
d : [a,a,b,c], d

which is equivalent to the result we get when we apply this to 'cabad' ('dcaba' shifted)
*Note here that the [c] and [d] should be considered one list
What is basically being done, is confirming for each letter that the order of it and the letters it can't switch with are the same. Since they cannot switch, they cannot 'pass' each other, so if the first string has two as followed by two ds followed by one a followed by one d than no matter how it's manipulated it can't be transformed into a string which has three as followed by three ds. Of course the order of the letters that it can't switch with is not an issue (they might be paired with each other and switchable), but their counts are, hence the sorting of the lists before comparison. In addition it's clear that any letters that can be switched don't matter at all for the purposed of comparison.
Using this algorithm the program could be made significantly more efficient; currently it loops through every possible transposition of both strings and compares them due to some issues with comparing cases in which there were lists bordering the beginning and end.


Faro shuffle an array A Faro shuffle is a technique frequently used by magicians to "shuffle" a deck. To perform a Faro shuffle you first cut the deck into 2 equal halves then you interleave the two halves. For example
[1 2 3 4 5 6 7 8]

Faro shuffled is
[1 5 2 6 3 7 4 8]

This can be repeated any number of times. Interestingly enough, if you repeat this enough times, you will always end up back at the original array. For example:
[1 2 3 4 5 6 7 8]
[1 5 2 6 3 7 4 8]
[1 3 5 7 2 4 6 8]
[1 2 3 4 5 6 7 8]

Notice that 1 stays on the bottom and 8 stays on the top. That makes this an outer-shuffle. This is an important distinction.
The Challenge
Given an array of integers A, and a number N, output the array after N Faro shuffles. A may contain repeated or negative elements, but it will always have an even number of elements. You can assume the array will not be empty. You can also assume that N will be a non-negative integer, although it may be 0. You can take these inputs in any reasonable manner. The shortest answer in bytes wins!
Test IO:
#N, A,                                              Output
1,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 5, 2, 6, 3, 7, 4, 8]
2,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 3, 5, 7, 2, 4, 6, 8]
7,  [-23, -37, 52, 0, -6, -7, -8, 89]               [-23, -6, -37, -7, 52, -8, 0, 89]
0,  [4, 8, 15, 16, 23, 42]                          [4, 8, 15, 16, 23, 42]
11, [10, 11, 8, 15, 13, 13, 19, 3, 7, 3, 15, 19]    [10, 19, 11, 3, 8, 7, 15, 3, 13, 15, 13, 19]

And, a massive test case:
23, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

Should output:
[1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100]

vim, 62 59 54

qrma50%mb:norm@q<cr>ggqOjdd'apjma'b@q<esc>0"qDJ<C-a>D@"i@r<esc>xxdd@"

Wow. This is possibly the hackiest thing I've written for PPCG, and that's saying something.

Input is taken as N on the first line followed by the elements of the array, each on its own line.

qr         first, we're going to record the contents of the @r macro. this is
             the macro which does the faro-shuffle operation.
  ma       set the mark 'a at the beginning of the file
  50%      move to the 50% point of the file (i.e. halfway down)
  mb       set another mark here
  :norm@q  evaluate the recursive macro @q. we'll get to what that does later,
             but the interesting part here is that it's :norm@q instead of @q.
             this is because a recursive macro terminates at the end of the
             file, which means when @q terminates, @r would also abort, which
             would make calling it with a count impossible. running @q under
             :norm prevents this.
  gg       move back to the top of the file for the next iteration
q          end recording
O          now we're inserting contents of the @q macro, the recursive part
             we can't record it directly because it's destructive
  j        move to line directly below mark 'b (which was just set before @q)
  dd       delete this line and bring it...
  'ap      up after mark 'a (which starts on line 1, bringing the N/2th line
             directly below line 1, aka line 2)
  jma      replace mark 'a one line below this so that the next time we call
             'ap, the line from the second half is interleaved with the lines
             from the first half
  'b       jump back to mark 'b (remember, 'b is the last line of the first
             half of the file, originally reached via 50%)
  @q       call ourselves, causing the macro to run until hitting EOF
0"qD       delete this into register "q
J          delete the empty line that remains
<C-a>      here's another interesting bit: we want to run @r N times. but 0@r
             means "go to column 0, and then run @r once." so we have to
             increment the input number...
D@"        and then *that* many times...
  i@r        insert @r...
xx         ... and finally, delete two characters, which is the extra @r from
             the increment
dd         delete the sequence of @rs into the "" register...
@"         and run it!

I actually possibly found several vim bugs while writing this answer:

recording macros is not possible within other macros (when setting their text manually, not with q) or within :*maps.
:let @a='<C-v><cr>'<cr>i<C-r>a outputs two newlines, not one, for whatever arcane reason.

I might investigate those further later.

Thanks to Dr Green Eggs and Ham DJ for 3 bytes!


Never trust a mastermind You probably know the game mastermind:
The player tries to guess a code of 4 slots, with 8 possible colors - no duplicates this time.
Let's call those colors A through H, so possible solutions could be ABCD or BCHD.
Each time you place a guess, the game master will respond with two information: how many slots you got right, and how many colors you got right but in the wrong place.
Some examples:
If the code is ABCD
and your guess is ACHB
the response 12: the color A is correctly placed, the two colors B&C are in the wrong place.

Code is ABCD
you guess EFGH
response is 00

Code is ABCD
you guess ABCD
response is 40

A full representation would be:
ABCD04,DCBA40
or
ABCD00,EFGH22,EFHG13,HFGE40

A partial game does not contain the final solution,
nor necessarily enough data to define a unique solution.
ABCD00,EFGH22,EFHG13

An example for an invalid partial game would be:
ABCD03,EFGH02: This would require that 5 colors are present

In essence, all games that cannot have a solution are invalid. The gamemaster made a mistake.
Your task
Never trust a game master. Your task is to write a program that takes a partial or full game description and validates whether such a game state is possible.

Expect that no game description is longer than 8 attempts.
Expect that the gamemaster can make a mistake on the very first turn, e.g. ABCD41
The player can make an "invalid" guess to gain further information, e.g. AAAA to check if there is an A at all. Such a game is still valid, you only evaluate the gamemaster's responses. In such a case, exact hit takes precedence over near-misses, for code ABCD it's AAAA10, not AAAA14.
You can format the input and output in whatever way you see fit, including replacing the colors by digits etc.
Any pre-generated hashtable counts towards the total number of bytes.
You know the loophole thing.

The shortest code wins.
Additional test cases:
 - ABCD11,ACEG02,HGFE11,CCCC10,CDGH01 => valid
 - ABCD01,EFGH03,CGGH11,HGFE21 => valid
 - ABCD22,EFGH01,ACDE11 => invalid
 - ABCD02,EFGH01,AABB21,AEDH30 => invalid
 - ABCD03,DCBA02 => invalid
 - ABCD32 => invalid

You can generate any number of valid cases by playing the game.
Invalid solutions are hard to come up with. If you find invalid combinations that first slipped through your code, please comment it below for your fellow golfers.
Bonus:
Bonus points if you come up with a solution that uses a significantly different approach than generating and traversing all possible permutations.

JavaScript (ES6),  116 112  107 bytes
Expects an array of entries in the following format: [[a,b,c,d], "XY"], where a to d are integers in [0..7], X is the number of correct digits and Y is the number of near-misses.
Returns 0 or 1.

f=(a,n)=>n>>12?0:!a.some(([a,x])=>!a.every(o=(d,i)=>o[x-=d^(v=n>>i*3&7)?a.includes(v):10,v]^=1)|x)|f(a,-~n)

Try it online!
Commented
f = (                     // f is a recursive function taking:
  a,                      //   a[] = input
  n                       //   n = 12-bit counter, initially undefined, to
) =>                      //       describe all possible codes
n >> 12 ?                 // if n = 4096:
  0                       //   stop the recursion
:                         // else:
  !a.some(([a, x]) =>     //   for each entry [a, x, y] in a[], with a[] =
                          //   guess, x = correct digits and near-misses:
    !a.every(o =          //     we use the object o to keep track of the
                          //     digits that were already extracted from n,
                          //     in order to discard invalid codes
      (d, i) =>           //     for each value d at position i in a[]:
      o[                  //
        x -=              //       update x:
          d ^ (           //         compare d with ...
            v =           //         ... v which is defined as ...
              n >> i * 3  //         ... the next 3-bit digit extracted from n
              & 7         //
          ) ?             //         if d is not equal to v, decrement x if ...
            a.includes(v) //           ... v appears elsewhere in a[]
          :               //         else:
            10,           //           subtract 10 from x
        v                 //       actual index in o to ...
      ] ^= 1              //       ... mark this digit as used; or yield 0
                          //       and exit every() if it was already used
    )                     //     end of every(); the iteration fails if it's
    | x                   //     falsy or x is not equal to 0
  )                       //   end of some()
  | f(a, -~n)             //   do a recursive call with n + 1


Validate Random Die Tippers Almost six years ago, fellow PPCG member steenslag posted the following challenge:

  In a standard dice (die) the numbers are arranged so that opposite
  faces add to seven. Write the shortest possible program in your
  preferred language which outputs a random throw followed by 9 random
  tippings. A tipping is a quarter turn of the dice, e.g. if the dice is
  facing 5, all possible tippings are 1,3,4 and 6.

  Example of desired output:

    1532131356

So, now that everybody has completely forgotten about it and the winning answer has long since been accepted, we'll be writing a program to validate the die tipping sequences generated by the submitted solutions. (This makes sense. Just pretend it does.)

Challenge

Your program or function  is given a sequence such as 1532131356. Validate that each consecutive digit is:

Not equal to the previous digit
Not equal to 7 minus the previous digit

(You don't have to validate the first digit.)

Rules

Your program must return a truthy value if the input is valid and a falsey value otherwise.
You can assume that the input consists of only the digits 1-6 and is at least 1 character long. Sequences won't have a fixed length like in steenslag's challenge.
You can take the input as a string ("324324"), an array or array-like datastructure ([1,3,5]) or as multiple arguments (yourFunction(1,2,4)).

Standard I/O and loophole rules apply.

Test cases

Truthy

1353531414
3132124215
4142124136
46
4264626313135414154
6
2642156451212623232354621262412315654626212421451351563264123656353126413154124151545145146535351323
5414142

Falsey

Repeated digit

11
3132124225
6423126354214136312144245354241324231415135454535141512135141323542451231236354513265426114231536245
553141454631
14265411

Opposing side of die

16
42123523545426464236231321
61362462636351
62362462636361

Python 2, 43 45 bytes

lambda s:reduce(lambda p,n:n*(7-p!=n!=p>0),s)

43 bytes (inspired heavily by @Zgarb)

lambda s:reduce(lambda p,n:n*(p>0<n^p<7),s)

This function combines my reduce statement with the bit-flicking logic from @Zgarb's answer, for a combination that is shorter than both.

Both answers output the following:

0 if the input is not a valid sequence
The last digit of the sequence if it is valid


Self-shortening Prime Tester Let's get right in to it.
Your challenge is to make a program that does these things depending on its input:

If the input is a number, output "Prime" if the number is a prime number and "Not prime" if the number isn't a prime number. You can assume the number is > 1.

If the input is two numbers, output every single prime number between the first number (inclusive) and the second number (exclusive). You can assume the first number is smaller than the second.

Here comes the real challenge: if there's no input, the program should output a shorter version of itself that does exactly the same things as the original program. The program is not allowed to read from any file or from the web. The new program should also be able to do this. It should work for at least 5 generations. The new program doesn't have to be in the same language as the first.

Scoring:
Your score is equal to the sum of the number of bytes in the first five generations of your submission (the submission itself being generation one). If the new code is hard-coded in to the first program, multiply the score by 1.5. Lowest score wins. (If you find some kind of flaw in the scoring system, please let me know in the comments)

CJam, 66 + 65 + 64 + 63 + 62 = 320 325 355  bytes

The following 5 lines are the first 5 generations:

{     `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~
{    `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~
{   `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~
{  `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~
{ `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~

The last one produces

{`(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~

which still performs the prime tasks correctly.

Test it here.

Explanation

The basic CJam quine is

{"_~"}_~

which can be extended very easily to a generalised quine. For an explanation of this see my answer here.

The basic ideas for this answer are:

Start the quine with a bunch of spaces and remove one of these when quining.
Get an array with all input numbers (0, 1 or 2) and choose some code to run depending on the length (by using it to index into an array).

Here is a breakdown of the code inside the quine:

"Remove a space from the block's string representation:";
`(\1>+
`      "Get the string representation of the block.";
 (\    "Slice off the leading '{' and pull the remaining string back up.";
   1>  "Remove the first character, i.e. a space.";
     + "Prepend the '{' to the string again.";

"Get the array of inputs and choose the code:";
q~](\_,[...]=~
q~             "Read and eval the input.";
  ]            "Wrap everything (including the string for the block) in an array.";
   (\          "Shift off the string and swap it with the rest of the array.";
     _,        "Duplicate the input array and get its length.";
       [...]=  "Use it to index into this array.";
             ~ "If there are no inputs there will now be an array on the top of the
                stack, which ~ will unwrap. Otherwise there will be a block which ~
                will evaluate.";

"If there is no input, push the string needed for the quine and put it in
 an array for ~ to unwrap:";
"_~"a

"If there is one input, test for primality:";
~mp'P"Not p"?"rime"@;
~mp                   "Unwrap the input array and test for primality.";
   'P"Not p"?         "Choose either 'P' or 'Not p' depending on the result.";
             "rime"   "Push the common part of the string.";
                   @; "Pull up the quine string and discard it.";

"If there are two inputs, print an array with all the primes in the range:";
~,>{mp},p;
~          "Unwrap the array leaving N and M on the stack.";
 ,         "Get a range [0 1 .. N-1].";
  >        "Drop the first M elements, giving [M M+1 .. N-1].";
   {mp},   "Filter to keep only the primes.";
        p  "Pretty-print the array.";
         ; "Discard the quine string.";


Write a program that can draw 2-D shapes using ASCII or any other method Rules (not too restrictive; flexible):

1.Must be able to draw shapes on command (e.g., I type in "square" and a square is drawn).

Minimum completed shapes that can be drawn on command: Square, Circle, Triangle, Pentagon.

2.Must also be able to also draw shapes vertex-by-vertex, specified by a command function that gives the user an input to determine line segment lengths between points in succession.

The program has to give the option to make polygons as well, but incomplete 2-D shapes, circles, unclosed planes, and non-polygons shall be allowed.

Winner: Most votes.

Logo
Just install it!
Then things like triangles, squares, pentagons and circles are defined as:
to triangle :length
    polygon :length 3
end

to square :length
    polygon :length 4
end

to pentagon :length
    polygon :length 5
end

to circle :length
    polygon :length 360
end

to polygon :length :sides
    repeat :sides [forward :length right 360/:sides]
end

Easy peasy lemon squeezy...


A program that outputs itself in reverse order Well the title says it all.

Standard loopholes apply
Nothing to read from stdin, and output goes to stdout
1-byte-long programs are... nonsense. They don't qualify
A program with a single byte repeated is also a nonsense (like aaa)
Please mark it out if your program is a palindrome

Sample:

A program with source code
abcde

should output
edcba

Because this is a code-golf, the shortest program wins!

RProgN 2, 3 bytes

1
0

Try it online!

Pretty sure this has been submitted before, but here's one in RProgN 2.

It outputs

0
1


Truncate continued fractions Related: Cleaning up decimal numbers
Background
A continued fraction is a way to represent a real number as a sequence of integers in the following sense:
$$
x = a_0 + \cfrac{1}{a_1 + \cfrac{1}{a_2 + \cfrac{1}{\ddots + \cfrac{1}{a_n}}}} = [a_0; a_1,a_2,\cdots,a_n]
$$
Finite continued fractions represent rational numbers; infinite continued fractions represent irrational numbers. This challenge will focus on finite ones for the sake of simplicity.
Let's take \$\frac{277}{642}\$ as an example. It has the following continued fraction:
$$
\frac{277}{642} =
0 + \cfrac{1}{2 + \cfrac{1}{3 + \cfrac{1}{6 + \cfrac{1}{1 + \cfrac{1}{3 + \cfrac{1}{3}}}}}} =  [0;2, 3, 6, 1, 3, 3]
$$
If we truncate the continued fraction at various places, we get various approximations of the number \$\frac{277}{642}\$:
$$
\begin{array}{c|c|c|c}
 \style{font-family:inherit}{\text{Continued Fraction}} & \style{font-family:inherit}{\text{Fraction}}
& \style{font-family:inherit}{\text{Decimal}} & \style{font-family:inherit}{\text{Relative error}}\\\hline
 [0] & 0/1 & 0.0\dots & 1 \\\hline
 [0;2] & 1/2 & 0.50\dots & 0.15 \\\hline
 [0;2,3] & 3/7 & 0.428\dots & 0.0067 \\\hline
 [0;2,3,6] & 19/44 & 0.4318\dots & 0.00082 \\\hline
 [0;2,3,6,1] & 22/51 & 0.43137\dots & 0.00021 \\\hline
 [0;2,3,6,1,3] & 85/197 & 0.431472\dots & 0.000018 \\\hline
 [0;2,3,6,1,3,3] & 277/642 & 0.4314641\dots & 0
\end{array}
$$
These are called convergents of the given number. In fact, the convergents are the best approximations among all fractions with the same or lower denominator. This property was used in a proposed machine number system of rational numbers to find the approximation that fits in a machine word of certain number of bits.
(There are some subtle points around "best approximation", but we will ignore it and just use the convergents. As a consequence, if your language/library has a "best rational approximation" built-in, it is unlikely to correctly solve the following task.)
Task
Given a rational number \$r\$ given as a finite continued fraction and a positive integer \$D\$, find the best approximation of \$r\$ among its convergents so that its denominator does not exceed \$D\$.
The continued fraction is guaranteed to be a finite sequence of integers, where the first number is non-negative, and the rest are strictly positive. You may output the result as a built-in rational number or two separate integers. The output fraction does not need to be reduced.
Standard code-golf rules apply. The shortest code in bytes wins.
Test cases
[0, 2, 3, 6, 1, 3, 3], 43 => 3/7
[0, 2, 3, 6, 1, 3, 3], 44 => 19/44
[5, 6, 7], 99 => 222/43

JavaScript (ES6),  72 68   67 bytes
Expects (max_denominator)(seq). Returns [numerator, denominator].

m=>g=([v,...a],n=0,d=1,N=1,D=0)=>(d+=D*v)<=m?g(a,N,D,N*v+n,d):[N,D]

Try it online!
Commented
m =>             // outer function taking m = maximum denominator
g = (            // inner recursive function taking:
  [v,            //   v = next term from the continued fraction
      ...a],     //   a[] = remaining terms
  n = 0,         //   n = previous numerator
  d = 1,         //   d = previous denominator
  N = 1,         //   N = current numerator
  D = 0          //   D = current denominator
) =>             //
  (d += D * v)   // we compute the new denominator d = D * v + d
                 // this results in NaN if v is undefined,
                 // which forces the comparison to fail
  <= m ?         // if it's less than or equal to m:
    g(           //   do a recursive call:
      a,         //     pass the remaining terms of the continued fraction
      N, D,      //     pass the current numerator and denominator
      N * v + n, //     pass the new numerator
      d          //     pass the new denominator
    )            //   end of recursive call
  :              // else:
    [N, D]       //   we're done: return [N, D]


Find the first word starting with each letter Given a string, find the first word starting with each letter (case insensitive).

Sample

Using Ferulas flourish in gorgeous gardens. as input:

"Ferulas flourish in gorgeous gardens."
 ^^^^^^^          ^^ ^^^^^^^^
 |                |  |
 |                |  --> is the first word starting with `g`
 |                --> is the first word starting with `i`
 --> is the first word starting with `f`

Then, the output for this sample should be the matched words joined by one single space:

"Ferulas in gorgeous"

Challenge

Both input and output must be a string representation, or the closest alternative in your language.

Program or function allowed.

You can consider a word being at least one of: lowercase or uppercase letters, digits, underscore.

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

Another samples:

input: "Take all first words for each letter... this is a test"
output: "Take all first words each letter is"

input: "Look ^_^ .... There are 3 little dogs :)"
output: "Look _ There are 3 dogs"

input: "...maybe some day 1 plus 2 plus 20 could result in 3"
output: "maybe some day 1 plus 2 could result in 3"

Retina, 28 bytes:

M!i`\b(\w)(?<!\b\1.+)\w*
¶
&#32

M! - Match each work and print all words separated by newlines.
i - Ignore case.
\b(\w) - Capture first letter of each word
(?<!\b\1.+) - After matching the letter, check if there wasn't a previous word starting with the same letter. \1.+ ensures at least two characters, so we are skipping the current word.
\w* - match the rest of the word.
The above matches only words - all other characters are removed.
¶\n  - Replace newlines with spaces.

Try it online!


Compute the difference between two days. Another date-manipulating problem :P

Task

  Write a program or a function that calculates the difference between two dates given by a user.

Input & Output

Similar to the previous one, inputs are two YYYYMMDDs, separated by a space , a comma ,, or a minus sign -.

Example of input values:

20100101-20010911
20110620-20121223
19000101 20101010
33330101,19960229
00010101 99991231

Output is an integer, which is difference between two dates, in days.

For example, input 20110101-20100101 yields 365, and 33320229 17000101 yields 596124.

You may test results at here at here. (See rintaun's comments below.) If two dates are same, the program should returns 0, if the date is valid (see Score).

Restriction

Of course, you must not use any kinds of function/class/... which are related to timestamp or date, and you should use Gregorian calender.

Score

If your code doesn't keep the restriction, then score = -∞.

Default bonus is 1.

If your code works regardless of order of inputs (for example, 20100101,20110101 returns 365 or -365), bonus+=1.
If your code can handle year 0, bonus+=0.5.
If your code recognizes invalid month(between 1~12)/date(between 1~31), like 20109901 or 34720132, and prints E (& terminates the program or returns something like 0), bonus+=1.
Regardless of above rule, if your code recognizes invalid dates, like 20100230, 20100229, or 20111131, and prints E (& terminates the program or returns something like 0), bonus+=1.
Regardless of above two rules, if your code recognizes invalid input string, like 20100101|20100202 or 2010010120100202, and prints E (& terminates the program or returns something like 0), bonus+=1.

score = floor(-4.2*code.length/bonus). Code with highest score wins. If two top codes have same score, then codes with highest bonus wins. If two top codes have both same score and bonus, then codes with highest votes wins.

(Due: When there's more than 5 codes which has more than (or equal) +1 votes.)

Perl 5.14, score = -162
-163 -181 -196 -214 -167 -213 -234

code.length = 211: 208 source characters + 3 for running perl with the -p option
bonus = 5.5: default, order, year 0, never-valid month/day, invalid date, wholly-invalid input

Code
$_=eval(join'-',map{($y,$m,$d)=/(....)(..)(..)/;die"E\n"if!($m*$d)||$m>12||$d>30+($m&1^$m>7)-($m==2)*(2-!($y=~s/00$//r%4));$y-=($m<3)-400;$d+int(($m+9)%12*30.6+.4)+int(365.2425*$y)}/^(\d{8})[ ,-](\d{8})$/)//E

Calculates a modified Julian day number for each date (ignoring the epoch-related adjustments to save code length) and subtracts the two. (ref. "Julian Day" at Wikipedia).

requires perl 5.14+ for the /r option on the substitutions
month-length calculation to get the invalid date bonus: the 30+($m&1^$m>7) part gives the length of any month but February; the rest adjusts for February in an ordinary or leap year

Assumptions

"use Gregorian calendar" means the proleptic Gregorian calendar for dates before whichever Julian to Gregorian transition we're using.  That is, don't subtract 11 days for intervals that cross, for example, the 3 Sep 1752 - 14 Sep 1752 British transition.
"handle year 0" means, for example, 00000101-00010101 should give 366, as 0 is an integral multiple of 400, and so year 0 is a leap year.


A bit, a nibble or byte? Inspired by this challenge
Given an integer in the range 0 <= n < 2**64, output the minimum sized container it can fit in out of

bit: 1
nibble: 4
byte: 8
short: 16
int: 32
long: 64

Testcases:
0 -> 1
1 -> 1
2 -> 4
15 -> 4
16 -> 8
123 -> 8
260 -> 16
131313 -> 32
34359750709 -> 64

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

Python, 39 bytes

f=lambda n:4**(n>1)*(n<16)or 2*f(n**.5)

Counts how many times one must take the square root for n to be below 16, with some special-casing to avoid outputs of 2.

If 2 were included, we could do

f=lambda n:n<2or 2*f(n**.5)

with True for 1.

41 bytes:

f=lambda n,i=1:i*(2**i>n)or f(n,i<<1+i%2)

Repeatedly doubles the exponent i until 2**i>n. Skips from i=1 to i=4 by shifting an additional bit when i is odd.

Alt 45 bytes:

f=lambda n,i=4:4**(n>1)*(2**i>n)or 2*f(n,i*2)


Ethan Finds the Maximum Element This is a problem that the Hacker Cup team made for the 2018 Facebook Hacker Cup, but we ended up not using it (though Ethan struggles through a variety of other challenges). Normally code size isn't a factor in the Hacker Cup, but we thought this would make for an interesting code golf challenge. We look forward to seeing how a different sort of competitive programmer tackles this problem!

Ethan Finds the Maximum Element

Ethan has been given quite the challenging programming assignment in school: given a list of \$N\ (1 <= N <= 50)\$ distinct integers \$A_{1..N}\ (1 <= A_i <= 100)\$, he must find the largest one!

Ethan has implemented an algorithm to solve this problem, described by the following pseudocode:

Set \$m\$ to be equal to \$A_1\$.
Iterate \$i\$ upwards from 2 to \$N\$ (inclusive), and for each \$i\$, if \$A_i > A_{i-1}\$, set \$m\$ to be equal to \$A_i\$.
Output \$m\$.

Sometimes this algorithm will output the correct maximum value, but other times it sadly won't.

As Ethan's teaching assistant, you have some say in what input data his solution will be evaluated on. The professor has given you a list of \$N\$ distinct integers \$A_{1..N}\$ to work with, but you may shuffle them into any permutation you'd like before feeding them into Ethan's program. This is your opportunity to show some mercy!

For how many different permutations of \$A_{1..N}\$ would Ethan's algorithm produce the correct output?

Input Format:

Line 1: 1 integer, \$N\$
Line 2: \$N\$ space-separated integers, \$A_{1..N}\$

Output Format:

1 integer, the number of permutations of \$A\$ for which Ethan's algorithm would produce the correct output.

Sample Input 1:

1
100

Sample Output 1:

1

Explanation:

Only one permutation of \$[100]\$ exists, and Ethan's program would correctly output 100 for it.

Sample Input 2:

3
16 82 43

Sample Output 2:

5

Explanation:

Ethan's program would correctly output 82 for 5 of the 6 possible permutations of \$[16, 82, 43]\$. However, when \$A = [82, 16, 43]\$, it would incorrectly output 43 instead.

Sample Input 3:

10
26 81 40 5 65 19 87 27 54 15

Sample Output 3:

986410

Rules

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

APL (Dyalog Unicode), 5 3 bytes

⍳⊥×

Try it online!

Adám gave me an inspiration to golf this further.

How it works

⍳⊥×  Monadic train. Input: n, the length of array A.
  ×  v: Signum, which always gives 1 because n ≥ 1
⍳    B: An array of 0..n-1
 ⊥   Scalar-expand v to get V, a length-n vector of ones,
       then mixed base conversion of V in base B

APL (Dyalog Unicode), 5 bytes

⍳⊥⍴∘1

Try it online!

Edited to remove modulo 107

Uses HyperNeutrino's formula, but optimized through the use of ⊥ (mixed base conversion) directly. Uses ⎕IO←0.

How the code works

⍳⊥⍴∘1  Monadic train. Input: n, the length of array A.
  ⍴∘1  V: An array of 1's of length n
⍳      B: An array of 0..n-1
 ⊥     Mixed base conversion of V in base B

How the ⊥ works

base:  0         1         2         .. n-3         n-2 n-1
digit: 1         1         1         .. 1           1   1
value: 1×..(n-1) 2×..(n-1) 3×..(n-1) .. (n-2)×(n-1) n-1 1
sum of all digit values is the answer.


Break the broken hash Some time ago, I found this unused hash function (written in Java) in our codebase:

long hashPassword(String password)
{
    password = password.toUpperCase();
    long hash = 0;
    int multiplier = 13;
    for (int i = 0; i < password.length(); i++)
    {
        hash += hash * multiplier + (short)password.charAt(i);
        multiplier++;
    }
    hash = Math.abs(hash);
    hash <<= hash % 11;
    hash = Math.abs(hash);
    return hash;
}

I am very happy that it was unused, because it is beyond broken. Not only is this hash function very weak with an ouput of only 8 bytes, but it is also reversible, and it collides very easily: there are many similar inputs that will generate the same hash. A friend and I worked on the problem, and we managed to create a C# program that does just that: take a hash, and show the reasonable inputs that could have generated this hash.

Now is your turn. Write a program, in any language, that accepts a numeric hash as its sole parameter, and yields all possible inputs (made of 5+ characters with only printable ASCII characters) that would produce the given hash if passed to the function above, each on a new line. You don't need to handle any specific kind of error, as long as it works for any given numeric hash.

On your post, please include the hash of a word of your choice, and five possible inputs that have this hash (though your program must not be limited to finding only five).

Most elegant solution wins, and elegance is defined as algorithmic elegance (in other words, brute-force won't win). I'll accept an answer on March 13.

Example input and output (UNIX shell optional):

$ ./hashbreaker 224443104
ZNEAK
Y^4Q]
\2'!'
ZMUB9
Y_%AK
[and many, many, many more results...]

I got more than enough answers without reversing both abs calls, so I skipped that.  They'd be trivial to add back if really needed.  I'm not even taking long overflow into account, but that'd let you insert most any word you like in the greater hashes.  As if that was needed to get collisions.

import Data.Char
import Data.Bits
import Control.Monad

printables = [32..95]

reverseModShift11 x = do
  let zeros = head $ filter (testBit x) [0..]
  b <- [0 .. zeros]
  let h = x `shiftR` b
  guard $ (h `mod` 11) == (fromIntegral b)
  return h

reverseBase p m n | m < 13    = []
                  | n <  0    = []
                  | n == 0 && m == 13 = return p
                  | otherwise = do
  let r = n `mod` m
  c <- filter (\x -> x `mod` m == r) printables
  reverseBase (chr c:p) (m-1) ((n-c) `div` m)

reverseBases = join . ap (map (reverseBase "") [14..29]) . return

breakHash = reverseModShift11 >=> reverseBases

Sample use:

*Main> breakHash 224443104
["]#'!'","\\2'!'","[A'!'","ZP'!'","Y_'!'",
  (...)
"[?EAK","ZNEAK","Y]EAK",
  (...)
"] TQ]","\\/TQ]","[>TQ]","ZMTQ]","Y\\TQ]"]


Make a webpage where it looks like the browser is hanging / crashing Your task today is to create a HTML page.

This page, when opened in a browser, behaves as if the browser has a problem (hanging, crashing, network error, virus, etc.)

You can use all the HTML(5), CSS(3) and JavaScript features you want.
You can't use Flash or other plugins.
You can't provoke a real problem in the browser (for example, you can't make the browser hang with an infinite loop, or crash with a bug exploit, etc.), just make it look like there is a problem.

Please post your source code and provide an URL to view your page, and precise on which browsers / devices it works (if specific).

I recommend http://www.c99.nl/ to host your page easily.

This is a popularity contest, so the most upvoted answer wins!

Thanks, and have fun!

  <title>Connecting...</title>

http://c99.nl/f/64943.html


May the first be with you Write a program to replace all occurrences of "force" with "first" and all occurrences of "first" with "force", keeping the original case for all character positions:

"ForcefoRcefOrcE" -> "FirstfiRstfIrsT"
"FirstfiRstfIrsT" -> "ForcefoRcefOrcE"

The rest of the string must stay unchanged, and so running your program twice shall return the original string:

"thirst of forces" -> "thirst of firsts" -> "thirst of forces"

Your program should work on any initial string. So as a hint, you better avoid using magic characters as intermediate representation, because if you try a three pass replacement ("force" -> "zzzzz", "first" -> "force", "zzzzz" -> "first"), it will fail on strings containing "zzzzz".

You should support the full range of characters allowed in a definition of a String by your programming language (in most cases, it's Unicode). Example, using JSON-style representation for non-printable characters (\u + 4 digits):

"\u0000\u0001\u0002\u0003the Force of the firsT"
                     |
                     V
"\u0000\u0001\u0002\u0003the First of the forcE"

JavaScript (ES6), 93 88 bytes

f=
s=>s.replace(/force|first/gi,s=>s.replace(/./g,c=>s[s.search(c)^1]||c,s="oicsetOICSET"))
<textarea oninput=o.textContent=f(this.value)></textarea><pre id=o>

Edit: Saved 5 bytes by optimising the unchanged letter case.


Construct a tournament bracket Given an input list of non-empty strings, output an ASCII art representation of a tournament, based on the following drawing rules:

The number of strings is guaranteed to be of quantity 2,4,8,16,etc.
The first two strings play each other, and the next two play each other, and so on. This is the first round.
For each game, choose the winner randomly with equal probability.
For the next round, the winner of the first game plays the winner of the second game, the winner of the third game plays the winner of the fourth game, and so on. Subsequent rounds follow the pattern.
There is eventually one overall winner.
For pretty output (required) the strings must all be prepended and appended with an underscore _.
In order for the brackets to line up appropriately, each entry must be padded with _ to all be the same length for that round.
You can choose whether the padding is prepended or appended, so long as it's consistent.
Instead, you can choose to pre-pad all strings to be the same length, rather than on a per-round basis. Whichever is golfier for your code.

Further Rules

Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

Example with cities ['Boston', 'New York', 'Charlotte', 'Atlanta', 'St. Paul', 'Chicago', 'Los Angeles', 'Phoenix']:

_Boston______
             \_New York____
_New York____/             \
                            \_New York_
_Charlotte___               /          \
             \_Charlotte___/            \
_Atlanta_____/                           \
                                          \_St. Paul_
_St. Paul____                             /
             \_St. Paul____              /
_Chicago_____/             \            /
                            \_St. Paul_/
_Los Angeles_               /
             \_Los Angeles_/
_Phoenix_____/

Example with ['Lions', 'Tigers', 'Bears', 'Oh My']:

_Lions__
        \_Tigers_
_Tigers_/        \
                  \_Tigers_
_Bears__          /
        \_Bears__/
_Oh My__/

Charcoal, 92 79 bytes

Ａ¹θＷＳ⊞υ⪫__ιＷυ«Ａ⌈ＥυＬκεＡ⁺θθδＦυ«Ｐ×_εＰκＭδ↓»ＡＥ✂υ¹Ｌυ²⎇‽²κ§υ⁺λλυＭε→Ｆυ«Ｍδ↑↗θ←↖θ→»Ｍθ↘Ａδθ

Try it online! Link is to verbose version of code. Needs a blank line to mark the end of the input. Explanation:

Ａ¹θ

Initialise the variable q. This holds the size of the zig-zags i.e. half the gap between rows.

ＷＳ⊞υ⪫__ι

Read nonblank input lines into the array u. The lines are automatically surrounded by _s as they are read in, although they are not padded yet.

Ｗυ«

Loop while there are still strings left.

Ａ⌈ＥυＬκε

Calculate the width of the largest string in e.

Ａ⁺θθδ

Calculate the gap between rows in d.

Ｆυ«Ｐ×_εＰκＭδ↓»

For each team, print the padding, print the team, and then move down to the next team.

ＡＥ✂υ¹Ｌυ²⎇‽²κ§υ⁺λλυ

For every other team, randomly pick between that team or the previous team. (Note that if there is only one team left then this produces an empty list.)

Ｍε→Ｆυ«Ｍδ↑↗θ←↖θ→»Ｍθ↘

If there are still teams left, draw the zigzags joining them in pairs.

Ａδθ

Double the length of the zigzags each time.


Exponentiation to multiplication to addition Multiplication between 2 integers can be reduced into a series of addition like so

3 * 5 = 3 + 3 + 3 + 3 + 3 = 5 + 5 + 5

Exponentiation (raising a to the power b) can also be reduced into a series of multiplications:

5 ^ 3 = 5 * 5 * 5

Therefore, exponentiation can be reduced into a series of additions, by creating a multiplication expression, then into a series of additions. For example, 5 ^ 3 (5 cubed) can be rewritten as

5 ^ 3 = 5 * 5 * 5
      = (5 + 5 + 5 + 5 + 5) * 5
      = (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5)
      = 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5

Your task is, given expressions added together consisting of exponentiation, multiplication and addition, reduce it to the shortest series of additions. The "shortest" expression is defined as the expression with the fewest number of + symbols, still using only one of the two numbers in the original expression. For example, the shortest expression of 10 * 2 is 10 + 10.

The numbers involved in the input will all be positive integers, and the expression will consist of only + (addition), * (multiplication) and ^ (exponentiation), along with integers and brackets (()) to indicate precedence.

The output should consist of positive integers and + symbols only. You shouldn't output the individual steps of the reductions, just the final output. The output may not consist of any numbers that don't appear in the input. However, you may use any 3 distinct symbols instead of +*^, but please say what symbols they are

The spaces  separating inputs and outputs may or may not be used in your programs, i.e. 3 * 5 can be outputted as either 5 + 5 + 5 or 5+5+5.

Note that in most cases, addition is not actually performed. The only case where addition is to be performed is when you have something like 5 ^ (1 + 2), in which case, addition is necessary to continue -> 5 ^ 3 -> 5 * 5 * 5 -> .... See test case #4.

Your code does not need to handle inputs that arrive at an ambiguous expression. For example, (2 + 2) * (4 + 1). Because of the rules set forth so far, the goal is not to calculate the answer, the goal is to simplify to additions. So the result could be different depending on the order that expressions are resolved or commuted (which additions to simplify, which to leave?). Another invalid example: ((3 + 2) ^ 2) ^ 3 -> ((3 + 2) * (3 + 2)) ^ 3 -> ???.

This is code-golf so shortest code wins

Test cases

Input => output

5 ^ 3 + 4 * 1 ^ 5 => 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 4
2 ^ 1 * 2 + 3 + 9 => 2 + 2 + 3 + 9
2 ^ 1 * (2 + 3) + 9 => 2 + 3 + 2 + 3 + 9
2 ^ (1 * (2 + 3)) + 9 => 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 9
10 + 3 * 2 + 33 ^ 2 => 10 + 3 + 3 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33
100 * 3 => 100 + 100 + 100
2 ^ 1 + 2 ^ 1 + 2 ^ 2 + 8 ^ 1 => 2 + 2 + 2 + 2 + 8
(1 + 2 + 5 * 8 + 2 ^ 4) * 2 => 1 + 2 + 8 + 8 + 8 + 8 + 8 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 1 + 2 + 8 + 8 + 8 + 8 + 8 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2

Retina, 302 bytes
I'm sure this can be golfed, but at this point, I'm just glad it works. The exponentiation and multiplication sections are both very similar, but since order of operations is important, I don't know how to combine them.
y - Exponentiation
x - Multiplication
p - Addition
\d+
$*
{1`(\(\w+\)|1+)y(\(\w+\)|1+)
>$0<
(?<=>(\(\w+\)|1+)y1*)1
$1x
>(\(\w+\)|1+)y
(
x<
)
\((1+(x1+)*)\)(?!y)
$1
(?<!1)(1+)x(\(\w+\)|1+\1)(?!1)
$2x$1
1`(\(\w+\)|1+)x1+
>$0<
(?<=>(\(\w+\)|1+)x1*)1
$1p
>(\(\w+\)|1+)x
(
p<
)
(?<!x|y)\((1+(p1+)*)\)(?!x|y)
$1
y\((1+)p([1p]*\))
y($1$2
}`y\((1+)\)
y$1
1+
$.0

Try it online - all test cases
Test case converter
Explanation
\d+                             Convert to unary
$*
{1`(\(\w+\)|1+)y(\(\w+\)|1+)    Begin loop: Delimit current exponentiation group
>$0<
(?<=>(\(\w+\)|1+)y1*)1          Replace exponentiation with multiplication
$1x
>(\(\w+\)|1+)y                  Replace garbage with parentheses
(
x<
)
\((1+(x1+)*)\)(?!y)             Remove unnecessary parentheses around multiplication
$1
(?<!1)(1+)x(\(\w+\)|1+\1)(?!1)  Maybe swap order of multiplicands
$2x$1
1`(\(\w+\)|1+)x1+               Delimit current multiplication group
>$0<
(?<=>(\(\w+\)|1+)x1*)1          Replace multiplication with addition
$1p
>(\(\w+\)|1+)x                  Replace garbage with parentheses
(
p<
)
(?<!x|y)\((1+(p1+)*)\)(?!x|y)   Remove unnecessary parentheses around addition
$1
y\((1+)p([1p]*\))               Handle the 4th test case by adding if necessary
y($1$2
}`y\((1+)\)                     End of loop
y$1
1+                              Convert unary back to decimal
$.0

You may also notice that the most commonly used group is (\(\w+\)|1+). This matches an inner expression with parentheses, or an integer. I chose to use the symbols I did so that I could use \w rather than a character class. I'm not sure if it would be better to use non-word symbols and replace some lookarounds with word borders (\b).


Same length sub arrays Background:
Here's a little simple challenge. You want to be able to find out whether the arrays inside an array have the same length.
Input:
Your input should consist of exactly one array (this is the value passed to the function, not a user input). Your function takes exactly 1 parameter.  It could contain arrays or be empty. No error checking needed, assume only list is ever passed in. Assume a 1-D array such as [1] or [1,2,3,4,5] is never passed in.
Output:
Return true if all the list elements have the same length, false if they don't, and the parameter itself if the list is empty (or null if your language doesn't support multiple return types).
Some test cases:
List: [] - [] (or null/your language equivalent)
List: [[1], [1], [2]] - True
List: [[1]] - True
List: [[1, 2, 3, 4]] - True
List: [[1, 2, 3, 4, 5], [2], [12, 314123]] - False
List: [[1, 2, 3, 4], [1]] - False

No std(in/out) input/output needed (however, it is allowed, just not required!), the function only needs to return boolean values true or false; or the parameter itself if the function is passed an empty list (or null/your language equivalent). Only one return value is returned.
Rules:
Shortest byte count wins, only function is necessary (full programs are allowed if you desire).

Python 2, 31

lambda l:l and l==zip(*zip(*l))

This requires the lists to be lists of tuples. zip Drops extra elements if the input was ragged, so double zipping is only a noop if the lists all have the same length.

Try it here


Convert a HTML page into a mountain Task: convert a HTML page into a mountain!

When HTML pages are indented, they can look like:

But to be honest, a mountain is more representative of this structure.

So we can rewrite it as:

     /\
  /\/  \
 /      \
/        \

The outermost slashes on the left and right correspond to the outer div - each pair of HTML tags should be represented as / for the starting tag and \ for the ending tag - inside all tags are "higher", with the same structure.

Input:

There will be no <!DOCTYPE>
There will be no self-closing tags e.g.  or

There may be attributes or content inside the tags
There may be spaces or tabs - your program should ignore these
There will be no spaces between < or </ and the tag name
All input will be valid HTML

Output - a mountain representing the tags as above.

More testcases:

Input:

 HI

Output:

   /\
/\/  \

Input:

<body id="<">

Output:

/\

HTML + CSS + JavaScript, 39 + 141 + 20 = 200 bytes

Outputs visually to the webpage. To allow this to work with special elements like , all letters in the input are replaced.

p.innerHTML=prompt().replace(/\w/g,'a')
#p,#p *{display:flex;padding:0 0 1rem;align-items:flex-end;font-size:0}#p :before,#p :after{content:'/';font-size:1rem}#p :after{content:'\\'

HTML + CSS + JavaScript, 10 + 103 + 20 = 133 bytes

Solution that works if there is no content within tags.

p.innerHTML=prompt()
#p,#p *{display:flex;padding:0 0 1em;align-items:flex-end}#p :before{content:'/'}#p :after{content:'\\'


Can I print my picture on {A,B,C}{0-10} paper? The task is to find the smallest paper size on which it is possible to print a picture of the dimensions given in milimetres. The image will be printed without margins.
Input:
Two integers (bigger than zero) and a letter a, b, or c, for example:
290
200
A

Output:
Paper size, for example:

A4

Another examples:
218,297,a      A3
1,1,c          C10
9999,9999,c    ??? (error)
74,52,A        A8
31,44,B        B10
26,1100,A       A0
250,177,b     b4
250,176,b    b5
1189,841,a    a0

The dimensions of the paper for \$i \in \{0,\dots, 10\} \$ are:
$$ \left( \frac{\alpha}{\sqrt{2}^{i+1}} , \frac{\alpha}{\sqrt{2}^{i}} \right) $$
where \$\alpha\$ depends on the type of paper:
$$
\begin{eqnarray}
\alpha_A &=& 2 ^ {1/4} \\
\alpha_B &=& 2 ^ {1/2} \\
\alpha_C &=& 2 ^ {3/8} \\
\end{eqnarray}
$$

Upper- and lowercase variants of letters "A", "B" and "C" are
allowed on input and on output. You need to handle both of them.
The image can be printed vertically or horizontally.
The values can be passed as a parameter or entered by the user.
Width and height of picture will be always > 0 (and they will be always integers), and letters will be always 'a', 'b', or 'c'. You don't need to validate them.
You need to handle paper sizes A0 - A10, B0 - B10 and C0 - C10. If the image is too large, you can throw an exception, print an error or whatever you want, as long as it is clearly different from valid result and the application will not hung up.

Paper sizes, please ignore inch values (source: Wikipedia) :

This is code-golf - fewest bytes wins.

Charcoal, 38 bytes
η⊞θ×⌊θ₂²Ｉ⊖Ｌ↨⌊Ｘ∕×φＸ²∕⁺²⌕ACB↥η⁸⁻⌈θ·²¦²¦²

Try it online! Link is to verbose version of code. Takes input as a pair of integers and a characters. Explanation:
η

Output the paper letter.
⊞θ×⌊θ₂²

Multiply the smaller dimension by √2 and use that if it is larger than the larger dimension.
Ｉ⊖Ｌ↨⌊Ｘ∕×φＸ²∕⁺²⌕ACB↥η⁸⁻⌈θ·²¦²¦²

Calculate the largest size of paper, divide by the larger dimension (less 0.2 due to rounding errors), square the result, convert to binary, and count the digits (because Charcoal has no logarithm function).


ASCII Art Code Generator I have a program that generates formatted Brainfuck code. I run my program

./example "S"

and the output is

 +[>+
<
 +++
    ]
>--.

which prints S in Brainfuck.

Your objective is to write a program which accepts a string as input and outputs source code in another language which prints that string.

The source code your program outputs must be formatted in such a way that it represents the string in ASCII art (printed horizontally, not vertically).
The source code cannot contain the string (it may, however, contain letters that occur in the string, just not sequentially)

Otherwise,

Standard loopholes apply.
Shortest code wins.

Please title your submission with the language it is written in, the language it outputs, and the total size in bytes. Please include the output of your program when you enter the string UNCOPYRIGHTABLE.

Thanks!

Perl → Befunge, 868 bytes

OK, I'll get the ball rolling. This could be golfed down a bit more, but my head is starting to hurt...

$_=" f,j f,jjj f,lgdlH,b >llb ,l,b lb ,lb , f,j f j f >>l>,lb ,9vb >lb,Hlb,H>vb >999*+,
mg8Hg8Ha8c8g8Hgb8Hab8,8k/ 8Ha8Hi /H8HgH8g8k >H9ghgH9b 'bhbhgH9ghg9+gH9ga//
ma8Hg8Ha8c8ahgbhabhh /bhah VdhibHH9ghb >H9ghgH9abhbhgH*g9+g ii /b>l,^b //
>H^>>Hned*angne ned* eneknabnn<b nangn idH*gned*gneb*>>,b *kngH5g*6 Adb><aha//b
H*g2HgH3a4Hg5Ha6c7gHHgb1Hab2+3H ib4Ha5Hg6kiHH7g8c, id1H iabHk3k4+g >+ ,^>^dd 7/ ib *k //b
+1g+HgH+g+Hg+Ha+c+g,Hgb+kk >^+ki +Ha+Hg+HgH+g+cki'+ki ,gk+k>^gbHc^H 9*gb8+b//a
^<b ^>^ebe^'>^e >^e>>^a >^>> >^gd>^ke> >^b '>^e>>^g>^g e^ >^a >^~'i>^b i >2+^b >^b e>gHaV V >^gb>^bHHHHHH";
s/n/*H/g;s/m/H8g8HgH8/g;s/l/v>/g;s/k/Hb/g;s/j/f>,/g;s/i/\\/g;s/h/9H/g;s/g/bd/g;s/f/ve/g;s/e/>>>/g;s/d/ H/g;s/c/HaH/g;s/b/  /g;s/a/    /g;@f=split$/;
@s=split('',$ARGV[0]);foreach$r(0..6){for($i=0;$i<@s;$i++){print substr($f[$r],(ord($s[$i])-65)*6,6).$"}print$r?'':' @',$/}

Examples:

The shorter examples can be copy-pasted into online interpreters like this one, but UNCOPYRIGHTABLE appears to result in a program that is too long for all the online interpreters to handle.

$ perl bf.pl ABCDEFGHI
 v>>>, v>>>>,  v>>>, v>>>>, v>>>>, v>>>>,  v>>>, v>   H  Hv>H,  @
H8   H 8H   H H8   H 8H   H 8H     8H     H8   H 8H   H   8H
H8   H 8H   H H8     8H   H 8H     8H     H8     9H   H   9H
>H^>>H *H>>>  H*     *H   H *H>>>  *H>>>  H* >>> *H>>>H   *H
H*   H 2H   H H3     4H   H 5H     6H     H7   H HH   H   1H
+1   H +H   H H+   H +H   H +H     +H     H+   H ,H   H   +H
^<   ^ >^>>>   >>>^' >^>>>  >^>>>> >^      >^>>  >^   H  H>^H

$ perl bf.pl JKLMNOPQR
   >v> v>   , v>,    v>   , v>   ,  v>>>, v>>>>,  v>>>  v>>>>,  @
    8, 8H  /  8H     8H\ /H 8H   H H8   H 8H   > H9   H 9H   H
    9H 9H /   9H     9H V H 9H\  H H9   H 9H   > H9   H 9H   H
    *H *H<    *H     *H   H *H \ H H*   H *H>>>  H*   H *H>>>
    2+ 3H \   4H     5H   H 6H  \H H7   H 8H     H, \ H 1H \
H   >^ +H  \  +H     +H   H +H   H H+   H +H     HH  \' +H  \
 >>>>  >^   ' >^>>>> >^   H >^   H  >>>^  >^      >^~'\ >^   \

$ perl bf.pl STUVWXYZ
 v>>>  >>v>>, v>   , 9v   > v>  ,H v>  ,H >v   > 999*+,  @
H9   '   9H   9H   H H9   H 9H   H 9+   H H9   H     //
H9       9H   9H   H H*   H 9+   H  \\ /   >v>,^    //
 *>>,    *H   *H   H H5   H *6 A H   ><     9H     //
    HH   3H   4+   H  >+ ,^ >^ H H  7/ \    *H    //
,   HH   +H   >^   H   HH     H^H  9*   H   8+   //
 >2+^    >^    >>>>    HH     V V  >^   H   >^   HHHHHH

$ perl bf.pl UNCOPYRIGHTABLE
v>   , v>   ,  v>>>,  v>>>, v>>>>, >v   > v>>>>,  Hv>H,  v>>>, v>   H >>v>>,  v>>>, v>>>>, v>,    v>>>>,  @
9H   H 8H   H H8   H H8   H 8H   > H9   H 9H   H   8H   H8   H 8H   H   9H   H8   H 8H   H 8H     8H
9H   H 9H\  H H8     H9   H 9H   >  >v>,^ 9H   H   9H   H8     9H   H   9H   H8   H 8H   H 9H     8H
*H   H *H \ H H*     H*   H *H>>>    9H   *H>>>    *H   H* >>> *H>>>H   *H   >H^>>H *H>>>  *H     *H>>>
4+   H 6H  \H H3     H7   H 8H       *H   1H \     1H   H7   H HH   H   3H   H*   H 2H   H 4H     5H
>^   H +H   H H+   H H+   H +H       8+   +H  \    +H   H+   H ,H   H   +H   +1   H +H   H +H     +H
 >>>>  >^   H  >>>^'  >>>^  >^       >^   >^   \  H>^H   >^>>  >^   H   >^   ^<   ^ >^>>>  >^>>>> >^>>>>

Note:

The @ character at the end of the first line of output tells Befunge to stop running. Without it, the program would keep repeating the same word forever.


Check if all non-zero elements in a matrix are connected Input:

A matrix containing integers in the range [0 - 9].

Challenge:

Determine if all non-zero elements are connected to each other vertically and/or horizontally.

Output:

A truthy value if all are connected, and a falsy value if there are non-zero elements/groups that aren't connected to other elements/groups.

Test cases:

Test cases are separated by line. Test cases can be found in more convenient formats here (Kudos to Dada).

The following are all connected and should return a truthy value:

0
---
0 0
---
1 1 1
0 0 0
---
1 0 0
1 1 1
0 0 1
---
0 0 0 0 0 0
0 0 3 5 1 0
0 1 0 2 0 1
1 1 0 3 1 6
7 2 0 0 3 0
0 8 2 6 2 9
0 0 0 0 0 5

The following are all not-connected, and should return a falsy value:

0 1
1 0
---
1 1 1 0
0 0 0 2
0 0 0 5
---
0 0 5 2
1 2 0 0
5 3 2 1
5 7 3 2
---
1 2 3 0 0 5
1 5 3 0 1 1
9 0 0 4 2 1
9 9 9 0 1 4
0 1 0 1 0 0

This is code-golf, so the shortest submission in each language wins. Explanations are encouraged!

Inspired by this challenge.

Retina 0.8.2, 80 77 bytes

T`d`@1
1`1
_
+m`^((.)*)(1|_)( |.*¶(?<-2>.)*(?(2)(?!)))(?!\3)[1_]
$1_$4_
^\D+$

Try it online! Edit: Saved 1 byte thanks to @FryAmTheEggman. Explanation:

T`d`@1

Simplify to an array of @s and 1s.

1`1
_

Change one 1 to a _.

+m`^((.)*)(1|_)( |.*¶(?<-2>.)*(?(2)(?!)))(?!\3)[1_]
$1_$4_

Flood fill from the _ to adjacent 1s.

^\D+$

Test whether there are any 1s left.


Verify a Tower of Hanoi solution If you don't know what the Tower of Hanoi is, I'll explain it briefly: There are three rods and some discs each of which has a different size. In the beginning all discs are on the first tower, in sorted order: The biggest one is at the bottom, the smallest at the top. The goal is to bring all the discs over to the third rod. Sounds easy? Here's the catch: You can't place a disc on top of a disc that is smaller than the other disc; you can only hold one disc in your hand at a time to move them to another rod and you can only place the disc on rods, not on the table, you sneaky bastard.

ascii example solution:

  A      B      C
  |      |      |
 _|_     |      |
__|__    |      |

  A      B      C
  |      |      |
  |      |      |
__|__   _|_     |

  A      B      C
  |      |      |
  |      |      |
  |     _|_   __|__

  A      B      C
  |      |      |
  |      |     _|_
  |      |    __|__

Challenge

There are three rods called A,B and C. (You can also call them 1,2 and 3 respectivly if that helps) In the beginning all n discs are on rod A(1).

Your challenge is to verify a solution for the tower of hanoi. You'll need to make sure that:

In the end all n discs are on rod C(3).
For any given disc at any given state there is no smaller disc below it.
No obvious errors like trying to take discs from an empty rod or moving discs to nonexistant rods.

(the solution does not have to be optimal.)

Input

Your program will receive two inputs:

The number of discs n (an integer)
The moves which are taken, which will consist of a set of tuples of: (tower to take the currently uppermost disc from),(tower to take this disc to) where each tuple refers to a move. You can choose how they are represented. For example something like the following ways of representing the solution for n=2 which I've drawn in ascii above. (I'll use the first one in the test cases, because it's easy on the eyes):

"A->B ; A->C ; B->C"

[("A","B"),("A","C"),("B","C")]

[(1,2),(1,3),(2,3)]

"ABACBC"

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

Output

Truthy, if the conditions that can be found under "challenge" hold.
Falsy, if they don't.

Test cases:

True:

n=1, "A->C"

n=1, "A->B ; B->C"

n=2, "A->B ; A->C ; B->C"

n=2, "A->C ; C->B ; A->C ; B->C"

n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C"

n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"

n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C"

False:

3rd one suggested by @MartinEnder, 7th by @Joffan

n=1, "A->B"

n=1, "C->A"

n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"

n=2, "A->B ; A->C ; C->B"

n=2, "A->C ; A->B ; C->B ; B->A"

n=2, "A->C ; A->C"

n=3, "A->B ; A->D; A->C ; D->C ; A->C"

n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"

n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C"

n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B"

n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C"

n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C"

This is code-golf, shortest solution wins. Standard rules and loopholes apply. No batteries included.

Retina, 167 165 157 150 123 bytes

This totally looks like a challenge that should be solved with a single regex... (despite the header saying "Retina", this is just a vanilla .NET regex, matching valid inputs).

^(?=\D*((?=(?<3>1+))1)+)((?=A(?<1-3>.+)|B(?<1-4>.+)|C(?<1-5>.+)).(?=A.*(?!\3)(\1)|B.*(?!\4)(\1)|C.*(?!\5)(\1)).)+(?!\3|\4)1

Input format is the list of instructions of the form AB, followed by n in unary using the digit 1. There are no separators. Output is 1 for valid and 0 for invalid.

Try it online! (The first two characters enable a linefeed-separated test suite.)

Alternative solution, same byte count:

^(?=\D*((?=(?<3>1+))1)+)((?=A(?<1-3>.+)|B(?<1-4>.+)|C(?<1-5>.+)).(?=A.*(?!\3)(\1)|B.*(?!\4)(\1)|C.*(?!\5)(\1)).)+(?<-5>1)+$

This can possibly be shortened by using 1, 11 and 111 instead of A, B and C but I'll have to look into that later. It might also be shorter to split the program into several stages, but where's the challenge in that? ;)

Explanation

This solution makes heavy use of .NET's balancing groups. For a full explanation see my post on Stack Overflow, but the gist is that capturing groups in .NET are stacks, where each new capture pushes another substring and where it's also possible to pop from such a stack again. This lets you count various quantities in a string. In this case it lets us implement the three rods directly as three different capturing groups where each disc is represented by a capture.

To move discs around between rods we make use of a weird quirk of the (?<A-B>...) syntax. Normally, this pops a capture from stack B and pushes onto stack A the string between that popped capture and the beginning of this group. So (?<A>a).(?<B-A>c) matched against abc would leave A empty and B with b (as opposed to c). However, due to .NET variable-length lookbehinds it's possible for the captures of (?<A>...) and (?<B-A>...) to overlap. For whatever reason, if that's the case, the intersection of the two groups is pushed onto B. I've detailed this behaviour in the "advanced section" on balancing groups in this answer.

On to the regex. Rods A, B and C correspond to groups 3, 4 and 5 in the regex. Let's start by initialising rod A:

^                 # Ensure that we start at the beginning of the input.
(?=               # Lookahead so that we don't actually move the cursor.
  \D*             # Skip all the instructions by matching non-digit characters.
  (               # For each 1 at the end of the input...
    (?=(?<3>1+))  # ...push the remainder of the string (including that 1)
                  # onto stack 3.
  1)+
)

So e.g. if the input ends with 111, then group 3/rod A will now hold the list of captures [111, 11, 1] (the top being on the right).

The next bit of the code has the following structure:

(
  (?=A...|B...|C...).
  (?=A...|B...|C...).
)+

Each iteration of this loop processes one instruction. The first alternation pulls a disc from the given rod (onto a temporary group), the second alternation puts that that disc onto the other given rod. We'll see in a moment how this works and how we ensure that the move is valid.

First, taking a disc off the source rod:

(?=
  A(?<1-3>.+)
|
  B(?<1-4>.+)
|
  C(?<1-5>.+)
)

This uses the weird group-intersection behaviour I've described above. Note that group 3, 4 and 5 will always hold substrings of 1s at the end of the string whose length corresponds to the disc's size. We now use (?<1-N>.+) to pop the top disc off stack N and push the intersection of this substring with the match .+ onto stack 1. Since .+ always necessarily covers the entire capture popped off N, we know that this simply moves the capture.

Next, we put this disc from stack 1 onto the stack corresponding to the second rod:

(?=
  A.*(?!\3)(\1)
|
  B.*(?!\4)(\1)
|
  C.*(?!\5)(\1)
)

Note that we don't have to clean up stack 1, we can just leave the disc there, since we'll put a new one on top before using the stack again. That means we can avoid the (?<A-B>...) syntax and simply copy the string over with (\1). To ensure that the move is valid we use the negative lookahead (?!\N). This ensures that, from the position where we want to match the current disc, it's impossible to match the disc already on stack N. This can only happen if either a) \N will never match because the stack is completely empty or b)the disc on top of stackNis larger than the one we're trying to match with\1`.

Finally, all that's left is ensuring that a) we've matched all instructions and b) rods A and B are empty, so that all discs have been moved onto C.

(?!\3|\4)1

We simply check that neither \3 nor \4 can match (which is only the case if both are empty, because any actual disc would match) and that we can then match a 1 so that we haven't omitted any instructions.


Can even numbers become prime? The Sequence

Everyone knows the only even prime number is 2. Ho-hum. But, there are certain even numbers n where, when concatenated with n-1, they become a prime number.

For starters, 1 isn't in the list, because 10 isn't prime. Similarly with 2 (21), and 3 (32). However, 4 works because 43 is prime, so it's the first number in the sequence a(1) = 4. The next number that works (neither 6 (65) nor 8 (87) work) is 10, because 109 is prime, so a(2) = 10. Then we skip a bunch more until 22, because 2221 is prime, so a(3) = 22. And so on.

Obviously all terms in this sequence are even, because any odd number n when concatenated with n-1 becomes even (like 3 turns into 32), which will never be prime.

This is sequence A054211 on OEIS.

The Challenge

Given an input number n that fits somewhere into this sequence (i.e., n concatenated with n-1 is prime), output its position in this sequence. You can choose either 0- or 1-indexed, but please state which in your submission.

Rules

The input and output can be assumed to fit in your language's native integer type.
The input and output can be given in any convenient format.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

The below examples are 1-indexed.

n = 4
1

n = 100
11

n = 420
51

Jelly,  8  7 bytes

ḊżṖVÆPS

A monadic link taking a sequence member and returning its index in the sequence.

Try it online!

How?

ḊżṖVÆPS - Link: number, n
Ḋ       - dequeue (implicit range) = [ 2   , 3   , 4   ,... ,              n         ]
  Ṗ     - pop (implicit range)     = [   1 ,   2 ,   3 ,... ,                  n-1   ]
 ż      - zip                      = [[2,1],[3,2],[4,3],... ,             [n , n-1]  ]
   V    - evaluate as Jelly code   = [ 21  , 32  , 43  ,... ,         int("n"+"n-1") ]
    ÆP  - is prime? (vectorises)   = [  0  ,  0  ,  1  ,... , isPrime(int("n"+"n-1"))]
      S - sum


How many answers does this question have? Write a program or a function that outputs the integer number of answers this question has. Your solution should still work as more answers are added.

Languages that run in a browser may be run from the js console while on this page. Otherwise, you'd probably have to download this page. Multi-language solutions, e.g. wgeting the page and parsing it using grep is ok. Just sum up the command line and all source used.

This is code golf; shortest answer in bytes wins.

EDIT:

Let's allow at most one occourance of the url of this page to not count, either as input or in the source. No url shorteners, no data stored as get parameters etc. Quotes around url, if needed, still count. Taking the url as input is also fine. If you want to remove some part of the url, e.g. /how-many-answers..., you can, but it probably doesn't help you.

Javascript + jQuery, 23 bytes

_=>+$("h2>span").text()


Output a primitive element for each field size A primitive element of a finite field is a generator of the multiplicative group of the field. In other words, alpha in F(q) is called a primitive element if it is a primitive q−1th root of unity in F(q).  This means that all the non-zero elements of F(q) can be written as alpha^i for some (positive) integer i.

All elements of the field F_{2^k} can be written as polynomials of degree at most k-1 with coefficients that are either 1 or 0.   In  order to make this complete, your code also needs to output an irreducible polynomial of degree k which defines the field you are using.

The task is write code that outputs a primitive element of F_{2^k} of your choosing for each k = 1 .. 32 in order.

Your output  must simply list the k coefficients of the primitive element in any format that you like and then  on a separate line the k+1 elements of the irreducible polynomial.  Please separate the outputs for each value of k if possible.

Your code may take as long as you like but you must have run it to completion before submitting your answer.

You may not use any builtin or library function which returns primitive elements of a finite field or tests whether an element is primitive.

An example

For k = 1 the only primitive element is 1.

For k = 2 we have  F_4. The 4 elements are {0, 1, x, x + 1} so there are two primitive elements x and x + 1.  So the code could output

1 1
1 1 1

as the coefficients for example where the second line is the irreducible polynomial which in this case is x^2+x+1 which has coefficients 1 1 1.


Finding Lonely Primes Lonely primes (as I call them) are primes, where given a number grid with width w ≥ 3, are primes which do not have any other primes adjacent to them orthogonally or diagonally.

For example, if we take this grid where w = 12 (primes highlighted in bold):

1   2   3   4   5   6   7   8   9   10  11  12
13  14  15  16  17  18  19  20  21  22  23...
 ...86  87  88  89  90  91  92  93  94  95  96
97  98  99  100 101 102 103 104 105 106 107 108
109 110 111 112 113 114 115 116 117 118 119 120

You can see that only the two primes 103 and 107 have no primes orthogonally or diagonally adjecant whatsoever. I've skipped over a section because there's no lonely primes there. (except 37, actually)

Your task is to, given two inputs w ≥ 3 and i ≥ 1, determine the first lonely prime in a number grid with width w, where said lonely prime must be greater than or equal to i. Inputs may be taken in any reasonable format (including taking them as strings). It is guaranteed there will be a lonely prime for width w.

The grid doesn't wrap around.

Examples:

w  i   output
11 5   11
12 104 107
12 157 157
9  1   151
12 12  37

As this is code-golf, shortest code wins!

C (gcc), 159 158 149 145 bytes

Saved a byte thanks to xanoetux; removing one newline character.
Saved nine thirteen bytes thanks to ceilingcat; golfing a break condition.

P(n,d,b){for(d=b=1<n;n>++d;)b*=n%d>0;n=b;}F(w,i){w=P(i)&!(P(i-w)|P(i+w)|i%w>1&(P(--i)|P(i-w)|P(i+w))|++i%w>0&(P(++i)|P(i-w)|P(i+w)))?i-1:F(w,i);}

Try it online!


Tips for Golfing in Batch Windows Batch (CMD) is probably the least suitable language for code golfing.

Avoid newline characters. If you're looking for the shortest code in bytes, as opposed to characters, you will want to get rid of all unnecessary carriage returns (newline characters = 2 bytes). You can use the & operation to do this, trimming one byte for each command.

echo Hello&echo World.

Setting variables. When setting variables using switches, the set parser will ignore spaces.

set /a a+=1
set /p b="User Input: "
:: Will be handled the same as..
set/aa+=1
set/pb="User Input: "

Note that the same parser rules do not apply to all commands - as an example, for loops require spaces. Except between the set, string, or command (i.e. what is inside the brackets) and the word do.

for /f %%a in (file.txt)do ...

Simple mathematical expressions. Also, notice the expression that I used for incrementing in the set /a command. For simple mathematical expressions use += -= *= /= instead of (for example) set /a a=%a%+1.

Gathering command output. To get the output of a command, it can sometimes be useful to output to and read from a file, where you otherwise might have used a for loop to gather the output:

for /f %%a in ('echo test') do set a=%%a
:: Can be shortened to
echo test>f&set/pa=<f

echo test send stdout to a file called f, >f, start a new command & and get the contents of the file in a variable set/pa=<f. Obviously this isn't always useful. But it can be when all you need is a single line of output.

Command output. When suppressing command output, use @ before the commands, unless you need to suppress more than 9 commands, in which case, use @echo off at the start of your script. @echo off is 9 bytes long, and therefore will generally save more bytes with longer scripts.

Commands often do more than just what is obvious - think about what your commands are doing. For example; if you need to set a variable and echo another variable, instead of:

set a=OUTPUT
echo %a%
echo test>f
set /p b=<f

You can use the set command with the /p switch to output %a% for you.

set a=OUTPUT
echo test>f
set /p b=%a%<f

Completely golfed...

set a=OUTPUT&echo test>f&set/pb=%a%<f

A couple of expamples - Count sum of all digits - Goldbach's conjecture.

Any other tips are more than appreciated - I'll keep updating this if I think of anything else.

Counters

Whenever you have a variable that will act as a counter starting from 0 you might want to write

set count=0
set/acount+=1

; however, you can eliminate the first lines because whenever set/a is used with an unset variable its value is assumed to be 0

set/acounter+=1

Code Blocks

There a number of ways you can shave off a few bytes when you have to used blocks of code.

Whenever you open a code block, you do not need to insert a line break before the first line of code in that block. The closing parentheses does not have to be on a line of its own either.

If %a%==%b% (
     echo true
) else (
    echo false
)

can be golfed to

If %a%==%b% (echo true)else (echo false)

Printing Without Trailing New Line

The common pattern for this is

echo|set/p=text

but, you can save 2 bytes changing echo to cd

cd|set/p=text


Can Pac-Man Eat This String? In the arcade version of the game, Pac-Man eats pac-dots. However, in this challenge, he's hungry for alphanumeric characters and punctuation in a string.

Your task is to create a function that feeds Pac-Man a string, evaluates if he can eat it or not, and returns the string with Pac-Man's location in it.

Pac-Man (<) eats characters from left to right, leaving an underscore or space for each character as he goes, and his goal is to get from the first position-1 to the last position+1:

1. <Pac
2. _<ac
3. __<c
4. ___<

However, Pac-Man's natural enemy, the ghost, will stop him if he encounters one of the letters in the word "GHOST" (not case sensitive). Your function should return the string with Pac-Man's location as he encounters the ghost character:

1. <No!
2. _<o!

The only thing that can defeat a ghost is a power pellet. If Pac-Man reaches a letter in the word "PELLET" (also not case sensitive) before coming to a ghost, he will eat the ghost and keep moving, and that pellet will be used up. Power pellets can stack (ie, in ppgg both ghosts would be eaten). The T character exists as both as a ghost and a pellet, so it can be ignored (treated as any other letter, like a).

1. <Pop
2. _<op
3. __<p
4. ___<

To further clarify, in the string "Pac-Man loses here", the following operations occur:

P <P, +1 Pellet (1 pellet)
a <a
c <c
- <-
M <M
a <a
n <n
  <[space]
l <l, +1 Pellet (2 pellets)
o <o, -1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
e <e, +1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
  <[space]
h <h, ghost wins, returns
e
r
e

Examples

Input: Pacman wins!
Output: ____________<

Input: Pacman loses wah-wah :(
Output: _______________<h-wah :(

Input: PELLET PELLET GHOST
Output: ___________________<

Input: Hello World!
Output: <Hello World!

Input: <_!@12<_<_<
Output: ___________<

This is code-golf--lowest score in bytes wins.

Retina, 55 38 bytes

i`^(([elp])|[^ghos]|(?<-2>.))*
$.&$*_<

Try it online! (The first line just allows running several test cases at once.)

Explanation

The problem is essentially to find the longest prefix that doesn't have an unmatched closing parenthesis. Except that we can use either e, l or p in place of ( and either g, h, o or s in place of ).

Hence, this solution is almost a textbook example of balancing groups. I won't go into too much detail about how they work, as this code is essentially the same as the standard example you can read up on in my SO answer on balancing groups.

The entire program is therefore a single regex substitution. The i activates case-insensitivity. Then we either match a pellet with [elp] and increment the depth counter (in the form of the capture stack of group 2), or we match something that isn't a ghost with [ghos] or we match a ghost with . and decrement the depth counter by popping from stack 2. Of course, in principle this allows matching a pellet with the [^ghos] section or a non-ghost with the . section, but thanks to greedy matching and the way the regex is backtracked, these possibilities are never attempted by the regex engine.

The substitution then uses two Retina specific features: $* repeats the character to its right as many times as specified by the token on its left. That token is $.& which is the length of the entire match. This just means that we replace each character in the match with a _. And then we also append a < to those underscores. The part of the input that isn't eaten simply remains unaffected by the substitution.


Nether Portal Detection The video game Minecraft is all about placing and removing different types of blocks in the 3D integer lattice that makes up the virtual world. Each lattice point can contain exactly one block or be empty (an "air" block officially). In this challenge, we will only be concerned with one vertical 2D plane of the 3D world, and one type of block: obsidian.

When obsidian forms the outline of an empty rectangle in a vertical plane, a nether portal can be created. The empty rectangle may be any size from 2 units wide by 3 units high to 22 units wide by 22 units high. The corners of the rectangle do not need to be bordered in obsidian, just the sides.

For example, suppose X is obsidian and . is emptiness: (The numbers are just for identification purposes and are also empty.)

...................................
..XXXX....XXXX....XXXXXXXXX........
..X..X...X....X..X.........X..XXXX.
..X.1X...X.2..X..X...3...X.X..X....
..X..X...X....XXXX.........X..X.6X.
..XXXX....XXXX...XXXXXXXXXXX..X..X.
.............X.4.X....X.5.X...XXXX.
.............X...X....X...X........
..............XXX......XXX.........
...................................

This grid contains 3 valid portals:

Portal 1 is 2 by 3 units, totally empty, and bordered in obsidian. Therefore it's valid.
Portal 2 is 4 by 3, totally empty, and bordered in obsidian. Therefore it's valid.
Portal 3 isn't totally empty. Therefore it's invalid.
Portal 4 is 3 by 3, totally empty, and bordered in obsidian. Therefore it's valid.
Portal 5 is 3 by 2 units, which is too small. Therefore it's invalid.
Portal 6 is missing a part of the border. Therefore it's invalid.

Challenge

Write a program or function that takes in these string representations of grids of obsidian and emptiness, and prints or returns the number of valid nether portals present.

Input can be from stdin or file or function argument.
You may assume the input is always well formed - i.e. a perfectly rectangular grid of text, at least 1 character wide and tall, only containing X and .. You may optionally assume there is a trailing newline after the last row.
If desired, you may use any two distinct printable ASCII characters in place of X and ..
Obsidian may be on the borders of the grid. Anything beyond the borders is considered empty.

Example input - the output should be 4:

................................................................
...................................XXXXXXXXXXXXXXXXXXXXXXXXX....
..XXXX....XXXX....XXXXXXXXX........X.......................X....
..X..X...X....X..X.........X..XXXX.X.......................X....
..X..X...X....X..X.......X.X..X....X.......................X....
..X..X...X....XXXX.........X..X..X..XXXXXXXXXXXXXXXXXXXXXXXX....
..XXXX....XXXX...XXXXXXXXXXX..X..X.X......................X..XXX
.............X...X....X...X...XXXX.X......................X..X..
.............X...X....X...X........X......................X..X..
..............XXX......XXX........XXXXXXXXXXXXXXXXXXXXXXXX...X..
..................................XX.........................XXX

Scoring

The submission with the fewest bytes wins.

Regex (.NET flavour), 182 181 145 132 126 114 104 100 98 97 96 bytes

2D ASCII art pattern recognition? Sounds like a job for regex! (It doesn't.)

I know this is going to kick loose endless discussions again about whether regex submissions are valid programs or not, but I doubt this will beat APL or CJam anyway, so I don't see any harm. (That being said, they do pass our die-hard test for "What is a programming language?".)

This takes input as the string to be matched, and the result is the number of matches found. It uses _ in place of ., because I'd have to escape the latter. It also requires a trailing newline.

(X(X){1,21})(?=\D+((?>(?<-2>_)+)_))(?=.((?!\7)(.)*
.*(X\3X|()\1.)(?=(?<-5>.)*(?(5)!)
)){4,23}\7)

You can test it live at RegexHero or RegexStorm). The matches will be the top obsidian rows of the portals. If you can find a test case where it fails, please let me know!

What is this sorcery?

The following explanation assumes a basic understanding of .NET's balancing groups. The gist is that captures are stacks in .NET regex - every new capture for the same name is pushes onto the stack, but there's also syntax to pop captures from those stacks again, as well as syntax to pop captures from one stack and push captures onto another at the same time. For a more complete picture, you can have a look at my answer on Stack Overflow which should cover all the details.

The basic idea is to match a pattern like:

 X{n}..{m}
X_{n}X.{m} |
X_{n}X.{m} |  3 to 22 times
X_{n}X.{m} |
 X{n}..{m}

Where n is between 2 and 22 (inclusive). The tricky thing is getting all the ns and all the ms to be the same. Since the actual characters won't be the same, we can't just use a backreference.

Note that the regex has to embedded newlines, which I'll write as \n in the following.

(                     # Open capturing group 1. This will contain the top of a portal, which
                      # I can reuse later to match the bottom (being of the same length).
  X                   # Match a single X.
  (X){1,21}           # Match 1 to 21 X's, and push each separately on the <2> stack. Let's
                      # Call the number of X's captured N-1 (so N is the inner width of the
                      # portal).
)                     # End of group 1. This now contains N X's.
(?=                   # Start a lookahead. The purpose of this lookahead is to capture a
                      # string of N underscores in group 2, so I can easily use this to match
                      # the inside rows of the portal later on. I can be sure that such a
                      # string can always be found for a valid portal (since it cannot have 0
                      # inner height).
  \D+                 # Skip past a bunch of non-digits - i.e. *any* of the vaild characters
                      # of the input (_, X, \n). This to make sure I search for my N
                      # underscores anywhere in the remainder of the input.
  (                   # Open capturing group 3. This will contain a portal row.
    (?>               # This is an atomic group. Once the engine hass successfully matched the
                      # contents of this group, it will not go back into the group and try to
                      # backtrack other possible matches for the subpattern.
      (?<-2>_)+       # Match underscores while popping from the <2> stack. This will match as
                      # many underscores as possible (but not more than N-1).
    )                 # End of the atomic group. There are two possible reasons for the
                      # subpattern stopping to match: either the <2> stack is empty, and we've
                      # matched N-1 underscores; or we've run out of underscores, in which
                      # case we don't know how many underscores we matched (which is not
                      # good).
    _                 # We simply try to match one more underscore. This ensures that we
                      # stopped because the <2> stack was empty and that group 3 will contain
                      # exactly N underscores.
  )                   # End of group 3.
)                     # End of the lookahead. We've got what we want in group 2 now, but the
                      # regex engine's "cursor" is still at the end of the portal's top.
(?=                   # Start another lookahead. This ensures that there's actually a valid
                      # portal beneath the top. In theory, this doesn't need to be a
                      # lookahead - I could just match the entire portal (including the lines
                      # it covers). But matches cannot overlap, so if there were multiple
                      # portals next to each other, this wouldn't return all of them. By
                      # putting the remainder of the check in a lookahead the actual matches
                      # won't overlap (because the top cannot be shared by two portals).
  .                   # Match either _ or X. This is the character above the portal side.

  (                   # This group (4) is where the real magic happens. It's purpose is to to
                      # count the length of the rest of the current line. Then find a portal
                      # row in the next line, and ensure that it's the same distance from the
                      # end of the line. Rinse and repeat. The tricky thing is that this is a
                      # single loop which matches both inner portal rows, as well as the
                      # bottom, while making sure that the bottom pattern comes last.

    (?!\7)            # We didn't have a group 7 yet... group 7 is further down the pattern.
                      # It will capture an empty string once the bottom row has been matched.
                      # While the bottom row has not been matched, and nothing has been
                      # captured, the backreference will fail, so the negative lookahead will
                      # pass. But once we have found the bottom row, the backreference will
                      # always match (since it's just an empty string) and so the lookahead
                      # will fail. This means, we cannot repeat group 4 any more after the
                      # bottom has been matched.
    (.)*              # Match all characters until the end of the line, and push each onto
                      # stack <5>.
    \n                # Match a newline to go to the next line.
    .*                # Match as many characters as necessary to search for the next portal
                      # row. This conditions afterwards will ensure that this backtracks to
                      # the right position (if one exists).
    (                 # This group (6) will match either an inner portal row, or the bottom
                      # of the portal.
      X\3X            # Match X, then N underscores, then X - a valid inner portal row.
    |                 # OR
      ()              # Capture an empty string into group 7 to prevent matching further rows.
      \1.             # Use the captured top to match the bottom and another character.
    )
    (?=               # This lookahead makes sure that the row was found at the same
                      # horizontal position as the top, by checking that the remaining line
                      # is the same length.
      (?<-5>.)*       # Match characters while popping from the <5> stack.
      (?(5)!)\n       # Make sure we've hit end of the line, *and* the <5> stack is empty.
    )
  ){4,23}             # Repeat this 4 to 23 times, to ensure an admissible portal height.
                      # Note that this is one more than the allowed inner height, to account
                      # for the bottom row.
  \7                  # Now in the above repetition there is nothing requiring that we have
                      # actually matched any bottom row - it just ensured we didn't continue
                      # if we had found one. This backreference takes care of that. If no
                      # bottom row was found, nothing was captured into group 7 and this
                      # backreference fails. Otherwise, this backreference contains an empty
                      # string which always matches.
)

C#, 185 bytes

Here is a full C# function, just to make this a valid entry. It's time I wrote a command-line "interpreter" for .NET regular expressions...

static int f(string p){return System.Text.RegularExpressions.Regex.Matches(p,@"(X(X){1,21})(?=\D+((?>(?<-2>_)+)_))(?=.((?!\7)(.)*
.*(X\3X|()\1.)(?=(?<-5>.)*(?(5)!)
)){4,23}\7)").Count;}


Count like Chuck Norris As is well known,

  Chuck Norris counted to infinity. Twice

Besides,

  Chuck Norris can count to infinity backwards.

Also, although perhaps less known, Chuck Norris can speak a little Spanish in addition to English.

The challenge

Write a program (or function) that can be run in two different languages. In one language the program should output the sequence

1, 1, 2, 2, 3, 3, 4, 4, ...

and in the other language it should produce the sequence (including leading zeros)

1, 2, ..., 9, 01, 11, 21, 31, ..., 89, 99, 001, 101, 201, ...

Rules

Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
Different versions of the same language (such as Python 2/3) don't count as different languages. Related languages (such as C/C++ or Matlab/Octave) do count as different.
No input will be taken.
The program should continue to output terms of the sequence until stopped by the user. Since the program will not stop by itself, output cannot be produced at the end. It must be produced while the program runs, either continuously or in batches.
Output can use STDOUT or equivalent, or can be displayed in a graphic window. Any non-numeric separator between sequence terms is allowed, as long as each term can be clearly distinguished from its neighbouring terms. It is also acceptable if the screen is cleared between terms.
Either sequence can start at 0 instead of 1. In that case, in the "twice" sequence the 0 should be repeated, just like the other numbers.
Leading zeros are significant in the "backwards" sequence. For example, the tenth term is 01; neither 1 nor 001 are acceptable.
If the two languages use different character encodings, the program is defined by its bytes, not its characters. That is, the bytes should be the same in the two languages.
Shortest code in bytes wins.

Python 2/C (clang), 109 107 100 84 95 88 89 88 87 84 bytes

i=0;
#/*
while 1:i+=1L;print`i`[::-1]
'''*/
a(){for(;;)printf("%i %1$i ",++i);}//'''

Python: Try it online!

C: Try it online!

The L in the Python code is part of the delimiter.

Explanation:

In the C code, It first sets i to 0. Then, it starts a comment (# is valid code in C for #include statements) where the Python code goes. At the end of the comment, it defines a function that forever increments a variable and prints it twice, space-delimited. It then begins a comment.

In the Python code, i=0; sets i to zero. Python ignores the next line because # starts a single-line comment. It then forever increments it and turns it into a long a number and prints its reversed string representation. The 'L' from the long is part of the delimiter. After that, it starts a multi-line string to comment the C code, that ends later.

-2 bytes thanks to @LuisMendo. -7 bytes thanks to @ZacharyT. -6 more bytes thanks to @ZacharyT. +11 bytes to fix a bug thanks to @mbomb007. -7 bytes thanks to @Doorknob. +1 byte to fix a bug thanks to @Doorknob. -1 byte thanks to @yoann. -1 more byte thanks to @yoann. -3 bytes thanks to @Cyoce.