title: She sells sanctuary

text:
# Question
Title: She sells sanctuary
A huge storm is ravaging the world and as you and your family run away from it, you come across a gigantic shelter run by a girl. She tells you that "she sells sanctuary" and that different types of rooms are offered at different prices.

A room may only house one person.

# The challenge

Write a program which takes in two inputs: the number of people staying at the sanctuary and an array, map, object or string, whatever is convenient as long as the structure is similar to:

```
[[2, 3], [3, 5], [6, 7]]

```

In this case, it's a two dimensional array, but it could be a string, like

```
2,3 3,5 6,7

```

For each entry, the first item is the number of rooms offered for that type, and the second item is the cost of one room. For instance,

```
[[1, 2], [3, 4]]

```

means that one room is offered for the first type for 2 dollars each, and three rooms for the second type at 4 dollars each.

Since your family has limited resources, you would like to find the configuration for which as little money is spent as possible. So, your program should output a few numbers containing information about the number of rooms. At the end, it should also output the total cost.

This might all sound confusing, so take a sample input:

```
First input: 5
Second input: [[2, 5], [2, 3], [7, 100]]

```

The cheapest possible configuration is to have two people stay in the first type, costing `3 * 2 = 6` dollars, then two people in the second type for `5 * 2 = 10` dollars, and one person in the last type, for `100 * 1 = 100` dollars. The total cost is therefore `116` dollars. Your output for this test case would be

```
2 // two people in the first type of room
2 // two people in the second type of room
1 // one person in the third type of room
116 // total cost

```

Let us try another.

```
first input: 10
second input: [[1340993842, 5500], [1, 5000]]

```

The cheapest configuration is to have one person stay in the second type, and the other nine in the first type. The cost is therefore `9 * 5500 + 1 * 5000 = 54500`. Output:

```
9
1
54500

```

A few extra rules:

* The number of people staying will never be more than the total number of rooms.
* Standard loopholes are disallowed as usual.
* The last output must be the price.
* You may output as an array if you would like.
* Nobody else is staying in the sanctuary.
* Shortest answer in bytes wins because this question is .
* Input may be taken as rest parameters.
* Order may be reversed, so for example the price might be the first item. You must make it clear though.
* The rooms are **not** guaranteed to be ordered from cheapest to most expensive.
* Output must be in order of the types given

# Answer
# Wolfram Language (Mathematica), 42 bytes

```
Minimize[{#.x,Tr@x>#3},x∈Cuboid[0#,#2]]&

```

Try it online!

Input `[prices, availability, #people]`.

---

`Cuboid` represents a hyperrectangular region, given two opposite corners: \\$\texttt{Cuboid\[$(a\_1,...,a\_n)$,$(b\_1,...,b\_n)$\]}=\\{(x\_1,...,x\_n)\\;|\\;\forall i=1,...,n:a\_i\le x\_i\le b\_i\\}\\$.

`Minimize` finds the minimum value of the expression \\$\textit{prices}\cdot x\\$ (the total price) and the corresponding vector \\$x\\$, where we additionally have the restrictions \\$x\in\texttt{Cuboid\[$0$,$\textit{availability}$\]}\\$ and \\$\sum\_ix\_i=\textit{#people}\\$.

```
Minimize[           (* minimize *)
 {#.x,              (*  the total price, given *)
  Tr@x==#3},        (*  the total number of people *)
 x∈Cuboid[0#,#2]]   (* and the room availability *)

```

`>` saves one byte over `==` while still returning the same result (albeit with a warning).
> 9 votes

# Answer
# JavaScript (ES6), 104 bytes

*Saved 5 bytes thanks to @tsh*

Expects `(list)(n)`, where the list consists of `[available_i, price_i]` pairs.

Returns `[[booked_1, ..., booked_N], total_cost]`.

```
(p,o=p.map(_=>s=0))=>g=n=>n?g(n-1,p.find(([k,c],i)=>k*!p.some(([K,C])=>K&&C<c)&&++o[s+=c,i])[0]--):[o,s]

```

Try it online!

### Commented

```
( p,                        // outer function taking the list p[]
  o = p.map(_ => s = 0)     // o[] = booking array, initialize to 0's
                            // s = total cost
) =>                        //
g = n =>                    // g is a recursive function taking the number of people n
  n ?                       // if there's still at least one room to book:
    g(                      //   do a recursive call:
      n - 1,                //     decrement n
      p.find(([k, c], i) => //     look for a room [k, c] at position i:
        k *                 //       if it is still available
        !p.some(([K, C]) => //       and there is not another room type
          K && C < c        //       that is cheaper and still available
        ) &&                //       then:
          ++o[s += c, i]    //         increment o[i] (i.e. book a room with index i)
                            //         and add c to the total cost
      )                     //     end of find() (guaranteed to be successful)
      [0]--                 //     decrement the number of available rooms of this type
    )                       //   end of recursive call
  :                         // else:
    [o, s]                  //   stop the recursion and return the results

```
> 8 votes

# Answer
# , 95 bytes

```
function(n,l)list(rowSums(outer(l[2,],y<-sort(unlist(Map(rep,l[2,],l[1,])))[1:n],`==`)),sum(y))

```

Try it online!
> 5 votes

# Answer
# , 30 bytes

```
1 :'(](],1#.*)1#.]=/u{./:~@#)'

```

Try it online!

Solution is a J adverb which modifies the first input, takes a list of available rooms as the left arg, and a list of prices as the right arg. For example, the first test case is written like:

```
2 2 7 (5 f) 5 3 100

```

Note that the output is a J array, not space-separated standard output -- even though J displays arrays with only a space between elements.

## how

Using the above test case as an example...

* `/:~@#` Copy `#` the right arg elementwise using the left arg as a mask:

```
2 2 7 # 5 3 100
5 5 3 3 100 100 100 100 100 100 100

```

and sort `/:~`:

```
3 3 5 5 100 100 100 100 100 100 100

```
* `u{.` Take "first input" `u` elements from that:

```
3 3 5 5 100

```
* `]=/` Create a table showing where the prices `]` are equal to that:

```
0 0 1 1 0
1 1 0 0 0
0 0 0 0 1

```
* `1#.` Sum rows:

```
2 2 1

```
* `](...)` Taking the last result as the new right arg, and the prices `]` as the new left arg, apply the verb in parens...
* `],1#.*` Append to the new right arg `],` the sum of `1#.` the two args multiplied elementwise `*`:

```
2 2 1 116

```
> 3 votes

# Answer
# Excel, ~~200~~ 198 bytes

```
=LET(r,A2#,n,ROWS(r)+1,x,SEQUENCE(n),q,{1,2,3,4},s,SORT(IFS(q=3,x,x=n,0,1,r),2),c,INDEX(s,,1),m,A1-MMULT((x>TRANSPOSE(x))*1,c),y,IF(m<c,m,c),INDEX(SORT(IF(q=4,IF(x=1,SUM(y*INDEX(s,,2)),y),s),3),,4))

```
> 3 votes

# Answer
# Jelly, 17 bytes

```
Wẋ$Ṫ$€ẎṢḣµċⱮ³,SḢ$

```

A full program that accepts two arguments, the list of pairs of room price and associated availability, and the number of guests which prints a list containing a list of room allocations, in the same order as the input pairs, and the total price.

**Try it online!**

### How?

```
Wẋ$Ṫ$€ẎṢḣµċⱮ³,SḢ$ - Main Link: list of [price, available] pairs, R; guests, N
     €            - for each ([p,a] in R)
    $             -   last two links as a monad:
  $               -     last two links as a monad:
W                 -       wrap -> [[p,a]]
 ẋ                -       repeat -> [[[p,a],...p times],[[p,a],...a times]]
   Ṫ              -     tail -> [[p,a],...a times]
      Ẏ           - tighten from a list of list of pairs to a list of pairs
       Ṣ          - sort
        ḣ         - head (to N)
         µ        - start a new monadic chain, f(X=this list of [price, availability] pairs)
           Ɱ³     - for [p,a] in R:
          ċ       -   count occurrences of [p,a] in X
                    -> allocations
                $ - last two links as a monad:
              S   -   sum (e.g. [[1,4],[7,9]] -> [8,13])
               Ḣ  -   head -> total price
             ,    - pair (the allocations and total price)
                  - implicit print

```

---

Maybe `Wẋ$Ṫ$€ẎṢḣ©ċⱮ⁸®SḢ` is acceptable for 16 - It's all OK until you consider the output when *only a single* priced room type exists: since Jelly list representations of a single element display just that element, we find that, for example, `[[15,7]] 3` would print `345` (rather than `[3]45`). Note, however, that we do know that the leading digits of this output will be the number of guests, so it is "parseable".
> 3 votes

# Answer
# Python 3.8, 108 bytes

Input is a list of `[number, price]` pairs. The numbers of booked rooms are printed and the total price is returned.

```
f=lambda p,r:p and(print(w:=min((X:=r.pop(0))[0],max(0,p-sum(x for x,y in r if y<X[1]))))or w*X[1]+f(p-w,r))

```

Try it online!
> 2 votes

# Answer
# Clojure, ~~152~~ ~~145~~ ~~105~~ 98 bytes

```
#(let[x(take %2(for[[i j](sort %)k(repeat j i)]k))][(for[i %](count(keep #{(i 0)}x)))(apply + x)])

```

Try it online!

Takes input as the listing of rooms with price given first followed by the number of guests, outputs the results as a vector.

### Explanation

First, we `sort` the input vector, by default sort is performed by the first element, which is the price. Next, we "explode" the input using `repeat`, simulating the actual row of rooms sorted by price, and `take` the first N elements, where N is the number of guests:

```
[[5, 2], [3, 2], [100, 7]], 5 => 3 3 5 5 100 | 100 100 100 100 100 100

```

Then, we loop through the vector of rooms again, and `count` how many of each price do we have in the cheapest collection `x`. After the discussion with OP it was settled that the prices of different room types may not be the same, and therefore, price can be used as the room type ID.

Finally, we add the total sum of the prices to the output.
> 2 votes

# Answer
# Jelly, 21 bytes

```
Ṣẋ/€,€"ỤẎḣƓZðṪċⱮJ},§{

```

Try it online!

Takes the number of people from STDIN and a list of \[price, number\] from a command-line argument. Outputs \[counts, price\].

## Explanation

```
Ṣẋ/€,€"ỤẎḣƓZðṪċⱮJ},§{   Main monadic link
Ṣ                       Sort
 ẋ/€                    For each sublist, repeat the first item the second item number of times
    ,€"Ụ                Pair each number with the corresponding index in the original list
        Ẏ               Flatten by one level => [[price, index], ...]
         ḣƓ             Take the first [number on STDIN] items
           Z            Transpose => [prices, indices]
            ð           Remember this list
             Ṫ          Take the second item (the list of prices) and remove it from the list
              ċⱮJ}      Count the occurences of each index of the original list
                  ,§{   Pair with the sum of what remains of the remembered list

```
> 2 votes

# Answer
# JavaScript (ES6), 103 bytes

```
(n,i,t=0,p=[...i].sort((a,b)=>a[1]-b[1]).map(v=>v[0]<n?n-=v[0]:v[0]=n))=>[i.map(([x,y])=>(t+=x*y,x)),t]

```

Similar to the other JavaScript answer, it returns `[[booked_1, ..., booked_N], total_cost]`.

However, it's just a single function that expects `(n, list)` (where `list` is an array of arrays, e.g. `[[1,2],[3,4]]`, just like the examples provided).

Here's the idea:

```
(n,                             // the number of family members
 i,                             // a list of rooms, e.g. [[1,2],[3,4]]
 t=0,                           // initialize total cost
 p=[...i]                       // shallow copy array
     .sort((a,b)=>a[1]-b[1])    // sort the shallow copy
     .map(v=>                   // loop it
         v[0]<n                 // if there is more family members than rooms,
             ?n-=v[0]           // put as many as possible in this room
             :v[0]=n            // otherwise, put the remaining ones in it
         )
                                // we've now edited the elements of the original array
                                // so the first number is the amount of people staying
                                // in that room, not the amount of rooms of that type
                                // that are available

)=>[                            // return an array
    i.map(([x,y])=>(            // loop the list of rooms
        t+=x*y,                 // add the cost to t
        x                       // return the number of people staying in the room
        )
    ),
t]                              // finally, the total cost as last element of array

```
> 2 votes

# Answer
# Java, ~~156~~ 152 bytes

```
r->p->{int l=r.length,o[]=new int[l+1],i,j;for(;p-->0;--r[j][0],++o[j],o[l]+=r[j][1])for(i=j=-1;++i<l;)j=r[i][0]>0&(j<0||r[i][1]<r[j][1])?i:j;return o;}

```

Try it online!

*Saved 4 bytes thanks to ceilingcat*
> 1 votes

# Answer
# Charcoal, 29 bytes

```
ＵＭη⊞ＯικＦθ⊞υ§⌊Φη⁻§κ¹№υλ²ＩＥη№υκ

```

Try it online! Input is the number of people and a list of \[price, count\] pairs, and output is a list of counts in the same order. Explanation:

```
ＵＭη⊞Ｏικ

```

Push the index to each pair, so they are now \[price, count, index\].

```
Ｆθ

```

Repeat for each person.

```
⊞υ§⌊Φη⁻§κ¹№υλ²

```

Filter out the prices of the counts that have been used up, find the minimum, and push the original index to the list of persons.

```
ＩＥη№υκ

```

Print the number of persons allotted to each type.
> 1 votes

# Answer
# 05AB1E, 21 bytes

```
ε`и}{˜I£©¹€нsk{γ€g®Oª

```

First input as a list of pairs \\$\[price, amount\]\\$. Output as an array (with the last item being the total price).

Try it online or verify all test cases.

**Explanation:**

```
ε             # Map over each pair in the first (implicit) input-list:
 `            #  Pop and push both values separated to the stack
  и           #  Repeat the first item the second item amount of times as list
}{            # After the map: sort the list based on their first items
  ˜           # Then flatten the list of lists
   I£         # Only leave the second input amount of leading values
     ©        # Store this list in variable `®` (without popping)
¹             # Push the first list of pairs again
 €н           # Only leave the first item (the price) of each pair
   s          # Swap so list `®` is at the top of the stack
    k         # Get for each the index in the list of prices
     {        # Sort these indices from lowest to highest
      γ       # Split it into groups of equivalent adjacent values
       €g     # Get the length of each group
         ®    # Push list `®` again
          O   # Pop and push its sum
           ª  # Append it to the list of lengths
              # (after which the result is output implicitly)

```
> 0 votes

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


title: Sociable sequences

text:
# Question
Title: Sociable sequences
Sociable numbers are a generalisation of both perfect and amicable numbers. They are numbers whose proper divisor sums form cycles beginning and ending at the same number. A number is \\$n\\$-sociable if the cycle it forms has \\$n\\$ unique elements. For example, perfect numbers are \\$1\\$-sociable (\\$6\to6\to\cdots\\$) and amicable numbers are \\$2\\$-sociable (\\$220\to284\to220\to\cdots\\$).

Note that the *entire* cycle must begin and end with the same number. \\$25\\$ for example is not a \\$1\\$-sociable number as it's cycle is \\$25 \to 6 \to 6 \to \cdots\\$, which, despite containing a period \\$1\\$ cycle, does not begin and end with that cycle.

The proper divisor sum of an integer \\$x\\$ is the sum of the positive integers that divide \\$x\\$, not including \\$x\\$ itself. For example, the proper divisor sum of \\$24\\$ is \\$1 + 2 + 3 + 4 + 6 + 8 + 12 = 36\\$

There are currently \\$51\\$ known \\$1\\$-sociable numbers, \\$1225736919\\$ known \\$2\\$-sociable pairs, no known \\$3\\$-sociable sequences, \\$5398\\$ known \\$4\\$-sociable sequences and so on.

You may choose whether to:

* Take a positive integer \\$n\\$, and a positive integer \\$m\\$ and output the \\$m\\$th \\$n\\$-sociable sequence
* Take a positive integer \\$n\\$, and a positive integer \\$m\\$ and output the first \\$m\\$ \\$n\\$-sociable sequences
* Take a positive integer \\$n\\$ and output all \\$n\\$-sociable sequences

If you choose either of the last 2, each sequence must have internal separators (e.g. `220, 284` for \\$n = 2\\$) and distinct, external separators between sequences (e.g. `[220, 284], [1184, 1210]` for \\$n = 2\\$). For either of the first 2, the sequences should be ordered lexicographically.

You can choose whether to include "duplicate" sequences, i.e. the sequences that are the same as others, just beginning with a different number, such as including both `220, 284` and `284, 220`. Please state in your answer if you do this.

The Catalan-Dickson conjecture states that every sequence formed by repeatedly taking the proper divisor sum eventually converges. Your answer may assume this conjecture to be true (meaning that you are allowed to iterate through each integer, testing if it is \\$n\\$-sociable by calculating if it belongs to an \\$n\\$-cycle, even though such approaches would fail for e.g. \\$276\\$ if the conjecture is false).

You may also assume that for a given \\$n\\$, there exists an infinite number of \\$n\\$-sociable sequences.

This is so the shortest code in bytes wins

## Test cases

```
n -> n-sociable sequences
1 -> 6, 28, 496, 8128, ...
2 -> [220, 284], [284, 220], [1184, 1210], [1210, 1184], [2620, 2924], [2924, 2620], [5020, 5564], [5564, 5020], [6232, 6368], [6368, 6232], ...
4 -> [1264460, 1547860, 1727636, 1305184], ...
5 -> [12496, 14288, 15472, 14536, 14264], [14264, 12496, 14288, 15472, 14536], ...
6 -> [21548919483, 23625285957, 24825443643, 26762383557, 25958284443, 23816997477], ...
8 -> [1095447416, 1259477224, 1156962296, 1330251784, 1221976136, 1127671864, 1245926216, 1213138984], ...
9 -> [805984760, 1268997640, 1803863720, 2308845400, 3059220620, 3367978564, 2525983930, 2301481286, 1611969514], ...

```

# Answer
> 6 votes
# Brachylog, 18 bytes

Generates the sequences with duplicates.

```
;X{≠tℕfk+}ᵃ⁽At~hAk

```

Try it online!

### How it works

```
;X{≠tℕfk+}ᵃ⁽At~hAk  implicit input n
;X                  [n, something]
  {      }ᵃ⁽        starting with [something], generate a list
                      by applying {…} n times:
   ≠                 all elements are different
    t                the last element
     ℕ               is a natural number
      f              and its factors
       k             without itself
        +            summed
                    -> [220, 284, 220]
            A       is A
             t      A's tail
              ~h    is the head
                A   of A
                 k  output A without the last element

```

# Answer
> 5 votes
# Ruby, ~~86~~ ~~84~~ 78 bytes

```
->n{1.step{|x,*a|x==(n.times{a|=[x=(1...x).sum{|i|x%i>0?0:i}]};a[n-1])&&p(a)}}

```

Try it online!

Prints the sequence for a given \\$n\\$ infinitely.

6 bytes saved by G B.

# Answer
> 4 votes
# Wolfram Language (Mathematica), 69 bytes

Takes a positive integer n and outputs all n-sociable sequences

```
Do[NestList[Tr@Divisors@#-#&,d,#]/.{a__,d}/;0!=a:>Print@{a},{d,∞}]&

```

Try it online!

-20 bytes thanks to @att

# Answer
> 4 votes
# JavaScript (V8),  ~~106 97~~  96 bytes

*Saved 1 byte thanks to @tsh*

A function that takes \\$n\\$ and prints the sequence forever, including duplicates.

```
n=>{for(k=0;a=[];)(g=j=>{for(s=d=0;++d<j;s+=j%d?0:d);a.push(s)<n?s-k&&g(s):s-k||print(a)})(++k)}

```

Try it online!

### Commented

```
n => {                     // n = input
  for(                     // main infinite loop:
    k = 0;                 //   start with k = 0
    a = [];                //   a[] = sequence of proper divisor sums
  ) (                      //
    g = j => {             //   g is a recursive function that takes an integer j,
                           //   fills the sequence a[] and prints it if valid
      for(                 //     loop:
        s =                //       s is the proper divisor sum
        d = 0;             //       d is the current divisor
        ++d < j;           //       increment d; stop when it's equal to j
        s += j % d ? 0 : d //       add d to s if d is a divisor of j
      );                   //     end of loop
      a.push(s)            //     push s into a[]
      < n ?                //     if there are less than n elements:
        s - k && g(s)      //       if s != k, do a recursive call with j = s
      :                    //     else:
        s - k || print(a)  //       if s = k, print a[]
    }                      //   end of g
  )(++k)                   //   initial call to g with j = k incremented
}                          // end of loop / end of function

```

# Answer
> 4 votes
# Haskell, ~~126~~ 115 bytes

```
import Data.List
f m=[init r|r@(h:t)<-[scanl(\a x->sum[d|d<-[1..a-1],a`mod`d<1])y[1..m]|y<-[1..]],h==r!!m,t==nub t]

```

Try it online!

* saved 10 thanks to @benrg

# Answer
> 3 votes
# , 75 73 67 bytes

```
(>:@][[echo@}:^:((~.-:}:)*{.={:)@]1&((,i.@{:(1#.[#~0=|){:)@]))^:_&1

```

Try it online!

Prints infinitely.

Note: TIO has +3 in the byte count because I changed infinite `_` iteration to 9999 times.

# Answer
> 3 votes
# Husk, 18 bytes

```
m₁fo=⁰S€₁N
Ut¡ȯΣhḊ

```

Outputs all n-sociable sequences (including duplicates beginning with different numbers).

Don't try it online!: Assumes Catalan-Dixon conjecture: calculates cycle for *every* integer befpre choosing which ones to output. So, the example on TIO stalls.
Try this for a (6-byte longer) version that restricts calculations up to a cycle-length of 10 (`↑10`), and only outputs sequences arising from integers up to 500 (`ḣ500` instead of `N`).

**Explanation:**

```
Ut¡ȯΣhḊ         # helper function ₁:
                # calculate cycle for input integer x
U               # longest unique prefix of list
 t              # (without first element)
  ¡ȯ            # from repeatedly applying 3 functions:
    Σ           # sum of
      Ḋ         # divisors
     h          # without the last one
                # to the input argument

m₁fo=⁰S€₁N      # main program:
m₁              # apply helper function ₁ to each of
         N      # all integers x
  fo            # filtered to include only those for which
      S€₁       # the position of x in
                # the results of applying helper function ₁ to x
    =⁰          # is equal to the input argument

```

# Answer
> 2 votes
# Scala, ~~114~~ ~~109~~ 119 bytes

+10 bytes to fix a mistake, indirectly pointed out by AZTECCO.

```
n=>for(k<-Stream from 2;s=Seq.iterate(k,n+1)(x=>1.to(x-1).filter(x%_<1).sum).tail.distinct if s.indexOf(k)>n-2)yield s

```

Try it in Scastie!

An infinite `Stream` that can also be treated as a function that returns the mth sequence. Uses `tail` instead of `init` like the previous one, so the sequences are `[284, 220]`, `[220, 284]`, `[1210, 1184]` (first element removed).

Using `>n-2`, as in Arnauld's answer, instead of `==n-1`, saves a byte.

```
n =>
  for(
    k <- Stream from 2         //For every integer k ≥ 2
    s = Seq.iterate(k, n + 1)( //Build first n+1 terms of the sequence by repeatedly applying:
      x =>                     //Function for proper divisor sum
        1.to(x - 1)            //Range of possible proper divisors
         .filter(x % _ < 1)    //Keep only divisors
         .sum                  //Sum them
    ).tail                     //Drop the first element (always k)
    if s.indexOf(k) > n - 2    //Make sure k appears at the end of the cycle (and only there)
  ) yield s                    //Yield the sequence (without k at the start)

```

# Answer
> 2 votes
# Charcoal, 53 bytes

```
Ｎθ≔⁰ζＦＮ«≔⟦⟧υＷ⁻θ⊕⌕υζ«≦⊕ζ≔ζη≔⟦⟧υＦθ«≔↨Φη∧μ¬﹪ημ¹η⊞υη»»»Ｉυ

```

Try it online! Link is to verbose version of code. Takes `n` and `m` as inputs and outputs the `m`th sequence, in order of last element of the cycle, including duplicate sequences. Very slow so in practice you need `n<3`. Explanation:

```
Ｎθ

```

Input `n`.

```
≔⁰ζ

```

Start at zero.

```
ＦＮ«

```

Repeat `m` times.

```
≔⟦⟧υ

```

Clear any previous calculation.

```
Ｗ⁻θ⊕⌕υζ«

```

Repeat until a perfect `n`-cycle is found.

```
≦⊕ζ

```

Increment the test number.

```
≔ζη

```

Make a copy of the number.

```
≔⟦⟧υ

```

Start building a list of divisor sums.

```
Ｆθ«

```

Repeat `n` times.

```
≔↨Φη∧μ¬﹪ημ¹η

```

Calculate the next divisor sum.

```
⊞υη

```

Save it to the list.

```
»»»Ｉυ

```

Output the collected divisor sums, including the copy of the original counter as the last element of this list.

# Answer
> 1 votes
# JavaScript (V8), 104 bytes

```
n=>{for(i=1;s=++i;)for(o=[];o.push(v=s)<=n;new Set(o).size-n|s-i||print(o))for(j=s=0;++j<v;s+=v%j?0:j);}

```

Try it online!

# Answer
> 1 votes
# , 105 bytes

```
function(n)repeat{y=v=T=T+1;w=n;while({z=1:y;y=sum(z[!y%%z])-y}!=T&(w=w-1)&y)v=c(v,y);if(!w&y==T)show(v)}

```

Try it online!

Outputs n-sociable sequences indefinitely.

# Answer
> 1 votes
# 05AB1E, 18 bytes

```
∞εIFDÑ¨O})}ʒćQJ}€¨

```

Outputs the infinite sequence including "duplicates".

Try it online.

If we're allowed to output every inner list one size to large (i.e. `[6,6]` instead of `[6]` for \\$n=1\\$; `[220,284,220]` instead of `[220,284]` for \\$n=2\\$, etc.) we could omit the last three bytes:
try it online.

**Explanation:**

```
∞         # Push the infinite positive sequence: [1,2,3,...]
 ε        # Map each to:
  IF      #  Loop the input amount of times:
    D     #   Duplicate the current integer
     Ñ    #   Get its divisors (including itself)
      ¨   #   Remove the last item (itself)
       O  #   Take the sum of those divisors
   })     #  After the loop: wrap all values into a list
 }ʒ       # After the map: filter the list of lists by:
   ć      #  Extract head; pop and push remainder-list and first item separated
    Q     #  Check for each value in the remainder-list if it's equal to this head
     J    #  Join those checks together to a string
          #  (only 1 is truthy in 05AB1E, including something like "00001";
          #   so in the filter we basically check if the first item is equal to the last
          #   item and NONE of the other items)
  }€      # After the filter: map over each remaining inner list
    ¨     #  And remove the final duplicated item

```

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


title: Self-Replicating Numbers

text:
# Question
Title: Self-Replicating Numbers
## Background

For the purpose of this challenge, all numbers and their string representations are assumed to be in *decimal* (base 10). I tried to find proper terminology for this challenge, but I do not think there is any, so I made it up.

A self-replicating number is a number that appears as a substring in any of its multiples up to and including its square, excluding itself. An \\$n\\$-order self-replicating number appears as a substring in ***exactly \\$n\\$*** multiples of itself up to its square, including itself. All numbers are *at least* 1st-order self-replicating numbers, because they appear as a substring in their first multiple (1 times the number).

For example: 5 is a 3rd-order self-replicating number, because it appears 3 times in the multiples of itself up to its square: **5**, 10, 1**5**, 20, 2**5**. On the other hand, 4 is a 1st-order self-replicating number, because it appears only once: **4**, 8, 12, 16.

There are only 6 1st-order replicators, because numbers will always have a self-replicator order \\$\geq\lfloor\log\_{10}(x)\rfloor+1\\$, where \\$x\\$ is the number, as multiples of the number and any power of ten are guaranteed to have the number as a substring. Because of this property of self-replicating numbers, the series of \\$n\\$-order self-replicating numbers cannot ever be an infinite series. The last possible \\$n\\$-order self-replicating number is \\$10^n-1\\$.

## The Challenge

Your task is to write a program which takes two integers, \\$m\\$ and \\$n\\$, and does one of the following:

* return the first \\$m\\$ \\$n\\$-order self-replicating numbers **\\$or\\$**
* return the \\$m^{th}\\$ \\$n\\$-order self-replicating number (0 or 1-indexed, your choice) **\\$or\\$**
* output the series of numbers that are either \\$m\\$-order or \\$n\\$-order self-replicating numbers. You may treat this series as if it were infinite; in other words, your code is not required to halt - it'd be very cool if it did, though. **\\$or\\$**
* By popular demand, and because the previous option was a source of valid misinterpretation, you may now instead take a single integer, \\$n\\$, and output the series of \\$n\\$-order self-replicating numbers. As with the last option, you may treat the series as if it were infinite.

## Rules

* You are allowed undefined behavior for values of \\$m\leq0\\$ or \\$n\leq0\\$.
* Your code is not required to halt if the next number in the sequence does not exist. For example: if you chose either of the first two output options and your code receives \\$m=7, n=1\\$ as input, a 7th 1st-order self-replicating number will never be found because no 1st-order self-replicating numbers higher than 9 exist.
* Standard loopholes forbidden.
* This is , shortest program in bytes for each language wins.

## Test Cases

| \\$m\\$ | \\$n\\$ | Output |
| --- | --- | --- |
| 5 | 0 | undefined |
| 6 | 1 | 1,2,3,4,7,9 |
| 7 | 1 | 1,2,3,4,7,9 **\\$or\\$** undefined |
| 20 | 2 | 6,8,10,11,12,13,14,15,16,17,18,19,21,22,23,24,26,27,29,31 |
| 30 | 4 | 30,45,48,52,55,59,68,69,82,94,110,115,122,128,130,136,137,139,144,145,152,168,170,171,176,177,184,187,190,192 |
| 10 | 38 | 650,3520,3680,3920,6050,6350,6840,7640,7880,7960 |
| 3 | 101 | 7125,8900,9920 |
| 1 | 2778 | 5000 |

# Answer
# Jelly, 11 bytes

```
1ẇⱮ×R$SƊ=¥#

```

Try it online!

Takes \\$n\\$ then \\$m\\$ on the command line and outputs the first \\$m\\$ \\$n\\$-order self-replicating numbers

## How it works

```
1ẇⱮ×R$SƊ=¥# - Main link. Takes n on the left
         ¥  - Group the previous 2 links into a dyad f(k, n):
       Ɗ    -   Group the previous 3 links into a monad on k:
     $      -     Group the previous 2 links into a monad on k:
    R       -       Yield the range [1, 2, ..., k]
   ×        -       Multiply each element by k
  Ɱ         -     For each element i in [k, 2k, ..., k²]:
 ẇ          -       Is k a substring of i?
      S     -     Sum; Count the 1s
        =   -   Does this equal n?
1         # - Count up k = 1, 2, 3, ... until m such k return true under f(k, n)

```
> 7 votes

# Answer
# JavaScript (V8),  ~~76 67~~  66 bytes

*Saved 1 byte thanks to @user81655*

A function expecting \\$n\\$ and printing the \\$n\\$-order self-replicating numbers forever.

```
n=>{for(m=0;k=++m;s||print(m))for(s=n;k;)s-=!!(k--*m+'').match(m)}

```

Try it online!

### Commented

```
n => {                   // n = input
  for(                   // infinite outer loop:
    m = 0;               //   start with m = 0
    k = ++m;             //   before each iteration, increment m and copy it in k
                         //   (always truthy, so we never exit the loop)
    s || print(m)        //   after each iteration, print m if s = 0
  )                      //
    for(                 //   inner loop:
      s = n;             //     start with s = n
      k;                 //     stop when k = 0
    )                    //
      s -=               //     decrement s if ...
        !!(k-- * m + '') //       ... k * m coerced to a string
        .match(m)        //       contains m (decrement k afterwards)
}                        // end

```
> 7 votes

# Answer
# , ~~58~~ 55 bytes

-3 bytes thanks to Dominic van Essen

```
n=scan();repeat if(sum(grepl(F,(F=F+1)*1:F))==n)show(F)

```

Try it online!

Prints all the \\$n\\$-order self-replicating numbers.
> 6 votes

# Answer
# , 47 bytes

```
(>:@][echo@]^:(e.~1#.1*@#.]E.&":"0]+]*i.))^:_&1

```

Try it online!

Third option for output.

TIO has +2 since I changed infinity `_` to 651 to make it clear that it works.
> 5 votes

# Answer
# Brachylog, 17 bytes

Generates the sequence for a given \\$n\\$.

```
≤≜.{≥.;?×s?∧≜}ᶜ?∧

```

Try it online!

```
≤≜.{≥.;?×s?∧≜}ᶜ?∧
≤≜                 a number k greater-equal than n
  .                is the output
   {         }ᶜ    count the outputs of the predicate,
               ?   unify with n
                ∧  return the output

    ≥              a number less-equal than k
     .             is the output
      ;?×          multiplied by k
         s?        has k as substring
           ∧≜      return the output

```
> 5 votes

# Answer
# Charcoal, 19 bytes

```
ＩΦＸχ⌈θ№θＬΦι№Ｉ×ι⊕λＩι

```

Try it online! Link is to verbose version of code. Takes a pair (actually any list) of integers `[n, m]` as input and outputs all self-replicating numbers of those order(s), but somewhat slow so avoid using it at all really. Explanation:

```
   χ                Predefined variable 10
  Ｘ                 Raised to power
     θ              Input integers
    ⌈               Maximum
 Φ                  Filter implicit range where
       θ            Input integers
      №             Contains
        Ｌ           Length of
          ι         Current value
         Φ          Filter implicit range where
              ι     Outer value
             ×      Multiplied by
                λ   Inner index
               ⊕    Incremented
            Ｉ       Cast to string
           №        Contains
                  ι Outer value
                 Ｉ  Cast to string
Ｉ                   Cast to string
                    Implicitly print

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 81 bytes

outputs the series of n-order self-replicating numbers forever

```
Do[Tr@Boole@StringContainsQ[(T=ToString)/@Array[m#&,m],T@m]==#&&Print@m,{m,∞}]&

```

Try it online!
> 3 votes

# Answer
# Python 2, 72 bytes

```
def f(n,i=1):
 if sum(`i`in`i*~k`for k in range(i))==n:print i
 f(n,i+1)

```

Try it online!

Trivial answer that loops through the numbers in order and checks if they are self-replicating.

-8 bytes thanks to *dingledooper*
> 2 votes

# Answer
# PowerShell, 99 bytes

```
param($n)for($x=1;;++$x){$o=0;for($i=$x;$i-le($x*$x);$i+=$x){$o+=("$i"-match"$x")};if($o-eq$n){$x}}

```

Try it online!

A script expecting \\$n\\$ and printing the first \\$n\\$-order self-replicating numbers forever.
> 2 votes

# Answer
# PowerShell, 77 bytes

```
param($m,$n)for(;$n*($m-=$z)){,++$i*($z=(1..$i|?{$i*$_-match$i}).Count-eq$n)}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 10 bytes

```
∞ʒL¤*¬δåOQ

```

Uses the last option: given an integer \\$n\\$, outputs the infinite (non-halting) sequence of \\$n\\$-order self-replicating numbers.

Try it online or verify for the first `n=[0,20]` inputs all output-values below 1000.

**Explanation:**

```
∞           # Push an infinite list of positive integers: [1,2,3,...]
 ʒ          # Filter each integer `y` by:
  L         #  Push a list in the range [1,y]
   y*       #  Multiply each by `y`
      δ     #  Map over each value in this list:
     y å    #   Check if it contains `y` as substring
        O   #  Sum this list together to get the amount of truthy values
         Q  #  And check if this is equal to the (implicit) input-integer `n`
            # (after which the filtered infinite list is output implicitly as result)

```
> 2 votes

# Answer
# Japt, 18 bytes

```
Èõ*X è_s øXÃ¥V}jU1

```

Try it

* we could save a byte by returning nth term 0 indexed just by using `iU` instead of `jU1` but this way is more easy to validate output.

```
    È ...}jU1 - first n terms
    õ*X       - multiples to X^2
    è .. ¥V   - number of multiples returning true to _ 'function (Z)'== second input?
    _s øXÃ    - convert to string and check if contains X

```
> 1 votes

# Answer
# Scala, 67 bytes

```
n=>Stream.from(1)filter(x=>x.to(x*x,x).count(_+""contains ""+x)==n)

```

Try it in Scastie! (ignore the deprecation warnings)
> 1 votes

# Answer
# APL(Dyalog Unicode), 27 bytes SBCS

```
{⍸⍵=(1⊥⊢(1∊⍷⍥⍕)¨⊢×⍳)¨⍳10*⍵}

```

Try it on APLgolf!

A dfn submission which takes \\$n\\$ and prints all self-replicating numbers of order \\$n\\$ and terminates.

**Commented:**

```
{⍸⍵=(...)¨⍳10*⍵}   ⍝ dfn which takes n as a right argument and returns all nth-order self-replicating numbers
          ⍳10*⍵    ⍝ the indices from 1 to 10^n
    (...)¨         ⍝ for each number, calculate the order of self-replication
  ⍵=               ⍝ is this order equal to n?
 ⍸                 ⍝ the indices of all 1's

(1⊥⊢(1∊⍷⍥⍕)¨⊢×⍳)   ⍝ train that takes a number k as a right argument and returns the order
            ⊢×⍳    ⍝ k × (1 2 ... k) = (k×1 k×2 ... k×k)
   ⊢( ... )¨       ⍝ for each value as a right argument and k as a left argument:
     1∊⍷           ⍝ is the left argument is a substring of the right after ...
        ⍥⍕         ⍝ ... both are formatted as a string
 1⊥                ⍝ sum all results

```
> 1 votes

# Answer
# Python 3, ~~160~~ 154 bytes

```
def am(m,n):
 k=lambda n:[i*n for i in range(1,n+1)if str(n)in str(i*n)];l=[];i=1
 while len(l)<m:
  q=k(i)
  if len(q)==n:l.append(q[0])
  i+=1
 return l

```

Try it online!
> 1 votes

# Answer
# Kotlin, 96 bytes

```
fun f(n:Int)=generateSequence(1){it+1}.filter{x->(x..x*x step x).count{"$it".contains("$x")}==n}

```

Try it online!

Returns the sequence of all \\$n\\$-order self-replicating numbers
> 0 votes

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


title: Generalised Fortunate Prime Sequences

text:
# Question
Title: Generalised Fortunate Prime Sequences
The primorial \\$p\_n\\#\\$ is the product of the first \\$n\\$ primes. The sequence begins \\$2, 6, 30, 210, 2310\\$.

A Fortunate number, \\$F\_n\\$, is the smallest integer \\$m \> 1\\$ such that \\$p\_n\\# + m\\$ is prime. For example \\$F\_7 = 19\\$ as:

$$p\_7\\# = 2\times3\times5\times7\times11\times13\times17 = 510510$$

Adding each number between \\$2\\$ and \\$18\\$ to \\$510510\\$ all yield composite numbers. However, \\$510510 + 19 = 510529\\$ which is prime.

Let us generalise this to integer sequences beyond primes however. Let \\$\Pi(S,n)\\$ represent the product of the first \\$n\\$ elements of some infinite sequence \\$S\\$. All elements of \\$S\\$ are natural numbers (not including zero) and no element is repeated. \\$S\\$ is guaranteed to be strictly increasing.

In this case, \\$p\_n\\# = \Pi(\mathbb P,n)\\$. We can then define a new type of numbers, generalised Fortunate numbers, \\$F(S,n)\\$ as the smallest integer \\$m \> 1\\$ such that \\$\Pi(S,n) + m \in S\\$.

You are to take an integer \\$n\\$ and an infinite sequence of positive integers \\$S\\$ and output \\$F(S,n)\\$.

You may take input in any reasonable representation of an infinite sequence. That includes, but is not limited to:

* An infinite list, if your language is capable of handling those (e.g. Haskell)
* A black box function which returns the next element of the sequence each time it is queried
* A black box function which returns two distinct values to indict whether it's argument is a member of that sequence or not
* A black box function which takes an integer \\$x\\$ and returns the \\$x\\$th element of the sequence

If you have another method you are considering using, please ask in the comments about it's validity.

This is so the shortest code in bytes wins

## Examples

I'll walk through a couple of examples, then present a list of test cases below.

**\\$n = 5, S = \\{1, 2, 6, 24, 120, ...\\}\\$**

Here, \\$S\\$ is the factorials from 1. First, \\$\Pi(S, 5) = 1\times2\times6\times24\times120 = 34560\\$. We then find the next factorial greater than \\$34560\\$, which is \\$8! = 40320\\$ and subtract the two to get \\$m = 40320 - 34560 = 5760\\$.

**\\$n = 3, S = \\{6, 28, 496, 8128, ...\\}\\$**

Here, \\$S\\$ is the set of perfect numbers. First, \\$\Pi(S, 3) = 6\times28\times496 = 83328\\$. The next perfect number is \\$33550336\\$, so \\$m = 33550336 - 83328 = 33467008\\$

## Test cases

```
n
S
F(S, n)

5
{1,2,6,24,120,...} (factorials)
5760

3
{6,28,496,8128,...} (perfect numbers)
33467008

7
{2,3,5,7,11,...} (prime numbers)
19

5
{1,3,6,10,15,...} (triangular numbers)
75

Any n
{1,2,3,4,...} (positive integers)
2

9
{1,4,9,16,25,...} (squares)
725761

13
{4,6,9,10,14,...} (semiprimes)
23

```

# Answer
# Husk, 8 bytes

```
ḟ>1M<¹Π↑

```

Try it online! (Missing the testcase for perfect numbers because it was too slow, and the one for semiprimes because implementing the list of semiprimes is a challenge itself)

Takes as input `S` and `n`, where `S` is an infinite list.

### Explanation

```
ḟ>1M<¹Π↑
       ↑     Take the first n elements from S
      Π       and get their product
   M ¹       For each element x in S
    <         subtract the product if it is smaller than x, return 0 if it is bigger
ḟ            Find the first element in this list
 >1           that is greater than 1

```
> 6 votes

# Answer
## JavaScript (V8), 70 bytes

```
n=>s=>{p=[...Array(n)].reduce(a=>a*s(),1);while((x=s()-p)<1);return x}

```

Can't access TIO on my school network. I'll post a link soon!
> 2 votes

# Answer
# Scala, 83 bytes

```
s=>n=>{val p=s.take(n).product;Stream.from(2)find(m=>s takeWhile(p+m>=_)toSet p+m)}

```

Try it in Scastie!

Takes an infinite `LazyList`.

If outputting the product + m had been allowed, I could've used a few evil syntax-bending tricks for 71 bytes, but this is a lot more boring.

```
s=>Stream.from(2)map s.take(_).product.+find(? =>s takeWhile?.>=toSet?)

```

Try it in Scastie!
> 2 votes

# Answer
# JavaScript (Node.js), 47 bytes

```
(S,x=1)=>f=n=>n?f(n-1,x*=S()):(t=S()-x)>0?t:f()

```

Try it online!

# JavaScript (Node.js), 51 bytes non-recursive

```
S=>n=>{for(x=1;e=S(),e<=(x*=n--<1||e););return e-x}

```

Try it online!
> 2 votes

# Answer
# Clojure, 58 bytes

```
#(nth(for[i % j[(- i(apply *(take %2%)))]:when(< 1 j)]j)0)

```

Try it online!

Takes input as a lazy sequence and a number \\$n\\$.
> 2 votes

# Answer
# , 36 bytes

```
1 :'([(-~u)>:@]^:(>:u)^:_)~[:*/u@i.'

```

Try it online!

This is an adverb modifying the sequence generator, which is assumed to be 0-indexed and which returns the nth element.

It just increments the input n until f(n) \> relevant product to find the number to subtract from.
> 1 votes

# Answer
# 05AB1E, 7 bytes

```
£P-.Δ1›

```

First input is \\$n\\$, second input is an infinite sequence \\$S\\$.

Verify all test cases or try it online with 05AB1E code as additional input to generate the infinite sequence. (The perfect numbers and semiprimes test cases have been lowered to \\$n=2\\$ and \\$n=4\\$ respectively, because they time out for \\$n=3\\$ and \\$n=13\\$ on TIO.)

**Explanation:**

```
£        # Leave the first (implicit) input `n` amount of leading items from the second
         # infinite input-list `S`
 P       # Take the product of these first `n` values
  -      # Subtract it from each item in the second infinite input-list `S`
   .Δ    # Pop and leave the first value which is truthy for:
     1›  #  Check that it's larger than 1
         # (after which the result is output implicitly)

```
> 1 votes

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


title: Golf Dennis a thermometer

text:
# Question
Title: Golf Dennis a thermometer
Dennis puts in a huge amount of effort for this community, including as moderator, language designer, and provider of TIO.

Unfortunately, his four-year-old daughter has caught a cold, so let us all help him keep track of her recovery (may it be speedy) by providing him with a thermometer:

```
.-----------.
|           |
|           |
'-.       .-'
.-'   -   '-.
|107.6- 42.0|
|106.7- 41.5|
|105.8- 41.0|
|104.9- 40.5|
|104.0- 40.0|
|103.1- 39.5|
|102.2- 39.0|
|101.3- 38.5|
|100.4- 38.0|
| 99.5- 37.5|
| 98.6- 37.0|
| 97.7- 36.5|
| 96.8- 36.0|
| 95.9- 35.5|
| 95.0- 35.0|
'---. - .---'
    | - |
    |---|
    |   |
    '---'

```

Since Dennis does not have much time to read code, you must keep yours as short as possible.

# Answer
> 16 votes
# Jelly, ~~90 89 84 83~~ 82 bytes

-1 byte thanks to Erik the Outgolfer (replace `10` with )

```
15r1×€9,5+“£Ȧ“¡^’d⁵Dj€€”.j€⁾- Uz⁶ZUj@€⁾||
“¡ẹƭgụḌẊṘgYƊxyẓṡƝçƤ5ȥṭ’ṃ“.| '-”s7ŒBs5j¢Y

```

**Try it online!**

### How?

```
15r1×€9,5+“£Ȧ“¡^’d⁵Dj€€”.j€⁾- Uz⁶ZUj@€⁾|| - Link 1, body: no arguments
15r1                                      - inclusive range(15,1)      = [15,14,...,2,1]
      9,5                                 - pair nine with five        = [9,5]
    ×€                                    - multiply for €ach          = [[135,75],[126,70],...,[18,10],[9,5]]
          “£Ȧ“¡^’                         - list of base 250 numbers   = [941,345]
         +                                - addition                   = [[1076,420],[1067,415],...,[959,355],[950,350]]
                 d⁵                       - div&mod 10                 = [[[107,6],[42,0]],[[106,7],[41,5]],...,[[95,9],[35,5]],[[95,0],[35,0]]]
                   D                      - convert to decimal lists   = [[[[1,0,7],6],[[4,2],0]],[[[1,0,6],7],[[4,1],5]],...,[[[9,5],9],[[3,5],5]],[[[9,5],0],[[3,5],0]]]
                       ”.                 - literal '.'
                    j€€                   - join €ach for €ach         = [[[1,0,7,'.',6],[4,2,'.',0]],[[1,0,6,'.',7],[4,1,'.',5]],...,[[9,5,'.',9],[3,5,'.',5]],[[9,5,'.',0],[3,5,'.',0]]]
                           ⁾- <space      - literal ['-',' ']
                         j€               - join €ach                  = [[1,0,7,'.',6,'-',' ',4,2,'.',0],[1,0,6,'.',7,'-',' ',4,1,'.',5],...,[9,5,'.',9,'-',' ',3,5,'.',5],[9,5,'.',0,'-',' ',3,5,'.',0]]
                              U           - upend (reverse each)       = [[0,'.',2,4,' ','-',6,'.',7,0,1],[5,'.',1,4,' ','-',7,'.',6,0,1],...,[0,'.',5,3,' ','-',9,'.',5,9],[0,'.',5,3,' ','-',0,'.',5,9]]
                               z⁶         - transpose space filler     = [[0,5,...,5,0],['.','.',...,'.','.'],[2,1,...,5,5],[4,4,...,3,3],[' ',' ',...,' ',' '],['-','-',...,'-','-'],[6,7,...,9,0],['.','.',...'.','.'],[7,6,...,5,5],[0,0,...,9,9],[1,1,...,' ',' ']]
                                 Z        - transpose                  = [[0,'.',2,4,' ','-',6,'.',7,0,1],[5,'.',1,4,' ','-',7,'.',6,0,1],...,[5,'.',5,3,' ','-',9,'.',5,9,' '],[0,'.',5,3,' ','-',0,'.',5,9,' ']]
                                  U       - upend                      = [[1,0,7,'.',6,'-',' ',4,2,'.',0],[1,0,6,'.',7,'-',' ',4,1,'.',5],...,[' ',9,5,'.',9,'-',' ',3,5,'.',5],[' ',9,5,'.',0,'-',' ',3,5,'.',0]]
                                      ⁾|| - literal ['|','|']
                                   j@€    - join €ach (reversed @rgs)  = [['|',1,0,7,'.',6,'-',' ',4,2,'.',0,'|'],['|',1,0,6,'.',7,'-',' ',4,1,'.',5,'|'],...,['|',' ',9,5,'.',9,'-',' ',3,5,'.',5,'|'],['|',' ',9,5,'.',0,'-',' ',3,5,'.',0,'|']]
                                          -                  effectively ["|107.6- 42.0|","|106.7- 41.5|","|105.8- 41.0|","|104.9- 40.5|","|104.0- 40.0|","|103.1- 39.5|","|102.2- 39.0|","|101.3- 38.5|","|100.4- 38.0|","| 99.5- 37.5|","| 98.6- 37.0|","| 97.7- 36.5|","| 96.8- 36.0|","| 95.9- 35.5|","| 95.0- 35.0|"]

“¡ẹƭgụḌẊṘgYƊxyẓṡƝçƤ5ȥṭ’ṃ“.| '-”s7ŒBs5j¢Y - Main link: no arguments   (using "..." below to represent lists of characters)
“¡ẹƭgụḌẊṘgYƊxyẓṡƝçƤ5ȥṭ’                  - base 250 number     =  1694125525350532761476179586378844141697690917975
                        “.| '-”          - literal ['.','|',' ',"'",'-']
                       ṃ                 - base decompression  =  ".------|      |      '-.    .-'   -'---. -    | -    |--    |      '--"
                               s7        - split into 7s       =  [".------","|      ","|      ","'-.    ",".-'   -","'---. -","    | -","    |--","    |  ","    '--"]
                                 ŒB      - bounce (vectorises) =  [".-----------.","|           |","|           |","'-.       .-'",".-'   -   '-.","'---. - .---'","    | - |    ","    |---|    ","    |   |    ","    '---'    "]
                                   s5    - split into 5s       = [[".-----------.","|           |","|           |","'-.       .-'",".-'   -   '-."],["'---. - .---'","    | - |    ","    |---|    ","    |   |    ","    '---'    "]]
                                      ¢  - call last link (1) as a nilad
                                     j   - join                = (using "..." below to represent mixed-type lists from the result of ¢)
                                                               = [".-----------.","|           |","|           |","'-.       .-'",".-'   -   '-.","|107.6- 42.0|","|106.7- 41.5|","|105.8- 41.0|","|104.9- 40.5|","|104.0- 40.0|","|103.1- 39.5|","|102.2- 39.0|","|101.3- 38.5|","|100.4- 38.0|","| 99.5- 37.5|","| 98.6- 37.0|","| 97.7- 36.5|","| 96.8- 36.0|","| 95.9- 35.5|","| 95.0- 35.0|","'---. - .---'","    | - |    ","    |---|    ","    |   |    ","    '---'    "]
                                       Y - join with newlines  = :
                                                                 .-----------.
                                                                 |           |
                                                                 |           |
                                                                 '-.       .-'
                                                                 .-'   -   '-.
                                                                 |107.6- 42.0|
                                                                 |106.7- 41.5|
                                                                 |105.8- 41.0|
                                                                 |104.9- 40.5|
                                                                 |104.0- 40.0|
                                                                 |103.1- 39.5|
                                                                 |102.2- 39.0|
                                                                 |101.3- 38.5|
                                                                 |100.4- 38.0|
                                                                 | 99.5- 37.5|
                                                                 | 98.6- 37.0|
                                                                 | 97.7- 36.5|
                                                                 | 96.8- 36.0|
                                                                 | 95.9- 35.5|
                                                                 | 95.0- 35.0|
                                                                 '---. - .---'
                                                                     | - |
                                                                     |---|
                                                                     |   |
                                                                     '---'

```

# Answer
> 12 votes
## Batch, 325 bytes

```
@echo off
for %%l in ("|           |" "|           |" "'-.       .-'" ".-'   -   '-.")do echo %%~l
set/ac=42,d=5
for /l %%f in (1076,-9,950)do call:c %%f
for %%l in ("'---. - .---'" "    | - |" "    |---|" "    |   |" "    '---'")do echo %%~l
exit/b
:c
set f= %1
set/ac-=!d,d=5-d
echo ^|%f:~-4,-1%.%f:~-1%- %c%.%d%^|

```

# Answer
> 11 votes
# SOGL, ~~98~~ 97 bytes

```
▼⅜¦┌Υ   υl←│Γφγ⅔3wο╚°⁸ofč√&@⁶‘O’⁴∫ |O:9L/*’a6L/+;-l4=?@o}oƧ- o12/*’ ;-o |o"ģ⌠℮Ζ║Kgš‰¶¶ksθ○╤Ƨ%←└⅟ΟS‘

```

note: the 3 spaces close to the beggining of the program are a tab

Explanation:

```
...‘O                                                  output the beginning part
     ’⁴∫                                               repeat 15 times, pushing (0-indexed iteration)
         |O                                            output in a new line "|"
           :                                           duplicate the iteration
            9L/                                        push 0.9 (9/10)
               *                                       multiply [0.9 and the iteration]
                ’a6L/+                                 push 107.6 (107+6/10)
                      ;-                               reverse subtract (107.6 - 0.9*iteration)
                        l4=?  }                        if length is 4
                            @o                           output a space
                               o                       output the number
                                Ƨ- o                   output "- "
                                    12/                push 0.5 (1/2)
                                       *               multiply that by iteration
                                        ’              push 42
                                          ;-           reverse subtract (42-0.5*iteration)
                                            o          output that
                                              |o       output "|"
                                                "...‘  push the ending part

```

To save one byte, I made it push the ending string every time in the loop just so it could get outputted once.

# Answer
> 9 votes
# , 113 bytes

```
i|1076- 420|14ñÙ9l5ñÎeé.$hé.
ç|9/á
o'³-. - .³-'
| - |
|³-|
|³ |
'³-'4>3kHO.±±-.
|±± |Ùo'-.· .-'
.-'³ -³ '-.

```

Try it online!

Hexdump:

```
00000000: 697c 3130 3736 2d20 3432 307c 1b31 34f1  i|1076- 420|.14.
00000010: d939 186c 3518 f1ce 65e9 2e24 68e9 2e0a  .9.l5...e..$h...
00000020: e77c 392f e120 0a6f 27b3 2d2e 202d 202e  .|9/. .o'.-. - .
00000030: b32d 270a 7c20 2d20 7c0a 7cb3 2d7c 0a7c  .-'.| - |.|.-|.|
00000040: b320 7c0a 27b3 2d27 1b34 3e33 6b48 4f2e  . |.'.-'.4>3kHO.
00000050: b1b1 2d2e 0a7c b1b1 207c 1bd9 6f27 2d2e  ..-..|.. |..o'-.
00000060: b720 2e2d 270a 2e2d 27b3 202d b320 272d  . .-'..-'. -. '-
00000070: 2e                                       .

```

More golfing on the way!

# Answer
> 7 votes
# PHP, 187 Bytes

storing 4 spaces in a variable saves 7 Bytes

```
<?=".-----------.
|",$f="    ","$f   |
|$f$f   |
'-.$f   .-'
.-'   -   '-.
";for($n=85;--$n>69;)printf("|%5.1f-%5.1f|
",$n*.9+32,$n/2);echo"'---. - .---'
$f| - |
$f|---|
$f|   |
$f'---'";

```

Try it online!

# PHP, 188 Bytes

```
<?$s=".000--.
|1223|1223'-.12.-'
.-'1-1'-.
4";for($n=85;--$n>69;)$t.=sprintf("|%5.1f-%5.1f|
",$n*.9+32,$n/2);$s.="'0. - .0'
2| - 32|032|132'0'";echo strtr($s,["---","   ","    ","|
",$t]);

```

Try it online!

## PHP, 220 Bytes

```
<?=gzinflate(base64_decode("XZBJCkUhDAT3niI7VzbOw908/O/EwIMviCnLQBukbyFc+db9o5jgNVIM3KwSd9S+khdmkl6Rr9LEIhUMo4Ft9FzHIWV3HdnouYaSpB13FdXouYJG2u4yupE6OewgLXNytmYhPbc0S5vupmYhPTc0SxvuhmYhZf0t58H/gWcMNgHSfRXvvLLJiE2B734="));

```

Try it online!

## PHP, 247 Bytes

```
<?=bzdecompress(base64_decode("QlpoNDFBWSZTWREU1+kAAEnYgEiQQIN/4AAEMAC6bDTRA1NBtqglJ7VIA0AJNSEAAXhknxmxdEkbQhoFWMYrEL1cASWoMYgwHEpJJJKZmZ638CwPCeQHBCLKs3qj1vvz37lF4trWtWviLC4wJoHJywEMA8GmAh2WwUSEom/JeNAioiokhJa9V5bL02pVVVXw+EiwPxdyRThQkBEU1+k="));

```

Try it online!

# Answer
> 5 votes
# Python 2, 163 bytes

```
i=89
for x in("------.x|x|x.-'x-   '-."+"x"*16+"- .---'x- |x--|x  |x--'").split('x'):y='%%-77ss'[i>80::2]%x;print['|%5s- %s|'%(32+.9*i,i/2.),y[:0:-1]+y][x>''];i-=1

```

Try it online!

# Answer
> 5 votes
# APL (Dyalog), ~~144~~ 143 bytesSBCS

```
m←⊢,1↓⌽
1⌽'.||',⍣2⊢11/⍪3↑d←'-'
m 7↑a←∪∊z←⊂'''---. -'
m(6↑⌽a),d
⊃{'|',⍵,'-',⍺,'|'}/(5 1⍕⍪)¨35 95+↓.5 .9∘.×⌽⍳15
↑m¨z,¯7↑¨'| -' '|--' '|  ' '''--'

```

Try it online!

# Answer
> 4 votes
# ///, 261 bytes

```
/`/\/\///i/|
|`~/---`_/   `+/- `f/.5`z/.0`(/i10`)/i 9`!/|
    |/
.--~~~.
|  ___i  ___|
'-. __.-'
.-'_-_'-.
|107.6+42z(6.7+41f(5.8+41z(4.9+40f(4.0+40z(3.1+39f(2.2+39z(1.3+38f(0.4+38z)9f+37f)8.6+37z)7.7+36f)6.8+36z)5.9+35f)5.0+35z|
'~. - .~'
    | - !~!_|
    '~'

```

Try it online!

Works by using common occurrences like `---` as replacements. Nothing fancy.

# Answer
> 4 votes
# JavaScript (ES8),  ~~198 193~~  189 bytes

Number formatting is a bit costly in JS and I seem to be stuck at this byte count. You win this time, PHP! ;-)

```
_=>`.111--.
|67|
|67|
'-.8.-'
.-'4-4'-.
${9e14}'1. - .1'
5| - |
5|1|
5|4|
5'1'`.replace(/\d/g,n=>n%9?''.padEnd(n-1)||'---':`|${F(32+.9*i)}-${F(i--/2)}|
`,i=84,F=v=>v.toFixed(1).padStart(5))

```

Try it online!

# Answer
> 3 votes
## Mathematica 247 Bytes

Hmmm... same as PHP

```
Uncompress@"1:eJxtkLsNAyEQRM+d4OgiRssf2rBTR27ADdCG+/WAODYxEkL7eKDR3N+fx/N7Ow5YXXiJ893o6n/BabFG2HMAHhws97n+cFKQrYke0hfIKAQO6QIJdYJtRDQCUSNCJthGgLMmNDU8/ATbcAgEVQ1BnGAZpvE1QbkM0+pISrCNMpKGrEYeSQm2kUbSkNRIIymBrILYJfsY3c6CZnUEfQ+80eEq1swG+eYH1XhZzA=="

```

# Answer
> 3 votes
# Japt, 106 bytes

```
[".{6î-}
|
'-.
.-'   -"y y 9"'
-
-
-
.|||'
  - -
--- -"y]·mê0R d9FÆ"|{S+(#k6-9*X)t4n)i.J}- {½*Xn84)x1}|"Ã·

```

Test it online!

Many thanks to @obarakon who got the code working in the first place, and did quite a bit of the golfing.

### Explanation

First we have **the data**:

```
[                                     // Create an array of:
  ".{6î-}\n|\n'-.\n.-'   -"           //   This string ({6î-} inserts 6 hyphens),
  y y                                 //   transposed twice to pad it with spaces;
  9                                   //   the number 9;
  "'\n-\n-\n-\n.|||'\n  - -\n--- -"   //   and this string,
  y                                   //   transposed once.
]·                                    // Join the array with newlines.

```

This gives us

```
.------
|
'-.
.-'   -
9
'---. -
    | -
    |--
    |
    '--

```

That is, the left half of the thermometer, with the main rectangle replaced with a `9`. Note that every line is padded with spaces except the one containing the `9`.

```
m  R   // Map each line with the function
 ê     //   ê, or "bounce"; mirrors the string about its last character ("abc" -> "abcba").
       // (The 0 is just filler because `m` expects the `R` to be the third parameter)

```

The net effect is that it mirrors the left half of the thermometer to the right:

```
.-----------.
|           |
'-.       .-'
.-'   -   '-.
9
'---. - .---'
    | - |
    |---|
    |   |
    '---'

```

Now that we have the ASCII-art part, all we have to do is put in the main rectangle:

```
d9FÆ  "|{S+(#k 6-9*X)t4n)i.J}- {½ *Xn84)x1}|"Ã ·
d9FoX{"|{S+(1076-9*X)t4n)i.J}- {.5*Xn84)x1}|"} qR

  FoX{  ...  }        // Create the range [0...15), and map each item X to
"|{ ... }- { ... }"   //   this string, with the two blanks filled in with...

S+(1076-9*X)t4n)i.J
   1076-9*X           //   Calculate 1076 - 9*X. This gives us °F * 10.
S+(        )t4n)      //   Prepend a space and take only the last 4 chars.
                      //   This pads the entries under 100°F to the correct length.
                i.J   //   Insert a decimal point before the last char.
                      //   This turns e.g. "1076" to "107.6".

.5*Xn84)x1
   Xn84               //   Take 84 - X.
.5*    )              //   Multiply it by 0.5. This gives us °C.
        x1            //   Convert to a string with exactly 1 decimal point.

                qR    // Join the resulting array with newlines.
d9                    // In the thermometer art, replace "9" with the resulting string.

```

And that concludes our ASCII-art generating session. Tune in next week to see more kinda-short ASCII-art programs written in Japt!

# Answer
> 3 votes
# Charcoal, 62 bytes

```
←⁶↓.↓²'-.¶.-'¶↓¹⁵'³↓.↓³'²Ｍ²↖¹↑×¹⁹-‖ＯＭ⁵¦¹⁶←Ｅ¹⁵⮌⁺⁺⁺⁹⁵×·⁹ι- ⁺³⁵⊘ι

```

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

```
←⁶↓.↓²'-.¶.-'¶↓¹⁵'³↓.↓³'²Ｍ²↖¹↑×¹⁹-

```

Print the left half of the thermometer.

```
‖Ｏ

```

Reflect it to complete the body.

```
Ｍ⁵¦¹⁶←Ｅ¹⁵⮌⁺⁺⁺⁹⁵×·⁹ι- ⁺³⁵⊘ι

```

Compute the scales and print them reversed and up-side down, which right-justifies them. At time of writing, Charcoal's concatenation operator converts floats to strings using Python's built-in `str` which appends `.0` for floats that represent integers, otherwise I would have to resort to formatting, as its `Cast` operator specifically avoids that behaviour.

# Answer
> 2 votes
Since there's a pandemic out there, I thought the world could use one more thermometer:

# Perl 5, 180 bytes

```
say$_=".-----------.
",y/.-/| /r x2,"'-.       .-'
.-'   -   '-.";map{printf"|%5.1f-%5.1f|
",32+$_*.9,$_/2}reverse 70..84;say"'---. - .---'
    | - |
    |---|
    |   |
    '---'"

```

Try it online!

# Answer
> 1 votes
## C, 222 bytes

```
f(){puts(".-----------.\n|           |\n|           |\n'-.       .-'\n.-'   -   '-.");for(float n=108.5,m=42.5;m>35;printf("|%5.1f- %.1f|\n",n-=.9,m-=.5));puts("'---. - .---'\n    | - |\n    |---|\n    |   |\n    '---'");}

```

Despite attempting to shorten the string, hardcoding it in a plain format is the best option. I doubt that any (significant) improvement is possible in C.

# Answer
> 1 votes
# vim, 222 keystrokes

```
:.!seq 42 -0.5 35
:%!awk '{printf("|\%5.1f- \%.1f|\n",1.8*$1+32,$1)}'
Go'===. - .==='<ESC>yy
:s/=/-/g
p
:.!tr "'.=" ' | '
:s/ *$/
yyP
:s/-/ /
ddpPlR---<ESC>yyGp
:s/|/'/g
ggO..<ESC>11i-<ESC>yyP
:.!tr .- '| '
yypo'-.<ESC>7a <ESC>a.-'<ENTER>.-'   -   '-.<ESC>

```

# Answer
> 1 votes
# C (gcc), ~~234~~ ~~217~~ ~~212~~ 210 bytes

```
f=420;main(){for(printf(".-----------.\n|%11s|\n|%1$11s|\n'-.%1$7s.-'\n.-'   -   '-.\n","");f>345;f-=5)printf("|%5.1f- %.1f|\n",32+f*.18,f*.1);puts("'---. - .---'\n    | - |\n    |---|\n    |   |\n    '---'");}

```

Try it online!

-15 bytes thanks to ceilingcat!!

-5 bytes thanks to TrapII!!

Output:

```
.-----------.
|           |
|           |
'-.       .-'
.-'   -   '-.
|107.6- 42.0|
|106.7- 41.5|
|105.8- 41.0|
|104.9- 40.5|
|104.0- 40.0|
|103.1- 39.5|
|102.2- 39.0|
|101.3- 38.5|
|100.4- 38.0|
| 99.5- 37.5|
| 98.6- 37.0|
| 97.7- 36.5|
| 96.8- 36.0|
| 95.9- 35.5|
| 95.0- 35.0|
'---. - .---'
    | - |
    |---|
    |   |
    '---'

```

# Answer
> 1 votes
# Deadfish~, 2064 bytes

```
{iiii}iiiiiicd{c}cic{ddd}ddddddc{{i}}{i}iiiic{{d}i}dd{c}c{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}dd{c}c{{i}d}iic{{d}}{d}ddddc{iii}dciiiiiicic{d}ddddccccccc{i}iiiicdcddddddc{ddd}ic{iii}iiiiiicdcddddddc{d}iiiccc{i}iiic{d}dddccc{i}dddciiiiiicic{ddd}ddddddc{{i}}{i}iiiic{{d}iii}dddddcdc{i}dddc{d}ic{i}ddc{d}ic{d}dddc{ii}cddcddddciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciiiiiic{d}iic{i}dc{d}c{d}dddc{ii}cdddcdddc{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciiiiic{d}iiic{i}c{d}dc{d}dddc{ii}cdddcdddciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciiiicddddddc{i}ic{d}ddc{d}dddc{ii}cddddcddc{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciiiicddddddciicdddc{d}dddc{ii}cddddcddciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciiicdddddciiicddddc{d}dddc{ii}dciiiiiic{d}dc{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciicddddciiiicdddddc{d}dddc{ii}dciiiiiic{d}dciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdcicdddciiiiicddddddc{d}dddc{ii}dciiiiic{d}c{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdccddciiiiiic{d}iiic{d}dddc{ii}dciiiiic{d}ciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicc{d}dc{i}dddc{d}iic{d}dddc{ii}dciiiic{d}ic{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicdc{d}c{i}ddc{d}ic{d}dddc{ii}dciiiic{d}iciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicddc{d}ic{i}dc{d}c{d}dddc{ii}dciiic{d}iic{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicdddc{d}iic{i}c{d}dc{d}dddc{ii}dciiic{d}iiciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicddddc{d}iiic{i}ic{d}ddc{d}dddc{ii}dciic{d}iiic{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicddddc{d}iiiciicdddc{d}dddc{ii}dciic{d}iiiciic{{i}ddd}iiiiiic{{d}}{d}ddddc{iii}dciiiiiicccic{d}ddddc{i}iiic{d}dddc{i}iiiicdcccddddddc{ddd}ic{ii}iicccc{{i}d}iic{{d}i}ddc{i}iiic{d}dddc{{i}d}iic{{d}}{d}ddddc{ii}iicccc{{i}d}iic{{d}ii}iccc{{i}dd}dc{{d}}{d}ddddc{ii}iicccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iicccc{i}dddciiiiiicccddddddc

```

Sorry Dennis.

# Answer
> 0 votes
# C, ~~460~~ 265 bytes

```
#define P(x) puts(x);
#define Z "|           |"
T(){float i=7,j=12.6;P(".-----------.")P(Z)P(Z)P("'-.       .-'")P(".-'   -   '-.")while(i>=0)printf("|%5.1f- %.1f|\n",95+j,35+i),i-=.5,j-=.9;P("'---. - .---'")P("    | - |")P("    |---|")P("    |   |")P("    '---'")}

```

**Output** Live

```
.-----------.
|           |
|           |
'-.       .-'
.-'   -   '-.
|107.6- 42.0|
|106.7- 41.5|
|105.8- 41.0|
|104.9- 40.5|
|104.0- 40.0|
|103.1- 39.5|
|102.2- 39.0|
|101.3- 38.5|
|100.4- 38.0|
| 99.5- 37.5|
| 98.6- 37.0|
| 97.7- 36.5|
| 96.8- 36.0|
| 95.9- 35.5|
| 95.0- 35.0|
'---. - .---'
    | - |
    |---|
    |   |
    '---'

```

# Answer
> 0 votes
# Go, 238 bytes

Wow, that string is really resistant to golfing...

```
package main
import."fmt"
func main(){p:=Printf
s,i:=`|           |
`,42.
p(`.-----------.
`+s+s+`'-.       .-'
.-'   -   '-.
`)
for;i>=35;i-=.5{
p(`|%5.1f- %.1f|
`,i*9/5+32,i)}
p(`'---. - .---'
    | - |
    |---|
    |   |
    '---'`)}

```

Try live here: https://play.golang.org/p/tPKYxII7NC

---
Tags: code-golf, ascii-art, kolmogorov-complexity, sequence
---


title: What's my TIO uniqueness?

text:
# Question
Title: What's my TIO uniqueness?
Try it online! currently has 680 listed languages, all of which are searchable. For most of those languages, when searching for it, you don't have to enter the entire string. For example, entering `lega` results in just 05AB1E (legacy) appearing, and entering `d+` results in only Add++. However, for some languages, there is no such string that results in *only* that languages, e.g. `Jelly` returns both `Jelly` and `Jellyfish`

We will call the length of the shortest string required to return *only* a specific language on TIO the *TIO uniqueness* of that language. The TIO uniqueness of a language for which this is impossible is undefined. Note that TIO ignores case when searching, so `bri` results in Brian & Chuck and `SOM` results in Somme.

You are to take the name of a programming language on Try it online!, exactly as spelt in the search function, and return that language's TIO uniqueness. If the language's TIO uniqueness is undefined, you may instead return any value which is not a positive integer (or could reasonably be interpreted as a positive integer). This value need not be consistent between such languages. Your program should handle all 680 languages currently on TIO.

This is , so the shortest code wins. Standard loopholes are forbidden, especially internet access. You may also not access the file system of TIO. Essentially, your program should work whether it's run on TIO or locally.

## Test cases

All test cases include the TIO uniqueness string in lowercase, as TIO is case insensitive in its search, and use 0 for undefined TIO uniquenesses

```
"Arcyóu" -> 1 ("ó")
"Befunge-98 (PyFunge)" -> 13 ("befunge-98 (p")
"Cauliflower" -> 3 ("cau")
"Shove" -> 3 ("hov")
"Funky" -> 0
",,," -> 2 (",,")
"Agony" -> 0
"Starry" -> 4 ("tarr")
"Add++" -> 2 ("d+")
"ATS2" -> 3 ("ts2")
"F# (.NET Core)" -> 5 ("f# (.")
"Dyvil" -> 2 ("yv")
"Python 3.8 (pre-release)" -> 2 ("3.")

```

The full list of names and the full list of test cases

# Answer
> 16 votes
# JavaScript (Node.js),  ~~819~~  779 bytes

Returns `0` for undefined TIO uniqueness.

```
s=>(B=Buffer)('J .!> . 8 " .  . 0 L"0"c$E"~~~="8"~1 Y$^"~~~j S$x"P S$;"7 @ Z G"/$8$A :%X!T%A G M$c*h"d"L!Q$8"~F$.$>"s$@"`"E 3 1$r"U">"8 F&~Y"="z"~Q"F"E"g |"R%m!c$"~N"~?$Q  1 ~W B$k"F ="d$> U"7%"""F"X%Y%s"S$E"<-O$b _"]"?$3 <$B i"0"~A"W">$6 L `"I%2"1"?$6"M "A _$2"A ="; T"t @$:"q"N i"["V&~= z"5"1 I!N"8"Z ` ~~B 4"1 }"#"2$."e P F ;!A"W$K G">$9$K"T M*W #"8 < 0"A ]""~~J Z""m"0"V!; ~~[ h+$2$~^"1"3$1"3 A$}"D"~i"9 H%N"~3 9 K"~4"; C%C"Q"3"/ X ^"D"9$4 4 /"7 J":$$0*o"~<"Z 9"T"I"~D$5"@ 1"j ". ~c"O$4"3 O ~X 6$K"I ~8 F  d$T } 6"#"V"W";$I$0 H$R"x$"[$6 j i"U"~M L"K$~~h W$L O"0%="Z 4"F$X"6!?$;"4"M"~0$~1%r"k"6"K"^"2 5$V v"4"J"z 1"1 H$;$W"#">!i"."V"V$e"6$~~<*~C!~/"7 8!/ q$3"U /"."? t"Y"J!<$4 i"~P K"Y'.replace(/[.-~]/g,c=>'#'.repeat(B(c)[p=0]-44))[B(s).map(c=>p=(p*79^c)>>>0)|p%12635])[0]-32

```

Try it online! (test cases)

Try it online! (all languages)

### How?

There are only \\$10\\$ distinct TIO uniqueness values, ranging from \\$0\\$ to \\$13\\$. Besides, more than 50% of the languages have a TIO uniqueness of \\$3\\$.

```
 uniq. | count | ratio
-------+-------+--------
   0   |   97  | 14.24%
   1   |   12  |  1.76%
   2   |  140  | 20.56%
   **3**   |  **357**  | **52.42%**
   4   |   56  |  8.22%
   5   |   11  |  1.62%
   6   |    2  |  0.29%
  10   |    4  |  0.59%
  11   |    1  |  0.15%
  13   |    1  |  0.15%
```

We need:

* a function \\$H\_0\\$ that turns the language name \\$s\\$ into an integer \\$H\_0(s)\\$
* a function \\$H\_1\\$ and a corresponding lookup table \\$T\\$ so that the TIO uniqueness of the language is \\$T\[H\_1(H\_0(s))\]\\$

It seems unlikely to find some simple functions \\$H\_0\\$ and \\$H\_1\\$ that would directly lead to a small lookup table. But if we use \\$3\\$ (the most common uniqueness) as the padding value for unused slots, the table is going to contain a lot of \\$3\\$'s.

So our strategy is to use:

* the first 14 printable ASCII characters (32 to 45, i.e.  to `-`) to encode the actual uniqueness values other than \\$3\\$
* all other printable characters (46 to 126, i.e. `.` to `~`) to encode runs of 2 to 82 consecutive \\$3\\$'s

Conveniently, the single quote `'` (ASCII code 39) will never appear in the table because no language has a uniqueness of 7. So we can use it as our string delimiter and safely use `"` and ``` in the table without having to escape them.

We now need to find \\$H\_0\\$ and \\$H\_1\\$ so that the distribution of actual uniqueness values among the \\$3\\$'s leads to the smallest table with this simple compression scheme.

After some brute-forcing, it turns out that the following functions work reasonably well:

* `Buffer(s).reduce((p, c) => p * 79 ^ c) >>> 0` (actually implemented with a `.map()`)
* `% 12635`

# Answer
> 3 votes
# Haskell, 750 bytes

```
(("K%J#3#=#5##2'#5#3#L%5#5'2';#J#[%O'%_%8#d#B'70_'%t%7#e%]%7%D%Zq'G#Z3#5#4#e#8%2#<%6#7%9%R%k%9%5)4%>%ZX%u(D'<'@#Zj'3#U%W%2(~'4#]'M'6%R#2#5%<#D%Z%c'U#D#9%I':#a'J$=%ZY%`%2#3%R%3%C-Z_%3%;($I#A%Q%N#G'æ%3'v#d'¨%G#U#E#B'[%>#B%5%7$f%Z3#`'8#ZX'5%6#d%E-Y%r%B#@#;%¶#2#Zl%Ò%f%<%G%q-;'8#Q'k$_%l%[%Z#3'6$7'y#9%¢%N%f#^'>#S#C'2'k%5%o%Z_%F'P#c%;']#Zu'?#6%Zs#a'>#I%I%Į'B#B%B'9%;%2%O%Q#9%]%F%x#?#g#T%N'ª%V%B%j%I#3%M%u%Z3'7#T%%ZW#Ze#5%U%7#V#P#N%D%8#V%9%`(W%W';#g$|%a(5#K#6$3%~##A._#7%M%3#2#5#a%9'C%c%Z%V%V$;#?%#U'2%@$7%<%?%3%ě%G'c'4%J#Y%L#?%8#4%q%B'%K'=%B%L%E#A#9%6(@'D%2(Z[#8-D%V'L'?%i%A'¨%['m(3(@#>$U%M)I(e#5(;%w%J'o%2'T%H%E$[#9$8%8'5%2#=%y%>'k#P%4#?%#>#E%4#ZV'C%4#Q">>=(\i->[i-35|i<49]++([1..i-49]>>[3])).e)!!).foldr(\y a->mod(1323*a+(e y))9960)0
e=fromEnum

```

Try it online!

After Arnauld added an explanation for his answer, it looks like my answer was just a Haskell port of his. Here are the relevant differences:

* lenghts from \\$0\\$ to \\$13\\$ are encoded with character points \\$35\\$ to \\$48\\$, in order to avoid double quotes `"`;
* runs of consecutives \\$3\\$'s are encoded with character points \\$49\\$ to \\$\infty\\$;
* I used \\$1323\\$ in \\$H\_0\\$ and \\$9960\\$ in \\$H\_1\\$ (which should result in a slightly smaller lookup table).

---
Tags: code-golf, string, subsequence, compression
---


# Question
Title: Average impact of multiple conversion errors
Imagine four people stand in a line. The first looks at a thermometer, and tells the temperature to the person on their right. This continues down the line, until the last person writes the temperature on a sheet of paper. Unfortunately, due to a miscommunication, every person in the line converts the temperature to their preferred unit, without knowing which it already was.

Let's say the people's preferred units are `celsius`, `fahrenheit`, `fahrenheit`, `celsius`. The first reads the temperature as 20°C. The second converts to fahrenheit, and determines that it is 68°F. The third, not knowing they have received the temperature in °F already, determines that it is 154.4°F. Finally, it is converted back to °C by the fourth person, who determines that it is 68°C.

**Task:**

You will be given two inputs: a temperature (`t`), and a number of people (`n`). Your program (or function) should return the average difference between the original and resulting temperatures, for every possible assortment of `n` people.

There are two temperature units: °F and °C. To convert between them, you can use \\$F=\frac95C+32\\$ and \\$C=\frac59(F-32)\\$.

You can choose whether your program receives the inputted temperature in °F or °C. The first person should always receive an accurate temperature, converted to their preferred unit only if necessary.

As an example, we'll use an inputted temperature of 41°F, and just 3 people. There are 8 temperature preferences possible:

```
FFF   41°F  ->  41.0  ->  105.8  ->  222.44  ->  222.44°F
FFC   41°F  ->  41.0  ->  105.8  ->   41.00  ->  105.80°F
FCF   41°F  ->  41.0  ->    5.0  ->   41.00  ->   41.00°F
FCC   41°F  ->  41.0  ->    5.0  ->  -15.00  ->    5.00°F
CFF   41°F  ->   5.0  ->   41.0  ->  105.80  ->  105.80°F
CFC   41°F  ->   5.0  ->   41.0  ->    5.0  ->    41.00°F
CCF   41°F  ->   5.0  ->  -15.0  ->    5.00  ->    5.00°F
CCC   41°F  ->   5.0  ->  -15.0  ->  -26.11  ->  -15.00°F

```

The average distance from 41°F is 54.88°F, which is the program's output.

**I/O:**

Temperature should be represented as a float, decimal, or fraction of some sort. The accuracy should be within reasonable bounds; for inputs less than ten people at low temperatures there shouldn't be floating point errors or imprecision noticeable in the first four decimal digits.

You may represent the temperatures inputted and outputted as either °F or °C, but must be consistent (although the input can output can be different units as long as they don't change). Temperatures can be negative. The number of people will never be less than two.

The output is referred to as a temperature above, although it's technically the arithmetic mean of multiple temperatures.

**Test Cases:**

Input unit is the same as output unit for all test cases.

```
41°F   2   ->  25.2
41°F   3   ->  54.88
41°F   4   ->  77.236444...
41°F   10  ->  295.4268...
20°C   4   ->  57.21218...
-1°C   2   ->  12.133...
-20°C  2   ->  6.2222...
-40°F  4   ->  0

```

**Other:**

This is , shortest answer in bytes per language wins!

# Answer
# APL (Dyalog Unicode), 41 bytes

```
(|40+⎕)+.×(|÷≢)1-1.8*1(-,+)⍨⍣(⎕-2)⊢1-3|⍳4

```

Try it online!

A full program. Takes the number of people, then the initial temperature. TIO version is wrapped in a function for easier testing. As I pointed out in a comment, the initial and final units do not matter as long as they are equal.

### The math

The code exploits the fact that Fahrenheit-Celsius conversion has a fixpoint at -40 (-40°F = -40°C). Then we can add 40 to all temperature readings, and then the whole series of conversion reduces into a (positive or negative) integer power of \\$\frac95\\$.

$$ F+40=\frac95(C+40), \quad C+40 = \frac59(F+40) $$

Since every temperature value is offset by the constant value of 40, the difference between two offset temperature values is the same as that of the original. Therefore, it suffices to apply the offset to the initial temperature and ignore it to the end.

Let's call \\$r = \frac95\\$.

Now to the part of counting all conversion paths. Let's say the initial reading is in Fahrenheit. Then:

* Initial conversion: `F→F` (\\$r^0\\$) or `F→C` (\\$r^{-1}\\$).
* Final conversion: `F→F` (\\$r^0\\$) or `C→F` (\\$r^1\\$).
* All inner conversions: `C→F` (\\$r^1\\$) or `F→C` (\\$r^{-1}\\$).

So the task reduces to finding all the individual terms in the expansion of \\$(r^0 + r^{-1})(r^1+r^{-1})^{n-2}(r^1+r^0)\\$. Then plug in the value of \\$r\\$, evaluate the average of differences to 1, and then multiply with the initial temperature (with offset).

### The code

```
(|40+⎕)+.×(|÷≢)1-1.8*1(-,+)⍨⍣(⎕-2)⊢1-3|⍳4

⊢1-3|⍳4  ⍝ A fancy way to create an array of 0 ¯1 1 0
         ⍝ which represents the powers in (1+r^-1)(r+1)
⍣(⎕-2)   ⍝ Repeat n-2 times...
1(-,+)⍨  ⍝ multiply the given polynomial with (r+r^-1)
         ⍝ and list all powers
1.8*     ⍝ Plug in r = 1.8 and evaluate the powers
1-       ⍝ Difference of each value from 1
(|÷≢)    ⍝ Average of absolute differences from 1
+.×      ⍝ Product and sum with...
(|40+⎕)  ⍝ Absolute difference between -40 and t

```
> 6 votes

# Answer
# Python 3, 126 bytes

```
f=lambda t,n,x=0,i=0,j=0:(f(i and 9*t/5+32or t,n,x or t,i+1,0)+f(5/9*(t-32),n,x or t,i+1,1))/2if i-n else abs(t+(32+.8*t)*j-x)

```

Try it online!

`j` is 0 or 1 depending on whether current temperature is in F or C.

`i` denotes the number of conversions that we have already performed. We perform both of the possible conversions and take the mean of the answer.

`x` is an extra variable just used to keep track of the original temperature.
> 2 votes

# Answer
# JavaScript (Node.js), 84 bytes

```
T=>U=>g=(N,p)=>(--N?g(N,~-p)+g(N,p+1|0):Math.abs(U**p-1)*(1+U)*(T+40))/2,C=5/9,F=9/5

```

Try it online!

Bubbler had worked out the correct formula, so I would like to remove the incorrect (many off-by-one errors) one here. You may read more about math formulas from Bubbler's post. You may find out a solution based on that formula from history of this post.

But calculating binomial coefficient costs too many bytes. So using recursion results a shorter solution here. And the recursion function:

$$ U=\begin{cases} 5/9 && \text{Input is ℃} \\ 9/5 && \text{Input is ℉} \end{cases} $$

$$ g\_U\left(n,p\right) = \begin{cases} \left(g\_U\left(n-1,p+1\right)+g\_U\left(n-1,p-1\right)\right)/2 & n \> 1 \\ \left|U^{p}-1\right| & n = 1 \end{cases} $$

$$ f(T,U,N)=\left(1+U\right)\left(T+40\right)\left(g\_U\left(N-1,0\right)+g\_U\left(N-1,-1\right)\right)/4 $$

---
> 2 votes

# Answer
# APL (Dyalog Unicode), <sup>~~55~~</sup> 51 bytes

```
{(2.8×|40+⍺)+.×(|1-1.8*x-⍨⍳2×x)×2/(⍳x←⍵-1)!⍵-2}÷2*⊢

```

Try it online!

*-4 bytes thanks to @tsh*

I finally managed to derive the correct version of tsh's formula, though it turns out to be slightly longer than brute force.

$$ (1+r)\sum\_{p=-n+1}^{n-2}{\binom{n-2}{\left\lfloor\frac{p+n-1}{2}\right\rfloor} r^p \operatorname{sgn}\left(p+\frac{1}{2}\right)} \div 2^n \\ = (1+r)r^{-n+1}\sum\_{p=0}^{2n-3}{\binom{n-2}{\left\lfloor\frac{p}{2}\right\rfloor} r^p \operatorname{sgn}\left(p-n-\frac{1}{2}\right)} \div 2^n \\ = (1+r)\sum\_{p=-n+1}^{n-2}{\binom{n-2}{\left\lfloor\frac{p+n-1}{2}\right\rfloor} \left|r^p - 1\right|} \div 2^n \\ \text{ where } r = 1.8 $$

In array terms, the first and second formula are equivalent to building a vector containing two copies of each binomial coefficient, negating half of it, and multiplying each with suitable power of \\$r\\$.

The code above uses the third line of the formula.

The process of deriving the formula was essentially spotting two copies of Pascal's triangle in the expansion of polynomial \\$(r^0 + r^{-1})(r^1+r^{-1})^{n-2}(r^1+r^0)\\$, defining an intermediate function (\\$\[x;y;z\]\\$ denotes `if x then y else z`)

$$ f^+(n, r) = \sum\_{p=0}^{n-1}{\binom{n-1}{p} r^{2p-n} \[2p-n\ge 0; 1; -1\]}, $$

defining the sum of differences in terms of \\$f^+\\$ as

$$ g(n) = f^+(n-1, r) - f^+(n-1, r^{-1}) + rf^+(n-1, r) - r^{-1}f^+(n-1, r^{-1}) $$

and simplifying it over an entire sheet of paper.
> 2 votes

# Answer
# , 84 bytes

```
g=.32+*&9r5
[:(+/%#)[|@-[(g inv@]`(g@])@.[/@,~)&>2<@([:1&,^:(1-{.)}:^:{:)"1@#:@i.@^]

```

Try it online!

Takes input and output in F.

Returns exact output as a rational number.

This hasn't been fully golfed, and it's possible there are large savings to be gained from a different approach.

## tldr how

* Generate all binary numbers from `0` to `2^(number of people)`.
* `1` represents "convert to F" and `0` "convert to C".
* Remove `1` from the end of any binary number that ends in `1` (since an initial F person reads the F thermometer correctly).
* Add `1` to the beginning of any binary number beginning with `0` (since a final C reading must be converted to F).
* Evaluate each resulting binary number right-to-left like a pipeline of conversions.
* One nice thing is that J is able to invert the conversion for us, so after defining the F conversion as `g`, we get the C for free as `g inv`.
* Finally take the average of the absolute differences from the starting temp.
> 1 votes

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