# Question
Title: Calculate the lowest number where the sum of the sequence of numbers exceeds a given value
Given you have an infinite sequence of numbers defined as follows:

```
1: 1 = 1
2: 1 + 2 = 3
3: 1 + 3 = 4
4: 1 + 2 + 4 = 7
5: 1 + 5 = 6
6: 1 + 2 + 3 + 6 = 12
7: 1 + 7 = 8
...

```

The sequence is the sum of the divisors of `n`, including 1 and `n`.

Given a positive integer `x` as input, calculate the lowest number `n` which will produce a result greater than `x`.

**Test cases**

```
f(100) = 48, ∑ = 124
f(25000) = 7200, ∑ = 25389
f(5000000) = 1164240, ∑ = 5088960

```

**Expected Output**

Your program should return **both** `n` and the sum of its divisors, like so:

```
$ ./challenge 100
48,124

```

**Rules**

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

# Answer
# Brachylog, 9 bytes

```
∧;S?hf+S>

```

This program takes input from the "output variable" `.`, and outputs to the "input variable" `?`. Try it online!

## Explanation

```
∧;S?hf+S>
∧;S        There is a pair [N,S]
   ?       which equals the output
    h      such that its first element's
     f     factors'
      +    sum
       S   equals S,
        >  and is greater than the input.

```

The implicit variable `N` is enumerated in increasing order, so its lowest legal value is used for the output.
> 8 votes

# Answer
# Jelly, ~~18~~ ~~12~~ ~~11~~ 10 bytes

```
1Æs>¥#ḢṄÆs

```

Try it online!

-1 byte thanks to Mr. Xcoder!

## How it works

```
1Æs>¥#ḢṄÆs - Main link. Argument: n (integer)
1   ¥#     - Find the first n integers where...
 Æs        -   the divisor sum
   >       -   is greater than the input
       Ṅ   - Print...
      Ḣ    -   the first element
        Æs - then print the divisor sum

```
> 10 votes

# Answer
# Japt, 15 bytes

```
[@<(V=Xâ x}a V]

```

Try it

---

## Explanation

Implicit input of integer `U`. `[]` is our array wrapper. For the first element, `@ }a` is a function that run continuously until it returns a truthy value, passing itself an incrementing integer (starting at 0) each time, and outputting the final value of that integer. `â` gets the divisors of the current integer (`X`), `x` sums them and that result is assigned to variable `V`. `<` checks if `U` is less than `V`. The second element in the array is then just `V`.
> 4 votes

# Answer
# Wolfram Language (Mathematica), 53 bytes

```
{#,f@#}&@@Select[Range[x=#]+1,(f=Tr@*Divisors)@#>x&]&

```

Try it online!

Tries all values between 2 and x+1, where x is the input.

(The `Select` returns a list of all values that work, but the function `{#,f@#}&` takes all of these as inputs, and then ignores all its inputs but the first.)
> 4 votes

# Answer
# Husk, ~~12~~ 11 bytes

```
§eVḟ>⁰moΣḊN

```

-1 byte, thanks to @Zgarb!

Try it online!
> 4 votes

# Answer
# , 73 bytes

```
n=scan();while(1){d=(x=1:T)[!T%%x];if(sum(d)>n)break;T=T+1};cat(T,sum(d))

```

Try it online!

Outgolfed by duckmayr.
> 4 votes

# Answer
# , 71 bytes

```
function(x)for(n in 1:x){z=sum(which(n%%1:n==0));if(z>x)return(c(n,z))}

```

Try it online!
> 4 votes

# Answer
# Clojure, 127 bytes

```
(defn f[n](reduce +(filter #(zero?(rem n %))(range 1(inc n)))))
(defn e[n](loop[i 1 n n](if(>(f i)n){i,(f i)}(recur(inc i)n))))

```

Try it online!

thanks to @steadybox for -4 bytes!
> 4 votes

# Answer
# 05AB1E, 11 bytes

```
>LʒÑO‹}нDÑO

```

Try it online!

Leaves the output on the stack, as allowed per meta consensus. I added `)` for the sake of visualization, but the program also implicitly prints the top of the stack.
> 3 votes

# Answer
## JavaScript (ES6), ~~61~~ 58 bytes

```
f=(n,i=1,s=j=0)=>j++<i?f(n,i,i%j?s:s+j):s>n?[i,s]:f(n,++i)
```

```
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>
```

Edit: Saved 3 bytes thanks to @Arnauld.
> 3 votes

# Answer
# Ruby, 58 bytes

Full program because I'm not sure if lambdas are allowed. /shrug

```
gets
$.+=1until$_.to_i.<v=(1..$.).sum{|n|$.%n<1?n:0}
p$.,v

```

Try it online!

# Explanation

```
gets     # read line ($_ is used instead of v= because it cuts a space)
$.+=1    # $. is "lines read" variable which starts at 1 because we read 1 line
    until     # repeat as long as the next part is not true
$_.to_i  # input, as numeric
  .<v=   # is <, but invoked as function to lower operator prescedence
  (1..$.)        # Range of 1 to n
  .sum{|n|       # .sum maps values into new ones and adds them together
     $.%n<1?n:0  # Factor -> add to sum, non-factor -> 0
  }
p$.,v    # output n and sum

```
> 3 votes

# Answer
# APL (Dyalog), 32 bytes

```
{⍺<o←+/o/⍨0=⍵|⍨o←⍳⍵:⍵,o⋄⍺∇⍵+1}∘0

```

Try it online!

*⍵o⍺⍵.*
> 2 votes

# Answer
# C,  ~~79~~  78 bytes

```
i,n,s;f(x){for(i=n=s=0;x>s;s+=n%++i?0:i)i-n||(++n,i=s=0);printf("%d %d",n,s);}

```

Try it online!
> 2 votes

# Answer
# SOGL V0.12, 14 bytes

```
1[:Λ∑:A.>?ao←I

```

Try it Here!

Explanation:

```
1               push 1
 [              while ToS != 0
  :Λ              get the divisors
    ∑             sum
     :A           save on variable A without popping
       .>?  ←     if greater than the input
          ao        output the variable A
            ←       and stop the program, implicitly outputting ToS - the counter
             I    increment the counter

```
> 2 votes

# Answer
# MATL, 12 bytes

```
`@Z\sG>~}@6M

```

Try it online!

### Explanation

```
`      % Do...while
  @    %   Push iteration index (1-based)
  Z\   %   Array of divisors
  s    %   Sum of array
  G    %   Push input
  >~   %   Greater than; logical negate. This is the loop condition
}      % Finally (execute on loop exit)
  @    %   Push latest iteration index
  6M   %   Push latest sum of divisors again
       % End (implicit). Run new iteration if top of the stack is true
       % Display stack (implicit)

```
> 2 votes

# Answer
# Gaia, 11 bytes

```
dΣ@>
↑#(:dΣ

```

Try it online!

Leaves the output on the stack, as allowed per meta consensus. I added `€.` for the sake of visualization, but the program also implicitly prints the top of the stack.
> 2 votes

# Answer
# Haskell, 59 bytes

```
f x=[(i,s)|i<-[1..],s<-[sum[d|d<-[1..i],i`mod`d<1]],s>x]!!0

```

-1 byte, thanks to @nimi!

Try it online!
> 2 votes

# Answer
# Ohm v2, 11 bytes

```
£^DVΣD³>‽;«

```

Try it online!
> 2 votes

# Answer
# Python 3, 163 bytes

```
def f(x):
    def d(x):return[i for i in range(1,x+1) if x%i==0]
    return min(i for i in range(x) if sum(d(i)) >x),sum(d(min(i for i in range(x) if sum(d(i)) >x)))

```
> 2 votes

# Answer
# Factor, 88

```
USE: math.primes.factors [ 0 0 [ drop 1 + dup divisors sum pick over > ] loop rot drop ]

```

Brute-force search. It's a quotation (lambda), `call` it with `x` on the stack, leaves `n` and `f(n)` on the stack.

As a word:

```
: f(n)>x ( x -- n f(n) )
  0 0 [ drop 1 + dup divisors sum pick over > ] loop rot drop ;

```
> 2 votes

# Answer
# Python 3, 100 bytes

```
d=lambda y:sum(i+1for i in range(y)if y%-~i<1)
f=lambda x:min((j,d(j))for j in range(x+1)if x<=d(j))

```

Try it online!

Thanks to Jonathan Frech's comment on the previous python 3 attempt, I have just greatly expanded my knowledge of python syntax. I'd never have thought of the -~i for i+1 trick, which saves two characters.

However, that answer is 1) not minimal and 2) doesn't work for x=1 (due to an off-by-one error which is easy to make while going for brevity; I suggest everyone else check their answers for this edge case!).

Quick explanation: `sum(i+1for i in range(y)if y%-~i<1)` is equivalent to `sum(i for i in range(1,y+1)if y%i<1)` but saves two characters. Thanks again to Mr. Frech.

`d=lambda y:sum(i+1for i in range(y)if y%-~i<1)` therefore returns the divisors of y.

`f=lambda x:min((j,d(j))for j in range(x+1)if x<=d(j))` is where I really did work. Since comparing a tuple works in dictionary order, we can compare j,d(j) as easily as we can compare j, and this lets us not have to find the minimal j, store it in a variable, and /then/ compute the tuple in a separate operation. Also, we have to have the \<=, not \<, in `x<=d(j)`, because d(1) is 1 so if x is 1 you get nothing. This is also why we need `range(x+1)` and not `range(x)`.

I'd previously had d return the tuple, but then I have to subscript it in f, so that takes three more characters.
> 2 votes

# Answer
# Python 2, 81 bytes

```
def f(n):
 a=b=0
 while b<n:
	a+=1;i=b=0
	while i<a:i+=1;b+=i*(a%i<1)
 return a,b

```

Try it online!
> 2 votes

# Answer
# Java (OpenJDK 8), 91 bytes

```
i->{for(int j=0;j++<i;)for(int k=0,l=0;k++<j;)if((l+=j%k<1?k:0)>i)return k+","+l;return"";}

```

Try it online! (timeout on third test case)
> 1 votes

# Answer
# Perl 5, 60 + 1 (`-p`) = 61 bytes

```
$"=$_;until($_>$"){$_=$/=0;$\--;$_+=$\%$/?0:$/until++$/>-$\}

```

Try it online!

Output format:

*sum*-*n*
> 1 votes

# Answer
## Clojure, 102 bytes

```
#(loop[i 1](let[s(apply +(for[j(range 1(inc i)):when(=(mod i j)0)]j))](if(> s %)[i s](recur(inc i)))))

```
> 0 votes

# Answer
# PHP, 69 bytes

```
for(;$argv[1]>=$t;)for($t=$j=++$i;--$j;)$t+=$i%$j?0:$j;echo$i,',',$t;

```
> 0 votes

# Answer
# Perl 6, 48 bytes

```
{first :kv,*>$_,map {sum grep $_%%*,1..$_},0..*}

```

Try it online!
> 0 votes

---
Tags: code-golf, math, number-theory
---


title: Power Grid Resource Costs

text:
# Question
Title: Power Grid Resource Costs
# Power Grid Resource Costs

**Introduction**

In the board game Power Grid, an integral part of the game is the act of buying resources to fuel your power stations. There are four types of resource used in the game (five, if you include renewable energy, but obviously you can't buy resources for that). These are Coal, Oil, Garbage, and Uranium. The resource market looks like this:

```
1---- | 2---- | 3---- | 4---- | 5---- | 6---- | 7---- | 8---- | 10  | 12
CCC   | CCC   | CCC   | CCC   | CCC   | CCC   | CCC   | CCC   |  U  |  U
OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | 14  | 16
GGG   | GGG   | GGG   | GGG   | GGG   | GGG   | GGG   | GGG   |  U  |  U

```

When resources are bought, they are taken from the left of the market, where they are cheapest. When new resources are added to the market, they are added from the right. As can be seen, this produces a supply and demand balance - if more resources of a particular type are being bought than are being replenished each round, the price of that resource will rise. Similarly, if it's less, the cost will reduce.

Coal, Oil, and Garbage all scale up in cost at the same rate, while Uranium scales much faster. A single unit of a non-Uranium resource costs `8 - floor((<units available> - 1) / 3)`. A single unit of Uranium costs `13 - <units available>` if there are 5 or more units available, and `18 - (2 * <units available>)` otherwise.

For example, at the start of the game there are all 24 units of Coal available to buy. If the first player would like to buy 4 units of Coal, the first three units would cost 1 each, and the 4th would cost 2, making the total cost 5. This leaves 20 units available. If the second player would also like to buy 4 units of Coal, the cost would be (2\*2 + 2\*3) = 10.

**The Challenge**

Your challenge is to write a program or function which calculates the cost of buying a given amount of a particular resource, assuming that there is a given amount of that resource present in the market.

Your submission should accept, in any reasonable input format and in any order, the following parameters:

* The resource type - guaranteed to be one of \[C, O, G, U\].
* The amount of that resource that is present in the market - guaranteed to be a non-negative integer. If the resource type is not U, it will not be greater than 24. If the resource type is U, it will not be greater than 12.
* The amount of that resource that a player would like to buy - guaranteed to be a non-negative integer which is less than or equal to the amount already present in the market.

The output should be the cost of the requested resources.

**Additional Rules**

* The formulae given are for illustrative purposes only, feel free to use any method of calculating the costs you like.
* The letter codes for the different resource types (C, O, G, U) may be replaced by their lower case equivalents. You may also replace the letters for numbers, either in the form `C=0, O=1, G=2, U=3` or `C=1, O=2, G=3, U=4`.
* This is , so the smallest submission in bytes will be the winner.
* If your submission requires the input in a different order or format than specified in the previous section, you should provide details.

**Test cases**

Test case format:

```
resource type, amount in market, amount to buy
> result

```

Test cases:

```
C, 24, 4
> 5

C, 20, 4
> 10

O, 3, 3
> 24

U, 1, 1
> 16

C, 1, 1
> 8

G, 0, 0
> 0

O, 10, 7
> 44

U, 12, 4
> 10

G, 11, 4
> 22

```

# Answer
> 3 votes
# Javascript (ES6), ~~71~~ 59 bytes

```
f=(t,m,b)=>b&&(t>2?m>4?13-m:18-m*2:9+~(~-m/3))+f(t,m-1,b-1)

```

Takes `type`, `market_amount` and `buy_amount` as arguments. `type` is an integer between 0 and 3.

### Demo

```
f=(t,m,b)=>b&&(t>2?m>4?13-m:18-m*2:9+~(~-m/3))+f(t,m-1,b-1)
function run() { var tests = document.getElementById("tests").value.split("\n"), test, C = 0, O = 1, G = 2, U = 3; console.clear(); for (var test of tests) { console.log(test); console.log("> " + eval(test)); } }
```

```
<textarea rows="10" id="tests">f(C, 24, 4)
f(C, 20, 4)
f(O, 3, 3)
f(U, 1, 1)
f(C, 1, 1)
f(G, 0, 0)
f(O, 10, 7)
f(U, 12, 4)
f(G, 11, 4)</textarea><br/><button onclick="run()">Run</button>
```

# Answer
> 4 votes
# Python 3, ~~71~~ 69 bytes

*Thanks to @xnor for -2 bytes*

```
f=lambda r,a,b:b and[8-int(~-a/3),max(18-2*a,13-a)][r>2]+f(r,a-1,b-1)

```

A function that takes input via argument of the zero-indexed resource type `r`, the amount available `a` and the amount to buy `b`, and returns the cost.

This makes use of the fact that `True` and `False` equate to `1` and `0` in Python, allowing the use of Boolean expressions to index into lists.

**How it works**

```
f=lambda r,a,b           Function with input resource type r, amount available a and amount
                         to buy b
b and...                 Base case: return 0 if b=0
[8-int(~-a/3),...][r>2]  If not uranium, yield the unit cost 8-floor((a-1)/3)...
max(18-2*a,13-a)         ..else yield the current uranium unit cost
...f(r,a-1,b-1)          Decrement a and b, then pass to function
...+...                  Add the cost of each unit to give the total cost
:...                     Return the above

```

Try it on Ideone

# Answer
> 3 votes
# Befunge, 142 bytes

```
&2`#v_&&>:!#v_\:1-3/8\-v
v:&&<   ^-1\ -1p15+g15 <
v>#<v       <
! v5<
# 1:
>^g-
| 81
\ 4\
: *-
4 -1
` .p
# @^15+g15<
>:49+\-   ^
|
>:2*92*\- ^

```

Try it here! Takes input as 3 integers, where the resource type is 0,1,2,3. Output is an integer.

No idea if this can be golfed any better. There's not that much whitespace, but the newlines probably hurt.

# Answer
> 3 votes
# Python 2.7, 85 bytes:

```
F,G,H=input();B=0;exec"B+=[[18-(2*G),13-G][G>5],8-((G-1)/3)][F!='U'];G-=1;"*H;print B

```

Based on R. Kap's answer, but you can shave a byte down to 85 by removing the extra / for floor division. Because these are all integers it's automatically floored down to a whole number.

# Answer
> 2 votes
## Lua, ~~107~~ 101 Bytes

Recursive function that have to be called with `f(resource,stock,buy)`. resource have to be a number between 0 and 3. The output is done via the returned value.

**Thanks LeakyNun for saving me 6 bytes : `(25-y+(y-1)%3)/3` is shorter than `8-math.floor((y-1)/3)` by 5 bytes and allow me to gain one more byte due to its placement.**

```
function f(x,y,z)return z<1 and 0or(x<3 and(25-y+(y-1)%3)/3or(y<5 and 18-y*2or 13-y))+f(x,y-1,z-1)end

```

### Ungolfed

```
function f(x,y,z)                      -- define a function f with 3 parameters
  return z<1                           -- if we don't buy anything else
           and 0                       --   return 0
         or(                           -- else
           x<3                         --   if we're not buying Uranium
             and (25-y+(y-1)%3)/3      --     return 8-floor((stock-1)/3)
           or(y<5                      --   elseif there's less than 5 Uranium left
                and 18-y*2             --     return 18-stock*2
              or 13-y))                --   else return 13-stock
         +f(x,y-1,z-1)                 -- if we bought this iteration
                                       -- add f(resource,stock-1,toBuy-1)
                                       -- to the returned value
end

```

You can test this code online by copy-pasting the following snippet.

```
function f(x,y,z)return z<1 and 0or(x<3 and(25-y+(y-1)%3)/3or(y<5 and 18-y*2or 13-y))+f(x,y-1,z-1)end
print(f(1,24,4))
print(f(2,20,4))
print(f(0,10,7))
print(f(3,1,1))
print(f(3,12,4))

```

# Answer
> 2 votes
# Python 2.7, 86 bytes:

```
F,G,H=input();B=0;exec"B+=[[18-(2*G),13-G][G>5],8-((G-1)//3)][F!='U'];G-=1;"*H;print B

```

Takes input by an array in the format `[resource type, units available, units to purchase]`. Output is an integer. Will try to golf more over time.

Try It Online! (Ideone)

---
Tags: code-golf
---


title: Accumulate some L.s.d

text:
# Question
Title: Accumulate some L.s.d
Prior to the decimalisation of Sterling in February 1971, a pound (**£** \- from Roman *libra*) comprised 20 shillings (**s** \- *solidus*), each of 12 pennies (**d** \- *denarius*). Additionally, until 1960, each penny could be divided into four farthings (some parts of the Commonwealth also had fractions of farthings, but we'll ignore those in this question).

Your task is to write a simple adding machine for financial quantities in the old system. You will receive a set of **strings**, and emit/return a single string that represents the total of all the inputs. The format of input and output strings is as follows (adapted from Wikipedia: £sd):

1. For quantities less than 1 shilling, the number of pence followed by the letter `d`:

```
¼d            -- smallest amount representable
1d
11¾d          -- largest value in this format

```
2. For quantities less than £1, `/` is used to separate shillings and pence, with `-` as a placeholder if there are no pence:

```
1/-           -- smallest amount in this format
1/6
19/11¾        -- largest value in this format

```
3. For quantities of £1 or greater, we separate the parts with `.`, and include the units:

```
£1
£1.-.¼d       -- one pound and one farthing
£1.1s.-       -- one pound and one shilling
£999.19s.11¾d -- largest value needed in this challenge

```

The inputs will never sum to £1000 or more (i.e. you can assume the pounds will fit into 3 digits).

Input will be as *strings* by any of the usual input methods (as an array of strings, as a single string with newlines or other separators, as individual arguments, etc). There will be no additional characters (not mentioned above) in each string.

Output will be as a single string, by any of the usual output methods (standard output stream, function return value, global variable, etc.). You may include additional spaces around the numbers if that helps.

## Examples

(assuming my mental arithmetic is up to scratch!)

1. Input: `¼d`, `¼d`
Output: **`½d`**
2. Input: `11¾d`, `¼d`
Output: **`1/-`**
3. Input: `£1`, `6d`, `9d`
Output: **`£1.1s.3d`**
4. Input: `£71.11s.4¼d`, `12/6`, `8/-`, `8/-`, `2½d`
Output: **`£73.-.¾d`**

---

If (and only if) your language/platform cannot represent the farthings (yes, I'm looking at you, ZX81!), you may use the letters `n`, `w` and `r` instead, to mean ¼ (o**n**e), ½ (t**w**o) and ¾ (th**r**ee) respectively.

This is , so the shortest working program (in bytes) is the winner. Please indicate the source character-coding if it's not UTF-8 (and not determined by the language).

Standard loopholes which are no longer funny are not permitted.

# Answer
> 2 votes
# Retina 0.8.2, 252 bytes

```
.+/.+
£.$&d
m`(?<!d)$
./d
m`^(?!£)
£./
s.
/
([¼½¾])?d
d0$1
T`¼½¾`123
[-\d]+
$*
+`.(1*)/(1*)d(1*)¶£(1*).(1*)/(1*)d
$4.$1$5/$2$6d$3
+`d1111
1d
+`/1{12}
1/
+`\.1{20}
1.
(.)(1*)
$1$.2
\b0
-
T`d`_¼½¾`.$
-?d(.)
$1d
£-.-/

£-.(.+)d
$1
(\..+)/
$1s.
-s
-
.-.-d

```

Try it online! Explanation:

```
.+/.+
£.$&d
m`(?<!d)$
./d
m`^(?!£)
£./
s.
/

```

Reformat the input into a fixed format `£<l>.<s>/<d>d<f>`.

```
([¼½¾])?d
d0$1
T`¼½¾`123
[-\d]+
$*

```

Convert to unary.

```
+`.(1*)/(1*)d(1*)¶£(1*).(1*)/(1*)d
$4.$1$5/$2$6d$3
+`d1111
1d
+`/1{12}
1/
+`\.1{20}
1.

```

Add up the values.

```
(.)(1*)
$1$.2
\b0
-
T`d`_¼½¾`.$
-?d(.)
$1d
£-.-/

£-.(.+)d
$1
(\..+)/
$1s.
-s
-
.-.-d

```

Convert back to decimal and format for display.

# Answer
> 2 votes
# Clean, ~~555~~ ... 504 bytes

*Uses ANSI codepage `Windows-1252`, but since TIO treats Clean source files as UTF-8, all invalid UTF-8 character literals are represented with octal escape sequences and counted as one byte.*

```
import StdEnv,Text,StdLib
n=0.0
e=entier
r=toReal
*0=""
*n=fromInt n
?'\274'=".25"
?'\275'=".5"
?'\276'=".75"
?c={c}
@s=r{#d\\c<-:s,d<-: ?c|all((<>)c)['sd\243']}
$s|"9"<s%(0,0)=(map@(split"."s)++[n,n])%(0,2)|endsWith"d"s=[n,n,@s]=[n:map@(split"/"s)]
^[x,y,z]#d=e z
#p=if(z>r d){'\273'+toChar(e((z-r d)/0.25))}""
#(y,d)=(d/12+e y,d rem 12)
#[x,y,d:_]=map*[y/20+e x,y rem 20,d]
|x>""=join"."["\243"+++x,y+++if(y>"")"s""-",d+++if(z>n)(p+++"d")"-"]|y>""=join"/"[y,d+++if(z>n)p"-"]=d+++p+++"d"

```

#

```
^o foldr(zipWith(+))[n,n,n]o map$

```

A partial function literal, taking `[String]` and returning `String`.

Try it online!

# Answer
> 2 votes
# APL (Dyalog Classic), ~~265~~ 260 bytes

*Now works even for edge cases not in the example cases.*

Full program. Prompts (STDERR) for input (STDIN) of list of strings. Outputs to STDOUT.

Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems.

`0(('^0' '$',d)⎕R('' 'd',f)⍕2↓t)r(r←' 0d' ' 0?'⎕R'/-' '/'⊢d⎕R f,∘'d'⍕1↓t)('£',⍕⊃t)(∊'£'(⍕⊃t)'.','-'('s',⍨⍕1⊃t)[×1⊃t]'.','-d' '-'⎕R'-' ''⊢'d',⍨(d,⊂'^0')⎕R(f,'-')⍕2⊃t)[5⌊2⊥×t←v⊤+/((v←0 20 12)⊥(¯3+6×'£'=⊃)↑∘⍎('-' '\D',⍨f←,¨'nwr')⎕R('0 ',⍨1↓¨d←('\.',⍕)¨25 5 75))¨⎕]`

Try it online! (or equivalent Unicode edition sporting proper fractions)

## Explanation

This program has five parts; one that handles input, conversion, summation, and *selection* of output format, and one for each of the four possible output formats which are:

1. *less* than a shilling: `¼d``11¾d`
2. a whole number of shilling, which is the same format as
3. *between* a shilling and a pound: `1/-``19/11¾`
4. *whole* pounds: `£1`, `£2`,… `£999`
5. *everything* else: `£1.-.¼d``£999.19s.11¾d`

The overall structure of the program is:

`0(` *less* `)r(r←'` *between* `)(` *whole* `)(` *everything* `)[` *selection* `]`

This uses *selection* to index from a list of all possible formats. The initial `0` is a placeholder for output format 0 which does not exist. `r←` assigns format 4. to the variable `r`, which is then used as format 2.

### input, conversion, summation, and *selection* of output format

`5⌊2⊥×t←v⊤+/((v←0 20 12)⊥(¯3+6×'£'=⊃)↑∘⍎('-' '\D',⍨f←,¨'nwr')⎕R('0' ' ',⍨1↓¨d←('\.',⍕)¨25 5 75))¨⎕`

prompt for (evaluated) user input (list of strings)

`(` on each string, apply the following tacit function:

`25 5 75` the numeric list `[25,5,75]`

`(` on each number, apply the following function:

the string representation

`'\.',` preceded by an escaped (for PCRE) period

`d←` store that in `d` (for **d**ecimals; `["\.25","\.5","\.75"]`)

`1↓¨` drop one character from each; `[".25",".5",".75"]`

`'0 ',⍨` append the two characters; `[".25",".5",".75","0"," "]`

`(``)⎕R` PCRE **R**eplace the following strings with the above:

`,¨'nwr'` ravel (make into own vector) each of these characters; `["n","w","r"]`

`f←` store in `f` (for **f**ractions)

`'-' '\D',⍨` append these two strings; `["n","w","r","-","\D"]`

execute as APL statement (this gives a numeric list)

then

`(``)↑` take this many elements (padding with zeros as needed):

the first of the argument (one of the strings)

`'£'=` Boolean (0 or 1) whether it is a pound symbol

multiply by six; gives 6 if string had pound(s), 0 if not

`¯3+` add negative three; gives 3 if string had pound(s), −3 if not

Taking a negative number of elements takes from the right and pads on the left if needed. Taking a positive number of elements takes from the left and pads on the right if needed. Thus we now have pounds, shillings, and pence in fixed positions in a length-3 list for each input string.

`(``)⊥` convert to regular number (pence) from the following mixed-base:

`0 20 12` 12 pence per shilling, 20 shilling per pound, no amount of pounds convert up

`v←` store in `v` (for **v**alues)

`+/` sum (lit. plus reduction)

`v⊤` convert to mixed-base `v`

`t←` store in `t` (for **t**otal)

`×` signum of those values

`2⊥` convert to regular number from base-2 (binary)

`5⌊` find the minimum of five and that.

Gives 1 for pence-only, 2 for shilling only, 3 for shilling and pence, 4 for pounds only, and 5 for pounds and change.

### *everything* else

`∊'£'(⍕⊃t)'.','-'('s',⍨⍕1⊃t)[×1⊃t]'.','-d' '-'⎕R'-' ''⊢'d',⍨(d,⊂'^0')⎕R(f,'-')⍕2⊃t`

`2⊃t` the third (pence) value of `t`

string representation of that

`⎕R(``)` PCRE **R**eplace the following strings:

`f,'-'` the list `f` followed by a dash; `["n","w","r","-"]`

`(``)` with:

`⊂'^0'` this string (regex: leading zero)

`d,` appended to `d`; `["\.25","\.5","\.75","^0"]`

`'d',⍨` append a "d" to that

`'-d' '-'⎕R'-' ''` remove stray "d"s and dashes (caused by less than a whole pence)

`…'.',` prepend the following and a period to that:

…`]` use

`1⊃t` the second element of `t` (the shilling)

`×` the signum of that (i.e. whether we have any shilling or not)

`'-'``[` to index from a dash and the following:

`1⊃t` the second element of `t` (the shilling)

the string representation of that

`'s',⍨` followed by an "s"

`'£'(``)'.',` prepend a pound sign, and the below, and a period to that:

`⊃t` the first element of `t` (the pounds)

the string representation of that

**ϵ**nlist (flatten)

### *whole* pounds

`'£',⍕⊃t`

`⊃t` the first element of `t` (the pounds)

the string representation of that

`'£',` prepend a pound symbol

### *between* a shilling and a pound

`' 0d' ' 0?'⎕R'/-' '/'⊢d⎕R f,∘'d'⍕1↓t`

`1↓t` drop one element from `t` (leaving the shillings and the pence)

the string representation (space separated) of that

`,∘'d'` append a "d" to that (lit. apply the append function with a curried right argument)

`d⎕R f` PCRE **R**eplace `d` (`["\.25","\.5","\.75"]`) with `f` (`["n","w","r"]`)

yield that (separates the following from `d`)

`' 0d' ' 0?'⎕R'/-' '/'` PCRE **R**eplace:
no-pence with slash-dash
leading pence-zero with slash

### *less* than a shilling

`('^0' '$',d)⎕R('' 'd',f)⍕2↓t`

`2↓t` drop the first two elements of `t` (leaving just pence)

the string representation of that

`⎕R(``)` PCRE **R**eplace with the following:

`'' 'd',f` the list `f` preceded by these two strings; `["","d","n","w","r"]`

`(``)` where the following occur:

`'^0' '$',d` the list `d` preceded by these two strings; `["^0","$","\.25","\.5","\.75"]`
the first is a leading zero
the second marks the end of a string

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


# Question
Title: Tri-interquine - Three programs that output each other in a loop
Related: Interquine

Program A outputs program B's code when run, and B outputs C's source, and C outputs A's source.

This time you can't exchange two characters and exchange again :)

### Requirements:

* Only one language across all programs
* Standard loopholes restrictions apply
* All programs are different. One program that outputs itself does not qualify. Two that output each other does not qualify, too.
* All programs are non-empty, or at least 1 byte in length.
* There's nothing to read because stdin is connected to `/dev/null` (You can abuse this rule if you *can*). Output goes to stdout.
* Do not use functions that generate random results.

Additional:

* Give explanations if possible

Score is **length of the shortest one** (can you generate a long program from a short one?). Please write the length of all programs and highlight the smallest number. Trailing newline does not count. Lowest score wins.

# Answer
# Python 3, 50 bytes

```
s='s=%r;print(s%%(s,%i*2%%7))';print(s%(s,1*2%7))

```

Try it online!

The last expression goes from `1*2%7` to `2*2%7` to `4*2%7` then back to `1*2%7`.
> 19 votes

# Answer
# RProgN 2, ~~12~~ 8 bytes

```
1
«\2*7%

```

## Explained

```
1   # Push the digit to the stack.

«\2*7%
«       # Define a function from here to the matching ». As there is no matching », define it from here to the end of the program, and continue running.
 \      # Flip the function under the constant number.
  2*    # Multiply by 2.
    7%  # Modulo 7.

```

Due to the convenient nature of how RProgN defaultly outputs, this leaves the number, which loops between 1, 2, and 4, on the first line, and the stringified version of the function on the second. Inspired by @LeakyNun's Python Answer

Try it online!
> 4 votes

# Answer
## CJam, 17 bytes

```
{sZZe\6Ye\"_~"}_~

```

```
{s6Ze\ZYe\"_~"}_~

```

```
{sZ6e\ZYe\"_~"}_~

```

Try it online!

Probably not optimal, but this is a modification of my approach to the previous challenge.

The basic idea is the same, but we perform two swaps, one of which is always a no-op. The affected indices are `2`, `3` and `6`:

```
1:     {sZZe\6Ye\"_~"}_~
ZZe\             does nothing
       {sZZe\6Ye\"_~"}_~
6Ye\     \   /
          \ /
           X
          / \
         /   \
2:     {s6Ze\ZYe\"_~"}_~
6Ze\      \  /
           \/    doesn't really do anything
           /\
          /  \
       {s6Ze\ZYe\"_~"}_~
ZYe\     \/
         /\
3:     {sZ6e\ZYe\"_~"}_~
Z6e\      \  /
           \/
           /\
          /  \
       {sZZe\6Ye\"_~"}_~
ZYe\     \/      doesn't really do anything
         /\
1:     {sZZe\6Ye\"_~"}_~

```
> 4 votes

# Answer
## CJam, 14 bytes

```
{_]3/W="_~"}_~

```

```
{_]3/W="_~"}{_]3/W="_~"}_~

```

```
{_]3/W="_~"}{_]3/W="_~"}{_]3/W="_~"}_~

```

Try it online!

The other programs are 26 and 38 bytes long, respectively.

### Explanation

Yet another approach!

```
{       e# Again, the usual quine framework. In this case, there might
        e# be one or two additional copies of the block on the stack.
  _     e#   Duplicate the top copy of the block.
  ]     e#   Wrap all copies in an array.
  3/    e#   Split into chunks of 3. For the first two programs, this will
        e#   just wrap all of them in an array. For the third program, this
        e#   splits the fourth copy off from the first three.
  W=    e#   Select the last chunk. So `3/W=` does nothing for the first
        e#   two programs, but discards three copies once we get to four.
  "_~"  e#   Push the remainder of the program.
}_~

```
> 3 votes

# Answer
# Jelly, 11 bytes

```
“Ḥ%7Øv;”Ṙv1

```

This generated the same program with **1** replaced by **2**, which replaced **2** by **4**, which generates the original program.

Try it online!
> 2 votes

# Answer
**Python 3, 127, 127 and 127 bytes**

```
a='a=%r;b=%r;c=%r;print(b%%(b,a,c))';b='b=%r;a=%r;c=%r;print(c%%(c,a,b))';c='c=%r;a=%r;b=%r;print(a%%(a,b,c))';print(b%(b,a,c))

```

prints

```
b='b=%r;a=%r;c=%r;print(c%%(c,a,b))';a='a=%r;b=%r;c=%r;print(b%%(b,a,c))';c='c=%r;a=%r;b=%r;print(a%%(a,b,c))';print(c%(c,a,b))

```

prints

```
c='c=%r;a=%r;b=%r;print(a%%(a,b,c))';a='a=%r;b=%r;c=%r;print(b%%(b,a,c))';b='b=%r;a=%r;c=%r;print(c%%(c,a,b))';print(a%(a,b,c))

```

This is based on my answer to the Interquine question, which is based on a normal Python quine. And I know exactly what to do when we get a quad-interquine question ;)
> 2 votes

# Answer
## CJam, 14 bytes

```
0{\)3%\"_~"}_~

```

```
1{\)3%\"_~"}_~

```

```
2{\)3%\"_~"}_~

```

Try it online!

### Explanation

```
0{      e# Again, the standard CJam quine framework, but this time we have a zero
        e# at the bottom of the stack.
  \     e#   Bring the 0 to the top.
  )     e#   Increment.
  3%    e#   Mod 3 to loop from 2 back to 0.
  \     e#   Put the result underneath the block again.
  "_~"  e#   Push the remainder of the source.
}_~

```
> 1 votes

# Answer
# Javascript (ES6), ~~63~~ 55 bytes

```
eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=0)

```

```
eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=1)

```

```
eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=2)

```

```
o1.innerText = eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=0)
o2.innerText = eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=1)
o3.innerText = eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=2)
```

```
<pre id="o1"></pre>
<pre id="o2"></pre>
<pre id="o3"></pre>
```

Alternative solution using `Function.prototype.toString` (cheaty, 30 bytes)

```
(f=n=>`(f=${f})(${++n%3})`)(1)

```
> 1 votes

# Answer
# Lambda Calculus, 38 characters, 44 bytes

A simple solution based on the mother of all quines: the y-combinator:

```
(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx)

```

Using beta reductions we see that this indeed a tri-interquine:

```
(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx)
(λy.y)(λz.z)(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx)
(λz.z)(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx)
(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx)
etc.

```
> 1 votes

# Answer
# Java 8, 118 bytes

```
v->{int i=0;String s="v->{int i=%d;String s=%c%s%2$c;return s.format(s,++i%%3,34,s);}";return s.format(s,++i%3,34,s);}

```

Only `int i=0;` is difference between the functions/outputs (it's either `0`, `1` or `2`).

**Explanation:**

Try it online.

```
v->{                       // Method with empty unused parameter and String return-type
  int i=0;                 //  Integer, starting at 0, 1 or 2 depending on the version
                           //  (this is the only variation between the functions/outputs)
  String s="v->{int i=%d;String s=%c%s%2$c;return s.format(s,++i%%3,34,s);}";
                           //  String containing the unformatted source code
  return s.format(s,++i%3,s);}
                           //  Quine to get the source code, which we return as result
                           //  ++i%3 is used to cycle 0→1→2→0

```

Additional explanation:

-part:

* `String s` contains the unformatted source code
* `%s` is used to put this String into itself with `s.format(...)`
* `%c`, `%2$c` and `34` are used to format the double-quotes (`"`)
* `%%` is used to format the modulo-sign (`%`)
* `s.format(s,...,34,s)` puts it all together

Difference of the outputs/functions:

Same approach as most other answers:

* `int i` starts at either `0`, `1` or `2`
* `++i%3` transforms this to the next (`0→1`; `1→2`; `2→0`)
> 0 votes

# Answer
# \>\<\>, 15 bytes

```
1'~r2*7%nd3*>o<

```

Try it online!

Uses the same general form as other \>\<\> quines, but has an extra character in front that is cycled through 1, 2 and 4.
> 0 votes

---
Tags: code-golf, quine
---


title: Visualize Visual Eyes

text:
# Question
Title: Visualize Visual Eyes
You may or may not remember Xeyes, a demo program that came with (and, as far as I know, still comes with) the X window system. Its purpose was to draw a pair of eyes that followed your mouse cursor:

Your challenge is to recreate Xeyes with ASCII art. Write a program or function that draws two ASCII art eyes (specified below) wherever the user clicks and then moves their pupils to point in the direction of the cursor.

The above GIF is a recording of this non-golfed Ruby implementation, which can be run with any recent version of Ruby. You may also find it useful as reference for Xterm control sequences.

## Specifications

This is , so the solution with the fewest bytes wins.

This is an challenge, so your program must draw using ASCII characters—specifically, the characters `-`, `.`, `|`, `'`, `0`, space, and newline.1 2

This is an challenge, so your program must accept input and draw its output in realtime.3

Before your program begins accepting input, it should initialize a blank canvas of at least 20 rows and 20 columns. It should not draw anything until the user clicks on the canvas.

Any time the user clicks4 on the canvas, the program should clear any previous output and then draw these ASCII eyes on the canvas, centered on the character nearest the location of the mouse cursor.5 6 (Below,  represents the mouse cursor and should not be drawn.)

```
.---. .---.
|   | |   |
|  0|✧|0  |
|   | |   |
'---' '---'

```

Note how the pupils "point" toward the cursor.

Any time the mouse cursor moves on the canvas, the program should re-draw the pupils so that they continue pointing toward the cursor,7 e.g.:

```
             ✧

.---. .---.
|  0| |  0|
|   | |   |
|   | |   |
'---' '---'

```

## Pupil pointing

Suppose we enumerated the positions of the inner nine characters of each eye like so:

```
.---.
|678|
|591|
|432|
'---'

```

The pupil will be drawn at one of the locations `1`-`9`. To decide which one, pretend the characters are square and that the canvas is a Cartesian grid, with the center of the `9` character at (0, 0), the center of `1` at (1, 0), and so on. When the program receives input—a click or movement—it should map the input location to the nearest grid coordinate . If is (0, 0), the pupil should be drawn at (0, 0), i.e. the location of the `9` above. Otherwise, it should be drawn as described below.

Imagine a Cartesian plane superimposed on the grid and divided into octants numbered **1****8**:

If lies within octant **1**, then the pupil should be drawn at the location of `1` above, i.e. at (1, 0). If is in octant **2** it should be drawn at `2`—and so on. To illustrate, the below image shows part of the grid color-coded according to where the pupil should be drawn when the mouse cursor is at a particular location. When, for example, the cursor is at any of the green coordinates (keeping in mind that the grid coordinates lie at the squares' centers, not their corners), the pupil should be drawn at `4`.

The two eyes' pupils move independently, so for each eye repeat the process with relative to that eye's center.

## Notes

1. This isn't a challenge. The output must be a grid of characters. You may, of course, use graphics routines to draw a grid of characters.
2. Whitespace may be drawn (or, rather, not drawn) however is convenient. An empty spot in the grid looks the same as a space character and will be considered equivalent.
3. "Real-time" is defined here as fewer than 200ms between input and the corresponding output being drawn.
4. It is at your discretion which mouse button(s) are observed for input, and whether a press or release constitutes a "click."
5. The canvas must be cleared, or the visual equivalent must be achieved. With a terminal-based solution, for example, printing a new canvas below the previous canvas is not considered equivalent.
6. When the user clicks near the edge of the canvas such that some of the eye characters would be drawn beyond its edge, the behavior is undefined. However, the program must continue running normally upon subsequent clicks.
7. When the mouse cursor leaves the "canvas," the behavior is undefined, but the program must continue running normally when the cursor re-enters the canvas.
8. A text cursor may appear on the canvas, as long as it does not obscure the output.

Standard loopholes are forbidden.

# Answer
> 11 votes
# QBasic (QB64), ~~361~~ 305 bytes

```
DO
WHILE _MOUSEINPUT
x=CINT(_MOUSEX)
y=CINT(_MOUSEY)
IF _MOUSEBUTTON(1)THEN l=x-3:k=y
IF(2<l)*(73>l)*(2<k)*(22>k)THEN CLS:FOR i=0TO 1:h=l+6*i:LOCATE k-2,h-2:?".---.":FOR j=1TO 3:LOCATE,h-2:?"|   |":NEXT:LOCATE,h-2:?"'---'":d=x-h:e=y-k:m=ABS(e/d):LOCATE k-SGN(e)*(m>=.5),h-SGN(d)*(m<=2):?"0":NEXT
WEND
LOOP

```

Left-click places the eyes. If placement of eyes would result in part of the eyes being out of bounds, the program "freezes" until a valid placement is made.

The main tricky part is placing the pupils. Most of the time, the coordinates of the pupil are just the center of the eye plus (sign(Δx), sign(Δy)), except that in octants 1 and 5, the y-coordinate equals y-center, and in octants 3 and 7, the x-coordinate equals x-center. Octant boundaries can be calculated using the slope `m` of the line from the center of the eye to the mouse coordinates. Conveniently, dividing by zero when calculating the slope gives floating-point infinity (+/-) rather than an error.

### Ungolfed

```
' Loop forever
DO
    ' Do stuff if there is new mouse data (movement or click)
    IF _MOUSEINPUT THEN
        ' Store the mouse coords rounded to the nearest integer
        mouse_x = CINT(_MOUSEX)
        mouse_y = CINT(_MOUSEY)
        ' If left mouse button was clicked, change location of eyes
        IF _MOUSEBUTTON(1) THEN
            ' Store center coordinates of left eye
            left_center_x = mouse_x - 3
            center_y = mouse_y
        END IF
        ' If eye location is in bounds, print the eyes and pupils
        x_in_bounds = left_center_x > 2 AND left_center_x < 73
        y_in_bounds = center_y > 2 AND center_y < 22
        IF x_in_bounds AND y_in_bounds THEN
            CLS
            FOR eye = 1 TO 2
                ' eye = 1 for left eye, eye = 2 for right eye
                IF eye = 1 THEN center_x = left_center_x
                IF eye = 2 THEN center_x = left_center_x + 6
                ' Print eye borders
                LOCATE center_y - 2, center_x - 2
                PRINT ".---."
                FOR row = 1 TO 3
                    LOCATE , center_x - 2
                    PRINT "|   |"
                NEXT row
                LOCATE , center_x - 2
                PRINT "'---'"
                ' Calculate coordinates of pupil
                xdiff = mouse_x - center_x
                ydiff = mouse_y - center_y
                slope = ydiff / xdiff
                ' For most cases, adding the sign of the diff to the center
                ' coordinate is sufficient
                pupil_x = center_x + SGN(xdiff)
                pupil_y = center_y + SGN(ydiff)
                ' But in octants 3 and 7, the x-coordinate is centered
                IF ABS(slope) > 2 THEN pupil_x = center_x
                ' And in octants 1 and 5, the y-coordinate is centered
                IF ABS(slope) < 0.5 THEN pupil_y = center_y
                LOCATE pupil_y, pupil_x
                PRINT "0"
            NEXT eye
        END IF   ' in bounds
    END IF   ' mouse data
LOOP   ' forever

```

# Answer
> 20 votes
# Excel VBA 32-Bit, ~~630~~ 519 Bytes

A `Worksheet` level `Sub`routine that activates on every click. Draws eyes in a \\$5\times 11\\$ range centered at the clicked cell.

This is calibrated to run at the default zoom of 100%. It breaks if when scrolling, zooming, or selecting multiple cells.

```
Sub Worksheet_SelectionChange(ByVal t As Range)
With Cells
.Clear
.ColumnWidth=1.3
.Font.Name="Courier"
End With
Dim l As p,p As p
Q l
On Error Resume Next
Do
DoEvents
Q p
For i=0To 1
v=l.x-p.x+56*(-1)^i
w=l.y-p.y
n=IIf(Abs(v)>6Or Abs(w)>9,(4*Application.Atan2(v,w)\[Pi()]+4)Mod 8,8)
For j=0To 24
m=Mid(".---.|567||480||321|'---'",j+1,1)
t.Offset(j\5-2,j Mod 5+1-6*i)=Mid("0 '"&m,3+(m Like"[0-9]")+(m=Val(n)))
Next j,i
Loop
End Sub

```

***Note:** terminal `"` on line 5 is included for Prettify.JS/Markdown syntax highlighting only, and does not contribute to byte count*

### Helper Function and Type Declaration

The below declarations allow for querying the cursor position using the Windows management function GetCursorPos.

These must be declared in an accessible `Module` level context.

```
Declare Sub Q Lib"user32"Alias"GetCursorPos"(l As p)
Type p
x As Long
y As Long
End Type

```

The above is only compatible with 32-bit installations of Excel, but may be adjusted to run in a 64-bit installs by modifying the the declaration to

```
Declare PtrSafe Sub Q Lib"user32"Alias"GetCursorPos"(l As p)

```

# Output

# Commented

```
''  execute the following every time the user changes selection
Sub Worksheet_SelectionChange(ByVal t As Range)

    ''  Tell VBA to keep running on errors
    ''    ( Necessary for specification Note #6 )
    On Error Resume Next

    ''  Clear All Cell, Make them Square, Use Monospace Font
    With Cells
        .Clear
        .ColumnWidth = 1.3
        .Font.Name = "Courier"
    End With

    ''  Dim two p (point) objects, defined below
    Dim l As p, p As p

    ''  Use Q (alias for User32 function GetCursoPos) to get initial mouse position (l)
    Q l

    ''  Implicitly loop until the next selection change event
    Do

    ''  Allow events
    DoEvents

    ''  Use User32 function to get current mouse position (p)
    Q p

    '' iterate over the two eyes (left: i=1, right: i=0)
    For i = 0 To 0 '1

        ''  define var (v) with horiontal distance between cursor and center of eye i
        v = l.x - p.x + 56 * (-1) ^ i

        ''  define var (w) with vertical distance between cursor and center of eyes
        w = l.y - p.y

        ''  Based off of (v) and (w), calculate which of the numbers in the below
        ''    should be the pupil for each eye
        ''
        ''  .---.
        ''  |567|
        ''  |480|
        ''  |321|
        ''  '---'
        ''
        n = IIf(Abs(v) > 6 Or Abs(w) > 9, (4 * Application.Atan2(v, w) \ [Pi()] + 4) Mod 8, 8)

        ''  Iterate over the 25 cells to be updated, per eye
        For j = 0 To 24

            ''  find character at current cell in template
            m = Mid(".---.|567||480||321|'---'", j + 1, 1)

            ''  stuff cell with the first *k* letters of  "0 '" & template char
            ''    where k defaults to 3,
            ''      is decremented by 1 if template char is a number  AND
            ''      is decremented by 1 if template char is n
            ''
            ''  Cases:
            ''    Border Characters (`.`,`-`,`|`,`'`):
            ''      start at 3rd character, cell holds `'` and template char
            ''      Note: `'` literal at beginning of cell coerces excel to display
            ''      any and all values as text, allowing `-` to be printed
            ''    Sclera Characters (` `):
            ''      start at 2nd character, cells hold ` '` and template char
            ''      but due to cell sizing and monospace font, only ` ` is visible
            ''    Iris / Pupil Characters (`0`):
            ''      start at 1st character, cells hold `0 '` and template char
            ''      but only leading `0` is visible
            ''      Note: use of `Val` here forces implicit type
            ''          coercion, and is generally *cursed*
            t.Offset(j \ 5 - 2, j Mod 5 + 1 - 6 * i) = Mid("0 '" & m, 3 + (m Like "[0-9]") + (m = Val(n)))

    ''  End For loops
    Next j, i

    ''  End Do loop
    Loop
End Sub

```

# Answer
> 16 votes
# HTML + CSS + JavaScript (ES6), 93 + 19 + ~~278~~ 276 = 388 bytes

```
w=7.8125
h=15
with(Math)r=round,
(onclick=e=>F.style=`margin:-3.5em -6.5ch;left:${x=r(e.x/w)*w}px;top:${y=r(e.y/h)*h}px`)({y:-40}),onmousemove=e=>(s=($,o)=>$.style=`left:${a=atan2(Y=r((e.y-y)/h),X=r((e.x-x)/w+o)),X|Y?w*r(cos(a)):0}px;top:${X|Y?h*r(sin(a)):0}px`)(L,3)&&s(R,-3)
```

```
*{position:relative
```

```
<pre id=F>.---. .---.
|   | |   |
| <a id=L>0</a> | | <a id=R>0</a> |
|   | |   |
'---' '---'
```

# Answer
> 14 votes
# 6502 machine code (C64 + 1351 mouse), 630 bytes

```
00 C0 20 44 E5 A9 FF 85 5E A2 3F A9 00 8D 10 D0 8D 1B D0 9D C0 02 CA 10 FA A0
0A A2 1E B9 5A C2 9D C0 02 CA CA CA 88 10 F4 A9 0B 8D F8 07 A9 18 8D 00 D0 A9
32 8D 01 D0 A9 0D 8D 27 D0 A9 01 8D 15 D0 78 A9 60 8D 14 03 A9 C1 8D 15 03 58
D0 FE 84 FD 85 FE A8 38 E5 FD 29 7F C9 40 B0 04 4A F0 0A 60 09 C0 C9 FF F0 03
38 6A 60 A9 00 60 20 44 E5 A5 69 38 E9 05 B0 02 A9 00 C9 1E 90 02 A9 1D 85 FD
18 69 02 85 5C 69 06 85 5D A5 6A 38 E9 02 B0 02 A9 00 C9 15 90 02 A9 14 85 FE
18 69 02 85 5E A9 65 8D BB C0 A9 C2 8D BC C0 A9 04 85 02 A6 FE 20 F0 E9 A9 02
85 5F A4 FD A2 00 BD FF FF 91 D1 C8 E8 E0 05 D0 F5 C8 C6 5F D0 EE E6 FE A9 6A
8D BB C0 A9 C2 8D BC C0 C6 02 30 0E D0 D1 A9 6F 8D BB C0 A9 C2 8D BC C0 D0 C5
60 C5 69 90 0A F0 5D E5 69 85 5F A9 C6 D0 09 49 FF 38 65 69 85 5F A9 E6 8D 1C
C1 8D 23 C1 8D 3E C1 A5 6A C5 5E 90 21 F0 12 E5 5E C5 5F 90 12 4A C5 5F B0 02
C6 FD A6 5E E8 D0 33 C6 FD A6 5E D0 2D 0A C5 5F B0 EE 90 F3 49 FF 38 65 5E C5
5F 90 0C 4A C5 5F B0 02 C6 FD A6 5E CA D0 11 0A C5 5F B0 F4 90 D7 A5 6A C5 5E
90 EE F0 D1 B0 C8 20 F0 E9 A9 30 A4 FD 91 D1 60 AD 19 D4 A4 FB 20 4E C0 84 FB
85 5F 18 6D 00 D0 8D 00 D0 6A 45 5F 10 08 A9 01 4D 10 D0 8D 10 D0 AD 10 D0 4A
AD 00 D0 B0 08 C9 18 B0 16 A9 18 D0 0F C9 58 90 0E 24 5F 10 05 CE 10 D0 B0 EF
A9 57 8D 00 D0 AD 1A D4 A4 FC 20 4E C0 84 FC 49 FF 85 5F 38 6D 01 D0 8D 01 D0
6A 45 5F 10 06 24 5F 10 11 30 07 AD 01 D0 C9 32 B0 04 A9 32 D0 06 C9 FA 90 05
A9 F9 8D 01 D0 A5 69 85 6B A5 6A 85 6C AD 10 D0 4A AD 00 D0 6A 38 E9 0C 4A 4A
85 69 AD 01 D0 38 E9 32 4A 4A 4A 85 6A AD 01 DC 29 10 C5 6D F0 0B 85 6D 29 10
D0 05 20 6C C0 30 10 A5 5E 30 46 A5 69 C5 6B D0 06 A5 6A C5 6C F0 3A A6 5E CA
86 5F A9 03 85 02 A6 5F 20 F0 E9 A9 20 A2 03 A4 5C 88 91 D1 C8 CA D0 FA A2 03
A4 5D 88 91 D1 C8 CA D0 FA E6 5F C6 02 D0 DD A5 5C 85 FD 20 E9 C0 A5 5D 85 FD
20 E9 C0 4C 31 EA 80 C0 E0 F0 F8 FC F0 D8 18 0C 0C 2E 2D 2D 2D 2E 5D 20 20 20
5D 27 2D 2D 2D 27

```

In action:

**No online demo**, sorry, because there's AFAIK no js C64 emulator supporting a mouse. If you want to try it yourself, grab VICE, download the binary executable and start it in the C64 emulator:

```
x64sc -autoload xeyes.prg -controlport1device 3 -keybuf 'sys49152\n'

```

To grab/ungrab the mouse input in the running emulator, use `ctrl+m` on Unix/Linux and `ctrl+q` on windows.

---

Yes, this had to be done ;) After all, there **is** an original Commodore mouse for the C64, but of course, the builtin operating system doesn't support it, so I first needed a mouse driver, which already took 230 bytes (including a mouse-cursor shaped hardware sprite and bounds checking code for the screen area, but without translating the pointer coordinates to text screen coordinates).

* To safe some bytes, I decided to keep the OS' IRQ working and use a few Kernal routines where possible (clearing the screen and getting a base pointer for a text screen row).
* The code also puts all variables in zeropage, which saves some more bytes, but destroys floating point values used by BASIC. As the program never exits anyways, this doesn't matter.
* The third trick to reduce size is self modification: There's only code to check for putting the pupil on the *left* side of the eye. The same code is reused after patching some decrement instructions to increment instructions for the right side.

If you're interested, you can read the code as *assembly source* here :)

# Answer
> 11 votes
# Clean, ~~1014~~ ~~904~~ ~~892~~ ~~884~~ ~~840~~ ~~814~~ ~~782~~ ~~772~~ 769 bytes

***-6 bytes if the eyes don't need to snap to a grid***

This wasn't easy. UIs in functional languages rarely are.

```
import StdEnv,StdIO,osfont,ostoolbox
a=toReal
c=1>0
Start w#(d,w)=openId w
#(t,w)=worldGetToolbox w
#(_,f,_)=osSelectfont("Courier",[],9)t
=let$p#(s,p)=accPIO getProcessWindowSize p
    =snd(openWindow NilLS(Window""NilLS[WindowId d,WindowMouse(\_=c)Able(noLS1@),WindowViewSize s,WindowPen[PenFont f]])p);@(MouseUp p _)s={s&ls=p};@(MouseMove p _)s=:{ls={x,y},io}={s&io=setWindowLook d c(c,(\_{newFrame}i#(w,i)=getFontCharWidth f' '(unfill newFrame i)
    =let g v=let m=y-p.y;n=p.x-x-v*w;s=abs(a m/a n);k|abs m<9&&abs n<w=5|s<0.4142=if(n>0)6 4=sign if(s>2.4143)0n+if(m>0)2 8in[".---.":["|"+++{if(k==e)'0'' '\\e<-[j..j+2]}+++"|"\\j<-[1,4,7]]]++["'---'"]in foldr(\e=drawAt{x=(x/w-5)*w,y=(y/9+e-2)*9}([a+++" "+++b\\a<-g -3&b<-g 3]!!e))i[0..4]))io};@_ s=s
in startIO SDI zero$[]w

```

Make sure that you're using iTasks Clean, have the `Courier` font installed, and have `StdLib` BEFORE any subfolders of `ObjectIO` in the module search path.

Compile with (example, may differ): `clm -IL StdLib -IL ObjectIO -IL "ObjectIO/OS <YOUR_OS_HERE>" -IL Dynamics -IL Generics -IL Platform -nci <MODULE_NAME_HERE>`

If you've never run Clean before, expect this project to take 5+ minutes to compile.

**Ungolfed:**

```
module main
import StdEnv,StdIO,osfont,ostoolbox
height=9
SlopeFor225 :== 0.4142

StartSize :== 8

Universe :== {corner1={x=0,y=0},corner2={x=1,y=1}}

Start :: *World -> *World
Start world = startConsole (openIds 1 world)

startConsole :: ([Id],*World) -> *World
startConsole ([windowID],world)
    # (toolbox,world) = worldGetToolbox world
    # (_,font,toolbox) = osSelectfont ("Consolas",[],height) toolbox
    = startIO SDI {x=0,y=0} (initialise font) [ProcessClose closeProcess] world
where
    initialise font pst
        # (size,pst) = accPIO getProcessWindowSize pst
        # (error,pst) = openWindow undef (window font size) pst
        | error<>NoError = abort "bad window"
        = pst

    window font size
        = Window "Xeyes" NilLS
            [WindowId           windowID
            ,WindowClose        (noLS closeProcess)
            ,WindowMouse        mouseFilter Able (noLS1 track)
            ,WindowViewDomain   Universe//(getViewDomain StartSize)
            ,WindowViewSize     size
            ,WindowPen          [PenFont font]
            ]

    track (MouseDown pos _ _) state=:{ls=point=:{x,y},io}
        # point = pos
        // move to mouse position
        = {state & ls=pos}

    track (MouseMove pos _) state=:{ls=point=:{x,y},io}
        //redraw to point at mouse
        # io = setWindowLook windowID True (True, look) io
        = {state & ls=point,io=io}
    where
        look _ {newFrame} picture
            # picture = unfill newFrame picture
            # (width,picture) = getPenFontCharWidth' 'picture
            = let
                determineSector u
                    # yDist = (y - pos.y)
                    # xDist = (pos.x - u)
                    # slope = abs(toReal yDist / toReal xDist)
                    | (abs yDist) < height && (abs xDist) < width = '9'
                    | slope < SlopeFor225 = if(xDist > 0) '1' '5'
                    | yDist > 0
                        | slope > (2.0+SlopeFor225) = '7'
                        = if(xDist > 0) '8' '6'
                    | slope > (2.0+SlopeFor225) = '3'
                    = if(xDist > 0) '2' '4'
                getEye u=map(map(\e|isDigit e=if(e==determineSector(x+u*width))'0'' '=e))[['.---.'],['|678|'],['|591|'],['|432|'],['\'---\'']]
            in foldr(\i pic=drawAt{x=(x/width-5)*width,y=(y/height+i-2)*height}([toString(a++[' ':b])\\a<-getEye -3&b<-getEye 3]!!i)pic)picture[0..4]

    mouseFilter (MouseDown _ _ _) = True
    mouseFilter (MouseMove _ _) = True
    mouseFilter _ = False

```

As you can see from the ungolfed version, most of the code is just setting up the combination of "monospaced font" with "respond to the mouse". And even though `Courier` doesn't make it easy to tell, it is actually drawing the `.`s and `'`s. Swapping to something like `Consolas` makes it clearer.

# Answer
> 3 votes
# Ruby, 335 + 13 = 348 bytes

+13 bytes for `-rio/console` flag to enable `IO#getch`.

Contains literal ESC (`0x1b`) characters, shown as  below. xxd dump follows.

**Caution:** This does not clean up after itself at exit. See note under **xxd dump** below.

```
include Math
$><<"␛[?1003h"
s=""
(s<<STDIN.getch
($><<"␛[2J"
x,y=$3.ord-32,$4.ord-32
u,v=x,y if$2
u&&[x-u+3,x-u-3].map{|a|b=y-v
e=4*asin(b/sqrt(a**2+b**2))/PI
printf"␛[%d;%dH.---.@|567|@|480|@|321|@'---'".gsub(/(#{(a<0?4-e:b<0?8+e:e).round%8rescue 8})|([0-8])|@/){$1?0:$2?" ":"␛[5D␛[1B"},v-2,x-a-2}
s="")if /M(C|(#))(.)(.)$/=~s)while 1

```

## Ungolfed

This is a pretty naïve golf of my original Ruby implementation.

```
include Math       # Saves a few bytes for asin, sqrt, and PI
$> << "␛[?1003h"   # Print xterm control sequence to start mouse tracking
s = ""             # Variable to hold input-so-far
(
  s << STDIN.getch   # Read a character from STDIN
  (
    $> << "␛[2J"                     # Clear terminal
    x, y = $3.ord - 32, $4.ord - 32  # Get cursor x and y from last match
    u, v = x, y if $2                # Update eye position if last matched control sequence was click ("#")

    u && [x-u+3, x-u-3].map {|a|     # For each eye's x-position
      b = y - v                                       # Eye's y position
      e = 4 * asin(b / sqrt(a**2 + b**2)) / PI        # Convert cursor (x,y) to angle w/ x-axis as 1/8 turns

      printf "␛[%d;%dH.---.@|567|@|480|@|321|@'---'"  # Control code to move text cursor, followed by template for eye
        .gsub(
          /(#{
            (a < 0 ? 4-e : b < 0 ? 8+e : e).round % 8 rescue 8  # Octant number 0-7 or 8 for center
          })|([0-8])|@/
        ){ $1 ? 0 : $2 ? " " : "␛[5D␛[1B" },            # Replace octant number with pupil; other digits with space; and @s with code to move cursor left and down for next line of eye
        v-2, x-a-2                                      # (y, x) position of top left corner of eye
    }
    s = ""                           # Clear input-so-far
  ) if /M(C|(#))(.)(.)$/ =~ s      # ...when input-so-far matches a movement ("C") or click ("#") control sequence
) while 1                        # ...forever

```

## xxd dump

This program turns on mouse tracking with the xterm control sequence `\e[?1003h` but doesn't turn it off at exit. To turn it off, use the control sequence `\e[?1003l`, e.g.:

```
ruby -rio/console visual_eyes.rb; printf '\e[1003l'

```

Since the program eats all input, it's hard to exit. If you want to be able to exit by pressing Ctrl+C, add the following line below `(s<<STDIN.getch`:

```
exit 130 if s.end_with?(?\003)

```

Without further ado:

```
00000000: 696e 636c 7564 6520 4d61 7468 0a24 3e3c  include Math.$><
00000010: 3c22 1b5b 3f31 3030 3368 220a 733d 2222  <".[?1003h".s=""
00000020: 0a28 733c 3c53 5444 494e 2e67 6574 6368  .(s<<STDIN.getch
00000030: 0a28 243e 3c3c 221b 5b32 4a22 0a78 2c79  .($><<".[2J".x,y
00000040: 3d24 332e 6f72 642d 3332 2c24 342e 6f72  =$3.ord-32,$4.or
00000050: 642d 3332 0a75 2c76 3d78 2c79 2069 6624  d-32.u,v=x,y if$
00000060: 320a 7526 265b 782d 752b 332c 782d 752d  2.u&&[x-u+3,x-u-
00000070: 335d 2e6d 6170 7b7c 617c 623d 792d 760a  3].map{|a|b=y-v.
00000080: 653d 342a 6173 696e 2862 2f73 7172 7428  e=4*asin(b/sqrt(
00000090: 612a 2a32 2b62 2a2a 3229 292f 5049 0a70  a**2+b**2))/PI.p
000000a0: 7269 6e74 6622 1b5b 2564 3b25 6448 2e2d  rintf".[%d;%dH.-
000000b0: 2d2d 2e40 7c35 3637 7c40 7c34 3830 7c40  --.@|567|@|480|@
000000c0: 7c33 3231 7c40 272d 2d2d 2722 2e67 7375  |321|@'---'".gsu
000000d0: 6228 2f28 237b 2861 3c30 3f34 2d65 3a62  b(/(#{(a<0?4-e:b
000000e0: 3c30 3f38 2b65 3a65 292e 726f 756e 6425  <0?8+e:e).round%
000000f0: 3872 6573 6375 6520 387d 297c 285b 302d  8rescue 8})|([0-
00000100: 385d 297c 402f 297b 2431 3f30 3a24 323f  8])|@/){$1?0:$2?
00000110: 2220 223a 221b 5b35 441b 5b31 4222 7d2c  " ":".[5D.[1B"},
00000120: 762d 322c 782d 612d 327d 0a73 3d22 2229  v-2,x-a-2}.s="")
00000130: 6966 202f 4d28 437c 2823 2929 282e 2928  if /M(C|(#))(.)(
00000140: 2e29 242f 3d7e 7329 7768 696c 6520 31    .)$/=~s)while 1

```

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


# Question
Title: How to solve the total task on "return true to win" in 21 chars
There is a site called "Return True to Win" with interesting tasks for Javascript programmers. The goal is to find arguments to a given function that force it to return true.

The following is one of the tasks:

```
function total(x) {
  return (x < x) && (x == x) && (x > x);
}

```

The users must find snippets for the value of `x` that cause the function to return true. To test snippets, you call the function with your snippet as the parameter (i.e. `total(<snippet>)`).

I found a 22-character solution:

```
{valueOf:_=>n++%3},n=0

```

Some people found the solution in 21 chars. I can't find out this solution. What is the solution in 21 chars?

# Answer
> 7 votes
# 21 chars

```
{valueOf:n=_=>n=2<<n}

```

---

My original joke, which got downvoted and proposed for deletion:

# 11 chars :)

```
total=_=>!0

```

Test:

```
function total(x) {
  return (x < x) && (x == x) && (x > x);
}
var arg = total=_=>!0
console.log(total(arg))

```

# Answer
> 4 votes
# Cheaty answer

I've already mentioned it in the comments, but it was not tested. It is now. You'll have to keep submitting it until it works.

```
{valueOf:Math.random}

```

### Demo

```
function total(x) {
  return (x < x) && (x == x) && (x > x);
}

for(i = 1; !total({valueOf:Math.random}); i++);

console.log('Returned true after ' + i + ' iteration(s)')
```

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


title: Defeat SVGCaptcha

text:
# Question
Title: Defeat SVGCaptcha
I came across SVGCaptcha, and immediately knew it was a bad idea.

I would like you to show just how bad an idea this is by extracting the validation code from the SVG images that code produces.

---

An example image looks like this:
Here is the source of the example image:

```
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
        "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"
             width="200" height="40"
    > <rect x="0" y="0" width="200" height="40"
        style="stroke: none; fill: none;" >
        </rect> <text style="fill: #4d9363;" x="5" y="34" font-size="20" transform="translate(5, 34) rotate(-17) translate(-5, -34)">8</text>
<text style="fill: #be8b33;" x="125" y="29" font-size="21" transform="translate(125, 29) rotate(17) translate(-125, -29)">f</text>
<text style="fill: #d561ff;" x="45" y="35" font-size="20" transform="translate(45, 35) rotate(-2) translate(-45, -35)">4</text>
<text style="fill: #3de754;" x="85" y="31" font-size="21" transform="translate(85, 31) rotate(-9) translate(-85, -31)">8</text>
<text style="fill: #5ed4bf;" x="25" y="33" font-size="22" transform="translate(25, 33) rotate(16) translate(-25, -33)">u</text>
<text style="fill: #894aee;" x="105" y="28" font-size="25" transform="translate(105, 28) rotate(9) translate(-105, -28)">1</text>
<text style="fill: #e4c437;" x="65" y="32" font-size="20" transform="translate(65, 32) rotate(17) translate(-65, -32)">x</text>
</svg>

```

---

The input is the SVG image, which is a textual format.

The only real restriction is that your code must produce the values in **the correct order**.
The input `<text>` elements are in random order so you have to pay attention to the `x` attribute in the `<text>` tag

---

Score is the number of bytes in the code

---

Since the code currently does two transforms that cancel each-other out you can ignore them, but if you do take them in consideration, go ahead and take a 30% reduction from your score.

# Answer
# Bash, 63 56 39 bytes

```
cat<<_|grep -o 'x=.*>'|cut -c4-|sort -n|grep -o '>.</t'|cut -c2

```

```
grep -o 'x=.*>'|cut -c4-|sort -n|grep -o '>.</t'|cut -c2

```

```
grep -o 'x=.*<'|sort -k1.4n|rev|cut -c2

```

Note: requires `cat`, `grep`, `sort`, `rev`, and `cut`. Takes input from stdin. The output is separated by line breaks on stdout. Make sure to press CTRL+D (not COMMAND+D on Mac) when finished entering the CAPTCHA. Input must be followed by a newline and then '\_'.

**EDIT**: Saved 13 bytes.

**EDIT 2**: Saved 20 bytes thanks to @manatwork!
> 18 votes

# Answer
# CJam, 26 bytes

```
q"x="/2>{'"/1=i}${'>/1=c}/

```

Try it online in the CJam interpreter.

### How it works

```
q     e# Read all input from STDIN.
"x="/ e# Split it at occurrences of "x=".
2>    e# Discard the first two chunks (head and container).
{     e# Sort the remaining chunks by the following key:
  '"/ e#   Split at occurrences of '"'.
  1=  e#   Select the second chunk (digits of x="<digits>").
  i   e#   Cast to integer.
}$    e#
{     e# For each of the sorted chunks:
  '>/ e#   Split at occurrences of '>'.
  1=  e#   Select the second chunk.
  c   e#   Cast to character.
}/    e#

```
> 13 votes

# Answer
# JavaScript, 95 93 91 bytes

```
l=[],r=/x="(\d*).*>(.)/g;while(e=r.exec(document.lastChild.innerHTML))l[e[1]]=e[2];l.join``

```

*edit: -2 bytes changing `documentRoot` to `lastChild`; -2 bytes changing `join('')` to `join```, thanks Vɪʜᴀɴ*

Enter code in the browser console on a page containg the SVG in question, writes to console output.
> 8 votes

# Answer
## Perl, 40 bytes

**39 bytes code + 1 for -n**

```
$a[$1]=$2 for/x="(.+)".+(.)</g}{print@a

```

### Example:

```
perl -ne '$a[$1]=$2 for/x="(.+)".+(.)</g}{print@a' <<< '<example from above>'
8u4x81f

```
> 7 votes

# Answer
# Bash + GNU utilities, 53

```
grep -Po '(?<=x=").*(?=<)'|sort -n|grep -Po '(?<=>).'

```

Like this answer, output is one char per line.
> 7 votes

# Answer
## Perl 6, 68 bytes

```
say [~] lines.map({/'x="'(\d+).*(.)\</??(+$0=>$1)!!()}).sort».value

```
> 3 votes

# Answer
# Befunge, 79 bytes

It feels like it should be possible to golf at least one more byte off of this, but I've been working on it for a couple of days now, and this is as good as I could get it.

```
<%*:"~"*"~"_~&45*/99p1v-">":_|#`0:~<
#,:#g7-#:_@^-+*"x~=":+_~99g7p>999p#^_>>#1+

```

Try it online!

**Explanation**

Make the execution direction right-to-left, and wrap around to start the main loop.
Read a char from stdin, and test for the end-of-file value.
If it's not end-of-file, check if it's a `>`.
If it's not a `>`, add it to the value on the stack which tracks the last two characters, and check if the current pair matches `x=`.
If not, multiply by 126 and mod with 126<sup>2</sup> to drop the oldest value from the pair and make space for the next character.
Wrap around again to repeat the main loop.
When an `x=` pair is encountered, skip the next character (the quote), read an integer (the *x* value), and divide by 20. This becomes the current offset which is saved for later.
When a `>` is encountered, read the next character (typically one of the captcha letters), and save that at the current offset in an "array". Reset the offset to 9, so the captcha letter won't be overwritten when later `>` characters are encountered.
Finally, when then end-of-file is reached, iterate over the 7 values saved in the array and output them one by one. That should give you all the captcha letters in the correct order.

I'm glossing over some of the details here, since the code paths overlap each other in ways which are a little difficult to explain, but it should give you a general idea of how the algorithm works.
> 3 votes

# Answer
# Python2, 129 bytes

```
import re,sys
print''.join(t[1] for t in sorted(re.findall(r'(\d+), -\d+\)"\>(.)\</t',sys.stdin.read()),key=lambda t:int(t[0])))

```

Takes the HTML source on stdin, produces code on stdout.
> 2 votes

# Answer
# Mathematica, 106 bytes

```
""<>(v=ImportString[#~StringDrop~157,"XML"][[2,3,4;;;;2]])[[;;,3]][[Ordering[FromDigits/@v[[;;,2,2,2]]]]]&

```

Note: The input needs to be in exactly the format specified by the example.
> 2 votes

# Answer
# , 28 26 25 24 bytes

```
d5jÍx=
ún
JÍ">
lH$dÍî

```

Try it online!

Explanation:

```
d5j              delete first 6 lines
   Í*<0x81>*x=     In every line, replace everything up to x=" (inclusive) by nothing
ún               Sort numerically
J                Join line (closing </svg>) with next line
 Í*<0x81>*">       In every line, replace everything up to "> by nothing
l␖H$d            Visual block around closing </text> tags, delete
     Íî          In every line, replace \n by nothing.

```

HexDump:

```
00000000: 6435 6acd 8178 3d0a fa6e 0a4a cd81 223e  d5j..x=..n.J..">
00000010: 0a6c 1648 2464 cdee                      .l.H$d..

```
> 2 votes

# Answer
# QuadS, 49 bytes

```
∊c[⍋⊃x c←↓⍎¨@1⍉(⊢⍴⍨2,⍨.5×≢)3↓⍵]
x="(\d+)
>(.)<
\1

```

Try it online!

Finds x values (digit-runs after `x="`) and "letters" (pinned by closing and opening tags), then executes the following APL (where  is the list of found x values and letters, in order of appearance):

`3↓⍵` drop the first three elements (spaces around `<rect``/rect>` and the `<rect`'s x value).

`(``)` apply the following tacit function on that:

the number of remaining items

`.5×` halve that

`2,⍨` append a two

`⊢⍴⍨` reshape to that shape (i.e. an n×2 matrix)

transpose (to a 2×n matrix)

`⍎¨@1` execute each string in the first row (turning them into numbers)

split the matrix into two vectors (one per row)

`x c←` store those two in x (x values) and c (characters) respectively

pick the first (x)

grade up (the indices into x which would sort x)

`c[``]` use that to index into `c`

**ϵ**nlist (flatten) because each letter is a string by itself

---

The equivalent APL expression of the entire QuadS program is:

```
∊c[⍋⊃x c←↓⍎¨@1⍉(⊢⍴⍨2,⍨.5×≢)3↓'x="(\d+)"' '>(.)<'⎕S'\1'⊢⎕]

```
> 2 votes

# Answer
# Java 8, ~~197~~ 173 bytes

```
import java.util*;s->{String a[]=s.split("x=\""),r="";Map m=new TreeMap();for(int i=2;i<a.length;m.put(new Long(a[i].split("\"")[0]),a[i++].split(">|<")[1]));return m.values();}

```

Outputs a `java.util.Collection` of characters.

**Explanation:**

Try it online.

```
import java.util*;            // Required import for Map and TreeMap
s->{                          // Method with String as both parameter and return-type
  String a[]=s.split("x=\""), //  Split the input by `x="`, and store it as String-array
         r="";                //  Result-String, starting empty
  Map m=new TreeMap();        //  Create a sorted key-value map
  for(int i=2;                //  Skip the first two items in the array,
      i<a.length;             //  and loop over the rest
    m.put(new Long(a[i].split("\"")[0]),
                              //   Split by `"` and use the first item as number-key
          a[i++].split(">|<")[1]));
                              //   Split by `>` AND `<`, and use the second item as value
    return m.values();}       //  Return the values of the sorted map as result

```
> 1 votes

# Answer
# Gema, 65 characters

```
x\="<D>*\>?=@set{$1;?}
?=
\Z=${5}${25}${45}${65}${85}${105}${125}

```

In Gema there is no sorting, but fortunately is not even needed.

Sample run:

```
bash-4.4$ gema 'x\="<D>*\>?=@set{$1;?};?=;\Z=${5}${25}${45}${65}${85}${105}${125}' < captcha.svg
8u4x81f

```
> 1 votes

# Answer
# XMLStarlet, 46 characters

```
xmlstarlet sel -t -m //_:text -s A:N:U @x -v .

```

Hopefully this is valid solution as XMLStarlet is transpiler that generates and executes XSLT code, which is a Turing complete language.

Sample run:

```
bash-4.4$ xmlstarlet sel -t -m //_:text -s A:N:U @x -v . < captcha.svg
8u4x81f

```
> 1 votes

# Answer
## PHP, 96 bytes

*Given that `$i` is the input string*

```
preg_match_all('|x="(\d+).*(.)\<|',$i,$m);$a=array_combine($m[1],$m[2]);ksort($a);echo join($a);

```
> 1 votes

# Answer
# Clean, ~~277~~ 150 bytes

Yay pattern matching!

```
import StdEnv,StdLib
?s=map snd(sort(zip(map(toInt o toString)[takeWhile isDigit h\\['" x="':h]<-tails s],[c\\[c:t]<-tails s|take 7 t==['</text>']])))

```

Try it online!

Defines the function `?`, taking `[Char]` and giving `[Char]`.
> 1 votes

---
Tags: code-golf, parsing
---


title: Regrowing trees

text:
# Question
Title: Regrowing trees
**Background**

Here you have another work-inspired challenge, but from my wife's work in this case. Imagine you have a service that returns the list of nodes in a tree structure (much like the files and folders in a file system), but in no particular order. For every node you get a tuple with its name and the name of its parent.

So if you get `[["C","B"],["D","C"],["A",""],["B","A"]]` (format: `[NodeName,ParentName]`), you could rebuild the tree structure and get a leaf with the path `/A/B/C/D` (`A` has no parent, then it is at the top level, then `B` is a child of `A`, `C` is a child of `B` and `D` is a child of `C`).

You could also get `[["C","B"],["D","C"],["A",""],["B","A"],["E","B"]]`, so the rebuilt tree would contain two leaves: one with the path `/A/B/C/D` (the same as in the previous example) and a new one with the path `/A/B/E` as the node `E` has `B` as its parent. Note that the nodes in the list are not duplicated (the leaves `D` and `E` have parts of their paths coincident but the common parts do not appear twice in the original list of nodes).

**Challenge**

Given a list of nodes as described above, rebuild the tree and output the paths for all the leaves in the tree structure, in no particular order as long as you return them all.

**Rules**

* The input will be a list of tuples with two elements each: the name of the current node and the name of its parent. If you don't like strings you can use arrays of chars. You can choose the order of the elements in the tuple (the node name first or the parent name first).
* The output format can be: a list of paths as strings like `["/A/B/C/D","/A/B/E"]` for the second example; a list of path nodes for each leaf, as in `[["A","B","C","D"],["A","B","E"]]` for the same example; or even a dictionary (something like `["A":["B":["E":[],"C":["D":[]]]]]`). Or you can just print the list of paths to STDOUT.
* There won't be nodes without a parent given explicitly.
* The node names will be strings of alphanumeric ASCII characters `[a-zA-Z0-9]` of any length. So you can use any other printable ASCII character as separator if you decide to print or return the paths as strings.
* There won't be duplicated tuples in the list.
* There won't be cyclic paths in the list of nodes.
* The node names are unique and case sensitive. Nodes `aa` and `AA` are not the same node.
* If you get an empty list of nodes, return an empty list/dictionary of leaves (or just print nothing).

**Test cases**

```
In:  [["C","B"],["D","C"],["A",""],["B","A"],["E","B"]]
Out: /A/B/C/D
     /A/B/E
Alt: [["A","B","C","D"],["A","B","E"]]
Alt: ["A":["B":["E":[],"C":["D":[]]]]]

In:  [["D3","D8"],["D5","d1"],["s2","S1"],["S1",""],["d1",""],["D8","D5"],["F4","s2"],["F7","S1"],["e3","D5"]]
Out: /d1/D5/D8/D3
     /d1/D5/e3
     /S1/s2/F4
     /S1/F7
Alt: [["d1","D5","D8","D3"],["d1","D5","e3"],["S1","s2","F4"],["S1","F7"]]
Alt: ["d1":["D5":["e3":[],"D8":["D3":[]]]],"S1":["F7":[],"s2":["F4":[]]]]

In:  [["Top",""]]
Out: /Top
Alt: [["Top"]]
Alt: ["Top":[]]

In:  []
Out:
Alt: []
Alt: []

```

This is , so may the shortest code for each language win!

---

This comes from the sandbox (for those who can see deleted posts).

# Answer
> 4 votes
# Haskell, 53 bytes

```
(""#)
e[]=[[]]
e a=a
p#l=[s:c|(q,s)<-l,p==q,c<-e$s#l]

```

Try it online!

Takes input as a pair `(parent,child)` because I find that order easier to read. Output is the "list of lists of strings" style.

The `#` operator takes a parent name on the left and the list of nodes on the right. First it iterates through the nodes that have that parent. Then it recurs, looking for that node's children and prepending the node to the list. If it has no children `e` will put in an empty list to terminate the sublist (otherwise nothing would ever get added to the output).

This code assumes that node names are unique which I thought must be the case because if there were two nodes like `/foo/bar/baz` and `/bar/baz` it would be impossible to tell where to put "baz".

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

```
a=>a.map(([c,p])=>g(p)[c]=g(c),g=s=>g[s]||(g[s]={}))&&g['']

```

Returns `undefined` if there are no top-level nodes. (+4 bytes to return an empty dictionary.)

# Answer
> 2 votes
# Pyth, 21 bytes

```
J.dQVf!}T_JJNWN=N@JNN

```

If we could take a dictionary, we could drop the first 4 bytes and replace the `J`s with `Q`s.
Try it online

### Explanation

```
J.dQVf!}T_JJNWN=N@JNN
J.dQ                    Convert the input to a dictionary and call it J.
     f!}T_JJ            Find the leaves (the keys of J that aren't values).
    V       N           For each leaf, print the label...
             WN=N@JNN   ... and climb the tree, printing along the way.

```

# Answer
> 1 votes
# Ruby 87 75 bytes

```
->d{k=d.flatten;k.map{|i|k.count(v=i)<2&&loop{v=(d.assoc(p v)||break)[1]}}}

```

inspired by this answer

Try it online!

---
Tags: code-golf, array, data-structures, tree-traversal
---


title: The Eyes are Following You

text:
# Question
Title: The Eyes are Following You
**This is inspired by the excellent Visualize Visual Eyes challenge. It is posted with permission from and credit to @Jordan**

We are going to create an ASCII art approximation of the Xeyes challenge but without worrying about the actual mouse movements. Just the positions.

**EDIT**

I thought about whether this could be seen as a duplicate but I don't believe it is.

* The previous question required detecting mouse movement. This does not and so is open to many more languages.This is simple interactive ASCII art which can be attempted in any language.
* While the algorithm for the eye movement may be similar, this is in many ways simpler to achieve.
* I'm not convinced that any answer given so far to the previous question could be trivially ported to this.
* I don't think I am good enough at languages that could answer the previous question to attempt it. I would have a try at this one.

If consensus is that I am wrong then I am happy to delete the question.

I have removed the comment about "interesting answer" as this is intended to be code golf.

**Overview**

In all cases the mouse position will be represented by an X.

Here are the eyes with no mouse position (cursor is off screen):

```
/---\ /---\
|   | |   |
| O | | O |
|   | |   |
\---/ \---/

```

Now let's say your mouse is to the right of the eyes:

```
/---\ /---\
|   | |   |
|  O| |  O|X
|   | |   |
\---/ \---/

```

and now at the bottom left:

```
 /---\ /---\
 |   | |   |
 |   | |   |
 |O  | |O  |
 \---/ \---/
X

```

and now at the top:

```
     X
/---\ /---\
| O | | O |
|   | |   |
|   | |   |
\---/ \---/

```

From this we can see that (in it's simplest case - we could make it a lot more complicated but let's not do that for now) there are 9 different positions for the eyes and nine different positions for the cursor as shown below:

```
1     2     3
 /---\ /---\
 |123| |123|
4|456| |456|6
 |789| |789|
 \---/ \---/
7     8     9

```

Position 5 represents no cursor (off screen). The eyes are both looking forward.

**The Challenge**

Take an integer (or any representation of an integer) between 1 and 9 inclusive and output the eyes if the cursor was in the position of that integer. You must include the X as the position of the cursor (except when it is off screen i.e. the eyes are looking forward - no X).

**Rules**

* Input format is your own choice.
* Program or function.
* Any amount of leading or trailing whitespace is allowed.
* Output must consist only of the characters /\\-| and either upper or
lowercase x and o.
* Assume that the input will always be valid, i.e. an integer between 1 and 9 inclusive.
* Feel free to change the order of the integers if it helps i.e. 2 does not have to be top and 5 does not have to be no cursor.
* Standard loopholes prohibited as usual.
* This is code golf. Shortest answer wins.

**Test Cases**

Note: All test cases use the numbering sequence detailed in the explanation. As stated in the rules, you do not have to use the same number sequence.

```
Input = 5

/---\ /---\
|   | |   |
| O | | O |
|   | |   |
\---/ \---/

Input = 6

/---\ /---\
|   | |   |
|  O| |  O|X
|   | |   |
\---/ \---/

Input = 2

     X
/---\ /---\
| O | | O |
|   | |   |
|   | |   |
\---/ \---/

Input = 7

 /---\ /---\
 |   | |   |
 |   | |   |
 |O  | |O  |
 \---/ \---/
X

```

This challenge has been in the sandbox for the last week.

# Answer
# Clean, 253 bytes

```
import StdEnv
?n=flatlines[[if([(0,0),(6,0),(12,0),(0,3),(0,9),(12,3),(0,6),(6,6),(12,6)]!!(n-1)==(v,u))'X'b\\b<-[' ':a++a]&v<-[0..]]\\a<-[spaces 6,['/---\\ ']]++[['|':[if(n==i)'0'' '\\i<-[j..j+2]]]++['| ']\\j<-[1,4,7]]++[['\\---/ '],spaces 6]&u<-[0..]]

```

Try it online!

This is mostly a port from my answer to the other question.
> 3 votes

# Answer
# , 119 112 bytes

```
d=.y-1
a=.'O'(d{,{;~2+i.3)}7 6$42$'       /---\ |   | |   | |   | \---/'
' '(<3 6)}'X'(d{,{(;+:)3*i.3)}a,.a,.' '

```

Try it online!
> 2 votes

# Answer
# Perl 5, ~~150~~ 140 bytes

```
$x=shift;$_='9     8     7
 /---\ /---\
 09870 09870
606540';$t=reverse;y/98764/12346/;$_.=" $t";s/(\d)$x(.)/\1O\2/g;s/$x/X/;y/0-9/| /;say

```

Try it online!

## Explanation

```
$x = shift;  # Shift the first value off the input argument array.
# Assign template string to default pattern-search variable.
# Only use first half of output. Use 0 instead of |.
$_ = '9     8     7
 /---\ /---\
 09870 09870
606540';
$t = reverse;  # $t is the reverse of $_.
y/98764/12346/;  # Correct digits in first half of template string $_,
                 # so 9 becomes 1, 8 becomes 2 etc.
$_ .= " $t";  # Append the two halves of the template.
s/(\d)$x(.)/\1O\2/g;  # Regexp replace all occurrences of $x, preceded by
                      # a digit and followed by any non-newline character,
                      # by "O" and the original surrounding characters.
s/$x/X/;  # Replace last remaining occurrence of $x by "X".
y/0-9/| /;  # Replace 0 by |, and all other remaining digits by a space.
say  # Print $_ followed by a newline.

```
> 2 votes

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


# Question
Title: Compute number of matrices with appropriate sums
When multiplying monomials in the Milnor basis for the Steenrod algebra, part of the algorithm involves enumerating certain "allowable matrices".

Given two lists of nonnegative integers *r1*, ... ,*rm* and *s1*, ... ,*sn*, a matrix of nonnegative integers X

is allowable if

1. The sum of the jth column is less than or equal to *sj*:
2. The sum of the ith row weighted by powers of 2 is less than or equal to *ri*:

## Task

Write a program which takes a pair of lists *r1*, ... ,*rm* and *s1*, *s1*, ... ,*sn* and computes the number of allowable matrices for these lists. Your program may optionally take m and n as additional arguments if need be.

* These numbers may be input in any format one likes, for instance grouped into lists or encoded in unary, or anything else.
* Output should be a positive integer
* Standard loopholes apply.

## Scoring

This is code golf: Shortest solution in bytes wins.

## Examples:

For `[2]` and `[1]`, there are two allowable matrices:

For `[4]` and `[1,1]` there are three allowable matrices:

For `[2,4]` and `[1,1]` there are five allowable matrices:

## Test cases:

```
   Input: [1], [2]
   Output: 1

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

   Input: [4], [1,1]
   Output: 3

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

   Input: [3,5,7], [1,2]
   Output: 14

   Input: [7, 10], [1, 1, 1]
   Output: 15

   Input: [3, 6, 16, 33], [0, 1, 1, 1, 1]
   Output: 38

   Input: [7, 8], [3, 3, 1]
   Output: 44

   Input: [2, 6, 15, 18], [1, 1, 1, 1, 1]
   Output: 90

   Input: [2, 6, 7, 16], [1, 3, 2]
   Output: 128

   Input: [2, 7, 16], [3, 3, 1, 1]
   Output: 175

```

# Answer
# JavaScript (ES7), 163 bytes

```
f=([R,...x],s)=>1/R?[...Array(R**s.length)].reduce((k,_,n)=>(a=s.map((_,i)=>n/R**i%R|0)).some(c=>(p+=c<<++j)>R,p=j=0)?k:k+f(x,s.map((v,i)=>v-a[i])),0):!/-/.test(s)

```

### Test cases

**NB**: I've removed the two most time-consuming test cases from this snippet, but they should pass as well.

```
f=([R,...x],s)=>1/R?[...Array(R**s.length)].reduce((k,_,n)=>(a=s.map((_,i)=>n/R**i%R|0)).some(c=>(p+=c<<++j)>R,p=j=0)?k:k+f(x,s.map((v,i)=>v-a[i])),0):!/-/.test(s)

console.log(f([1],[2]))            // 1
console.log(f([2],[1]))            // 2
console.log(f([4],[1,1]))          // 3
console.log(f([2,4],[1,1]   ))     // 5
console.log(f([3,5,7],[1,2]))      // 14
console.log(f([7,10],[1,1,1]))     // 15
console.log(f([7,8],[3,3,1]))      // 44
console.log(f([2,6,7,16],[1,3,2])) // 128
console.log(f([2,7,16],[3,3,1,1])) // 175
```

### Commented

```
f = (                               // f = recursive function taking:
  [R,                               //   - the input array r[] splitted into:
      ...x],                        //     R = next element / x = remaining elements
  s                                 //   - the input array s[]
) =>                                //
  1 / R ?                           // if R is defined:
    [...Array(R**s.length)]         //   for each n in [0, ..., R**s.length - 1],
    .reduce((k, _, n) =>            //   using k as an accumulator:
      (a =                          //     build the next combination a[] of
        s.map((_, i) =>             //     N elements in [0, ..., R - 1]
          n / R**i % R | 0          //     where N is the length of s[]
        )                           //
      ).some(c =>                   //     for each element c in a[]:
        (p += c << ++j)             //       increment j; add c * (2**j) to p
        > R,                        //       exit with a truthy value if p > R
        p = j = 0                   //       start with p = j = 0
      ) ?                           //     end of some(); if truthy:
        k                           //       just return k unchanged
      :                             //     else:
        k +                         //       add to k the result of
        f(                          //       a recursive call to f() with:
          x,                        //         the remaining elements of r[]
          s.map((v, i) => v - a[i]) //         s[] updated by subtracting the values of a[]
        ),                          //       end of recursive call
      0                             //     initial value of the accumulator k
    )                               //   end of reduce()
  :                                 // else:
    !/-/.test(s)                    //   return true if there's no negative value in s[]

```
> 3 votes

# Answer
# Jelly, 26 bytes

```
UḄ€Ḥ>⁴
0rŒpṗ⁴L¤µS>³;ÇẸµÐḟL

```

A full program taking **S**, **R** which prints the count

**Try it online!**

### How?

```
UḄ€Ḥ>⁴ - Link 1, row-wise comparisons: list of lists, M
U      - upend (reverse each)
 Ḅ€    - convert €ach from binary (note bit-domain is unrestricted, e.g. [3,4,5] -> 12+8+5)
   Ḥ   - double (vectorises) (equivalent to the required pre-bit-shift by one)
     ⁴ - program's 2nd input, R
    >  - greater than? (vectorises)

0rŒpṗ⁴L¤µS>³;ÇẸµÐḟL - Main link: list S, list R
0r                  - inclusive range from 0 to s for s in S
  Œp                - Cartesian product of those lists
       ¤            - nilad followed by link(s) as a nilad:
     ⁴              -   program's 2nd input, R
      L             -   length
    ṗ               - Cartesian power = all M with len(R) rows & column values in [0,s]
        µ      µÐḟ  - filter discard if:
         S          -   sum (vectorises) = column sums
           ³        -   program's 1st input, S
          >         -   greater than? (vectorises) = column sum > s for s in S
             Ç      -   call the last link (1) as a monad = sum(2^j × row) > r for r in R
            ;       -   concatenate
              Ẹ     -   any truthy?
                  L - length

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 101 bytes

Let Mathematica solve it as a system of inequalities over the integers. I set up a symbolic array in `f` and thread over three sets of inequalities. `Join@@` just flattens the list for `Solve`.

```
Length@Solve[Join@@Thread/@{Tr/@(t=f~Array~{q=(l=Length)@#2,l@#})<=#2,2^Range@q.t<=#,t>=0},Integers]&

```

Try it online!
> 1 votes

# Answer
# Mathematica 139 bytes

```
Tr@Boole[k=Length[a=#]+1;AllTrue[a-Rest[##+0],#>=0&]&@@@Tuples[BinCounts[#,{2r~Prepend~0}]&/@IntegerPartitions[#,All,r=2^Range@k/2]&/@#2]]&

```

Try it online

Explanation: Partitions each of the *ri* into powers of 2 and then makes all tuples with one decomposition into powers of two for each integer, subtract the column totals from the list of the *si*. Count the number of tuples that make all remaining entries are positive.
> 0 votes

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


title: Factoring factorials

text:
# Question
Title: Factoring factorials
Today in my statistics class, I found that some factorials can be simplified when multiplied together! For example: `5! * 3! = 5! *3*2 = 5! *6 = 6!`

## Your job:

Given a string containing only Arabic numbers and exclamation points, simplify my factorial to its shortest possible string, in the least amount of bytes for your language, code golf style.

## Input

A string containing only Arabic numbers and exclamation points. The factorials for the input won't be bigger than 200!. Factorials will not have more than one factorial per number. Input may be taken as a list of integers.

## Output

A possibly shortened string, that has the equivalent value on the input. Order is unimportant. Factorial notation is a must, but you aren't required to use more than one factorial symbol per number.

## Test cases

```
In: 3!2!2!
Out: 4!

In 2!3!2!0!
Out: 4!

In: 7!2!2!7!2!2!2!2!
Out: 8!8!

In: 23!3!2!2!
Out: 24!
Also: 4!!

In: 23!3!2!2!2!
Out: 24!2!

In: 127!2!2!2!2!2!2!2!
Out: 128!

In: 32!56!29!128!
Out: 29!32!56!128!

```

Best of luck

# Answer
# Jelly,  ~~17~~  18 bytes

```
!P
ÇṗLÇ⁼¥ÐfÇḢḟ1ȯ0F

```

A monadic link taking and returning a list of the numbers (sticks to the one factorial per number option)

**Try it online!**

### How?

A golfed (although independently written) version of Pietu1998's solution.

```
!P - Link 1, product of factorials: list
!  - factorial (vectorises)
 P - product

ÇṗLÇ⁼¥ÐfÇḢḟ1ȯ0F - Main link: list                       e.g. [3,2,2]
Ç               - call the last link (1) as a monad           24
  L             - length                                      3
 ṗ              - Cartesian power      [[1,1,1],[1,1,2],...,[1,1,24],...,[24,24,24]]
        Ç       - call the last link (1) as a monad           24
      Ðf        - filter keep if:
     ¥          -   last two links as a dyad:
   Ç            -     call the last link (1) as a monad     [1,2,...,24!,...,24!^3]
    ⁼           -     equal?
         Ḣ      - head
          ḟ1    - filter out any ones
            ȯ0  - or with zero (for the empty list case)
              F - flatten (to cater for the fact that zero is not yet a list)

```
> 5 votes

# Answer
# Jelly, 19 bytes

```
,!P€E
SṗLçÐfµḢḟ1ȯ1F

```

Try it online!

Quick and dirty. Very slow, even the `23!2!3!2!` test case is a stretch. I/O as lists of integers.

### Explanation

```
,!P€E    Helper link. Arguments: attempt, original
,        Make the array [attempt, original].
         Example: [[1,1,1,4], [2,3,2,0]]
 !       Take the factorial of each item.
         Example: [[1,1,1,24], [2,6,2,1]]
  P€     Take the product of each sublist.
         Example: [24, 24]
    E    Check if the values are equal.

SṗLçÐfµḢḟ1ȯ1F   Main link. Arguments: original
S               Find the sum S of the integers in the input.
  L             Find the number N of integers in the input.
 ṗ              Generate all lists containing N integers from 1 to S.
   çÐf          Take the lists whose factorial-product is the same as the original.
       Ḣ        Take the first match. This is the one with the most ones.
        ḟ1      Remove any ones.
          ȯ1    If there were only ones, return a one instead.
            F   Turn into a list if needed.

```
> 3 votes

# Answer
# Clean, ~~397~~ ... 317 bytes

```
import StdEnv,StdLib
c=length
f c m=sortBy c o flatten o map m
%n=f(>)@[2..n]
@1=[]
@n#f=[i\\i<-[2..n]|n/i*i==n&&and[i/j*j<i\\j<-[2..i-1]]]
=f++ @(n/prod f)
?l=group(f(>)%l)
$l=hd(f(\a b=c a<c b)(~(?l))[0..sum l])
~[]_=[[]]
~i n=[[m:k]\\m<-take n[hd(i!!0++[0])..],k<- ~[drop(c a)b\\a<-group(%m)&b<-i|b>a]n|i== ?[m:k]]

```

Try it online!

This takes an `[Int]`, determines the prime factors of the result, and reduces over the factors to find the smallest representation, using the largest factor at any stage as a baseline value for the next factorial term. It won't complete some test cases on TIO, but it is *fairly** fast, and can run them all in under 3 minutes on a midrange laptop.

* for an `O((prod(N)!)^sum(N))` complexity algorithm
> 2 votes

# Answer
# Ruby, ~~240 237~~ 233 bytes

This is incredibly inefficient

Accepts an array of ints as input

Returns a string and chooses the shortest option between, say, `'720!'`,`'6!!'` and `'3!!!'`

```
->i{f=->n{n>0?n*f[n-1]:1}
s=->a{eval a.map{|i|f[i]}*?*}
r=->e,a=[2]{e==s[a]?a:s[a]<=e&&(r[e,a[0..-2]+[a[-1]+1]]||r[e,a+[2]])}
j=->v{v.join(?!)+?!}
u=r[s[i]]
while j[g=u.map{|i|i&&r[i]?[r[i],p]:i}.flatten].size<j[u].size;u=g;end
j[u]}

```

Try it online!
> 1 votes

# Answer
# \>\<\>, 66 bytes

```
1}:?\~l1=?v{!
-:?!\:{*}1
v?( 4:{/}1<o"!"n-1
{:,} :{/?%}:+1
\:1-?n;

```

Try it online!

Not efficient, doesn't find the smallest string, and the interpreter doesn't deal very well with extremely large numbers. But at least I tried? Takes input as a list of numbers through the `-v` flag.

First it calculates the value of the input by factorialising each number and multiplying them together. Then it finds the largest factorial that divides cleanly into the total and outputs it. Repeat until it either gets a prime, (which it outputs) or a 1 and exits the program. Because of this, it sometimes doesn't find the shortest representation of the number, for example, the test case `7!2!2!7!2!2!2!2!` returns `10!224` instead of `8!8!` because it finds the total is divisible by 10! first.
> 1 votes

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