Kuznetsov's Sequence Kuznetsov's Sequence
(I made the name up, don't bother with Wikipedia or Google)

Given any number n > 0, let r represent the reverse of the number n. Iterate until the final result is zero, passing the result of each iteration back into the function using recursion or a methodology of your choice by performing the below operation:

If r > n for that iteration the result is r % n.
If n > r for that iteration the result is n % r.
If n % r = 0 or r % n = 0, you terminate iteration.

Take the intermediate result of each execution and store them in an array for the final answer. The initial number n is not part of the sequence, nor is 0; the examples should make everything a little more obvious.
Lets walk through an example where n=32452345.
54325423 % 32452345 = 21873078 # r > n, uses r % n
87037812 % 21873078 = 21418578 # r > n, uses r % n
87581412 % 21418578 = 1907100  # r > n, uses r % n
1907100 % 17091 = 9999         # n > r, uses n % r
9999 % 9999 = 0                # r % n = n % r = 0, terminated

Result: [21873078, 21418578, 1907100, 9999]

Another example n=12345678:
87654321 % 12345678 = 1234575 # r > n, uses r % n
5754321 % 1234575 = 816021    # r > n, uses r % n
816021 % 120618 = 92313       # n > r, uses n % r
92313 % 31329 = 29655         # n > r, uses n % r
55692 % 29655 = 26037         # r > n, uses r % n
73062 % 26037 = 20988         # r > n, uses r % n
88902 % 20988 = 4950          # r > n, uses r % n
4950 % 594 = 198              # n > r, uses n % r
891 % 198 = 99                # r > n, uses r % n
99 % 99 = 0                   # r % n = n % r = 0, terminated

Result: [1234575, 816021, 92313, 29655, 26037, 20988, 4950, 198, 99]

A final example n=11000:
11000 % 11 = 0 # n % r = 0, terminated

Result: []

This is code-golf lowest byte-count wins.

PowerShell v2+, 89 bytes

param($n)for(){$r=-join"$n"["$n".length..0];if(!($n=(($r%$n),($n%$r))[$n-gt$r])){exit}$n}

Iterative solution. Lengthy because there's no easy way to reverse an array, so we stringify it and index on it backwards to store into $r. Then a pseudo-ternary to pull out the appropriate modulo and re-store into $n for the next round. However, if the result is zero, that means the !($n...) will be $true, so we exit instead of $n. The numbers are left on the pipeline and (implicitly) returned as an array, but without an encapsulating pipeline or saving the results into a variable, the default Write-Output sticks a newline between.

Try it online! (Yes, dead serious.)
PowerShell is now on TIO! You gotta give it a second or two, because PowerShell is a beast to startup, but now you, yes you, can verify PowerShell code right in your browser!


Number of characters skipped determines code printed Write a program which, when every nth character is skipped, it prints n. For example, if every 2nd character is skipped, it prints 2.

Example

n=0

foobar

Output:

0

n=1

foa

Output:

1

n=2

fobr

Output:

2

Rules

If n=0 (no characters are skipped), 0 must be returned.
Must print to STDOUT.
Standard loopholes are forbidden.
The first character is never skipped.
Obviously, it doesn't need to work for more characters than the code has (e.g. if your code is 11 characters long, it doesn't need to work for every 11th character)

Scoring

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

Polyglot, 1 byte

0

Try it in Retina

Try it in Jelly

Try it in 05AB1E

Try it in Husk

Try it in ///

Try it in GolfScript

Try it in BrainGolf

Try it in Pyth

Try it in Japt

Try it in ink

Try it in PHP

Try it in Brachylog

Try it in MATL

Try it in Keg

Try it in Carrot


Pristine Bit Checking Write a program/function that takes two integers in the range \$0\$ to \$255\$ inclusive, and returns whether the binary forms of the numbers are exactly one bit different.

For example, \$1\$ and \$0\$ have binary forms 00000001 and 00000000, which are one bit apart. Similarly, \$152\$ and \$24\$ are 010011000 and 000011000, so they return true.

However, your code must be pristine, such that if any one bit in your program is flipped, it should throw an error. For example, if your program was the single byte a (01100001), then all the 8 possible modified programs:

á ! A q i e c `

must throw an error. Make sure you are modifying by bytes (e.g. the á up there is actually representing the byte \$225\$, not the actual two byte character á).

Test cases:

0,1     => Truthy
1,0     => Truthy
152,24  => Truthy
10,10   => Falsey
10,11   => Truthy
11,12   => Falsey
255,0   => Falsey

Rules:

Provide a testing framework that can verify that your program is properly pristine, since there will be a lot of possible programs (number of bytes*8), or else a complete proof of pristineness.

Please make sure your program is valid before you post it.

Output needs to be either truthy/falsey (either way around is fine), or else two distinct non-error values
Errors can be runtime, compiler, interpreter etc.

Python 2, 35 bytes

lambda a,b:(a^b)&-(a^b)in[a^b or[]]

Try it online!

Uses the power-of-two check n&-n==n, eliminating the n==0 false positive.

For reference, these are the pairs of one-char binary operators that are one bit apart, making them hard to use:

+ /
- /
* +
% -
< |
< >

Fortunately, & and ^ are not among these.

Also note that == can become <=, and + can become the comment character #.

Python 2, 41 bytes

lambda a,b:bin(a^b).count(`+True`)is+True

Try it online!

Taking TFeld's lambda a,b:bin(a^b).count('1')==1 and making it pristine by changing the 1's to +True and == to is. Thanks to Jo King for 1 byte.


Bowl Filled with Water You should write a program or function which receives the volume of a bowl and the volume of the water in it as input and outputs or returns an ASCII representation of a bowl with water in it with the desired volumes.

A bowl has the following structure:

 \     /
  \___/

The bowl has at least one _ character. The count of \'s and /'s are also positive and they are equal due to symmetry.

The volume of the bowl is the total number of _ and space characters between the \'s and /'s plus one for every pair of \ and /. This means the above bowl has the volume of 10:

 \     /  =>  xxxxx x (the last one is for the \/ pair)
  \___/        xxx x (the last one is for the \/ pair)

Note that two different bowl could have the same volume. E.g. both the following bowls have a volume of 18:

\       /
 \     /      \         /
  \___/        \_______/

We can pour some water into the bowl. The water is represented as a row of ~ characters instead of spaces inside the bowl. The bottom row has no spaces so it can not contain the ~'s. This means our example can be filled with water in only one way:

 \~~~~~/
  \___/

Other bowls could be filled in multiple ways:

 \~~~~~/   \     /
  \   /     \~~~/
   \_/       \_/

The volume of the water in a bowl is the volume of the bowl rows below the ~ characters. The above examples have water volumes of 4, 6 and 2 respectively.

Input

Two positive integers, the volume of the bowl and the volume of the water.
You can choose the order of the two numbers.
The two integer can be inputted in any common list format (list, tuple, array, etc.) or as two separate integers.
At least one valid bowl-water configuration is guaranteed for the input values.

Output

The ASCII representation of a bowl with water where the bowl and water volumes match the input.
If you choose to return the result instead of printing, it should be returned as single string (or your language's closest alternative).
Any trailing whitespace is allowed.
No unnecessary leading whitespace is allowed.
If there are multiple correct configurations you are free to choose which one you output but you can only output one of them.

Examples

Each input integer pair is followed by its one or more possible outputs.

6 2
\~~~/
 \_/

10 4
\~~~~~/
 \___/

24 8
\        /
 \~~~~~~/
  \    /
   \__/

42 12 //either of the two output is correct
\           /
 \         /
  \~~~~~~~/
   \     /
    \   /
     \_/

\               /
 \~~~~~~~~~~~~~/
  \___________/

90 68
\~~~~~~~~~~~~~~~~~~~~~/
 \                   /
  \                 /
   \               /
    \_____________/

102 42
\                     /
 \                   /
  \~~~~~~~~~~~~~~~~~/
   \               /
    \             /
     \___________/

This is code golf so the shortest entry wins.

CJam, 72 70 69 bytes

q~:QW=3m*{:,2ff*),)ff+}%{::)1fbQ=}=~W%ee_,S*W'_t@,~'~t.{S\+.*"\/".+N}

Try it online in the CJam interpreter.

Run time and memory usage are O(scary), so the last three test cases should be verified using the Java interpreter (and extra heap space).

Example run

$ time java -Xmx4G -jar cjam-0.6.5.jar bowl.cjam <<< '[42 102]'
\                     /
 \                   /
  \~~~~~~~~~~~~~~~~~/
   \               /
    \             /
     \___________/

real    0m40.669s
user    3m13.100s
sys     0m11.690s

How it works

q~:Q     e# Read from STIDN, evaluate and save the result in Q.
W=       e# Select the last element of Q (bowl volume B).
3m*      e# Push all vectors of {0,...,B-1} × {0,...,B-1} x {0,...,B-1}.

{        e# For each vector [X Y Z]:
  :,     e#   Push [[0 1 ... X-1] [0 1 ... Y-1] [0 1 ... Z-1]].
  2ff*   e#   Multiply each coordinate by 2.
  ),)    e#   Pop the last vector, compute its length and increment.
  ff+    e#   Add the result to each component of each vector.
}%       e# Result: [[Z Z+2 ... Z+2(X-1)] [Z Z+2 ... Z+2(Y-1)]]

{        e# Find:
  ::)    e#   Increment each coordinate (to account for the volume in "\/").
  1fb    e#   Sum the coordinate of both vectors.
  Q=     e#   Compare the result to Q (desired volumes).
}=       e# If they match, push the array and break.

~        e# Dump both vectors on the stack.
W%       e# Reverse the rightmost one (corresponds to the bowl volume).
ee       e# Enumerate its coordinates.
         e# [Z+2(Y-1) ... Z+2 Z] -> [[0 Z+2(Y-1)] ... [Y-2 Z+2] [Y-1 Z]].
_,S*     e# Compute the length (Y) and push a string of Y spaces.
W'_t     e# Replace the last space with an underscore.
@        e# Rotate the leftmost vector (corresponds to the water volume) on top.
,        e# Compute its length (X).
~'~t     e# Replace the space at index X from the right with a tilde.

.{       e# For each enumerates coordinate and the corresponding character:
  S\+    e#   Append the character to the string " ".
  .*     e#   Vectorized repetition: [1 2] " ~" -> [" " "~~"]
  "\/".+ e#   Append the first (second) solidus to the first (second) string.
  N      e#   Push a linefeed.
}


Fizz Buzz with unique characters in columns Inspired by Digits in their lanes and 1, 2, Fizz, 4, Buzz

Introduction

Your task is to generate exactly the following output:

1
2
Fizz
4
  Buzz
    Fizz
7
8
      Fizz
        Buzz
 11
          Fizz
   13
    14
            FizzBuzz
     16
      17
              Fizz
       19
                  Buzz
                    Fizz
 22
    23
                      Fizz
                        Buzz
   26
                          Fizz
     28
      29
                            FizzBuzz
       31
      32
                              Fizz
34
                                  Buzz
                                    Fizz
 37
  38
                                      Fizz
                                        Buzz
        41
                                          Fizz
  43
   44
                                            FizzBuzz
      46
       47
                                              Fizz
         49
                                                  Buzz

Challenge

This challenge is based on the Fizz Buzz challenge, and here is a recap: output the numbers from 1 to 100 inclusive, each number on its own line, but if the number is a multiple of 3, you should output "Fizz" instead of the original number, if the number is a multiple of 5, you should output "Buzz" instead of the original number. If the number is a multiple of 15, you should output "FizzBuzz" instead of the original number.

However, in addition to the requirement above, you should also indent each line using spaces to make that every column contains unique characters (excluding spaces and newlines) only. The spaces prepended to each line are the minimum required to make all the lines appeared before it (inclusive) has unique characters in each column.

For example, 1,2,Fizz,4 does not need any indentation because they already have unique characters in each column (column 1: 12F4, column2: i, column3: z, column4: z), but when adding Buzz we need to indent by two spaces because otherwise we would have two z's in both the 3rd and the 4th column. Since two spaces is enough to achieve the goal you should not indent it by three spaces. 7 and 8 does not need any indentation but when outputting 11 we need to indent by one space because the 1st column already has a 1. 13 then needs to be indented by three spaces because now 1st, 2nd and 3rd column all have a 1. Indentation for the remaining lines follow the same rule.

To make the challenge simpler, The upper limit has been changed to 50.

Specs

You can write a program or a function. Neither of them should take any non-empty input. Taking an empty input is fine.
Since this is a KC challenge you need to produce the output as specified in the Introduction section. A single trailing newline is fine. No heading newlines or extra heading spaces. No extra trailing spaces for each line.
Your program can exit with error or have non-empty STDERR output as long as STDOUT conforms to the specification.
This is intra-language code-golf, the program with lowest number of bytes wins in its language.
Default loopholes apply.

Python 2, 127 bytes

i=0;exec"print ord('<<<<>@<<BD=F?@HABJCNP=@RT?VABXCBZ<^`=>bdDf>?hBCjEn'[i])%60*' '+(i%3/2*'Fizz'+i%5/4*'Buzz'or`-~i`);i+=1;"*50

Try it online!

A fifty-byte lookup table seems to hurt the code size less than the logic necessary to track which characters have occurred in each column.


Add up two algebraic numbers Definitions

An algebraic number is a number that is a zero of a non-zero polynomial with integer coefficients. For example, the square root of 2 is algebraic, because it is a zero of x^2 - 2.
The corresponding polynomial is called the minimal polynomial of the algebraic number, provided that the polynomial is irreducible over ℚ.

Task

Given the minimal polynomials of two algebraic numbers, construct a set of numbers that are the sum of two numbers, one from the root of one polynomial, and one from the other. Then, construct a polynomial having those numbers as roots. Output the polynomial. Note that all roots are to be used, including complex roots.

Example

The two roots of x^2-2 are √2 and -√2.
The two roots of x^2-3 are √3 and -√3.
Pick one from a polynomial, one from the other, and form 4 sums: √2+√3, √2-√3, -√2+√3, -√2-√3.
A polynomial containing those four roots is x^4-10x^2+1

Input

Two polynomials in any reasonable format (e.g. list of coefficients). They will have degree at least 1.

Output

One polynomial in the same format, with integer coefficients.

You are not required to output an irreducible polynomial over ℚ.

Testcases

Format: input, input, output.

x^4 - 10 x^2 + 1
x^2 + 1
x^8 - 16 x^6 + 88 x^4 + 192 x^2 + 144

x^3 - 3 x^2 + 3 x - 4
x^2 - 2
x^6 - 6 x^5 + 9 x^4 - 2 x^3 + 9 x^2 - 60 x + 50

4x^2 - 5
2x - 1
x^2 - x - 1

2x^2 - 5
2x - 1
4x^2 - 4 x - 9

x^2 - 2
x^2 - 2
x^3 - 8 x

The outputs are irreducible over ℚ here. However, as stated above, you do not need to output irreducible polynomials over ℚ.

Scoring

This is code-golf. Shortest answer in bytes wins.

Mathematica, 32 bytes

Resultant[#,#2/.x->z-x,x]/.z->x&

Or the same length:

Resultant[#/.x->y,#2/.x->x-y,y]&

Example:

In[1]:= Resultant[#,#2/.x->z-x,x]/.z->x&[x^4 - 10 x^2 + 1, x^2 + 1]

Out[1]= 144 + 192 x^2 + 88 x^4 - 16 x^6 + x^8

In[2]:= Resultant[#/.x->y,#2/.x->x-y,y]&[x^2 - 2, x^2 - 2]

Out[2]= -8 x^2 + x^4

Explanation:

If x is a root of f(x), y is a root of g(y), and let z = x + y, then (x, z) is a root of the simultaneous equations f(x) = 0, g(z - x) = 0. Then we can eliminate the variable x using the resultant.


Jelly, 26 25 bytes

œ&µL‘<⁴ȧ⁹ȯ
œċµç\L€=⁴œṗµḊ’

Full program which prints a representation of a list of lists, each list being a part, e.g. for n=5, k=3:

[[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 0, 4]], [[0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 1, 4]], [[0, 2, 2], [0, 2, 3], [0, 2, 4]], [[0, 3, 3], [0, 3, 4]], [0, 4, 4], [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4]], [[1, 2, 2], [1, 2, 3], [1, 2, 4]], [[1, 3, 3], [1, 3, 4]], [1, 4, 4], [[2, 2, 2], [2, 2, 3], [2, 2, 4]], [[2, 3, 3], [2, 3, 4]], [2, 4, 4], [[3, 3, 3], [3, 3, 4]], [[3, 4, 4], [4, 4, 4]]]

Note: the representation used removes the redundant [ and ] around lists of length 1.

Try it online! or see a pretty print version (cost 3 bytes)

How?

œ&µL‘<⁴ȧ⁹ȯ - Link 1, conditional multi-set intersection: list x, list y
œ&         - multi-set intersection(x, y)
  µ        - monadic chain separation (call that i)
   L       - length(i)
    ‘      - increment
     <     - less than?:
      ⁴    -     2nd program input, k
       ȧ   - logical and with:
        ⁹  -     link's right argument, y (y if i is too short, else 0)
         ȯ - logical or (y if i is too short, else i)

œċµç\L€=⁴œṗµḊ’ - Main link: n, k
œċ             - combinations with replacement(n, k) (sorted since n implies [1,n])
  µ            - monadic chain separation (call that w)
         œṗ    - partition w at truthy indexes of:
   ç\          -     reduce w with last link (1) as a dyad
     L€        -     length of €ach
        ⁴      -     2nd program input, k
       =       -     equal (vectorises)
           µ   - monadic chain separation
            Ḋ  - dequeue (since the result will always start with an empty list)
             ’ - decrement (vectorises) (since the Natural numbers were used by œċ)


Work it harder, make it better In this challenge your goal will be to output the lyrics to Daft Punk's Harder, Better, Faster, Stronger. Specifically, output this text:

Work It
Make It
Do It
Makes Us
Harder
Better
Faster
Stronger
More Than
Hour
Our
Never
Ever
After
Work Is
Over

Work It
Make It
Do It
Makes Us
Harder
Better
Faster
Stronger
More Than
Hour
Our
Never
Ever
After
Work Is
Over

Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over

Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over

Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over

Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over

Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over

Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over

Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour After
Our Work Is Never Over

Work It Harder, Make It
Do It Faster, Makes Us
More Than Ever, Hour
Our Work Is Never Over

Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour Af-
Our Work Is Never Over

Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour Af-
Our Work Is Never Over

Work It Harder Make It Better
Do It Faster, Makes Us Stronger
More Than Ever Hour Af-
Our Work Is Never Over

Work It Harder
Make It Better
Do It Faster Makes Us Stronger
More Than Ever Hour
Our Work Is Never Over

Work It Harder
Do It Faster
More Than Ever
Our Work Is Never Over

Work It Harder
Make It Better
Do It Faster
Makes Us Stronger
More Than Ever
Hour After
Our Work Is Never Over

Your output may have a trailing newline or trailing whitespace.

Built in compression methods are not allowed.

This is code golf, so shortest code wins!

Ruby, 308 303
puts a='Work It|Make It|Do It|Makes Us|Harder|Better|Faster|Stronger|More Than|Hour|Our|Never|Ever|After|Work Is|Over

'.split(?|),a
56.times{|i|puts a[j=i%4/2*4+i%4*2]+' '+a[j+4]+[[' ',', ','
']["l4yq62lhgnizb0kfu".to_i(36)/3**i%3]+a[j+1]+' ',''][i%51/48]+[a[j+5],['','Af-'][i%44/32]][7619655>>i-28&1]}

Algorithm
Song intro: Take 16 tokens, and print them twice (last one bears an extra newline)
Verses: Riffle the tokens together to make the verses, 4 tokens per line, in the following order:
 0  4  1  5
 2  6  3  7
 8 12  9 13
10 14 11 15

In some lines, the last token is omitted, or exchanged for Af-. These lines are noted with a 1 bit in the magic number 0x744447=7619655.
In three lines, the penultimate token is also omitted, those where i%51/48==1
The punctuation in the middle of the line can be one of ' ' ', ' '\n'. These are encoded in the number 02220010000200100010001001110010001000100010001000100010 (base 3) = "l4yq62lhgnizb0kfu" (base 36.)
With comments
puts a='Work It|Make It|Do It|Makes Us|Harder|Better|Faster|Stronger|More Than|Hour|Our|Never|Ever|After|Work Is|Over

'.split(?|),a                                                    #Set up array containing all 16 tokens, print it, and print it again (note newlines at end of last token.)

56.times{|i|                                                     #14 verses, 4 lines each

puts a[j=i%4/2*4+i%4*2]+                                         #expression cycles through 0,2,8,10. Print the first token on the line.

' '+a[j+4]+                                                      #print a space, and the second token on the line.

[[' ',', ','
']["l4yq62lhgnizb0kfu".to_i(36)/3**i%3]+a[j+1]+' ',''][i%51/48]+ #if i%51/48==1,print nothing. Otherwise print the 3rd token, followed by a space, and preceded by one of ' ' or ', ' or '\n'

[a[j+5],['','Af-'][i%44/32]][7619655>>i-28&1]                    #if 7619655>>i-28&1==0 print the fourth token. Otherwise print either nothing or Af- depending on the value of i%44/32

}


Generate an RGB colour grid This! is an RGB colour grid...

Basically it's a 2-dimensional matrix in which:

The first row, and the first column, are red.
The second row, and the second column, are green.
The third row, and the third column, are blue.

Here are the colours described graphically, using the letters R, G, and B.

Here's how we calculate the colour of each space on the grid is calculated.

Red + Red = Red (#FF0000)
Green + Green = Green (#00FF00)
Blue + Blue = Blue (#0000FF)
Red + Green = Yellow (#FFFF00)
Red + Blue = Purple (#FF00FF)
Green + Blue = Teal (#00FFFF)

The Challenge

Write code to generate an RGB colour grid.
It's code golf, so attempt to do so in the smallest number of bytes.
Use any programming language or markup language to generate your grid.
Things I care about:

The result should graphically display an RGB grid with the defined colours.

Things I don't care about:

If the output is an image, HTML, SVG or other markup.
The size or shape of the colour blocks.
Borders, spacing etc between or around the blocks.
It definitely doesn't have to have labels telling you what the row and column colours should be.

Bash, 44

2 bytes saved thanks to @NahuelFouilleul
2 bytes saved thanks to @manatwork

printf "${f=^[[3%dm.}$f$f
" 1 3 5 3 2 6 5 6 4

Here, blocks are . characters.  ^[ is a literal ASCII escape character (0x1b).

You can recreate this script as follows:
base64 -d <<< cHJpbnRmICIke2Y9G1szJWRtLn0kZiRmCiIgMSAzIDUgMyAyIDYgNSA2IDQ= > rgbgrid.sh


Four-Four-Four-Four! This is the sequel to one of my previous challenges, Three-Three-Three!

Write a program (or function, or snippet) that takes no input and produces an output according to the following four Conditions.

Both the program and the output must be written such that:

At least 16 distinct characters appear (since 16 = 4 × 4).
The number of occurrences of each character is a multiple of 4.

Also:

The program and the output must not be the same (because programs consisting of a single literal like 1111222233334444 are quite boring).

Finally, the program:

Cannot be written as a string repeated 4 times (e.g. f();f();f();f();, 123412341234).

It's code-golf! In anticipation of a multi-way tie for 64 bytes, the first submission whose output also satisfies Condition 4 will be the winner.
Notes

You are encouraged not to use comments to satisfy Conditions 1 and 2.
Feel free to embed wild bananas in your variable names as you see fit.

CJam, 16 bytes
4,4,4,4,@@@@\\\\

Try it online!


Create a checkerboard matrix Take a positive integer n as input, and output a n-by-n checkerboard matrix consisting of 1 and 0.

The top left digit should always be 1.

Test cases:

n = 1
1

n = 2
1 0
0 1

n = 3
1 0 1
0 1 0
1 0 1

n = 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1

Input and output formats are optional. Outputting the matrix as a list of lists is accepted.

Jelly, 4 bytes

52 seconds!

+€ḶḂ

Try it online!


How old is it roughly? Write a short program which takes in a positive number of seconds representing an age, and outputs an estimate of that time in English.

Your program must output the least precise amount of time which has passed, among the following metrics and their lengths in seconds:

second = 1
minute = 60
hour   = 60 * 60
day    = 60 * 60 * 24
week   = 60 * 60 * 24 * 7
month  = 60 * 60 * 24 * 31
year   = 60 * 60 * 24 * 365

Examples

input      : output
1          : 1 second
59         : 59 seconds
60         : 1 minute
119        : 1 minute
120        : 2 minutes
43200      : 12 hours
86401      : 1 day
1815603    : 3 weeks
1426636800 : 45 years

As you can see above, after the time of say, 1 day (60 * 60 * 24 = 86400 seconds), we no longer output minute(s) or hour(s), but only days until we surpass the time of one week, and so on.

Consider the given length of time to be an age. For example, after 119 seconds, 1 minute has passed, not 2.

Rules

No specification for 0 or negative inputs.
Follow proper pluralization. Every measure greater than 1 must include an s following the word.
You may not use a pre-existing library which serves the function of the entire program.
This is a code golf, shortest program wins the internet points.
Have fun!

Jelly, 62 bytes

TṀị
“¢<<ð¢‘×\×€0¦7,31,365F⁸:µç“ɲþḣ⁹ḢṡṾDU¤µQƝṁ⁼ẹ»Ḳ¤ṭÇK;⁸Ç>1¤¡”s

A full program printing the result.
(As a monadic link it returns a list of an integer followed by characters)

Try it online!

How?

TṀị - Link 1: list of integers, K; list, V  e.g. [86401,1440,24,1,0,0,0], ["second","minute","hour","day","week","month","year"]
T   - truthy indexes of K                        [1,2,3,4]
 Ṁ  - maximum                                    4
  ị - index into V                               "day"

“¢<<ð¢‘×\×€0¦7,31,365F⁸:µç“...»Ḳ¤ṭÇK;⁸Ç>1¤¡”s - Main link: integer, N  e.g. 3599
“¢<<ð¢‘                                       - list of code-page indices = [1,60,60,24,1]
        \                                     - cumulative reduce with:
       ×                                      -  multiplication = [1,60,3600,86400,86400]
             7,31,365                         - list of integers = [7,31,365]
            ¦                                 - sparse application...
           0                                  - ...to index: 0 (rightmost)
         ×€                                   - ...of: multiplication for €ach = [1,60,3600,86400,[604800,2678400,31536000]]
                     F                        - flatten = [1,60,3600,86400,604800,2678400,31536000]
                      ⁸                       - chain's left argument, N    3599
                       :                      - integer divide         [3599,59,0,0,0,0,0]
                        µ                     - start a new monadic chain, call that X
                                ¤             - nilad followed by links as a nilad:
                          “...»               -   compression of "second minute hour day week month year"
                               Ḳ              -   split at spaces = ["second","minute","hour","day","week","month","year"]
                         ç                    - call the last link (1) as a dyad - i.e. f(X,["second","minute","hour","day","week","month","year"])
                                              -                             "minute"
                                  Ç           - call the last link (1) as a monad - i.e. f(X,X)
                                              -                             59
                                 ṭ            - tack                        [59,['m','i','n','u','t','e']]
                                   K          - join with spaces            [59,' ','m','i','n','u','t','e']
                                           ”s - literal character '
                                          ¡   - repeat...
                                         ¤    - ...number of times: nilad followed by link(s) as a nilad:
                                     ⁸        -   chain's left argument, X  [3599,59,0,0,0,0,0]
                                      Ç       -   call the last link (1) as a monad - i.e. f(X,X)
                                              -                             59
                                       >1     -   greater than 1?           1
                                    ;         - concatenate                 [59,' ','m','i','n','u','t','e','s']
                                              - implicit print - smashes to print  "59 minutes"


Combinatorial products of unique primes Statement of problem

Given a set of unique, consecutive primes (not necessarily including 2), generate the products of all combinations of first powers of these primes — e.g., no repeats — and also 1. For example, given the set { 2, 3, 5, 7 }, you produce { 1, 2, 3, 5, 6, 7, 10, 14, 15, 21, 30, 35, 42, 70, 105, 210 } because:

  1  =  1
  2  =  2
  3  =  3
  5  =  5
  6  =  2 x 3
  7  =  7
 10  =  2 x 5
 14  =  2 x 7
 15  =  3 x 5
 21  =  3 x 7
 30  =  2 x 3 x 5
 35  =  5 x 7
 42  =  2 x 3 x 7
 70  =  2 x 5 x 7
105  =  3 x 5 x 7
210  =  2 x 3 x 5 x 7

Note that if the cardinality of your input set is k, this will give you 2^k members in your output set.

Rules/Conditions

You can use any language. Aim for the smallest character count of source code.
Your solution must be either a complete program or a complete function. The function can be anonymous (if your language supports anonymous functions).
Your solution should be able to support products up to at least 2^31. Don't worry about detecting or handling integer overflow if you are passed numbers whose product is too great to represent. However, please state the limits of your calculations.
You may accept either a list or a set and produce either a list or a set. You may assume the input is sorted but you are not required to produce sorted output.

Background

When or why is this useful? One place it is very useful is in generating a table of multipliers to race in parallel in an integer factoring algorithm known as Square Forms Factorization. There, each odd multiplier you try decreases the probability of the algorithm failing (to find a factor) by approximately 50% on hard semiprimes. So with the set of generating primes { 3, 5, 7, 11 }, which produces a set of 16 trial multipliers to race in parallel, the algorithm fails approximately 2^–16 of the time on hard semiprimes. Adding 13 to the primes list produces a set of 32 trial multipliers, reducing the chance of failure to approximately 2^–32, giving a drastic improvement in outcome at no additional computational expense (because even with twice as many multipliers racing in parallel, on average it still finds the answer in the same total number of steps).

Pure Bash, 32 bytes
eval echo \$[{1,${1// /\}*{1,}}]

Reads input list (single space separated) passed as a command-line arg.
Three different shell expansions are used:

${1// /\}*{1,} is a parameter expansion that replaces spaces in 2 3 5 7 with }*{1, to give 2}*{1,3}*{1,5}*{1,7.  \$[{1, and }] are added to the start and end respectively to give \$[{1,2}*{1,3}*{1,5}*{1,7}].  The \$[ is backslash-escaped to prevent attempts to do arithmetic expansion at this stage.
\$[{1,2}*{1,3}*{1,5}*{1,7}] is a brace expansion.  Because brace expansion typically happens before parameter expansion, we use have to useeval to force the parameter expansion to happen first.  The result of the brace expansion is $[1*1*1*1] $[1*1*1*7] $[1*1*5*1] ... $[2*3*5*7].
$[1*1*1*1] $[1*1*1*7] $[1*1*5*1] ... $[2*3*5*7] is a list of arithmetic expansions, which are then evaluated to give the list of numbers we require.

Output:
$ ./comboprime.sh "2 3 5 7"
1 7 5 35 3 21 15 105 2 14 10 70 6 42 30 210
$


Calculate the binary split sum of a word Take a string, s containing printable ASCII-characters as input, and output its "binary split sum". Need an explanation?

How do you get the binary split sum?

We'll use the string A4 as an example in the following explanation.

Convert the characters to binary, treating each letters as a 7-bit ASCII character

A -> ASCII 65 -> 1000001
4 -> ASCII 52 -> 0110100

Concatenate the binary numbers into a new binary number

A4 -> 1000001 & 0110100 -> 10000010110100

Split the new binary number into chunks, where no 1 can have a 0 to its left. You should not split consecutive 1s.

10000010110100 -> 100000, 10, 110, 100

Convert these binary numbers to decimal

100000, 10, 110, 100 -> 32, 2, 6, 4

Take the sum of these numbers:

32 + 2 + 6 + 4 = 44

So, the output for the string A4 should be 44.

Test cases:

a
49

A4
44

codegolf
570

Hello, World!
795

Python 2, 86 81 76 bytes

-5 bytes thanks Adnan
-5 bytes thanks xnor

s=0
for c in input():s=s*128+ord(c)
print eval(bin(s).replace('01','0+0b1'))

Try it online!

for c in input():s=s*128+ord(c) to do the ASCII conversion numerically, where *128 is used to left shift s 7 times (steps 1 and 2)
eval(('0'+new_bin).replace('01','0+0b1')) to split and sum (steps 3, 4 and 5)


Cantor's unspeakable numbers An unspeakable number is a number which is divisible by seven or has seven as one of its digits. A children game is to count skipping unspeakable numbers

1 2 3 4 5 6 ( ) 8 9 10 11 12 13 ( ) 15 16 ( ) 18 ...

Cantor's version of the game is the sequence defined by recursively filling in the sequence "1 2 3 4 5 6 ( ) 8..." into the gaps ( ) above.

1 2 3 4 5 6 1 8 9 10 11 12 13 2 15 16 3 18 19 20 4 22 23 24 25 26 5 6 29 30 31 32 33 34 1 36 8 38 ...

Print/output at least the first 7^7 numbers of Cantor's unspeakable number game...

While the definition is given recursively, you are not obliged to use recursion in the code.

This is code-golf, so the program with the shortest byte count wins!

Note: The sum of numbers in 1 to 7^7 is 203511962727. The last 10 numbers in that range are
   823534 823535 221563 108068 823538 823539 823540 823541 823542 221565.

Pastebin dump of first 1000 iterates: http://pastebin.com/Ksiu9Svf

Python 2, 77 75 74 70 bytes
Thanks to @MartinEnder for suggesting the limit of 9e5 which enderd up working after a change.Thanks to @mschauer for suggesting an infinite stream, saving 4 bytes.
def f(n=0):
 i=f()
 while 1:n+=1;yield next(i)if'7'in`n`or n%7<1else n

This is a generator that yields an infinite stream of the numbers.


Let's see some action! Who doesn't love action movies with fast noisy cars, especially those with a lot of crashes? Who doesn't love action shots in ascii art?
The scene is:
Two cars are starting at opposite sides of a straight road (with 60 spaces between). They start driving towards each other at constant speeds. The car to the left drives at 1 space per second, and the one to the right drives at 2 spaces per second.
Obviously, the cars can't pass through each other, so for n ≥ 20, the scene will be two crashed cars with bonnets up at the position where the crash occurred.
As a movie lover, I want to pause the scene now and then, just to enjoy the beauty of it.
Given an integer n (function argument or STDIN), representing the number of seconds from the start of the scene, show the scene at that moment.
This is the starting scene, with 60 spaces between the front wheels:
  __                                                                __
_/  \_                                                            _/  \_
o    o                                                            o    o

this is the scene after 11 seconds:
             __                               __
           _/  \_                           _/  \_
           o    o                           o    o

and this is what it looks like after the crash (note that the bonnets are up after the crash):
                      __    __
                    _/  \/\/  \_
                    o    oo    o

I'm only interested in watching two cars crashing, so spaces, newlines, ++ doesn't matter.
This is code golf, so the shortest code in bytes wins. Answers added later can still win if they are shorter than the current accepted answer.

Labyrinth, 394 386 bytes

I proudly introduce...

<}74}}:23}29}59}}}}}}}:111_}}}}:::::::23_}:111
?                        @
:" }}_47}_95    3""""""""(
 _ :       }    _   }    {=}
 2 23_}29_ _    ;   :      \
 0       ; 3  +_( 3_"  60{ .{.{.
"-_95:}}"" 2  0 ) 2 "  _ _ {
""       _ :  2 _ ."(; } 3 .{
 ;_92}_47} :  _ 0    = : *  ;
           : "" 2 {.{{ . -""(
}}:59_}}:::: "";_ .    {  _ "
}             "   {.{.{.  32.
}}}_95:}}}}_20-

...my new two-dimensional esolang Labyrinth! The code above isn't incredibly well golfed (there are 161 spaces and 25 NOPs, so a better layout could shorten this a lot), but at least I managed to show that the language is usable for non-trivial tasks. :)

How it works

First, a quick overview of the language:

Labyrinth operates on two stacks, main and auxiliary, which can hold arbitrary signed integers. At the bottom of both stacks there is an infinite amount of zeroes.
Commands are individual characters on a 2D grid and they form a maze (that is unknown characters, particularly spaces, are walls). " is a NOP which is not a wall and can be helpful for padding certain paths in the code. As opposed to many other 2D languages, the edges do not wrap around.
The instruction pointer (IP) starts at the first non-wall character (in reading order) moving to the right. @ terminates the program.
If possible, the IP follows corridors (also around bends). If the IP has multiple cells to move to, it will generally turn left if the top of the main stack is negative, move straight ahead if it's zero, or turn right if it's positive. When the IP hits a wall it reverses direction. (There are a few more subtleties, but they shouldn't matter for this code.) This is the only way to implement control flow.
Apart from arithmetic and stack manipulation commands, the source code can be modified at runtime with the four commands >v<^ which will shift a row or column of the source code cyclically by one cell. Which row or column is affected depends on the top of the stack. If the IP's own row or column is shifted, it will move with the shift. This makes it possible to jump from one edge of the source code to the other.

Now for this particular challenge, here is the general idea of the algorithm:

Push the ends of the cars up to the bonnets (i.e. /  \_o    oo    o) onto the auxiliary stack.
Read the input and determine whether to push __ or /\ next.
Push the remainder of the cars (i.e. __    __  _/  \ and two leading spaces) onto the auxiliary stack.
Clamp the input to a maximum value of 20, let's call this N.
Now do the following 3 times:

Print N spaces.
Print 6 stored characters.
Print 60 - 3*N spaces.
Print 6 stored characters.
Print a newline.

Finally, let's look at some parts of the code. The IP starts in the top left corner, on a grid shifting command. The top of the main stack is 0 (which is used as a relative index), so the first row is shifted to the left, which also moves the IP to the right end of the grid. Now the first row is simply executed from right to left, which pushes the first set of fixed characters onto the auxiliary stack:

}74}}:23}29}59}}}}}}}:111_}}}}:::::::23_}:111<

This row shifting is useful for golfing when you want to start with a large amount of linear code.

Next we read the input and push the correct bonnets:

?
:"
 _
 2
 0       ;
"-_95:}}""
""       _
 ;_92}_47}

The bit on the left with the three NOPs sends negative results along the top branch and non-negative results along the bottom branch. At the right they are joined back together.

Now follows another large linear section (which could probably be golfed a lot with another row-shifting trick):

   }}_47}_95
   :       }
   23_}29_ _
           3
           2
           :
           :
           :
}}:59_}}::::
}
}}}_95:}}}}

This pushes the remainder of the cars onto the auxiliary stack.

Next, we compute min(20, input), which is similar to first branch:

                ;
              +_(
              0 )
              2 _
              _ 0
             "" 2
             "";_
              "
           _20-

Finally, we have the loop which runs three times to print the lines. Each iteration of the loop contains two small (3x3) loops to print the spaces, as well as two sections to print 6 characters from the auxiliary stack:

                         @
                3""""""""(
                _   }    {=}
                    :      \
                  3_"  60{ .{.{.
                  2 "  _ _ {
                  ."(; } 3 .{
                     = : *  ;
                  {.{{ . -""(
                  .    {  _ "
                  {.{.{.  32.

One nifty trick I'd like to draw attention to is the .{.{. at the right edge. This is a dead end, so apart from the . at the end the code is executed twice, once forward and once backward. This gives a neat way to shorten palindromic code (the catch is that you need to make sure the IP takes the correct turn when exiting the dead end again).


Pick up your phone! It's vibrating! You just recently got a new phone, but you don't quite like the way it vibrates, you've decided you want to create your own vibration patterns. So, you've written a program where you used the keywords long, short and pause to make your phone vibrate according to these keywords.

Task

Create a small program that accepts a string of long, short, and pause and outputs another string representing the phonetic sound of a phone vibrating; Rrrr - Rr

long sounds are Rrrr
short sounds are Rr
(Casing matters)
pause is a dash -
all sounds are delimited by dash with surrounding spaces ' - '

Test Cases

input:   long long short long short
output: Rrrr - Rrrr - Rr - Rrrr - Rr

input:   long long long short short short
output: Rrrr - Rrrr - Rrrr - Rr - Rr - Rr

input:   short short short pause short short short
output: Rr - Rr - Rr - - - Rr - Rr - Rr

input:   long short short long long pause short short
output: Rrrr - Rr - Rr - Rrrr - Rrrr - - - Rr - Rr

This is a code-golf question so answers will be scored in bytes, with the fewest bytes winning.

JavaScript, 70 63 bytes

2 bytes saved thanks to Luke

a=>a.replace(/./g,a=>[['Rr','rr','-',' - ']['onp '.search(a)]])

Try it online!


Mr. Moneybag's Money Piles Mr. Moneybags is a very rich man. He has an assistant Mr. Perfect, who one day, got very mad, and shredded some of Mr. Moneybag’s $100 bills! Mr. Moneybags decided to punish Mr. Perfect.

Mr. Moneybags tells Mr. Perfect to stack his money into different piles.

He starts with N (1 <= N <= 1,000,000, N odd) empty stacks, numbered 1..N. Mr. Moneybags then gives him a sequence of K instructions (1 <= K <= 25,000), each of the form "A B", meaning that Mr. Perfect should add one new bill to the top of each stack in the range A to B, inclusive.  For example, if Mr. Perfect is told "11 13", then he should add a bill to each of the stacks 11, 12, and 13.

After Mr. Perfect finishes stacking the money according to his instructions, Mr. Moneybags would like to know the median height of his N stacks -- that is, the height of the middle stack if the stacks were to be arranged in sorted order (N is odd, so this stack is unique).  Please write an efficient program to help Mr. Perfect determine the answer to Mr. Moneybag’s question.

INPUT FORMAT:

Line 1: Two space-separated integers, N K.
Lines 2..1+K: Each line contains one of Mr. Moneybag’s instructions in the form of two space-separated integers A B (1 <= A <= B <= N).

SAMPLE INPUT:

7 4
5 5
2 4
4 6
3 5

INPUT DETAILS:

There are N=7 stacks, and Mr. Moneybags issues K=4 instructions.  The first instruction is to add a bill to stack 5, the second is to add a bill to each stack from 2..4, etc.

OUTPUT FORMAT:

Line 1: The median height of a stack after Mr. Perfect completes the
   instructions.

SAMPLE OUTPUT:

1

The winner is the one with the "most efficient" algorithm. So, if someone posts an O(N) solution, then it will beat any O(N^2). If there is a tie, aka, two or more people who post an O(N) solution, for example, then whoever has is the shortest code (code-golfed) wins.

So, your purpose is to write a efficient algorithm, and to prevent possible ties with other people, try to code-golf it as well.

Another thing, the input is to be read from a file and the output must be written to a file.

EDIT
Also, the solution must be returned under or equal to 2 seconds. If it is not, you will receive a T. A wrong answer is an X. Which means, if no one can get it under time, then the most efficient algorithm sigh score of T can win.

EDIT #2
Here are some more samples:

http://pastebin.com/x88xAyPA
http://pastebin.com/y6Cuxm7W
http://pastebin.com/kgbeiQtd

EDIT #3
Bonus: (subtract 100 chars from total)

Solve this under 2 seconds :)

http://pastebin.com/3uT9VSzv

O(K log N), many characters of Python

Edit: Improved by replacing merge sort with radix sort.

This is an improvement over my previous answer, but I'm posting it separately because it's a different strategy, and so the post doesn't get super-long.

This is now optimal because simply reading the input can take 2*K*lg N time in the worst case -- 2*K numbers each with lg N bits.

The goal is to have minimal dependence on N. To do this, rather than store counts for each pile index, we realize that all piles in a contiguous cluster unaffected by the endpoints of any interval must have the same counts. So, if we see that an interval starts with 5, and there's no changes until 15, then those 10  piles have the same value.

Each change in pile size from a pile to the next one is caused by an interval starting or ending. We call these "events". Each event increases or decreases the current pile size by 1. If, from one event to the next, there's some number of piles, each of those piles has the current size.

We extract the 2*k events from the intervals, and sort them using a radix sort, taking advantage of the values being 1 through N. This take takes O(K*log(N)) because the numbers have O(lg N) bits.

We then run over the events, and for each one, update the list of counts to the previous event, which requires adding a number up to N (so lg N bits). This takes O(log(N)) per step, and so O(K*log(N))

Finally, having gotten the counts of the pile sizes, it's easy to quickly find the median by computing the cumulative number of piles up to a given size (or, rather, we subtract it from our desired count). This also takes O(K*log(N)).

The algorithm does the huge test case in under a second.

The code (ungolfed) is below with comments.

# Process input
def get_ints(line):
 vals = line.split()
 return (int(vals[0]),int(vals[1]))

s = input()

lines = s.split("\n")
N,K = get_ints (lines[0])
intervals = [get_ints(line) for line in lines[1:]]

mins,maxes=map(list,zip(*intervals))

#Each event will represent an increase or decrease of a pile from the previous one
#Each min increases the count by 1
#Each max causes the count to decrease by 1, starting with the next pile
events = [(a,1) for a in mins] + [(b+1,-1) for b in maxes]
events.append((N+1,0))

#Do a radix sort on the first element of each pair
#Each number has O(lg N) digits, so this takes O(k lg N)
events.sort()

#Count of the number of piles of each size
#pile_sizes[size] counts the number of piles of that size
pile_sizes = [0]*K
cur_pile = 1
cur_size = 0

#For each event, we track the pile size after the event
#Then, on the next event, we know there were some number of piles of that size
#The number of piles equals the distance between events
#Multiple events on the same pile have zero distance and don't affect the counts
for event in events:
 event_pile = event[0]
 piles_current_size = event_pile - cur_pile
 pile_sizes[cur_size] += piles_current_size
 cur_pile = event_pile
 cur_size += event[1]

#Get the i_th largest pile size from a list of pile size counts
def get_order_stat(counts,i):
 for val in range(len(counts)):
  cur_count = counts[val]
  if i<cur_count:
   return val
  i-=cur_count
 return None

median = get_order_stat(pile_sizes,N//2)

print(median)


Code Golf Measurer © 2019 Code Golf Measurer © 2019

Hexdumps used with xxd look something like this:

00000000: 666f 6f20 6261 7220 7370 616d 2065 6767  foo bar spam egg
00000010: 730a                                     s.

Your task is to convert a hexdump in this form in to the number of bytes used.

Rules:

Usual loopholes forbidden.
This is code-golf, so shortest valid answer in bytes wins.
You may or may not include the newline at the end of text (0a). This means that if the hexdump ends in a newline (0a), that input may have it's output reduced by one.
An empty input (literally nothing: empty list/string/etc.) must output 0.
Input can be taken in any form
Input will be valid ASCII with no control characters
The input must contain the whole hexdump

Test cases:

00000000: 4865 6c6c 6f2c 2077 6f72 6c64 2120 4865  Hello, world! He
00000010: 6c6c 6f2c 2077 6f72 6c64 210a            llo, world!.

returns 28 or 27

00000000: 0a                                       .

returns 1 or 0

00000000: 6368 616c 6c65 6e67 650a                 challenge.

returns 10 or 9

00000000: 4865 6c6c 6f2c 2077 6f72 6c64 21         Hello, world!

returns 13

returns 0 (This is literally nothing: empty list/string/etc.)

Explanations would be nice for non-standard languages.

Retina 0.8.2, 8 bytes

.{51}

.

Try it online! Explanation:

.{51}

Delete the first 51 characters of each line. (Lines can only have between 52 and 67 characters, so this always matches once per line.)

.

Count the remaining non-newline characters.

7 bytes if empty input did not have to be supported:

.{52}

Try it online! Explanation:

.{52}

Delete the first 52 characters of each line. (Lines can only have between 52 and 67 characters, so this always matches once per line.)

Count 1 more than the number of remaining characters (including newlines).


Enumerate the primes using only unary arithmetic Write a program which prints the sequence of prime numbers. The shortest solution wins!

All numbers must have a unary representation (not just in the output, but throughout the entire program). This could be a string of 1s, a list of 1s, Peano-style objects, etc.

No particular output format is required, as long as numbers are recognizable. 111, [1, 1, 1], and S(S(S(0))) are all acceptable representations of 3, for example.

Examples of permissible operations:

Appending or prepending a constant value to a string/list
Deleting a constant number of elements from a string/list
Comparing something with a constant, such as "11"
Calling is_empty on a string/list

Examples of what's not allowed:

Any operations on non-unary integers or floats, such as +, %, == or <
Built-in functions which operate on multiple strings/lists, like + or ==
Importing or downloading a library which does unary arithmetic ;-)

Sample programs

Java, with Peano numbers
Python, with strings of 1s

Haskell, 212 135 130 111 104 characters

x⊡[1]=print x>>p x
x⊡s@(_:r)=s∇x where[]∇[]=p x;_∇[]=x⊡r;[]∇y=s∇y;(_:t)∇(_:y)=t∇y
p x=(1:x)⊡x
main=p[1]

The sieve was fun to implement, but simple exhaustive remainder checking is smaller. Strictly adheres to the terms. Unary numbers are represented as lists of 1.

First ten primes:

& runhaskell 13159-UnaryPrimes.hs | head
[1,1]
[1,1,1]
[1,1,1,1,1]
[1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]

No library functions are used at all in the computation. In fact, the only library function used is print, which you can't get away from since you need some library function to output.


What's the ugliest line of R code that still parses? The goal is to produce a single line of R code that:

Does as little as possible
In as many characters as possible (max of 100 characters)
And is as ugly as possible (where "ugly" can be taken to mean inefficient computational strategies, extraneous characters such as a terminating semicolon, and so forth).

Do your worst, gentlefolk!

Objective criteria for winning

The winning answer will be judged according to the following point scale (the answer with the most points wins):

Generate a sequence from 0 to 10 (100 points)
In as many characters (N) as possible

0 points if N=100
N-100 points if N<100 (i.e. lose a point for every character under 100)
2(100-N) points if N>100 (i.e. lose two points for every character over 100)

Using as many negative examples from the R Inferno as possible

6 points per cited example
Each example only counts once.  This is so because a "heretic imprisoned in [a] flaming tomb" can only be so imprisoned one time.  Thus two global assignments in your line of code only net you 6 points.

72 96 characters.

`c`<-function(...){list(...)[[-1]];}->>`c`;`[`=0;`]`=10;c(c,c)(c,c)(c,invisible)(`[`[]:`]`[])[];

Ugliness:

Reusing a standard function name
Using symbols as variable names
Global assignment
Right assignment
Self-redefinition of function
Unnecessary trailing semicolon(s)
Unnecessary sub-scripting numbers
Unnecessary quoting of variable name
Leaves the workspace in a state which will almost certainly break any subsequent code run

Generates the sequence 0-10 (thanks to Andrie for the idea to do that).

output:

 [1]  0  1  2  3  4  5  6  7  8  9 10


How do I split a string??? Help plz? (code trolling) My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!

Note: This is a code-trolling question. Please do not take the question and/or answers seriously. More information here.

C

  My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!

Tricky problem for a beginning C programming class!  First you have to understand a few basics about this complicated subject.

A string is a sequence made up of only characters.  This means that in order for programmers to indicate an "invisible" thing (that isn't a space, which counts as a character), you have to use a special sequence of characters somehow to mean that invisible thing.

On Windows, the new line is a sequence of two characters in the string: backslash and n (or the string "\n")
On Linux or OS/X Macs, it is a sequence of four characters: backslash, n, backslash, and then r: (or "\n\r").

(Interesting historical note: on older Macintoshes it was a different sequence of four characters: "\r\n"... totally backwards from how Unix did things!  History takes strange roads.)

It may seem that Linux is more wasteful than Windows, but it's actually a better idea to use a longer sequence.  Because Windows uses such a short sequence the C language runtime cannot print out the actual letters \n without using special system calls.  You can usually do it on Linux without a system call (it can even print \n\ or \n\q ... anything but \n\r).  But since C is meant to be cross platform it enforces the lowest common-denominator.  So you'll always be seeing \n in your book.

(Note: If you're wondering how we're talking about \n without getting newlines every time we do, StackOverflow is written almost entirely in HTML...not C.  So it's a lot more modern.  Many of these old aspects of C are being addressed by things you might have heard about, like CLANG and LLVM.)

But back to what we're working on.  Let's imagine a string with three pieces and two newlines, like:

"foo\nbaz\nbar"

You can see the length of that string is 3 + 2 + 3 + 2 + 3 = 13.  So you have to make a buffer of length 13 for it, and C programmers always add one to the size of their arrays to be safe.  So make your buffer and copy the string into it:

/* REMEMBER: always add one to your array sizes in C, for safety! */
char buffer[14];
strcpy(buffer, "foo\nbaz\nbar");

Now what you have to do is look for that two-character pattern that represents the newline.  You aren't allowed to look for just a backslash.  Because C is used for string splitting quite a lot, it will give you an error if you try.  You can see this if you try writing:

char pattern[2];
strcpy(pattern, "\");

(Note: There is a setting in the compiler for if you are writing a program that just looks for backslashes.  But that's extremely uncommon; backslashes are very rarely used, which is why they were chosen for this purpose.  We won't turn that switch on.)

So let's make the pattern we really want, like this:

char pattern[3];
strcpy(pattern, "\n");

When we want to compare two strings which are of a certain length, we use strncmp.  It compares a certain number of characters of a potentially larger string, and tells you whether they match or not.  So strncmp("\nA", "\nB", 2) returns 1 (true).  This is even though the strings aren't entirely equal over the length of three... but because only two characters are needed to be.

So let's step through our buffer, one character at a time, looking for the two character match to our pattern.  Each time we find a two-character sequence of a backslash followed by an n, we'll use the very special system call (or "syscall") putc to put out a special kind of character: ASCII code 10, to get a physical newline.

#include "stdio.h"
#include "string.h"

char buffer[14]; /* actual length 13 */
char pattern[3]; /* actual length 2 */
int i = 0;

int main(int argc, char* argv[]) {
    strcpy(buffer, "foo\nbar\nbaz");
    strcpy(pattern, "\n");

    while (i < strlen(buffer)) {
       if (1 == strncmp(buffer + i, pattern, 2)) {
           /* We matched a backslash char followed by n */
           /* Use syscall for output ASCII 10 */
           putc(10, stdout);
           /* bump index by 2 to skip both backslash and n */
           i += 2;
       } else {
           /* This position didn't match the pattern for a newline */
           /* Print character with printf */
           printf("%c", buffer[i]);
           /* bump index by 1 to go to next matchable position */
           i += 1;
       }
    }

    /* final newline and return 1 for success! */
    putc(10, stdout);
    return 1;
}

The output of this program is the desired result...the string split!

foo
baz
bar

\t is for \trolling...

   Absolutely incorrect from the top to the bottom.  Yet filled with plausible-sounding nonsense that has scrambled information like what's in the textbook or Wikipedia.  Program logic appears transparent in the context of the misinformation, but is completely misleading.  Even global variables and returning an error code, for good measure...

...

   Of course, there's only one character in the C string representation of the two-character source literal sequence \n.  But making a buffer larger is harmless, as long as strlen() is used to get the actual length to operate on.

...

   We try to convince the reader that strncmp is a boolean operation that either matches (1) or doesn't (0).  But it actually has three return values (-1 matching less, 0 for equal, 1 for matching greater).  Our two character "pattern" being compared is not [\, n], but rather [\n, \0]...picking up the implicit null terminator.  As that sequence slides through the string it will never be greater than a two-character sequence it's compared to...at best it will be zero if there is a terminating newline in the input string.

...

   So all this does is loop through the string and print it one character at a time.  The top branch never runs.  (Though you could get it to if your string had lower-than \n codes in it, say tab...which could be used to mysteriously omit characters from the output :-P)


Put together cut strips of paper to get original message This question is from a programming challenge (not DARPA) which has ended. A sheet of paper consists of message, which has been shredded into vertical strips. Given the vertical strips and a dictionary of valid words, the goal is to put together the original message.

The vertical strips contain only one character from a line. The input to the program is the number of vertical strips (N), number of lines in the original message (K) and a string containing the characters in each vertical strip. Then the number of words in the dictionary and the list of valid words.

EXAMPLE INPUT

10
3
"MrM"
"ak "
"Gaa"
"oM "
" d "
"t 3"
" aP"
"nt "
"ont"
"ie "
15
1
2
3
4
5
AND
AM
AT
GO
IN
Main
Market
ON
PM
TO

OUTPUT

Go to Main
and Market
at 3 PM

Description of the input above
10 - number of vertical strips
3 - number of lines in the original message corresponds to number of characters in each string of the veritcal strips
{actual strings} - pay careful attention to spaces in strings
15 - number of words in the dictionary
{valid words}

I was able to create a map of characters -> count of each character, for each line from the vertical strips. Then parsing the dictionary and looking at the character map, you can recreate words in each line. Looks like finding the order of words is the difficult problem. What is the best approach to finding the correct message?

Python 3 - Trie and DFS

Trie is a tree shape data structure. If we build a trie from a collection of words, then each path from the root to a leaf node will represent a word from the collection.

To solve this problem, first we build a trie using the valid words. Suppose the original text has n rows and m columns, then we will have m strips to put together. We try to reconstruct the original text from left to right, column by column, using a recursive depth-first search. To perform branch elimination, we also maintain a list of heads on the trie, name it heads. Each head points to a node on the trie and point to the root at first. We will need n heads, each correspond to a row. Each time after a column(strip) is appended, heads[i] will be moved according to the character strip[i]. If we found any head that cannot be moved, then we know the column just appended is incorrect. After putting m columns, we get the original text.

I implemented this algorithm using Python. It is fast enough to solve a 40x80 case with 10000 valid word in instant.

I use this python 3 script to generate test cases. Run it with:

python3 make_script.py {dict path} {n rows} {n cols} > intput.txt

The following is a 40 x 80 case. The dictionary file can be found here, which has 10000 words.

80
40
c el efp e otl  desaiweseeme  jomp ebc g
synwds  irnsatseityl rkutpsiysei ssraat
gvmjewrell fclpadrll nbsvwiwteqdeniditba
uet criderndm eesih dalbrcra d iacnnoi e
lbipoeivedrwddivensne aeihrpaa eicangpni
 gontgtulvcbatdo glunsniiguoleu eigtbelh
xmsyyu ereio edvrttdonure tpselriniipnxs
ssdieop bgkg  wu  eloyr dllrhza t hic af
rttruminetnt rcu rasa ogosrywrnietvldgod
lpe aritour alolt yeomlpimmxryftenen  sn
cneregsc igodbsigeca r kbhiiisoss eagglp
crm nhdreh raokdtr rcfiotpsfgtjanotaaiaf
s pntenpnmv plemiaaxeeittgtg ncnaooaou a
srrganeu ut toaantetedccnr seiise eur ni
 xpndg psafl ooemlusof nba pauosina esnb
ge du  tbfe  spuoeuesen o s um ldsted  w
eto rs l nhuc caexr bsoptwcrrnaennrasary
e  maldneg nep nmaid isie ko ctedh necaa
esoeisi u ifran  rgirrts ntipuneccnvftrp
gui oeriwraisc og vsepharn latotts aenra
eenylorobneyrem nwtefrasdeoeet ot  osdsr
abia e i iwrcneaaiaeeu lie oihotgdicntdi
euugmjsdfcamazndei e yoagaserxatrultoaio
tamdfesgtitc xseuegs  fene thatfueo l ut
ocn sdrtn mai aerwmimoss te  oceorrit el
netbu wymsrfobelltemetrisioao uri  l ce
deaa ee e aadrgcoln cnto semroi  ofdnanu
aeaunrmvonirieaxapicnaioxaoromeviiuaeoou
 oaodtb hpretdarie n e recei etunsrsedal
ejht n jy ees tnr gsegr s  e jhb ayegup
ohids bi g iesiogs rytimtorrsab pnirwlc
ieuereaklieapeatlan sdeeg e lasedaob  be
rihbegaisvdtrprnatservaraco na imtcgplna
denrdnnelymisenimi gnfw bssalupcnansu et
itsrwnbeclwfmstasg craaim ei  atrifvpr
ubksogxernu auletinieo krte cgmltiliioir
atnhndcutigiasuir ntsaiauem usiireg idms
yniis ssle aisicsngqseazdifiertercaauvoc
ds prcatnoiaafsiopiratdrrmksnfidakr  gon
p ngaoolyeolg nep oae dnsnln srfcontsrve
boges massscgss arsobod ierseh rnivtagsp
nlstadhndnroieecntc slhoucbrcouo uohtiis
ltainnpif nfrn tinrdoi ninsanteu n   aeb
oun htoioaftupedsmowtmeatanyi sltnh ftto
a emgrasancass oelrefddy alacinsut n s
kgttnltednrmea t yhug welentn tu fsneeah
yia bilgwybnisgfrmidlh t rssnaiultgagk a
  iaeeorega sdbhc otadiresdagcipcuet rde
tygui artnsot le wtes etrracm pde oev e
cvrpsabemddamylpeiscdmktpnnolbsesardlwro
rnirmestiwntlrfresosedlvshydrsrrucnntr a
nans hinslmoxenfeolo cxeeneosgrphantiuyg
m dans llnrtlav ensptun acfaev s gtesfad
litl gonungirgk pioeutvinsstgintpsmbrdsu
altpjretooode rtnseeyepdrotllxric s rice
aikaunnskdoh agtnl cuegoacwhnsx esrurgg
ef drant  rsaaeymreleiiessmniesdoeeroeer
eereozurmoicueeegtcolbeioteodocrsnaeaatt
 h cre g  snsihssatlunisi odeelcpminoeba
oisstnirhpmnaybaertcnenhdnondsunaaprlipr
vetou egriemerpicacb  ygmiaw rrrocnisecm
ibs tara  neeiaqlbbtsgegcs sooeoeuel ten
blrkqaiacortqmn ien ylrrrnecieircs qeind
en s e ieu cnaiscikuirocnr hlnpfjooimohs
dctlehtr ntlgpddeoipmog elllrnncnkgcseeu
o  aaet henyaue mbntgeeselsws   mmawnwve
lns e xoorail yn  eesnee uctaud nrasenha
swydiecacaefolsenmttnsoer ohmahttpt radc
yvltaxin pgrauluktystkmot mrf aluuiepl
b sea usksoim hr idhtttd e owrn cnferevc
lstsibaocesfsmbejsdaellmepmbdedoffdbrtmq
axou nlnae ise gn esse  ihbstgsfmeteestf
yeaasra oopaeaildkiynteteidilnuenec vral
msylcdecsy  lkgr  icdkxrmie strle fei sz
 rdae gde al ngswsc soaru  tlsrtg durfne
 rrpodl i asg  essvuo aeaaheenaloe  geru
grus nbrls eqme ydioradhsoolmdiouoggnssv
 tfirotrkdnnnrtmwenan   abs cfcigscmpsed
 a soteiicdero nsaeuisrmisntau iirammlyi
anroiim tsiiaarrhoyaimdo oera dblogysmr

Solved:

lacerated deliberateness canvas gould scold sexually piggyback obey agrimony moe
seventy except fixates warble shrubbery instrumenting beveling convolute hairs j
tarring aptness homotopy misted unkindness frustrations marketing latitudinary h
superhumanly redbud bends atomics sprawls piggy oiling djakarta estop reads plat
insomnia delaware fruition auger hooded terramycin statuesqueness adjourns boca
brazed leghorn agnes seethed roentgen sen conjuring goa wrangled extremes hidden
ambuscade tribunals winced heap boxing fixates impostor rainstorm iberia billet
overturn protestingly pairings grieved protruded insulate ascertain tinkling c j
committees bock sat muncie drab lorelei honk fretfully block dense howell swishy
endowing annuls veins machining sandy reproducers neve flooding supportingly ye
sidings afterword thrived wrecks furman maintaining cone programs groaner mba ne
fractionally fisticuff ferromagnet wilsonian modifiable fathom accreditations ye
simulated grammars corporacies squads atalanta marriage ceq designates plexiglas
meyers propels apex ballooners impudently froze angst islamabad saud creases ku
baleful godmother scenes keep wheelings bystander kidnappings basilar caving get
experienced laryngeal mendacious devise animadvert coequal tithe surtout offer n
jaeger moments manuel instance systemwide ownerships plodding cracking legers mr
spits wallow girt extramarital administer petitioning berkeley writes ransoms b
discontinuity desegregate accretions cysteine thyroglobulin chomsky evans living
accosted speechless mixture bellowing lacerated adequately cautiousness products
endless comforters berenices fourteens insane odiousness nyu gambit yeasty lodge
lambda informative stressful dynamo forwent dynamites gentler doorkeep dutch keg
likeliest galatia fortiori hydride awakened could vandenberg wisdom phoenix axer
motivation spider epistemology shake rusher carbonizing strokers cordage meters
exposure bedim saints tritium distributed ranger indiscoverable interrogate ames
panther salem eschewing special oaths penumbra consigns winchester cons conrail
moneymake lome mob cottons ballooners smocks stressful sidewinder met refreshes
brood complexion straightforwardly patients separations wichita shrilly arose we
doldrum rarer winthrop magic chemically dancers angel outlining elf lawlessness
emboss county reagan unauthorized gauss suffixed tiresomeness cohn extravagant j
description fans staunch journalism prejudicial denture quixotic patrons briar h
override scott differentiators collection distribute folder superfluities pull b
fissured intercommunicating outputting managerial precedences conjuncted phloem
fiance honk nineteen coproduct monica sparks unconsciousness furious stagnate ma
durango fag effector notation highlands parceling magnetic reservoirs voting fay
baden end converge alva machining insurers mutiny battled quantities alberta ewe
relativeness propels formants configurable propos rubs diverge tampered swigging
toward cased reels actualities estop facings animadvert trigger golding fluke wu
mort meanness venturer dyadic abstinent phoenix resolve bangladesh acrobacy rsvp
quotas auburn crafty pacifism favorite grandiose buchenwald phelps leaded gauze

Code

def build_trie(words):
    root = {}
    for word in words:
        node = root
        for c in word:
            if c in node:
                node1 = node[c]
            else:
                node1 = node[c] = {}
            node = node1
    return root

def search_origins(root, strips):
    n_rows = len(strips[0])
    n_cols = len(strips)
    ordered = [None] * n_cols
    heads = [root] * n_rows
    used = set()

    def get_next(node, c):
        if c == ' ':
            return root
        return node.get(c, None)

    def search(col_id, heads):
        if col_id == n_cols:
            yield transpose(ordered)
            return
        for i in range(n_cols):
            if i in used:
                continue
            heads1 = [get_next(head, c) for c, head in zip(strips[i].lower(), heads)]
            if any(x is None for x in heads1):
                continue
            used.add(i)
            ordered[col_id] = strips[i]
            yield from search(col_id + 1, heads1)
            used.remove(i)
    yield from search(0, heads)

def transpose(cols):
    return '\n'.join(map(''.join, zip(*cols)))

def parse():
    m = int(input())
    n = int(input())
    strips = []
    for i in range(m):
        strip = input()
        if strip[0] == '"':
            strip = strip[1:1 + n]
        strips.append(strip)
    n_words = input()
    if n_words:
        words = [input() for _ in range(int(n_words))]
    else:
        dict_path = input()
        words = list(map(str.rstrip, open(dict_path)))
    return words, strips

def main():
    words, strips = parse()
    words = list(map(str.lower, words))
    # print(words, strips)
    root = build_trie(words)
    for i, result in enumerate(search_origins(root, strips)):
        print('#{}{}'.format(i, '-' * 80))
        print(result)
        # Uncomment next line if you want only one result
        # break

if __name__ == '__main__':
    main()


Split a grid into a grid Introduction

There is a small village with nothing but a few houses and empty fields.
The local bureaucrats want to divide the village into lots so that each lot contains exactly one house, and the borders of the lots form a nice straight-line grid.
Your task is to determine whether this is possible.

The task

Your input is a rectangular 2D array of bits; 1 represents a house and 0 an empty field.
Its size will be at least 1×1, and it will contain at least one 1.
You can take the input in any reasonable format (nested list of integers, list of strings, multiline string etc).

Your program shall determine whether the array can be divided into grid cells using straight horizontal and vertical lines so that each grid cell contains exactly one 1.
The grid cells may have different sizes and shapes, although they will always be rectangular.
The lines must run from one edge of the array to the opposite edge.

For example, the following is a valid division of an array:

00|0010|01|1
01|0000|00|0
--+----+--+-
00|0000|00|1
01|0010|01|0
--+----+--+-
01|1000|10|1

whereas the following division is not valid, since there are grid cells with no 1s or more than one 1:

00|0010|01|1
--+----+--+-
01|0000|00|0
00|0000|00|1
01|0010|01|0
--+----+--+-
00|1000|10|1

If a valid division exists, you shall output a truthy value, and otherwise a falsy value.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins.

Test cases

[[1]] -> True
[[0,1],[1,0]] -> True
[[1,1],[1,0]] -> False
[[1,0,1],[0,1,0]] -> True
[[1,0],[0,1],[0,1]] -> True
[[1,0,0],[0,0,1],[0,1,1]] -> True
[[1,1,1],[1,1,1],[1,1,1]] -> True
[[1,0,1],[0,1,0],[1,0,0]] -> True
[[1,0,0],[1,0,0],[0,1,1]] -> False
[[0,0,0,0,1],[1,0,0,1,0],[0,0,0,1,0]] -> False
[[0,0,1,0,1],[0,0,0,1,0],[0,0,0,0,0]] -> True
[[1,1,0,0,0],[0,0,0,0,0],[1,0,1,0,0]] -> True
[[1,1,0,1,1],[0,1,0,1,1],[1,0,0,0,0]] -> True
[[0,0,0,0,0,0,0],[0,1,1,1,0,1,0],[0,1,0,0,1,0,0],[0,0,0,0,0,0,1],[0,0,1,0,0,0,1],[1,1,0,1,1,0,0]] -> False
[[1,1,0,0,0,0,0],[1,0,1,1,0,1,0],[0,0,0,0,1,0,0],[0,1,0,1,1,0,0],[1,0,0,0,1,1,0],[0,0,0,0,0,1,0]] -> False
[[0,1,0,1,1,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,0],[1,0,0,1,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,1]] -> True
[[0,1,0,0,1,0,1],[1,0,0,0,1,0,1],[0,0,1,0,1,0,1],[1,0,0,0,1,1,0],[0,0,0,1,1,1,0],[0,1,0,0,1,0,1]] -> True
[[0,1,0,0,1,0,0,1,0],[0,0,0,0,1,1,0,1,0],[1,1,0,0,1,0,0,0,0],[0,0,1,0,1,0,1,0,0],[0,0,1,0,1,0,1,0,0],[0,1,0,0,0,1,0,0,1],[0,1,0,0,0,0,1,0,0]] -> False
[[1,0,1,0,0,1,1,0,1],[0,1,1,0,0,1,1,0,1],[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],[0,1,1,0,1,0,1,0,1],[1,0,1,0,0,1,1,0,1]] -> True

Pyth, 30 29 26 24 23 bytes
sm.Asmmq1ssbCkds./MC./M

Try it online.
I'm sure this will get shorter. This is O(2mn), where m and n are the width and height of the array, but completes the last two test cases in 45 seconds on my laptop on battery (i5-5200U with limited performance).
Outputs the number of solutions.
Explanation
Five-dimensional arrays are really fun to work with.</sarcasm> You are not supposed to understand how this works even with the explanation.
                    ./M    Find all partitions of each row. Now we have a list of rows,
                           each containing the ways to split the row, each containing
                           the parts of the split (3D).
                   C       Transpose. Now we have a list of ways to split the columns,
                           each containing the rows, each containing the parts of the
                           row (3D).
                ./M        Find all partitions of each row list. Now we have a list of
                           ways to split the columns, each containing the ways to split
                           the rows, each containing the bunch of rows, each containing
                           the rows in the bunch, each containing the parts of the row
                           (6D).
               s           Combine the ways to split rows & columns into one array (5D).
 m            d            Do the following for each way to split rows & columns (4D):
     m       k                 Do the following for each bunch of rows (3D):
            C                      Transpose the array. We now have a list of column
                                   groups, each containing the row parts (3D).
      m    b                       Do the following for each column group (2D):
          s                            Combine the row parts in the column group. We now
                                       have the list of cells in this row/column group
                                       (1D).
         s                             Sum the cells.
       q1                              Check if the sum is one.
                                   We now have the list of booleans that tell if each
                                   row/column group is valid (1D).
                               We now have the 2D list of booleans that tell if each
                               row/column group in each bunch of rows is valid. (2D)
    s                          Combine the 2D list of booleans to 1D.
  .A                           Check if all values are truthy; if the split is valid.
                           We now have the validity of each split.
s                          Sum the list to get the number of valid solutions.


Find all problems that equal an integer In this challenge, your job is to write a program that allows a user to enter an integer. Then, the program must find all the possible ways of multiplying two numbers to get the user's integer.
Rules:

The program should not show any problem more than once.
The user should be able to enter any integer.
The program should only show problems that contain 2 numbers.
The shortest program (in Bytes) wins.
It does not matter what order the program outputs the problems in.

Example Output (user enters 20, then the program outputs the problems):

    20

    1 * 20
    2 * 10
    4 * 5

Let's give VIM some love (96 chars)

let n=input('')|for x in range(1,n/2-1)|for y in range(1,n)|if x*y==n|ec x."*".y|en|endfo|endfo

The abbreviations ec, en and endfo stand for echo, endif and endfor respectively.

I was rather disappointed that I couldn't use fo; that expands to fold.


(1) Determine the amount of statues Inspired by this stack of little statues that are currently on my desk at work, given to me by my colleagues from Sri Lanka when they visited The Netherlands:

This is split into two different challenges due to popular demand:
Part 1) Determine the amount of statues (this challenge)
Part 2) Can the statues be stacked?
Challenge 1:
Input:
\$statues\$: a multi-line string (or character matrix), containing only the characters  \n|-# (where the  |-# can be other characters of your own choice)
Output:
The amount of statues in the input.
Statues input example:
      ##|
####    |
# ##
#  #  |##
----  |######
      |   ###
|##   |##   #
|## - |######
    # |####

The | and - represent the bases of the statues. So with the input above, we'll have the following statues:
       ####
       ## #
       ## ##
####   #  ##
# ##  ## ###  ##      #
#  #  ## ###  ##  #   #
----  ------  --  -  --

So the output will be 5.
Challenge rules:

You can use a different consistent character other than #, -, and/or | for the statue if you want ( \n are mandatory, though). Please state which one you've used in your answer if it's different than the defaults.
You are allowed to take the \$statues\$ input in any reasonable format. Can be a multi-line string, a list/array/stream of strings, a character matrix, etc.
You are allowed to pad the statues input with trailing spaces so it's a rectangle.
You can assume statues are always separated by at least one space or blank line from one-another, so something like #|#| or #||# won't be in the input.
You can assume the statues will only have a base at ones side, so a statue like this won't be in the input:

##|
##|
--

It is possible that a smaller statue is within the rectangular boundaries of another oddly shaped statue. For example, this is possible:

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

Statues will never be inside of each other, though. So something like this won't be in the input:

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

You can assume the base determines the width of a statue. So you won't have statues like these in the input:

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

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.

Test cases:
      ##|
####    |
# ##
#  #  |##
----  |######
      |   ###
|##   |##   #
|## - |######
    # |####

Output: 5
__________________________________________________

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

Output: 2
__________________________________________________

      #
|###  #
| #   #
|#### -

Output: 2
__________________________________________________

--- ##|
### ##|
###
### |#

Output: 3
__________________________________________________

####             #####|
# ##
###              |#           |#
#####            |#           |##
-----            |#           |#
                 |#
                 |#
                 |#

Output: 4
__________________________________________________

|# |# |# |# |# #| #| #|

Output: 8
__________________________________________________

|##
|   ##
|#  --

Output: 2
__________________________________________________

      |##
----  |####
# ##
###   |#
      |#  ###|
      |#    #|
      |#   ##|
      |#

Output: 4
__________________________________________________

- |##
#      #
  #| ###
  #| ---

Output: 4
__________________________________________________

#
####
----

--
 #

Output: 2
__________________________________________________
##
##
--

--
##
##

Output: 2

05AB1E, 15 bytes
„-|v€Åγ˜y¢Iø}Š+

Try it online!
Commented:
„-|              # push string literal "-|"
   v        }    # iterate over this string
    €Åγ          #   run-length encode each line of the input / transposed input
                 #   this pushes the chunk elements and the chunk lengths
       ˜         #   flatten the list
        y¢       #   count the chunks of the current character
          Iø     #   push the transposed input to the stack for the second iteration
             Š   # triple-swap: move the transposed input to bottom
              +  # sum both counts


Finding the Value of Words! Introduction
In the land of [Insert cool name here], people don't buy things with money, because everyone has a severe allergy to paper. They pay eachother with words!
But how is that? Well, they give each letter number values:
a=1,b=2,c=3,etc.

(With some other special rules that will be described later)
In this challenge, your task will be to calculate the value of sentences.
Challenge
You will take an input which will be a sentence. You may assume the input has no newlines or trailing spaces. The challenge will be to calculate the value of the sentence, using these rules:
a=1,b=2,c=3,etc.

A capital letter is worth 1.5 times it's corresponding lowercase
letter

H=h*1.5
So, the word
cab

Would be worth c+a+b = 3+1+2 = 6
But the word Cab with a capital c would be worth (c*1.5)+a+b = 4.5+1+2 = 7.5
So if your program input was "Cab" your program would output 7.5

All non alphabetic characters are worth 1.

This is code golf, so shortest answer in bytes wins. Good luck!

Python 3, 71 65 61 bytes

lambda z:sum((ord(s)*1.5**(s<'_')-96)**s.isalpha()for s in z)

By an extraordinary coincidence, (ord(s)-64)*1.5 is equal to ord(s)*1.5-96, so we only have to write -96 once. The rest is pretty straight forward.

Edit: Shaved off some bytes using exponentiation shenanigans.


Match strings with wildcards Problem: given any input string that does not contain null bytes, determine whether or not the input string matches glob as defined below:

null   is disallowed in both string in glob
*      matches zero or more characters
**     is disallowed in glob
?      matches exactly 1 character
[ch]   matches a character class of the specified characters
       to include ] in a class, it must be the first character
[^ch]  matches a character class of all but specified characters
       to include ] in a class, it must be the first character after ^

The empty glob only matches the empty string.

The system glob() on the target platform implements glob where * doesn't match a /, so you can't use it. This has infested all shells. You could try converting to a regex; however this won't be as easy it it looks.

You must specify an encoding for your program. Your program must be valid in that encoding. All bytes including null are allowed in cp437. Your score is the number of characters in your encoding.

Bonus: If your program is expressed in a well-known encoding that uses 6 or fewer bits, your score is multiplied by the number of bits used in the encoding and divided by 7. Your program will be passed its arguments in ASCII in that case.

Your program will receive the string to match or not as the first argument and the glob pattern as the second argument. Your return code must be 0 on match and nonzero on nonmatch.

You may leave it undefined what happens if you get passed a disallowed glob.

Standard loopholes are disallowed; however the following are allowed:

 You may compress your program but it must work if executed directly.
 Binaries are allowed. Submit a disassembly with it so I can read it.
 Using two different chars which look the same is allowed.
 You may use trigraphs (but I can't see how it helps).

Examples:

"w*c*d" matches "wildcard" but doesn't match "wildcards"
"ww*w*d" matches "wwwdwd" but doesn't match "wwd"
"ww*[w-c]?*" matches "www-" and "wwcc" but doesn't match "wwc"
"[a-c]" matches "-" but doesn't match "b"
"^[*][^]]" matches "^*[" but doesn't match "^?[" or "^*]" or "**]"

Common Lisp, 368 340

Encoding is implementation-dependent, but UTF-8 is generally supported among implementations (see also the set of standard characters that must be supported).

(ql:quickload'cl-ppcre)(lambda(s g)(ppcre:scan(do(e(L(coerce g'list))c p)((not L)`(:sequence,@(reverse e):end-anchor))(push(case(setf c(pop L))(#\*'(:regex".*"))(#\? :everything)(#\[(prog1`(,(or(and(char=(car L)#\^)(pop L):inverted-char-class):char-class),@(subseq L 0(setf p(position #\] L :start 1))))(setf L(nthcdr(1+ p)L))))(t c))e))s))

Pretty-printed

(lambda (s g)
  (cl-ppcre:scan
   (do (e
        (l (coerce g 'list))
        c
        p)
       ((not l) `(:sequence ,@(reverse e) :end-anchor))
     (push
      (case (setf c (pop l))
        (#\* '(regex".*")
        (#\? :everything)
        (#\[
         (prog1
             `(,(if (char= (car l) #\^)
                    (prog1 :inverted-char-class (pop l))
                    :char-class)
               ,@(subseq l 0 (setf p (position #\] l :start 1))))
           (setf l (nthcdr (1+ p) l))))
        (t c))
      e))
   s))

Converting to regex is not so hard when using non-string representations of regexes. CL-PPCRE is a regular expression library by Edi Weitz which accepts two ways of defining such expressions:

the usual string-based syntax, or
a more lispy approach using a DSL

Today I answered a question about alternative syntaxes for regular expressions, and this challenge is a good example of why a structured format can be useful instead of strings.

Example

For the following glob, "ww*[w-c]?*", the regular expression being built is described by this form:

(:sequence #\w
           #\w
           (:regex ".*")
           (:char-class #\w #\- #\c)
           :everything
           (:regex ".*"))

And we match "www-". The (:char-class ...) list takes indiviudal charaters, which does not need escaping like it would if I wrote "[w-c]" as a string regex.

Test suite

(loop for (glob match no-match) in
      '(("w*c*d"      ("wildcard")    ("wildcards"))
        ("ww*w*d"     ("wwwdwd")      ("wwd"))
        ("ww*[w-c]?*" ("www-" "wwcc") ("wwc"))
        ("[a-c]"      ("-")           ("b"))
        ("^[*][^]]"   ("^*[")         ("^?[" "^*]" "**]"))
        ("w*\\*s"     ("wild\\ness")  ()))

      for matchp = (lambda(s)(funcall *fun* s glob))

      always (every matchp match)
      never (some matchp no-match))

=> T


Fill in an increasing sequence with as many numbers as possible A list of numbers is called monotonically increasing (or nondecreasing) is every element is greater than or equal to the element before it.

For example, 1, 1, 2, 4, 5, 5, 5, 8, 10, 11, 14, 14 is monotonically increasing.

Given a monotonically increasing list of positive integers that has an arbitrary number of empty spots denoted by ?, fill in the empty spots with positive integers such that as many unique integers as possible are present in the list, yet it remains monotonically increasing.

There may be multiple ways to accomplish this. Any is valid.

Output the resulting list.

  For example, if the input is

?, 1, ?, 1, 2, ?, 4, 5, 5, 5, ?, ?, ?, ?, 8, 10, 11, ?, 14, 14, ?, ?

  it is guaranteed that without the empty spots the list will be
  monotonically increasing

1, 1, 2, 4, 5, 5, 5, 8, 10, 11, 14, 14

  and your task is to assign positive integers to each ? to maximize
  the number of distinct integers in the list while keeping it
  nondecreasing.

  One assignment that is not valid is

1, 1, 1, 1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 5, 8, 10, 11, 14, 14, 14, 14, 14

  because, while it is nondecreasing, it only has one more unique
  integer than the input, namely 3.

  In this example it is possible to insert six unique positive integers and
  keep the list nondecreasing.
  A couple possible ways are:

1, 1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8, 8, 10, 11, 12, 14, 14, 15, 16

1, 1, 1, 1, 2, 3, 4, 5, 5, 5, 5, 6, 6, 7, 8, 10, 11, 13, 14, 14, 20, 200

  Either of these (and many others) would be valid output.

All empty spots must be filled in.

There is no upper limit on integers that can be inserted. It's ok if very large integers are printed in scientific notation.

Zero is not a positive integer and should never be inserted.

In place of ? you may use any consistent value that is not a positive integer, such as 0, -1, null, False, or "".

The shortest code in bytes wins.

More Examples

[input]
[one possible output] (a "*" means it is the only possible output)

2, 4, 10
2, 4, 10 *

1, ?, 3
1, 2, 3 *

1, ?, 4
1, 2, 4

{empty list}
{empty list} *

8
8 *

?
42

?, ?, ?
271, 828, 1729

?, 1
1, 1 *

?, 2
1, 2 *

?, 3
1, 3

45, ?
45, 314159265359

1, ?, ?, ?, 1
1, 1, 1, 1, 1 *

3, ?, ?, ?, ?, 30
3, 7, 10, 23, 29, 30

1, ?, 2, ?, 3, ?, 4
1, 1, 2, 3, 3, 3, 4

1, ?, 3, ?, 5, ?, 7
1, 2, 3, 4, 5, 6, 7 *

1, ?, 3, ?, 5, ?, ?, 7
1, 2, 3, 4, 5, 6, 7, 7

1, ?, ?, ?, ?, 2, ?, ?, ?, ?, 4, ?, 4, ?, ?, 6
1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 6

98, ?, ?, ?, 102, ?, 104
98, 99, 100, 101, 102, 103, 104 *

Haskell, 41 bytes

f takes a list and returns a list, with 0 representing ?s.

f=scanr1 min.tail.scanl(#)0
m#0=m+1
_#n=n

Basically, first scan list from left, replacing 0s by one more than the previous element (or 0 at the start); then scan from right reducing too large elements to equal the one on their right.

Try it online! (with wrapper to convert ?s.)


How many chapters do I have? The Bible is one of the most influential books ever written, and commonly cited as the best selling book of all time. It was written by approximately 40 different authors over hundreds of years before being compiled into it's current form. But what's interesting about The Bible is the way it's divided up. It is split up into 2 different testaments, which are split up into 66 smaller books, which are each split up into smaller chapters, which are each split up into individual verses.

I thought it would be a fun challenge to try to encode the number of chapters in each book in the shortest code possible. So for today's challenge, you must write a program or function that takes one of the books as input, and outputs the number of chapters in that book according to The King James Version.

You may take IO in any reasonable format, for example reading/writing STDIN/STDOUT or a file, function arguments/return values, prompting the user, etc. are all allowed. The input will always be one of the 66 books of The Bible, and only lowercase. This means that if you are given any other input, undefined behavior is allowed. Since there are only 66 possible inputs and outputs, they are all provided here, according to Wikipedia's page on Bible chapters in The King James Version:

genesis         50
exodus          40
leviticus       27
numbers         36
deuteronomy     34
joshua          24
judges          21
ruth            4
1 samuel        31
2 samuel        24
1 kings         22
2 kings         25
1 chronicles    29
2 chronicles    36
ezra            10
nehemiah        13
esther          10
job             42
psalms          150
proverbs        31
ecclesiastes    12
song of solomon 8
isaiah          66
jeremiah        52
lamentations    5
ezekiel         48
daniel          12
hosea           14
joel            3
amos            9
obadiah         1
jonah           4
micah           7
nahum           3
habakkuk        3
zephaniah       3
haggai          2
zechariah       14
malachi         4
matthew         28
mark            16
luke            24
john            21
acts            28
romans          16
1 corinthians   16
2 corinthians   13
galatians       6
ephesians       6
philippians     4
colossians      4
1 thessalonians 5
2 thessalonians 3
1 timothy       6
2 timothy       4
titus           3
philemon        1
hebrews         13
james           5
1 peter         5
2 peter         3
1 john          5
2 john          1
3 john          1
jude            1
revelation      22

Since this challenge is about finding the optimal way to encode every book name and chapter count, using any builtins that give information about The Bible are not permitted. However, since it would be interesting to see which languages have such builtins, feel free to share a second non-competing version along with your answer. Fetching information from external sources is also not permitted (none of the standard loopholes are allowed, but I thought it would be useful to explicitly mention that one).

As usual, this is a code-golf challenge, so try to make the shortest possible program (measured in bytes) as you can. Have fun golfing!

Jelly, 127 bytes

“£ÐgƁ÷ḅ*Wßßɦ*⁷ċṗṿỵ×Ɓṿ⁷ḢQ’b7+\;“BƝ‘
OḄ;407;270;“ọḷḊḲɦ‘%/i@“¡Ṙ×!⁸Ọ5`ỊV-ṙQȷṖÞ(sĿȮ^k³M"ɓmEf¤*0C[ạƇŻȥ#BṚñİmZẓeȦUƈ!ċ€@Ȧʋ)ƙḅyẉ’b158¤ị¢

Try it online!

Test Cases

How it Works

Essentially, this tries to convert the ords of the characters input into a binary value, for example "joel" -> [106, 111, 101, 108]-> 2^3*106 + 2^2*111 + 2^1*101 + 2^0*108.

Then, this value is taken mod 407, then mod 270, then [a few more mods], then mod 160. This is useful because it maps all 66 string inputs to integers between 0 and 158 (lucky on final mod).

The integer is indexed from the integer list “ọḷḊḲɦ...ƙḅyẉ’b158¤ to find the value of n such that the input has the n-th least number of chapters. Joel happens to have the 7-th least number of chapters.

This value of n is further indexed into the list “£ÐgƁ÷ḅ*Wßßɦ*⁷ċṗṿỵ×Ɓṿ⁷ḢQ’b7+\;“BƝ‘ to find the exact number of chapters.

Possible improvement: inputs with the same number of chapters can hash to the same value from the mods (0% collision is not necessary), but I did not account for that in my program to determine the sequence of mods.


Arbitrary Precision Integer Division We will be implementing division for arbitrarily large integers.
This is code-golf.
The task is to write a program or function that implements arbitrary precision integers and Division on them.
Note that many things that might make this very easy are disallowed, please make sure to read through the spec.
Input
You will be given 2 things as input:

a string of base 10 digits, call it \$n\$.
another string of base 10 digits, call it \$m\$

Assume that \$n>m>0\$ meaning that you will never be asked to divide by zero.
Output
You will output two numbers, \$Q\$ and \$R\$ where \$m\times Q+R=n\$ and \$0 \leq R < m\$
Specifications

Your submission should work for arbitrarily large integers (limited by available memory).

You may not use external libraries. If you need an external library for i/o, you may treat it as a built-in. (looking at things like iostream, etc).

If your language has a built-in that trivializes this, you may not use it. This includes (but may not be limited to) built-in types that can handle arbitrary precision integers.

If a language for some reason uses arbitrary precision integers by default, this functionality cannot be used to represent integers that could not be typically stored in a 64 bits.

Input and output MUST be in base 10. It does not matter how you store the numbers in memory or how you perform arithmetic on them, but i/o will be base 10.

You have 15 Seconds to output a result. This is to prohibit iterated subtraction.

The goal here is to actually implement arbitrary precision integers. If for some reason you are able to adhere to the challenge specs and successfully do this without implementing them, well I guess good for you, sounds valid.

Test Cases

In this case, inputs are \$39!\$ and \$30!\$

Input
n = 20397882081197443358640281739902897356800000000
m = 265252859812191058636308480000000

Output
Q = 76899763100160
R = 0

n is the sum of all factorials up to 50, plus 1. m is concatenated numbers up to 20.

input
n = 31035053229546199656252032972759319953190362094566672920420940313
m = 1234567891011121314151617181920

output
q = 25138393324103249083146424239449429
r = 62459510197626865203087816633

n is 205! + 200!. m is how many tears PeterTaylor has made me shed by tearing apart things I post in the sandbox.

Input
n = 271841734957981007420619769446411009306983931324177095509044302452019682761900886307931759877838550251114468516268739270368160832305944024022562873534438165159941045492295721222833276717171713647977188671055774220331117951120982666270758190446133158400369433755555593913760141099290463039666313245735358982466993720002701605636609796997120000000000000000000000000000000000000000000000000
m = 247

Output
q = 1100573825740813795225181252819477770473619155158611722708681386445423816849801159141424129060075102231232666057768175183676764503262931271346408394876267875141461722640873365274628650676808557279259873162169126398101692109801549256156915750794061370041981513180387019893765753438422927286098434193260562682052606153857091520795991080960000000000000000000000000000000000000000000000000
r = 0;

I'll probably add more test cases at some point.
Related
Sounds related, but really isn't