# Question
Title: ID generator with no matching contiguous pairs
Given 2 inputs (m=*minimum starting id*, n=*number of ids*), generate a sequential list of ids, starting at \>=m, made up of the digits 0-9 where no 2 contiguous numbers are the same, e.g. 1232 is ok, 1233 is not (contains 2 '3's next to each other).

**Example**

for m=985, n=6, below shows what ids would be generated/skipped

```
...
985 - ok, 1st
986 - ok, 2nd
987 - ok, 3rd
# skip 0988 (contains '88')
989 - ok, 4th
# Skip 099x (contains '99')
# Skip 100x (contains '00')
1010 - ok, 5th
# Skip 1011 (contains '11')
1012 - ok, 6th
...

```

**Output**

Each ID should be printed on a new line, as for the above sequence:

```
985
986
987
989
1010
1012

```

**Rules**

Standard code-golf rules, lowest byte count wins

# Answer
# Jelly, 6 bytes

```
DIẠµ#Y

```

Try it online!

## How it works?

```
DIẠµ#Y – Full program. Argument: two integers, X and Y.

   µ#  – Return the first Y integers higher than or equal to X that satisfy:
 I     – The increments ...
D      – ... Of their base-10 digits ...
  Ạ    – ... Are all non-0.
     Y – Join the result by newlines.

```
> 3 votes

# Answer
# Brachylog, ~~11~~ 10 bytes

```
{≤ṫẹ~ḅẉ}ᶠ⁾

```

Input is a list of two numbers. Try it online!

## Explanation

The built-in  takes a list or string, like `"1000220"`, and splits it into blocks of equal adjacent elements, like `["1","000","22","0"]`. In this program, I apply the `~` operator to it, so it works in reverse: it takes a list of strings, checks that each string consists of repetitions of a single character and neighboring strings have different characters, and concatenates the list. The predicate  enumerates numbers starting from the first input in increasing order, and I check a condition on them, printing those that satisfy it and stopping when I've found enough.

```
{≤ṫẹ~ḅẉ}ᶠ⁾  Input is a pair, say [M=988,N=3].
{      }ᶠ⁾  Apply this predicate to M and compute the first N results.
 ≤          Take a number that is greater than or equal to M (first up is 988).
  ṫ         Convert it to string: "988"
   ẹ        Split it into substrings of length 1: ["9","8","8"]
     ~ḅ     Apply ḅ in reverse: fails, try next number.
       ẉ    If ḅ succeeds, print the resulting string and a newline.
            This counts as a result of the predicate.

```
> 8 votes

# Answer
# 05AB1E, 9 bytes

```
µÐÔQi=¼}>

```

Try it online!

**Exlpanation**

```
µ           # loop until counter equals n
 Ð          # triplicate current value (initially m)
  Ô         # connected uniqueified on the copy at the top of the stack
   Q        # compare to unmodified for equality
    i  }    # if true
     =      # print current value while leaving it on the stack
      ¼     # increment the counter
        >   # increment current value

```
> 6 votes

# Answer
# Java 8, 83 bytes

```
(m,n)->{for(;n>0;m++)if(!(m+"").matches(".*(.)\\1.*")){System.out.println(m);n--;}}

```

**Explanation:**

Try it online.

```
(m,n)->{                      // Method with two integer parameters and no return-type
  for(;n>0;                   //  Loop as long as `n` is larger than 0
      m++)                    //    After every iteration: increase `m` by 1
    if(!(m+"").matches(".*(.)\\1.*")){
                              //   If there are no repeated adjacent digits:
      System.out.println(m);  //    Print `m`
      n--;}}                  //    And decrease `n` by 1

```
> 4 votes

# Answer
# , ~~111~~ ~~92~~ 71 bytes

```
function(m,n)while(F<n){if(!grepl("(.)\\1",m)){cat(m,'
');F=F+1}
m=m+1}

```

Try it online!

Uses `grepl` to search for repeated digits.
> 3 votes

# Answer
# PowerShell, 59 bytes

```
param($m,$n)for(;$n){if("$m"-notmatch"(.)\1"){$m;$n--}$m++}

```

Try it online!

Basically similar to the other answers. Loops so long as we have numbers left to print (`for(;$n)`), tests whether we have a regex match against a double-digit and if not it puts that on the pipeline and decreases `$n`. Then we increment `$m` and loop again. The elements are picked up from the pipeline and the implicit `Write-Output` gives us a newline-separated output for free.
> 3 votes

# Answer
# Jelly, 9 bytes

```
DŒgZLỊµ#Y

```

Try it online!

If not for the output restriction, `Y` can be removed.
> 2 votes

# Answer
# C, 73 bytes

```
k;f(s,n){for(;n--;printf("%d\n",s++))for(k=s;k;)k=k%10-k/10%10?k/10:++s;}

```

Try it online!
> 2 votes

# Answer
# Perl 6, 56 bytes

```
{.put for grep({none .comb Zeq.comb.skip},$^a..*)[^$^b]}

```

Try it

## Expanded:

```
{  # bare block lambda with placeholder params $a $b

  .put for

  grep(

    {
      none          # create a none junction (True if all are False)

        .comb       # the input split into digits
        Zeq         # Zip using &infix:«eq» operator
        .comb.skip  # the input split into digits starting at second one
    },

    $^a .. *        # a Range starting at the first argument

  )[ ^ $^b ]        # take the first $b values
}

```
> 2 votes

# Answer
# Perl 5.10.0 \+ `-n`, ~~40~~ 39 bytes

```
for(;$i;$_++){!/(.)\1/&&$i--&&say}$i=$_

```

Try it online!

*-1 byte thanks to Xcali*

Input on two lines, first n, then m. Make sure that there is NO newline after m:

```
(echo '6'; echo -n '985') | perl -nE 'for(;$i;$_++){!/(.)\1/&&$i--&&say}$i=$_'

```
> 2 votes

# Answer
# Perl 5, `-ln` 33 bytes

Enter 2 lines on STDIN, first starting id then count

```
#!/usr/bin/perl -ln
$n-=!/(.)\1/&&say,$_++while$n.=<>

```

Try it online!
> 2 votes

# Answer
# Retina, 34 bytes

```
.0A`
"$+"{\/(.)\1/{`.+
*
)C`
.+
*

```

Try it online! Takes `n` and `m` as input on separate lines. Explanation:

```
.0A`

```

Turn off automatic output and delete `n` from the work buffer.

```
"$+"{

```

Repeat `n` times.

```
\

```

Print the value of `m` at the end of the following looped group.

```
/(.)\1/{`

```

Loop while there are contiguous digits.

```
.+
*

```

Convert to unary.

```
)C`

```

Count the number of empty strings, which is one more than the number of characters, thus adding 1 and converting back to decimal. This ends the inner loop.

```
.+
*

```

Having printed `m`, add 1 again in the same way. (The last line doesn't need a `C`` because it's the default stage type for the last line.) The outer loop is implicitly ended.

Note that converting to unary and back to decimal is a little slow; for 39 bytes, a version that doesn't do any conversion:

```
.0A`
"$+"{\/(.)\1/+`.+
$.(*__
.+
$.(*__

```

Try it online! Explanation: `$.(` calculates the length of the rest of the substitution, conveniently without actually expanding it; since the length of `*_` is implicitly the matched value and the length of `_` is of course 1 this just increments the value.
> 2 votes

# Answer
# Pyth, 12 bytes

```
j.f.A.+jZTEQ

```

**Try it here**
> 1 votes

# Answer
# Stax, ~~9~~ 8 bytesCP437

```
ç@F6╕↔┤ú

```

Try it online!

Happen to coincide with @Mr.Xcoder's algorithm in his Jelly answer.

-1 byte per comment by @recursive.

## Explanation

Uses the unpacked format to explain.

```
{$:-|A}gn
{     }gn    Generator, generate given number of values, using block as a filter
                 And implicit output, one element on a line.
             In Stax, only 0 and [] is falsy.

 $           Convert the number to string
  :-         Difference between contiguous digit
    |A       All of them are truthy (may use `:*` as well)

```
> 1 votes

# Answer
# Haskell, ~~94~~ ~~93~~ 91 bytes

-1 byte thanks to Laikoni
-2 bytes thanks to Zgarb

```
import Data.List
a!0=[]
a!b|all(null.tail)$group$show a=show a++'\n':(a+1)!(b-1)|c<-a+1=c!b

```

Try it online!

First Haskell golf.
> 1 votes

# Answer
# Python 2, ~~80~~ 73 bytes

-7 bytes thanks to Mr. Xcoder

```
m,n=input()
while n:
 if~-sum(i*2in`m`for i in`99**9`):print m;n-=1
 m+=1

```

Try it online!
> 1 votes

# Answer
# Haskell, 70 bytes

*-19 bytes thanks to nimi.*

```
s#n=unlines$map show$take n$filter(and.(zipWith(/=)=<<tail).show)[s..]

```

Try it online!

17 bytes dedicated to separating by newlines.
> 1 votes

# Answer
# JavaScript (ES6), 50 bytes

Takes input in currying syntax `(m)(n)`.

```
m=>g=n=>n?/(.)\1/.test(m++)?g(n):~-m+`
`+g(n-1):''

```

Try it online!
> 0 votes

# Answer
# C# (.NET Core), 91 bytes

```
m=>n=>{for(;n-->0;System.Console.WriteLine(m++))for(int k=m;k>0;k=k%10!=k/10%10?k/10:++m);}

```

Port of @Steadybox' C answer.

Try it online.
> 0 votes

# Answer
# Perl 5 (`-nl`), 42 bytes

```
$l=<>;do{!/(.)\1/&&$l--&&say}while++$_&&$l

```

Try it online!
> 0 votes

# Answer
# AWK, 90 bytes

```
{for(j=$1;k<$2;j++){for(a=b=d;++b<=(n=split(j,A,""))&&a!=c=A[b];a=c);if(n<b&&++k)print j}}

```

Try it online!

This is a lot uglier than I thought it would be. I discovered that `AWK` only has back-substitution in its `gensub` function which would make it not very efficient to use for this application.

So this is a very straightforward approach of incrementing an ID counter, splitting the counter at each character, looping through the characters to see if any character is the same as the previous character. If no repeated characters are found, print the ID counter and increment the number of IDs printed.

I will try to refrain from making a statement along the lines of "`AWK` should have the ability to do more robust regular expressions", but it will be difficult.
> 0 votes

# Answer
# Bash + GNU utilities, 35

```
seq $1 inf|egrep -v '(.)\1'|sed $2q

```

Try it online.
> 0 votes

# Answer
# Ruby, 47 bytes

```
->s,n{/(.)\1/!~s&&p(s)&&n-=1;s.next!;n>0&&redo}

```

Try it online!

### If you don't like the quote marks, it's 50 bytes

```
->s,n{puts s if/(.)\1/!~s&&n-=1;s.next!;n>0&&redo}

```

Try it online!
> 0 votes

# Answer
# Pip, 22 bytes

```
--aLb{W`(.)\1`N++a0Pa}

```

Try it online!

### Explanation

```
--aLb{W`(.)\1`N++a0Pa}
                        a,b are command-line arguments
--a                     Decrement a
   Lb{               }  Loop b times:
       `(.)\1`           Regex matching a character followed by itself
      W       N++a       While that regex matches in incremented a:
                  0       No-op
                   Pa    When the while loop exits, a is a valid ID; print it

```
> 0 votes

---
Tags: code-golf, subsequence
---


title: Is my prison secure?

text:
# Question
Title: Is my prison secure?
Your challenge is given an input of a prison layout to work out whether any of the prisoners can escape.

**Input**

Input may be in any reasonable format such as a string, array, array of arrays etc. The input will consist of three characters, in this case `#`, `P` and space. The input will not necessarily contain all three characters.

* `#`: A wall
* `P`: A prisoner
* space: An empty space

An example input will look like:

```
#####
#   #
# P #
#   #
#####

```

**Output**

A truthy/falsey value of whether or not the prison is secure. The prison is only secure if it can hold **all** of the prisoners. If **any** prisoner can escape it is not secure.

A prisoner can escape if they are not fully enclosed by a wall. A diagonal joining is fully enclosed.

**Test cases**

```
############# Truthy
# P #  P#   #
#   #   # P #
#############

############# Truthy
# P    P    #
#   #   # P #
#############

############# Falsey
# P #  P#   #
#   #   # P #
########## ##

####          Truthy
#   #
 #   #
  # P ####
  ####

P             Falsey

###           Falsey
# #
# #
### P

```

# Answer
> 55 votes
## Snails, 13 bytes

```
!(t\P(o\ ),o~

```

Try it online!

Prints `0` for insecure prisons and the size of the input's bounding box for secure prisons.

The idea is to ensure that we can't find a path from a `P` to an out of bounds cell (`~`) moving only orthogonally (`o`) through spaces. The `t` is a teleport so that regardless where we attempt the match it tries all possible starting positions to find a `P`.

# Answer
> 16 votes
# C# (.NET Core), 485 480 474 470 421 408 bytes

The absolutely wrong tool and approach, but nonetheless...

* 7 bytes (and more) saved with the useful tips from TheLethalCoder.
* 4 bytes saved by returning an integer.
* 4 more bytes saved thanks (once again) to TheLethalCoder by replacing `' '` with `32` in the comparisons.
* LOTS of bytes saved by refactoring the code.
* 13 more bytes thanks to (guess who?) TheLethalCoder. :) I keep forgetting his tips and he keeps reminding me them.

```
m=>{var p='P';int a=m.Length,b=m[0].Length,i=0,j,x,y;var c=new System.Collections.Stack();for(;i<a;i++)for(j=0;j<b;j++)if(m[i][j]==p)c.Push(new[]{i,j});while(c.Count>0){var t=(int[])c.Pop();x=t[0];y=t[1];if(x<1|x>a-2|y<1|y>b-2)return 0;foreach(var v in new[]{-1,1}){var z=x>0&x<a-1&y>0&y<b-1;if(z&m[x+v][y]==32){m[x][y]=p;c.Push(new[]{x+v,y});}if(z&m[x][y+v]==32){m[x][y]=p;c.Push(new[]{x,y+v});}}}return 1;}

```

Try it online!

Basically I expand the positions of the P's whenever a white space is around until it reaches (or not) the border of the layout.

Some licenses:

* I use a `char[][]` as the input for the layout.
* Returns `0` as insecure and `1` as secure.

# Answer
> 15 votes
# Perl 5, 69 bytes

*-10 bytes thanks to @Grimy.*

*-2 bytes thanks to @Neil.*

77 byte of code + `-p0` flags.

```
/
/;$_=s/(P| )(.{@{-}})?(?!\1)(?1)/P$2P/s?redo:!/\A.*P|P.*\Z|^P|P$/m

```

Try it online!

Some *short* explanations:
The idea is to put a `P` everywhere the prisoners can go. If any `P` is on the first/last line, or the first/last column, then the prisoners can go there and therefor escape, which means the prison isn't secure.
`s/(P| )(.{@{-}})?(?!\1)(?1)/P$2P/s` replaces a space on the right of or bellow a `P` with a `P`, or a space on the left or on top of a `P`.
Finally, `/\A.*P|P.*\Z|^P|P$/m` checks if a line starts or ends with a `P`, or if there is a `P` on the first or the last line.

# Answer
> 7 votes
## JavaScript (ES6), ~~134~~ 133 bytes

Takes input as an array of arrays of characters. Returns `0` (insecure) or `1` (secure).

```
f=a=>a.map((r,y)=>r.map((c,x)=>c>'O'&&[-1,1,0,0].map((X,i)=>(R=a[y+1-'1102'[i]])&&R[X+=x]?R[X]<'!'?R[o=2,X]=c:0:o=0)),o=1)|o&2?f(a):o

```

### Test cases

```
f=a=>a.map((r,y)=>r.map((c,x)=>c>'O'&&[-1,1,0,0].map((X,i)=>(R=a[y+1-'1102'[i]])&&R[X+=x]?R[X]<'!'?R[o=2,X]=c:0:o=0)),o=1)|o&2?f(a):o

console.log(f([
  [...'#############'],
  [...'# P #  P#   #'],
  [...'#   #   # P #'],
  [...'#############']
]))

console.log(f([
  [...'#############'],
  [...'# P    P    #'],
  [...'#   #   # P #'],
  [...'#############']
]))

console.log(f([
  [...'#############'],
  [...'# P #  P#   #'],
  [...'#   #   # P #'],
  [...'########## ##']
]))

console.log(f([
  [...'####'],
  [...'#   #'],
  [...' #   #'],
  [...'  # P ####'],
  [...'  ####']
]))

console.log(f([
  [...'P']
]))

console.log(f([
  [...'###'],
  [...'# #'],
  [...'# #'],
  [...'### P']
]))
```

# Answer
> 6 votes
## JavaScript (ES6), 121 bytes

```
f=s=>s==(s=s.replace(eval('/( |P)([^]{'+s.search`
`+'})?(?!\\1)[ P]/'),'P$2P'))?!/^.*P|P.*$/.test(s)&!/^P|P$/m.test(s):f(s)

```

Takes input as a newline-delimited rectangular string. Returns 0 for insecure and 1 for secure. Based on my answer to Detect Failing Castles, although it would be more efficient to test for an escaped prisoner at each step, rather than once they'd finished exploring the prison.

# Answer
> 3 votes
# APL (Dyalog Classic), 40 bytes

```
{⊃2≠(××{1⊃⌈/⍵,⍉⍵}⌺3 3)⍣≡(⌽1,⍉)⍣4⊢'# '⍳⍵}

```

Try it online!

`'# '⍳⍵` encode `'#'`, `' '`, `'P'` as 0 1 2

`(⌽1,⍉)⍣4` surround with 1s

`(××{1⊃⌈/⍵,⍉⍵}⌺3 3)⍣≡` max-of-neighbours flood fill of non-zero cells

`⊃2≠` do we not have a 2 at the top left?

# Answer
> 2 votes
# Octave, ~~64~~ 55 bytes

```
@(a,z=padarray(a,[1 1]))~nnz(bwfill(z==35,1,1,4)&z>35);

```

Try it online!

or

Verify all test cases!

Explanation:

```
z=padarray(a,[1 1])       %add a boundary(of 0s) around the scene
F = bwfill(z==35,1,1,4)   %flood fill the prison starting from the boundary
~nnz(F&z>35);             %if position of at least a prisoner  is filled then the prison is not secure

```

# Answer
> 1 votes
# Stax, 35 bytesCP437

```
ä¬my■╡╤▲l@┤êr*⌠\¶ƒläå─▄¶√¿ [Uy⌠Só4↔

```

Try it online!

Surely golfing language without an internal to handle path-finding can do this as well!

## Explanation

Uses the unpacked format to explain.

```
zLz]Y+Mys+y+{{{" P|P ""PP"Rm}Y!My!Mgphh' =
zLz]Y+Mys+y+                                  Surround the original matrix with four borders of whitespaces
            {                      gp         Iterate until a fixed point is found, return the single fixed point
             {              }Y!               Store the block in register Y and execute it
              {" P|P ""PP"Rm                  For each row, flood every space adjacent to a P with P.
                               My!            Transpose the matrix and do the flooding again
                                     hh' =    The final matrix has a space on the upper left corner that has not been flooded by P

```

# Answer
> 1 votes
# SmileBASIC, ~~154~~ 146 bytes

I was hoping an answer using flood fill would be shorter than this.

```
DEF S P
FOR J=0TO 1X=1Y=1FOR I=0TO LEN(P)-1GPSET X,Y,-(P[I]=="#")GPAINT X,Y,-1,-J*(P[I]>@A)X=X*(P[I]>"31")+1INC Y,X<2NEXT
NEXT?!GSPOIT(0,0)GCLS
END

```

Replace `31` with the corresponding ASCII character.

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


# Question
Title: 2016 Time Capsule String: Climb The Integer Ladder
Using the 74 characters from the 2016 time capsule string

```
H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``#|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%

```

write N code snippets all in the same language where:

* The 1st snippet outputs `1`.
* The 2nd snippet outputs `2`.
* The 3rd snippet outputs `3`.
* ... etc. ...
* The Nth snippet outputs `N` (the number, not the literal letter).

A "code snippet" is defined as any of these:

* A full program with no required input that outputs the number normally.
* A function with no required arguments that outputs/returns the number normally.
* A REPL expression that evaluates to the number.

(You may mix and match these three variants in your N snippets.)

The characters you're allowed to use in the combined set of N snippets are **precisely the 74 characters of the time capsule, *plus* `floor(N/2)` extra "wildcard" bytes** that you may use anywhere.

For example, the time capsule contains three `@`'s so in the entirety of your N snippets there may only be up to three `@`'s present unless you decide to use some of your `floor(N/2)` wildcard bytes for additional `@`'s.

Thus, not counting wildcards, the combined set of characters in your N snippets must be a subset of the 74 time capsule characters. Their combined lengths cannot exceed 74. **You may not reuse time capsule characters or wildcard bytes between snippets.**

# Notes

* The are no other limits on snippet length or how many wildcards may be used per snippet.
* You must write *all* snippets for 1 through N. It's not 0 to N-1, not k to N+k-1.
* The snippets must be individual, not one snippet that outputs the list `1, 2, 3, ..., N`.
* Outputs may be floats like `3.0` in place of `3` and you can use a base other than decimal if it is your language's natural base. You must use the same base for all snippets.
* The wildcards are counted as bytes in *your language's encoding*. This will probably be ASCII but e.g. if  counts as one byte in your encoding then you can use it as a single wildcard byte.
* You may use wildcard bytes for multibyte characters. e.g.  is normally three bytes so you could use it in a snippet but it will cost three of your `floor(N/2)` wildcard bytes.
* Newlines such as `\r\n` may be considered one byte.

# Example

In Python, N = 4 is possible just using the REPL. There are `floor(4/2) = 2` wildcards.

1. `1` from the time capsule is an expression that evals to `1`.
2. `2` consists of a single wildcard, namely the `2`. Evals to `2`.
3. `3` also consists of a single wildcard. Evals to `3`. No more wildcards.
4. `4` is luckily in the time capsule and it evals to `4`.

These snippets are short and trivial. A real answer would likely be much more complex.

(Five and beyond in Python may certainly be possible but I'll leave it to the professionals.)

# Scoring

**The answer with the highest N wins;** i.e. the one that climbs the integer ladder the highest.

In case of a tie, the answer that used the fewest wildcard bytes wins.
In case there is still a tie, the answer that used the fewest cumulative characters wins.
If there is *still* a tie, the earlier answer wins.

# Answer
> 9 votes
# CJam, 23 snippets, 11 wildcards, 45 bytes

```
Q!
Q!)
Z
4
4)
6
7
8
9
A
B
C
D
E
F
G
H
I
J
QT|T+e`
O!)1
L!`e`(:)
6mf

```

Try it online! | wildcard counter (ignore the newlines)

# Answer
> 9 votes
# CJam, 25 snippets, 12 wildcards, 64 bytes

```
1
Q!)
Z
4
5
6
L``(*$)#
8
9
T!T
B
C
D
E
F
G
H
I
J
K
O`e`~~!!
B`:)
Q``$e`~~@~@=~+
Q!)4
Amf

```

Try it online!

Wildcards:

```
568BBCDEFGJK

```

I feel that I have to post quickly, before Dennis outgolfing me.

# Answer
> 5 votes
# JavaScript, 10 numbers, 5 wildcards

Remaining characters: `!!#$$%&())))*...:=@@@HILOQQQTTZ\^```eefmpy{|||~~~~~~~~~`

5/5 bonus characters used: `37680`

Programs:

1. `1`
2. ```
!``+!``
```
3. `3`
4. `4`
5. `4|!```
6. `6`
7. `7`
8. `8`
9. `9`
10. `0xA`

I had hoped one of the strings I could make using `\xAB` would be a number, but unfortunately none of the combinations I tried would yield any. The `^` (XOR) character would also be interesting to use, but I currently don't see any opportunities where it can be used to make a great enough number.

If you see another feasible combination, let me know in the comments.

**Edit:** Added #10 thanks to Arnauld

# Answer
> 4 votes
## Pyth, 12 snippets, 20 bytes (6 wildcards)

```
f@

```

Find the first number where root(n,n) is truthy, starting from 1. Output: 1

```
y!H

```

Double not `{}`. Output: 2

```
3

```

Wildcard #1. Output: 3

```
4

```

Output: 4.

```
5

```

Wildcard #2. Output: 5

```
6

```

Wildcard #3. Output: 6

```
7

```

Wildcard #4. Output: 7

```
8

```

Wildcard #5. Output: 8

```
9

```

Output: 9

```
T

```

Preinitialized variable. Output: 10

```
+T!Z

```

Ten plus not zero. Output: 11

```
12

```

Wildcard #6 (`2`). Output: 12

# Answer
> 4 votes
# Octave, 6 numbers, 3 wildcards

```
1: ~~I          % not(not(sqrt(-1))) evaluates to true (or 1)
2: 2            % Wildcard
3: 3            % Wildcard
4: 4
5: (T=4)+~~T    % Create a variable T=4, then add not(not(T)) which evaluates to 1.
6: 6            % Wildcard

```

I still have `1`, `9` and `*` left, but I don't know if it will help me much. I'll see what I can do with those :)

Not easy getting many numbers when not using an Esolang. I'm hoping I'll be able to get one or two more, but I think it'll be hard.

# Answer
> 2 votes
# Pushy, 10 numbers (4 wildcards)

All of these are snippets which leave the result on the stack. You can test this in the **online interpreter** by appending `#` to each snippet (to print the number)

```
A(      \ 1:  Get alphabet and check that 'Z' >= 'Y'. Results in 1 (True)
x&+     \ 2:  Check stack equality (True - both are empty) then duplicate and sum.
3       \ 3:  Push 3 (1 wildcard)
4       \ 4:  Push 4
1 4+    \ 5:  1 + 4 in postfix, leaves 5 on the stack (1 wildcard)
`L`T%   \ 6:  Get character code of 'L' and modulo by T (ten) - leaves 6 on the stack
7       \ 7:  Push 7 (1 wildcard)
8       \ 8:  Push 8 (1 wildcard)
9       \ 9:  Push 9
T       \ 10: Push 10

```

This answer is not yet complete - although it seems unlikely I will get much further.

# Answer
> 1 votes
# 05AB1E, 12 numbers, 6 wildcards

```
 1:    1                                   -> 1
 2:    )O!x                                -> sum([])!*2
 3:    4L`\                                -> 2nd_last(range(1...4))
 4:    4                                   -> 4
 5:    5        # wildcard 1 = 5           -> 5
 6:    6        # wildcard 2 = 6           -> 6
 7:    Tf`~                                -> or(last2(prime_factors(10)))
 8:    8        # wildcard 3 = 8           -> 8
 9:    9                                   -> 9
10:    T                                   -> 10
11:    A`Q!T+   # wildcard 4 = T           -> (y==z)!+10
12:    TÌ       # wildcard 5,6 = T,Ì       -> 10+2

```

# Answer
> 1 votes
## Hexagony, 6 numbers, 3 wildcards, 23 bytes

```
1!@
))!@
)|\@$!
4!%
4)!:
6!@

```

Try it online!

The entire sixth program is made from wildcards.

The only really interesting one is `3`. While I could do that as `4(!@`, that would leave me without a `4` to generate `5` easily, so I went with this instead:

```
 ) |
\ @ $
 ! .

```

Due to the `|`, the `)` on the first line is run twice, before the IP wraps to right-hand corner. `$` skips over the `@`, and then the `\` redirects the IP through the `)` a third time. The IP wraps to the bottom left corner, `!` prints the `3` and `@` terminates the program.

I don't think more than 6 snippets are possible, because there are only 5 printing commands (`!!!!!`) and 5 commands that can be used to terminate the program (`@@@%:`). So after the fifth snippet, we need at least two wildcards per snippet. Hence, even if I managed to get `6` without using a wildcard for it, there wouldn't be enough wildcards left to go to snippet seven.

# Answer
> 1 votes
# JavaScript, 8 numbers, 4 wildcards

```
 1: 1
 2: -~!``
 3: 4+~!$
 4: ~!``*~!``
 5: 4|!$
 6: 0xf^9
 7: 7
 8: 8

```

I might try again later - I'm kind of wasting characters on 2 and 6, when you get down to it.

# Answer
> 0 votes
# Befunge-98, 4 snippets, 18 bytes, 2 wildcards

```
!.@
!:+.@
41-.@    wildcard 1 = -
4.#A9H   wildcard 2 = .

```

**Characters left:**  `!!!$$%&())))*=ILOQQQTTZ\^`````````eefmpxy{||||~~~~~~~~~`

I doubt more are possible, since every extra program will require a form of output, and all `.,` are already used up. If I can figure out a way to make 3 and 5 without a wildcard, then it's possible.

The last program will eventually terminate due to the stack filling up. `A` and `H` with no fingerprints loaded will reflect, and the program will keep pushing 9's.

# Answer
> 0 votes
# SmileBASIC, 12 snippets, 5 wildcards, 31 bytes

```
!.     '. is parsed as the number 0.0; taking the logical not gives 1
!.+!.  'Previous value added to itself
@Q||Q  '@Q is a label string and Q is a variable. For some reason, certain comparison/logical operations between strings and numbers return 3 rather than 1 or 0.
4      '4
#TLIme 'Constant for the text color lime green, value is 5.
6      '6 (wildcard)
7      '7 (wildcard)
8      '8 (wildcard)
9      '9
&HA    'Hexadecimal A
11     '11 (one of them is a wildcard)
4*3    '4 multiplied by 3 (3 is wildcard)

```

I could've also used a variable instead of `.` (variables start at 0), and a string variable (like `Q$`) instead of `@Q`

Characters used: `!!!#&*+...1449@AHILQQTem||`

Wildcards used: `67813`

unused characters:  `!!$$%()))):=@@OQTZ\\^`````````efpxy{||~~~~~~~~~`

---
Tags: code-challenge, number, restricted-source, integer
---


# Question
Title: Find prime factors of sum of non-composite Fibonacci numbers up to n
**The Challenge**

Given a number, find the sum of the non-composite numbers in the Fibonacci sequence up to that number, and find the prime factors of the sum.

For example, if you were given 8, the non-composite numbers would be 1, 1, 2, 3, and 5. Adding these up would get 12. The prime factors of 12 are 2, 2 and 3, so your program should return something along the lines of `2, 2, 3` when given 12.

**The Objective**

This is Code Golf, so the answer with the least amount of bytes wins.

# Answer
# Neim, 8 bytes

```
fΣ}

```

Doesn't work on TIO, but works locally.

Explanation:

```
            Inclusive range [1 .. input]
 f           Fibonacci numbers
           Get elements that are only in both lists
   Σ         Keep each element where running the following is falsy
              Check if composite
     }       Close loop
             Sum
            Prime factors

```
> 2 votes

---
Tags: code-golf, number-theory, primes, fibonacci
---


title: The cell at the end of the rainbow

text:
# Question
Title: The cell at the end of the rainbow
We all know of, or at least have heard of, **brainfuck**, one of the most famous and influential esoteric languages. While these days most implementations use an infinite tape, the original compiler by Urban Müller had a tape of 30000 cells. A little known fact\* is that there is actually a special value at the end of the tape, something that is almost never interacted with in a typical brainfuck program.

While you could print this value with 29999 `>`s and a `.`, brainfuck is known for its short and concise solutions, so your aim is to print this value with the minimum number of characters.

<sup>\*fiction</sup>

### Rules:

* A refresher on the brainfuck instructions:
    + `+`/`-`: Increment/decrement the current cell, wrapping from 255 to 0 when 255 is incremented and vice-versa
    + `<`/`>`: Move the pointer left/right on the tape
    + `.`: Print the value of the current cell.
    + `[`: Jump to the corresponding `]` if the value at the cell is 0
    + `]`: Jump to the corresponding `[` if the value at the cell is not 0
* In this case `,` (Get input) does nothing, as the original compiler leaves the cell unchanged on EOF, and this program should receive no input.
* The tape is initially filled with all 0s, except for cell 30000, which contains an unknown value
* The pointer starts at cell 1 and should end on cell 30000, having printed it.
* Cells to the left of 1 and to the right of 30000 have undefined behaviour, so solutions should **not** visit these cells.
* Note that the value at 30000 ~~is~~ may be a 0, so simply looping until you hit a non-zero cell will not work.
* You should print *only* the value at cell 30000
* The shortest solution wins!
    + Tie-breaker is the more efficient program (executes in the least steps), followed by the fastest submission time.

**Tip:** Esolanging Fruit suggests using https://copy.sh/brainfuck to test your code. The specs are as described in this challenge, and you can select the `abort` option so your program halts if it goes out of bounds.

# Answer
# 50 bytes

```
>+[>+[<]>->+]>-<<[>>-------[[>]+[<]>-]<<-]>>>[>]>.

```

Try It Here!

The first section (`>+[>+[<]>->+]>-<<`) sets up the tape as

```
0*12 121' 0 110

```

The next section (`[>>-------[[>]+[<]>-]<<-]`) iterates 121 times, appending 249 `1`s to the end of the tape each time. If you're quick with math, you might realise this 121\*249 results in 30129 `1`s, but the first iteration has the leftover 110 to deal with and only appends (`110-7`) 103 `1`s to the tape, meaning there's only 29983 `1`s. The final tape looks like:

```
0*12 0' 0 0 1*29983 0 ???

```

And a final `>>>[>]>.` to print the value.

Some other algorithms of note:

* 252\*119 = 29988 (also 50 bytes)
* 163\*184 = 29992 (56 bytes)
* 204\*147 = 29988 (60 bytes)
* 153\*196 = 29988 (56 bytes)
* 191\*157 = 29987 (57 bytes)
* 254\*118 = 29972 (56 bytes)
    + This one is the one I consider the next closest to beating 50, since the extra bytes are basically just travelling the extra distance. If I could find an algorithm that generates 118 and travels further than 14 cells, this could beat it.
> 13 votes

# Answer
# 54 Bytes

```
------[>+++<--]>[->----[-[->+<]<[->+<]>>]<]>>>>>>>>>>.

```

119 x 252 = 29988. Straightforward nested loop.

I used this tool to verify that the pointer stops at 29999.
> 19 votes

# Answer
# 81

```
-[+>+[<]>++]<<+[-->-[-<]>]>-[>[->+[[->+<]<]>>>]<[-<<+>>]<<<-]>-------[[->+<]>-]>.

```

This moves over by 150 cells 200 times.

This is much longer than I'd like it to be, and there's a serious obstacle to golfing:

I no longer know why I works.

This is littered with compensations for off-by-ones to the point where some of them could probably cancel out. I've added and deleted various segments so much that I no longer remember why I put certain things where they are (for example, why does the first part initialize the tape cells to 199 and 151 instead of 200 and 150?).

Here is my commented version of this monstrosity anyways, in the hope that I (or someone else) might find them useful:

```
-[+>+[<]>++]<<+[-->-[-<]>]>-

0 0 0 199' 155

[
  n' k 0
  >[
    n k' j
    ->+[[->+<]<]>
    0' n k－1 j＋1 OR
    n 0 0' j＋1
    >>
  ]
  0*k n 0 0 k 0'
  <[-<<+>>]<<<-
  0*k n－1' k
]
>-------[[->+<]>-]>.

```
> 4 votes

---
Tags: code-golf, brainfuck
---


title: Counting Sheep to Fall Asleep

text:
# Question
Title: Counting Sheep to Fall Asleep
Most people are familiar with the trope about counting sheep to fall asleep. There's a herd of sheep, some of them jumping over a fence, and you count the sheep as they jump. Supposedly, this helps quiet your mind and gets you into a sleep-like state so that you'll fall asleep.

Here's an ASCII sheep facing to the right, waiting to be counted:

```
'00^>
 ||

```

Here's an ASCII sheep jumping over a fence:

```
'00^>
 /\
 ++

```

Here's one facing to the left, having already been counted:

```
<^00'
  ||

```

### The Challenge

Given two input integers, `n` and `m`, with `n > 2` describing how many sheep total, and `m > 0` saying how many sheep have already been counted, output an ASCII art representation of counting sheep to fall asleep.

**Now for the twist:**

* Due to the size of the pens the sheep are in, the top row can only hold a maximum of `10` sheep, not counting the currently jumping sheep which must also always be in the top row.
* The subsequent rows cannot have the sheep outside their respective pens (you can't have more sheep on the left in the second row than you do in the first row, and same for the right).
* If there are `11` or more total sheep, the top row must have `10` plus the jumping sheep in it.
* Leading/trailing whitespace, and whitespace between the sheep doesn't matter, so long as:
    1. There is a minimum of one whitespace character between sheep
    2. All the characters line up appropriately.

So long as these rules are met, the actual arrangement of the sheep is up to your implementation.

### Examples

For example, here is `n=3` and `m=1`, the simplest case.

```
         '00^>
'00^>     /\      <^00'
 ||       ++        ||

```

Here is `n=11` and `m=6`, the most sheep that can fit on one horizontal line.

```
                        '00^>
'00^> '00^> '00^> '00^>  /\   <^00' <^00' <^00' <^00' <^00' <^00'
 ||    ||    ||    ||    ++     ||    ||    ||    ||    ||    ||

```

Here's a different example of that, with `n=11` and `m=1`

```
                                                      '00^>
'00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^>  /\   <^00'
 ||    ||    ||    ||    ||    ||    ||    ||    ||    ++     ||

```

A bigger example with `n=30` and `m=12`

```
                                                '00^>
'00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^>  /\   <^00' <^00'
 ||    ||    ||    ||    ||    ||    ||    ||    ++     ||    ||

'00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^>       <^00' <^00'
 ||    ||    ||    ||    ||    ||    ||    ||           ||    ||

'00^>                                                 <^00' <^00'
 ||                                                     ||    ||

                                                      <^00' <^00'
                                                        ||    ||

                                                      <^00' <^00'
                                                        ||    ||

                                                      <^00' <^00'
                                                        ||    ||

```

Here's an example with `n=17` and `m=2`

```
                                                '00^>
'00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^>  /\   <^00' <^00'
 ||    ||    ||    ||    ||    ||    ||    ||    ++     ||    ||

'00^> '00^> '00^> '00^> '00^> '00^>
 ||    ||    ||    ||    ||    ||

```

Here's an example with `n=19` and `m=3`

```
                                          '00^>
'00^> '00^> '00^> '00^> '00^> '00^> '00^>  /\   <^00' <^00' <^00'
 ||    ||    ||    ||    ||    ||    ||    ++     ||    ||    ||

'00^> '00^> '00^> '00^> '00^> '00^> '00^>
 ||    ||    ||    ||    ||    ||    ||

'00^>
 ||

```

Note that all of these are *examples*. For the last one, you may wind up creating a vertical array of sheep on the right-hand side, which will allow the left hand side to fit onto two rows instead. Or maybe a 2x2 square of sheep on the right-hand side, which would also fit the left-hand side sheep onto two rows. Etc.

## I/O and Rules

* Input can be taken in any reasonable format and by any convenient method.
* Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, returned as a list of strings, returned as a single string, etc.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# APL (Dyalog Unicode), 118 bytesSBCS

Anonymous infix lambda. Takes `n` as left argument and `m` as right argument. Returns a nested array result, but the default display of this nested array follows specifications. Uses up to nine columns for counted sheep and remaining columns for waiting sheep.

```
{(r⍴(×/r←d,⍨⌈w÷d←10-⍵⌊⊢/r)↑w⍴(w←⍺-⍵+1)⍴⊂s@2⌽S)(↑(s←'>',⍨¯1↓b)' /\' ' ++')(r⍴(×/r←9,⍨⌈⍵÷9)↑⍵⍴⊂S←⌽↑''(b←'''00^<')' ||')}

```

Try it online!

`{``}` anonymous lambda;  is left argument,  is right argument

This function has three distinct parts: **Waiting**, **Jumping**, and **Counted**. Each one is parenthesised, causing the result to be a three-element list.

### Counted `(r⍴(×/r←9,⍨∘⌈⍵÷9)↑⍵⍴⊂S←⌽↑''(b←'''00^<')' ||')`

`''(``)' ||'` the three lines of a mirrored counted sheep, the middle one being:

`b←'''00^<'` the body and is assigned to `b`

mix the list of strings into a character matrix (padding with spaces)

mirror that

`S←` assign to `S` (big **S**heep)

enclose it so we can deal with it as a unit

`⍵⍴` use the number of counted sheep to cyclically reshape that

`(``)↑` take the following number of elements from that (padding with prototypical items, i.e. the same array but with all characters replaced by spaces)

`⍵÷9` a ninth of the number of counted sheep

round up

`9,⍨` append 9 to that

`r←` assign to `r` (what we will **r**eshape with; rows and columns)

`×/` product of that list (this is how many elements we need, including fills)

`r⍴` reshape that to an array with the dimension lengths `r`

### Jumping `(↑(s←'>',⍨¯1↓b)' /\' ' ++')`

`(``)' /\' ' ++'` the three lines of a jumping sheep, the first one being:

`¯1↓b` drop the last character from `b`

`'>',⍨` append a right-facing head

`s←` store in `s` (small **s**heep)

mix the list of strings into a character matrix (padding with spaces)

### Waiting `(r⍴(×/r←d,⍨⌈w÷d←10-⍵⌊⊢/r)↑w⍴(w←⍺-⍵+1)⍴⊂s@2⌽S)`

`⌽S` mirror `S`

`s@2` put `s` **at** line 2 of that (replacing the current data there)

enclose it so we can deal with it as a unit

`(``)⍴` cyclically reshape that to the following size:

`⍵+1` the number of counted sheep plus one

`⍺-` subtract that from the total

`w←` assign to `w` (**w**aiting)

`(``)↑` take the following number of elements from that (padding with prototypical items)

`⊢/r` the rightmost element of `r` (i.e. the number of used columns for counted sheep)

`⍵⌊` the minimum of total and that

`10-` subtract that from ten

`d←` assign to `d` (**d**ifference; missing columns)

divide `w` by that

round up (gives number of needed rows)

`d,⍨` append `d`

`r←` assign to `r` (what we will **r**eshape with; rows and columns)

`×/` product of that list (this is how many elements we need, including fills)

`r⍴` reshape that to an array with the dimension lengths `r`
> 9 votes

# Answer
# Javascript, ~~281~~, ~~293~~, 288 Bytes

```
a="      ";c=((n,m)=>{b="";for(i=0;i<(q=m>(o=(l=(t=n-m-1)?t:0)/9)?m:o);++i){for(j=0;j<3;++j){b+=[a,"'00^> "," ||   "][j].repeat(r=l>i*9?(z=o-i)>1?9:Math.ceil(z*9):0)+a.repeat((l>9?9:l)-r)+(i?"     ":["'00^>"," /\\  "," ++  "][j])+[a," <^00'","   || "][j].repeat(m>i?1:0)+"\n"}}return b});

```

### Be careful when using the below snippet, there's a heavy risk of sudden induced narcolepsy.

```
  <form id="form">
    <input type="text" name="n" placeholder="n (sheep total)">
    <input type="text" name="m" placeholder="m (sheep in right hand field)">
    <button type="submit">Let's Go!</button>
  </form>

  <pre id="output">
  </pre>

  <script>
    a="      ";c=((n,m)=>{b="";for(i=0;i<(q=m>(o=(l=(t=n-m-1)?t:0)/9)?m:o);++i){for(j=0;j<3;++j){b+=[a,"'00^> "," ||   "][j].repeat(r=l>i*9?(z=o-i)>1?9:Math.ceil(z*9):0)+a.repeat((l>9?9:l)-r)+(i?"     ":["'00^>"," /\\  "," ++  "][j])+[a," <^00'","   || "][j].repeat(m>i?1:0)+"\n"}}return b});
      form.addEventListener("submit", function(e){
        e.preventDefault();

        var n = parseInt(form.n.value);
        var m = parseInt(form.m.value);

        if(n != NaN && m != NaN){
          if(m > n){
            output.innerText = "C'mon man, how can you have more sheep in the right hand field than there are sheep in general?";
          }
          else{
            output.innerText = c(n, m);
          }
        }
        else{
          output.innerText = "Numbers only please.";
        }
      });
    </script>
```
> 3 votes

# Answer
# C, 392 bytes

*Thanks to @Jonathan Frech for saving a byte!*

```
#define F;for(
x,y,k;p(L,a,b,t)char L[][78];{F k=5;k--;)L[x=a*4+(t<2)][y=b*6+k]=t?"'00^>"[k]:"<^00'"[k];L[++x][y-=~!t]=47;L[x][++y]=92;L[x][--y]=L[x+=(t>1)][y]=t<2?'|':43;}i,l;f(n,m){char L[i=n*4][78]F;i--;){F L[i][l=77]=0;l--;)L[i][l]=32;}F l=n+~m;++i<l&&i<9+!m;)p(L,0,i,1);l-=i;p(L,0,i++,2)F;i<11&&m--;)p(L,0,i++,0)F i=0;l--;)p(L,++i,0,1)F i=1;m-->0;)p(L,i++,10,0)F l=0;l<i*4;)puts(L+l++);}

```

Try it online!

**Unrolled:**

```
#define F;for(

x, y, k;
p(L, a, b, t) char L[][78];
{
    F k=5; k--;)
        L[x=a*4+(t<2)][y=b*6+k] = t ? "'00^>"[k] : "<^00'"[k];

    L[++x][y-=~!t] = 47;
    L[x][++y] = 92;
    L[x][--y] = L[x+=(t>1)][y] = t<2 ? '|' : 43;
}

i, l;
f(n, m)
{
    char L[i=n*4][78]
    F; i--;)
    {
        F L[i][l=77]=0; l--;)
            L[i][l] = 32;
    }

    F l=n+~m; ++i<l&&i<9+!m;)
        p(L,0,i,1);

    l-=i;
    p(L,0,i++,2)

    F; i<11&&m--;)
        p(L,0,i++,0)

    F i=0; l--;)
        p(L,++i,0,1)

    F i=1; m-->0;)
        p(L,i++,10,0)

    F l=0; l<i*4;)
        puts(L+l++);
}

```
> 2 votes

# Answer
# Python 2, ~~222~~ 277 bytes

```
n,m=input();n-=m+1
s=" '00^>"
j=1;L='  ||  '
a,b=[[[5,5],[10-m,m]][m<9],[n,10-n]][n<9]
print' '*6*a+s
while n>0 or 0<m:N,M=min(n,a),min(m,b);n-=a;m-=b;print '%-*s'%(6*a,N*s),'%5s'%('/\  '*j)+'%*s'%(6*b,M*" <^00'")+'\n'+'%*s'%(-6*a,N*L),'%5s'%('++  '*j),'%*s'%(6*b,M*L)+'\n';j=0

```

Try it online!
> 1 votes

# Answer
# AWK, 293 bytes

```
{f=" '00^>"
l="  ||  "
L="  /\\   "
p="  ++   "
Y=$2
X=$1-Y-1
E="      "
x=$1>11?Y<5?10-Y:X>5?5:X:X
y=$1>11?X<5?10-X:5:Y
printf"%"6*(x+1)"s\n",f
for(;X>0||Y>0;A=B=""){for(i=0;i++<x;B=B (X>=0?l:E))A=A (--X>=0?f:E)
A=A L
B=B p
for(i=0;i++<y&&--Y>=0;B=B l)A=A"<^00' "
print A"\n"B"\n"
L=p=E" "}}

```

Try it online!

I tried using string substitutions to avoid some loops, but it took a lot more code.

**Explanation**

```
{f=" '00^>"    Let's assign
l="  ||  "     some variables
L="  /\\   "   for the ASCII
p="  ++   "    pieces
Y=$2        The number of sheep that have already jumped
X=$1-Y-1    Sheep patiently waiting to jump
E="      "  A string to keep things spaced properly
x=$1>11?Y<5?10-Y:X>5?5:X:X  If there's enough sheep, let's use 5 per column
y=$1>11?X<5?10-X:5:Y        Otherwise, use enough to get 11 sheep in first row
printf"%"6*(x+1)"s\n",f     Print the top part of the jumping sheep
for(;X>0||Y>0;A=B=""){      Loop until we've printed all the sheep
  for(i=0;i++<x;              Loop over waiting sheep in this row
    B=B (X>=0?l:E))             Build the "legs" string
      A=A (--X>=0?f:E)            Build the "bodies" string
  A=A L                       Add the legs and post
  B=B p                       for the jumping sheep
  for(i=0;i++<y&&--Y>=0;   Loop over the jumped sheep in this row
    B=B l) A=A"<^00' "     Add to the "legs" and "bodies" string
  print A"\n"B"\n"         Print what we've got so far
  L=p=E" "                 Prevent the jumping sheep's parts from printing lots of times
}}

```

I must say the sheep art is rather cute. :)
> 0 votes

# Answer
# Charcoal, 98 bytes

```
Ｎθ≔⁻⊖ＮθηＦ⟦⟦00¶/\¶++ θ⌊⟦⌈⟦⁵⁻χη⟧θ⟧⟧⟦0^>¶\¶+  η⌊⟦⌈⟦⁵⁻χθ⟧η⟧⟧⟧«Ｊ⁰¦⁰‖Ｔ§ι⁰↗Ｆ§ι¹«<^00'¶  || ↗¿¬﹪⊕κ§ι²”|Ｉ4Ｏ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｎθ

```

Input the number of sheep that have already been counted.

```
≔⁻⊖Ｎθη

```

Input the total number of sheep and calculate how many still need to be counted.

```
Ｆ⟦⟦00¶/\¶++ θ⌊⟦⌈⟦⁵⁻χη⟧θ⟧⟧⟦0^>¶\¶+  η⌊⟦⌈⟦⁵⁻χθ⟧η⟧⟧⟧«

```

Create an array of two arrays. Each array has the following elements:

* A string containing half of the jumping sheep
* The number of sheep on that side of the fence
* The number of sheep in one row on that side of the fence, which is either
    + the number of sheep on that side of the fence, if fewer than 5, or
    + 10 - the number of sheep on the other side of the fence, if fewer than 5, or
    + 5, if both sides have at least 5 sheep

```
Ｊ⁰¦⁰‖Ｔ§ι⁰↗

```

Reflect the canvas and print the half jumping sheep.

```
Ｆ§ι¹«

```

Loop through the sheep on that side.

```
<^00'¶  || ↗

```

Print a sheep.

```
¿¬﹪⊕κ§ι²”|Ｉ4Ｏ

```

If this is the end of the row then print some newlines and spaces to get to the start of the next sheep.
> 0 votes

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


title: Count stacking sequences

text:
# Question
Title: Count stacking sequences
Given a list of stack heights, calculate the number of ways those heights could have been arrived at by stacking blocks one at a time. Shortest code wins.

Test cases:

```
[2, 2] 6
[3,3,3] 1680
[1,5,9,1] 480480
[] 1
[10] 1
[2,2,2,10] 720720

```

Reference Python implementation:

```
def stacking_count(stacks):
     if sum(stacks) == 0:
         return 1
     count = 0
     for i, n in enumerate(stacks):
         if n == 0:
             continue
         stacks[i] -= 1
         count += stacking_count(stacks)
         stacks[i] += 1
     return count

```

# Answer
# Python 3, 85 bytes

```
f=lambda a:sum(f(a[:i]+[a[i]-1]+a[i+1:])for i in range(len(a))if a[i])if sum(a)else 1

```

Try it online!
> 0 votes

# Answer
# Jelly, 6 bytes

```
;@S!:/

```

Try it online!

-7 bytes thanks to Jonathan Allan
> 0 votes

---
Tags: code-golf, combinatorics, counting
---


title: Visit and exit an array

text:
# Question
Title: Visit and exit an array
## Challenge:

### Input:

* An integer `n` (`> 0`)
* An integer-array `a` of size `> 0` (which contains positive and negative values, but no zeroes)

### Output:

1. First output the first `n` items
2. Then take the last item you've outputted (let's call it `e`), and go `e` steps forward if `e` is positive, or `abs(e)` steps backwards if `e` is negative. And from that position, output `abs(e)` items (again either going forward / backwards depending on positive / negative).
3. Continue the process until you've either:
    * Outputted every distinct value of the array
    * Output one of the items at least `n` times

### Example 1:

```
n = 3
a = [2, 6, 9, 2, -4, -1, 3, 5, -7, 3, -2, 2, 2, 3]
     ^  ^  ^  ^   ^   ^  ^  ^   ^  ^   ^  ^  ^  ^
     A  B  C  D   E   F  G  H   I  J   K  L  M  N   ← Added as clarification

```

**Step 1:**
\- Starting position `A`, `n=3`
\- Output line 1: `2, 6, 9` (`A-C`)
\- `e = 9` (`C`)
\- Distinct values already visited: `2, 6, 9`
\- Distinct values left to visit: `-7, -4, -1, -2, 3, 5`
\- Amount of times we've visited the items: `A=1, B=1, C=1`

**Step 2:**
\- Starting position `L` (9 steps forward from position `C`), `e=9`
\- Output line 2: `2, 2, 3, 2, 6, 9, 2, -4, -1` (`L-N` \+ `A-F`)
\- `e = -1` (`F`)
\- Distinct values already visited: `-4, -1, 2, 3, 6, 9`
\- Distinct values left to visit: `-7, -2, 5`
\- Amount of times we've visited the items: `A=2, B=2, C=2, D=1, E=1, F=1, L=1, M=1, N=1`

**Step 3:**
\- Starting position `E` (1 step backwards from position `F`), `e=-1`
\- Output line 3: `-4` (`E`)
\- `e = -4` (`E`)
\- Distinct values already visited: `-4, -1, 2, 3, 6, 9`
\- Distinct values left to visit: `-7, -2, 5`
\- Amount of times we've visited the items: `A=2, B=2, C=2, D=1, E=2, F=1, L=1, M=1, N=1`

**Step 4:**
\- Starting position `A` (4 steps backwards from position `E`), `e=-4`
\- Output line 4: `2, 3, 2, 2` (`A` \+ `N-L`)
\- `e = 2` (`L`)
\- Distinct values already visited: `-4, -1, 2, 3, 6, 9`
\- Distinct values left to visit: `-7, -2, 5`
\- Amount of times we've visited the items: `A=3, B=2, C=2, D=1, E=2, F=1, L=2, M=2, N=2`

We've now visited `A` `n (3)` amount of times, so we stop.

### Example 2:

```
n = 2
a = [2, 3, 2]
     ^  ^  ^
     A  B  C   ← Added as clarification

```

**Step 1:**
\- Starting position `A`, `n=2`
\- Output line 1: `2, 3` (`A-B`)
\- `e = 3` (`B`)
\- Distinct values already visited: `2, 3`
\- Distinct values left to visit: none
\- Amount of times we've visited the items: `A=1, B=1`

We've already outputted all distinct values, so we stop.

## Challenge rules:

* Input and output are flexible. Input can be an array/list of integers, string with delimiter, etc. Output can be to STDOUT, can be a 2D integer array/list, a string, etc.
* As you may have noticed from the test cases, you wrap around the array if you're out of bounds.
* The input `n` can also be larger than the size of `a` (i.e. `n = 5, a = [2, 3, 4]` will have an output of `2, 3, 4, 2, 3`, and will stop there since we've outputted all distinct values already).
* Input array can contain any reasonable integer (including those larger than the array-size) excluding `0`.
* If the input for `n` is 1, it means the output will always be just the first item.

## General rules:

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

## Test cases:

```
Input: 3, [2, 6, 9, 2, -4, -1, 3, 5, -7, 3, -2, 2, 2, 3]
Output: [[2, 6, 9], [2, 2, 3, 2, 6, 9, 2, -4, -1], [-4], [2, 3, 2, 2]]

Input: 2, [2, 3, 2]
Output: [[2, 3]]

Input: 5, [2, 3, 4]
Output: [[2, 3, 4, 2, 3]]

Input: 1, [2, 1, -3]
Output: [[2]]

Input: 2, [1, 1, 2, -3]
Output: [[1, 1], [2], [1, 1]]

Input: 17, [1, 4, 9]
Output: [[1, 4, 9, 1, 4, 9, 1, 4, 9, 1, 4, 9, 1, 4, 9, 1, 4]]

Input: 2, [1, -2, 3, -4, 5, -6, 6, -5, 4, -3, 2, -1, 1, 1, 1]
Output: [[1, -2], [1, 1], [1]]

Input: 4, [1, -2, 3, -4, 5, -6, 6, -5, 4, -3, 2, -1, 1, 1, 1]
Output: [[1, -2, 3, -4], [1, 1, 1, -1], [2], [1, 1], [1], [1], [-2], [1, 1], [1]]

Input: 3, [-1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Output: [[-1, 1, 2], [4, 5], [10, 11, 12, 13, -1], [13], [12, 13, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

Input: 5, [5, 2, -3, 7, -3, 2, -4, 4, 4, 4]
Output: [[5, 2, -3, 7, -3], [2, 5, 4], [7, -3, 2, -4]]

Input: 2, [7, 24, 11]
Output: [[7, 24], [24, 11, 7, 24, 11, 7, 24, 11, 7, 24, 11, 7, 24, 11, 7, 24, 11, 7, 24, 11, 7, 24, 11, 7]]

```

# Answer
> 4 votes
# Python 2, ~~149~~ 140 bytes

```
n,a=input()
l=len(a)
s=set(a)
i=0
v=[n]*l
while min(v)and s:
 for x in range(i,i+n,n>0 or-1):v[x%l]-=1;n=a[x%l];s-={n};print n,
 i=x+n;print

```

Try it online!

---

* -9 bytes, thanks to Bubbler

# Answer
> 3 votes
# , ~~167~~ 163 bytes

```
function(n,a,l=sum(a^0),u=rep(n,l),v=0)while(!(all(a%in%v))&min(u)){for(i in F+0:(n-sign(n))){x=i%%l+1
v=c(v,a[x]);u[x]=u[x]-1}
print(tail(v,abs(n)));n=a[x];F=i+n}

```

Try it online!

I started with a slightly longer solution but then got inspired by TFeld's Python 2 answer which saved me 3 bytes.

*−4 bytes thanks to Giuseppe.*

# Answer
> 2 votes
## Pyth, ~~112~~ 109 bytes

```
=HQJ@H0K@H1=H.{K=bJ=Y*]0lKW&>J@.MZY0HI._bVrZ+Zb XYNh@YN=b@KN=-Hbp+bd).?Vr+ZbZ XYNh@YN=b@KN=-Hbp+bd))=Z+Nbp"\n

```

Try it online!

This is just a translation of TFeld's Python 2 answer. Could probably be golfed far better by someone with a better understanding of Pyth, but I figured I might as well share this anyway.

# Answer
> 1 votes
# JavaScript (ES6), 188 bytes

```
(n,l)=>{for(N=l.length,b=l.map(_=>0),o=[],u=l,e=n,p=0,O=[];!o[n]*u[0];p+=j-s,e=j,O.push(g))for(s=e<0?-1:1,g=[],i=0;i<e*s;p+=s)g[i++]=j=l[p=(p%N+N)%N],o[++b[p]]=u=u.filter(k=>k-j);return O}

```

Try it online! Comes with a header/footer that run the test cases.

Works somewhat like TFeld's Python answer, but ended up slightly longer.

# Answer
> 1 votes
# Perl 5, `-a` ~~123~~ ~~120~~ ~~116~~ ~~115~~ 114 bytes

This has the slight blemish that it prints an extra space at the start of each line

```
#!/usr/bin/perl -a
@;{@F}=$,=$";say$e!~/-?/,map$U{$z}=$S[++$s[$%]]=$e=$F[$%=($&.1+$%)%@F],($%+=$&.~-$')x($' or$@.=<>)until@S>$@|%U~~%

```

Try it online!

---
Tags: code-golf, number, array, subsequence
---


# Question
Title: I really wanted a rhombus, but all I got was this stupid rectangle
Given only a straightedge and compass, inscribe a rhombus inside the given rectangle, sharing two opposite points.

### Input

Input is the dimensions of the rectangle. In the example shown, that would be `125, 50`. You can take input in whatever way is most convenient (as two integers, list, strings, etc).

The larger dimension will be 100 minimum, while the smaller will be 25 minimum. Both cap at 200.

### Output

Output will be an image (displayed on screen or saved as a file) showing

* The input rectangle
* All "working" lines/circles
* The inscribed rhombus

in distinct colors. In the image above, The rectangle is black, working lines blue, and rhombus orange. The lines should be drawn in the order shown in the list (eg rhombus overwrites working lines and rectangle).

The output image needs to be large enough to contain everything. For example, the circles shown cannot go out of bounds.

### Method

The method used in the example image above is:

* Draw a circle using the lower left corner as center, and the upper right as a point on the perimeter, giving a radius equal to the rectangle's diagonal.
* Do the same, but swapping center and perimeter points.
* Draw a line between the intersections of the two circles, giving a perpendicular bisector to the rectangle's diagonal.
* Use the intersections of the new line and rectangle to draw the rhombus.

This works because the interior diagonals of a rhombus always perpendicularly bisect each other. I'm not including a full proof of this here, though.

This is not the *only* method to get your rhombus, and you can use another, given that you explain what you are doing. I *believe* it's probably the easiest, though.

### Rules

You can only draw circles and lines (or rather, line segments). A circle is defined with a center point and perimeter point. A line is defined by any two points. Lines do not have to be any specified length, but they must *at least* cover the defining points (note the example image: the line goes a bit past the circle intersections, but not to the edge). For circles, the radius from center to the chosen perimeter point is considered a working line, and must be shown.

To rasterize the lines, you can use any recognized algorithm (e.g. Bresenham's), or rely on whatever builtins your language might have. If your output is vector-based, please ensure that it is show at a resolution *at least* as large as the input rectangle in pixels. Also, you'll be drawing on a plain canvas, so please suppress any grid marks or extraneous output.

No cheating! You can only determine placement of points/lines/circles using what you've established so far. If you can't explain how to use your working lines/circles to show it's a rhombus, you're doing it wrong.

You can use whichever pair of opposite points you want, and the rectangle does not *need* to be drawn axis-aligned, so long as the output is correct.

Input will always be a non-square rectangle, so don't worry about special-casing that.

Lastly, this is standard code golf, so lowest size in bytes wins.

# Answer
> 11 votes
## HTML + JavaScript (ES6), 34 + 353 = 387 bytes

Input should be given in the format `[125,50]`.

```
[w,h]=eval(prompt(c=C.getContext("2d"))).sort();d=q=>(c.strokeStyle=q,b);l=(x,y=Z)=>x?c.lineTo(x,y)||l:c.stroke();b=(x,y=H,r)=>(c.beginPath(),r?c.arc(x,y,Math.sqrt(r),0,2*Math.PI):c.moveTo(x,y),l);b(Z=300,Z)(W=Z+w)(W,H=Z+h)(Z,H)(Z)();d`red`(Z,H,s=w*w+h*h)();b(W,Z,s)();b(Z)(W)();b(Z+w/2-h,Z+h/2-w)(H+w/2,W+h/2)();d`lime`(Z)(W-s/2/w)(W)(Z+s/2/w,H)(Z,H)()
```

```
<canvas id=C width=800 height=800>
```

Just a lot of math and drawing... The rectangle is drawn sideways if the height is greater than the width, which I believe is allowed.

# Answer
> 10 votes
# Mathematica, ~~157~~ ~~148~~ 158 bytes

*Thanks to Martin Ender for comments with their usual high quality! 9 bytes saved in this case.*

*Edited once it was clarified that the arguments can come in either order; 10 bytes added to compensate.*

```
Graphics@{(m=Line)@{o=0{,},{#,0},c={##},{0,#2},o},Blue,m[l={o,c}],Circle[#,(c.c)^.5]&/@l,m[{k={#2,-#},-k}+{c,c}/2],Red,m@{o,p={0,c.c/2/#2},c,c-p,o}}&@@Sort@#&

```

Again, this is where Mathematica shines: high-level graphics output involving mathematical computation. The same code with spaces and newlines for human readability:

```
Graphics@{
  (m=Line)@{o = 0{,}, {#, 0}, c = {##}, {0, #2}, o},
  Blue, m[l = {o, c}], Circle[#, (c.c)^.5] & /@ l,
  m[{k = {#2, -#}, -k} + {c, c}/2],
  Red, m@{o, p = {c.c/2/#2, 0}, c, c - p, o}
} & @@ Sort@# &

```

Unnamed function of a single argument which is an ordered pair of positive numbers; the final `@@ Sort@# &` converts that pair into two numerical arguments where the first number is the smaller. `Line` produces a polygonal path from point to point, which will turn into a closed polygon if the first and last points are the same; `Circle` produces a circle with given center and radius. Special points `o` and `c` (the lower-left and upper-right rectangle corners), `p` (a third rhombus corner, given by a mathematical formula), and `k` (helping to draw the perpendicular bisector) are given names along the way to save bytes when called again, as is the special pair of points `l = {o,c}`. Mathematica is happy to add points directly, multiply both coordinates by the same factor, take their dot product, etc., all of which simplify the code.

Sample output, with arguments `125` and `50`:

# Answer
> 9 votes
# MetaPost, 473 (with color) 353 (without color)

## Colored (473 bytes):

```
A:=170;B:=100;pair X,Y;path C,D,E,F,G,R,T;X=(0,0);Y=(A,B);R=X--(A,0)--Y--(0,B)--cycle;T=(0,B)--(A,B);draw R;E=X--Y;C=X..Y*2..cycle;D=Y..-Y..cycle;F=(D intersectionpoint C)--(C intersectionpoint D);draw C withcolor green;draw D withcolor green;draw E withcolor red;draw F withcolor red;draw (F intersectionpoint R)--Y withcolor blue;draw X--(F intersectionpoint T) withcolor blue;draw (F intersectionpoint T)--Y withcolor blue;draw (F intersectionpoint R)--X withcolor blue;

```

## Noncolored (353 bytes):

```
A:=170;B:=100;pair X,Y;path C,D,E,F,G,R,T;X=(0,0);Y=(A,B);R=X--(A,0)--Y--(0,B)--cycle;T=(0,B)--(A,B);draw R;E=X--Y;C=X..Y*2..cycle;D=Y..-Y..cycle;F=(D intersectionpoint C)--(C intersectionpoint D);draw C;draw D;draw E;draw F;draw (F intersectionpoint R)--Y;draw X--(F intersectionpoint T);draw (F intersectionpoint T)--Y;draw (F intersectionpoint R)--X;

```

Never EVER used this before, and I'm sure I butchered it...
But when you run that on this website:

http://www.tlhiv.org/mppreview/

It uses the intersection of the circles to draw the second axis, and then uses the intersection of the axis and the rectangle to draw the final rhombus. Though I could've cheated and just drawn a line perpendicular to the first axis haha.

To change the dimensions, just alter A and B.

Regardless, you end up with (for L=170, H=100):

# Answer
> 3 votes
## Desmos, 375 (or 163) bytes

```
w=125
h=50
\left(wt,\left[0,h\right]\right)
\left(\left[0,w\right],ht\right)
\left(x-\left[0,w\right]\right)^2+\left(y-\left[0,h\right]\right)^2=w^2+h^2
\frac{h}{w}x\left\{0\le x\le w\right\}
-\frac{w}{h}\left(x-\frac{w}{2}\right)+\frac{h}{2}
a=\frac{h^2}{2w}+\frac{w}{2}
\left(t\left(w-a\right)+\left[0,1\right]a,ht\right)
\left(at-\left[0,a-w\right],\left[0,h\right]\right)

```

`w` and `h` are the inputs. Try it on Desmos!

**Alternate 163-byte version:**

```
w=125
h=50
(wt,[0,h])
([0,w],ht)
(x-[0,w])^2+(y-[0,h])^2=w^2+h^2
hx/w\left\{0\le x\le w\right\}
-w(x-w/2)/h+h/2
a=h^2/2/w+w/2
(t(w-a)+[0,1]a,ht)
(at-[0,a-w],[0,h])

```

This version requires each line to be copy and pasted into each separate line into Desmos. Meta still needs to decide if this is a valid counting method, but the former method is definitely fine.

# Answer
> 3 votes
# ImageMagick Version 7.0.3 + bash + sed, 496 bytes

```
M=magick
L=$((400-$(($1))/2)),$((400+$(($2))/2))
R=$((400+$(($1))/2)),$((400-$(($2))/2))
Z=" $L $R" Y=" -1 x";D=' -draw' K=' -stroke'
A=' -strokewidth 3 +antialias -fill'
$M xc:[800x]$A none$K \#000$D "rectangle$Z"$D "line$Z"$K \#00F8$D "circle$Z"$K \#0F08$D "circle $R $L" -depth 8 png:a
$M a txt:-|sed "/38C/!d;s/:.*//">x;P=`head$Y`;Q=`tail$Y`
$M a$A \#F008$K \#F008$D "line $P $Q" b
$M b txt:-|sed "/C70/!d;s/:.*//">x;S=`head$Y`;T=`tail$Y`
$M b$A \#F804$K \#F80$D "polyline $L $S $R $T $L" x:

```

# Result with "rhombus.sh 180 120"

# More precise (using 6400x6400 canvas instead of 800x800), 570 bytes

The intersections aren't exact; the "strokewidth" directive makes the lines wide enough to make sure at least one entire pixel gets mixed with just the colors of the two intersecting lines, but in the worst cases (25x200 and 200x25) the crossings are at a small angle so the cloud of mixed pixels is several pixels long, and since we select the first and last mixed pixel, there is a slight error. Using an 8x larger canvas with the same strokewidth and then scaling the result down reduces the error to less than one pixel, but at about a 64x time penalty.

```
M=magick
L=$((3200-$(($1))*4)),$((3200+$(($2))*4))
R=$((3200+$(($1))*4)),$((3200-$(($2))*4))
K=-stroke;A='-strokewidth 3 +antialias'
$M xc:[6400x] $A -fill none $K \#000 -draw "rectangle $L $R" \
-draw "line $L $R" $K \#00F8 -draw "circle $L $R" \
$K \#0F08 -draw "circle $R $L" -depth 8 png:a
$M a txt:-|grep 38C077|sed -e "s/:.*//p">x
P=`head -1 x`;Q=`tail -1 x`
$M a $A -fill \#F008 $K \#F008 -draw "line $P $Q" png:b
$M b txt:-|grep C70000|sed -e "s/:.*//p">x
S=`head -1 x`;T=`tail -1 x`
$M b $A -fill \#F804 $K \#F80 -draw "polyline $L $S $R $T $L" -resize 800 x:

```

# Results of normal 800x800 versus precise 6400x6400:

# Ungolfed:

```
# rhombus.sh
# Inscribe a rhombus in the rectangle with dimensions 2*$1, 2*$2

# Run with "rhombus.sh W H"

M=magick

W=${1:-100};H=${2:-40}

# L locates the lower left corner of the rectangle
L=$((400-$((W))/2)),$((400+$((H))/2))

# R locates the upper right corner of the rectangle
R=$((400+$((W))/2)),$((400-$((H))/2))

# We'll need this several times
A='-strokewidth 3 +antialias'

# Establish 800x800 canvas (white) (circles + rectangle will
# always fit in 764x764)
#
# Draw the W x H rectangle (black) in center of canvas
#
# Draw two circles (blue, 50% alpha [#00F8] and green, 50% alpha [#0F08])
#  one centered at point L with peripheral point R
#  the other centered at point R with peripheral point L

$M xc:[800x] $A -fill none \
       -stroke \#000  -draw "rectangle $L $R" \
                      -draw "line      $L $R" \
       -stroke \#00F8 -draw "circle    $L $R" \
       -stroke \#0F08 -draw "circle    $R $L" \
       -depth 8 a.png

# Find P and Q, the 2 intersections of the circles,
# that have mixed color #38C077
$M a.png txt:-|grep 38C077|sed -e "s/:.*//p">x
P=`head -1 x`;Q=`tail -1 x`

# Draw line connecting the intersections P and Q
$M a.png $A -fill \#F008 -stroke \#F008 -draw "line $P $Q" b.png

# Find S and T, the 2 intersections of the line with the original rectangle,
# that have mixed color #C70000
$M b.png txt:-|grep C70000|sed -e "s/:.*//p">x
S=`head -1 x`;T=`tail -1 x`

# Draw the rhombus
$M b.png $A -fill \#F804 -stroke \#F80 -draw "polyline $L $S $R $T $L" d.png

```

# Answer
> 2 votes
# R, 290 bytes

```
function(A,B,p=polygon){R=A^2+B^2
D=2*A
a=sqrt(R)*cbind(cos(t<-seq(0,2*pi,.01)),sin(t))
b=t(t(a)+c(A,B))
x=range(a,b)
plot(NA,xli=x,yli=x,as=1,ax=F,an=F)
rect(0,0,A,B)
segments(0,0,A,B,c=4)
p(a,b=4)
p(b,b=4)
curve(B/2-A*x/B+A^2/2/B,co=4,a=T)
p(cbind(c((R-2*B^2)/D,A,R/D,0),c(B,B,0,0)),b=3)}

```

Anonymous function, output is displayed on screen. Slightly ungolfed, with comments:

```
function(A,B){
    R=A^2+B^2
    D=2*A
    t=seq(0,2*pi,.01)
    a=sqrt(R)*cbind(cos(t),sin(t)) #Circle with (0,0) as center
    b=t(t(a)+c(A,B)) #Second circle transposed to (A,B) center
    x=range(a,b)
    #Empty plot, large enough to fit the 2 circles:
    plot(NA,xlim=x,ylim=x,asp=1,axes=F,ann=F)
    rect(0,0,A,B) #Initial rectangle
    segments(0,0,A,B,col=4) #Rectangle diagonal
    polygon(a,border=4) #Circle 1 (border is b thanks to partial matching)
    polygon(b,border=4) #Circle 2
    curve(B/2-A*x/B+A^2/2/B,col=4,add=T) #Line joining circles intersection
    polygon(cbind(c((R-2*B^2)/D,A,R/D,0),c(B,B,0,0)),border=3) #Rhombus
}

```

Example output for (120,100):

# Answer
> 2 votes
# LibreLogo, 270 bytes

> User input is taken as an array: `[width, height]` or `[height, width]`.

**Code:**

```
fc [24]
D=180
R=sorted(eval(input "))
W=R[1]
H=R[0]
L=sqrt W**2+H**2
A=D/π*asin(H/L)
Z=A*2
S=L/2/cos A*π/D rectangle[W,H]pc 255 lt A fd 400 bk 800 fd 400 rt A pu bk H/2 lt 90 fd W/2 pd circle L*2 rt D-A fd L circle L*2 pc [5]lt D-A fd S lt Z fd S rt D+Z fd S lt Z fd S

```

**Result:**

**Explanation:**

```
fc [24]                        ; Fill Color = Invisible
D = 180                        ; D = 180° (Saved Bytes)
R = sorted( eval( input " ) )  ; R = Sorted Array of Rectangle Width and Height (User Input)
W = R[1]                       ; W = Rectangle Width
H = R[0]                       ; H = Rectangle Height
L = sqrt W**2 + H**2           ; L = Rectangle Diagonal Length
A = D / π * asin( H / L )      ; A = Rectangle Diagonal Angle°
Z = A * 2                      ; Z = Rectangle Diagonal Angle° * 2 (Saved Bytes)
S = L / 2 / cos A * π / D      ; S = Rhombus Side Length
rectangle [W, H]               ; Draw Rectangle
pc 255                         ; Pen Color = Blue
lt A                           ; Left = Rectangle Diagonal Angle°
fd 400                         ; Forward = 400 pt
bk 800                         ; Back = 800 pt
fd 400                         ; Forward = 400 pt
rt A                           ; Right = Rectangle Diagonal Angle°
pu                             ; Pen Up
bk H / 2                       ; Back = Rectangle Height / 2
lt 90                          ; Left = 90°
fd W / 2                       ; Forward = Rectangle Width / 2
pd                             ; Pen Down
circle L * 2                   ; Draw Left Circle (Radius = Rectangle Diagonal Length)
rt D - A                       ; Right = 180° - Rectangle Diagonal Angle°
fd L                           ; Forward = Rectangle Diagonal Length
circle L * 2                   ; Draw Right Circle (Radius = Rectangle Diagonal Length)
pc [5]                         ; Pen Color = Red
lt D - A                       ; Left = 180° - Rectangle Diagonal Angle°
fd S                           ; Forward = Rhombus Side Length
lt Z                           ; Left = Rectangle Diagonal Angle° * 2
fd S                           ; Forward = Rhombus Side Length
rt D + Z                       ; Right = 180° + Rectangle Diagonal Angle° * 2
fd S                           ; Forward = Rhombus Side Length
lt Z                           ; Left = Rectangle Diagonal Angle° * 2
fd S                           ; Forward = Rhombus Side Length

```

# Answer
> 1 votes
# Python 3.5 + Tkinter, 433 or 515 bytes

## Non-Colored (433 bytes):

```
from tkinter import*
def V(a,b):S=500;Y,Z=S+a,S-b;M=(a**2+b**2)**0.5;D=Tk();C=Canvas(D);B=C.create_oval;X=C.create_line;B(S+M,S-M,S-M,S+M);B(Y-M,Z+M,Y+M,Z-M);X(Y,Z,S,S);C.create_rectangle(Y,S,S,Z);Q=-((Z-S)/(Y-S))**-1;U,V=(Y+S)/2,(Z+S)/2;X(U+M,V+M*Q,U-M,V-M*Q);P=[(Y,Q*(Y-U)+V),(((Z-V)/Q)+U,Z)][a>b];L=[(S,Q*(S-U)+V),(((S-V)/Q)+U,S)][a>b];X(S,S,P[0],P[1]);X(Y,Z,P[0],P[1]);X(Y,Z,L[0],L[1]);X(S,S,L[0],L[1]);C.pack(fill=BOTH,expand=1)

```

## Colored (515 bytes):

```
from tkinter import*
def V(a,b):S=500;t='blue';Y,Z=S+a,S-b;M=(a**2+b**2)**0.5;D=Tk();C=Canvas(D);B=C.create_oval;X=C.create_line;B(S+M,S-M,S-M,S+M,outline=t);B(Y-M,Z+M,Y+M,Z-M,outline=t);X(Y,Z,S,S,fill=t);C.create_rectangle(Y,S,S,Z);Q=-((Z-S)/(Y-S))**-1;U,V=(Y+S)/2,(Z+S)/2;X(U+M,V+M*Q,U-M,V-M*Q,fill=t);P=[(Y,Q*(Y-U)+V),(((Z-V)/Q)+U,Z)][a>b];L=[(S,Q*(S-U)+V),(((S-V)/Q)+U,S)][a>b];o='orange';X(S,S,P[0],P[1],fill=o);X(Y,Z,P[0],P[1],fill=o);X(Y,Z,L[0],L[1],fill=o);X(S,S,L[0],L[1],fill=o);C.pack(fill=BOTH,expand=1)

```

A named function that takes input as 2 comma-separated numbers. The output is given in a separate window that you may have to resize to see the full output. Here is a sample colored output for `V(180,130)`:

# Answer
> 0 votes
# SmileBASIC, 280 bytes

```
INPUT W,H
W=MAX(W,H)/4H=MIN(W,H)/4D=SQR(W*W+H*H)N=D+W
M+D+H
GBOX D,D,N,M,#RED
GCIRCLE D,M,D
GCIRCLE N,D,D
GLINE D,M,N,D
X=D+W/2Y=D+H/2A=ATAN(W,H)E=D*H/W/2S=E*COS(A)T=E*SIN(A)GLINE X-S*9,Y-T*9,X+S*9,Y+T*9GCOLOR-#L
GLINE D,M,X-S,Y-T
GLINE D,M,X+S,M
GLINE N,D,X+S,Y+T
GLINE N,D,X-S,D

```

(Screenshot/explanation will be posted soon) Background color is black, rectangle is red, circles and lines are white, and the rhombus is yellow.

---
Tags: code-golf, graphical-output, geometry
---


# Question
Title: Evaluate expressions with significant figures
Given an expression, your task is to evaluate it. However, your answer cannot show more digits than necessary, as this gives the impression of having more precise measurements than reality.

The number of significant figures that a number has is how many digits it has when written in scientific notation, including zeros at the end if a decimal point is present. For example, `1200` has 2 significant figures because it is `1.2*10^3` but `1200.` has 4 significant figures and `1200.0` has 5 significant figures.

When adding two numbers, the result should be rounded to the same number of places as the number whose least significant digit is furthest to the left. For example, `1200 + 3 = 1200` (rounded to the hundreds place since 1200 is rounded to the hundreds place), `1200.01 + 3 = 1203`, and `4.59 + 2.3 = 6.9`. Note that `5` rounds up. This same rule applies to subtraction. `0` is rounded to the ones place. Note that adding and subtracting do not depend on the number of significant digits. For example, `999 + 2.00 = 1001` because 999 is rounded to the ones place and 2.00 is rounded to the hundredths place; the one rounded to fewer places is 999, so the result, 1001.00, should be rounded to the ones place as well. Similarly, 300 + 1 - 300 is exactly equal to 1, but 300 is rounded to the hundreds place, so the final result should also be rounded to the hundreds place, giving 0. 300. + 1 - 300. would equal 1 on the other hand.

When multiplying or dividing two numbers, round to the number of significant digits of the number with the least significant digits. For example, `3.839*4=20` because the exact value, `15.356`, rounds to `20` since `4` has only one significant figure. Similarly, `100/4=30` since both numbers have one significant figure, but `100./4.00=25.0` since both numbers have 3 significant figures. `0` is defined to have 1 significant figure.

Expressions will only contain `*`, `/`, `+`, and `-`, (and parentheses). Order of operations should be followed and results should be rounded after *every* operation. If parentheses are left out in a string of additions or subtractions or a string of multiplications and divisions, then round after all operations are completed. For example, `6*0.4*2 = 5` (one significant figure), while `0.4*(2*6)=0.4*10=4` and `(6*0.4)*2=2*2=4`.

**Input**: A string, with an expression containing `()*/+-` and digits. To simplify things, `-` will only be used as a subtraction operator, not to signify negative numbers; answers, however, could still be negative and would require `-` as a prefix.

**Output**: The result of the expression, evaluated and rounded to the correct number of digits. Note that `25` is incorrect for `25.0`.

**Test cases**:

```
3 + 0.5 --> 4
25.01 - 0.01 --> 25.00
4*7*3 --> 80
(4*7)*3 --> 90
(8.0 + 0.5)/(2.36 - 0.8 - 0.02) --> 5.7
6.0 + 4.0 --> 10.0
5.0 * 2.0 --> 10.0
1/(2.0 * (3.0 + 5.0)) --> 0.06
0.0020 * 129 --> 0.26
300 + 1 - 300 --> 0
0 - 8.8 --> -9
3*5/2*2 --> 20

```

Edge case: Consider the problem of `501*2.0`. The exact value is `1002`. Printing `1002` gives too many significant figures (4, when we need 2) but `1000` gives too few (1, when we need 2). In this case, your program should print `1000` anyway.

This source explains significant digits as well: http://www.purplemath.com/modules/rounding2.htm

# Answer
> 10 votes
# Java 11, ~~1325~~ ~~1379~~ ~~1356~~ ~~1336~~ 1290 bytes

```
import java.math.*;String c(String s)throws Exception{String r="",T=r,a[],b[],z="\\.";int i=0,l,A[],M=0,m=s.length(),j,f=0,q=m;if(s.contains("(")){for(;i<m;){var c=s.charAt(i++);if(f<1){if(c==40){f=1;continue;}r+=c;}else{if(c==41&T.replaceAll("[^(]","").length()==T.replaceAll("[^)]","").length()){r+="x"+s.substring(i);break;}T+=c;}}return c(r.replace("x",c(T)));}else{for(a=s.split("[\\+\\-\\*/]"),A=new int[l=a.length];i<l;f=b.length>1&&(j=b[1].length())>f?j:f)M=(j=(b=a[i++].split(z))[0].length())>M?j:M;for(b=a.clone(),i=0;i<l;A[i]=b[i].contains(".")?j=b[i].length()-1:b[i].replaceAll("0*$","").length(),i++)for(q=(j=b[i].replace(".","").length())<q?j:q,j=a[i].split(z)[0].length();j++<M;)b[i]=0+b[i];double R=new Double(new javax.script.ScriptEngineManager().getEngineByName("JS").eval(s)+""),p;for(int x:A)m=x<m?x:m;m=m==M&R%1==0&(int)R/10%10<1&(j=(r=R+"").split(z)[0].length())>m?j-q>1?q:j:R>99?m:R%10==0?r.length()-1:m<1?1:m;R=new BigDecimal(R).round(new MathContext((R<0?-R:R)<1?m-1:m)).doubleValue();r=(m<M&(p=Math.pow(10,M-m))/10>R?(int)(R/p)*p:R)+"";l=r.length()-2;r=(r=f<1?r.replaceAll(z+"0$",""):r+"0".repeat(f)).substring(0,(j=r.length())<m?j:r.contains(".")?(j=r.replaceAll("^0\\.0+","").length())<m?m-~j:m+1:m);for(i=r.length();i++<l;)r+=0;return r.replaceAll(z+"$","");}}

```

+54 bytes to fix the edge case `501*2.0` (gave result `1002` before, but now correct `1000`).

I now understand why this challenge was unanswered for almost two years.. \>.\> This challenge has more special cases than the Dutch language, which is saying something..
Java is certainly not the right language for these kind of challenges (or any codegolf challenge for that matter.. ;p), but it's the only language I know good enough to even attempt a difficult challenge like this.

Input format as `String` without spaces (if that is not allowed, you can add `s=s.replace(" ","")` (+19 bytes) at the top of the method).

**Try it online.**

### Explanation:

*Sorry for the long post.*

```
if(s.contains("(")){
  for(;i<m;){
    var c=s.charAt(i++);
    if(f<1){
      if(c==40){
        f=1;
        continue;}
      r+=c;}
    else{
      if(c==41&T.replaceAll("[^(]","").length()==T.replaceAll("[^)]","").length()){
        r+="x"+s.substring(i);
        break;}
      T+=c;}}
  return c(r.replace("x",c(T)));}

```

This part is used for input containing parenthesis. It will get the separated parts and use recursive-calls.

* `0.4*(2*6)` becomes `0.4*A`, where `A` is a recursive call to `c(2*6)`
* `(8.3*0.02)+(1.*(9*4)+2.2)` becomes `A+B`, where `A` is a recursive call to `c(8.3*0.02)` and `B` a recursive call to `c(1.*(9*4)+2.2)` → which in turn becomes `1.*C+2.2`, where `C` is a recursive call to `c(9*4)`

---

```
for(a=s.split("[\\+\\-\\*/]"),A=new int[l=a.length];
    i<l;
    f=b.length>1&&(j=b[1].length())>f?j:f)
  M=(j=(b=a[i++].split(z))[0].length())>M?j:M;

```

This first loop is used to fill the values `M` and `k`, where `M` is the largest integer-length regarding significant figures and `k` the largest decimals-length.

* `1200+3.0` becomes `M=2, k=1` (`12, .0`)
* `999+2.00` becomes `M=3, k=2` (`999, .00`)
* `300.+1-300.` becomes `M=3, k=0` (`300, .`)

---

```
for(b=a.clone(),i=0;
    i<l;
    A[i]=b[i].contains(".")?j=b[i].length()-1:b[i].replaceAll("0*$","").length(),i++)
  for(q=(j=b[i].replace(".","").length())<q?j:q,
      j=a[i].split(z)[0].length();
      j++<M;)
    b[i]=0+b[i];

```

This second loop is used to fill the arrays `A` and `b` as well as value `q`, where `A` is the amount of significant figures, `b` hold the integers with leading zeroes to match `M`, and `q` is the lowest length disregarding dots.

* `1200+3.0` becomes `A=[2, 5] (12, 00030)`, `b=[1200, 0003.0]`, and `q=2` (`30`)
* `999+2.00` becomes `A=[3, 5] (999, 00200)`, `b=[999, 002.00]`, and `q=3` (both `999` and `200`)
* `300.+1-300.` becomes `A=[3, 3, 3] (300, 001, 300)`, `b=[300., 001, 300.]`, and `q=1` (`1`)
* `501*2.0` becomes `A=[3, 4] (501, 0020)`, `b=[501, 002.0]`, and `q=2` (`20`)

---

```
double R=new Double(new javax.script.ScriptEngineManager().getEngineByName("JS").eval(s)+"")

```

Uses a JavaScript engine to eval the input, which will be saved in `R` as double.

* `1200+3.0` becomes `R=1203.0`
* `999+2.00` becomes `R=1001.0`
* `300.+1-300.` becomes `R=1.0`

---

```
for(int x:A)
  m=x<m?x:m;

```

This sets `m` to the smallest value in the array `A`.

* `A=[2, 5]` becomes `m=2`
* `A=[3, 5]` becomes `m=3`
* `A=[3, 3, 3]` becomes `m=3`

---

```
 m=m==M                // If `m` equals `M`
   &R%1==0             // and `R` has no decimal values (apart from 0)
   &(int)R/10%10<1     // and floor(int(R)/10) modulo-10 is 0
   &(j=(r=R+"").split(z)[0].length())>m?
                       // and the integer-length of R is larger than `m`:
    j-q>1?             //  If this integer-length of `R` minus `q` is 2 or larger:
     q                 //   Set `m` to `q` instead
    :                  //  Else:
     j                 //  Set `m` to this integer-length of `R`
   :R>99?              // Else-if `R` is 100 or larger:
    m                  //  Leave `m` the same
   :R%10==0?           // Else-if `R` modulo-10 is exactly 0:
    r.length()-1       //  Set `m` to the total length of `R` (minus the dot)
   :m<1?               // Else-if `m` is 0:
    1                  //  Set `m` to 1
   :                   // Else:
    m;                 //  Leave `m` the same

```

This modifies `m` based on multiple factors.

* `999+2.00 = 1001.0` & `m=3,q=3` becomes `m=4` (because `m==M` (both `3`) → `R%1==0` (`1001.0` has no decimal values) → `(int)R/10%10<1` (`(int)1001.0/10` becomes `100``100%10<1`) → `"1001".length()>m` (`4>3`) → `"1001".length()-q<=1` (`4-3<=1`) → so `m` becomes the length of the integer-part `"1001"` (`4`))
* `3.839*4 = 15.356` & `m=1,q=1` stays `m=1` (because `m==M` (both `1`) → `R%1!=0` (`15.356` has decimal values) → `R<=99``R%10!=0` (`15.356%10==5.356`) → `m!=0` → so `m` stays the same (`1`))
* `4*7*3 = 84.0` & `m=1,q=1` stays `m=1` (because `m==M` (both `1`) → `R%1==0` (`84.0` has no decimal values) → `(int)R/10%10>=1` (`(int)84/10` becomes `8``8%10>=1`) → `R<=99``R%10!=0` (`84%10==4`) → `m!=0` → so `m` stays the same (`1`))
* `6.0+4.0 = 10.0` & `m=2,q=2` becomes `m=3` (because `m!=M` (`m=2, M=1`) → `R<=99``R%10==0` (`10%10==0`) → so `m` becomes the length of the total `R` (minus the dot) `"10.0".length()-1` (`3`))
* `0-8.8 = -8.8` & `m=0,q=1` becomes `m=1` (because `m!=M` (`m=0, M=1`) → `R<=99``R%10!=0` (`-8.8%10==-8.8`) → `m<1` → so `m` becomes `1`)
* `501*2.0 = 1001.0` & `m=3,q=2` becomes `m=2` (because `m==M` (both `3`) → `R%1==0` (`1001.0` has no decimal values) → `(int)R/10%10<1` (`(int)1001.0/10` becomes `100``100%10<1`) → `"1001".length()>m` (`4>3`) → `"1001".length()-q>1` (`4-2>1`) → so `m` becomes `q` (`2`))

---

```
R=new BigDecimal(R).round(new MathContext((R<0?-R:R)<1?m-1:m)).doubleValue();

```

Now `R` is rounded based on `m`.

* `1001.0` & `m=4` becomes `1001.0`
* `0.258` & `m=3` becomes `0.26` (because `abs(R)<1`, `m-1` (`2`) instead of `m=3` is used inside `MathContext`)
* `-8.8` & `m=1` becomes `-9.0`
* `1002.0` & `m=2` becomes `1000.0`

---

```
m<M&(p=Math.pow(10,M-m))/10>R?(int)(R/p)*p:R;

```

This modifies the integer part of `R` if necessary.

* `300.+1-300. = 1.0` & `m=3,M=3` stays `1.0` (because `m>=M` → so `R` stays the same (`1.0`))
* `0.4*10 = 4.0` & `m=1,M=2` stays `4.0` (because `m<M``(10^(M-m))/10<=R` (`(10^1)/10<=4.0``10/10<=4.0``1<=4.0`) → so `R` stays the same (`4.0`))
* `300+1-300 = 1.0` & `m=1,M=3` becomes `0.0` (because `m<M``(10^(M-m))/10>R` (`(10^2)/10>1.0``100/10>1.0``10>1.0`) → so `R` becomes `0.0` because of `int(R/(10^(M-m)))*(10^(M-m))` (`int(1.0/(10^2))*(10^2)``int(1.0/100)*100``0*100``0`)

---

```
r=(...)+"";                  // Set `R` to `r` as String (... is the part explained above)
l=r.length()-2;              // Set `l` to the length of `R` minus 2
r=(r=k<1?                    // If `k` is 0 (no decimal values in any of the input-numbers)
      r.replaceAll(z+"0$","")
                             //  Remove the `.0` at the end
     :                       // Else:
      r+"0".repeat(f)
                             //  Append `k` zeroes after the current `r`
  ).substring(0,             // Then take the substring from index `0` to:
     (j=r.length())<m?       //  If the total length of `r` is below `m`:
       j                     //   Leave `r` the same
     :r.contains(".")?       //  Else-if `r` contains a dot
       (j=r.replaceAll("^0\\.0+","").length())<m?
                             //   And `R` is a decimal below 1,
                             //   and its rightmost decimal length is smaller than `m`
        m-~j                 //    Take the substring from index 0 to `m+j+1`
                             //    where `j` is this rightmost decimal length
       :                     //   Else:
        m+1                  //    Take the substring from index 0 to `m+1`
     :                       //  Else:
      m);                    //   Take the substring from index 0 to `m`

```

This sets `R` to `r` as String, and modifies it based on multiple factors.

* `1203.0` & `m=4,k=2` becomes `1203.` (because `k>=1` → so `r` becomes `1001.000`; `r.length()>=m` (`8>=4`) → `r.contains(".")``r.length()>=m` (`8>=4`) → substring from index `0` to `m+1` (`5`))
* `6.9` & `m=2,k=2` stays `6.9` (because `k>=1` → so `r` becomes `6.900`; `r.length()>=m` (`5>=2`) → `r.contains(".")``r.length()>=m` (`5>=2`) → substring from index `0` to `m+1` (`3`))
* `1.0` & `m=3,k=0` becomes `1` (because `k<1` → so `r` becomes `1`; `r.length()<m` (`1<3`) → substring from index `0` to `r.length()` (`1`))
* `25.0` & `m=4,k=4` becomes `25.00` (because `k>=1` → so `r` becomes `25.00000`; `r.length()>=m` (`8>=4`) → `r.contains(".")``r.length()>+m` (`8>=4`) → substring from index `0` to `m+1` (`5`))
* `0` & `m=1,k=0` stays `0` (because `k<1` → so `r` stays `0`; `r.length()>=m` (`1>=1`) → `!r.contains(".")` → substring from index `0` to `m` (`1`))

---

```
for(i=r.length();i++<l;)
  r+=0;

```

This puts trailing zeroes back again to the integer part if necessary.

* `r="12"` & `R=1200.0` becomes `r="1200"`
* `r="1"` & `R=10.0` becomes `r="10"`
* `r="8"` & `R=80.0` becomes `r="80"`

---

```
return r.replaceAll(z+"$","");

```

And finally we return the result, after we've removed any trailing dots.

* `1203.` becomes `1203`
* `5.` becomes `5`

---

Can definitely be golfed by a couple hundred bytes, but I'm just glad it's working now. It already took a while to understand each of the cases and what was being asked in the challenge. And then it took a lot of trial-and-error, testing and retesting to get to the result above. And while writing this explanation above I was able to remove another ±50 bytes of unused code..

---
Tags: code-golf, math
---