Program that encodes a message into its own text Write a program that encodes given text into its own text, provided as input, without disrupting its logic. The program must also work as a decoder, restoring the original message from its text. It must retain its encoding/decoding functions after transformation.

More formally speaking, the required program P must perform the following transformations with the given message text M:
P(M,P)->P*
P*(P*)->M

Here P* is the transformed program, which also must satisfy the above rules, that is:
P*(M2,P*)->P**
P**(P**)->M2
and so on... Each subsequent encoding doesn't erase previously encoded text, so P** carries two messages - M and M2.

The easiest way for the program to distinguish between encoding/decoding modes is by the presence of the extra argument M, but the final decision is up to you, provided it is clearly stated. The program may read it's own text from the file. If the chosen language doesn't have means for this, the source text can be passed to the program in any other way.

There are trivial solutions, of course, so this is rather a popularity contest. Nevertheless, I impose restriction forbidding comments in the program text.

Perl

This is a one-liner in Perl just because it's possible.

if($ARGV[0]){open(F,__FILE__);while(<F>){print;print"$ARGV[0]\n"if/^_/;}}else{print<DATA>;}
__DATA__

The messages are written after __DATA__, most recent first.


Lead Your Turtle by a String Write a program or function that takes in a nonempty single-line string of printable ascii characters excluding space:

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

You may assume the input is valid.

Based on the input, draw a new string arranged on a textual grid of spaces and newlines following turtle graphics-esque rules where the turtle always occupies one grid space and can only face the cardinal directions.

Print the first character in the input string to the text grid. The turtle starts here facing right. Iterate over the rest of the characters in the input string (only stopping if the turtle gets stuck), repeating this process:

If the 4 grid spaces directly neighboring the turtle are all filled (i.e. none of them is a space), stop iterating. The turtle is stuck and the grid is as  complete as it can be.
Look at the current character in the input compared to the previous character:

If the current character is lexically before the previous, rotate the turtle a quarter turn left.
If the current character is lexically after the previous, rotate the turtle a quarter turn right.
If the current character equals the previous, don't rotate the turtle.

If the grid space the turtle is now facing is not empty (i.e. not a space), repeatedly rotate the turtle a quarter turn left until she is facing an empty grid space.
Move the turtle one grid step forward in the direction she's facing and print the current character on the grid in the turtle's new location.

Print or return the resulting text grid string with no extraneous rows or columns of whitespace. Lines may have trailing spaces up to the rightmost column with a non-space, but not beyond. A single trailing newline is optionally allowed.

The shortest code in bytes wins.

Example

Here are all the steps of the input spattuuxze. The ^V<> characters show the direction the turtle is facing, they are not part of the input or output.

s>

^
p
s

<ap
  s

^
t
ap
 s

^
t
t
ap
 s

tu>
t
ap
 s

tuu>
t
ap
 s

tuu
t x
apV
 s

tuu
<zx
ap
 s

At this point the turtle is stuck so the e never gets printed and the final output is:

tuu
tzx
ap
 s

Following is a similar but invalid output since it has an unnecessary leading column of whitespace:

 tuu
 tzx
 ap
  s

Test Cases

spattuuxze

tuu
tzx
ap
 s

spattuuxxze

tuu
t x
apx
 sze

1111111

1111111

ABCDEFGHIJKLMNOP

PEFG
ODAH
NCBI
MLKJ

`_^]\[ZYXWVUTSR

 ^_RS
\]`UT
[ZWV
 YX

Woo!

W
o
o!

woo!

!o
 o
 w

Wheeee

W
heeee

banana

  a
 an
an
b

Turtle

T
ure
 tl

turTle

  e
tTl
ur

(Do tell me right away if any of these seem wrong.)


Elias omega coding: decoding Related: Elias omega coding: encoding
Background
Elias omega coding is a universal code which can encode positive integers of any size into a stream of bits.
Given a stream of bits \$S\$, the decoding algorithm is as follows:

If \$S\$ is empty, stop. Otherwise, let \$N=1\$.
Read the next bit \$b\$ of \$S\$.
If \$b=0\$, output \$N\$ and return to step 1.
Otherwise, \$b=1\$. Read \$N\$ more bits from \$S\$, append to \$b\$, and convert it from binary to integer. This is the new value of \$N\$. Go back to step 2.

In Python-like pseudocode:
s = input()
while s.has_next():
    n = 1
    while (b = s.next()) == 1:
        loop n times:
            b = b * 2 + s.next()
        n = b
    output(n)

Illustration
If the given bit stream is 101001010100:

Initially \$N = 1\$.
Since the first bit is 1, we read 1 more bit (2 bits in total) to get the new value of \$N = 10_2 = 2\$. Now the stream is 1001010100.
Proceed as the same. Read a bit (1) and \$N = 2\$ more bits to get \$N = 100_2 = 4\$. Stream: 1010100
Read a bit (1) and \$N = 4\$ more bits to get \$N = 10101_2 = 21\$. Stream: 00
Read a bit (0). Since it is 0, output the current \$N = 21\$. The stream has more bits to be consumed, so we reset to \$N=1\$ and continue. Stream: 0
Read a bit (0). Output the current \$N = 1\$. The stream is empty, and decoding is complete.

The output for the input stream 101001010100 is [21, 1].
Task
Given a stream of bits which consists of zero or more Elias omega coded integers, decode into the original list of integers. You can assume the input is valid (the input stream won't be exhausted in the middle of decoding a number).
Shortest code in bytes wins.
Test cases
Input => Output
(empty) => []
0       => [1]
00      => [1,1]
00100   => [1,1,2]
101001010100 => [21,1]
1110000111100001110000 => [8,12,1,8]
1111000111000101011001011110011010100001010 => [12,345,6789]

convey, 66 bytes
1<<<<,<<
/>>>v$1^
,<"<##<^
:`#?@#^^
{1$v>"}%2
  ~,>/+?<
  3 0$,>*2

Try it online!
Explanation will follow after I tried some other orientations …


Expand a bash brace expansion For mostly historical reasons, bash is quite a hodge-podge of syntax and programming paradigms - this can make it awkward and sometimes frustrating to golf in.  However it does have a few tricks up its sleeve that can often make it competitive with other mainstream script languages.  One of these is brace expansion.

There are two basic types of brace expansion:

List braces may contain comma-separated lists of arbitrary strings (including duplicates and the empty string).  For example {a,b,c,,pp,cg,pp,} will expand to a b c  pp cg pp (note the spaces around the empty strings).
Sequence braces may contain sequence endpoints separated by ... Optionally another .. may follow, followed by a step size.  Sequence endpoints may be either integers or characters.  The sequence will automatically ascend or descend according to which endpoint is greater.  For example:

{0..15} will expand to 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
{-10..-5} will expand to -10 -9 -8 -7 -6 -5
{3..-6..2} will expand to 3 1 -1 -3 -5
{a..f} will expand to a b c d e f
{Z..P..3} will expand to Z W T Q

Beyond this, sequence and list braces may exist with list braces:

{a,b,{f..k},p} will expand to a b f g h i j k p
{a,{b,c}} will expand to a b c

Braces expand with non-whitespace strings either side of them.  For example:

c{a,o,ha,}t will expand to cat cot chat ct

This also works for multiple braces concatenated together:

{ab,fg}{1..3} will expand to ab1 ab2 ab3 fg1 fg2 fg3

This can get quite complex.  For example:

{A..C}{x,{ab,fg}{1..3},y,} will expand to Ax Aab1 Aab2 Aab3 Afg1 Afg2 Afg3 Ay A Bx Bab1 Bab2 Bab3 Bfg1 Bfg2 Bfg3 By B Cx Cab1 Cab2 Cab3 Cfg1 Cfg2 Cfg3 Cy C

However, if there is whitespace between expansions, then they simply expand as separate expansions.  For example:

{a..c} {1..5} will expand to a b c 1 2 3 4 5

Note how order is always preserved.

Entries for this challenge will expand bash brace expansions as described above.  In particular:

eval by bash (or other shells that perform similar expansion) is not allowed
sequence braces will always be number-to-number, lowercase-to-lowercase or uppercase-to-uppercase with no mixing.  Numbers will be integers in the 32-bit signed range.  If given, the optional step size will always be a positive integer.  (Note that bash will also expand {A..z} as well, but this may be ignored for this challenge)
individual items in list braces will always be composed only of upper- and lower-case alphanumeric characters (empty string included)
list braces may contain arbitrary nestings of other brace expansions
braces may be concatenated arbitrary numbers of times.  This will be limited by your language's memory, so the expectation is that you can theoretically do arbitrary numbers of concatenations but if/when you run out of memory that won't count against you.

The examples in the text above serve as testcases.  Summarised, with each line of input corresponding to the same line of output, they are:

Input

{0..15}
{-10..-5}
{3..-6..2}
{a..f}
{Z..P..3}
{a,b,{f..k},p}
{a,{b,c}}
c{a,o,ha,}t
{ab,fg}{1..3}
{A..C}{x,{ab,fg}{1..3},y,}
{a..c} {1..5}
{a{0..100..10},200}r

Output

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-10 -9 -8 -7 -6 -5
3 1 -1 -3 -5
a b c d e f
Z W T Q
a b f g h i j k p
a b c
cat cot chat ct
ab1 ab2 ab3 fg1 fg2 fg3
Ax Aab1 Aab2 Aab3 Afg1 Afg2 Afg3 Ay A Bx Bab1 Bab2 Bab3 Bfg1 Bfg2 Bfg3 By B Cx Cab1 Cab2 Cab3 Cfg1 Cfg2 Cfg3 Cy C
a b c 1 2 3 4 5
a0r a10r a20r a30r a40r a50r a60r a70r a80r a90r a100r 200r

Ruby, 405 403 401 400 bytes
A wise man (Jamie Zawinski) once said, "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."
I don't think I fully appreciated that quote until I tried to solve this problem with recursive regex. Initially, the regex cases seemed simple, until I had to deal with the edge cases involving letters adjacent to brackets, and then I knew that I was in hell.
Anyways, run it online here with test cases
->s{s.gsub!(/{(-?\w+)..(-?\w+)(..(\d+))?}/){x,y=$1,$2;a,b,c=[x,y,$4].map &:to_i
$1[/\d/]?0:(a,b=x,y)
k=a<b ?[*a..b]:[*b..a].reverse
?{+0.step(k.size-1,$4?c:1).map{|i|k[i]}*?,+?}}
r=1
t=->x{x[0].gsub(/^{(.*)}$/){$1}.scan(/(({(\g<1>|,)*}|[^,{}]|(?<=,|^)(?=,|$))+)/).map{|i|i=i[0];i[?{]?r[i]:i}.flatten}
r=->x{i=x.scan(/({(\g<1>)*}|[^{} ]+)/).map(&t)
i.shift.product(*i).map &:join}
s.split.map(&r)*' '}

Ungolfed:
->s{
  s.gsub!(/{(-?\w+)..(-?\w+)(..(\d+))?}/){  # Replace all range-type brackets {a..b..c}
    x,y=$1,$2;a,b,c=[x,y,$4].map &:to_i     # Set up int variables
    $1[/\d/]?0:(a,b=x,y)                    # Use int variables for a,b if they're numbers
    k=a<b ?[*a..b]:[*b..a].reverse          # Create an array for the range in the correct direction
    '{'+                                    # Return the next bit surrounded by brackets
      0.step(k.size-1,$4?c:1).map{|i|k[i]   # If c exists, use it as the step size for the array
      }*','                                 # Join with commas
      +'}'
  }
  r=1                                       # Dummy value to forward-declare the parse function `r`
  t=->x{                                    # Function to parse a bracket block
    x=x[0].gsub(/^{(.*)}$/){$1}             # Remove outer brackets if both are present
                                            # x[0] is required because of quirks in the `scan` function
    x=x.scan(/(({(\g<1>|,)*}|[^,{}]|(?<=,|^)(?=,|$))+)/)
                                            # Regex black magic: collect elements of outer bracket
    x.map{|i|i=i[0];i[?{]?r[i]:i}.flatten   # For each element with brackets, run parse function
  }
  r=->x{                                    # Function to parse bracket expansions a{b,c}{d,e}
    i=x.scan(/({(\g<1>)*}|[^{} ]+)/)        # Regex black magic: scan for adjacent sets of brackets
    i=i.map(&t)                             # Map all elements against the bracket parser function `t`
    i.shift.product(*i).map &:join          # Combine the adjacent sets with cartesian product and join them together
  }
  s.split.map(&r)*' '                       # Split on whitespace, parse each bracket collection
                                            #   and re-join with spaces
}


Simulate a game of Craps Craps is a fairly simple dice game often played in casinos. Even if you aren't a gambler (which I'm not), it's still a fairly interesting game. Here's the rules:
At the start of a game of Craps there's what is called the come-out round. The player rolls two d6s (six-sided die) and the two die rolls are added. If the result is 7 or 11, the person automatically wins (this is known as a natural). If the result is 2, 3 or 12 the person automatically loses (this is known as crapping out). Otherwise, the result is set as the point for the point round.
After this, the point round begins. During the point round, the player must continuously roll 2 d6s until the person rolls a 7 or his/her point from the previous round. If the person rolls a 7, they lose. If they roll their point, they win.
Challenge
Implement a simple program that simulates a game of craps. If the person rolls a natural or a crap-out during the come-out round, the program should output "Natural: " or "Crapping out: " followed by the die-roll and then exit. Otherwise, it should output "Point: " followed by the point. Then, during the point round, it should output every die-roll until a 7 or the point is reached. If the person wins, it should output "Pass"; if they lose it should output "Don't Pass".
Reference Implementation
Groovy, 277 bytes
def a={return Math.random()*6+1};int b=a()+a();(b<4||b==12)?{println"Crapping out: "+b}():{(b==7||b==11)?{println"Natural: "+b}():{println"Point: "+b;for(;;){int x=a()+a();println x;(x==7)?{println"Don't Pass";System.exit(0)}():{if(x==b){println"Pass";System.exit(0)}}()}}()}()

Try it online.
Sample outputs
Natural: 7
Crapping out: 3
Point: 9
4
8
11
9
Pass

and
Point: 5
3
7
Don't Pass

This is code-golf, so shortest code wins.
(DISCLAIMER: This challenge is not intended to promote gambling in any way. Remember, the house always wins.)

Ruby 164
Pretty straightforward. Interesting features:
The crapping out cases are summarised as r%12<4 and the remaining natural cases are summarised as r%4==3.
The initial string is stored in c and further rolls are taken only if this is later alphabetically than the single letter ?P (which only occurs for Point.)
f=->{rand(6)+rand(6)+2}
s=0
r=f[]
print c=r%12<4?'Crapping out':r%4==3?'Natural':'Point',": #{r}
"
c>?P&&(until s==r||s==7
p s=f[]end
print s==7?"Don't ":"","Pass")


Crash your favorite compiler Write a perfectly legal code in a decent language of your choice whose compiling will either crash the compiler or send it into an infinite loop (infinite compile time).

Restrictions:

Use a standard language that is used in real world.
Use a standard, well-developed compiler (no answers like "I wrote my C compiler that crashes on everything").
The code must be legal in the language (so most likely you'll have to exploit a compiler or a language bug).
Give your compiler version and options used so that others can replicate it.
Explain why the compiler crashed, if possible.

Have fun :)

My favorite solution for GHC:

data Bad a = C (Bad a -> a)

xx :: Bad a -> a
xx (x@(C x')) = x' x

omega :: a
omega = xx (C xx)

main = omega

For GHC 6.12.1 both ghci Bad.hs and ghc Bad.hs loop infinitely.
GHC 7.4.1 loops infinitely when ghc -O2 Bad.hs is executed.

Explanation: omega is defined using an infinite recursion (the only way it can inhabit any type). Compiler's inliner sees xx as a simple, non-recursive function, so it tries to inline it in the definition of omega. It results in (\x@(C x') -> x' x) (C xx). Seeing a pattern match on a constructor the compiler tries to reduce it, getting xx (C xx) again and loops. The trick is that xx is actually recursive, but the recursion is hidden within the data type.

Note: While writing the puzzle, I forgot I left GHC running in the infinite loop. It took all my memory, crashed Firefox and I barely managed to kill it without hard reset.


VEVO User Account Checker We often see music videos on Youtube. Many Youtube channels that host music videos are "powered by VEVO". Those can be easily identified by both embedding VEVO at their video thumbnails and appending VEVO to their channel name.

Now write some code to test whether a string given by user is a VEVO user account or not.

Requirements for valid VEVO user account strings:

Must only contain uppercase, lowercase, and digit characters. (no whitespace or punctuation)
Must not exceed 80 characters length.
Must have "VEVO" substring at the end of string

Test cases:

Valid inputs:

AdeleVEVO
ConnieTalbotVEVO
SHMVEVO
justimberlakeVEVO
DJMartinJensenVEVO
test123VEVO

Invalid inputs:

syam kapuk
jypentertainment
Noche de Brujas
testVEVO123

Of course, because this is code-golf, I'm looking for the shortest code using any programming language.

Python 2, 45 bytes

-3 bytes thanks to Rod. -2 bytes thanks to ovs.

lambda s:len(s)<81*s.isalnum()<'VEVO'==s[-4:]

Try it online!

A regex solution turns out to be longer.

lambda s:re.match('^[^\W_]{0,76}VEVO$',s)
import re


Rafting Problem (Knapsack variant) First puzzle from me, suggestions for improvement gladly received!

The scenario is;
You work as a manager for a whitewater rafting company. Every morning, you are given a list of bookings, and you have to sort them into raft loads. Write a program or function in your chosen language that does this for you.

Each raft holds a maximum of n clients, and each booking is for a group of between 1 and n people (inclusive).
The following rules must be observed;

No groups may be split up. If they booked together, they must all be in the same raft.
The number of rafts must be minimised.
Subject to the two preceeding rules, the groups must be spread as equally as possible between the rafts.

Inputs.
The number n (you may assume that this is a positive integer), and the size of all the bookings. This may be an array, list or similar data structure if your language supports such things. All of these will be positive integers between 1 and n. The order of the bookings is not defined, nor is it important.

Output.
A list of the booking numbers, grouped into raft loads. The grouping must be indicated unambiguously, such as;

a list, or array of arrays.
a comma separated list for each raft. Newline between each raft.

How you implement the third rule is up to you, but this could involve finding the average raft occupancy, and minimising deviations from it as much as possible. Here are some test cases.

n  Bookings       Output
6  [2,5]          [5],[2]
4  [1,1,1,1,1]    [1,1,1],[1,1]
6  [2,3,2]        [2,2],[3]
6  [2,3,2,3]      [2,3],[2,3]
6  [2,3,2,3,2]    [2,2,2],[3,3]
12 [10,8,6,4,2]   [10],[8,2],[6,4]
6  [4,4,4]        [4],[4],[4]
12 [12,7,6,6]     [12],[7],[6,6]

Standard rules apply, shortest code wins. Have fun!

Edited;
A suggested way to define as equally as possible for the third rule.

Once the number of rafts r has been determined (subject to the second rule), the average occupancy a can be calculated by summing over the bookings, and dividing by r. For each raft, the deviation from the average occupancy can be found using d(x) = abs(n(x)-a), where n(x) is the number of people in each raft and 1 <= x <= r.
For some continuous, single-valued function f(y), which is strictly positive and has a strictly positive first and non-negative second derivatives for all positive y, we define a non-negative quantity F, as the sum of all the f(d(x)), 1 <= x <= r. Any choice of raft allocation that satisfies the first two rules, and where F is equal to the global minimum will satisfy the third rule also.

Haskell 226 228 234 268 bytes

Naive answer in Haskell

import Data.List
o=map
u=sum
p=foldr(\x t->o([x]:)t++[(x:y):r|(y:r)<-t>>=permutations])[[]]
m x=foldl(\[m,n]x->[m+(x-m)/(n+1),n+1])[0,0]x!!0
a!z=abs$u z-a
s t=(length t,u$o((m$o u t)!)t)
a n=head.sortOn s.filter(all$(<=n).u).p

Or ungolfed

partition' :: [a] -> [[[a]]]
partition' [] = [[]]
partition' (x:xs) = [[x]:ps     | ps <- partition' xs]
                 ++ [(x:p):rest | ps <- partition' xs, (p:rest) <- permutations ps]

-- from Data.Statistics
mean :: [Double] -> Double
mean xs = fst $ foldl (\(m, n) x -> (m+(x-m)/n+1, n+1)) (0, 0) xs

diff :: Double -> [Double] -> Double
diff avg xs = abs $ sum xs - avg

rawScore :: [[Double]] -> Double
rawScore xs = sum . map (diff avg) $ xs where avg = mean . map sum $ xs

score :: [[Double]] -> (Int, Double)
score xs = (length xs, rawScore xs)

-- from Data.Ord
comparing :: (Ord b) => (a -> b) -> a -> a -> Ordering
comparing p x y = compare (p x) (p y)

candidates :: Double -> [Double] -> [[[Double]]]
candidates n xs = filter (all (\ ys -> sum ys <= n)) . partition' $ xs

answer :: Double -> [Double] -> [[Double]]
answer n xs = minimumBy (comparing score) $ candidates n xs

With some test cases

import Text.PrettyPrint.Boxes

testCases :: [(Double, [Double])]
testCases = [(6 , [2,5])
            ,(4 , [1,1,1,1,1])
            ,(6 , [2,3,2])
            ,(6 , [2,3,2,3])
            ,(6 , [2,3,2,3,2])
            ,(12, [10,8,6,4,2])
            ,(6 , [4,4,4])
            ,(12, [12,7,6,6])]

runTests tests = transpose
                 $ ["n", "Bookings", "Output"]
                 : map (\(n, t) -> [ show . floor $ n
                                   , show . map floor $ t
                                   , show . map (map floor) $ a n t]) tests

test = printBox
     . hsep 3 left . map (vcat top) . map (map text) . runTests $ testCases

Where test yields

n    Bookings       Output
6    [2,5]          [[2],[5]]
4    [1,1,1,1]      [[1,1],[1,1,1]]
6    [2,3,2]        [[2,2],[3]]
6    [2,3,2,3]      [[2,3],[2,3]]
6    [2,3,2,3,2]    [[2,2,2],[3,3]]
12   [10,8,6,4,2]   [[10],[8,2],[6,4]]
6    [4,4,4]        [[4],[4],[4]]
12   [12,7,6,6]     [[12],[7],[6,6]]

Edit

Thanks to @flawr and @nimi for advice.

Squashed p a bit.

Shaved off a couple bytes.


Treasure Map Drawing Bot You're organizing a treasure hunt for your friends. To conduct things more easily, you want to draw a map of all locations where you hid the precious objects.
Input
Any form of input denoting a list of points consisting of (nonnegative) x- and y-coordinate, 0 0 being the upper left corner is permitted (Note: You may also use 1-based indexing in your answer, please comment on that if you do). Example:
1 2
3 0
0 1

Challenge
Your function or program should be able to construct a map denoting every given location with an x where the mark is found in row y + 1 and column x + 1 in the output. Unmarked locations are represented with a  . The map also consists of a frame where the corners are +s, the vertical lines are |s and the horizontal lines are -s. Your solution should output the smallest possible frame. Map for the input example given above:
+----+
|   x|
|x   |
| x  |
+----+

Possible Test Cases

"0 0"
=>
+-+
|x|
+-+

"0 10
 5 5
 10 0"
=>
+-----------+
|          x|
|           |
|           |
|           |
|           |
|     x     |
|           |
|           |
|           |
|           |
|x          |
+-----------+

""
=>
++
++

"0 0
 0 2
 2 0"
=>
+---+
|x x|
|   |
|x  |
+---+

Of course, this is code-golf, meaning that the solution with the lowest byte count wins! Explanations of your solution are encouraged.

J, 37 34 bytes

0<@|:' x'{~((i.@]e.#.~)1+>./) ::#:

Try it online!

                       1+>./          maximum for each coordinate + 1
             i.@]                     make an array with these dimensions filled with 0..x*y
                                      /* if the input is empty,
                                         1+>./ is negative infinity
                                         and i.@] throws an error  */
                   #.~                mixed base conversion of input
                 e.                   replace the elements of i.@]
                                        with 1 if it's present in the
                                        converted input, 0 otherwise
           (                ) ::      if there's an error do the other thing instead
                                #:    "to binary", for empty input this returns a 0x0 matrix
0<@|:' x'{~                           index into character string, transpose and put in a box


Is that number a Two Bit Number™? Let's start by defining a Two Bit Number™:

It is a positive integer
When expressed as a binary string it has exactly 2 true bits OR
When expressed as a decimal number, it has exactly 2 of the numeral one, and all other numerals are zero.

Or as a sentence
A Two Bit Number™ is a number which contains exactly 2 of the numeral 1 and no other numerals besides 0, when expressed as a decimal string or a binary number.
So here area all the Two Bit Numbers™ between 0 and 256
Dec  Bin       Type
3    00000011  Binary
5    00000101  Binary
6    00000110  Binary
9    00001001  Binary
10   00001010  Binary
11   00001011  Decimal
12   00001100  Binary
17   00010001  Binary
18   00010010  Binary
20   00010100  Binary
24   00011000  Binary
33   00100001  Binary
34   00100010  Binary
36   00100100  Binary
40   00101000  Binary
48   00110000  Binary
65   01000001  Binary
66   01000010  Binary
68   01000100  Binary
72   01001000  Binary
80   01010000  Binary
96   01100000  Binary
101  01100101  Decimal
110  01101110  Decimal
129  10000001  Binary
130  10000010  Binary
132  10000100  Binary
136  10001000  Binary
144  10010000  Binary
160  10100000  Binary
192  11000000  Binary

The challenge:

Write some code which accepts a number and outputs true or false (or some indicator of true or false) if it is a Two Bit Number™.
Input will always be an integer, but it may not always be positive.
It can be in any language you like.
It's code golf, so the fewest bytes wins.
Please include links to an online interpreter for your code (such as tio.run).

Test Cases
Binary Two Bit Numbers™:

3
9
18
192
288
520
524304

Decimal Two Bit Numbers™:

11
101
1001
1010
1100
1000001
1100000000
1000000010

Non Two Bit Numbers™:

0
1
112 (any numerals over 1 prevent it being a binary
200
649
-1
-3

Fun fact: I was not able to find any DecimalBinary Two Bit Numbers™ checking up to about 14 billion, and I have a hypothesis that such a number does not exist, but I have no mathematical proof. I'd be interested to hear if you can think of one.

Python 3, 68 62 48 bytes
-6 bytes thanks to xnor!
-14 bytes thanks to Jitse!

lambda n:' 11 'in f' {n:b} {n} '.replace('0','')

Try it online!


Display percent battery remaining Display the remaining battery charge, as a percentage of maximum charge

Remember if you can't run your code on a phone, calculator, etc, you can probably install your environment on a laptop at least. If you absolutely can't run on a device that has a battery, then unfortunately your language isn't eligible since you have no useful value to print.

You must display the results on the screen. This is theoretically supposed to be a handy utility for the user to check the battery. Writing battery percent to a file is too clunky, requiring the user to then check the file. Displaying on-screen is therefore a part of the specification that can't be overridden by default IO. That said, you can assume nothing is preventing things like STDOUT from being displayed on screen in the usual way.

If the battery percent is already displayed on screen all the time by the OS, like on many phones, that does not mean you've got a zero-byte solution. You must assume that built-in display doesn't exist, and display the battery percent again somewhere else.

Edit: The output format is being opened up. You are free to display as little as just the digits of the percent, or the digits with some extra output as well.

Edit2: The digits representing the percent must appear in a known location within the output, not more than 50 lines from the end of the output, and that location shouldn't change between invocations. The digits representing the percent must be separated from other output by at least one non-digit character on each side.

For reference here is the old output format from before the change:

Remaining battery is ddd%
or
Remaining battery is ddd percent

Bash, 70 67 50 46 43 16 bytes

`</*/*/*/B*/c*y`

Outputs: <battery 0-100>: command not found

Reads the file /sys/class/power_supply/BAT1/capacity.

Tested using Ubuntu 18.04 on a LENOVO ideapad 500.

Takes a while (since it searches the entire filesystem) - but it saves a byte!

Old answer:

echo Remaining battery is `</*/*/*/B*/c*y`%


Is my triangle on the lattice? Write a program or function which takes three positive integers \$a, b, c\$ and returns/outputs one value if there is, and a different value if there isn't, a triangle on the square lattice, whose sides' lengths are \$\sqrt{a}, \sqrt{b}, \sqrt{c}\$. By "on the square lattice" I mean that its vertices are in the \$xy\$ plane, and their \$x\$ and \$y\$-coordinates are all integers
This is code-golf so the shortest code in bytes wins.
Test cases:

16 9 25: true (3-4-5 triangle)
8 1 5: true (e.g. (0,0), (1,0), (2,2))
5 10 13: true (e.g. (0,1), (1,3), (3,0); sides needn't be on grid lines)
10 2 1: false (not a triangle: long side is too long for short sides to meet)
4 1 9: false (not a triangle: three points in a straight line)
3 2 1: false (triangle is on the cubic lattice but not the square lattice)
3 7 1: false (triangle is on the hex lattice but not the square lattice)
25 25 25: false (no such triangle on this lattice)
5 5 4: true (isosceles is OK)
15 15 12: false (OK shape, wrong size)
25 25 20: true (OK shape and size; common prime factor 5 is OK)
4 4 5: false (Bubbler's suggestion)
17 17 18: true (acute isosceles with equal short sides OK)
26 37 41: true (acute scalene is OK)

These same test cases, but just the numbers. First, those that should return true:
16 9 25
8 1 5
5 10 13
5 5 4
25 25 20
17 17 18
26 37 41

Then those that should return false:
10 2 1
4 1 9
3 2 1
3 7 1
25 25 25
15 15 12

Python3, 171 151 142 137 133 bytes

151 => 142 Thanks to @user
142 => 137 and fixed correctness thanks to @Bubbler
137 => 133 thanks to @xnor and @Bubbler

lambda l:l in[[d*d+D*D,e*e+E*E,(d-e)**2+(D-E)**2]for d,e,D,E in product(*[range(-max(l),max(l))]*4)if d*E-e*D]
from itertools import*

Tests here:
TESTS = [
    (16,9,25,True),
    (8,1,5,True),
    (5,10,13,True),
    (10,2,1,False),
    (4,1,9,False),
    (3,2,1,False),
    (3,7,1,False),
    (25,25,25,False),
    (5,5,4,True),
    (15,15,12,False),
    (25,25,20,True),
    (4,4,5,False)
]

for x,y,z,true in TESTS:
    print('testing',x,y,z)
    computed = f([x,y,z])
    assert computed == true

Try it online!


Generate white noise The challenge is: generate an audio file made of white noise.
Requirements and instructions:

Your program must generate an audio file containing only white noise, meaning its intensity is the same for all (reasonable) frequencies and nonzero [see an example plot];
One must be able to play the audio file on the latest version of VLC [at the time of writing your answer];
The program doesn't need cryptographically-strong randomness, rand functions or reading from /dev/rand is okay;
The program must be able to generate at least 1 hour of audio, at least in theory (meaning system limitations like maximum filesize don't apply);
Your score is the number of bytes in your source code, plus all bonuses that apply;
Using any third-party, external library is okay;
The program must work without access to the Internet.

Bonuses are:

-15%: Allow to specify the format of the audio file (at least two choices; the number of possible choices doesn't change the score);
-10%: Allow to specify the duration of the audio file;
-5%: Allow to specify the bitrate of the audio file.

The settings can be stored in variables, files, or given as command line parameters, your choice. Percentages are calculated from the original number of bytes, before any bonus is applied.

Bash, 34

dd if=/dev/sda of=file.wav count=1

If you don't want hard drive 'randomness', (a lot slower)

dd if=/dev/random of=file.wav count=9

SPIN, 28

word x=0
repeat
 word[?x]=?x


Permutation group operation There is a well-known bijection between the permutations of \$n\$ elements and the numbers \$0\$ to \$n!-1\$ such that the lexicographic ordering of the permutations and the corresponding numbers is the same. For example, with \$n=3\$:
0 <-> (0, 1, 2)
1 <-> (0, 2, 1)
2 <-> (1, 0, 2)
3 <-> (1, 2, 0)
4 <-> (2, 0, 1)
5 <-> (2, 1, 0)

It is also well-known that the permutations of \$n\$ elements form a group (the symmetric group of order \$n!\$) - so, in particular, that one permutation of \$n\$ elements applied to a second permutation of \$n\$ elements yields a permutation of \$n\$ elements.
For example, \$(1, 0, 2)\$ applied to \$(a, b, c)\$ yields \$(b, a, c)\$, so \$(1, 0, 2)\$ applied to \$(2, 1, 0)\$ yields \$(1, 2, 0)\$.
Write a program which takes three integer arguments: \$n\$, \$p_1\$, and \$p_2\$; interprets \$p_1\$ and \$p_2\$ as permutations of \$n\$ elements via the bijection described above; applies the first to the second; and outputs the corresponding integer, reapplying the above bijection. For example:
$ ./perm.sh 3 2 5
3

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

J, 30

I like the elegance of this:

[:A.[:{/]A.~/~i.@[

or this:

13 :'A.{/(i.x)(A.)~/y'

but they work like this:

3 f 2 5
3
12 f 8 9
17

So this is the valid entry:

([:A.[:{/i.@{.A.~/}.)".}.>ARGV

Some explanations:

3 A. 0 1 2: gives the 3rd permutation of 0 1 2 (= 1 2 0)
0 1 2 (A.)~ 3: is the same but with arguments reversed
0 1 2 (A.)~/ 3 4 5 ... "applies" (A.)~ to 3 4 5 ..., so it gives the 3rd, 4th, 5th, ... permutation of 0 1 2.
A. 1 2 0: gives the order of the permutation of 1 2 0 (= 3)
i. n: gives the sequence 0 1 2 ... n-1
1 2 0 { 0 2 1 arranges 0 2 1 by 1 2 0 (= 2 1 0)


Hotel room numbering Given an input of a "hotel" in ASCII art with a single room marked, output the
room number according to certain rules.

Here's an example of an ASCII hotel:

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

Here are a few more things about the ASCII hotels:

Each "building" is represented by a rectangle of # characters, where each
# represents a "room".
The above hotel consists of three buildings. Each building is separated by
two columns of spaces, and the lowest "floor" will always be on the last
line.
Each building will always have anywhere from 1-9 "floors" (rows) and 1-9
"rooms" on each floor. There will also always be 1-9 buildings.
Rooms are numbered as follows: [building #][floor #][room on floor #]. For
example, let's mark a few rooms in the above drawing:

               ##
               ##
#####          ##
#####  ####$#  ##
##%##  ######  ##
#####  ######  #@

The room marked with the % is room 123 (building 1, floor 2, 3rd room on
floor). Similarly, the room marked with the $ is room 235, and the @ is
room 312.
Buildings, floors, and "nth room on floor"s are always 1-indexed.

The input will consist of an ASCII hotel with a single room replaced with an
asterisk (*). This is the room for which you must output the room number. The
input must be taken as a single string, but you may use commas as line
separators instead of newlines (in case your language of choice cannot take
multiline input or if it's shorter to take single-line input). You may
optionally require a trailing comma/newline. You may also pad lines with
trailing spaces to make the input a complete rectangle.

Since this is code-golf, the shortest code in bytes wins.

Test cases (contained within a single code block to conserve vertical space):

Input:
*

Output: 111

Input:
#  #  *  #  #

Output: 311

Input:
#####
#####
####*
#####
#####

Output: 135

Input:
         #####
         #####           ######
         #####           ######
#  #  #  #####  #  #  #  ######  *

Output: 911

Input:
#
#  #
#  #  ##
#  #  ##  ###
#  #  ##  ###  #####
#  #  ##  ###  ##*##  ########
#  #  ##  ###  #####  ########

Output: 523

Input:
           #
           *
           #
           #
           #
           #
           #
           #
#########  #  #

Output: 281

Input:
                        ########*
                        #########
                        #########
                        #########
                        #########
                        #########
                        #########
                        #########
#  #  #  #  #  #  #  #  #########

Output: 999

CJam, 34 31 bytes

qN/W%zSf-La%{_{s'*&}#_)@@=}3*;\

This requires the input to be padded to a rectangle with spaces.

Try it online! Alternatively, run all test cases.

Explanation

qN/      e# Read input and split into lines.
W%z      e# Rotate 90° counter-clockwise.
Sf-      e# Remove all spaces from the rows.
La%      e# Split into buildings. We've now got a 3D array of rooms, where the first
         e# dimension is the building, the second the room number and the third is the
         e# the floor number.
{        e# Run this block three times. At each stage it will find the index of the "*"
         e# along the current dimension and leave the element at that index on the stack
         e# for the next round...
  _      e#   Duplicate the current array.
  {      e#   Find the index of the first element where this block yields something
         e#   truthy...
    s    e#     Flatten into a single string.
    '*&  e#     Set intersection with "*".
  }#
  _)     e#   Duplicate the index and increment it, because the results should be 1-based.
  @@=    e#   Pull up the array and the other copy of the index and select the
         e#   corresponding element.
}3*
;\       e# We've now got the building, room and floor index on the stack, as well as the
         e# "*" character itself. We discard the character and swap the room and the floor
         e# floor number. When the three indices are printed back-to-back at the end of
         e# the program, that will yield the desired result.


Illustrate music beats You know—they look like this:

source

The goal is to draw a music beats illustration like the following:

=     =      =
=  =  =      =          =
== = ==   =  ==     = ====
== ====  == ===   = = =======
======== == ====  = ========= =
=================================

The rules are:

The width of the illustration is 33 symbols, but if you need—any trailing spaces exceeding this width are allowed.
Each column is made of equals signs (=).
Each column has a random height (the height of the next column shouldn’t depend in any way on the height of the previous column), varying from 1 to 6. It’s also fine if it’s at least possible to get some input with no strict math probability (i.e. some inputs could appear more rarely than others).
A column can’t float above the bottom and have gaps in it.
Since every column has the minimal height of 1, the last row can’t have any gaps either—it always consists of 33 equals signs.
Since it’s possible to have no columns with the height of 6 (it’s all random after all): in this case you don’t need to have a top line made of spaces. Applies to any edge cases of this nature: if suddenly your code provided no columns with the height greater than 1, you don’t need to have additional lines made of spaces above the bottom line.
You don’t take any input.


I know you, but you don't know me You're tasked with writing two programs. Program A must print out nothing on all inputs except when program B is input, in which case it should print 1. Program B must print out 1 on all inputs except when program A is input, in which case it should print nothing.

Scoring:

+1 For each character from both programs.
Lowest score wins.

Bash - 32 characters

Script A - 16 characters

cmp -s b&&echo 1

Script B - 16 characters

cmp -s a||echo 1

Usage

$> echo "foo" | ./a
$> cat b | ./a
1
$> echo "foo" ./b
foo ./b
$> cat a | ./b


Blackjack Bust Calculator Blackjack,  also known as twenty-one, is a comparing card game between yourself and a dealer, where each player in turn competes against the dealer, but players do not play against each other.

Play goes as follows, the dealer deals you a card. The dealer then deals them-self a card, face down. The dealer then deals you another card. Then finally, the dealer deals them-self a card, face-up.

Challenge

Your challenge is to write a program (or function) that when run (or called), outputs (or returns) the probability that the next card the dealer gives you will make you bust, which means the cumulative score of cards in your hand after the dealer gives you another card is over 21.

Input

The three visible cards in play. They are the two cards you have in your hand, and the one face card you can see in the dealers hand. This can be in whatever format you find suitable for your application.

There are 52 cards in a deck(4 of each of the cards below). The value of the cards are as follows:

Symbol(Case Insensitive)  Name     Value
2                         Two      2
3                         Three    3
4                         Four     4
5                         Five     5
6                         Six      6
7                         Seven    7
8                         Eight    8
9                         Nine     9
T                         Ten      10
J                         Jack     10
Q                         Queen    10
K                         King     10
A or 1                    Ace      1

In Blackjack, an ace can count as 1 or 11. In our challenge, only count it as a 1

Output

The probability, in a ratio or percentage format, that the next card we draw will make us bust.

You may output the percentage, the fraction, or just the numerator of the fraction.

Examples

In this example, the first two cards are in our hand, the third card is the dealers visible card

 Input          ->       Output

 A 2 Q          ->       0.00%  or  0/49 or 0
 A 2 3          ->       0.00%  or  0/49 or 0
 T T T          ->       91.84% or 45/49 or 91.84
 T J K          ->       91.84% or 45/49 or 45
 9 7 3          ->       61.22% or 30/49 ...
 9 7 Q          ->       59.18% or 29/49 ...

Rules

Standard loopholes are not allowed.

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

Jelly,  26  24 bytes

O%48«⁵µ13R«⁵ẋ4œ-+ṖS$>21S

A monadic link accepting a list of characters (using either the lower-case option OR the upper-case option with 1 for A) which returns the numerator (the number of 49ths) in [0,49].

Try it online! Or see the test-suite

How?

Note that by using lower-case the minimum of 10 and the ordinals modulo by 48 gives the card values. The same holds for upper-case T, J, Q, K and 1 for an ace, as shown on the right (but an upper-case A does not work):

     card:   a   2   3   4   5   6   7   8   9   t   j   q   k   |   1   T   J   Q   K
  ordinal:  97  50  51  52  53  54  55  56  57 116 106 113 107   |  49  84  74  81  75
   mod 48:   1   2   3   4   5   6   7   8   9  20  10  17  11   |   1  36  26  33  27
min(_,10):   1   2   3   4   5   6   7   8   9  10  10  10  10   |   1  10  10  10  10

O%48«⁵µ13R«⁵ẋ4œ-+ṖS$>21S - Link: list of characters   e.g. "q3a"
O                        - ordinals (of the input list)    [113, 51, 97]
 %48                     - modulo by 48                    [17,3,1]
     ⁵                   - ten
    «                    - minimum                         [10,3,1]
      µ                  - start a new monadic chain
       13R               - range of 13                     [1,2,3,4,5,6,7,8,9,10,11,12,13]
           ⁵             - ten                             10
          «              - minimum                         [1,2,3,4,5,6,7,8,9,10,10,10,10]
            ẋ4           - repeat four times               [1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10]
              œ-         - multi-set difference            [1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10  ,2  ,4,5,6,7,8,9   ,10,10,10]
                   $     - last two links as a monad:
                 Ṗ       -   pop                           [10,3]
                  S      -   sum                           13
                +        - add (vectorises)                [14,15,16,17,18,19,20,21,22,23,23,23,23,14,15,16,17,18,19,20,21,22,23,23,23,23,14,15,16,17,18,19,20,21,22,23,23,23,23,15,17,18,19,20,21,22,23,23,23]
                    >21  - greater than 21?                [0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1]
                       S - sum                             19


Seeking Secret Swapping Sequences This is a cops-and-robbers challenge, the robbers thread can be found here.

Your task is to write some code that outputs an OEIS sequence, and contains the name of the sequence in the code (A______) and outputs a second separate sequence when the name of the sequence in the code is changed to the name of the second sequence.

Here's an example in Haskell that works for A000217 and A000290.

f x|last"A000217"=='0'=x^2|1>0=sum[1..x]

Try it online!

You are then to reveal one of the two sequences, and the code keeping the second sequence a secret.  Robbers will attempt to figure out what the hidden sequence is.  If a robber manages to determine what your sequence is (or another sequence that fits the criteria) you answer is cracked.  If none do so in a week of your answer being posted you may mark your answer as Safe and reveal the intended solution for verification.  Safe answers cannot be cracked.

Input Output

Taken from here

Your code can be a function or complete program that takes n via a standard input method and outputs the nth term of the sequence as indexed by the provided index on the OEIS page.

You must support all values provided in the OEIS b files for that sequence, any number not in the b files need not be supported.

Scoring

Your score will be the number of bytes in your code, with less bytes being better.

Python 3, 59 bytes, A162626, cracked
lambda n:n*(n+1)*(n+2)/3if 0<=n<=3else n*(n**2+5)/3#A162626

This is was supposed to be impossible, wasn't it?


Low Entropy Literature This is one of my favourite poems I wanted to share. Especially because it looks good for compressing. Who cares about literature in the 21st century anyway.
Goal
Your goal is to write the shortest program possible that prints out the following poem: http://pastebin.com/aXV0C515
Rules

The HQ9Monkey++ language is prohibited


Undo the square roots Your job is to convert decimals back into the sum of the square roots of integers. The result has to have an accuracy of at least 6 significant decimal digits.

Input:

A number indicating the number of square roots and a decimal indicating the number to approximate.

Example input:

2 3.414213562373095

Output:
Integers separated by spaces that, when square rooted and added, are approximately the original decimal accurate to at least 6 significant decimal digits.

Zeros are not allowed in the solution.

If there are multiple solutions, you only have to print one.

Example output (in any order):

4 2

This works because Math.sqrt(4) + Math.sqrt(2) == 3.414213562373095.

This is code golf. Shortest code (with optional bonus) wins!

There is always going to be a solution but -10 if your program prints "No" when there is no solution with integers. In addition, -10 if your program prints all solutions (separated by newlines or semicolons or whatever) instead of just one.

Test cases:

3 7.923668178593959 --> 6 7 8
2 2.8284271247461903 --> 2 2
5 5.0 --> 1 1 1 1 1
5 13.0 --> 4 4 9 9 9 --> 81 1 1 1 1 --> 36 9 4 1 1 etc. [print any, but print all for the "all solutions bonus"]

And yes, your program has to finish in finite time using finite memory on any reasonable machine. It can't just work "in theory," you have to be able to actually test it.

Python 3, 90 - 10 = 80

def S(N,x,n=[],i=1):
 if x*x<1e-12>N==0:print(*n)
 while.1+x*x>i:S(N-1,x-i**.5,n+[i]);i+=1

(Mega thanks to @xnor for tips, especially the restructuring of the for loop into a while)

A simple recursive attempt. It starts off with the target number and continuously subtracts square roots until it hits 0 or lower. The function S can be called like S(2,3.414213562373095) (the second argument is assumed to be positive).

The program doesn't just print out all solutions, it prints out all permutations of solutions (a little extraneous, I know). Here's the output for the last case: Pastebin.

A slight tweak gives a 98 - 10 = 88 solution which doesn't print permutations, making it more efficient:

def S(N,x,n=[]):
 *_,i=[1]+n
 if x*x<1e-12>N==0:print(*n)
 while.1+x*x>i:S(N-1,x-i**.5,n+[i]);i+=1

And just for fun, this 99 - 10 = 89 one is about as efficient as it gets (unlike the others, it doesn't blow the stack on S(1,1000):

def S(N,x,n=[]):
 *_,i=[1]+n
 if x*x<1e-12>N:print(*n)
 while(.1+x*x>i)*N:S(N-1,x-i**.5,n+[i]);i+=1

Note that, although we have a mutable default argument, this never causes a problem if we rerun the function since n+[i] creates a new list.

Proof of correctness

In order to end up in an infinite loop, we must hit some point where x < 0 and 0.1 + x2 > 1. This is satisfied by x < -0.948....

But note that we start from positive x and x is always decreasing, so in order to hit x < -0.948... we must have had x' - i0.5 < -0.948... for some x' > -0.948... before x and positive integer i. For the while loop to run, we must also have had 0.1 + x'2 > i.

Rearranging we get x'2 + 1.897x' + 0.948 < i < 0.1 + x'2, the outer parts implying that x' < -0.447. But if -0.948 < x' < -0.447, then no positive integer i can fit the gap in the above inequality.

Hence we'll never end up in an infinite loop.


40 Numbers in 9 Bytes There are 40 ways a directed Hamiltonian path can be arranged on a 3×3 grid:

This graphic (thanks Sp3000!) shows only the 20 undirected paths. Traverse each colored line in both directions for the 40 directed paths.
Challenge
Using only printable ASCII, write a 3×3 grid of characters, such as:
ABC
DEF
GHI

When each of the 40 directed paths are read from this grid as 40 single-line, 9-character programs, the goal is to have each program output a unique integer from 1 to 40. Doing this for all 40 paths seems difficult and unlikely, so you only need to make it work for as many paths as you can.
The submission whose 40 path-programs output the most distinct numbers from 1 to 40 will be the winner. Tiebreaker goes to the earlier submission.
Path-programs that error or do not output an integer from 1 to 40 or output an integer that another path-program already covered are not counted. Specifically:

Programs that error while compiling, running, or exiting are not counted. Warnings are ok.
Programs that don't output an integer from 1 to 40 or output something slightly malformed such as -35 or 35 36 are not counted.
Programs that require user input to produce the output are not counted.
Programs that never end are not counted.
From now on, programs that aren't deterministic aren't counted.
Otherwise valid programs that output an integer from 1 to 40 that another valid program has already output are not counted. (The first program is counted.)
Only programs that output integer representations of numbers from 1 to 40 (inclusive) are counted towards your total. The numbers are expected to be in the usual 1, 2, ..., 39, 40 format, unless that is not the norm for your language. (A trailing newline in the output is fine.)
Which numbers your programs output and what order they are in does not matter. Only the number of distinct integers from valid programs matters.

All path-programs must be run in the same language. However, the "programs" may in fact be functions (with no required arguments) or REPL commands, as well as full programs, that print or return their target integer. You may mix and match between functions, REPL commands, and full programs.
Your 9 printable ASCII characters do not need to be distinct.
Example
If your 3×3 grid were
ABC
DEF
GHI

and your 40 programs and outputs looked like this
ABCFEDGHI -> 26
ABCFIHEDG -> 90
ABCFIHGDE -> 2
ABEDGHIFC -> syntax error
ADEBCFIHG -> prints 40 but then errors
ADGHEBCFI -> 6
ADGHIFCBE -> 6
ADGHIFEBC -> 6
CBADEFIHG -> runtime error
CBADGHEFI -> 3
CBADGHIFE -> 4
CFEBADGHI -> -32
CFIHEBADG -> 38.0
CFIHGDABE -> "36"
EDABCFIHG -> 33
EFCBADGHI -> no output
EHGDABCFI -> compilation error
EHIFCBADG -> 8
GDABCFEHI -> 22
GHEDABCFI -> 41
IHGDEFCBA -> 0
GDEHIFCBA -> '9'
EDGHIFCBA -> +10
CFIHGDEBA -> 11
GHIFCBEDA -> error
IFCBEHGDA -> error
EBCFIHGDA -> prints 23 but then loops infinitely
CBEFIHGDA -> randomly prints either 24 or 44
GHIFEDABC -> error
IFEHGDABC -> 30
EFIHGDABC -> 39
IHGDABEFC -> 7
GDABEHIFC -> 29
EBADGHIFC -> -1
GHIFCBADE -> 26
IHGDABCFE -> 1
IFCBADGHE -> error
GDABCFIHE -> no output
IHEFCBADG -> no output
IFCBADEHG -> "quack"

your score would be 14, because there are 14 distinct integers from 1 to 40 validly output, namely 26 2 6 3 4 33 8 22 11 30 39 7 29 1.

Deadfish, 18

This was actually the first language I tried before I considered infix operators. I'm posting it now for the sheer hilarity of the idea that Deadfish could be useful for something.

iii
ios
sii

For those who don't know Deadfish, i is increment, s is square and o is output, with the accumulator starting at 0 (there's also a 4th instruction d for decrement not used here). The fact that we don't have automatic printing and need to use o is a major drawback, but surprisingly Deadfish doesn't do too terribly here, all things considered. It turns out that the optimal placement of the output operator is in the middle.

iiisoisii 9
iiisiiois 11
iiisiisio 122
iioisiisi 2
iioiisiis 2
iisioiisi 5
iisiisiio 38
iisiisoii 36
iiiiosiis 4
iiiisiosi 17
iiiisiiso 324
isoiiisii 1
isiioiiis 3
isiisiiio 12
oiiiisiis 0
osiiiisii 0
oisiiiisi 0
oiisiiiis 0
siiiisoii 16
sioiiiisi 1
iisiosiii 5
sioiisiii 1
oisiisiii 0
isiisioii 10
siisiioii 6
isiioisii 3
oiisiisii 0
iiosiisii 2
siisoiiii 4
isoisiiii 1
osiisiiii 0
iisiiiosi 7
siiioiisi 3
oiiisiisi 0
siisiiiio 8
iisiiiiso 64
isiiiisio 26
siiiisiio 18
iiosiiiis 2
isiiiiois 5


Find the smallest file Goal:
Create a program to find the smallest file in the current folder.

File size may be measured in bytes or characters.

If multiple files have the same size, you can either choose one or display all of them.

You can assume there will be at least one file in the folder, and no files will have a size of 0.

Assume that all files in the folder can be loaded by the language you're using.

Assume that there are no folders in the current directory.

Input:
The program should not take any input from the user, unless:

If your language doesn't have a "current folder", it may ask the user for a folder name/path.
If your language cannot directly access files on your computer, it may allow the user to upload files. (JavaScript, for example)

Output:
The name of the smallest file should be displayed.

Leading/trailing symbols are allowed, as long as it's clear which file has been chosen.
(Printing a list of all the files is against the rules).

Notes:

Standard Loopholes are not allowed.
You cannot modify/create/delete files in the folder to change the result.
This is code-golf; shortest answer (in bytes) wins.

Bash + coreutils, 13 bytes
ls -Sar|sed q

Explanation:
ls -Sar|sed q
ls            # list files
   -S         # sorted, biggest first
     a        # show hidden files
      r       # reversed (smallest first)
       |sed q # q is quit at first line that matches given regex,
              # given regex is empty so guaranteed match.


Constant output program I was wondering how one might go and produce a program that takes input from some kind of random source and uses it to produce constant output. An obvious way is, for example, to take an integer x and output x/x for 1, but that isn't too clever, is it? Therefore, the task is to write a program that outputs the same thing, no matter which input is given to it.

Specifications

The program may assume that the input is either a number or a one line string (that is, valid characters are [a-z][A-z][0-9] and spaces). If you adopt one of those restrictions, specify which in your answer.
The program must use the entered input in some way. To put it more formally, the contents of the variable that takes the input must be used afterwards in some calculation that affects the final variable to be printed.

The winner will be the most upvoted solution.

Python

This question is boring.  I'd rather sleep.

from time import sleep
sleep(input())

Input a number.


Extract words with clue numbers in a Crossword puzzle Related: Read a crossword

Task

Given a completed Crossword puzzle, extract the words in it with their respective clue numbers, with "across" (horizontal) and "down" (vertical) words grouped and ordered like a real crossword puzzle.

The words are numbered in the row-major order of their first letters. If an "across" word and a "down" word share the first letter, the two words share one number. (As in regular Crossword, single-letter words don't count; they should not be numbered or included in the output.)

The input is given as a character matrix (or equivalent), with letters being uppercase (or lowercase if you want) and non-letter cells being blank. You can assume that single-letter islands won't appear in the input. If you want, you can assume the grid is rectangular (shorter rows are padded with spaces).

The output must be clearly grouped into "across" and "down" (you don't need to return or print these strings though), and the words must be ordered in the increasing order of the clue number (see test cases).

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

Test cases

Input:
MESS
YAWN
 SAID
 TYPO
Output:
Across: 1. MESS 5. YAWN 6. SAID 8. TYPO
Down: 1. MY 2. EAST 3. SWAY 4. SNIP 7. DO

Input:
   RECURS
  PARAPET
 TRIANGLE
COOLS RAW
HUTS MATE
ORE CODED
INCLUDES
RETIRES
SYSTEM
Output:
Across: 1. RECURS 7. PARAPET 8. TRIANGLE 9. COOLS 10. RAW 11. HUTS
        12. MATE 13. ORE 14. CODED 15. INCLUDES 17. RETIRES 18. SYSTEM
Down: 1. RAILS 2. ERAS 3. CAN 4. UPGRADES 5. RELATES 6. STEWED
      7. PROTECTS 8. TOURNEY 9. CHOIRS 12. MODEM 14. CURE 16. LIT

Input:
MICROWAVE
U       S
M OCEAN C
M  OWL  A
I SWELL P
E       E
SCHEDULES
Output:
Across: 1. MICROWAVE 3. OCEAN 7. OWL 8. SWELL 9. SCHEDULES
Down: 1. MUMMIES 2. ESCAPES 4. COW 5. EWE 6. ALL

Input:
TAB
A U
BUBBLE
  B O
  LOVED
  E E
Output:
Across: 1. TAB 3. BUBBLE 5. LOVED
Down: 1. TAB 2. BUBBLE 4. LOVE

Charcoal, 118 bytes

ＷＳ⊞υιＰ⪫υ¶≔⟦⟧θＦυ«Ｆι«Ｆ‹ κ«≔✂ιⅈＬι¹η≔⪫ＫＤ⁻Ｌυⅉ↓ωζ≡÷⌕2374ce6⍘↨ＥＫＶ‹ μ²φ³¦²⊞θ⟦ηζ⟧¹⊞θ⟦ηω⟧⁰⊞θ⟦ωζ⟧»→»⸿»⎚Ｅ²⪫ＥΦＥθ⟦⊕μ§⪪§λι ⁰⟧§λ¹⪫λ ¦

Try it online! Link is to verbose version of code. Takes input as a rectangular string of newline-terminated lines. Explanation:

ＷＳ⊞υιＰ⪫υ¶

Input the rectangle and print it to the canvas.

≔⟦⟧θ

Start off with no clues.

Ｆυ«Ｆι«

Loop over the rows and columns.

Ｆ‹ κ«

If the current character is not a space, then...

≔✂ιⅈＬι¹η

Get the substring of the current line starting at this character.

≔⪫ＫＤ⁻Ｌυⅉ↓ωζ

Get the substring of the current column starting at this character by reading it from the canvas.

≡÷⌕2374ce6⍘↨ＥＫＶ‹ μ²φ³

Check which orthogonally adjacent characters are spaces.

²⊞θ⟦ηζ⟧

If only the characters to the left and above are spaces, then a word starts both across and down.

¹⊞θ⟦ηω⟧

Otherwise if the character to the left is a space but the character to the right is not, then a word starts across but not down.

⁰⊞θ⟦ωζ⟧

Otherwise if the character above is a space but the character below is not, then a word starts down but not across.

»→»⸿»

Move on to consider the next character on each iteration.

⎚

Clear the canvas.

Ｅ²⪫ＥΦＥθ⟦⊕μ§⪪§λι ⁰⟧§λ¹⪫λ ¦

Map over the across and down clues, numbering them all, but keeping only those clues with words in the respective direction.

(Out of interest I tried using just string manipulation instead of canvas operations but that cost 29 bytes.)


Create a hash from an array of arrays of key|value pairs Starting from an array of sub-arrays, each sub-array is a 2 elements key|value pair. Example

input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]

Convert this into a hash that has distinct keys from above, with values summed up, so the above would be:

output = {"A" => 17, "B" => 0, "C" => 7}

Perl

Hopefully this thread won't get tagged code-golf

use strict;
use warnings;

my $a = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]];

my %h = ();

map { $h{shift @$_} += shift @$_ } @$a;

while (my ($k, $v) = each %h)
{
  print "$k = $v $/";
}

Output:

$ perl cg-arraysum.pl
A = 17
C = 7
B = 0


What my dog really hears My dog is called Rex. Every time I scold him, he seems not very impressed and the only times I see him react is when I pronounce his name. If I say

Rex, I told you not to do this! You're making me angry Rex!

all he hears is

Rex, * **** *** *** ** ** ****! ***'** ****** ** ***** Rex!

The challenge : given an input string, your program must output the same string where all alphabetic characters have been turned to stars, except the characters in the appearances of the word Rex, who must be left untouched. The non-alphabetic characters are also left untouched.

Details : The challenge is case-insensitive, thus rex must be left untouched also. The word Rex can be part of another word, so for example anorexic must be rendered as ***rex**.

Update : as the initial text of this challenge did not clarify how underscores or numbers or accentuated characters should be treated, I do not make any special requirement on those characters. Thus, a solution is valid as long as characters in a-zA-Z (and also the one mentioned in the examples, ,!".) are handled correctly.

Test cases :

Input : Rex lives in Rexland.

Output : Rex ***** ** Rex****.

Input : To call Rex, just say "Rex".

Output : ** **** Rex, **** *** "Rex".

Input : My cat is getting anorexic.

Output : ** *** ** ******* ***rex**.

**REXX 151 148 141 bytes **

(Kinda seemed appropriate)

i=arg(1)
m=i
o=translate(m,'',xrange('A','z'),'*')
p=0
do forever
   p=pos('REX',m,p+1)
   if p=0 then leave
   o=overlay(substr(i,p,3),o,p)
end
say o

Try it here

Notes for non-REXXers:

translate is a character replacement function (name comes from an assembler instruction on IBM MF).  It searches string1 for the characters in string3. Every time it finds one it replaces it with the same positioned one in string2. If string2 is too short it is padded with the pad character.

See here for translate function

overlay simply overlays the string1 on top of string2 at the specified position.

See here for overlay function


Maximum number of PEP8 violations in a single line Your task is to write a file which contains a line with many pep8 violations.

The rules:

We use pep8 version 1.5.7 and the default settings.
Calling pep8 with other command line options or using a custom rc file is not allowed.
Maximum line length 120 characters.  You can violate E501, sure, but the line which your score is calculated on has to be <= 120 characters.
Your module can have other lines before or after, but only one line contributes to your score.
Your file can contain SyntaxErrors or any kind of garbage, it needn't import or run.

Example of scoring:

The following module thing.py has a score of 2, because it contains a line (line 1) with 2 pep8 violations.

 spam='potato'

To check a score:

~$ mktmpenv
(tmp-ae3045bd2f629a8c)~/.virtualenvs/tmp-ae3045bd2f629a8c$ pip install pep8==1.5.7
(tmp-ae3045bd2f629a8c)~/.virtualenvs/tmp-ae3045bd2f629a8c$ echo -n "spam='potato'" > thing.py
(tmp-ae3045bd2f629a8c)~/.virtualenvs/tmp-ae3045bd2f629a8c$ pep8 thing.py
thing.py:1:5: E225 missing whitespace around operator
thing.py:1:14: W292 no newline at end of file

241

if you want the most error, just go crazy with semicolon

$ cat test.py
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

$ cat test.py | wc -m
120

$ pep8 test.py | wc -l
241

most of the error are:

test.py:1:119: E231 missing whitespace after ';'
test.py:1:119: E702 multiple statements on one line (semicolon)

with those error at the end:

test.py:1:120: E703 statement ends with a semicolon
test.py:1:121: W292 no newline at end of file


Print Leonardo DiCaprio without using any of the letters in his name The Oscars are coming up soon and we all know who's going to win Best Actor in a Leading Role this year right? The great Leonardo DiCaprio of course! Despite his superb performances in all of his films during his career, he has yet to win an Academy Award. So as tribute and as a way to wish him luck during the Awards Ceremony this year, your task is to print "Leonardo DiCaprio" (without quotes and case-sensitive) without using any letters in his name in your code. This is code-golf so the shortest code wins. Score is based on your code in bytes. Any language is acceptable.

-100 Points if you can print his name on an ascii plate like so (Best Actor not required):

 _____________________________
|                             |
|      Leonardo DiCaprio      |
|         Best Actor          |
|_____________________________|

Edit For clarification, the rule for not "using any letters in his name in your code" is  case-insensitive.

Also another edit you may use spaces.


Fastest algorithm to take the product of all subsets Given n numbers in an array (you can't assume they are integers), I would like to compute the product of all subsets of size n-1.

You can do this by  multiplying all the numbers together and then dividing by each one in turn, as long as none of the numbers is zero.  However, how quickly can you do this with no division?

  If you don't allow division, what is the minimum number of
  arithmetic operations (e.g. multiplication and addition) needed to compute the product of all subsets of size
  n-1?

Clearly you can do it in (n-1)*n multiplications.

To clarify, the output is n different products and the only operations apart from reading and writing to memory allowed are multiplication, addition and subtraction.

Example

If the input has three numbers 2,3,5, then the output is three numbers 15 = 3*5, 10 = 2*5 and 6 = 2*3.

Winning criterion

Answers should give an exact formula for the number of arithmetic operations their code will use in terms of n.  To make life simple, I will just plug n = 1000 into your formula to judge its score. The lower the better.

If it's too hard to produce an exact formula for your code, you can just run it for n = 1000 and count the arithmetic operations in  the code.  An exact formula would be best however.

You should add your score for n=1000 to your answer for easy comparison.

Python, 3(n-2) operations, score = 2994

l = list(map(float, input().split()))
n = len(l)

left = [0] * len(l)
right = [0] * len(l)
left[0] = l[0]
right[-1] = l[-1]
for i in range(1,len(l)-1):
  left[i] = l[i] * left[i - 1]
  right[-i-1] = l[-i-1] * right[-i]

result = [0] * len(l)
result[-1] = left[-2]
result[0] = right[1]
for i in range(1, len(l) - 1):
  result[i] = left[i - 1] * right[i+1]

print(result)

The arrays left and right contain the cumulated products of the array from the left and from the right, respectively.

EDIT: Proof that 3(n-2) is the optimal number of operations needed for n >= 2, if we only use multiplication.

We will do that by induction; by the above algorithm, we just have to prove that for n >= 2, 3(n-2) is a lower bound on the number of multiplications needed.

For n = 2, we need at least 0 = 3(2-2) multiplications, so the result is trivial.

Let n > 2, and suppose for n - 1 elements, we need at least 3(n-3) multiplications. Consider a solution for n elements with k multiplications.
Now, we remove the last of these elements as if it was 1, and simplify all multiplications directly by it. We also remove the multiplication leading to the product of all the other elements, since that one is not needed as it can never be used as an intermediate value to get the product of n-2 of the other elements, since division is not allowed. This leaves us with l multiplications, and a solution for n - 1 elements.

By induction hypothesis, we have l >= 3(n-3).

Now, let's have a look at how many multiplications were removed. One of them was the one leading to the product of all elements except the last. Moreover, the last element was used directly in at least two multiplications: if it was used in only one, then it was used when multiplying by an intermediate result consisting in some product of the other elements; let's say, without loss of generality, this this intermediate result included the first element in the product. Then, there is no way to get the product of all the elements but the first, since every product that contains the last element is either the last element, or contains the first element.

We thus have k >= l+3 >= 3(n-2), proving the claimed theorem.


Make them sum to 10,000 We've recently reached the threshold of 10,000 questions on PPCG. Hooray! Let's celebrate this with a simple challenge.
Input
Two integers \$A\$ and \$B\$, both in \$[1..9999]\$, such that \$A+B<10000\$.
Task
Your task is to add one single digit to one of these integers or one single digit to both of them such that \$A+B=10000\$. If adding a digit to both \$A\$ and \$B\$, it need not necessarily be the same digit.
The new digit can be added at the beginning, at the end or anywhere in the middle of the original integer. However, you can't add a leading zero.
Example:
For \$A=923\$, the following transformations are valid:
$$\color{red}1923\\92\color{red}73\\923\color{red}8$$
But these ones are invalid:
$$\color{red}{0}923\\\color{red}{10}923\\9\color{red}{4}2\color{red}{7}3$$
Given \$A=923\$ and \$B=72\$, there are two possible solutions:
$$923\color{red}8 + 7\color{red}62 = 10000\\92\color{red}73 + 72\color{red}7 = 10000$$
Output
You must print or output a list of all possible solutions.
For the above example, the expected output would be [[9238,762],[9273,727]].
Rules

I/O can be processed in any reasonable, unambiguous format. You may use strings, lists of digits, etc. instead of integers.
The input is guaranteed to have at least one solution.
You are allowed not to deduplicate the output. However, it would be appreciated if the test code is deduplicating it with some post-processing, for instance in the footer section of TIO.
This is a code-golf challenge.

Test cases
Input    --> Output

934, 654 --> [[9346,654]]

737, 628 --> [[7372,2628]]

9122, 88 --> [[9122,878]]

923, 72  --> [[9238,762],[9273,727]]

998, 3   --> [[9968,32],[9987,13]]

900, 10  --> [[9900,100],[9090,910]]    NB: solutions such as [9000,1000] are NOT valid
                                            (more than one digit added to 10)

363, 632 --> [[3673,6327],[3638,6362]]

288, 711 --> [[2881,7119],[2882,7118],[2883,7117],[2884,7116],[2885,7115],[2886,7114],
              [2887,7113],[2888,7112],[2889,7111]]

365, 635 --> [[365,9635],[1365,8635],[2365,7635],[3365,6635],[4365,5635],[5365,4635],
              [6365,3635],[7365,2635],[8365,1635],[9365,635],[3065,6935],[3165,6835],
              [3265,6735],[3465,6535],[3565,6435],[3665,6335],[3765,6235],[3865,6135],
              [3965,6035],[3605,6395],[3615,6385],[3625,6375],[3635,6365],[3645,6355],
              [3655,6345],[3675,6325],[3685,6315],[3695,6305],[3650,6350]]

Haskell, 99 97 82 81 bytes

-16 bytes thanks to Delfad0r (taking inputs as a list, using abusing that we don't need to deduplicate -> n can always be in [0,4] & using a clever combination of input-format and ap)!

filter((==1e4).sum).mapM([read.(take n<>(c:).drop n)|c<-['0'..'9'],n<-[0..4]]<*>)

Try it online!


Can the cursor reach the bottom? In a matrix of characters, a cursor is a movable position between two adjacent characters, before the first character or after the last character in a line, like that "I"-shaped indicator which moves while you type.
In this challenge, a cursor position is considered valid if at least one of its two sides touches a space. The cursor travels through valid positions in a matrix, by moving up, down, left or right by one position each time. It could also move left or right though the line separator, to the end of the previous line, or the beginning of the next line respectively.
Given a character matrix as input, and a cursor initially at the top left corner, your task is to determine whether it can reach the bottom line.
This is a code-golf and decision-problem problem; the rules of this question is the same as what these two tags specified.
Rules

You can assume that the input consists only of .,  , and newlines. (Only these three characters and no more characters; otherwise its behavior is undefined.)
You may require there must or must not be a trailing newline in the input, if you want to.
Your code should output either a truthy value (if the condition is true), or a falsy value (if the condition is false).

Examples
Example input(where ░ is the space character):
░.....░
░......
.░.░.░.
.░░░░░░
......░

The cursor can reach the bottom in this case. This process of moving the cursor will work: down, right(touches spaces on the left), down(touches spaces on the right), down, right(touches spaces on both sides) 6 times, and down(touching spaces on the left).
This will also work(░ still represent spaces):
░░
.░
.░

The cursor starts at the up-left corner. After moving right two times, it can move down twice, which touches the bottom of the lines.
This example will not work(░ represent spaces again):
░...
...░

The cursor cannot move down, as there is no sufficient whitespace to be touched. There are only newline characters on the right of the input, and there are no newline characters on the left(otherwise a line would have spanned two lines.)
The cursor can also move up and left, in order to solve a maze-like input as in this one:
░....
░░░░.
...░.
.░░░.
░....
░░░░░

In this case, the cursor has to move left in order to get through spaces and get to the bottom line.
Here is another important test case: the cursor can move left or right to another line.
░░░░
...░
░...

In this case, the cursor can reach the last line, as the cursor can move left or right in order to get to the next line. Moving the cursor down is blocked on the right position of row 2, column 4; however, the cursor can still get to the last line if it moves right (touching spaces).
This is a fairly interesting test input:
░░..░
░...░
....░

In this case, the cursor can reach the last line, by moving down and left to the end of the first line, then down twice to reach the end of the bottom line.

APL (Dyalog Unicode), 60 bytesSBCS

Full program. Prompts for character matrix from stdin. Prints 1 or 0 to stdout. Requires zero-indexing (⎕IO←0) which is default on many systems.

P←{' '0∊⍨s←(×⍨≢⍺)⊃,⍵:1∊⍵⋄s}
1∊⊢⌿{P⌺3 3⊢(⍴⍵)⍴1@0P⌺3,⍵}⍣≡3/3⌿⎕

Try it online! (space characters replaced by ░ for clarity)

The method here is basically to seed fill from the top left corner, but alternating between 1D and 2D seed fill to account for line wrapping and vertical/diagonal motion. Diagonal motion is simple horizontal motion followed by vertical motion, since the cursor sits in between adjacent characters.

The first line defines a helper function P(rocess) which will be called on each neighbourhood.

P←{…} "dfn"; ⍵ is the neighborhood, ⍺ is the number of padded elements for each dimension:

 ,⍵ ravel (flatten) the neighbourhood into a list

 (…)⊃ pick the following element from that:

  ⍺ the paddings per dimension (so a 1 or 2 element list, depending on ⍵ being 1D or 2D)

  ≢ the tally of that (1 or 2)

  ×⍨ the square of that (lit. multiplication selfie; 1 or 4)

 s← assign to s(elf; i.e. the centre of the neighbourhood)

' '0∊⍨ is that a member of [" ",0]?

 : if so:

  1∊⍵ return whether the neighbourhood has a one

 ⋄ else:

  s return s(elf unmodified, i.e. leave as-is for now)

The second line is the main part of the program:

⎕ prompt for evaluated input via the console (stdin)

3⌿ triplicate each row (ensures we have at least 3 — makes no difference to connectivity)

3/ triplicate each column (ensures we have at least 3 — makes no difference to connectivity)

{…}⍣≡ apply this function repeatedly until two successive results are identical (i.e. until stable):

 ,⍵ ravel (flatten) the matrix into a list

 P⌺3 apply P to each neighbourhood of 3 elements

 1@0 replace the current value at position 0 with a 1 (this seeds the top left corner)

 (…)⍴ reshape that into the following shape:

  ⍴⍵ the original shape of the matrix

⊢⌿ get the bottom row (lit. vertical right-reduction)

1∊ is there any 1 there?


Find the Second Zero Challenge

Given an integer in 32-bit two's complement format, return the index of the second least-significant zero digit in the binary representation, where an index of 0 represents the least significant bit, and an index of 31 represents the most significant bit.

If there is no second zero, you may return 0, any negative number, any falsy value, or report an error in a way that makes sense in your language.

You may use 1-indexing if you prefer, but the test cases below will use 0-indexing.

You may use unsigned integers if you prefer; if you do, then you must handle integers in the range [0, 2^32). If you use signed integers, you must handle integers in the range [-2^31, 2^31). The test cases here will use signed integers, but note that -x (signed) is 2^32 - x (unsigned).

Test Cases

0  (0b00)        -> 1
1  (0b001)       -> 2
10 (0b1010)      -> 2
11 (0b01011)     -> 4
12 (0b1100)      -> 1
23 (0b010111)    -> 5
-1 (0b11..11)    -> None
-2 (0b11..10)    -> None
-4 (0b11..00)    -> 1
-5 (0b11..1011)  -> None
-9 (0b11..10111) -> None
2^31-2 (0b0111..1110) -> 31

Scoring

This is code-golf, so the shortest answer in each language wins!

Python 2, 45 bytes

lambda n:[i for i in range(32)if n|1<<i>n][1]

Try it online!

Uses 0-indexing, unsigned numbers, and throws an error on no second zero.

Simply creates a list of indices of non-set bits, from lowest to highest, and returns the second entry.


Smallest integers after N divisible by 2, 3, and 4 Give credit to whom credit is due.

Objective Given an integer N > 0, out the smallest integers A, B, and C so that:

All of A, B, and C are strictly greater than N;
2 divides A;
3 divides B;
and 4 divides C.

This is a code-golf, so the shortest answer in bytes wins. You may use a language made/updated after this challenge, but it is strictly non-competing.

Test cases

N => A, B, C
1 => 2, 3, 4
4 => 6, 6, 8
43 => 44, 45, 44
123 => 124, 126, 124
420 => 422, 423, 424
31415 => 31416, 31416, 31416
1081177 => 1081178, 1081179, 1081180

Python 2, 32 bytes

lambda n:[n+2&-2,n/3*3+3,n+4&-4]

Bit arithmetic for 2 and 4, modular arithmetic for 3.
I found four 7-byte expressions for the next multiple of k above n but none shorter:
n-n%k+k
~n%k-~n
n/k*k+k
~n/k*-k

Any gives 34 bytes when copies for k=2,3,4, and 33 bytes if combined:
[n/2*2+2,n/3*3+3,n/4*4+4]
[n/k*k+k for k in 2,3,4]

But, 2 and 4 are powers of 2 that allow bit tricks to zero out the last 1 or 2 bytes.
n+2&-2
n+4&-4

This gives 6 bytes (instead of 7) for getting the next multiple, for 32 bytes overall, beating the for k in 2,3,4.
Unfortunately, the promising-looking n|1+1 and n|3+1 have the addition done first, so incrementing the output takes parentheses.


PowerShell: test connection in as few characters as possible I need this down to as few characters as possible.  I would use Test-NetConnection but I need PSv2 compatability.  Any help would be appreciated.

$socket = new-object Net.Sockets.TcpClient
$socket.Connect("192.168.5.5",445)
$socket.Connected

As a note I have tried this but it doesn't work

(new-object Net.Sockets.TcpClient).Connect("192.168.5.5",445).Connected

PowerShell v2+, 63 bytes

You can use a different constructor to create the object and connect in one go.

(new-object Net.Sockets.TcpClient('192.168.5.5',445)).Connected

I've verified this works in v2 on my Windows 8.1 machine. That constructor is supported by .NET 2.0, so this should be v2 compatible.


Kolmogorov Complexity Meta Golfer Mike Bufardeci (Pyth) - 175 bytes

Leo (Retina) - 175 bytes

devRicher (Lua) - 182 bytes

Peter Taylor (CJam) - Waiting for clarification

Lyth (C++11) - Waiting for clarification

Edit: Several changes made, should not affect any already submitted answers.
Edit #2: Very few people are taking advantage of the 1024 byte limit. The point of this challenge is to output code golf answers, not things like the example at the bottom of this post.
Edit #3: Here is the paragraph to test against: WASHINGTON - These are chaotic and anxious days inside the National Security Council, the traditional center of management for a president's dealings with an uncertain world. I will test the submissions myself later.
At PPCG, we pride ourselves in writing programs to solve problems. However, it's very time consuming to write the programs to solve problems. Instead we should write programs to write programs to solve problems!
In this case, the problem is Kolmogorov Complexity. You must write a program that golfs a program, that outputs piece of text.
Main program -> Generated program -> Text
You do not necessarily need to golf the main program. Your score is the length of the generated program.

You will not know the final text when writing the main program. Therefore, you will not be able to write the generated program by hand. The main program should take a string input and create the generated program, which correctly outputs the text.

On February 12th, the first paragraph of the headline of the New York Times will be used for scoring. I will post the article at 10 AM ESThttps://www.nytimes.com/

You may use any language for the main program and generated program. They do not have to be the same.

The final text will never contain these characters: ", ', \n, \r.

The main program is limited to 1024 bytes (not characters). The generated program has no byte limit, as long as it outputs the text.

Compression algorithms built in to your language are not allowed (both ways), unless you code it from scratch. This includes any type of text compression libraries, and base conversion. This does not include Regexes.

Standard loopholes apply.

Example: (JavaScript)
f=(g)=>{console.log("console.log('" + g + "')")}

Retina, worst case (3+original length) bytes

EDIT: added support for newlines, in order to try this code in actual kolmogorov complexity challenges. Behaviour on strings without newlines remains unchanged.

Retina is great at substituting substrings, so that's what we're going to do!

This program looks for repeated sequences of characters and replaces them every time with a single character not appearing in the full string. The generated program then starts with the "compressed" string and applies all substitutions in reverse.

This code adds 3 bytes of boilerplate (a newline at the beginning, and a \` towards the end to suppress a trailing newline), so in the worst case (when there are no repeated sequences worth substituting) we have a length of 3 bytes more than the starting string. On average, this will shave a few bytes from the original length, not much but still a compression.

Here's the code with some comments:

First, we use a trick with transliteration ranges to change newlines into ¶, which is how newlines are printed in a Retina program

T`µ¶·`µ-·

then we start the main loop, duplicating the first line

{`^.+
$&¶$&

we only substitute when the sequence is repeated enough times (depending on its length)

^.*?((......+).*?\2|(.....?).*?\3.*?\3|(...).*?\4.*?\4.*?\4|(..).*?\5.*?\5.*?\5.*?\5.*?\5).*
"$2$3$4$5
^"(.+)|^.*
$+

to find a character not in the string, we append a list of candidates to the string, using " as separator, and then remove duplicates

^(.*)¶(.*)
$2" 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#%&\'()*+,-./:;?@\^_`{|}~¶$2¶$1
D`(?<=^.*).
^.*"(.)?.*¶(.+)
$2¶$1

here the actual substitution in the text happens

+`^(.*)(.+)(.*¶(.)¶\2(¶|$))
$1$4$3

in case we couldn't find a repeated sequence or an unused character, we restore the string to the original state (which makes us break from the loop)

}`(.*)¶(¶.*|.*¶)(¶|$)
$1$3

at the end, we add the 3 bytes of boilerplate

^
¶
\-1=`.*¶
\`$&

Try it online!

In the linked example, the 292 bytes paragraph gets compressed to a 286 bytes Retina code.

NOTE: the substitutions made are not optimal, we just make every time the first suitable substitution we find; I don't know if an algorithm finding the optimal substitutions could run in a reasonable amount of time.


How great is your land? In this challenge, you'll calculate how great your land is.

Write a program or function that calculates the size of your land, given a wall you have built. You're given a non-empty input string containing a set of 4 distinct characters of your choice that represent the four directions "up", "down", "left" and "right" (I'll use ^ v < > in this challenge). It's not possible to take 180 degree turns (<> or ^v), but you may cross your wall.

The way you "capture" land is by encircling it with your wall. The wall itself is also considered part of your land. A few examples will make it more clear. I'll use o for land that has been encircled by the wall, x for the wall itself, and S for the starting point of the wall, just to illustrate how the wall is built. The output should be the total size of your land (the number of o, x and S in the test cases below).

Input: >>>>
Land: Sxxxx
Output: 5

Input: <<<^^^>>>vv
Land:
xxxx
xoox
xoox
xxxS
Output: 16

Input: <<<^^^>>>v
Land:
xxxx
x  x
x
xxxS
Output: 11

Input: <
Land: xS
Output: 2

Input: >>>>>>vvvvvvvvv<<<<<^^^^>>>>>>>>vvvvvvvvvv<<<<<<<<<<<<<<<^^^^^^^^^>>>vvvvvv<<<<<
Land:
        Sxxxxxx
              x
              x
              x
              x
         xxxxxxxxx
  xxxx   xoooox  x
  xoox   xoooox  x
  xoox   xoooox  x
  xoox   xxxxxx  x
  xoox           x
  xoox           x
xxxxxx           x
  x              x
  x              x
  xxxxxxxxxxxxxxxx
Output: 101

Input: >>vvvv>>^^<<<<^
Land:
Sxx
xox
xxxxx
  xox
  xxx
Output: 17

Input: <<^^^>>>vv
Land:
xxxx
x  x
x  x
xxS
Output: 11   <- Note, diagonal edges do not close the "loop"

Clarifications:

You do not need to draw the wall, the output should only be an integer
The input format is optional. You may take a string with <>^v, a list of digits, (1, -1, i, -i), a list of characters ABCD etc.

This is code-golf so the shortest code in each language wins. Remember, explanations are important, even in "regular" languages!

Python 2, 385 345 332 bytes

A,I,R=max,min,range
a=b=0
p=[[a,b]]
for i in input():a+=i%2*(2-i);b+=(1-i%2)*(1-i);p+=[a,b],
k,l=zip(*p)
x=A(k)-I(k)+3
y=A(l)-I(l)+3
o=[[1]*y for _ in' '*x]
def g(m,n):
 if 0<o[m][n]and[m+I(k)-1,n+I(l)-1]not in p:o[m][n]=0;[g(i,j)for i in R(A(0,m-1),I(x,m+2))for j in R(A(0,n-1),I(y,n+2))if(i,j)!=(m,n)]
g(0,0)
print sum(map(sum,o))

Try it online! or Try all test cases

Input is numerical, 0~3, the 0-index of the symbols here: >v<^

#starting position
a,b=0
#new list to hold the wall coordinates
p=[[a,b]]

#iterate over the input calculating
#the next coordinate and storing on p
for i in input():
 a=a+i%2*(2-i)
 b=b+(1-i%2)*(1-i)
 p+=[[a,b]]
#i%2*(2-i) and (1-i%2)*(1-i) generate the increment
#of each symbol from last position
# >/0 : (0,1)
# v/1 : (1,0)
# </2 : (0,-1)
# ^/3 : (-1,0)

#transpose the coordinate list
k,l=zip(*p)
#calculate the difference between the max and min values
#to generate the total land size
#adding a border to avoid dead-ends
x=max(k)-min(k)+3
y=max(l)-min(l)+3

#create a matrix of 1's with the total land size
o=[([1]*y) for _ in ' '*x]

#recursive function that sets a cell to 0
#and call itself again on all surrounding cells
def g(m,n):
 #correct the indexes (like negative ones)
 a,b=m+min(k)-1,n+min(l)-1
 #if this cell contains 1 and don't belong to the wall
 if o[m][n]>0 and (a,b) not in p:
  #sets to 0
  o[m][n]=0
  #call again on surrounding cells
  for i in range(max(0,m-1),min(x,m+2)):
   for j in range(max(0,n-1), min(y,n+2)):
    if (i,j)!=(m,n):g(i,j)

#call the recursive function o origin
g(0,0)
#print the sum of the cells
print sum(map(sum,o))

This is the resulting matrix:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0]
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0]
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0]
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0]
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


You are the Weakest Link, Goodbye This king-of-the-hill challenge is based off of the game show, Weakest Link.  For those unfamiliar with the show, the crux of this challenge deals with who you vote off:

If the other players are smarter than you, then you have less of a chance of getting the pot.
If the other players are dumber than you, then you have less of a pot to get.

At the start of each round, the Pot starts out with $0.  A group of 9 players is formed, and each player is given a unique Smartness from 1 to 9.
At the start of each turn, Pot += Smartness for each player still in the round.  Then, players vote on the player they wish to remove.  The player with the most votes is removed.  In case of a tie, the smarter player is kept.
When there are only 2 players are left in the round, they face off in a battle of wits.  The chance of the player winning is Smartness/(Smartness+OpponentSmartness).  The winning player then receives the entire pot.
The player who has received the most money at the end of the game wins.
Input / Output
Each turn, you will receive the current list of opponents.  You will have access to your smartness and all players' entire voting history for the round via functions in the Player class.
As output, you must return a single integer, representing the player you wish to vote for (representing their smartness).  Voting for yourself is allowed (but not recommended).
Rounds of 9 will repeat until all players have played at least 100010000 rounds, and all players have played in the same number of rounds.
You can find the controller here: https://github.com/nathanmerrill/WeakestLink
To create a player, you need to extend the Player class, and add your player to the PlayerFactory class.  Your class must follow the following rules:

Communication or interference with any other player (include your other players of the same type) is strictly prohibited.

Reflection and static variables (except for constants) are not allowed.

If you want to use randomness, I have provided a getRandom() function in the Player class.  Use it, so simulations can be deterministic.

I have provided many functions in the Player class for easy access to data.  You can find them online on Github.  Your player will be instantiated each new round.  "Dumb/suicidal" players are allowed (but not players with the same strategy).
Scores
377195  WeakestLink.Players.PrudentSniper
362413  WeakestLink.Players.Sniper
353082  WeakestLink.Players.VengefulSniper
347574  WeakestLink.Players.AntiExtremist
298006  WeakestLink.Players.BobPlayer
273867  WeakestLink.Players.MedianPlayer
247881  WeakestLink.Players.TheCult
240425  WeakestLink.Players.Leech
235480  WeakestLink.Players.SniperAide
223128  WeakestLink.Players.Guard
220760  WeakestLink.Players.Anarchist
216839  WeakestLink.Players.RevengePlayer
215099  WeakestLink.Players.IndependentVoter
213883  WeakestLink.Players.SniperKiller
210653  WeakestLink.Players.MaxPlayer
210262  WeakestLink.Players.Bandwagon
209956  WeakestLink.Players.MeanPlayer
208799  WeakestLink.Players.Coward
207686  WeakestLink.Players.Spy
204335  WeakestLink.Players.Hero
203957  WeakestLink.Players.MiddleMan
198535  WeakestLink.Players.MinPlayer
197589  WeakestLink.Players.FixatedPlayer
197478  WeakestLink.Players.HighOrLowNotSelf
181484  WeakestLink.Players.RandomPlayer
165160  WeakestLink.Players.BridgeBurner

Sniper

The general idea is to keep around one of the stupid players (i.e. ones we are more likely to beat in the face-off) to snipe for the points. After that we try to remove the other low-value players to raise the pot. But when we get to the intelligent players we opt to remove for the most dangerous ones in case our stupid player gets removed. That way if we don't have someone to snipe we should get someone we at least stand a chance against. Also, since we always vote with either a min or max player, I expect we are fairly effective in getting our way.

package WeakestLink.Players;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
public class Sniper extends Player {
    @Override
    public int vote(Set<Integer> currentOpponents) {
        int smrt = getSmartness();

        //count number of players smarter/stupider than me
        Iterator<Integer> opps = currentOpponents.iterator();
        int cnt_smrt=0, cnt_stpd=0, opp_smrt, min_stpd=10, max_smrt=0;

        while(opps.hasNext()){
            opp_smrt = opps.next().intValue();
            if(opp_smrt > smrt){
                cnt_smrt++;
                if(opp_smrt > max_smrt) max_smrt = opp_smrt;
            }
            else if(opp_smrt < smrt){
                cnt_stpd++;
                if(opp_smrt < min_stpd) min_stpd = opp_smrt;
            }
        }

        //remove low-value, then dangerous players
        if(cnt_stpd>1)
            return min_stpd;
        else
            return max_smrt;
    }
}


Jam don't add like that Background

Jelly's arithmetic atoms vectorize automatically. In fact, x + y is well-defined whenever x and y are numbers or ragged arrays of numbers. Jelly's source code implements this behavior using a generic vectorizer, but for this challenge, we'll only consider addition of integers and nested integer arrays.

Definitions

Define the depth of x as 0 if x is an integer, as 1 if it is a (possibly empty) flat array of integers, and as n + 1 if it contains at least one element of depth n and no elements of depth k > n.

This way, 1 has depth 0, [] and [1] and [1, 1] have depth 1, [[], []] and [[1], [1]] and [[1]] and [1, []] have depth 2, [1, [1, [1]]] has depth 3, etc.

The operation x + y is defined as follows.

If x and y have depth 0, return their sum.
If x and y have equal but positive depths, recursively apply + to all items of x and the corresponding items of y.

If x and y have different lengths, append the tail of the longer array to the array of sums.

Return the result.
If x's depth is strictly smaller than y's depth, recursively apply + to x and all items of y, and return the result.

Do the opposite if y's depth is strictly smaller than x's.

For example, consider the operation [1, [2, 3], [4]] + [[[10, 20], [30], 40, 50], 60].

The depth of the left argument is 2, while the depth of the right argument is 3, so we compute [1, [2, 3], [4]] + [[10, 20], [30], 40, 50] and [1, [2, 3], [4]] + 60.

[1, [2, 3], [4]] and [[10, 20], [30], 40, 50] both have depth 2, so we compute 1 + [10, 20], [2, 3] + [30] and [4] + 40.

1 + [10, 20] = [1 + 10, 1 + 20] = [11, 21]
[2, 3] + [30] = [2 + 30, 3] = [32, 3]

Note that 3 remains untouched, since it doesn't have a matching element.
[4] + 40 = [4 + 40] = [44]

50 doesn't have a matching element, so the result is [[[11, 21], [32, 3], [44], 50]].
[1, [2, 3], [4]] + 60 = [1 + 60, [2, 3] + 60, [4] + 60] = [61, [2 + 60, 3 + 60], [4 + 60]], resulting in [61, [62, 63], [64]].

The final result is [[[11, 21], [32, 3], [44], 50], [61, [62, 63], [64]]].

Task

Write a program or a function that takes two integers, two nested arrays of integers or a combination thereof as input and returns their sum, as defined above.

If your language has multiple array-like types (lists, tuples, vectors, etc.) you may choose any of them for your answer. The return type must match the argument type.

To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language.

All built-ins of all other languages are allowed. If your language of choice permits this, you may overload and/or redefine the built-in addition.

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

Test cases

0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]

To generate more test cases, you can use this Jelly program.

APL, 44 bytes

{1=≡⍺⍵:⍺+⍵⋄=/∆←|≡¨⍺⍵:⊃∇¨/↓↑⍺⍵⋄</∆:⍺∘∇¨⍵⋄⍵∇⍺}

APL's + distributes over arrays as well, but in a different enough manner that this can't really be used. However, there is a built-in depth function (≡).

Explanation:

1=≡⍺⍵:⍺+⍵: if the depths of ⍺ ⍵ are both zero (and therefore the depth of ⍺ ⍵ is 1), add them.
∆←|≡¨⍺⍵: take the absolute of the depth of both ⍺ and ⍵ and store them in ∆. (≡ gives a negative value if not all elements have the same depth.)
=/∆: if they have the same depth:

↓↑⍺⍵: pad the shortest array with zeroes to match the longer array
⊃∇¨/: distribute the function over both arrays

</∆: if the depth of ⍺ is less than that of ⍵:

⍺∘∇¨⍵: bind ⍺ and then map over ⍵

⍵∇⍺: if nothing else (so ⍵ is deeper than ⍺), swap the arguments and try again.