How many cubes can be built task

Your task is to build a structure with \$n\$ cubes. The volume of cubes follow the following sequence (bottom -> top)

\$n^3, (n-1)^3, (n-2)^3,...,1^3\$

input

The total volume of the structure (\$V\$).

output

value of (\$n\$), i.e : The total number of cubes.

\$V = n^3 + (n-1)^3 + .... + 1^3\$

notes

Input will always be an integer.
Sometimes it isn't possible to follow the sequence, i.e : \$V\$ doesn't represent a specific value for \$n\$. In that event return -1, or a falsy value of your choosing (consistency is required though).
This is code-golf so shortest answer in bytes for each language wins.
No answer will be marked accepted for the above mentioned reason.

requests

This is my first challenge on the site so bear with me, and forgive (and tell me about) any mistakes that I made.
Kindly provide a link so your code can be tested.
If you can, kindly write an explanation on how your code works, so others can understand and appreciate your work.

examples

input  : 4183059834009
output : 2022

input  : 2391239120391902
output : -1

input  : 40539911473216
output : 3568

Thanks to @Arnauld for the link to this :

Isn't that nice.

Link to orignial : Link

JavaScript (ES7), 31 bytes

A direct formula. Returns 0 if there's no solution.

v=>(r=(1+8*v**.5)**.5)%1?0:r>>1

Try it online!

How?

The sum \$S_n\$ of the first \$n\$ cubes is given by:

$$S_n = \left(\frac{n(n+1)}{2}\right)^2 = \left(\frac{n^2+n}{2}\right)^2$$

(This is A000537. This formula can easily be proved by induction. Here is a nice graphical representation of \$S_5\$.)

Reciprocally, if \$v\$ is the sum of the first \$x\$ cubes, the following equation admits a positive, integer solution:

$$\left(\frac{x^2+x}{2}\right)^2=v$$

Because \$(x^2+x)/2\$ is positive, this leads to:

$$x^2+x-2\sqrt{v}=0$$

Whose positive solution is given by:

$$\Delta=1+8\sqrt{v}\\
x=\frac{-1+\sqrt{\Delta}}{2}
$$

If \$r=\sqrt{\Delta}\$ is an integer, it is guaranteed to be an odd one, because \$\Delta\$ itself is odd. Therefore, the solution can be expressed as:

$$x=\left\lfloor\frac{r}{2}\right\rfloor$$

Commented

v =>                    // v = input
  ( r =                 //
    (1 + 8 * v ** .5)   // delta = 1 + 8.sqrt(v)
    ** .5               // r = sqrt(delta)
  ) % 1 ?               // if r is not an integer:
    0                   //   return 0
  :                     // else:
    r >> 1              //   return floor(r / 2)

Recursive version, 36 35 bytes

Returns NaN if there's no solution.

f=(v,k=1)=>v>0?1+f(v-k**3,k+1):0/!v

Try it online!

Commented

f = (v,                   // v = input
        k = 1) =>         // k = current value to cube
  v > 0 ?                 // if v is still positive:
    1 +                   //   add 1 to the final result
    f(                    //   do a recursive call with:
      v - k ** 3,         //     the current cube subtracted from v
      k + 1               //     the next value to cube
    )                     //   end of recursive call
  :                       // else:
    0 / !v                //   add either 0/1 = 0 if v is zero, or 0/0 = NaN if v is
                          //   non-zero (i.e. negative); NaN will propagate all the
                          //   way to the final output


ASCII art uncompression from a base-n number This is inspired by an 05AB1E answer by Magic Octupus Urn.

Given two arguments, a positive integer and a string/list of characters:

Translate the number to base-n, where n is the length of the string.
For each character, replace every appearance of the index of that character in the base-n number with that character.
Print or return the new string.

Examples:

Input:
2740, ["|","_"]
2740 -> 101010110100 in base 2
     -> Replace 0s with "|" and 1s with "_"
Output: _|_|_|__|_||

Input:
698911, ["c","h","a","o"]
698911 ->  2222220133 in base 4
       ->  Replace 0s with "c", 1s with "h", 2s with "a", and 3s with "o"
Output -> "aaaaaachoo"

Input:
1928149325670647244912100789213626616560861130859431492905908574660758972167966, [" ","\n","|","_","-"]
Output:
    __   __
   |  |_|  |
___|       |___
-   -   -   -
 - - - - - - -
- - - - - - - -
_______________

Input: 3446503265645381015412, [':', '\n', '.', '_', '=', ' ', ')', '(', ',']
Output:
_===_
(.,.)
( : )
( : )

Rules:

IO is flexible.

You can take the number in any base, as long as it is consistent between inputs
The list of characters has to be 0-indexed though, where 0 is the first character and n-1 is the last

Possible characters can be any printable ASCII, along with whitespace such as tabs and newlines
The given list of characters will have a length in the range 2-10 inclusive. That is, the smallest base is binary and the largest is decimal (no pesky letters here)
Standard loopholes are forbidden
Feel free to answer even if your language can't handle the larger test cases.

As this is code-golf, the shortest code for each language wins. (I know all you golfing languages have one byte built-ins ready to go ;)

05AB1E, 7 6 bytes
gв¹sèJ

Since it was inspired by an 05AB1E answer, an answer given in 05AB1E seems fitting. :)
-1 byte thanks to @Emigna by removing the foreach and doing this implicitly.
Try it online or verify all test cases.
Explanation:

g         # `l`: Take the length of the first (string) input
 в        # And then take the second input in base `l`
          # For each digit `y` of this base-converted number:
  ¹sè     #  Push the `y`'th character of the first input
     J    # Join everything together (and output implicitly)


There's no such thing as a free lunch ...or is there?

Your challenge is to parse my lunch bill, which contains the base price, tips, discounts, coupons, and extras and find out if my lunch was $0 or less. If this is the input:

12.34
15 tip
25 discount
1.5 extra
2 coupon

Then the output might be false. Here's how it works:

12.34 is the base price.

15 tip means to add 15% to the total.

25 discount means to subtract 25% from the total.

1.5 extra means to add 1.5 to the total.

2 coupon means to subtract 2 from the total.

There may be any amount of tips, discounts, coupons, and extras, but there will always be one base price.

Then we do (12.34 * 1.15) * 0.75 + 1.5 - 2 for an output of 10.14. 10.14 is greater than 0, so we output false. My lunch was not free.

Rules

number tip means to add number percent to the total.

number discount means to subtract number percent from the total

number extra means to add number to the total

number coupon means to subtract number from the total

Another example:

10
20 tip
20 discount
2 coupon
2 coupon
1 coupon
50 discount
2.55 coupon

The price is -0.24 ((10 * 1.20 * 0.80 - 2 - 2 - 1) * 0.5 - 2.55), so the output is true (my lunch was free.)

Notes:

Precision must be at least 2 decimal places.
You can take input as a string with newlines (trailing newline optional) or another separation character, or an array/list of the inputs.

JavaScript (ES6), 88 85 bytes

Takes input as an array of strings. Returns 0 for not free or 1 for free.

a=>a.map(s=>([a,b]=s.split` `,t+={e:+a,c:-a,t:x=t*a/100,d:-x}[(b||'e')[0]]),t=0)|t<=0

How it works

Each line is split on the space to get a = amount, b = type of operation. If there's no operation at all (which is the case on the first line), b is set by default to "e" for "extra".

To add the correct amount to the total t, we use an object whose keys are the first letter of the operation:

{
  e: +a,           // extra
  c: -a,           // coupon
  t: t * a / 100,  // tip
  d: -t * a / 100  // discount
}

Note: If the bill consisted of only one element, map() would return a single-element array which would be coerced to an integer when applied the | operator, making the final test fail. But the OP confirmed that this can't happen. (Arrays of 2 or more elements are coerced to 0.)

Demo

let f =

a=>a.map(s=>([a,b]=s.split` `,t+={e:+a,c:-a,t:x=t*a/100,d:-x}[(b||'e')[0]]),t=0)|t<=0

console.log(f([
'12.34',
'15 tip',
'25 discount',
'1.5 extra',
'2 coupon'
]))

console.log(f([
'10',
'20 tip',
'20 discount',
'2 coupon',
'2 coupon',
'1 coupon',
'50 discount',
'2.55 coupon'
]))


Calculate the area of a regular polygon Given an integer, n, where 3 <= n < 2^32, calculate the area of a regular n-gon with an apothem of 1; the formula for which is n * tan(π / n). For those that don't know what the apothem is:

  The apothem of a regular polygon is a line segment from the center to the midpoint of one of its sides.

Output the area of the n-gon as a floating point with no less than 8 decimal places.

Test cases

3
5.1961524227

6
3.4641016151

10
3.2491969623

20
3.1676888065

99
3.1426476062

1697
3.1415962425

15000
3.1415926995

Note: The test cases above include 2 more digits than you are required to output.

Mathematica, 16 bytes
N[Tan[Pi/#]#,9]&

Try it online!
of course mathematica has built-ins for this
Area@*RegularPolygon


Determine the position of a non-negative number in the infinite spiral Definition

The infinite spiral used in this question has 0 on the position (0,0), and continues like this:

16-15-14-13-12
 |           |
17  4--3--2 11
 |  |     |  |
18  5  0--1 10
 |  |        |
19  6--7--8--9
 |
20--21...

It is to be interpreted as a Cartesian plane.

For example, 1 is on the position (1,0), and 2 is on the position (1,1).

Task

Given a non-negative integer, output its position in the spiral.

Specs

Your spiral can start with 1 instead of 0. If it starts with 1, please indicate so in your answer.
Output the two numbers in any sensible format.

Testcases

The testcases are 0-indexed but you can use 1-indexed as well.

input output
0     (0,0)
1     (1,0)
2     (1,1)
3     (0,1)
4     (-1,1)
5     (-1,0)
6     (-1,-1)
7     (0,-1)
8     (1,-1)
9     (2,-1)
100   (-5,5)

Python, 46 bytes

f=lambda n:n and 1j**int((4*n-3)**.5-1)+f(n-1)

Dennis's answer suggested the idea of summing a list of complex numbers representing the unit steps. The question is how to find the number of quarter turns taken by step i.

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

These are generated by int((4*k-n)**.5-1), and then converted to a direction unit vector via the complex exponent 1j**_.


Create a fractal tree What I would like to see is a fractal tree being drawn where the you can input an integer, and the output will be a fractal tree with the entered amount of branch steps.

Rules:

The fractal should be a line fractal tree:
the shape of the fractal should also be the same as this picture.
Each branch should decrease by 25% in width for each time it splits
The final layer of branches should be an 1px wide line
Shortest code wins

Tip: this site might be useful.

Context Free, 82 65 57 characters

rule T{9*[y 1]SQUARE[]2*{f 90}T{s.75y 8r 25}}startshape T

See: http://www.contextfreeart.org/gallery/view.php?id=3384

Golf'd further with help from Context Free Art users minimaleye, MtnViewJohn, and kipling.


Goldbach's conjecture Write a program that prompts the user for an even integer greater than 2.

Given Goldbach’s conjecture that every even integer greater than 2 can
be expressed as the sum of two primes, print out two prime numbers which, when
added together, provide the requested even number.
Edit: the program only has to print A PAIR of primes, not all.
For example:

4 : 2 + 2

6: 3 + 3

8: 3 + 5

10: 5 + 5 or 3 + 7

APL, 34 or 44 bytes
The first version is 34 symbol long and is restricted to characters from the original single-byte APL charsets, such as the one still supported in Dyalog APL:
↑c/⍨n=+/¨c←,∘.,⍨v/⍨~v∊v∘.×v←1↓⍳n←⎕

Explanation:
                               n←⎕   ⍝ ask for a number, store as n
                          v←1↓⍳n     ⍝ generate all integers from 2 to n
                      v∘.×v          ⍝ compute the product table of any two such integers
                v/⍨~v∊               ⍝ select those that don't appear in the product table
         c←,∘.,⍨                     ⍝ generate all possible pairs of these primes
    n=+/¨c                           ⍝ check which pairs have a sum equal to n
↑c/⍨                                 ⍝ take the first that does

The second version is only 22 symbol long, because it exploits the π function to check for prime numbers, but that's only available in NARS2000 which uses Unicode, so the byte count is 44 in UCS-2:
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1

Explanation:
                   ⎕    ⍝ ask for a number N
                  ⍳ -1  ⍝ generate all naturals from 1 to N-1
             (⍪,⌽)      ⍝ arrange it into a table of all pairs of naturals with sum N
     {∧/0π⍵}            ⍝ check which pairs are made of all primes
2⍴(⌿⍨       )           ⍝ return the first pair that does

Examples
(⎕: is the prompt asking for a number)
      2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
      4
2 2
      2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
      6
3 3
      2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
      8
3 5
      2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
      124
11 113


Decode my I2C Stream! From the sandbox!

I2c or TWI, is a 2 way stream that uses 2 signal lines: SDA and SCK. This is used in sensors to communicate between a master and a slave.
So, how does this work? Well, here's the boilerplate:

Input:

1 I2c command represented by 2 strings where - is a high signal, and _ is low. SDA is always the first string.

Output:

The debug info for that command, including weather
it's a READ or WRITE,
which address it's to (in Hex), and
what memory the signal's addressing(in Hex).
if the transmission is invalid, print "Invalid"

How does I2c work, then?

Image from Sparkfun!
An i2c request has 2 9-bit parts. the address and the payload. The address comes first.

A bit is only READ when the clock signal goes from LOW to HIGH. Going from HIGH to LOW is not a valid reading event.

The address is 7 bits, which come after both SDA and SCL are LOW. This is sent by the master.

After the 7th bit, the next is sent by the master, which is the READ Bit. If this bit is HIGH, then it's a READ operation, if the bit is LOW, then it's a WRITE operation.

After the 8 bits, the slave responds with an ACK bit, if the ACK bit is HIGH, then the entire transmission is invalid.

Then, the second transmission is sent.

The first 8 bits represent the data address that the master is READing or WRITEing.

and the final bit is the 2nd ACK bit. If this bit is HIGH, then the entire transmission is invalid.

Examples:

Raw IN: ["--____--__----__----__----__--__--__","___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"]
SDA: --____--__----__--__--__----__--__--__
SCK: ___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
Result: 0 0 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 0
Parse:  addr[22] op:[R] data:[181] success[yes]
out: address:0x16 op:Read data:0xB5

Raw IN: ["--____--__----__------__----__--__--__","___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"]
SDA: --____--__----__------__----__--__--__
SCK: ___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
Result: 0 0 1 0 1 1 0 1 1 1 0 1 1 0 1 0 1 0
Parse:  addr[22] op:[R] data:[181] success[No]
out: invalid
Note: (the ACK bit flipped high);

Raw IN: ["--_-_--__--_-__--_-_-__-_-_-_--__--__-","___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"]
SDA: --_-_--__--_-__--___-__-_-_-_--__--__-
SCK: ___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
Result: 0 0 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 0
Parse:  addr[22] op:[R] data:[181] success[yes]
out: address:0x16 op:Read data:0xB5
Note: (the bit before the change is read.);

Raw IN: ["--_____--___-----___--___--___-----__---____--____","___--_-_--_--_-_--_-_--_-_--_-_--_-_--_-___-_--__-"]
SDA: --_____--___-----___--___--___-----__---____--____
SCK: ___--_-_--_--_-_--_-_--_-_--_-_--_-_--_-___-_--__-
Result: 0  0 1  0  1 1  0 1  0 1  0 1  1 0  1   0 1   0
Parse:  addr[22] op:[R] data:[181] success[yes]
out: address:0x16 op:Read data:0xB5
Note: (Clock signals Don't have to be perfect.);

Raw IN: ["--_____--___-----___--___--___-----__---____--____","___---_-_--_-___-_--__-"]
SDA: --_____--___-----___--___--___-----__---____--____
SCK: ___---_-_--_-___-_--__-
Result: 0   0 1  0   1 0   1
Parse:  Invalid
out: invalid
Note: (They do however, have to match the length of the data dignal.);

Extra rules:

The 0x prefix must be appended to all hex values in the output, as a formality.
The input is strictly - for HIGH and _ for LOW, and will always be 2 separate strings with a separator character.
If both SDA and SCL change at the same time, then the previous bit is read.

This is a code golf, so whoever creates a running program in the least number of bytes wins! Good luck

GNU sed, 427 378 364 + 1 = 428 379 365 bytes

+1 byte for -r flag. Takes colon-separated input. Output format is e.g. a0x16oRd0xB5, where a precedes the address, o precedes the operation (R or W), and d precedes the data.

Why do I do this to myself?

s/^/:/
:Q
s/:.+:$|::./E/
s/:(.).(.*):_-/\1:x\2:x/
s/:./:/g
tQ
s/(.{7})(.)(.)(.*)(.):/#\3\1%\2#\5\4:/
/#-|E/{z;iinvalid
q}
s/#./#/g
:R
s/[:%]/!u0;%0123456789ABCDEF,/
:A
s/((-)|_)!/!\2/
s/!-(u+)(.+);/!\1\2;\1/
:
/u%/!bZ
s/F;/;0/
t
s/(.);(.*%.*\1)(.)/\3\2\3/
s/u;/u1/
s/u(u*)%/;\1%/
b
:Z
s/!(u+)/!\1\1/
/#!/!bA
s/#!u+(.+);.+,/\1/
/:/bR
s/(..)(.)/a0x\1o\2d0x/
y/-_/RW/

Try it online!

Explanation

The code works in two phases. In phase 1 we turn the two signals into a single binary string. This is the easy part.

# Prepend a `:`
s/^/:/
:Q
  # Check for length mismatch (one string exhausted before the other)
  s/:.+:$|::./E/

  # If the first two characters of SCK are `_-`, record first character of SDA
  # and discard second; replace each pair with `x` so we can unconditionally...
  s/:(.).(.*):_-/\1:x\2:x/

  # ...consume a character from each signal
  s/:./:/g

  # If we did a substitution, branch to :Q
  tQ

If this was our input:

--_____--___-----___--___--___-----__---____--____:___--_-_--_--_-_--_-_--_-_--_-_--_-_--_-___-_--__-

...we now have this:

__-_--_-_-_--_-_-_:

Before phase 2, we reformat this to make it a little easier to work with:

# Reformat `.......ma........b:` to `#a.......%m#b........:`
s/(.{7})(.)(.)(.*)(.):/#\3\1%\2#\5\4:/

# Check if ACK high or length mismatch; if either, print error and quit
/#-|E/{z;iinvalid
q}

# Delete ACK bits
s/#./#/g

Now we have:

#__-_--_%-#-_--_-_-:

In phase 2, we convert each run of _ and - (0 and 1) to a hexadecimal number. Because sed doesn't do math, this is almost half of the code. It actually takes each binary digit, converts it to unary, and then increments the hexadecimal number once for each unary digit.

:R
# Initialize: u = magnitude (unary 1); 0 = running sum (decimal); lookup table
s/[:%]/!u0;%0123456789ABCDEF,/

:A
  # Take the least-significant bit; if it's 0 drop it
  s/((-)|_)!/!\2/

  # If 1 (-), remove it and copy current magnitude (`u+`) after `;`
  s/!-(u+)(.+);/!\1\2;\1/

  # Increment number for each `u` after `;`
  # e.g. 12;uu -> 13uu -> 13;u -> 14u -> 14;
  :
    # No more `u`s, branch to :Z
    /u%/!bZ

    # Carry: 1F;u -> 1;0u -> 20u -> 20;
    s/F;/;0/
    t

    s/(.);(.*%.*\1)(.)/\3\2\3/
    s/u;/u1/

    # Drop a `u`; branch to `:`
    s/u(u*)%/;\1%/
    b

  :Z
    # Double magnitude: !uu3 -> !uuuu3
    s/!(u+)/!\1\1/
    # If there are binary digits left, branch to :A
    /#!/!bA

# Clean up
s/#!u+(.+);.+,/\1/

# Branch to :R for the second number
/:/bR

# Format output
s/(..)(.)/a0x\1o\2d0x/
y/-_/RW/

Before formatting, we have:

16-B5

All that remains is to add a prefix to each hexadecimal number change the operation (- or _) to read (R) or write (W), giving us:

a0x16oRd0xB5


Tips for golfing in Scala What general tips do you have for golfing in Scala? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Scala (e.g. "remove comments" is not an answer). Please post one tip per answer.

(This is a shameless copy of ... in Python)

The shortest way of repeating something is with Seq.fill.

1 to 10 map(_=>println("hi!")) // Wrong!
for(i<-1 to 10)println("hi!") // Wrong!
Seq.fill(10)(println("hi!")) // Right!


Binary Images of Triangle Counts My challenges tend to be a little bit hard and unattractive. So here something easy and fun.

Alcuin's sequence

Alcuin's sequence A(n) is defined by counting triangles. A(n) is the number of triangles with integer sides and perimeter n. This sequence is called after Alcuin of York.

The first few elements of this sequence, starting with n = 0 are:

0, 0, 0, 1, 0, 1, 1, 2, 1, 3, 2, 4, 3, 5, 4, 7, 5, 8, 7, 10, 8, ...

For instance A(9) = 3, because the only triangles with integer sides and perimeter 9 are 1 - 4 - 4, 3 - 3 - 3 and 2 - 3 - 4. You can see the 3 valid triangles down below.

There are some quite interesting pattern in this sequence. For instance A(2*k) = A(2*k - 3).

For more information, see A005044 on OEIS.

Challenge

But your challenge is about the binary representation of these numbers. If we convert each sequence number to it's binary representation, put them in column vectors and line them up, it creates a quite interesting binary picture.

In the following picture you can see the binary representation of the sequence numbers A(0), A(1), ..., A(149). In the first column you can see the binary representation of A(1), in the second column the representation of A(1), and so on.

You can see some sort of repeating pattern in this picture. It even looks kinda like fractals, if you look for instance at the image with the sequence numbers A(600), A(601), ..., A(899).

Your job is to generate such an image. Your function, your script will receive two integer 0 <= m < n, and it has to generate the binary image of Alcuin's sequence A(m), A(m+1), A(m+2), ..., A(n-2), A(n-1). So the input 0, 150 generates the first picture, the input 600, 900 the second picture.

You can use any popular graphics format you want. Let's say every format that can be converted to png using image.online-convert.com. Alternatively, you may display the image on screen. No leading white rows are allowed!

This is code-golf. So the shortest code (in bytes) wins.

Mathematica, 126 122 121 89 bytes

Image[1-Thread@IntegerDigits[l=Round[(#+3#~Mod~2)^2/48]&/@Range@##,2,⌈2~Log~Max@l⌉]]&

This defines an unnamed function taking the two integers as parameters and displaying the image on screen. It plots each square as a single pixel, but if you like you can actually zoom in.

I'm now using an explicit formula given in the OEIS article (first one in the Mathematica section, thanks to David Carraher for pointing that out). It's also blazingly fast now.

Here is the indented code with a few comments:

Image[1-Thread@IntegerDigits[   (* 3. Convert each number to padded binary, transpose
                                      invert colours, and render as Image. *)
    l = Round[
      (#+3#~Mod~2)^2/48
    ] & /@ Range@##,            (* 1. Turn input into a range and get the Alcuin
                                      number for each element. *)
    2,
    ⌈2~Log~Max@l⌉               (* 2. Determine the maximum number of binary digits. *)
]] &

Here is the output for 0, 600:


Dice from Changing Random Generator Introduction

You are given a random integer generator with the following implementation

The first invocation always returns 1.
The second invocation returns a random integer between 1 and 2.
The third invocation returns a random integer between 1 and 3.
The nth invocation returns a random integer between 1 and n, inclusive.

Based on the above function, write a random dice generator that is perfectly random, returning a value between 1 and 6 (inclusive) with equal probability.

Rules

Your program/function should result in a random integer between 1 and 6, inclusive, in some usable form, i.e., to standard output or as a function return value.
The ascending random number generator above can be defined as a "free" function in your program (i.e., doesn't count toward your character count), or a separate script/program that is executed as needed, assuming the state (n) is persistent between calls.
Assume that no more than 1000 dice rolls will ever be requested in a single use case of your program, and the initial random number generator can be reset to 1 at the end of 1000 dice rolls to avoid overflow of n.
Your program may not use any other source of random numbers except the ascending random generator defined above.  You may of course request multiple random numbers from the random number generator for each single dice roll output.
This is code-golf, so winner is shortest answer or most votes in the event of a tie.  If you can generate 1000 dice rolls using less than 1000 generated random numbers, give yourself a 10-point efficiency bonus.

Example

./asc-rand
1 # random integer between 1 and 1
./asc-rand
1 # random integer between 1 and 2
./asc-rand
3 # random integer between 1 and 3
./asc-rand
4 # random integer between 1 and 4

# dice-gen generates random dice based on output of asc-rand program.
./dice-gen
3
./dice-gen
6
./dice-gen
5
./dice-gen
1

Python, 31 chars

Similarly to scleaver, define the generator like this:

from random import randint
n=0
def r():
    global n;n+=1
    return randint(1,n)

Then a function to return dice rolls:

D=lambda:eval('r(),'*6)[-1]%6+1

Call D() any time you need a uniformly random dice roll.


Read a retro display Art stolen from What size is the digit?

7-segment digits can be represented in ASCII using _| characters. Here are the digits 0-9:

 _     _  _       _   _  _   _   _
| | |  _| _| |_| |_  |_   | |_| |_|
|_| | |_  _|   |  _| |_|  | |_|  _|

Your job is to parse the art into normal numbers.

Notes on numbers

Each digit has a different width.

1 has a width of 1
3 and 7 are 2 wide
245689 and 0 are all 3 wide

Also between each digit is one char of padding. Here is the full char set:

 // <-- should be one space, but SE formatting messed it up
|
|
-------------
 _
 _|
|_
-------------
_
_|
_|
-------------

|_|
  |
-------------
 _
|_
 _|
-------------
 _
|_
|_|
-------------
_
 |
 |
-------------
 _
|_|
|_|
-------------
 _
|_|
 _|
-------------
 _
| |
|_|

Input

Input can be either from the console or as a string arg to a function.

Output

Output is either put to the console or is returned from the function.

Examples:

  _  _   _
|  |  | |_
|  |  | |_|
1776

 _   _     _
 _| | | | |_
|_  |_| | |_|
2016

   _       _
| |_| |_| |_
|  _|   |  _|
1945

   _   _   _   _   _   _
| | | | | | | | | | | | |
| |_| |_| |_| |_| |_| |_|
1000000

 _     _  _       _   _  _   _   _
| | |  _| _| |_| |_  |_   | |_| |_|
|_| | |_  _|   |  _| |_|  | |_|  _|
0123456789

This is code-golf so shortest byte count wins!

Ruby, 184 bytes

a=0
l=$<.map{|x|x.bytes.map{|y|y==32?0:1}+[0]*2}
(0..l[0].count-1).map{|i|l[0][i]+2*l[1][i]+4*l[2][i]}.each{|x|
x>0?(a=x+2*a):(p Hash[[40,6,32,20,18,26,42,8,44,64].zip(0..9)][a];a=0)}

Explanation

takes the input from stdin
converts the strings to binary sequences, 1/0 for segment on/off
encodes columns to 3bit binary number
encodes sequences of 3 bit numbers to 9 bit numbers, use '0' columns as stop symbols
use a lookup table to convert the 9 bit numbers to digits

This is my first code-golf. Thanks for the fun!


Find the largest number n positions away from n A sequel to this question.

Task

Given an array of positive integers, find the largest element k for which:

  There exists some positive integer distance n, so that the element in the array located n places to the left or right from k equals n.

The array is guaranteed to contain at least one element satisfying this condition.

The shortest code (in bytes) wins. You may choose whichever I/O format you like.

Example

Given the input

[4, 6, 7, 9, 3, 6, 5, 7, 2]

The eligible values are:

The 4, as there is a 7 located 7 positions to its right
The first 6, as there is a 3 located 3 positions to its right
The 3, as there is a 4 located 4 positions to its left
The 5, as there is a 2 located 2 positions to its right
The second 7, as there is a 3 located 3 positions to its left.

Of these values, the largest is 7.

Test cases

[1, 13] → 13
[2, 9, 8, 3, 72, 2] → 8
[5, 28, 14, 5, 6, 3, 4, 7] → 14
[1, 3, 5, 15, 4, 1, 2, 6, 7, 7] → 7
[5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3] → 5
[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5] → 10

05AB1E, 21 bytes

vyN+Ny-})¹gL<Ãv¹yè})Z

Explanation

v      }               # for each num in input
 yN+                   # push index + num
    Ny-                # push index - num
        )              # wrap stack in a list
         ¹gL<Ã         # remove indices outside the range of input
              v¹yè})   # get list of elements in input at the remaining indices
                    Z  # get max

Try it online!


What year will it be in n seconds? You are given an integer n as input, and, regardless of the current date, must return the calendar year (Gregorian calendar, other calendars not allowed) taking place n seconds from now.
Rules

You may not assume that the current year is 2021. In other words, imagine a user testing your solution in five years.
Standard loopholes forbidden.
Shortest answer in bytes wins.
Built-in date functions are allowed.
You must also support negative numbers.
On the topic of the year zero: Your answer must follow the ISO specifications, meaning there is a year zero.
You may assume that the input is always an integer within bounds of your language number system.
If your language's date functions take leap seconds into account, then follow your language, otherwise do not take leap seconds into account.

Examples (in this case, measured at the time of writing, which is February 15, 2021)
100000000000 -> 5190
1000 -> 2021
54398643 -> 2022
54398643234 -> 3744
-100000000000 -> -1148

Ohm v2, 5 bytes
υ!+υy

Try it online!
Explanation:
υ!+υy
υ!     get the current timestamp in seconds
  +    sum with the implicit input
   υy  get the year from the resulting timestamp


Visual Long Multiplication There is a nice way to perform long multiplication for two integers without having to do anything but counting, which occasional gets shared around the internet. You write the digits of each number as a bunch of slanted lines, with the two numbers at a 90 degree angle. Then you can simply count the intersections in the separate columns that arise. A diagram will probably clarify this. Here is an example for calculating 21 * 32:

If you google for "visual/graphical long multiplication" you'll find a lot more examples.

In this challenge, you are to generate these diagrams using ASCII art. For the same example, the output would look like this:

   \ /
    X /
 \ / X /
\ X / X
 X X / \ /
/ X X   X /
 / X \ / X
  / \ X / \
     X X
    / X \
     / \

It's probably easiest to figure out the construction rules for these from some examples (see below), but here some details:

Intersecting segments are X, non-intersecting segments of the lines are / or \.
There should be exactly one segment after the outermost intersections.
There should be exactly one segment between intersections belonging to different digits. If there are zero-digits, these will result in consecutive / or \ segments.
You have to support any positive input (at least up to some reasonable limit like 216 or 232), and any digits from 0 to 9. However, you may assume that there neither leading nor trailing 0s.
You must not print extraneous leading whitespace or leading or trailing empty lines.
You may print trailing whitespace but it must not exceed the diagram's axis-aligned bounding box.
You may optionally print a single trailing newline.
You may choose in which order you take the two input numbers. However, it you must support arbitrary numbers for either orientation, so you can't choose something like "The larger number is given first".
If you're taking input as a string, you can use any non-digit separator between the two numbers.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

This is code golf, the shortest answer (in bytes) wins.

Examples

1*1
\ /
 X
/ \

2*61
 \ /
\ X /
 X X /
/ X X /
 / X X /
  / X X /
   / X X
    / X \ /
     / \ X
        X \
       / \

 45*1
         \ /
        \ X
       \ X \
      \ X \
     \ X \
      X \
   \ / \
  \ X
 \ X \
\ X \
 X \
/ \

21001*209
       \ /
        X /
       / X
      / / \
   \ / /   \ /
    X /     X /
 \ / X     / X /
\ X / \   / / X /
 X X   \ / / / X /
/ X \   X / / / X /
 / \ \ / X / / / X /
    \ X / X / / / X /
     X X / X / / / X /
    / X X / X / / / X
     / X X / X / / / \
      / X X / X / /
       / X X / X /
        / X X / X
         / X X / \
          / X X
           / X \
            / \


Self-Identifying Coordinates Write a program or function that, given an integer n, construct an array with n dimensions of n length, where each element is an identifier of its own coordinates. That is, starting with one array, populate it with n arrays, where each of those contain n more arrays, up to a depth of n-1. The elements of the deepest arrays are the coordinates describing where they are in the full array.

Some examples in case my explanation was confusing.

n = 1

["1"]

n = 2

[
 ["11", "12"],
 ["21", "22"]
]

n = 3

[
  [
    ["111","112","113"],
    ["121","122","123"],
    ["131","132","133"]
  ],
  [
    ["211","212","213"],
    ["221","222","223"],
    ["231","232","233"]
  ],
  [
    ["311","312","313"],
    ["321","322","323"],
    ["331","332","333"]
  ]
]

Here, "321" means it is the 1st element of the 2nd element of the 3rd array.

Rules:

Coordinates and dimension (n) can be either 0 or 1 indexed
You may assume n is single digit, below 10 for both indexing options to prevent ambiguous outputs
IO is flexible.

In particular, coordinates can be arrays, strings etc. as long as they are clear. "321" => [3,2,1]
Output can be integers in base 10 with or without leading zeroes.
Coordinates can be in reverse order if you wish, as long as it is consistent. "321" => "123"
Output doesn't necessarily have to be an array structure in your language. As long as there's clear distinct markers for the start of an array, end of an array and for separating elements.
The output for n=1 can just be 1
If your output is atypical, make sure to explain the format.

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

Dyalog APL, 5 3 bytes

⍳⍴⍨

-2 bytes thanks to FrownyFrog

Try it online!

⍳ gives all the indices given the shape of an array. e.g. 2 3.
⍴ reshapes the right arg to be the size of the left arg. ⍨ makes both be the right arg.


Decorate Pascal's Triangle Although what is a Pascal's triangle is well-known and we already can generate it, the task is now different:
Output \$n\$ first lines of the Pascal's triangle as colored bricks.
Color number is computed as maximal power of \$d\$, that divides the needed-to-color element or \$7\$ if power is more than \$7\$.
Numbered colors are (\$0\$-based): default, red, green, yellow, blue, magenta, cyan, white (default color is 0th, red is 1st, .. white is 7th).

Any space-filling (I mean not .,' or " or smth small) character
can be used for bricks, even '\u2588'.
Whitespace before or after the bricks are optional.
Brick horizontal length (\$1\$ or \$2\$) is your choice.
You may choose any convenient output method -- ansi text or graphics or HTML or whatever
If you choose output letters or color numbers instead of coloring the triangle itself, you should specify in the text of your answer which character corresponds to which color, but output wouldn't look so nice)

Input Integers \$n\$ and \$d>1\$ in any convenient method.
This is code-golf, the shortest code in each language wins.

C (gcc),  157 153 143 139  135 bytes
Saved several bytes thanks to @AlexeyBurdin
Saved  4  8 more bytes thanks to @ceilingcat
Outputs with ANSI colors.

long p,a,s,c,L;f(n,d){for(a=0;c=a++-n;puts(""))for(;p=c<a;printf(c<0?" ":"\e[3%dm@@",L),s=++c<1?1:s*a/c-s)for(L=0;p*=d,L<7&s%p<1;L++);}

Try it online! (no colors on TIO)
Example output for \$f(40,2)\$

Formula
At row \$r\$ and column \$c-1\$, we have:
$$P_{r,c-1}={r\choose c-1}=\frac{r!}{(c-1)!(r-c+1)!}$$
On the same row and the next column \$c\$, we have:
$$\begin{align}P_{r,c}={r\choose c}&=\frac{r!}{c!(r-c)!}\\
&=\frac{r-c+1}{c}\times\frac{r!}{(c-1)!(r-c+1)!}\\
&=\frac{r-c+1}{c}\times P_{r,c-1}\\
&=\frac{r+1}{c}P_{r,c-1}-P_{r,c-1}\end{align}$$
which is translated as s = s * a / c - s in the C code (with \$a=r+1\$).
Commented
long p, a, s, c, L;               // declare a few 64-bit integers
f(n, d) {                         // n = number of rows, d = colorization parameter
  for(a = 0; a++ < n; puts(""))   // for a = 1 to n, with a linefeed added after each
    for(                          // iteration:
      c = a + ~n;                 //   for c = a - n - 1 to a - 1:
      p = c < a;                  //
      printf(                     //     update the output after each iteration:
        c < 0 ?                   //       if c is negative:
          " "                     //         just append a space
        :                         //       else:
          "\e[3%dm@@",            //         append the ANSI color code, followed by '@@'
        L                         //       set the 2nd digit of the color code
      ),                          //
      s = ++c < 1 ? 1             //     increment c; set s to 1 while c is less than 1
                  : s * a / c - s //     then, update s to s * a / c - s
    )                             //
      for(                        //       compute the color L:
        L = 0;                    //         start with L = 0
        p *= d,                   //         multiply p by d
        L < 7 & s % p < 1;        //         stop if L = 7 or p does not divide s
        L++                       //         increment L
      );                          //
}                                 //


Attraction Between Words Newton's theory of gravitation says that the gravitational force between two point masses is

 F=(Gm1m2)/ r2

Where

G is the gravitational constant: 6.674×10−11 N · (m/kg)2
m1 is the mass of the first object
m2 is the mass of the second object
r is the distance between their centers of mass

Challenge

You need to simulate the pull between two words. Each lowercase letter has mass given by its position in the alphabet. Capital letters have twice the mass of their lowercase counterparts! You will be given a string containing two words separated by several spaces, as well as a positive integer number of seconds, s. Output what the string would look like after s seconds.

Info

Because words are abstract they have a different set of units and constants

Mass: WMU (Word Mass Unit) - equal to the mass of the letter 'a'.
Distance: em, the length of one character.
Force:  NW (Word Newton) = WMU · em/s2
Gravitational Constant: G = 1 Nw · (em/WMU)2

The first character corresponds to the position 0 on the x-axis.
All calculations should be done with as much precision as possible, only at the end do you round to the nearest em.
You do not need to use calculus, you just need to recalculate the F every second, automatically apply the new acceleration to the velocity, and after a second apply the velocity to the position (see example).
Once two words collide with each other (like    catdog   ), they don't move any further.

Center of Mass

The center of mass of a word can be found with the formula:

Where M is the total mass of the word, mi is the mass of a letter, and ri is the position of the letter.

Example:

(Note: Although this example doesn't show it, remember that capital letters have twice the mass of their lowercase counterparts.)

Input: cat      dog, 2

First what are the positions of each word? "cat" starts at position 0 and "dog" starts at position 9, so

xc = 0 and xd = 9

Next, let's find the center of mass of "cat".

It has a mass of 24 WMU (3+1+20).
Rc = 1/24(3*0+1*1+20*2) = 41/24 = 1.70833 em
So unsurprisingly the center of mass is very close to the letter 't'.

Now let's get the center of mass of "dog"

Rd = 1/26(4*9+15*10+7*11) = 263/26 = 10.11538 em
So the center of mass for dog is close to the letter 'o', slightly towards 'g'.

Now we can calculate the force between the two words.

F = 24*26/(10.11538-1.70833)2 = 8.82871 Nw

Now we need to apply this force to both words and get their accelerations

ac = 8.82871/24 = .36786 em/s2
ad = -8.82871/26 = -.33957 em/s2

Following the rules above, we apply the acceleration to the velocity, so

vc = .36786 em/s
vd = -.33957 em/s

Then we apply the velocity to the position, so after one second,

xc = .36786 em
xd = 9 -.33957 = 8.66043  em.
Rc = 1.70833+.36786 = 2.07619 em
Rd = 10.11538-.33957 = 9.77581 em

Now we repeat the procedure one more time with the new positions:

F = 24*26/((9.77581)-(2.07619))2 = 10.52558 Nw
ac = 10.52558/24 = .43857 em/s2, ad = 10.52558/26 = -.40483 em/s2
vc = .36786 + .43857 = .80643 em/s, vd = -.33957 - .40483 = -.74440 em/s
xc = .36786 + .80643 = 1.17429 em, xd = 8.66043 - .74440 = 7.91603 em
Rc = 2.07619 + .80643 = 2.88262 em, Rd = 9.77581 - .74440 = 9.03141 em

So we end up with "cat" at x=1.17429 and "dog" at x=7.91603.

We round those to the nearest integer so "cat" goes to position 1 and "dog" goes to position 8, so the output is  cat    dog

Handling Collisions

Remember that the new acceleration is immediately added to the velocity every second. Therefore, if two words collide at certain time, use algebra to find the point of collision. Take this example:

word 1 is 4 letters long (||w1|| = 4)
word 2 is 4 letters long (||w2|| = 4)
x1 = 3, x2 = 8
v1 = 2,v2 = -6

Solve 3 + (4-1) + 2t = 8 - 6t. t = .25s. The position of the collision is xcol = 6.5. Therfore, the collision should appear as occurring between x = 6 and x = 7, as such

   ####@@@@    .

The explicit formula for the positions of the words after a collision is

x1 = floor(xcol)-||w1||+1
x2 = floor(xcol)+1

Python 3, 556 bytes
Thanks to FryAmTheEggman and Sherlock9 for some bytes
s,E,a,b,e=str.split,enumerate,lambda c:ord(c)%32*-~c.isupper(),lambda w:sum(map(a,w)),' '
def j(w):z,y=map(len,s(w));h=w.count(e);return sum(i*a(x)for i,x in E(w)if i<z)/b(w[:z]),sum(i*a(x)for i,x in E(w)if i>=y+h)/b(w[-y:])
def f(w):x,v=j(w);m,n=map(b,s(w));return m*n/(x-v)**2
def q(w):x,v=s(w);return f(w)/b(x),-f(w)/b(v)
def p(w,t):
 x,v=q(w);c,d=x,v;m,n=map(b,s(w));r,u=j(w);g,h=r,u;
 for i in range(t):r+=x;u+=v;f=m*n/(r-u)**2;c,d=f/m,f/n;x+=c;v+=d
 return int(r-g),int(1+h-u)
def g(w,t):x,y=p(w,t);u,v=s(w);return e*x+u+e*(len(w)-len(u+v)-x-y)+v+e*y

g(w,t) takes the string (w) and the time (t), and returns the result. The other functions are helpers.
Try it online (prints out *s instead of spaces so that it is more visible)


Generate combinations that add up to a target value Challenge

Suppose you have a list of numbers, and a target value. Find the set of all combinations of your numbers which add up to the target value, returning them as list indices.

Input and Output

The input will take a list of numbers (not necessarily unique) and a target summation number. The output will be a set of non-empty lists, each list containing integer values corresponding to the position of the values in the original input list.

Examples

Input: values = [1, 2, 1, 5], target = 8
Output: [ [0,1,3], [1,2,3] ]

Input: values = [4.8, 9.5, 2.7, 11.12, 10], target = 14.8
Output: [ [0,4] ]

Input: values = [7, 8, 9, -10, 20, 27], target = 17
Output: [ [1,2], [0,3,4], [3,5] ]

Input: values = [1, 2, 3], target = 7
Output: [ ]

Scoring

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

JavaScript (ES6), 96 bytes

Takes input in currying syntax (list)(target).

a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s))

Test cases

This would fail on the 2nd test case if 4.8 and 10 were swapped because of an IEEE 754 precision error -- i.e. 14.8 - 4.8 - 10 == 0 but 14.8 - 10 - 4.8 != 0. I think this is fine, although there may be a more relevant reference somewhere in meta.

let f =

a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s))

console.log(JSON.stringify(f([1, 2, 1, 5])(8)))
console.log(JSON.stringify(f([4.8, 9.5, 2.7, 11.12, 10])(14.8)))
console.log(JSON.stringify(f([7, 8, 9, -10, 20, 27])(17)))
console.log(JSON.stringify(f([1, 2, 3])(7)))

Commented

a => s =>                 // given an array a[] of length N and an integer s
  a.reduce((b, _, x) =>   // step #1: build the powerset of [0, 1, ..., N-1]
    [ ...b,               //   by repeatedly adding to the previous list b[]
      ...b                //   new arrays made of:
      .map(y =>           //     all previous entries stored in y[]
        [...y, x]         //     followed by the new index x
      )                   //   leading to:
    ],                    //   [[]] -> [[],[0]] -> [[],[0],[1],[0,1]] -> ...
    [[]]                  //   we start with a list containing an empty array
  )                       // end of reduce()
  .filter(b =>            // step #2: filter the powerset
    !b.reduce((p, i) =>   //   keeping only entries b
      p - a[i],           //     for which sum(a[i] for i in b)
      s                   //     is equal to s
    )                     //   end of reduce()
  )                       // end of filter()


Write a formatted Morse code cheatsheet Challenge:

Write a program that produces the following output:

. E   .. I   ... S   .... H
                     ...- V
             ..- U   ..-. F
                     ..--
      .- A   .-. R   .-.. L
                     .-.-
             .-- W   .--. P
                     .--- J
- T   -. N   -.. D   -... B
                     -..- X
             -.- K   -.-. C
                     -.-- Y
      -- M   --. G   --.. Z
                     --.- Q
             --- O   ---.
                     ----

This is a formatted table of the Morse codes of the letters from A to Z. Each column is separated by three spaces.

There are four missing slots, which are used by international character sets. Your program must write a space there.

The output must consist of ASCII spaces, dots, dashes, uppercase letters and newlines (either LF or CRLF) only.

Your program accepts no input.

The following is a sample Python program that produces the desired output:

b = "."
out = []
last = 0
ch = "EISHVUF ARL WPJTNDBXKCYMGZQO  "
cx = 0
while b:
    if last >= len(b):
        print("   ".join(out))
        out = ["   ", "    ", "     ", "      "][0:len(b) - 1]
    out.append(b + " " + ch[cx])
    cx += 1
    last = len(b)
    if len(b) < 4:
        b += "."
    elif b[-1] == ".":
        b = b[0:-1] + "-"
    else:
        i = len(b) - 1
        while b[i] == "-":
            i -= 1
            if i < 0:
                break
        if i < 0:
            break
        b = b[0:i] + "-"
print("   ".join(out))

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

Python 3.6, 201 197 193 187 bytes

for i in range(16):print('   '.join(i%k and' '*(2+j)or f'{i//k:0{j}b}'.replace(*'0.').replace(*'1-')+' '+'ETIANMSURWDKGOHVF L PJBXCYZQ  '[2**j-2+i//k]for j,k in zip((1,2,3,4),(8,4,2,1))))

Uses some formatting, unpacking and A000918 magic.


Decompose a permutation into cycles There is a well-known theorem that any permutation can be decomposed into a set of cycles.  Your job is to write the shortest possible program to do so.

Input:

Two lines.  The first contains a number N, the second contains N distinct integers in the range [0,N-1] separated by spaces.  These integers represent a permutation of N elements.

Output:

One line for each cycle in the permutation.  Each line should be a space-separated list of integers in cycle order.

Cycles can be output in any order, and each cycle can be output starting at any position.

Example 1:

8
2 3 4 5 6 7 0 1

This input encodes the permutation 0->2, 1->3, 2->4, 3->5, 4->6, 5->7, 6->0, 7->1.  This decomposes into cycles like this:

0 2 4 6
1 3 5 7

An equally valid output would be

5 7 1 3
2 4 6 0

Example 2:

8
0 1 3 4 5 6 7 2

valid output:

0
1
4 5 6 7 2 3

C 145 134 Characters

N,A[999],i,j,f;main(){gets(&i);for(;~scanf("%d",A+N);)N++;for(;j<N;j++,f=f&&!puts(""))while(i=A[j]+1)f=printf("%d ",j),A[j]=-1,j=--i;}

http://www.ideone.com/BrWJT


Check if simple regex matches string A simple regex is either:

_ (which matches the empty string)
Any lowercase letter a to z (which matches that letter)
r*, where r is a regex (which matches r any number of times)
(r|s), where r and s are regexes (which matches either r or s)
(r+s), where r and s are regexes (which matches r followed by s)

Note that due to the recursive definition, * can occur multiple times in a row.

Here are some examples of regexes and their matches:

(a+b) matches only ab
((a|_)+b*) matches , a, b, ab, bb, abb, but not baaa, aab
(c+(o+((l+(o+(u|_)))+r))) matches only color and colour
(a|b)* matches only strings containing letters a and b (so , ab, bab, but not abc)
(_***|(a+b***)) matches only the empty string or a followed by any number of bs.

Your task is to write a program that takes such a regex and a string of lowercase letters, and outputs whether or not the regex matches the entire string (output should be as described here).

The shortest code in bytes wins.

Haskell, 203 bytes

Nobody had done this by implementing a small regex engine yet, and I felt like it had to be done. This obviously won't win. but I'm hoping it will inspire someone to write an even more golfed regex engine.

I've rewritten my solution to avoid directly parsing the regular expression into its AST. Instead, the parsing process constructs a function that is used to match a string against the input regex.

The main function is (&) :: String -> String -> Bool which takes a string representation of a regex and a string to test, returning a boolean value. This calls to the next function which handles most of the work in parsing the regex and matching the string.

Function p :: String -> ([String] -> [String], String) takes a string representation of a regex and returns as the first element of a tuple a function that returns a list of all possible unmatched suffixes of strings in the input list after satisfying the regex parsed from the input string. The regex fully matches the string if the empty string is contained in the list of possible unmatched suffixes.

r&s=elem""$fst(p r)[s]
p(c:t)|c>'`'=t% \s->[t|h:t<-s,c==h]|c>'^'=t%id|(l,o:t)<-p t,(r,_:u)<-p t=u%last(r.l:[\s->r s++l s|o>'+'])
m#s=s++filter(`notElem`s)(m s)
('*':t)%m=t%until(\s->s==m#s)(m#)
s%m=(m,s)

Try it online!

To get rid of one byte, I replaced import Data.List; m#s=nub$s++m s with m#s=s++filter(`notElem`s)(m s). These functions aren't equivalent if there are duplicate elements in either s of m s. The new function does, however, remove all elements from m s that already exist in s, so until still terminates once no new suffixes are discovered by the application of m.

Ungolfed Code

import Data.List

match :: String -> String -> Bool
match r s =elem ""$(fst $ parseRegex r)[s]

parseRegex :: String -> ([String] -> [String], String)
parseRegex ('_':t) = parseKleene id t
parseRegex (c:t) | c >= 'a' = parseKleene (>>=p) t
  where p (c':t')| c==c' = [t']
        p _ = []
parseRegex ('(':t) =
  let (l, (o:t')) = parseRegex t in
  let (r, (_:t'')) = parseRegex t' in
  parseKleene (if o=='+' then (r.l) else (\ss-> (r ss)++(l ss))) t''

parseKleene :: ([String] -> [String]) -> String -> ([String] -> [String], String)
parseKleene p ('*':t) = parseKleene p' t
  where
    p' ss
      | ss' <- nub$ p ss,
        ss /= ss' = ss ++ (p' ss')
      | otherwise = ss
parseKleene p s = (p,s)

GolfScript, 198 bytes

I was able to beat my Haskell solution by implementing the first algorithm I tried in GolfScript instead of Haskell. I don't think it's interesting enough for a separate answer, so I'll just leave it here. There are likely some golfing opportunities since I learned GolfScript just for this.

This solution is in the form of a block that expects the test string on the top of the stack followed by the regex string.

{[.;]\1+{(.96>{0[\]}{2%0{r\(\r\:s;[@]s(;\}i}{if}:i~\{(.3%}{;\2[\]\}until[.;]\+\}:r~\;{.{(.{.4%{2%{)@\m\)\;m}{)\;{.@.@m 1$|.@={\;}{\o}i}:o~}i}{;)@.@m@@\)\;m|}i}{;(:c;;{,},{(\;c=},{(;}%}i}{;}i}:m~""?}

Try it online!


Consonance or dissonance? Given two note names, you are to write a program that determines if the interval formed by these two notes is consonant or dissonant.

Introduction

In Western music, there are only 12 "different" tones. Their names, sorted from lowest to highest, are these: C, C#, D, D#, E, F, F#, G, G#, A, A#, B. The sequence is cyclical, i. e. it continues with another C after the B, infinitely.

The distance between two tones is called an interval. The interval between any two notes that are adjacent in the series above (e. g. C — C# or E — F) is called a semitone. The interval between more distant notes is defined as the number of semitone steps needed to get from the first to the second (while possibly wrapping around the sequence). Some examples: D to E = 2 semitones, C to G = 7 semitones, B to D# = 4 semitones (this wraps around the sequence).1

Now, these intervals are divided into two categories: consonant (pleasantly sounding if you play the two notes at once) and dissonant (not so much).

Let's define the consonant intervals to be: 0, 3, 4, 5, 7, 8 and 9 semitones.

The rest of them is dissonant, namely: 1, 2, 6, 10 and 11 semitones.

The Challenge

Write a "program" (in the usual broad sense of the word: a function is perfectly OK) to do the following:

Take two note names (strings from the sequence above) as an input. You may take them however you like (from stdin, as arguments, separated by whatever you want, even feel free to take them as a list of characters (e. g. ["C","#"]). However, you may not assign any other names to the notes (especially you may not number them from 0 to 11 and use the numbers).
For you music geeks out there, the notes will be specified without the octave. In this case, it also does not matter in which order the notes come and which is lower and which is higher. Finally, you don't need to handle any names not in the list above. No other enharmonics like E#, no flats, double-alterations and so on.
Pick any two different values. Your program must output one of them whenever the interval formed by the two notes in the input is consonant, and the other if they are not. (Could be True and False, but even π and e if you want :))
This is a code-golf. The shortest program in bytes in each language wins. Have fun!

Examples and Test Cases

Note 1    Note 2    Output    Interval [semitones]
  C          D     Dissonant   2
  A#         A#    Consonant   0
  G          D     Consonant   7 (wraparound)
  D#         A     Dissonant   6
  F          E     Dissonant   11
  A          C     Consonant   3

I don't add more of them since there aren't any particularly treacherous cases in this.

This is a first challenge of mine, so any constructive criticism is warmly welcome :—). If you find the theory explanation sloppy, feel free to ask questions. Finally, please do not tell me that this is a dupe of this or this. I made sure it's not. (The latter is quite similar but more complex. I thought that putting up a little simpler challenge will make it easier for people to join.)

1: I tried to simplify this explanation as far as I could. There's a lot more theory around intervals. Please don't bash me for leaving it out.

Jelly, 21 bytes

Takes input as a list of two strings. Returns 0 for dissonant or 1 for consonant.

OḢ6×%21_Lµ€IA“¬ɠṘ’æ»Ḃ

Try it online!

OḢ6×%21_Lµ€IA“¬ɠṘ’æ»Ḃ   - main link
         µ€             - for each note             e.g. ["A#", "C"]
O                       -   convert to ASCII codes  -->  [[65, 35], 67]
 Ḣ                      -   keep the first element  -->  [65, 67]
  6×                    -   multiply by 6           -->  [390, 402]
    %21                 -   modulo 21               -->  [12, 3]
       _L               -   subtract the length     -->  [12, 3] - [2, 1] = [10, 2]
           IA           - absolute difference       -->  8
             “¬ɠṘ’      - the integer 540205
                  æ»    - right-shift               -->  540205 >> 8 = 2110
                    Ḃ   - isolate the LSB           -->  2110 & 1 = 0

Making-of

We first should note that the function F that we're looking for is commutative: for any pair of notes (A, B), we have F(A, B) = F(B, A).

Since there are not too many possible inputs and only 2 possible outputs to deal with, it must be possible to find a rather simple hash function H, such that |H(A) - H(B)| produces a limited range of values and is collision-free for all possible pairs of notes (A, B) with respect to the expected output.

We're going to test the set of functions H(mul, mod), which are defined as:

H(mul, mod)(s) = ((ORD(s[0]) * mul) MOD mod) - LEN(s)

Where ORD(s[0]) is the ASCII code of the first character of the note and LEN(s) is the length of the note (2 if there's a '#' and 1 if not).

Below is a commented version of the JS code that was used to find a couple of valid pairs (mul, mod) and the resulting bitmasks. There are many possible solutions, but * 6 % 21 is the shortest one with this method.

// all 12 notes
note = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];

// reference implementation that takes 2 notes
// and returns 0 for dissonant or 1 for consonant
F = (a, b) =>
  +!~[1, 2, 6, 10, 11].indexOf((note.indexOf(a) - note.indexOf(b) + 12) % 12)

for(mul = 1; mul < 100; mul++) {
  for(mod = 1; mod < 31; mod++) {
    // hash function
    H = s => s.charCodeAt() * mul % mod - s.length;

    table = {};

    // for all possible pairs of notes (a, b)
    if(note.every(a => note.every(b => {
      // compute the table index
      idx = Math.abs(H(a) - H(b));

      // and the expected result
      res = F(a, b);

      // if the slot is empty, store the correct value
      if(table[idx] === undefined) {
        table[idx] = res;
        return 1;
      }
      // else, make sure that the correct value is already there
      return table[idx] == res;
    }))) {
      // if all tests pass: translate the table into a binary mask
      for(n = 0, msk = 0; n < 31; n++) {
        msk |= (table[n] || 0) << n;
      }
      // and display the result
      console.log('mul ' + mul + ', mod ' + mod + ' --> ' + msk);
    }
  }
}


This Question Has _____ Views Inspired by this Youtube Video from Tom Scott.

Write a program or function that prints the current amount of views this question has.

That's it.

Your program may only access the stack exchange api, any other websites are disallowed.

Output

An integer with the exact amount of views this question has at the moment. Outputs with the k for thousand are disallowed.

05AB1E, 46 42 36 bytes
Reading from the question-URL: 36 bytes
’ƒËŠˆ.Â‚‹º.ŒŒ/q/’žYì•3X&•«.w'Ž‡¡1èþ¨

-6 bytes thanks to @CommandMaster, by reading from this question's URL instead of the API
No direct TIO, since the .w builtin (to access a website) is disabled on TIO. But:
’ƒËŠˆ.Â‚‹º.ŒŒ/q/’žYì•3X&•«

Try this part online to see the generation of the URL.
'Ž‡¡1èþ¨

Try this part online to see the extraction of the amount of views from the HTML content. (Input doesn't contain the entire HTML content, because the TIO URL would extend 65k+ characters and be too big to post, haha.. xD)
Reading from the API: 46 42 bytes
•3X&•’¸¸.Â‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’žYì.w'š‹¡Åsþ

No direct TIO, since the .w builtin (to access a website) is disabled on TIO. But:
•3X&•’¸¸.Â‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’žYì

Try this part online to see the generation of the API-URL.
'š‹¡Åsþ

Try this part online to see the extraction of the amount of views from the JSON.
Explanation:

’ƒËŠˆ.Â‚‹º.ŒŒ/q/’
              # Push dictionary string "codegolf.stackexchange.com/q/"
 žY           # Push builtin "https://"
   ì          # And prepend it in front of the url
    •3X&•     # Push compressed integer 203590 (the id of this question)
         «    # Append it to the url
          .w  # Access this URL and read its contents
'Ž‡          '# Push dictionary string "wed"
   ¡          # Split the HTML on this word
    1è        # Get the second item (at index 1)
              #  (i.e. ` 119 times">\n                    <span class="fc-light mr2">Vie`)
      þ       # Only leave the digits (i.e. 1992)
       ¨      # And remove the last digit (2), that was part of the class
              # (after which it is output implicitly as result)

•3X&•         # Push compressed integer 203590 (the id of this question)
 ’¸¸.Â‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’
              # Push dictionary string "api.stackexchange.com/questions/ÿ?site=codegolf",
              # where the `ÿ` is automatically filled with this integer
  žY          # Push builtin "https://"
    ì         # And prepend it in front of the url
     .w       # Access this URL and read its contents
'š‹          '# Push dictionary string "count"
   ¡          # Split the JSON on this word:
              #  (i.e. `...,"view_count":14,"answer_count":2,...` will be split to
              #   [`...,"view_`, `":14,"answer_`, `":2,...`])
    Ås        # Pop and only leave the middle item (i.e. `":14,"answer_`)
      þ       # Pop and only leave its digits (i.e. 14)
              # (after which it is output implicitly as result)

See this 05AB1E tip of mine (sections How to use the dictionary? and How to compress large integers?) to understand why ’ƒËŠˆ.Â‚‹º.ŒŒ/q/’ is "codegolf.stackexchange.com/q/"; •3X&• is 203590; 'Ž‡ is "wed"; ’¸¸.Â‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’ is "api.stackexchange.com/questions/ÿ?site=codegolf"; and 'š‹ is "count".


Title Keywords in Context This challenge is based on a problem described in D. Parnas, On the criteria to be used in decomposing systems into modules, and elaborated upon in J. Morris, Real Programming in Functional Languages.

Write a program or function which takes a list of book titles from stdin or as an argument, in a reasonable, convenient format for your language. For example,

Green Sleeves
Time Was Lost

or

("Green Sleeves";"Time Was Lost")

Return or print to stdout an alphabetized list of the keywords, showing their context within the original titles by enclosing each keyword in angle braces (< and >). As with input, output can be in a reasonable format which is convenient for your language- newline-separated lines, a list of strings, etc:

<Green> Sleeves
Time Was <Lost>
Green <Sleeves>
<Time> Was Lost
Time <Was> Lost

Titles will consist of a series of keywords separated by a single space. Keywords will contain only alphabetic characters. Keywords are to be sorted lexicographically. Titles will be unique, and keywords will be unique within each title but the same keyword may exist in several titles. If a keyword exists in more than one title, the output should list each appearance in an arbitrary order. For example, given this input:

A Dugong
A Proboscis

A valid output would be either:

<A> Proboscis
<A> Dugong
A <Dugong>
A <Proboscis>

Or:

<A> Dugong
<A> Proboscis
A <Dugong>
A <Proboscis>

This is code-golf- the winner is the shortest solution in bytes. Standard loopholes are disallowed.

Pyth, 25 24 22 bytes
VSsm,Rdcd\ QAN:HGjG"<>

Try it online.
Takes input as an array of lines, like ["Green Sleeves","Time Was Lost"].
Explanation
VSsm,Rdcd\ QAN:HGjG"<>   implicit: Q = evaluated input

   m       Q                   map input lines:
       cd\                         split input line to words
    ,Rd                          replace each word by pair [word, entire line]
  s                          concatenate results for all input lines
 S                         sort the array of pairs lexicographically
V                        loop over the array
            AN             assign the word to G and the corresponding line to H
                 jG"<>       put the word between <>
              :HG          replace the word by the above in the line and print


Jelly, 10 8 bytes

Thanks to Dennis for saving 2 bytes.

^\Ḅ‘^H$B

Input and output are lists of 0s and 1s.

Try it online!

Explanation

The inverse of the Gray code is given by A006068. Using this we don't need to generate a large number of Gray codes to look up the input. One classification of this sequence given on OEIS is this:

a(n) = n XOR [n/2] XOR [n/4] XOR [n/8] ...

Where the [] are floor brackets. Consider the example of 44 whose binary representation is 101100. Dividing by 2 and flooring is just a right-shift, chopping off the least-significant bit. So we're trying to XOR the following numbers

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

Notice that the nth column contains the first n bits. Hence, this formula can be computed trivially on the binary input as the cumulative reduction of XOR over the list (which basically applies XOR to each prefix of the list and gives us a list of the results).

This gives us a simple way to invert the Gray code. Afterwards, we just increment the result and convert it back to the Gray code. For the latter step we use the following definition:

a(n) = n XOR floor(n/2)

Thankfully, Jelly seems to floor the inputs automatically when trying to XOR them. Anyway, here is the code:

^\          Cumulative reduce of XOR over the input.
  Ḅ         Convert binary list to integer.
   ‘        Increment.
    ^H$     XOR with half of itself.
       B    Convert integer to binary list.


An Array of Challenges #2: Separate a Nested Array Note: This is #2 in a series of array-manipulation challenges. For the previous challenge, click here.

Separating Nested Lists

  To separate values in a nested list, flatten it, and then wrap each value so it is at the same nested depth as before.

That is to say, this list:

[1, [2, 3], [4, 4, [5, 2], 1]]

Would become:

[1, [2], [3], [4], [4], [[5]], [[2]], [1]]

The Challenge

Your task is to write a program which takes any nested list of positive integers (within your language's limits) and performs this separation operation.

You may submit a function which takes the list as an argument, or a full program which performs I/O.

As this is code-golf, the shortest submission (in bytes) wins!*

*Standard golfing loopholes are banned. You know the drill.

Test Cases

Input lists will only ever contain integers in your language's standard integer size. To avoid languages' constraints preventing them from competing, values will not be nested at depths of more than 10.

You may assume that input will not have empty sub-lists: for example - [[5, []]] will not be given. However, the main list could be empty.

[]            ->  []

[[1, 2]]      ->  [[1], [2]]
[3, [4, 5]]   ->  [3, [4], [5]]
[3, [3, [3]]] ->  [3, [3], [[3]]]
[[6, [[7]]]]  ->  [[6], [[[7]]]]
[[5, 10], 11] ->  [[5], [10], 11]

Don't hesitate to leave a comment if I've missed out a corner case.

Example

I threw together a quick (ungolfed) Python 3 solution as an example - you can test it on repl.it.

Mathematica, 24 21 bytes

##&@@List/@#0/@#&/@#&

or one of these:

##&@@List/@#&/@#0/@#&
##&@@List@*#0/@#&/@#&
##&@@List/@#&@*#0/@#&

Explanation

The reason this is so short is that it's basically a recursion that doesn't require an explicit base case.

There's a lot of syntactic sugar here, so let's start by ungolfing this. & denotes an unnamed function left of it, whose argument is written as #. Inside this function #0 refers to the function itself, which allows one to write unnamed recursive functions. But let's start by giving the inner function a name and pulling it out:

f[x_] := ##& @@ List /@ f /@ x
f /@ # &

The other important syntactic sugar is f/@x which is short for Map[f, x] i.e. it calls f on every element of x. The reason f[x_] := ... f /@ x doesn't lead to infinite recursion is that mapping something over an atom leaves the atom unchanged without actually calling the function. Hence, we don't need to check for the base case (current element is an integer) explicitly.

So the function f first recurses down to the deepest list inside x, at which point f/@ becomes a no-op. Then we call use ##& @@ List /@ on that. Mapping List over the list simply wraps each element in a separate list, so {1, 2, 3} becomes {{1}, {2}, {3}}. Then we apply ##& to it, which means the head (i.e. the outer list) gets replaced by ##&, so this turns into ##&[{1}, {2}, {3}]. But ##& simply returns it's arguments as a Sequence (which you can think of as an unwrapped list, or a sort of "splat" operator in other languages).

So ##& @@ List /@ turns a list {1, 2, 3} into {1}, {2}, {3} (kind of, that last thing is actually wrapped in the head Sequence, but that vanishes as soon as we use the value anywhere).

That leaves the question why f itself isn't already the solution to the challenge. The problem is that the outermost list should be treated differently. If we have input {{1, 2}, {3, 4}} we want {{1}, {2}, {3}, {4}} and not {{1}}, {{2}}, {{3}}, {{4}}. My original solution fixed this by passing the final result as a list of arguments to Join which would restore the outer level of lists, but this one just skips the outer level by using f itself in a map on the output. Hence f is only applied to the individual elements of the outermost list and never gets to touch that list.

As for the other three solutions, the first one simply applies the recursion outside of f which works just as well. The other two solutions avoid a repeated Map operation by first composing two functions and then mapping the result only once.


Haskell, 59 bytes

a#((b:c):r)=b*p(a++map tail r)+(c:a)#r
_#_=0
p[]=1
p l=[]#l

This does a Laplace-like development along the first column, and uses that the order of the rows doesn't matter. It works for any numeric type.

Input is as list of lists:

Prelude> p [[1,2],[3,4]]
10


Separate my integers Introduction

In the field of mathematics known as topology, there are things called separation axioms.
Intuitively, you have a set X and a collection of subsets of X, which we can think of as properties.
The system is well separated, if one can distinguish between all items of X based on their properties.
The separation axioms formalize this idea.
In this challenge, your task is to check three separation axioms, given X and the list of properties.

Input

Your inputs are an integer n ≥ 2, and a list of lists T of integers.
The integers in T are drawn from X = [0, 1, ..., n-1].
The lists in T may be empty and unsorted, but they will not contain duplicates.

Output

Your output is one of four strings, determined by three separation axioms, each stronger than the last.
There are other axioms, but we stick with these for simplicity.

Suppose that for all distinct x and y in X, there exists a list in T containing exactly one of them.
Then X and T satisfy axiom T0.
Suppose that for all distinct x and y in X, there exist two lists in T, one of which contains x but not y, and the other contains y but not x.
Then X and T satisfy axiom T1.
Suppose that the two lists above also contain no common elements.
Then X and T satisfy axiom T2.

Your output is one of T2, T1, T0 or TS, depending on which of the above conditions holds (TS means none of them do).
Note that T2 is stronger than T1, which is stronger than T0, and you should always output the strongest possible axiom.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test cases

2 [] -> TS
2 [[],[1]] -> T0
2 [[0],[1]] -> T2
3 [[0],[0,1,2],[1,2]] -> TS
3 [[],[0],[0,1],[2]] -> T0
3 [[0],[0,1],[2,1],[0,1,2]] -> T0
3 [[0],[0,1],[2,1],[2,0]] -> T1
6 [[0,2,4],[0,3,5],[1,2],[3,4,5]] -> TS
6 [[0,2,4],[0,3,5],[1,2],[2,5],[3,4,5]] -> T0
6 [[0,2,4],[0,3,5],[1,2],[2,5],[3,1],[3,4,5]] -> T1
6 [[0,1],[0,2,3],[1,4],[2,4],[2,3,5],[1,3],[4,5]] -> T2


Shortest self-modifying code to wish a happy New Year! Your code just has to print "Happy 2013".
However, if it detects that it's 2014, it has to modify itself (as a running process!!) and print "Happy 2014" instead.

By self-modifying I mean the running process must really modify itself: it should alter its own instructions while it is executing.

Shortest code wins.

-10% size bonus if it's general, so it works for 2015, etc.

Sorry if the task excludes some languages or systems where it's not possible...

Bash / shell script (35 chars - 10% = 31.5)
I think this shell script counts as self-modifying:

$ eval "y()(echo Happy `date +%Y`)";y
Happy 2013
$

At least, it does modify its own function y:

$ set | grep -A3 '^y ()'
y ()
{
    ( echo Happy 2015 )
}
$

@manatwork suggested eval "y()(date +Happy\ %Y)";y, which produces the desired output, but I'm not sure if this counts as self-modifying, to the extent that it self-modifies with the current year.  The generated function is as follows, which won't be a different function on a yearly basis:

y ()
{
    ( date +Happy\ %Y )
}

If it does count, then the score is:
Bash / shell script (29 chars - 10% = 26.1)

A lot of entries don't seem to make any attempt to self-modify.  If we lift this restriction for shell-script, then we can do this which weighs in at:
15 chars - 10% = 13
date +Happy\ %Y


Positional Bathroom Etiquette Background

Bathroom Etiquette, when pertaining to the available urinals, states that the next urinal to be filled in should be the one that minimizes the total discomfort. The total discomfort equation is given by the following set of equations:

dist(x,y) = linear distance between person x and person y in Urinal Units
discomfort(x) = sum(1/(dist(x,y)*dist(x,y))) for all persons y excluding person x
total_Discomfort = sum(discomfort(x)) for all x

A more in depth paper dealing with a similar (not the exact same) problem can be found here: (Thanks to @Lembik for alerting me to this amazing whitepaper!)

Input/Output

Given an input of a empty and full urinals, output the resulting set of urinals with the addition of one person. If there is a tie for a position the urinals should fill in left to right. The output should be in the same format as the input.

If given a case with full urinals, return the input.
The input will always have at least one urinal defined.

Test Cases

INPUT     -> OUTPUT
1000001   -> 1001001
101010101 -> 111010101
100       -> 101
00000     -> 10000
1111111   -> 1111111
0100      -> 0101
101000    -> 101001

Rules

This is code-golf, so shortest code in bytes wins. Standard loop-holes are forbidden.

MATL, 19 18 17 bytes
lyf!Gn:-H_^Xs&X<(

Try it online! Or verify all test cases (slightly modified code).
Explanation
It suffices to compute the distance from each potential new position to the already occupied ones. The remaining distances are do not depend on the potential new position, and so constitute a constant term, which can be ignored.
Let's take input [1 0 0 0 0 0 1] as an example.
l      % Push 1
       % STACK: 1
y      % Take input implicitly. Duplicate from below
       % STACK: [1 0 0 0 0 0 1], 1, [1 0 0 0 0 0 1]
f!     % Indices of nonzero elements, as a column array
       % STACK: [1 0 0 0 0 0 1], 1, [1 7]
Gn:    % Push [1 2 ... n], where n is input size (array of possible positions)
       % STACK: [1 0 0 0 0 0 1], 1, [1; 7], [1 2 3 4 5 6 7]
-      % Matrix with all pairs of differences
       % STACK: [1 0 0 0 0 0 1], 1, [1; 7], [0 -1 -2 -3 -4 -5 -6;
                                             6  5  4  3  2  1  0]
H_^    % Raise each entry to -2
       % STACK: [1 0 0 0 0 0 1], 1, [   Inf 1.0000 0.2500 0.1111 0.0625 0.0400 0.0278;
                                     0.0278 0.0400 0.0625 0.1111 0.2500 1.0000    Inf]
Xs     % Sum of each column
       % STACK: [1 0 0 0 0 0 1], 1, [Inf 1.04 0.3125 0.2222 0.3125 1.04 Inf]
&X<    % Index of minimum. Takes the first if there is a tie
       % STACK: [1 0 0 0 0 0 1], 1, 4
(      % Assign: write 1 at the position of the minimizer
       % STACK: [1 0 0 1 0 0 1]
       % Implicitly display


Draw the XNOR digital timing diagram Below is a (schematic) Digital timing diagram, for the XNOR logic gate.

    ┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐
A ──┘ └─┘ └─┘     └─┘ └─┘ └─┘   └──
  ┌───┐ ┌───┐ ┌─┐ ┌─────┐   ┌─┐ ┌─┐
B ┘   └─┘   └─┘ └─┘     └───┘ └─┘ └
    ┌─────┐   ┌─┐   ┌─┐   ┌───┐
X ──┘     └───┘ └───┘ └───┘   └────

Your goal is to reproduce it exactly as depicted.

Rules:

You can either print it or return a multiline string;
Arbitrary number of traling and/or leading newlines are allowed;
Trailing (but not leading !) whitespace is allowed;
If you can not use the extended ASCII box-drawing characters,
you may substitute them for the unicode equivalents (at no byte penalty).

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

Binary Representation

For your convenience, binary representation of the diagram above is as follows:

INP A=0101011101010110
INP B=1101101011100101
  ___
X=A⊕B=0111001001001100

Sample Output

Sidenote

While working on this question, I've implemented two different bash solutions for it, one is 122 characters/bytes long (as depicted above), and another one is exactly 100 bytes long.

I do not have plans to post them (as I don't normally post answers to my own questions), so that is just for reference.

I also believe that at least some sub-100 byte solutions are possible.

05AB1E, 101 bytes + 5 UTF-8 bytes = 116 Total Bytes = 106 Bytes

(LEGACY 05AB1E VERSION, NO LONGER ON TIO)

•=(Ín§Àoà`œ¯_eè8y1ÜŸ,Ú®:¹$:,õKA–x[Âì0ãXÔfz}y×ì¹Ï½uEÜ5äÀTë@ºQÈ™ñó:ò…Eä•6B"102345"" ┌─┐└┘"‡6ävyN" A B X"èì}»

Try it online!

The compression:

•=(Ín§Àoà`œ¯_eè8y1ÜŸ,Ú®:¹$:,õKA–x[Âì0ãXÔfz}y×ì¹Ï½uEÜ5äÀTë@ºQÈ™ñó:ò…Eä•
# Pattern, converted to base-6 in base-6=214.

111023102310222223102310231022231112251425142511111425142514251114221022231022231023102222231110231023151114251114251425111114222514251411102222231110231110231110222311111225111114222514222514222511142222
# Actual base-6 pattern.

1110231023102222231023102310222311
1225142514251111142514251425111422
1022231022231023102222231110231023
1511142511142514251111142225142514
1110222223111023111023111022231111
1225111114222514222514222511142222
#Pattern split into chunks of 34.

   ┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐
 ──┘ └─┘ └─┘     └─┘ └─┘ └─┘   └──
 ┌───┐ ┌───┐ ┌─┐ ┌─────┐   ┌─┐ ┌─┐
 ┘   └─┘   └─┘ └─┘     └───┘ └─┘ └
   ┌─────┐   ┌─┐   ┌─┐   ┌───┐
 ──┘     └───┘ └───┘ └───┘   └────
# Pattern after replacing 0,1,2,3,4,5 with appropriate blocks.

The conversion:

6B                                   # Convert back to base-6.
  "102345"" ┌─┐└┘"‡                  # Replace numbers with appropriate counterparts.
                   6ä                # Split into 6 equal parts (the rows).
                     vy           }  # For each row (chunk).
                       N" A B X"èì   # Push label at index [i], prepend to line.
                                   » # Print all separated by newlines.

Using the CP-1252 encoding.


Slowing Down Sped Up Videos Summary
Videos which are sped up every time a particular word is said exist for everything from the Bee Movie to the classic Rick Roll. The goal for this challenge is to figure out how much you'd have to slow down the sped-up video in order to match the duration of the original video.
For example, the original Bee Movie has a duration of 95 minutes. The sped up version is 5:40 or ~5.667 minutes. 95/5.667 = 16.76. We'd have to play the sped up version 16.76x slower in order for the overall duration to match the original movie.
Inputs
Your program must take in 3 inputs:

The duration of the original video (Bee Movie was 95 minutes)
The speedup factor per occurence (Bee Movie was 15% or .15)
A list of timestamps of occurrences (Bee movie has more than I care to look up/list)

The exact way these are passed in is flexible: 3 separate parameters is my default assumption, but if you want to take in a single list of values and pop the duration/speedup factor off the front that's fine, or take a single string in JSON or whatever format floats your boat, etc.
For the duration: seconds, minutes, or some builtin duration type are all fine.
For the speedup factor of the bee movie, any of 15, .15, or 1.15 could be used to represent the 15% speedup.
You can assume the occurrences are ordered in the most convenient manner, but there can be duplicate values (such as multiple characters talking over one another in a movie).
Output
A scaling factor to make the durations of the original and sped-up video match. The exact format is flexible.
Examples
{"duration": 10, "speedup-factor": 2, "occurrences": [1,2,3,4,5,6,7,8,9]} -> {"slowdown-factor": 5.004887585532747}
{"duration": 500, "speedup-factor": 1.15, "occurrences": [1,2,3, ..., 497, 498, 499]} -> {"slowdown-factor": 65.21739130434779}
{"duration": 100, "speedup-factor": 3, "occurrences": [0]} -> {"slowdown-factor": 3}
{"duration": 100, "speedup-factor": 3, "occurrences": [0, 0, 0]} -> {"slowdown-factor": 27}
{"duration": 100, "speedup-factor": 100, "occurrences": [99.99]} -> {"slowdown-factor": 1.0000990098}

Notes: First two generated programmatically with 100/(sum(1/(2**i) for i in range(10))) and 500/(sum(1/(1.15**i) for i in range(500))). 4th example: 3 * 3 * 3 = 27x speedup, occurring right at the start of the video. Last example calculated by hand with 100/(99.99 + .01/100)
Note
I've kept most of the examples fairly simple, but I believe they cover all the relevant edge cases (a program which solves all of them should be totally correct). If I've left things ambiguous or difficult to parse, let me know and I'll add comments!

Python 2, 47 bytes

lambda m,r,l:m/reduce(lambda u,x:u/r+x-x/r,l,m)

Try it online!
Takes timestamps sorted in descending order.
The idea is to compute the video duration as a polynomial in the inverse speedup rate 1/r using Horner's method with coefficients given by the sorted timestamps. This avoids needing to explicitly take the differences of consecutive timestamps. We then divide the duration of the original video by the resulting duration to get the desired slowdown factor.
53 bytes

f=lambda m,r,l:l==[]or r/(l.pop()*(r-1)/m+1/f(m,r,l))

Try it online!
An attempt to write the function fully recursively. While the new duration itself has a clean recursive expression, we want to get the slowdown factor which divides the original duration by the new duration, and this is messier to express recursively.


Generate a Kolakoski sequence Definition1

  A Kolakoski sequence is a self-describing infinite sequence {kn} of alternating blocks of 1's and 2's, given by the following rules:

  k0 = 1
  kn = the length of the (n+1)'th block

The Task

Given a positive integer n, generate the first n elements of the Kolakoski sequence.

Details

Input will be provided as a single command line argument n. Please write a full program that will print the first n elements of the Kolakoski sequence (in order) to STDOUT, with each element separated by your favorite whitespace.

Scoring

Lets count source code bytes this time with all whitespace included. Fewest number of bytes wins. In the event of a tie, the solution with the earliest submission time wins.

The Sequence2

1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, ...

References

John Smith, Ariel Scolnicov, yark. "Kolakoski sequence" (version 3). PlanetMath.org. Freely available at http://planetmath.org/KolakoskiSequence.html.

The Online Encyclopedia of Integer Sequences http://oeis.org/A000002

Other resources

Kolakoski Sequence at Wikipedia http://en.wikipedia.org/wiki/Kolakoski_sequence
Kolakoski Sequence at Wolfram MathWorld http://mathworld.wolfram.com/KolakoskiSequence.html

J - 23 char

A little late to the party, but I'd like to bust out a neat little J trick here.

1($1+2|I.)^:_~".>2{ARGV

Given input N, this verb operates by executing N&($1+2|I.) on a starting argument of 1 until it reaches a fixed point. If the item at index i in y is n, there will be n copies of i in I.y, so for instance I. 0 1 1 0 0 3 1 is 1 2 5 5 5 6. We mod the result of that by 2 and add one. Then, x $ y forces y into a list of length x, truncating it or extending it cyclically as necessary.

So here's what happens when the input is, say, 10.

   10 ($1+2|I.)^:a: 1
1 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1
1 2 1 2 1 2 1 2 1 2
1 2 2 1 2 2 1 2 2 1
1 2 2 1 1 2 1 1 2 2
1 2 2 1 1 2 1 2 2 1

We start with a row of all 1s and then "settle down" into the Kolakoski sequence. First, it turns into 1 2 1 2 1 2... as each contiguous block of ones or twos is described by length 1. Then we apply it again and it turns into 1 2 2 1 2 2 1 2 2... since the ones are described by 1 and the twos are described by 2. The we continue again and again until we see there is no change, at which point we stop and give the result.

Other "self-describing" sequences can be similarly derived in J using I. and ^:_.

Edit

Over a year ago, @ardnew asked:

  what is the relationship between n and the number of those intermediate iterations required to generate the sequence of length n?

To make sure we're on the same page, I consider the calculation for n = 10 above to have taken 5 iterations.

If there are s terms settled at the i-th iteration for n, then at the (i+1)-th iteration, there will be (at least) k0 + k1 + ... + ks + 1 terms settled. The '+ 1' appears because the next term will also be correct, since it must be and is different from the term before it.

So if K(s) is the sequence of partial sums of kn, then we can lower bound the number of iterations for n by the least a such that (1+K)a(1) ≥ n. I don't how to prove we don't accidentally do a bit better (by picking up more correct terms than we expected in some iteration), but according to the numbers, we don't:

   k =: ($ 1 + 2 | I.)^:_&1               NB. Kolakoski seq
   pk =: +/\ @: k                         NB. partial sums ("K")
   ((1 + pk 2000) {~ <:) ::_:^:(i.20) 1   NB. iterating 1+K, say, 20 times
1 2 4 7 11 18 28 43 65 99 150 226 340 511 768 1153 1728 2590 _ _
   NB. compare with observed number of settled terms up to 2000:
   +/"1 }. (k <./\ . ="1 ($1+2|I.)^:a:&1) 2000
1 2 4 7 11 18 28 43 65 99 150 226 340 511 768 1153 1728 2000

The underscores are index errors (:: _:), telling us 20 iterations is too much for the first 2000 terms of kn to handle.


Terms of the EKG sequence Introduction
The EKG sequence begins with 1 and 2, then the rule is that the next term is the smallest positive integer not already in the sequence and whose common factor with the last term is greater than 1 (they are not coprimes).
The first terms are:

1, 2, 4, 6, 3, 9, 12, 8, 10, 5, 15, ...

It's called EKG because the graph of its terms is quite similar to an EKG.
It's sequence A064413 in the OEIS.
Challenge
You have to write a function which takes an integer n as input and outputs how many of the n first terms of the sequence are greater than n.
As the sequence's rule begins with the third term, the input integer has to be greater or equal to 3. For example, given input 10 the output is 1 because the 7th term is 12 and none of the other first ten terms exceed 10.
Test cases

3  ->  1
10 ->  1
100 -> 9
1000 -> 70

Rules

For integers lower than 3, the function may output 0 or an error code.
No other particular rules except: it's code golf, the shorter the better!

Jelly, 20 19 18 bytes

S‘gṪ’ɗƇḟ¹Ṃṭ
1Ç¡>¹S

This is a full program.

Try it online!

How it works

1Ç¡>¹S       Main link. Argument: n (integer)

1            Set the return value to 1.
 Ç¡          Call the helper link n times.
   >¹        Compare the elements of the result with n.
     S       Take the sum, counting elements larger than n.

S‘gṪ’ɗƇḟ¹Ṃṭ  Helper link. Argument: A (array or 1)

S            Take the sum of A.
 ‘           Increment; add 1.
     ɗƇ      Drei comb; keep only elements k of [1, ..., sum(A)+1] for which the
             three links to the left return a truthy value.
  g              Take the GCD of k and all elements of A.
   Ṫ             Tail; extract the last GCD.
    ’            Decrement the result, mapping 1 to 0.
       ḟ¹    Filterfalse; remove the elements that occur in A.
         Ṃ   Take the minimum.
          ṭ  Tack; append the minimum to A.

Note that the generated sequence is \$[1, \mathbf{0}, 2, 4, 6, 3, 9, 12, 8, 10, 5, 15, \dots]\$. Since calling the helper link \$n\$ times generates a sequence of length \$n + 1\$, the \$0\$ is practically ignored.


Convert Chinese numbers In Chinese, numbers are written as follows:

1 一 2 二 3 三 4 四 5 五 6 六 7 七 8 八 9 九 10 十

For numbers above 10, it is expressed as the number of tens and the number of ones. If there is only one ten, you do not need to explicitly say one, and if there are no ones, you don't need to put anything after:

11 十一
24 二十四
83 八十三
90 九十

For numbers above 100, you use the same logic, but with the character 百. This time though, if there is only one hundred, you still need to write it out, and if there are no tens, you need to say 零.

100 一百 231 二百三十一 803 八百零三 999 九百九十九

Your task is to convert these Chinese numerals into Arabic numerals. Given a number N in Chinese (一 (1) <= N <= 九百九十九 (999)), convert it into an Arabic number.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

JavaScript (ES6), 112 bytes

s=>[...s].map(c=>d=(i="零一二三四五六七八九十百".search(c))>9?(n+=(d||1)*(i*90-890),0):i,n=d=0)&&n+d

Digits 一-九 are converted to decimal and saved in d, while 十 and 百 multiply the last digit by 10 or 100 respectively and accumulate it in n. 零 is effectively ignored, since d is already zero when it is encountered.


Find all numbers between 2 and 100 co-prime to a given number Your program will be given a number as input. Your challenge is to output all the numbers between 2 and 100 inclusive that are co-prime to the given number. (Two numbers are co-prime if their GCD is 1.) If no numbers between 2 and 100 are co-prime to the given number, the program shall not output anything.

The program must receive the number from STDIN, and the output must be a list of numbers separated by a comma and a space.

Contest closes June 14th, 2014, two weeks from now. The shortest solution wins.

Examples (here the range is from 2 to 20):

3:

2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20

12:

5, 7, 11, 13, 17, 19

9699690:

(No output: no numbers between 2 and 20 are co-prime to 9699690).

EDIT: Esoteric languages (e.g. J or GolfScript) are now being assessed separately from non-esoteric languages. This is to make the challenge fair.

CJam, 23 bytes

101,:N2>q~mf{N%-}/", "*

Try it online. Paste the Code, type an integer in Input and click Run.

Example

$ cjam factor.cjam <<< 210
11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

How it works

101,:N # Push the array [ 0 ... 100 ] and save it in “N”.
2>     # Remove 0 and 1 from the array.
q~mf   # Read from STDIN, interpret the input and factorize the resulting integer.
{      # For each prime factor:
  N%   # Collect all multiples of the prime factor in an array.
  -    # Apply set difference with the array on the stack.
}/     # This leaves only integers that are coprime with the input.
", "*  # Join by commas and spaces.


Swap prime exponents with their neighbours (Follow-up to my question about swapping bits with their neighbours.)
Task
Given a positive integer x = (2a · 3b) · (5c · 7d) · (11e · 13f) · …, print the integer obtained by swapping the exponents in this factorization for each successive pair of primes, y = (2b · 3a) · (5d · 7c) · (11f · 13e) · …
A061898 in the OEIS. This is code-golf, so the shortest program (in bytes) wins!
Test cases
1 -> 1
2 -> 3
3 -> 2
10 -> 21
37 -> 31
360 -> 756
12345 -> 11578
67895678 -> 125630871

Jelly, 10 bytes

ÆE;0s2UFÆẸ

Try it online! or verify all test cases.

How it works

ÆE;0s2UFÆẸ  Main link. Argument: n

ÆE          Yield the exponents of n's prime factorization.
  ;0        Append a zero.
    s2      Split into pairs.
      U     Upend; reverse each pair.
       F    Flatten the resulting list of pairs.
        ÆẸ  Convert the prime exponents to integer.


Transpose columns in table Let's say you've got a table of data:

meter_id date   0000 0600 1200 1800
0        030915 10   20   30   40
1        030915 15   7    49   2

where the last four columns are meter readings at different times. You want to output

meter_id date   time reading
0        030915 0000 10
0        030915 0600 20

etc.

Your input and output will not have headers, unlike in this example. The set of columns you'll transpose will be provided as numeric arguments to your program, from 1 onwards. Input is stdin and output is stdout.

So here's an example of it actually being used.

$ ./tpose 3 4 5 6

Stdin:

0        030915 10   20   30   40
1        030915 15   7    49   2

Stdout:

0       030915  3       10
0       030915  4       20
0       030915  5       30
0       030915  6       40
1       030915  3       15
1       030915  4       7
1       030915  5       49
1       030915  6       2

The third column contains values from 3 to 6. This is because the reading is from columns 3 to 6 from the input table.

Happy golfing.

kdb k, 101 bytes
1@"\n"/:{"\n"/:{" "/:(r@&{~#&x=a}'!#r),(,$1+a@x),,c@x}'!#c::(r::" "\:x)@a::-1+.:'.z.x}'-1_"\n"\:0::0;

Me: (reads the word "transpose" in the title) K will be perfect for this! It'll kick everything else's hind!
20 minutes and 101 bytes later
Me: Idiot.


Sum the Vertex Connections Let's say you have a positive integer N. First, build a regular polygon, that has N vertices, with the distance between neighbouring vertices being 1. Then connect lines from every vertex, to every other vertex. Lastly, calculate the length of all lines summed up together.

Example

Given the input N = 6, build a hexagon with lines connecting every vertex with the other vertices.

As you can see, there are a total of 6 border lines (length=1), 3 lines that have double the border length (length=2) and 6 other lines that we, by using the Pythagoras Theorem, can calculate the length for, which is

If we add the lengths of the lines together we get (6 * 1) + (3 * 2) + (6 * 1.732) = 22.392.

Additional Information

As structures with 2 or less vertices are not being considered polygons, output 0 (or NaN, since distance between a single vertex doesn't make much sense) for N = 1, since a single vertice cannot be connected to other vertices, and 1 for N = 2, since two vertices are connected by a single line.

Input

An integer N, in any reasonable format.

Output

The length of all the lines summed up together, accurate to at least 3 decimal places, either as a function return or directly printed to stdout.

Rules

Standard loopholes are forbidden.
This is code-golf, so the shortest code in bytes, in any language, wins.

Good luck!

Test Cases

(Input) -> (Output)
1 -> 0 or NaN
2 -> 1
3 -> 3
5 -> 13.091
6 -> 22.392

Python 3 (with sympy),  61 60 58 54  48 bytes
-6 (maybe even -10 if we do not need to handle n=1) thanks to xnor (further trigonometric simplification plus further golfing to handle edge case of 1 and save parentheses by moving a (now unnecessary) float cast).
Hopefully beatable with no 3rd party libraries? Yes!! but Lets get things rolling...

lambda n:1%n*n/2/(1-cos(pi/n))
from math import*

Try it online!
This uses a formula for the sum of the lengths if a polygon is inscribed inside a unit circle, n*cot(pi/2/n)/2 and adjusts the result to one for the side length being one by dividing by the sin of that cord length sin(pi/n).
The first formula is acquired by considering the n-1 cord lengths of all the diagonals emanating from one corner which are of lengths sin(pi/n) (again), sin(2*pi/n), ..., sin((n-1)pi/n). The sum of this is cot(pi/2/n), there are n corners so we multiply by n, but then we've double counted all the cords, so we divide by two.
The resulting n*cot(pi/2/n)/2/sin(pi/n) was then simplified by xnor to n/2/(1-cos(pi/n)) (holding for n>1)
...this (so long as the accuracy is acceptable) now no longer requires sympy over the built-in math module (math.pi=3.141592653589793).