# Question
Title: A single pixel moving in a circular path
This is a graphical output challenge where the task is to give the shortest code *per* language.

**Task**

Your code should plot a single purple pixel (hex value #800080 or rgb(128, 0, 128)), moving clockwise round a circle. It should take exactly 60 seconds to make a full journey round the circle and should continue indefinitely. Nothing else should be shown on the screen or window except for the pixel. The width of the circle should be 0.75 (rounding suitably) the width of the screen or window and the background should be white. To prevent silly solutions, the screen or window should be at least 100 pixels wide.

Your code should be a **full program**.

**Languages and libraries**

You can use any language or library you like. However, I would like to be able to test your code if possible so if you can provide clear instructions for how to run it in Ubuntu that would be very much appreciated.

**Missing top twenty languages. Help needed.**

The following top twenty programming languages are currently missing any solution at all.

* C, C++, C#, Python, PHP, Visual Basic .NET, Perl, Delphi/Object Pascal, Assembly, Objective-C, Swift, Pascal, Matlab/Octave, PL/SQL, OpenEdge ABL, R

### Catalog

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

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 62095; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 9206; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
# Processing, ~~101~~ ~~97~~ 96 bytes

*4 bytes thanks to Flambino.*

*1 byte thanks to Kritixi Lithos.*

```
float d;void draw(){background(-1);stroke(#800080);d+=PI/1800;point(50+cos(d)*38,50+sin(d)*38);}

```

This creates a default 100 by 100 pixel window with the required animation.

Disclaimer: that image is not a GIF. Don't stare at it for a minute.
> 23 votes

# Answer
# QB64, 79 bytes

*QB64 is a QBasic emulator that adds some nice features. This program uses one (`CLS,15`) that isn't supported by vanilla QBasic.*

```
SCREEN 7
DO
T=TIMER/9.55
PSET(COS(T)*75+99,SIN(T)*75+99),5
PLAY"c8"
CLS,15
LOOP

```

**This is very loud.** It uses the `PLAY` command to halt execution for a short while before clearing the screen; otherwise the pixel will flicker and become invisible.

Download QB64, load this file, click `Run` and then `Start`.

Here it is in action:

I took some tricks (`SCREEN 7` instead of `SCREEN 13`, and `PSET` instead of `POKE`) from @DLosc's answer, so credit is due. As in his answer, my magenta is actually `#8B008B`, which was deemed acceptable by the OP.

(The constant `9.55` is an approximation of `30/π = 9.54929658551`. Is it close enough?)
> 16 votes

# Answer
# HTML, 235 ~~290~~ ~~295~~ ~~354~~ ~~347~~ bytes

```
<a><style>*{position:absolute;margin:0;box-sizing:border-box}body{height:100vh;width:100vh}a{left:12.5%;top:50%;width:75%;height:1px;border-left:1px solid purple;animation:r 60s infinite linear}@keyframes r{100%{transform:rotate(360deg

```

Save as a `.html` file and open in a browser, that doesn't need vendor prefixes, like Chrome or Firefox. Or try this fiddle.

---

This is a new version which is way shorter than my first attempt, that I had written 5 minutes before a meeting. The new size of the canvas is a square based on the viewport height. That works pretty well and is not restricted to a certain defined height. I'm very accurate about the settings in the challenge (75% size of its parent, purple and 1px). Therefore I need and can't discard or simplify the following rules:

```
* { margin: 0; box-sizing:border-box; }
a { left: 12.5%; }

```

---

**Ungolfed**

This is the *ungolfed* version with clean markup:

```
<!DOCTYPE html>
<html>

<head>
    <style>
        * {
            position: absolute;
        }

        body {
            margin: 0;
            height: 100vh;
            width: 100vh;
        }

        a {
            left: 12.5%;
            top: 50%;
            width: 75%;
            height: 1px;
            border-left: 1px solid purple;
            box-sizing: border-box;
            animation: r 60s infinite linear;
        }

        @keyframes r {
            100%{
                transform: rotate(360deg)
            }
        }
    </style>
</head>
<body>
    <a></a>
</body>

```

**Edits**

* *Added* **7 bytes**. I thought nobody would notice, that there's a default easing on the animation. ;) I've set it to `linear` now.
* *Saved* **59 bytes** by throwing everything abort that the browser will handle automatically.
* *Saved* **3 bytes** by removing the trailing `)}}`. Thanks to toothbrush.
* *Saved* **2 bytes** by using `12%` instead of `12px` which is the same value corresponding to the size of the parent element.
* *Saved* **55 bytes** due to massive refactoring, also taken a lot of comments into account. Thanks a lot for all the contributions.
> 14 votes

# Answer
# Java, ~~449~~ ~~443~~ 439 bytes

Because I've always had stupid ideas. Like golfing in Java ;) .

```
import java.awt.*;import javax.swing.*;class F extends JFrame{F()throws Exception{setContentPane(new P());setSize(400,400);setVisible(0<1);for(;;Thread.sleep(100))repaint();}class P extends JPanel{double c;public void paintComponent(Graphics g){g.setColor(new Color(8388736));c=(c-0.1)%60;double t=0.104*c;g.fillRect((int)(180+Math.sin(t)*120),(int)(180+Math.cos(t)*120),1,1);}}public static void main(String[]x)throws Exception{new F();}}

```

Edit: Thanks for @Ypnypn for golfing 7 bytes!

Edit2: Thanks for @Franz D. for saving 3 bytes!
> 14 votes

# Answer
# TI-BASIC, 44 bytes

For the TI-84+ CSE/CE calculators, which support some limited BASIC color graphics.

```
AxesOff
ZSquare
While rand
Pt-Off(imag(Ans),real(Ans
7.5e^(-i6startTmr°
Pt-On(imag(Ans),real(Ans),13
End

```

The color here is magenta, or color 13 (one can also use the `MAGENTA` token).

I use `rand` instead of `1` for the infinite loop condition to provide a tiny bit of delay (~15 ms) between when the pixel is displayed and when it is turned off again.

Set your calculator to radian mode before running this program; I don't count this in the size because it's the default state. Also set `Ans` to 0 by entering a 0 before the program; this is also the default.

Thanks to @quartata for testing this program (I don't own a color calculator).
> 14 votes

# Answer
# Mathematica, ~~102~~ ~~101~~ 94 bytes

```
Animate[Graphics[{White,Disk[],{Purple,Point[{0,1}]}}~Rotate~-t],{t,0,2π},DefaultDuration->60]

```

Creates a white circle that is hidden and places a point that follows its edge from 0 to 2π. Mathematica's `DefaultDuration` option let's me set it to complete a loop every 60 seconds.

Here's a sped up version of the output:

EDIT: Change `Circle` to `Disk` to save 2 characters, added a negative sign to `t` to make it move clockwise.

EDIT: Saved 7 bytes by using the `~` operator (thanks to Mauris).
> 13 votes

# Answer
# Java, 339 308 289 287 bytes

```
import java.awt.*;class F extends Frame{{setSize(200,200);show();}int c;public void paint(Graphics g){g.setColor(new Color(8388736));g.fillRect((int)(99+Math.sin(--c*.01)*75),(int)(99+Math.cos(c*.01)*75),1,1);for(int i=0;++i<62864;)paint();}public static void main(String[] x){new F();}}

```

Thanks to @Peter Lenkefi, whose great solution got me started, and whose for-loop I shamelessly copied!

The main saving was due to switching to pure AWT and rendering directly in the Frame -- no need for a JPanel (or Canvas). I also made the counter an integer variable, updated by simple increment, and saved a few bytes twiddling the constants to be able to strip a digit here and there.

**EDIT:** Thanks to @Peter Lenkefi and @tobii for their suggestions in the comments. Beating HTML would be nice -- does anyone know how to reliably pause execution in Java without using sleep() and having to catch exceptions?

**EDIT 2:** JAVA BEATS HTML (currently at 290 bytes!) :D Timing is now machine-dependent, but ~60 seconds for a full circle on my machine, which is OK according to @Lembik. Thanks again to @PeterLenkefi for his suggestion -- my answer is more than half his :)

**EDIT 3:** @Ajay suggested to remove the "re" from "repaint". Two bytes less. We're getting there :)
> 13 votes

# Answer
# Haskell, ~~143~~ 136 bytes

This uses the gloss package:

```
import Graphics.Gloss
main=animate(InWindow""(100,100)(0,0))white$ \t->color(makeColor 0.5 0 0.5 1).rotate(t*6).translate 38 0$circle 1

```

The prettier version is

```
import Graphics.Gloss

purple :: Color
purple = makeColor 0.5 0.0 0.5 1.0

main :: IO ()
main = animate (InWindow "" (100,100) (0,0)) white $ \t ->
    color purple . rotate (t * 6) . translate 38 0 $ circle 1

```
> 9 votes

# Answer
## HTML (CSS?), 167 bytes

Inspired by insertusernamehere's answer

```
<style>body{position:fixed;left:50%;top:12%;width:1px;height:75vmin;border-top:1px solid #800080;animation:r 60s infinite linear}@keyframes r{to{transform:rotate(1turn

```

Ungolfed:

```
body {
    position: fixed;
    left: 50%;
    top: 12%;
    width: 1px;
    height: 75vmin;
    border-top: 1px solid #800080;
    animation: r 60s infinite linear;
}
@keyframes r {
    to {
        transform: rotate(1turn);
    }
}
```
> 8 votes

# Answer
# QBasic, 106

```
SCREEN 7
COLOR 5,15
DO
t=TIMER
CLS
PSET(99+99*COS(i),99+99*SIN(i))
i=i+ATN(1)/75
1IF TIMER<t+.1THEN 1
LOOP

```

Tested on QB64, which says it has a Linux version (though I've only tried it on Windows).

* `SCREEN 7` sets the graphics mode.
* `COLOR 5,15` sets dark magenta as foreground color and bright white as background color.
* `DO ... LOOP` is an infinite loop. Usually you would see it as `DO WHILE ... LOOP` (or you can put `LOOP WHILE` instead, or use `UNTIL` for a negated condition), but you can also leave the condition out, in which case it loops forever.
* `TIMER` is the number of seconds since midnight, as a floating-point value.
* `CLS` = CLear Screen.
* `PSET` SETs a Point to a color, foreground color by default.
* `i` starts at zero and counts up by pi/300 each time through the loop, thus completing a full circle after 600 repetitions. We calculate pi as 4\*arctan(1).
* The last line waits until 0.1 seconds have elapsed. The idiom that I learned from my QBasic books was `t# = TIMER: WHILE TIMER < t# + 0.1: WEND`. But we don't need double-precision numbers (marked with `#`) for a 0.1-second difference, and it turns out that the `IF cond THEN [GOTO] line` syntax is 1 character shorter than a `WHILE ... WEND` loop.

The loop repeats 600 times in 60 seconds, thus completing a full circle.

### Caveats

* Color 5, dark magenta, is `#8B008B` instead of the requested `#800080` (cleared with the OP).
* Screen mode 7 is 320x200, and so the circle has diameter 198, which isn't \>= 0.75 of the width but is \>= 0.75 of the height (also cleared with the OP).
* If you run this on DOS QBasic, it's fullscreen, so the "pixel" isn't actually a single pixel on the monitor (unless you happen to have a 320x200 monitor). But it should be close enough. QB64 runs in a window that uses the exact dimensions, and thus the pixel is a literal pixel.
* In QB64 at least, this takes more like 65 seconds to make a complete revolution. I don't really know why; it must be either rounding errors or overhead on the loop, though I've tried mitigating both without success. In theory, the code should work correctly as-is. In practice, one can tweak the amount by which `i` is incremented until a revolution is close enough to 60 seconds. (Try a denominator of 69 or 68.)
* No pretty picture here. :( LICEcap's quality wasn't good enough to capture a single pixel accurately.
> 7 votes

# Answer
# mIRC script, 184 bytes

```
alias g {
window -p @m -1 -1 100 128
f
}
alias f {
inc %s 1
set %o $calc(%s *38/360)
clear @m
drawdot -r @m $rgb(128,0,128) 1 $calc($cos(%o)*38+50) $calc($sin(%o)*38+52)
.timer 1 1 f
}

```

This is optimised for mIRC in Wine. Start mIRC, press `Alt + R` then paste this, close the editor and run it with `/g`

  The timing on the gif might be off.
> 7 votes

# Answer
# Ruby with Shoes, 159 bytes

```
Shoes.app{animate{background stroke white
fill purple
r=0.75*c=self.width/2
t=Time.now
m=Math
rect c+r*m.sin(a=(t.sec+t.usec*1e-6)*m::PI/30),c-r*m.cos(a),2,2}}

```

The pixel is actually the tip of an analog clock's seconds hand. So this one is absolutely precise.

## Ruby with Shoes, 134 bytes

```
m=Math
Shoes.app{animate{|f|r=0.75*c=self.width/2
background stroke white
fill purple
rect c+r*m.sin(a=f*m::PI/360),c-r*m.cos(a),2,2}}

```

This is a frames-per-seconds based alternative, inspired by the other answers. Although the documentation says the default fps is 10, practical tests shows it is actually 12.

Both solutions take “The width of the circle should be 0.75 (rounding suitably) the width of the screen or window” literally: calculate based on window width, so the pixel occasionally may leave the bottom of a non-square window. Not sure how such case is expected to be handled. (Use minimum of width and height? Walk on oval path?) The window starts with default 600 x 500 size and is resizable.
> 6 votes

# Answer
## R, 170 bytes

```
library(animation);for(i in 1:60){par(mar=rep(0,4));plot.new();t=2*pi*(1-i)/60;points(3*cos(t)/8+.5,3*sin(t)/8+.5,pch=19,col="#800080");ani.record()};repeat{ani.replay()}

```

It relies on package `animation`. And here 's a gif to show it works:

### Invalid Solution saving to a gif (139 bytes):

```
animation::saveGIF({for(i in 1:60){par(mar=rep(0,4));plot.new();t=2*pi*(1-i)/60;points(3*cos(t)/8+.5,3*sin(t)/8+.5,pch=19,col="#800080")}})

```

This one requires ImageMagick to be installed. The result is saved to a gif.
> 6 votes

# Answer
## X86 Machine-code - ~~150~~ ~~146~~ ~~149~~ ~~133~~ 127 bytes

**Golfed version:**

```
        00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
        --------------------------------------------------------------------
0000    B0 13 CD 10 BA C9 03 88 F1 BE 76 01 F3 6E B0 0F - °.Í.ºÉ.ˆñ¾v.ón°.
0010    49 68 00 A0 07 F3 AA 64 66 A1 6C 04 66 A3 80 01 - Ih. .óªdf¡l.f£€.
0020    64 66 A1 6C 04 66 2B 06 80 01 66 50 89 E5 D9 EB - df¡l.f+.€.fP‰åÙë
0030    D8 C0 DA 4E 00 DE 34 D9 FB BB 7D 01 DE 0F DE 47 - ØÀÚN.Þ4Ùû»}.Þ.ÞG
0040    FE DF 5E 02 DE 0F DE 47 FE DF 5E 00 5F 69 FF 40 - þß^.Þ.ÞGþß^._iÿ@
0050    01 58 01 C7 BB 88 01 8B 0F 39 CF 74 C3 30 C0 AA - .X.Ç»ˆ.‹.9ÏtÃ0Àª
0060    4F 89 3F 89 CF B0 0F AA 31 C0 FE C4 CD 16 74 B0 - O‰?‰Ï°.ª1ÀþÄÍ.t°
0070    B8 03 00 CD 10 C3 20 00 20 44 04 64 00 4B 00    - ¸..Í.Ã . D.d.K.

```

**'Ungolfed', source version:**

```
; golfCrcl.asm
;
; - 16 bit implementation of an animated pixel that circumscribes a circle.
; - 127 bytes .COM file
;
;   - enhzflep -
;   31 Oct 2015 - initial
;               - set closest colour to desired #800080
;    2/3 Nov 2015 - removed unnecessary instuctions, used BX register to index mem by fpu
;               - removed .data section alignment, better register use in curPixel/lastPixel compares and calcs, reusing value of si after palette setting
[section .text]
[bits 16]
[org 0x100]
EntryPoint:
;   mov     fs, bx          ; bx is 0 on entry. Set fs seg register to this

    ; set graphics mode 320x200
    mov     al, 0x13
    int     0x10

    ; set colour #0 to be as close to the desired one as possible
    ; the vga palette registers are 6 bits by default (some models allow switching to 8 bits)
    ; therefore, we cant represent all of the 16.7m colours that we can in 24bit modes
    ; we're limited to 'just' 64*64*64 = 262,144 (256k) colours. Unfortunately, #800080 is not
    ; a colour we can represent exactly in mode13 or any other mode with 6 bit regs.
    mov     dx, 0x3c9
    mov     cl, dh
    mov     si, desiredCol
    rep     outsb                           ; cx now=0 and si now points to totalTicksNeeded

    ; clear the screen to white
    mov     al, 0x0f                        ; index of a colour thats already FF,FF,FF
;   xor     cx, cx                          ; cx = 0 - its zeroed by the rep outsb instruction above.
    dec     cx                              ; cx = FFFF
    push    word 0xA000                     ; segment of video memory
    pop     es                              ; pop it into es
    rep     stosb                           ; es:[di] = 0F, inc di, dec cx. If cx != 0 then repeat.

    ; setup the timing stuff
    mov     eax, [fs:0x046C]                ; 32 bit value updated at 18.2Hz by bios
    mov     [initialTicks], eax

.drawLoop:
    mov     eax, [fs:0x046C]                ; 32 bit value updated at 18.2Hz by bios
    sub     eax, [initialTicks]             ; eax = curTime-startTime (in increments of 1/18.2 of a second --- 182 = 10 seconds)

    push    eax                             ; number of elapsed clock ticks - ready to be loaded by fpu. Also stack space for calc result
    mov     bp, sp                          ; get pointer to last element pushed onto the stack
    fldpi                                   ; st0 = pi
    fadd    st0                             ; st0 = 2pi
    fimul   long [bp]                       ; (currentTick/requiredTicks) * 2pi
;   fidiv   word [totalTicksNeeded]
    fidiv   word [si]                       ; si still points to totalTicksNeeded after setting the palette earlier
    fsincos                                 ; st0 = cos(old_st0), st1 = sin(old_st0)

    mov     bx, radius
    fimul   word [bx]                       ;   fimul word [radius] -  cos(angle)*radius
    fiadd   word [bx-2]                     ;   fiadd word [origin] -  origin + cos(angle)*radius
    fistp   word [bp+2]                     ; ---- X-coord -------

    fimul   word [bx]                       ;   fimul   word [radius]
    fiadd   word [bx-2]                     ;   fiadd   word [origin]
    fistp   word [bp+0]                     ;  ---- Y-coord -------

    ;---------------
    pop     di                              ; calculated Y-coord
    imul    di, 320                         ; multiply it by the screen width
    pop     ax                              ; calculated X-coord
    add     di, ax                          ; di = x + (pixels_per_row * y_coord)

    mov     bx, lastIndex
    mov     cx, [bx]                        ; get the mem index for the last pixel
    cmp     di, cx                          ; check if we're indexing the same pixel as last time through the loop
    je      .drawLoop                       ; if so, return to start of loop - no need to delete and redraw the pixel in the same spot.

    xor     al, al                          ; col index 0
    stosb                                   ; draw our purple pixel
    dec     di                              ; stosb advanced di to the next pixel, undo this (stosb followed by dec di is still shorter than mov es:[di], al)
    mov     [bx], di                        ; save the pixel's mem address
    mov     di, cx                          ; restore index of pixel drawn last time through the loop
    mov     al, 0x0f                        ; pal index of white
    stosb                                   ; erase the last pixel

    ; check for a keystroke
    xor     ax, ax
    inc     ah
    int     0x16
    jz      .drawLoop                           ; loop if no keys pressed

.drawingDone:
    ; set text mode 80x25
    mov     ax, 0x3
    int     0x10

    ; program exit
    ret                                     ; Dos pushes a 0000 onto the stack and copies CD 20 to offset 0 of our code-seg
                                            ; before it invokes our program. ret jumps back to that CD 20 (int 0x20) instruction

; Since this is a .COM file, all program, data and stack exist in the same segment.
; Using .text and .data sections only improves program readability - doing so only has minor effects on the binary produced.
;
; In this case, the assembler word aligns anything in the data section. This may have the effect of adding a padding byte,
; which we really dont need/want here. Data is machine-word aligned to improve the speed of access for the hardware. Machine-word
; is used to refer to the size of an int. In the case of 16 bit code, this will generally be 16 bits, 32 bit code has 32 bit words
; and so on. This code is 16 bit, so things should be aligned to word boundaries for maximum execution speed
;
;[section .data]
desiredCol          db  0x80/4, 0x00, 0x80/4        ; palette registers are only 6 bit.
totalTicksNeeded    dw  1092
origin              dw  100
radius              dw  75

; ticks/second = 18.2
; totalTime = 60 seconds
; totalTicks = 1092 (18.2 * 60)
; degreesPerTick = 360 / 1092 = 0.3296703
; timerTicksAddr = 0040:006C (0000:046C) dword
[section .bss]
initialTicks    resd    1
lastTickValue   resd    1
lastIndex       resw    1

```

**Downloadable, base64 encoded version**

```
data:application/octet-stream;base64,sBPNELrJA4jxvnYB826wD0loAKAH86pkZqFsBGajgAFkZqFsBGYrBoABZlCJ5dnr2MDaTgDeNNn7u30B3g/eR/7fXgLeD95H/t9eAF9p/0ABWAHHu4gBiw85z3TDMMCqT4k/ic+wD6oxwP7EzRZ0sLgDAM0QwyAAIEQEZABLAA==

```

Copy and paste this address into your browser. Rename the resulting file `golfcrcl.com` and run in a DOS environment, i.e DosBox.
> 5 votes

# Answer
# SVG, 177 bytes

```
<svg><g transform=translate(75,75)><circle id=x r=.5 cx=56 fill=#800080><animateTransform xlink:href=#x attributeName=transform type=rotate to=360 dur=60s repeatCount=indefinite
```

Invalid markup from hell to breakfast, but it runs (in Chrome at least). Like a HTML5 canvas, the default size for an SVG appears to be 300x150, so that's what this is assuming.

*Edit: Whoops, I'd accidentally left in a duration of 6 instead of 60. Fixed that, but also found that `0.5` works as just `.5`, so no change in the byte count.*
> 5 votes

# Answer
# Javascript / Processingjs, ~~175~~ ~~173~~ ~~156~~ ~~153~~ 152 bytes

```
var s=256,e,h,m;void setup(){size(s,s);h=s/2;}void draw(){background(-1);m=-millis()*(PI/36000);stroke(h,0,h);e=s/2*0.75;point(h+sin(m)*e,h+cos(m)*e);}

```

To run : either visit http://www.openprocessing.org/sketch/226733 to see it in action using processing.js, or download processing 2.0 from processing.org, paste the code into the processing IDE, select Javascript mode and watch it go.
> 4 votes

# Answer
# D, 286 280 bytes

(392 if written normally)

```
import simpledisplay,std.math;void main(){auto w=new SimpleWindow(100,100);auto c=50;auto r=c*2/3;int t;auto y=600/PI;w.eventLoop(50,{auto p=w.draw();p.clear;p.outlineColor=Color(128,0,128);p.drawPixel(Point(c+cast(int)(r*cos(t/y)),c+cast(int)(r*sin(t/y))));if(++t==1200)t=0;});}

```

Or the way I originally wrote it without golfing:

```
import simpledisplay, std.math;

void main() {
        auto window = new SimpleWindow(100, 100);
        auto c = window.width/2;
        auto r = c*2/3;
        int t;
        float cycle = 20*60/(PI*2);
        window.eventLoop(50, {
                auto p = window.draw();
                p.clear;
                p.outlineColor = Color(128, 0, 128);
                p.drawPixel(Point(c + cast(int) (r*cos(t/cycle)), c + cast(int) (r*sin(t/cycle))));
                if(++t == 20*60)
                        t = 0;
        });
}

```

Depends on simpledisplay.d and color.d located here: https://github.com/adamdruppe/arsd

Just download those two individual files and put them in your same directory as the above code, then: `dmd yourfile.d simpledisplay.d color.d` to compile and then just run it.

My little library was written to make quick animations like this fairly simple so this plays well to its strengths! Alas, I kinda like long identifier names and didn't provide a `Point` constructor that takes `float` so that adds 18 bytes casting and.... idk a couple dozen spelling out my method names.
> 4 votes

# Answer
# Mathematica ~~208 185~~ 139 bytes

Moves a purple pixel around an array used as an Image.

**Method 1** 139 bytes

```
n=900;Dynamic@Refresh[t=DateValue@"Second";ReplacePixelValue[Image@Array[1&,{n,n}],
400{Cos[z=Pi/30t],Sin@z}+450->Purple],UpdateInterval->1]

```

---

**Method 2** 154 bytes

Plots a pixel along a circular path in 60 seconds.

```
Dynamic@Refresh[t=DateValue@"Second";Graphics[{AbsolutePointSize@.01,Purple,
Point[{Cos[z=Pi/30t],Sin@z}]},PlotRange->1,ImageSize->Full],UpdateInterval->1]

```

---

**Method 3** 193 bytes

This draws a clock, with ticks and labels in white, for which the second hand is a pixel.

```
Dynamic@Refresh[ClockGauge[AbsoluteTime[],TicksStyle->White,
GaugeMarkers->{None,None,Graphics[{White,Disk[],Purple,
AbsolutePointSize[.01],Point@{3,0}}]},PlotTheme->"Minimal"],UpdateInterval->1]

```
> 4 votes

# Answer
# C#, ~~379~~ 365 bytes

```
using System.Windows.Forms;using static System.Math;class P:Form{static void Main(){var f=new P();var p=new PictureBox();f.SetBounds(0,0,1000,1000);f.Controls.Add(p);f.Show();for(var i=0d;;i+=PI/3000){p.SetBounds((int)(Cos(i)*375+500),(int)(Sin(i)*375+500),1,1);p.CreateGraphics().Clear(System.Drawing.Color.FromArgb(-8388480));System.Threading.Thread.Sleep(10);}}}

```

Depends on `System.Windows.Forms` and `System.Drawing` to run. Output is in a 1000x1000 window.
> 4 votes

# Answer
# Obj-C++ / Cocoa, ~~777~~ ~~678~~ ~~668~~ ~~657~~ ~~643~~ 628 bytes

```
#include <Cocoa/Cocoa.h>
float r;@implementation V:NSView-(void)drawRect:(NSRect)d{CGContext*c=(CGContext*)NSGraphicsContext.currentContext.graphicsPort;CGContextSetRGBFillColor(c,.5,0,.5,1);CGContextFillRect(c,(CGRect){cos(r)*38+50,sin(r-=pi/300)*38+50,1,1});[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(x)userInfo:0 repeats:0];}-(void)x{self.needsDisplay=1;}@end
int main(){NSRect b={0,0,100,100};NSWindow*w=[[NSWindow alloc]initWithContentRect:b styleMask:1 backing:2 defer:0];[w orderFront:0];w.backgroundColor=[NSColor whiteColor];w.contentView=[[V alloc]initWithFrame:b];[NSApp run];return 0;}

```

So this is probably the worst way to do anything, but I figured I'd try.

Can be compiled on a Mac (mine anyway) with `g++ -framework Cocoa file.mm` and run from the terminal (`ctrl-C` to quit, since it's not an app).

*Edit: Saved 99 bytes: Fixed `main()` to run on OS X 10.10 (1st version only ran on 10.8), skipped translate/rotate in favor of plain trig calculations, stopped bothering with window placement, and other small stuff.*

*Edit: Saved another 10 bytes: Changed to just `orderFront` to display the window. Doesn't actually make it the front window, though, but neither did `orderFrontAndMakeKey`, so...*

*Edit: Saved another 11 bytes: Skipped `NSMakeRect` and found a digit that just had to go.*

*Edit: Saved another 14 bytes: Didn't need to assign the `NSTimer` instance to anything, and can apparently skip initializing `r` to zero.*

*Edit: Saved another 15 bytes: I can't stop. Send help.*
> 4 votes

# Answer
## Elm, 274 bytes

```
import Color exposing (..)
import Graphics.Collage exposing (..)
import Time exposing (..)
main=Signal.map((\t->collage 200 200 [move(75*cos(-2*pi*t/60),75*sin(-2*pi*t/60))(filled(rgb 128 0 128)(circle 2)),outlined(solid black)(square 200)])<<inSeconds)(every(0.01*second))

```

Try or edit it in your browser:

Note that if we get rid of the imports and drawing the outline around the canvas, we're down to 149 bytes, but that's probably cheating!
> 3 votes

# Answer
# Python 2 + Pygame, ~~221~~ ~~198~~ 193

```
exec'from %s import*;'*3%('math','pygame','time')
_,p,D=[255],128,display
S=D.set_mode(_*2)
while 1:S.fill(_*3);S.set_at(map(lambda f:int(p+f(pi*(time()%60)/30)*96),(cos,sin)),(p,0,p));D.flip()

```
> 3 votes

# Answer
# C#, 301 bytes

```
using System.Windows.Forms;using System.Drawing;class P:Form{static void Main(){Application.Run(new P());}P(){Paint+=(o,e)=>{var g=e.Graphics;g.Clear(Color.White);g.TranslateTransform(150,150);g.RotateTransform(System.DateTime.Now.Second*6);g.FillRectangle(Brushes.Purple,105,0,1,1);Invalidate();};}}

```

Depends on default size metrics; size and position may be a bit off depending on a number of factors. May or may not flicker horribly; to solve that, add the following:

```
SetStyle(ControlStyles.OptimizedDoubleBuffer|ControlStyles.AllPaintingInWmPaint,true);

```
> 3 votes

# Answer
# Lua + Löve, 189 characters

```
t=0
m=math
l=love
g=l.graphics
function l.update(d)t=t+d end
function l.draw()a=t*m.pi/30
g.setBackgroundColor(255,255,255)g.setColor(127,0,127)g.point(400+225*m.cos(a),300+225*m.sin(a))end

```

`love.update()` receives as parameter the time elapsed since previous frame. Draws in the default 800 x 600 window at fixed coordinates, as the window is not resizable anyway.
> 3 votes

# Answer
# C (using SDL1.2), ~~237~~ 233

```
#include <SDL.h>
#define P(f)(int)(128+96.0*f(3.14*((int)(.001*SDL_GetTicks())%60)/30))
main(){SDL_Surface*s=SDL_SetVideoMode(255,255,32,0);while(1){int*p=s->pixels;memset(p,255,260100);p[P(cos)+s->w*P(sin)]=0x800080FF;SDL_Flip(s);}}

```

Compiles & run using `gcc -I/usr/include/SDL snippet.c -lSDL -lm && ./a.out`
> 3 votes

# Answer
# ActionScript 2.0, 151 bytes

Unfortunately, Adobe Flash isn't freeware, and Google informs that it doesn't work on Linux without a VM or Wine (and even with Wine, it only *mostly* works). Still, I wanted to see how well it would do on this task. Pretty well, it turns out.

```
createEmptyMovieClip("p",0)
p._x=p._y=r=200
p.beginFill(0x800080)
p.moveTo(r,0)
p.lineTo(r-1,0)
p.lineTo(r,1)
onEnterFrame=function(){p._rotation+=.25}

```

The basic idea: create a new movie clip object, position it at (200, 200), and then draw a dot2 in it 200 pixels farther right. Now the movie clip is 200 pixels wide and 1 pixel high. The pivot point is the original coordinates where we started, so when we modify the `_rotation` property, the dot moves in a circle around the point (200, 200). Conveniently, `_rotation` is in degrees; 0.25 degrees/frame * 24 frames/second * 60 seconds/minute = 360 degrees/minute.

To run from scratch if you have Flash, create a new Flash document1, open the Actions panel, and paste the above code. No further customization is required, assuming the default white background, 550x400 canvas, and 24 fps. Hit Ctrl-Enter and watch it go.

If you don't have Flash itself, you can still view the results with the free Flash Player, which should come with most modern browsers. Download the SWF file here. If you can't play it, try downloading this HTML page as well and opening it, with the SWF file in the same directory.

1 Tested on Adobe Flash CS4 Professional, choosing "Flash File (ActionScript 2.0)" when asked what type of new file to create.

2 Actually a small triangle, as you'll see if you zoom in on it enough. It was the golfiest way I could find to draw a dot.
> 2 votes

# Answer
# JavaScript w/jQuery, 205 bytes

```
y=75;with($('<canvas/>').appendTo(document.body)[0].getContext('2d')){fillStyle='#800080';translate(y,y);(f=function(){clearRect(-y,-y,y*2,y*2);fillRect(0,56,1,1);rotate(Math.PI/300);setTimeout(f,100)})()}

```

jsfiddle, snippet below

This is maybe not quite by the book. The default size of a canvas (in Chrome at least) is 300x150, so I've centered the circle on 75x75. I could center it on 150x75, and make its radius 113px (~75% of width), but it'd be outside the canvas some of the time, so I chose ~75% of height instead.

But it's not particularly short anyway, so meh'

```
y=75;with($('<canvas/>').appendTo(document.body)[0].getContext('2d')){fillStyle='#800080';translate(y,y);(f=function(){clearRect(-y,-y,y*2,y*2);fillRect(0,56,1,1);rotate(Math.PI/300);setTimeout(f,100)})()}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
```
> 2 votes

# Answer
## Blitz 2D/3D, 126 bytes

```
Graphics 180,180
ClsColor 255,255,255
Color 128,0,128
While 1
Cls
ang#=ang+3
Plot 90+67*Cos(ang),90+67*Sin(ang)
Delay 500
Wend

```

Unfortunately, this language is only supported on Windows (though it *may* run in Wine).
> 2 votes

# Answer
# Javascript ES6, 202 bytes

```
a=0;with((D=document).body.appendChild(D.createElement`canvas`).getContext`2d`)with(Math)setInterval((f=t=>t(a+=PI/6e3)*60+75)=>fillRect(f(cos,clearRect(0,0,150,150),fillStyle=`#800080`),f(sin),1,1),10)

```

Tested in Firefox 41.

Like the other (almost) pure Javascript answer, the circle is centered at 75x75 since the canvas elements default size is 300x150 as defined by the HTML specs.
> 2 votes

# Answer
# Matlab, ~~141~~ 136

I just submit this for you, Lembik, to have a complete list.

```
v=-100:100;
[y,x,m]=ndgrid(v,v,0);
n=75;
while 1;
    pause(1);
    c=m;
    c(x+i*y==round(n))=1;
    imshow(c);
    colormap([1,1,1;.5,0,.5]);
    n=n*exp(pi*i/30);
end

```

Old version:

```
v=-100:100;
[x,y,m]=ndgrid(v,v,0);
while 1;
c=m;
c(x+i*y==round(75*(-1)^(s/30)))=1;
imshow(c);
colormap([1,1,1;.5,0,.5]);
s=mod(s-1,60);
pause(1);
end

```
> 2 votes

# Answer
# PHP, 291 ~~295~~ bytes

I don't know whether this qualifies, but here is something:

```
function d($y,$a){$s=strrev(str_pad("
",140));echo"\033[0G".str_repeat($s,abs($y-30)).str_pad("\033[35m■",80+$a*sqrt(abs(pow(30,2)-pow($y,2)))*2,' ',STR_PAD_LEFT)."
".str_repeat($s,abs(30+$y))."\033[120A";usleep(5e5);}for(;;){for($y=30;$y>-30;--$y)d($y,1);for($y=-30;$y<=30;++$y)d($y,-1);}

```

Runs as a PHP-file from command line, like:

```
php what_is_this.php

```

---

**In Action**

This examples GIF runs 10 times faster than the original code (`usleep(5e4)` instead of `usleep(5e5)`):

---

**Notes**

* As I can't output one single pixel, I supersized it to this .
* One cycle should be approx. 1 minute.
* Yes, your whole console output is purple. ;)
* You need a large terminal window. If you're on OS X zoom out at least one or two times using `CMD + -` (Restore using `CMD + 0`).
* It doesn't know anything about 75%. Could be simulated by adding blank lines before and after the output.

Yes, it is rounding heavily and yes I think this can be golfed more, but I'm too tired right now. :)

---

**Ungolfed**

```
function d($y,$a){
    $s = strrev(str_pad("\n",140));
    echo "\033[0G";
    echo str_repeat($s, abs($y-30));
    echo str_pad("\033[35m■", 80 + $a * sqrt(abs(pow(30,2) - pow($y,2)))*2,' ', STR_PAD_LEFT) . "\n";
    echo str_repeat($s, abs(30+$y));
    echo "\033[120A";
    usleep(500000);
}

for(;;){
    for($y = 30; $y > -30; --$y) {
        d($y,1);
    }
    for ($y = -30; $y <= 30; ++$y) {
        d($y,-1);
    }
}

```

---

**Edits**

* *Saved* **4bytes** by throwing some `{}` over board.
> 2 votes

# Answer
# Tcl/Tk, 174

```
grid [canvas .c -bg #FFF -he 202 -w 202]
.c cr r 0 0 0 0 -outline #800080 -t p
while 1 {after 167;incr A;.c coo p [lmap r {cos sin cos sin} {expr 75*$r\($A/57.3)+77}]
update}

```
~~Tcl/Tk, 168
```
grid [canvas .c -bg #FFF -he 202 -w 202]
.c cr o 0 0 0 0 -f #800080 -t p
while 1 {after 167;incr A;.c coo p [lmap r {cos sin cos sin} {expr 75*$r\($A/57.3)+77}]
update}

```~~ ~~Tcl/Tk, 172
```
grid [canvas .c -bg #FFF -he 202 -w 202]
set p [.c cr o 0 0 0 0 -f #800080]
while 1 {after 167;incr A;.c coo $p [lmap r {cos sin cos sin} {expr 75*$r\($A/57.3)+77}]
update}

```~~  ~~Tcl/Tk, 173
```
grid [canvas .c -bg #FFF -he 202 -w 202]
set p [.c cr o 0 0 0 0 -f #800080]
while 1 {after 167;incr A;.c coo $p [lmap r {1.57 0 1.57 0} {expr 75*sin($A/57.3+$r)+77}]
update}

```~~ ~~Tcl/Tk, 195
```
proc P {y\ 0} {expr 75*sin($::A/57.3+($y?0:1.57))+77}
grid [canvas .c -bg #FFF -he 202 -w 202]
set p [.c cr o 0 0 0 0 -f #800080]
while 1 {after 167;incr ::A;.c coo $p [P] [P 1] [P] [P 1]
update}

```~~ ~~Tcl/Tk, 204
```
proc P {A y\ 0} {expr 75*sin($A/57.3+($y?0:1.57))+77}
grid [canvas .c -bg #FFF -he 202 -w 202]
set p [.c cr o 0 0 0 0 -f #800080]
while 1 {after 167;.c coo $p [P [incr A]] [P $A 1] [P $A] [P $A 1]
update}

```~~ ~~Tcl/Tk, 210
```
proc P {A y\ 0} {expr 75*[expr $y?"sin":"cos"]($A/57.3)+77}
grid [canvas .c -bg #FFF -he 202 -w 202]
set p [.c cr o 0 0 0 0 -f #800080]
while 1 {after 167;.c coo $p [P [incr A]] [P $A 1] [P $A] [P $A 1]
update}

```
Tcl/Tk, 214
```
proc P {A y\ 0} {expr 75*[expr $y?"sin":"cos"]($A*3.14/180)+77}
grid [canvas .c -bg #FFF -he 202 -w 202]
set p [.c cr o 0 0 0 0 -f #800080]
while 1 {after 167;.c coo $p [P [incr A]] [P $A 1] [P $A] [P $A 1]
update}

```~~
> 2 votes

# Answer
# Processing, ~~101~~ 100 bytes

```
float r;void draw(){background(-1);translate(50,50);stroke(#800080);rotate(r+=PI/1800);point(0,38);}

```

Instead of the sin/cos calculations, this uses the `translate` and `rotate` methods. Funnily enough, it ends up being 101 bytes just like Pietu1998's Processing code.1

I wish `rotate` calls would stack so I could skip `r`, but the transformation matrix is reset on each frame. Boo.

1: Well, at the time of writing it's the same, but there are 4 bytes to be saved in Pietu1998's, so it wins.

*Edit: Saved a byte thanks to Kritixi Lithos*
> 1 votes

# Answer
# javascript/html/css ~~343~~ ~~202~~ 182

```
s=document.getElementById('c').style
i=0
setInterval(function(){s.left=52+50*Math.cos(i+=.005)+'px'
s.top=52+50*Math.sin(i)+'px'},50)
```

```
b{color:#800080;position:absolute}
```

```
<b id=c>.</b>
```
> 1 votes

# Answer
# GLSL (Shadertoy), ~~180~~ ~~165~~ 142 bytes

```
void mainImage(out vec4 a,in vec2 b){float r=-iGlobalTime/9.55;a=floor(vec2(cos(r),sin(r))*135.+vec2(180))==floor(b)?vec4(.5,0,.5,1):vec4(1);}

```

Try it out by pasting it here. Can't golf the built-in variables unfortunately.

I have never written anything WebGL/OpenGL, but I figured why not? Seems to work, but it's probably horrible.

*Edit 1: Saved 15 bytes by skipping a variable, though it means the circle is no longer centered horizontally in the canvas, just offset the same as it is vertically.*

*Edit 2: Saved 23 bytes by also making it resolution dependent. Shadertoy's canvas is 640x360 by default.*
> 1 votes

# Answer
# Matlab, ~~104 103~~ 102 bytes

```
figure('Color','w');while 1;plot(3*exp(toc*pi/30i),'Co',[.5 0 .5]);axis([-4 4 -4 4],'off');drawnow;end

```

Smallest I could get it with the colour requirements. If you had gone for magenta rather than purple it would be 12 bytes shorter :).

```
figure('Color','w');                        %Start with a white background
while 1
         3*exp(toc*pi/30i)                  %This bit makes the point - e^(theta/i)
    plot(                 ,'Co',[.5 0 .5]); %This plots it
    axis([-4 4 -4 4],'off');                %Make the axis 33% larger than the circle and invisible
    drawnow;                                %Update within the loop
end

```

Basically it creates a figure which has a white background. Then in a forever loop it plots a figure which is a single point of a complex number which has a magnitude of 3 and an angle of the current time normalised to a 60 second circle. The colour of the plotted point is purple (#7f007f). Once plotted, the axis are set to limits of +/-4 which means the circle drawn will be 75% of the axis size. The axes are then turned off (made invisible) and the figure updated. This gives a nice point moving around a circle in real time.

I've corrected the code so that it rotates clockwise (it was going anticlockwise before) and in the process saved a byte :). The wonders of `-j*n` = `n/j`.
> 1 votes

# Answer
# VB.NET, 361 ~~395~~ ~~452~~ bytes

Thanks @ClickRick for pointing out all the unnecessary white-space :-)

```
Module m
Sub Main()
Dim f As New Form
f.BackColor=Color.White
f.MinimumSize=New Size(100,100)
f.ClientSize=New Size(100,100)
AddHandler f.Paint,Sub(r,g)
Dim u=Date.Now.Ticks/10000000/9.55,k=CInt(Cos(u)*37.5+37.5),l=CInt(Sin(u)*37.5+37.5)
g.Graphics.FillRectangle(Brushes.Magenta,k,l,1,1)
f.Invalidate()
End Sub
Application.Run(f)
End Sub
End Module

```

This is a console application that creates a form. This saves a lot of designer generated clutter.

Add a reference to `System.Drawing.dll` and `System.Windows.Forms.dll`. Add user Imports for System.Drawing, System.Windows.Forms and System.Math namespaces.

I shamelessly ripped the position calculation from Mauris' QB64 answer (https://codegolf.stackexchange.com/a/62126/20520), but based the calculation on `Date.Now.Ticks` instead, which needs to be converted to seconds by dividing by 10 million!

~~The form is refreshed by a timer~~ and the dot is painted directly to the form in its `Paint` event. This saves a lot of initialization code for any picturebox or similar.

From user12864's answer in C# (https://codegolf.stackexchange.com/a/62433/20520) I got the idea of invalidating the form in its own paint handler, which is a horrible thing to do but gets rid of any need for a timer. The timer solution looked a lot prettier due to all the flickering induced by this solution...but length over style in Code Golf I guess :-)

Unfortunately, the forms have a larger default `MinimumSize` than 100,100, which needs to be adjusted to fullfill the requirement. You also need to set `ClientSize` instead of `Size` to correctly scale the "active" drawing surface.

Believe it or not, GDI+ does not have a simple DrawPoint function. You draw a point by drawing a filled 1x1 rectangle.

`Application.Run()` starts the message loop for the form and shows it.
> 1 votes

# Answer
# SpecBAS, 103 bytes

```
1LET r=SCRh*.75/2,a=0:DO:PLOT INK 3;r*COS a+SCRw/2,r*SIN a+SCRh/2:INC a,TAU/60000:WAIT SCREEN:CLS:LOOP

```

INK 11 in SpecBAS isn't quite the right colour but it's close. Other than that, this is pretty standard stuff. A single pixel isn't easy to see on an 800x480 screen though!
> 1 votes

# Answer
## Python 2, 173 bytes

```
exec"from %s import*;"*3%("time","math","turtle")
color("#800080")
pu()
shape("square")
shapesize(.1)
while 1:r=screensize()[0]*.75;a=-time()%60/9.55;goto(r*cos(a),r*sin(a))

```

Here's an answer which uses the `turtle` module. Unfortunately I can't remember how big the turtle's square pen is, so I hope I scaled it down right (I'm passing `.1` into `shapesize`).

As a bonus, here's an invalid 163 byte version which skips out on the `math` module but the turtle blinks a lot:

```
from time import*
from turtle import*
color("#800080")
pu()
shape("square")
shapesize(.1)
speed(0)
while 1:ht();home();rt(time()%60*6);fd(screensize()[0]*.75);st()

```
> 1 votes

# Answer
# Qt Quick via qmlscene, 315

```
import QtQuick 2.5
Rectangle {id:p;visible:true;property double t: 0.0; Rectangle{width: 4;y: p.height / 2 + .75*p.height/2*Math.sin(p.t);x: p.width / 2 + .75*p.height/2*Math.cos(p.t);height: 4;color: "#800080"}NumberAnimation {target: p;property: "t";from: 0; to:3.14159*2;duration: 60000;loops: -1;running: true}}

```
> 1 votes

# Answer
# Progress ABL, character Interface, 445 bytes

A couple of comments:

I have no way in ABL to really work with pixels. It could possibly be done by creating a rectangle that's 1 x 1 pixel and moving it around. But even that would be cumbersome. Instead I choose to use a period character (.): hence this solution is for character interface and not a graphic client. Maybe I'll come back with a graphical solution some other time...

Since the space of one character is higher than it is wide I've set the screen size to 65 columns by 20 rows. Roughly estimating a square.

Purple colour is another problem. From start I'm limited to 16 preset colors and none match the purple I need. Changing the colors in character mode is done by editing a init file used when starting the program. Therefore I instead set the period to "color 13" - 255,0,255 by default. Not the wanted purple but at least a purple color.

Another dilemma is the absence of sine and cosine functions or anything remotely like that (rotate etc). To bypass this I choose to call an external Windows DLL - meaning this specific solution only works in Windows environments. However if there are any similar Linux libraries available it should be easy enough to port.

Of course I've been "inspired" by solutions in other languages to pull this off...

My main ways of reducing size:

* Shortening certain statements, ie `DISP` instead of `DISPLAY`.
* Global definitions (preprocessors).
* Whitespace and line breaks

*This is my first attempt at Golf so I might very well be doing something wrong here - like byte count or otherwise. Please tell me if so!*

Solution:

```
&GLOB v DEF VAR
&GLOB e EXTERNAL "MSVCRT40.DLL" CDECL:
PROCE cos {&e} DEF INPUT PARAM v AS DO. DEF RETURN PARAM r AS DO. END. PROCE sin {&e} DEF INPUT PARAM v AS DO. DEF RETURN PARAM r AS DO. END. {&v} c AS C FORM "x". {&v} t AS DE. {&v} i AS DE. {&v} j AS DE. c=".". REPEAT: t=t - 0.1. DISP c NO-LABEL WITH FRAM f SIZE 65 BY 20. c:FGC=13. RUN cos(T, OUTPUT i). RUN sin(t, OUTPUT j). c:ROW=10 + i * 7.5. c:COLUMN=30 + j * 26.3. PAUSE 1. END

```

Ungolfed:

```
&GLOBAL-DEFINE v DEFINE VARIABLE
&GLOBAL-DEFINE e EXTERNAL "MSVCRT40.DLL" CDECL:

PROCEDURE cos {&e}
    DEFINE INPUT PARAM v AS DOUBLE.
    DEFINE RETURN PARAM r AS DOUBLE.
END.

PROCEDURE sin {&e}
    DEF INPUT PARAM v AS DOUBLE.
    DEF RETURN PARAM r AS DOUBLE.
END.

{&v} c AS CHARACTER FORMAT "x".
{&v} t AS DECIMAL.
{&v} i AS DECIMAL.
{&v} j AS DECIMAL.

c = ".".

REPEAT:
    t = t - 0.1.
    DISPLAY c NO-LABEL WITH FRAM f SIZE 65 BY 20.
    c:FGCOLOR = 13.
    RUN cos(T, OUTPUT i).
    RUN sin(t, OUTPUT j).
    c:ROW = 10 + i * 7.5.
    c:COLUMN = 30 + j * 26.3.
    PAUSE 1.
END

```

(All lines normally end with period or colon (colon for start of blocks) but the compiler lets this slip on the very last line...)

The preprocessor statements are basically pre run/compile replacements so `{&v}` in the part `{&v} t AS DE.` is replaced with `DEF VAR` rewriting the entire line to

```
DEF VAR t AS DE.

```
> 1 votes

# Answer
# SmileBASIC, 70 bytes

```
G=99@L
A=A+1745E-6GCLS
GPSET G+COS(A)*G,G+G*SIN(A),#PURPLE
WAIT
GOTO@L

```

Luckily `#PURPLE` is exactly `FF800080`
`1745E-6` is an approximation of 2pi/(60\*60)
> 1 votes

# Answer
# LOGO, 58 bytes

A language of turtle graphics.

```
settimer 1 50[setpixel 7 arc2 .3 99 setpixel "purple]ht pu

```

Unfortunately, I can't find any webpage (LOGO interpreter) support `settimer`, and this one does not support turtle-graphics. However you can download UCBLogo or FMSLogo and test.

Alternatively, this version is compatible with JSLogo (which can be try online):

```
setpc "purple
forever[pe setpensize 9 bk 99 rt 1 fd 99 ppt setpensize 1 fd 0 wait 10]

```

Because the pixel almost can't be seen, you can use this version instead:

```
setpc "purple
forever[pe setpensize 9 bk 99 rt 1 fd 99 ppt setpensize 5 fd 0 wait 1]

```

Which increases the pixel size and make it moves 10x faster.

---

Explanation:

```
settimer 1 50[   For each 50 millisecond, do:
setpixel 7       Set the color under the turtle to white (color 7). Alternatively: "white (6 bytes) or [255 255 255] (too many bytes)
arc2 .3 99       Rotate 0.3 degrees around a circle with radius 99
setpixel "purple Set the pixel under the turtle to purple (800080).
                 Color magenta (FF00FF, if allowed) would takes much less bytes (just 1 bytes: "5")
]                End instruction-list.
ht               Hide the turtle. Avoid drawing the turtle on the screen together with the pixel.
pu               Pen-up. Avoid the turtle leave a trail while moving.

```
> 1 votes

# Answer
# Pascal (FPC), 216 bytes

```
Uses Graph,Crt;Var
a:Real;b,c:integer;Begin
b:=0;
InitGraph(b,c,'');SetRGBPalette(1,$80,0,$80);repeat
a:=a+Pi/500;b:=Trunc(60+50*sin(a));c:=Trunc(60+50*cos(a));PutPixel(b,c,1);Delay(60);PutPixel(b,c,0);until 1<0
End.

```

Ungolfed code and explanation here on TIO. Can't run on TIO, however.
> 1 votes

# Answer
## Ruby+RMagick+FFmpeg, 203 bytes

```
include Magick
a=ImageList.new
600.times{|i|Draw.new.fill('purple').translate(80,80).rotate(i*0.6).point(60,0).draw(a.new_image(160,160))}
a.delay=10
a.write'c.gif'
system'ffplay -loop 0 c.gif'

```

Run with `ruby -rrmagick circle.rb`; I count 193 bytes in the file, plus 10 bytes to edit `ruby circle.rb` into `ruby -rrmagick circle.rb`. This is longer than Ruby with Shoes (134 bytes).

Before running this program, you must install ImageMagick, ffmpeg, ruby, then run `gem install rmagick`. Ubuntu user would need some dev packages. The program takes a few minutes to save the c.gif file, then displays it in ffplay's window. It leaves c.gif in the current directory.

## Commented version

```
require 'rmagick'
include Magick  # for Magick::ImageList, Magick::Draw

# Draw 600 frames.
a = ImageList.new
600.times {|i|
  Draw.new
    .fill('purple')     # Set fill color to #800080.
    .translate(80, 80)  # Move origin to center of circle.
    .rotate(i * 0.6)    # Rotate axes by 0...360 degrees.
    .point(60, 0)       # Draw pixel in fill color.
    .draw(a.new_image(160, 160))
  # Draw image of 160x160 pixels on the default white background.
}

# Set delay between frames to 10 ticks.
# By default, 100 ticks = 1 second.
# Therefore, 600 frames at 10 ticks = 60 seconds.
a.delay = 10

a.write 'c.gif'
system 'ffplay -loop 0 c.gif'

```

If I use `a.animate`, then RMagick displays the animation in its own window, but the timing is too slow. The circle takes about 66 seconds, not the correct 60 seconds.

To get the correct timing, I must add 36 bytes by deleting `a.animate` and adding code to save a .gif and display it in another program. If I run `firefox c.gif` or `chrome c.gif`, the timing is correct, but the white box of 160x160 pixels appears in the center of a much larger window, so the circle seems too small in the window. I run `ffplay -loop 0 c.gif` to get both the correct timing and the correct window size.

ImageMagick also comes with shell commands, so it might be possible to translate this answer into shell script, but I have not done so.
> 1 votes

# Answer
# Haskell 265 bytes

Runs in a terminal and prints a `@` which changes position.

It takes about 64 seconds to do a full loop but `999999` can be changed to fix this. If someone can be bothered working out the right number then feel free to change it.

```
import Control.Concurrent
f _ _ _ 0=[]
f a 0 x y=(g a x)++f a(-1)x(y-1)
f a b x y="\n"++f a(b-1)x(y-1)
g _ 0="\n"
g 0 x="\27[1;35m@"++g(-1)(x-1)
g a x=' ':g(a-1)(x-1)
main=h 0
h i=threadDelay 999999>>putStrLn(f(round$(sin i)*w+w)(round$(cos i)*w+w)(w*2+1)(w*2+1))>>h(i+0.1)

```
> 0 votes

# Answer
# APL (dzaima/APL), 72 bytes

```
G←P5.G
d←0
P5.draw←{G.bg¯1
d+←○÷1800
G.stroke←'800080'
G.pt 50+38×2 1○d}

```

Try it online!

A port of the Processing solution with some APL tweaks.
> 0 votes

---
Tags: code-golf, graphical-output, animation, trigonometry
---


# Question
Title: Find maximal matching in divisibility relation
You are given a set of positive integers. You must arrange them into pairs such that:

* Each pair contains 2 numbers, one of which is a multiple of another. For example, 8 is a multiple of 4, and 9 is a multiple of 9.
* If the same number occurs many times in the initial set, it can be used that many times in the pairs; a number can even be paired with another occurence of the same number
* The maximum possible number of pairs is obtained.

Output must be the number of pairs. **Shortest code wins.**

**Sample data**

`2,3,4,8,9,18` -\> `3`

`7,14,28,42,56` -\> `2`

`7,1,9,9,4,9,9,1,3,9,8,5` -\> `6`

`8,88,888,8888,88888,888888` -\> `3`

`2,6,7,17,16,35,15,9,83,7` -\> `2`

# Answer
## Haskell, ~~109~~ ~~107~~ ~~76~~ 70 bytes

*Thanks to nimi for saving 33 bytes and teaching me some more Haskell.* :)
*Thanks to xnor for saving another 6 bytes.*

```
import Data.List
f l=maximum$0:[1+f t|a:b:t<-permutations l,a`mod`b<1]

```

Yay, my first Haskell golf. It works the same as all the answers so far (well, not quite: it only counts the length of the longest prefix of valid pairs in each permutation, but that's equivalent and is actually what my original CJam code did).

For extra golfitude it's also extra inefficient by recursively generating all permutations of the suffix each time the first two elements of a permutation are a valid pair.
> 6 votes

# Answer
# Japt `-h`, 11 bytes

**My 1000th Japt solution!** (According to SEDE)
I *had* wanted to do something epic to mark the occasion but I couldn't find a suitable challenge and, also, realised I don't have the time or brainspace these days for epic. So, instead I shall "celebrate" with a victory over Jelly :) And a bag of cans, of course!

```
á ®ò xr'vÃñ

```

Try it

```
á ®ò xr'vÃñ     :Implicit input of array
á               :Permutations
  ®             :Map
   ò            :  Partitions of length 2
     x          :  Reduce by addition after
      r         :    Reducing each by
       'v       :    Testing divisibility
         Ã      :End map
          ñ     :Sort
                :Implicit output of last element

```

The `'v` trick saves a byte over the more straightforward method of using a function which would be `xÈrvÃ` instead of `xr'v`, although we *could* get that byte back by replacing the `ÃÃ` with a newline.
> 6 votes

# Answer
## CJam, ~~22~~ 18 bytes

```
q~e!{2/::%0e=}%:e>

```

Try it online.

Expects input in the form of a CJam-style list.

This is a *bit* inefficient for larger lists (and Java will probably run out of memory unless you give it more).

### Explanation

```
q~     e# Read and evaluate input.
e!     e# Get all distinct permutations.
{      e# Map this block onto each permutation...
  2/   e#   Split the list into (consecutive) pairs. There may be a single element at the
       e#   end, which doesn't participate in any pair.
  ::%  e#   Fold modulo onto each chunk. If it's a pair, this computes the modulo, which
       e#   yields 0 if the first element is a multiple of the second. If the list has only
       e#   one element, it will simply return that element, which we know is positive.
  0e=  e#   Count the number of zeroes (valid pairs).
}%
:e>    e# Find the maximum of the list by folding max() onto it.

```
> 3 votes

# Answer
# Pyth, 13 bytes

```
eSm/%Mcd2Z.pQ

```

The time and storage complexity is really terrible. The first thing I do is to create a list with all permutations of the originally list. This takes `n*n!` storage. Input lists with length 9 already take quite a long time.

Try it online: Demonstration or Test Suite

### Explanation:

```
eSm/%Mcd2Z.pQ
            Q   read the list of integer
          .p    create the list of all permutations
  m             map each permutation d to:
      cd2          split d into lists of length 2
    %M             apply modulo to each of this lists
   /     Z         count the zeros (=number of pairs with the first
                   item divisible by the second)
 S              sort these values
e               and print the last one (=maximum)

```
> 3 votes

# Answer
## Mathematica, ~~95~~ ~~93~~ ~~87~~ ~~83~~ ~~79~~ ~~60~~ 58 bytes

```
Max[Count[#~Partition~2,{a_,b_}/;a∣b]&/@Permutations@#]&

```

Takes a few seconds for the larger examples.
> 2 votes

# Answer
# Jelly, 12 bytes

```
Œ!s2ḍ/€ċ1Ʋ€Ṁ

```

Try it online!

Uses the same method as Jakube's Pyth answer and Martin's CJam answer, which seems to be the best method

## How it works

```
Œ!s2ḍ/€ċ1Ʋ€Ṁ - Main link. Takes a list l on the left
Œ!           - All permutations of l
         Ʋ€  - Do the following over each permutation:
  s2         -   Split into pairs
      €      -   Over each pair:
     /       -     Reduce the pair by:
    ḍ        -       x divides y?
       ċ1    -   Count the 1s
           Ṁ - Take the maximum

```
> 2 votes

# Answer
# Scala, ~~71~~ 67 bytes

```
_.permutations.map(_.grouped(2)count(x=>x.size>1&&x(0)%x(1)<1)).max

```

Try it online!

* -4 thanks to user!
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
œεüÖιO}à

```

Try it online!

**Commented:**

```
œ          # get all permutations
 ε    }    # map over the permutations ... ex: [8, 4, 9, 9]
  üÖ       #   pairwise divisibility           [1, 0, 1]
           #     [8%4==0, 4%9==0, 9%9==0]
    ι      #   de-interleave                   [[1, 1], [0]]
           #     split into two alternating lists
     O     #   sum both lists                  [2, 0]
       à   # get the maximum

```
> 1 votes

# Answer
# Husk, 10 bytes

```
▲mȯ#IĊ2Ẋ¦P

```

Try it online!

**How?**

```
▲mȯ#IĊ2Ẋ¦P
▲               # maximum of
 m              # map function over list:
  ȯ             # function: 3 functions combined
   #I           #   number of truthy elements of
     Ċ2         #   every second element of
       Ẋ        #   result of applying to every pair
        ¦       #   a divides b?
         P      # list: all permutations of input

```
> 1 votes

# Answer
## Matlab (120+114=234)

```
  function w=t(y,z),w=0;for i=1:size(z,1),w=max(w,1+t([y,z(i,:)],feval(@(d)z(d(:,1)&d(:,2),:),~ismember(z,z(i,:)))));end

```

**main:**

```
  a=input('');h=bsxfun(@mod,a,a');v=[];for i=1:size(h,1) b=find(~h(i,:));v=[v;[(2:nnz(b))*0+i;b(b~=i)]'];end;t([],v)

```

---

* the topper function is called by the main part.
* the input is in the form `[. . .]`
> 0 votes

# Answer
## Matlab(365)

```
  j=@(e,x)['b(:,' num2str(e(x)) ')'];r=@(e,y)arrayfun(@(t)['((mod(' j(e,1) ',' j(e,t) ')==0|mod(' j(e,t) ',' j(e,1) ')==0)&',(y<4)*49,[cell2mat(strcat(r(e(setdiff(2:y,t)),y-2),'|')) '0'],')'],2:y,'UniformOutput',0);a=input('');i=nnz(a);i=i-mod(i,2);q=0;while(~q)b=nchoosek(a,i);q=[cell2mat(strcat((r(1:i,i)),'|')) '0'];q=nnz(b(eval(q(q~=0)),:));i=i-2;end;fix((i+2)/2)

```

---

* This apparently is longer, but oneliner and executive, and I managed to escape `perms` function because it takes forever.
* This function takes many reprises to run quiet well due to anonymous functions, I m open to suggestions here :)
> 0 votes

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


title: Trithagorean Triples

text:
# Question
Title: Trithagorean Triples
A Pythagorean Triple is a positive integer solution to the equation:

A Trithagorean triple is a positive integer solution to the equation:

Where Δn finds the nth triangular number. All Trithagorean triples are also solutions to the equation:

## Task

Given a positive integer `c`, output all the pairs of positive integers `a,b` such that the sum of the `a`th and `b`th triangular numbers is the `c`th triangular number. You may output the pairs in whatever way is most convenient. You should only output each pair once.

This is

## Test Cases

```
2: []
3: [(2, 2)]
21: [(17, 12), (20, 6)]
23: [(18, 14), (20, 11), (21, 9)]
78: [(56, 54), (62, 47), (69, 36), (75, 21), (77, 12)]
153: [(111, 105), (122, 92), (132, 77), (141, 59), (143, 54), (147, 42), (152, 17)]
496: [(377, 322), (397, 297), (405, 286), (427, 252), (458, 190), (469, 161), (472, 152), (476, 139), (484, 108), (493, 54), (495, 31)]
1081: [(783, 745), (814, 711), (836, 685), (865, 648), (931, 549), (954, 508), (979, 458), (989, 436), (998, 415), (1025, 343), (1026, 340), (1053, 244), (1066, 179), (1078, 80), (1080, 46)]
1978: [(1404, 1393), (1462, 1332), (1540, 1241), (1582, 1187), (1651, 1089), (1738, 944), (1745, 931), (1792, 837), (1826, 760), (1862, 667), (1890, 583), (1899, 553), (1917, 487), (1936, 405), (1943, 370), (1957, 287), (1969, 188)]
2628: [(1880, 1836), (1991, 1715), (2033, 1665), (2046, 1649), (2058, 1634), (2102, 1577), (2145, 1518), (2204, 1431), (2300, 1271), (2319, 1236), (2349, 1178), (2352, 1172), (2397, 1077), (2418, 1029), (2426, 1010), (2523, 735), (2547, 647), (2552, 627), (2564, 576), (2585, 473), (2597, 402), (2622, 177), (2627, 72)]
9271: [(6631, 6479), (6713, 6394), (6939, 6148), (7003, 6075), (7137, 5917), (7380, 5611), (7417, 5562), (7612, 5292), (7667, 5212), (7912, 4832), (7987, 4707), (8018, 4654), (8180, 4363), (8207, 4312), (8374, 3978), (8383, 3959), (8424, 3871), (8558, 3565), (8613, 3430), (8656, 3320), (8770, 3006), (8801, 2914), (8900, 2596), (8917, 2537), (9016, 2159), (9062, 1957), (9082, 1862), (9153, 1474), (9162, 1417), (9207, 1087), (9214, 1026), (9229, 881), (9260, 451), (9261, 430), (9265, 333)]

```

# Answer
> 8 votes
# Mathematica, ~~53~~ ~~49~~ 48 bytes

```
Solve[{x.(x+1)==#^2+#,a>=b>0},x={a,b},Integers]&

```

Example:

```
In[1]:= Solve[{x.(x+1)==#^2+#,a>=b>0},x={a,b},Integers]&[21]

Out[1]= {{a -> 17, b -> 12}, {a -> 20, b -> 6}}

```

# Answer
> 6 votes
# MATL, ~~17~~ 13 bytes

```
:Ys&+G:s=R&fh

```

Each pair is output with the smaller number first.

Try it online!

### Explanation

Consider input `3`.

```
:      % Implicitly input n. Push [1 2 ... n]
       % STACK: [1 2 3]
Ys     % Comulative sum
       % STACK: [1 3 6]
&+     % All pairwise sums
       % STACK: [2 4 7; 4 6 9; 7 9 12]
G:s    % Push 1+2+...+n
       % STACK: [2 4 7; 4 6 9; 7 9 12], 6
=      % Is equal?
       % STACK: [0 0 0; 0 1 0; 0 0 0]
R      % Upper triangular part of matrix. This removes duplicate pairs
       % STACK: [0 0 0; 0 1 0; 0 0 0]
&f     % Push row and column indices (1-based) of non-zero entries
       % STACK: 2, 2
h      % Concatenate horizontally. Implicitly display
       % STACK: [2, 2]

```

# Answer
> 6 votes
# Jelly, 12 bytes

```
j‘c2ḅ-
ŒċçÐḟ

```

Try it online!

### How it works

```
ŒċçÐḟ   Main link. Argument: c

Œċ      Yield all 2-combinations w/repetition of elements of [1, ..., c].
  çÐḟ   Filterfalse; keep only 2-combinations for which the helper link returns 0.

j‘c2ḅ-  Helper link. Left argument: [a, b]. Right argument: c

j       Join [a, b] with separator c, yielding [a, c, b].
 ‘      Increment; yield [a+1, c+1, b+1].
  c2    Combination count; compute [C(a+1,c), C(c+1,c), C(b+1,c)], yielding
        [½a(a+1), ½c(c+1), ½b(b+1)].
    ḅ-  Convert from base -1 to integer, yielding
        ½(-1)²a(a+1) + ½(-1)¹c(c+1) + ½(-1)⁰b(b+1) = ½(a(a+1) - c(c+1) + b(b+1)),
        which is 0 if and only if a(a+1) + b(b+1) = c(c+1).

```

# Answer
> 4 votes
# Jelly, ~~16~~ 14 bytes

```
RS
ŒċÇ€S$⁼¥ÐfÇ

```

Try it online!

This is too long for sure...

Explanation:

```
ŒċÇ€S$⁼¥ÐfÇ (main) Arguments: z
Œċ             Return [[1, 1], [1, 2], ..., [1, z], [2, 2], ..., [z, z]]
          Ç    Return T(z)
  Ç€S$⁼¥Ðf     Only keep the pairs such as ΣT(a, b)=T(z)

RS (helper 1) Arguments: z
R  [1, 2, ..., z]
 S Take the sum

```

# Answer
> 4 votes
## Python 2, 69 bytes

Try it online

```
lambda c:[(a,b)for a in range(c)for b in range(a+1)if~a*a==c*~c-~b*b]

```

-9 bytes, thanks to @WheatWizard

# Answer
> 4 votes
# AWK, 72 bytes

```
{for(n=$1;++i<=n;)for(j=i;j<=n;++j)if(i^2+j^2+i+j==n^2+n)$0=$0" "i":"j}1

```

Try it online!

Output is `c a1:b1 a2:b2 ...`. The TIO link has 4 extra bytes `i=0;` to allow for multiline input.

This isn't efficient at all, but it works. :)

# Answer
> 3 votes
# PHP, 94 Bytes

```
for($a=$c=$argn;$a--;)for($b=$a;$b;$b--)$a**2+$a+$b**2+$b!=$c**2+$c?:$e[]=[$a,$b];print_r($e);

```

Try it online!

# Answer
> 3 votes
## Haskell, 50 bytes

```
f c=[(a,b)|a<-[1..c],b<-[1..a],a^2+a+b^2+b==c^2+c]

```

Usage example: `f 21` -\> `[(17,12),(20,6)]`. Try it online!

Uses the 2nd equation.

# Answer
> 2 votes
# Axiom, ~~281~~ ~~204~~ ~~196~~ 191 bytes

```
q(b,m)==(r:=1+4*m;v:=4.*b*(b+1);r<v=>0;(sqrt(r-v)-1)/2);g(c:NNI):Any==(r:List List INT:=[];i:=0;repeat(i:=i+1;i>=c=>break;w:=q(i,c^2+c);w>=i and fractionPart(w)=0=>(r:=cons([w::INT,i],r)));r)

```

test and ungolf

```
-- if m=c^2+c than a^2+a+b^2+b-m=0 has the solutions [a,b] with a>0,b>0
-- if it is used a=(-1+sqrt(1+4*m-4*(b)*(b-1)))/2 because the other return a<0
-- o(b,m) return that solution if 1+4*m-4*(b)*(b-1)>0 [so exist in R sqrt] else return 0
o(b,m)==(r:=1+4*m;v:=4.*b*(b+1);r<v=>0;(sqrt(r-v)-1)/2)

--it Gets one not negative integer c; return one list of list(ordered) of 2 integers
--[a,b] with  a^2+a+b^2+b=c^2+c
gg(c:NNI):List List INT==
   r:List List INT:=[]  -- initialize the type make program more fast at last it seems 10x
   i:=0
   repeat
      i:=i+1
      i>=c=>break
      w:=o(i,c^2+c)
      w>=i and fractionPart(w)=0=>(r:=cons([w::INT,i],r))
   r

(6) -> [[i,g(i)]  for i in [2,3,21,23,78,153,496,1081,1978,2628,9271]]
   (6)
   [[2,[]], [3,[[2,2]]], [21,[[17,12],[20,6]]], [23,[[18,14],[20,11],[21,9]]],
    [78,[[56,54],[62,47],[69,36],[75,21],[77,12]]],
    [153,[[111,105],[122,92],[132,77],[141,59],[143,54],[147,42],[152,17]]],

     [496,
       [[377,322], [397,297], [405,286], [427,252], [458,190], [469,161],
        [472,152], [476,139], [484,108], [493,54], [495,31]]
       ]
     ,

     [1081,
       [[783,745], [814,711], [836,685], [865,648], [931,549], [954,508],
        [979,458], [989,436], [998,415], [1025,343], [1026,340], [1053,244],
        [1066,179], [1078,80], [1080,46]]
       ]
     ,

     [1978,
       [[1404,1393], [1462,1332], [1540,1241], [1582,1187], [1651,1089],
        [1738,944], [1745,931], [1792,837], [1826,760], [1862,667], [1890,583],
        [1899,553], [1917,487], [1936,405], [1943,370], [1957,287], [1969,188]]
       ]
     ,

     [2628,
       [[1880,1836], [1991,1715], [2033,1665], [2046,1649], [2058,1634],
        [2102,1577], [2145,1518], [2204,1431], [2300,1271], [2319,1236],
        [2349,1178], [2352,1172], [2397,1077], [2418,1029], [2426,1010],
        [2523,735], [2547,647], [2552,627], [2564,576], [2585,473], [2597,402],
        [2622,177], [2627,72]]
       ]
     ,

     [9271,
       [[6631,6479], [6713,6394], [6939,6148], [7003,6075], [7137,5917],
        [7380,5611], [7417,5562], [7612,5292], [7667,5212], [7912,4832],
        [7987,4707], [8018,4654], [8180,4363], [8207,4312], [8374,3978],
        [8383,3959], [8424,3871], [8558,3565], [8613,3430], [8656,3320],
        [8770,3006], [8801,2914], [8900,2596], [8917,2537], [9016,2159],
        [9062,1957], [9082,1862], [9153,1474], [9162,1417], [9207,1087],
        [9214,1026], [9229,881], [9260,451], [9261,430], [9265,333]]
       ]
     ]
                                                      Type: List List Any

```

# Answer
> 2 votes
# , 35 bytes

```
1+[:~.,~/:~@#:[:I.@,@({:=+/~)2!2+i.

```

Try it online!

# Answer
> 1 votes
# CJam, ~~30~~ 28 bytes

```
{_,2m*:$_&f+{{_)*}%~+=},1f>}

```

Anonymous block expecting its argument on the stack and leaving the result on the stack.

Try it online!

### Explanation

I will refer to the input as `n`

```
_,     e# Copy n, and get the range from 0 to n-1.
2m*    e# Get the 2nd Cartesian power of this range.
:$_&   e# Sort the pairs and deduplicate, to get all unique pairs.
f+     e# Prepend n to each pair.
{      e# Filter these triplets; keep only those that give a truthy result:
 {     e#  Map this block over the triplet:
  _)*  e#   Multiply x by x+1. (i.e. x^2 + x)
 }%    e#  (end map)
 ~+=   e#  Check if the sum of the second and third is equal to the first.
},     e# (end filter)
1f>    e# Remove the first element from all remaining triplets.

```

# Answer
> 1 votes
# Pyth - ~~23~~ 21 bytes

```
L*bhbfqyQ+yhTyeT.CUQ2

```

Try it

```
L*bhbfqyQ+yhTyeT.CUQ2
L*bhb                     Define y(b)=b*(b+1)
                .CUQ2     All pairs of numbers less than the input
     fqyQ+yhTyeT          Filter based on whether y(input) == y(1st elem. of pair) + y(2nd elem. of pair)

```

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

```
c=>[...Array(c*c)].map((_,x)=>[x%c,x/c|0]).filter(([a,b])=>a>=b&a++*a+b++*b==c*c+c)

```

### Test cases

Omitting here the largest inputs that take too much time for the snippet.

```
let f =

c=>[...Array(c*c)].map((_,x)=>[x%c,x/c|0]).filter(([a,b])=>a>=b&a++*a+b++*b==c*c+c)

console.log(JSON.stringify(f(2)))
console.log(JSON.stringify(f(3)))
console.log(JSON.stringify(f(21)))
console.log(JSON.stringify(f(23)))
console.log(JSON.stringify(f(78)))
console.log(JSON.stringify(f(153)))
console.log(JSON.stringify(f(496)))
```

# Answer
> 1 votes
# Husk, ~~12~~ 11 bytes

```
fo=Σ¹ṁΣüOπ2

```

Try it online!

`Σ` has a mode where it returns the nth triangular number, which is very useful here.

-1 byte from Dominic van Essen.

## Explanation

```
fo=Σ¹ṁΣüOπ2
         π2  cartesian power 2 for range 1..n(all possible pairs)
       üO    uniquify, ignoring ordering
fo           filter by the following 2 functions:
     ṁΣ      triangular numbers of the pair summed
  =          equals
   Σ¹        nth triangular number?

```

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


# Question
Title: Remove letters while keeping strings unique
Inspired by this wonderful (based on the number of views and votes) challenge, which, in my humble opinion, has way too few answers.

Given (by any means) a list of strings, return (by any means) a set of letters that, when removed from the given strings, leaves the total length of (what remains of) the strings as small as possible, while keeping each string unique and at least one character long.

**Examples:**

Given "Day" and "day"; return "ay", because the given strings will be "D" and "d" when the characters "ay" are removed.

Given "Hello World!", "Hello world.", and "Hello world"; return "Helo Wrd" gives because the strings will be "!", "w.", and "w" when the characters "Helo Wrd" (with a space) are removed.

Given "century", "decade", "year", "month", "week", "day", "hour", "minute", and "second"; return "centurdowi" because the given words will be "y", "a", "ya", "mh", "k", "ay", "h", "m", "s" when the characters "centurdowi" are removed.

The order and format of the returned set is not important.

# Answer
## Haskell, ~~138~~ 130 bytes

```
import Data.List
c=concat
f i=snd$minimum[(length$c q,s)|s<-subsequences$nub$c i,q<-[map(filter(`notElem`s))i],nub q==q,all(>"")q]

```

Usage example: `f ["century", "decade", "year", "month", "week", "day", "hour", "minute", "second"]` -\> `"centurdoki"`.

This is a brute force approach.

```
     s<-subsequences$nub$c i  -- concatenate input i to a single string, remove
                              -- duplicates and make a list of all subsequences
       q<-[map(filter(...))i] -- remove chars appearing in subsequence s from all
                              -- input words, call result q
          nub q==q            -- keep those s where q has no duplicates (i.e. each
                              -- resulting string is unique) and
            all(>"")q         -- contains no empty strings
  (length$c q,s)              -- make pairs from all kept s, where the first element
                              -- is the combines length of all strings in q,
                              -- second element is s itself
snd$minimum                   -- find minimum of those pairs and discard length

```

Edit: @Seeq helped me saving 8 bytes. Thanks!
> 4 votes

# Answer
# JavaScript (V8), 288 bytes

```
s=>(l=[...new Set(s.join``)],g=[],[...Array(2**l[L="length"])].map((x,i)=>l.filter((c,j)=>(i&2**j))).filter(x=>new Set(h=s.map(m=>[...m].filter(n=>!x.includes(n)).join``)).size==s[L]&&h.every(n=>n[L])&&g.push(h.reduce((a,b)=>a+b[L],0))).map(x=>[x,g.shift()]).sort((a,b)=>a[1]-b[1])[0][0])

```

Try it online!

Explanation:

```
s=>                                     // Arrow function with argument s
(l=[...new Set(s.join``)],              // Create a set l containing every character in s
                                          // Sets automatically remove duplicates
                                          // This converts the set back to an array, since arrays are easier to work with
g=[],                                   // Create an empty array g
[...Array(2**l[L="length"])]            // Create an array with length 2 ** number_of_inputs
.map((x,i)=>l.filter((c,j)=>(i&2**j)))  // Populate the array with each combination of characters in l
.filter(x=>new Set(h=s.map(m=>          // Filter the array (with each combination being x)
  [...m].filter(n=>!x.includes(n))        // For each inputted string, after removing the characters in x
  .join``)).size==s[L]&&                  // Check if the number of unique strings is equal to the number of inputs
  h.every(n=>n[L])&&                      // Ensure every string is at least one character
  g.push(h.reduce((a,b)=>a+b[L],0)))      // Push the total length to g
.map(x=>[x,g.shift()])                  // For each item x in the array, put it in an array with its corresponding item in g
.sort((a,b)=>a[1]-b[1])[0][0])          // Sort the array to find the shortest valid result, and output it

```
> 3 votes

# Answer
# Pyth, 34

Takes input in the format `["century", "decade", "year", "month", "week", "day", "hour", "minute", "second"]`. Golfing tips are appreciated, as always.

```
hh.mlsebfqlQl{eTf!}keTm,dm-kdQy{sQ

```
> 2 votes

# Answer
# Pyth, 24 bytes

```
hols-RNQf<}kJ-RTQ{IJy{sQ

```

Try it online. Test suite.

Note that the last test case will take a little while to run.

Takes input in array form, like `["Day", "day"]`.

Another interesting one I found and isaacg improved (also 24 bytes):

```
-J{sQhlDsM.A#f{ITm-RdQyJ

```
> 2 votes

---
Tags: code-golf, string, set-partitions, optimized-output
---


title: Index of a multidimensional array

text:
# Question
Title: Index of a multidimensional array
Lower level languages, such as C and C++ actually have no concept of multidimensional arrays. (Other than vectors and dynamic arrays) When you create a multidimensional array with

```
int foo[5][10];

```

This is actually just syntactic sugar. What C really does is create a single contiguous array of *5 * 10* elements. This

```
foo[4][2]

```

is also syntactic sugar. This really refers to the element at

```
4 * 10 + 2

```

or, the 42nd element. In general, the index of element `[a][b]` in array `foo[x][y]` is at

```
a * y + b

```

The same concept applies to 3d arrays. If we have `foo[x][y][z]` and we access element `[a][b][c]` we are really accessing element:

```
a * y * z + b * z + c

```

This concept applies to *n*-dimensional arrays. If we have an array with dimensions `D1, D2, D3 ... Dn` and we access element `S1, S2, S3 ... Sn` the formula is

```
(S1 * D2 * D3 ... * Dn) + (S2 * D3 * D4 ... * Dn) + (S3 * D4 ... * Dn) ... + (Sn-1 * Dn) + Sn

```

# The challenge

You must write a program or function that calculates the index of a multidimensional array according to the formula above. Input will be two arrays. The first array is the dimensions, and the second array is the indices. The length of these two arrays will always be equal and at least 1.

You can safely assume that every number in the arrays will be an non-negative integer. You can also assume that you will not get a `0` in the dimension array, although a `0` *might* be in the indices. You can also assume that indices will not be larger than the dimensions.

# Test IO

```
Dimensions: [5, 10]
Indices: [4, 2]
Output: 42

Dimensions: [10, 10, 4, 62, 7]
Indices: [1, 2, 3, 4, 5]
Output: 22167

Dimensions: [5, 1, 10]
Indices: [3, 0, 7]
Output: 37

Dimensions: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
Indices: [3, 1, 5, 5, 3, 0, 5, 2, 5, 4]
Output: 33570178

```

# Answer
> 62 votes
# APL, 1 byte

Test it on TryAPL.

# Answer
> 12 votes
# J, 2 bytes

```
#.

```

Where there's an APL, there's a J! Kind of. Takes dimensions as left arg and index as right arg. "Indexing a multidimensional array is essentially mixed base conversion."

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

```
(d,a)=>a.reduce((r,i,j)=>r*d[j]+i)

```

Surely `reduce` must be better than `map`.

# Answer
> 7 votes
# Jelly, ~~7~~ 6 bytes

```
Ṇ;żḅ@/

```

Try it online! or verify all test cases.

### How it works

```
Ṇ;żḅ@/  Main link. Arguments: D (list of dimensions), I (list of indices)

Ṇ       Yield 0, the logical NOT of D.
  ż     Zip D with I.
        If D = [10, 10, 4, 62, 7] and I = [1, 2, 3, 4, 5], this yields
        [[10, 1], [10, 2], [4, 3], [62, 4], [7, 5]].
 ;      Concatenate, yielding [0, [10, 1], [10, 2], [4, 3], [62, 4], [7, 5]].
   ḅ@/  Reduce by swapped base conversion to integer.
        [10, 1] in base    0 is    0 × 10 + 1 = 1.
        [10, 2] in base    1 is    1 × 10 + 2 = 12.
        [ 4, 3] in base   12 is   12 ×  4 + 3 = 51.
        [62, 4] in base   51 is   51 × 62 + 4 = 3166.
        [ 7, 5] in base 3166 is 3166 ×  7 + 5 = 22167.

```

# Answer
> 7 votes
# Python, 43 bytes

```
f=lambda x,y:x>[]and y.pop()+x.pop()*f(x,y)

```

Test it on Ideone.

# Answer
> 6 votes
# Pyth, 10 bytes

```
e.b=+*ZNYC

```

Try it online: Demonstration or Test Suite

Using Horner's method to calculate the index.

# Answer
> 5 votes
# MATL, 11 bytes

```
4L)1hPYpP*s

```

This uses 0-based indexing, as in the original challenge.

**Try it online!**

### Explanation

The code explicitly does the required multiplications and additions.

```
4L)    % Take first input array implicitly. Remove its first entry
1h     % Append a 1
PYpP   % Cumulative product from right to left
*      % Take second input array implicitly. Multiply the two arrays element-wise
s      % Sum of resulting array. Implicitly display

```

# Answer
> 5 votes
# MATL, 9 bytes

```
PiPZ}N$X]

```

This uses 1-based indexing (now allowed by the challenge), which is the natural choice in MATL.

To compare with the test cases in the challenge, add `1` to each entry in the input index vector, and subtract `1` from the output.

**Try it online!**

### Explanation

The code is based on the builtin `X]` function, which converts multidimensional indices to a single, linear index (like Matlab or Octave's `sub2ind` function).

```
P      % Take dimension vector implicitly. Reverse
iP     % Take vector of indices. Reverse
Z}     % Split vector into its elements
N$X]   % Convert indices to linear index (`sub2ind` function). Implicitly display

```

# Answer
> 5 votes
# Julia, ~~29~~ 27 bytes

```
x%y=prod(x)÷cumprod(x)⋅y

```

Try it online!

# Answer
> 4 votes
# Python, 85 bytes

```
lambda a,b:sum(b[i]*eval('*'.join(str(n)for n in a[i+1:])or'1')for i in range(len(a)))

```

I'll probably get my butt kicked by the better python golfers out there.

# Answer
> 4 votes
# Python 3.5, 69

```
lambda d,i:sum(eval("*".join(map(str,[z,*d])))for z in i if d.pop(0))

```

Test here

# Answer
> 4 votes
## Haskell, 34 bytes

```
a#b=sum$zipWith(*)(0:b)$scanr(*)1a

```

Usage example: `[10,10,4,62,7] # [1,2,3,4,5]` -\> `22167`.

How it works:

```
      scanr(*)1a  -- build partial products of the first parameter from the right,
                  -- starting with 1, e.g. [173600,17360,1736,434,7,1]
    (0:b)         -- prepend 0 to second parameter, e.g. [0,1,2,3,4,5]
  zipWith(*)      -- multiply both lists elementwise, e.g. [0,17360,3472,1302,28,5]
sum               -- calculate sum

```

# Answer
> 4 votes
# C++, 66 bytes

A quick macro:

```
#include<stdio.h>
#define F(d,i) int x d;printf("%d",&x i-(int*)x)

```

Use like:

```
int main(){
    F([5][1][10], [3][0][7]);
}

```

This may be a bit of an abuse of the rules. Creates an array with the given size, than checks to see how far the given indexes offset the pointer. Outputs to STDOUT.

This feels so dirty... But I just love the fact that this is valid.

# Answer
> 3 votes
# Octave, ~~58~~ 54 bytes

*Thanks to @AlexA. for his suggestion, which removed 4 bytes*

```
@(d,i)reshape(1:prod(d),flip(d))(num2cell(flip(i)){:})

```

Input and output are 1-based. To compare with the test cases, add `1` ot each entry in the input and subtract `1` from the output.

This is an anonymous function. To call it, assign it to a variable.

**Try it here**.

### Explanation

This works by actually building the multidimensional array (`reshape(...)`), filled with values `1`, `2`, ... in linear order (`1:prod(d)`), and then indexing with the multidimensional index to get the corrresponding value.

The indexing is done by converting the input multidimensional index `i` into a cell array (`num2cell(...)`) and then to a comma-separated list (`{:}`).

The two `flip` operations are needed to adapt the order of dimensions from C to Octave.

# Answer
> 3 votes
## Mathematica, 27 bytes

```
#~FromDigits~MixedRadix@#2&

```

An unnamed function which takes the list of indices as the first argument and the list of dimensions second. Based on the same observation as Dennis's APL answer that computing the index is really just a mixed-base conversion.

# Answer
> 3 votes
# CJam, 7 bytes

```
0q~z+:b

```

Try it online!

### How it works

```
0        e# Push 0 on the stack.
 q       e# Read and push all input, e.g., "[[10 10 4 62 7] [1 2 3 4 5]]".
  ~      e# Eval, pushing [[10 10 4 62 7] [1 2 3 4 5]].
   z     e# Zip, pushing [[10 1] [10 2] [4 3] [62 4] [7 5]].
    +    e# Concatenate, pushing [0 [10 1] [10 2] [4 3] [62 4] [7 5]]
     :b  e# Reduce by base conversion.
         e# [10 1] in base    0 is    0 * 10 + 1 = 1.
         e# [10 2] in base    1 is    1 * 10 + 2 = 12.
         e# [ 4 3] in base   12 is   12 *  4 + 3 = 51.
         e# [62 4] in base   51 is   51 * 62 + 4 = 3166.
         e# [ 7 5] in base 3166 is 3166 *  7 + 5 = 22167.

```

# Answer
> 2 votes
# Haskell, 47 bytes

Two equal length solutions:

```
s(a:b)(x:y)=a*product y:s b y
s _ _=[]
(sum.).s

```

Called like: `((sum.).s)[4,2][5,10]`.

Here's an infix version:

```
(a:b)&(x:y)=a*product y:b&y
_ & _=[]
(sum.).(&)

```

# Answer
> 2 votes
# Octave, ~~47~~/~~43~~/31 bytes

`@(d,i)sub2ind(flip(d),num2cell(flip(i+1)){:})-1`

Test it here.

Having said that, as it was asked in a comment, 1-based indexing was said to be OK when this is natural to the language being used. In this case, we can save 4 bytes:

`@(d,i)sub2ind(flip(d),num2cell(flip(i)){:})`

In analogy, I argue that if the objective of the code is to linearly index an array **within that language**, the whole flipping around and accounting for MATLAB/Octave's column major order should not be necessary, either. In that case, my solution becomes

`@(d,i)sub2ind(d,num2cell(i){:})`

Test that one here.

# Answer
> 1 votes
# Mathematica, 47 bytes

```
Fold[Last@#2#+First@#2&,First@#,Rest/@{##}]&

```

(Unicode is U+F3C7, or `\[Transpose]`.) For this, I rewrote the expression as *D**n*(*D**n*-1( ⋯ (*D*3(*D*2*S*1 \+ *S*2) + *S*3) ⋯ ) + *S**n*-1) + *S**n*. Just `Fold`s the function over both lists.

# Answer
> 1 votes
## Actually, 13 bytes

```
;pX╗lr`╜tπ`M*

```

Try it online!

This program takes the list of indices as the first input and the list of dimensions as the second input.

Explanation:

```
;pX╗lr`╜tπ`M*
;pX╗            push dims[1:] to reg0
    lr`   `M    map: for n in range(len(dims)):
       ╜tπ        push product of last n values in reg0
            *   dot product of indices and map result

```

# Answer
> 1 votes
## Racket 76 bytes

```
(λ(l i(s 0))(if(null? i)s(f(cdr l)(cdr i)(+ s(*(car i)(apply *(cdr l)))))))

```

Ungolfed:

```
(define f
  (λ (ll il (sum 0))
    (if (null? il)
        sum
        (f (rest ll)
           (rest il)
           (+ sum
              (* (first il)
                 (apply * (rest ll))))))))

```

Testing:

```
(f '(5 10) '(4 2))
(f '(10 10 4 62 7) '(1 2 3 4 5))
(f '(5 1 10) '(3 0 7))

```

Output:

```
42
22167
37

```

# Answer
> 1 votes
## Javascript, 119 79 bytes

```
x=(d,i)=>{a=0;for(m in d){m*=1;a+=i[m];if(m!=i.length-1){a*=d[m+1];}}return a;}

```

Try it online!

# Answer
> 0 votes
# C#, 73 bytes

```
d=>i=>{int n=d.Length,x=0,y=1;for(;n>0;){x+=y*i[--n];y*=d[n];}return x;};

```

Full program with test cases:

```
using System;

namespace IndexOfAMultidimensionalArray
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int[],Func<int[],int>>f= d=>i=>{int n=d.Length,x=0,y=1;for(;n>0;){x+=y*i[--n];y*=d[n];}return x;};

            int[] dimensions, indices;
            dimensions =new int[]{5, 10};
            indices=new int[]{4,2};
            Console.WriteLine(f(dimensions)(indices));      //42

            dimensions=new int[]{10, 10, 4, 62, 7};
            indices=new int[]{1, 2, 3, 4, 5};
            Console.WriteLine(f(dimensions)(indices));      //22167

            dimensions=new int[]{5, 1, 10};
            indices=new int[]{3, 0, 7};
            Console.WriteLine(f(dimensions)(indices));      //37

            dimensions=new int[]{6, 6, 6, 6, 6, 6, 6, 6, 6, 6};
            indices=new int[]{3, 1, 5, 5, 3, 0, 5, 2, 5, 4};
            Console.WriteLine(f(dimensions)(indices));      //33570178
        }
    }
}

```

# Answer
> 0 votes
# Perl 6, 39 bytes

```
->\d,\i{sum i.map:{[×] $_,|d[++$ ..*]}}

```

A rather naive golf here, just squished a anonymous sub.

Perl 6 has an anonymous state variable `$` which is useful for creating a counter in a loop (eg, using post-increment `$++` or pre-increment `++$`). I pre-increment this state variable to increment the starting index of the dimension array slice inside a map.

Here's a ungolfed function that creates the sub-lists

```
sub md-index(@dim, @idx) {
    @idx.map(-> $i { $i, |@dim[++$ .. *] })
}
say md-index([10, 10, 4, 62, 7], [1, 2, 3, 4, 5]);
# OUTPUT: ((1 10 4 62 7) (2 4 62 7) (3 62 7) (4 7) (5))

```

Then it's just a matter of reducing the sub-lists with the multiplication (`×`) operator, and `sum`ing the results.

```
sub md-index(@dim, @idx) {
    @idx.map(-> $i { [×] $i, |@dim[++$ .. *] }).sum
}
say md-index([10, 10, 4, 62, 7], [1, 2, 3, 4, 5]);
# OUTPUT: 22167

```

# Answer
> 0 votes
# Perl, 71 bytes

```
sub{$s+=$_[1][-$_]*($p*=$_[0][1-$_])for($p=$_[0][$s=0]=1)..@{$_[0]};$s}

```

Ungolfed:

```
sub {
    my $s = 0;
    my $p = 1;

    $_[0]->[0] = 1;
    for (1 .. @{$_[1]}) {
        $p *= $_[0]->[1 - $_];
        $s += $_[1]->[-$_] * $p;
    }

    return $s;
}

```

# Answer
> 0 votes
# C++17, ~~133~~ 115 bytes

-18 bytes for using `auto...`

```
template<int d,int ...D>struct M{int f(int s){return s;}int f(int s,auto...S){return(s*...*D)+M<D...>().f(S...);}};

```

Ungolfed:

```
template <int d,int ...D> //extract first dimension
struct M{
 int f(int s){return s;} //base case for Sn
 int f(int s, auto... S) { //extract first index
  return (s*...*D)+M<D...>().f(S...);
  //S_i * D_(i+1) * D(i+2) * ... + recursive without first dimension and first index
 }
};

```

Usage:

```
M<5,10>().f(4,2)
M<10,10,4,62,7>().f(1,2,3,4,5)

```

## Alternative, only functions, 116 bytes

```
#define R return
#define A auto
A f(A d){R[](A s){R s;};}A f(A d,A...D){R[=](A s,A...S){R(s*...*D)+f(D...)(S...);};}

```

Ungolfed:

```
auto f(auto d){
  return [](auto s){
   return s;
  };
}
auto f(auto d, auto...D){
  return [=](auto s, auto...S){
    return (s*...*D)+f(D...)(S...);
  };
}

```

Usage:

```
f(5,10)(4,2)
f(10,10,10)(4,3,2)
f(10,10,4,62,7)(1,2,3,4,5)

```

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