108
\$\begingroup\$

I always used aMandelbrot image as the 'graphical' version of Hello World in any graphical application I got my hands on. Now it's your guys' turn.

  • Language must be capable of graphical output or drawing charts (saving image files disallowed)
  • Render a square image or graph. The size at least 128 and at most 640 across*
  • The fractal coordinates range from approximately -2-2i to 2+2i
  • The pixels outside of the Mandelbrot set should be colored according to the number of iterations before the magnitude exceeds 2 (excluding* black & white)
  • Each iteration count must have a unique color*, and neighboring colors should preferably be easily distinguishable by the eye
  • The other pixels (presumably inside the Mandelbrot set) must be colored either black or white
  • At least 99 iterations
  • ASCII art not allowed

* unless limited by the platform,e.g. graphical calculator

Allowed:
Allowed
Disallowed:
Disallowed
(shrunken images)

Winning conditions:

Shortest version (size in bytes) for each language will get a mention in this post, ordered by size.
No answer will ever be 'accepted' with the button.

Leaderboard:

/* Configuration */var QUESTION_ID = 23423; // Obtain this from the url// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question pagevar ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER = 17419; // This should be the user ID of the challenge author./* App */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.toLowerCase() > b.lang_raw.toLowerCase()) return 1;    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) 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);  }}
body {  text-align: left !important;  display: block !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;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f"><div>  <h2>Shortest Solution by Language</h2>  <table>    <thead>      <tr><td>Language</td><td>User</td><td>Score</td></tr>    </thead>    <tbody>    </tbody>  </table></div><div>  <h2>Leaderboard</h2>  <table>    <thead>      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>    </thead>    <tbody>    </tbody>  </table></div><table>  <tbody>    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>  </tbody></table><table>  <tbody>    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>  </tbody></table>

askedMar 7, 2014 at 21:39
Mark Jeronimus's user avatar
\$\endgroup\$
14
  • 9
    \$\begingroup\$"Easily distinguished by the eye" is hard to make objective. ...Also, apart from your personal association of the two, the Mandelbrot set has nothing to do with Hello World, so it's best to omit that from the title unless you are deliberately trolling the search engines.\$\endgroup\$CommentedMar 7, 2014 at 21:50
  • 4
    \$\begingroup\$I've seen a few people now mentioning that they render the Mandelbrot as a "Hello World". I've done that too, for something like 30 years. The Mandelbrot is the perfect "Hello World" because it shows both that you have pixel access to the display and gives a good feel for compute bound performance on the new platform.\$\endgroup\$CommentedMar 9, 2014 at 2:00
  • 7
    \$\begingroup\$Great idea to ask a question which requires a combination of mathematical and aesthetic sensitivities, then impose all the the design decisions in advance.\$\endgroup\$CommentedMar 10, 2014 at 8:25
  • 3
    \$\begingroup\$Anyone manages to make one in brainfuck WINS, I'd say :D\$\endgroup\$CommentedMar 10, 2014 at 18:45
  • 3
    \$\begingroup\$Not mine and not golfed, butthis code is a marvel of obfuscated python producing a mandelbrot fractal\$\endgroup\$CommentedMay 26, 2017 at 8:37

45 Answers45

113
\$\begingroup\$

Sharp EL-9300 Graphics Calculator, 296 bytes

This was my secondary school graphing calculator in the early '90s. I remember writing a mandelbrot generator for it way back then. And sure enough, its still sitting there in the NV memory:

ClrGDispGRange -2.35,2.35,.5,-1.55,1.55,0.5y=-1.55Label lyx=-2.35Label lxn=1zx=0zy=0Label lntzx=zx²-zy²+xzy=(2*zx*zy)+yzx=tzxIf zx²+zy²>4Goto escn=n+1If n<20Goto lnLabel escIf fpart (n/2)=0Goto nplPlot x,yLabel nplx=x+.05If x<=2.35Goto lxy=y+.05If y<=1.55Goto lyWait

It took about 90 minutes to render. Only 20 iterations, but at this resolution it probably doesn't make much difference.

This is totally ungolfed. I'm sure I could save a bit of space, but I just wanted to share this historical curiosity.

I love that the only control statements available areifs andgotos.

Here's a photo. I don't have any other means to get the graphical output out:enter image description here

answeredMar 8, 2014 at 4:51
Digital Trauma's user avatar
\$\endgroup\$
14
  • 2
    \$\begingroup\$Me too, but my NV memory went blank after years of shelf-time.\$\endgroup\$CommentedMar 8, 2014 at 9:10
  • 2
    \$\begingroup\$zx²+zy²>4 couldn't that beAbs(x)>2?\$\endgroup\$CommentedMar 8, 2014 at 9:31
  • 32
    \$\begingroup\$Interesting. So you've been anerd for quite a while.\$\endgroup\$CommentedMar 9, 2014 at 3:34
  • 4
    \$\begingroup\$@devnull Touché! Guilty as charged.\$\endgroup\$CommentedMar 9, 2014 at 3:58
  • 6
    \$\begingroup\$Nice "Screenshot"\$\endgroup\$CommentedMar 9, 2014 at 10:01
94
\$\begingroup\$

I came across this the other day. I don't take credit for it, but damn, is it awesome:

Python 2:

_                                      =   (                                        255,                                      lambda                               V       ,B,c                             :c   and Y(V*V+B,B,  c                               -1)if(abs(V)<6)else               (              2+c-4*abs(V)**-0.4)/i                 )  ;v,      x=1500,1000;C=range(v*x                  );import  struct;P=struct.pack;M,\            j  ='<QIIHHHH',open('M.bmp','wb').writefor X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))or C:            i  ,Y=_;j(P('BBB',*(lambda T:(T*80+T**9                  *i-950*T  **99,T*70-880*T**18+701*                 T  **9     ,T*i**(1-T**45*2)))(sum(               [              Y(0,(A%3/3.+X%v+(X/v+                               A/3/3.-x/2)/1j)*2.5                             /x   -2.7,i)**2 for  \                               A       in C                                      [:9]])                                        /9)                                       )   )

enter image description herehttp://preshing.com/20110926/high-resolution-mandelbrot-in-obfuscated-python/

\$\endgroup\$
9
  • 13
    \$\begingroup\$Seems to be disallowed: the regions are not easily distinguishable, or even at all.\$\endgroup\$CommentedMar 8, 2014 at 13:32
  • 5
    \$\begingroup\$Also, this writes to a file.\$\endgroup\$CommentedMar 8, 2014 at 21:49
  • 43
    \$\begingroup\$disallowed or not, this is pretty awesome :D\$\endgroup\$CommentedMar 9, 2014 at 2:28
  • 18
    \$\begingroup\$@DigitalTrauma, heck, +1 for most beautiful input!\$\endgroup\$CommentedMar 10, 2014 at 15:26
  • 23
    \$\begingroup\$Does this count as a quine? ;-)\$\endgroup\$CommentedMar 10, 2014 at 21:04
56
\$\begingroup\$

LaTeX, 673 bytes

\countdef\!1\!129\documentclass{article}\usepackage[margin=0pt,papersize=\!bp]{geometry}\usepackage{xcolor,pgf}\topskip0pt\offinterlineskip\def~{99}\let\rangeHsb~\countdef\c2\countdef\d3\countdef\e4\begin{document}\let\a\advance\let\p\pgfmathsetmacro\makeatletter\def\x#1#2#3{#10\@whilenum#1<#2\do{#3\a#11}}\d0\x\c{\numexpr~+1}{\expandafter\edef\csname\the\c\endcsname{\hbox{\noexpand\color[Hsb]{\the\d,1,1}\/}}\a\d23\ifnum\d>~\a\d-~\fi}\def\/{\rule{1bp}{1bp}}\x\c\!{\hbox{\x\d\!{\p\k{4*\d/(\!-1)-2}\p\K{2-4*\c/(\!-1)}\def\z{0}\def\Z{0}\x\e~{\p\:{\z*\z-\Z*\Z+\k}\p\Z{2*\z*\Z+\K}\let\z\:\p\:{\z*\z+\Z*\Z}\ifdim\:pt>4pt\csname\the\e\endcsname\e~\fi}\ifnum\e=~\/\fi}}}\stop

Result 129x129 (129 × 129)

The PDF image consists of colored square units with size 1bp × 1bp.

Ungolfed

% count register \size contains the width and height of the square\countdef\size=1\size=31\documentclass{article}\usepackage[margin=0pt,papersize=\size bp]{geometry}\usepackage{xcolor,pgf}\topskip0pt\offinterlineskip\def\iterations{99}\let\rangeHsb\iterations\countdef\c2\countdef\d3\countdef\e4\begin{document}\let\p\pgfmathsetmacro\makeatletter% \Loop: for (#1 = 0; #1 < #2; #1++) {#3}\def\Loop#1#2#3{%  #1=0  \@whilenum#1<#2\do{#3\advance#11}%}\d0%\Loop\c{\numexpr\iterations+1\relax}{%  \expandafter\edef\csname\the\c\endcsname{%    \hbox{\noexpand\color[Hsb]{\the\d,1,1}\noexpand\pixel}%  }%  \advance\d23 \ifnum\d>\iterations\advance\d-\iterations\fi}\def\pixel{\rule{1bp}{1bp}}% \c: row% \d: column% \e: iteration\Loop\c\size{%  \typeout{c: \the\c}%  \hbox{%    \Loop\d\size{%      \pgfmathsetmacro\k@re{4*\d/(\size-1)-2}%      \pgfmathsetmacro\K@im{2-4*\c/(\size-1)}%      \def\z@re{0}%      \def\Z@im{0}%      \Loop\e\iterations{%         % calculate z(n+1) = z^2(n) + k         \pgfmathsetmacro\temp{\z@re*\z@re-\Z@im*\Z@im+\k@re}%         \pgfmathsetmacro\Z@im{2*\z@re*\Z@im+\K@im}%         \let\z@re\temp         % calculate abs(z)^2         \pgfmathsetmacro\temp{\z@re*\z@re+\Z@im*\Z@im}%         \ifdim\temp pt>4pt\csname\the\e\endcsname\e\iterations\fi      }%         \ifnum\e=\iterations\pixel\fi    }%  }%}\stop
answeredMar 8, 2014 at 2:16
Heiko Oberdiek's user avatar
\$\endgroup\$
1
  • \$\begingroup\$I wonder if functional shading is shorter / meets the rule (not loading the pre-defined shading but define it yourself). Also includingtikz includes bothpgf andxcolor.\$\endgroup\$CommentedMar 26, 2022 at 3:33
43
\$\begingroup\$

x86 DOS Assembly,208177 173 bytes

The full binary, in HEX, that I created by hand, is:

DBE3BE00A0B81300CD1056BA640007BF87F9FDBDC7008BCDE81A008AC3AA4979F7B9C70083EF784D79EE33C0CD16B80300CD10CD208BC12BC289441CDF441CDF06A701DEF9D95C088BC52BC289441CDF441CDF06A701DEF9D95C0CD9EED914D95404D95410D95C14B301D904D84C04DE0EA901D8440CD95404D94410D86414D84408D914D80CD95C10D84C04D95414D84410DF06AB01DED99BDFE09B9E7207433ADA72C632DBC3320002000400

The sample image is:

Mandlebrot screen shot with black cropped

The full source in readable ASM is fairly long (I used this to figure out how I was coding this sucker):

.286CODE SEGMENTASSUME CS:code, DS:codeORG 0100h  ; *****************************************************************************start:  ; Mandlebrot coordinates  zr   = DWORD PTR [SI+0]  zi   = DWORD PTR [SI+4]  cr   = DWORD PTR [SI+8]  ci   = DWORD PTR [SI+12]  zrsq = DWORD PTR [SI+16]  zisq = DWORD PTR [SI+20]  ; Temp int  Temp = WORD PTR  [SI+28]  ; ===========================================================================  ; Initialize  ; Initialize the FPU  FNINIT  ; SI points to our memory  mov si, 0A000h ; So we can push it  ; Shave off some bytes by reusing 100  mov dx, 100  ; Switch to MCGA  mov ax, 013h  int 010h  ; ES:DI is the end of our drawing area  push si  pop es  mov di, 63879  std ; We're using stosb backwards  ; Initialize our X and Y  mov bp, 199  mov cx, bp  ; ===========================================================================  ; Main draw loop  MainLoop:  ; Get our next mandelbrot value  call GMV  ; Store it  mov al, bl  stosb  ; Decrement our X  dec cx  jns MainLoop  ; Decrement our Y  mov cx, 199  sub di, 120  dec bp  jns MainLoop  ; ===========================================================================  ; Done  ; Wait for a key press  xor ax, ax  int 016h  ; Change back to text mode  mov ax, 3  int 010h  ; Exit to DOS  int 020h; *****************************************************************************; GMV: Get Mandelbrot Value; Gets the value for the next Mandelbrot pixel; Returns:;   BL - The color to useGMV:  ; ===========================================================================  ; Initialize  ; cr = (x - 100) / 50;  mov ax, cx  sub ax, dx                  ; \  mov Temp, ax                ;  > ST0 = Current X - 100  FILD Temp                   ; /  FILD Divisor                ; ST0 = 50, ST1 = Current X - 100  FDIVP                       ; ST0 = (Current X - 100) / 50  FSTP cr                     ; Store the result in cr  ; ci = (y - 100) / 50;  mov ax, bp  sub ax, dx                  ; \  mov Temp, ax                ;  > ST0 = Current Y - 100  FILD Temp                   ; /  FILD Divisor                ; ST0 = 50, ST1 = Current Y - 100  FDIVP                       ; ST0 = (Current Y - 100) / 50  FSTP ci                     ; Store the result in ci  ; zr = zi = zrsq = zisq = 0;  FLDZ  FST zr  FST zi  FST zrsq  FSTP zisq  ; numiteration = 1;  mov bl, 1  ; ===========================================================================  ; Our main loop  ; do {GMVLoop:  ; zi = 2 * zr * zi + ci;  FLD zr  FMUL zi  FIMUL TwoValue  FADD ci  FST zi ; Reusing this later  ; zr = zrsq - zisq + cr;  FLD zrsq  FSUB zisq  FADD cr  FST zr ; Reusing this since it already is zr  ; zrsq = zr * zr;  ;FLD zr ; Reused from above  FMUL zr  FSTP zrsq  ; zisq = zi * zi;  ;FLD zi ; Reused from above  FMUL zi  FST zisq ; Reusing this for our comparison  ; if ((zrsq + zisq) < 4)  ;   return numiteration;  FADD zrsq  FILD FourValue  FCOMPP  FSTSW ax  FWAIT  sahf  jb GMVDone  ;} while (numiteration++ < 200);  inc bx  cmp bl, dl  jb GMVLoop  ;return 0;  xor bl, blGMVDone:    ret;GMV; *****************************************************************************; Data; DivisorDivisor DW 50; Two ValueTwoValue DW 2; 4 ValueFourValue DW 4CODE ENDSEND start

This is designed for compiling with TASM, runs in MCGA, and waits for a keypress before ending the program. The colors are just the default MCGA palette.

EDIT: Optimized it, now it draws backwards (same image though), and saved 31 bytes!

EDIT 2: To assuage the OP, I have recreated the binary by hand. By doing so, I also shaved another 4 bytes off. I documented every single step of the process, showing all of my work so anybody can follow along if they really want to, here (warning, it's boring and very long):https://web.archive.org/web/20160308132501/http://lightning.memso.com/media/perm/mandelbrot2.txt

I used a couple regex's in EditPadPro, to find all the; Final: ... entries in the file and dump them as hex binary to a .com file. The resulting binary is what you see at the top of this post.

Themoonisacheese's user avatar
Themoonisacheese
3,19713 silver badges34 bronze badges
answeredMar 9, 2014 at 0:19
Mara Ormston's user avatar
\$\endgroup\$
10
  • 6
    \$\begingroup\$I could hand code the entire thing in binary if it makes it easier for you, but that would be like asking anybody using a high level language to avoid using automatic constructs, macros, etc. That's ALL that assembly really is, just a bunch of macros. The resulting binary to run a full JavaScript, Perl, etc. includes the binary of the library. With ASM, the final hex value is everything, libraries, ALL CODE, included.\$\endgroup\$CommentedMar 10, 2014 at 18:50
  • 7
    \$\begingroup\$No. I can hand convert ASM to binary if really necessary. It will come out with the exact same 177 bytes that my assembler helped with. The resulting code can be pasted by anybody with a binary editor into a new file, saved out, 177 bytes, and it will work as expected. Apparently SO is divided on ASM submissions, so maybe you should clarify if you feel it does not count:meta.codegolf.stackexchange.com/questions/260/…\$\endgroup\$CommentedMar 10, 2014 at 19:14
  • 10
    \$\begingroup\$Alright, so, to prove this a valid entry, I spent the time it took to hand translate this to binary. I have updated my answer accordingly.\$\endgroup\$CommentedMar 12, 2014 at 5:34
  • 2
    \$\begingroup\$Machine code should count if the author actually codes in it directly. I used to code directly in Z80 machine code on my ZX Spectrum in 1983. I didn't even know what an assembler was. I never transferred this skill to any other processor or platform though. That it might be hard to decide who really wrote directly in machine code and who wrote in assembly then lied about it is an entirely separate thing.\$\endgroup\$CommentedMar 12, 2014 at 12:23
  • 10
    \$\begingroup\$The thing is, there is no compiler with assembly. You just use macros. Saying that it doesn't count is like saying you can't use any predefined#define statements in C. It's just time consuming to manually replace it all.\$\endgroup\$CommentedMar 12, 2014 at 16:33
27
\$\begingroup\$

Java,505405 324 bytes

Just a standard calculation,with golfitude now with extra golfitude.

enter image description here

Golfed:

import java.awt.*;class M{public static void main(String[]v){new Frame(){public void paint(Graphics g){for(int t,s,n=640,i=n*n;--i>0;g.setColor(new Color(s*820)),g.drawLine(i/n,i%n+28,i/n,i%n),setSize(n,668)){float c=4f/n,a=c*i/n-2,b=i%n*c-2,r=a,e=b,p;for(s=t=99;t-->0&&r*r+e*e<4;s=t,p=r*r-e*e+a,e=r*e*2+b,r=p);}}}.show();}}

With line breaks:

import java.awt.*;class M{    public static void main(String[]v){        new Frame(){            public void paint(Graphics g){                for(int t,s,n=640,i=n*n;--i>0;g.setColor(new Color(s*820)),g.drawLine(i/n,i%n+28,i/n,i%n),setSize(n,668)){                    float c=4f/n,a=c*i/n-2,b=i%n*c-2,r=a,e=b,p;                    for(s=t=99;t-->0&&r*r+e*e<4;s=t,p=r*r-e*e+a,e=r*e*2+b,r=p);                }            }        }.show();    }}
MD XF's user avatar
MD XF
14.2k5 gold badges70 silver badges108 bronze badges
answeredMar 8, 2014 at 3:06
Geobits's user avatar
\$\endgroup\$
13
  • \$\begingroup\$f.setSize(n,668); - depends heavily on the used Theme, but I'll accept it.\$\endgroup\$CommentedMar 8, 2014 at 9:11
  • \$\begingroup\$You can drop the imports in Java because they're auto-generated anyway.\$\endgroup\$CommentedMar 8, 2014 at 9:23
  • \$\begingroup\$I also seedouble wherefloat could be used if you tried\$\endgroup\$CommentedMar 8, 2014 at 9:29
  • \$\begingroup\$JFrame =>Frame shaves off 2 chars. Although you can't close the window anymore. ;)\$\endgroup\$CommentedMar 8, 2014 at 15:01
  • 2
    \$\begingroup\$Your class do not need to be public. Further, use Java 8 to get rid of thefinal modifier. And you must not omit the imports in order to be a complete submission.\$\endgroup\$CommentedMar 10, 2014 at 4:53
21
\$\begingroup\$

Javascript (ECMAScript 6) -315 308 Characters

document.body.appendChild(e=document.createElement("canvas"));v=e.getContext("2d");i=v.createImageData(e.width=e.height=n=600,n);j=0;k=i.data;f=r=>k[j++]=(n-c)*r%256;for(y=n;y--;)for(x=0;x++<n;){c=s=a=b=0;while(c++<n&&a*a+b*b<5){t=a*a-b*b;b=2*a*b+y*4/n-2;a=t+x*4/n-2}f(87);f(0);f(0);k[j++]=255}v.putImageData(i,0,0)

Default Output

(d=document).body.appendChild(e=d.createElement`canvas`);v=e.getContext`2d`;i=v.createImageData(e.width=e.height=n=600,n);j=0;k=i.data;f=r=>k[j++]=(n-c)*r%256;for(y=n;y--;)for(x=0;x++<n;){c=s=a=b=0;while(c++<n&&a*a+b*b<5){t=a*a-b*b;b=2*a*b+y*4/n-2;a=t+x*4/n-2}f(87);f(0);f(0);k[j++]=255}v.putImageData(i,0,0)

  • Changen to vary the image size (and number of iterations).
  • Change the values passed in thef(87);f(0);f(0); calls (near the end) to change the RGB colour values. (f(8);f(8);f(8); is greyscale.)

Withf(8);f(23);f(87);:

enter image description here

(d=document).body.appendChild(e=d.createElement`canvas`);v=e.getContext`2d`;i=v.createImageData(e.width=e.height=n=600,n);j=0;k=i.data;f=r=>k[j++]=(n-c)*r%256;for(y=n;y--;)for(x=0;x++<n;){c=s=a=b=0;while(c++<n&&a*a+b*b<5){t=a*a-b*b;b=2*a*b+y*4/n-2;a=t+x*4/n-2}f(8);f(23);f(87);k[j++]=255}v.putImageData(i,0,0)

answeredMar 9, 2014 at 0:05
MT0's user avatar
\$\endgroup\$
5
  • 2
    \$\begingroup\$Nice.d=document would save you a few more. (Also, Is there a reason for creating the canvas? Does codegolf assume a certain level of HTML available?)\$\endgroup\$CommentedMar 10, 2014 at 15:47
  • 1
    \$\begingroup\$You can writedocument.createElement`canvas` and save 2 bytes. Same as thegetContext`2d`.\$\endgroup\$CommentedOct 7, 2019 at 10:17
  • \$\begingroup\$I didn't assume a HTML Canvas as this is a pure JavaScript solution.\$\endgroup\$CommentedOct 7, 2019 at 10:42
  • \$\begingroup\$or you can 'drop' canvas at all likehere\$\endgroup\$CommentedOct 7, 2019 at 19:59
  • \$\begingroup\$The first image looks like a Virtual Boy game.\$\endgroup\$CommentedJan 7, 2023 at 19:36
20
\$\begingroup\$

J, 73 bytes

load'viewmat'(0,?$~99 3)viewmat+/2<|(j./~i:2j479)(+*:) ::(3:)"0^:(i.99)0

mandelbrot set

Edit, some explaining:

x (+*:) y           NB. is x + (y^2)x (+*:) ::(3:) y    NB. returns 3 when (+*:) fails (NaNs)j./~i:2j479         NB. a 480x480 table of complex numbers in required rangev =: (j./~i:2j479)(+*:) ::(3:)"0 ]     NB. (rewrite the above as one verb)v z0                NB. one iteration of the mandelbrot operation (z0 = 0)v v z0              NB. one iteration on top of the other(v^:n) z0           NB. the result of the mandelbrot operation, after n iterationsi.99                NB. 0 1 2 3 4 ... 98(v^:(i.99))0        NB. returns 99 tables, one for each number of iterations2<| y               NB. returns 1 if 2 < norm(y), 0 otherwise2<| (v^:(i.99))0    NB. 99 tables of 1s and 0s+/...               NB. add the tables together, element by element.NB. we now have one 480x480 table, representing how many times each element exceeded norm-2.colors viewmat M    NB. draw table 'M' using 'colors'; 'colors' are rgb triplets for each level of 'M'.$~99 3              NB. 99 triplets of the numbers 99,3?$~99 3             NB. 99 random triplets in the range 0 - 98 and 0 - 20,?$~99 3           NB. prepend the triplet (0,0,0): black
MD XF's user avatar
MD XF
14.2k5 gold badges70 silver badges108 bronze badges
answeredMar 9, 2014 at 16:08
Eelvex's user avatar
\$\endgroup\$
3
  • 1
    \$\begingroup\$+1 but would it be possible for you to explain a little how that code work? In particular i m curious to know how (where in the code) does it pick the colors?\$\endgroup\$CommentedMar 10, 2014 at 8:40
  • 1
    \$\begingroup\$@MarkJeronimus, I can make it 70 but I kept some things for clarity. I, thus, took the liberty to ignore the LF when counting.\$\endgroup\$CommentedMar 10, 2014 at 12:39
  • \$\begingroup\$@plannapus, OK, added some comments. The color picking is done with(0,?$~99 3) which produces 100 rgb triplets, one for each level. Because of the randomness, you might get less than 100 triplets so some levels will have a smoother transition (but still have different colors).\$\endgroup\$CommentedMar 10, 2014 at 13:07
20
\$\begingroup\$

Mathematica,21419121519 30

Since version 10.0 there is a built-in: (19 bytes)

MandelbrotSetPlot[]

mandelbrot


To conform to the coordinate range requirements, 11 additional bytes are required. (30 bytes)

MandelbrotSetPlot@{-2-2I,2+2I}

m2


A hand-rolled case:

m=Compile[{{c,_Complex}},Length[FixedPointList[#^2+c&,0,99,SameTest→(Abs@#>=2&)]]];ArrayPlot[Table[m[a+I b],{b,-2,2,.01},{a,-2,2,.01}],DataRange→{{-2,2},{-2,2}},ColorRules→{100→Black},ColorFunction→(Hue[Log[34,#]]&)]

green

MD XF's user avatar
MD XF
14.2k5 gold badges70 silver badges108 bronze badges
answeredMar 7, 2014 at 23:15
DavidC's user avatar
\$\endgroup\$
6
  • \$\begingroup\${b, -2, 2, .01}, {a, -2, 2, .01} is shorter and closer to the rules\$\endgroup\$CommentedMar 7, 2014 at 23:50
  • \$\begingroup\$@MarkJeronimus Thanks. I used the suggested range for the iterating picture.\$\endgroup\$CommentedMar 8, 2014 at 3:20
  • \$\begingroup\$You had it almost right, then you made the inside non-black. The last frame in the GIF is black inside and an allowed answer. EDIT: and I count 195 bytes.\$\endgroup\$CommentedMar 8, 2014 at 9:20
  • \$\begingroup\$I missed the point about being black. The count increased because some single characters became two characters in the cut-and-paste to SE.\$\endgroup\$CommentedMar 8, 2014 at 13:34
  • \$\begingroup\$Your built-in solution uses a very loose interpretation ofThe fractal coordinates range from approximately -2-2i to 2+2i.\$\endgroup\$CommentedSep 25, 2017 at 12:58
18
\$\begingroup\$

Python with Pylab+Numpy, 151 bytes

I couldn't bear to see a non-DQ'ed Python entry, but I think I really outdid myself on this one, and I made it down to 153 characters!

import numpy as nfrom pylab import*i=99x,y=n.mgrid[-2:2:999j,-2:2:999j]c=r=x*1j+yx-=xwhile i:x[(abs(r)>2)&(x==0)]=i;r=r*r+c;i-=1show(imshow(x))

Also, notably, the second to last line raises 4 distinct runtime warnings, a new personal record!

enter image description here

MD XF's user avatar
MD XF
14.2k5 gold badges70 silver badges108 bronze badges
answeredMar 9, 2014 at 8:11
meawoppl's user avatar
\$\endgroup\$
7
  • \$\begingroup\$I count 152. No space is required betweenimport and*, and not definingf at all should be shorter, unless i've misunderstood something, which is possible. You should also change it around such that 0 iterations and 1 iterations are distiguished (they're currently both grey).\$\endgroup\$CommentedMar 9, 2014 at 14:02
  • \$\begingroup\$Weird. Does wc include the eof? Fixed and slightly smaller. Just a moment.\$\endgroup\$CommentedMar 9, 2014 at 17:46
  • \$\begingroup\$I get 151 with wc. First golf, so not sure how to score it.\$\endgroup\$CommentedMar 9, 2014 at 18:01
  • \$\begingroup\$I count 150, without trailing newline. Some interpreters/compilers demand one, but the python interpreter does fine without. Not sure aboutwc, but maybe trystat -c %s instead. Are the black upper and lower borders part of the image?\$\endgroup\$CommentedMar 9, 2014 at 18:09
  • 1
    \$\begingroup\$You can save 1 character by usingfrom numpy import* instead ofimport numpy as n andmgrid instead ofn.mgrid.\$\endgroup\$CommentedJun 15, 2014 at 15:15
16
\$\begingroup\$

C + Allegro 4.2.2 - 248 bytes

#include<allegro.h>x=-1,y,K=400;float a,h,c,d,k;main(i){set_gfx_mode('SAFE',K,K,allegro_init(),0);while(x++<K)for(y=0;y<K;y++){for(a=h=i=0;a*a+h*h<4&&++i<256;k=a,a=a*a-h*h+x*0.01-2,h=2*k*h+y*0.01-2);putpixel(screen,x,y,i);}while(1);}END_OF_MAIN()

Output:

MSet 1

answeredMar 8, 2014 at 13:42
Oberon's user avatar
\$\endgroup\$
8
  • \$\begingroup\$You should mention that this is Allegro 4 (which is quite different from Allegro 5). Which exact version is this?\$\endgroup\$CommentedMar 10, 2014 at 4:57
  • \$\begingroup\$it's either 246 or 249 long\$\endgroup\$CommentedMar 10, 2014 at 6:42
  • \$\begingroup\$@Victor Allegro 4.2.2.\$\endgroup\$CommentedMar 10, 2014 at 14:34
  • 1
    \$\begingroup\$@MarkJeronimus Isn't there supposed to be a newline between... allegro.h> andx=-1, ...? I suppose Notepad++ counts it as\r\n =0D 0A.\$\endgroup\$CommentedMar 10, 2014 at 21:05
  • 2
    \$\begingroup\$I think0.01 can be typed as.01.\$\endgroup\$CommentedJun 21, 2016 at 9:53
15
\$\begingroup\$

Windows PowerShell (v4), 299 bytes

Mandelbrot fractal picture

# Linewrapped here for show:$M='System.Windows.Forms';nal n New-Object;Add-Type -A System.Drawing,$M;($a=n "$M.Form").backgroundimage=($b=n Drawing.Bitmap 300,300);0..299|%{$r=$_;0..299|%{$i=99;$k=$C=n numerics.complex($_/75-2),($r/75-2);while((($k=$k*$k).Magnitude-lt4)-and$i--){$k+=$C}$b.SetPixel($_,$r,-5e6*++$i)}};$a.Show()# The single line 299 char entry version:$M='System.Windows.Forms';nal n New-Object;Add-Type -A System.Drawing,$M;($a=n "$M.Form").backgroundimage=($b=n Drawing.Bitmap 300,300);0..299|%{$r=$_;0..299|%{$i=99;$k=$C=n numerics.complex($_/75-2),($r/75-2);while((($k=$k*$k).Magnitude-lt4)-and$i--){$k+=$C}$b.SetPixel($_,$r,-5e6*++$i)}};$a.Show()

Instructions

  • Run a normal PowerShell console (ISE might not work)
  • Copy/paste code in, press Enter
  • Wait - it takes a minute or more to run
  • The only way to quit is to close the console

Comment

  • There's a tiny bit of rule-testing going on with the colours inside the set; the rules say"The other pixels (presumably inside the Mandelbrot set) must be colored either black or white'"; the code is colouring the pixels completely black RGB(0,0,0) ... it just happens to be a transparent black RGBA(0,0,0,0). So what shows up is the form background colour of the current Windows theme, a slightly off-white RGB(240,240,240) in this case.
answeredSep 30, 2015 at 1:28
TessellatingHeckler's user avatar
\$\endgroup\$
3
  • \$\begingroup\$I'd changelt2 tolt4 to make it a "mandelbrot set" instead of the image you have now, Many points of the set are swallowed up by the color bands.\$\endgroup\$CommentedSep 30, 2015 at 11:05
  • \$\begingroup\$Apparently Magnitude isa*a+b*b notsqrt(a*a+b*b)\$\endgroup\$CommentedSep 30, 2015 at 13:41
  • \$\begingroup\$I thought I tested that earlier, but I went in search of an answer to "where's the horizontal line on the left gone?", and after a bit, I found it exactly where you said,-lt4. Which is good - thank you. I've updated my answer with corrected code, and image. (Will have to rethink my understanding of what it's doing, since I'm missing something).\$\endgroup\$CommentedSep 30, 2015 at 18:02
15
\$\begingroup\$

Python +PIL, 166 bytes

import Imaged=600;i=Image.new('RGB',(d,d))for x in range(d*d): z=o=x/9e4-2-x%d/150.j-2j;c=99 while(abs(z)<2)*c:z=z*z+o;c-=1 i.putpixel((x/d,x%d),5**8*c)i.show()

Output (will open in the default *.bmp viewer):

MD XF's user avatar
MD XF
14.2k5 gold badges70 silver badges108 bronze badges
answeredMar 8, 2014 at 16:06
primo's user avatar
\$\endgroup\$
6
  • 1
    \$\begingroup\$You can shave off 3 if you get rid of they loop.r=range(d*d), usex/d andx%d for x and y.\$\endgroup\$CommentedMar 8, 2014 at 16:15
  • 1
    \$\begingroup\$Complex types can be initialized like: c=1+2j, which I think would save you a couple characters with: z=o=x/9e4-2+(x%d/150.-2)*1j;c=99\$\endgroup\$CommentedMar 9, 2014 at 3:10
  • \$\begingroup\$@meawoppl another 7 :D\$\endgroup\$CommentedMar 9, 2014 at 5:07
  • \$\begingroup\$Technically disallowed: this doesn't any graphical output feature of Python itself (andImage.show() implicitly saves a temporary file).\$\endgroup\$CommentedMar 9, 2014 at 5:51
  • \$\begingroup\$This post totally got me started on the 153 character version I posted below :)\$\endgroup\$CommentedMar 9, 2014 at 8:27
13
\$\begingroup\$

BBC Basic (228 bytes)

What about languages that nobody ever heard of in code golf? Most likely could be optimized, but I'm not quite where - improvements possible. Based ofhttp://rosettacode.org/wiki/Mandelbrot_set#BBC_BASIC, but I tried to code golf it as much as possible.

VDU23,22,300;300;8,8,8,8ORIGIN0,300GCOL1FORX=0TO600STEP2i=X/200-2FORY=0TO300STEP2j=Y/200x=0y=0FORI=1TO128IFx*x+y*y>4EXIT FORt=i+x*x-y*yy=j+2*x*yx=tNEXTCOLOUR1,I*8,I*4,0PLOTX,Y:PLOTX,-YNEXTNEXT

The generated Mandelbrot set

The> symbol on image is prompt, and it's automatically generated after running the program.

answeredMar 9, 2014 at 9:01
null's user avatar
\$\endgroup\$
1
  • \$\begingroup\$No need to plot twice, just go with a more inefficient version. Doesn;t it supportNEXT Y,X?\$\endgroup\$CommentedMar 9, 2014 at 11:59
12
\$\begingroup\$

APL, 194 chars/bytes*

m←{1{⍺=99:0⋄2<|⍵:⍺⋄(⍺+1)∇c+⍵*2}c←⍵}¨⍉v∘.+0j1×v←¯2+4÷s÷⍳s←640'F'⎕WC'Form'('Coord' 'Pixel')('Size'(s s))'B'⎕WC'Bitmap'('CMap'(0,,⍨⍪0,15+10×⍳24))('Bits'(24⌊m))'F.I'⎕WC'Image'(0 0)('Picture' 'B')

This is for Dyalog APL with⎕IO ⎕ML←1 3

Most of the space is taken by API calls to show a bitmap in a window (lines 2, 3, 4)
If there was a shortcut to do it, the code would be down to 60 chars (line 1)

Ungolfed version (only line 1)

s←640            ⍝ size of the bitmapv←(4×(⍳s)÷s)-2   ⍝ vector of s reals, uniform between ¯2 and 2m←(0j1×v)∘.+v    ⍝ square matrix of complex numbers from ¯2j¯2 to 2j2m←{              ⍝ transform each number in matrix m according to the following  1{             ⍝   function that takes iteration counter as ⍺ and current value as ⍵    ⍺=99: 0      ⍝     if we have done 99 iterations, return 0    2<|⍵: ⍺      ⍝     if |⍵| > 2 return the number of iterations done    (⍺+1)∇c+⍵*2  ⍝     otherwise, increment the iterations and recurse with the new value  }c←⍵           ⍝   save the initial value as c}¨m

Screenshot:

screenshot

*: Dyalog has its own single byte charset, with the APL symbols mapped to the upper 128 byte values, so the entire code can be stored in 194 bytes.

answeredMar 13, 2014 at 21:17
Tobia's user avatar
\$\endgroup\$
11
\$\begingroup\$

TI-80 BASIC,125 106 bytes

ZDECIMALFOR(Y,-2,2,.1FOR(X,-2,2,.10->S0->T1->NLBL NN+1->NIF S²+T²≥4GOTO BS²-T²+X->I2ST+Y->TI->SIF N<20GOTO NLBL BIF FPART (N/2PT-ON(X,YENDEND

Based on Digital Trauma's answer.enter image description here

answeredFeb 13, 2017 at 22:39
12Me21's user avatar
\$\endgroup\$
10
\$\begingroup\$

R,199 211 characters

Old solution at 199 characters:

r=seq(-2,2,l=500);c=t(sapply(r,function(x)x+1i*r));d=z=array(0,dim(c));a=1:25e4;for(i in 1:99){z[a]=c[a]+z[a]^2;s=abs(z[a])<=2;d[a[!s]]=i;a=a[s]};image(d,b=0:99,c=c(1,sample(rainbow(98))),ax=F,asp=1)

With indentation:

r=seq(-2,2,l=500)c=t(sapply(r,function(x)x+1i*r)) #Produces the initial imaginary number matrixd=z=array(0,dim(c)) #empty matrices of same size as c a=1:25e4            #(z will store the magnitude, d the number of iterations before it reaches 2)for(i in 1:99){     #99 iterations    z[a]=c[a]+z[a]^2    s=abs(z[a])<=2    d[a[!s]]=i    a=a[s]    }image(d,b=0:99,c=c(1,sample(rainbow(98))),ax=F,asp=1) #Colors are randomly ordered (except for value 0)

enter image description here

Edit: Solution at 211 characters that colors the inside of the set and the outside of the first layer differently:

r=seq(-2,2,l=500);c=t(sapply(r,function(x)x+1i*r));d=z=array(0,dim(c));a=1:25e4;for(i in 1:99){z[a]=c[a]+z[a]^2;s=abs(z[a])<=2;d[a[!s]]=i;a=a[s]};d[a[s]]=-1;image(d,b=-1:99,c=c(1:0,sample(rainbow(98))),ax=F,asp=1)

With indentation:

r=seq(-2,2,l=500)c=t(sapply(r,function(x)x+1i*r))d=z=array(0,dim(c))a=1:25e4for(i in 1:99){    z[a]=c[a]+z[a]^2    s=abs(z[a])<=2    d[a[!s]]=i    a=a[s]    }d[a[s]]=-1 #Gives the inside of the set the value -1 to differenciate it from value 0.image(d,b=-1:99,c=c(1,sample(rainbow(99))),ax=F,asp=1)

enter image description here

answeredMar 8, 2014 at 8:55
plannapus's user avatar
\$\endgroup\$
5
  • \$\begingroup\$technically black on the outside is disallowed. Did you miss that or is it difficult to implement?\$\endgroup\$CommentedMar 8, 2014 at 9:19
  • \$\begingroup\$@MarkJeronimus both actually :) I'll try to have a look of how to do that but i m not 100% confident that I ll find a way to do that cleanly.\$\endgroup\$CommentedMar 8, 2014 at 9:20
  • \$\begingroup\$@MarkJeronimus Done!\$\endgroup\$CommentedMar 8, 2014 at 9:40
  • 5
    \$\begingroup\$Second place in the hideous colors division.\$\endgroup\$CommentedMar 9, 2014 at 10:02
  • 1
    \$\begingroup\$@meawoppl blamerainbow() :)\$\endgroup\$CommentedMar 10, 2014 at 7:23
10
\$\begingroup\$

Mathematica 10.0, 19 chars

MandelbrotSetPlot[]

MandelbrotSetPlot is a new function in Mathematica 10.0.

enter image description here

MD XF's user avatar
MD XF
14.2k5 gold badges70 silver badges108 bronze badges
answeredMar 29, 2014 at 13:25
alephalpha's user avatar
\$\endgroup\$
2
  • \$\begingroup\$How convenient, that this built in function just happens to satisfy all my requirements (except location, which can be set with 13 more characters). Except this is a standard loophole.\$\endgroup\$CommentedMar 30, 2014 at 10:03
  • 24
    \$\begingroup\$Code golf is generally won by specialist languages with single-character tokens, or by systems like Mathematica that have a massive number of special functions built-in. To use them is not cheating, any more than using single-character commands would be in APL.\$\endgroup\$CommentedApr 17, 2014 at 15:08
10
\$\begingroup\$

Java - Processing (271 bytes)

void setup(){int h=100,e=5*h,i;float d,v,w,a,b,c;size(e,e);colorMode(HSB,h);loadPixels();d=4./e;v=2;for(int x=1;x<=e;x++){v-=d;w=2;for(int y=0;y<e;){w-=d;a=b=c=0;i=-1;while(a*a+b*b<4&&++i<h){c=a*a-b*b+v;b=2*a*b+w;a=c;}pixels[e*++y-x]=color(i*9%h,h,h-i);}}updatePixels();}

Expanded:

void setup(){  int h=100, e=5*h, i; //init of size "e", max hue "h", iterator "i"  float d,v,w,a,b,c; //init of stepwidth "d", y-coord "v", x-coord "w", Re(z) "a", Im(z) "b", temp_a "c"  size(e,e);  colorMode(HSB,h);  loadPixels();  d = 4./e;  v = 2;  for(int x = 1; x <= e; x++){    v -= d;    w = 2;    for(int y = 0; y < e;){      w -= d;      a = b = c = 0;      i = -1;      while(a*a + b*b < 4 && ++i < h){        c = a*a - b*b + v;        b = 2*a*b + w;        a = c;      }      pixels[e * ++y - x] = color(i*9 % h, h, h-i);    }  }  updatePixels();}

mousetail's user avatar
mousetail
14.4k1 gold badge42 silver badges91 bronze badges
answeredMar 8, 2014 at 17:11
Jan K's user avatar
\$\endgroup\$
1
  • \$\begingroup\$Aw, maaaaan, I wanted to do this.+1.\$\endgroup\$CommentedSep 28, 2017 at 12:57
8
\$\begingroup\$

Applesoft BASIC,302286 280 bytes

This picks random points to draw, so it will run forever and may never fill in the full plane.

1HGR:POKE49234,0:DIMco(10):FORc=0TO10:READd:co(c)=d:NEXT:DATA1,2,3,5,6,1,2,3,5,6,02x=INT(RND(1)*280):y=INT(RND(1)*96):x1=x/280*3-2:y1=y/191*2-1:i=0:s=x1:t=y13s1=s*s-t*t+x1:t=2*s*t+y1:s=s1:i=i+1:IFs*s+t*t<4ANDi<20THENGOTO34c=co(i/2):IFc THENHCOLOR=c:HPLOTx,y:HPLOTx,191-y5GOTO2

Turns out Applesoft BASIC isreally forgiving about lack of spaces. Only one space is necessary in the entire program.

Output after 14 hours:

        output

GIF:

        gif

Before golfing:

10 HGR : POKE 49234,020 DIM co(10) : FOR c = 0 TO 10 : READ d : co(c) = d : NEXT30 DATA 1, 2, 3, 5, 6, 1, 2, 3, 5, 6, 0100 x = INT(RND(1) * 280) : y = INT(RND(1) * 96)110 x1 = x / 280 * 3 - 2 : y1 = y / 191 * 2 - 1120 i = 0:s = x1:t = y1130 s1 = s * s - t * t + x1140 t = 2 * s * t + y1:s = s1: i = i + 1150 IF s * s + t * t < 4 AND i < 20 THEN GOTO 130160 c = co(i/2) : IF c THEN HCOLOR= c : HPLOT x,y : HPLOT x,191 - y170 GOTO 100

Note:POKE 49234,0 (in Applesoft BASIC) puts the machine into full graphics mode.

A version optimized for B&W displays:

110 HGR:POKE 49234,0:HCOLOR=3120 FOR x = 0 TO 279:FOR y = 0 TO 95130 x1 = x / 280 * 3 - 2:y1 = y / 191 * 2 - 1140 i = 0:s = x1:t = y1:c = 0150 s1 = s * s - t * t + x1160 t = 2 * s * t + y1:s = s1:c = 1 - c:i = i + 1170 IF s * s + t * t < 4 AND i < 117 THEN GOTO 150180 IF c = 0 THEN HPLOT x,y:HPLOT x,191 - y190 NEXT:NEXT

Output after 12 hours:

        b&w

A version that will work in GW-BASIC (DOS):

5 CLS6 SCREEN 120 DIM co(10) : FOR c = 0 TO 10 : READ d : co(c) = d : NEXT30 DATA 1, 2, 3, 5, 6, 1, 2, 3, 5, 6, 0100 x = INT(RND(1) * 280) : y = INT(RND(1) * 96)110 x1 = x / 280 * 3 - 2 : y1 = y / 191 * 2 - 1120 i = 0 : s = x1 : t = y1130 s1 = s * s - t * t + x1140 t = 2 * s * t + y1 : s = s1 : i = i + 1150 IF s * s + t * t < 4 AND i < 20 THEN GOTO 130160 c = co(i/2) : PSET (x,y),C : PSET (x,191 - y),C170 GOTO 100
answeredMay 26, 2017 at 6:02
MD XF's user avatar
\$\endgroup\$
2
  • \$\begingroup\$Would be smaller (and slower) if you didn't plot two pixels at once but choose a random pixel on the entire screen.\$\endgroup\$CommentedMay 31, 2017 at 6:09
  • 1
    \$\begingroup\$@MarkJeronimus It's already so slow that the color version has not yet finished, after posting this 5 days ago. I don't think I can afford it to be any slower :P\$\endgroup\$CommentedMay 31, 2017 at 20:11
8
\$\begingroup\$

R,140136128124123110 109 bytes*

image(outer(j<-1:396/99-2,j,Vectorize(function(x,y,n=99){while((n=n-1)&abs(F)<2)F=F*F+x+1i*y;n})),c=colors())

Try it at rdrr.io

6y after the Q was asked, but I love Mandelbrot sets, and the earlier R solution was 211 characters...

enter image description here

*Or just62 bytes as apixel-shader function inR≥4.1:
\(x,y,n=99){while((n=n-1)&abs(F)<2)F=F*F+x+1i*y;colors()[n+1]}

answeredMay 18, 2020 at 19:23
Dominic van Essen's user avatar
\$\endgroup\$
1
  • 2
    \$\begingroup\$No problem, submissions are always welcome. En welkom.\$\endgroup\$CommentedMay 19, 2020 at 21:03
7
\$\begingroup\$

JavaScript,284 283 ...(12 improvements)... 191 190 188 199 bytes

currenty (2019-10-05) this is shortest js solution (the shortest one before this has285 bytes)

enter image description here

Expanded

// Fractal calculationsc=512;// p has pixels, p+= allways join 4 digit number implicit casted to string// 4 char string interpred as base64 gives 3bytes = 1 RGB pixelfor( p=i=''; j=x=y=0,++i<=c*c; p+= j<c ? 9*c+9*j : 'AAAA' )   while( x*x+y*y<4 && ++j-c )    [x,y] = [ x*x-y*y+i%c/128-2, 2*x*y+i/c/128-2 ];  // draw pixels in 512x512 BMP base64 imagedocument.write("<img src=data:;base64,Qk0bAAwAAAAAABsAAAAMAAAAAAIAAgEAGAAA"+p)

After small constans changes

c=512;for(p=i='';j=x=y=0,++i<=c*c;p+=j<c?2*c+9*j:'AAAA')while(x*x+y*y<4&&++j-c)[x,y]=[x*x-y*y+i%c/128-2,2*x*y+i/c/128-2]document.write("<img src=data:;base64,Qk0bAAwAAAAAABsAAAAMAAAAAAIAAgEAGAAA"+p)

answeredOct 3, 2019 at 9:44
Kamil Kiełczewski's user avatar
\$\endgroup\$
3
  • \$\begingroup\$This is very cool, but the pixels inside the set should be black or white. I'm not sure what either of those are in base 64\$\endgroup\$CommentedApr 22, 2022 at 0:11
  • \$\begingroup\$@MatthewJensen you are right - AAAA - fixed\$\endgroup\$CommentedMay 5, 2022 at 15:48
  • 1
    \$\begingroup\$A few minor changes gets 194 bytesfor(c=i=512,p='<img src=data:;base64,Qk0bAAwAAAAAABsAAAAMAAAAAAIAAgEAGAAA';i++<c*c;p+=j<c?9*c+9*j:'AAAA')for(j=x=y=0;x*x+y*y<4&&++j-c;)[x,y]=[x*x-y*y+i%c/128-2,2*x*y+i/c/128-2];document.write(p)\$\endgroup\$CommentedJun 16, 2022 at 1:01
7
\$\begingroup\$

Mindustry, 492 bytes

set xset yop div v x 44op sub v v 2op div w y 44op sub w w 2set aset bset nop pow c a 2op pow d b 2op sub A c dop mul B 2 aop add a A vop mul B Bop add b B wop pow c a 2op pow d b 2op add s c dop sqrt r sop add n n 1jump 23 greaterThan r 2jump 11 lessThan n 100op mul r n 42op mod r r 256op mul g n 83op mod g g 256op mul b n 160op mod b b 256draw color r g bdraw rect x y 1 1drawflushop add x x 1jump 2 lessThan x 176op add y y 1set xjump 2 lessThan y 176

How the result looks:Setup of the blocks

What this is

Mindustry contains, among many other things, a few blocks related to running computations (processors, memory cells, switches, screens, messages). The above code is the "assembly" language of the processor (bottom left).

The resolution of the image drawn is 176x176, because this is the largest possible screen block (the other is 80x80).The processor can only process up to 1500 operations per second, so the program takes at least an hour to run.

How to run it

The code should be copied into the processor block, which must be connected with the display. Ideally, this should be constructed on a sandbox map.

Scoring

In the in-game program editor, this would be shown as 37 assembly blocks, but since it is stored as text internally, the byte count of the textual representation is used to score it.

Golfing

Since this language is assembly-like and its text representation is not designed to take few bytes, a lot of things are quite verbose.The main way in which this program is golfed is by removing the last argument to many of these calls if it is the default value for this call, since it will be inserted automatically. For example,set x 0 can beset x and when copying it into the processor, the 0 is added.

answeredOct 11, 2024 at 7:19
Dornteufel's user avatar
\$\endgroup\$
2
  • 1
    \$\begingroup\$Very cool "processor"! Looking at the game and source code, the program is stored in plain text, that is to say the score is the sum of the characters that make it up, including newlines. Also, no matter what size display is in the game, at least one display is always allowed by the rule exception.\$\endgroup\$CommentedOct 11, 2024 at 21:21
  • \$\begingroup\$I've updated my answer to incorporate your feedback.\$\endgroup\$CommentedOct 12, 2024 at 20:30
7
\$\begingroup\$

Bendix G-15 Machine Code

292 29-bit words

The Bendix G-15 is a vacuum tube computer from 1956. The rules specify "No ASCII Art" but this machine pre-dates ASCII, therefor the typewriter output is not ASCII. The machine is only capable of outputting hexadecimal values, but note that it also predates the convention of using A-F, and instead uses the characters u-z.

Program is not measured in bytes, because this computer predates the term.

This program was written in 2025, but uses subroutines written in 1957.

Typewriter Output

# BBL - Bill's Bendix Loader# Prepared by: Bill Kuker# Date: 2-24-2025### As the first block on a tape (after the number track) this# Program reads the specified number of blocks into the first# N lines of the drum in reverse order. The final block is# copied into line 0, and then execution is transferred to# Line 0 Instruction zero.## It might waste a few inches of tape, but lets be real I'll# never get to run it on the real thing.# # (BBL Rhymes with nibble)## Usage:# Include this file, store number of tracks to load at :ct# ct = 4 will load 4 tracks into lines 3,2,1,0 and then jump# to 00:00## #include "bbl.asm"# ct:                      Count# .     +4                 Number of blocks to load## Copy loaded program from 19 -> 0 and begin execution at 0:03#.00 . u.01.02.0.19.00   Line 19 to Line 0 - Test not set.01 . u.02.02.0.19.00   Line 19 to Line 0 - Test set.02 .  .03.03.0.21.31   GOTO 0:3# After each block is copied it goes to 0.# The following code replazes the original instruction at zero with a# jump to lp: at instruction iterate the loop.## When the count reaches zero, this program will have been replaced# by final block loaded from tape. I feel vaguely clever.                        Replace instruction a 0.0 with jump to lp:.03 .  .22.04.1.00.28   nz -> ARc.04 .  .00.05.1.28.00   AR -> 00lp:                     Loop                        Clear Line 19.05 .  .06.06.0.29.28   0 -> AR.06 . u.07.07.0.28.19   AR -> Line 19                        Load a block, copy it to Line nr in :ct.07 .  .09.08.0.15.31   Read next tape block.08 .  .08.08.0.28.31   Wait for IOReady                        Calculate Checksum.09 .  .10.10.0.29.28   0 -> AR.10 . u.11.11.1.19.29   Sum line 19 to AR.11 .  .13.12.0.28.27   If AR == 0.12 .  .00.14.0.00.00   goto ok                        else.13 .  .00.20.0.00.00   got bcok:                     OK Checksum                        Decrement count.14 .  .24.15.1.00.28   ct -> ARc.15 .  .23.16.3.00.29   AR--.16 .  .24.17.1.28.00   AR -> ct                        Execute copy instruction.17 .  .18.19.1.00.29   Add copy intruction to ct in AR.18 . u.22.00.0.19.00   Copy Instruction: Line 19 to Line 0                        Added to AR, which has target line.19 .  .21.21.0.31.31   NCAR                        Copy instruction jumps to 0:0bc:                     BAD Checksum.20 .  .21.21.0.17.31   DING.21 .  .23.14.0.16.31   Halt#Datanz:                     New Instruction for location Zero .22 .  .05.05.0.20.31   GOTO 0.lpon:                     One - Constant.23   +0000001          ct:                     Count.24   +0000003          <BLOCK>rs:                     Return Setup.00 .  .01.02.1.02.28   Copy return command to A.01 .  .40.40.2.20.31   Return Command.02 .  .02.03.0.28.21   command for normal return.03 .  .03.04.0.28.21   command for overflow return                        Skip the above code after the                        first call to this fractal code.04 .  .05.06.0.02.28   Skip command to AR.05 .  .01.07.0.00.00   .06 .  .00.07.0.28.02   AR -> 2:0                        Clear count.07 .  .08.09.0.02.28   1 -> AR.08   +0000001          .09 .  .10.11.0.28.23   AR -> ct                        Initialize Z                        Load 23:0,1 (Ci,Cr) -> 20:0,1 (Zi,Zr).11 .  .12.13.0.23.20   Ci -> Zi.13 .  .17.18.0.23.20   Cr -> Zrlp:#43-55#                        Put Z into line 22 as complex mult params#                        Copy 20:0,1 (Zi,Zr) to....18 .  .21.22.0.20.28   Zr -> AR.22 .  .23.24.0.28.22   AR -> P1r.24 .  .25.26.0.28.22   AR -> P2r.26 .  .28.29.0.20.28   Zi -> AR.29 .  .30.31.0.28.22   AR -> P1i.31 .  .32.35.0.28.22   AR -> P2i.35 .  .40.40.1.20.31   "goto" 01.40 (complex multiply)                        Add position to Z^2rt:                        Zr = Zr + Cr.40 .  .41.42.1.23.28   Cr -> AR.42 .  .45.46.1.20.29   AR += 20.01 (ResultR / Zr).46 .  .49.50.1.28.20   AR -> 20.01                        Zi = Zi + Ci.50 .  .52.53.1.23.28   Ci -> AR.53 .  .56.57.1.20.29   AR += 20.00 (ResultI / Zi).57 .  .60.61.1.28.20   AR -> 20.00                        if |Zi| > 2 goto ot.61 .  .64.65.2.20.28   |Zi| -> AR.65 .  .66.67.3.02.29   Subtract two.66   +051yv85          Two shifted.67 .  .69.70.0.22.31   Test AR sign.70 .  .71.96.0.00.00   if AR >= 0 goto ot                        else continue on                        if |Zr| > 2 goto ot.71 .  .73.74.2.20.28   |Zr| -> AR.74 .  .75.76.3.02.29   Subtract two.75   +051yv85          Two shifted.76 .  .78.79.0.22.31   Test AR sign.79 .  .80.96.0.00.00   if AR >= 0 goto ot                        else continue on                        ct = ct + 1.80 .  .82.83.1.23.28   ct -> AR.83 .  .84.85.1.02.29   AR += 1.84   +0000001          .85 .  .86.87.1.28.23   AR -> ct                        if ct > limit goto in.87 .  .88.89.3.02.29   Subtract limit.88   +0000011           Limit 12.89 .  .91.92.0.22.31   Test AR sign.92 .  .93.94.0.00.00   if AR >= 0 goto in.93 .  .94.18.0.00.00   else loopin:                     Point is IN.94 .  .95.17.0.02.28   Eights -> AR; GOTO tp.95   +0000000          ot:                     Point is OUT.96 .  .98.99.6.23.25 - Ct -> ID1.99 .  .10.14.1.26.31   Shift R 4.14 .  .16.17.0.25.28   ID0 -> ARtp:.17 .  .19.18.0.20.31   RETURN<BLOCK># Bendix subroutine - Complex Multiplication# Prepared by: D. Stein, S. H. Lewis #1205# Date: 3-13-1957# Line: 01# Multiplication#   Calculates:#       (x + yi) = (a + bi) * (c + di)#   Entry:  40#   Exit:   38#   Input:#      10^-2d -> 22.00#      10^-2c -> 22.01#      10^-2b -> 22.02#      10^-2a -> 22.03#      Return Command#           Normal 21.02#           Overflow 21.03#   Output:#      10^-2y -> 20.00#      10^-2x -> 20.01## https://rbk.delosent.com/allq/Q5531.pdf Page 53# Dave Green archive: David-Green-Files\kimpel\1205A.G15# Corrections to the bendix publications are noted in# comments, these were in the David Green Files## Multiplication seems to work# Division untested.## Transcribed: Bill Kuker 3/13/2025## .40 .  .42.44.6.22.25   ID(1):=22.02  =(10^-2)b.44 . u.46.47.0.22.24   MQ(1):=22.01  =(10^-2)c.47 .  .56.u4.0.24.31   PN = (10^-4)bc.u4 .  .u6.02.4.26.20   20.02.03:=PN(0.1).02 .  .04.06.6.22.25   ID(1):=22.00  =(10^-2)d.06 . u.08.09.0.22.24   MQ(1):=22.03  =(10^-2)a.09 .  .56.66.0.24.31   PN = (10^-4)ad.66 .  .68.70.4.26.21   21.00.01:=PN(0.1).70 .  .72.76.5.21.26   PN(0.1):=21.00.01.76 .  .78.80.5.20.30   PN:=PN+20.02.03  =(10^-4)(ad+bc).80 .  .82.84.5.26.20   20.02.03:=PN(0.1).84 .  .86.88.4.20.25   ID(0.1):=20.02.03.88 . u.90.91.0.01.24   MQ(1):=01.89  =10^2(2^-7).89   +w800000              10^2(2^-7).91 .  .10.01.0.24.31   PN:=(10^-2)(2^-7)(ad+bc)# Typo?# From Scan:#01 .  .16.18.?.??.??   2^?? *? |PN| -> PN0,1+# From David Green:.01 . u.16.18.6.26.30   PN:=(10^-2)(ad+bc).18 . u.21.22.2.26.20   20.00:=PN(1)  =(10^-2)y.22 .  .24.26.0.23.31   clear (even).26 . u.28.28.0.22.25   ID(1):=22.03  =(10^-2)a.28 . u.30.31.0.22.24   MQ(1):=22.01  =(10^-2)c.31 .  .56.92.0.24.31   =(10^-4)ac.92 .  .94.96.4.26.20   20.02.03:=PN(0.1).96 .  .98.u0.6.22.25   ID(1):=22.02  =(10^-2)b.u0 .  .u4.05.6.22.24   MQ(1):=22.00  =(10^-2)d.05 .  .56.62.0.24.31   =(10^-4)bd# Typo?#From Scan:#62 .  .66.68.0.2?.2?   10^-4bd * (PN0,1) -> 21.00,01# From David Green:.62 .  .64.68.4.26.21   21.00.01:=PN(0.1).68 .  .70.74.5.20.26   PN(0.1):=20.02.03.74 .  .76.78.7.21.30   PN:=PN-21.00.01.78 .  .80.82.5.26.21   21.00.01:=PN(0.1).82 .  .84.86.4.21.25   ID(0.1):=21.00.01.86 .  .89.93.0.01.24   MQ(1):=01.89  =10^2(2^-7).93 .  .10.03.0.24.31   # Typo?#From Scan - Very clear#.03 .  .18.20.6.26.30#From David Green.03 . u.18.20.6.26.30   .20 . u.22.24.0.26.20   20.01:=PN(1)  =(10^-2)x.24 .  .26.33.0.29.31   overflow?.33 . u.35.36.0.21.28   no:  AR:=21.02.34 . u.36.36.0.21.28   yes: AR:=21.03.36 .  .38.38.0.31.31   execute AR (exit)# Complex Division .35 .  .38.38.0.23.31   clear.38 .  .40.41.2.22.28   AR:=21.00  =(10^-2)abs(d).41 . u.43.43.0.28.20   20.02:=AR.43 .  .45.48.2.22.28   AR:=22.01  =(10^-2)abs(c).48 .  .50.51.3.20.29   AR:=AR-20.02  =abs(c)-abs(d).51 .  .53.54.0.22.31   is AR negative?.54 .  .57.83.0.22.25   +ve: (c>=d) ID(1):=22.01  =(10^-2)c.55 . u.61.63.2.22.22   -ve: (c<d)  22.01-00:=22.00-03.63 . u.65.65.3.22.28   AR:=-22.00.65 . u.67.69.3.22.30   PN(0):=22.02.69 . u.71.72.1.28.22   22.02:=AR.72 .  .76.77.1.26.22   22.00:=PN(0).77 .  .81.83.0.22.25   ID(1):=22.01.83 .  .84.87.6.22.26   PN(1):=22.00 tva.87 .  .56.39.5.25.31   divide.39 . u.41.45.0.24.21   21.00:=MQ(0).45 .  .48.50.6.21.25   ID(1):=21.00 tva.50 .  .52.61.6.22.24   MQ(1):=22.00 tva.61 .  .56.10.0.24.31   multiply.10 .  .12.16.4.26.20   20.00.01:=PN(0.1).16 .  .19.19.0.23.31   clear.19 .  .21.23.0.22.25   ID(1):=22.01.23 .  .02.29.0.26.31   shift 1 bit.29 .  .32.37.4.25.20   20.02.03:=ID(0.1).37 . u.42.42.5.20.30   PN(0.1):=20.00.01+20.02.03.42 .  .44.46.5.26.22   22.00.01:=PN(0.1)  =denominator.46 .  .48.52.6.21.25   ID(1):=21.00 tva.52 .  .54.57.6.22.24   MQ(1):=22.02 tva.57 .  .56.07.0.24.31   multiply.07 .  .10.11.4.26.20   20.00.01:=PN(0.1).11 .  .14.14.0.23.31   clear.14 . u.16.17.0.22.25   ID(1):=22.03.17 .  .02.21.0.26.31   shift.21 . u.24.25.4.25.20   20.02.03:=ID(0.1).25 . u.30.32.5.20.30   PN(0.1):=20.02.03+20.00.01.32 .  .34.49.5.26.20   20.02.03:=PN(0.1).49 .  .52.58.4.20.25   ID(0.1):=20.02.03.58 .  .81.99.1.01.24   MQ(1):=01.88  =10^-2.81   -zx70u3y          .99 .  .58.53.0.24.31   multiply.53 . u.56.56.4.26.20   20.02.03:=PN(0.1).56 .  .60.64.4.22.25   ID(0.1):=22.00.01  =denominator.64 .  .66.15.4.20.26   PN(0.1):=20.02.03.15 .  .58.90.5.25.31   divide.90 .  .92.94.1.24.27   test for zero.94 .  .96.98.6.24.20   yes: 20.01:=MQ(0) tva.95 .  .99.36.0.21.28   no:  21.03:=AR  (command).98 .  .u0.00.6.21.25   ID(1):=21.00 tva.00 .  .03.13.0.22.24   MQ(1):=22.03.13 .  .56.79.0.24.31   multiply.79 .  .82.85.4.26.20   20.02.03:=PN(0.1).85 .  .88.97.6.22.25   ID(1):=22.02 tva.97 .  .02.u1.0.26.31   shift 6 bits.u1 . u.u4.04.4.25.22   22.02.03:=ID(0.1).04 .  .06.08.5.22.26   PN(0.1):=22.02.03.08 .  .10.12.7.20.30   PN(0.1):=PN-20.02.03.12 .  .16.59.5.26.21   21.00.01:=PN(0.1).59 .  .60.73.4.21.25   ID(0.1):=21.00.01.73 .  .81.u3.1.01.24   MQ(1):=01.81  =10^-2.u3 .  .58.60.0.24.31   multiply.60 .  .64.67.4.26.21   21.00.01:=PN(0.1).67 . u.70.71.4.22.25   ID(0.1):=22.00.01  =denominator.71 . u.74.75.4.21.26   PN(0.1):=21.00.01  =no.75 .  .58.27.5.25.31   divide.27 . u.29.30.0.24.20   20.00:=MQ(0)  =(10^-2)y.30 .  .32.33.1.24.27   MQ(1) zero?<BLOCK>#define ILOW d-0.0110#define IHIGH d0.0110#define ISTEP d0.0040#define RLOW d-0.021#define RHIGH d0.0052#define RSTEP d0.0016                        Reset Imaginary Position.00 .  .01.02.1.00.28   Imaginary Start -> AR.01   -02x0y56              .02 .  .00.03.1.28.23   AR -> Cinl:                     Loop start for a new line                        Print a newline.03 .  .04.05.1.00.28   AR = Format Newline.04   +4400000          F3 Format code, 0 digit, CR end.05 .  .03.06.1.28.03   03:03 = AR.06 .  .08.07.0.08.31   Output AR to typewriter.07 .  .07.07.0.28.31   Wait for IOReady                        Set up single digit format code.08 .  .09.10.1.00.28   AR = Format Digit.09   +0400000          Format code, 1 digit, end.10 .  .03.11.1.28.03   03:03 = AR                        ci = ci + d0.0040.11 .  .00.12.1.23.28   Ci -> AR.12 .  .13.14.1.00.29   AR += Stepis:.13   +010624y            Imaginary Step.14 .  .00.15.1.28.23   AR -> Ci                        if ci > d0.0110 then HALT.15 .  .00.16.1.23.28   Ci -> AR.16 .  .17.18.3.00.29   Subtract end point.17   +02x0y56            .18 .  .20.19.0.22.31   Test AR sign.19 .  .21.48.0.16.31   if AR >= 0 HALT                        else continue on                        Reset Real Position.20 .  .21.22.1.00.28   Real Start -> AR.21   -0560419             .22 .  .01.23.1.28.23   AR -> Crnc:                     Next Character loop start                                                Cr = Cr + d0.0016.23 .  .25.26.1.23.28   Cr -> AR.26 .  .27.28.1.00.29   AR += Steprs:.27   +0068xv9            .28 .  .29.30.1.28.23   AR -> Cr###CALL FRACTAL CODE.30 . w.31.00.2.21.31   GOSUB 2.0 Line 2 instruction zero#.%2 .  .L1.L2.0.00.28   AR = ones#.   +1111111            F3 Format code, 0 digit, CR endtp:                     Print out value in AR.31 .  .33.34.0.08.31   Output AR to typewriter.34 .  .34.34.0.28.31   Wait for IOReady                        If Cr > d0.0052                            goto nl - Next Line                        else                            goto nc - Next Character.35 .  .37.38.1.23.28   Cr -> AR.38 .  .39.40.3.00.29   Subtract end point.39   +0154w98            .40 .  .42.43.0.22.31   Test AR sign.43 .  .44.03.0.00.00   if AR >= 0 goto nl.44 .  .45.23.0.00.00   else goto ncbg:                     MAKE IT BIGGER  .48 .  .13.49.0.00.25   is -> ID.49 .  .02.50.1.26.31   Shift ID 1 bit right.50 .  .13.52.0.25.00   ID -> is.52 .  .27.53.0.00.25   is -> ir.53 .  .02.54.1.26.31   Shift ID 1 bit right.54 .  .27.00.0.25.00   ID -> ir
answeredOct 13 at 16:20
Bill Kuker's user avatar
\$\endgroup\$
6
\$\begingroup\$

GLSL - 225 bytes:

void main(){vec2 c=gl_FragCoord.xy/iResolution.y*4.-2.,z=c,v;for(int i=0;i<99;i++){z=vec2(z.x*z.x-z.y*z.y,2.*z.x*z.y)+c;if(length(z)>2.&&v.y<1.)v=vec2(float(i)/99.,1.);}gl_FragColor=(v.y<1.)?vec4(v,v):texture2D(iChannel0,v);}

Defining variables in the code (242 bytes):

uniform vec3 r;uniform sampler2D t;void main(){vec2 c=gl_FragCoord.xy/r.y*4.-2.,z=c,v;for(int i=0;i<99;i++){z=vec2(z.x*z.x-z.y*z.y,2.*z.x*z.y)+c;if(length(z)>2.&&v.y<1.)v=vec2(float(i)/99.,1.);}gl_FragColor=(v.y<1.)?vec4(v,v):texture2D(t,v);}

See it in ShaderToy

Mandelbrot Golf

This requires a suitable palette texture be loaded asiChannel0. (The colouring here is from the "random pixel" texture on ShaderToy).

answeredMar 9, 2014 at 5:44
nneonneo's user avatar
\$\endgroup\$
3
  • \$\begingroup\$Variable declarations should be counted too, unless they can be auto-generated from the code. (color scheme is fine if it's only available as an external setting)\$\endgroup\$CommentedMar 10, 2014 at 6:40
  • \$\begingroup\$@MarkJeronimus: For the ShaderToy environment, these variables are fixed. Otherwise, for standard shaders, I would have picked shorter variable names.\$\endgroup\$CommentedMar 10, 2014 at 7:25
  • \$\begingroup\$Is this the fastest of them all?\$\endgroup\$CommentedAug 3, 2015 at 7:15
6
\$\begingroup\$

Octave (212 136 bytes)

(Now including some ideas due to @ChrisTaylor.)

[y,x]=ndgrid(-2:.01:2);z=c=x+i*y;m=c-c;for n=0:99;m+=abs(z)<2;z=z.^2+c;end;imagesc(m);colormap([hsv(128)(1+mod(0:79:7890,128),:);0,0,0])

With whitespace:

[y,x] = ndgrid(-2:.01:2);z = c = x + i*y;m = c-c;for n=0:99    m += abs(z)<2;    z = z.^2 + c;endimagesc(m)colormap([hsv(128)(1+mod(0:79:7900,128),:);          0,0,0])

Output:

Mandelbrot steps to abs(z)>2

To convert to Matlab, change "m+=abs(z)<2" to "m=m+(abs(z)<2)". [+3 bytes]

To make the aspect ratio 1:1, add ";axis image". [+11 bytes]

My first answer (212 bytes):

[x,y]=meshgrid(-2:.01:2);z=c=x+i*y;m=0*e(401);for n=0:99;m+=abs(z)<2;z=z.^2+c;endfor;t=[0*e(1,7);2.^[6:-1:0]];[s{1:7}]=ndgrid(num2cell(t,1){:});t=1+sum(cat(8,s{:}),8);imagesc(m);colormap([hsv(128)(t(:),:);0,0,0])
answeredMar 8, 2014 at 20:38
aschepler's user avatar
\$\endgroup\$
6
  • \$\begingroup\$There's probably a shorter way to get a discontinuous colormap....\$\endgroup\$CommentedMar 8, 2014 at 20:40
  • \$\begingroup\$Yes, much better now.\$\endgroup\$CommentedMar 9, 2014 at 1:13
  • \$\begingroup\$+1 nice and concise solution. But your aspect ratio is not 1:1 (cf. rule n°2: output should be square).\$\endgroup\$CommentedMar 10, 2014 at 7:39
  • \$\begingroup\$Fixing the aspect ratio will take 11 more bytes: append ";axis image". Is that required to qualify?\$\endgroup\$CommentedMar 10, 2014 at 14:39
  • \$\begingroup\$i think it was just me nitpicking :) , the OP doesn't seem to have a problem with it since he didn't say anything.\$\endgroup\$CommentedMar 11, 2014 at 7:46
6
\$\begingroup\$

Excel VBA,251246224223 221 bytes

Saved 5 bytes thanks to ceilingcatSaved 23 bytes thanks to Taylor Scott

Sub mD=99For x=1To 4*DFor y=1To 4*Dp=0q=0For j=1To 98c=2*p*qp=p^2-q^2-2+(x-1)/Dq=c+2+(1-y)/DIf p^2+q^2>=4Then Exit ForNextj=-j*(j<D)Cells(y,x).Interior.Color=Rnd(-j)*1E6*j/DNext y,xCells.RowHeight=48End Sub

Output:

Output with D = 99

I made a version that did this a long time ago but it had a lot of extras like letting the user pick the basic color and easy-to-follow math. Golfing it way down was an interesting challenge. TheColor method uses1E6 as a means to get a wide range of colors since the valid colors are0 to2^24. Setting it to10^6 gave nice contrast areas.

Explanation / Auto-Formatting:

Sub m()    'D determines the number of pixels and is factored in a few times throughout    D = 99    For x = 1 To 4 * D    For y = 1 To 4 * D        'Test to see if it escapes        'Use p for the real part and q for the imaginary        p = 0        q = 0        For j = 1 To 98            'This is a golfed down version of complex number math that started as separate generic functions for add, multiple, and modulus            c = 2 * p * q            p = p ^ 2 - q ^ 2 - 2 + (x - 1) / D            q = c + 2 + (1 - y) / D            If p ^ 2 + q ^ 2 >= 4 Then Exit For        Next        'Correct for no escape        j = -j * (j < D)        'Store the results        'Rnd() with a negative input is deterministic        'This is what gives us the distinct color bands        Cells(y, x).Interior.Color = Rnd(-j) * 1000000# * j / D    Next x, y    'Resize for pixel art    Cells.RowHeight = 48End Sub

I also played around withD=999 andj=1 to 998 to get a much larger and more precise image. The results are irrelevant to the challenge because they're way too large but theyare neat.

D=999

answeredSep 26, 2017 at 20:39
Engineer Toast's user avatar
\$\endgroup\$
5
  • \$\begingroup\$@ceilingcat Thanks. That was a carryover from my original which had specialized functions for complex number math.\$\endgroup\$CommentedSep 27, 2017 at 12:07
  • \$\begingroup\$Does it really need to be >=4 or can you get away with >4? Also, can replacej<99 withj<D.\$\endgroup\$CommentedSep 27, 2017 at 22:38
  • \$\begingroup\$@EngineerToast you can drop the() from the sub name,you should change(j<99) to(j<d) and you can, for the purpose of making square cells use onlyCells.RowHeight=48 in place of theCells.RowHeight=9,Cells.ColumnWidth=1 - this does making messing around with your output more difficult but has been accepted as valid by the community -\$\endgroup\$CommentedSep 28, 2017 at 5:03
  • 1
    \$\begingroup\$@TaylorScott I remember theRowHeight trick from the VBA tips post and had meant to integrate it after I got all my pretty pictures. That was a nice chunk'o'bytes, thanks.\$\endgroup\$CommentedSep 28, 2017 at 12:31
  • \$\begingroup\$I believe that you can get away with removing another byte by swapping2^20 with1E6\$\endgroup\$CommentedOct 8, 2017 at 17:55
6
\$\begingroup\$

PostScript,290285282271 261 bytes

Screenshot:

screeshot

Golfed code:

-2 .01 2{/a exch def -2 .01 2{/b exch def/x 0 def/y 0 def 0 1 99{/i exch def x x mul y y mul add 4 ge{i log 2 div 1 1 sethsbcolor a 2 add 100 mul b 2 add 100 mul 1 1 rectfill exit}if/x x x mul y y mul sub a add/y 2 x mul y mul b add def def}for}for}for showpage

Ungolfed code:

-2 .01 2 {    /a exch def    -2 .01 2 {        /b exch def        /x 0 def        /y 0 def        0 1 99 {           /i exch def                       % iteration count           x x mul y y mul add 4 ge {               i log 2 div 1 1 sethsbcolor   % rainbow colors outside               a 2 add 100 mul               b 2 add 100 mul 1 1 rectfill               exit           } if           /x x x mul y y mul sub a add           /y 2 x mul y mul b add           def def       } for    } for} forshowpage
answeredDec 24, 2021 at 21:06
Thomas Fritsch's user avatar
\$\endgroup\$
1
  • \$\begingroup\$Golfed some more for 198 bytes:[/d{-2 .01 2}(]){exch def}([){mul}/p{add}/s{2 p 100[}/q{x x[y y[}>>begin d{/a]d{/b]0/x 0/y]]0 1 99{q p 4 ge{log .5[1 1 sethsbcolor a s b s 1 1 rectfill exit}if q sub a p 2 x[y[b p/y]/x]=}for}for}for\$\endgroup\$CommentedMay 5, 2022 at 16:51
5
\$\begingroup\$

gnuplot 110 (105 without newlines)

Obligatory gnuplot entry. It's been done countless times but this one is from scratch (not that it's difficult). I like howgnuplot golfs its commands intrinsically :)

f(z,w,n)=abs(z)>2||!n?n:f(z*z+w,w,n-1)se vi mapse si sqse isos 256sp [-2:2] [-2:2] f(0,x+y*{0,1},99) w pm

ungolfed:

f(z,w,n)=abs(z)>2||n==0?n:f(z*z+w,w,n-1)set view mapset size squareset isosamples 256splot [-2:2] [-2:2] f(0,x*{1,0}+y*{0,1},99) with pm3d

However, I'm DEEPLY disappointed at the entry of complex numbers.x*{1,0}+y*{0,1} must be the saddest existing way of constructing a complex number.

Oops, the image:gnuplot mandelbrot

Set isosamples higher for better resolution. We could also sayunset tics andunset colorbox for a pure image, but I think this version qualifies just fine.

answeredMar 9, 2014 at 12:36
orion's user avatar
\$\endgroup\$
2
  • \$\begingroup\$Bet it's copy/pasta from the first google hit "gnuplot mandel". For starters,*{1,0} is unity and is more like a code-bowling way of saying*1, and probably can be dropped. (untested)\$\endgroup\$CommentedMar 10, 2014 at 6:26
  • 1
    \$\begingroup\$No it's not a copy-paste. It's a very straight forward formula and it wasn't even necessary to search for it. However, I did find the pages you get with that search when I was looking for a better way of initializing complex numbers (their implementation is different, well, as different as it can be in this case). Thanks for the tip about the real part, it works. Fixing.\$\endgroup\$CommentedMar 10, 2014 at 7:53
5
\$\begingroup\$

Floater, 620 pixels

A language I made up when I got inspired by my own challenge, as well as from the esoteric language Piet.

enter image description here

answeredMar 28, 2014 at 22:13
Mark Jeronimus's user avatar
\$\endgroup\$
1
  • 3
    \$\begingroup\$Link to a language and description of the code? Or actually, what is the code?\$\endgroup\$CommentedSep 26, 2017 at 3:20
5
\$\begingroup\$

TI-BASIC (TI-83), 103111118 bytes

-7 bytes fromAnsmanipulation and better variable modifications
-8 bytes from removing usage of theA andB variables

1.88→Xmax                 ; Set the graph bounds to something⁻Ans→Xmin                 ;   reasonable so that it looks nice1.24→Ymax⁻Ans→YminAxesOffFor(X,Xmin,Xmax,ΔX        ; Loop over each pixel on the graphFor(Y,Ymin,Ymax,ΔYDelVar NX+Yi→C            ; Reset N to 0 and set the constantWhile N<20 and 2≥abs(Ans  ; Loop for at most 20 iterations or until                          ;   the number's magnitude is > 2IS>(N,0:                  ; Increment N without updating AnsAns²+C                    ; Put the next number in AnsEndIf N≥20                   ; Draw a dot if the coordinate did notPt-On(X,Y                 ;   result in a diverging seriesEndEnd

Graph result

A simple nested loop with the standard\$z_{n+1}=z_n^2+c\$ function for the iterations.

The coordinates\$(X,Y)\$ are converted to a complex number\$X+Yi\$ to allow for complex arithmetic.

X-bounds of[-2,2] and Y-bounds of[-1.32,1.32] would result in a closer graph, but the step forY would end up being an ugly and longer fraction of\$\frac{33}{775}\$ (.04258) instead of a clean\$\frac{1}{20}\$ (.05), so I opted for the bounds used instead.
The original answer used X-bounds of[-2.35,2.35] and Y-bounds of[-1.55,1.55] so that each pixel was a step of\$\frac{1}{20}\$, but the new answer has each pixel as a step of\$\frac{1}{25}\$.
This results in a closer and more detailed graph of the set.

TI-BASIC Quirks:
DelVar N ends at the variable token, so a newline isn't needed.
The effective code is:

DelVar NX+Yi→C

IS>(N,0: uses the same amount of tokens asN+1→N, but it doesn't updateAns.
This allows incrementingN while still preservingAns as the current sequence number.


Note: TI-BASIC is a tokenized language. Character count doesnot equal byte count.

Program size is equal to\$MEM\: byte\: count - program\: name\: length - 9\: bytes\$.

While the image shows me using a TI-84+ calculator, all of the tokens used are present in the TI-83 set of tokens, so this program can be used there as well.

answeredMar 17 at 17:00
absoluteAquarian's user avatar
\$\endgroup\$
1
  • 1
    \$\begingroup\$you can skipA andB :2.35→Xmax:-Ans→Xmin ... For(X,Xmin,Xmax,ΔX (they are 2 bytes each)\$\endgroup\$CommentedMar 25 at 10:12

Your Answer

More generally…

  • …Please make sure to answer the question and provide sufficient detail.

  • …Avoid asking for help, clarification or responding to other answers (use comments instead).

Draft saved
Draft discarded

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.