You are given a string to make and starting with the empty string, make it using appending and cloning cost Your task is to create the given target string. Starting with an string that is empty, you will have to add characters to it, until your string is the same as the one we want. You can either add a character to the end of you string with cost x, or you can clone you string with cost y. What we want is the cheapest way to do this.
Test Cases
targetString , appendcost, clonecost -> totalcost

"bb", 1, 2 -> 2
"bbbb", 2, 3 -> 7
"xzxpcxzxpy", 10, 11 -> 71
"abababab", 3, 5 -> 16
"abababab", 3, 11 -> 23

Husk, 25 bytes

φ?ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ0

Try it online!

Inputs are in the order append cost, clone cost, target.

Explanation

φ?ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ0  Two explicit inputs and one implicit.
                           Example: 2, 3, s="abab"
φ                          Make a recursive function and call it on s:
 ?                      0   If s is empty, return 0.
  ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ    Otherwise do this.
                       ḣ    Prefixes: ["a","ab","aba","abab"]
                    otṫ     Suffixes except the first one: ["bab","ab","b"]
               §δf`€        Keep those prefixes that have the corresponding suffix as substring: ["ab","aba"]
            §:h             Prepend s minus last character: ["aba","ab","aba"]
          m⁰                Recurse on each: x=[6,4,6]
        ∞²                  Repeat the clone cost: [3,3,3,..
      :⁴                    Prepend append cost: [2,3,3,3,..
    z+                      Add component-wise to x: [8,7,9]
   ▼                        Minimum: 7


Evaluate a chain of inequalities Write code to evaluate whether a chain of inequalities is true or false. An example input is the string

3<=4!=9>3==3

This is true because each of its components is true:

(3<=4) and (4!=9) and (9>3) and (3==3)

Input:

A string that represents a chain of one or more inequalities. The allowed comparison operators are

==   equals
!=   does not equal
>    is greater than
>=   is greater than or equal to
<    is less than
<=   is less than or equal to

The allowed numbers are single-digit numbers 0 through 9. There won't be any spaces, parentheses, or other symbols.

Output:

The correctness of the inequality as a consistent Truthy or Falsey value. Consistent means every Truthy output is the same and every Falsey output is the same.

Restriction:

The intent of this challenge is for you to write code that processes the inequalities, rather than have them be evaluating them as code, even for a single inequality in the chain. As such, methods like Python's eval and exec that evaluate or execute code are banned. So are functions which look up a method or operator given its name as a string. Nor is it allowed to launching processes or programs to do the evaluation for you.

Test cases:

3<=4!=9>3==3
True

3<=4!=4
False

5>5
False

8==8<9>0!=2>=1
True

Ruby, 71 + 1 = 72

With command-line flag -n, run

p (0..99).none?{|i|~/#{a=i%10}(#{%w/!=|. <?=* >?=*/[a<=>b=i/10]})#{b}/}

Generates all possible failing regular expressions, and checks whether the input string matches any of them. Outputs true if none do, else false. Takes input via STDIN, separated by newlines.

Tricks:

We get all possible pairs of digits by looping from 0 to 99 and extracting the 10s and 1s digits.
The only actual comparison we do is a<=>b, which returns -1,0,or 1 for less than, equal to, or greater. These all slice to different elements of a three-string array, finding the regular expression for comparisons that don't match.


Calculating Collatz Cousins Define the function f(n) for a positive integer n as follows:

n / 2, if n is even
3 * n + 1, if n is odd

If you repeatedly apply this function to any n greater than 0, the result always seems to converge to 1 (though nobody's been able to prove that yet). This property is known as the Collatz Conjecture.

Define an integer's stopping time as the number of times you have to pass it through the Collatz function f before it reaches 1. Here are the stopping times of the first 15 integers:

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

Let's call any set of numbers with the same stopping time Collatz cousins. For example, 5 and 32 are Collatz cousins, with a stopping time of 5.

Your task: write a program or function that takes a nonnegative integer and generates the set of Collatz cousins whose stopping time is equal to that integer.

Input

A nonnegative integer S, given via STDIN, ARGV, or function argument.

Output

A list of all numbers whose stopping time is S, sorted in ascending order. The list may be output by your program, or returned or output by your function. Output format is flexible: space-separated, newline-separated, or any standard list format of your language is fine, as long as the numbers are easily distinguishable from one another.

Requirements

Your submission must give correct results for any S ≤ 30. It should finish in seconds or minutes, not hours or days.

Examples

0  -> 1
1  -> 2
5  -> 5, 32
9  -> 12, 13, 80, 84, 85, 512
15 -> 22, 23, 136, 138, 140, 141, 150, 151, 768, 832, 848, 852, 853, 904, 906, 908, 909, 5120, 5376, 5440, 5456, 5460, 5461, 32768

Here is a Gist of the output for S = 30.

This is code-golf: shortest program in bytes wins. Good luck!

Mathematica, 98 92 89 bytes

This solution solves S = 30 immediately:

(p={0};l={1};Do[l=Complement[##&@@{2#,Mod[a=#-1,2]#~Mod~3~Mod~2a/3}&/@l,p=p⋃l],{#}];l)&

This is an unnamed function taking S as its only parameter and returning a list of the Collatz cousins.

The algorithm is a simple breadth-first search. The Collatz cousins for a given S are all the integers that can be reached from the Collatz cousins for S-1 via 2*n or odd numbers that can be reached via (n-1)/3. We also need to ensure that we only produce those integers which were reached for the first time after S steps, so we keep track of all previous cousins in p and remove those from the result. Since we're doing that anyway, we can save a few bytes by computing the steps from all previous cousins (not just those from S-1) to save a few bytes (that makes it slightly slower, but not noticeably for the required S).

Here is a slightly more readable version:

(
  p = {0};
  l = {1};
  Do[
    l = Complement[
      ## & @@ {2 #, Mod[a = # - 1, 2] #~Mod~3~Mod~2 a/3} & /@ l,
      p = p ⋃ l
    ]~Cases~_Integer,
    {#}
  ];
  l
) &


Challenge about advacado Inspired by this. No avocados were harmed in the making of this challenge.
Hello I have challenge I need help juic an avocado so I need program to tell me how long to juic avocad for
Observe this ASCII art avocado:
    ######
   #      #
   # #### #
  #  # p# #
  ## #### #
   #      #
    ######

This avocado consists of an exterior of #s (specifically the first and last sequences of #s on each line) and a pit (a shape of #s in the avocado that does not touch the avocado exterior).
Through rigorous experiments on these ASCII art avocados I have discovered the following:
avocado juice in fluid ounces = number of spaces inside avocado but outside pit (the pit is marked with a p in the example) + 2 * number of spaces inside pit

time to juice avocado in minutes = 13 * number of spaces inside pit

For example, this avocado will take 26 (2 spaces inside pit * 13) minutes to juice and will give 23 (19 spaces inside avocado but outside pit + 2 * 2 spaces inside pit) fl oz of juice.
Challenge
Given an input of exactly one ASCII art avocado such as the one above that consists of only # and whitespace, output the amount of time in minutes it will take to juice it and the amount of juice it will produce in any order.
You may assume that the input avocado will always have exactly one pit and both the avocado and the pit will always be closed. The pit and avocado will always be connected, and any subset of the pit will be connected as well. The avocado and the pit will always be convex. Note that the avocado exterior may be arbitrarily thick.
Sample Inputs and Outputs
    ######
   #      #
   # #### #
  #  #  # # -> 26 23
  ## #### #
   #      #
    ######

   #######
  #       #
  #  ###   ##
  #  #  #   # -> 26 35
  #   ##   #
  #        #
  ##########

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

Pyth, 59 51 bytes

*Ksm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z13+-/s.sR\ .zdK*2K

Try it here!

Outputs the time to juic the advacado (totally correct english) first and on the next line the amount of juic.

Explanation

Code - Overview

*Ksm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z13+-/s.sR\ .zdK*2K # .z=list of all input lines

                    fq4l:T"#+"4.z                   # Get the pit-lines
   m/.s.s.sd\ \#\ \                                 # Map the pit-lines to the whitespace amount
 Ks                                                 # Sum the amount of pit-spaces and assign to K
*                                13                 # Print the juic time
                                     /s.sR\ .zd     # Count all whitespaces in the advacado
                                    -          K    # Subtract the pit size from it
                                   +            *2K # Do the Rest of the amount calcluation and print it

Detailed explanations of the size calculation parts see below.

Getting the advacado size

Let's look at this one:

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

First the leading and trailing whitespaces get removed. After that we wrap everything in one line, which results in this string:

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

This contains all whitespaces in the advacado, so we just have to count them (the advacado will always be convex, so this works for all valid inputs). This number still contains the spaces in the pit, but for the juic amount calculation we only need the spaces in the fruit without the pit-spaces. So we need to calculate them too.

The code for that explained in detail:

/s.sR\ .zd   # .z=list of all input lines

  .sR\ .z    # strip spaces from every input line
 s           # Concatenate all lines
/        d   # Count all spaces

Getting the pit size

This is a bit trickier. First we remove the lines which don't contribute to the pit size. This is done by filtering out all lines that have less than 4 groups of hashes (using the regex #+ and counting its matches). In the example above only one line will survive this process:

  #  #--# #

The spaces I marked with a - here are the ones we need to count. So we just strip spaces, then hashes and then spaces again which leaves us with this:

#  #

There we just have to count the spaces. We do all that for every line which survived the filtering process, sum everything and we are done. The rest is trivial math.

The code for that explained in detail:

sm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z   # .z=list of all input lines

                  f          .z   # filter the input
                     l:T"#+"4     # length of the matches for the regex `#+`
                   q4             # if there are 4 groups of hashes its a pit line
 m                                # map the pit lines to...
  /             \                 # The occurences of spaces in..
   .s.s.sd\ \#\                   # ...the stripped pit line (see explanation above)
s                                 # Sum all amounts of spaces in the pits


Generate strong primes In number theory, a strong prime is a prime number that is greater than the arithmetic mean of the nearest prime above and below (in other words, it's closer to the following than to the preceding prime).

Given an input integer, n, where n >= 0, your task is to generate the first n strong primes. For example, the sixth, seventh, and eighth primes are 13, 17, and 19, respectively:

(13 + 19) / 2 < 17

Therefore, 17 is a strong prime.

Input

an integer

Output

if n is 0

program: output nothing
function: return an empty array

if n is greater than 0

program: output the first n strong primes, each on its own line
function: return an array containing the first n strong primes

Test cases

0
[]

4
[11, 17, 29, 37]

7
[11, 17, 29, 37, 41, 59, 67]

47
[11, 17, 29, 37, 41, 59, 67, 71, 79, 97, 101, 107, 127, 137, 149, 163, 179, 191, 197, 223, 227, 239, 251, 269, 277, 281, 307, 311, 331, 347, 367, 379, 397, 419, 431, 439, 457, 461, 479, 487, 499, 521, 541, 557, 569, 587, 599]

See also: Strong primes on OEIS

Husk, 12 11 bytes

↑§foẊ<Ẋ-tİp

Try it online!

-1 byte thanks to H.PWiz.

Explanation

↑§foẊ<Ẋ-tİp  Input is n.
         İp  The infinite list of primes.
      Ẋ-     Take pairwise differences,
   oẊ<       then pairwise comparisons.
        t    Frop the first element from İp
 §f          and filter the rest using the result of oẊ<Ẋ-.
↑            Take first n elements of this list.


How Many Ways To Empty The Glove Box? Inspired by this glove-themed 538 Riddler Express Puzzle.
Task
You are given a positive integer n, and a list A = [a_1, a_2, ..., a_k] of k distinct positive integers.
Then a restricted composition is an ordered list P = [p_1, p_2, ..., p_m] where each p_i is a (not necessarily distinct) member of A, and p_1 + p_2 + ... + p_m = n.
So, if n = 10, and A = [2,3,4] then an example of a restricted composition would be P = [3,4,3]. Another example would be P = [2,3,3,2]. A third example would be P = [3,3,4]. But there's no restricted composition that starts [3,3,3,...], because 10-(3+3+3) = 1, which is not in A.
We want the total number of different restricted compositions given the inputs, as an integer.
Inputs
A positive integer n and a list A of distinct positive integers. All reasonable input formats allowed.
Output
The number of distinct restricted compositions.
Terms and Conditions
This is code-golf; and thus we seek the shortest submissions in bytes satisfying the constraints. Any use of the usual loopholes voids this contract.
Test Cases
(5, [2, 3, 4]) => 2
(10, [2, 3, 4]) => 17
(15, [3, 5, 7]) => 8

Python 2, 50 49 bytes

-1 byte thanks to @Jonathan Allan

f=lambda n,A:n>=0and(n<1)+sum(f(n-x,A)for x in A)

Try it online!


Fully-palindromic triangles Consider the string 160615051. It can be "triangulated" as such:

  1
 606
15051

Then, each row is a palindrome. Also note that each side on the perimeter is also a palindrome:

  1  |   1   |
 6   |    6  |
1    |     1 | 15051

Therefore, this string can be considered to be a fully-palindromic triangle. Don't worry about the altitude 100 in this case, it doesn't have to be palindromic.

Input: A string of printable ASCII characters from 0x20 to 0x7E. This can be a character array, a single string, or an array of ASCII code points. Your input will always be able to be triangulated (that is, its length will always be a perfect square).

Output: A truthy value if the string is a fully-palindromic triangle, or a falsey value otherwise.

Test cases

input => output

1 => true
A => true
AAAA => true
nope => false
{{}} => false
1101 => true
1011 => false
1202 => false
111110001 => true
160615051 => true
160625052 => false
1111111111111111 => true
1121123211234321123454321 => true
HHeHHeleHHellleHHellolleH => true
HellolleHHellleHHeleHHeHH => false
111111111111111111111111111111111111 => true
abcbdefeddefgfedbcdefedcbabcdefedcba => true

Jelly, 14 12 bytes

J’Æ²œṗZ⁻¦µU⁼

Try it online!

Background

We start by looking at the 0-based indices of the input string.

 H  H  e  H  H  e  l  e  H  H  e  l  l  l  e  H  H  e  l  l  o  l  l  e  H
 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

To get the rows of the triangle, we can split the string before the indices 1, 1 + 3 = 4, 1 + 3 + 5 = 9, and 1 + 3 + 5 + 7 = 16. Since (n + 1)² = n² + (2n + 1), these sums are precisely the positive, perfect squares in the index list. If we also split the string before 0, this is as simple as splitting before all 0-based indices that are perfect squares.

After splitting, we get the following strings.

""
"H"
"HeH"
"HeleH"
"HellleH"
"HellolleH"

Next, we replace the empty string at the beginning with all the characters in the first column.

"HHHHH"
"H"
"HeH"
"HeleH"
"HellleH"
"HellolleH"

The task is now reduced to checking whether reversing all strings yields the same string array.

How it works

First J generates all 1-based indices of the input string J, then decrements them with ’ to yield all 0-based indices. Æ² tests all 0-based indices for squareness. For our example from above, this yields the following Boolean array.

 1  1  0  0  1  0  0  0  0  1  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0

Next, we call œṗ to partition the input string, e.g.,

 H  H  e  H  H  e  l  e  H  H  e  l  l  l  e  H  H  e  l  l  o  l  l  e  H

before all 1's (actually, all truthy elements). For our example, this yields the following string array.

['',
 'H',
 'HeH',
 'HeleH',
 'HellleH',
 'HellolleH'
]

Z⁻¦ is arguably the most interesting part of this answer. Let's analyze the more straightforward Z1¦ first.

¦ is the sparse quick. It consumes two links from the stack, specifically 1 and Z in this case. First Z is applied to its argument: the string array from before. Z is the zip atom and reads the string array / 2D character array by columns, yielding

['HHHHH',
 'eeee',
 'Hlll',
 'ell',
 'Hlo',
 'el',
 'Hl',
 'e',
 'H'
]

What used to be left side of the input string and the first column of the string array now becomes the first string.

Now ¦ peeks at 1 and finds a single index: 1. Thus the first string in the original string array is replaced with the first string in the return value of Z; strings at other indices remain unaffected.

['HHHHH',
 'H',
 'HeH',
 'HeleH',
 'HellleH',
 'HellolleH'
]

Let's call this array A.

We used Z⁻¦ instead of Z1¦, but this makes no difference: ⁻ compares the string array with the input string for inequality, yielding 1 since they're not equal. The difference between the two is that Z⁻¦ is dyadic because ⁻ is, allowing us to write œṗZ⁻¦ instead of œṗ¹Z1¦. This is because a dyad (œṗ) followed by a monad (œṗ¹Z1¦) is a fork (the monad is applied to the chain's argument / the input string, and the returned value is passed as the right argument to œṗ), while a dyad followed by another dyad (or at the end of the chain) is a hook, i.e., its right argument is the chain's argument.

All that's left to do is check for palindromicness. µ begins a new (monadic) chain who's argument is A. The upend atom U reverses all strings in A (but not A itself), then ⁼ compares the result with A for equality. The returned Boolean 1 indicates a fully-palindromic triangle; other strings would return 0.


Outputting ordinal numbers (1st, 2nd, 3rd) I would like to generate (as a return result of a function, or simply as the output of a program) the ordinal suffix of a positive integer concatenated to the number.

Samples:

1st
2nd
3rd
4th
...
11th
12th
13th
...
20th
21st
22nd
23rd
24th

And so on, with the suffix repeating the initial 1-10 subpattern every 10 until 100, where the pattern ultimately starts over.

The input would be the number and the output the ordinal string as shown above.

What is the smallest algorithm for this?

Python 2, 49 bytes

lambda n:`n`+'tsnrhtdd'[n%5*(n%100^15>4>n%10)::4]

An anonymous function. A full program would be counted at 55 bytes.

'tsnrhtdd'[i::4] encodes the suffixes th st nd rd for values of i from 0 to 3. Given this, all we need is a way to map the values of n to the index of the corresponding suffix, i. A straightforward expression that works is (n%10)*(n%10<4 and 10<n%100<14). We can easily shorten this by dropping the first set of parentheses and observing that n%5 gives the same results as n%10 for the values of n with the special suffixes. With a bit of trial and error, one may also shorten 10<n%100<14 to n%100^15>4, which can be chained with the other conditional to save even more bytes.


Make a regex polyglot Write a regex that works in at least 2 regex flavors (or versions), and match a different string in each flavor (or version) it is running in.

The strings to be matched in this challenge are the first words of the Ubuntu code names, which are listed below. Your regex has to match from the top of the list. That is, if your regex works in 3 flavors, it has to match Warty Hoary and Breezy, and not others.

Warty
Hoary
Breezy
Dapper
Edgy
Feisty
Gutsy
Hardy
Intrepid
Jaunty
Karmic
Lucid
Maverick
Natty
Oneiric
Precise
Quantal
Raring
Saucy
Trusty
Utopic
Vivid
Wily
Xenial
Yakkety
Zesty
17.10
18.04
18.10
19.04
19.10
...

If your regex works in more than 26 flavors, you can match the Ubuntu version numbers instead. Starting from 17.10, for each new flavor, change the second number to 10 if it was 04, and increment the first number and change the second to 04 otherwise.

In each flavor, your regex should match only the supposed string and nothing else (not limited to the code names). Trailing newlines doesn't matter. That means your regex could either match only the string without the trailing newline, match only the string with the trailing newline, or match both. And it doesn't have to be consistent in different flavors. You can assume the input is in printable ASCII (except for the trailing newline, if there is one).

Your score is (the length of your code+10)/((number of flavors)^2). Lowest score wins.

87 bytes, 5 flavours, (87+10)/25 = 3.88

^(((?=W)[[:word:]&&]art|Ho(?=a)\ar|Bre(?=ez)[]e]\z|E(?=dg)[[d]]g)y|(?=Da)[D-[E]]apper)$

I've gone with the easy to test flavours for now, which are:

Regex101: PCRE (PHP), Javascript, Python
Regex Storm: .NET
Rubular: Ruby

The general structure is ^((...)y|...)$, i.e. factoring out the trailing ys and adding anchors.

Warty (PCRE)

(?=W)[[:word:]&&]art

In PCRE and Ruby, [[:word:]] is a POSIX character class matching a word character — in other flavours you get a [[:word:] character class then literal &&], which fails the (?=W) assert. To make Ruby fail, && is used to intersect the POSIX class with nothing, whereas in PCRE && has no special meaning.

Hoary (Javascript)

Ho(?=a)\ar

For whatever reason, Javascript is the only flavour out of the bunch where \a is a literal a — in other flavours it matches the bell character (ASCII 7).

Breezy (Python)

Bre(?=ez)[]e]\z

In Python and Javascript, \z is a literal z — in the other flavours it is equivalent to the $ end of string anchor. To make Javascript fail we use the char class []e], which is an empty char class [] then literal e] in Javascript, and a two-char class []e] in Python.

Dapper (.NET)

(?=Da)[D-[E]]apper

In .NET, [D-[E]] is a set difference, removing the set [E] from [D]. In PCRE, Javascript and Python, we have the class [D-[E] then a literal ]. Ruby's a little different, but for some reason it parses as a class [D-[E]] which only matches E, and I have yet to figure out why...

Edgy (Ruby)

E(?=dg)[[d]]g

Ruby allows char classes inside char classes, so [[d]] is actually equivalent to [d], or just d. In the other flavours, we have [[d] then a literal ].


Project Euler Problem 12: optimize memory usage I am referring to Project Euler #12. Write the solution in any language you want, but consume the least amount of memory while executing. Running time is not measure in this case.

  The sequence of triangle numbers is
  generated by adding the natural
  numbers. So the 7th triangle number
  would be 1 + 2 + 3 + 4 + 5 + 6 + 7 =
  28. The first ten terms would be:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55,
  ...

  Let us list the factors of the first
  seven triangle numbers:

  1: 1  3: 1,3  6: 1,2,3,6 10: 1,2,5,10
  15: 1,3,5,15 21: 1,3,7,21 28:
  1,2,4,7,14,28 We can see that 28 is
  the first triangle number to have over
  five divisors.

  What is the value of the first
  triangle number to have over five
  hundred divisors?

No hardcoding of values/results. Honour system here folks :)

MIPS32 Assembly.  Uses 8 bytes of memory (4 for format string, 4 for saving a pointer), everything else stays in registers.  This should work in x86-64, too, but ia32 will probably require some temporary values to be stored in memory.

    .text
    .globl main
main:
    xor $t0, $t0, $t0
    xor $t1, $t1, $t1
loop1:
    addiu $t0, $t0, 1
    addu $t1, $t1, $t0
    addiu $t3, $zero, 1
    addiu $t5, $zero, 2
    srl $t6, $t1, 1
loop2:
    slt $t4, $t6, $t5
    bne $t4, $zero, loop2end
    div $t1, $t5
    mfhi $t4
    bne $t4, $zero, non_divisor
    addiu $t3, $t3, 1
non_divisor:
    addiu $t5, $t5, 1
    j loop2
loop2end:
    slti $t4, $t3, 501
    bne $t4, $zero, loop1
    la $a0, str
    addu $a1, $t1, $zero
    addiu $sp, $sp, -4
    sw $ra, 0($sp)
    jal _printf
    lw $ra, 0($sp)
    addiu $sp, $sp, 4
    jr $ra
    .data
str:
    .asciiz "%d\n"


Self-Mutilating Program Simply put, your goal is to create a complete program that modifies its own source code until every character of the source is different than what it started as.
Please include the beginning source as well as the ending source in your post, as well as a description. E.g. Describe what (else) your program does, the language you used, your strategy, etc.
Rules

Your program must halt sometime after the modification is complete.

It must actually modify its own, currently running source code (not necessarily the file you passed to the interpreter, it modifies its instructions), not print a new program or write a new file.

Standard loopholes are disallowed.

Shortest program wins.

If your language can modify its own file and execute a new compiler process, but cannot modify its own (currently running) source code, you may write such a program instead at a +20% bytes penalty, rounded up. Real self-modifying languages should have an advantage.

Edit: If your program halts with errors, please specify it as such (and maybe say what the errors are.)

Labyrinth, 2 bytes

>@

The > rotates the source so that it becomes

@>

The instruction pointer is now in a dead end and turns around to hit the @ which terminates the program.

Of course, <@ would also work.


Replay previous console text Create a script that, when run from a console, will display the text already in the console, prior to running.

Challenge

How will the winner of the challenge will be determined?

  The golf with the shortest length (in bytes) will win.

Example Input and Output

Input:
(Shown is Windows)

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\Users\CSS>dir
 Volume in drive C has no label.
 Volume Serial Number is B0A1-E768

 Directory of C:\Users\CSS

11/30/2016  07:18 PM    <DIR>          .
11/30/2016  07:18 PM    <DIR>          ..
12/01/2016  04:45 PM    <DIR>          .android
10/25/2016  12:41 PM    <DIR>          .atom
11/29/2016  05:52 PM    <DIR>          .dnx
10/27/2016  09:34 PM               148 .gitconfig
11/28/2016  03:02 PM    <DIR>          .MemuHyperv
11/29/2016  05:55 PM    <DIR>          .nuget
12/01/2016  04:42 PM    <DIR>          .oracle_jre_usage
10/26/2016  11:37 PM    <DIR>          .ssh
12/04/2016  06:20 PM    <DIR>          .VirtualBox
11/29/2016  12:56 PM    <DIR>          .vscode
11/28/2016  03:53 PM             8,528 2016-11-28-20-44-28.000-VBoxSVC.exe-2608.log
11/28/2016  05:09 PM    <DIR>          Andy
11/23/2016  10:01 AM    <DIR>          Contacts
12/11/2016  11:16 PM    <DIR>          Desktop
11/30/2016  07:35 PM    <DIR>          Documents
12/11/2016  01:43 AM    <DIR>          Downloads
11/23/2016  10:01 AM    <DIR>          Favorites
11/22/2016  07:23 PM               409 fciv.err
11/22/2016  07:21 PM               266 hi
11/23/2016  10:01 AM    <DIR>          Links
11/22/2016  04:28 PM                15 me.txt
11/28/2016  03:08 PM    <DIR>          Music
10/25/2016  12:44 AM    <DIR>          OneDrive
12/09/2016  05:57 PM    <DIR>          Pictures
11/23/2016  10:01 AM    <DIR>          Saved Games
11/24/2016  08:56 PM               151 search.bat
11/23/2016  10:01 AM    <DIR>          Searches
11/07/2016  11:00 AM                11 t.bat
11/24/2016  08:55 PM                93 update.bat
11/28/2016  03:08 PM    <DIR>          Videos
               8 File(s)          9,621 bytes
              24 Dir(s)  152,887,300,096 bytes free

C:\Users\CSS>

Output:

The script must display something like the text above, in the sense that it must display exactly what was in the console before the script was called.

MacOS terminal, 84 bytes

osascript -e 'tell app "System Events" to keystroke "ac" using command down'
pbpaste

Simple select-all then copy-and-paste.


What ROT is this? - decrypt ROT-n Here are the letters of the English alphabet in order by frequency:

e t a o i n s h r d l c u m w f g y p b v k j x q z

That is, e is the most frequently used letter, and z is the least common. (Data from Wikipedia.)

Your challenge is to take some ROT-n'd text, such as:

ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz

This is the text "thisisaverysecretmessagethatisverysecureandsafe" that is "encrypted" through ROT-21 (half of 42). Your program, using the frequency table above, should be able to determine by how much each character was rotated and the original text.

(If you are not familiar with ROT-n, it is essentially shifting each character by n. For example, in ROT-2, a -> c, b -> d, ..., x -> z, y -> a, z -> b.)

How, you ask? The (very naive) algorithm you must use is:

for each n from 0 to 25 inclusive, apply ROT--n to the input string. (Negative n because we want to reverse the encryption. ROT--n is equivalent to ROT-26-n, if that's any easier.)
convert each input string to a number by adding up the relative frequencies of the characters. e is 0, t is 1, a is 2, etc. For example, the corresponding number for the string "hello" is 7 + 0 + 10 + 10 + 3 = 30.
find the string that has the lowest corresponding number.
output that string and its corresponding n.

Rules:

input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.)
you may use a different algorithm, as long as it always produces identical results. For example, having z be 0 and e be 25 and choosing the highest number is also okay.
if two strings have identical scores, you can choose to output either one (or both) of them. This is an edge case and you do not have to account for it.
this is code-golf, so the shortest code in bytes will win!

Test cases:

Input: ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz
Output: 21 thisisaverysecretmessagethatisverysecureandsafe

Input: pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom
Output: 8 hellopeopleofprogrammingpuzzlescodegolfstackexchange

Input: ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq
Output: 12 thiswasencryptedwithrottwelvesoitmustbeperfectlysafe

Input: jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv
Output: 2 hereisthefinaltestcasethatyoumustdecrypt

In case you were wondering, here is a JSFiddle of the JavaScript test code I wrote, which successfully decrypted all the test cases I threw at it.

Haskell - 192 175
f y=sum.map(\x->length.fst$break(==x)y)
main=interact(\s->snd$minimum$[(f"etaoinshrdlcumwfgypbvkjxqz"r,show(26-n)++" "++r)|n<-[0..25],let r=map(\x->([x..'z']++['a'..])!!n)s])

Running
% ./rot-n <<< "pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom"
8 hellopeopleofprogrammingpuzzlescodegolfstackexchange


Parse a list of signed unary numbers Unary numbers typically only represent nonnegative integers, but we can extend them to represent all integers as follows:

A positive integer N is represented as N 1's: 5 -> 11111
A negative integer -N is represented as a 0 followed by N 1's: -5 -> 011111
Zero is represented as 0

We can then represent a list of these numbers unambiguously if we use 0 as the separator:

3,-2,0,1
111,011,0,1
111 0 011 0 0 0 1
11100110001

Your task: take a string representing such a list of signed unary numbers, and translate it into a list of decimal numbers.

Details

You may assume that the input is a complete list of signed unary numbers. In particular, your program will not have to handle 1) empty input or 2) input that ends with a separator.

You may assume that the magnitude of each number will not exceed 127. For languages with maximum sizes of strings or lists, you may assume that the input and output will fit in your language's data structures, but your algorithm should theoretically work for a list of any size.

Your program or function may perform I/O in any of the standard ways. Input may be a string or a list of characters, single-character strings, integers, or booleans. You may use any two characters to represent 1 and 0; if you don't use 1 and 0, please specify which characters you're using.

Output must be decimal numbers in any reasonable list format (in particular, there must be some kind of a separator between numbers). Negative numbers should be indicated with a minus sign, although if your language has a different format for negative integers I will also accept that. Zero may be represented in the output as 0 or -0.

Test cases

1 -> 1
0 -> 0 (or -0, and similarly for the other test cases)
011 -> -2
1101 -> 2,1
1100 -> 2,0
11001 -> 2,-1
110001 -> 2,0,1
11100110001 -> 3,-2,0,1
00000001 -> 0,0,0,-1
01111011111111001111111111111110111111111111111100111111111111111111111110111111111111111111111111111111111111111111 -> -4,8,-15,16,-23,42
01111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 -> -127

Python 2, 73 70 bytes

A function that takes a string as input and returns a string representation of a Python list. Zero can be represented both by 0 and -0 (when it comes last):

lambda s:`map(len,s.split('0'))`.replace('0, ','-').replace('--','0,')

Explanation

split the input string s on zeroes.
Take the length of each string in the resulting list (using map).

That takes us a long way. Zeroes were separators after all. And the numbers were unary, so len conveniently converts those to decimal. But now we've messed up all the non-separator uses of 0. Luckily, all non-separator uses were leading zeroes so they came after a separator-zero and gave us zero-length strings ('00'.split('0') == ['', '', '']). Those zero-length strings then also became 0 because of the len.

Turn the list into a string (using "reverse quotes"), so we can fix up the mess more easily.
replace each zero that precedes another number by a negative sign on that number instead. That fixes the use of 0 as a sign but it breaks the literal zeroes. Literal zeroes were also preceded by a separator, so they've now become pairs of extra dashes on the next number.
replace each -- back into a 0 element in the "list".


Iterated Prisoner's Trilemma CHALLENGE STATUS: OPEN

Comment, open a PR, or otherwise yell at me if I'm missing your bot.

Prisoner's dilemma ... with three choices. Crazy, huh?

Here's our payoff matrix. Player A on the left, B on the top

A,B| C | N | D
---|---|---|---
 C |3,3|4,1|0,5
 N |1,4|2,2|3,2
 D |5,0|2,3|1,1

The payoff matrix is engineered so that it's best for both players to always cooperate, but you can gain (usually) by choosing Neutral or Defection.

Here's some (competing) example bots.

# turns out if you don't actually have to implement __init__(). TIL!

class AllC:
    def round(self, _): return "C"
class AllN:
    def round(self, _): return "N"
class AllD:
    def round(self, _): return "D"
class RandomBot:
    def round(self, _): return random.choice(["C", "N", "D"])

# Actually using an identically-behaving "FastGrudger".
class Grudger:
    def __init__(self):
        self.history = []
    def round(self, last):
        if(last):
            self.history.append(last)
            if(self.history.count("D") > 0):
                return "D"
        return "C"

class TitForTat:
    def round(self, last):
        if(last == "D"):
            return "D"
        return "C"

Your bot is a Python3 class. A new instance is created for every game, and round() is called each round, with your opponent's choice from last round (or None, if it's the first round)

There's a 50 rep bounty for the winner in like a month.

Specifics

Every bot plays every other bot (1v1), including itself, in [REDACTED] rounds.
Standard loopholes disallowed.
No messing with anything outside your class or other underhanded shenanigains.
You may submit up to five bots.
Yes, you can implement handshake.
Any response other than C, N, or D will be silently taken as N.
Each bot's points from every game they play will be totaled up and compared.

Controller

Check!

Other Languages

I'll throw together an API if anyone needs it.

Scores: 2018-11-27

27 bots, 729 games.

name            | avg. score/round
----------------|-------------------
PatternFinder   | 3.152
DirichletDice2  | 3.019
EvaluaterBot    | 2.971
Ensemble        | 2.800
DirichletDice   | 2.763
Shifting        | 2.737
FastGrudger     | 2.632
Nash2           | 2.574
HistoricAverage | 2.552
LastOptimalBot  | 2.532
Number6         | 2.531
HandshakeBot    | 2.458
OldTitForTat    | 2.411
WeightedAverage | 2.403
TitForTat       | 2.328
AllD            | 2.272
Tetragram       | 2.256
Nash            | 2.193
Jade            | 2.186
Useless         | 2.140
RandomBot       | 2.018
CopyCat         | 1.902
TatForTit       | 1.891
NeverCOOP       | 1.710
AllC            | 1.565
AllN            | 1.446
Kevin           | 1.322

EvaluaterBot

class EvaluaterBot:
    def __init__(self):
        self.c2i = {"C":0, "N":1, "D":2}
        self.i2c = {0:"C", 1:"N", 2:"D"}
        self.history = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        self.last = [None, None]

    def round(self, last):
        if self.last[0] == None:
            ret = 2
        else:
            # Input the latest enemy action (the reaction to my action 2 rounds ago)
            # into the history
            self.history[self.last[0]][self.c2i[last]] += 1
            # The enemy will react to the last action I did
            prediction,_ = max(enumerate(self.history[self.last[1]]), key=lambda l:l[1])
            ret = (prediction - 1) % 3
        self.last = [self.last[1], ret]
        return self.i2c[ret]

Wins against all previously submitted bots except (maybe) the random bot (but it could have an advantage, because it picks D in a draw and D should optimal) and plays a constant draw against themself.


Emulate a 7-segment display Task

The task is to display any of the 128 possible states of a
7-segment display.

Your program should accept a string of 7 characters ("bits") that are either 0 or 1.
First bit of input corresponds to segment A of the following illustration, the
second to B, etc (ignore dp):

How you represent the display is up to you -- a single Unicode or ASCII symbol,
ASCII art, grafically, or whatever you can come up with. However, each
input must have it's own distinct output. If you come up with something fancy I'm sure you can harvest upvotes by showing off some examples.

All 128 possible states of the display are:

Rules

Codegolf
As I said, any kind of output is allowed, but it would be nice if you specified it.
Input can be stdin or command line argument.

Examples

Input

1101101

Output

As ASCII/Unicode:

2

Different kinds of ASCII art (I'm not too good at this)

 _   ╺┓  ╒╗   ---
 _|  ┏┛  ╔╝     |
|_   ┗╸  ╚╛   ---
              |
              ---

C, 106

Size is 74 chars if allowed to rename program "W00WG5WW1GW66WG4WW2GW33WG"

main(int i,char**s){
    for(s[0]="W00WG5WW1GW66WG4WW2GW33WG";i=*s[0]++;putchar(s[1][i&7]-49?i==71?10:32:42));
}

running:

./a.out 1101101
 **
   *
 **
*
 **

notes:

'W' and 'G' (0x47 and 0x57) are chosen such that the value & 7 = 7, i.e they safely index the null character that terminates the input string.


Base Conversion With Strings Introduction
We've have a few base conversion challenges here in the past, but not many designed to tackle arbitrary length numbers (that is to say, numbers that are long enough that they overflow the integer datatype), and of those, most felt a little complicated. I'm curious how golfed down a change of base code like this can get.
Challenge
Write a program or function in the language of your choice that can convert a string of one base to a string of another base. Input should be the number to be converted (string), from-base (base-10 number), to-base (base-10 number), and the character set (string). Output should be the converted number (string).
Some further details and rules are as follows:

The number to be converted will be a non-negative integer (since - and . may be in the character set). So too will be the output.
Leading zeroes (the first character in the character set) should be trimmed. If the result is zero, a single zero digit should remain.
The minimum supported base range is from 2 to 95, consisting of the printable ascii characters.
The input for the number to be converted, the character set, and the output must all be of the string datatype. The bases must be of the base-10 integer datatype (or integer floats).
The length of the input number string can be very large. It's hard to quantify a sensible minimum, but expect it to be able to handle at least 1000 characters, and complete 100 characters input in less than 10 seconds on a decent machine (very generous for this sort of problem, but I don't want speed to be the focus).
You cannot use built in change-of-base functions.
The character set input can be in any arrangement, not just the typical 0-9a-z...etc.
Assume that only valid input will be used. Don't worry about error handling.

The winner will be determined by the shortest code that accomplishes the criteria. They will be selected in at least 7 base-10 days, or if/when there have been enough submissions. In the event of a tie, the code that runs faster will be the winner. If close enough in speed/performance, the answer that came earlier wins.
Examples
Here's a few examples of input and output that your code should be able to handle:
F("1010101", 2, 10, "0123456789")
> 85

F("0001010101", 2, 10, "0123456789")
> 85

F("85", 10, 2, "0123456789")
> 1010101

F("1010101", 10, 2, "0123456789")
> 11110110100110110101

F("bababab", 2, 10, "abcdefghij")
> if

F("10", 3, 2, "0123456789")
> 11

F("<('.'<)(v'.'v)(>'.'>)(^'.'^)", 31, 2, "~!@#$%^v&*()_+-=`[]{}|';:,./<>? ")
> !!~~~~~~~!!!~!~~!!!!!!!!!~~!!~!!!!!!~~!~!~!!!~!~!~!!~~!!!~!~~!!~!!~~!~!!~~!!~!~!!!~~~~!!!!!!!!!!!!~!!~!~!~~~~!~~~~!~~~~~!~~!!~~~!~!~!!!~!~~

F("~~~~~~~~~~", 31, 2, "~!@#$%^v&*()_+-=`[]{}|';:,./<>? ")
> ~

F("9876543210123456789", 10, 36, "0123456789abcdefghijklmnopqrstuvwxyz")
> 231ceddo6msr9

F("ALLYOURBASEAREBELONGTOUS", 62, 10, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
> 6173180047113843154028210391227718305282902

F("howmuchwoodcouldawoodchuckchuckifawoodchuckcouldchuckwood", 36, 95, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_-+=[{]}\\|;:'\",<.>/? ")
> o3K9e(r_lgal0$;?w0[`<$n~</SUk(r#9W@."0&}_2?[n

F("1100111100011010101010101011001111011010101101001111101000000001010010100101111110000010001001111100000001011000000001001101110101", 2, 95, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_-+=[{]}\\|;:'\",<.>/? ")
> this is much shorter

Python 2, 115 114 106 105 94 bytes

Golfing suggestions welcome. Try it online!

Edit: -9 bytes thanks to mbomb007. -2 bytes thanks to FlipTack.

def a(n,f,t,d,z=0,s=''):
 for i in n:z=z*f+d.find(i)
 while z:s=d[z%t]+s;z/=t
 print s or d[0]

Ungolfed:

def arbitrary_base_conversion(num, b_from, b_to, digs, z=0, s=''):
    for i in num:
        z = z * b_from + digs.index(i)
    while z:
        s = digs[z % b_to] + s
        z = z / t
    if s:
        return s
    else:
        return d[0]


Descending digit sequences Introduction
As an example, let's take the number 7. We then duplicate this and place 7 spaces in between. We get this:
7_______7

After that, we are going to decrease the number, until there are no spaces left. We get the following for the number 7:
7_______7
 6543210

Then, we just merge the two of them, so:
7_______7
 6543210  becomes

765432107

This will be out output for N = 7.
Looks easy, right? Now let's take N = 12. We again insert 12 spaces between the two numbers, which gives us:
12____________12

Then we start the decrement:
12____________12
  111098765432

And this finally gives us:
1211109876543212

As you can see, the descending part ends at 2, not at 0.
Task
Given an integer, greater than 1, output the descending sequence as shown above.
Test cases
Input   Output

2       2102
3       32103
4       432104
5       5432105
6       65432106
7       765432107
8       8765432108
9       98765432109
10      10987654321010
11      111098765432111
12      1211109876543212
13      13121110987654313
14      141312111098765414
15      1514131211109876515
20      201918171615141312111020
99      9998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150499
100     1009998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150100

This is code-golf, so the submission with the fewest number of bytes wins!

Julia, 30 bytes

n->"$n"join(n-1:-1:0)[1:n]"$n"

This is an anonymous function that accepts an integer and returns a string. To call it, assign it to a variable.

We construct and join the descending sequence from n-1 to 0, and take the first n characters from the resulting string. We prepend and append this with the input as a string.

Verify all test cases online


Shortest code to secure wipe a disk Let's write the shortest code to perform a simplified variant of the DoD 5220.22-M Wipe Method with only two writing passes.

Any programming language accepted, but the use of disk-wiping-oriented libraries is prohibited.

Here's how we are to implement it in pseudocode:

Set x to 0

[Start]
'Write Pass
For each sector in disk write the content of x
'Verification Pass
For each sector in disk {
    If sector does not contain the content of x then goto [Start]
}
'Check whether we already did the pass with 1
If x is not 1 then {
    Set x to 1
    GoTo [Start]
}
Else end

In other words, this code will run twice, with a write pass and verification pass for 0, and a write pass and verification pass for 1.

Anyone ballsy enough to implement it code-golf style? ;)

On a linux system there's no need for special handling of devices. Just use the device file interface.
Python 3 (byte strings) - 141 bytes
d=input()
f=open(d,'r+b')
z=f.seek
z(0,2)
s=f.tell()
i=0
while i<2:
 z(0);f.write([b'\0',b'\xff'][i]*s);f.flush();z(0)
 if f.read()==x:i+=1

It's fairly straightforward, and not really optimised heavily, but it works. Here's a basic rundown.

Get input (device file path)
Open device file
Seek to the end, get filesize (block devices are always their real size)
enter write-and-check loop
construct 0-bit and 1-bit strings (x)
write bitstring
flush output (I could have set buffering=0 but this is shorter)
test file against x, and increment step of loop if it passes

exit loop when the increment is high enough
As a bonus, you could modify this for any set and number of byte-modification patterns, like 0x55/0xaa for stronger overwriting effects.
I did actually test this on a device file, using loopback. However, I'm not 100% sure the checking actually works. It might be necessary to close and reopen the file each pass, due to buffering behaviors. I would hope flush prevents this.
*edited to incorporate some suggestions in the comments


Is it a brainfuck instruction? A very simple challenge today. Output a truthy value whether the ASCII character (or it's code) supplied is a brainfuck instruction (one of +-,.<>[]), and a falsy value if it's a comment (everything else).

Input

+
#
<
>
.
P
,

Output

true
false
true
true
true
false
true

brainfuck, 105 103 95 bytes

Outputs \x00 for false and \x01 for true.

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

Try it online!

The general principle is comparing against all values (decreasing partial distances of the char-codes), using loops to logically OR the results, and if none matched - change the output cell from 1 to 0.

See my 4 answer for a more detailed explanation (4 instructions read more easily).


Rosetta Stone Challenge: Run-Length Encoding v2.0 The goal of a Rosetta Stone Challenge is to write solutions in as many languages as possible. Show off your programming multilingualism!

The Challenge

We've done run-length encoding before but only considered runs of a single character. Of course, we can sometimes make even greater savings if we consider runs of multiple characters.

Take aaaxyzxyzxyzdddd for instance. This can be compressed to 3a3{xyz}4d. Your task is to write a program of function which, given a case-sensitive string of letters and spaces, compresses it optimally using run-length encoding for multi-character runs.

You may take input via function argument, STDIN or ARGV and return the result or print it to STDOUT.

Runs must not be nested, so aaabbbaaabbb must be 3a3b3a3b, not 2{3a3b}. I.e. the string should be encoded (or decoded) in a single pass.

Consequences of Optimal Compression

Some examples where naive application of run-length encoding might lead to suboptimal results:

abab must not be "compressed" to 2{ab}
aaaabcdeabcde must not be compressed to 4abcdeabcde but 3a2{abcde} instead.

If there are two optimal versions (e.g. aa and 2a or abcabc and 2{abc}) either result is fine.

Examples

Input              Output

aa                 aa -or- 2a
aaaaaAAAAA         5a5A
ababa              ababa
abababa            a3{ba} -or- 3{ab}a
foo foo bar        2{foo }bar
aaaabcdeabcde      3a2{abcde}
xYzxYz             xYzxYz -or- 2{xYz}
abcabcdefcdef      abcab2{cdef}
pppqqqpppqqq       3p3q3p3q
pppqqqpppqqqpppqqq 3{pppqqq}

Scoring

Each language is a separate competition as to who can write the shortest entry, but the overall winner would be the person who wins the most of these sub-competitions. This means that a person who answers in many uncommon languages can gain an advantage. Code golf is mostly a tiebreaker for when there is more than one solution in a language: the person with the shortest program gets credit for that language.

If there is a tie, the winner would be the person with the most second-place submissions (and so on).

Rules, Restrictions, and Notes

Please keep all of your different submissions contained within a single answer.

Also, no shenanigans with basically the same answer in slightly different language dialects. I will be the judge as to what submissions are different enough.

Current Leaderboard

This section will be periodically updated to show the number of languages and who is leading in each.

C# (265) — edc65
JavaScript (206) — edc65
Python (214) — Will
VB.NET (346) — edc65

Current User Rankings

edc65 (3)
Will (1)

Python 214

def t(s):
 b=s;l=len;r=range(1,l(s))
 for i in r:
  p=s[:i];b=min(b,p+t(s[i:]),key=l);x=1
  for j in r:k=i*j+i;x*=p==s[i*j:k];b=min(b,(b,''.join((`j+1`,"{"[i<2:],p,"}"[i<2:],t(s[k:]))))[x],key=l)
 return b

(second level indent is tab)

As this is code-golf, this is the naive recursive approach without early-exit, so its really really slow.


Generate Men of Culture This challenge is inspired by the meme Men of Culture.

The meme involves blanking out parts of the original caption,

  Ah, I see you're a man of culture as well.

to make it appear as if the character is saying something else.

Your challenge is to write a program that, given an input, show how the original sentence can be blanked out to achieve the input string.

Rules:

Use a - character to represent a blanked out character.
You must not add additional letters to achieve the input string
You may treat string comparisons as case-insensitive
You may ignore whitespace in string comparisions
If no substitution is possible, output a falsy value.
You may substitute redundant whitespace with a - as well, although not required.
Where multiple solutions are possible, you may output any of them.

Test cases:

Basic:

Example Meme 1

Ah, I see you're a well.
> Ah, I see you're a --- -- ------- -- well.

Example Meme 2

Ah, I see well.
> Ah, I see ------ - --- -- ------- -- well.

Edge case 1:

What did you just say about me, you little
> false

Edge case 2 (edited):

*no input*
> --- - --- ------ - --- -- ------- -- -----

Intermediate:

Example Meme 3

Ah, I see you're Orwell.
> Ah, I see you're - --- o- -----r- -- well.

Example Meme 4

Ah, ymca.
> Ah, - --- y----- - m-- -- c------ a- ----.

Example Meme 5

Ah, a manual.
> Ah, - --- ------ a man -- -u----- a- --l-.
OR: > Ah, - --- ------ a man -- -u----- a- ---l.

Harder:

Example Meme 6

tea.
> --- - --- ------ - --- -- ---t--e a- ----.

Example Meme 7

eeeee
> --- - -ee -----e - --- -- ------e -- -e---

TL;DR: Given an input string, output a string which represents how the original string should be modified to fit the input string, by using a "-" to represent a blanked out character. If a substitution is not possible, output a falsy value.

Code golf, so shortest code in bytes wins.

Edit: Clarifications

Ignore whitespace in string comparisions means you can strip away whitespace before you compare strings. For instance, the inputs Ah, a manual and Ah ,      a   manual are treated as equal. Other punctuation , ' . must be preserved. Similarly for output, Ah, a manual is equal to Ah, amanual.
substitute redundant whitespace refers to the spaces present in the original caption. You don't need to replace them with "-", but if replacing nets you more points then go ahead.

><>, 94 bytes

"vAh, I see you're a Man of Culture as well.
0/i~ <r
!\:?!^:}=0={:@*:@"-"$?$~}$:@?
<>~i+0)?;>o

Try it online!

Case-sensitive, doesn't ignore whitespace or punctuation and outputs an empty string if the input is invalid. If you want to try other strings, you can just modify the first line after the "v, as long as it doesn't contain a " or a null byte.


How many valid programs can you write? Backstory:
I think that my boss might finally realize that I don't any enough work, despite being paid by the hour. I want to throw him off track, by writing as many valid programs as I can to send to him. Unfortunately, due to budget cuts, my keyboard only allows each key to be pressed once.
Specification:
Write as many different valid programs as you can for your language. You may not reuse any character at any time (even within the same program). A program is "valid" is it compiles and runs without any errors (warnings are acceptable), for any given input. Your score is the number of unique programs written.
It does not matter what the program actually does. It does not need to take input, produce output, or even terminate. The only restriction is that may never return an error.
Example (JavaScript):

b=1
alert(2)

APL (Dyalog Unicode) version 16.0, 8384 programs

⍝ empty program
 ⍝ single space
	⍝ single tab
0
1
2
3
4
5
6
7
8
9
+
-
×
÷
⌈
⌊
*
⍟
|
!
○
~
∨
∧
⍱
⍲
<
≤
=
≥
>
≠
≡
≢
⍴
,
⍪
⍳
↑
↓
?
⍒
⍋
⍉
⌽
⊖
∊
⊥
⊤
⍎
⍕
⌹
⊂
⊃
∪
∩
⍷
⌷
→
⎕
1 2 3           ⍝ input for above program
⍞
Hello, World!   ⍝ input for above program
/
⌿
\
⍀
¨
&
⍨
⌶
#
⊆
⊣
⊢
⌸
⍸
⍝
⋄
L:
⍬
{}
⍝ just a newline
⍝ this line belong with the previous one

Try it online! (except for two which cannot run on TIO's version 15.0)
Explanations:
Most of the programs just print their content. Exceptions are:

The four whitespace ones do nothing.
→ terminates
⎕ asks for evaluated input
⍞ asks for character input
⍝ is a comment
⋄ is a statement separator (i.e. two statements that each do nothing)
⍬ prints an empty numeric list (i.e. just a newline)


Sum in each dimension You are given a multi-dimensional array of integers. Each dimension has a fixed size (so that it would be always rectangular if it is 2D). Your program should calculate the sums in each dimension and append the sums as the new last items in that dimension.
Assume the input and output arrays are A and B, and the size of dimension i of A is ni. B would have the same number of dimensions as A and the size of dimension i would be ni+1. Bj1,j2,...,jm is the sum of Ak1,k2,...,km where:

ki = ji if ji <= ni
0 < ki <= ni if ji = ni+1

For the input:
[[1 2 3]
 [4 5 6]]

Your program (or function) should output:
[[1 2 3 6]
 [4 5 6 15]
 [5 7 9 21]]

The input contains only the array. The total number of dimensions and the size of each dimension are not given in the input. (But you can get them from the array by your own code.) You can use any convenient list formats in your language, as long as it doesn't specify the number of dimensions or dimension sizes directly.
The input has at least 1 dimension, and has at least 1 item in the array.
This is code-golf. Shortest code wins.
Test cases
Input:
[5 2 3]
Output:
[5 2 3 10]

Input:
[[1 2 3] [4 5 6]]
Outputs:
[[1 2 3 6] [4 5 6 15] [5 7 9 21]]

Input:
[[[1] [1] [1] [0]]]
Output:
[[[1 1] [1 1] [1 1] [0 0] [3 3]] [[1 1] [1 1] [1 1] [0 0] [3 3]]]

Input:
[[[[-1]]]]
Output:
[[[[-1 -1] [-1 -1]] [[-1 -1] [-1 -1]]] [[[-1 -1] [-1 -1]] [[-1 -1] [-1 -1]]]]


Write a JSON validator Write a program that determines whether its input is valid JSON.

Input: ASCII text: [\x00-\x7F]*

Note: if ASCII is problematic, feel free to use another encoding, but indicate it in your post.
Output: Valid or Invalid.  Trailing newline may be omitted.
Example:

$ echo '{"key": "value"}' | ./json-validate
Valid
$ echo '{key: "value"}' | ./json-validate
Invalid

Rules:

Do not use a JSON parsing library.
Partially-correct solutions are allowed, but frowned upon.
Post your test suite score (see below).

The shortest correct solution wins.

Please run json-validate-test-suite.sh on your program, and post your score.  Example:

$ ./json-validate-test-suite.sh ./buggy-prog
fail: should be invalid:  [ 0.1e ]
fail: should be invalid:  [ 0.1e+-1 ]
fail: should be invalid:  [ 0.1e-+1 ]
score: 297/300

Resources:

json.org - Concise definition of the JSON grammar with easy-to-follow pictures.
RFC 4627 - JSON specification
json-validate.c - A 200-line implementation that passes the testsuite.

The JSON grammar is as follows:

json: object | array

object: '{' members? '}'
    members: pair (',' pair)*
    pair:    string ':' value

array: '[' elements? ']'
    elements: value (',' value)*

value: string
     | number
     | object
     | array
     | 'true'
     | 'false'
     | 'null'

string: '"' char* '"'
    char: [^"\\\x00-\x1F]
        | '\' escape
    escape: ["\\/bfnrt]
          | u [0-9A-Fa-f]{4}

number: '-'? (0 | [1-9][0-9]*) ('.' [0-9]+)? ([Ee] [+-]? [0-9]+)?

Also, whitespace can appear before or after any of the six structural characters {}[]:,

ws = [\t\n\r ]*

Bear in mind the following:

Be careful with functions like isspace().  Whitespace in JSON is [\t\n\r ], but isspace() also treats \v (vertical tab) and \f (form feed) as space.  Although word has it that isdigit() can accept more than just [0-9], should be okay to use here, as we assume input is in ASCII.
\x7F is technically a control character, but the JSON RFC doesn't mention it (it only mentions [\x00-\x1F]), and most JSON parsers tend to accept \x7F characters in strings.  Because of this ambiguity, solutions may choose to either accept them or not.

PHP : 297 285 264 253 characters

<?=preg_match(<<<'R'
~([\h
]*)({(?1)((("([^"\\\0- ]| |\\(["\\/bfnrt]|u[\dA-Fa-f]{4}))*")(?1):(?1)((?5)|-?(0|[1-9]\d*)(\.\d+)?([Ee][+-]?\d+)?|(?2)|true|false|null))(((?1),(?1))(?4))*)?}|\[(?1)((?8)((?13)(?8))*)?(?1)])(?1)\z~A
R
,`cat`)?'Valid':'Invalid';

score: 300/300

This is a full, recursive implementation of the JSON grammar.

It works only on PHP ≥ 5.3 due to nowdoc syntax (heredoc would have required to double all \).

Readable version:

(this is the same regex, with named capture groups and extended syntax):

#!/usr/bin/env php
<?php

$re = <<< 'RE'
~\A (?P<ws>[\t\n\r ])* (
    (?P<object>\{ (?P>ws)*
        (?P<members>
            (?P<pair>
                (?P<string>
                    "(?P<char>
                        [^"\\\x00-\x1F]
                        |\\(?P<escape>
                            ["\\/bfnrt]
                            |u [0-9A-Fa-f]{4}
                        )
                    )*"
                ) (?P>ws)* : (?P>ws)* (?P<value>
                    (?P>string)
                    | (?P<number>-? (0 | [1-9][0-9]*) (\. [0-9]+)? ([Ee] [+-]? [0-9]+)? )
                    | (?P>object)
                    | (?P>array)
                    | true
                    | false
                    | null
                )
            ) ( (?P>ws)* , (?P>ws)* (?P>pair) )*
        )?
    \})
    |(?P<array>\[ (?P>ws)*
        (?P<elements>
            (?P>value) ( (?P>ws)* , (?P>ws)* (?P>value) )*
        )?
    (?P>ws)* \])
) (?P>ws)* \z~x
RE;

if (preg_match($re, stream_get_contents(STDIN))) {
    echo 'Valid';
} else {
    echo 'Invalid';
}


24 and 12 Hour Times Write a program or function with no input that prints or returns this string of 24-hour and 12-hour times:

00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm

The string must be output exactly as it appears here. The only exception is that it may optionally have a single trailing newline.

So the MD5 hash of your output should be

827ae6e2dbb1df494930baedb3ee2653

if you do not have a trailing newline and

cd4c3d18abee9bafb495f390a919a13f

if you do. (Your hash could be different if your system uses another type of newline but that's OK.)

The shortest code in bytes wins. Tiebreaker is earlier answer.

Bash + coreutils, 43 30

Saved 7 bytes thanks to @Yossarian
Saved 3 bytes thanks to @AndersKaseorg

seq 0 23|date -f- +%R\ %l:00%P

seq generates integers 0-23, one per line.
date interprets each line as a datetime.  Bare integers appear to be sufficient to be recognised as hours of the day by date.  date then outputs each time with the required formatting using the available time format specifiers.

Assumes LANG=C locale, as per this meta answer.
Ideone.


Eiffel Towers: Create a large "A" from "A"s Create a function which given a number of lines n, makes a bigA.

The horizontal bar of bigA must be at the middle row, or the lower of the two if n is even
Assume a monospace font for output

Output should be a string (or similar, eg character array) with clear linebreaks to break up the lines, and with correct whitespace for left-padding (you can assume \t to be 4 spaces). There can be any whitespace on the right.

Examples

n = 1

A

n = 2

 A
AAA

n = 3

  A
 AAA
A   A

n = 4

   A
  A A
 AAAAA
A     A

n = 5

    A
   A A
  AAAAA
 A     A
A       A

This is inspired by Create an "H" from smaller "H"s

05AB1E, 13 bytes

Code:

Ð;î¹)'A1376SΛ

Uses the 05AB1E encoding. Try it online!

Explanation:

Ð                  # Triplicate the input.
 ;î                # Compute ceiling(n / 2).
   ¹               # Push the first input again.
    )              # Wrap into an array. For input 7, this would result in:
                     [7, 7, 4, 7].
     'A            # Push the character 'A'
       1376S       # Push the array [1, 3, 7, 6]. These are the directions of the canvas.
                     This essentially translates to [↗, ↘, ↖, ←].
            Λ      # Write to canvas using the previous three parameters.

Canvas

I should probably document the canvas a little bit more (and a lot of other functions), but this basically sums it up. The canvas has different 'modes' based on the parameter types given. The canvas command has three parameters: <length> <string> <direction>.

Since the length and direction parameters are lists, it 'zips' these lists to create a set of instructions to be executed. The string parameter is just the letter A, so this is the fill character used by all instructions. The canvas interprets this as the following set of instructions (for input 7):

Draw a line of length 7 with the string A in direction ↗
Draw a line of length 7 with the string A in direction ↘
Draw a line of length 4 with the string A in direction ↖
Draw a line of length 7 with the string A in direction ←

The directions are translated in the following manner:

7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

If nothing has been outputted, 05AB1E automatically outputs the canvas result.


Write all possible Braille characters An interesting puzzle came to me looking at the elevator buttons this morning.

You are required to generate a list of all Braille patterns that fit in a 2x3 grid.  Use a hash # to denote a bump and a hyphen - to denote a flat area.

Expected output sample:

#-
--
--

##
--
--

#-
#-
--

(and so on...)

Rules:

Your program must separate each pattern by at least one character or line.
The patterns may be generated in any order.
All patterns, regardless of what the Braille alphabet actually uses, should be produced.  The completely blank pattern is optional.
Only unique bump patterns should be generated.  The following patterns are considered equivilent as the bumps are in an identical arangement.  In these cases, use the pattern that is closest to the top-left corner (ie. the first option in this example.)

#-  -#  --  --
#-  -#  #-  -#
--  --  #-  -#

Bonus points if you can make it work for any x by y sized grid. (EDIT: Within reasonable bounds.  Up to 4x4 is enough for proof of concept.)

Reading the wiki article, it appears there are 45 patterns (including the blank) that meet this puzzle's rules.

GolfScript, 34 32 chars

44,{84+2base(;{'-#'=}/@\n.}%2/n*

Turns out that there are shorter solutions than simply generating all 64 patterns and filtering out the bad ones.  In fact, by suitably mapping bits to grid positions, it's possible to map all valid (non-empty) patterns to a consecutive range of numbers, as this program does.

Specifically, the mapping I use is:

5 4
3 1
2 0

where the numbers denote the bit position (starting from the least significant bit 0) mapped to that position in the grid.  With this mapping, the valid grids correspond to the numbers 20 to 63 inclusive.

This is almost the same as the obvious mapping obtained by writing out the 6-bit number in binary and adding line breaks between every second bit, except that the bits 1 and 2 are swapped — and indeed, that's exactly how my program computes it.  (I also add 64 to the numbers before converting them to binary, and then strip the extra high bit off; that's just to zero-pad the numbers to 6 bits, since GolfScript's base would otherwise not return any leading zeros.)

Ps. Online demo here. (Server seems overloaded lately; if you get a timeout, try again or download the interpreter and test it locally.)

Edit: Managed to save two chars by avoiding unnecessary array building and dumping.  Phew!


Carrot Popularity Statistics In the PPCG chatroom the Nineteenth Byte, using carets ^ (or carrots) is a way of indicating that you agree with one of the previously made comments just above yours.
A caret message consists solely of N ^ characters (where N is a positive integer) and it means agreement with the Nth previous message. So a single ^ means agreement with the message immediately previous, ^^ means agreement with the message two lines up, ^^^ means agreement with the message three lines up, and so on.
Additionally, when a caret message X is in agreement (a.k.a. pointing towards) another caret message Y, then X is said to be in agreement with what Y is in agreement with. There may be multiple layers of this and, in the end, all caret messages are indicating agreement with one non-caret message.
For example, if a chat transcript looks like this: (one message per line)
I like dogs           [line 1]
I like cats           [line 2]
^                     [line 3]
^^^                   [line 4]
^^                    [line 5]
I like turtles        [line 6]
^                     [line 7]
^^^                   [line 8]
^^                    [line 9]

Then lines 1, 2, and 6 are non-caret messages and all the others are caret messages which point to non-caret messages:

Line 3 points directly to line 2.
Line 4 points directly to line 1.
Line 5 points to line 3, which points to line 2.
Line 7 points to line 6.
Line 8 points to line 5, which points to line 3, which points to line 2.
Line 9 points to line 7, which points to line 6.

Thus, including the users who wrote the non-caret message (and assuming people don't caret their own message) we can conclude that:

2 people agree with I like dogs (Lines 1 and 4.)
4 people agree with I like cats (Lines 2, 3, 5, and 8.)
3 people agree with I like turtles (Lines 6, 7, and 9.)

Challenge
Write a program or function that takes in a multiline string similar to the example above where every line represents a chat message, with older messages coming first.
Every line will have at least one character and there will be at least one line. All messages will either be caret messages consisting solely of ^'s, or be non-caret messages consisting of letters and spaces ([ a-zA-Z]+ in regex).
For every non-caret message, in any order, output the number of people that agree with it in some clear format that contains the message text, e.g.
2 - I like dogs
4 - I like cats
3 - I like turtles

or
I like cats (4)
I like dogs (2)
I like turtles (3)

or
{"I like cats" : 4, "I like turtles" : 3, "I like dogs" : 2}

You can assume that:

People always agree with their own messages and do not caret themselves.
No two non-caret messages are identical.
Caret messages won't point to things before the first message.
Lines will not contain leading or trailing spaces.

The shortest code in bytes wins.
Test Cases
bread is bread

1 - bread is bread

---

animals are fuzzy
^
^
^
^^^
^^
^^^^^^

7 - animals are fuzzy

---

pie
^
^^
pi
^
^^
^^^^
^
^^^^^
^^^^^
^^^
^^^^
^^
^
^^^^^^^^^

9 - pie
6 - pi

---

a
b
c
^
^
^

1 - a
1 - b
4 - c

---

a
b
c
^
^^
^^^

1 - a
1 - b
4 - c

---

a
b
c
^^^
^^^^
^^^^^

4 - a
1 - b
1 - c

---

W
^
^^
X
^^^
^^^^
Y
^^^^^
^^^^^^
Z
^^^^^^^
^^^^^^^^

1 - Y
3 - X
1 - Z
7 - W

---

ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqretuvwxyz
^
ABCDEFGHIJKLMNOPQRSTUVWXYZ  abcdefghijklmnopqretuvwxyz

2 - ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqretuvwxyz
1 - ABCDEFGHIJKLMNOPQRSTUVWXYZ  abcdefghijklmnopqretuvwxyz

---

I like dogs
I like cats
^
^^^
^^
I like turtles
^
^^^
^^

2 - I like dogs
4 - I like cats
3 - I like turtles

CJam, 18
qN/{_'^e=$\;}%$e`p

2 bytes eliminated thanks to Martin :)
Try it online
Explanation:
q         read the input
N/        split into lines
{…}%      transform each line as follows:
  _       make a copy
  '^e=    count '^' characters in the string
  $       copy the corresponding earlier line from the stack
           if 0, it copies the current line again
  \;      discard the current line (from before the copied line)
          * after the loop, all caret lines have been replaced
          * with the original messages they agree with
$         sort the messages
e`        RLE encode
p         pretty print


Knödel numbers - Find Kn The Knödel numbers are a set of sequences. Specifically, the Knödel numbers for a positive integer \$n\$ are the set of composite numbers \$m\$, such that all \$i < m\$, coprime to \$m\$, satisfy \$i^{(m-n)} \equiv 1 \mod m\$. The set of Knödel numbers for a specific \$n\$ is denoted \$K_n\$. (Wikipedia).
For example, \$K_1\$ are the Carmichael numbers, and OEIS A002997. They go like: \$\{561, 1105, 1729, 2465, 2821, 6601, ... \}\$. \$K_2\$ is OEIS A050990 and goes like, \$\{4, 6, 8, 10, 12, 14, 22, 24, 26, ... \}\$.
Your task
Your task is to write a program/function/etc. that takes two numbers, \$n\$ and \$p\$. It should return the first \$p\$ numbers of the Knödel Sequence, \$K_n\$.
This is code-golf, so shortest code in bytes wins!
Examples
1, 6   ->   [561, 1105, 1729, 2465, 2821, 6601]
2, 3   ->   [4, 6, 8]
4, 9   ->   [6, 8, 12, 16, 20, 24, 28, 40, 44]
3, 1   ->   [9]
3, 0   ->   []
21, 21 ->   [45, 57, 63, 85, 105, 117, 147, 231, 273, 357, 399, 441, 483, 585, 609, 651, 741, 777, 861, 903, 987]

Pyth, 29 28 bytes

.f&tPZ!f&q1iTZt%^T-ZQZSZvzhQ

1 byte saved thanks to Jakube and orlp.

Demonstration.

Input in the form

p
n

A fairly straightforward calculation. Relative primeness is checked via Pyth's gcd function. This code showcases .f, Pyth's "first n satisfying" function.

I have incorporated the implicit condition that m > n by starting the search for m values at n + 1.


Calculate the Trump Tax If elected president, Donald Trump plans to implement a system of four income tax brackets (full details can be found on his website here). Your job is to take two inputs, annual income and filing status (single, married, or head of household), and output the income tax that must be paid.
Income Tax Brackets

(We are only interested in the income tax rate; you can ignore the long-term capital gain rate).
Note that income taxes are computed using marginal rates — that is, you only pay the bracket rate for the portion that exceeds the bracket's minimum amount.
For example, a single filer making $45,000 a year would pay 0% on the first $25,000, and 10% on the $20,000 after that, for a total of $2,000 in taxes.
A married couple filing jointly for $500,000 would count 25% only on the amount exceeding $300,000, and add $45,000 to that to account for the income earned in lower brackets (which is 10% of $50,000 plus 20% of $200,000).
Input/Output
Input/Output is flexible. You can take input as command-line arguments or prompt for inputs, as well as either return or output/display the result. The inputs and output must be numbers, but you are free to determine what the second number would be (for example, 0 = single, 1 = married, 2 = head of household). Just don't be ridiculous - Single digit numbers only.
Also, functionality for decimal inputs (i.e. including cents) is undefined, so you only have to worry about integer inputs. For your output, you may either output a decimal value or round it to the nearest whole number.
Test Cases
Although the second number's range can be flexible as stated above, these test cases assume that 0 = single, 1 = married, and 2 = head of household:
25000  0 --> 0
37501  2 --> 0.1 or 0
51346  1 --> 134.6 or 135
75000  0 --> 7500
75000  1 --> 2500
123456 2 --> 13441.2 or 13441
424242 0 --> 91060.5 or 91061


Implement Multiplicative Fuzzy Logic Inspired by this excellent challenge (from which the bulk of this text is blatantly duct-taped) – and my highschool philosophy project...
I define the following operators:
Fuzzy Conjunction a ×F b is a × b
Fuzzy Division a ÷F b is a ÷ b
Fuzzy Negation –F b is 1 – b
Fuzzy Disjunction a +F b is –F ((–F a) ×S (–F b) which is equivalent to 1 – (1 – a) × (1 – b)
With all this in mind, create an interpreter that will evaluate infix expressions that use the following operators (i.e., a + b, not a b + or + a b). Alternatively, extend the language of your choice to include the notation.
×    Multiplication
÷    Division
–    Subtraction
+    Addition
×F   Fuzzy Conjunction
÷F   Fuzzy Division
–F   Fuzzy Negation
+F   Fuzzy Disjunction

Notice that a -F b is not defined. You may leave it undefined, or define it as you see fit.
You may substitute * for × and/or - for – and/or / for ÷, (or use whatever single symbols your language uses for the four basic arithmetic operations) as long as you stay consistent: You may not use * and ×F together.
You may choose to require or prohibit spacing around tokens.
You may choose any of the following rules for order of precedence:

As normal mathematics, and each Fuzzy operator has a higher order precedence than their normal counterpart.

As normal mathematics, and each Fuzzy operator has a lower order precedence than their normal counterpart.

As normal mathematics, and the Fuzzy operators all have higher order precedence than all the normal operators.

As normal mathematics, and the Fuzzy operators all have lower order precedence than all the normal operators.

Strict left-to-right.

Strict right-to-left.

Normal and Fuzzy operators have the same precedence and are evaluated left-to-right.

Normal and Fuzzy operators have the same precedence and are evaluated right-to-left.

Leave a comment if you desire another precedence rule.
Test cases using precedence rule 6:
> 5 +F 10 + 3
-47     // 1 - (1 - 5) × (1 - 13)
> 10 × 2
20      // 2 × 10
> 10 ×F 1
10      // 1 × 10
> 23 × 3
69      // 23 × 3
> 123 ×F 2 × 3
738     // 123 × 2 × 3
> 5 + 3 +F 2
4       // 5 + 1 - (1 - 3) × (1 - 2)
> 150 ÷F 3
50      // 150 ÷ 3
> 150 ÷ 53
2.83    // 150 ÷ 53
> -F -F -F 0
1       // 1 - (1 - (1 - 0))
> -500
-500    // - 500
> -F 6 - 1
-4      // 1 - 5
> 12 +F 633 ×F 3
-20877  // 1 - (1 - 12) × (1- 633 × 3)

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

CJam, 45 bytes

q"-F"/"1 -"*"+F"/"1Y$-*+"*'F-S/)d\2/'\f*W%S*~

Uses precedence rule 6: strictly right-to-left. It expects ASCII input.

Take it for a spin!

Explanation

Read input, and perform the following transformations in order:

"-F"   to   "1 -"
"+F"   to   "1Y$-*+"
 "F"   to   ""

Then split over spaces (S/). Extract the rightmost element and convert it to a double ()d). Then take pairs from the rest of the list (\2/), join them all by \ ('\f*) and evaluate the resulting strings as CJam code in reverse order (W%S*~).

For example, it converts 5 +F 10 + 3

to 5 1Y$-*+ 10 + 3 in the first step,
then to 3 [["10" "+"] ["5" "1Y$-*+"]],
then to 3 ["10\+" "5\1Y$-*+"],
then to 3 10\+ 5\1Y$-*+, which is CJam code that computes the right answer, -47.


Javascript: Mini Space Invaders I'm pretty new to code golfing, so I gave one of my first shots to a space invader clone called "Invas!on". It's a little less than 500 bytes, fully ASCII generated, and covers moving around and shooting at the aliens. There is also a little point system.

My specific question is about generating enemy patterns. I want to generate something like this:

...x.x.x.x.x.x...
..x.x.x.x.x.x.x..
...x.x.x.x.x.x...

...and so on.

Currently, I'm using this code:

for(b=[],j=2;j<136;j+=2)b.push(j),j==14&&(j=41)||j==55&&(j=80)||j==94&&(j=121)

It's just a loop that pushes enemy positions into an array b. Positions are every two spaces on a line, with a varying margin on both sides.

What is the shortest way to do this?

58 : -20 bytes(25%) from OP

for(b=[],j=2;j<136;j+=j==14||j==94?29:j==55?27:2)b.push(j)

This should do the same thing as your code, but without all the ugly parentheses and explicit assignments. Since all you're really doing is adding each time, all you have to do is check how much to add.

I should note that I have no idea where you got the numbers from in the original code. Since it doesn't seem to match the pattern you gave, I assume the pattern is just an example (and the actual lines are longer), or there's something going on in your other code (not shown here). Either way, I matched up my positions with yours.

For a fixed pattern like this, though, it  might be shorter to just encode it in a bitmap-style string or bitmasked integer. Doing it loop-style allows you to vary it a bit easier, but if your pattern is constant it's something to be aware of. For instance, your shown pattern has 51 positions, which are either "on" or "off". This means it needs 51 bits for a straight bitmask, which can fit in a single number:

000101010101010000010101010101010000010101010101000 = 0xAAA0AAA82AA8

So, if you can unpack that into an array efficiently, you may be able to score some more bytes. Unfortunately, I'm no Javascript whiz, so I couldn't get it shorter this way, leaving it at 61 bytes. Others may be able to improve upon this:

for(b=[],j=0,m=0xAAA0AAA82AA8;m>0;m>>>=1,j++)if(m&1)b.push(j)

So for this exact pattern, the first method is shorter (for me). If the pattern wasn't so evenly spaced (allowing simple additions), the second would most likely end up shorter.


Brachylog, 8 bytes
ṫ{~cịᵐ}ᵘ

Convert to string ṫ and get all unique {…}ᵘ reverse concatenations ~c mapped to integers ịᵐ (to remove leading zeros).
Try it online!


k (72 bytes)

Credit for this goes to Arthur Whitney, creator of the k language.

p,:3/:_(p:9\:!81)%3
s:{*(,x)(,/{@[x;y;:;]'&21=x[&|/p[;y]=p]?!10}')/&~x}


Create a Language of The Month answer scraper When I was posting answers for the Husk Language of The Month thread, I realized it took more time to enter them in the thread than it took to actually write the answers. So, why not automate it?
Write a program/function which inputs a language name, and displays all answers in that language during the current month so far)
Sandbox
Introduction
You are to find all answers in Code Golf Stack Exchange in the current month so far, whose first non-empty line matches the following:
#<whitespace>[<language name>(case insensitive match)]<anything else>

For example, the current month's answers should have been posted within the time frame of Nov 1 till the current date(Nov 6, as of this question's sandbox post).
for each answer, you must find the following:

Question name
Answer URL
Answer Poster's Name
Answer Poster's Profile URL

And format them in the following manner for Markdown:
- [<Question Name>](Answer URL) by [<Answer Poster's Name>]

Once you are done listing the answers, to keep the post short, you must key in the usernames to their respective profile URLs as follows:
- [<Answer Poster's Name>]:<Answer Poster's Profile URL>

This must be added at the end of the output.
Output
The final result should look like the following:
- [Size up a number](http://example1.com) by [Razetime]
- [My smartphone's Phonebook](http://example2.com) by [Bubbler]
- [1,2,Fizz,4,Buzz](http://example3.com) by [Lyxal]
- [Upgoat or Downgoat?](http://example3.com) by [LegionMammal978]
- .....

[Razetime]:http://exampleA.com
[Bubbler]:http://exampleB.com
[Lyxal]:http://exampleC.com
[LegionMammal978]:http://exampleD.com
...

Scoring
This is code-golf. Shortest answer in each language wins.

05AB1E, 283 282 bytes
žgŽ7?-©ƵÇ+400÷®<т÷(®69-4÷®70-365*•ΘÏF•ºS₂+žf<£`žgт‰0Kθ4ÖOŽª+·*’¸¸.Â‚‹º.ŒŒ/–«?€¼=ƒËŠˆ&€š‚‚=ÿ’žYì.w„†ä_¡¦ε',¡нþ}Ùε’ƒËŠˆ.Â‚‹º.ŒŒ/’žYì©’ÿ…é/ÿ’.w……<h1¡¦ε„><S¡3èy’="/a/’¡1è'"¡н®"ÿa/ÿ"y'†§™’ÜÇ.µÔ/ÿ’¡1è…><"S¡64Sè`®¨ì)}ćнδª}€`ʒнlIlQ}ʒ1è'/¡4èXså]DεƵ=Sè`“- [ÿ](ÿ)€‹ [ÿ]“}»sε32Sè`"[ÿ]:ÿ"}Ù»¶2×ý

Ugh..
No TIO of the full program, because .w is disabled.
Explanation:

Step 1: Get the current year and month, and convert it to a Unix timestamp (using this formula):
žg                     # Push the current year
  Ž7?-                 # Subtract 1900
      ©                # Store it in variable `®` (without popping)
       ƵÇ+             # Add 299
          400÷         # Integer-divide by 400
      ®                # Push year-1900 again from variable `®`
       <               # Subtract 1
        т÷             # Integer-divide by 100
          (            # Negate it
      ®                # Push year-1900 again
       69-             # Subtract 69
          D            # Duplicate it
           4÷          # Integer-divide the copy by 4
          s            # Swap so year-1969 is at the top again
           <           # Subtract 1 to make it year-1970
            365*       # Multiply by 365
•ΘÏF•                  # Push compressed integer 5254545
     º                 # Mirror it to 52545455454525
      S                # Convert it to a list of digits
       ₂+              # Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31]
         žf            # Push the current month
           <           # Subtract it by 1
            £          # Leave that many trailing items in the list
             `         # Pop and push them all separated to the stack
žg                     # Push the current year again
  т‰                   # Divmod by 100: [year//100,year%100]
    0K                 # Remove 0s from this pair
      θ                # Leave the last item
       4Ö              # Check if it's divisible by 4
                       # (this results in 1 for leap years; 0 for non-leap years)
O                      # Sum all values on the stack
 Žª+                   # Push compressed integer 43200
    ·                  # Double it to 86400
     *                 # Multiply the sum by this 86400

Try just this first step online.
Step 2: Use this timestamp to create the stackexchange-API URL, and get the content of this url (which contains the JSON of all answers created this month):
’¸¸.Â‚‹º.ŒŒ/–«?€¼=ƒËŠˆ&€š‚‚=ÿ’
                       # Push dictionary string "api.stackexchange.com/answers?site=codegolf&fromdate=ÿ",
                       # where the `ÿ` is automatically replaced with the timestamp
 žYì                   # Prepend constant "https://"
    .w                 # Browse to this URL, and read its contents as string

Try the first two steps online (without .w).
Step 3: Extract all unique answer-id and question-ids from this JSON:
D                      # Duplicate the JSON
 „†ä_¡                 # Split it on dictionary string "question_"
      s                # Swap so the JSON is at the top again
       „Ž»_¡           # Split it on dictionary string "answer_"
            ‚          # Pair those two lists together
ε                      # Map over the pairs:
 ¦                     #  Remove the first item
  ε                    #  Map over each inner string:
   ',¡                '#   Split it on ","
      н                #   Pop and leave just the first item
       þ               #   Pop and leave just the digits in this string
  }Ù                   #  After the inner map: uniquify the resulting ids
}                      # Close the outer map

Try just this third step with the JSON as input.
Step 4: Convert each question-id to an URL, and get its contents (which is the entire HTML page of a question):
`                      # Pop and push both lists separated to the stack
 U                     # Pop the list of answer-ids and store it in variable `X`
ε                      # Map over the question-ids:
 ’ƒËŠˆ.Â‚‹º.ŒŒ/’       #  Push dictionary string "codegolf.stackexchange.com/"
   žYì                 #  Prepend constant "https://"
      ©                #  Store this string in variable `®` (without popping)
       ’ÿ…é/ÿ’         #  Push dictionary string "ÿ/questions/ÿ",
                       #  where the first `ÿ` is automatically replaced with "https://codegolf.stackexchange.com/"
                       #  and the second `ÿ` is automatically replaced with the current question-id
              .w       #  Browse to this URL, and read its contents as string

Try steps 3 and 4 with JSON input (without .w).
Step 5: For each HTML-content of a question, get a list of its [language_name, answer_url, user_name, user_url, question_name] (this may contain some garbage in the result - i.e. the trailing item, or if an answer contains multiple <h1>-refs, but we'll filter those out later):
…<h1¡                  #  Split the HTML-content on "<h1"
     ¦                 #  Remove the first item
      ε                #  Map over each string:
       „><S¡           #   Split it on both ">" and "<"
            3è         #   Get the fourth item (which is the question name in the first iteration,
                       #   and language name in every other iteration)
       y               #   Push the string again
        ’="/a/’¡      "#   Split it on "="/a/"
                1è     #   Get the second item (which is the trailing answer-id URL portion)
                  '"¡ '#   Split that on '"'
                     н #   Pop and leave the first item
        ®              #   Push "https://codegolf.stackexchange.com/" from variable `®`
         "ÿa/ÿ"        #   Push dictionary string "ÿa/ÿ",
                       #   where the `ÿ` are filled again to create the answer-URL
       y               #   Push the string again
        '†§           '#   Push dictionary string "person"
           ™           #   Titlecase it to "Person"
            ’ÜÇ.µÔ/ÿ’  #   Push dictionary string "schema.org/ÿ",
                       #   where the `ÿ` is replaced with "Person"
             ¡         #   Split the string on that
              1è       #   Get the second item
        …><"S¡        "#   Split that on ">", "<", and '"'
              64Sè     #   Get the seventh and fifth items
                       #   (which are the user name and trailing user URL portion)
                  `    #   Push those separated to the stack
                   ®   #   Push "https://codegolf.stackexchange.com/" again
                    ¨  #   Remove the trailing "/"
                     ì #   Prepend it in front to create the user-URL
       )               #   Wrap all four values into a list
      }ć               #  After the map: extract the first quadruple
        н              #  Pop and push its first item (the question name)
         δ             #  Map over each remaining quadruples
          ª            #   And append the question name as trailing item to each

Try just this fifth step with the HTML as input.
Step 6: Filter this list, so it only contains answers from the earlier list, and only the language that's equal to the input:
ʒ                      #  Filter this list of quintuples by:
 н                     #   Pop and leave its first item (the language name)
  l                    #   Convert it to lowercase
   Il                  #   Get the input in lowercase as well
     Q                 #   And check that both are equal
}ʒ                     #  After the filter: filter once again:
  1è                   #   Get the second item (the answer URL)
    '/¡               '#   Split it on "/"
       4è              #   Leave its fifth item (the answer-id)
         X             #   Push the list of answer-ids from variable `X`
          så           #   And check if the current answer-id is in it
]                      # Close both the filter and outer map

Try just the sixth step with the list of quintuples of the previous step as input.
Step 7: Convert it to the output in the specified format:
 €`                    # After the map over the questions, flatten it one level down
   D                   # Duplicate this list
    ε                  # Map over the quintuplets:
     Ƶ=                #  Push compressed integer 214
       Sè              #  Leave just the third, second, and fifth items
          `            #  Pop and push them separated to the stack
      “- [ÿ](ÿ)€‹ [ÿ]“ #  Push dictionary string "- [ÿ](ÿ) by [ÿ]",
                       #  where the `ÿ` are filled again
    }»                 # After the map: join the strings by newlines
   sε                  # Swap, and map over the quintuplets again:
     32Sè              #  Leave just the fourth and third items
         `             #  Pop and push them separated to the stack
      "[ÿ]:ÿ"          #  Push string "[ÿ]:ÿ",
                       #  where the `ÿ` are filled again
    }»                 # After the map: join the strings by newlines as well
      ¶2×ý             # Then join these two strings with "\n\n" as delimiter
                       # (after which the result is output implicitly)

Try just the sixth and seventh steps with the list of quintuplets of step five as input.
See this 05AB1E tip of mine (sections How to use the dictionary? and How to compress large integers?) to understand how the dictionary strings and compressed integers work.


Count cyclically self-describing lists Cyclically self-describing lists

A list \$L\$ of positive integers is cyclically self-describing, if the following conditions hold.

\$L\$ is nonempty.
The first and last elements of \$L\$ are different.
If you split \$L\$ into runs of equal elements, the element of each run equals the length of the next run, and the element of the last run equals the length of the first run.

For example, consider \$L = [1,1,1,2,3,3,1,1,1,3]\$.
It is nonempty, and the first and last elements are different.
When we break it into runs, we get \$[[1,1,1],[2],[3,3],[1,1,1],[3]]\$.

The first run is a run of \$1\$s, and the length of the next run, \$[2]\$, is \$1\$.
The second run is a run of \$2\$s, and the length of the next run, \$[3,3]\$, is \$2\$.
The third run is a run of \$3\$s, and the length of the next run, \$[1,1,1]\$, is \$3\$.
The fourth run is a run of \$1\$s, and the length of the next run, \$[3]\$, is \$1\$.
Finally, the last run is a run of \$3\$s, and the length of the first run, \$[1,1,1]\$, is \$3\$.

This means that \$L\$ is a cyclically self-describing list.

For a non-example, the list \$[3,2,2,2,1,4,1,1,1]\$ is not cyclically self-describing, since a run of \$2\$s is followed by a run of length \$1\$.
The list \$[2,2,4,4,3,3,3,3]\$ is also not cyclically self-describing, since the last run is a run of \$3\$s, but the first run has length \$2\$.

The Task

In this challenge, your input is an integer \$n \geq 1\$.
Your output shall be the number of cyclically self-describing lists whose sum equals \$n\$.
For example, \$n = 8\$ should result in \$4\$, since the cyclically self-describing lists whose sum is \$8\$ are \$[1,1,1,1,4]\$, \$[1,1,2,1,1,2]\$, \$[2,1,1,2,1,1]\$ and \$[4,1,1,1,1]\$.
The lowest byte count wins, and other standard code-golf rules apply.

Here are the correct output values for inputs from \$1\$ to \$50\$:

1 -> 0
2 -> 0
3 -> 0
4 -> 2
5 -> 0
6 -> 2
7 -> 0
8 -> 4
9 -> 0
10 -> 6
11 -> 6
12 -> 12
13 -> 0
14 -> 22
15 -> 10
16 -> 32
17 -> 16
18 -> 56
19 -> 30
20 -> 96
21 -> 56
22 -> 158
23 -> 112
24 -> 282
25 -> 198
26 -> 464
27 -> 364
28 -> 814
29 -> 644
30 -> 1382
31 -> 1192
32 -> 2368
33 -> 2080
34 -> 4078
35 -> 3844
36 -> 7036
37 -> 6694
38 -> 12136
39 -> 12070
40 -> 20940
41 -> 21362
42 -> 36278
43 -> 37892
44 -> 62634
45 -> 67154
46 -> 108678
47 -> 118866
48 -> 188280
49 -> 209784
50 -> 326878

Haskell, 75 bytes

Thanks Ørjan for saving one byte!

g n=sum[x#n|x<-[1..n],let a#n=sum$[b#(n-a*b)|b<-[1..n],a/=b]++[0^n^2|a==x]]

Try it online!

The problem is equivalent to:

How many ways can \$n\$ be written as \$\sum_{i=0}^ka_ia_{i+1}\$ with \$a_i\in\mathbb N,a_i\neq a_{i+1},a_0=a_k\$


JavaScript (ES6), 101 99 bytes

Takes input as 2 arrays. Returns a string.

f=(a,b,j=0,s='')=>a.map((v,i)=>(s+=i*j?' ':s&&'][',s+=b[j]+v,j=++j%b.length))|j?f(a,b,j,s):`[${s}]`

How it works

We iterate on the first array a with a pointer i while updating another pointer j into the second array b. The sums a[i] + b[j] are appended to the output string s. A separator is inserted each time i == 0 or j == 0. We repeat this process until j is back exactly at the beginning of b at the end of an iteration.

Note: When the | operator is applied, a.map(...) is coerced to either NaN (if a contains more than one element) or the current value of j (if a contains exactly one element). Therefore, a.map(...)|j == j in all cases and is safe to use here.

Test cases

f=(a,b,j=0,s='')=>a.map((v,i)=>(s+=i*j?' ':s&&'][',s+=b[j]+v,j=++j%b.length))|j?f(a,b,j,s):`[${s}]`

console.log(f([1], [4]));
console.log(f([1,2,-3,-4], [15]));
console.log(f([0,-4], [2,1,0,-3]));
console.log(f([0,3,2,2,8,4], [7,8,7,2]));
console.log(f([18,17,16], [-1,-2,-3,-4]));
console.log(f([18,17,16,15], [-1,-2,-3,-4]));
console.log(f([1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
console.log(f([1,1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
console.log(f([1,1,1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));


Draw an SQL Output Table I'm sure most of us have seen SQL results in a terminal, all neatly formatted into rows and columns. If you haven't, here's an example:

+----------+-----------+----------------+
| column 1 | column 2  | column 3       |
+----------+-----------+----------------+
| data     | more data | even more data |
| etc      | just goes | on and on      |
+----------+-----------+----------------+

Your goal for this challenge is, given the columns and row data for a table, draw the table in this style. There should be a horizontal line at the top and bottom of the table, and one right below the header row. There should be vertical lines between every column, and one on both sides of the table. You should use pipes for vertical lines, hyphens for horizontal lines, and plusses for where they intersect.

Specifics:

The data can be entered via stdin, or as the argument to a function, but it must be in some form of string
The data should be split by the string delimiter ;
The data will consist of only ASCII characters, is not quoted, and will not contain the delimiter.
The first row of the data will be used for column headers
The data will always have the same number of columns
The input will always contain at least two rows (one header, one data). You do not have to handle empty sets.
A trailing or preceding newline is permitted
Each column should be as wide as the widest element, padding shorter elements on the right (bonus -5% if you pad numbers on the left)
There should be 1 space of padding before and after the headers and data, except when the column is wider
You are not allowed to use the actual mysql program to generate the table
Standard loopholes apply

Sample Input:

column 1;column 2;column 3
hello;world;test
longer data;foo;bar

Output

+-------------+----------+----------+
| column 1    | column 2 | column 3 |
+-------------+----------+----------+
| hello       | world    | test     |
| longer data | foo      | bar      |
+-------------+----------+----------+

Scoring:

Lowest number of bytes wins, of course. -5% bonus for padding numbers on the left (see specifics).

CJam, 67 58 bytes

' qN/';f/ff+z_.{[z,):TS*'|+f.e|T'-*'++:T\(T@~T]}z{s_W=\N}/

Try it online in the CJam interpreter.


Separate alphabets and numbers A paragraph of text has numbers and alphabetic letters mixed. Your task is to separate the numbers to the left side and the alphabetic letters to the right side in the same order of each line.

Rules:

Numbers are plain integers; so no decimal point, and no negative/positive signs.
Numbers may or may not be contiguous, but whatever the case may be, they have to be pushed to left side in the same order.
Numbers may occur in between words.
The text contains only ASCII alphabetic letters and numbers, along with spaces, underscores, commas and dots.
The one who does this with minimum keystrokes (like vim macros) or least amount of bytes in case of scripting is the winner.

Example Text:

A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.

Expected output:

433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

Retina, 14 bytes

O%$`\d|(.)
$#1

Try it online!

Explanation

O introduces a sorting stage. % tells Retina to apply the transformation to each line separately. $ tells it to sort the matches by the result of the specified substitution.

The regex itself is \d|(.) which either matches a digit, or anything else which is captured into group 1. This is substituted with $#1 which is the number of captures of group 1. That is, the sorting key for digits is 0 and the sorting key for everything else is 1. Since sorting in Retina is stable, this simply moves digits to the left and everything else to the right.