title: My Squiggly Lamp

text:
# Question
Title: My Squiggly Lamp
While moving, I broke my lamp. Now, I need a new one. It's your job to make me a lamp! I'm not sure what size I want, though I know I want a squiggly one.

Your program/function must take in a number input, and print out a lamp with that many squiggles/bumps.

**Examples:**

Input:`2`

Output:

```
/--\
 ()
 ()
/__\

```

Input:`3`

Output:

```
/--\
 ()
 ()
 ()
/__\

```

Input:`5`

Output:

```
/--\
 ()
 ()
 ()
 ()
 ()
/__\

```

**Rules:**

* 0 & negative numbers don't matter
* To give the lamps (an this challenge) more of a variety, you **must** change the lamp shade.
    + They must be **4** characters wide and **1** character high.
    + They can be in any shape, including non-lamp-shade shapes.
    + They must not contain whitespace.
    + The base must stay the same.
* You must show an example input & output with your lamp shade.
* Shortest code wins!

# Answer
# Pyth - 16 bytes

Uses quotes for the shade since N is preinitialized to that.

```
*N4VQ+d`();"/__\

```

Try it online here.

```
* 4            String repetition 4x, implicit print
 N             Preinitialized to Quote
VQ             For N in range(Q)
 +             String concat
  d            Space
   `()         Repr of empty tuple
;              Close for loop
"/__\          Implicitly print string, implicit close quote

```

Sample for 5:

```
""""
 ()
 ()
 ()
 ()
 ()
/__\

```
> 5 votes

# Answer
# Snowman 0.2.0, 42 chars

```
)vg10sB]"[--]
"sP:" ()
"sP;bR"/__"sP92wRsP

```

Sample run:

```
llama@llama:...Code/snowman/ppcg53483lamp$ snowman lamp.snowman
5
[--]
 ()
 ()
 ()
 ()
 ()
/__\

```

So I only noticed that I forgot to implement the ability to escape backslashes within strings when I solved this challenge. That's definitely going to be a thing in the next version, but for now, here's what I did to print the final line:

```
"/__"sP92wRsP

```

`92` is the ASCII code for a backslash, `wR` wraps it in an array, and I can now print it with `sP` because "strings" in Snowman are actually just arrays of numbers.
> 7 votes

# Answer
# \>\<\>, ~~43~~ ~~41~~ 38 bytes

```
"\__/"aiv
"&-1v!?:<&a" ()
~"!_\
?!;o>l

```

Input via a code point, e.g. space is 32. This uses part of the program's own code as the lampshade, resulting in something that looks like a satellite dish:

```
~\_!
 ()
 ()
 ()
 ()
 ()
/__\

```

*(Suggestion thanks to @randomra)*

For three more bytes, we can change the third line to add a bit more customisation:

```
"\__/"aiv
"&-1v!?:<&a" ()
__\"\~"/
?!;o>l

```

This produces one of those lamps which shoot light upwards, for lack of a better way of putting it:

```
\__/
 ()
 ()
 ()
 ()
 ()
/__\

```
> 3 votes

# Answer
# R, ~~54~~ ~~52~~ 46 bytes

```
cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n")

```

In this version, **input** and **output** are almost mixed together :

**{in/out}PUT :**

```
> cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n")
1: 4
2:
Read 1 item
RRRR
 ()
 ()
 ()
 ()
/__\

```

*EDIT 1* : **-2** bytes thanks to @manatwork comment.
*EDIT 2* : **-6** bytes. Full credit goes to @manatwork again
> 3 votes

# Answer
## Straw, 26 bytes (non-competing)

```
<#~('--'
)>( ()
)-*>(/__\)>

```

Use `'--'` as lamp shade, ~~take input in unary~~ now in decimal
> 3 votes

# Answer
# CJam, 18 bytes

```
"/__\
"" ()
"ri*1$

```

Sample run for input 5:

```
/__\
 ()
 ()
 ()
 ()
 ()
/__\

```

Try it online here
> 2 votes

# Answer
# JavaScript ES6, 34 bytes

```
i=>`|==|
${` ()
`.repeat(i)}/__\\`

```

The newlines are significant

Example with input of 5:

```
|==|
 ()
 ()
 ()
 ()
 ()
/__\

```
> 2 votes

# Answer
# sed, 28 bytes

```
s#.# ()\n#g
s#^\|$#/__\\\n#g

```

Takes input in unary. The shade is the obvious selection (same as the base).

### Test run

```
$ echo -n 111 | sed -f lamp.sed
/__\
 ()
 ()
 ()
/__\

```
> 2 votes

# Answer
# 05AB1E, ~~17~~ ~~15~~ ~~13~~ 11 bytes

```
„ (и„/_.ø)˜∞

```

-2 bytes (17 → 15) thanks to *@EriktheOutgolfer*.
-2 byte (13 → 11) after being inspired by *@dzaima*'s Canvas answer.

Cap is the same as the base (`/__\`).

**Explanation:**

```
„ (            # Literal string " ("
   и           # Repeat " (" the input amount of times
               #  i.e. " (" and 3 → [' (',' (',' (']
    „/_        # Literal string "/_"
       .ø      # Surround the list of " (" with "/_" on both ends
               #  i.e. [' (',' (',' ('] → ['/_',[' (',' (',' (',' ('],'/_']
         ˜     # Flatten this list
               #  i.e. ['/_',[' (',' (',' ('],'/_'] → ['/_',' (',' (',' (','/_']
          ∞    # Mirror each item
               #  i.e. ['/_',' (',' (',' (','/_'] → ['/__\',' () ',' () ',' () ','/__\']
               # And output the list new-line delimited (implicitly due to the mirror)

```

---

**Old 13 bytes answer:**

```
„/_D„ (Iиs)˜∞

```

Try it online.
> 2 votes

# Answer
# 1+, 114 bytes

```
11+""*+"*";";";;1.1##(A|11+""""**+;)"""*"**;""*""*+*";1+;"\"1+/<1+#(A)11+"*(|1+"1+")1+*+;1()"*"1+*++";;1()*"1+*+;

```

You all! Stop complaining about the length, this is the best I could do! Go blame Parcly Taxel for designing such a bowly language!

Shade is `$$$$`.
> 2 votes

# Answer
# Python 2, 36 bytes

```
print"-"*4+"\n ()"*input()+"\n/__\\"

```

For input 4:

```
----
 ()
 ()
 ()
 ()
/__\

```

Note that for Python that any lamp shade using pipes is a byte less.

-1 bytes thanks to @Alex!
> 1 votes

# Answer
# jq: 30 characters

(29 characters code + 1 character command line option.)

```
8888,(range(.)|" ()"),"/__\\"

```

Sample run:

```
bash-4.3$ jq -r '8888,(range(.)|" ()"),"/__\\"' <<< 3
8888
 ()
 ()
 ()
/__\

```

On-line test (Passing `-r` through URL is not supported – check Raw Output yourself.)
> 1 votes

# Answer
# Gema: 30 characters

```
*=gema\n@repeat{*;\ ()\n}/__\\

```

Sample run:

```
bash-4.3$ gema '*=gema\n@repeat{*;\ ()\n}/__\\' <<< 3
gema
 ()
 ()
 ()
/__\

```
> 1 votes

# Answer
# C, 54 bytes

Call `f()` with the desired height of the lamp.

```
f(n){for(puts("||||");n--;puts(" ()"));puts("/__\\");}

```

Try it on ideone.

Example output for 5:

```
||||
 ()
 ()
 ()
 ()
 ()
/__\

```
> 1 votes

# Answer
## Pyke, 15 bytes

```
" ()"~mQAD"/__\

```

Try it here!

```
     ~m         - 1000
" ()"           -  " ()"
       QAD      - duplicate(^) input times
          "/__\ - "/__\"

```

Outputs:

```
1000
 ()
 ()
/__\

```
> 1 votes

# Answer
# PowerShell 5.1, ~~28~~ 26 Bytes

Thanks Mazzy for 2 bytes

```
8008;," ()"*"$args";"/__\"

```

Since the shade can be any 4 characters, using a number saves a pair of quotes. The hardest part was finding a nice looking shade.

Output:

```
PS C:\Users\ItsMe\Desktop> .\scratch.ps1 4
8008
 ()
 ()
 ()
 ()
/__\

```
> 1 votes

# Answer
# Kotlin, 36 bytes

```
{"|MM|\n${" ()\n".repeat(it)}/__\\"}

```

Try it online!
> 1 votes

# Answer
# Canvas, 8 bytes

```
(×_¶/ｅ⟳║

```

Try it here!

Explanation:

```
(×        repeat "(" input times
  _¶/e    encase it on both sides in "_\n/"
          the 1st line is surrounded in "_" and the second ends and starts with "/"
      ⟳   rotate the string clockwise without changing characters
       ║  palindromize horizontally with 0 overlap

```
> 1 votes

# Answer
# Whitespace, 169 bytes

```
[S S S N
_Push_0][T  N
T   T   _Read_STDIN_as_integer][S S S T S T T   T   S S N
_Push_92_\][S S S T S T T   T   T   T   N
_Push_95__][S N
S _Duplicate_95__][S S S T  S T T   T   T   N
_Push_47_/][N
S S N
_Create_Label_LOOP][S S S N
_Push_0][T  T   T   _Retrieve_at_address_0][S S S T N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][S S S N
_Push_0][S N
T   _Swap_top_two][T    T   S _Store_at_address_0][N
T   T   S N
_If_neg_Jump_to_Label_PRINT][S S S T    S T S N
_Push_10_newline][S S S T   S T S S T   N
_Push_41_)][S S S T S T S S S N
_Push_40_(][S S S T S S S S S N
_Push_32_space][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S S S T    S T S N
_Push_10_newline][S S S T   S S S S T   N
_Push_33_!][S N
S _Duplicate_33_!][S N
S _Duplicate_33_!][S N
S _Duplicate_33_!][N
S S T   N
_Create_Label_LOOP_2][T N
S S _Print_as_character][N
S N
T   N
_Jump_to_Label_LOOP_2]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

Pushes all characters in reversed order to the stack, and then prints them in a loop.

```
Integer i = STDIN as input
Push "\__/" to the stack
Start LOOP:
  i = i - 1
  if(i is negative):
    Go to function PRINT
  Push "\n)( " to the stack
  Go to next iteration of LOOP

function PRINT:
  Push "\n!!!!" to the stack
  Start LOOP_2:
    Print top as character to STDOUT
    Go to next iteration of LOOP_2

```

NOTE: `i` in the pseudo-code above is stored back in the heap in every iteration of `LOOP`, because we don't want to leave it on the stack to be printed at the end.
> 1 votes

# Answer
# Excel, 31 bytes

An anonymous worksheet function that takes input as a numeric from range `[A1]` and outputs to the calling cell.

This lamp is musical - and will help to liven and lighten up your day.

```
="/\
"&REPT(" ()
",A1)&"/__\"

```

### Output
> 1 votes

# Answer
# Japt, 17 bytes

```
Æ` ()`Ãi¥² p"/__\

```

Try it online!

Output for `5` is:

```
====
 ()
 ()
 ()
 ()
 ()
/__\

```
> 1 votes

# Answer
# MAWP, ~~65~~ 61 bytes

```
@95W2M!;2A!!;;2W2M;[25W;84W;85W!;1M;1A]25W;95W2M!;2W1M!!;;3A;

```

I'm sure it can be golfed by a few more bytes when displaying characters.

Try it!
> 1 votes

# Answer
# Vyxal `j`, 15 bytes

```
×d?(‛ ()‛/_WvøṀ

```

Try it Online!

Example output:

```
****
 ()
 ()
 ()
 ()
/__\

```

I kinda golfed the shade.

```
×d              # two asterisks
  ?(   )        # Input times...
    ‛ (         # Push the two-char ` (`
        ‛/_     # Push the two-char `/_`
           W    # Push the entire stack
            vøṀ # Ascii-art mirror each item.

```
> 1 votes

# Answer
## Pascal, 118 characters

Strings consist of `char` values. The available `char` values beyond the bare minimum (i. e. necessary to write Pascal language elements) are implementation-defined. Provided that all `char` values present are available in your implementation, you can write:

```
program p(input,output);var l:integer;begin
read(l);writeLn('‥〜');for l:=1 to l do
writeLn(' ()');write('/__\')end.

```

Input:

```
4

```

Output (pun intended):

```
‥〜
 ()
 ()
 ()
 ()
/__\

```

This lamp grants you a wish if you rub it.
> 1 votes

# Answer
# SWI-Prolog, ~~73~~ 60 bytes

```
a(X):-write(golf),writef("%r",["\n ()",X]),write("\n/__\\").

```

`a(5).` outputs

```
golf
 ()
 ()
 ()
 ()
 ()
/__\

```
> 0 votes

# Answer
# Julia, 36 bytes

```
n->print("|~~|\n"*" ()\n"^n*"/__\\")

```

This creates an unnamed function that takes an integer as input and prints to stdout.

Example:

```
julia> f(4)
|~~|
 ()
 ()
 ()
 ()
/__\

```
> 0 votes

# Answer
# Java ~~7~~ 11, ~~84~~ ~~83~~ 37 bytes

```
n->"i!!i\n"+" ()\n".repeat(n)+"/__\\"

```

Try it online. (NOTE: Java 11 isn't supported on TIO yet, so `String.repeat(int)` has been emulated with `repeat(String,int)` for the same byte-count.)

Uses `i!!i` as cap. `¡!!¡` looks better, but is two bytes more.

**Explanation:**

```
n->                    // Method with integer parameter and String return-type
  "i!!i\n"             //  Return the cap + new-line
  " ()\n".repeat(n)    //   appended with " ()" and a new-line `n` amount of times
  "/__\\"              //   append with "/__\"

```
> 0 votes

# Answer
# PyMin, 24 bytes / 17 characters

```
»ƒ+ѿ+" ø\n"*¬+ɓ+ѿ

```

Output for 5:

```
Fizz
 ()
 ()
 ()
 ()
 ()
Buzz

```

Shorter version with `v0.5`:

### 21 bytes / 13 characters

```
»ƒƜ+" ø¶"¯+ɓƜ

```
> 0 votes

# Answer
## Neoscript, 28 bytes

```
{n|"[~~]
"+" ()
"*n+"/--\\"}

```
> 0 votes

# Answer
## Bash + coreutils, 37 bytes

```
yes ' ()'|sed '1i####
'$1'{a/__\\
q}'

```

The newlines are necessary and counted in the bytes total. GNU sed is required.

**Run:**

```
./squiggly_lamp.sh 2

```

**Output:**

```
####
 ()
 ()
/__\

```
> 0 votes

# Answer
## Ruby, 42 bytes

```
i=gets.to_i
puts "|--|\n#{" ()\n"*i}/__\\"

```
> 0 votes

# Answer
# Noether, 26 bytes

```
"-"4*P?I(" ()"P?!i)"/__\"P

```

**Try it online!**
> 0 votes

# Answer
# Ahead, 38 bytes

```
I"|MM|"Wr
~W" ()"oN<s!:-1~
@W"/__\"oN<

```

Try it online!

## Samples

```
1
|MM|
 ()
/__\

2
|MM|
 ()
 ()
/__\

3
|MM|
 ()
 ()
 ()
/__\

```
> 0 votes

# Answer
## Perl 5, 24 bytes

```
$_=$<.'
 ()'x$_.'
/--\
'

```

Try it online!

Uses `1000` as the cap.
> 0 votes

# Answer
# Befunge-93, 50 bytes

```
"\__/"&v
0-1_v#:<g00" ()"*25p0
*25$<>:#,_@#::::"_"

```

Try it online!

Example with Input 3

```
____
 ()
 ()
 ()
/__\

```
> 0 votes

# Answer
# PHP, 38 bytes

```
/--\<?while($argn--)echo"
 ()"?>

/__\

```

Save to file; run as pipe with `-nF` or try it online.
> 0 votes

# Answer
# Charcoal, ~~16~~ ~~12~~ 10 bytes

```
8Ｅ⊕Ｎ(←_/‖Ｍ

```

-4 bytes thanks to *@ASCII-only*.
-1 byte thanks to *@Neil* by using a `Map`.

Try it online (verbose) or try it online (pure).

Uses `8()8` as cap, but the `8` can be any character from Charcoal's code-page that isn't used as a command/operator.

**Explanation:**

Print `8`:

```
Print("8");
8

```

Print `(` the `input+1` amount of times downwards:

```
Print(Map(Incremented(InputNumber()), "("));
Ｅ⊕Ｎ(

```

Then after that print `_/` in a left direction:

```
Print(:Left, "_/");
←_/

```

And finally mirror everything vertically:

```
ReflectMirror();
‖Ｍ

```
> 0 votes

# Answer
# Brain-Flak, 164 bytes

```
({}<((((((((((()()){}()){})()){}()){}())){}()))[[]]()){({}<>)<>}<>>()){({}[()]<(((((((()()){}()){}){}){}())[()])[(()()()()){}])((()()()()()){})>)}(((({}{}{}{}{}))))

```

Try it online!

Output for `5`:

```
{{{{
 ()
 ()
 ()
 ()
 ()
/__\

```
> 0 votes

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


title: Product over a range

text:
# Question
Title: Product over a range
Your task is simple: given two integers \\$a\\$ and \\$b\\$, output \\$\Pi\[a,b\]\\$; that is, the product of the range between \\$a\\$ and \\$b\\$. You may take \\$a\\$ and \\$b\\$ in any reasonable format, whether that be arguments to a function, a list input, STDIN, et cetera. You may output in any reasonable format, such as a return value (for functions) or STDOUT. \\$a\\$ will always be less than \\$b\\$.

Note that the end may be exclusive or inclusive of \\$b\\$. I'm not picky. ^\_^

## Test cases

```
[a,b) => result
[2,5) => 24
[5,10) => 15120
[-4,3) => 0
[0,3) => 0
[-4,0) => 24

[a,b] => result
[2,5] => 120
[5,10] => 151200
[-4,3] => 0
[0,3] => 0
[-4,-1] => 24

```

---

This is a , so the shortest program in bytes wins.

---

## Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=66202,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 38 votes
# Jelly, 2 bytes

```
rP

```

Takes two numbers as command line arguments. Try it online.

Note that this is inclusive range. For the cost of a byte (3 bytes), we can make this exclusive:

```
’rP

```

Try it online. Note that the arguments must be given in the order `b a` for this version.

## Explanation

### Inclusive

```
a rP b
  r   dyadic atom, creates inclusive range between a and b
   P  computes product of the list

```

### Exclusive

```
b ’rP a
  ’   decrement b (by default, monadic atoms in dyadic chains operate on the left argument)
   r  range
    P product

```

# Answer
> 34 votes
## ArnoldC, ~~522~~ 511 bytes

First post on codegolf !

I had fun doing this. Exclusive range.

```
LISTEN TO ME VERY CAREFULLY f
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE a
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE b
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE r
YOU SET US UP 1
HEY CHRISTMAS TREE l
YOU SET US UP 1
STICK AROUND l
GET TO THE CHOPPER r
HERE IS MY INVITATION r
YOU'RE FIRED a
ENOUGH TALK
GET TO THE CHOPPER a
HERE IS MY INVITATION a
GET UP 1
ENOUGH TALK
GET TO THE CHOPPER l
HERE IS MY INVITATION b
LET OFF SOME STEAM BENNET a
ENOUGH TALK
CHILL
I'LL BE BACK r
HASTA LA VISTA, BABY

```

Explanations (Thanks Bijan):

```
DeclareMethod f
        MethodArguments a
        MethodArguments b
        NonVoidMethod
        DeclareInt r
        SetInitialValue 1
        DeclareInt l
        SetInitialValue 1
        WHILE l
                AssignVariable r
                        SetValue r
                        MultiplicationOperator a
                EndAssignVariable
                AssignVariable a
                        SetValue a
                        + 1
                EndAssignVariable
                AssignVariable l
                        SetValue b
                        > a
                EndAssignVariable
        EndWhile
        Return r
EndMethodDeclaration

```

# Answer
> 21 votes
## Python, 30 bytes

```
f=lambda a,b:a>b or a*f(a+1,b)

```

Inclusive range. Repeatedly multiplies by and increments the left endpoint, until it is higher than the right endpoint, in which case it's the empty product of 1 (as True).

# Answer
> 18 votes
## Minecraft 15w35a+, program size 456 total (see below)

This calculates `PI [a,b)`. Input is given by using these two commands: `/scoreboard players set A A {num}` and `/scoreboard players set B A {num}`. Remember to use `/scoreboard objectives add A dummy` before input.

Scored using: `{program size} + ( 2 * {input command} ) + {scoreboard command} = 356 + ( 2 * 33 ) + 34 = 456`.

This code corresponds to the following psuedocode:

```
R = 1
loop:
  R *= A
  A += 1
  if A == B:
    print R
    end program

```

Download the world here.

# Answer
> 14 votes
## TI-BASIC, 9 bytes

```
Input A
prod(randIntNoRep(A,Ans

```

Takes one number from `Ans` and another from a prompt.

Also 9 bytes, taking input as a list from `Ans`:

```
prod(randIntNoRep(min(Ans),max(Ans

```

# Answer
> 12 votes
## Python 2, ~~44~~ 38 bytes

```
lambda l:reduce(int.__mul__,range(*l))

```

Pretty much the obvious anonymous function answer.

EDIT: Thanks to xnor for saving 6 bytes with some features I didn't know.

# Answer
> 10 votes
## Pyth, 5 bytes

```
*FrQE

```

Pyth doesn't have product, so we reduce * over the range.

Uses exclusive range.

# Answer
> 10 votes
# R, 22 bytes

```
function(a,b)prod(a:b)

```

# Answer
> 8 votes
# Mathematica, 15 bytes

```
1##&@@Range@##&

```

A shorter solution that only works for non-negative integers:

```
#2!/(#-1)!&

```

# Answer
> 8 votes
# JavaScript (ES6), 34 bytes

```
(a,b)=>eval("for(c=a;a<b;)c*=++a")

```

Sometimes the simplest answer is the best! Just a `for` loop inside `eval`. Inclusive range.

# Answer
> 7 votes
# Japt, 7 bytes

Easy challenges like this are always fun. :)

```
UoV r*1

```

Try it online!

### Explanation

```
UoV r*1  // Implicit: U = first input, V = second input
UoV      // Generate range [U,V).
    r*1  // Reduce by multiplication, starting at 1.

```

Wow, this seems pathetic compared to the other answers so far. I need to work on Japt some more...

# Answer
> 6 votes
## Seriously, 4 bytes

```
,ixπ

,         Read list [a,b] from stdin
 i        Flatten it to a b
  x       Pop a,b, push range(a,b)
   π      Pop the list and push its product.

```

Hex Dump:

```
2c6978e3

```

Try it online

# Answer
> 6 votes
## CJam, ~~6~~ ~~19~~ ~~18~~  10 bytes

Thanks to Dennis and RetoKoradi for help with golfing!

```
q~1$-,f+:*

```

Try it online

Takes input as `a b`. Calculates `PI [a,b)`.

*Note: this program is 6 bytes long, and only works if `a` and `b` are positive.*

```
q~,>:*

```

Try it online

Takes input as `a b`. Calculates `PI [a,b)`.

# Answer
> 6 votes
# Prolog, 45 bytes

**Code:**

```
p(A,B,C):-A=B,C=A;D is A+1,p(D,B,E),C is A*E.

```

**Explained:**

```
p(A,B,C):-A=B,      % A is unifiable with B
          C=A       % Unify C with A
          ;         % OR
          D is A+1, % D is the next number in the range
          p(D,B,E), % Recurse on the range after the first element
          C is A*E. % The result C is the product of the first element and the result
                      of the recursion

```

**Example:**

```
p(5,10,X).
X = 151200

p(-4,-1,X).
X = 24

```

# Answer
> 6 votes
## Octave, 15 bytes

```
@(a,b)prod(a:b)

```

Straightforward. Uses the inclusive range.

# Answer
> 6 votes
## Haskell, ~~19~~ 17 bytes

```
a#b=product[a..b]

```

Usage example: `2#5`-\> `120`.

# Answer
> 5 votes
# Julia, 16 bytes

```
f(a,b)=prod(a:b)

```

Note: if the range object `a:b` (which is literally stored as a start value and a stop value, and internally includes a "increment by 1 on each step" value) is permitted as the input, then just 4 bytes are required: `prod`.

# Answer
> 5 votes
# Bash + GNU utilities, 13

```
seq -s* $@|bc

```

Assumes there are no files in the current directory whose names start with `-s`. Start and end (inclusive) are passed as command-line parameters.

This simply produces the sequence from start to end, separated by `*`, then pipes to `bc` for arithmetic evaluation.

# Answer
> 5 votes
# C, 32 bytes

For `[a,b)`:

```
f(a,b){return a-b?a*f(a+1,b):1;}

```

For `[a,b]` (On Katenkyo's suggestions, 32 bytes again) :

```
f(a,b){return a<b?a*f(a+1,b):b;}

```

# Answer
> 5 votes
# MATL, 4 bytes

Inclusive Range

```
2$:p

```

**Try it online!**

### Explanation

```
2$: % Implicitly grab two input arguments and create the array input1:input2
p   % Take the product of all array elements

```

Thanks to @Don Muesli for helping me get the hang of this whole MATL thing.

# Answer
> 5 votes
## JavaScript (ES6), 22 bytes

I can't believe none of us JS golfers thought to use recursion...

```
a=>F=b=>a-b?b*F(b-1):a

```

Assign to a variable with e.g. `var q = a=>F=b=>a-b?b*F(b-1):a`, then call like `q(2)(5)`.

# Answer
> 5 votes
# Brachylog, 3 bytes

```
⟦₃×

```

Try it online!

Input is passed as `[A,B]`. The range is exclusive of B, but could be made inclusive by replacing the  with .

# Answer
> 4 votes
# Jolf, 4 bytes

Try it here!

```
OrjJ
  jJ two inputs
 r   range between them [j,J)
O    product

```

# Answer
> 4 votes
# Ruby, 22 bytes

```
->i,n{(i..n).reduce:*}

```

**Ungolfed:**

```
-> i,n {
  (i..n).reduce:* # Product of a range
}

```

**Usage:**

```
->i,n{(i..n).reduce:*}[5,10]
=> 151200

```

# Answer
> 4 votes
## PowerShell, 30 Bytes

```
param($a,$b)$a..$b-join'*'|iex

```

Takes input as two integers, creates a range with `..`, then `-join`s that with asterisks, pipes it into `Invoke-Expression` (similar to `eval`). The range operator in PowerShell is inclusive.

Pretty competitive with non-golfing languages.

# Answer
> 4 votes
# 05AB1E, 2 bytes

Code:

```
ŸP

```

Explanation:

```
Ÿ   # Inclusive range [input, ..., input]
 P  # Total product of the list
    # Implicit printing top of the stack

```

# Answer
> 4 votes
# J, 8 bytes

```
[:%/!@<:

```

### Usage

```
>> f =: [:%/!@<:
>> f 10 5
<< 15120

```

where `>>` is STDIN and `<<` is STDOUT.

### Explanation

It computes `∏[a,b]` as `(b-1)!/(a-1)!`.

```
minus_one =: <:
factorial =: !
of        =: @
monadic   =: [:
division  =: %/
f =: monadic division factorial of minus_one

```

## Previous 13-byte version

Written when I had no idea what `J` even is :p

```
*/(}.[:>:i.)/

```

Usage:

```
   */(}.[:>:i.)/ 5 10
30240

```

Explanation:

```
*/            NB. multiply over
  (
   }.         NB. remove [the first x items] from
     [:>:     NB. increment all of
         i.   NB. the numbers from 0 to [y-1]
           )
            / NB. insert the above code into the following numbers

```

Detailed explanation:

```
i.10 would produce 0 1 2 3 4 5 6 7 8 9

>:i.10 would make it 1 2 3 4 5 6 6 7 8 9 10

the [: is used to make the ">:" take only one argument (a monad)
because if it takes two arguments, it is a different function.
so [:>:i.10 becomes 1 2 3 4 5 6 7 8 9 10

}. means take away the first [x] items from the following list,
so 5}.1 2 3 4 5 6 7 8 9 10 becomes 6 7 8 9 10

the two slashes "/" in the code are actually the same
for example, */6 7 8 9 10 becomes 6*7*8*9*10

```

# Answer
> 4 votes
# APL (Dyalog Extended), ~~8~~ 3 bytesSBCS

```
×/…

```

Try it online!

range

`×/` multiplication across

This is an "atop" so `a(×/…)b` is `×/a…b`.

# Answer
> 4 votes
# , 21 bytes

*Thanks to Dominic van Essen for helping me brainstorm input methods.*

```
prod((a=scan()):a[2])

```

Uses inclusive range. Try it online!

### Explanation

```
      a=scan()         Read the two inputs as a vector and assign it to a
     (        ):       Use a as the lower end of a range (R interprets this as "use the
                        first element of the vector" by default)
                a[2]   Use the second element of a as the upper end of the range
prod(               )  Take the product of all numbers in the range

```

# Answer
> 4 votes
# Desmos, 19 bytes

```
f(a,b)=∏_{n=a}^bn

```

Try it on Desmos!

# Answer
> 3 votes
## Minkolang 0.14, 7 bytes

```
nnL$*N.

```

Try it here.

### Explanation

```
nn         Takes two numbers from input
  L        Pops b,a and pushes a..b
   $*      Product the whole stack
     N.    Output as number and stop.

```

# Answer
> 3 votes
# Python, 52 bytes

Very simple code; a bit too long.

```
def p(a,b):
 t=1
 for i in range(a,b):t*=i
 return t

```

# Answer
> 3 votes
# JavaScript (ES6), ~~45~~ 41 bytes

*Saved 4 bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ*

```
(a,b)=>[...Array(b-a)].reduce(x=>x*a++,1)

```

Seems a little too long...

```
(a,b)=>           // Define an anonymous function that takes parameters a and b, and returns:
[...Array(b-a)]   // An array of b-a items,
.reduce(          // Reduced by
x=>x*a++          //  multiplying each item with the previous,
,1)               //  starting at 1.

```

# Answer
> 3 votes
## Perl 6, 14 bytes

```
{[*] $^a..$^b}

```

usage:

```
my &code = {[*] $^a..$^b}
say code |$_ for (2,5),(5,10),(-4,3),(0,3),(-4,-1);
# 120
# 151200
# 0
# 0
# 24

say chars code 1,10000;
# 35660

```

If you wanted to exclude the last element use `..^` instead of `..`

# Answer
> 3 votes
# gs2, 4 bytes

Hex: `57 0e 4f 65`

Mnemonics: `read-nums dump crange product`

Try it online!

`dump` pops a list from the stack and pushes its contents (like `~` in GolfScript), and `crange` gives `[a,b)`.

# Answer
> 3 votes
# LabVIEW, 14 LabVIEW Primitives

Range is exclusive. Creates an array from `a` to `b` then multiplies all elements.

# Answer
> 3 votes
# Java 7, 54 characters

```
int p(int a,int b){int p=a;while(++a<b)p*=a;return p;}

```

We cheat the first multiply by assigning it to the temp-product. Then we pre-increment the counter (shamelessly stolen from the input parameter) to skip the first one.

Compare `< b` instead of `<= b` \- both are to spec, but this saves a character.

Sample:

```
C:\files>type BadProd.java
class BadProd {
    public static void main(String...args) {
        System.out.println(p(2,5));
        System.out.println(p(5,10));
        System.out.println(p(-4,3));
        System.out.println(p(0,3));
        System.out.println(p(-4,0));

    }
    static int p(int a,int b){int p=a;while(++a<b)p*=a;return p;}
}
C:\files>java BadProd
24
15120
0
0
24

```

# Answer
> 3 votes
# dc, 27 bytes

Input assumes `a` is on top of the main stack and `b` is under it

```
dsar[dsc*lc1-dla<A]sAlAxrp

```

Ungolfed:

```
dsa        # duplicate 'a', store a copy in register a
r          # reverse top two items on stack
[          # start macro definition
  dsc      # duplicate counter, store in register c
           #  ('b' is the initial counter value)
  *        # pop top two elements of stack, multiply and push result
  lc       # copy the stored counter to the stack
  1- d     # decrement and duplicate it
  la       # copy 'a' to the stack
  <A       # if 'a' is < the counter, run macro A
]sA        # store this macro as A
lAx        # execute macro A
r          # reverse top two elements of stack
p          # pop/print the result

```

# Answer
> 3 votes
## dc, ~~41~~ ~~38~~ 37 bytes

This is my first code golf, so bear with me

```
[lad1+sa*dstlalb>d]sd?sbdst1+saltldxf

```

It must be saved as a file, and invoked (with bash, so UNIX only) as

```
dc -f [filename]

```

It will proceed to wait for input, in the form of `a b` integers. Note that negative numbers must come as `_number`.

---

Alternatively,

```
echo "X Y [lad1+sa*dstlalb>d]sd?sbdst1+saltdxf" | dc

```

with X and Y replaced with the two numbers you'd like to product-over-range. This one won't wait unless you don't pipe two numbers.

---

# Explanation:

```
The recursive macro:
[lad    # load the contents of register a onto the stack, and duplicate it
 1+sa   # Add 1 to the top of the stack (a) and store it in register a
 *dst   # Multiply two off the stack, duplicate and store in register t (stack contains t)
 lalb>d # load a and b, as long as b>a execute d (which is this macro)
 ]sd    # Store that macro in register d
 ?      # Wait for input, hope it is [a b] without braces
 sbd    # store b, duplicate a (stack == a a) (old: sbddsa)
 st     # store a => t (stack == a)
 1+sa   # add 1 to a and store it in a
 lt     # load t since d expects the total to be on the stack
 ldx    # load d and execute it as a macro
 f      # after d is done recursively calling, t will still be on the stack.
        # Print the stack and close (close is implicit)

```

There was a removal of a spare duplication and store (dsa)

# Answer
> 3 votes
# Kotlin, 30 bytes

Range is inclusive

```
{a,b->(a..b).reduce{c,d->c*d}}

```

Try it online!

---

# Kotlin, 21 bytes

If you can take input as an `IntRange`:

```
{it.reduce{c,d->c*d}}

```

Try it online!

# Answer
> 3 votes
# Branch, 26 bytes

```
Z}N\;^-[n^\z^*Zn}N^\o^-]z#

```

Try it on the online Branch interpreter!

```
Z                   Save the value (the first argument) as register Z
}N                  Increment and save to N
\;                  Go to the right child and copy the parent value
^-                  Go to the parent and subtract (the left child is pre-set as the second argument)
[               ]   While non-zero (basically, while N is not the same as the end)
 n                  Restore register N
  ^\z^              Put Z in the right child and go to the parent
      *Z            Multiply and save to Z; these three lines do Z = Z * N
        n}N         Restore N, increment, and save back to N
           ^\o^-    Compare against register O; automatically set to the second argument
z#                  Restore Z, the product, and output

```

This is right-exclusive.

# Answer
> 3 votes
# K (ngn/k), 11 bytes

```
{*/x+!y-x}

```

Try it online!

*-1 byte thanks to PyGamer0 for telling me that I don't need `'` after `+`*

Another easy one. Exclusive at b.

Explainations:

```
Assuming that a is 2 and b is 5

{*/x+!y-x}            Main program. Takes x as `a` and y as `b`
      y-x              b-a to fix the range (5 - 2 = 3)
     !                 Range   (0 1 2)
   x+                  += x to each elenent    (2 3 4)
 */                    Product (2*3*4 = 24)

```

# Answer
> 3 votes
# Kotlin, 30 bytes

```
{a,b->(a..b).reduce{c,d->c*d}}

```

Kotlin Playground

# Answer
> 2 votes
# Mouse, 36 bytes

```
?A:?B:A.I:(A.B.<^A.1+A:A.I.*I:)I.!$

```

This reads two integers from STDIN and prints an integer to STDOUT. This computes the sum over the closed interval, i.e. `[a,b]` rather than `[a,b)`.

Ungolfed:

```
? A:             ~ Read an integer from STDIN, assign to A
? B:             ~ Read STDIN, assign B
A. I:            ~ Begin an accumulator at A
( A. B. < ^      ~ While A < B...
  A. 1 + A:      ~ Increment A
  A. I. * I:     ~ I *= A
)
I. !             ~ Print I to STDOUT
$

```

# Answer
> 2 votes
# JavaScript (ES6), 39

Inclusive range.

```
(a,b)=>[...Array(b-a)].map(_=>b*=a++)|b

```

Note: `map` beats `reduce` once again

# Answer
> 2 votes
# zsh, 30 bytes

```
f=({$1..$2})
echo $[${f// /*}]

```

Sample run:

```
manatwork% zsh product.zsh 5 10
151200

```

# Answer
> 2 votes
# jq, 36 bytes

(35 characters code + 1 character command line option)

```
reduce range(.[0];.[1])as$i(1;.*$i)

```

Sample run:

```
bash-4.3$ bin/jq -s 'reduce range(.[0];.[1])as$i(1;.*$i)' <<< '5 10'
15120

```

On-line test (Passing `-s` through URL is not supported – so input passed as \[5, 10\].)

# Answer
> 2 votes
# TI-Basic, ~~14~~ 11 bytes

```
Prompt A,B:prod(randIntNoRep(A,B

```

# Answer
> 2 votes
## Fortran, 44 bytes

Finally a use for those pesky implicit types.

```
function j(k,l)
j=1
do i=k,l
j=j*i
enddo
end

```

Test program:

```
program testProduct
  integer :: a, k, l
  k = -4
  l = -1
  a = j(k,l)
  print*,a
end program testProduct

```

# Answer
> 2 votes
# Vitsy, 14 bytes

Note to self: add range

Expects input as `b a`.

```
D{-\[D1+]l1-\*
D               Duplicate the top input.
 {-\[   ]       Repeat the stuff in the brackets by the difference between the
                inputs.
     D1+        Duplicate, add one.
                I now have the range [a,b].
         l1-\*  Multiply all the items together.
```

This is a function in Vitsy that will leave the product of the range `[a,b]` on the stack. "But how do I test it?!?" I hear you ask?

Concatenate `N`. c:

Try it online!

# Answer
> 2 votes
# Milky Way 1.5.17, 28 bytes

```
1%{¢¢L§{?{¢1-e__^}}£*}!

```

---

### Explanation

```
1          1             # push integer to the stack
 %{                £ }   # for loop
   ¢¢     ¢              # read a single line of input from the command line
     L                   # push a Pythonic range(0, TOS + 1)
      §{          }      # mapping
        ?{    __ }       # if-else statement
            -            # subtract the STOS from the TOS
             e           # order the TOS and STOS (greater-than)
                ^        # pop the TOS
                      !  # output the TOS

```

---

### Usage

```
$ ./mw <path-to-code> -i <input>

```

Example:

```
$ ./mw test.mwg -i "2
5"

```

Milky Way takes line breaks literally. `\n` is not interpreted as a line break. In future versions, this will be changed.

# Answer
> 2 votes
# Arcyóu, 17 bytes

```
(F(a b)(r *(_ a b

```

This includes `a` but excludes `b`.

Explanation:

```
(F(a b)    ; Anonymous function F(a, b)
  (r *     ; Reduce by multiplication
    (_ a b ; Range from a to b

```

# Answer
> 2 votes
# PlatyPar, 4 bytes

```
_XF*

```

`_` gets the range `[a,b)`, `X` expands it onto the stack, and `F*` folds multiplication over the range. Try it online!

# Answer
> 2 votes
# Rust, 52 51 bytes

```
fn p(mut a:i32,b:i32)->i32{for i in a+1..b{a*=i;}a}

```

Usage (+ ungolfed version) as follows:

```
fn p(mut a:i32, b:i32) -> i32 {
    for i in a+1..b {
        a *= i;
    }
    a
}

fn main() {
    println!("{}", p(2, 5));
    println!("{}", p(5, 10));
    println!("{}", p(-4, 3));
    println!("{}", p(-4, 0));
}

```

Uses the current stable version of Rust (1.5.0)

# Answer
> 2 votes
# Java 7, ~~49~~ 48 bytes

```
int c(int a,int b){return-~a!=b?a*c(a+1,b):a*b;}

```

*corsiKa*'s answer is exclusive, mine is inclusive (and slightly shorter by using recursion instead of a loop).

**Explanation:**

Try it here.

```
int c(int a,int b){  // Method with two integer parameters and integer return-type
  return-~a!=b?      //  If `a+1` is not equal to `b`
         a*c(a+1,b)  //   Return `a` multiplied by the recursive call with `a+1,b`
        :            //  Else:
         a*b;        //   Return `a*b`
}                    // End of method

```

# Answer
> 2 votes
## PHP, 42 Bytes

```
<?=array_product(range($ARGV[1],$ARGV[2]))

<?=                         // Open file, '=' is shorthand for 'echo'
array_product(              // Get product of array
range($argv[1],$argv[2])    // array is range from a to b
)

```

# Answer
> 2 votes
# Fith, 17 bytes (non-competing)

*This language was created after the challenge.*

```
{ range product }

```

Anonymous function. Excludes `b`. Pretty self-explanatory.

Stack effect: `a b -- *[a,b)`

# Answer
> 2 votes
## \>\<\>, 33 bytes

```
 1&:@$:@)?\&n;
:$@:+1&*&:/?@@$@)@

```

My first fish attempt.

Inclusive range
Assumes a and b are on the stack.

# Answer
> 2 votes
# Swift, ~~26~~ 58 bytes

```
func p(a:Int,b:Int)->Int{return(a+1..<b).reduce(a){$0*$1}}

```

# Answer
> 2 votes
# tcl, 55

```
incr p
while \$a<$b {set p [expr $p*$a];incr a}
puts $p

```

# demo

# Answer
> 2 votes
# Ahead, 7 bytes

Input is taken as two numbers on standard in. Range is `[a,b]`.

```
IIEK*O@

II       read two ints and push to stack
  E      expand range between top two stack items
   K     reduce stack by...
    *    multiplying
     O   pop and print number
      @  terminate

```

Try it online!

# Answer
> 2 votes
# F# (.NET Core), 27 bytes

```
fun a b->Seq.fold(*)1[a..b]

```

Try it online!

# Answer
> 2 votes
# Clam, 5 bytes

```
p;Brr

```

## Explanation

```
p     - Print...
 ;    - Product of...
  B   - Range...
   r  - Next input
    r - Next input

```

# Answer
> 2 votes
# Keg `-hr`, 3 bytes

```
ɧ∑*

```

Try it online!

Explanation:

```
ɧ   # Generate inclusive range from two integer inputs
 ∑* # Calculate product of whole stack
    # Output

```

# Answer
> 2 votes
# Python 2, 30 bytes

```
f=lambda a,b:b<a or a*f(a+1,b)

```

Try it online!

Range is inclusive (e.g., `f(2,5) => 120`).

# Answer
> 2 votes
## `W`, 3 bytes (inclusive)

```
.*r

```

## Explanation

```
ab.   % Generate inclusive range from a to b
   *  % Multiplication
    r % Preserve the operation's action & reduce by it

```

# Answer
> 2 votes
# Pip, 6 bytes

```
$*Ya,b

```

Try it online!

-1 byte from DLosc.

# Answer
> 2 votes
# Vyxal, 2 bytes

Range of a to b, then product

Try it!

# Answer
> 2 votes
# Pyth, 4 bytes

```
*F}F

```

Test suite

Range is inclusive.

# Answer
> 2 votes
# Factor \+ `math.unicode`, 12 bytes

```
[ [a,b] Π ]

```

Try it online!

It's a quotation (anonymous function) that takes 2 integers from the data stack as input and leaves one integer on the data stack as output.

* `[a,b]` Create a range from two integers. As you may have guessed, this is inclusive of both. All of the other words are also available, such as `[a,b)`.
* `Π` Find the product.

# Answer
> 2 votes
# HBL, 2.5 bytes

```
*(0.,

```

Uses inclusive range. Try it at HBL Online!

### Explanation

After parentheses autocompletion, we have `'(*(0.,))`:

```
'(*(0.,))
'(      )  Define a function which returns
  *        the product of
   (0  )   the range from
     .     the first argument to
      ,    the second argument

```

# Answer
> 2 votes
## PostScript, 27 bytes

```
{1 exch 1 4 1 roll{mul}for}

```

Anonymous function for inclusive product. Takes two inputs from the stack and leaves output on the stack.

(Usage: e.g., `5 10 {1 exch 1 4 1 roll{mul}for} exec =` prints `151200`.)

Try it online!

# Answer
> 2 votes
# Fig, \\$2\log\_{256}(96)\approx\\$ 1.646 bytes

```
rR

```

See the README to see how to run this

Calculates using the range \[a, b\] (because of bug). Explanation:

```
rR # Takes input as "a b"
 R # Range [a, b]
r  # Product

```

# Answer
> 2 votes
# Regex  (PCRE2 v10.35 or later), 128 bytes

`^(?!-x*,(?!-))(-())?+(?=(x*),-?(x*))(?=(x*),?(?=\3)(?=\4)(x*,-?|[^,]*)(x*))\5,?+(?=(\2(xx)*(?11))?)((?*x+)x?+)*(?*x+)(\5\7(,|$))`

Attempt This Online!

Takes its input in unary, as two strings of `x` characters whose lengths represent the numbers, with optional `-` signs on their left side, joined by a `,` delimiter, specifying an inclusive range. Returns the absolute value of its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)

Additionally, capture group `\8` is set iff the result is negative. This value is taken from the last found possible match, if there is a conflict. But this regex always returns a consistent value in it within a run.

It takes two shortcuts:

* It assumes that the left argument is less than the right argument. This isn't necessary, and in fact removing this assumption wouldn't cost many bytes.
* If the two arguments have different signs, it doesn't even bother calculating anything, because the result will always be zero. This isn't a necessary shortcut (it worked without it), but it results in a *much* shorter regex.

```
^
(?!
    -x*,(?!-)           # If A is negative and B is nonnegative, let there
                        # be no possible matches, as the product would be 0.
)
(-())?+                 # \2 = set if A is negative
(?=
      (x*),             # \3 = abs(A);
    -?(x*)              # \4 = abs(B)
)
(?=
    (x*),?(?=\3)(?=\4)  # \5 = what to skip so tail = the larger of A or B;
                        # tail = the larger of A or B
    (x*,-?|[^,]*)(x*)   # \7 = {the smaller of A or B} - \5
)
\5                      # tail = the larger of A or B
,?+                     # skip sign of B, if any
                        # First handle the range from larger inclusive to
                        # {smaller inclusive or 0 exclusive}
(?=
    (\2(xx)*(?11))?     # \8 = set iff the inclusive range is negative and has
                        #      an odd number of total members, i.e. the product
                        #      is negative
)
(
    (?*x+)              # Multiply the number of possibilities by tail.
    x?+                 # Advance by 1, but if already at the end, allow the
                        # loop to iterate once more so as to include 0 in
                        # the count.
)*                      # Iterate any number of times (cover the whole range)
(?*x+)                  # Multiply the number of possibilities by tail again
                        # at the end of the range.
(                       # Define subroutine (?11)
    \5\7                # Clamp the range at the smaller end.
    (,|$)               # Assert that we've reached the end.
)

```

As far as I know, this absolutely requires non-atomic lookaround (used here as `(?*`...`)` molecular lookahead) and -output, so it would not be portable to other regex engines currently – though it would be easily portable to  ECMAScript+`(?*)`.

# Answer
> 1 votes
# golflua, 26 characters

```
\p(f,t)~@i=f+1,t f=f*i$~f$

```

Sample run:

```
Lua 5.2.2  Copyright (C) 1994-2013 Lua.org, PUC-Rio
> \p(f,t)~@i=f+1,t f=f*i$~f$
> w(p(5, 10))
151200

```

# Answer
> 1 votes
## C#, 66 bytes

Not great, but not too bad.

```
int d(int a,int b)=>Enumerable.Range(a,b-a).Aggregate((x,y)=>x*y);

```

# Answer
> 1 votes
# Hassium, 49 Bytes

```
func f(a,b){t=a;for(x=a+1;x<b;x++)t=t*x;print(t)}

```

See expanded and run online with test case here

# Answer
> 1 votes
## Befunge, 51 bytes

```
 v          @.$<
v>&20p&30p1
>20g*20g:30g-!#^_1+20p

```

This can probably be optimised with some stack manipulation wizardry.
I went for put and get instructions instead. Might get back to it later on.
Also fails with negative numbers, since AFAIK Befunge doesn't handle them, instead looping back to maxint.

# Answer
> 1 votes
# , 4 chars / 11 bytes

```
⨴⩥…ï

```

`Try it here (Firefox only).`

Creates an exclusive range from the array input, and multiplies everything in the resulting range. (Note that although the interpreter is using v2 of the language, this code still works in v1.)

# Answer
> 1 votes
**Python 56**

```
a=input()
b=input()
print reduce(int.__mul__,range(a,b))

```

# Answer
> 1 votes
# Detour, 3 bytes (non-competing)

```
rP.

```

Try it online!

Same as @quartata's Jelly answer, except `.` is required to output the result so it doesn't wrap back around to `r`.
This was not intended to be a golfing language, but the 1-character commands necessary to operate on a 2d grid make small challenges like this really short.

# Answer
> 1 votes
# CoffeeScript, ~~46 45 44~~ 29 bytes

Inclusive range

29 bytes version (anonymous function):

```
(a,b)->c=a;c*=++a while a<b;c

```

Equivalent to next JS code:

```
(function(a, b) {
    var c;
    c = a;
    while (a < b) {
        c *= ++a;
    }
    return c;
});

```

44 bytes version (prompt()):

```
alert [prompt()..prompt()].reduce (a,b)->a*b

```

45 bytes version:

```
alert [prompt()..prompt()].reduce((a,b)->a*b)

```

46 bytes version:

```
alert([prompt()..prompt()].reduce((a,b)->a*b))

```

# Answer
> 1 votes
# Reng v.3, 25 bytes

This is encoded in ISO 8859-1, and you can try it out at the new IO page!

```
ii#x:1+::xe)2(¿Bh$1¶a*¡n~

```

Is an inclusive range.

`ii` takes 2 inputs, and stores the second one (the maximum) in `x`. `:1+::` sets `a` to `a (a+1) (a+1) (a+1)`. `xe` sets the TOS to the equality of the counter `(a+1)` and `)2(` sets the STOS to `2`. `¿` pops two numbers and, if the TOS is true, the pointer moves STOS times. Otherwise, we just go forward. In the event that we have not reached the maximum, `Bh` goes back 11 units. `$` drops the excess counter from the TOS once we are done looping.  sets the default pop from an empty stack to `1`, so we can use a double-sided mirror loop to multiply everything. `a` is a one-sided mirror, and `*` multiplies values. `¡` mirrors until the stack's length is `1`. Once the length *is* 1, `n~` is met and outputs the result and exits the program.

# Answer
> 1 votes
# Factor, ~~79~~ ~~43~~ 29 bytes

Hooray for auto use!

It's quite elegant, really. A lambda, that goes on the stack.

```
[ 1 - [a,b] 1 [ * ] reduce ]

```

# Answer
> 1 votes
# Mathcad, 4 "bytes"

Uses the built-in Iterated Product Operator, which is entered from the keyboard by ctl-#. Type k into the iterator and expression placeholders and then type the evaluation operator (=), giving a total of 4 "bytes" where one byte is taken to be the number of characters needed to enter an expression.

# Answer
> 1 votes
## Matricks, 24 bytes

Matricks is a new esolang I invented to deal with matrices. Run like: `python matricks.py [[<num1>,<num2>]]`

```
mg:;+c:1:g:1;-g:;;kp{};;

```

This is a simple answer. Matricks has a built-in for taking the product of an array, `p`, so all I need to do is make the range with the constructor, `m`

# Answer
> 1 votes
# /kona, 8 bytes

```
*/a+!b-a

```

Let's break this down: k reads right-to-left, so:

`b-a` finds the difference between b and a, to give the number of numbers required

`!(b-a)` generates a list from 0 to (b-a), giving the range \[0, (b-a))

`a+(!b-a)` adds a to each element of the list, to get the range \[a, b)

`*/(a+!b-a)` applies multiplication over all elements of the list; `*` is the multiply operator, and `/` is the *over* adverb, which is like a map/reduce function, applying its left-hand argument over all elements of its right-hand argument.

# Answer
> 1 votes
## Racket (scheme), 29 bytes

Functional programming woot

Apply applies a function to all elements of a list, and range creates a list ranging from a to b. The function being applied is \*. Exclusive.

```
(λ(a b)(apply *(range a b)))

```

# Answer
> 1 votes
# Perl 6 - 15 bytes

```
{[*] $^a..$^b}

```

Usage:

```
> {[*] $^a..$^b}(2,5)
120

```

# Answer
> 1 votes
# Forth, 33 bytes

Pretty simple looping program.

```
: f DUP ROT DO DUP I * LOOP ; f .

```

**Try it online**

# Answer
> 1 votes
## JavaScript (using external library) (31 bytes)

```
 (a,b)=>_.RangeTo(a,b).Product()

```

Link to lib: https://github.com/mvegh1/Enumerable/

Explanation of code: Anonymous method accepts low bound and high bound for range, and uses built in .Product method to produce the product for that range

# Answer
> 1 votes
# C#, 56 Bytes

```
int f(int a,int b){var r=1;for(;a<b;a++)r*=a;return r;}

```

# Answer
> 1 votes
# Excel, 37 bytes

```
=PRODUCT(A2-ROW(OFFSET(A1,,,A2-A1)))

```

Data will be **a** in A1 and **b** in A2.

The above should be entered as an array formula (ctrl\_shift\_enter) in any other cell. The result is exclusive of **b**.

# Answer
> 1 votes
# Pushy, 8 bytes

Non-competing as the language postdates the challenge.

```
w-:&h;P#

```

Try it online!

Most of the code is building the range, as there is a builtin for finding the product (`P`).

```
w          \ Mirror stack, yielding [a, b, a]
 -         \ Pop (b, a) and push b - a, the difference
  :  ;     \ That many times do:
   &h      \   Push last item +1
      P#   \ Print product

```

The `w-:&h;` is essentially a long-winded binary range function, as Pushy only has unary range commands.

# Answer
> 1 votes
# Triangular, ~~21~~ 20 bytes

```
$\S=t$iUprP%..%/*U:<

```

Try it online!

Takes input with order `b, a` from standard in.

**Ungolfed:** (Explanation to be added later)

```
      $
     \ S
    = t $
   i U p r
  P % . . %
 / * U : <

```

---

**Previous Version (21 bytes):**
```
1\P\p$?Ud$=0%)(/P*U:<

```

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

```
f=(a,b)=>a-b?a*f(a+1,b):b

```

Inclusive.

# Answer
> 1 votes
# Perl 5 `-MList::Util=product -p`, 16 bytes

```
$_=product$_..<>

```

Try it online!

# Answer
> 1 votes
# Perl 6, 14 bytes

```
{[*] [...] @_}

```

Try it online!

Reduce the two inputs by range, then reduces by multiplication.

# Answer
> 1 votes
# GolfScript, 8 bytes

Idea copied from the gs2 solution.

```
~,\>{*}*

```

Try it online!

## Explanation

```
~        # Dump the input,            e.g. 2 4
 ,       # Generate range from 0 to input: 2 [0 1 2 3 4]
  \      # Swap the stack                : [0 1 2 3 4] 2
   >     # Keep all those that are larger: [2 3 4]
    {*}* # Reduce by multiplication      : 24

```

# Answer
> 1 votes
# Gol\>\<\>, 13 bytes

```
I::I-F$M:@*|h

```

Try it online!

Takes `b` then `a` from stdin, and uses inclusive range.

### How it works

```
I::I-F$M:@*|h

I::I-           Take b, duplicate twice, take a, subtract
                [b b b-a]
     F     |    Repeat b-a times:
                [counter product]
      $M          Swap two, decrement counter
                  [product counter-1]
        :@        Duplicate, rotate 3
                  [counter-1 counter-1 product]
          *       Multiply
                  [counter-1 product']
            h   Print top as number and exit

```

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 37 bytes

```
int f(int a,int b)=>a<b?a*f(a+1,b):b;

```

Try it online!

# Answer
> 1 votes
# Javascript

```
f=(a,b)=>a>b||a*f(a+1,b)

```

or

```
f=(a,b)=>[...Array(b-a).keys()].map(i=>i+a).reduce((a,b)=>a*b)

```

# Python

```
f=lambda a,b:reduce(lambda x,y:x*y,range(a,b))

```

# Answer
> 1 votes
# Arn, 5 bytes

```
ë|¶Ý║

```

Try it!

# Explained

Unpacked: `*\(=>\`

```
  \           Fold with
*             Multiplication
    (         Begin expression
        \     Fold with
      =>      Inclusive range
          _   Variable initialized to STDIN; implied
    )         End expression; implied

```

The power of the fold operator, alternatives would be `*\=>?1` or `*\=>:}` (hypothetically, for some reason they are broken as of typing this. Trying to fix).

# Answer
> 1 votes
# Scala, 9 bytes

```
_.product

```

Try it in Scastie

Accepts input as a `Range` object (inclusive or exclusive).

# Answer
> 1 votes
# , 12 bytes

```
[j:v,;]jv-+*

```

Try it online!

```
[j:v            Input and save to v without popping
    ,;          Range (1..n inclusive)
      ]jv-      Range end - start
          +     Add it vectorised with range
           *    Product

```

# Answer
> 1 votes
# Husk, 2 bytes

```
Π…

```

Try it online!

```
   # arguments (² => second last argument & ⁰ => last argument) are implicit
 … # inclusive numeric range
Π… # product of list

```

# Answer
> 1 votes
# x86-16 machine code, 10 bytes

```
00000000: 8bc8 f7eb 4b3b d97f f9c3                 ....K;....

```

Listing:

```
8B C8       MOV  CX, AX         ; running product start at a
        MUL_LOOP:
F7 EB       IMUL BX             ; multiply running product by b
4B          DEC  BX             ; decrement b
3B D9       CMP  BX, CX         ; is b > a?
7F F9       JG   MUL_LOOP       ; if so, go forth and multiply
C3          RET                 ; return to caller

```

Input *a* in `AX`, *b* in `BX`, inclusive of *b*. Output to `AX`.

Tests using DOS DEBUG:

Note: before anyone asks... you cannot use `LOOPNZ` to decrement and compare *a* and *b*. In the case where input *a* (`CX`) is `0`, it will end the loop before multiplying by the value of *a*, so no good.

# Answer
> 1 votes
# Ly, ~~23~~ 11 bytes

```
&nRy[p*y,]p

```

Try it online!

Let's try not doing it the "hard way" this time... :) The code generates a sequence of numbers on a stack, then works through the stack multiplying entries until there's only one number. When the program ends, that single entry prints as a number automatically.

```
&nRy[p*y,]p  -
&n           - read in the two numbers
  R          - generate a range of numbers (inclusive)
   y[p y,]p  - as long as the stack size is 2 or more
      *      - multiply the top two entries

```

# Answer
> 1 votes
## dc, 23 bytes

```
dsc[lc1+dsc*lclb>g]dsgx

```

Takes input with the upper bound (inclusive) in register `b` and the lower bound (inclusive) at the top of the stack. Returns the answer at the top of the stack.

Uses register `c` a lot, so removing that would save a lot of bytes. Basically it's just a for-loop.

Run as:

```
{UPPER_BOUND}sb{LOWER_BOUND} dsc[lc1+dsc*lclb>g]dsgx p

```

# Answer
> 1 votes
# Nim, 47 bytes

```
proc f(a,b,c:var int)=
  c=1;for i in a..b:c*=i
```

Attempt This Online!

All arguments must be variables, passed by reference. Return value in third parameter, original value ignored. As usual with Nim, not very small byte count.

# Answer
> 1 votes
# APL, 12 bytes

```
{⍺×.-1-⍳⍵-⍺}

```

Explanation on example of arguments 2 and 5:

```
⍳⍵-⍺ ⍝ Array of numbers from 1 to ⍵-⍺: 1 2 3
1-   ⍝ Substract the array from 1: 0 ¯1 ¯2
⍺×.- ⍝ Substract the array from ⍺: 2 3 4
     ⍝ Then reduce by multiplication, of course

```

Mathematical justification: ⍺-(1-x) = (⍺-1)+x

# Answer
> 1 votes
# Nibbles, 2.5 bytes (5 nibbles)

```
`*>$,

```

Input is `(a,b]` (so `5 10` represents the range `6 7 8 9 10`).

```
    ,      # range from 1..(implicit) arg1
  >        # drop first      elements
   $       #            arg2
`*         # product

```

# Answer
> 1 votes
# Knight, 34 bytes

```
;;;;=xP=yP=p 1W<=x+1x+2y=p*p-x 1Op

```

Try it online!

# Answer
> 1 votes
# Arturo, 12 bytes

```
$=>[∏&..&]

```

Try it

# Answer
> 1 votes
# HP48 User RPL,

Input is `a` and `b` in the stack.

```
«
  'X'
  DUP
  4 UNROLL
  UNROT
  1 SEQ
  ∏LIST
»

```

# Answer
> 1 votes
# Pyt, 2 bytes

```
ŘΠ

```

Try it online!

Takes inputs as `b, a` separated by newlines

# Answer
> 1 votes
# \>\<\> (Fish), 29 bytes

```
&1$:&v
v?=&:<|.!02$*@+1:
>~n;

```

Try it

# Answer
> 1 votes
# BQN, 7 bytes

```
×´⊢+↕∘-

```

Thanks to @ConorO'Brien

Try it

# BQN, 10 bytes

```
{×´+↕¬}

```

Try it

Uses an inclusive range. This is the first thing I've ever written in BQN and I couldn't figure out how to make it tacit for the life of me. Any tips appreciated. :)

# Answer
> 1 votes
# Itr, 5 bytes

`â-º+P`

solution for exclusive range

online interpreter

## Explantion

```
â-º+P ; implicit input, stack: [hi low]>
â     ; under -> stack: [low hi low]>
 -    ; subtraction -> stack: [low hi-low]>
  º   ; zero-based range
   +  ; add low to zero based range giving range [low,...hi-1]
    P ; product
      ; implicit output

```

---

# Itr, 7 bytes

solution for inclusive range

`â-1+º+P`

### 2 bytes using the new range built-in

`¨P`

# Answer
> 1 votes
## Pascal, 76 B

Utilizing a recursive definition of the product you may arrive at one of the following solutions:

```
function p(a,b:integer):integer;begin if a=b then p:=a else p:=a*p(a+1,b)end

```

```
function p(a,b:integer):integer;begin if a<b then p:=a*p(a+1,b)else p:=a end

```

```
function p(a,b:integer):integer;begin if b>a then p:=a*p(a+1,b)else p:=a end

```

**86 B (standard iterative solution)**: Pascal’s `for`-loop limits are inclusive (just like the \\$\prod\\$ and \\$\sum\\$ limits in mathematics are inclusive, too). In Standard Pascal (as specified by ISO standard 7185) `for`-loop counters must fulfill certain eligibility criteria (some dialects may be more lenient with that). Therefore a new variable is declared:

```
function p(a,b:integer):integer;var i:integer;begin for i:=a+1 to b do a:=a*i;p:=a end

```

# Answer
> 0 votes
# Charcoal, 20 bytes

```
≔¹ξＮαＮβＦ…αβ«≔×ξιξ»Ｉξ

```

Try it online!

## Verbose

```
Assign 1 x
InputNumber a; InputNumber b;
for(Range a b){
    Assign (Times x i) x
}
Print Cast x

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 2 bytes

```
Ip

```

Attempt This Online! Uses \\$\[a..b\]\\$ (the inclusive range).

**Explanation:** `p`roduct of the `I`nclusive range between the two inputs.

# Answer
> 0 votes
# J-uby, 9 bytes

```
:!~|:/&:*

```

Attempt This Online!

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


title: Matrix Trigonometry

text:
# Question
Title: Matrix Trigonometry
## Introduction

The two most common trigonometric functions, `sine` and `cosine` (or `sin` and `cos` for short), can be extended to be matrix-valued functions. One way to compute the matrix-valued analogs is as follows:

Consider these two important trigonometric identities: $$ e^{i x} = \cos(x) + i \sin(x) \\ \sin^2(x) + \cos^2(x) = 1 $$ Using these identities, we can derive the following equations for `sin` and `cos`: $$ \sin(x) = \frac{e^{i x} - e^{-i x}}{2 i} \\ \cos(x) = \frac{e^{i x} + e^{-i x}}{2} $$ The matrix exponential exists for all square matrices and is given by: $$ e^A = \sum\_{k = 0}^\infty \frac{1}{k!} A^k $$ where **A0** is the identity matrix **I** with the same dimensions as **A**. Using the matrix exponential, these two trigonometric functions (and thus all the other trigonometric functions) can be evaluated as functions of matrices.

## The Challenge

Given a square matrix **A**, output the values of `sin(A)` and `cos(A)`.

## Rules

* Input and output may be in any convenient, reasonable format (2D array, your language's matrix format, etc.).
* You may write a single program, two independent programs, a single function, or two functions. If you choose to write two functions, code may be shared between them (such as imports and helper functions).
* The input matrix's values will always be integers.
* Your solution may have accuracy issues as the result of floating-point imprecision. If your language had magical infinite-precision values, then your solution should work perfectly (ignoring the fact that it would require infinite time and/or memory). However, since those magical infinite-precision values don't exist, inaccuracies caused by limited precision are acceptable. This rule is in place to avoid complications resulting from requiring a specific amount of precision in the output.
* Builtins which compute trigonometric functions for matrix arguments (including hyperbolic trig functions) are not allowed. Other matrix builtins (such as multiplication, exponentiation, diagonalization, decomposition, and the matrix exponential) are allowed.

## Test Cases

Format: `A -> sin(A), cos(A)`

```
[[0]] -> [[0]], [[1]]
[[0, 2], [3, 5]] -> [[-0.761177343863758, 0.160587281888277], [0.240880922832416, -0.359709139143065]], [[0.600283445979886, 0.119962280223493], [0.179943420335240, 0.900189146538619]]
[[1, 0, 1], [0, 0, 0], [0, 1, 0]] -> [[0.841470984807897, -0.158529015192103, 0.841470984807897], [0, 0, 0], [0, 1, 0]], [[0.540302305868140, -0.459697694131860, -0.459697694131860], [0, 1, 0], [0, 0, 1]]
[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] -> [[0.841470984807897, 0, 0, 0, 0], [0, 0.841470984807897, 0, 0, 0], [0, 0, 0.841470984807897, 0, 0], [0, 0, 0, 0.841470984807897, 0], [0, 0, 0, 0, 0.841470984807897]], [[0.540302305868140, 0, 0, 0, 0], [0, 0.540302305868140, 0, 0, 0], [0, 0, 0.540302305868140, 0, 0], [0, 0, 0, 0.540302305868140, 0], [0, 0, 0, 0, 0.540302305868140]]
[[-3, 2, -6], [3, 0, 4], [4, -2, 7]] -> [[-0.374786510963954, 0.135652884035570, -1.35191037980742], [1.14843105375406, 0.773644542790111, 1.21625749577185], [1.21625749577185, -0.135652884035570, 2.19338136461532]], [[4.13614256031450, -1.91289828483056, 5.50873853927692], [-2.63939111203107, 1.49675144828342, -3.59584025444636], [-3.59584025444636, 1.91289828483056, -4.96843623340878]]

```

## Further Reading

This excellent question over at Math.SE includes some alternate derivations of the matrix-valued analogs of trigonometric functions.

# Answer
# Julia, ~~33~~ 19 bytes

```
A->reim(expm(A*im))

```

This is a function that accepts a 2-dimensional array of floats and returns a tuple of such arrays correponding to the cosine and sine, respectively. Note that this is the reverse of the order given in the test cases, in which sine is listed first.

For a real-valued matrix *A*, we have

and

That is, the sine and cosine of *A* correspond to the imaginary and real parts of the matrix exponential *e**iA*. See *Functions of Matrices* (Higham, 2008).

Try it online! (includes all test cases)

Saved 14 bytes thanks to Dennis!
> 7 votes

# Answer
# Mathematica, 27 bytes

```
{Im@#,Re@#}&@MatrixExp[I#]&

```

Based on @Rainer P.'s solution.

Takes the square matrix `A` as an argument and outputs a list containing `{sin(A), cos(A)}`.

The input is formatted with `N` to get a numerical value instead of a long exact formula and `Column` to display the results of `sin(A)` and `cos(A)` as separate matrices instead of a nested list.

Calculating the values separately requires **38** bytes

```
{(#2-#)I,+##}/2&@@MatrixExp/@{I#,-I#}&

```
> 6 votes

# Answer
# Jelly, ~~23~~ 22 bytes

```
³æ*÷!
®Ḥ‘©r0Ç€s2_@/µÐL

```

Try it online!

### Background

This approach directly computes the Taylor series for *sine* and *cosine*, i.e.,

It increases the number of initial terms of both series until the result no longer changes, so its accuracy is only limited by the precision of the floating point type.

### How it works

```
®Ḥ‘©r0Ç€s2_@/µÐL  Main link, Argument: A (matrix)

             µÐL  Loop; apply the chain until the results are no longer unique.
                  Return the last unique result.
®                   Yield the value of the register (initially zero).
 Ḥ                  Unhalve/double it.
  ‘©                Increment and copy the result (n) to the register.
    r0              Range; yield [n, ..., 0].
      Ç€            Apply the helper link to each k in the range.
        s2          Split the results into chunks of length 2. Since n is always
                    odd, this yields [[Ç(n), Ç(n-1)], ..., [Ç(1), Ç(0)]].
          _@/       Reduce the columns of the result by swapped subtraction,
                    yielding [Ç(1) - Ç(3) + ... Ç(n), Ç(0) - Ç(2) + ... Ç(n - 1)].

³æ*÷!             Helper link. Argument: k (integer)

³                 Yield the first command-line argument (A).
 æ*               Elevate A to the k-th power.
    !             Yield the factorial of k.
   ÷              Divide the left result by the right one.

```
> 6 votes

# Answer
# C++, 305 bytes

```
#include<cmath>
#include<iostream>
#include<vector>
int x,i=0, j;void p(std::vector<double> v){int x=sqrt(v.size());for(i=0;i<x;i++){for(j=0;j<x;j++) std::cout << v[x] << " ";std::cout << "\n";}}int main(){std::vector<double> s, c;while(std::cin >> x){s.push_back(sin(x));c.push_back(cos(x));}p(s);p(c);}

```

Input is a list of numbers that are a perfect square on stdin. Output is a pretty printed 2d array on stdout
> 4 votes

# Answer
# Matlab, 37 bytes

```
@(A){imag(expm(i*A));real(expm(i*A))}

```
> 2 votes

# Answer
# Matlab, ~~138 121 52~~ 50 bytes

Since matrix exponentiation is allowed, (what I didnt notice first, d'oh) I do not need to define my helper funciton anymore, and the whole thing can be trivially solved:

```
A=input('')*i;a=expm(A);b=expm(-A);[(b-a)*i,a+b]/2

```

The input should be a matrix e.g. `[1,2;4,5]` or alternatively `[[1,2];[3,4]]`

An unexpected thing (in hindsight not so unexpected) is that the cosine and sine matrix still satisfy

```
I = sin(A)^2+cos(A)^2

```
> 1 votes

# Answer
# Julia 0.4, 28 bytes

```
A->imag({E=expm(im*A),im*E})

```

Input is a matrix of floats, output is an array of matrices. Try it online!
> 1 votes

# Answer
## Sage, 44 bytes

```
lambda A:map(exp(I*A).apply_map,(imag,real))

```

Try it online.

This anonymous function returns a list of 2 matrices corresponding to `sin(A)` and `cos(A)`, respectively. `exp(I*A)` computes the matrix exponential for `I*A` (`A` with all elements multiplied by the imaginary unit), and `matrix.apply_map(f)` returns a matrix where `f` has been applied to all of its elements. By applying `imag` and `real` (the functions for getting the imaginary and real parts of a scalar value) to the matrices, we get the values of `sin(A)` and `cos(A)`, thanks to Euler's famous identity (referenced in the challenge text).
> 0 votes

# Answer
# Itr, 8+9=17 bytes

cosine

```
iäeà~e+½

```

sine:

```
iä~eàe-½i

```

Takes a matrix as input, also works for complex inputs

## Explanation

implements the equations

\\$ \sin(x)= i\*\frac{e^{-ix}-e^{ix}}{2}\\$

\\$ \cos(x)= \frac{e^{ix}+e^{-ix}}{2}\\$

```
i         ; i times the implicit input
 ä        ; duplicate
  ~       ; negate
   e      ; exponential
    à     ; swap
     e    ; exponential
      -   ; subtract
       ½  ; half
        i ; times i
          ; implicit output

```
> 0 votes

---
Tags: code-golf, math, linear-algebra, matrix, trigonometry
---


# Question
Title: Calculate the Distance to a Line Segment
## The Challenge

Given two vertexes and a point calculate the distance to the line segment defined by those points.

This can be calculated with the following psudocode

```
def dist(point, v1, v2):
    direction       := normalize(v2-v1)
    distance        := length(v2-v1)
    difference      := point - v1
    pointProgress   := dot(difference, direction)
    if (pointProgress <= 0):
        return magnitude(point - v1)
    else if (pointProgress >= distance):
        return magnitude(point - v2)
    else
        normal := normalize(difference - (direction * pointProgress))
        return dot(difference, normal)

```

Answers may support either 2 dimensions, or 3, and may optionally support any number of higher or lower dimensions.

As it does not substantially change the difficulty of the challenge, answers need only be accurate to the whole number, and I/O can be assumed to fit within the \[0,127\] range. This is to allow more languages to focus only on the challenge spec, rather than implementing floating points.

## Test Cases

```
1: point=[005,005], v1=[000,000] v2=[010,000] :: distance=005.00 # Horizontal
2: point=[005,005], v1=[010,000] v2=[010,010] :: distance=005.00 # Vertical
3: point=[000,010], v1=[000,000] v2=[010,010] :: distance=007.07 # Diagonal
4: point=[010,000], v1=[000,000] v2=[010,010] :: distance=007.07 # Diagonal, Clockwise
5: point=[000,000], v1=[002,002] v2=[004,008] :: distance=002.83 # Not near the normal
6: point=[000,002], v1=[002,002] v2=[002,002] :: distance=002.00 # Zero length segment

```

## Rules

# Answer
# MATL, 9 bytes

```
9W&ZS-|X<

```

Supports two dimensions. Inputs are complex numbers: first the segment endpoints, then the other point.

Try at MATL it online! Or verify all test cases.

### Explanation

```
9W      % Push 9. Compute 2 raised to that number, that is, 512
&ZS     % Implicit inputs: segment endpoints. Generate vector of 512 evenly
        % spaced numbers in the range defined by the endpoints, including them
-       % Implicit input: point. Subtract, element-wise
|       % Absolute value of each entry
X<      % Minimum. Implicit display

```
> 9 votes

# Answer
# , ~~34~~ 33 bytes

*Edit: -1 byte thanks to Giuseppe*

```
\(p,a,b)min(abs(p-seq(a,b,,1e4)))

```

Attempt This Online!

Input point `p` and segment endpoints `a` and `b` as complex numbers.

Approach copied from Luis Mendo's answer: upvote that!

Accuracy can be improved by changing `1e4` to a higher value (for instance, `1e9` without increasing code-length), but as-is it's easily within the ±1 accuracy in the x,y-range of 0–127.
> 6 votes

# Answer
# Charcoal, ~~65~~ 61 bytes

```
ＵＭθ₂ΣＸＥ§θ⊕κ⁻λ§ιμ²≔§θ⁰η≔⎇η⊗∕₂Π⁻⊘Σθ⁺θ⟦⁰⟧η⌈θζＩ⎇›Ｘ⌈θ²⁺Ｘη²Ｘζ²⌊Φθκζ

```

Try it online! Link is to verbose version of code. Takes input as a list of the two vertices and the point. Explanation:

```
ＵＭθ₂ΣＸＥ§θ⊕κ⁻λ§ιμ²

```

Calculate the lengths of the sides of a triangle with the given points.

```
≔§θ⁰η

```

Get the base of the triangle separately.

```
≔⎇η⊗∕₂Π⁻⊘Σθ⁺θ⟦⁰⟧η⌈θζ

```

Unless the base is zero, divide the triangle's area by it and double the result, giving the altitude.

```
Ｉ⎇›Ｘ⌈θ²⁺Ｘη²Ｘζ²⌊Φθκζ

```

Determine whether the base of the triangle contains the foot, and if so, output the altitude, otherwise output the shorter of the other two sides.

~~58~~ 54 bytes taking complex numbers as input:

```
ＵＭθ↔⁻ι§θ⊕κ≔§θ⁰η≔⎇η⊗∕₂Π⁻⊘Σθ⁺θ⟦⁰⟧η⌈θζＩ⎇›Ｘ⌈θ²⁺Ｘη²Ｘζ²⌊Φθκζ

```

Attempt This Online! Link is to verbose version of code.
> 5 votes

# Answer
# , 32 bytes

```
[:(1#.&.:*:[-]*1<.0>.%. ::0)/-"1

```

Attempt This Online!

Takes input as `v1 f point ,: v2` (a vector `v1` on the left side, and a two-row matrix containing `point` and `v2` on the right side). Supports arbitrary dimensions.

The main approach is to translate `v1` to origin and compute the vector component of `point` onto `v2`. When the value is clamped to the range `[0, 1]`, that times `v2` becomes the point on the line segment that is closest to `point`. Then we can compute the norm of the difference.

```
[:(1#.&.:*:[-]*1<.0>.%. ::0)/-"1    left: v1, right: point ,: v2
                             -"1    (point - v1) ,: (v2 - v1)
[:(                        )/       run dyadically with the two rows as two args:
                     %. ::0     vector component
               1<.0>.           clamp to [0,1]
           [-]*                 get the distance vector
   1#.&.:*:                     norm of the vector

```

`::0` attached to `%.` handles the case of zero-length line segment (if it would throw an error, return 0 instead). `&.:*:` is a fancy way of saying "square something, do something on it, and take its square root".

# , 23 bytes

```
[:([|@-]*1<.0>.9 o.%)/-

```

Attempt This Online!

Same algorithm, but takes a complex number for each vector instead, therefore supporting only two dimensions. `%.` is replaced with `%` (division) followed by `9 o.` (extract real part). Norm is simply `|`.
> 4 votes

# Answer
# JavaScript (Node.js), ~~146~~ ~~144~~ ~~140~~ 156 bytes

-2 bytes because of oversight noted by @noodleman

-4 bytes thanks to @TheThonnu's suggestion

+16 bytes because I noticed my own error with the solution

Algorithm somewhat yoinked from @Neil's Charcoal answer, though with a slightly different method for handling the "segment" of "line segment."

```
(a,b,c,d,e,f,S=Math.sqrt)=>((x,y,z)=>Math.min(S((x+y+z)*(x+y-z)*(x-y+z)*(y+z-x))/2/x,y,z))(S((f-d)**2+(e-c)**2),S((f-b)**2+(e-a)**2),S((d-b)**2+(c-a)**2))

```

`(a,b)` is the point, `(c,d)` is vertex 1, `(e,f)` is vertex 2. Returns a float.

## Versions

### Version 1 (original + oversight fix) (INCORRECT—SEE COMMENTS)

```
(S=>(a,b,c,d,e,f)=>((x,y,z)=>S((x+y+z)*(x+y-z)*(x-y+z)*(y+z-x))/2/x)(S((f-d)**2+(e-c)**2),S((f-b)**2+(e-a)**2),S((d-b)**2+(c-a)**2)))(Math.sqrt)

```

Try this old version online!

### Version 2 (uses default arg instead of separate call) (INCORRECT—SEE COMMENTS)

```
(a,b,c,d,e,f,S=Math.sqrt)=>((x,y,z)=>S((x+y+z)*(x+y-z)*(x-y+z)*(y+z-x))/2/x)(S((f-d)**2+(e-c)**2),S((f-b)**2+(e-a)**2),S((d-b)**2+(c-a)**2))

```

Try this old version online!

### Version 3 (current, fixes issue with solution)

```
(a,b,c,d,e,f,S=Math.sqrt)=>((x,y,z)=>Math.min(S((x+y+z)*(x+y-z)*(x-y+z)*(y+z-x))/2/x,y,z))(S((f-d)**2+(e-c)**2),S((f-b)**2+(e-a)**2),S((d-b)**2+(c-a)**2))

```

## Explanation

```
(a,b,c,d,e,f,S=Math.sqrt)=>(...)

```

The function declaration. Uses `S` as a default argument in this version instead of a different call.

```
((x,y,z)=>...)(S((f-d)**2+(e-c)**2),S((f-b)**2+(e-a)**2),S((d-b)**2+(c-a)**2))

```

This is slightly more efficient than declaring `x,y,z` as variables outright—it uses another one of those define-exec chains. (Is there a canon term for this?)

`x,y,z` are the side lengths for a triangle with vertices at the three points, with `x` being the length of the segment between the two vertices. **THIS IS IMPORTANT.** To find these, I just used the bog-standard distance formula. Nothing special here.

```
Math.min(S((x+y+z)*(x+y-z)*(x-y+z)*(y+z-x))/2/x,y,z)

```

The final part. This calculates the area with \[a slightly modified\] Heron's formula, and then works backwards to find the height with one tiny optimization. It also accounts for the cases where the endpoints are closer with a `Math.min()` call.

## Links

Try this online! This is a link to the golfed version. The verbose version no longer exists as of v2.
> 3 votes

# Answer
## Mathematica (Wolfram Language) 33 bytes

```
RegionDistance[Line[{#2, #3}],#]&

```

Try it online!

This uses Mathematica built-ins, but this program has the benefit of working in any dimension. You could use Mathematica graphics options to see the computation graphically. The TIO link above has the last of the test cases, but in 3D instead of 2D!
> 2 votes

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


title: Golf the fast growing hierarchy

text:
# Question
Title: Golf the fast growing hierarchy
The fast growing hierarchy is a way of categorizing how fast functions are growing, defined the following way (for finite indices):

* \\$ f\_0(n)=n+1 \\$
* \\$ f\_k(n)=f\_{k-1}^n(n)\\$ with \\$f^n\\$ meaning repeated application of the function f

## Examples

```
f0(5) = 6
f1(3) = f0(f0(f0(3))) = 3+1+1+1= 6
f2(4) = f1(f1(f1(f1(4)))) = 2*(2*(2*(2*4))) = 2⁴*4 = 64
f2(5) = f1(f1(f1(f1(f1(5))))) = ... = 2⁵*5 = 160
f2(50) = f1⁵⁰(50) = ... = 2⁵⁰*50 = 56294995342131200
f3(2) = f2(f2(2)) = f2(f2(2^2*2))) = f2(8) = 2^8*8 = 2048
f3(3) = f2(f2(f2(3))) = f2(f2(2³*3)) = f2(2²⁴*24)=2⁴⁰²⁶⁵³¹⁸⁴*402653184 = ...
f4(1) = f3(1) = f2(1) = f1(1) = f0(1) = 2
f4(2) = f3(f3(2)) = f3(2048) = f2²⁰⁴⁸(2048) = ...
...

```

shortcuts:

```
f1(n) = f0(...f0(n))) = n+n*1 = 2*n
f2(n) = f1(... f1(n)...)  = 2^n * n

```

Your goal is to write a program of function that given two positive integers \\$k\\$ and \\$n\\$ outputs \\$f\_k(n)\\$

## Rules

* Given unlimited time and using unbounded integer types the *algorithm* you program is using should compute the correct result of f\_k(n) for arbitrarily large `n` and `k` (even if the program will not finish in the lifetime of the universe)
* Your *program* only has to work for values that fit in a signed 32-bit integer
* Supporting the case \\$k=0\\$ is optional
* This is , the shortest solution in bytes wins

# Answer
> 5 votes
# K (ngn/k), 16 bytes

```
{{y x/y}x}/[;1+]

```

Try it online!

A curried function that takes `k` and then `n`. Call it as `f[k][n]`. (`f[k;n]` doesn't work.)

The trick here is to iterate directly on the function `f`. The formula \\$f\_k(n) = f\_{k-1}^{n}(n)\\$ can be seen as a transformation on a function \\$f\_{k-1}\\$ to \\$f\_k\\$. Given a function `x` (\\$f\_{k-1}\\$) and input value `y` (\\$n\\$), \\$f\_k(n)\\$ can be written as `y x/y`, and `{y x/y}x` is the partially applied function \\$f\_k\\$ that we want. We can iterate this transformation `k` times to \\$f\_0\\$ (`1+`) to get \\$f\_k\\$. However, `k{y x/y}/(1+)` invokes a wrong overload of `/` because `{y x/y}` itself is syntactically dyadic. So I put it in `{...x}` to make it monadic.

# Answer
> 5 votes
# x86 32-bit machine code, 18 bytes

```
4A 78 0C 51 89 C1 E8 F5 FF FF FF E2 F9 59 48 40 42 C3

```

Try it online!

Following the `regparm` calling convention, this takes *n* in EAX and *k* in EDX, and returns a number in EAX. For easier recursion, this function also preserves the values of EDX and ECX (ending with them unchanged).

In assembly:

```
f:  dec edx         # Subtract 1 from k in EDX.
    js z            # Jump if the result is negative (k was 0).
    push ecx        # Save the value of ECX onto the stack.
    mov ecx, eax    # Set ECX to n. This will be the iteration count.
r:  call f          # Recursive call, to apply fₖ₋₁ to EAX.
    loop r          # Subtract 1 from ECX and jump back to repeat if it's nonzero.
    pop ecx         # Restore the value of ECX from the stack.
    dec eax         # Subtract 1 from EAX, cancelling out the next instruction.
z:  inc eax         # Add 1 to n in EAX.
    inc edx         # Add 1 to EDX, restoring the value of k.
    ret             # Return.

```

# Answer
> 4 votes
# K (ngn/k), 19 bytes

```
{y$[x;o@x-1;]/y+~x}

```

Try it online!

```
{y$[x;o@x-1;]/y+~x}    / function with arguments x:k, y:n
  $[x;o@x-1;]          / if x>0, f_(k-1), else identity function
 y           /         / Apply the selected function n times to:
              y+~x     /   n + [0=k]

```

# Answer
> 4 votes
# Python 3, ~~96 79 70 69 63 61 59~~ 58 bytes

```
g=lambda k,n:-~n*(k<1)or eval(f"({'n:=g(k-1,n),'*n})")[-1]

```

It takes time to compute k=2, n=50, but it should be completed after some time...

While this answer is longer, I'm keeping it because it inspired the other two winning answers in Python:

> ~~70 67~~ 65 bytes if Python could handle huge nested parentheses (this answer is allowed, but other golfs based on this are already present, with the other answers being this one by xnor, and this other one by SUTerliakov):
> `f=lambda k,n:n+1if k>1else eval(f"{n*('f(%d,'%(k-1))}{n}{')'*n}")`

# Answer
> 4 votes
# Charcoal, 38 bytes

```
Ｆ²⊞υＮＷ⊖Ｌυ«≔⊟υθ≔⊟υη¿η«Ｆθ⊞υ⊖η⊞υθ»⊞υ⊕θ»Ｉυ

```

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

```
Ｆ²⊞υＮ

```

Push `k` and `n` to the predefined empty list.

```
Ｗ⊖Ｌυ«

```

Repeat until the list only contains one value.

```
≔⊟υθ≔⊟υη

```

Extract `k` and `n` for the deepest recursion depth.

```
¿η«

```

If `k` is non-zero, then...

```
Ｆθ⊞υ⊖η

```

... push `n` copies of `k-1`, representing the recursive calls...

```
⊞υθ

```

... and push `k` back as the argument.

```
»⊞υ⊕θ

```

Otherwise just push `n` incremented as the result of `f0(n)`.

```
»Ｉυ

```

Output the final value.

52 bytes for a version optimised for `k<3`:

```
Ｆ²⊞υＮＷ⊖Ｌυ«≔⊟υθ≔⊟υη≡η⁰⊞υ⊕θ¹⊞υ⊗θ²⊞υ×Ｘ²θθ«Ｆθ⊞υ⊖η⊞υθ»»Ｉυ

```

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

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

```
Nest[fNest[f,#,#]&,#+1&,#]&

```

Try it online!

Input `[k][n]`.

# Answer
> 4 votes
# , 24 bytes

```
>:@]`(<:@[$:^:]])@.(0<[)

```

Attempt This Online!

*-4 thanks to Bubbler for this straightforward approach*

# , ~~28~~ 27 bytes

```
>:@]`(]$:/@,~]#_1+[)@.(0<[)

```

Attempt This Online!

*-1 using thanks to Bubbler's `0<]` instead of `0=]` idea*

This approach conceives uses a reduction which expands its left argument in place recursively:

```
2 f 3
1 1 1 f 3
1 1 0 0 0 f 3
1 1 0 0 f 4
1 1 0 f 5
1 1 f 6
1 0 0 0 f 6
... etc ...

```

And this is what the above code does:

* `@.(0=[)` If the left arg is 0...
* `(1+])` Return 1. Otherwise...
* `]#_1+[` Repeat "left arg minus 1" as many times as the right arg...
* `]...,~` Prepend the right arg...
* `$:/@` And continue reducing the result using this fn.

# Answer
> 4 votes
# , 15 bytes

```
'>:'".@,'^:]'&,

```

Attempt This Online!

Takes `k` on the left as a number, and `n` on the right as a string.

Without `".@`, the function constructs the expression `>:^:]^:] ... ^:]n` as a string, where `^:]` is repeated `k` times.

`f^:]n` applies `f` `n` times to the initial value `n`. \\$f\_0\\$ is increment, which is `>:`. \\$f\_1(n) = f\_0^n(n)\\$ is `>:^:]n`. In general, \\$f\_k(n) = f\_{k-1}^n(n)\\$ can be expressed as `(f_{k-1})^:]n`, and expanded recursively down to `k=0`, we get the expression above.

# Jelly, 9 bytes

```
ẋ@⁾¹¡”‘;v

```

Try it online!

The same strategy applied to Jelly.  (increment) plus `¹¡` (repeat *argument* times) repeated `k` times, evaluated and applied to `n`.

# Answer
> 4 votes
# , 50 bytes

```
f=function(k,n){if(k)for(i in 1:n)n=f(k-1,n);n+!k}

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 39 bytes

A shorter version with a single recursive function suggested by @att.

```
f=(k,n,i=n)=>k*i?f(k-1,f(k,n,i-1)):n+!k

```

Try it online!

---

# JavaScript (ES6), 42 bytes

```
f=(k,n)=>k--?(g=i=>f(k,--i?g(i):n))(n):n+1

```

Try it online!

### Commented

```
f = (k, n) => // f is a recursive function taking (k, n)
k-- ?         // if k is not 0 (decrement it afterwards):
  ( g = i =>  //   g is another recursive function taking a counter i
    f(        //   do a recursive call to f:
      k,      //     pass the updated value of k
      --i ?   //     decrement i, if it's not 0:
        g(i)  //       use the result of a recursive call to g for n
      :       //     else:
        n     //       final call: use n
    )         //   end of recursive call to f
  )(n)        //   initial call to g with i = n
:             // else (k = 0):
  n + 1       //   f0(n) = n + 1

```

# Answer
> 3 votes
# Haskell, 31 bytes

```
0%n=n+1
k%n=iterate((k-1)%)n!!n

```

Try it online!

Writing out the definition.

**34 bytes**

```
q((>>=)id.q)(+1)
q=((!!).).iterate

```

Try it online!

A pointfree mess.

# Answer
> 2 votes
# Python, 50 bytes

```
f=lambda k,n:k and eval(n*'f(k-1,'+'n'+')'*n)or-~n

```

Try it online!

Based on the second solution of UndoneStudios. In practice gives a `MemoryError` for larger values from trying to generate huge strings of Python code.

# Answer
> 2 votes
# Jelly, 10 bytes

```
x@’ßƒ⁸ʋ‘⁹?

```

A dyadic Link that accepts \\$n\\$ on the left and \\$k\\$ on the right and yields \\$f\_k(n)\\$.

**Try it online!**

### How?

```
x@’ßƒ⁸ʋ‘⁹? - Link: integer, n; integer, k
         ? - if...
        ⁹  - ...condition: chain's right argument, k -> k > 0?
      ʋ    - ...then: last four links as a dyad - g(n, k):
  ’        -            decrement {k} -> k-1
 @         -            with swapped arguments:
x          -              {k-1} repeated {n} times -> [k-1,k-1,...,k-1]
     ⁸     -            chain's left argument, n
    ƒ      -            reduce {[n, k-1,k-1,...,k-1]} by:
   ß       -              {current value} this Link {next value}
       ‘   - ...else: increment {n} -> n+1

```

# Answer
> 2 votes
# PARI/GP, 41 bytes

```
f(k,n,i=n)=if(k*i,f(k-1,f(k,n,i-1)),n+!k)

```

Attempt This Online!

A port of @Arnauld's JavaScript answer.

---

# PARI/GP, 49 bytes

```
f(k,n,i)=if(i,f(k,f(k,n,i-1)),k,f(k-1,n,n-1),n+1)

```

Attempt This Online!

# Answer
> 2 votes
# Python, 53 bytes

```
g=lambda k,n:k and[n:=g(k-1,n)for _ in[0]*n][-1]or-~n

```

Attempt This Online!

Does not support \\$ n = 0 \\$; supports \\$ k = 0 \\$.

# Answer
> 1 votes
# Ruby, 39 bytes

```
f=->k,n{k>0?n.times{n=f[k-1,n]}:n+=1;n}

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~51~~ ~~46~~ 43 bytes

```
f(k,n,i){for(i=n;k*i--;)n=f(k-1,n);k=n+!k;}

```

Try it online!

5 bytes shaved off thanks to the `n+!k` trick I saw others do, and 3 more thanks to c-- :)

# Answer
> 1 votes
# Brain-Flak, 92 bytes

```
({}<>)(()){{}((){[()](<({}[()])<>(({})<>){({}[()]<(({}))>)}{}{}>)}{}){({}<>{})(<>)}{}([])}<>

```

Try it online!

Supports \\$k=0\\$ and \\$n=0\\$. Large outputs take an unreasonable amount of time to compute, since no shortcuts are taken for \\$f\_1\\$ or \\$f\_2\\$.

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


# Question
Title: Pick a random string at a fixed edit distance
I have string \\$s\\$ of length \\$n\\$ and some constant integer \\$k\\$ which is at most \\$n\\$. Give the fastest algorithm to sample a random string with Levenshtein distance \\$k\\$ from \\$s\\$ uniformly.

Your algorithm should output any of the strings with edit distance exactly \\$k \leq n\\$ from the input string \\$s\\$ with the same probability. You should assume that only the characters in the string \\$s\\$ are used.

For example, if \\$s\\$ = "1111011010" the number of strings with distance \\$k\\$ is

```
 k | # of results

 0              1
 1             28
 2            302
 3           1652
 4           5533
 5          14533
 6          34808
 7          80407
 8         180663
 9         395923

```

If \\$k\\$ = 9 you should output one of the 395923 possible output strings chosen uniformly at random.

# Answer
> 7 votes
# Python, 3453 bytes

```
import random

def skip():pass

class State:
    states = []
    def __init__(self, accepting=False):
        self.n = len(State.states)
        State.states.append(self)
        self.accepting = accepting
        self.transitions = {}
    def __repr__(self):
        return f'q_{self.n}'
    def add(self, c, s):
        self.transitions.setdefault(c, set()).add(s)
    def __eq__(self, o):
        return self.n == o.n
    def __hash__(self):
        return hash((State, self.n))
    def epsilon_helper(self):
        z = {self}
        if '' in self.transitions:
            for s in self.transitions.pop(''):
                z.update(s.epsilon_helper())
        self.epsilon_helper = lambda:z
        return z
    def remove_epsilon(self):
        self.remove_epsilon = skip
        for a in self.epsilon_helper():
            a.remove_epsilon()
            for x, S in a.transitions.items():
                for b in list(S):
                    b.remove_epsilon()
                    for c in b.epsilon_helper():
                        self.add(x, c)
                        c.remove_epsilon()
    def freeze(self):
        self.freeze = lambda:None
        for c, s in self.transitions.items():
            for x in s:
                x.freeze()
            self.transitions[c] = frozenset(s)
    def count_accepting(self):
        x = self.accepting + sum(s.count_accepting() for S in self.transitions.values() for s in S)
        self.count_accepting = lambda:x
        return x
    def accept(self, w):
        if w == '': return self.accepting
        return any(s.accept(w[1:]) for s in self.transitions.get(w[0],()))
    def pick(self, i):
        if self.accepting:
            if i == 0: return ''
            i -= 1
        for j, s in self.transitions.items():
            s = min(s)
            x = s.count_accepting()
            if i < x:
                return j + s.pick(i)
            i -= x
        raise IndexError

def levenshtein(w, n):
    A = set(w)
    W = len(w)
    states = [[State(j <= i) for j in range(len(w),-1,-1)] for i in range(n,-1,-1)]
    for i, c in enumerate(w):
        for j in range(n):
            s = states[j][i]
            for x in A:
                s.add(x, states[j+1][i])
                if x != c:
                    s.add(x, states[j+1][i+1])
            s.add('', states[j+1][i+1])
            s.add(c, states[j][i+1])
        states[n][i].add(c, states[n][i+1])
    for j in range(n):
        s = states[j][W]
        for x in A:
            s.add(x, states[j+1][W])
    s = states[0][0]
    s.remove_epsilon()
    s.freeze()
    return s

def union(states):
    d = {}
    accepting = False
    for s in states:
        for c, S in s.transitions.items():
            d[c] = d.get(c, frozenset()) | S
        if s.accepting:
            accepting = True
    return d, accepting

def difference(q0, q1, D = None):
    if D is None:
        return difference(frozenset([q0]), frozenset([q1]), {})
    if (q0, q1) in D:
        return D[q0, q1]
    d0, a0 = union(q0)
    d1, a1 = union(q1)
    Q0 = State(a0 and not a1)
    D[q0, q1] = Q0
    for i in set(d0) | set(d1):
        Q0.transitions[i] = frozenset([difference(d0.get(i, frozenset()), d1.get(i, frozenset()), D)])
    return Q0

def exact(w, n):
    if n == 0: raise ValueError
    return difference(levenshtein(w, n), levenshtein(w, n-1))

def f(w, n):
    s = exact(w, n)
    return s.pick(random.randrange(s.count_accepting()))

```

Attempt This Online!

My attempt at implementing user1502040's idea of sampling the DFA.

The algorithm runs in basically three stages:

* First it generates NFAs for `s,k` and `s,k-1` (where each accepts words with at most `k` or `k-1` errors respectively)
    + The NFAs have \\$O(|s|\cdot k)\\$ states, and building them takes time proportional to that (also proportional to the size of the alphabet)
* Then it uses the algorithm outlined in this cs.se answer to find a DFA for the difference of two NFAs
    + This takes the majority of the time, but I'm not sure of the actual complexity. Given that the algorithm is basically the powerset construction, it's worst case exponential, but it appears to do better than that. (I found an algorithm that can find a DFA for a given word with `<=k` errors that takes time linear with respect to the length of the word (for fixed k). See Schulz and Mihov (2002)).
    + I tried graphing the number of states in the DFA for `s="1111011012"` and `k` from `1` to `30` and it appeared linear (especially for `k>10`), but I also tried `s="the quick brown fox jumps over the lazy dog"` and `k` from `1` to `7` and it appeared exponential. \**
* It counts the number of states, and picks a random index and chooses the path with that index in a preorder traversal of the DFA. (am I using my jargon right?)
    + This takes time linear in the size of the DFA (using dynamic programming).

In practice, the program appears to run quite quickly; it takes about 5 seconds for `s="the quick brown fox jumps over the lazy dog"` and `k=5`.

\** For some reason the image feature isn't working for me, so here is the data: `[35, 101, 228, 436, 722, 1080, 1464, 1833, 2184, 2519, 2844, 3162, 3480, 3798, 4116, 4434, 4752, 5070, 5388, 5706, 6024, 6342, 6660, 6978, 7296, 7614, 7932, 8250, 8568]` and `[172, 669, 2579, 10226, 40094, 155722, 606044]`

# Answer
> 6 votes
# Python, 932 bytes, \\$O(4^k\cdot n^{2k+2})\\$

```
import random
def levenshteinDistance(s,t):
  m=len(s);
  n=len(t);
  d=[(n+1)*[0]for _ in range(m+1)]
  for i in range(m+1):
    d[i][0]=i
  for j in range(n+1):
    d[0][j]=j
  for j in range(n):
    for i in range(m):
      if s[i] == t[j]:
        substitutionCost = 0
      else:
        substitutionCost = 1
      d[i+1][j+1] = min(d[i][j+1] + 1,                # deletion
                         d[i+1][j] + 1,               # insertion
                         d[i][j] + substitutionCost)  # substitution
  return d[m][n]

def build(s,k,i0=0):
  if k==0:
    yield s;return
  for i in range(i0,len(s)+1):
    t=s[:i]+s[i+1:]
    for q in build(t,k-1,i):
     yield q
    for c in set(s):
      t=s[:i]+c+s[i+1:]
      for q in build(t,k-1,i):
       yield q
      t=s[:i]+c+s[i:]
      for q in build(t,k-1,i):
       yield q

def f(s,k):
  return random.choice([t for t in set(build(s,k))if levenshteinDistance(s,t)==k])

```

Attempt This Online!

Runs in \\$O(n(n+k)(2n(n+k))^k\\$

Generates all possible strings reachable with k edits, then pick a random string with edit distance k.

The filtering by edit distance is necessary to filter out combinations of edits the can be expressed by a shorter edit sequence (e.g. `Hello` -\> `HHello` -\> `Heello` -\> `Hello`), I did not find any generation rule that reliably avoids every possible way to generate a shorter edit sequence.

## Running time:

*I am not that familiar with estimating the exact running time of recursive functions, so there might be a mistake in my calculations*

`levenshteinDistance(s,t)` runs in \\$O(|s||t|)\\$

setting \\$n=|s|\\$

`build(s,k,i)` runs in \\$b(l,k,i)=O(\sum\_{j=i}^{l}\*(b(l-1,k-1,j)+n(b(l+1,k-1,j)+b(l,k-1,j)))\\$ \\$=\sum\_{j=i}^{l}\*O((2n+1)\*b(l+1,k-1,j))=O(((n+k)\*(2n+1))^k)\\$

`f` runs in \\$O(((n+k)\*(2n+1))^k)\*O(n(n+k))=O(n(n+k)(2n(n+k))^k)\\$

or assuming \\$k\le n\\$ \\$O(n(n+n)(2n(n+n))^k)=O(4^k\cdot n^{2k+2})\\$

# Answer
> 4 votes
# Python, \\$\mathcal{O}((n+k)^{2k})\leq\mathcal{O}(4^k n^{2k})\\$

```
from random import choice
from collections import deque
from sys import stderr

def randomWithFixedDistance(s: str, k: int) -> str:
  if k <= 0: return s

  chars: set[str]          = set(s)
  distances: dict[str,int] = {s: 0}
  queue                    = deque((s,))
  valid: set[str]          = set()

  while len(queue) > 0:
    current = queue.popleft()
    nextdist = distances[current] + 1
    for nxt in insertions(current, chars) | substitutions(current, chars) | removals(current):
      if nxt in distances: continue
      distances[nxt] = nextdist
      if nextdist < k:
        queue.append(nxt)
      else:
        valid.add(nxt)

  print(f"DEBUG: Found {len(valid)} possible strings", file=stderr)
  return choice(list(valid))

def insertions(s: str, chars: set[str]) -> set[str]:
  result = set()
  for i in range(len(s)+1):
    result.update(s[:i] + c + s[i:] for c in chars)
  return result

def substitutions(s: str, chars: set[str]) -> set[str]:
  result = set()
  for i in range(len(s)):
    result.update(s[:i] + c + s[i+1:] for c in chars if c != s[i])
  return result

def removals(s:str) -> set[str]:
  return set(s[:i] + s[i+1:] for i in range(len(s)))

```

Attempt This Online!

Uses BFS to construct the sampling list, by using the principles of how Levenshtein distance is calculated to walk through the set of insertions, substitutions and deletions necessary. The process used actually looks somewhat similar to bsolech's answer, but without the need to check the Levenshtein distance of every resulting string at the end, since it keeps track of the growing distances while building the list. I believe this makes it faster than their answer by an order of about \\$O(n^2)\\$, although it's still nowhere near close to gsitcia's answer. Oh well.

Efficiency reasoning is as follows:

1. \\$f(s,1)\\$ looks at up to \\$n\times(n+1)\\$ insertions, which is \\$\mathcal{O}(n^2)\\$. Substitutions and deletions are always fewer than insertions, being \\$n\times(n-1)\\$ and \\$n\\$ respectively, so they get wrapped into this big-O.
2. \\$f(s,k)\\$, for each of the strings from \\$f(s,k-1)\\$, looks at a number of strings on the order of \\$\mathcal{O}((n+k)^2)\\$, so \\$\mathcal{O}((n+k)^2 \times f(s,k-1))\\$.
3. This means the entire function is \\$\mathcal{O}(\prod\_{i=1}^k (n+i)^2) = \mathcal{O}((n+k)^{2k})\\$. And since \\$k\leq n\\$ this can also be expressed as the (IMO) cleaner \\$\mathcal{O}((2n)^{2k}) = \mathcal{O}(2^{2k} n^{2k}) = \mathcal{O}((2^2)^k n^{2k}) = \mathcal{O}(4^k n^{2k})\\$.

---
Tags: fastest-algorithm, probability-theory, edit-distance
---