title: Show the input RGB color

text:
# Question
Title: Show the input RGB color
Write a program that takes R, G, and B values as command arguments and then displays that color some way. It doesn't matter how, as long as at least 100 pixels have the color. Shortest code wins.

# Answer
## JavaScript, 25

```
document.bgColor=prompt()

```

You'll have to specify the three components in hexadecimal. This is code golf, so no commas or whitespace.
> 17 votes

# Answer
# JavaScript, 57 characters

```
document.body.setAttribute('bgcolor','rgb('+prompt()+')')

```

Enter the RGB values in the prompt input box, comma separated.

(I feel so dirty, using `bgcolor` :O )
> 4 votes

# Answer
## xterm: 18 bytes

```
xterm -bg \#$1$2$3

```

Input the color as three 1- or 2-digit hex numbers, e.g., if this command is in the file "xterm.sh", then

```
./xterm.sh ff 00 00
./xterm.sh f 0 0

```

opens a terminal window with a red background.

If you prefer, you can omit the blanks between the components:

```
./xterm.sh f00

```

The "-bg" option is not available in some old versions of xterm. It's missing from version 271 but present in versions 215, 251, 261, and 297.
> 4 votes

# Answer
# Bash, 69

```
read c;set $c;printf '\e]4;1;rgb:'"$1"'/'"$2"'/'"$3"'\e\\\e[31mc\e[m'

```

Partially stolen from here.

Just input your values in hex (e.g. FF 00 00).

Tested on `xterm-256color`.

# Bash, 43

```
printf '\e]4;1;rgb:FF/00/00\e\\\e[31mc\e[m'

```

Here you have to input the values yourself.

**Edit**: For 100 Pixels+ Just choose font-size infinite :D.
> 2 votes

# Answer
# Javascript in PCCG, 65 ~~105~~

**Edit 2** shortened as suggested by @manatwork

**Edit** Thanks @blender

```
question.style.background='#'+prompt('R G B').split(' ').join('')

```

Just for fun
> 1 votes

# Answer
## Bash/sh + ImageMagick: 28 bytes

```
display -size 96 xc:\#$1$2$3

```

Input the color as three 1- or 2-digit hex numbers, with or without whitespace between them.
> 1 votes

# Answer
**C# WPF : 54**

```
new Windows(){Background=Color.FromArgb(RGB);}.Show();

```
> 1 votes

# Answer
# Postscript ~~61~~ 56

Fills the graphics window with the color, components as decimals in the range 0..1.

```
ARGUMENTS{cvr}forall setrgbcolor clippath fill showpage

```

Run using ghostscript's `--` option which enables argument processing.

```
gs -- rgb.ps .9 .2 .2

```
> 1 votes

# Answer
# Java, 215

```
import java.awt.*;class C{public static void main(String[]a){Frame f=new Frame();f.setSize(9,99);f.setBackground(new Color(Integer.parseInt(a[0]),Integer.parseInt(a[1]),Integer.parseInt(a[2])));f.setVisible(true);}}

```
> 0 votes

# Answer
# Tcl/Tk, 15

```
. co -bg #$argv

```
~~Tcl/Tk, 22
```
. configure -bg #$argv

```~~

If called with

```
wish show_color.tcl 6666AA

```

one gets

~~Tcl/Tk, 27
```
grid [canvas .c -bg #$argv]

```
If called with
```
wish show_color.tcl 6666AA

```
one gets
~~
> 0 votes

---
Tags: code-golf
---


# Question
Title: Program template for printing *any* string
Write a program with the following properties:

* When run as-is, the program produces no output (i.e. 0 bytes of output).
* There is a location within the program (of your choice: it could be at the start, end, or somewhere in the middle) with the following property: modifying the program via placing *any* string there will cause the resulting program to print that string when executed.

This must work regardless of whether the string contains quotes, backslashes, comment marks, delimiters, NUL bytes, etc.; no matter what you place there, the string is still interpreted as a string and printed entirely verbatim. You can, however, fail to handle very very long strings if they would cause the compiler to run out of memory, or the like (to be precise, you should at least be able to handle strings up to 1000 bytes long or three times the length of your program, whichever is longer).

An example of an *invalid* solution would be

```
print("");
#      ^ text goes here

```

in Python, Perl, Ruby, etc.; although it works for many strings, it will not work for a string containing a double quote, or a string containing the substring `\n` (which would be interpreted as a newline).

Note that this problem is probably impossible in most languages; the challenge is at least partially about finding a language where it works. Your chosen language must be a programming language under this site's definition, e.g. no submitting a solution in Text.

As this is a , the shortest program template wins. However, do not be discouraged from submitting solutions even if they can't beat the current winner! You can still compete for second, third, etc. place, or simply to find as many answers where it works as possible. You should, however, ensure that your program meets the entire specification before submitting it; approximate solutions would miss the point of the problem.

# Answer
## Excel, 1 byte

```
'

```

Ungolfed version

```
'        <-- print the following text,
             and exit the current formula

```
> 37 votes

# Answer
# Jolf, 6 bytes

```
a Lq6(

```

## Explanation

```
a Lq6(
a       print
  L 6   all but the first 6 characters of
   q    the source code
     (  and exit

```
> 20 votes

# Answer
# Zsh, 6 bytes

```
<<'
'

```

There is a trailing newline. The string is inserted at the end of the program.

# Bash, ~~20~~ 17 bytes

Thanks to Adam for removing 3 bytes.

```
exec sed 1d "$0"

```

# \*nix shell script, ~~21~~ 14 bytes

Thanks to Adam for removing 7 bytes.

```
#!/bin/sed 1d

```
> 14 votes

# Answer
# Perl 5, ~~30~~ ~~21~~ 19 bytes

```
print<DATA>__END__

```

Try it online!

Trailing newline. This makes use of a Perl feature which allows arbitrary data to be appended to the source file, which can then be read via the `DATA` filehandle. When we give a filehandle as an argument to `print`, it's given a list context, which causes the filehandle to return a list of all the lines in the file, newlines included (likewise, a newline on the final line will be omitted). Then `print` implicitly concatenates them all, undoing the splitting into lines and giving us the exact original string regardless of where the newlines were.

Thanks to @Dada, who realised there was no need to handle newlines manually, and @ninjalj and @b\_jonas, who each spotted a character which could be golfed off.
> 14 votes

# Answer
# brainfuck (Unreadable Brainfuck), 9 bytes

```
,+[-.,+]!

```

Append the input to the end. There isn't a trailing newline, this time.

Looking for languages which would accept input appended to the end of the program, brainfuck seemed like a distinct possibility; many brainfuck interpreters written in esolangs take both the program and the program's input from standard input, and thus need some way to tell between them. There's a convention that's used in this case that a `!` character differentiates between the program and the input, a trick that's often used to write short brainfuck programs like `,[.,]!Hello, world!`; this basically creates a different dialect of brainfuck in which `!` has a different meaning from normal.

In theory, therefore, we could just find one of these interpreters and give it a `cat` program in order to fulfil the spec. There's a major subtlety, though; brainfuck typically uses 256 values for each cell, there are 256 octets, and one needs to be used for EOF. So if we want to be able to echo all 256 octets literally, we can't detect EOF at all and will need to end the program some other way. In other words, we need to find an implementation that either gives the 256 octets and EOF 257 different values, or that crashes on EOF.

Enter Unreadable. There's a brainfuck interpreter in Unreadable that predates this challenge, and which accepts input after an `!`; additionally, unlike most brainfuck interpreters, it uses bignum cells and -1 for EOF, allowing EOF to be distinguished from the other 256 possible octets. Thus, by use of Unreadable Brainfuck as the specific interpreter for the program, we can solve the challenge in just 9 bytes, via writing a brainfuck `cat` program that halts on EOF=-1.

Is it possible to do better? Well, we could try the following 7-byte program, which attempts to *output* EOF at the end of the string before it breaks out of the loop:

```
+[,.+]!

```

The behaviour of this program depends on the behaviour of the Unreadable interpreter on error conditions (thus, it depends not only on the implementation of brainfuck, but on the implementation used to *run* the implementation of brainfuck). Unfortunately, the Unreadable interpreter I use outputs errors on standard *output*, meaning that this saving doesn't work. If anyone knows of an Unreadable interpreter that exits on an attempt to output EOF, or silently skips the attempt, let me know; that would be a seven-byte solution right there.
> 13 votes

# Answer
# Dyalog APL, 11 bytes

The following is the body of the function *f*:

```
2↓⎕CR'f'⋄→

```

There is a trailing newline, after which anything may be inserted.

`2↓` drop the first two lines (header and this line) of

`⎕CR'f'` the **C**haracter **R**epresentation of *f*

then

quit
> 9 votes

# Answer
# Ruby, 20 bytes

```
print *DATA
__END__

```

Input goes at the end (after the trailing newline). The `DATA` idiom is one of many that Ruby stole from Perl.

Try it on eval.in: https://eval.in/684370
> 9 votes

# Answer
# JavaScript + HTML5 DOM, 163 Bytes

```
<html><body><script>fetch(location).then((r)=>r.text().then((t)=>console.log(t.slice(145,t.lastIndexOf("</b")))));document.body.remove()</script></body></html>

```

You may insert anything you like directly before the closing body tag. This works by fetching the page source and stripping the opening code and the closing tags.

The real kicker was figuring out how to escape an infinite loop. Putting `while(true){}` in the page blocks all callbacks forever, freezing the execution, and JavaScript has no way of pausing the main thread. However, code that no longer exists never runs, so the document body commits seppuku in the very last command, deleting itself while it waits for its clone to load.

Yeah, it's long and roundabout, but the mere fact that it's possible in JS is kind of amazing.
> 9 votes

# Answer
# PHP, 46 bytes

(including the trailing linebreak)

```
<?=join([""]+file(__FILE__));halt_compiler();
STRING HERE

```

Yes: even the `file` function is binary safe.

`[""]+` replaces the 0-index (first line of the file) with an empty string
> 7 votes

# Answer
# gs2, 4 bytes

```
╥¶=☼

```

Uses CP437 encoding. The string goes at the end.  gets the source code,  pushes 4, `=` drops that many leading characters, and  exits.

Try it online!
> 6 votes

# Answer
# PHP 94 bytes

```
<?$f=fopen(__FILE__,'rb');fseek($f,93);while(false!==($c=fgetc($f)))echo$c;__halt_compiler();

```

Place your string after the final semicolon.

Yay for obscure features I guess? \__halt\_compiler() does exactly what you'd expect from the name. The prior code just opens the file and writes any bytes after that last semicolon to stdout. NUL, BEL etc come out fine. Unicode literals (♪) get screwed up on Windows but I think that's just Windows cmd failing at unicode.
> 5 votes

# Answer
# Perl 6, 23 bytes

```
print $=finish
=finish

```

The string is placed starting on the newline after `=finish`.
> 3 votes

# Answer
# PHP, ~~48~~ 60 bytes

```
<?=substr(file_get_contents(__FILE__),60);__halt_compiler();STRING HERE

```

Just became aware that closing PHP does not prevent the string from containing `<?`.
> 3 votes

# Answer
# Bash, 17 bytes

```
tail -n+3 $0
exit
<string here>

```

Developed independently of jimmy23013's answer.
> 2 votes

# Answer
# Binary Lambda Calculus, 1 byte

```
 [text goes here]

```

That’s a single space (0x20) before the text.

Try it online!

### How it works

0x20 = 001000002 is parsed as

```
00    λx.
01        x
0000  (ignored, can be anything)

```

(So in fact, any of the characters `!"#$%&\'()*+,-./` will work equally well.)

Since this is a complete expression, the remainder of the program is interpreted as input data, and under the binary lambda calculus I/O conventions, the identity function λ*x.* *x* copies the input directly to the output.
> 2 votes

# Answer
# RProgN, 19 Bytes

```
Q 19 Q L sub exit

```

Note the trailing space.

Insert any text after that chunk and it will be printed.

Based off of Lynn's gs2 answer.

Try it Online!
> 1 votes

# Answer
# Excel VBA, 6 Bytes

This is mainly to answer the question of how to print the text as held in Adam's Answer to the Immediates Window in the VBA environment

## Basic Setup:

In cell *A1* in the activesheet the use the formula below to hold the string to be printed. *For the sake of byte counting this shall add 1 Byte*

```
'[Your Text Here]

```

eg:

```
'Hello
World

```

## Immediates Window Function, 5 + 1 = 6 Bytes

```
?[A1]

```

+1 Byte for a `'` in cell A1
> 1 votes

# Answer
# Vim (in ex mode), 28 bytes

```
#!/bin/ex -c ':1d' -c ':wq'
[string]

```

28 bytes is including the last newline.
> 0 votes

# Answer
# Vim, 738 bytes

```
:imap <esc> <c-v><esc>
:imap <c-a> <c-v><c-a>
:imap <c-b> <c-v><c-b>
:imap <c-c> <c-v><c-c>
:imap <c-d> <c-v><c-d>
:imap <c-e> <c-v><c-e>
:imap <c-f> <c-v><c-f>
:imap <c-g> <c-v><c-g>
:imap <c-h> <c-v><c-h>
:imap <c-i> <c-v><c-i>
:imap <c-j> <c-v><c-j>
:imap <c-k> <c-v><c-k>
:imap <c-l> <c-v><c-l>
:imap <c-m> <c-v><c-m>
:imap <c-n> <c-v><c-n>
:imap <c-o> <c-v><c-o>
:imap <c-p> <c-v><c-p>
:imap <c-q> <c-v><c-q>
:imap <c-r> <c-v><c-r>
:imap <c-s> <c-v><c-s>
:imap <c-t> <c-v><c-t>
:imap <c-u> <c-v><c-u>
:imap <c-v> <c-v><c-v>
:imap <c-w> <c-v><c-w>
:imap <c-x> <c-v><c-x>
:imap <c-y> <c-v><c-y>
:imap <c-z> <c-v><c-z>
:imap <c-@> <c-v><c-@>
:imap <c-\> <c-v><c-\>
:imap <c-]> <c-v><c-]>
:imap <c-^> <c-v><c-^>
:imap <c-?> <c-v><c-?>
i

```

Rebinds all control characters in insert mode to `<c-v>`, followed by that control character, which will enter them literally. ^\_ (unit seperator) doesn't seem to need rebinding, as it gets outputted literally by default.

The variable text comes at the end, of course.
> 0 votes

---
Tags: code-golf, source-layout
---


title: Grid ASCII art code golf

text:
# Question
Title: Grid ASCII art code golf
# Challenge

Create the shortest program that meets the requirements

## Requirements

1. The code must generate a 5x5 grid of 0s, like so:

```
00000
00000
00000
00000
00000

```
2. The code must accept an input (column, row, character). The grid must change accordingly:

Start:

```
00000
00000
00000
00000
00000

```

Input:

```
(2,5,*)

```

Output:

```
0*000
00000
00000
00000
00000

```

(Note: the bottom-left corner is position 1,1.)
3. The program must return an error message other than the grid if the row/column input is not 1,2,3,4, or 5. This can be any message of your choice (as long as it's not the grid), so `0` is an acceptable error-output.
4. The program must work with all printable ASCII characters (of a US keyboard).

## THE WINNER

The winner will be the person who has the shortest code and fulfills all requirements. If more than one answer works and has the same (shortest) length, the person who answered first will be the winner.

# Answer
# Dyalog APL, ~~17~~ ~~13~~ 10 bytes

Prompts for an enclosed array containing (row, column) and then for a character. Gives INDEX ERROR on faulty input.

```
⊖⍞@⎕⊢5 5⍴0

```

Try it online!

flip upside-down the result of

inputted-character

`@` replacing the content **at** position

evaluated-input (enclosed row, column)

of

`5 5⍴` 5×5 array of

`0` zeros
> 11 votes

# Answer
## Ruby, ~~157~~ 149 bytes

```
g=(1..5).map{[0]*5}
loop{puts g.map(&:join).join ?\n
x=gets.match /\((.),(.),(.)\)/
a,b=x[1].hex,x[2].hex
1/0 if a<1||a>5||b<1||b>5
g[5-b][a-1]=x[3]}

```

Error on malformed input or out of bound position

Thanks to ConorO'Brien (8 bytes) and afuous (2 bytes) for helping saving bytes
> 5 votes

# Answer
## Batch, 199 bytes

```
@echo off
if %1 gtr 0 if %1 lss 6 if %2 gtr 0 if %2 lss 6 goto g
if
:g
for /l %%j in (5,1,-1)do call:l %* %%j
exit/b
:l
set s=000000
if %2==%2 call set s=%%s:~0,%1%%%3%%s:~%1%%
echo %s:~1,5%

```

Errors out if the position is out of range.
> 4 votes

# Answer
# PHP, ~~111~~ ~~100~~ 97 bytes

```
$s=str_repeat("00000\n",5);$s[($x=($a=$argv)[1])+29-6*$y=$a[2]]=$a[3];echo$x&&$y&&$x<6&$y<6?$s:E;

```

prints `E` if row/column out of range.
Run with `php -r <code> <row> <column> <character>`
> 3 votes

# Answer
## Python, 66 bytes

```
lambda a,b,n,l='00000\n':6>b>0<a<6and(5-b)*l+l[:a-1]+n+l[a:]+~-b*l

```
> 3 votes

# Answer
# Dyalog APL, ~~24~~ ~~20~~ 18 bytes

Saved 4 bytes thanks to Zgarb! Saved 2 bytes thanks to Adam!

```
a←5 5⍴0⋄a[⊂⎕]←⍞⋄⊖a

```

Prompts for input. See below for an explanation.

---

## 20 bytes

```
{a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a}

```

Assign to a function and call it `y x f 'c'`. E.g.:

```
      f←{a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a}

      5 2 f '*'
0 * 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

      6 6 f '*'
INDEX ERROR
     ←{a←5 5⍴0 ⋄ a[⊂⍺]←⍵ ⋄ ⊖a}
               ∧

      0 0 f '*'
INDEX ERROR
     ←{a←5 5⍴0 ⋄ a[⊂⍺]←⍵ ⋄ ⊖a}
               ∧

```

## Explanation

```
{a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a}

```

`{...}` is a function with left argument  and right argument .  separates statements, so there are three statements:

```
a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a

```

The first statement `a←5 5⍴0` sets `a` to a `5` by `5` grid of `0`s.

The second statement sets the member at coordinates dictated by  to  (that is, the character).

Finally, we perform  on `a` and return that, yielding the firsts of `a` reversed.
> 3 votes

# Answer
## JavaScript (ES6), ~~73~~ 76 bytes

Throws a `TypeError` if the column or the row is out of range.

```
(c,r,C,a=[...`00000
`.repeat(5)])=>(a[29+c-r*6]=C,c<1|r<1|c>5|r>5||a).join``

```

### Demo

```
let f =

(c,r,C,a=[...`00000
`.repeat(5)])=>(a[29+c-r*6]=C,c<1|r<1|c>5|r>5||a).join``

console.log(f(2,5,'*'));
```
> 3 votes

# Answer
# C#, 199 Bytes

Based on Pete Arden's answer

```
string g(int c, int r, char a){if(c<1|c>5|r<1|r>5)return "Index Error";var b="00000";var d=new[]{b,b,b,b,b};c--;d[r-1]=new string('0',c)+a+new string('0',4-c);return string.Join("\r\n",d.Reverse());}

```

Ungolfed:

```
public static string G(int c, int r, char a)
    {
        if (c < 1 || c > 5 || r < 1 || r > 5) return "Index Error"; // Check it's not out of range
        var b = "00000";
        var d = new [] { b, b, b, b, b };                           // Generate display box, and fill with the default character
        c--;                                                        // Convert the X to a 0 based index
        d[r - 1] = new string('0',c) + a + new string('0',4-c);     // Replace the array's entry in y coordinate with a new string containing the new character
        return string.Join("\r\n", d.Reverse());                    // Reverse the array (so it's the right way up), then convert to a single string
    }

```
> 3 votes

# Answer
# Jelly, 28 bytes

This feels way too long...

```
Ṫ0ẋ24¤;ṙÑs5UY
’ḅ5
Ṗḟ5R¤
-ÑÇ?

```

**TryItOnline!**

### How?

```
Ṫ0ẋ24¤;ṙÑs5UY - Link 1, make grid: [row, column, character] e.g. [5,2,'*']
Ṫ             - tail: character                                  '*'
     ¤        - nilad followed by link(s) as a nilad
 0            -     zero
  ẋ           -     repeated
   24         -     24 times                                     [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
      ;       - concatenate:                                     "000000000000000000000000*"
        Ñ     - call next link (2) as a monad                    21
       ṙ      - rotate left by                                   "000*000000000000000000000"
         s5   - split into chunks of length 5                    ["000*0","00000","00000","00000","00000"]
           U  - upend (reveres each)                             ["0*000","00000","00000","00000","00000"]
            Y - join with line feeds                              0*000
              - implicit print                                    00000
                                                                  00000
’ḅ5 - Link 2, position: [row, column]                             00000
’   - decrement                                                   00000
 ḅ5 - convert from base 5

Ṗḟ5R¤ - Link 3, input error checking: [row, column, character]
Ṗ     - pop: [row, column]
 ḟ    - filter out values in
  5R¤ - range(5): [1,2,3,4,5] - any values not in this remain giving a truthy result

-ÑÇ? - Main link: [row, column, character]
   ? - ternary if:
  Ç  -    last link (3) as a monad
-    -    -1 (if truthy - the error identification)
 Ñ   - next link (1) as a monad (if falsey - the grid)

```
> 2 votes

# Answer
# 05AB1E, ~~27~~ 22 bytes

Returns no grid when row/column \> 5.

```
‚6‹Pi25L²<5*¹+Q5äR»1³‡

```

Try it online!

**Previous version**

```
‚6‹Pi26G¾5²<*¹+NQi\³}})5äR»

```
> 2 votes

# Answer
# JavaScript (ES6), 89 bytes

```
f=(X,Y,Z,x=5,y=5)=>x+y>1?(x?X+x-6|Y-y?0:Z:`
`)+f(X,Y,Z,x?x-1:5,y-!x):X<1|X>5|Y<1|Y>5?e:""

```

Because I love recursion. Throws a `ReferenceError` on invalid coordinates.
> 2 votes

# Answer
# Excel VBA, 67 Bytes

Outputs to the range *A1:E5* on the activesheet of the vba project, exits with

> Run-time error '1004':
>
> Application-defined or object-defined error

when an invalid input is provided.

**Code:**

```
Sub a(c,r,x)
c=IIf(r<1Or c>5,-1,c)
[A1:E5]=0
Cells(6-r,c)=x
End Sub

```

**Usage:**

```
a 4,5,"#"

```

**Output** (from example above)**:**

```
    A   B   C   D   E
1   0   0   0   #   0
2   0   0   0   0   0
3   0   0   0   0   0
4   0   0   0   0   0
5   0   0   0   0   0

```
> 2 votes

# Answer
**Mathematica, 38 bytes**

```
(x=Table[0,5,5];x[[-#2,#]]=#3;Grid@x)&

```
> 2 votes

# Answer
# Brain-Flak 415 Bytes

Includes +3 for `-c`

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

```

Try it Online!

Takes the character to insert first, then the row then column without spaces.

Most of this is just error handling. Brain-Flak doesn't have a good way to check if values are in a range. For errors, it either outputs nothing, or just the character that was supposed to be inserted. Solving the actual problem only takes 211 bytes:

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

```
> 2 votes

# Answer
# C#, 208 Bytes

Golfed:

```
string G(int c,int r,char a){if(c<1||c>5||r<1||r>5)return"Index Error";var b="00000";var d=new string[]{b,b,b,b,b};d[r-1]=d[r-1].Substring(0,c-1)+a+d[r-1].Substring(c);return string.Join("\r\n",d.Reverse());}

```

Ungolfed:

```
public string G(int c, int r, char a)
{
  if (c < 1 || c > 5 || r < 1 || r > 5) return "Index Error";
  var b = "00000";
  var d = new string[] { b, b, b, b, b };
  d[r - 1] = d[r - 1].Substring(0, c - 1) + a + d[r - 1].Substring(c);
  return string.Join("\r\n", d.Reverse());
}

```

Testing:

```
Console.Write(G(6, 6, '*')); //Index Error

Console.Write(G(1, 4, '#'));

00000
#0000
00000
00000
00000

Console.Write(G(5, 5, '@'));

0000@
00000
00000
00000
00000

Console.Write(G(1, 1, '}'));

00000
00000
00000
00000
}0000

```
> 1 votes

# Answer
## QBIC, ~~53~~ 50 bytes

EDIT: Now that I know that I don't have to show the starting grid, I've swapped out the user inputs `_!_!_?` for command line parameters `::;`, saving 3 bytes.

```
[5|?@00000|]::;~(b>5)+(c>5)>1|_Xd\$LOCATE 6-c,b|?B

```

Original version: This halts between printing the 0-grid and taking the coordinates for the substitution, showing the 0-grid.

```
[5|?@00000|]_!_!_?~(b>5)+(c>5)>1|_Xd\$LOCATE 6-c,b|?B

```

Prints 5 strings of 5 `0`'s, asks user for 2 numerical inputs and 1 string input, checks if the numbers are \< 5 and uses QBasic's `LOCATE` function to substitute the right character.
> 1 votes

# Answer
# WinDbg, 95 bytes

```
j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0

```

Almost half of it just verifying the indexes are in range... Input is done by setting the psuedo-registers `$t0`, `$t1`, and `$t2` (where `$t2` holds the ascii value of the char to replace). For example, `(2,5,*)` like the example would be:

```
0:000> r$t0=2
0:000> r$t1=5
0:000> r$t2=2a

```

Prints `0` on error.

How it works:

```
j (0<(@$t0|@$t1)) & (6>@$t0) & (6>@$t1)  * If $t0 and $t1 are both positive and less than 6
'
    f 8<<16 L19 30;                      * Put 19 (0n25) '0's (ascii 30) at 2000000 (8<<16)
    eb 2000018+@$t0-@$t1*5 @$t2;         * Replace the specified cell with the new char
    da /c5 8<<16 L19                     * Print 19 (0n25) chars in rows of length 5
';
    ?0                                   * ...Else print 0

```

Sample Output:

```
0:000> r$t0=2
0:000> r$t1=5
0:000> r$t2=2a
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Filled 0x19 bytes
02000000  "0*000"
02000005  "00000"
0200000a  "00000"
0200000f  "00000"
02000014  "00000"

0:000> r$t0=-2
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Evaluate expression: 0 = 00000000

0:000> r$t0=4
0:000> r$t1=2
0:000> r$t2=23
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Filled 0x19 bytes
02000000  "00000"
02000005  "00000"
0200000a  "00000"
0200000f  "000#0"
02000014  "00000"

0:000> r$t1=f
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Evaluate expression: 0 = 00000000

```
> 1 votes

# Answer
## Haskell, 77 bytes

```
r=[1..5]
(x#y)c|x>0,x<6,y>0,y<6=unlines[[last$'0':[c|i==x,j==6-y]|i<-r]|j<-r]

```

Usage example:

```
*Main> putStr $ (2#5) '*'
0*000
00000
00000
00000
00000

```

If `x` and `y` are within range, outer and inner loop through `[1..5]` and take the char `c` if it hits the given `x` and `y` and a `0` otherwise. If `x` or `y` is not in range, a `Non-exhaustive patterns` exception is raised.
> 1 votes

# Answer
# Octave 49 bytes

```
@(c,r,s)char(accumarray([6-r c],s+0,[5 5],[],48))

```
> 1 votes

# Answer
# Java, 99 bytes

```
(i,j,k)->{int[]b=new int[]{60,60,60,60,60};int[][]a=new int[][]{b,b,b,b,b};a[i-1][5-j]=k;return a;}

```
> 0 votes

# Answer
# Vim, ~~60~~ ~~47~~ ~~42~~ 76 keystrokes

Input is in the format (on the first line):

```
25*

```

With the cursor starting at the beginning

```
"ax"bxx:if<C-r>a<1||<C-r>a>5||<C-r>b<1||<C-r>b>5
^
endif
6i0<ESC>Y5pG:norm <C-r>al<C-r>bkr<C-r>-
Hqqxjq5@qdd

```

If the input is invalid, then throws: `E492: Not an editor command: ^`

The cide that produces the output is only `42` bytes, but in order to create an error, my bytecount is drastically increased.
> 0 votes

# Answer
# Bash, 59 bytes

**Golfed**

```
printf '00000%0.s\n' {1..5}|sed "$1 s/./$3/$2"|grep -z "$3"

```

*$1*, *$2* \- row, column, *$3* \- replacement char, error is reported via exit code

**Test**

```
>./box 2 2 "*"
00000
0*000
00000
00000
00000
>echo $?
0

>./box 6 2 '*'
>echo $?
1

```
> 0 votes

# Answer
# Java 8, ~~194~~ 192 bytes

```
interface M{static void main(String[]a){String r="";int i=0,j,z=new Byte(a[0]),y=new Byte(a[1]);for(;++i<6;r+="\n")for(j=0;++j<6;r+=6-i==y&j==z?a[2]:0);System.out.print(z>0&z<7&y>0&y<7?r:0);}}

```

Try it here with correct input.
Try it here with incorrect input.

This would be **~~116~~ 114 bytes** instead as function instead of full program:

```
(a,b,c)->{String r="";for(int i=0,j;++i<6;r+="\n")for(j=0;++j<6;r+=b==6-i&a==j?c:0);return a>0&a<7&b>0&b<7?r:"0";}

```

Try it here.

**Explanation:**

```
interface M{                  // Class
  static void main(String[]a){//  Mandatory main-method
    String r="";              //   Result-String, starting empty
    int i=0,j,                //   Index-integers
        z=new Byte(a[0]),     //   First input converted to integer
        y=new Byte(a[1]);     //   Second input converted to integer
    for(;++i<6;               //   Loop (1) from 1 to 6 (inclusive)
        r+="\n")              //     After every iteration: Append a new-line to the result
      for(j=0;++j<6;          //    Inner loop (2) from 1 to 6 (inclusive)
        r+=6-i==y             //     If the second input equals `6-1`,
           &j==z?             //     and the first input equals `j`:
            a[2]              //      Append the third input to the result-String
           :                  //     Else:
            0                 //      Append a zero to the result-String
      );                      //    End of inner loop (2)
                              //   End of inner loop (1) (implicit / single-line body)
    System.out.print(         //   Print:
     z>0&z<7&y>0&y<7?         //    If the coordinates are valid (1-6):
      r                       //     Print the result `r`
     :                        //    Else:
      0);                     //     Print 0 as error instead
  }                           //  End of main-method
}                             // End of class

```
> 0 votes

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


title: A train crosses a labeled bridge

text:
# Question
Title: A train crosses a labeled bridge
Consider a bridge of length **B** formed by tiles labeled with the digits of the positive integers concatenated. For example, if **B** was 41, then it would look like this:

```
-----------------------------------------
12345678910111213141516171819202122232425

```

Now imagine a train of length **T** crossing the bridge. The leftmost point of the train starts at position **X** (1-indexed). To get a better understanding of the problem, let's make a scheme of the event, with **B = 41, T = 10, X = 10**. The train is drawn using equal signs (`=`) and lines:

```
         __________
         |========|
         |========|
-----------------------------------------
12345678910111213141516171819202122232425

```

The train can advance, at each step, by sum of the unique tiles it is located on. For example, the tiles the train stands on above are: `[1, 0, 1, 1, 1, 2, 1, 3, 1, 4]`, the unique (deduplicated) tiles are: `[1, 0, 2, 3, 4]`, and their sum is `10`. Hence, the train can advance by `10` tiles. We should draw it again and repeat the process until the leftmost point of the train has passed the last tile:

```
                   __________
                   |========|
                   |========|
-----------------------------------------
12345678910111213141516171819202122232425

Sum of unique tiles: 1 + 5 + 6 + 7 + 8 + 9 = 36. The train advances by 36 tiles...

                                                       __________
                                                       |========|
                                                       |========|
-----------------------------------------
12345678910111213141516171819202122232425

The train obviously crossed the bridge completely, so we should stop now.

```

Since the people inside are bored, they count the tiles the train has advanced each time. In this specific case, `10` and `36`. Summing everything up, the train has moved `46` before it passed the bridge.

---

# Task

Given three positive integers, **B** (the bridge length), **T** (the train length) and **X** (the starting position, **1-indexed**), your task is to determine how many tiles the train has moved until it crossed the bridge following the rules above.

* You can assume that:
    + **B** is higher than **T**.
    + **X** is lower than **B**.
    + **T** is at least **2**.
    + The train eventually crosses the bridge.
* All our standard rules apply.
* This is , so the shortest code in bytes wins!

---

# Test cases

```
Input ([B, T, X]) -> Output

[41, 10, 10] -> 46
[40, 10, 10] -> 46
[30, 4, 16] -> 24
[50, 6, 11] -> 50

```

Another worked example for the last test case:

```
The bridge is of length 50, the train 6, and the starting position is 11.

          ______
          |====|
          |====|
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Unique tiles: [0, 1, 2]. Sum: 3.

             ______
             |====|
             |====|
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Unique tiles: [1, 2, 3, 4]. Sum: 10.

                       ______
                       |====|
                       |====|
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Unique tiles: [1, 7, 8, 9]. Sum: 25.

                                                ______
                                                |====|
                                                |====|
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Unique tiles: [9, 3]. Sum: 12.
                                                            ______
                                                            |====|
                                                            |====|
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Train exists the bridge. Total sum: 3 + 10 + 25 + 12 = 50.

```

# Answer
> 3 votes
# Husk, 20 bytes

```
ṁ←U¡S↓←moΣuX_⁰↓Θ↑ṁdN

```

Try it online!

Takes three arguments in order **T**, **B**, **X**.

### Explanation

```
ṁ←U¡S↓←moΣuX_⁰↓Θ↑ṁdN
                 ṁdN    Build the list of digits of natural numbers
              ↓Θ↑       Take the first B digits, add a 0 in front
                        then drop the first X digits
           X_⁰          Get all sublists of length T
       moΣu             Map the sum of unique values of each sublist

   ¡S↓←                 Repeatedly drop as many elements from the start of the list as the
                        first element of the list says;
                        keep all partial results in an infinite list.

  U                     Take elements until the first repeated one
                        (drops tail of infinite empty lists)

ṁ←                      Sum the first elements of each remaining sublist

```

# Answer
> 5 votes
# Python 2, ~~110~~ ~~105~~ ~~104~~ ~~103~~ ~~100~~ ~~97~~ 96 bytes

* Saved five bytes thanks to Mr. Xcoder; removed unnecessary assignment, moved negation into available whitespace.
* Saved a byte thanks to Mr. Xcoder; golfed `[~-x:x+~-t]` to `[~-x:][:t]`.
* Saved a byte; golfed `...range(1,-~b)))[:b]` to `...range(b)))[1:-~b]`.
* Saved three bytes; golfed `[1:-~b][~-x:]` to `[:-~b][x:]`.
* Saved three bytes; golfed `[:-~b][x:]` to `[x:-~b]`.
* Saved a byte thanks to Lynn; golfing the `while` loop to an `exec` statement.

```
b,t,x=input();S=x;exec"x+=sum(set(map(int,''.join(map(str,range(b)))[x:-~b][:t])));"*b;print-S+x

```

Try it online!

# Answer
> 4 votes
## Haskell, ~~106~~ 102 bytes

```
import Data.List
(b#t)x|x>b=0|y<-sum[read[c]|c<-nub$take t$drop(x-1)$take b$show=<<[1..]]=y+(b#t)(x+y)

```

Try it online!

```
(b#t)x
   |x>b=0                 -- if the train has left the bridge, return 0
   |y<-sum[   ]           -- else let y be the sum of
      read[c]|c<-         -- the digits c where c comes from
        nub               -- the uniquified list of
            show=<<[1..]] -- starting with the digits of all integers concatenated
          take b          -- taking b digits (length of bridge)
         drop(x-1)        -- dropping the part before the train
        take t            -- take the digits under the train
     =y+(b#t)(x+y)        -- return y plus a recursive call with the train advanced

```

# Answer
> 3 votes
# , 123 bytes

```
function(B,T,X){s=substring
while(X<B){F=F+(S=sum(unique(strtoi(s(s(paste(1:B,collapse=''),1,B),K<-X+1:T-1,K)))))
X=X+S}
F}

```

Just implements the described algorithm.

R is quite terrible at strings.

```
function(B,T,X){
 s <- substring                         # alias
 b <- s(paste(1:B,collapse=''),1,B)     # bridge characters
 while(X<B){                            # until we crossed the bridge
  K <- X+1:T-1                          # indices of the characters
  S <- s(b,K,K)                         # the characters from b
  S <- sum(unique(strtoi(S)))           # sum
  F <- F + S                            # F defaults to 0 at the beginning
  X <- X + S                            # advance the train
 }
 F                                      # number of steps, returned
}

```

Try it online!

# Answer
> 2 votes
# Jelly,  ~~22~~  21 bytes

```
ḣ⁵QS
RDẎḣ⁸ṫṫÇ‘$$ÐĿÇ€S

```

A full program taking three arguments - the order is **B**, **X**, **T** \- which prints the result.

**Try it online!**

### How?

```
ḣ⁵QS - Link 1, calculate next jump: list of digits, bridge under and beyond train's left
 ⁵   - program's fifth command line argument (3rd input) = T (train length)
ḣ    - head to index (get the digits of the tiles under the train)
  Q  - de-duplicate
   S - sum

RDẎḣ⁸ṫṫÇ‘$$ÐĿÇ€S - Main link: number, B (bridge length); number, X (starting position)
R                - range(B) = [1,2,3,...,B-1,B]
 D               - to decimal list (vectorises) = [[1],[2],[3],...,[digits of B-1],[digits of B]]
  Ẏ              - tighten (flatten by one) = [1,2,3,...,digits of B-1,digits of B]
    ⁸            - chain's left argument, B
   ḣ             - head to index (truncate to only the bridge's digits)
     ṫ           - tail from index (implicit X) (truncate from the train's left)
           ÐĿ    - loop, collecting results, until no more change occurs:
          $      -   last two links as a monad:
         $       -     last two links as a monad:
       Ç         -       call last link (1) as a monad (get next jump)
        ‘        -       increment
      ṫ          -     tail from that index (remove the track to the left after train jumps)
             Ç€  - call last link (1) as a monad for €ach (gets the jump sizes taken again)
               S - sum
                 - implicit print

```

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

```
f=(B,T,X,g=b=>b?g(b-1)+b:'',o=0)=>X<B?[...g(B).substr(X-1,T)].map((e,i,a)=>o+=i+X>B|a[-e]?0:a[-e]=+e)&&o+f(B,T,X+o):0

```

A pair of recursive functions:

1. `f()` sums the train's moves.
2. `g()` creates the string of numbers.

**Less golfed:**

```
f=
(B,T,X,
 g=b=>b?g(b-1)+b:'',                       //creates the string of numbers
 o=0                                       //sum of tiles the train sits on
)=>
  X<B?                                     //if we're not past the bridge:
      [...g(B).substr(X - 1,T)].map(       //  grab the tiles we're sitting on
        (e,i,a)=>o += i + X > B |          //  if we've passed the bridge,
                      a[-e] ? 0 :          //  ... or we've seen this tile before, add 0 to o
                              a[-e] = +e   //  else store this tile and add its value to o
      ) &&
      o + f(B,T,X+o) :                     //recurse
  0

```

```
f=(B,T,X,g=b=>b?g(b-1)+b:'',o=0)=>X<B?[...g(B).substr(X-1,T)].map((e,i,a)=>o+=i+X>B|a[-e]?0:a[-e]=+e)&&o+f(B,T,X+o):0

console.log(f(41, 10, 10));  //46
console.log(f(40, 10, 10));  //46
console.log(f(30, 4, 16));   //24
console.log(f(50, 6, 11));   //50
```

# Answer
> 0 votes
# PHP \>= 7.1, 153 bytes

```
<?$s=substr;[,$p,$q,$r]=$argv;while($i<$p)$a.=++$i;$a=$s($a,0,$p);;while($r<$p){$x+=$n=array_sum(array_unique(str_split($s($a,$r-1,$q))));$r+=$n;}echo$x;

```

Try it online!

To make it compatible with lower versions of PHP, change `[,$p,$q,$r]=` to `list(,$p,$q,$r)=` (+4 bytes).

```
<?
[,$bridgelen,$trainlen,$position] = $argv;                  // grab input
while($i<$bridgelen)                                        // until the bridge is long enough...
  $bridgestr .= ++$i;                                       // add to the bridge
$bridgestr = substr($bridgestr,0,$bridgelen);               // cut the bridge down to size (if it splits mid-number)
while($position<$bridgelen){                                // while we are still on the bridge...
  $currtiles =                                              // set current tiles crossed to the...
    array_sum(                                              // sum of tiles...
      array_unique(                                         // uniquely...
        str_split(substr($bridgestr,$position-1,$trainlen)) // under the train
      )
    )
  ;
  $totaltiles += $currtiles;                                // increment total tiles crossed
  $position += $currtiles;                                  // set new position
}
echo $totaltiles;                                           // echo total tiles crossed

```

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


# Question
Title: Demonstrate a lower bound for the Ramsey number R(4,4)
A special case of Ramsey's theorem says the following: whenever we color the edges of the complete graph on 18 vertices red and blue, there is a monochromatic clique of size 4.

In language that avoids graph theory: suppose we place 18 points around a circle and draw all possible line segments connecting them in one of two colors: either red or blue. No matter how this is done, it's always possible to choose 4 of the points such that all 6 line segments between them are the same color: either all 6 are red or all 6 are blue.

Moreover, 18 is the least number for which this will work. For 17 points, we can color the line segments so that it's impossible to choose 4 points in this way.

Your goal is to print one such coloring. Your output must be a 17 by 17 adjacency matrix in which the (i,j) entry gives the color of the line segment joining points i and j. It must be in a format such as the one below:

```
  R R B R B B B R R B B B R B R R
R   R R B R B B B R R B B B R B R
R R   R R B R B B B R R B B B R B
B R R   R R B R B B B R R B B B R
R B R R   R R B R B B B R R B B B
B R B R R   R R B R B B B R R B B
B B R B R R   R R B R B B B R R B
B B B R B R R   R R B R B B B R R
R B B B R B R R   R R B R B B B R
R R B B B R B R R   R R B R B B B
B R R B B B R B R R   R R B R B B
B B R R B B B R B R R   R R B R B
B B B R R B B B R B R R   R R B R
R B B B R R B B B R B R R   R R B
B R B B B R R B B B R B R R   R R
R B R B B B R R B B B R B R R   R
R R B R B B B R R B B B R B R R

```

The exact output above represents a valid coloring, so it is perfectly acceptable. But you have the following additional freedom to do something else:

* You may print the adjacency matrix for any graph that satisfies the Ramsey condition, not just this one. (For example, any permutation of the rows with a corresponding permutation of the columns gives another acceptable output. I haven't checked if any non-isomorphic colorings exist.)
* You may use any two distinct, non-whitespace characters in place of `R` and `B` to represent the two colors.

However, the spacing must appear exactly as in the example above: a space between cells in the same row, spaces in the diagonal entries, and newlines after each row. Leading and trailing spaces and newlines are allowed (but the entries of the adjacency matrix should be aligned with each other).

This is , so the shortest code in bytes wins. Because this is , hardcoding the output is allowed. Otherwise, standard loopholes apply.

# Answer
# Jelly, 12 bytes

```
“ḍ⁾’B⁶;ṙJ$ṚG

```

Try it online!

### How it works

```
“ḍ⁾’B⁶;ṙJ$UG  Main link. No arguments.

“ḍ⁾’          Set the return value to 53643.
    B         Binary; yield [1,1,0,1,0,0,0,1,1,0,0,0,1,0,1,1].
     ⁶;       Prepend a space, yielding [' ',1,1,0,1,0,0,0,1,1,0,0,0,1,0,1,1].
         $    Monadic chain:
        J       Yield all indices of the array, i.e., [1, ..., 17].
       ṙ        Rotate the array 1, ..., 17 units to the left, yielding a matrix.
          Ṛ   Reverse the order of the rows.
           G  Format the matrix as a grid.

```
> 3 votes

# Answer
# Python 3, 56 bytes

```
s=' '+bin(53643)[2:]
for _ in s:print(*s);s=s[-1]+s[:-1]

```

Try it online!

---

**Python 3, 56 bytes**

```
s=' 1101000110001011'*16
while s:print(*s[:17]);s=s[16:]

```

Try it online!

---

**Python 2, 64 bytes**

```
for k in range(289):print'\n'[k%17:]+' ab'[(k/17-k%17)**8%17%7],

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 18 bytes

```
18G•Ó₆•bð«NFÁ}Sðý=

```

Try it online!

---

Uses 1 for `R` and 0 for `B`.
> 2 votes

# Answer
# Ruby, 53 bytes

```
17.times{|i|puts (" %b"%53643*99).chars[i*16,17]*' '}

```

Try it online!

# Ruby, 58 bytes

```
289.times{|i|$><<(" %b"%53643)[-i*16/17%17]+"
"[i%17/16]}

```
> 2 votes

# Answer
# , 30 bytes

```
(-+:i.17)|."0 1'   ',":#:53643

```

Explanation

```
                          #: - converts the number to a list of binary digits
                       ":    - converts the list to a string
                '   ',       - prepends 3 spaces in front of the string
         |."0 1              - rotates the list (rank 0 1)
(-+:i.17)                    - offset for the 0, 2, 4... 32 rotations

```

Try it online!
> 1 votes

---
Tags: code-golf, kolmogorov-complexity, graph-theory
---


# Question
Title: Find the intersection point of a plane and ray
Given a ray with a point and a vector and a plane with a point and a normal vector to the plane. You have to find the intersection point of the plane and the ray..

So your job if you choose to accept is to write a shortest function that will do the job.

```
RULES:
The submission must be a complete program
And that's all

INPUT FORMAT:
x y z rx ry rz //gives the ray point and the ray vectors
x y z px py pz //gives the point on the plane and the vector normal to plane

OUTPUT FORMAT:
(x,y,z) //intersection point

Test Case:
2 3 4 0.577 0.577 0.577
7 1 3 1 0 0
(7,8,9)

```

The shortest codes in bytes win.

References: https://www.siggraph.org/education/materials/HyperGraph/raytrace/rayplane\_intersection.htm thanks orlp for the reference

# Answer
> 3 votes
# Mathematica, 20 bytes

Takes 4 lists as input. The dot product operator `.` has precedence over multiplication and division, so no more parentheses are needed.

```
#+#2(#3-#).#4/#2.#4&

```

Readable version:

```
x + v (r - x).n / v.n

```

where the arguments in order are `x` (ray point), `v` (ray direction), `r` (plane point), `n` (plane normal).

# Answer
> 3 votes
# Perl, 107 bytes

Tested for all test cases (i.e. not tested at all) Run with each input number on its own line on STDIN

```
perl -M5.010 plane.pl
0
1
0
0
0
1
3
3
1
0
0
1
^D

```

`plane.pl`:

```
#!/usr/bin/perl
$$_=<>for a..l;say$a+($t=($j*($g-$a)+$k*($h-$b)+$l*($i-$c))/($j*$d+$k*$e+$l*$f))*$d,$",$b+$t*$e,$",$c+$t*$f

```

This kind of problem is absolutely ***not*** a good match for perlgolf. Perl lacks vector operations and uses too many `$`s

# Answer
> 1 votes
## Haskell, ~~137~~ 157/102 bytes

Follows both input and output pattern. Program reads input from stdin. 157 bytes.

```
z=zipWith
main=do
[(p,r),(l,n)]<-map(splitAt 3.map read.words).lines<$>getContents
print$(\[a,b,c]->(a,b,c))$z(+)p$map(*(sum(z(*)n(z(-)l p))/sum(z(*)n r)))r

```

With an input file that has format `[[x,y,z],[rx,ry,rz],[x,y,z],[px,py,pz]]` and output of format `[x,y,z]` (102 bytes):

```
z=zipWith
main=do
[p,r,l,n]<-read<$>getContents
print$z(+)p$map(*(sum(z(*)n(z(-)l p))/sum(z(*)n r)))r

```

# Answer
> 1 votes
# R, 88 bytes

```
x=scan()
v=scan()
r=scan()
n=scan()
C=cat
C("(");C(x+v*sum((r-x)*n)/sum(v*n),sep=", ");C(")")

```

Adapted from the Mathematica answer. Takes the following values from stdin, `x` (ray point), `v` (ray direction), `r` (plane point), `n` (plane normal). Outputs `(7, 8, 9)` for the test case.

# Answer
> 0 votes
## JavaScript (ES6), 157 bytes

This could probably be shorter. The test case is subject to rounding errors, but otherwise it respects the challenge.

```
P=prompt;[a,b,c,d,e,f,g,h,i,j,k,l]=(P()+' '+P()).split` `.map(e=>+e);alert('('+(a+(t=(j*(g-a)+k*(h-b)+l*(i-c))/(j*d+k*e+l*f))*d)+','+(b+t*e)+','+(c+t*f)+')')

```

# Answer
> 0 votes
# JavaScript (ES6), 93 bytes

```
(a,b,c,A,B,C,x,y,z,X,Y,Z)=>`(${t=X*(x-a)+Y*(y-b)+Z*(z-c)/(X*A+Y*B+Z*C),[a+t*A,b+t*B,c+t*C]})`

```

```
f=
(a,b,c,A,B,C,x,y,z,X,Y,Z)=>`(${t=X*(x-a)+Y*(y-b)+Z*(z-c)/(X*A+Y*B+Z*C),[a+t*A,b+t*B,c+t*C]})`

console.log(f(2, 3, 4, 0.577350269, 0.577350269, 0.577350269, 7, 1, 3, 1, 0, 0))
```

---
Tags: code-golf, math, 3d
---


title: How to code colors in hex

text:
# Question
Title: How to code colors in hex
Hexagonal tessellations, or tilings of the plane, are three-colorable -- meaning that using only three colors, such as Red, Blue, and Green, every hexagon can be colored without any two hexagons that share a border sharing a color. A partial example showing such a pattern.

Given a partial hexagonal tiling in ASCII (via STDIN, reading from a file, etc.), change the characters' colors (via ANSI codes, image manipulation, etc.) to fit this coloring. The twist is the middle of the hexagons (the `*`, below) are the three colors, and the lines between need to be a mix of their two corresponding hex's `*` colors. If the line is on the outside border, it should match the corresponding `*`.

For example, given the partial hexagonal tiling of

```
 / \ / \ / \ / \
| * | * | * | * |
 \ / \ / \ / \ /
  | * | * | * |
   \ / \ / \ /

```

suppose we decide to color the top-left hex `*` to be Red, and its two neighbors to be Blue and Green (going clockwise). Then the `|` line needs to be Magenta and the `/` line needs to be Yellow. If we keep coloring, we'll eventually end up with something like this (enlarged for clarity):

Or, for an input of

```
     / \
    | * |
   / \ /
  | * |
 / \ /
| * |
 \ /

```

you might color it like so (enlarged for clarity):

A few additional test cases (your code should be able to handle these):

```
 / \ / \
| * | * |
 \ / \ /
  | * |
 / \ / \
| * | * |
 \ / \ /

 / \
| * |
 \ / \
  | * |
 / \ /
| * |
 \ /

 / \
| * |
 \ /

```

## Rules

* The input is guaranteed to have at least one hexagon, and no input will have a "hole."
* You don't need to start your coloring with Red, so long as you maintain the three-color rule.
* If the partial tiling can be two-colored, you can do so without penalty (such as in the second example) - you don't necessarily need to extrapolate the partial tiling to a full tiling.
* The hexagon centers `*` must be colored with either Red, Blue, or Green, while the lines between must be either Cyan, Yellow, or Magenta. For example, having a Magenta `*` is not allowed, and a Red `|` or `\` or `/` must be on the outside border of the drawing. See *Colors*, below.
* If your console doesn't have these exact colors, please use the closest approximation and specify in your answer what approximation you're using.
* Leading or trailing whitespace, including trailing newlines, are acceptable so long as the characters line up.
* The partial tiling can be input with space-padding to form a rectangle, if that makes it easier for your code.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, saved as an image, etc.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Colors and Color Mixtures:

The three available base colors are (with color codes in RGB decimal format):

* Red `(255,0,0)`
* Green `(0,255,0)`
* Blue `(0,0,255)`

The combinations are:

* Red and Green combine to make Yellow `(255,255,0)`
* Blue and Green combine to make Cyan `(0,255,255)`
* Red and Blue combine to make Magenta `(255,0,255)`

# Answer
## JavaScript (ES6), ~~219~~ ~~203~~ 201 bytes

```
f=
s=>s.split`
`.map((b,i,a)=>b.replace(/./g,(c,j)=>`<font color=#${g=(x,y)=>((a[x+i]||``)[b=y+j]==`*`&&15<<b%3*4)|(y<0?8<<9:g(x,y-2)),(g(0,2)|g(-1,1)|g(1,1)).toString(16).slice(1)}>${c}</font>`)).join`
`
```

```
<input type=button value="Colourise!" onclick=i.innerHTML=f(i.textContent)>
<pre id=i contenteditable> / \ / \
| * | * |
 \ / \ / \
  | * | * |
 / \ / \ / \
| * |   | * |
 \ / \ / \ / \
  | * | * | * |
 / \ / \ / \ /
| * | * |
 \ / \ /</pre>
```

Explanation: Each character is wrapped in a `font` tag to set its colour, which is calculated by checking each square, plus the squares two to the left and right, plus the four squares one away diagonally, for `*`s and if so combining the colours of all `*`s found. The `*` colours are chosen simply by taking their horizontal coordinate modulo 3 and shifting a bitmask appropriately. Edit: Saved 2 bytes by switching from `#RRGGBB` to `#RGB` colours.
> 7 votes

# Answer
# JavaScript (ES6), 210 bytes (using HTML + CSS)

Similar to my canvas approach; locates all the `*`s in the input string and writes hexagons to the page in the form of absolutely positioned `<pre>` elements. Because `mix-blend-mode` is set to `lighten`, color addition is performed automatically when characters overlap.

```
s=>s.split`
`.map((r,y)=>[...r].map((c,x)=>c=='*'&&document.write(`<pre style=position:fixed;mix-blend-mode:lighten;line-height:1;left:${x}ch;top:${y}em;color:${['red','lime','blue'][x%3]}> / \\
| * |
 \\ /`)))

```

```
f=

s=>s.split`
`.map((r,y)=>[...r].map((c,x)=>c=='*'&&document.write(`<pre style=position:fixed;mix-blend-mode:lighten;line-height:1;left:${x}ch;top:${y}em;color:${['red','lime','blue'][x%3]}> / \\
| * |
 \\ /`)))

f(` / \\ / \\ / \\ / \\
| * | * | * | * |
 \\ / \\ / \\ / \\ /
  | * | * | * |
   \\ / \\ / \\ /`)
```
> 4 votes

# Answer
# Python 2, 279 bytes

```
e=enumerate
x=input()
c=[[i,j]for i,t in e(x)for j,_ in e(t)if"*"==x[i][j]]
C=[[j%3*([i,j]in c)for j,_ in e(o)]for i,o in e(x)]
for J,K in c:
	for i in-1,0,1:q=2-(i&1);_=C[i+J];_[K+q]=_[K-q]=_[K-q]|C[J][K]
for i,o in e(x):print"".join("[%dm"%(30+C[i][j])+x[i][j]for j,_ in e(o))

```

Try it online!

Golfed and fixed thanks to user202729!
-27 bytes thanks to Mr. Xcoder
-24 bytes thanks to Jonathan Frech
> 3 votes

# Answer
# Python 2, ~~346~~ 331 bytes

```
e=enumerate
C='0132645'
def f(s):
 c={(i,j):[1+(i/2%2+j/4)%3*2]for i,l in e(s)for j,x in e(l)if'*'==x}
 for i,l in e(s):
  r=''
  for j,x in e(l):a=c.get((i,j),c.get((i-(x<'|'),j+[-1,1][x>'/']+(x>'z')),[]))+c.get((i+(x<'|'),j+[1,-1][x>'/']-(x>'z')),[])if' '<x else[0];r+='\033[3'+C[[sum(a)/len(a),6][set(a)=={5,1}]]+'m'+x
  print r

```

Try it online!
> 2 votes

# Answer
# HTML (Canvas) + JavaScript (ES6), 13 + 251 = 264 bytes

Locates all the `*`s in the input string and paints an ASCII hexagon on the canvas at the corresponding positions. Because `globalCompositeOperation='lighter'`, color addition is performed automatically when characters overlap.

### HTML

```
<canvas id=c>

```

### JavaScript

```
s=>{c.width=c.height=s.length
with(c.getContext`2d`)font='1px monospace',globalCompositeOperation='lighter',s.split`
`.map((r,y)=>[...r].map((c,x)=>c=='*'&&[` / \\`,`| * |`,` \\ /`].map((t,i)=>fillText(t,x,y+i),fillStyle=['red','lime','blue'][x%3])))}

```

---

A multiplier and additional `scale()` command were added to the snippet for visibility.

```
// Unscaled
/*
f=
s=>{c.width=c.height=s.length
with(c.getContext`2d`)font='1px monospace',globalCompositeOperation='lighter',s.split`
`.map((r,y)=>[...r].map((c,x)=>c=='*'&&[` / \\`,`| * |`,` \\ /`].map((t,i)=>fillText(t,x,y+i),fillStyle=['red','lime','blue'][x%3])))}
*/

// Scaled
let scaleFactor = 40

f=
s=>{c.width=c.height=s.length*scaleFactor
with(c.getContext`2d`)scale(scaleFactor,scaleFactor),font='1px monospace',globalCompositeOperation='lighter',s.split`
`.map((r,y)=>[...r].map((c,x)=>c=='*'&&[` / \\`,`| * |`,` \\ /`].map((t,i)=>fillText(t,x,y+i),fillStyle=['red','lime','blue'][x%3])))}

// Test
f(` / \\ / \\ / \\ / \\
| * | * | * | * |
 \\ / \\ / \\ / \\ /
  | * | * | * |
   \\ / \\ / \\ /`)
```

```
<canvas id=c>
```

---

Also see my CSS-based approach.
> 1 votes

# Answer
# MATLAB/Octave, 223 bytes

```
a=input('')';s=size(a);p=zeros([s 3]);[i,j]=ind2sub(s,find(a=='*'));
for f=1:nnz(i)
p((-2:2)+i(f),(-1:1)+j(f),mod(f+~mod(j(f)/2,2),3)+1)=1;end
for f=1:nnz(a)
[i,j]=ind2sub(s,f);text(i/s(1),1-j/s(2),a(i,j),'Co',p(i,j,:));end

```

In slightly neater code format:

```
a=input('')';                  %Grab input as 2D array
s=size(a);                     %Get input size
p=zeros([s 3]);                %Make empty colour matrix of matching size with RGB
[i,j]=ind2sub(s,find(a=='*')); %Find all *'s
for f=1:nnz(i)                 %For each *
    %Fill a 5x3 box centred at the * on the colour channel for this box
    %Overlapping regions between boxes will result in the correct mix.
    p((-2:2)+i(f),(-1:1)+j(f),mod(f+~mod(j(f)/2,2),3)+1)=1;
end
%Display as text on a figure
for f=1:nnz(a)
    [i,j]=ind2sub(s,f);
    text(i/s(1),1-j/s(2),a(i,j),'Co',p(i,j,:))
end

```

The input is taken as a 2D array, such as entering the following when prompted for input:

```
[' / \ / \ / \ / \ ';'| * | * | * | * |';' \ / \ / \ / \ / ';'  | * | * | * |  ';'   \ / \ / \ /   ']

```

MATLAB so far as I'm aware doesn't have the ability to output colours to the console (except for dirty Java hacks which I am discounting). As such the output is instead printed to a figure.

Colouring is achieved by finding the location of all `*`'s in the input, and then in an RGB colour array (`p`), a 5x3 box of 1's (255 in MATLAB colour representation) are written centred about the `*`. The box is written to the colour corresponding with the mod-3 index along each line, with even lines having the colour index shifted by an offset.

This produces a colour matrix where any boxes that overlap will result in the required mixed colour. The example above produces the following colour matrix.

The white and black regions are irrelevant because at those locations a space is printed meaning we don't actually see the incorrect colour.

Once the colour matrix is created, we display each character on a figure using the `text` command, setting the colour of the text to the corresponding entry in the colour matrix. The above example will display:
> 1 votes

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


# Question
Title: Pentagonal numbers made from pentagonal numbers
### Introduction

A pentagonal number (A000326) is generated by the formula **Pn= 0.5×(3n2-n)**. Or you can just count the amount of dots used:

You can use the formula, or the gif above to find the first few pentagonal numbers:

```
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, 176, 210, 247, 287, 330, 376, 425, 477, etc...

```

Next, we need to compute the sum of **x** consecutive numbers.

For example, if **x = 4**, we need to look at Pn \+ Pn+1 \+ Pn+2 \+ Pn+3 (which consists of **4** terms). If the sum of the pentagonal numbers also is a pentagonal number, we will call this a ***pentagonal pentagon number***.

For **x = 4**, the smallest pentagonal pentagon number is `330`, which is made of **4** consecutive pentagonal numbers: `51, 70, 92, 117`. So, when the input is `4`, your program of function should output `330`.

---

### Task

* When given an integer greater than 1, output the smallest pentagonal pentagon number.
* You may provide a function or a program.
* **Note:** There are no solutions for e.g. **x = 3**. This means that if a number **cannot be made** from the first 10000 pentagonal numbers, you must stop computing and output whatever fits best for you.
* This is , so the submission with the least amount of bytes wins!

---

### Test cases:

```
Input: 2
Output: 1926 (which comes from 925, 1001)

Input: 3
Output: ?

Input: 4
Output: 330 (which comes from 51, 70, 92, 117)

Input: 5
Output: 44290 (which comes from 8400, 8626, 8855, 9087, 9322)

Input: 6
Output: 651 (which comes from 51, 70, 92, 117, 145, 176)

Input: 7
Output: 287 (which comes from 5, 12, 22, 35, 51, 70, 92)

Input: 8
Output: ?

Input: 9
Output: 12105 (which comes from 1001, 1080, 1162, 1247, 1335, 1426, 1520, 1617, 1717)

Input: 10
Output: ?

```

Also bigger numbers can be given:

```
Input: 37
Output: 32782

Input: 55
Output: 71349465

Input: 71
Output: 24565290

```

# Answer
## CJam, 29 bytes

```
6e5{)_3*(*2/}%_A4#<riew::+&1<

```

Try it online.

Takes a couple of seconds to run.

### Explanation

First, we need to check how many pentagonal numbers we need to consider as potential sums. The sum of the first 10,000 pentagonal numbers is `500050000000`. The first pentagonal number greater than that is the 577,380th.

```
6e5       e# 600,000 (a short number that's a bit bigger than we need).
{         e# Map this block onto every number from 0 to 599,999...
  )       e#   Increment.
  _3*(*2/ e#   Apply the pentagonal number formula given in the challenge.
}%
_         e# Make a copy.
A4#<      e# Truncate to the first 10,000 elements.
ri        e# Read input and convert to integer.
ew        e# Get sublists of that length.
::+       e# Sum each sublist.
&         e# Set intersection with all 600k pentagonal numbers computed earlier.
1<        e# Truncate to the first result.

```

I used a slightly modified program to find the largest inputs which yield a non-empty solution. These are all the solutions for inputs greater than 9,000:

```
9919 -> 496458299155
9577 -> 446991927537
9499 -> 455533474060
9241 -> 401702906276
9017 -> 429351677617

```
> 4 votes

# Answer
# Lua, 142 Bytes

```
p={}o={}n=...for i=1,10^4 do p[i]=(3*i^2-i)/2o[p[i]]=1 end for i=0,10^4-n do s=0 for j=1,n do s=s+p[i+j]end if(o[s])then print(s)break end end

```

**Ungolfed**

```
p={}o={}n=tonumber(...)
for i=1,10^4 do
    p[i]=(3*i^2-i)/2o[p[i]]=1
end
for i=0,10^4-n do
    s=0
    for j=1,n do
        s=s+p[i+j]
    end
    if(o[s])then
        print(s)
        break
    end
end

```

Yay for inverting tables!

*Update 142 Bytes:* Saved 10 bytes by removing superfluous 'tonumber' function call.
> 4 votes

# Answer
## Haskell, 109 bytes

```
p=map(\n->div(3*n^2-n)2)[1..10^7]
(%)=(sum.).take
x#l|length l<x=0|elem(x%l)p=x%l|1<2=x#tail l
(#take(10^4)p)

```

Returns `0` if there's no pentagonal pentagon number.

Usage example (takes some time to finish): `map (#take(10^4)p) [1..10]` -\> `[1,1926,0,330,44290,651,287,0,12105,0]`.

It's more or less a direct implementation of the definition: if the sum of the first `x` elements is in the list, output it, else re-try with the tail of the list. Start with the first 10,000 pentagonal numbers, stop and return `0` if the list has less than `x` elements.
> 3 votes

# Answer
# PARI/GP, 71 bytes

I like the `ispolygonal` function in PARI/GP.

```
x->[p|p<-vector(10^4,i,sum(n=i,i+x-1,(3*n^2-n)/2)),ispolygonal(p,5)][1]

```
> 3 votes

# Answer
# Python 3, 144 bytes

```
R,P=range,list(map(lambda n:(3*n*n-n)/2,R(1,10001)))
def F(X):
 for a in R(0,len(P)-X):
    S=sum(P[a:a+X])
    if(1+(1+24*S)**.5)%6==0:print(S);break

```

This reverses the definition of a pentagonal number; if P(n) = (3n^2-n)/2, then a given P will be a pentagonal number iff (1+sqrt(24\*P+1))/6 is an integer. (Technically, it should also look at (1-sqrt(24\*P+1))/6, but that should always be negative.) Also uses spaces and tabs as two different indentation levels, as suggested here. This doesn't output anything if it can't find a pentagonal pentagonal number; I trust that's OK?

I strongly believe that someone more clever than I am could find a way to shorten this even more, probably around the for loop.
> 3 votes

# Answer
# R, ~~114~~ 100 bytes

```
k=.5*(3*(t=1:1e6)^2-t);z=1;for(i in 1:(1e4-(n=scan()-1)))z[i]=sum(k[i:(i+n)]);cat(intersect(k,z)[1])

```

ungolfed (kinda)

```
k=.5*(3*(t=1:1e6)^2-t)                 # map all pentagon numbers up to 1e6
z=1                                    # create a vector
for(i in 1:(1e4-(n=scan()-1))){        # from 1 to 10.000 - n loop
  z[i]=sum(k[i:(i+n)])}                # get the sum of all pentagon numbers i:(i+n)
cat(intersect(k,z)[1])                 # see which sums is a pentagon number itself, plot the first

```
> 2 votes

# Answer
# Mathematica 85 bytes

```
n=577380;Intersection[#(3#-1)/2&/@Range@n,Table[#((#-1)^2+x(3#-4+3x))/2,{x,n}]][[1]]&

```

perfoms a quick search up to **P104**.
> 2 votes

# Answer
# LabVIEW, 39 LabVIEW Primitives

No gif of it running this time.

Math node in loop creates an array of all the numbers. Take Sub-array, add elements, search for that number, if found take index and stop loop.

An invalid input puts out the highest pentagonal number.
> 2 votes

# Answer
# Jelly, 30 bytes

```
×24‘½‘%6¬Oị
15ȷ7RÇṫ³R$zȷ.5ZSÇḢ

```

This code works with this version of Jelly and is equivalent to the following binary code:

```
0000000: 94 32 34 b2 90 b2 25 36 87 4f b1 0a 31 35 a0  .24...%6.O..15.
000000f: 37 52 92 ad 8b 52 24 7a a0 2e 35 5a 53 92 a6  7R...R$z..5ZS..

```

It is by far to slow and memory hungry for the online interpreter, since it checks the first 150,000,000 for pentagonality (149,995,000 happens to be the 10,000th pentagonal number).

By shortening the range to something more sensible, you can Try it online! for small enough inputs.

### Idea

A known result about pentagonal numbers is that **x** is pentagonal if and only if **sqrt(24x + 1) - 1** is divisible by **6**.

Rather than computing the first 10,000 pentagonal numbers, we define a helper link that removes non-pentagonal numbers from a given array. Why? Because the latest version of Jelly that predates this challenge has no sane way to intersect lists...

### Code

```
×24‘½‘%6¬Oị  Define the aforementioned helper link. Left argument: a (list)

×24          Multiply each list item by 24.
   ‘         Increment each product.
    ½        Apply square root to each result.
     ’       Decrement each square root.
      %6     Compute all remainders of division by 6.
        ¬    Apply logical NOT.
         O   Get the indices of ones.
          ị  Hook; get the elements of a at those indices.

15ȷ7RÇṫ³R$zȷ.5ZSÇḢ  Define the main link. Input: x

15ȷ7R               Yields [1, ..., 1.5e8].
     Ç              Apply the helper link; keep only pentagonal numbers.
       ³R$          Yield r = [1, ..., x].
      ṫ             Remove the first y-1 pentagonal numbers for each y in r.
          zȷ.5      Transpose the resulting array, padding with sqrt(10).
              Z     Transpose once more. The shifted lists have now been padded.
                    This makes sure incomplete sums (i.e., of less than x
                    pentagonal numbers) will not be integers.
               S    Compute all sums.
                Ç   Apply the helper link once more.
                 Ḣ  Select the first match, if any.

```

---

# Jelly, 21 bytes (non-competing)

```
ȷ6Rµ²×3_¹Hµḣȷ4ṡ³ZSf¹Ḣ

```

The latest version of Jelly has two new features (overlapping slices and and list filtering / intersection) and a bug fix, which allows a much lower byte count.

This code works fine on my desktop computer, but it's a tad to slow for TIO's time limit. To Try it online! (for sufficiently small inputs), we have to reduce the initial range once again.

### How it works

```
ȷ6Rµ²×3_¹Hµḣȷ4ṡ³ZSf¹Ḣ  Input: x

ȷ6R                    Yield [1, ..., 1,000,000].
   µ                   Begin a new, monadic chain.
    ²                  Square each number in the range.
     ×3                Multiply the squares by 3.
       _¹              Subtract the numbers from the range.
         H             Halve each difference.
                       This yields the first 1,000,000 pentagonal numbers.
          µ            Begin a new, monadic chain.
           ḣȷ4         Keep only the first 10,000 pentagonal numbers.
              ṡ³       Yield all overlapping slices of length x.
                ZS     Transpose and sum. This computes the sum of each slice.
                  f¹   Filter; intersect with the long list of pentagonal numbers.
                    Ḣ  Select the first match, if any.

```
> 2 votes

# Answer
# Axiom, 157 bytes

```
p(n)==(3*n*n-n)quo 2;f(x)==(a:=0;for i in 1..x repeat a:=a+p(i);for j in 1..10000 repeat(p(floor((1+sqrt(1.+24*a))/6)::INT)=a=>return a;a:=a+p(j+x)-p(j));-1)

```

ungolfed and results

```
h(x:PI):INT==
   a:=0;for i in 1..x repeat a:=a+p(i) -- sum(p(i),i=1..x)
   for j in 1..10000 repeat
      p(floor((1+sqrt(1.+24*a))/6)::INT)=a=>return a
      a:=a+p(j+x)-p(j)
   -1

(5) -> [[i,f(i)] for i in 1..10]
   (5)
   [[1,1], [2,1926], [3,- 1], [4,330], [5,44290], [6,651], [7,287], [8,- 1],
    [9,12105], [10,- 1]]
                                                  Type: List List Integer

```

esplenation: We can find n using the result "a", see below

```
a=(3*n^2-n)/2 => 3*n^2-n-2*a=0 => n=floor((1+sqrt(1.+24*a))/6)::INT

```

\[use 1+sqrt(...) because n\>0\]

This above means that if exist one n0 such that

```
p(n0)=a

```

than

```
n0=floor((1+sqrt(1.+24*a))/6)::INT

```

Afher that we have to prove that p(n0)=a for to be sure (because it is not always so)

But the main trick would be doing the sum

```
a:=sum(p(i),i=1..x) [x elements sum]

```

only at the start, and find the next x elements sum simply using

```
a=a+p(x+1)-p(1)=sum(p(i), i=2..x+1)

```

and so on for the other sums (using above in the statement a:=a+p(j+x)-p(j) ). This means it is not necessary one number x element sum inside the loop... ..
> 0 votes

# Answer
# Javascript 93 bytes

```
p=i=>i>0&&3*i*i-i>>1
f=(x,i=1,t=0)=>i<1e4?(24*(t+=p(i)-p(i-x))+1)**.5%6==5&i>x?t:f(x,i+1,t):0

console.log(f(4))
console.log(f(5))
console.log(f(6))
console.log(f(7))
console.log(f(8))
console.log(f(9919)==496458299155)
console.log(f(9577)==446991927537)
console.log(f(9499)==455533474060)
console.log(f(9241)==401702906276)
console.log(f(9017)==429351677617)
console.log(f(9))
console.log(f(10))
```
> 0 votes

# Answer
# Python 2, ~~128~~ 124 bytes

```
X=input();N=S=0
while all(S-(3*n*n-n)/2for n in range(S)):N+=1;S=sum(3*(n+N)**2-n-N>>1for n in range(X));N<1e4or 0/0
print S

```

Try it online!
> 0 votes

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


title: matrix determinant

text:
# Question
Title: matrix determinant
## Calculate the determinant of an n x n matrix.

### Rules

* read matrix from standard input
* write to standard output
* do not use ready solutions from library or language
* input: columns separated by any space char
* input: lines separated by cr and/or lf

### Winner

* The shortest code :)

# Answer
> 5 votes
## GolfScript, 58 chars

```
n%{~]}%{[.!{(.,,0\{:^2$=-1^?*3${.^<\^)>+}%d*+}/}or])\;}:d~

```

A straightforward recursive algorithm using Laplace expansion.

Example input (random 5 × 5 matrix):

```
-562   40   43 -586  347
-229  177  305 -367   50
-434  343  241 -365  -86
-3   -384 -351   61 -214
-400   96 -339   25 -116

```

Output: `282416596900` (Online demo; Verify with Wolfram Alpha)

The code consists of three parts:

* `n%{~]}%` parses the input,
* `{[.!{(.,,0\{:^2$=-1^?*3${.^<\^)>+}%d*+}/}or])\;}:d` defines a recursive subroutine to calculate the determinant, and
* the final `~` applies the subroutine to the input.

I'm sure there's room for improvement in this code, but at least I beat Gareth by three chars. Also, `{:^2$=` is a pretty nice GS smiley. :)

# Answer
> 4 votes
## Haskell, ~~139~~ 131

```
(a:r)%0=r;(a:r)%n=a:r%(n-1)
d[]=1;d(f:r)=foldr(\(j,x)->(x*d(map(%j)r)-))0$zip[0..]f
main=interact$show.d.map(map read.words).lines

```

# Answer
> 2 votes
# Python 233

```
def d(x):
 l=len(x)
 if l<2:return x[0][0]
 return sum([(-1)**i*x[i][0]*d(m(x,i))for i in range(l)])
def m(x,i):y=x[:];del(y[i]);y=zip(*y);del(y[0]);return zip(*y)
x=[input()]
for i in (len(x[0])-1)*[1]:x+=[input()]
print d(x)

```

### Ungolfed:

```
def det(x):
    l = len(x)
    if l == 1:
        return x[0][0]
    return sum([(-1)**i*x[i][0]*det(minor(x,i+1,1)) for i in range(l)])

def minor(x,i,j):
    y = x[:]
    del(y[i-1])
    y=zip(*y)
    del(y[j-1])
    return zip(*y)

def main():
    x = [input()]
    for i in range(len(x[0])-1):
        x += [input()]
    print det(x)

if __name__ == '__main__':
    main()

```

## Usage

As requested, input is on stdin and output is to stdout.

I interpreted columns separated by any space char to mean that I can use comma delimited numbers. If this is not the case, I will rework my solution.

This could be about 30 characters shorter if I could specify my input matrix in the form \[\[a,b,c\],\[d,e,f\],\[g,h,i\]\].

```
./det.py
1,-4,9
-6,7,3
1,2,3

```

Result

```
-240

```

The determinant is found using Laplace Expansion

# Answer
> 2 votes
# Python, 369

This is ridiculously long, but I thought I'd provide a solution that implements the Leibniz formula.

```
def f(l):
    if len(l)==1:return [l]
    a=[]
    for s in l:
        for p in f(list(set(l)-set([s]))):a+=[[s]+p]
    return a
def s(a):
    n=1
    for i in range(len(a)):n*=(-1)**(a[i]>i);a[a.index(i)]=a[i];a[i]=i
    return n
m=[map(int,w.split(','))for w in raw_input().split(' ')]
r=range(len(m))
print sum([reduce(lambda x,y:x*y,[m[p[i]][i] for i in r],1)*s(p) for p in f(r)])

```

Values are read from stdin in a format like `1,2,-3 7,0,4 -1,-3,0` with a single space between columns. I wouldn't have posted this, but it was fun to write and contains a couple interesting sub-problems. The function f generates all permutations of n elements, and the function s determines the parity of those permutations.

# Answer
> 2 votes
## Python, 198

This also uses the Liebniz formula. I'm using a heavily-modified version of ugoren's permutation solution to generate permutations and their inversion counts simultaneously. (edit: now correct!)

```
t=input()
e=enumerate
p=lambda t:t and((b+[a],j+i)for i,a in e(t)for b,j in p(t[:i]+t[i+1:]))or[([],0)]
print sum(reduce(lambda t,(i,r):t*r[i],e(p),1-i%2*2)for p,i in p([t]+[input()for x in t[1:]]))

```

# Answer
> 1 votes
## J, 61 characters

```
-/>([:+/#(([{.<:@[}.])[:*//._2,\2#])])&.>(|.;])".];._2[1!:1[3

```

A big ugly bit of code that takes its input from stdin (if you're running this on Windows you may need to change `".];._2[1!:1[3` to `".}:@];._2[1!:1[3` to ensure both character return and line feed are removed).

```
   -/>([:+/#(([{.<:@[}.])[:*//._2,\2#])])&.>(|.;])".];._2[1!:1[3
1 8 5
2 7 3
9 9 4
_72
   -/>([:+/#(([{.<:@[}.])[:*//._2,\2#])])&.>(|.;])".];._2[1!:1[3
_2 2 3
_1 1 3
2 0 _1
6

```

Of course, no-one using J would ever bother to do this. They'd just use:

```
(-/ .*)".];._2[1!:1[3

```

making use of the `.` determinant verb.

# Answer
> 1 votes
# Dyalog APL, 53 ~~58~~ ~~59~~ characters

```
{1=≢⍵:⊃⍵⋄-/⍵[1;]×∇¨{w[f~1;f~⍵]}¨f←⍳⊃⍴w←⍵}U⍪↑{⎕}¨1↓⍳⍴U←⎕

```

I'm pretty late to the party here. **Please**, alert me if there are any issues with this code! Takes negatives as input via ¯ (the APL negative sign). I *think* values by default go to STDOUT in APL, but I may be wrong.

Uses Laplace expansion to find the determinant of the matrix.

This program is separated into three main parts: an input section, and the case of a 1x1 matrix, and the actual recursive function.

Input program:

```
U⍪↑{⎕}¨1↓⍳⍴U←⎕
             ⎕ - Takes evaluated input, space separated numbers are vectors in APL.
           U←  - Stores the input into variable `U`.
         ⍳⍴    - The array of integers from 1 to the length of `U` (inclusive).
       1↓      - Drops the first element of the result.
   {⎕}¨        - Receives a new input for each element in the vector. (Result is a vector of vectors)
  ↑            - Transforms the vector vector into a 2D-array.
U⍪             - The original line was stored then used for its length, so we stick it on top of the new array.

```

1x1 case:

```
{1=≢⍵:⊃⍵⋄...}
       ⍵      - The input
      ⊃       - The first element of the input
     :        - Return that if and only if ...
   ≢⍵         - The largest dimension of the input matrix
 1=           - Has equality with 1.
        ⋄     - Statement separator
{           } - Function enclosure brackets.

```

Actual determinant program:

```
{...-/⍵[1;]×∇¨{w[f~1;f~⍵]}¨f←⍳⊃⍴w←⍵}
                                w←⍵  - The input stored in `w`
                               ⍴     - The dimensions of `w`
                              ⊃      - The first dimension
                             ⍳       - 1 to the result of last operation
                           f←        - Store the result in `f`
              {          }¨          - Do what is inside the brackets to each member of `f`
               w[f~1;f~⍵]            - Return the minor matrix.
            ∇¨                       - Find determinant of each element (recursive)
      ⍵[1;]×                         - Multiply elementwise by the first row of the input matrix
    -/                               - Reduction using subtraction, since APL evaluates right to left, it comes out to be + - + - ...

```

# Answer
> 0 votes
## Python, 181 characters

Late to the party, but here's a simple 181 character implementation of Laplace:

```
l,r=len,range
d=lambda A:sum((-1)**i*A[0][i]*d([[A[x][y]for x in r(1,l(A))]for y in r(i)+r(1+i,l(A))])for i in r(l(A)))if len(A)>1 else A[0][0]
print d(map(eval,iter(raw_input,'')))

```

This meets the specs if "any space character" includes commas, which seems to be the norm here. Otherwise,

```
l,r=len,range
d=lambda A:sum((-1)**i*A[0][i]*d([[A[x][y]for x in r(1,l(A))]for y in r(i)+r(1+i,l(A))])for i in r(l(A)))if len(A)>1 else A[0][0]
print d(map(lambda x:map(int,x.split(' ')),iter(raw_input,'')))

```

is 207 characters.

Input is terminated by entering a blank line.

# Answer
> 0 votes
# Jq 1.5, 171 bytes

This is a golf-ed version of `det` from rosettacode Matrix arithmetic - jq.

```
def d:if[paths]==[[0],[0,0]]then.[0][0]else. as$m|reduce range(length)as$i(0;.+({"0":1}["\($i%2)"]//-1)*$m[0][$i]*($m|reduce del(.[0])[]as$r([];.+[$r|del(.[$i])])|d))end;d

```

Original

```
def except(i;j):
  reduce del(.[i])[] as $row ([]; . + [$row | del(.[j]) ] );

def det:
  def parity(i): if i % 2 == 0 then 1 else -1 end;
  if length == 1 and (.[0] | length) == 1 then .[0][0]
  else . as $m
    | reduce range(0; length) as $i
        (0; . + parity($i) * $m[0][$i] * ( $m | except(0;$i) | det) )
  end ;

```

Alterations:

* replace base case condition with `[paths]==[[0],[0,0]]`
* replace `parity($i)` with `({"0":1}["\($i%2)"]//-1)`
* replace `except(0;$i)` with inline definition
* replace `det`,`row` with `d`,`r` and remove whitespace

Try it online!

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


title: Symmetric Ladybugs

text:
# Question
Title: Symmetric Ladybugs
## Introduction:

When we think about Ladybugs, we usually think of a red or dark orange bug with black spots. Although this isn't necessary true, since there are also black with red/orange spotted ladybugs, or ladybugs without spots at all, we mainly picture ladybugs something like this Asian Ladybug:

Another thing to note is that the spots on the ladybugs are almost always symmetric. And that is where this challenge comes in.

## Challenge:

Given an integer `n` (`>= 0`), output the following ASCII-art ladybug one or multiple times, with symmetric spots evenly divided between the two sides, as well as the two or more ladybugs.

Here is the default ladybug layout:

```
    _V_
  /(@I@)\
 /   |   \
|    |    |
 \   |   /
  ''-!-''

```

If `n=0`, we output the ladybug above as is.

When `n` is larger than zero, we either fill in the spaces of the ASCII-art bug with a lowercase `o`, or replace the `|` in the center with a capital `O`. The goal is to make `n` changes to the 'empty' ladybug(s), while still producing a symmetric output (per ladybug), and outputting as few ladybugs as possible.

So valid outputs for `n=1` are:

```
    _V_
  /(@I@)\
 /   O   \
|    |    |
 \   |   /
  ''-!-''

    _V_
  /(@I@)\
 /   |   \
|    O    |
 \   |   /
  ''-!-''

    _V_
  /(@I@)\
 /   |   \
|    |    |
 \   O   /
  ''-!-''

```

But this would be invalid:

```
    _V_
  /(@I@)\
 /   |   \
| o  |    |
 \   |   /
  ''-!-''

```

Valid outputs for `n=2` are:

```
    _V_
  /(@I@)\
 /   O   \
|    O    |
 \   |   /
  ''-!-''

    _V_
  /(@I@)\
 /   O   \
|    |    |
 \   O   /
  ''-!-''

    _V_
  /(@I@)\
 /  o|o  \
|    |    |
 \   |   /
  ''-!-''

    _V_
  /(@I@)\
 /   |   \
| o  |  o |
 \   |   /
  ''-!-''

etc. There are a lot of possible outputs.

```

The first `n` that isn't possible to fit into a single ladybug anymore is `n=24`. In which case you'll have to divide it as evenly as possible into two ladybugs (you can choose whether to output them next to each other, or under one another - with optionally one space or one new-line in between them). For example:

```
    _V_        _V_
  /(@I@)\    /(@I@)\
 /o o|o o\  /o o|o o\
|o o | o o||o o | o o|
 \o o|o o/  \o o|o o/
  ''-!-''    ''-!-''

```

OR:

```
    _V_
  /(@I@)\
 /ooo|ooo\
|    |    |
 \ooo|ooo/
  ''-!-''
    _V_
  /(@I@)\
 /ooo|ooo\
|    |    |
 \ooo|ooo/
  ''-!-''

```

## Challenge rules:

* `n` will be in the range of `0-1000`.
* You can choose to output to STDOUT, return as String or 2D-char array/list, etc. Your call.
* Leading new-lines or unnecessary whitespaces aren't allowed. Trailing white-spaces and a single trailing new-line are allowed.
* As mentioned above, when two or more ladybugs are necessary, you can choose whether to output them next to each other or below each other (or a mix of both..)
* When two or more ladybugs are printed next to each other, a single optional space in between is allowed. When two or more ladybugs are printed down one another, a single optional new-line in between is allowed.
* You can choose the layout of the ladybugs at any step during the sequence, as long as they are symmetric and equal to input `n`.
* Since the goal is to have `n` changes AND as few ladybugs as possible, you will start using more than one ladybug when above `n=23`. The layout of these ladybugs doesn't necessary have to be the same. In fact, this isn't even possible for some inputs, like `n=25` or `n=50` to name two.
* In addition, sometimes it isn't possible to evenly split the dots among two or more ladybugs. In that case you'll have to split them as evenly as possible, with at most a difference of 1 between them.

So for `n=50`, keeping the last two rules in mind, this would be a valid possible output (where the first bug has 16 spots, and the other two have 17):

```
    _V_        _V_        _V_
  /(@I@)\    /(@I@)\    /(@I@)\
 /oooOooo\  /   O   \  /o oOo o\
|ooooOoooo||ooooOoooo||o ooOoo o|
 \   |   /  \oooOooo/  \o oOo o/
  ''-!-''    ''-!-''    ''-!-''

```

## General rules:

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

# Answer
# Charcoal, ~~84~~ 81 bytes

```
Ｎθ≔⌈∕∨θ¹¦²³ηＦη«≔⁺÷θη‹ι﹪θηζV_¶I@)↘²↙|/←''-↑!↑⎇›ζ²¹OO²§|OζＥ037×o⌊⟦⁻÷ζ²Ｉκ⁺³⁼κ3⟧↙»‖Ｂ←

```

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

```
Ｎθ

```

Input the total number of spots.

```
≔⌈∕∨θ¹¦²³η

```

Calculate the number of ladybirds needed.

```
Ｆη«

```

Loop over each ladybird.

```
≔⁺÷θη‹ι﹪θηζ

```

Calculate the number of spots to put on this ladybird.

```
V_¶I@)↘²↙|/←''-↑!

```

Print the head and right wing of the ladybird.

```
↑⎇›ζ²¹OO²

```

If there are more than 21 spots, print two spots, otherwise print the back.

```
§|Oζ

```

If the number of spots is odd print another spot otherwise print the rest of the back.

```
Ｅ037×o⌊⟦⁻÷ζ²Ｉκ⁺³⁼κ3⟧

```

Divide the number of spots by two, and distribute them among three rows of 3, 4, and 3 spots.

```
↙»

```

Move to the start of the next ladybird.

```
‖Ｂ←

```

Reflect the canvas to the left, keeping the back.
> 5 votes

# Answer
# Python 2, ~~252~~ ~~249~~ ~~238~~ ~~212~~ ~~211~~ ~~213~~ 209 bytes

```
n=input()
x=(n+22)/23or 1
for i in range(x):b=n/x+(n%x>i);c=r"""    _V_
  /(@I@)\
 /361%s163\
|408717804|
 \5201025/
  ''-!-''"""%'|O'[b%2];i=0;exec"c=c.replace(`i%9`,' |oO'[i>9::2][i<b/2],2);i+=1;"*11;print c

```

Try it online!

* Saved 9 bytes thanks to Kevin Cruijssen
* Saved 18 bytes thanks to Mr. Xcoder
* Saved 2 bytes thanks to Jonathan Frech
> 8 votes

# Answer
# JavaScript (ES6), ~~183~~ 186 bytes

Uses the same formula as TFeld's answer to split the spots among the ladybugs.

```
n=>(g=k=>k--?`    _V_
  /(@I@)\\
 /3\\
|4|
 \\3/
  ''-!-''
`.replace(/\d/g,i=>(h=s=>i--?h((p=N?(N-=2,'o'):' ')+s+p):s)('|O'[N>2*i|N&1&&+!!N--]),N=(n%j>k)+n/j|0)+g(k):'')(j=n/23+.99|0||1)

```

### Demo

```
let f =

n=>(g=k=>k--?`    _V_
  /(@I@)\\
 /3\\
|4|
 \\3/
  ''-!-''
`.replace(/\d/g,i=>(h=s=>i--?h((p=N?(N-=2,'o'):' ')+s+p):s)('|O'[N>2*i|N&1&&+!!N--]),N=(n%j>k)+n/j|0)+g(k):'')(j=n/23+.99|0||1)

console.log(f(0))
console.log(f(1))
console.log(f(9))
console.log(f(25))
```
> 7 votes

# Answer
# Befunge, ~~292~~ 279 bytes

```
#j07-00p&>::1-27*9+/\!!*:1+06pv-1_@#:<<g61$<<:
v"h"**95%2:+`g61%g60\/g60::p61<>-0g*+35*-,:!|
>\-30p2/:55+`:59**"g"\-40p-26pv^*84\!`"."::<<9
v\%+55+g62:%+55+4*g62:::-1<+55<>:"/n"$#->#<^#<
>`26g!+"O"*"Y"\-\-\5+0p:>#^_" 66<0<66// >,-"v
"n //>7OXO8k />'&%$%&'k !(*+)#)+*(! /k,-.$."<v

```

Try it online!

**Explanation**

The ASCII art for the ladybug is encoded in a single Befunge string, offset by 15, to allow the first 15 printable characters to be reserved for special purposes. The first two of these special characters represent the newline and the `|` character, both of which would otherwise not be printable. The third isn't used, because it's a `"`, which can't be used in a string. The next two represent the large spots in the centre. And the remaining ten are for the spots on the wings.

These special characters are translated into their final form via a lookup table, which is written over the first part of the first line.

To make it easier to explain, this is the code with the various component parts highlighted:

We start by initialising the newline and `|` character in the lookup table, since these are constant.
Next we read in the number of spots from stdin and calculate the number of ladybugs required.
We can then start the outer loop for the set of bugs, calculating the number of spots for the next ladybug to be rendered.
For each ladybug, we calculate whether the large centre spot needs to be shown (if `spots%2 == 1`), and write the appropriate value into the lookup table.
Similarly, we calculate whether the other pair of large spots need to be shown (if `spots/2 > 10`), again updating the lookup table. We also calculate the remaining spots required on each wing.
The final part of the lookup table initialization is a loop that calculates which of the small spots need to be displayed. Essentially the algorithm is: if `(spotnum*spotcount+4)%10 > ((spotnum+1)*spotcount+4)%10`, then the spot needs to be displayed.
Next we push the encoded string representation of the ladybug onto the stack. This is essentially just a simple string, but it became a bit convoluted as I tried to squeeze it into the gaps in the code so the source would form a rectangle.
At this point, we're ready to begin the output loop, processing the characters one by one, converting the special cases (the spots, line breaks, etc.) via the previously constructed lookup table.
Finally we check whether we've displayed all the required ladybugs, otherwise continue back to the start the of the outer loop.
> 6 votes

# Answer
# Ruby, ~~203~~ ~~193~~ 190 bytes

```
f=->n{s=%q{    _V_
  /(@I@)\
 /137x731\
|0596x6950|
 \248x842/
  ''-!-''
}
n-=d=n>0?n/(1+~-n/23):0
s.gsub!(/\d/){$&.to_i<d/2??o:' '}
x=[d%2,d<=>21]*2
s.gsub!(?x){"|O|"[x.pop]}
n>0?s+f[n]:s}

```

Try it online!

* Saved 10 bytes thanks to Jordan
> 3 votes

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


title: Evaluate the binomial theorem!

text:
# Question
Title: Evaluate the binomial theorem!
Your mission, even if you don't accept it, is to input three numbers from STDIN or file:

> 5 0.5 6

What you must do is evaluate this:

> (5a + 0.5b)^6

This basically means that the first two numbers are the coefficients of a and b and the third is the exponent in a binomial expansion.

Rules:

* The first two numbers are either integers or simple terminating fractions.
* The third number is a positive integer.
* Do not use any inbuilt binomial functions from libs. (thanks to comments)
* The shortest code wins!

Go on, do it.

# Answer
> -2 votes
### C (C99), 223 chars

```
#include <stdio.h>
#include <math.h>
int f(int n,int k){
    return k==0?1:(n*f(n-1,k-1))/k;
}
int main(void){
    float a,b;int n;
    scanf("%f%f%d",&a,&b,&n);
    for(int k=0;k<=n;k++)
        printf("%d*(%fa)^%d*(%fb)^%d+",f(n,k),a,n-k,b,k);
    puts("0");
}

```

Input:

```
1 1 2

```

Output:

```
1*(1.000000a)^2*(1.000000b)^0+2*(1.000000a)^1*(1.000000b)^1+1*(1.000000a)^0*(1.000000b)^2+0

```

# Answer
> 1 votes
## Mathematica 36

```
InputForm@Expand[(#1 a + #2 b )^#3] &

```

Usage

```
InputForm@Expand[(#1 a + #2 b )^#3] &[5, .5, 6]

```

Result:

```
15625*a^6 +9375.*a^5*b +2343.75*a^4*b^2 +312.5*a^3*b^3 +23.4375*a^2*b^4 + 0.9375*a*b^5 + 0.015625*b^6

```

# Answer
> 0 votes
F# 153 chars 156 bytes

```
let a,b,n=1.,2.,3
let rec C k=if k=0 then 1 else (n-k+1)*C(k-1)/k
List.iter(fun i->printf"%+ga^%ib^%i"(pown a (n-i)*pown b i*float(C i)) (n-i) i)[0..n]

```

# Answer
> 0 votes
# Python 2, 144 bytes

```
a,b,n=input();f=lambda n:-~(n and~-n*f(~-n))
for k in range(-~n):print"+ "[0**k]+"%d*(%d*a^%d)*(%d*b^%d)"%(f(n)/f(k)/f(n-k),a**(n-k),n-k,b**k,k)

```

Try it online!

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