# Question
Title: Find two integers from an unordered list to sum to the input
This is a Google interview question, see here for a youtube link.

### The task:

Find 2 integers from an unordered list that sum to a given integer.

1. Given an unordered list of integers, find 2 integers that sum to a given value, print these 2 integers, and indicate success (exit 0). They don't need to be any particular numbers (i.e. the first 2 integers summing to the right number), any pair that sums to the value will work.
2. an integer is positive and greater than zero.
3. a list of integers can be in any data structure including a file of integers - one integer per line.
4. if no integers can be found, indicate a failure (exit 1).
5. two integers at different positions in list must be returned. (i.e. you can't return the same number from the same position twice)

(Note: in the video, these are not exactly the requirements. The 'interviewer' changed his multiple times.)

eg.

```
sum2 8 <<EOF
1
7
4
6
5
3
8
2
EOF

```

Prints `3` and `5` and exit status is 0. Note that in this `1,7` and `2,6` would also be allowed results.

```
sum2 8 <<EOF
1
2
3
4

```

Returns exit status 1 since no possible combo. `4,4` isn't allowed, per rule 5.

# Answer
> 5 votes
# Bash, 84 bytes

My implementation of (roughly) Google's engineer's solution but using bash and an input stream - not my solution, so this does not count.

```
while read V;do((V<$1))&&{ ((T=R[V]))&&echo $T $V&&exit;((R[$1-V]=V));};done;exit 1

```

Method

while we can read integer V from input stream if less than target $1 then if already seen $1-V then print $1-V and V and exit 0 (else) save candidate for input $1-V exit 1

# Answer
> 4 votes
# JavaScript ES6, 58 70 68 64 bytes

```
a=>b=>{for(i in a)if(a.includes(b-a[i],i+1))return[a[i],b-a[i]]}

```

Returns a pair of numbers in the form of an array if found, otherwise returns `undefined`, a falsy value.

```
f=a=>b=>{for(i in a)if(a.includes(b-a[i],i+1))return[a[i],b-a[i]]}

console.log(f([1,7,4,6,5,3,8,2])(8));
console.log(f([1,2,3,4,5,6,7,8])(8));
console.log(f([1,2,3,4])(8));
console.log(f([2,2])(4));
```

# Answer
> 4 votes
# Brachylog, 9 bytes

```
h⊇Ċ.+~t?∧

```

Try it online!

Assuming I understood the challenge correctly…

### Explanation

```
h⊇Ċ          Ċ ('couple') has two elements, and is a subset of the head of the input
  Ċ.         Output = Ċ
   .+~t?     The sum of the elements of the Output is the tail of the Input
        ∧    (disable implicit unification)

```

# Answer
> 4 votes
# Perl 6, 59 bytes

```
$_=get;put lines().combinations(2).first(*.sum==$_)//exit 1

```

Try it
Try it with no possible result

## Expanded:

```
$_ = get;            # get one line (the value to sum to)

put                  # print with trailing newline
    lines()          # get the rest of the lines of input
    .combinations(2) # get the possible combinations
    .first(          # find the first one
      *.sum == $_    # that sums to the input
    )
  //                 # if there is no value (｢Nil｣)
    exit 1           # exit with a non-zero value (｢put｣ is not executed)

```

# Answer
> 4 votes
## JavaScript (ES6), ~~61~~ ~~57~~ 56 bytes

Takes the array of integers `a` and the expected sum `s` in currying syntax `(a)(s)`. Returns a pair of matching integers as an array, or `undefined` if no such pair exists.

```
a=>s=>(r=a.find((b,i)=>a.some(c=>i--&&b+c==s)))&&[r,s-r]

```

### Formatted and commented

```
a =>                      // given an array of integers (a)
  s => (                  // and an expected sum (s)
    r = a.find((b, i) =>  // look for b at position i in a such that:
      a.some(c =>         //   there exists another c in a:
        i-- &&            //     - at a different position
        b + c == s        //     - satisfying b + c == s
      )                   //   end of some()
    )                     // end of find(): assign the result to r
  ) &&                    // if it's not falsy:
  [r, s - r]              // return the pair of integers

```

### Test

```
let f =

a=>s=>(r=a.find((b,i)=>a.some(c=>i--&&b+c==s)))&&[r,s-r]

console.log(f([1,7,4,6,5,3,8,2])(8))
console.log(f([1,2,3,4])(8))
```

# Answer
> 3 votes
# Perl 5, 51 bytes

46 bytes of code + for 5 bytes for `-pli` flags.

```
$\="$_ $v"if$h{$v=$^I-$_};$h{$_}=1}{$\||exit 1

```

Try it online!

The idea is to iterate on the input list: on a number `x` (`$_`), if we previously saw `n-x` (`$^I-$_`) then we found what we were looking for, and set `$\` to these two values (`"$_ $v"`). At the end, if `$\` isn't set, then we `exit 1`, else it will be implicitly printed.

# Answer
> 3 votes
# Röda, ~~60~~ 56 bytes

```
f s,a{seq 1,s|{|x|[[x,s-x]]if[x in a,s-x in a-x]}_|pull}

```

Try it online!

This code throws an error if there is no answer. It generates all possible pairs that can form the sum `s`, ie. `1, s-1`, `2, s-2`, `3, s-3`, ... Then it checks if both numbers are in the array `a` and if so, pushes them to the stream. `pull` reads one value from the stream and returns it. If there are no values in the stream, it throws an error. `a-x` returns the array `a` with `x` removed.

# Answer
> 3 votes
# Jelly, 14 bytes

```
ŒcS=⁹$$ÐfḢṄo⁶H

```

Try it online!

This is a function (not a full program) that outputs to standard output. (The TIO link has a wrapper that runs a function and disregards its return value.)

This program could be 4 bytes shorter if not for the exit code requirement; returning an exit code of 1 in Jelly is fairly hard. (It's possible that there's a terser way to do this that I've missed.)

## Explanation

```
ŒcS=⁹$$ÐfḢṄo⁶H
Œc                All pairs of values from {the first argument}
       Ðf         Take only those which
  S=⁹               sum to {the second argument}
     $$           Parse the preceding three builtins as a group
         Ḣ        Take the first result (0 if there are no results)

          Ṅ       Output this result (plus a newline) on standard output
           o⁶     If this value is falsey, replace it with a space character
             H    Halve every element of the value

```

We can halve every integer in a pair just fine, so the `o⁶H` will do nothing if we found a result, other than returning a useless return value that isn't relevant anyway (the  serves as a convenient single-byte method to determine the function's return value early, under PPCG rules). However, if we didn't find a result, we end up trying to halve a space character, an operation so meaningless it causes the Jelly interpreter to crash. Fortunately, this crash produces an exit code of 1.

# Answer
> 2 votes
## Javascript, ~~114~~ ~~96~~ ~~86~~ 84 bytes

```
a=>b=>{c=b.length;for(x=0;x<c;x++)for( y=x;++y<c;)if(b[x]+b[y]==a)return[b[x],b[y]]}

```

*Saved 1 byte thanks to @Cyoce and another 8 bytes thanks to @ETHProductions*

This returns a tuple with the first combination of list-elements that sum up to the given input, or nothing for no match. I've removed the `var`s in the function; REPL.it crashes without them, but the Chrome Dev Console handles this just fine...

Try it online!

# Answer
> 2 votes
## Python 2, 60 bytes

This short, until rules with exiting with code 1 are clarified. Now exits with error if nothing is found.

-5 bytes thanks to @Peilonrayz

-4 bytes thanks to @Rod

Try it online

```
a,s=input()
while a:
 x=a.pop()
 if s-x in a:r=s-x,x
print r

```

# Answer
> 2 votes
## PowerShell, ~~109~~ 97 bytes

```
param($i,$a)($c=0..($a.count-1))|%{$c-ne($f=$_)|%{if($a[$f]+$a[$_]-eq$i){$a[$f,$_];exit}}};exit 1

```

Took a 12 byte deal that AdmBorkBork offered

**Explanation**

```
# Get the parameter passed where $i is the addition target from the array of numbers in $a
param($i,$a)

($c=0..($a.count-1))|%{
    # We are going to have two loops to process the array elements.
    # The first loop element will be held by $f
    $f=$_
    # Create a second loop that will be the same as the first except for the position of $f to
    # prevent counting the same number twice.
    $c|?{$_-ne$f}|%{
        # Check if the number at the current array indexes add to the target value. If so print and exit.
        if($a[$f]+$a[$_]-eq$i){$a[$f],$a[$_];exit}
    }

}
# If nothing was found in the loop then we just exit with error.
exit 1

```

The current rules look for exit code which this does. Those could be removed and just check for numbers being returned and a falsy.

**Sample Usage**

If the code above was saved as function `s`

```
s 8 @(1,2,3,4)
s 8 @(1,7,4,6,5,3,8,2)

```

# Answer
> 2 votes
# C++ 133 bytes (compiled with clang 4 and gcc 5.3 -std=c++14)

```
#include <set>
auto f=[](auto s,int v,int&a,int&b){std::set<int>p;for(auto i:s)if(p.find(i)==end(p))p.insert(v-i);else{a=v-i;b=i;}};

```

# C 108 bytes

```
void f(int*s,int*e,int v,int*a,int*b){do{int*n=s+1;do if(v-*s==*n){*a=*s;*b=*n;}while(++n<e);}while(++s<e);}

```

# Answer
> 2 votes
# Haskell, 34 bytes

```
(n:v)#s|elem(s-n)v=(n,s-n)|1<2=v#s

```

Try it online!

For each element of the list, this function checks if (sum-element) is in the following part of the list. Returns the first couple it finds. If the function reaches the end of the list it throws a "non -exhaustive patterns" error and exits with code 1.

# Answer
> 2 votes
## R, 49 bytes

```
function(x,y){r=combn(x,2);r[,colSums(r)==y][,1]}

```

This finds all 2-combinations of `x` and returns a matrix. Then, sums by column and finds all the sums that equal to `y` (so without the `[,1]` part at the end it will print all the combinations that their sums equal to `y`)

# Answer
> 2 votes
# Japt, 9 bytes

*Saved many bytes thanks to @ETHproductions*

```
à2 æ_x ¥V

```

Try it online!

### Explanation

```
à2 æ_x ¥V
à2         // Creates all combinations of the input, length 2
   æ       // Returns the first item where:
    _x     //     The sum of the two items in each set
       ¥V  //     == Second input

```

### Example

```
Input:        [1,2,3], 4
à2         // [[1,2],[1,3],[2,3]]
   æ_x     // [3,    4,    5    ]
       ¥V  //  3!=4, 4==4 ✓
Output:    //  1,3

```

# Answer
> 1 votes
## Clojure, 77 bytes

```
#(first(mapcat(fn[i a](for[b(drop(inc i)%):when(=(+ a b)%2)][a b]))(range)%))

```

Returns the first such pair or `nil`.

# Answer
> 1 votes
## Haskell, 62 bytes

```
r=return;s#[]=r 1;s#(a:b)|elem(s-a)b=print(a,s-a)>>r 0|1<2=s#b

```

I still don't know what's allowed by the challenge and what not. I'm going for a function that prints a pair of numbers and returns 0 if there's a solution and prints nothing and returns 1 if there's no solution. As printing is I/O, I have to lift the return values into the IO-Monad (via `return`) and the actual type of the function is `Num a => IO a`.

Usage example (with return value printed by the repl):

```
*Main> 4 # [2,2]
(2,2)
0

```

Try it online!.

If raising exceptions is allowed, `fail` will save some bytes (total 51):

```
s#[]=fail"";s#(a:b)|elem(s-a)b=print(a,s-a)|1<2=s#b

```

# Answer
> 1 votes
# Jelly, 9 bytes

```
ŒcS=¥ÐfḢZ

```

Jelly has no way of setting the exit code to arbitrary values, so this produces a *TypeError* for input without a valid solution that will cause the parent interpreter to exit with exit code **1**.

Try it online!

### How it works

```
ŒcS=¥ÐfḢZ  Main link. Argument: A (array of integers), n (integer)

Œc         Yield all 2-combinations of different elements of A.
     Ðf    Filter by the link to the left.
    ¥        Combine the two links to the left into a dyadic chain.
  S            Take the sum of the pair.
   =           Compare the result with n.
       Ḣ   Head; extract the first pair of the resulting array.
           This yields 0 if the array is empty.
        Z  Zip/transpose the result.
           This doesn't (visibly) alter pairs, but it raise a TypeError for 0.

```

# Answer
> 1 votes
# Nova, 101 bytes

```
q(Int[] a,Int x)=>a{if(Int y=a.firstWhere({a.contains(x-a.remove(0))}))return [y,x-y];System.exit(1)}

```

One nice thing about code golf is that it helps me find bugs in my language. e.g. the space required between `return` and `[y,x-y]`.

Once I add push/pop functions to Array.nova and fix return, would be 96 bytes:

```
q(Int[] a,Int x)=>a{if(Int y=a.firstWhere({a.contains(x-a.pop())}))return[y,x-y];System.exit(1)}

```

Usage:

```
class Test {
    static q(Int[] a,Int x)=>a{if(Int y=a.firstWhere({a.contains(x-a.remove(0))}))return [y,x-y];System.exit(1)}

    public static main(String[] args) {
        Console.log(q([1, 2, 3, 4, 5], 8)) // [5, 3]
        Console.log(q([1, 2, 3, 4, 5], 5)) // [1, 4]
        Console.log(q([1, 2, 3, 4], 8)) // exit code 1
    }
}

```

Edit: Also, there's this way at 73 bytes (69 using pop), too:

```
q(Int[] a,Int x)=>[Int y=a.firstOrThrow({a.contains(x-a.remove(0))}),x-y]

```

firstOrThrow will throw an Exception, which will be uncaught and therefore ultimately exiting the program with exit code 1. ;)

This way seems more readable too.

# Answer
> 0 votes
# Pyth, 12 bytes

```
hfqsThQ.ceQ2

```

### Explanation

```
       .ceQ2   Get all pairs from the second input
 fqsThQ        Find the ones whose sum is the first input
h              Take the first (exits with error code 1 if there aren't any)

```

# Answer
> 0 votes
# PHP, 88 bytes

```
for($i=1;$a=$argv[$k=++$i];)for(;$b=$argv[++$k];)if($a+$b==$argv[1])die("$a $b");die(1);

```

takes input from command line arguments, sum first. Run with `-nr`.

Fortunately, `die`/ `exit` exits with `0` when you give it a string as parameter.

I tried to merge the loops to one; but it requires a longer initialization and test this time.

# Answer
> 0 votes
## Mathematica, 76 bytes

```
f::e="1";If[(l=Cases[#~Subsets~{2},x_/;Tr@x==#2])=={},Message@f::e,First@l]&

```

Fairly straightforward: `#~Subsets~{2}` gets all 2-element subsets of the list, then `Cases[...,x_/;Tr@x==#2]` picks only the ones whose sum is the number we want. If there are none of these, `If[l=={}, Message@f::e,First@l]` prints the error message `f::e : 1` that we defined earlier (since I have no idea what else "exit status 1" might mean for Mathematica); otherwise, it returns the first entry in the list of pairs that sum to the correct thing.

If we're allowed to return a falsey value instead of doing that weird exit status thing, the following code has 58 bytes:

```
If[(l=Cases[#~Subsets~{2},x_/;Tr@x==#2])=={},1<0,First@l]&

```

# Answer
> 0 votes
# Scala, 55 41 bytes

```
(l,n)=>l combinations 2 find(_.sum==n)get

```

Returns a list of the two numbers if they exist and throws an error otherwise. Uncaught, this error will result in an exit status of 1.

# Answer
> 0 votes
# Ruby, ~~53~~ 48 bytes

```
->a,s{p(a.combination(2).find{|x,y|x+y==s})?0:1}

```

Input: a is the list, s is the expected sum.

If the 2 numbers are found, print them and return 0, otherwise return 1, as in the specification.

# Answer
> 0 votes
# TI-Basic, 59 bytes

```
Prompt L<sub>1</sub>
Prompt X
While 1
L<sub>1</sub>(1→B
seq(L<sub>1</sub>(C),C,2,dim(L<sub>1</sub>→L<sub>1</sub>
If sum(not(X-L<sub>1</sub>-B
Then
Disp B,X-B
Return
End
End

```

Explanation:

```
Prompt L<sub>1</sub>               # 4 bytes, input array like "{1, 2, 3}"
Prompt X                # 3 bytes, Input target sum
While 1                 # 3 bytes, until the list is empty
L<sub>1</sub>(1→B                  # 7 bytes, try the first element (now B)
seq(L<sub>1</sub>(C),C,2,dim(L<sub>1</sub>→L<sub>1</sub>  # 18 bytes, remove first element from list
If sum(not(X-L<sub>1</sub>-B       # 10 bytes, if any element in the list plus B is the target
Then                    # 2 bytes, then...
Disp B,X-B              # 7 bytes, print it and it's "complement"
Return                  # 2 bytes, and exit gracefully
End                     # 2 bytes
End                     # 1 byte
```

If the program did not exit gracefully, it will cause an error when there are not enough elements in the list for it to continue.

# Answer
> 0 votes
## CJam, 23 bytes

```
l~_,1>{e!2f<::+#)}{;;}?

```

Input is `sum numbers`. For example: `6 [3 2 3]`. Leaves a positive number for truthy and an empty string or 0 for falsey.

Explanation:

```
l~    e# Read input and evaluate:  | 7 [3 2 3]
_     e# Duplicate:                | 7 [3 2 3] [3 2 3]
,     e# Take the length:          | 7 [3 2 3] 3
1>{   e# If more than 1:           | 7 [3 2 3]
  e!  e#   Unique permutations:    | 7 [[2 3 3] [3 2 3] [3 3 2]]
  2f< e#   Slice each to length 2: | 7 [[2 3] [3 2] [3 3]]
  ::+ e#   Some each:              | 7 [5 5 6]
  #   e#   Index:                  | -1
  )   e#   Increment:              | 0
}{    e# Else:                     | 7 [3 2 3]
  ;   e#   Pop                     | 7
  ;   e#   pop                     |
}?    e# Endif
e# Implicit output: 0

```

---
Tags: code-golf, arithmetic, array
---


title: Tips for golfing in 2D languages

text:
# Question
Title: Tips for golfing in 2D languages
What general tips do you have for golfing in 2 dimensional programming languages? I'm looking for tips which can be applied to code-golf problems and are specific to 2D programming languages, but not specific to any one language (Responses like "remove comments" and "use the `M` operation" are not answers).

Please post one tip per answer.

# Answer
# Avoid horizontal gaps

Often, code will leave largs gaps of whitespace to the left hand side of the program, like so.

```
abc
  d
  e

```

This adds 4 bytes, when this could be avoided by left aligning.

```
cde
b
a

```

If you need to use large gaps of whitespace, try to make them vertical, instead of horizontal.

```
########
#      #
#      #
#      #

```

vs

```
####
#
#
#
#
#
#
####

```
> 19 votes

# Answer
# Carriage Returns Are Bytes Too

The less 2D you can make it, the better. A carriage return is another no-op. Without ignoring the tips from @ATaco and @ASCII-only, try and keep the Y dimension as small as possible.

This

```
###
####
########

```

is better than

```
###
###
###
##
#
#
#
#

```
> 11 votes

# Answer
# Use one dimension when possible

Typically, simpler programs can be written on a single line. For example, the classic cat program could be:

```
>iv
^o<

```

But one could abuse the wrapping behavior and make this:

```
io

```

Or, in languages without such wrapping behavior:

```
> ?oi<

```

(Assuming `?` doesn't pop.) In the case of a non-wrapping language, an explicit loop is often better.

## With jump commands

In 2D languages with jump and conditional jump commands, a program could look like this:

```
abc >de?v;
    ^hgf<

```

This could also be:

```
abc de?!;hgf04&

```

(if `!` is a trampoline, and `&` is jump to position)
> 11 votes

# Answer
# DRY (Don't Repeat Yourself)

While abstracting with functions is usually longer in Code Golf, it can really help for 2D languages. Try to rework your code so it can re-use the same snippet, entering/exiting it with two different branches of execution.
> 9 votes

# Answer
# Interleave paths

Usually in a 2D language there is an IP that moves according to direction commands. Since spaces are wasted bytes, it is almost always more efficient to rearrange the program so it moves closer to the left as often as possible, saving the need for unnecessary padding spaces.
> 8 votes

# Answer
# Use mirrors

Mirrors can sometimes be used in two paths at the same time (each path bounces off one side of the mirror). This may not seem to help, but it may allow you to rearrange your program, or if you have a lot if direction changes they may be able to be replaced with fewer mirrors.
> 3 votes

# Answer
# Memorize idioms

Here are a few "idioms" that do certain things, depending on the nature of the language.

## Pseudo-linear code

If dynamic code generation is ever required, it may be of use to use the pseudo-linear code model:

```
v
\"line 1"
\"line 2"
.
.
\"line N"

```

Assuming `\` and `v` mean what they usually do.

## Infinite loop

In almost all 2D languages, `><` is an infinite, unbreakable loop. If, for some reason, you need to do this, this is the best way, despite how nice this might look:

```
>v
^<

```

In fact, if you make your code a 1-liner, you could just use `^` or `v`, as such:

```
i?vo;

```

This `v` will send the IP to itself, wrapping around. You may still be able to use this approach in any instance where a directional command points to a series of (relative) no-ops.

## Quine framework

Usually, languages with a string/quote framework can have a quine like this:

```
<quote><generate "><output stack><terminate>

```

For \>\<\>, this would look like:

```
":1-r>o<#

```

Except this one exits with an error as termination. It is probably the shortest \>\<\> quine, or, at least, the shortest one that I have found.
> 3 votes

---
Tags: code-golf, tips
---


title: Lots of seconds!

text:
# Question
Title: Lots of seconds!
**OUTPUT:** The number of seconds since midnight on January 1, 1 A.D., as an integer.

**INPUT:** None, you must pull the current timestamp yourself.

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

Standard loopholes apply.

# Answer
> 2 votes
# Bash + GNU utilities, 26

```
date +62135596800\ %s+p|dc

```

This doesn't attempt to do anything special wrt Julian vs. Gregorian or leap-seconds or timezones - I'm just assuming GNU `date` is doing the right thing.

The 62135596800 is the output of `date -ud 1/1/1 +%s` multiplied by -1. `date`'s `%s` format specifier gives the number of seconds since the unix epoch (1970), and so is a negative number for 1/1/1.

Try it online.

---
Tags: code-golf, date
---


title: Correct peoples grammar

text:
# Question
Title: Correct peoples grammar
(yes, that title was intentional)

Your task is to correct common grammatical mistakes.

You must:

* Capitalise the first letter of each sentence, ie the first non-whitespace letter after any of `.!?` and, additionally, capitalise the first letter of the input
* Remove repeating punctuation, such as `!!! -> !`. Ellipses (`...`) are not special, and will collapse into `.`.
* Remove repeating whitespace `<space><space><space> -> <space>`
* Remove whitespace directly before any of `.,;!?` as in: `Hello , World ! -> Hello, World!`
* If there is no space directly after any of `.,;!?`, add it.
* Add a `.` at the end of the input if there is not any of `.!?` at the end.
* ~~Not use Mathematica's builtins~~

## Examples:

```
This is a  sentence .Unfortunately, it's not very grammatically correct.can you fix it ???
This is a sentence. Unfortunately, it's not very grammatically correct. Can you fix it?

buffalo, buffalo;buffalo   buffalo? Buffalo.buffalo Buffalo buffalo
Buffalo, buffalo; buffalo buffalo? Buffalo. Buffalo Buffalo buffalo.

i'm not sure what to put for this test case...
I'm not sure what to put for this test case.

!this is a test. .Can ...you . . . 'ear me Ground-Control? ?! 'ere as in what you do with you're [sic] ears !
! This is a test. Can. You. 'ear me Ground-Control?! 'ere as in what you do with you're [sic] ears!

```

# Answer
# Retina, ~~80~~ ~~74~~ ~~73~~ ~~71~~ ~~74~~ ~~64~~ ~~65~~ ~~62~~ ~~78~~ 72 bytes

```
 *([.,;!? ])(\1| )*
$1
T`l`L`[.!?].|^.
([.,;!?])(\w|')
$1 $2
[^.!?]$
$&.

```

Try it online!

This is my first Retina answer.

-12 bytes thanks to @BusinessCat!

-3 bytes thanks to @Neil.
> 2 votes

---
Tags: code-golf, string, natural-language
---


title: Draw the Moon Phase

text:
# Question
Title: Draw the Moon Phase
# Challenge

Given the phase of the moon, draw it using ASCII art.

Your program must handle new moon, waxing crescent, first quarter, waxing gibbous, full moon, waning gibbous, last quarter, and waning crescent. Your input will be an integer.

```
0 -> new moon
1 -> waxing crescent
2 -> first quarter
3 -> waxing gibbous
4 -> full moon
5 -> waning gibbous
6 -> last quarter
7 -> waning crescent

```

The ASCII art is all placed on a 16x8 grid (because character dimension ratios). You can replace `.` with any character and `#` with any other non-whitespace character.

The output for new moon should be:

```
................
................
................
................
................
................
................
................

```

For waxing crescent:

```
..........######
............####
.............###
.............###
.............###
.............###
............####
..........######

```

For first quarter:

```
........########
........########
........########
........########
........########
........########
........########
........########

```

For waxing gibbous:

```
......##########
....############
...#############
...#############
...#############
...#############
....############
......##########

```

And for full moon:

```
################
################
################
################
################
################
################
################

```

The waning crescent is just the waxing crescent with each line reversed, as with the waning gibbous and the waxing gibbous, and the first and last quarter.

# Rules

* Standard Loopholes Apply
* You may choose to output waxing/waning in the opposite direction if you want, though it should make no difference (the graphics shown in this question are for the northern hemisphere)
* Your output must be exactly as specified. Your newlines can be any reasonable line separator, and you may have a trailing newline if you would like.

# Answer
# Jelly,  ~~43~~ 32 bytes

-7 bytes moving from bit-mask to comparison-mask
-2 bytes with some tacit programming improvements
-1 byte moving to the southern hemisphere
-1 byte - **use the all-new `ɓ` chain separator** ...its first ever use!

```
“>,##‘m0Dm€0ż@€4Ḷ¤Œṙɓ%4>C¹⁸:4¤?Y

```

Uses the characters `0` for `.` and `1` for `#`.

All cases in a test suite at **Try it online!**

### How?

Builds a mask capturing the first four phases, and rather than reversing the lines complements the resulting values of the modulo-4 phase result when the phase div-4 is non-zero.

I originally built a bit mask, but the mask values were `0`,`8`,`12`, and `14` \- `0000`, `1000`, `1100`, and `1110` \- these have `phase` leading ones - so a comparison-mask could be used instead.

```
“>,##‘m0Dm€0ż@€4Ḷ¤Œṙɓ%4>C¹⁸:4¤?Y - Main link 1: number phase
“>,##‘                           - code-page index literal [62,44,35,35]
      m0                         - reflect -> [62,44,35,35,35,35,44,62]
        D                        - decimalise -> [[6,2],[4,4],[3,5],[3,5],[3,5],[3,5],[4,4],[6,2]]
         m€0                     - reflect €ach -> [[6,2,2,6],[4,4,4,4],[3,5,5,3],[3,5,5,3],[3,5,5,3],[3,5,5,3],[4,4,4,4],[6,2,2,6]]
                 ¤               - nilad and link(s) as a nilad:
               4                 -   literal 4
                Ḷ                -   lowered range -> [0,1,2,3]
            ż@€                  - zip (reverse @rguments) for €ach -> [[[0,6],[1,2],[2,2],[3,6]],[[0,4],[1,4],[2,4],[3,4]],[[0,3],[1,5],[2,5],[3,3]],[[0,3],[1,5],[2,5],[3,3]],[[0,3],[1,5],[2,5],[3,3]],[[0,3],[1,5],[2,5],[3,3]],[[0,4],[1,4],[2,4],[3,4]],[[0,6],[1,2],[2,2],[3,6]]]
                  Œṙ             - run-length decode -> [[0,0,0,0,0,0,1,1,2,2,3,3,3,3,3,3],[0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3],[0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3],[0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3],[0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3],[0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3],[0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3],[0,0,0,0,0,0,1,1,2,2,3,3,3,3,3,3]]
                                    -   i.e.: 0000001122333333  -
                                              0000111122223333  - Marking out the separate
                                              0001111122222333  - regions as filled up by
                                              0001111122222333  - the phases of the moon in
                                              0001111122222333  - the southern hemisphere.
                                              0001111122222333  -
                                              0000111122223333  -
                                              0000001122333333  -
                    ɓ            - dyadic chain separation & swap arguments, call that m
                     %4          - phase mod 4
                       >         - greater than? (vectorises across m) 1 if so 0 if not
                              ?  - if:
                             ¤   -   nilad followed by link(s) as a nilad:
                          ⁸      -     link's left argument, phase
                           :4    -     integer divide by 4
                        C        - then: complement
                         ¹       - else: identity (do nothing)
                               Y - join with newlines
                                 - implicit print

```
> 7 votes

# Answer
## JavaScript (ES6), ~~121~~ ... ~~103~~ 92 bytes

```
f=(n,i=128)=>i--?f(n,i)+(i%16?'':`
`)+'.#.'[i%16+4*n-~-'31000013'[n&1?i>>4:1]*~-(n&2)>>4]:''

```

### Demo

```
f=(n,i=128)=>i--?f(n,i)+(i%16?'':`
`)+'.#.'[i%16+4*n-~-'31000013'[n&1?i>>4:1]*~-(n&2)>>4]:''

o.innerHTML=f(0)
```

```
<input type="range" oninput="o.innerHTML=f(this.value)" value=0 min=0 max=7><pre id=o>
```
> 8 votes

# Answer
# Haskell, ~~98~~ 90 bytes

```
f i=do{a<-[3,1,0,0,0,0,1,3];[".#."!!div(i*4+x+[0,a-1,0,1-a]!!mod i 4)16|x<-[0..15]]++"\n"}

```

It loops through the rows and columns using the list monad (a `do` block for rows and a list comprehension for columns) and determines which character for each cell using a expression of the input (`i`), offset value for the row (`a`), and column index (`x`).

Saved 8 bytes by simplifying the subexpression for the true offset.
> 4 votes

# Answer
# Python 2, ~~144~~ ~~142~~ 127 bytes

```
i=input()
a,b='#.'[::i/4*2-1]
i%=4
for x in range(8):y=(int(abs(x-3.5))or 1)+2;y=[y,16-y][i>2];y=[i*4,y][i%2];print(16-y)*a+b*y

```

Try it online!

Can definitely be golfed further, tips are appreciated :)

Golfed off 1 byte thanks to undergroundmonorail!

Golfed off many bytes thanks to ovi and Mego because I'm a fool who forgets to not use 4 spaces for codegolf :)
> 3 votes

# Answer
# PHP, 105 Bytes

```
for(;$i++<8;)echo($p=str_pad)($p("",[16,16-$b=_64333346[$i],8,$b][3&$a=$argn],_M[$a/4]),16,M_[$a/4])."
";

```

Try it online!
> 2 votes

# Answer
## Mathematica, 125 bytes

```
s=Switch;Grid@If[1<#<6,#&,1-#&][s[m=#~Mod~4,0,0,2,1,_,1-{3.4,5}~DiskMatrix~{8,16}]s[m,1,h=Table[Boole[i>8],8,{i,16}],_,1-h]]&

```

Returns a grid using `1` and `0` instead of `.` and `#` respectively.

It works using two masks, one circular one and one half-shaded one, and logically combining them to get the appropriate shapes.

The two masks are made with `1-{3.4,5}~DiskMatrix~{8,16}` for the circular one, and `Table[Boole[i>8],8,{i,16}]` for the half one. The logic is as follows:

```
output = f(a AND b)

where f, a and b are:

n | f    a  b
--+-----------
0 | NOT  F  ◨
1 | NOT  ○  ◧
2 | 1    T  ◨
3 | 1    ○  ◨
4 | 1    F  ◨
5 | 1    ○  ◧
6 | NOT  T  ◨
7 | NOT  ○  ◨

```

The logic is simulated with `1`s and `0`s by using multiplication for `AND` and `x -> 1-x` for `NOT`.

A bonus (non-ASCII) solution, for 28 bytes: `IconData["MoonPhase",#/4-1]&`
> 1 votes

---
Tags: code-golf, ascii-art
---


title: Multidimensional array

text:
# Question
Title: Multidimensional array
This is a **code-golf**, so keep your code small!

The **objective** is to create a function that receives 3 arguments:

* **Rows**(int): The max number of an item in each array;
* **Cols**(int): The max number of dimensions (sub-arrays);
* **Val**(\*): The starting value in each item;

This function should return a **multidimensional array** with the proper size and with the items containing the value specified.

It should be able to return any number of dimensions.

### Example:

```
var multiArray = createMultiArray(2, 4,'empty');

multiArray[0][0][0][0] === 'empty' //true
multiArray[0][0][0][1] === 'empty' //true
multiArray[0][0][0][2] === 'empty' //true
multiArray[0][0][1][0] === 'empty' //true
...
multiArray[2][2][2][2] === 'empty' //true

```

# Answer
> 8 votes
## GolfScript

This is pretty trivial, so there's no need to over-complicate it:

```
{[1$({2$@(@A}{\;}if]*}:A;

```

Online demo

# Answer
> 6 votes
### GolfScript, 17 characters

A non-recursive approach in GolfScript.

```
{\{\[.;]*}+@*}:A;

```

Online demo

# Answer
> 4 votes
## JavaScript, 132 characters

```
function m(e,t,n){var r=0,i=[];var s=function(i){r++;for(var o=0;o<=e;o++){if(r==t)i[o]=n;else i[o]=s([])}r--;return i};return s(i)}

```
UnGolfed:
```
function multiArray(maxRows, maxCols, val){
  var c = 0, farray = [];
  var recursive = function(array){
    c++;
    for(var r = 0; r <= maxRows; r++){
      if(c == maxCols) array[r] = val;
      else array[r] = recursive([]);
    }
    c--;
    return array;
  };
  return recursive(farray);
}

```

# Answer
> 0 votes
## Mathematica, 32 bytes

~~Within reach of GolfScript for once!~~ Scrap that, I didn't see Howard's answer.

```
f=ConstantArray[#3,#+0Range@#2]&

```

# Answer
> 0 votes
## APL, 19 bytes

```
{(¯1↑⍵)⍴⍨⊃(//)⌽2↑⍵}

```

Sample:

```
    {(¯1↑⍵)⍴⍨⊃(//)⌽2↑⍵} 2 4 'empty'
┌─────┬─────┐
│empty│empty│
├─────┼─────┤
│empty│empty│
└─────┴─────┘
┌─────┬─────┐
│empty│empty│
├─────┼─────┤
│empty│empty│
└─────┴─────┘

┌─────┬─────┐
│empty│empty│
├─────┼─────┤
│empty│empty│
└─────┴─────┘
┌─────┬─────┐
│empty│empty│
├─────┼─────┤
│empty│empty│
└─────┴─────┘

```

# Answer
> 0 votes
# Python 3, 36 bytes

```
lambda a,b,x:eval("["*b+"x"+"]*a"*b)

```

Try it online!

# Answer
> 0 votes
# , 8 bytes

```
$/@]$<@[

```

Try it online!

---
Tags: code-golf
---


# Question
Title: Find the shortest representation of a number in Modular SNUSP
# Background

Many esoteric programming languages don't have numbers built in at literals, so you have to calculate them at runtime; and in many of these cases, the number representation can be quite interesting. We've already had a challenge about representing numbers for Underload. This challenge is about representing numbers in Modular SNUSP. (Note that you don't need to learn SNUSP in order to complete this challenge – all the information you need is in the specification – but you might find the background interesting.)

# The task

For the purpose of this challenge, a Modular SNUSP number is a string formed out of the characters `@`, `+`, and `=`, except that the last character is a `#`, and that the penultimate character must be `+` or `=` (it cannot be `@`). For example, valid numbers include `@+#`, `==#`, and `@@+@=#`; examples of invalid numbers include `+=`, `@@#`, and `+?+#`.

The value of a Modular SNUSP number is calculated recursively as follows:

* `#` has a value of 0 (this is the base case).
* If the number has the form `=x`, for any string `x`, its value is equal to the value of `x`.
* If the number has the form `+x`, for any string `x`, its value is equal to the value of `x`, plus 1.
* If the number has the form `@cx`, for any single character `c` and any string `x`, its value is equal to the value of `x`, plus the value of `cx`.

For this challenge, you must write a program that takes a nonnegative integer as input, and outputs a string that's the shortest possible Modular SNUSP number that has a value equal to the input.

# Clarifications

* It's entirely possible that there will be more than one string with the same value, and in particular, for some integers there will be a tie for the shortest Modular SNUSP number with that value. In such a case, you may output any of the numbers involved wit the tie.
* There's no restriction on the algorithm you use to find the number; for example, brute-forcing strings and evaluating them is a legal tactic, but so is doing something cleverer to reduce the search space.
* As usual on PPCG, your submission may be either a full program or a function (pick whichever is more concise in your language).
* This isn't a problem about handling input and output formats, so you can use any reasonable means to input a nonnegative integer and output a string. There's a full guide on meta, but the most commonly used legal methods include function arguments/returns, command line arguments, and standard input/standard output.

# Test cases

Here are the shortest representations of the first few numbers:

* **0**: `#`
* **1**: `+#`
* **2**: `++#`
* **3**: `+++#` or `@++#`
* **4**: `++++#` or `+@++#` or `@=++#`
* **5**: `@+++#` or `@@++#`
* **6**: `+@+++#` or `+@@++#` or `@=+++#` or `@=@++#` or `@@=++#`
* **7**: `@++++#` or `@+@++#`
* **8**: `@@+++#` or `@@@++#`
* **9**: `+@@+++#` or `+@@@++#` or `@+++++#` or `@++@++#` or `@+@=++#` or `@@=+++#` or `@@=@++#`
* **10**: `@=@+++#` or `@=@@++#` or `@@@=++#` (**this is a fairly important test case to check**, as all the possible answers include `=`)
* **11**: `@+@+++#` or `@+@@++#` or `@@++++#` or `@@+@++#`
* **12**: `+@+@+++#` or `+@+@@++#` or `+@@++++#` or `+@@+@++#` or `@=+@+++#` or `@=+@@++#` or `@=@=+++#` or `@=@=@++#` or `@=@@=++#` or `@@=++++#` or `@@=+@++#` or `@@=@=++#`
* **13**: `@@@+++#` or `@@@@++#`
* **14**: `+@@@+++#` or `+@@@@++#` or `@=@++++#` or `@=@+@++#` or `@@+++++#` or `@@++@++#` or `@@+@=++#`
* **15**: `@+@++++#` or `@+@+@++#` or `@@=@+++#` or `@@=@@++#` or `@@@=+++#` or `@@@=@++#`

As a larger test case, the output from input **40** should be `@@@=@@+++#`, `@@@=@@@++#`, `@@@@=@+++#`, or `@@@@=@@++#`.

# Victory condition

As a challenge, the winner is the shortest entry, measured in bytes.

# Answer
> 3 votes
# Oracle SQL 11.2, ~~341~~ 262 bytes

```
WITH e AS(SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4),n(s,v,p,c,i)AS(SELECT'#',0,0,e,1 FROM e UNION ALL SELECT c||s,DECODE(c,'+',1,'@',p,0)+v,v,e,i+1 FROM n,e WHERE i<11)CYCLE s SET y TO 1 DEFAULT 0 SELECT s FROM n WHERE:1=v AND rownum=1;

```

Old version

```
WITH e AS(SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4),n(s,v,p,c) AS(SELECT'#',0,0,e FROM e UNION ALL SELECT s||c,CASE c WHEN'+'THEN 1 WHEN'='THEN 0 WHEN'@'THEN p ELSE 0 END+v,v,e FROM n,e WHERE LENGTH(s)<10)CYCLE s SET y TO 1 DEFAULT 0 SELECT MIN(REVERSE(s))KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s))FROM n WHERE v=:1;

```

:1 the number to represent in Modular SNUSP

Un-golfed :

```
WITH e AS (SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4),
n(s,v,p,c,i) AS
(
  SELECT '#',0,0,e,1 FROM e
  UNION ALL
  SELECT s||c
       , DECODE(c,'+',1,'@',p,0)+v
       , v
       , e
       , i+1
  FROM n,e
  WHERE i<11
) CYCLE s SET y TO 1 DEFAULT 0
SELECT s FROM n WHERE:1=v AND rownum=1;

```

First create a view with 3 lines, one for each symbol used to represent numbers, minus # which is only used at the end of the string :

```
SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4;

```

Then the recursive view n generates every string possible with those 3 symbols, concatenates them to # and evaluates them.

The parameters are :

s : the Modular SNUSP representation of the number being evaluated
v : the decimal value of s computed by the previous iteration
p : v computed by the i-2 iteration
c : the next symbol to concatenate to s
i : the length of s, only needed to get rid of two LENGTH() for golfing purpose

```
DECODE(c,'+',1,'@',p,0)+v

```

If the last symbol is + then add 1
If it is @ add the value of the i-2 iteration
Else the symbol is either # or =. v is initialised with 0 in the init part of the recursive view, so the new v is equal to the previous v in either case.

```
WHERE i<11

```

Every string possible with the 3 symbols is computed, this part insure that the request does not run until the big crunch.

```
CYCLE s SET y TO 1 DEFAULT 0

```

Since there is no rule to the construction of the strings, duplicates are bound to arise. Being in a recursive view Oracle interprets those duplicates as cycles and throw an error if the case is not explicitly taken care of.

```
SELECT s FROM n WHERE:1=v AND rownum=1;

```

Returns the first Modular SNUSP representation that evaluate to the decimal number entered as parameter :1

In my tests that first line is always one of the shortest representations.

In the case your database would not act in the same way, then that last clause should be replaced with

```
SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY i)FROM n WHERE:1=v

```

# Answer
> 2 votes
## JavaScript (ES6), 100 bytes

```
n=>eval("for(a=[['#',0,0]];[[s,t,p],...a]=a,t-n;)a.push(['='+s,t,t],['+'+s,t+1,t],['@'+s,t+p,t]);s")

```

Simple brute-force breadth-first search algorithm.

# Answer
> 2 votes
# Pyth, 41 bytes

```
L?b+ytb@[yttb001)Chb0+hfqQyTs^L"+@="UhQ\#

```

Test suite

How it works:

There are two parts. A recursive function which calculates the value of a SNUSP expression without the trailing `#`, and a brute force routine.

Evalutaion:

```
L?b+ytb@[yttb001)Chb0
L                        Define the function y(b) as follows
 ?b                      If b is nonempty
   +ytb                  The sum of y(tail(b)) and   # tail(b) = b[1:]
   @[       )            The element in the list at location
   Chb                   Character values of the first character.
                         Modular indexing means that
                         + -> 3
                         @ -> 0
                         = -> 1
                         Index 2 is filler.
    [yttb001)            @ adds y(tail(tail(b)). Tail suppresses the error when
                         called on an empty list, so this treats @# as zero, but
                         this can't lead to problems because removing the @ will
                         always make the expression shorter.
                         + adds 1, = adds 0.
 0                       If b is the empty string, return 0

```

Brute force:

```
+hfqQyTs^L"+@="UhQ\#
               UhQ      0 ... Q     # Q is the input
        ^L"+@="         Map that list to all strings formed from the characters
                        "+@=", with that many characters.
       s                Concatenate
  fqQyT                 Filter for strings which evaluate to the input
 h                      Take the first success, which is the shortest due to
                        the order the strings were generated.
+                 \#    Add a '#' and output

```

# Answer
> 1 votes
# CJam, 58

```
ri:M;'#0_]]{_{M&}#_)!}{;{~[2,+1$f+"@=+"\]z\f+\af.+~}%}w=0=

```

Brute force, with a little inspiration from Neil's answer. Try it online

**Efficient version, 107**

```
ri0"#"a{_{:B\:A={'=A0j+}{A(B={'+B0j+}{AB>{BAB-j_N={'@\+}|}N?}?}?}{;_(0j'+\+a\,1>_W%.{j}Na-'@\f++{,}$0=}?}2j

```

Try it online

This uses dynamic programming.

# Answer
> 1 votes
# Haskell, ~~89~~ 86 bytes

EDIT:

* -3 bytes: zipping was shorter than indexing.

Another brute force solution which ended up with a lot of inspiration from Neil's answer. (Although it worked more like isaacg's Pyth before golfing introduced the `l`.)

```
f n=[s|(a,_,s)<-l,a==n]!!0
l=(0,0,"#"):[(a+c,a,d:s)|(a,b,s)<-l,(c,d)<-zip[0,1,b]"=+@"]

```

Try it online!

* `f` is the main function, which takes an integer and returns a string.
* `l` is an infinite list of tuples `(a,b,s)`, shortest representations `s` first, together with their value `a` and the value `b` of the representation with the first char stripped. (as others have also noted/noticed, it's harmless to treat the latter as 0 for `#`.)
* The elements of `l` other than the first one are generated recursively with a list comprehension. `d` is the character that is to be prepended to `s` to generate a new representation in the list, and 'c' is the corresponding increment to `a`.

---
Tags: code-golf, number
---


title: Mean Reputation Change

text:
# Question
Title: Mean Reputation Change
# Challenge

Given a the ID for a PPCG user who has existed for at least a month, output the average amount of reputation they gain per month. You can do this by dividing their reputation by the time since their account was created (which you can find on the profile). This should be returned floored; that is, truncate all of the decimals. (We don't care about the small stuff).

# Input

A single integer, which is the user's ID

# Output

A single integer, representing the floored rep change per month.

# Test Cases

```
input -> output
42649 -> 127 (me)
12012 -> 3475 (Dennis)
8478  -> 3015 (Martin Ender)

```

# Answer
> 2 votes
# JS, ES6 ~~243~~ ~~235~~ ~~168~~ ~~166~~ ~~165~~ 164 bytes

```
i=>fetch(`//api.stackexchange.com/users/${i}?site=codegolf`).then(x=>x.json()).then(x=>alert(~~((y=x.items[0]).reputation/((new Date/1e3-y.creation_date)/2592e3))))

```

Based on the Python answer.

Run this in the console:

```
(i=>fetch(`//api.stackexchange.com/users/${i}?site=codegolf`).then(x=>x.json()).then(x=>alert(~~((y=x.items[0]).reputation/((new Date/1e3-y.creation_date)/2592e3)))))(+prompt("Enter a userId"))

```

-4 thanks to @insert\_name\_here

### Old answer:

```
z=>fetch("//codegolf.stackexchange.com/u/"+z).then(x=>x.text()).then(x=>alert((/([\d,]+) <span class="label-uppercase">repu/.exec(x)[1].replace(/,/g,"")/(((y=/Member for <.+>((\d+) years?, )?(\d+) month/.exec(x))[2]||0)*12+ +y[3]||0))))

```

Improvements welcome! Just fetches the profile page and parses it with regular expressions!

Won't work as a stack snippet, but you can paste this in your console:

```
(z=>fetch("//codegolf.stackexchange.com/u/"+z).then(x=>x.text()).then(x=>alert(Math.floor(/([\d,]+) <span class="label-uppercase">repu/.exec(x)[1].replace(/,/g,"")/(((y=/Member for <.+>((\d+) years?, )?(\d+) month/.exec(x))[2]||0)*12+ +y[3]||0)))))(+prompt("Enter a userId"))

```

# Answer
> 1 votes
## Python ~~3~~ 2, ~~206~~ ~~219~~ ~~201~~ 193 bytes

```
import requests,time
a=requests.get('http://api.stackexchange.com/users/'+str(input())+'?site=codegolf').json()['items'][0]
print a['reputation']/((int(time.time())-a['creation_date'])/2592000)

```

I am estimating the months as the OP suggested, but actually `print(int(b/((d-c)/2592000)))` is a more accurate solution than `print(int(b/int((d-c)/2592000)))` and also saves a few bytes.

---
Tags: code-golf, stack-exchange-api
---


title: Partitions of a list

text:
# Question
Title: Partitions of a list
The answer to this question is much too long

Your challenge is to write a **partitioning function** in the smallest number of characters.

Input example

```
['a', 'b', 'c']

```

Output example

```
[(('a'),('b'),('c')),
 (('a', 'b'), ('c')),
 (('a', 'c'), ('b')),
 (('b', 'c'), ('a')),
 (('a', 'b', 'c'))]

```

The input can be a list/array/set/string etc. whatever is easiest for your function to process

You can also choose the output format to suit yourself as long as the structure is clear.

Your function should work for at least 6 items in the input

# Answer
## GolfScript (43 chars)

```
{[[]]:E\{:v;{:^E+1/{^1$-\[~[v]+]+}/}%}/}:P;

```

or

```
{[[]]:E\{:v;{:^E+1/{^1$-\{[v]+}%+}/}%}/}:P;

```

Same input format, output format, and function name as Howard's solution. There's no brute forcing: this takes the simple iterative approach of adding one element from the input list to the partition each time round the outer loop.
> 3 votes

# Answer
### GolfScript, 51 characters

```
{[[]]\{[.;]`{1$[1$]+@@`1$`{[2$]-@@[+]+}++/}+%}/}:P;

```

The script defines a variable `P` which takes an array from top of the stack and pushes back a list of all partitions, e.g.

```
[1 2] P            # => [[[1] [2]] [[1 2]]]
["a" "b" "c"] P    # => [[["a"] ["b"] ["c"]] [["b"] ["a" "c"]] [["a"] ["b" "c"]] [["a" "b"] ["c"]] [["a" "b" "c"]]]

```

It does also work on larger lists:

```
6, P ,p            # prints 203, i.e. Bell number B6
8, P ,p            # 4140

```

You may perform own tests online.
> 6 votes

# Answer
## J, 51 characters

```
([:<a:-.~])"1~.((>:@i.#:i.@!)#l)<@;/."1[l=:;:1!:1[1

```

Takes input from the keyboard, items separated by spaces:

```
   ([:<a:-.~])"1~.((>:@i.#:i.@!)#l)<@;/."1[l=:;:1!:1[1
a b c
+-----+------+------+------+-------+
|+---+|+--+-+|+--+-+|+-+--+|+-+-+-+|
||abc|||ab|c|||ac|b|||a|bc|||a|b|c||
|+---+|+--+-+|+--+-+|+-+--+|+-+-+-+|
+-----+------+------+------+-------+

```
> 6 votes

# Answer
# Haskell, ~~90~~ ~~87~~ ~~71~~ 66

Saved 5 bytes thanks to nimi.

```
x#[]=[[[x]]]
x#(y:s)=((x:y):s):map(y:)(x#s)
p=foldr((=<<).(#))[[]]

```

Example:

```
*Main> p "abc"
[["abc"],["bc","a"],["ac","b"],["c","ab"],["c","b","a"]]

```
> 1 votes

# Answer
# Python 2, 131 bytes

```
def P(L):
 if len(L)<2:yield[L];return
 for p in P(L[1:]):
	for n,s in enumerate(p):yield p[:n]+[[L[0]]+s]+p[n+1:]
	yield[[L[0]]]+p

```

**Try it online**

Uses this algorithm.
> 0 votes

---
Tags: code-golf, set-partitions
---


# Question
Title: (Can I) Add parentheses to make this true
I saw this recent Puzzling question:

### Add parentheses to make this true

And saw that one answer used a Python script to try all possibilities.

Your challenge is, given an expression (as a string) and an integer, is to make a program that can tell whether you can add parens to make the expression equal the integer.

For example, if the expression is `1 + 2 * 3` and the integer is `9`, than you can add parens like `(1 + 2) * 3`, which equals 9, so the output should be truthy. But if the expression is `1 + 2 - 3 * 4 / 5` and the integer is `9999999999999`, you can't add any amount of parens to make that equal `9999999999999`, so the output should be falsey.

Note that the integer input may be positive or negative, but the expression will only contain positive integers. In fact, the expression will always match `(\d+ [+*/-] )+ \d` (regex). In other words, no parens, no exponents, just `+`, `-`, `*` and `/`. Standard operator order (`*` and `/`, then `+` and `-`).

More test cases:

```
1 + 2 - 3 * 4 / 9 and -1 -> truthy, ((1 + 2) - (3 * 4)) / 9
10 - 9 * 8 - 7 * 6 - 5 * 4 - 3 * 2 - 2 * 1 and 1, falsey, see linked question
10 + 9 - 8 * 7 + 6 - 5 * 4 + 3 - 2 * 1 and 82 -> truthy, (10 + (9 - 8)) * 7 + (6 - 5) * 4 + 3 - 2 * 1
34 + 3 and 15 -> falsey
1 + 2 + 5 + 7 and 36 -> falsey
1 / 10 * 3 + 3 / 10 * 10 and 6 -> truthy, (1/10*3+3/10)*10

```

Any questions?

You may output the expression with parenthesis if it is possible, for instance `(10 + (9 - 8)) * 7 + (6 - 5) * 4 + 3 - 2 * 1` for the last test case. I would prefer this over just a truthy value, but it is up to you. Using `2(5)` for multiplication is not allowed, only `*`.

# Answer
> 2 votes
# Python 2, ~~286~~ ~~285~~ 282 bytes

```
from fractions import*
P=lambda L:[p+[L[i:]]for i in range(len(L))for p in P(L[:i])]or[L]
x,y=input()
x=x.split()
for p in P(['Fraction(%s)'%e for e in x[::2]]):
 try:print 1/(eval(''.join(sum(zip(eval(`p`.replace("['","'(").replace("']",")'")),x[1::2]+[0]),())[:-1]))==y)
 except:0

```

**Try it online**

### Explanation:

This version will print all of the working expressions (with the `Fraction` objects).

```
from fractions import*
# Sublist Partitions (ref 1)
P=lambda L:[p+[L[i:]]for i in range(len(L))for p in P(L[:i])]or[L]
x,y=input()
x=x.split()
# Convert all numbers to Fractions for division to work
n=['Fraction(%s)'%e for e in x[::2]]
# Operators
o=x[1::2]
# Try each partition
for p in P(n):
    # Move parens to be inside strings
    n=eval(`p`.replace("['","'(").replace("']",")'"))
    # Alternate numbers and operators (ref 2)
    x=''.join(sum(zip(n,o+[0]),())[:-1])
    # Prevent division by zero errors
    try:
        # Evaluate and check equality
        if eval(x)==y:print x
    except:0

```

**Try it online**

### References:

1. Partitioning function
2. Alternating zip

<sub>*Saved 3 bytes thanks to Felipe Nardi Batista*</sub>

---
Tags: code-golf, math, arithmetic, decision-problem
---


title: Climb to America

text:
# Question
Title: Climb to America
Now that other users have helped Trump build the wall, its time for you to climb it.

This is an ascii art challenge where you need to output a climbing wall with randomly placed holds.

A climbing wall is made up of panels each of which has between 3 and 10 holds and is 5 panels high. Each panel is 4 characters high and 10 characters across

We use `|` to represent the side of the wall (the arête) and a `-` to represent the edges of panels. The corners of the panels are shown by `+` and the holds are shown as `o`.

Finally, the wall must have `America!` at the top and `Mexico` at the bottom.

Your program should take no input unless input is required to run and should output something that looks similar to the below

This is an example output:

```
  America!
+----------+
|  o       |
|    o o   |
| o    o   |
|  o    o  |
+----------+
|  o       |
|    o o   |
| o    o   |
|  o    o  |
+----------+
|  o       |
|    o o   |
| o    o   |
|  o    o  |
+----------+
|  o       |
|    o o   |
| o    o   |
|  o    o  |
+----------+
|  o       |
|    o o   |
| o    o   |
|  o    o  |
+----------+
   Mexico

```

This may be confusingly set out so it's structured more clearly below

## Input

Zilcho. You should take no absolutely input.

## Output

An ascii-art climbing wall made up of 5 panels, each one 6 lines by 12 columns with `America!` centered at the top and `Mexico` centered at the bottom. Each panel has an identical pattern that is randomly generated by the program. The panel pattern consists of a randomly distributed random number of holds, between 3 and 10.

## Rules

* No input allowed
* I would say "no builtins" but if your language has a builtin for this, I will automatically accept it as the winner.
* This is so shortest code (in bytes) wins.
* The output without holds must be exactly the same as above, again without holds.
* Random is the random defined here

# Answer
> 5 votes
# Jelly, ~~65~~ 57 bytes

**First ever use of the new-fangled , a two-code-point integer string literal** (`⁽¥0` = 2049)

```
⁽¥0ṃ⁾+-W
“K2X)»Ṅø40RẊ<8X+3¤s⁵ị⁾o j@€⁾||Yṭ¢µṄ€5¡Ṗ;⁷“Ç€:;#»

```

Full program taking no input and printing the wall.

**Try it online!**

### How?

```
⁽¥0ṃ⁾+-W - Link 1, panel separator: no arguments
⁽¥0      - literal 2049
    ⁾+-  - literal "+-"
   ṃ     - convert 2049 to base "+-" as if they were [1,0]
       W - wrap in a list   -> ["+----------+"]

“K2X)»Ṅø40RẊ<8X+3¤s⁵ị⁾o j@€⁾||Yṭ¢µṄ€5¡Ṗ;⁷“Ç€:;#» - Main link: no arguments
“K2X)»                                           - "  America!"
      Ṅ                                          - print with line feed
       ø                                         - niladic chain separation
        40                                       - literal 40
          R                                      - range -> [1,2,...,40]
           Ẋ                                     - random shuffle
                 ¤                               - nilad and link(s) as a nilad:
             8X                                  -   random integer between 1 and 8
                3                                -   literal 3
               +                                 -   add
            <                                    - less than? (vectorises)
                   ⁵                             - literal 10
                  s                              - split into chunks of length 10
                     ⁾o <-- a space              - literal "o "
                    ị                            - index into
                           ⁾||                   - literal "||"
                        j@€                      - join with reversed @rguments
                              Y                  - join with line feeds
                                ¢                - call last link (1) as a nilad
                               ṭ                 - tack left to right
                                 µ               - call that p... (monadic chain separation)
                                    5¡           - repeat five times:
                                   €             -   for €ach (separator & panel)
                                  Ṅ              -     print with trailing line feed(separator and panel):
                                      Ṗ          - pop (just the separator now)
                                        ⁷        - literal line feed
                                       ;         - concatenate
                                                 - unused value printed
                                         “Ç€:;#» - "   Mexico"
                                                 - implicit print

```

# Answer
> 4 votes
# JavaScript (ES6), ~~194~~ 160 bytes

```
(h=0,g=p=>h>2?p:g(p.replace(/ /g,_=>" o"[(h+=s=Math.random()>.8)<11&s])))=>`  America!
${t=`+----------+
`}${g(`|          |
`.repeat(4)+t).repeat(5)}   Mexico`

```

---

## Try It

The pattern of the holds will change every 2 seconds in the Snippet below.

```
f=
(h=0,g=p=>h>2?p:g(p.replace(/ /g,_=>" o"[(h+=s=Math.random()>.8)<11&s])))=>`  America!
${t=`+----------+
`}${g(`|          |
`.repeat(4)+t).repeat(5)}   Mexico`
o.innerText=f()
setInterval("o.innerText=f()",2e3)
```

```
<pre id=o>
```

---

## Explanation

* We create an anonymous function, which, although it doesn't take any input, does have 2 parameters with default values:
    + `h`, which is given an initial value of `0`; this will keep count of number of holds on the panel when we go to add them.
    + `g`, which is a recursive function we'll use to create the random pattern of holds on the panel. We'll come back to this in a bit.
* In the main function body, we output a template literal, starting with  `America!\n`.
* We then create the panel divider (`+----------+\n`) and assign it to variable `t`, adding it to the output in the process.
* Next, we create a single line of the panel (`| |\n`), repeat it 4 times and append `t`.
* We call `g`, passing the string from the step above as an argument, via parameter `p`.
* Now, for the hold pattern. Within `g`:
    + We check to see if `h>2` (i.e., do we have 3 or more holds).
    + If so, we return the string `p`.
    + If not, we call `g` again, this time passing a modified copy of `p` as the argument.
    + The modified copy of `p` has the `replace` method used on it, replacing all `<space>` characters with a `<space>` or an `o` by referencing the character index (0 or 1) of the string `<space>o`.
    + We determine the character index by
        1. Calling `Math.random()`, which returns a decimal number between 0 & 1, exclusive.
        2. Checking if that is greater than `.8`. With their being 40 spaces in the panel and there only being a maximum of 10 holds, doing this improves the distribution of the holds across the panel (`.75` would be more accurate, but, hopefully, you'll allow me the concession for the sake of saving a byte!).
        3. The boolean of that check is assigned to variable `s`.
        4. `s` is coerced to an integer (0 or 1) and added to `h`.
        5. We check if `h` is now less than 11 (i.e., do we currently have less than 10 holds) *and* if `s` was true.
        6. That boolean is in turn coerced to an integer, giving us an index in the string.
* Back to our output! We repeat the string returned by `g` 5 times.
* And then simply add  `Mexico` to the end of the string to finish things off. Phew!

---

## Alternative

And, simply because I thought it would have made a nice addition to the challenge: For only 12 extra bytes, we can have a unique pattern of holds on each panel, instead of them all being identical.

```
(g=(p=`|          |
`.repeat(4)+t,h=0)=>h>2?p:g(p.replace(/ /g,_=>" o"[(h+=s=Math.random()>.8)<11&s]),h))=>`  America!
${t=`+----------+
`}${g()+g()+g()+g()+g()}    Mexico`

```

---

### Try It

Again, the patterns of the holds will change every 2 seconds.

```
f=
(g=(p=`|          |
`.repeat(4)+t,h=0)=>h>2?p:g(p.replace(/ /g,_=>" o"[(h+=s=Math.random()>.8)<11&s]),h))=>`  America!
${t=`+----------+
`}${g()+g()+g()+g()+g()}    Mexico`
o.innerText=f()
setInterval("o.innerText=f()",2e3)
```

```
<pre id=o>
```

# Answer
> 4 votes
# PHP, 138 Bytes

```
<?=($p=str_pad)("  America!",349,strtr("
+----------+
|0|
|1|
|2|
|3|",str_split(str_shuffle($p($p(o,rand(3,10),o),40)),10)))."   Mexico";

```

Try it online!

Expanded

```
<?=($p=str_pad)("  America!",349,
#fill the string till a length of 349 with
strtr("
+----------+
|0|
|1|
|2|
|3|",
# before replace the digits with strings in the array
str_split(str_shuffle($p($p(o,rand(3,10),o),40)),10)))
# make a string with o length 3- 10 fill it with spaces to length 40
# shuffle the resulting string and split it into a array of strings with length 10
."   Mexico"; # add the end

```

# Answer
> 3 votes
# Pyth - ~~58~~ 57 bytes, possibly 47

```
Ks(b\+*\-T\+*+++b\|*dT\|4)J<.SxdmdK+3O8+*s.e?/Jk\obK5<K13

```

Try it

Explanation of old solution (I'll update when I have the time):

```
J+++b\+*\-T\+K+J*+++b\|*dT\|4=Y<.SxdmdK+3O8+*s.e?/Yk\obK5J
J+++b\+*\-T\+                                                Create the +----------+, and store as J
             K+J*+++b\|*dT\|4                                Create a full panel (minus bottom border, and without holes), store as K
                                  xdmdK                      Get indices of spaces
                                .S                           Create random permutation of these indices
                               <       +3O8                  Get first several indices (a random number from 3 to 10)
                                             s.e?/Yk\obK     Replace space with 'o' at these indices
                                           +*           5J   Create 5 copies, and add bottom border

```

I think I can get 47 while still technically following the rules:

```
JhO2Ks(b\+*\-T\+*+++b\|.S+*\oJ*d-TJ\|4)+*K5<K13

```

Here, the number of holes is still randomly chosen (from the set {4,8}) and the configuration of those holes is randomly chosen (from the set of configurations where each row is identical)

Try it

# Answer
> 2 votes
## Mathematica, 201 bytes

```
c=Column;s=RandomSample[Tuples[{" ",o," "," "},10],4];t="+----------+";w=c[{t,c[Row/@Table[AppendTo[s[[i]],"|"];PrependTo[s[[i]],"|"],{i,Length@s}]]}];c[Flatten@{"  America!",Table[w,5],t,"   Mexico"}]

```

# Answer
> 1 votes
## Powershell (255 Bytes)

```
echo "  America!"
for($l=0;$l-lt4;$l++){$a=," "*12;$a[0]="|";$a[11]="|";$i=get-random -Max 10 -Min 6;$j=get-random -Max 5 -Min 1;$a[$i]=$a[$j]="o";$b+=($a-join"")}
for($k=0;$k-lt5;$k++){echo +----------+($b-join"`n")}
echo +----------+`n"   Mexico"

```

# Answer
> 1 votes
# Python 2, ~~259~~ ~~224~~ ~~221~~ 218 bytes

```
from random import*
b=[' ']*40
for x in sample(range(40),randint(3,10)):b[x]='o'
a=["+"+"-"*10+"+"]+['|'+''.join(o)+'|'for o in[b[x*10:x*10+10]for x in 0,1,2,3]]
print'\n'.join(['  America!']+a*5+[a[0]]+['   Mexico'])

```

Try it at repl.it

-35 including some hints from @Satan'sSon - thanks!

-3 with thanks to @Wondercricket

# Answer
> 0 votes
## Python 2, 197 bytes

```
from random import*
n=randint(3,10)
s=list('o'*n+' '*(40-n))
shuffle(s)
t=10
S='+'+'-'*t+'+'
print'\n'.join(['  America!']+([S]+['|'+''.join(s[x:x+t])+'|'for x in range(0,40,t)])*5+[S,'   Mexico'])

```

---
Tags: code-golf, ascii-art, random
---


title: Binary Tetris in tweets

text:
# Question
Title: Binary Tetris in tweets
There was recently (a few years back) some buzz on programming websites about an implementation of Tetris in 140 Bytes. ...

It turns out that although it is small, it is a simplified version of Tetris, and not even a complete implementation. Only the core logic function fits in 140 bytes of Javascript. To actually run it, you need another ~840 characters of HTML.

We can do better!
This challenge is to implement a complete version of "Binary Tetris" in as few tweets as possible.

**Binary Tetris Rules:**

* The program must display a playing field containing at least 5 columns and 6 rows of cells.
    + Any method of display may be used, as long as the blocks and the edges of the field are clearly marked.
* There must be at least two types of blocks: `#` and `##`. Additional block support such as `###` or angle blocks shaped like an L will get upvoted by me :P and the most complete game of binary tetris (the most blocks like the original and rotation features) will win my happiness and a possible bounty up 50 rep.
* New blocks are added to the field in the top row, and one block cell must occupy the center column.
* Blocks descend towards the bottom row at a fixed rate. Blocks must descend even without user input.
* When blocks touch the bottom of the field or a lower block, they stop falling and are fixed in place. A new block is added.
* When all the columns in the row are filled with blocks, the row is emptied, and all the fixed blocks above drop down one row.
* The program must respond to keypresses. There must be 3 unique keys that perform the following functions
    + shift current block left 1 column
    + shift current block right 1 column
    + shift current block down 1 row
* Each tweet may only have 140 characters. Using multi-byte characters that can be put in tweets is allowed.
* The rules for what can be in a tweet is simple. If you can tweet it you can use it.
* Interpreted languages follow the same rules. Each section must follow the specs. As long as no run time errors occur (and the rest is valid following the specs) your answer is valid **Golfing Rules:**
Because the original implementation was "tweetable", this challenge requires the same. Entries must be able to be transmitted as a series of tweets (lines of 140 characters or less).
* The first tweet must contain the name of the compiler/interpreter, the name of the program, and any command line arguments

+ it will be saved as file "P0"
* The following N tweets must contain the program as a series of lines.
    + Each tweet will be stored in a file with the name T\<n\>, where n is 1..N
* Each line will be added to the previous lines and compiled or interpreted. It must produce a valid object file or program.
* The program does not need to be functional until the last line is added.
* The program will be run in the following manner *(pseudo-bash)*

```
interp,prog,args = split P0 /\s/
touch $prog
for file in ./T* do
  cat $prog file > $prog
  $interp $prog $args
  die("FAIL") if $? #detect error
done

```

The interpreter must be a commonly available executable program that does not already implement Tetris.

**Scoring**:
Fewest Tweets, including P0. Ties broken by largest number of spare characters (140 * num tweets - total character count).

**Example Entries**

```
chrome a.htm
<html><div id="output"></div></html>
<script>cool java script here</script>

```

Score = 3 (334 spare)

```
cc a.c ;a.out
main(){/*cool prog here*/}

```

Score = 2 (241 spare)

```
tetris

```

Score = 1 (134 spare) *if it were legal, which it's not*

# Special thanks

I was allowed to post this by Ashelly's consent here

# Answer
> 8 votes
# Python 3, Score of 5 Tweets (242 spare, counting P0)

-19 bytes thanks to Jonathan Allan!

The spare count does not take into account newlines from between tweets.

## Tweet 1 (Declaration, 12 bytes)

```
python3 t.py

```

## Tweet 2 (70 bytes)

```
import msvcrt as m,os;f=c=s=0;a=34636833;r=range;p=1<<32;t=30
while 1:

```

## Tweet 3 (129 bytes)

```
 if m.kbhit()and b"\xe0"==m.getch():p=[p>>(not(a|f<<1)&p),p,p<<(not(a<<4|f>>1)&p),p>>5-5*(bool(f&p>>5)or p<t)][ord(m.getch())-77]

```

## Tweet 4 (113 bytes)

```
 c+=1;print("\n".join("".join(".#"[1&(f|p)>>i*5+j]for j in r(5))for i in r(6))[::-1]);os.system("cls")
 if c%t<1:

```

## Tweet 5 (134 bytes)

```
  if f&p>>5or p<t:s=~s;f|=p;p=2-s<<26
  else:p>>=5
 for i in r(0,t,5):
  if f|31<<i==f:b=bin(f)[2:].zfill(t);f=int(b[:-i-5]+b[t-i:],2)

```

## Full Program (449 bytes)

```
import msvcrt as m,os;f=c=s=0;a=34636833;r=range;p=1<<32;t=30
while 1:
 if m.kbhit()and b"\xe0"==m.getch():p=[p>>(not(a|f<<1)&p),p,p<<(not(a<<4|f>>1)&p),p>>5-5*(bool(f&p>>5)or p<t)][ord(m.getch())-77]
 c+=1;print("\n".join("".join(".#"[1&(f|p)>>i*5+j]for j in r(5))for i in r(6))[::-1]);os.system("cls")
 if c%t<1:
  if f&p>>5or p<t:s=~s;f|=p;p=2-s<<26
  else:p>>=5
 for i in r(0,t,5):
  if f|31<<i==f:b=bin(f)[2:].zfill(t);f=int(b[:-i-5]+b[t-i:],2)

```

Does some evil bit point hacking and stores the field and piece in two integers. I'll try and post an explanation soon.

Note: This only runs on Windows, but it could be switched to Linux through `msvcrt``getch` and `"cls"``"clear"`. Additionally, character input doesn't work on Python's IDLE, so I'd recommend running it elsewhere.

# Answer
> 3 votes
# JavaScript (4 Tweets / 343 317 bytes / 243 spare)

Not quite sure about the requirements of the header & Tweets format, so please advise if it needs correcting. Still a bit more can be shaved off I'm certain.

### Tweet 1 - P0 (11 bytes)

```
chrome a.js

```

## Tweet 2 (82 bytes)

```
a=y=z=j=0,onkeyup=b=>R((k=b.keyCode-40)?z*2*(d=k+3?k+1?1:.5:2)&65|j*d&a||(z*=d):0)

```

## Tweet 3 (126 bytes)

```
R=d=>{d||(!(!y||a&j>>5)||(y>25?a=0:(31^31&(a|=j)>>y||(a=a>>y+5<<y|a&-1>>>-y-5>>5),y=0)),y-=5),y>=0||(y=30,z=12/(new Date%3+1))

```

## Tweet 4 (98 bytes)

```
j=z<<y;for(o="",i=30;i--;)o+=1<<i&(a|j)?"#":"_",o+=i%5?"":"<br>";O.innerHTML=o},setInterval(R,300)

```

# Run it in JSFiddle: https://jsfiddle.net/CookieJon/7Lenhcge/

(Click on the output pane to provide focus for keyboard events)

---
Tags: code-challenge, game
---


title: Year progress bar

text:
# Question
Title: Year progress bar
# Create a progress bar indicating year progress

Your code has to output the percentage of the year already passed form 1st of January of the current year.

You have to display a progress bar and the figure.

# Input

You may use builtins to get the current date, if your language doesen't have it you can get date as input but it would be added to your byte count (has to ba a reasonable input format like 2017-05-12)

# Output

**Bar status:** At least 10 different status relating to figure.

**Figure**: can be rounded or float, has to represent `current (or input) day of the year / 365(366) * 100`

> ### Example
>
> Today 2017-05-12
>
> **Output**
>
> ▓▓▓▓▓░░░░░░░░░░ 36%

**Take into account leap years** informal definition (occurring evey 4 years) progess of the year for 12-Feb is 12% on leap years.

Inspiration

# Answer
> 4 votes
# PHP, 69 Bytes

```
for($p=date(z)/(364+date(L))*100^0;$i<100;)echo$i++>$p?_:Z;echo"$p%";

```

Try it online!

date

parameter `z` The day of the year (starting from 0) 0 through 365

parameter `L` Whether it's a leap year 1 if it is a leap year, 0 otherwise.

PHP+HTML, 49 Bytes Non-Competenting

```
<progress value=<?=date(z)?> max=<?=364+date(L)?>

```

add `></progress>` if you don't want that the browser makes the rest

Output for today in the snippet

```
<progress value=131 max=364
```

# Answer
> 2 votes
# Fourier, 68 bytes

***Note, this has been invalidated by rule changes since it does not handle leap years***

```
3d~D4d*30+D~s*100/365~p365(s>0{1}{9618asv~s}s{0}{9617a}i^~i)32apo37a

```

**Try it in FourIDE!**

Outputs the bar like in the question but with 365 segments instead of 15.

Makes the assumption that every year has 365 days and every month has 30 days.

Output for today, 12th May:

```
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 36%

```

## Explanation

Firstly, it looks at the day part of the date and the month part of the month. To get how many days have come before this month, you multiply the month by 30. You then add the day to number of days.

From that point, the calculations are academic and the only extra bytes are for drawing the bar.

# Answer
> 1 votes
# JavaScript (ES8), ~~137~~ ~~135~~ ~~149~~ ~~155~~ ~~137~~ ~~123~~ ~~110~~ ~~108~~ ~~102~~ ~~100~~ ~~98~~ ~~96~~ 92 +7 bytes

Requires `new Date` to be passed as an argument for an additional 7 bytes.

```
n=>"=".repeat(v=(n-new Date(y=n.getFullYear(),0))/864e5/(y%4?3.65:3.66)|0).padEnd(100)+v+"%"

```

If we can't use spaces in the progress bar then 2 bytes will need to be added:

```
n=>"1".repeat(v=(n-new Date(y=n.getFullYear(),0))/864e5/(y%4?3.65:3.66)|0).padEnd(100,0)+v+"%"

```

---

## Try It

```
o.innerText=(n=>"=".repeat(v=(n-new Date(y=n.getFullYear(),0))/864e5/(y%4?3.65:3.66)|0).padEnd(100)+v+"%")(new Date)
```

```
<pre id=o>
```

# Answer
> 1 votes
# Ruby, 72+7 = 79 bytes

Uses `-rdate` flag. -1 byte from Tutleman.

```
t=Date.today;d=t.yday;e=t.leap??366:365;$><<?=*d+?-*(e-d)+" #{d*100/e}%"

```

Today's output (2017-05-17):

```
=========================================================================================================================================------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 37%

```

# Answer
> 0 votes
# C#, 133 bytes

```
using static System.DateTime;int k=Now.DayOfYear*100/(IsLeapYear(Now.Year)?366:365);()=>$" {k}%".PadLeft(103-k,'-').PadLeft(103,'@');

```

Uses '@' and '-' Symbols

# Answer
> 0 votes
## Python 2, 134 bytes

Too long built-ins(

Try it online

```
from datetime import*
D=datetime
N=D.now()
Y=D(N.year,1,1)
P=100*(N-Y).days/-~(D(N.year,12,31)-Y).days
print'H'*P+'-'*(100-P)+'%s%%'%P

```

This line evaluates length of the current year to handle leap ones:

```
-~(D(N.year,12,31)-Y).days

```

# Answer
> 0 votes
# CJam, 75 bytes

```
et3<~@[sS+2m<~e|4%!:L28+T31@"\x1F\x1E\x1F\x1E\x1F\x1F\x1E\x1F\x1E\x1F":i~]@<:++e2 365L+/_'#*100'_*.e<S@'%

```

The bar goes up to 100, so it's a straight percentage bar.

The code for detecting leap years has been "borrowed" from Dennis's answer on another challenge.

The code contains several unprintable characters. They have been replaced by hex codes like `\x1F` in this answer.

Try it online!

or try it for every day in 2017

**Explanation**

```
et                e# Get the date/time.
3<~               e# Get the first three elements ([year month day]) and dump it on the stack.
@                 e# Bring the year to the top.
[                 e# Begin an array:
 sS+2m<~e|4%!     e#  Check if the current year is a leap year, returning 0 or 1.
 :L               e#  Save the result in L.
 28+              e#  Add it to 28.
 T31@             e#  Push 0 and 31, bring (28 or 29) to the top.
                  e#    The 0 is there because you can't reduce an empty array (later...).
 "..........":i~  e#  Dump the char codes of the unprintable string into the array.
]                 e# Close array. This now contains the length of each month.
@                 e# Bring the month to the top.
<                 e# Slice the array before the month, to get only those that have passed.
:+                e# Sum the days in those months.
+                 e# Add that sum to the day of the month.
e2                e# Multiply the result by 100.
365L+/            e# Divide by 365+L to get the percentage.
_'#*              e# Duplicate it, and repeat '#' that many times.
100'_*            e# Push a string containing 100 underscores.
.e<               e# Superimpose the hashes onto the underscores.
S@'%              e# Push a space, bring the percentage to the top, and push '%'.

```

# Answer
> 0 votes
# Python 2, 91 bytes

```
from time import*
t=gmtime()
d=t.tm_yday
n=365+(t.tm_year%4<1)
print'#'*d+'-'*(n-d),d/.01/n

```

Progress bar is 366 characters long on the pseudo-leap years (from the specification) and 365 on others, but uses the actual day count as a numerator (so it will have precision errors on century non-leap years). This could be fixed with `y=t.tm.year;n=[y%4,y%100,y%400].count(0)%2` in place of `n=365+(t.tm_year%4<1)`

**Try it online!** (added tomorrow's output for comparison using extra code in the footer)

# Answer
> 0 votes
# Excel, 159 bytes

Relevant Quote:

```
=LEFT(REPT("|",10*(Now()-DATE(YEAR(Now()),1,0))/(365+(MOD(YEAR(Now()),4)=0)))&"::::::::::",10) & 100*(Now()-DATE(YEAR(Now()),1,0))/(365+(MOD(YEAR(Now()),4)=0))

```

Example Output:

```
|||:::::::38.0821917808219

```

Note that the progress bar rounds down because of how `REPT` works.

---

If using multiple cells is acceptable (I would tend to say it's not), an alternative answer is 97 bytes.

A1: `=YEAR(NOW())`
A2: `=10*(NOW()-DATE(A1,1,0))/(365+(MOD(A1,4)=0))`
A3: `=LEFT(REPT("|",A2)&"::::::::::",10)&10*A2`

---
Tags: code-golf, ascii-art, date
---


title: Calculate gravity on a 1D field

text:
# Question
Title: Calculate gravity on a 1D field
Given a string or list, calculate the effects of gravity on that string/list.

The string will be made of 5 characters:

* `N` has a weight of 2
* `L` has a weight of 1
* `S` has a weight of -2
* `D` has a weight of -1

(the 5th character is whatever you want, it means empty space. I use  (space) in my examples)

Items with negative weight fall upwards (towards the top of the string), and items with positive weight fall downwards (towards the bottom of the string).

When an object collides with something, one of three things happens:

* If the object collides with the top or bottom "walls" of the input, then it just stops.
* If the object collides with another object, their weight/velocity is summed (i.e. `N` and `D` would give `1`). If the result is positive, both objects fall downwards. If it's negative, they fall upwards.
* If an object (let's call it `A`) collides with an object `B`, and `B` is already pinned against the ceiling/floor, `A` will just come to rest against `B`.

All non-occupied spaces of the string/list should be filled with the empty character.

If it wasn't clear already: each character in the string/line is on top of the next one. i.e. `NL` is the same as:

```
N
L

```

And  `SD` is:

```
(blank)
S
D

```

**Test cases:** (uses  (the space character) to show empty space)

```
" L D " -> " LD  " or "  LD "

" SDLN " -> "SD  LN"

" NLLSSD " -> "NLLSSD  "

```

# Answer
> 4 votes
# Haskell, ~~169~~ 180 bytes

```
g s=sum[n|c<-s,(d,n)<-zip"SD LN"[-2..],c==d]
w=elem ' '
h(x:y:r)|(w x&&g y<0)||(w y&&g x>0)=y:h(x:r)|w(x++y)||g x<0=x:h(y:r)|t<-x++y=h$t:r
h r=r
concat.until((==)=<<h)h.map(:[])

```

Try it online! Example usage: `concat.until((==)=<<h)h.map(:[]) $ " SDLN "`.

*Edit:* +11 bytes, now also works for the `" NSDLLD "` test case proposed by @zgrep.

(short) **Explanation:**

`h` works on a list of tokens where initially each char of the input string is token. Until the token list no longer changes, `h` bubbles through the list comparing two tokens `x` and `y` at a time. Depending on the tokens their order is kept (`x:h(y:r)`), they are swapped (`y:h(x:r)`) or combined to a single token (`t<-x++y=h$t:r`).

`g` computes the weight of a token and `w` checks whether a token contains a space.

# Answer
> 2 votes
# OCaml, 379 bytes

```
let rec n f a i=try n f(f a i)(i+1)with _->a
let r s=String.(concat""(let rec w s=if ' '=s.[0]then`E else(function
0->`F|w when w<0->`L|_->`H)(n(fun a i->index"SD LN"s.[i]-2+a)0 0)and l=function
a::b::t->(function`E,`L|`H,`E->l(b::a::t)|_,`L|`H,_|`F,`F|`E,`E->l((a^b)::t)|_->let
c=a::l(b::t)in if b=List.nth c 1 then c else l c)(w a,w b)|x->x in l(n(fun a
i->a@[sub s i 1])[]0)))

```

To test:

```
let () =
    List.iter (fun s -> Printf.printf "`%s`\n" (r s)) [
        "   S S   S S   ";
        "   D D   D D   ";
        "               ";
        "   L L   L L   ";
        "   N N   N N   ";
        "NL";
        " SD";
        " L D ";
        " SDLN ";
        " NLLSSD ";
    ]

```

# Answer
> 1 votes
## Python 2, 322 bytes

Try it online

```
import re
S=input()
C=str.count
D=''
while S!=D:
 D=S
 for i in[(i.group(),i.span())for i in re.finditer('\w+',S)]:
    s=i[0];g=C(s,'N')*2+C(s,'L')-C(s,'S')*2-C(s,'D');l=g<0;b=g>0;c=(1,-1)[b]
    if g:S=S[:i[1][0]-1]*l+re.sub('^ '*l+i[0]+' $'*b,''.join([i[0],' '][::c]),[S[i[1][0]-1:],S[:i[1][1]+1]][b])+S[i[1][1]+1:]*b
print S

```

---
Tags: code-golf, ascii-art, physics
---


title: Was this bite mine?

text:
# Question
Title: Was this bite mine?
Yesterday, I left my sandwich on the table. When I got up today, there was a bite in it... Was it mine? I can't remember...

# Problem:

Take a representation of the sandwich and my bite pattern and tell me if it was my bite or not.

# Examples:

### Example 1:

My bite pattern:

```
..
.

```

Sandwich:

```
#####
.####
..###

```

Output:

```
truthy

```

### Example 2:

My bite pattern:

```
..
..

```

Sandwich:

```
...##
..###
.####

```

Output:

```
falsy

```

### Example 3:

If there is at least 1 rotation that counts as truthy, the output is truthy.

My bite pattern:

```
.
 .
  .

```

Sandwich:

```
##.
#.#
.##

```

Output:

Two possible rotations (biting in the northeast or southwest corner).

```
truthy

```

### Some valid bites:

```
..
.

...
.
.

.
 .
  .

..
. .
 ..

 ..
.
. .

```

### Some invalid bites:

```
..

...
.

..
.
 .

```

# Rules:

* My bite pattern orientation will always be for biting the northwest corner. And must be rotated to bite other corners;
* There will always be 1 and only 1 bite in the sandwich;
* The bite in the sandwich can be in any of the 4 cornes (rotated accordingly);
* Bite patterns will always be symmetrical along the main diagonal;
* Bite patterns will always be at least 1 wide and non empty;
* The sandwich will always be a rectangle with width and height equal or greater than the width of my bite pattern;
* In your input, you can choose any 2 distinct non-whitespace characters to represent the sandwich and the bite;
* Spaces in the bite pattern means that my bite does not touch that part of the sandwich.

# Answer
# Ruby, 103 bytes 101 bytes

```
->b,s{[a=s.map(&:reverse),s,s.reverse,a.reverse].any?{|t|b.zip(t).all?{|y,x|y==x.tr(?#,' ').rstrip}}}

```

Try it online!

Saved 2 bytes by moving the assignment to the first use of a. Apparently Ruby is smart enough to not confuse the commas in the array definition and commas that would arise from simultaneous variable assignment (at least in this case :D)
> 2 votes

# Answer
# Python 2, 134 bytes

```
b,s=input()
a=[''.join(l[::-1])for l in s]
print any(b==[l.replace('#',' ').rstrip()for l in x][:len(b)]for x in(a,a[::-1],s[::-1],s))

```

Takes input as two lists of strings (one for each line). Assumes no trailing whitespace on the lines.

Try it online!

**Examples:**

```
Input: ['..','.'],['#####','.####','..###'] (example 1)
>True

Input: ['..','..'],['...##','..###','.####'] (example 2)
>False

Input: ['',' .'],['#####','#.###','#####'] (no bite in top row)
>True

```
> 2 votes

# Answer
## Python 2, 173 bytes

Try it online

```
S,b=input()
L=len
B=map(lambda x:[y<'.'and'#'or y for y in x]+['#']*(L(S[0])-L(x)),b+[[]]*(L(S)-L(b)))
R=map(lambda x:x[::-1],B)
print S==B or S==B[::-1]or S==R[::-1]or S==R

```

Takes input as two lists of lists of characters.
First - sandwich
Second - bite

First it extends bite array to the size of sandwich array:

```
B=map(lambda x:[y<'.'and'#'or y for y in x]+['#']*(L(S[0])-L(x)),b+[[]]*(L(S)-L(b)))

```

`[y<'.'and'#'or y for y in x]` replaces all spaces to `#`
`(L(S[0])-L(x)),b+[[]]*(L(S)-L(b))` calculates the number of missing element

Then it compares all 4 rotation of this "extended" bite to the sandwich:

```
R=lambda:map(lambda x:x[::-1],B)
print S==B or S==B[::-1]or S==R()or S==R()[::-1]
print any(map(S.__eq__,[B,B[::-1],R(),R()[::-1]])) #longer but pretty

```

lambda R is used to mirror list of lists horizontally

In the linked example sandwich is:

```
##.
#.#
###

```

And bite is:

```
.
 .

```
> 1 votes

---
Tags: code-golf, ascii-art, grid, decision-problem
---