# Question
Title: Calculate the difficulty of a Code Golf question
# Briefing

The difficulty of a Code Golf question can be calculated as such:

$$\text{clamp} \left( \left\lceil \left( \frac v a \div 700 \right) \times 10 \right\rceil, 0, 10 \right)$$

Where \\$v\\$ is the number of views a question has

and \\$a\\$ is the number of answers a question has

and \\$⌈x⌉\\$ is the ceiling operator.

Also:

$$\text{clamp}(x, min, max) = \begin{cases} min & x \< min \\ x & min \le x \le max \\ max & max \< x \end{cases}$$

This question's current difficulty: `***`

# Task

Write a program that will take two integers `(v and a)` and output the difficulty in `asterisks (*)`.

The input can be in the form of an array, a separated string or as separate function arguments

# Test Data

```
Views   Answers Difficulty  Program Output
163     2       2           **
548     22      1           *
1452    24      1           *
1713    37      1           *
4162    32      2           **
3067    15      3           ***
22421   19      10          **********

```

### Example with pseudocode

```
v: 1713
a: 37
out = clamp(ceil(((v/a)/700)*10), 0, 10); // evaluates to 1
//program will output '*'

```

The shortest code in bytes wins! Trailing/ leading spaces are allowed.

# Answer
## JavaScript (ES6), ~~40~~ 39 bytes

```
v=>a=>"**********".substring(10-v/a/70)

```

Because `substring` provides the required clamping and "ceil"ing behaviour. Edit: Normally I'm too lazy to bother, but because it got 4 upvotes, I've followed @MarsUltor's advice to save 1 byte by currying.
> 49 votes

# Answer
I've been wanting to do this for a while...

## HTML + CSS ~~491~~ ~~487~~ 485 bytes

*-4 bytes thanks to Conor O'Brien*
*-2 bytes thanks to Releasing Helium Nuclei*

Input is taken as the width and height of the page window; width being the number of Views, and height being the number of Answers.

```
<style>p{overflow:hidden;width:1ch}@media(max-aspect-ratio:70/2){p{width:1ch}}@media(max-aspect-ratio:70/3){p{width:2ch}}@media(max-aspect-ratio:70/4){p{width:3ch}}@media(max-aspect-ratio:70/5){p{width:4ch}}@media(max-aspect-ratio:70/6){p{width:5ch}}@media(max-aspect-ratio:70/7){p{width:6ch}}@media(max-aspect-ratio:70/8){p{width:7ch}}@media(max-aspect-ratio:70/9){p{width:8ch}}@media(max-aspect-ratio:7/1){p{width:9ch}}@media(max-aspect-ratio:70/11){p{width:10ch</style><p>**********

```

You can try it in your browser by entering

```
data:text/html,<style>p{overflow:hidden;width:1ch}@media(max-aspect-ratio:70/2){p{width:1ch}}@media(max-aspect-ratio:70/3){p{width:2ch}}@media(max-aspect-ratio:70/4){p{width:3ch}}@media(max-aspect-ratio:70/5){p{width:4ch}}@media(max-aspect-ratio:70/6){p{width:5ch}}@media(max-aspect-ratio:70/7){p{width:6ch}}@media(max-aspect-ratio:70/8){p{width:7ch}}@media(max-aspect-ratio:70/9){p{width:8ch}}@media(max-aspect-ratio:7/1){p{width:9ch}}@media(max-aspect-ratio:70/11){p{width:10ch</style><p>**********

```

as a url in a new tab.
> 38 votes

# Answer
## 05AB1E, 11 bytes

```
/70/î'*T×s£

```

**Explanation**

```
/            # divide v by a
 70/         # divide by 70
    î        # round up, call this n
     '*T×    # push 10 asterisks
         s£  # take n up to 10 asterisk
             # implicitly print

```

Try it online
> 12 votes

# Answer
## Javascript (ES6), ~~37~~ 36 bytes

```
v=>a=>"*".repeat((v/=a*70)<9?v+1:10)

```

*Saved 1 byte by currying, thanks to TheLethalCoder*

```
let F=
v=>a=>"*".repeat((v/=a*70)<9?v+1:10)

console.log("Test #1:", F(163)(2))    // **
console.log("Test #2:", F(548)(22))   // *
console.log("Test #3:", F(1452)(24))  // *
console.log("Test #4:", F(1713)(37))  // *
console.log("Test #5:", F(4162)(32))  // **
console.log("Test #6:", F(3067)(15))  // ***
console.log("Test #7:", F(22421)(19)) // **********
```
> 12 votes

# Answer
# Mathematica, ~~38~~ 35 bytes

```
StringRepeat["*",10,⌈#/#2/70⌉]&

```

*Thanks to @MartinEnder for 3 bytes*
> 11 votes

# Answer
## EXCEL, 29 bytes

If you count Excel as a representation of VBA Excel, then you can use

```
=REPT("*",MIN(1+v/(70*a),10))

```

where `v` and `a` are the name of reference cells.
> 9 votes

# Answer
## CJam, ~~18~~ ~~15~~ 14 bytes

*Saved 1 byte thanks to Peter Taylor and 3 bytes thanks to Adnan*

```
'*A*q~d/70/m]<

```

Try it online

```
'*A*            e# Push "**********"
    q~d/        e# Get the input and divide the two numbers
        70/     e# Divide by 70
           m]   e# Ceil, yielding x
             <  e# Slice the string, taking the first x elements

```
> 8 votes

# Answer
## C#, ~~68~~ ~~49~~ 48 bytes

```
v=>a=>"**********".Substring((int)(10-v/a/70d));

```

This is the C# version of this excellent answer by Neil.

*Saved another 19 bytes thanks to Neil*
> 7 votes

# Answer
# Java 8, 57 bytes

Uses a lambda to save bytes, performs the calculation and substrings to return the answer.

```
(v,a)->"**********".substring(Math.max(0,(700*a-v)/70/a))

```

---

Here is my class for testing it.

```
public class DifficultyCalculator{
    static interface h{ String f(int v, int a);}
    static void g(h H){
        System.out.print(H.f(163,2));System.out.println("\t**");
        System.out.print(H.f(548,22));System.out.println("\t*");
        System.out.print(H.f(1452,24));System.out.println("\t*");
        System.out.print(H.f(1713,37));System.out.println("\t*");
        System.out.print(H.f(4162,32));System.out.println("\t**");
        System.out.print(H.f(3067,15));System.out.println("\t***");
        System.out.print(H.f(22421,19));System.out.println("\t**********");
    }
    public static void main(String[] args) {
        g( // 70
            (v,a)->"**********".substring(java.lang.Math.max(0,(int)(10-v/70d/a)))
        );
    }
}

```

---

**Update**

* **-3** \[16-08-19\] Utilized integer division
* **-10** \[16-08-18\] Removed unnecessary import, thanks to *@OlivierGrégoire*!
* **-18** \[16-08-17\] Return string instead of print
> 7 votes

# Answer
# MATL, 12 bytes

```
/70/0:9>42*c

```

**Try it online!**

### Explanation

The rounding up and clamping are done simultaneously as follows: the number `x = v/a/70` is compared against each element of the array `[0 1 ... 9]`. The numbers of that array that are exceeded by `x` will become asterisks, and the rest will be spaces.

```
/      % Take the two numbers implicitly. Divide. (Example: for inputs 3067, 15
       % we get 204.47)
70/    % Divide by 70 (we get 2.92)
0:9    % Push array [0 1  ... 9]
>      % See which of those are exceeded by the previous number (2.92 exceeds
       % 0, 1 and 2, so we get [1 1 1 0 ... 0]). This does the rounding up
       % and the clamping
42*    % Multiply by 42, which is the ASCII code of '*' (we get [42 42 42 0 ... 0])
       % Char 0 will be displayed as space
c      % Convert to char. Implicitly display

```
> 6 votes

# Answer
# Python2, 32 bytes

saved 3 + 2 bytes and corrected off by one error thanks to Leaky Nun

```
lambda v,a:('*'*10)[:~-v/a/70+1]

```

similar to Neils answer. Uses the fact that Python2 does integer division.
> 5 votes

# Answer
# Haskell, 35 bytes

```
v#a=[1..min(ceiling$v/a/70)10]>>"*"

```

`[1..min(ceiling$v/a/70)10]` creates a range from 1 to the computed difficulty (an empty list for difficulty 0). `a>>b` repeats the list `b` `length a` often.
> 5 votes

# Answer
## C#, ~~97~~ ~~89~~ ~~87~~ ~~77~~ ~~42~~ 41 bytes

```
v=>a=>new string('*',(v/=a*70)<9?v+1:10);

```

*Saved 10 bytes thanks to Adám*

*Saved a few bytes thanks to Arnauld*
> 4 votes

# Answer
# Pyth, ~~17~~ 13 bytes

**4 bytes in credit to Luis Mendo for his algorithm.**

```
~~*\*htS[0T.EccFQ70~~
*\*s>LccFQ70T

```

Test suite.
> 4 votes

# Answer
# R,  68, 50 52 bytes

```
f=function(v,a)cat(rep("*",1+min(v/a/70,10)),sep="")

```

`rep` implicitly places a min on number of 0.

Thanks to @plannapus and @Anastasiya-Romanova秀 for spotting my error.
> 4 votes

# Answer
# Perl, ~~35~~ 32 bytes

```
say"*"x(10-($-=10-pop()/70/pop))

```

Use `-E` to activate `say` and give the arguments in the reverse order:

```
perl -E 'say"*"x(10-($-=10-pop()/70/pop))' 2 163

```

If arguments on STDIN are allowed the following is 29 bytes:

```
(echo 163; echo 2) | perl -pe '$_="*"x(10-($-=10-$_/70/<>))'

```
> 4 votes

# Answer
## Pyke, ~~13~~ 9 bytes

```
/70/\**T<

```

Try it here!

Explanation:

```
/         -    num_1 / num_2
 70/      -   ^ / 70
    \**   -  "*" * ^
       T< - ^[:10]

```
> 4 votes

# Answer
# Javascript ES6, 48 bytes

```
a=>b=>"*".repeat(Math.ceil(Math.min(a/b/70,10)))

```
> 3 votes

# Answer
# m4, ~~136~~ 135 bytes

```
define(r,`ifelse($1,0,,eval($1>9),1,*`r(9)',*`r(decr($1))')')define(f,`r(ifelse(eval($1%($2*70)),0,eval($1/$2/70),eval($1/$2/70+1)))')

```

Defines a macro `f` which takes `v` and `a`, and expands to the correct output. Most of the program is an implementation of ceiling.
> 3 votes

# Answer
# C, ~~54~~, ~~51~~, ~~50~~, 49 bytes

Assuming that `v` is positive or zero and `a` positive, the `x < min` clamping case is never met, since there is no way the result of the ceiling operation can be negative. Additionally, integer maths on non-negative values always yields the floor of the result, so we add `1` to get the ceiling.

This solution requires a `write` function, works on Linux at least.

```
F(v,a){write(1,"**********",(v/=a*70)>9?10:v+1);}

```

Test main:

```
int main() {
  F(163, 2);
  putchar('\n');
  F(548, 22);
  putchar('\n');
  F(1452, 24);
  putchar('\n');
  F(1713, 37);
  putchar('\n');
  F(4162, 32);
  putchar('\n');
  F(3067, 15);
  putchar('\n');
  F(22421, 19);
  putchar('\n');
}

```
> 3 votes

# Answer
## javascript: ~~82~~ 73 bytes

```
 (v,a)=>console.log("*".repeat(Math.min(Math.max(0,Math.ceil(v/a/70),10)))

```
* *saved some bytes after Adám pointed out I overlooked the /700\*10=/70*, and the removal of parens
> 2 votes

# Answer
# Dyalog APL, 15 bytes

```
'*'⍴⍨10⌊⌈⎕÷70×⎕

```

`'*'⍴⍨` the character repeated this many times:
`10⌊` min(10,...
`⎕÷` input divided by
`70×` seventy times
input

TryAPL online!
> 2 votes

# Answer
## Jellyfish, 18 bytes

```
P
#'*
mM/%i
10 %70

```

Takes input in the format `[a v]`. Try it online!

## Explanation

* `%` is reciprocal, so `%70` is 1/70.
* `i` is input, as a two-element array.
* `/%` with inputs `i` and `%70` reduces the array `i` by flipped division with initial value `%70`. In other words, it computes **v/(a/(1/70))**, which is equal to **v / (70\*a)**.
* `M` takes the ceiling of this value, and `m` takes the maximum of that and `10`.
* `#'*` repeats the literal `*` character that many times.
* `P` prints the result without quotes.
> 2 votes

# Answer
# MATLAB, 34 33 bytes

Because I like this challange so much, here is one for MATLAB (outputs trailing whitespaces):

```
@(v,a)[(ceil(v/a/70)>0:9)*42,'']

```

Inspired by @Luis Mendo's answer. Thanks to @pajonk for saving one byte.
> 2 votes

# Answer
# dc, ~~110 108 104~~ 98 bytes

This was a doozy since slicing isn't a thing. Also, dc doesn't manipulate strings. I just really was waiting for a string one that would be \< 5 hours of coding. On the plus side, I finally started writing down common constructs, like for loops. Also had to formulate rounding/ceiling, so thanks for that.

```
[42P]sd[dsi[li0!=dli1-dsi0!=L]dsLx]sl[Isi[li0!=dli1-dsi0!=L]dsLx]sg[1+]saIk/70*0k1~0!=adI>ldI!>gIP

```

Invoked in bash:

```
echo 'v a (above)'|dc
# Wholly:
>> echo '163 2 [42P]sd[dsi[li0!=dli1-dsi0!=L]dsLx]sl[Isi[li0!=dli1-dsi0!=L]dsLx]sg[1+]saIk/70*0k1~0!=adI>ldI!>gIP'|dc
# outputs:
**
>>

```

Replacing (above) with the code, and `v` and `a` with their respective counterparts above. The single quotes are important (otherwise you get bash's history stuff).

---

Explained:

```
[42P]sd   # Here we store a macro in register d to print 1 * without a newline

[dsi[li0!=dli1-dsi0!=L]dsLx]sl # Store the "less than" case, a for loop which
                        # uses the top-of the stack as it's number of iterations.
[Isi[li0!=dli1-dsi0!=L]dsLx]sg # Store the "greater than" case. It's the above,
                        # but it puts 10 on the stack to use instead.

[1+]sa # Store a macro to add 1 to whatever is the top-of-stack.

Ik # Set precision at non-zero to allow decimal division

/70* # Divide the top two of the stack, v/a; multiply by 70 (`/700*10` == `/70`)
             # dc is postfix and stack-based, so operators come after operands.

0k1~0!=a     # This is a ceiling function.
|> 0k  # set precision to 0 to perform integer division
|> 1~  # push the quotient of integer division by 1, and then the remainder. (r is top)
|> 0!=a # If the top-of-stack (decimal part) is not 0, add 1 to the quotient

dI>ldI!>g # Conditional statement
|> dI>l  # (d)uplicate the top, push 10 on. If 10 > the old top, execute the `l`ess-than
          # case, which loops top-of-stack times.
|> dI!>g # Complement of the above, using the `g`reater-than to loop 10 times.

IP # print a newline

```

This is probably more golf-able, but I was trying to get it finished to avoid premature optimization.

* 2 bytes saved by duplicating-saving instead of saving-loading
* 4 bytes saved dividing by 70
* 6 bytes from daniero's suggestions (non-strings, ASCII nums instead; 10 =\> I)
> 2 votes

# Answer
# Haskell, 35 bytes

This solution is as completely different from *Laikoni*s answer as it gets for something this trivial. Yet the score (for now) is exactly the same.

```
v%a=take(ceiling$v/a/70)[0..9]>>"*"

```

This produces ten stars, then shaves off some. Easy to extend to arbitrary difficulty with an infinite list.

I did manage to shave off one more byte. But while all test cases work, this shouldn't be correct in general.

```
v%a=take(1+div v(a*70))[0..9]>>"*"

```
> 2 votes

# Answer
# TI-Basic, 39 bytes

```
Prompt V,A
sub("**********",1,max(0,min(10,int(V/A/70)+1

```
> 2 votes

# Answer
# Vyxal, 9 bytes

```
/70/ṙ›\**

```

Try it Online!
> 2 votes

# Answer
## PowerShell v2+, 47 bytes

```
-join(('*'*11)[1..($args[0]/$args[1]/70+.499)])

```

Somewhat a port of @Neil's JavaScript answer.

Takes input `$args` and divides them, then divides that by `70`, and adds `.499`. Since PowerShell does banker's rounding, this is effectively `ceil` to two decimal points of precision. If additional precision is required, tack on as many additional `9`s as required.

Along with the `1..`, this forms a range index into a string. The string is `'*'*11`, i.e. `'***********'`. That results in a char-array, so we `-join` it together back into a string. That string is left on the pipeline and output is implicit. Like Neil's answer, this effectively "clamps" the output to be between 1 and 10 stars.

### Test Suite

```
PS C:\Tools\Scripts\golfing> @(@(163,2), @(548,22), @(1452,24), @(1713,37), @(4162,32), @(3067,15), @(22421,19))|%{($_-join', ')+" -> " +(.\difficulty-of-a-question $_[0] $_[1])}
163, 2 -> **
548, 22 -> *
1452, 24 -> *
1713, 37 -> *
4162, 32 -> **
3067, 15 -> ***
22421, 19 -> **********

```
> 1 votes

# Answer
# Python 3, ~~69~~ 68 bytes

I didn't want to copy the Python 2 answer, so mine is slightly longer.

```
from math import*
x=lambda v,a:print(max(0,min(ceil(v/a/70),10))*'*')

```

Saved 1 byte thanks to Program man
> 1 votes

# Answer
# Fourier, 46 bytes

All division in Fourier is integer division, so I just add one after division.

```
I*10/I/700^~X<0{1}{0~X}X>10{1}{10~X}X(42ai^~i)

```

**Try it online!**
> 1 votes

# Answer
## Actually, 14 bytes

```
:70a\\u9ukm'**

```

Try it online!

Takes advantage of the fact that 0 views and 0 answers is impossible, and thus `ceil(v/a) > 0`.

Explanation:

```
:70a\\u9ukm'**
:70             push 70 ([70 a v])
   a            invert stack ([v a 70])
    \\          integer division twice ([v//a//70])
      u         add 1 ([v//a//70 + 1])
       9uk      push 10, make stack into list ([[v//a//70+1, 10]])
          m     minimum of list
           '**  push "*", repeat

```
> 1 votes

# Answer
# PHP 5.6, 66 bytes

```
function a($v,$a){echo str_repeat('*',max(0,min(10,1+$v/$a/70)));}

```

First we simplify the equation to `v/a/70`. From there we add 1 since PHP will use this number as an integer for the `str_repeat`, essentially doing `abs($number+1)`. Then we use the hand-rolled `clamp` function of `max($min_number, min($max_number, $the_number))` to keep it between 1 and 10.

The `substr` version is a few bytes shorter (due to not having to have to build in the clamp functionality), but this one was more fun to make.
> 1 votes

# Answer
## Ruby, 47 35 bytes

```
f=->(v,a){'*'*((v/=a*70)<9?v+1:10)}

```

Called with `f.call(v,a)`

Saved 12 bytes thanks to user3334690, now the function implicitly returns the result.
> 1 votes

# Answer
# Ruby, 27 bytes

```
->v,a{(?**10)[1..(v/a/70)]}

```
> 1 votes

# Answer
# Perl 6: 32 bytes

As a lambda that takes two arguments:

```
{"*"x min 10,ceiling $^x/$^y/70}

```
> 1 votes

# Answer
# Add++, 17 bytes

```
L^,/70/i9b<"*"$yp

```

Try it online!

Not often I get to use the `^` flag in

## How it works

```
L^,		; Create a lambda that returns the stack joined
		; Example arguments:	[3067 15]
	/	; Divide;		[204.46]
	70/	; Divide by 70;		[2.921]
	i	; Floor;		[2]
	9b>	; Minimum with 9;	[2]
	"*"	; Push '*';		[2 '*']
	y	; Repeat with an extra;	['*' '*' '*']

```
> 1 votes

# Answer
# Jelly, 10 bytes

```
÷÷70Ċ«⁵”*x

```

Try it online!

## How it works

```
÷÷70Ċ«⁵”*x - Main link. Takes v on the left and a on the right
÷          - v ÷ a
 ÷70       - v ÷ a ÷ 70
    Ċ      - ⌈v ÷ a ÷ 70⌉
     «⁵    - min(⌈v ÷ a ÷ 70⌉, 10)
       ”*x - Repeat "*" min(⌈v ÷ a ÷ 70⌉, 10) times

```
> 1 votes

# Answer
## Batch, 81 bytes

```
@set/an=(700*%2-%1)/%2/70,n*=!(n^>^>31)
@set s=**********
@call echo %%s:~%n%%%

```

Port of my JavaScript answer, except that Batch uses integer arithmetic, so I wrote the formula as `(700*a-v)/a/70` which will truncate towards zero, and then the `n*=!(n^>^>31)` clears `n` if it is negative.
> 0 votes

# Answer
# Thunno 2, 10 bytes

```
/70/ṃ'*T×ɱ

```

Try it online!

#### Explanation

```
/70/ṃ'*T×ɱ  '# Implicit input
/            # Divide v by a
 70/         # Divide this by 70
    ṃ        # Take the ceiling
     '*T×   '# Push 10 asterisks
         ɱ   # Take that many characters
             # (with a maximum of 10)
             # from the string
             # Implicit output

```
> 0 votes

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


title: How long should my microwave run?

text:
# Question
Title: How long should my microwave run?
I'm hungry. Let's microwave something. Given a numerical input of between 1 and 4 digits, output the number of seconds that the microwave should run.

## Details

The trick is figuring out if the user is inputting seconds or a combination of seconds and minutes. The ones and the tens places should be interpreted as seconds and the hundreds and thousands places should be minutes. For example, the value `1234` should be interpreted as 12 minutes, 34 seconds and `9876` should be 98 minutes, 76 seconds. Typing `130` and `90` should both result in a cook time of 90 seconds.

Here are a few other inputs and outputs:

* 1 = 1
* 11 = 11
* 111 = 71
* 1111 = 671
* 9 = 9
* 99 = 99
* 999 = 639
* 9999 = 6039

## Rules

This is , so the shortest program in bytes wins. Standard loopholes are not allowed. The winning entry must return the right answer when given any integer input from 1 to 9999.

# Answer
# Python 2, 19 bytes

```
lambda t:t-t/100*40

```

Try it online!
> 28 votes

# Answer
# Japt, 6 bytes

```
ìL ì60

```

Test it online! `ìL` converts to base-100, and `ì60` converts back to base 60, resulting in `floor(n/100)*60 + n%100`. Also works with hours (`10000 -> 3600`, the number of seconds in an hour).
> 9 votes

# Answer
# Pyth - ~~9~~ 8 bytes

Converts input to base 100, then interprets that as a base 60 number.

```
ijQ*TT60

```

Test Suite.
> 8 votes

# Answer
# TI-Basic (83 series), 8 bytes

```
Ans-40int(sub(Ans

```

Requires OS version 1.15 or higher.
> 8 votes

# Answer
## C, C++, Java, C#, D : 36 bytes

### D : 35 bytes

### C : 28 bytes

First time i have an answer that short !

```
int r(int i){return i/100*60+i%100;}

```

D can have a special optimization because of the golfy template system :

```
T r(T)(T i){return i/100*60+i%100;}

```

C has a special optimization with the implicit int :

```
r(i){return i/100*60+i%100;}

```

Code to test

In **C** ( have to include `stdio.h` ) :

```
int main() {
    int testArr[] = {1,11,111,1111,9,99,999,9999};
    for(int i=0;i<8; ++i) {
        printf("%d = %d\n",testArr[i],r(testArr[i]));
    }
    return 0;
}

```

TIO Link

In **C++** ( have to include `iostream` ) :

```
int main() {
    std::initializer_list<int> testList{
        1,11,111,1111,9,99,999,9999
    };

    for (auto x : testList) {
        std::cout << r(x) << '\n';
    }
}

```

Try it online!

In **Java** :

```
public class MainApp {

    int r(int i){return i/100*60+i%100;}

    public static void main(String[]a) {
        MainApp m = new MainApp();
        int testArr[] = new int[]{
                1,11,111,1111,9,99,999,9999
        };

        for (int v : testArr) {
            System.out.println(v + " = " + m.r(v));
        }
    }
}

```

Try it online!

In **C#**

```
class Program {
    int r(int i){return i/100*60+i%100;}
    static void Main(string[] args) {
        var p = new Program();
        int[] testArr = new int[8]
        {
            1,11,111,1111,9,99,999,9999
        };
        foreach(int a in testArr) {
            Console.WriteLine(a + " = " + p.r(a));
        }
    }
}

```

In **D** ( have to import `std.stdio` ) ( exactly, i have no idea how to use arrays in D ) :

```
void main() {
    int[] arr = [1,11,111,1111,9,9,999,9999];
    for(int i = 0; i < arr.length; i++)
        writeln(arr[i]," = ",r(arr[i]));
}

```

TIO Link
> 7 votes

# Answer
## dc, 10 bytes

```
?9A~r60*+p

```

Try it online!

**Explanation:** in dc when you push sth. on the stack it goes on top

```
?         # read and push the input number on the stack
9A        # push 100: 9 * 10^1 + A[10] * 10^0 :D
~         # divide 2nd nr. by the top nr., push quotient, then remainder
r60*      # swap top 2 nr., then multiply the top by 60
+p        # add top 2 nr., then print result

```
> 6 votes

# Answer
# Bash bc + sed, ~~30~~ 28 bytes

*-2 bytes thanks to @seshoumara.*

```
bc<<<0`sed 's/..\?$/*60+&/'`

```

Try it online!

Takes input from stdin. Went for a more creative approach: inserts `*60+` before the last 1 or 2 digits, and prepends a `0` to the beginning to account for inputs with only 1 or 2 digits. The result is then passed to `bc`.
> 5 votes

# Answer
# Perl 5, 15+1(-p) bytes

```
/..$/;$_-=40*$`

```
* -l switch not counted because for tests readability

Try it online
> 4 votes

# Answer
# Jelly, 5 bytes

As a monadic link (thanks for the heads-up, caird!):

```
b³ḅ60

```

Try it online!

... Or as a full program:

```
bȷ2ḅ60

```

This can be ported easily to 05AB1E, so:

# 05AB1E, 5 bytes

```
тв60β

```

Try it online!

Simply converts the input integer to base **100** and then converts the result from base **60** to integer. Hence, it is equivalent to **Input % 100 + 60 * ⌊Input / 100⌋**
> 3 votes

# Answer
# C (gcc), 50 bytes

```
t;f(){scanf("%d",&t);printf("%d",t%100+t/100*60);}

```

Try it online!
> 3 votes

# Answer
# Java 8, 13 bytes

```
n->n-n/100*40

```

Port of *@ovs*' amazing Python 2 formula.

Try it here.
> 3 votes

# Answer
# PowerShell, ~~38~~ 33 bytes

<sup>-5 bytes thanks to mazzy</sup>

```
$args|%{$_-40*($_-replace'..?$')}

```

Try it online!

Uses the same formula popularizes by ovs. Truncating is still expensive in PowerShell. Now uses a better regex to instead rip the last one or two characters off to division.
> 3 votes

# Answer
# JavaScript, 21 bytes

```
a=>(a/100^0)*60+a%100

```

Try it online!
> 2 votes

# Answer
# , 12 bytes

```
-40*&<.%&100

```

It's ovs' Python 2 solution expressed in J. It consist of a hook and a fork:

```
┌─┬───────────────────────┐
│-│┌──┬────────┬─────────┐│
│ ││40│┌─┬─┬──┐│┌─┬─┬───┐││
│ ││  ││*│&│<.│││%│&│100│││
│ ││  │└─┴─┴──┘│└─┴─┴───┘││
│ │└──┴────────┴─────────┘│
└─┴───────────────────────┘

       %&100  - divides the number by 100
   *&<.       - finds the floor of the left argument and multiplies it to the left arg.
 40           -
-             - subtracts the result of the above fork from the input

```

Try it online!
> 2 votes

# Answer
## Batch, 23 bytes

```
@cmd/cset/a%1-%1/100*40

```
> 2 votes

# Answer
# Pushy, ~~10~~ 9 bytes

Kevin outgolfed me in my own language... (using the approach from ovs' answer)

```
2dH/40*-#

```

**Try it online!**

# 10 bytes

```
sjvj60*^+#

```

**Try it online!**

```
s             \ Split input into digits
 jvj          \ Join the first two and the last two
    60*       \ Multiply the first by 60
       ^+     \ Add the values
         #    \ Print

```

# 11 bytes

For one byte more we can use the `Input % 100 + 60 * ⌊Input / 100⌋` approach:

```
H2d%}/60*+#

```

**Try it online!**
> 2 votes

# Answer
# bash, 20 bytes

```
echo $[$1-$1/100*40]

```

Try it online
> 2 votes

# Answer
# Haskell, 18 bytes

```
f t=t-t`div`100*40

```

Try it online!

Anotha port.

## Pointfree solution, 21 bytes

```
(-)<*>(*40).(`div`40)

```
> 2 votes

# Answer
## Retina, 11 bytes

```
.{100}
60$*

```

Try it online!

Input and output in unary. The test suite converts from and to decimal for convenience.

Doing this kind of base conversion for only up to two digits is surprisingly simple to do in unary. We just match runs of 100 `1`s and replace them with 60 `1`s. Anything that's left over would correspond to the last two digits in the decimal representation and remains unchanged.
> 2 votes

# Answer
## Alice, 19 bytes

```
/o
\i@/.'d%~'d:'<*+

```

Try it online!

### Explanation

Too bad I removed *divmod* from the language, I guess...

```
/o
\i@/...

```

This is just the usual framework for linear programs with decimal I/O operating purely in Cardinal (arithmetic) mode.

```
.     Duplicate input.
'd%   Mod 100.
~     Swap with other copy.
'd:   Divide by 100.
'<*   Multiply by 60.
+     Add.

```
> 2 votes

# Answer
## Labyrinth, 19 bytes

```
?:_100%}#00/_60*{+!

```

Try it online!

### Explanation

```
?      Read input.
:      Duplicate.
_100%  Mod 100.
}      Move off to auxiliary stack.
#00/   Divide by 100, using the stack depth to get a 1, instead of _1.
_60*   Multiply by 60.
{+     Retrieve the earlier result and add it.
!      Print.

```

The IP then hits a dead end and starts moving backward. When it reaches the `/` it attempts a division by zero which terminates the program.
> 2 votes

# Answer
# Excel VBA, 29 Bytes

Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window.

```
?[A1]Mod 1E2+60*[Int(A1/100)]

```
> 2 votes

# Answer
# APL (Dyalog), ~~11~~ 10 bytes

```
60⊥0 100⊤⊢

```

Try it online!

**How?**

`0 100⊤` \- encode in base 100, stopping at the second LSB, effectively producing `n ÷ 100, n % 100`.

`60⊥` \- decode in base 60
> 2 votes

# Answer
# PARI/GP, 16 bytes

Straightforward:

```
n->n\100*60+n%100

```

Unfortunately this nice method is simply too long to use:

```
n->[60,1]*divrem(n,100)

```
> 2 votes

# Answer
# , 21 bytes

```
x=scan();x-x%/%100*40

```

Try it online!
> 2 votes

# Answer
# Common Lisp, 34 bytes

```
(lambda(n)(- n(*(floor n 100)40)))

```

Try it online!

Another port of @ovs' formula.
> 2 votes

# Answer
# Symbolic Python, ~~66~~ ~~48~~ 46 bytes

Thanks to Jo King for -16 bytes!

```
__=-~-~_-_
_-=_/(__<<__^__)**__*(__-~__<<-~__)

```

Try it online!

---

## Explanation

```
                      # input is initially in _
__=-~-~_-_            # set __ to (2+input-input) = 2
_-=                   # subtract from _:
   _/                 # _ divided by:
     (__<<__^__)**__  # (2<<2 ^ 2) ** 2 = (8^2)**2 = 100
    *                 # multiplied by
     (__-~__<<-~__)   # (2 - ~2 << -~2) = 5 << 3 = 40
                      # value in _ is the implicit output

```
> 2 votes

# Answer
# Husk, 7 bytes

```
B60B100

```

Try it online! Not very exciting, just converts to base 100 and back from base 60.
> 2 votes

# Answer
# GAP, 45 bytes

Try it online!

```
f:=function(t) return t-QuoInt(t,100)*40;end;

```
> 2 votes

# Answer
# Nibbles, 4 bytes (8 nibbles)

```
`@60`@@

```

```
    `@      # convert input in command-line arg to base
      @     # 100 (default value for @ when no input from STDIN)
`@          # and convert from base
  60        # 60

```
> 2 votes

# Answer
# Julia 1.0, 14 bytes

```
~x=x-x÷100*40

```

Try it online!

Uses the same algorithm as Misha Lavrov's TI-Basic solution.

Julia supports implicit multiplication (`40x` instead of `40*x`), but it takes precedence over most other operators.
> 2 votes

# Answer
# 05AB1E, 9 bytes

```
т÷60*¹т%+

```

Try it online!

Explanation:

```
т÷60*¹т%+

т         // Push number 100
 ÷        // Integer division with the input
  60      // Push number 60
    *     // Multiply with the previous result
     ¹    // Push input
      т   // Push 100 again
       %  // Modulo
        + // Add the first and the second result

```

Probably there is some trick with base conversions which can be achieved in 05AB1E, but I couldn't find it.
> 1 votes

# Answer
# Milky Way, 10 bytes

```
':Z/v40*-!

```

usage: `./mw code.mwg -i 9999`

## Explanation:

```
code       explanation                          stack

'          push input to stack                  [input]
 :         duplicate ToS                        [input, input]
  Z        push 100                             [input, input, 100]
   /v      integer division (divide and floor)  [input, ⌊input/100⌋]
     40    push 40                              [input, ⌊input/100⌋, 40]
       *   multiply                             [input, ⌊input/100⌋*40]
        -  subtract                             [input - ⌊input/100⌋*40]
         ! print

```
> 1 votes

# Answer
## REXX, 25 bytes

```
arg t
say t%100*60+t//100

```

(Just another translations of @ovs)
> 1 votes

# Answer
# 05AB1E, 7 bytes

```
т‰ć60*+

```

Try it online!

# Explanation

```
         command                              current stack
т‰ć60*+  full program. push input implicitly  [1234]
т        push 100                             [1234] [100]
 ‰       push divmod                          [12, 34]
  ć      push head extracted (n[1:], n[0])    [34] [12]
   60*   multiply by 60                       [34] [720]
      +  add and display implicitly           [754]

```
> 1 votes

# Answer
# Arturo, 16 bytes

```
$->t->t-40*t/100

```

Try it

Another port of ovs' Python answer.
> 1 votes

# Answer
# Rattle, 14 bytes

```
|s/100R1*40$-~

```

Try it Online!

# Explanation

```
|                  parse input
 s                 save input to memeory
  /100             divide by 100
      R1           convert to int
        *40        multiply by 40
           $       swap with value in memory
            -~     subtract value in memory from top of stack, print implicitly

```

# Rattle, 18 bytes

```
|s/100R1*60$%100+~

```

Try it Online!

There's probably some room to reduce the byte count if someone were to pass 100 as a hard-coded argument using `100&\|` instead of just `|`. Yes, that's a challenge!

# Explanation

```
|                         parse input
 s                        save input to memory slot 0 (also kept on top of the stack)
  /100                    divide by 100
      R1                  reformat to int (e.g. 1.52 -> 1)
        *60               multiply by 60
           $              swap value with the value in storage
            %100          mod 100
                +~        add this value to the value in storage, print implicitly

```
> 1 votes

# Answer
# Desmos, 20 bytes

```
f(x)=x-40floor(.01x)

```

Try it on Desmos!

Port of ovs's Python 2 answer
> 1 votes

# Answer
# SageMath, 29 bytes

Run it on SageMathCell!

```
def f(t):return t-(t//100)*40

```
> 1 votes

# Answer
# Thunno 2, 5 bytes

```
ɦB60ḋ

```

Try it online!

Port of Mr. Xcoder's Jelly answer

#### Explanation

```
ɦB60ḋ  # Implicit input
ɦB     # To base 100
  60ḋ  # From base 60
       # Implicit output

```
> 0 votes

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


title: Expand some number

text:
# Question
Title: Expand some number
This challenge is based on this Stackoverflow question.

With a positive number as input, output it as the sum of each digit multiplied by its power-of-10 representation.

## Input

A number, as an integer, a string or a list of digits/characters.

* The number will be strictly positive.
* If you accept the number as a string or list, it will not start with a `0`.

## Output

A string representing a sum of each relevant base-10 digits, each multiplied by its respective base-10 power. A sum is represented as `a + b`. You may use up to one space around each side of the `+` sign if you want. The operands are listed in descending order.

* `0` can never be a valid operand.
* The `+` sign (surrounded or not by spaces) may not be the leading or trailing part.

## Examples

```
Input       Output
12          10 + 2
         or 10+2
         or 10 +2
         or 10+ 2
9           9
123         100 + 20 + 3
10          10
101         100 + 1

```

## Invalid outputs

```
2           1 + 1
10          10 + 0
1           0 + 1
12          + 10 + 2
12          10 + 2 +
12          2 + 10

```

This is code-golf so the shortest code in bytes wins!

# Answer
## Python 3: ~~83~~ ~~80~~ 79 Bytes

Try It Online!

My first Code Golf submission.

```
t=input();x=len(t);print(*[t[i]+'0'*(x+~i)for i in range(x)if'0'<t[i]],sep='+')

```

-3 Bytes by ovs. Thank you for that useful tip :) -4 Bytes by mypetlion. Thank you for that shortening tip :)
> 11 votes

# Answer
# Jelly, 9 bytes

```
ḊƬḌQIAj”+

```

Try it online!

### How it works

```
ḊƬḌQIAj”+  Main link. Argument: A (digit array)

 Ƭ         Til; apply the link to the left until the results are no longer unique.
           Return all unique results.
Ḋ              Dequeue; discard the first element.
           For input [1,2,0,4], this yields [[1,2,0,4], [2,0,4], [0,4], [4], []].
  Ḍ        Undecimal; convert the digit arrays into integers.
           For input [1,2,0,4], this yields [1204, 204, 4, 4, 0].
   Q       Unique; deduplicate the resulting integers.
           For input [1,2,0,4], this yields [1204, 204, 4, 0].
    I      Increments; yield the forward differences.
           For input [1,2,0,4], this yields [-1000, -200, -4].
     A     Absolute value.
      j”+  Join with separator '+'.

```
> 11 votes

# Answer
# JavaScript (ES6), 47 bytes

Takes input as an integer.

```
f=(n,m=1,k=n%m)=>n-k?f(n-k,m*10)+(k?'+'+k:''):n

```

Try it online!

### Commented

```
f = (                     // f is a recursive function taking:
  n,                      //   n = number to process
  m = 1,                  //   m = modulo (a power of 10, starting at 1)
  k = n % m               //   k = n mod m
) =>                      //
  n - k ?                 // if n is not equal to k:
    f(n - k, m * 10)      //   do a recursive call with n - k and m * 10
    + (k ? '+' + k : '')  //   if k is not zero: append '+' and k
  :                       // else:
    n                     //   append n and stop recursion

```
> 8 votes

# Answer
# , 55 bytes

Assuming integers are all under 1e10, which is larger than the maximum 32 bit integer anyway...

```
function(n,p=10^(9:0),x=p*n%/%p%%10)cat(x[!!x],sep='+')

```

Try it online!
> 7 votes

# Answer
# Shakespeare Programming Language, ~~807~~ ~~806~~ ~~805~~ 804 bytes

```
,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy!Scene V:.Ajax:Remember the remainder of the quotient between I twice the sum of a cat a big big cat.You be the sum of you a cat.Ford:You be the quotient between you twice the sum of a cat a big big cat.Be you nicer zero?If solet usScene V.You be I.Scene X:.Ajax:Recall.Be you worse a cat?If solet usScene D.[Exit Ford][Enter Page]Ajax:Be you nicer zero?If sospeak thy.You be the sum of a big big big big cat the cube of the sum of a cat a big cat.[Exit Page][Enter Ford]Ajax:Open heart.Remember I.You zero.Scene L:.Ajax:Am I nicer a cat?If notlet usScene C.Open heart.Ford:You be the sum of you a pig.Let usScene L.Scene C:.Ajax:Recall.Ford:You be I.Scene D:.Ford:You be the sum of you a pig.Be you nicer zero?If solet usScene X.

```

Try it online!

*-23 bytes if a null character may be output first*

```
,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy!Scene V:.Ajax:Remember the remainder of the quotient between I twice the sum of a cat a big big cat.You be the sum of you a cat.Ford:You be the quotient between you twice the sum of a cat a big big cat.Be you nicer zero?If solet usScene V.You be I.Scene X:.Ajax:Recall.Be you worse a cat?If solet usScene D.[Exit Ford][Enter Page]Ajax:Speak thy.You be the sum of a big big big big cat the cube of the sum of a cat a big cat.[Exit Page][Enter Ford]Ajax:Open heart.Remember me.You zero.Scene L:.Ajax:Am I nicer a cat?If notlet usScene C.Open heart.Ford:You be the sum of you a pig.Let usScene L.Scene C:.Ajax:Recall.Ford:You be I.Scene D:.Ford:You be the sum of you a pig.Be you nicer zero?If solet usScene X.

```

## Explanation

```
,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]

    Boilerplate, introducing the characters.

Ford:Listen tothy!

    Input a value to Ajax.

Scene V:.Ajax:Remember the remainder of the quotient between I twice the sum of a cat a big big cat.You be the sum of you a cat.Ford:You be the quotient between you twice the sum of a cat a big big cat.Be you nicer zero?If solet usScene V.

    Push the digits of Ajax onto Ford's stack, and set Ford's value to be the number of digits in Ajax.

You be I.

    Store the number of digits in the input to Ajax.

Scene X:.Ajax:Recall.Be you worse a cat?If solet usScene D.

    Pop the next digit off the stack, and skip processing it if it equals 0.

[Exit Ford][Enter Page]Ajax:Be you nicer zero?If sospeak thy.You be the sum of a big big big big cat the cube of the sum of a cat a big cat.[Exit Page][Enter Ford]

    All characters start out with a value of 0.
    If Page is 0, that means this is the first number being processed, and we shouldn't output a plus.
    In either case, store the ASCII value of "+" to Page to output next time it is needed.

Ajax:Open heart.Remember I.You zero.

    Output the digit, save the remaining-digit-count for later, and store 0 to Ford for output purposes.

Scene L:.Ajax:Am I nicer a cat?If notlet usScene C.Open heart.Ford:You be the sum of you a pig.Let usScene L.

    Output one fewer 0 than the number of remaining digits to process.

Scene C:.Ajax:Recall.Ford:You be I.

    Store the remaining-digit-count back into Ajax.

Scene D:.Ford:You be the sum of you a pig.Be you nicer zero?If solet usScene X.

    Subtract 1 from the remaining-digit-count, and loop back until there are no more digits left to process.

```
> 7 votes

# Answer
# Python 2, 64 bytes

```
f=lambda s='',*x:s and(s>'0')*(s+'0'*len(x)+(f(*x)and'+'))+f(*x)

```

Try it online!

---

# Python 2, 66 bytes

```
f=lambda n,m=1:n>10and f(n/10,m*10)+(n%10>0)*('+'+`n%10*m`)or`n*m`

```

Try it online!
> 6 votes

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

```
J’⁵*Ṛ×ḟ0j”+

```

A full program accepting the number as a list of digits (in Python format) which prints the result.

**Try it online!**

### How?

```
J’⁵*Ṛ×ḟ0j”+ - Main Link: list of digits  e.g. [1,0,2,0,3,0]
J           - range of length                 [1,2,3,4,5,6]
 ’          - decrement (vectorises)          [0,1,2,3,4,5]
  ⁵         - literal 10                      10
   *        - exponentiate (vectorises)       [1,10,100,1000,10000,100000]
    Ṛ       - reverse                         [100000,10000,1000,100,10,1]
     ×      - multiply (vectorises)           [100000,0,2000,0,30,0]
      ḟ0    - filter discard zeros            [100000,2000,30]
        j”+ - join with '+'                   [100000,'+',2000,'+',30]
            - implicit (smashing) print       "100000+2000+30"

```

---

Previous @12 bytes:

```
Ḣ;0€ƊÐƤẸƇj”+

```
> 6 votes

# Answer
## Haskell, ~~60~~ 54 bytes

Edit: -6 bytes thanks to Delfad0r.

```
tail.(>>=('+':)).filter(>="1").scanr((.('0'<$)).(:))""

```

Takes the input number as a string.

Try it online!

```
    scanr(        )""    -- starting with the empty string fold from the right and
                         -- collect the intermediate results in a list
      (.('0'<$)).(:)     -- non pointfree: \d s -> d : ('0'<$s)
                         -- i.e. take the next digit 'd' and append the current result
                         -- from the scanr where each char is replaced by 0
                         --
                         -- e.g. "103" -> ["100","00","3"]
                         --
  f ilter(>="1")         -- keep only elements that have not a 0 as the first char
 (>>=('+':))             -- prepend a + to each element and flatten into
                         -- a single list
tail                     -- drop the first char, ie.e the leading +

```
> 5 votes

# Answer
# 05AB1E, 10 bytes

Straight forward implementation.
Input as list of digits.

```
āR<°*0K'+ý

```

Try it online!

**Explanation**

```
    *        # multiply each digits in the input with
āR<°         # 10^(len(input)-1-index)
     0K      # remove results that are zero
       '+ý   # merge on "+"

```
> 5 votes

# Answer
# Haskell, ~~56~~ ~~55~~ 52 bytes

-4 byte thanks to nimi.

```
tail.f
f('0':x)=f x
f(d:x)='+':d:('0'<$x)++f x
f x=x

```

Try it online!

---

**explanation**

```
g :: String -> String

-- drop the first char (the leading +) from f
g = tail.f

f :: String -> String

-- if the first digit is 0, continue with the rest of the number
f ( '0' :rest) = f rest

-- otherwise, add a +, the digit and as many 0s as there are digit in the rest.
f (digit:rest) = '+' : digit : ('0' <$ rest) ++ f rest

-- if there is no digit left, return the empty string
f "" = ""

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~82~~ ~~73~~ 71 bytes

*-9 bytes thanks to @ovs*

*-2 bytes thanks to @JonathanAllan*

```
lambda n:'+'.join(v+'0'*(len(`n`)-i)for i,v in enumerate(`n`,1)if'0'<v)

```

Try it Online
> 4 votes

# Answer
# Python 2, 64 bytes

```
lambda n:'+'.join(`b`+~e*'0'for e,b in enumerate(n,-len(n))if b)

```

An unnamed function which takes a list of digits, `n`, and returns a string.

**Try it online!**

`enumerate(n)` would yield tuples of `index, item` across `n` with an index starting at `0`.

However `enumerate` also takes an optional starting index as its second argument, by setting this to `-len(n)` we get indices (`e`s) of `-len(n)`, `-len(n)+1`, ..., `-1`.

This means the number of required trailing zeros for any item (`b`) is `-1-e`, which is `~e` so `~e*'0'` gets the required trailing zeros.

``b`` gets a string representation of the integer digit `b` and `+` concatenates this with those zeros.

`if b` filters out the entries with `b==0`.

`'+'.join(...)` then joins the resulting strings up with `+` characters.
> 4 votes

# Answer
# Perl 6, 38 bytes

```
{join '+',grep +*,($_ Z~[R,] 0 Xx^$_)}

```

Try it online!

Anonymous code block that takes a list of digits and returns a string.

### Explanation:

```
{                                    }  # Anonymous code block
                   $_ Z~   # Zip concatenate the list of digits with
                        [R,] 0 Xx^$_   # The correct number of 0s

          grep +*,(                 )  # Filter out all all the 0 values
 join '+',   # And join with '+'s

```
> 3 votes

# Answer
# Brachylog, ~~35~~ 32 bytes

```
l⟧₅;?z{tℕ₁I&h;10↔^;I×ṫ}ˢ;"+"zckc

```

-3 bytes cause 0 isn't a valid input

Try it online! or testsuite

# Explanation

```
                                    #   implicit input          eg  105
l                                   #   length of input             3
 ⟧₅                                 #   descending range ]n,0]      [2, 1, 0]
   ;?                               #   pair with input             [[2, 1, 0], [105]]
     z                              #   zip (considers numbers as array of digits)
                                    #                               [[2, 1], [1, 0], [0, 5]]
      {               }ˢ            #   select (map and filter)     [2, 1]  |   [1, 0]  |   [0, 5]
       t                            #       tail (last element)     1       |   0       |   5
        ℕ₁                          #       is at least 1           1       |   fail    |   5
          I                         #       store in I
           &h                       #       head of input           2       |           |   0
             ;10↔                   #       pair with 10 & reverse  [10, 2] |           |   [10, 0]
                 ^                  #       power                   100     |           |   1
                  ;I                #       pair with I             [100, 1]|           |   [1, 5]
                    ×               #       multiply                100     |           |   5
                     ṫ              #       to string               "100"   |           |   "5"
                        ;"+"        #   pair with "+"               [["100", "5"], "+"]
                            z       #   zip (cycles shorter)        [["100", "+"], ["5", "+"]]
                             c      #   concat (flattens)           ["100", "+", "5", "+"]
                              k     #   knife (remove last)         ["100", "+", "5"]
                               c    #   concat                      "100+5"

```
> 3 votes

# Answer
# APL(Dyalog), ~~46~~ ~~41~~ 40 bytes

```
{¯1↓∊{'0'=⊃⍵:⍬⋄⍵}¨⍵,¨('0'⍴⍨¨⌽⍳≢⍵),¨'+'}

```

*-5 bytes thanks to @dzaima*

Anonymous prefix function. Takes input as a string. TIO

(This is my first time using APL on PPCG, probably golfable. Also, curse you, zeroes!)
> 3 votes

# Answer
# Retina, 19 bytes

```
|'+L$`[1-9]
$&$.'*0

```

Try it online! Link includes test cases. Explanation:

```
L`[1-9]

```

List all non-zero digits

```
$
$&$.'*0

```

For each digit, append as many zeros as there were trailing digits.

```
|'+

```

Separate each result with `+`s instead of the default newline.

# Retina 0.8.2, 21 bytes

```
M&!`[1-9].*
\B.
0
¶
+

```

Try it online! Link includes test cases. Explanation:

```
M&!`[1-9].*

```

List all suffixes of the input that begin with non-zero digits.

```
\B.
0

```

Replace all trailing digits with zeros.

```
¶
+

```

Join the results with `+`s.
> 3 votes

# Answer
# C (gcc), 71 69 bytes

Each step of the recursive function subtracts the part that it will print and passes the rest of the number on.

Thanks to ceilingcat for the suggestion.

```
g(v,c,w){v&&printf("+%d"+!g(v-w,c*10)+!w*3,w=v%c);w=v;}f(v){g(v,10);}

```

Try it online!
> 3 votes

# Answer
# Brachylog v2, 15 bytes

```
~+bᵛ⁰↔;"+"zckwᵐ

```

Try it online!

Very, very inefficient.

Somehow, this manages to use only 6 bytes on what is in most languages the hard part (splitting the number into the form *a*10<sup>*b*</sup> where *a* is a single digit, in descending order), and a whole 9 bytes for the "join with `+`" (which is a builtin in most golfing languages, but not Brachylog).

Unlike most of my Brachylog submissions (which are functions), this one's a full program, taking input from standard input and producing output on standard output.

## Explanation

```
~+bᵛ⁰↔;"+"zckwᵐ
~+               Find an additive partition of the input number
   ᵛ               such that each component of the partition,
  b                when the first digit is removed
    ⁰              is equal to 0;
     ↔           reverse it,
      ;"+"z      pair every element with "+",
           c     flatten the resulting list one level,
            k    remove the last element (i.e. the final "+"),
             w   and print
              ᵐ  each remaining element.

```

(The reason `wᵐ` is used rather than the more normal `c` is that we're dealing with a heterogenous list – it contains both numbers and strings – and rather than allowing these to mix, it's simplest to just print them all individually.)

The algorithm here brute-forces over all additive partitions of the input until it finds a suitable one (!). Brachylog favours partitioning into fewer possibilities, and with the possibilities sorted in ascending order, so the first solution it will find is the reverse of the solution that the question is asking for. So we just have to reverse it to get the solution we want.
> 3 votes

# Answer
# Pip, 17 bytes

```
FI(REE,#a)*^aJ:'+

```

Attempt This Online!

### Explanation

Different approach from my earlier 21-byte answer in Pip Classic:

```
FI(REE,#a)*^aJ:'+
      ,#a          Range(length(input number))
    EE             10 to the power of each element of the range
   R               Reversed
  (      )*        Multiply each element of that list by
           ^a      The corresponding element in split(input number)
FI                 Filter, removing zeros
             J:'+  Join on the + character

```

(A similar approach would be 19 bytes in Pip Classic: `_FI(^a).RV0X,#aJ:'+`.)
> 3 votes

# Answer
# Canvas, ~~14~~ 13 bytes

```
Ａ⁸Ｌ²－＾×？²｝］+＊

```

Try it here!
> 2 votes

# Answer
# Clean, 73 bytes

```
import StdEnv,Text
$n=join"+"[rpad{c}(size n-p)'0'\\c<-:n&p<-[0..]|c>'0']

```

Try it online!

Defines the function `$ :: String -> String` taking a string and returning a string.
> 2 votes

# Answer
# Japt, 13 bytes

Takes input as an array of digits.

```
í*¡ApYÃw)f q+

```

Try it

---

## Explanation

```
í                 :Interleave
  ¡               :  Map input
   A              :    10
    p             :    To the power of
     Y            :    The current 0-based index
      Ã           :  End map
       w          :  Reverse
 *                :  Reduce each pair by multiplication
        )         :End interleaving
         f        :Filter (remove 0s)
           q+     :Join with "+"

```

---

## Alternative

Takes input as an array of digit strings.

```
ËúTUÊ-EÃfn q+

```

Try it
> 2 votes

# Answer
# Attache, 37 bytes

```
Join&"+"@{Id\`-&>Pairs[_'0]}@Suffixes

```

Try it online!

Pointfree version (41 bytes): `Join&"+"##`\&:Id##`-&>Pairs@`'&0@Suffixes`

## Explanation

```
Join&"+"@{Id\`-&>Pairs[_'0]}@Suffixes      input e.g.: 1203
                             Suffixes      take the suffixes of the input digit
                                           e.g.: [1203, 203, 3, 3]
         {                 }@              apply the inner lambda to the suffixes:
                       _'0                   append `0`
                                             e.g.: [1203, 203, 3, 3, 0]
                 Pairs[   ]                  generate the pairs of integers of the above
                                             e.g.: [[1203, 203], [203, 3], [3, 3], [3, 0]]
             `-&>                            subtraction over each pair
                                             e.g.: [1000, 200, 0, 3]
          Id\                                keep only truthy (nonzero) elements
                                             e.g.: [1000, 200, 3]
Join&"+"@                                  join the result by `+`
                                           e.g.: "1000+200+3"

```
> 2 votes

# Answer
# Powershell, ~~55~~ 52 bytes

```
$i=$args.Count;($args|%{$_+'0'*--$i}|?{+$_})-join'+'

```

Script expects an array of strings, each string contains one digit. Test script:

```
$f = {

$i=$args.Count;($args|%{$_+'0'*--$i}|?{+$_})-join'+'

}

@(
    ,('10','1','0')
    ,('10+2','1','2')
    ,('9','9')
    ,('100+20+3','1','2','3')
    ,('100+1','1','0','1')
) | % {
    $e, $a = $_
    $r = &$f @a
    "$($e-eq$r): $(-join$a)=$r"
}

```

Output:

```
True: 10=10
True: 12=10+2
True: 9=9
True: 123=100+20+3
True: 101=100+1

```
> 2 votes

# Answer
# C (gcc), 87 bytes

```
j;k;f(x){for(j=1;j<x;j*=10);for(;k=x*10/j*j/10%j,j/=10;)k&&printf("%d%c",k,j-1?43:10);}

```

Try it online!
> 2 votes

# Answer
# Java 10, ~~82~~ 78 bytes

```
n->f(n,1)Object f(int n,int m){return m<n?f(n-n%m,m*10)+(n%m>0?"+"+n%m:""):n;}

```

Port of *Arnauld*'s JavaScript (ES6) answer.
-2 bytes thanks to *@ceilingcat*.
-2 bytes thanks to *Arnauld*.

Try it online.

**Explanation:**

```
n->                      // Method with int parameter & Object return-type
  f(n,1)                 //  Call the recursive method with `n` and 1

Object f(int n,int m){   // Recursive method with 2 int parameters & Object return-type
  return m<n?            //  If `m` is smaller than `n`:
          f(n-n%m,m*10)  //   Do a recursive call with `n-n%m` and `m` multiplied by 10
          +(n%m>0?       //   And if `n` is not divisible by `m`:
            "+"          //    Append a "+"
            +n%m         //    As well as `n%m`
           :             //   Else:
            "")          //    Append nothing more
         :               //  Else:
          n;}            //   Simply return the input `n`

```
> 2 votes

# Answer
# Brainfuck, 147 bytes

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

```

Try it online! (You will have to tick the box marked "!" and type your input after the "!" on the second line of the code otherwise it will continue asking for inputs forever.)

Its probably not going to be the shortest answer or golfed to the shortest it could be but it was pretty fun to try and do this in Brainfuck so I might as well post it.

As @JoKing pointed out, this program does not remove 0's. I will try and fix this but it might be quite hard.

**Explanation:**

```
>>+[[<]>+[>],]                            Takes inputs and records the amount of them
-[>+>+<<-----]>--->--------               Sets the next 2 cells to 48 (0) and 43 (plus)
<<<[<]>---                                Returns to the start and corrects the number of inputs
                                          Loop
[[<+<+>>-]<[>+<-]>>.                      Prints the first number
<<<[>>[>]>.<<[<]<-]                       Prints the correct number of 0's
>>[>]>>.                                  Prints plus
<<<[<]>                                   Returns to the first cell
>>[<[-]>[<+>-]>]>[<+>-]>[<+>-]<<<<[<]>-]  Removes the first number and shifts everything up by one to make the second number the first
                                          Loops until on last number
>.                                        Prints last number

```
> 2 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~134~~ ~~133~~ 129 bytes

```
	N =INPUT
	S =SIZE(N) - 1
V	N LEN(X) LEN(1) . V	:F(O)
	O =GT(V) O V DUPL(0,S - X) '+'
	X =X + 1	:(V)
O	O ARB . OUTPUT RPOS(1)
END

```

Try it online!

Saved a whole byte by doing string processing rather than arithmetic!
> 2 votes

# Answer
# sed -E, ~~109~~ ~~99~~ ~~97~~ ~~75~~ 74 bytes

```
h;s:.:0:g;G
:l;s:.(.*)\n(.)(.*)\+?(.*):\1\n\3+\4\2\1:;tl
s:\+0+::g;s:..?::

```

Each line of the input is considered a separate number. Try it online.

### Explanation:

```
h;                                           | copy the original string to the temporary buffer
  s:.:0:g;                                   | substitute all digits with zeroes
          G                                  | append the original string to the substituted one
                                             |
:l;                                          | main loop start
   s:.(.*)\n(.)(.*)\+?(.*):\1\n\3+\4\2\1:;   | cut the next digit from the number, append with zeroes and add to the back
                                          tl | loop if the substitution hasn`t converged yet
                                             |
s:\+0+::g;                                   | remove all zero terms
          s:..?::                            | remove \n and the first +, if any

```

…can be golfed futher, I presume.
> 2 votes

# Answer
# MathGolf, ~~12~~ ~~11~~ 10 bytes

```
hrzúm*ç'+u

```

Try it online!

## Explanation

The first command is not needed as input can be given as a list of digits.

```
(▒           Convert to a list of digits)
 h           Get length of input list without popping
  r          Push range(a)
   z         Reverse sort
    ú        Map i -> 10**i for each element in list
     m*      Element-wise multiplication
       ç     Filter faulty items in list
        '+   Push "+"
          u  Join with separator

```

I might add a pairwise multiplication operator that is one byte, but that's not currently part of the language. Then I could remove one byte from this solution.
> 2 votes

# Answer
# APL (Dyalog Unicode), 20 bytes

```
{⍵'+'⍺}/0~⍨(10×⊢)\∘⌽

```

Try it online!

Takes input as a vector of digits. Outputs with a space before and after each `+`, and includes a variable amount of leading spaces.

This is a train. It is divided into the following.

```
  ┌───┴───┐
  /     ┌─┼──┐
┌─┘     0 ⍨  ∘
{⍵'+'⍺} ┌─┘ ┌┴┐
        ~   \ ⌽
          ┌─┘
       ┌──┼─┐
       10 × ⊢

```

The first function is , this reverses the array, so `1 0 2` becomes `2 0 1`.

Then we come into `(10×⊢)\`, which is applied to the reversed array. This part is inspired by ngn's answer to the Boustrophedonise challenge. Borrowing ngn's explanation, given a vector of digits `A B C ...`, applying `(10×⊢)\` on this vector gives the following.

```
A (A (10×⊢) B) (A (10×⊢) (B (10×⊢) C)) ...
A ((10×⊢) B) ((10×⊢) (10×C)) ...
A (10×B) (10×10×C) ...

```

On `2 0 1`, `(10×⊢)\` gives `2 0 100`.

Next comes `0~⍨`. This removes all `0`s from the array, giving `2 100`.

Finally comes the `+`s. `{⍵'+'⍺}/` is a reduction that starts from the right that concatenates the left arg with a `+`, followed by the right arg. Effectively, this reverses the array while inserting `+`s. This gives `100 '+' 2`, which is displayed as `100 + 2`.
> 2 votes

# Answer
# Vyxal, 8 bytes

```
ẏṘ↵*ꜝ\+j

```

Takes input as a list of digits.

Try it online, or verify all test cases.

Explanation:

```
   *       # Multiply each digit in the input by the corresponding value in:
ẏ          # the range from 0 to the length of the input
 Ṙ         # reversed
  ↵        # with each value mapped to 10^n.
    ꜝ      # Remove falsey values.
     j     # Join on
       \+  # "+"

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 58 bytes

```
StringRiffle[ToString/@(NumberExpand[#]/.(0->Nothing)),"+"]&

```

In Use:

```
In[101]:= StringRiffle[ToString /@ (NumberExpand[#] /. (0 -> Nothing)), "+"] &[101]
Out[101]= "100+1"

```
> 1 votes

# Answer
## BASH, ~~86~~ 83 bytes

Try it online!

```
for((t=$1;++m<${#1};t=10#$g)){
g=${t#?}
b+=${t/$g}${g//?/0}+;}
a=$b$t
echo ${a//+0}

```
> 1 votes

# Answer
# Pip, 21 bytes

```
W+:axPB['+POa0Ma];@>x

```

Takes input as a command-line argument. Try it online!

### Explanation

Partially inspired by nimi's Haskell answer.

```
                       x is empty string; a is 1st cmdline arg (implicit)
W                      While loop
 +:a                    Loop condition: a, after unary + is applied in-place
                         Unary + adds 0 to a number, with the side effect of converting it to
                         standard numerical form; in this case, that means eliminating leading zeros
                        Inside the loop, we know that a is nonzero and has no leading zeros
       [        ]       Construct a list containing the following items:
        '+               A + character
          POa            Pop the first character from a (leaving a one character shorter)
             0Ma         Map 0 to a, giving a list of 0's with the same length as a
                        E.g. if a was 123, the list is ["+" 1 [0 0]] and a becomes 23
    xPB                 Push this list to the back of x
                        Since x is a string, PB will cast the list to a string and append it to x
                        The default list -> string format is to concatenate all the items, so in
                        the above example, x will have "+100" appended
                 ;     Required for parsing
                  @>x  Take all but the first character of x and autoprint it

```

---

Here's a less creative map-and-filter approach, also 21 bytes:

```
_FI_*t**BMZaRV,#aJ:'+

```

Try it online!

I tried a few ways to golf this, but ran into parsing problems that forced me back up to 21. Quite possibly there's a shorter way to do it.
> 1 votes

# Answer
## Python 3, 114 bytes

```
s,n=[],input()
[s.append(("+"+n[-i-1]+"0"*i)*(int(n[-i-1])>0))for i in range(len(n))]
print("".join(s[::-1])[1:])

```

Try it online!
> 1 votes

# Answer
# brainfuck, 116 bytes

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

```

Try it online!

### Explanation:

```
--->-[<+>-----]     Push 48
Tape: 48 0'
>,[>,]<[<]          Get all inputted digits
Tape: 48 0' digits
>[                  Loop over each digit
  Tape: 48 0 d' igits
  <<[->+>-<<]       Subtract 48 from the digit
  Tape: 0' 48 d-48 igits
  >>[               If the digit is not a zero
     [>]>[          Check if the flag is set
        [<]>-----.  Subtract 5 from the 48 to print a plus
        +++++[>]    Restore the 48
     ]
     <[->+<<+>]     Restore the 48 and the first digit
     Tape: 48 0' d igits
     >.,            Print and remove the first digit
     Tape: 48 0 0' igits
     >[             For each of the remaining digits
        [-<+>]      Move it over one
        <[<]<.      Print a zero
        >>[>]>      Move to the next digit
     ]
     Tape: 48 0 digits? 0 0'
     ,+<<[<]        Set the plus flag
     Tape: 48 0' digits? 0 1
  ]
  Tape: 48 0' digits?
>]

```
> 1 votes

# Answer
# MBASIC, 131 bytes

```
1 INPUT N$:N=VAL(N$):FOR P=LEN(N$)-1 TO 0 STEP -1:T=10^P:X=INT(N/T):G=X*T
2 IF G>0 THEN PRINT G;:N=N-G:IF N>0 THEN PRINT"+";
3 NEXT P

```

Input a number as a string, allowing us to walk it's length, subtracting power of 10 multiples as we go.

```
? 12
10 + 2

? 9
9

? 123
100 + 20 + 3

? 10
10

? 101
100 + 1

```
> 1 votes

# Answer
# PHP, 89 bytes

```
<?for($i=0;$i<$l=strlen($a=$argv[1]);$i++)echo$a[$i]?($i?"+":"").$a[$i]*10**($l-$i-1):"";

```

Try it online!
> 1 votes

# Answer
# Ruby, 55 bytes

```
->n{w=-1;(n.digits.map{|x|x*=10**w+=1}-[0]).reverse*?+}

```

Try it online!
> 1 votes

# Answer
# Thunno 2, 9 bytes

```
Żre×0o'+j

```

Try it online!

Note: `0o` could also be `æ;` or `Dị`.

#### Explanation

```
Żre×0o'+j  '# Implicit input
Żr          # Push (length..0]
  e         # Ten power of each
   ×        # Multiply with input
    0o      # Remove zeros
    æ;      # OR truthy items only
    Dị      # OR filter by itself
      '+j  '# Join by "+"
            # Implicit output

```
> 1 votes

# Answer
# Ruby `-pl`, 47 bytes

```
gsub(/.(?=.)/){$&+?0*$'.size+?+}
gsub /\+0+/,''

```

Attempt This Online!
> 1 votes

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


title: Make a polyglot generator

text:
# Question
Title: Make a polyglot generator
A polyglot is a program that runs in several languages.

Your challenge is to:

Choose at least two languages (Different versions count as different languages)

Create a program or function that takes several positive integers (one for each language you chose) and returns a program that:

Is a valid program in all of those languages

When run in language A, outputs the first number; When run in language B, outputs the second number; etcetera. Exiting by error is allowed, as long as the generated program prints the number first

The generator does not need to be in one of your chosen languages.

You can assume the inputted numbers within your chosen languages' limits. For example, if BF is one of your languages, the number for BF will be at most 255.

### UPDATE

Explicitly checking the version number or implementation of the language is forbidden. To differentiate, use differences in language features.

# Scoring

Your score is \[code length\] / \[number of languages\]2.

Example:

Let's say you were using JS/Python 3, in a JS program:

```
(x,y)=>`1//1;'''
console.log(${x})
//''';print(${y})`

```

Your score would be \\$\frac{53}{2^{2}}\\$ = 13.25.

The lower your score, the better.

# Answer
## Backhand, Turtlèd, Gol\>\<\>, \>\<\>, Pushy, Wumpus, Fission, Beeswax, Emoji, Emotinomicon, AsciiDots, Cardinal, Befunge-93, Functoid, Alice, Befunge-98, Klein, PingPong, Whispers v1 and v2, Thue, Perl, Raku, Rail, Self-modifying Brainfuck

### Score: ~~3.04 1.3 0.934 0.693 0.605~~ \\${\frac{295}{25^2} = 0.472}\\$

```
puts'#\ v/v"Z"rH"Z"y"#"Z"#>o<~"`Z"#!
  # Z#ZOi@R"Z"Y#_`Z`;[Z➡Z⏪⏬⏩.-$_"Z"x%"Z"
[ #< >Ov"Z"0_F1"Z".# @#
 #\ @=.}#"Z">
]; #@  >:#,##_@#1"Z"
#\"Z"@
# <#/.
#-10\Z
"
> 0.0
> Z
> Z
>> Output 2
x::=~Z
::=
x
";
$-|\'main\';print (Z)&&Z
#\-[Z]o]<-[<-]>[+.>]Z'.gsub(?Z){$*.pop}

```

Try it online! or Try them all at once!

My personal constraints were to only use languages where the number can be placed in without modification, which are represented by each of the `Z`s. Ruby is used just as a simple formatter to insert the numbers. A typical output using the numbers 1-25 looks like:

```
#\ v/v"25"rH"24"y"#"23"#>o<~"`22"#!
  # 21#20Oi@R"19"Y#_`18`;[17➡16⏪⏬⏩.-$_"15"x%"14"
[ #< >Ov"13"0_F1"12".# @#
 #\ @=.}#"11">
]; #@  >:#,##_@#1"10"
#\"9"@
# <#/.
#-10\8
"
> 0.0
> 7
> 6
>> Output 2
x::=~5
::=
x
";
$-|'main';print (4)&&3
#\-[2]o]<-[<-]>[+.>]1

```

Explanations coming soon...
> 17 votes

# Answer
# Python 3, 167 bytes, produces Python 3.0, 3.1, ..., 3.9, 3.10, \\${167 \over 11^2}\approx1.38\\$

thanks to SuperStormer for refreshing my memory, allowing to add 3.10.

```
lambda r:'try:exec("%s");o=%d\nexcept:0\n'*10%sum(zip("0;int.bit_length;callable;u'';import enum;b''%();f'';breakpoint;(a:=0);{}|{}".split(';'),r),())+'print(o)'

```

Try it online!

This works by trying to evaluate expressions code that rely on new language features and updating the output value if successful. By including more subversions, the score could probably be decreased by quite a bit.

| Version | Code | New Language feature |
| --- | --- | --- |
| 3.1 | `int.bit_length` | New builtin |
| 3.2 | `callable` | New builtin |
| 3.3 | `u''` | Old syntax for unicode strings re-added from Python 2 |
| 3.4 | `import enum` | New module called `enum` |
| 3.5 | `b''%()` | String formatting with `%` for bytes objects |
| 3.6 | `f''` | *f-strings* |
| 3.7 | `breakpoint` | New builtin function |
| 3.8 | `(a:=0)` | Assignment expressions |
| 3.9 | `{}|{}` | Dictionary union with `|` |
| 3.10 | `a:x=0` | postponed evaluation of annotations is now enabled by default |
> 17 votes

# Answer
# Jelly =\> py 2, py 3, Jelly, Vyxal, Brain-Flak: 2.28

```
“1or"”©Ɠ“,Q"
”“£Ỵġcȯ9VĊƤ¿»⁶¹;¹⁾or⁶¹;⁸⁾)
®“(1)”Ɠẋ@Ø(j“"
”⁵

```

Try it online!

## Explanation

Taking `{α}`, `{β}`, `{γ}` as command line arguments and `{δ}` and `{ε}` from STDIN:

```
1or"{δ},Q"
print(1/2and {α}or {β})
1or"((1)(1)...(1))"
{γ}

```

In Python 2, `1or"{δ},Q"` is an expression and doesn't do anything. The second line prints the number. Since `1/2` is `0` in Python 2, `1/2and {α}` yields `0`, and `or {β}` makes that yield `{β}`. Finally, `{γ}` is an expression and does nothing.

In Python 3, the only difference with Python 2 is that `1/2` is `0.5`, so `1/2and {α}` yields `{α}`, and `or {β}` has no effect since the value is positive and therefore truthy.

In Jelly, each line is a link, and only the last link gets evaluated, so `{γ}` is returned and automatically outputted.

In Vyxal, `1` pushes `1`, `o` pops `a,b` and pushes `a.replace(b, "")` which happens to not error here, `r` does a regex match if the arguments are strings, which also doesn't error, and `"` pairs the top to values, which also doesn't error. Here, Vyxal automatically supplying zeroes when the stack is too small is very convenient. Then, `{δ}` pushes `{δ}`, `,` prints it, and finally `Q` exits the program, and thus the rest of the code doesn't matter.

In Brain-Flak, only brackets matter. The `()` in the print function call don't matter. The main part is `(()()...())` with `{ε}` `()`s in between. This pushes `{ε}` to the stack which gets output. Nothing else is brackets so this is fine.

The `1or` is needed otherwise Jelly complains that `"`, a quick, has no atoms to pop from the command stack, even though the link isn't called. Same goes for `'`, though Vyxal also has a meaning for that that wouldn't work with this idea.

The `(1)` is needed otherwise Jelly complains that `)`, which ends a chain and maps over it, has nothing to pop because `(` seems to just yeet the whole chain. Thus, `1` satisfies Jelly.
> 9 votes

# Answer
# Vyxal , =\> Grok, 05AB1E, brainfuck, Vyxal, tcsh, ;#, Vim, Jelly \- ~~.7778~~ ~~.7755~~ ~~.6719~~ 46 bytes / 82 = .71875

```
\I?\Z?\q\+?*‛. ?`,|echo `?\#\;?*`#dH`?\¶?

```

Try it Online!

Resulting programs: Grok, 05AB1E, brainfuck, Vyxal, tcsh, ;#, Vim, Jelly

In brainfuck and ;#, the output is a character, as allowed by this meta post.

Also, ;# only supports \\$7\\$-bit numbers, so any number higher than \\$127\\$ will be output modulo \\$127\\$.
> 9 votes

# Answer
Not quite sure its correctness, since I don't have all environment installed to test this... So I would just mark this answer non-competitive unless someone may test its correctness

# JavaScript (ES6) =\> ES3, AS, ES5, ES6, ES7, ES8, ES9, ES10, ES11, ES12, 166/102=1.66 (non-competitive)

```
a=>`function f(){return[${a}][[].removeAt?0:9-![].map-![].fill-![].includes-!''.padEnd-!(this.Promise||f).prototype['finally']-![].flat-!''.matchAll-!''.replaceAll]}`

```

Input an array with 10 elements... Output is source of a function...
> 7 votes

# Answer
# PHP =\> MY-BASIC, PHP 7, PHP 5, PHP 8, Perl 4, Perl 5, : 111 bytes

## Score: 111 / 36 = 3.08

```
fn($a,$b,$c,$d,$e,$f)=>"\$n.=\"$a\";
print \$n.''&0+true?0==''?eval('return 1<=>2;')?$b:$c:$d:(-1**2+1?$e:$f);"

```

Try it online!

**Code generated with 1, 2, 3, 4, 5, 6:**

```
$n.="1";
print $n.''&0+true?0==''?eval('return 1<=>2;')?2:3:4:(-1**2+1?5:6);

```

Relies on my usual trick, `true` added to a numeric value is `1` in PHP but is ignored by perl. And in Perl 4, negation operator `-` takes precedence over exponentiation `**` while in Perl 5 it is the contrary.

Quick answer, I'll try to add languages or shorten the generator later..

**EDIT**: -1 byte, the last `;` is not necessary for an arrow function definition, it belongs to the assignment to the header's variable (moved to footer)

**EDIT 2**: -1 byte by removing the round brackets for `print` and using a space, works in both languages

**EDIT 3**: added MY-BASIC language using these tricks:

* `.` seems to be a valid character for variables names in MY-BASIC, while it's the concatenation operator in PHP and Perl. Allows at the same time to declare a value for `$n.` in MY-BASIC and `$n` for the others (by concatenation to the undefined var). Double quotes are needed here because of the next point.
* `'` is the single line comment in MY-BASIC, so the rest of the line is ignored after the var output
* for the other languages, it concatenates an empty string and then we remove the value of `$n` so that the value is zero like before the edit (thank you, loose types languages!)

**EDIT 4**: taking in account the inputs are positive integers, I removed the single quotes for PHP and Perl

**EDIT 5**: added distinction between PHP 5, 7 and 8:

* `0==''` was true before PHP 8
* the spaceship operator `<=>` didn't exist before PHP 7. An `eval` is needed here, not only for PHP 5 not to throw a parse error, but for Perl versions also, where you can eval any incorrect code without errors. The `return` keyword allows to have a return value for the `eval` call in PHP
* `$n.''-$n` caused an arror in PHP 8, which cannot subtract strings anymore, and was replaced by `$n.''&0` which is actually shorter
> 4 votes

# Answer
# Js =\> Js, Python 3, Python 2, Deadfish~, Deadfish x, brainfuck - Score \\$\frac{118}{36} = 3.278\\$

I wanted to have a go too!

```
(x,y,z,d,X,b)=>`1//1;'''${'i'.repeat(d)}oh${'x'.repeat(X)}k
_=>${x}
//''';print(1/2and ${y}or ${z})#${'+'.repeat(b)}.

```

Ok, the generated code will look something like this, where `{a}` to `{f}` are the inputs:

```
1//1;'''{'i'*{d}}oh{'x'*{e}}k
_=>{a}
//''';print(1/2and {b}or {c})#{'+'*{f}}.

```

And let's pick it apart.

```
1//1;'''{'i'*{d}}oh{'x'*{e}}k
_=>{a}
//''';print(1/2and {b}or {c})#{'+'*{f}}.

```

This is the standard JS/Python polyglot structure. Everything except the `_=>{a}` and the 1 at the top (which is a NOP anyway) are ignored.

```
1//1;'''{'i'*{d}}oh{'x'*{e}}k
_=>{a}
//''';print(1/2and {b}or {c})#{'+'*{f}}.

```

In Python, `//` is an operator, so we can just add a NOP expression, followed by a multiline string so all the JS stuff is ignored. The difference is (copied from hyper) that 1/2 in python 2 is 0, but in Python 3 it is 0.5, which is truthy.

In Deadfish~, the only bit that matters is the `i`s at the start, followed by `oh`. `i` increments the accumulator, `o` prints it and `h` halts the program.

Deadfish X is basically the same, but with `x` and `k`, and no halt. Fortunately, it's not like any `k`s are going to show up in the rest of the program, so we should be safe.

Finally, for brainfuck, there's a string of plusses appended to the end, along with a `.` to print. This outputs by charcode, because numbers are a pain.

Try it online!

Try All The Test Cases Online!
> 4 votes

# Answer
# Retina, 28 bytes, produces Retina or Retina 0.8.2, score 7

```
^
¶
,
$*_
$
$$$*1¶\d+\$*.¶¶.

```

Try it online! Explanation: For an example input of `3,4` the following program is produced:

```

3*_4$*1
\d+\*.

.

```

The first stage operates differently in the two versions. In Retina, `*` is the repetition operator while `$*` is a quoted `*`, while in Retina 0.8.2, `*` is a literal and `$*` is the repetition operator. The result in Retina is therefore `___4*1` while in Retina 0.8.2 it is `3*_1111`.

The second stage simply deletes the `*`, the preceding number, and the following character.

The final stage counts the number of characters remaining, which gives the desired result.
> 2 votes

# Answer
# Zsh =\> Zsh, Bash, Ruby, Python, 51 bytes, score 3.1875

```
<<Q
'\';print $1||echo $2 #'
0and p($4)or print($3)

```

Try it online!

* `<<Q` essentially just prints the rest of the file, but `$1` to `$4` are replaced by the input values.

The generated polyglot looks like:

```
'\';print 1||echo 2 #'
0and p(4)or print(3)

```
* In Zsh and Bash, backslashes don't work in single-quotes, so what gets executed is `print 1||echo 2`:
    + In Bash, there is no `print`, so the command fails. `||` means "if this command failed, then execute the following one", so `echo 2` gets executed instead
    + In Zsh, `print 1` just gets executed and doesn't fail
* In Python and Ruby, `0and p(4)or print(3)` is what gets executed
    + In Ruby, `0` is truthy, so `p(4)` gets executed
    + In Python, `0` is falsey, so `print(3)` gets executed
> 1 votes

# Answer
# Python 3 Julia 1.0 =\> Julia 1.0 and Python 3, 32 23 bytes, score 8 5.75

*Solution by MarcMush using Julia's custom syntax:*

```
a$b="print([$a,$b][1])"

```

Try it online!

*My previous score 8 solution:*

```
f=lambda*a:"print([%s,%s][1])"%a

```

Try it online! Julia uses 1-based indexes and Python uses 0.
> 1 votes

# Answer
# JavaScript =\> JavaScript (V8), Python 3, Python 2, Foo - ~~57~~ 56 bytes, ~~3~~ 4 languages = 3.5

*Thanks to The Thonnu for -1 byte!*

```
(x,y,z,w)=>`print( ${x}//${x/y}if 1/2else ${z}#"${w}"
)`

```

Try it online!

Examples for the numbers 1, 2, 3, and 4:

```
print( 1//0.5if 1/2else 3#"4"
)

```

JavaScript (1) Python 3 (2) Python 2 (3) Foo (4)
> 1 votes

# Answer
# Python 3 =\> Python 3, Python 2, Befunge-93; 67 bytes =\> \\$\frac{67}{3^2}\\$=7,4444444444...

```
lambda x,y,z:f'\'v\';print(1/2 and {x} or {y})\n#<v"{z}"\n# >:#,_@'

```

Try it online!

Upon giving input to the function above (`12`, `34` and `56` used as an example), we will get something like the following:

```
'v';print(1/2 and 12 or 34)
#<v"56"
# >:#,_@

```

First off is Python 3. It ignores the string at the start, then because `1/2` results in `0.5`, `1/2 and 12` will output `12`, and `or`ring with `34` still results in `12` so it gets printed. The rest of the lines are comments.

Then is Python 2, in which the only thing that changes is that `1/2` evaluates into `0`, so `0 and 12` results in `0` and `or`ring with `34` results in `34`, which gets printed.

Then is Befunge-93, where it takes the `v` (single quotes are not an instruction, only double quotes are) and then the `<`, which leads to push mode-ing `65` and then a simple printing loop which leads into `@` and ends the program.
> 0 votes

---
Tags: code-challenge, polyglot, code-generation
---