# Question
Title: Valid python function invocation signatures
## Background

In Python, function arguments are defined within the parentheses following the function name in the function definition. There are different ways to present function arguments, and they can be categorised into three types:

1. Positional-only arguments,
2. Positional or keyword arguments, and
3. Keyword-only arguments

Each of these may also have a default value.

### Example function (de)composition

Let's break down an example function definition:

```
def fn(q: str, /, z: int, x: float, b: int = 1, *, c: int = 1) -> None:
    ...

```
1. Positional-only argument (`q: str`): The parameter `q` is a positional-only argument because it is defined before the slash (`/`) in the argument list. It means that this argument can only be passed by its position and not by using a keyword. For example, you can call the function as `fn("hello", 2.5, 3)`.
2. Positional or keyword argument (`z: int`, `x: float`): The parameters `z` and `x` are defined after the slash (`/`), but they are not marked as keyword-only arguments. It means that these arguments can be passed either by their position or by using their corresponding keyword. For example, you can call the function as `fn("hello", 5, x=2.5)` or `fn("hello", z=5, x=2.5)`.
3. Default argument (`b: int = 1`): The parameter `b` has a default value of `1`. It means that if no argument is provided for `b` when calling the function, it will automatically be assigned the default value. For example, you can call the function as `fn("hello", 5, 2.5, c=3)` or `fn("hello", 5, 2.5, 2)`.
4. Keyword-only argument (`c: int = 1`): The parameter `c` is a keyword-only argument because it is defined after the asterisk (`*`). It means that this argument can only be passed by using its corresponding keyword and cannot be passed by position. For example, you can call the function as `fn("hello", 5, 2.5, c=3)`.
5. Return type (`-> None`): The `-> None` annotation specifies the return type of the function. In this case, the function is expected to return `None`. This can be ignored.

N.B. Non-default positional arguments can not come after a default argument. That is, `def fn_bad(a: int = 1, / b: int, *, c: int = 1, d: str) -> None:...`  is invalid due to `b`. `b` is a positional or keyword argument but it comes after a defaulted positional argument. `d` is valid however since this is a keyword only argument and their order does not matter.

### Valid method invocations

There are 14 possible ways to call the function `fn` based on its function definition. Here are all the combinations:

1. `fn("hello", 2, 3.0)`
2. `fn("hello", 2, 3.0, 1)`
3. `fn("hello", 2, 3.0, c=1)`
4. `fn("hello", 2, x=3.0)`
5. `fn("hello", 2, x=3.0, b=1)`
6. `fn("hello", 2, x=3.0, c=1)`
7. `fn("hello", z=2, x=3.0)`
8. `fn("hello", z=2, x=3.0, b=1)`
9. `fn("hello", z=2, x=3.0, c=1)`
10. `fn("hello", 2, 3.0, b=1, c=1)`
11. `fn("hello", z=2, x=3.0, b=1, c=1)`
12. `fn("hello", z=2, x=3.0, b=1, c=1)`
13. `fn("hello", 2, x=3.0, b=1, c=1)`
14. `fn("hello", 2, 3.0, 1, c=1)`

In the above examples, `"hello"` is passed as the value for the positional-only argument `q`, `2` is passed for the positional or keyword argument `z`, `3.0` is passed for the positional or keyword argument `x`, `1` is passed for the default argument `b`, and `1` is passed for the keyword-only argument `c`. The arguments can be passed either by position or by using their corresponding keywords, depending on the argument type.

Keyword arguments are order independent, that is `fn("hello", b=1, c=1, x=3.0, z=2)` and `fn("hello", x=3.0, b=1, z=2, c=1)` are congruent.

Invalid invocation examples include: `fn("hello", 2, x=3.0, 1)` since a positional argument comes after a keyword argument, and `fn("hello", z=2, b=1, c=1)` due to missing required argument `x`

## The Challenge

Create a script which generates all possible python function invocation signatures, describing the function arguments as their argument name, if it is passed as a keyword argument, and the type of the argument.

To make things fair across languages; let's say: the inputs are three lists; `positional_only`, `positional_or_keyword` and `keyword_only` where their elements describe the python function's arguments in the format of `[string name, string type, bool has_default]` Or some similar data structure. These inputs are not counted towards the character count. The output can be any intelligible format.

(N.B. This challenge disregards any function which contains args or kwargs catch all variables (`*foo`, or `**bar`))

## Test cases (need more)

```
# def fn(q: str, /, z: int, x: float, b: int = 1, *, c: int = 1) -> None:
positional_only = [["q", "str", false]]
positional_or_keyword = [["z", "int", false], ["x", "float", false], ["b", "int", true]]
keyword_only =[["c", "int", true]]

generate_signatures(positional_only, positional_or_keyword, keyword_only)

# returns:
[
    [(None, 'str'), ('x', 'float'), ('z', 'int')],
    [(None, 'str'), ('c', 'int'), ('x', 'float'), ('z', 'int')],
    [(None, 'str'), ('b', 'int'), ('x', 'float'), ('z', 'int')],
    [(None, 'str'), ('b', 'int'), ('c', 'int'), ('x', 'float'), ('z', 'int')],
    [(None, 'str'), (None, 'int'), ('x', 'float')],
    [(None, 'str'), (None, 'int'), ('c', 'int'), ('x', 'float')],
    [(None, 'str'), (None, 'int'), ('b', 'int'), ('x', 'float')],
    [(None, 'str'), (None, 'int'), ('b', 'int'), ('c', 'int'), ('x', 'float')],
    [(None, 'str'), (None, 'int'), (None, 'float')],
    [(None, 'str'), (None, 'int'), (None, 'float'), ('c', 'int')],
    [(None, 'str'), (None, 'int'), (None, 'float'), ('b', 'int')],
    [(None, 'str'), (None, 'int'), (None, 'float'), ('b', 'int'), ('c', 'int')],
    [(None, 'str'), (None, 'int'), (None, 'float'), (None, 'int')],
    [(None, 'str'), (None, 'int'), (None, 'float'), (None, 'int'), ('c', 'int')],
]

# def fn_2(a: int, b: int = 1, *, d: int, c:int = 1) -> None: ...
positional_only = []
positional_or_keyword = [["a", "int", false], ["b", "int", true]]
keyword_only =[["d", "int", false], ["c", "int", true]]

generate_signatures(positional_only, positional_or_keyword, keyword_only)

# returns
[
    [('a', int), ('d', int)],
    [('a', int), ('c', int), ('d', int)],
    [('a', int), ('b', int), ('d', int)],
    [('a', int), ('b', int), ('c', int), ('d', int)],
    [(None, int), ('d', int)],
    [(None, int), ('c', int), ('d', int)],
    [(None, int), ('b', int), ('d', int)],
    [(None, int), ('b', int), ('c', int), ('d', int)],
    [(None, int), (None, int), ('d', int)],
    [(None, int), (None, int), ('c', int), ('d', int)]
]

# def fn_3(a: int, b:int = 1, /, q:int = 1, *, r: int): ...
positional_only = [(None, 'int', False), (None, 'int', True)]
positional_or_keyword = [('q', 'int', True)]
keyword_only = [('r', 'int', False)]

generate_signatures(positional_only, positional_or_keyword, keyword_only)

# returns
[
    [(None, int), ('r', int)],
    [(None, int), ('q', int), ('r', int)],
    [(None, int), (None, int), ('r', int)],
    [(None, int), (None, int), ('q', int), ('r', int)]
    [(None, int), (None, int), (None, int), ('r', int)]
]

```

The way these outputs are structured is a tuple of argument name and type. If the argument name is `None` then the argument is a positional argument.

That is `(None, int)` is a positional argument (e.g. `fn(1)`) whereas `("x", int)` is a keyword argument e.g. `fn(x=1)`.

`[(None, int), (None, int), ('c', int), ('d', int)]` describes a function call of `fn(1, 1, c=1, d=1)`

### Testing your outputs

A neat way to check is go to vscode.dev, install the python plugin, convert your list of lists to function invocations and paste it into a new document. The static analyser will tell you which are (in)valid. I think there is a way to run pyright in code, but this was quicker:

```
for i, sig in enumerate(sigs):
    print(f"# {i} - {sig}")
    s = 'fn('
    for arg in sig:
        if arg[0] is not None:
            s += f"{arg[0]}="
        typ = arg[1]
        val = None
        if typ == 'str':
            val = "\"str\""
        elif typ == 'int':
            val = "1"
        elif typ == 'float':
            val = "1.0"
        else:
            val = "UNKNOWN"
        s += f"{val},"
    print(f"{s})\n")

```

### Bonus challenge

Given `fn_a(...)` and `fn_b(...)` determine any ambiguous valid signatures to these methods.

e.g. `fn_a(x: str, y: int) -> None: ...` `fn_b(z: str, /, x: int) -> None: ...` are distinct for `fn(x="foo", y=1)` and `fn(x="foo", z=1)` but conflict for the signature `fn("foo", 1)` That is, both functions contain the valid signature of `[(None, "str"), (None, "int")]`

# Answer
> 1 votes
# Python3, 302 bytes

```
from itertools import*
V=lambda v:not any(not v[i][0] and v[i-1][0]for i in range(len(v))if i)
def f(a,b,c):
 P=product(*[*[[(None,t)]+[[]]*k for n,t,k in a],*[[(None,t),(n,t)]+[[]]*k for n,t,k in b],*[[(n,t)]+[[]]*k for n,t,k in c]])
 return[*map(eval,{str(K)for i in P if V(K:=[j for j in i if j])})]

```

Try it online!

For those interested, here is a larger solution which parses the function signature:

```
import ast
from itertools import*
A=lambda x:x.annotation.id
H=lambda v:not any(not v[i][0] and v[i-1][0]for i in range(len(v))if i)
def f(s):
 a=ast.parse(s).body[0].args
 V=['kw_defaults','defaults']
 d=sum(len(getattr(a,i))for i in V)
 l=sum(len(i)for j in a._fields if(i:=getattr(a,j))and j not in V)
 K=0
 P=product(*[*[[(None,A(i))]for i in a.posonlyargs if(K:=K+1)],*[[(None,A(i)),(i.arg,A(i))]+[[]]*(((K:=K+1))>l-d)for i in a.args],*[[(i.arg,A(i)),[]]for i in a.kwonlyargs]])
 return[K for i in P if H(K:=[j for j in i if j])]

```

Try it online!

# Answer
> 0 votes
# Haskell, 208 bytes

```
import Data.List
y=elem '='
o(a:b)=[c++d|d<-o b,c<-[a]:[[]|y a]];o[]=[[]]
s s=inits s`zip`tails s
i(p,a,n)=nub[(map(\\"=")d,map((++"=").(\\"="))g)|(b,c)<-s$a,(d,e)<-s$p++b,all y e,f<-o$c++n,g<-permutations f]

```

Try it online!

The idea here is to split the semipositionals into positional or named. The default-having positionals can be omitted when trailing all mere positionals. The named can be omitted when default-having. The named can be freely permuted, while the positionals cannot.

# Answer
> 0 votes
# Charcoal, 68 bytes

```
≔⁺θηυＦ…·ＬΦθ¬⊟ιＬυ«≔⁻⁺ηζ…υιε≔Φε§κ²δＥＸ²Ｌδ⭆¹⁺Ｅ…υι⟦ω§ξ¹⟧Ｅ⁺⁻εδΦδ﹪÷κＸ²π²…ξ²

```

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

```
≔⁺θηυ

```

Get all of the positional arguments.

```
≔⁺θηυＦ…·↨¹Ｅθ¬⊟ιＬυ«

```

Count the number of mandatory positional-only parameters and loop from there up to all positional parameters.

```
≔⁻⁺ηζ…υιε

```

Get the remaining named arguments.

```
≔Φε§κ²δ

```

Get those that are optional.

```
ＥＸ²Ｌδ⭆¹⁺Ｅ…υι⟦ω§ξ¹⟧Ｅ⁺⁻εδΦδ﹪÷κＸ²π²…ξ²

```

For each possible combination of optional named parameters, concatenate the positional parameters and the mandatory named parameters with them.

---
Tags: code-golf, combinatorics, python, function
---


title: Interpret Volatile

text:
# Question
Title: Interpret Volatile
# Interpret Volatile

Volatile is a stack-based esolang made by A\_/a'\_'/A that only has 8 instructions and is turing complete. However, it is also non-deterministic... meaning that programs don't always give the same output. Your task is to interpret this language.

## Language specs

Taken from the esolangs page:

```
~: Push a random integer in any range of integers. Minimum range of 0 through 32768

+: Pop 2 values and push the sum of the 2 values

-: Like +, but subtracts

*: Multiply

/: Divide. 0-division will result in an error.

:: Duplicate the top of the stack

.: Output the top of the stack without popping it

(...): Execute ... inside a while loop when the top of the stack is not 0

```

Everything else is disregarded

## Input

*Note that these programs may randomly fail*

```
~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++.~:/:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/:::::::::::::::::::::::::::::::::+++++++++++++++++++++++++++++++++.~:/::::::::::++++++++++.

~:-.~:/+.(~:/+.)

~:-:/

```

## Output

```
73 102 109 109 112 45 33 120 112 115 109 101 34 11

0 1 2 3 4 5 6 7 8 9 ...

<Any Error Message>

```

More examples, as well as a reference implementation (use the second one, found under *(Another) python 3 interpreter*) can be found at https://esolangs.org/wiki/Volatile

## Scoring

This is code-golf, so shortest answer in bytes wins

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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 leaderboard snippet:

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

```

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

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

```
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><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><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```

# Answer
# 05AB1E, 35 bytes

```
"~:/.()"”žGÝΩ DŠéõq}÷ = [D_# }”#‡.V

```

Try it online!

Transpiles Volatile code to 05AB1E, then evals it. `*`, `+` and `-` can be left as-is. `:`, `.`, and `)` have direct one-byte equivalent. The other commands take a few bytes each. Unfortunately, 05AB1E does not crash on division by 0, so this is instead implemented by a conditional "quit if top of stack == 0".
> 7 votes

# Answer
# Julia 1.0, 334 bytes

```
a\b=push!(a,b)
√a=pop!(a)
v(q,s=[],l=0)=(i=1;
for c in q
!r=c==r
i+=1
!')' ? (l<1 && break;l-=1) :
!'(' ? (while s[end]!=0 v(q[i:end],s) end;l+=1) :
l>0 ? continue :
!'~' ? s\rand(Int) :
!'+' ? s\(√s+√s) :
!'-' ? s\(√s-√s) :
!'*' ? s\(√s*√s) :
!'/' ? s\(√s÷√s) :
!':' ? s\s[end] :
!'.' ? print(s[end]," ") : 0
end)

```

My first "interpreter" of any type, it was easier than I expected. I did some basic golfing, but there is probably room for more. I made it print a space after the output for . to mach to example output. The ungolfed version is in the header at the TIO link. Example usage `v("~:-:/")`.

+41 bytes to fix the bug Night2 pointed out by adding a loop counter. Now I see why transpiling is a good option. A good test case is `~:-.(~:/+.)(~:/+.())~:-.` with expected output `0 0`

Try it online!
> 4 votes

# Answer
# Runic Enchantments, ~~266~~ 264 bytes

```
DS͗{r;'ui[0[0y̤<<<<<?+f2,;$"!0/"?*7≠0:S͗\
RS͗}:'~=?!\:':=?!\:'+=?!\:'-=?!\:'/=?!/:'.=?!\:'*=?!\:';=?!;:')≠3*?04B͍:'(=?!S͗
U/lA`R耀`S͗/?7  :S͗/?+f1+S͗/?3  -S͗/?3     $ '$:S͗/?7  *S͗/
U\m(d*?"SO!"$;
{:'(=?!\:')=?!\R
~/?)0l{͗/?8 {͗l}͗/U
 \}͗21B͍

```

Try it online!

Due to limitations built into Runic, it can only support program lengths (and stack size) of ~501. Programs that are too large will simply fail. If the stack grows too large, it will error with `SO!` (wasn't required, but was better than silent termination; cost 24 bytes). If the program attempts to divide by 0, it will print `/0!`.

Errors are appended to the end of standard output as Runic has no way of writing to STDERR.

This version will support arbitrarily long programs, but is still limited to a stack of ~90 (and thus errors out on the 2nd result of the first test program) and has not been golfed very well (the increase in command length between `S͗}:` and `S͗}͍:0%:` required some additional spacing to get sections to line up, but that extra space also allowed for more `<` for a larger max stack size).

Alternatively, this program will avoid `~` generating a zero and the program will terminate after 1 million execution steps (a safeguard against infinite loops built into the Runic interpreter). Also includes a few bytes to skip over excess NOP space and run a little longer.

1. Stack oversize fizzling occurrs at (IP mana+10) and the check I put in for Volatile's stack is `sizeof(stack) < mana` and there are 5 IPs that merge and combine their mana (50 initial). Increasing that value to the true limit (the +10) would cost another 2 bytes and I left the logic golfy instead of accurate.

### Explanation

1. Program begins in the top-center blue area along the `<<<<<` and the five IPs merge together at the `y`
2. IP moves to the left, setting up the stacks and reading input and moves to the cyan section
3. IP moves to the right down this line checking the top char on the stack for what command it is. This line continues to the right further than is visible. when the correct instruction is found it executes the code on the line below to the left (skipping over other sections to return back to the cyan via the blue).
4. Magenta section is executed during `~` or `:` commands to error on Stack Overflow, yellow section is skipped if the stack is not overfull and returns via wraparound to the dark blue.
5. Far off to the right when the `)` is found the program branches to the red section and moves to the right.
6. This section rotates the command stack to the right until a `(` is found (proceed green).
7. For each additional `)` is found (proceed orange), the stack depth stack is bumped and when a `(` is found, the stack depth stack is popped once (proceed dark green and orange re-entry)
8. If the depth stack is empty continue following green to the `B` and return to cyan to main parsing loop, otherwise wrap via orange-\>yellow-\>red (re-entering the loop-reset loop).
9. The purple in the top right handles division, if the value to divide by is 0, the brown section handles the error and termination. Re-enters main parsing loop by skipping over the cyan section.
> 3 votes

# Answer
# Lua, 323 bytes

```
l,s=load,{}u=l't=...s[#s+1]=t'o=l'n=t s[#s]=_ t=s[#s]return n'math.randomseed(os.time())l((...):gsub('[^-*+/:.()~]',''):gsub('.',{['~']='u(math.random(1e5))',['+']='u(o()+o())',['-']='u(o()-o())',['*']='u(o()*o())',['/']='u(0~=s[#s-1]and o()//o()or-_)',[':']='u(t)',['.']='print(t)',['(']='while 0~=t do ',[')']='end '}))()

```

Try it online!

Transpiles the Volatile code into Lua. Note that `s` represents the stack itself, `u` pushes onto the stack, `o` pops off the stack, and `t` represents the value at the top of the stack.

| Volatile | Lua |
| --- | --- |
| `~` | `u(math.random(1e5))` |
| `+` | `u(o()+o())` |
| `-` | `u(o()-o())` |
| `*` | `u(o()*o())` |
| `/` | `u(0~=s[#s-1]and o()//o()or-_)` |
| `:` | `u(t)` |
| `.` | `print(t)` |
| `(` | `while 0~=t do` |
| `)` | `end` |
> 3 votes

# Answer
# PHP, 196 bytes

```
eval(strtr($argn,[':'=>($v='$a[]=').$e='end($a);','~'=>$v.'rand();','+'=>($q=$v.$p='array_pop($a)')."+$p;",'-'=>"$q-$p;",'*'=>"$q*$p;",'/'=>"$q/$p;",'.'=>"echo' ',$e",'('=>"for(;$e){",')'=>'}']));

```

Input 1: Try it online!

Input 2 (0, 1, 2, ...): Try it online!

Input 3 (Division by zero error): Try it online!

Just translates the code to PHP and evaluates it!
> 2 votes

# Answer
# Java 8, ~~420~~ ~~418~~ ~~402~~ ~~373~~ ~~359~~ ~~357~~ ~~341~~ 339 bytes

```
import java.util.*;s->f(s,new Stack());void f(String s,Stack<Integer>S){for(int i=0,c,t,u;i<s.length();){if((c=s.charAt(i++))<42&&S.peek()!=0)f(s.substring(40/c*i),S);if(c==46)System.out.println(S.peek());if(c>57)S.add(c>99?new Random().nextInt():S.peek());if(c<44|c==45|c==47){t=S.pop();u=S.pop();S.add(c<43?u*t:c<45?u+t:c<46?u-t:u/t);}}}

```

-2 bytes thanks to *@Grimy*.
-18 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
import java.util.*;       // Required import for 2x Stack and Random

s->                       // Method with String parameter and no return-type
  f(s,new Stack())        //  Call the recursive function, with a new Stack

// Separated recursive method with String and Stack parameters
void f(String s,Stack<Integer>S){
  int i=0,                //  Index integer
      c,                  //  Temp integer used for the current character
      t,u;                //  Temp integers used for the peeked/popped top of the stack
  for(;i<s.length();){    //  Loop `i` in the range [0, String-length):
    if((c=s.charAt(i      //   Set `c` to the current character
                    ++))  //   And increase index `i` by 1 right after
        <42               //   If the character is either '(' or ')',
        &&S.peek()!=0)    //   and the top of the stack is not 0:
         f(s.substring(   //    Take the substring, either removing everything before and
            40/c*i),      //    including the "(", or keeping the string as is for ")"
           S);            //    And do a recursive call with this String
    if(c==46)             //    If the character is '.'
      System.out.println( //     Print with trailing newline:
       S.peek());         //      The peeked top of the stack
    if(c>57)              //    If the character is ':' or '~':
      S.add(c>99?         //     If the character is '~':
        new Random().nextInt()
                          //      Add a random [0,2147483647) integer to the stack
       :                  //     Else (the character is ':')
        S.peek());        //      Add the peeked top to the stack
    if(c<44|c==45|c==47)  //    If the character is '*', '+', '-', or '/':
      t=S.pop();u=S.pop();//    Pop and set the top two values to `t` and `u`
      S.add(c<43?         //     If the character is '*':
        u*t               //      Add the product of the two values to the stack
       :c<44?             //     Else-if the character is '+':
        u+t               //      Add the sum of the two values to the stack
       :c<46?             //     Else-if the character is '-':
        u-t               //      Subtract the top two values, and add it to the stack
       :                  //     Else (the character is '/'):
        u/t;}}}           //      Divide the top two values, and add it to the stack

```
> 2 votes

# Answer
# JavaScript (V8),  ~~178 172~~  171 bytes

Transpiles to JS. May throw either `Z is not defined` or `x is not defined` if the code attempts to do something bad.

```
s=>eval(s.replace(/./g,c=>`S.push(${c>'}'?'x=Math.random()*1e5|0':c>'9'?'x':c=='.'?');print(x':c<')'?');while(x){(0':c<'*'?')}(0':`1/(x${c}=S.pop(S.pop()))?x:Z`});`,S=[]))

```

Try the 1st program online!

Try the 2nd program online!

Try the 3rd program online!

### How?

Each instruction is transpiled to `S.push(`, followed by a specific pattern, followed by `);`.

We have to test the division by zero explicitly because JS doesn't give the slightest damn about such a harmless operation. :-p

```
 char. | JS code
-------+--------------------------------------
   ~   | S.push( **x=Math.random()*1e5|0** );
   +   | S.push( **1/(x+=S.pop(S.pop()))?x:Z** );
   -   | S.push( **1/(x-=S.pop(S.pop()))?x:Z** );
   *   | S.push( **1/(x*=S.pop(S.pop()))?x:Z** );
   /   | S.push( **1/(x/=S.pop(S.pop()))?x:Z** );
   :   | S.push( **x** );
   .   | S.push( **);print(x** );
   (   | S.push( **);while(x){(0** );
   )   | S.push( **)}(0** );

```
> 2 votes

# Answer
# C (gcc) for Linux x86\_64, ~~675 643 621 613 597 432 404~~ 399 bytes

```
printf();*z;*mmap();(*p)();*j(char*a){char*t=a,*n,c;for(p=0;read(0,&c,!p);t=!~c?n=j(t+9),z=mempcpy(t,L"\xf00f883Ƅ",5),*z=n-t-9,n:!c?p=*t++=233,z=t,*z=a-13-t,z+1:stpcpy(t,c-85?c-2?c-4?c-1?c-6?c-17?"PAPTYh%ld T_P^1\xc0QH\x83\xcc\bQA\xff\xd0\\AXX":"P":L"\xfef7995e":"[\xf7\xeb":"[)\xd8":"[\1\xd8":L"\xf0c70f50"))c-=41;return t;}main(){p=mmap(0,1<<20,6,34,0,0);p(strcpy(j(p),"j<X\xf\5"),0,0,0,printf);}

```

Try it online!

This is a JIT that directly translates Volatile instructions into x86\_64 machine language and executes the code. If your machine doesn't have the `rdrand` instruction, you can replace `L"\xf0c70f50"` with `"Pj*X"` for a "*less uniform PRNG*". To port to something other than Linux, replace the syscalls in the `printf()` and `exit()` blobs and adjust parameters to `mmap()`.

EDIT: This version calls `printf()` instead of implementing a subset from scratch.

EDIT2: Supported integers are now 32 bits instead of 64.

Slightly less golfed...

```
printf();*z;*mmap();(*p)();
// recursive function translates Volatile commands to x86_64 instructions
*j(char*a){
  char*t=a,*n,c;
  for(p=0;read(0,&c,!p);)
    c-=41,
    t=c=='('+41?
      // cmp eax,0
      // je n-t-9
      n=j(t+9),
      z=mempcpy(t,"\x83\xf8\x00\x0f\x84",5),
      *z=n-t-9,
      n
    :
      c==')'+41?
        // jmp a-13-t
        p=*t++=233,
        z=t,
        *z=a-13-t,
        z+1
      :
        stpcpy(t,c-'~'+41?
                   c-'+'+41?
                     c-'-'+41?
                       c-'*'+41?
                         c-'/'+41?
                           c-':'+41?
                             // ; This calls printf("%ld ",%rax)
                             // push rax
                             // push r8
                             // push rsp
                             // pop  rcx
                             // push 0x20646c25
                             // push rsp
                             // pop  rdi
                             // push rax
                             // pop  rsi
                             // xor  eax, eax
                             // push rcx
                             // or   rsp, 8
                             // push rcx
                             // call r8
                             // pop  rsp
                             // pop  r8
                             // pop  rax
                             "\x50\x41\x50\x54\x59\x68\x25\x6c\x64\x20\x54\x5f\x50\x5e\x31\xc0\x51\x48\x83\xcc\x08\x51\x41\xff\xd0\x5c\x41\x58\x58"
                           :
                             // push rax
                             "\x50"
                         :
                           // pop rsi
                           // cdq
                           // idiv esi
                           "\x5e\x99\xf7\xfe"
                       :
                         // pop rbx
                         // imul ebx
                         "\x5b\xf7\xeb"
                     :
                       // pop rbx
                       // sub eax, ebx
                       "\x5b\x29\xd8"
                   :
                     // pop rbx
                     // add eax, ebx
                     "\x5b\x01\xd8"
                 :
                   // push rax
                   // rdrand eax
                   "\x50\x0f\xc7\xf0");
  return t;
}
main(){
  p=mmap(0,1<<20,6,34,0,0);
  p(strcpy(j(p),"\x6a\x3c\x58\x0f\x05"),0,0,0,printf);
}

```
> 2 votes

# Answer
# Python 2, ~~460~~ ~~454~~ ~~428~~ ~~417~~ ~~413~~ ~~412~~ 406 bytes

```
from random import*
a=raw_input();i=v=0;s=[];o='p(s.pop()%ss.pop())';l=len;p=s.append
def L(u,c,N,r):
 u=u[::r];f=0
 for i in range(l(u)):
    if c==u[i]:f+=1
    if f==N:return l(u)-i+l(u)*(r>0)
while i<l(a):c=a[i];exec['v+=1;'+'i=L(a,")",v,1)'*(c=='('and not s[-1]),'i=L(a,"(",v,-1)-1'if')'==c and s[-1]else'v-=1','p(randint(0,4e4))','p(s[-1])','print(int(s[-1]))',o%c,o%c,o%c,o%c,'']['()~:.+-*/'.find(c)];i+=1

```

Try it online!
Try it ungolfed!

*-19 bytes thanks to emanresu*
*-26 bytes thanks to implicit loop errors*
*-2 bytes because `-1` wraps to the end of the array*
*-1 byte by moving operators into main array*
*-6 bytes by fitting everything into the exec array*

Transpiles to Python code.

### Explanation

```
from random import*

```

We need this for access to `randint`, and of course importing everything is golfier than just importing `randint`

```
a=raw_input();i=v=0;s=[];o='p(s.pop()%ss.pop())';l=len;p=s.append

```

This defines a few initial variables.
`a` is the source code, read from STDIN
`i` is the instruction pointer, ie the index of the current character in source
`v` is used to track nested loops
`s` is the stack
`o` is a string template used for the four operators, they're all the same logic just with a different operator, and that operator is conveniently also the instruction that triggers it, so we can just interpolate the char into this string
`l` and `p` are just short aliases to save bytes on repeated functions
`;l=len` costs 6 bytes, but saves 2 on each call to `len`, so as long as we use `len` more than 3 times in the program, we save bytes.
`;p=s.append` costs 11 bytes, but saves 7 on each push to the stack, meaning it's worth it even if we only push twice.

```
def L(u,c,N,r):
 u=u[::r];f=0
 for i in range(l(u)):
    if c==u[i]:f+=1
    if f==N:return l(u)-i+l(u)*(r>0)

```

This function is used to find the opposite end of a loop while considering nested loops. `u` is the source code, `c` is the char to find, `N` is the nest depth, and `r` is the direction. Returns the index of the first char after the found character.

If for any reason this function can't find a matching end of the loop, it returns `None`, which then throws an error on the next iteration of the main while loop.

```
while i<l(a):c=a[i];exec['v+=1;'+'i=L(a,")",v,1)'*(c=='('and not s[-1]),'i=L(a,"(",v,-1)-1'if')'==c and s[-1]else'v-=1','p(randint(0,4e4))','p(s[-1])','print(int(s[-1]))',o%c,o%c,o%c,o%c,'']['()~:.+-*/'.find(c)];i+=1

```

This is the main parsing loop

```
while i<l(a):

```

Keep looping while the instruction pointer has not reached the end of the code

```
 c=a[i]

```

This is setup for each individual character.
`c` is the current character, ie the character at index `i` in the source code

```
 exec['v+=1;'+'i=L(a,")",v,1)'*(c=='('and not s[-1]),'i=L(a,"(",v,-1)-1'if')'==c and s[-1]else'v-=1','p(randint(0,4e4))','p(s[-1])','print(int(s[-1]))',o%c,o%c,o%c,o%c,'']['()~:.+-*/'.find(c)]

```

Finally, we get the index of `c` in the string `'()~:.+-*/'`. ie 0 for `(`, 1 for `)`, 2 for `~`, 3 for `:`, 4 for `.`, 5-8 for an operator, and -1 for anything else, and then use that to index into this array with to get the relevant code to execute. As indexing with `-1` in Python wraps to the end of the array, `-1` will return `''` here.

```
'v+=1;'+'i=L(a,")",v,1)'*(c=='('and not s[-1])

```

The transpiled code for `(` increments `v` and, if the top of the stack is falsey, moves the instruction pointer to the end of the loop. We have to check that `c=='('` so that `s[-1]` is not being evaluated on every instruction, causing an error when the program first starts and the stack is empty.

```
'i=L(a,"(",v,-1)-1'if')'==c and s[-1]else'v-=1'

```

The transpiled code for `)` jumps to the beginning of the loop if the top of the stack is truthy, or otherwise decrements `v`. Again we have to check that `')'==c` first to prevent `s[-1]` incorrectly evaluating on an empty stack.

```
p(randint(0,4e4))

```

The transpiled code for `~` pushes a random value between 0 and 40,000 (inclusive). `4e4` was the smallest 3-byte expression I found that was greater than or equal to the required max of 32,768, because `2**15` is still 5 bytes. Unfortunately I don't think it's possible to create a number large enough in fewer bytes.

```
p(s[-1])

```

The transpiled code for `:` simply pushes the top of the stack to the stack.

```
print(int(s[-1]))

```

The transpiled code for `.` prints the top of the stack with a trailing newline. Unfortunately we have to cast to an int costing 5 bytes as otherwise every value that's touched division will be printed with a trailing `.0`

```
o%c

```

The transpiled code for operators is the operator template `o` interpolated with the operator. ie:

```
p(s.pop()Xs.pop())

```

Where `X` is whatever character (one of `+-*/`) we're currently on.

We then `exec` the result of this indexing, running the transpiled code for the current instruction.

```
;i+=1

```

Last but not least, we increment `i` and repeat the loop.
> 2 votes

# Answer
# PowerShell Core, 176 bytes

```
for($k=0;$c=$args[$k++]){switch -r($c){~{$t=,((get-random)%32768)+$t}'[-+*/]'{$a,$b,$t=$t
$t=,("$a$c $b"|iex)+$t}:{$t=,$t[0]+$t}'\.'{$t[0]}'\('{$l=$k-1}'\)'{if($t[0]){$k=$l}}}}

```

Try it online!

This is a special version that stops after a few iterations to validate the loop's behaviour: Try it online!

I saved about 50 bytes by faking a stack using arrays concatenation and deconstruction:

* `$a,$t=$t` to pop values
* `$t=,$a+$t` to push values
> 2 votes

# Answer
# Kotlin, 412 bytes

Unfortunately I lost to Java, but I didn't want to `import java.util.Stack` (and I'm not sure it would close the gap anyway.)

```
{p->var i=0
var s=List(0){0}
var c=List(0){0}
while(i<p.length){when(val o=p[i]){'~'->s+=(0..32768).random()
in "+-*/"->{val(a,b)=s.takeLast(2)
s=s.dropLast(2)+when(o){'+'->a+b
'-'->a-b
'*'->a*b
'/'->a/b
else->0}}
':'->s+=s.last()
'.'->println(s.last())
'('->{if(s.last()!=0)c+=i else{var z=0
do{if(p[i]=='(')z++else if(p[i]==')')z--
i++}while(z>0)
i--}}
')'->if(s.last()!=0)i=c.last()else c=c.dropLast(1)}
i++}}

```

## Ungolfed

```
{ p ->                  // open lambda: p is the code string
    var i = 0           // program counter
    var s = List(0){0}  // data stack
    var c = List(0){0}  // jump stack

    // main loop
    while(i<p.length) {
        // match on the current character
        when(val o = p[i]) {
            // add random number to end of stack
            '~' -> s += (0..32768).random()
            // if a math op...
            in "+-*/" -> {
                // pick top stack items
                val (a, b) = s.takeLast(2)
                // pop two items and then push based on op
                s = s.dropLast(2) + when(o) {
                    '+' -> a+b
                    '-' -> a-b
                    '*' -> a*b
                    '/' -> a/b
                    else -> 0  // else is required here
                }
            }
            // duplicate top stack item
            ':' -> s += s.last()
            // print top stack item
            '.' -> println(s.last())
            // open loop
            '(' -> {
                if(s.last()!=0)
                    // push to jump stack if top of data stack is nonzero
                    c+=i
                else {
                    // skip ahead
                    var z=0
                    do {
                        // seek to matching brace
                        if(p[i]=='(') z++ else if(p[i]==')') z--
                        i++
                    } while(z>0)
                    // ensure program counter doesn't go too far
                    i--
                }
            }
            // close loop
            ')' -> if(s.last()!=0) i=c.last() else c=c.dropLast(1)
        }
        // next character
        i++
    }
}

```

Try it online!
> 1 votes

# Answer
# Go, 660 bytes, fixed seed

```
import."math/rand"
func f(C string){for i,S,P:=0,[]uint{},[]int{};i<len(C);i++{if c:=C[i];c=='~'{
S=append(S,uint(Int()))}else if c=='+'{b:=S[len(S)-1];S=S[:len(S)-1];a:=S[len(S)-1];S=S[:len(S)-1];S=append(S,a+b)}else if c=='-'{
b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a-b)}else if c=='*'{b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a*b)}else if c=='/'{b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a/b)}else if c==':'{S=append(S,S[len(S)-1])}else if c=='.'{println(S[len(S)-1])}else if c=='('{P=append(P,i)}else if c==')'{if S[len(S)-1]<1{i=P[len(P)-1]}else{P=P[:len(P)-1]}}}}

```

Attempt This Online!

~~confirmed go worse than java~~

Most of this is handling the pops. The title has "fixed seed" because in Go, the random number generator starts with the same fixed seed, every time. You need to seed it with some changing value for it to be truly random (+29 bytes):

## Go, 689 bytes, truly random

```
import(."math/rand";."time")
func f(C string){Seed(Now().Unix())
for i,S,P:=0,[]uint{},[]int{};i<len(C);i++{if c:=C[i];c=='~'{
S=append(S,uint(Int()))}else if c=='+'{b:=S[len(S)-1];S=S[:len(S)-1];a:=S[len(S)-1];S=S[:len(S)-1];S=append(S,a+b)}else if c=='-'{
b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a-b)}else if c=='*'{b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a*b)}else if c=='/'{b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a/b)}else if c==':'{S=append(S,S[len(S)-1])}else if c=='.'{println(S[len(S)-1])}else if c=='('{P=append(P,i)}else if c==')'{if S[len(S)-1]<1{i=P[len(P)-1]}else{P=P[:len(P)-1]}}}}

```

Attempt This Online!
> 1 votes

# Answer
# Vyxal `D`, 215 bitsv1, 26.875 bytes

```
`~.(/``kεʀ℅`\…‛{:|`:0=ß•/`WḣĿ∑Ė

```

Try it Online!

Translates volatile to its vyxal equivalent (which is almost 1 to 1, given that volatile is a subset of Keg which is a subset of Vyxal).
> 1 votes

---
Tags: code-golf, random, interpreter
---


title: Hello World Rainbow

text:
# Question
Title: Hello World Rainbow
Dealing with colors in non-markup languages often complicates things. I would like to see some variations of how color is used in different languages.

The object of this competition is to output 'Hello World' in the seven colors of the rainbow.

According to Wikipedia, these are the 7 colors.

```
Red      #FF0000 (RGB: 255, 0, 0)
Orange   #FF7F00 (RGB: 255, 127, 0)
Yellow   #FFFF00 (RGB: 255, 255, 0)
Green    #00FF00 (RGB: 0, 255, 0)
Blue     #0000FF (RGB: 0, 0, 255)
Indigo   #6600FF (RGB: 111, 0, 255)
Violet   #8B00FF (RGB: 143, 0, 255)

```

**The rules**

1. The program must output 'Hello World'. (Doesn't necessarily need to be text, but it must be distiguishable as 'Hello World')
2. Each letter must be a different color.
3. The colors can be in any order.
4. You must use each of the seven colors at least once. (You may use more than the given colors)
5. No use of markup languages *in any case*.

**The winner is whoever has the lowest amount of characters AND follows the rules**

**Bonus -1 character if it is written in DART**

I will pick the winner on Jan 11 (if I remember ;D).

Good luck

## WINNER(s)

I made a mistake D:, updated winners.

1st. stranac - Python, 60 chars

2nd. Ilmari - Karonen Perl + GD, 146 chars

Shortest length with all rules adhered to.

Brownie points to JiminP for the DART answer.

# Answer
> 7 votes
# Python, 60 chars

Now using 7 colors, and the "correct" ones.
Uses ansi escape sequences. The underscore is there just so it's not an invisible space.
This version prints some extra spaces, because of the way python's print works, but those spaces save quite a few chars, so I'm fine with them being there.

```
for p in zip(range(7)*2,'Hello_World'):print'\033[3%im%s'%p,

```

And a screenshot, as required by MrZander:

# Answer
> 12 votes
## Mathematica

```
ImageMultiply[ColorNegate[Graphics[Text[Style["Hello World",30]],ImageSize->190]],ColorData["Rainbow","Image"]]

```

I know, I know, it doesn't comply with the rules.. but I had to try playing with Mathematica's image processing functions.

Screenshot:

# Answer
> 10 votes
## Haskell, 88 characters

```
f(c,n)=putStr$"\27["++show n++"m"++[c]
main=mapM_ f$zip"Hello World\n"$35:cycle[31..36]

```

Note that this uses ANSI terminal colors, of which there are only 6 and they might not match the exact ones given (it depends on terminal settings), so I'm bending the rules a little here.

**Slightly longer version with almost correct colors, 107 characters**

This version uses xterm colors instead of ANSI ones. This does not rely on any custom palettes, and uses the closest colors I could find in the 256-color xterm palette.

```
f(c,n)=putStr$"\27[38;5;"++show n++"m"++[c]
main=mapM_ f$zip"Hello World\n"$cycle[196,208,226,46,21,57,93]

```

# Answer
> 7 votes
## Perl -\> ANSI terminal, 53 chars

```
s//Hello World/;s/./\e[3${[5,(1..6)x2]}[pos]m$&/g;say

```

This produces the exact same output as Hammar's Haskell solution. It uses `say`, so needs perl 5.10+ and the `-M5.010` (or `-E`) switch. For older perls, replace `say` with `print`. A trivial one-character reduction could be achieved by replacing `\e` with a literal ESC character, but that would make the code much harder to read and edit.

**Edit:** Added two chars to match Hammar's output exactly, and to actually show all six possible terminal colors. (In the earlier version, the only character printed in color 6 = cyan was the space.)

Screenshot:

---

**Edit 2:** If using a custom terminal palette (and an underscore for the space) is allowed, then I can easily reproduce the exact colors given in the spec with just 50 chars:

```
$_=Hello_World;s/./\e[3${[(0..6)x2]}[pos]m$&/g;say

```

Screenshot:

# Answer
> 7 votes
## Python, 261 chars

```
C=((255,0,0),(255,127,0),(255,255,0),(0,255,0),(0,0,255),(111,0,255),(143,0,255))
print'P3 67 5 255'
for i in range(335):print'%d %d %d'%(C+C[2:])[i%67/6]if 0x4f7c938a00e7df7d12208a8aa0220820a34413d154044105f7e8828a28808820828cf04f39100e0417d1>>i&1 else'0 0 0'

```

Implements the spec exactly, generating a ppm image. Here is the result, converted to gif and scaled up by a factor of 4:

# Answer
> 3 votes
## Perl -\> HTML, 99 chars

```
@c=(("00")x5,77,(ff)x5,77)x2;print"<font color=#",@c[$i+8,$i+4,$i++],">$_"for split//,"Hello World"

```

**Screenshot:**

The HTML probably won't pass any validators, but should be understood by just about all browsers. This code doesn't produce the *exact* RGB colors you listed, but it does get very close. Specifically, the colors of the letters are:

```
H  Red           #FF0000
e  Orange        #FF7700
l  Yellow        #FFFF00
l  Chartreuse    #77FF00
o  Green         #00FF00
  (Spring green  #00FF77)
W  Cyan          #00FFFF
o  Sky blue      #0077FF
r  Blue          #0000FF
l  Indigo        #7700FF
d  Violet        #FF00FF

```

The output looks a lot nicer on a black background, but explicitly printing a `<body bgcolor=black>` would've cost me 28 extra characters. You may adjust your browser settings to achieve the same effect instead. :-)

# Answer
> 3 votes
## Perl + GD, 146 chars

Per the comments to my other answer, here's a solution that directly produces an image file using the GD library:

```
use GD'Simple;move{$m=new GD'Simple 70,12}2,12;s//Hello World/;s/./fgcolor$m(((0)x5,127,(255)x5,127)x2)[$i+8,$i+4,$i++];string$m$&/eg;print$m->png

```

And here's the output:

Again, using a black background would look better, but would cost me 29 characters (`$m->bgcolor(0,0,0);$m->clear;`).

**Edit:** Figured out how to shave off 20 chars by (ab)using indirect object notation and a few other tweaks. The new code emits a warning, but still runs fine.

# Answer
> 3 votes
Some cheating but solve the problem

## Bash + Ruby (needs `lolcat` gem)

```
echo Hello World | lolcat -p 0.25

```

# Answer
> 3 votes
**Postscript 155 143**

This relies on Ghostscript's ability to "figure-out" that Palatino is short for Palatino-Roman.

```
/h{c 1 1 sethsbcolor}def/c 0 def
200 400 moveto/Palatino 36 selectfont
h{32 ne{/c c .14 add dup 1 gt{1 sub}if def}if pop
h}(Hello World!)kshow

```

# Answer
> 3 votes
Some different approaches to doing this with

**PostScript**

First: Shortest one (**89**):

```
9 9 moveto/Courier 9 selectfont
0{pop pop
dup 1 1 sethsbcolor
.07 add}( Hello World)kshow

```

Un-golfed:

```
9 9 moveto
/Courier 9 selectfont
0                       % hue
{                       % hue c1 c2
  pop pop               % hue
  dup 1 1 sethsbcolor   % hue
  .07 add               % newHue
}( Hello World)kshow

```

This is continuously changing colour in x direction using the hsb color space. (Idea to use hsb colors and kshow are credited to luser droog - see his entry!) It does not use the exact seven colors given by MrZander.

When restricting myself to MrZander's colors, I get there using **141** chars:

```
9 9 moveto/Courier 9 selectfont(H e*l4l4oI  WIosrsl{d~)dup
0 2 20{2 copy
1 add get 32 sub 166 div 1 1 sethsbcolor
1 getinterval show
dup}for

```

This encodes the hue value of MrZander's colors as one byte in the printable ASCII range. This byte is translated to a hue value in the range between 0 and 1 by subtracting 32 and dividing by 166. Each character of the "Hello World" string is followed by its encoded hue value.

Un-golfed:

```
9 9 moveto
/Courier 9 selectfont
(H e*l4l4oI  WIosrsl{d~)dup     % string string
0 2 20{                         % string string index
  2 copy                        % string string index string index
  1 add get                     % string string index hueChar
  32 sub 166 div                % string string index hueValue
  1 1 sethsbcolor               % string string index
  1 getinterval                 % string substring
  show                          % string
  dup                           % string string
}for

```

**TODO**: Something isn't quite right with the colors.

# Answer
> 2 votes
# Bash, 81 bytes

```
s="Hello World";for((i=0;i<11;i++));do printf "\e[$((RANDOM%9+31))m${s:i:1}";done

```

Try it online!

# Answer
> 1 votes
## Dart to HTML, ~~135~~ 134-1 = 133

`main(){for(var s="Hello World",i=0;i<11;print("<font color=#${'F00F60FB0FF06F00F00B606B00F60F90F'.substring(i*3,i*3+3)}>${s[i++]}"));}`

Is there any way to color texts without using markup language? I can't test canvases...

# Answer
> 1 votes
I know it says "no markup in any case", but I'd like to submit this CSS one in 468 characters:

```
<style>b{font-weight:normal}i{font-style:normal}u{text-decoration:none}b:after{content:'e';color:orange}b:before{content:'H';color:red}i:after,i:before{content:'l'}i:before{color:#ff0}i:after{color:#0f0}u:before{content:'o ';color:#66f}u:after{content:'W';color:blue}s{text-decoration:none}s:before{content:'o';color:#006}s:after{content:'r';color:#60f}p{display:inline}p:before{content:'l';color:#8b00ff}p:after{content:'d'}</style><b></b><i></i><u></u><s></s><p></p>

```

None of the styling is done with the markup.

# Answer
> 1 votes
# Japt, 64 bytes

```
Ol`HÁM Wld`Ëici%Ã$,...$BÇg`ff7fo8Þ»èç36nãr`qÍ ro0 i`¬l:#

```

Test it (open your browser's console)

Or, for the benefit of those on devices without browser consoles:

# Answer
> 0 votes
## Ruby

242 more procedural way:

```
require 'paint'

s = "HelloWorld"
out = ""
[
  '#FF0000',
  '#FF7F00',
  '#FFFF00',
  '#00FF00',
  "#00FFFF",
  "#5555FF",
  '#0000FF',
  '#000077',
  '#6600FF',
  '#8B00FF'
].each_with_index { |c, i| out << "#{Paint[s[i], c.dup]}" }
puts out

```

If i manage to think of a better way to generate the colours i will. A few of the middle ones i just did some trial and error for getting the colours close.

---
Tags: code-golf, hello-world
---


# Question
Title: Generate all \$3\times 3\$ magic squares
Though challenges involving magic squares abound on this site, none I can find so far ask the golfer to print / output all normal magic squares of a certain size. To be clear, a normal magic square of order \\$n\\$ is:

1. An \\$n\times n\\$ array of numbers.
2. Each positive integer up to and including \\$n^2\\$ appears in exactly one position in the array, and
3. Each row, column, and both main- and anti-diagonals of the array sum to the same "magic number".

Your challenge is to write the shortest program that prints all normal magic squares of order 3. There are 8 such squares. For the purposes of this challenge, the characters surrounding the output array, such as braces or brackets that accompany arrays in many languages, are allowed. For a non-optimized example in python, see here. Happy golfing!

# Answer
# Jelly, 16 bytes

```
“ÑṆ6Ẉ’Ds3ZU$Ƭ;U$

```

A niladic Link that yields a list of eight lists of lists of digits, the eight magic squares.

**Try it online!**

### How?

Builds one then constructs the other seven using rotations and reflections.

```
“ÑṆ6Ẉ’Ds3ZU$Ƭ;U$ - Link: no arguments
“ÑṆ6Ẉ’           - base 250 literal = 276951438
      D          - decimal digits -> [2,7,6,9,5,1,4,3,8]
       s3        - split into threes -> [[2,7,6],[9,5,1],[4,3,8]]
            Ƭ    - collect up until a fixed point is found under:
           $     -   last two links as a monad - f=rotate(current):
         Z       -     transpose - i.e. swap rows with columns
          U      -     upend - i.e. reverse each row
               $ - last two links as a monad - f=add_reflections(four_rotations):
              U  -   upend - i.e. revese each row of each rotation
             ;   -   (four_rotations) concatenate (upended)

```

---

#### Alternatives

```
⁽Xð×3Œ?s3ZU$Ƭ;U$

```

```
“=ẹʋ‘×3D‘ZU$Ƭ;U$

```
> 3 votes

# Answer
# Python 3, 61 bytes

Outputs every magic square, each as three comma-separated rows in the form: `XXX,XXX,XXX`.

```
for c in'\zÁßİĺ':print(f'{ord(c)*1780218+275171220:,}')

```

Try it online!

### Explanation

There are only eight magic squares, each of which are rotations/reflections of each other. In their flattened decimal representation, they are:

```
276951438, 294753618, 438951276, 492357816, 618753294, 672159834, 816357492, 834159672

```

What's remarkable about these numbers is that they are all congruent to `1017648 (mod 1780218)`, meaning they can be expressed in the form `x*1780218+1017648`. In the code, we actually use `x*1780218+275171220` as the formula instead, since it takes up less bytes to represent in our string. The number is then comma-formatted with `f'{x:,}'` to show the separation of the rows.

### Python 3, 61 bytes

The same method but does not contain unicode characters, is (annoyingly) the same length.

```
n=50863752
for c in b'~	PFP	':n-=~c*1780218;print(f'{n:,}')

```

Try it online!
> 13 votes

# Answer
# MATL, ~~15~~ 12 bytes

```
4:"3tYL@X!tP

```

Try it online! Outputs all matrices without separation. Note that the output is unambiguous.

Alternatively, this version uses a line as separator, for 15 bytes.

### How it works

```
4:      % Range [1 2 3 4]
"       % For each k in that range
  3tYL  %   Magic square of size 3 (gives one of the 8 possible squares)
  @     %   Push k
  X!    %   Rotate matrix 90 degrees k times
  t     %   Duplicate
  P     %   Flip vertically
        % End (implicit)
        % Display stack, bottom to top (implicit)

```
> 4 votes

# Answer
# JavaScript (Node.js), 201 bytes

```
_=>(h=S=>S[1]?S.flatMap(e=>h(S.filter(a=>a!=e)).map(a=>[e,...a])):[S])([1,2,3,4,5,6,7,8,9]).filter(e=>[[0,3],[0,1],[3,1],[6,1],[1,3],[2,3],[0,4],[2,2]].every(l=>e[l[0]]+e[l[0]+=l[1]]+e[l[0]+l[1]]==15))

```

Try it online!

# Explanation

The integers 1 thru 9 should appear once each in the magic square, so the sum of all elements is \\$\frac{9(9+1)}{2}=45\\$ using a relatively simple formula.

Therefore, since each row forms one-third of the magic square, the sum of each row should equal 15 (and, by definition, the sums of columns and three-length diagonals must also equal 15).

The first thing my code does is that it creates all permutations of `[1,2,3,4,5,6,7,8,9]` (362880 of them to be exact) and checks for the ones which follow specifications. This is done using a special procedure I used in the Parker square challenge.

Rows, columns and diagonals are encoded in a format `[b, i]`:

* `b` is the starting index
* `i` is the number of indexes to add

The obtained subarray for such an array `[b, i]` would be (if the original array was `l`) `l[b], l[b+i], l[b+i+i]`. This is done using a slightly golfier method.

We check if, for each array, the corresponding sub-array (obtained via simple indexing methods) has a sum of 15.

As it turns out there are only eight magic squares of order 3. Right after writing my solution (and golfing it), I returned to this question and clicked the `math.se` link to find that someone had come up with a very simple formula. This notwithstanding, I am posting my answer because I think it offers a more creative approach than simple hard-coding. I am open to suggestions for reducing length.
> 3 votes

# Answer
# Jelly, ~~22~~ 18 bytes

```
9Œ!i⁼ṛɗƇ5s€3§;SEƲƇ

```

Try it online!

The Footer simply formats the output into a nice column of grids, remove it to see the list of matrices

-4 bytes thanks to Jonathan Allan

## How it works

```
9Œ!i⁼ṛɗƇ5s€3§;SEƲƇ - Main link. Takes no arguments
9                  - Set the left argument to 9
 Œ!                - All permutations of [1,2,3,4,5,6,7,8,9]
      ɗ 5          - Group the previous 3 links into a dyad f(p, 5):
   i               -   Index of 5 in p
     ṛ             -   Yield 5
    ⁼              -   Does the index of 5 equal 5?
       Ƈ           - Keep those permutations for which f(p, 5) is true
         s€3       - Split each into a 3x3 matrix
                ƲƇ - Keep those matrices for which the following is true:
            §      -   Sums of the rows
              S    -   Sums of the columns
             ;     -   Concatenate
               E   -   Are all equal?

```
> 3 votes

# Answer
# Python 3, ~~89~~ 83 bytes

The 8 magic squares of order 3 are all just rotations / reflections of each other, so this stores one of them and calculates the remaining ones.

```
exec("x='672','159','834'"+(';*map(print,*x),print();x=[*zip(*x)][::-1]'*4)[:-6]*2)

```

Try it online!

A few bytes can be saved by using an uglier output format: Try it online!

---

Here are two programs with numpy that don't use hardcoding. The first one is quite slow, 157 bytes:

```
import itertools as I,numpy as N
for p in I.permutations(N.r_[1:10]):d=N.r_[p].reshape(3,3);{*d.sum(0),*d.sum(1),d.trace(),d[:,::-1].trace()}-{15}or print(d)

```

Try it online!

And the second one is decently fast, 175 bytes:

```
from numpy import*
from itertools import*
d=r_[[*permutations(r_[1:10])]].reshape(-1,3,3)
print(d[all(c_[sum(d,1),sum(d,2),trace(d,0,1,2),trace(flip(d,2),0,1,2)]==15,axis=1)])

```

Try it online!
> 3 votes

# Answer
# , ~~79~~ ~~78~~ ~~76~~ ~~75~~ 70 bytes

*Edit: -6 bytes thanks to Dominic van Essen.*

```
m=matrix(c(2,7,6,9,5,1,4,3,8),3)
while(print(m<-t(print(m[3:1,])))-2)1

```

Try it online!

Hardcodes one square and loops though its rotations, displaying also a transposition with every iteration.

Abuses the fact that `while` takes only the first element in a vector/matrix to check the looping condition.
> 3 votes

# Answer
# Japt, ~~29~~ 21 bytes

Well, this is ~~pretty damned~~ *slightly* less hideous! Outputs a 3D-array.

```
4o!z49#ë7816ì ò3
cUmy

```

Test it (footer formats output into squares)

```
4o!z49#ë7816ì ò3\ncUmy
4o                         :Range [0,4)
  !z                       :For each rotate the following that many times
    49#ë7816               :  492357816
            ì              :  To digit array
              ò3           :  Partitions of length 3
                \n         :Assign to variable U
                  c        :Concat
                   Um      :  Map U
                     y     :    Transpose

```
> 2 votes

# Answer
# Haskell, ~~102~~ 91 bytes

```
r=reverse
m=map
[id,r,m r,r.m r]<*>m(m$m((+0).read.pure).show)[[276,951,438],[294,753,618]]

```

Try it online!

Doesn't actually bother calculating anything, just compresses a hard-coded output.

There are some tactics used for compression

1. We encode each row as a base 10 number and use `m((+0).read.pure).show` to turn it into a list of intergers.
2. We only encode 2 of the squares and use flips to get the remaining squares.

I tried also other methods

* Only encoding the first two rows / columns and calculating the remainder
* Encoding each starting square only as a single number and splitting it into pieces

Plus some specific optimizations that only make sense with the above (e.g. multiply by 33 or 66).
> 2 votes

# Answer
# 05AB1E, 25 bytes

```
9Lœε3ô}ʒ4.DÅ\ªsÅ/ªsÅ|ªO˜Ë

```

Try it online!

Brute force, takes ~42 seconds to run on TIO.

**Attempted explanation**

```
9Lœε3ô}                      # All possible 3×3 squares (1..9 permutations, chunk in 3 pieces)
       ʒ4.D                  # Filter by (Create 4 copies of the current square first to get the parts)
           Å\ªsÅ/ªsÅ|ª       # Take the rows, cols and diagonals in a list (Through builtins and appending into one another)
                      O˜Ë    # Flattened sums are equal? Determines magic square (filter)

```

Or, 23 bytes if flat lists of magic squares are acceptable:

```
9Lœʒ3ô4.DÅ\ªsÅ/ªsÅ|ªO˜Ë

```

Try it online!
> 2 votes

# Answer
# Python 2, 59 bytes

```
l="276","951","438"
exec"r=zip(*l);l=r[::-1];print r,l,;"*4

```

Try it online!

Prints the eight arrays space-separated.
> 2 votes

# Answer
# Ruby, 67 bytes

```
r=259149258
"

Q\x1EG\x1EQ
".bytes{|x|p (r+=x*1780218).digits 1000}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 15 bytes

```
•G´dI•S3ô4F=í=ø

```

This hard-coded approach is 4 bytes shorter than the brute-force generator approach.

Try it online.

**Explanation:**

```
•G´dI•    # Push compressed integer 276951438
      S   # Convert it to a list of digits: [2,7,6,9,5,1,4,3,8]
       3ô # Split it into triplets to a 3x3 matrix: [[2,7,6],[9,5,1],[4,3,8]]
4F        # Loop 4 times:
  =       #  Print the current matrix with trailing newline (without popping the matrix)
   í      #  Reverse each row
    =     #  Print that matrix without popping as well
     ø    #  Zip/transpose; swapping rows/columns

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•G´dI•` is `276951438`.
> 2 votes

# Answer
# Nibbles, 15 bytes (30 nibbles)

```
:;`.`/3`D10`'.$\$.$\$ 1081f18e

```

```
       `D10                     # get base-10 digits of
                      1081f18e  # data in hex: 1081f18e
                                # (digits are 2,7,6,9,5,1,4,3,8);
    `/3                         # split into chunks of 3
  `.                            # and iterate over this while unique:
             .$                 #   map over each group of 3 digits
               \$               #     reversing them
           `'                   #   and transpose the result;
 ;                              # now save these 4 magic squares
:                               # and join them to
                 .$             # each of themselves
                   \$           # reversed

```

Using the decimal number `276951438` directly (instead of encoding it as data in hex) also comes-out at 15 bytes (`:;`.`/3`p276951438`'.$\$.$\`), since the final argument `$` of program code can be omitted & added implicitly by Nibbles.
> 2 votes

# Answer
# brainfuck, 317 bytes

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

```

Score includes one unnecessary newline for "clarity."

Line 1 sets the code up.

Line 2 prints a vertically mirrored pair (separated by `.`) on three rows, then the horizontal mirrors of the first pair (Slightly odd but more user readable than some other answers!)

Then, internally, the six values off the `4 5 6` diagonal are adjusted (by +/-6 each) to flip the square diagonally, and line 2 is run again to print the other four squares.

Try it online!

**Commented code**

```
++++++>++>-                                                                 FIll cells 0 1 and 2 with 6 2 and 255 respectively for looping
[----->+>+>+>+>+>+>+>+>+>+>+>+<<<<<<<<<<<<]                                 Iterate 255/5=51 times to fill cells 3 to 14 with ASCII "2"
++++++++++>                                                                 Cell 2 = 10 for linefeed
->++++>+++>----->++++++>++>-->----->+>>+++++>-----<<<<<<<<<<<<              Adjust cells 3 to 14 to 276/951/438/ (cannot include period in comments so used slash instead)
<[->                                                                        Iterate twice (counter in cell 1)
  >.>.>.>.<.<.<.<.>>>>>.>.>.>.<.<.<.<<<<<.>>>>>>>>>.>.>.>.<.<.<.<<<<<<<<<..   Output characters for 1st pair of squares (each row needs more arrows to get away from cell 2 linefeed)
  >>>>>>>>>.>.>.>.<.<.<.<<<<<<<<<.>>>>>.>.>.>.<.<.<.<<<<<.>.>.>.>.<.<.<.<..   Output characters for 2nd pair of squares (basically the reverse of the first)
  <<[->>>+>->>>->>+>>>+>-<<<<<<<<<<<<<]>                                      Flip diagonal by ajusting the 6 values off the 4 5 6 diagonal plus or minus 6
]                                                                           And loop to output 3rd and 4th pairs of squares

```
> 1 votes

# Answer
# Charcoal, 21 bytes

```
”)‴vv»!C”Ｆ⁴«Ｆ²«Ｄ‖»⟲»⎚

```

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

```
”)‴vv»!C”

```

Write a compressed magic square of digits to the canvas.

```
Ｆ⁴«Ｆ²«Ｄ‖»⟲»

```

Output all the rotations and reflections of the canvas.

Clear the canvas so that there's no implicit output.

The squares can be padded for easier viewing at a cost of 3 bytes:

```
←＆!↶⸿⦃3εⅉ‽”Ｆ⁴«Ｆ²«Ｄ‖»⟲»⎚

```

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

If two columns of four squares is acceptable output, then for 17 bytes:

```
”←＆!↶⸿⦃3εⅉ‽”⟲Ｃ‖Ｃ¬

```

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

```
”←＆!↶⸿⦃3εⅉ‽”

```

Output a padded magic square. (An unpadded square would save 3 bytes, but it would make the output format unreadable.)

```
⟲Ｃ

```

Make a 90° rotated copy.

```
‖Ｃ¬

```

Make four reflected copies of each copy. (One of these is reflected both horizontally and vertically, which is equivalent to a 180° rotation. Also the horizontal and vertical reflections are simply 180° rotations of each other. This therefore produces all of the rotations and their reflections.)
> 0 votes

# Answer
# Perl 5, 70 bytes

```
map{say for/.../g,''}map$_*1780218+275171220,unpack"W*",'\zÁßİĺ'

```

Try it online!

Borrowed method from @dingledooper's python3 answer.
> 0 votes

# Answer
# APL (Dyalog Unicode), 47 bytes

```
⎕←(3 3⍴⍕)¨1↓+\50863752,1780218×1+⎕UCS'~	PFP	'

```

Try it online!

nice, my sixth APL answer

fast hardcoding (fork of dingledooper method)

`'`...`'` magic string

`⎕UCS` cast to unicode codepoints

`1+` increment

...`×` multiply by magic

...`,` prepend by magic

`+\` cumulative sum

`1↓` decapitate

`(`... for each

stringify

`3 3⍴` mold to 3×3 matrix

`⎕←` to stdout
> 0 votes

# Answer
# Haskell, 215 bytes, intractable for n\>3

```
import Data.List
m n|let g=sum[1..n^2]`div`n=filter(\s->and[all((g==).sum)(m++[d])|
 m<-[s,reverse.transpose$s],let d=map(\i->m!!i!!i)[0..n-1]]).
 map(takeWhile(>[]).map(take n).iterate(drop n))$permutations[1..n^2]

```

Try it online!

# Haskell, 361 bytes, intractable for n\>4

```
import Data.List
s 0 l=[[]]
s n[]=[]
s n(a:b)=map(a:)(s(n-1)b)++s n b
m n|let g=sum[1..n^2]`div`n=
 filter(\m->g==sum(map(\i->m!!(n-i-1)!!i)[0..n-1]))$
 filter(\m->g==sum(map(\i->m!!i!!i)[0..n-1]))$concatMap permutations$
 filter(all((g==).sum).transpose)$concatMap(sequence.map permutations)$
 filter(([1..n^2]==).sort.concat)$s n$filter((g==).sum)$s n[1..n^2]

```

Try it online!

# Haskell, 472 bytes, intractable for n\>5

```
import Data.List
m n=let
 g=sum[1..n^2]`div`n
 t 1 _ s x l=[[x]|sum x==s]
 t i 0 0 r l=map([]:)(t(i-1)n g(l++r)[])
 t i j s (a:b) l|i>0&&j>0&&s>0=map(\(e:f)->(a:e):f)(t i(j-1)(s-a)b l)++t i j s b(l++[a])
 t _ _ _ _ _=[]
 u s[c]=[[s]|elem s c]
 u s(a:b)=[e:f|e<-a,f<-u(s-e)b]
 v m@([c]:_)=[transpose$m]
 v m=[x:y|x<-u g m,y<-v(map(\\x)m)]
 in
 filter(\m->g==sum(map(\i->m!!(n-i-1)!!i)[0..n-1])).
 filter(\m->g==sum(map(\i->m!!i!!i)[0..n-1])).
 concatMap v$t n n g[1..n^2][]

```

Try it online!
> 0 votes

# Answer
# MATLAB/Octave, ~~165~~ ~~163~~ ~~155~~ 153 bytes

Using the `magic` function directly in MATLAB/Octave for a \\$3\times3\\$ magic square would only generate a single solution, not all \\$8\\$ possible solutions.

\\$\textbf{Saved 12 bytes thanks to the comment of @ceilingcat} \\$

---

Golfed version. Try it online!

```
p=perms(1:9);p(:,5)=5;for i=1:362880,if all(sum(r=reshape(p(i,:),3,3))==15&&sum(r.')==15&sum(diag(r))==15&sum(diag(rot90(r)))==15) m(:,:,end+1)=r;end end

```

---

Ungolfed version. Try it online!

```
p = perms([1 2 3 4 6 7 8 9]);
m = zeros(3, 3, 0);
for i=1:size(p,1)
    r = [p(i,1:4),5,p(i,5:8)];
    r = reshape(r,[3,3]);
    if isequal(sum(r),[15 15 15]) && isequal(sum(r.'),[15 15 15]) && isequal(sum(diag(r)),15) && isequal(sum(diag(rot90(r))),15)
        m = cat(3,m,r);
    end
end
disp(m);

```
> 0 votes

---
Tags: code-golf, math, kolmogorov-complexity
---