title: Make a search engine

text:
# Question
Title: Make a search engine
You need to make a program, that when giving a list and a string, searches on the list for items that contains the string.

Examples:

```
Input: th [thing, awesome, potato, example]
Output: thing (Because it starts with "th")

Input: ing [thing, potato]
Output: thing (Because it ends with "ing")

Input: tat [thing, potato]
Output: potato (Because it contains "tat")

Input: tat [tato, potato]
Output: tato, potato (If there are 2 or more results matching, print all of them)

```

Remember, this is code golf, so the shortest code wins.

## Leaderboard

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

```
/* Configuration */

var QUESTION_ID = 72079; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // 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,]*[^\s,]),.*?(\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,
      });

  });

  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;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, 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 > b.lang) return 1;
    if (a.lang < b.lang) 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}

#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="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
> 3 votes
# TeaScript, 4 bytes

```
F@Iσ

```

Output is cast to string.

Try it online

## Explanation

```
F@  // Filter input 1
 Iσ // Includes input 2

```

# Answer
> 2 votes
## JavaScript ES6, 32 bytes

```
(s,a)=>a.filter(e=>~e.search(s))

```

33 bytes if the string might contain regexp metacharacters:

```
(s,a)=>a.filter(e=>~e.indexOf(s))

```

# Answer
> 2 votes
## Python 2, ~~42~~ 36 bytes

```
lambda i,a:filter(lambda v:i in v,a)

```

Thanks to muddyfish for saving 6 bytes

Test:

```
a=lambda i,a:filter(lambda v:i in v,a)
a('th', ['thing', 'awesome', 'potato', 'example']) # ['thing']
a('ing', ['thing', 'potato'])                      # ['thing']
a('tat', ['thing', 'potato'])                      # ['potato']
a('tat', ['tato', 'potato'])                       # ['tato', 'potato']

```

# Answer
> 1 votes
# Pyth - 5 bytes

```
f}zTQ

```

Try it online here.

Filters the input list by if the input string is in it.

# Answer
> 1 votes
## vim, 13

```
dd:v/\V<C-r>"<BS>/d<cr>

```

Expects input as

```
th
thing
awesome
potato
example

```

Outputs on separate lines.

```
dd      delete first line into " (default) register
:v/     apply to every line that doesn't match the following regexp...
\V        "very nomagic" - strips chars of their special regex meaning
<C-r>"    paste contents of " register into the command
<BS>      remove the trailing newline from the first line
/d      ... delete the lines

```

# Answer
> 1 votes
# Racket, 49 bytes

```
(λ(l s)(filter-map(curryr string-contains? s)l))

```

# Answer
> 1 votes
## , 5 bytes

```
b@t!W

```

## Explanation

ba      % Implicit inputs
  b     % Access the second operand
   @    % Show two operands (yields [b,b,a])
      W % Select everything in a that fullfills this condition:
    t   % Trim everything in the current item
        % that appears in the input
        % Yields ([b,b.trim(a)])
     !  % Negate this result, determining whether
        % the input is a subset of the current item

        % Keeping all of the items that fullfill
        % this condition yields a list by default
```
</code></pre>

# Answer
> 0 votes
## Python 2, 47 bytes

```
a=input()
print[x for x in input()if x in a]

```

# Answer
> 0 votes
## Bash, 27 bytes

```
tr \  \\n<<<${@:2}|fgrep $1

```

Sample run:

```
llama@llama:...code/shell/ppcg72079search$ ./search.sh th thing awesome potato example
thing

```

With multiple outputs, they will be on separate lines.

```
tr \  \\n   replace spaces with newlines (equivalent to tr ' ' '\n')
<<<${@:2}   ... with STDIN as all but first argument
|fgrep $1   fgrep for first argument (fgrep is grep w/ "fixed" string, not regex)

```

# Answer
> 0 votes
# sh, 5 bytes

Accepts a list of words on stdin, one per line, and a search string as command line argument.

```
fgrep

```

This submisson should be valid by the rules on scoring builtin functions.

# Answer
> 0 votes
# , 4 chars / 5 bytes

```
í⒡ăî

```

`Try it here (Firefox only).`

Simple.

# Explanation

Filter input array by string input.

# Answer
> 0 votes
# R, ~~38~~ 28 bytes

```
function(x,y)grep(y,x,,,T,T)

```

simply a wrapper for `grep`, with value = `TRUE` to return the value \[not a logical flag\], and fixed (to allow regex-like strings to be searched and not processed as `regex`.

*edit* \- 10 bytes by passing empty arguments to allow positional matching

# Answer
> 0 votes
# Mathematica, 29 bytes

```
Select[#2,StringContainsQ@#]&

```

Very simple.

---
Tags: code-golf, string, array
---


title: Make The Finest Magic Code Square

text:
# Question
Title: Make The Finest Magic Code Square
In math a magic square is an N×N grid of numbers from 1 to N2 such that every row, column, and diagonal sums to the same total. For example here's a 3×3 magic square:

In this challenge we'll extend the idea to magic *code* squares where, instead of numbers, each grid cell is any non-newline character. They can be be repeated and in any order.

And instead of sums, each row, column, and diagonal is viewed as an N-character single-line program whose output is a distinct number from 0 to 2N+1 (inclusive).

For example, if you had a 4×4 magic code square that looked like

```
ABCD
EFGH
IJKL
MNOP

```

it would need to output the numbers 0 through 9, perhaps like:

```
  ABCD-9
  EFGH-2
  IJKL-6
  MNOP-5
 /||||\
3 4180 7

```

That is, the ten embedded 4-character single-line programs that form the rows, columns, and diagonals of the grid each need to output a unique number from 0 through 9. In this case:

```
ABCD -> 9
EFGH -> 2
IJKL -> 6
MNOP -> 5
AFKP -> 7
DHLP -> 0
CGKO -> 8
BFJN -> 1
AEIM -> 4
DGJM -> 3

```

(Note that the diagonals are read from top to bottom. This is required.)

As another example, this 3×3 code square

```
d*P
0##
! d

```

would need to output 0 through 7 when its rows, column, and diagonals are run to make it magical, perhaps like:

```
  d*P-1
  0##-0
  ! d-6
 /|||\
5 432 7

```

# Scoring

The goal of this challenge is not necessarily to make the smallest or the biggest magic code square. In some programming languages very small magic code squares might be easy to make and in other languages very large ones might be.

**The challenge here is to create what you think is the best, most elegant, or most impressive magic code square or related set of magic code squares.** Hence this is a , the answer with the highest number of votes wins.

* Your submission must include at least one valid magic code square, and may include many related ones if you have found them, or even an infinite neighborhood of them.
* Please list the N (or range of N's) you found at the top of your answer.
* For submitting multiple magic code squares in the same language but with very different implementations use multiple answers.
* Of course you are encouraged to share your process of searching for magic code squares and explain why yours is interesting! (Info about any Parker magic code squares might be funny.)

# Answer
> 23 votes
# Keg, 4x4 magic square

```
0601
7.92
3._.
8654

```

Try it online!

## Outputs

```
 0601 - 1
 7.92 - 7
 3._. - 3
 8654 - 4
/||||\
98652 0

```

I can't believe this actually works! Programs need the `-hr` flag to properly output the required result.

Test suite. Uncomment each line to run it. The `-in` flag is purely to make the test suite a nicer experience, as otherwise, the newlines would interfere with the programs.

## Programs

```
0601 - 1 (Push 0, 6, 0 and 1,then print the top of stack (TOS))
7.92 - 7 (Push 7 and print it. This makes the rest of the program a NOP)
3._. - 3 (Push 3 and print it. The _ will the try and pop from an empty stack, ending execution)
8654 - 4 (Push 8, 6, 5 and 4 and then print TOS)
0738 - 8 (Push 0, 7, 3 and 8 and then print TOS)
6..6 - 6 (Push 6 and print it. The . will try and print from an empty stack, end execution)
09_5 - 5 (Push 0 and 9, then pop the 9 and discard it then push 5. TOS is then printed)
12.4 - 2 (Push 1, then 2 and print TOS. The rest of the program is NOPs after that.)
0._4 - 0 (Like the program for 3, but with 0)
19.8 - 9 (Like the program for 2 but with 9)

```

# Answer
> 18 votes
# 05AB1E, ~~4x4~~ 5x5

```
8www4
w3Tαw
Uw₃4<
XθнĀ·
wTwºß

```

Try it online. (Loops over the rows; columns; main diagonal; and main anti-diagonal of the square, and will run it as 05AB1E code with `.V`, after which it will print the result and discard everything that remains on the stack for the next iteration with `)\`.)

### Explanation:

The `w` are no-ops, so I'll ignore them in the explanations below. In addition, the top of the stack is output implicitly for all of these programs as result.

**Horizontal:**

* 4. `8 4`: push \\$8\\$; push \\$4\\$.
* 7. `3Tα`: push \\$3\\$; push \\$10\\$; take the absolute difference between the two: \\$\lvert3-10\rvert\\$.
* 3. `U₃4<`: pop and store in variable `X` (stores an empty string in `X` with an empty stack); push \\$95\\$; push \\$4\\$; decrease the top by 1: \\$4-1\\$.
* 2. `XθнĀ·`: push \\$1\\$; pop and push its last digit: \\$1\\$; pop and push its first digit: \\$1\\$; Python-style truthify it: \\$1\\$; double it: \\$2×1\\$.
* 0. `Tºß`: push \\$10\\$; mirror it without overlap: \\$1001\\$; pop and push its smallest digit: \\$0\\$.

**Vertical:**

* 8. `8UX`: push \\$8\\$; pop and store it in variable `X`; push variable `X`.
* 10. `3θT`: push \\$3\\$; pop and push its last digit: \\$3\\$; push \\$10\\$.
* 9. `T₃н`: push \\$10\\$; push \\$95\\$; pop and push its first digit: \\$9\\$.
* 11. `α4Āº`: take the absolute difference (no-op with an empty stack); push \\$4\\$; Python-style truthify it: \\$1\\$; mirror it without overlap: \\$11\\$.
* 6. `4<·ß`: push \\$4\\$; decrease it by 1: \\$4-1\\$; double it: \\$2×3\\$; pop and push its smallest digit: \\$6\\$.

**Main diagonal / anti-diagonal:**

* 1. `83₃Āß`: push \\$83\\$; push \\$95\\$; Python-style truthify it: \\$1\\$; pop and push its smallest digit: \\$1\\$.
* 5. `4α₃θ`: push \\$4\\$; push the absolute difference (will use the single argument on the stack twice): \\$\lvert4-4\rvert\\$; push \\$95\\$; pop and push its last digit: \\$5\\$.

# Answer
> 18 votes
# Polyglot, 10x10

```
0     14
      5
    16
    7
        18
        9
20
 10
 12
  13

```

This yields the following row/column/diagonal programs (one per line):

```
0
       01
0     2
         3
4
      5
  6
    7
    8
        9
 10
      011
 12
  13
0     14
15
    16
  17
        18
    19
20
       021

```

In many stack-based languages, including 05AB1E and Jelly, each of those programs outputs the corresponding integer.

# Answer
> 13 votes
# Jelly, A simple 3 by 3

Surely we can get a bigger one in Jelly, but if not...

```
5+2
+ḷ*
1+2

```

**Try them online!**
(splits on new lines () and evaluates (`V`) each () as Jelly programs)

```
5+2 : 5 + 2 = 7
5+1 : 5 + 1 = 6
5ḷ2 : left(5, 2) = 5
2*2 : 2 ^ 2 = 4
1+2 : 1 + 2 = 3
2ḷ1 : left(2, 1) = 2
+ḷ* : left((0 + 0), 0) ^ 0 = 1
+ḷ+ : left((0 + 0), 0) + 0 = 0

```

---
Tags: popularity-contest, integer, source-layout
---


title: Keta Bracket Autocompletion

text:
# Question
Title: Keta Bracket Autocompletion
<sup> Special thanks to Bubbler and AdmBorkBork for supplying feedback about this challenge</sup>

**Keta** (**Ke**yboard **ta**cit — clever naming, I know!) is a golfing language I’ve been working on recently. One of it’s features is it’s *most probably* unique bracket autocompletion system, which will hopefully allow for shorter programs.

There are two types of brackets in Keta: grouping brackets (`[]` and `{}`) and list brackets (`()`). This challenge only involves completing grouping brackets.

Much like it’s predecessor Keg, Keta will automatically close any open brackets within your program. For example:

```
[3+H

```

Will be turned into

```
[3+H]

```

And:

```
{0L100R3

```

Will be turned into:

```
{0L100R3}

```

Obviously, matched brackets won’t be autocompleted, as they are already fully closed.

Now, this may seem like a very trivial challenge, but I ain’t done yet. Keta will also close open closing brackets as well. More specifically:

```
H+4}

```

Turns into

```
{H+4}

```

But what happens if two bracket types are mixed together? For example:

```
P[DD+s}S3

```

In cases like this, the opening bracket will complete up until a non-matching closing bracket. The closing bracket will then complete up until the start of the string. This means our above example will turn into:

```
{P[DD+s]}S3

```

More concisely:

> \[S\]can left to right, maintaining a stack of open brackets. If I meet a non-matching closing bracket, close the open one(s) until they match or stack is empty. If the stack is empty, put a matching open bracket at the beginning instead. If the stack is nonempty at the end of the string, close all of them. ~ Bubbler

## The Challenge

Given a string of potentially unmatched brackets, autocomplete the brackets as described above.

## Test Cases

```
Input -> Output
[3+H --> [3+H]
{0L100R3 --> {0L100R3}
H+4} --> {H+4}
P[DD+s}S3 --> {P[DD+s]}S3
3+HH} --> {3+HH}
{abc --> {abc}
(3..12)S4] --> [(3..12)S4]
[0L100 --> [0L100]
A[BC}D --> {A[BC]}D
x{yz]a --> [x{yz}]a
[AbC] --> [AbC]
{12345678} --> {12345678}
A[bc} --> {A[bc]}
X{yz] --> [X{yz}]
'Hello, World!' --> 'Hello, World!'
AB(CD{EF]GH --> [AB(CD{EF}]GH
AB(CD}EF]GH --> [{AB(CD}EF]GH
AB[CD{EF]GH --> AB[CD{EF}]GH
AB[CD[EF}GH --> {AB[CD[EF]]}GH
AB{CD]EF]GH --> [[AB{CD}]EF]GH
A[bc --> A[bc]
A{bc --> A{bc}
[ --> []
{ --> {}
] --> []
} --> {}
 -->

```

Note that the last test case represents a literally empty string.

## Rules

* Input can be taken in any convenient and reasonable format.
* Output can be given in any convenient and reasonable format.
* The input string will be limited to printable ASCII characters, although it may be empty.
* An ungolfed reference program can be found here

## Scoring

Of course, this is code golf, so the answer *in each language* consisting of the fewest number of bytes wins. Happy golfings!

## 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=198087;
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}
#language-list h2{color:#215F06}
```

```
<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
> 4 votes
# Charcoal, ~~74~~ 68 bytes

```
ＦＳ«Ｗ∧υ›№]}ι⁼§υ±¹ι≔⁺ω⊟υω≔⁺ωιω≡ι]Ｆ¬∧υ⊟υ≔⁺[ωω}Ｆ¬∧υ⊟υ≔⁺{ωω[⊞υ]¦{⊞υ}»ω↑⮌υ

```

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

```
ＦＳ«

```

Loop over the characters of the input.

```
Ｗ∧υ›№]}ι⁼§υ±¹ι≔⁺ω⊟υω

```

If the current character is a closing bracket and we're expecting the other sort of closing bracket then append that bracket now. Keep doing this until we run out of other closing brackets to insert.

```
≔⁺ωιω

```

Append the current character.

```
≡ι]Ｆ¬∧υ⊟υ≔⁺[ωω}Ｆ¬∧υ⊟υ≔⁺{ωω[⊞υ]¦{⊞υ}

```

Switch on the current character. If it's a closing bracket, then remove the (now) matching closing bracket, but if that can't be done then prepend the desired matching opening bracket. If it's an opening bracket, then just save the desired matching closing bracket.

```
»ω↑⮌υ

```

After all the characters have been processed, output the processed characters (now including autocompleted missing opening brackets and wrong closing brackets), and then any remaining missing closing brackets.

# Answer
> 3 votes
# JavaScript (ES6),  ~~145~~  142 bytes

```
s=>[...s].map(c=>o+=(i=(S='[]{}').indexOf(c)^1)&1?(s=S[i]+s,c):i<0?c:(g=_=>s?(C=s[s=s.slice(1),0])==c?c:C+g():(p=S[i]+p,c))(),s=o=p='')&&p+o+s

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 269 bytes

```
\[(\[(?=.*(]))|\{(?=.*(?<2>}))|[^][}{]|(?<-2>\2))*(?(2)(?!))(?=}|$)
$&]
\{(\[(?=.*(]))|\{(?=.*(?<2>}))|[^][}{]|(?<-2>\2))*(?(2)(?!))(?=]|$)
$&}
^(\[(?=.*(]))|\{(?=.*(?<2>}))|[^][}{]|(?<-2>\2))*(?(2)$)]
[$&
}`^(\[(?=.*(]))|\{(?=.*(?<2>}))|[^][}{]|(?<-2>\2))*(?(2)$)}
{$&

```

Try it online! Link includes test suite. Explanation: In .NET, the regex `(\[(?=.*(]))|\{(?=.*(?<2>}))|[^][}{]|(?<-2>\2))*(?(2)(?!))` matches a string containing only balanced brackets. This is broken down into four alternatives, which are repeated, and then the capture group is checked for emptiness (this can be done more golfily in the latter cases), proving that all brackets have been balanced. It then remains to match the appropriate mismatched brackets and/or start/end and insert the correct matching bracket. Finally, the whole script is repeated using `}`` until all mismatched brackets have been autocompleted.

```
\[(?=.*(]))

```

Match a `[` and capture a `]` (which happens to be capture group `2`).

```
\{(?=.*(?<2>}))

```

Match a `{` and capture a `}`, but name this capture group `2` as well.

```
[^][}{]

```

Match anything that isn't a bracket (under this question's definition).

```
(?<-2>\2)

```

Match the last closing bracket that we captured earlier, and then forget that bracket, so that the previous closing bracket becomes the next potential match.

# Answer
> 2 votes
# Prolog (SWI), 246 bytes

Input is taken as a list of ASCII character codes while ouput is printed to stdout. The approach is a straightforward translation of the algorithm described in the post into Prolog.

```
\T:-T+D+[],maplist(put_code,D).
[]+[]+[].
X+[D|U]+S:-X=[],S=[O|Z],D is O+2,X+U+Z;X=[H|T],(D=H,(\+H^`[]{}`,T+U+S;H^`]}`,O is H-2,(S=[O|Z],T+U+Z;S=[],put_code(O),T+U+S);H^`[{`,T+U+[H|S]);S=[O|V],H^`}]`,D^`}]`,H\=D,O is D-2,X+U+V).
A^B:-member(A,B).

```

Try it online!

Prolog has a special syntax for literal lists of character codes so, invoking the predicate is easy.

```
?- \`A[bc}`.
{A[bc]}
true .

```

---
Tags: code-golf, string, parsing, balanced-string
---


title: How many ACUs do I have?

text:
# Question
Title: How many ACUs do I have?
Posted from sandbox

**The Intro**

What is an ACU? This challenge is based on the concept of money and since this is an international community, we all use different currencies, so in keeping with our spirit of inclusiveness, I have invented a new currency called Arbitrary Currency Units (ACUs) specifically for this challenge. In reality, the challenge is the same whether we are using Dollars, Pounds, Euros, Bitcoins, Lao Kip or Baked Beans.

**The Idea**

It's New Year. We all have ideas about how we can improve things in the coming year. Mine is to save some money but randomly putting money aside quickly becomes uninteresting so I am following up on something I read on a news site last year. Each week, I put the amount of ACUs equal to the week number into a tin and after 52 weeks I will have saved ACU 1378. That's enough for a nice golfing holiday somewhere in 2021!

**The Problem**

I need an incentive to keep me going with this so I need to know how much I have or will have in the tin on any given date during 2020. For example, if I enter a date before today I want to know how much was in the tin on that date. For a date after today I want to know how much I will have if I stay with the plan.

**The Challenge**

Write a program or function which will, when given any date in 2020 (apart from 30-31 Dec - see "The Details"), output the number of ACUs that are in my tin.

**The Details**

* Each week in 2020 consists of exactly 7 days.
* The first week of the year starts on 1 January 2020.
* We are considering only weeks that are completely within 2020. The last week ends on 2020-12-29 so there are exactly 52 weeks and 30/31 December are not included.
* Each week I will put a number of ACUs equal to the week number into my tin on the first day of the week, that is on the 1st January I will put 1 ACU into the tin, on the 8th January I will put 2 ACUs, etc. I will at no point take any ACUs out of the tin.

**The Rules**

* Program or function - your choice.
* Input in whatever convenient format but it must be a date. I have a feeling that accepting a day-of-year input may trivialise this challenge but I am open to other opinions on this.
* Output however you like but it must be a number of ACUs or a string representation of same.
* We are only talking about complete weeks in 2020 so you can assume that the input will not include 30 or 31 December. It's up to you how you deal with it if it does.
* Don't forget that in 2020 February has 29 days.
* Usual loopholes barred and this is code golf so the shortest program/function in each language will be the winner. All languages welcome and I will not be accepting an answer as per current consensus. Upvotes will decide who wins.

A small Python script that generates the expected output for each week is available here Try it online!. The output can also be printed to stick on the side of your tin if you decide to do the same :)

# Answer
> 10 votes
# APL (Dyalog Extended), ~~20~~ 19 bytesSBCS

Anonymous tacit prefix function taking `[year,month,day]` as argument.

```
2!∘⌊7÷⍨43816-⍨⌂days

```

Try it online!

`⌂days` calculate the number of **days** since 1899-12-31

`43816-⍨` subtract 43816; days since 2019 12 18, i.e 14 days weeks extra

`7÷⍨` divide by 7; weeks since 2019 12 18, i.e two weeks extra

floor; whole weeks since 2019 12 18, i.e two weeks extra

`2!` count the number of ways to choose 2 out of that many

In other words, if \\$d(x)\\$ is the number of days since 1899-12-31, then the answer is

$${\Big\lfloor{d(x)-43816\over7}\Big\rfloor\choose2}= {\Big\lfloor{d(x)-43823\over7}\Big\rfloor-1\choose2}= \sum\_{n=1}^{\big\lfloor\frac{d(x)-43823}7\big\rfloor}n$$

# Answer
> 9 votes
# , ~~56~~ 34 bytes

```
function(d)sum(1:format(d-2,"%V"))

```

Try it online!

A function taking an R `Date` as its argument and returning a number. Works because `2019-12-30` was a Monday, `strftime(,"%V")` returns the ISO week number and then calculates the relevant triangular number.

Thanks to @Giuseppe for saving 17 bytes, and @RobinRyder a further 3!

# Answer
> 9 votes
# Perl 6, 33 bytes

```
{[+] 1..Date.new(24,|@_).week[1]}

```

Try it online!

Takes input as `month,day`. This initialises a date in the year 24 (since that year starts on Monday and is a leap year), and calculates the sum of the range of 1 to the current week number.

# Answer
> 6 votes
# JavaScript (ES6),  ~~53~~  51 bytes

Takes input as `(month)(day)`.

This is longer than my other answer but does not use any date built-in.

```
m=>g=d=>--m?g(d+31+~m%9%2-(m==2)):~(d=~-d/7)*~-~d/2

```

Try it online!

### Commented version

```
m =>               // m = month
g = d =>           // g is a recursive function taking the day d
  --m ?            // decrement m; if it's not equal to 0:
    g(             //   do a recursive call:
      d + 31       //     add 31
      + ~m % 9 % 2 //     subtract 1 if (m + 1) mod 9 is odd
                   //     to account for the August -> July transition
      - (m == 2)   //     subtract 1 if m = 2, for February
    )              //   end of recursive call
  :                // else:
    ~(             //   compute the triangular number
      d = ~-d / 7  //   using d' = (d - 1) / 7:
    ) *            //     -floor(d' + 1) *
    ~-~d           //     -floor(d' + 2)
    / 2            //     / 2

```

# Answer
> 4 votes
# JavaScript (ES6),  ~~61 50 49~~  47 bytes

*Assumes that the system is set up to UTC time (as the TIO servers are)*

Takes input as `(month)(day)`.

```
m=>d=>(n=new Date(68,m-1,d+738)/6048e5|0)*-~n/2

```

Try it online!

### How?

Given the month \\$m\\$ and the day \\$d\\$, we generate the corresponding date in \\$1968\\$ (the closest leap year before Epoch) with an additional offset of \\$738\\$ days.

```
new Date(68, m - 1, d + 738)

```

We implicitly coerce this value to a number of milliseconds and divide it by:

$$7\times24\times60\times60\times1000=604800000$$

We discard the decimal part of the result to turn it into a 1-based week index \\$n\\$ in \\$1970\\$ (Epoch's year) which is consistent with the week index in \\$2020\\$.

\\$738\\$ is the sum of:

* a leap year (\\$366\\$ days) to reach 1969
* a non-leap year (\\$365\\$ days) to reach 1970
* a week (\\$7\\$ days) to go from 0-indexed to 1-indexed

Finally, we return the \\$n\\$th triangular number \\$\dfrac{n(n+1)}{2}\\$.

# Answer
> 4 votes
# 05AB1E, ~~20~~ 19 bytes

```
•Σ₁t•ºS₂+6šI£O+7÷LO

```

-1 byte thanks to *@Arnauld*.

Input in the order `month`, `day`, `year` (although the year is ignored).

Try it online.

**Explanation:**

```
•Σ₁t•                # Push compressed integer 5354545
     º               # Mirror it: 53545455454535
      S              # Convert it to a list of digits: [5,3,5,4,5,4,5,5,4,5,4,5,3,5]
       ₂+            # Add 26 to each: [31,29,31,30,31,30,31,31,30,31,30,31,29,31]
         6š          # Prepend a 6: [6,31,29,31,30,31,30,31,31,30,31,30,31,29,31]
           I£        # Leave the first month-input items of this list
             O       # And sum those
              +      # Add it to the (implicit) day-input
               7÷    # Integer-divide it by 7
                 L   # Pop and push a list in the range [1,n]
                  O  # And sum that list
                     # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•Σ₁t•` is `5354545`.

# Answer
> 4 votes
# Red, 38 bytes

```
func[d][(t: pick d - 2 14)*(t + 1)/ 2]

```

Try it online!

Takes input as a date in any reasonable format: dd-mm-yyyy, yyyy-mm-dd, dd-MMM-yyyy. Red's `date` datatype fourteenth field holds the week nember.

# Answer
> 3 votes
# Python 3.8 (pre-release), ~~94~~ \\$\cdots\\$ ~~82~~ 77 bytes

```
lambda d:(n:=(date(*d)-date(2020,1,1)).days//7+1)*-~n/2
from datetime import*

```

Try it online!

Function takes date as a `(year, month, day)` tuple and returns the number of ACUs. Tests ported from Arnauld's answer.

# Answer
> 2 votes
# Perl 5 `-ap -MTime::Local -MTime::Piece`, 61 bytes

```
$_=($w=(gmtime timegm 0,0,0,$F[0],$F[1]-1,24)->week)*($w+1)/2

```

Try it online!

# Answer
> 2 votes
# Ruby, 42 bytes

A function that takes the month and date.

`Time#yday` returns the day of the year.

```
->m,d{k=1+~-Time.gm(4,m,d).yday/7;k*-~k/2}

```

Try it online!

# Answer
> 2 votes
# PowerShell, 48 bytes

Thanks to @mazzy

```
(1..(((Date|% DayOfYear)/7)+1)|measure -sum).sum

```

Try it online!

Originally 76 bytes

```
[Linq.Enumerable]::Sum([Linq.Enumerable]::Range(1,(Get-Date).DayOfYear/7+1))

```

Try it online!

# Answer
> 2 votes
# C (gcc), ~~34~~ ~~32~~ ~~38~~ ~~34~~ 32 bytes

```
g(n){n=n/604800-2607;n=n*-~n/2;}

```

Takes as input the number of seconds since January 1st, 1970 (the Unix epoch) at 0:00 AM UTC time.

Explanation:

```
n=n/604800-2607;

```

Divide by number of seconds in a week and subtract the number of weeks from Jan 1 1970 to Jan 1 2020 minus one so we don't have to increment later.

```
n=n*-~n/2;

```

Return the n'th triangle number. This is equivalent to the ACU calculation but without any builtin language constructs or loops. Due to TIO's calling convention I can assign to the first argument instead of using `return`.

*-2 bytes thanks to Arnauld!*
*+6 bytes thanks to Arnauld and ElPedro!* (:P)
*-4 bytes thanks (indirectly) to ceilingcat!*
*-2 more bytes thanks to ceilingcat!*

Try it online!

# Answer
> 2 votes
# PHP, ~~67~~ ~~59~~ 57 bytes

```
<?=(($d=(int)(date(z,strtotime($argv[1]))/7+1))+$d*$d)/2;

```

Try it online!

# Answer
> 1 votes
# Jelly, ~~23~~ 21 bytes

```
“¢(Y’b3+29ÄŻ⁸ị++6:7RS

```

Try it online!

A full program taking the date as three arguments: month, day, year. Alternatively a dyadic link taking the month as its left and day as its right argument. (The year is ignored in any case.) Jelly has no date type, so this needs to generate the cumulative month lengths.

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

```
x=>Enumerable.Range(1,x.DayOfYear/7+1).Sum()

```

Try it online!

# Answer
> 1 votes
# TI-BASIC, ~~26~~ 25 bytes

```
∑(X,X,1,1+int(7⁻¹(1+dbd(1.012,Ans

```

Hooray for built-ins!

Input is the compressed version of the end date in the form `MM.DDYY` or `DDMM.YY` where `MM` is the month (e.g. `01`), `DD` is the day (e.g. `24`) and YY is the year (in this case, `20`).
Input is in `Ans`.

Output is the wanted result as specified in the challenge.

**Update:**

In my attempt to fix the code, I somehow made it shorter.

**Explanation:**

```
∑(X,X,1,1+int(7⁻¹(1+dbd(1.012,Ans

                    dbd(1.012,Ans  ;difference in days between 1Jan2020 and the
                                   ;  compressed input
                  1+               ;add one to allow 1Jan2020 to be an input
              7⁻¹(                 ;multiply by 1/7
          int(                     ;truncate
        1+                         ;convert week index from 0-indexed to 1-indexed
∑(X,X,1, ...                       ;summation of X from 1 to the above
                                   ;implicit print of Ans

```

**Examples:**

```
1.2420:prgmCDGF28
               6
2.2920:prgmCDGF28
              36
1.3120:prgmCDGF28
              10
1.0120:prgmCDGF28
               1

```

---

**Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count.

# Answer
> 0 votes
## Java, 24 characters/bytes

```
c->c.get(3)*-~c.get(3)/2

```

Try it online

* This is an instance of ToIntFunction as a Lambda function.
* c is a reference to a Calendar object.
* c.get(3) returns the week of year field (Calendar.WEEK\_OF\_YEAR == 3)
* x\*-~x/2 is the triangle number calculation.

---
Tags: code-golf, date
---


title: Gauss to Eisenstein

text:
# Question
Title: Gauss to Eisenstein
Given a Gaussian integer \\$a+bi\\$ where \\$a\\$,\\$b\\$ are integers and \\$i = \exp\left(\pi i/2\right)\\$ is the imaginary unit, return the closest (w.r.t to the Euclidean distance) Eisenstein integer \\$k+l\omega\\$ where \\$k\\$,\\$l\\$ are integers and \\$\omega = \exp(2\pi i/3) = (-1+i\sqrt{3})/2\\$.

### Background

It is probably quite obvious that every Gaussian integer can uniquely be written as \\$a+bi\\$ with \\$a\\$,\\$b\\$ integers. It is not so obvious but nonetheless true: Any Eisenstein integer can uniquely be written as \\$k+l\omega\\$ with \\$k\\$,\\$l\\$ integers. They both form a \\$\mathbb{Z}\\$-module within the complex numbers, and are both p-th cyclotomic integers for \\$p=2\\$ or \\$3\\$ respectively. Note that \\$3+2i \neq 3+2\omega\\$

Source: commons.wikimedia.org

### Details

* In case the given complex number has two or three closest points, any of those can be returned.
* The complex number is given in rectangular coordinates (basis \\$(1,i)\\$), but other than that in any convenient format like `(A,B)` or `A+Bi` or `A+B*1j` etc.
* The Eisenstein integer has to be returned as coordinates of the basis \\$(1,\omega)\\$ but other than that in any convenient format like `(K,L)` or `K+Lω` or `K+L*1ω` etc.

### Examples

All real integers should obviously be mapped to the real integers again.

```
  6,14 -> 14,16
  7,16 -> 16,18
-18,-2 ->-19,-2
 -2, 2 -> -1, 2
 -1, 3 -> 1, 4

```

# Answer
# APL (Dyalog Extended), 16 bytesSBCS

```
⎕0+⌈3÷⍨1 2×⌊⎕×√3

```

Try it online!

A full program that takes `y` then `x` from standard input and prints a 2-element vector of integers.

### How it works: the math

First of all, note that any Gaussian integer will be placed on the vertical diagonal of a diamond, with the point \\$Z\\$ placed at \\$(x,\sqrt3y)\\$ for some integer \\$x,y\\$.

```
      + W
     /|\
    / | \
   /  |  \
  /   + X \
 /    |    \
+-----|-----+V
 \    |    /
  \   + Y /
   \  |  /
    \ | /
     \|/
      + Z

```

In the figure, \\$\overline{WZ}=\sqrt3\\$ and \\$\overline{WX}=\overline{XY}=\overline{YZ}=\overline{XV}=\overline{YV}=\frac{1}{\sqrt3}\\$. So, given the vertical position of a point, we can identify the nearest Eisenstein point as follows:

$$ \text{Given a point }P \in \overline{WZ}, \\ \left\\{ \begin{array}{c} P \in \overline{WX} \implies \text{the nearest point is } W \\ P \in \overline{XY} \implies \text{the nearest point is } V \\ P \in \overline{YZ} \implies \text{the nearest point is } Z \end{array} \right. $$

Given a Gaussian point \\$P\\$, we first determine which diamond \\$P\\$ belongs to, measured by how many diamonds (denoted \\$h\\$) \\$Z\\$ is away from the \\$x\\$-axis.

$$ h = \lfloor P.y \div \sqrt3 \rfloor $$

Then the Eisenstein coordinates of \\$Z\\$ are

$$ Z.x\_E = P.x+h, \quad Z.y\_E = 2h $$

Now, we determine which of the segments \\$\overline{WX},\overline{XY},\overline{YZ}\\$ \\$P\\$ belongs to. For this, we can calculate the indicator \\$w\\$ as follows:

$$ w = \lfloor P.y \times \sqrt3 \rfloor \\% 3 $$

Then the cases \\$ w = 0, 1, 2 \\$ correspond to \\$\overline{YZ},\overline{XY},\overline{WX}\\$ respectively. Finally, the nearest Eisenstein point of \\$P\\$ (which is one of \\$Z\\$, \\$V\\$, or \\$X\\$) can be calculated as:

$$ P\_E.x\_E = P.x+h+\lceil \frac{w}2 \rceil, \quad P\_E.y\_E = 2h+w $$

Using the identities for \\$h\\$ and \\$w\\$, we can further simplify to:

$$ y' = \lfloor P.y \times \sqrt3 \rfloor, \quad P\_E.x\_E = P.x+\lceil y' \div 3 \rceil, \quad P\_E.y\_E = \lceil 2y' \div 3 \rceil $$

### How it works: the code

```
⎕0+⌈3÷⍨1 2×⌊⎕×√3
           ⌊⎕×√3  ⍝ Take the first input (P.y) and calculate y'
   ⌈3÷⍨1 2×       ⍝ Calculate [ceil(y'/3), ceil(2y'/3)]
⎕0+  ⍝ Take the second input(P.x) and calculate [P.x+ceil(y'/3), ceil(2y'/3)]

```
> 7 votes

# Answer
## JavaScript (ES6), 112 bytes

```
(a,b,l=b/Math.pow(.75,.5),k=a+l/2,f=Math.floor,x=k-(k=f(k)),y=l-(l=f(l)),z=x+y>1)=>[k+(y+y+z>x+1),l+(x+x+z>y+1)]

```

ES7 can obviously trim 9 bytes. Explanation: `k` and `l` initially represent the floating-point solution to `k+ωl=a+ib`. However, the coordinates needed to be rounded to the nearest integer by Euclidean distance. I therefore take the floor of `k` and `l`, then perform some tests on the fractional parts to determine whether incrementing them would result in a nearer point to `a+ib`.
> 2 votes

# Answer
# MATL, ~~39~~ ~~38~~ 35 bytes

```
t|Ekt_w&:2Z^tl2jYP3/*Zeh*!sbw6#YkY)

```

Input format is `6 + 14*1j` (space is optional). Output format is `14 16`.

**Try it online!**

### Explanation

The code first takes the input as a complex number. It then generates a big enough hexagonal grid in the complex plane, finds the point that is closest to the input, and returns its Eisenstein "coordinates".

```
t         % Take input implicitly. This is the Gauss number, say A. Duplicate
|Ek       % Absolute value times two, rounded down
t_        % Duplicate and negate
w&:       % Range. This is one axis of Eisenstein coordinates. This will generate
          % the hexagonal grid big enough
2Z^       % Cartesian power with exponent 2. This gives 2-col 2D array, say B
t         % Duplicate
l         % Push 1
2jYP3/*   % Push 2*j*pi/3
Ze        % Exponential
h         % Concatenate. Gives [1, exp(2*j*pi/3)]
*         % Multiply by B, with broadcast.
!s        % Sum of each row. This is the hexagonal grid as a flattened array, say C
bw        % Bubble up, swap. Stack contains now, bottom to top: B, A, C
6#Yk      % Index of number in C that is closest to A
Y)        % Use as row index into B. Implicitly display

```
> 2 votes

# Answer
# Haskell, 128 bytes

```
i=fromIntegral;r=[floor,ceiling];a!k=(i a-k)**2;c(a,b)|l<-2*i b/sqrt 3,k<-i a+l/2=snd$minimum[(x k!k+y l!l,(x k,y l))|x<-r,y<-r]

```

Try it online!

For input Gaussian integer (a,b), convert it into Eisenstein coordinates, floor and ceil both components to get four candidates for closest Eisenstein integer, find the one with minimal distance and return it.
> 2 votes

# Answer
# Tcl, ~~124~~ ~~116~~ 106 bytes

```
{{a b f\ int(floor(2*$b/3**.5)) {l "[expr $f+(1-$f%2<($b-$f)*3**.5)]"}} {subst [expr $l+$a-($f+1)/2]\ $l}}

```

Try it online!

This is somewhat inspired by the three-year old post from @Neil

The floor function returns the corner of the rhombus whose edges are the vectors 1 and \\$\omega\\$. With respect to this rhombus, the Gaussian integer lies on the perpendicular bi-sector of either the top (if l is even) or bottom (if l is odd). This is important because it means that either the lower left corner or the upper right corner will be an acceptable solution. I compute k for the lower left corner, and do one test to see if the Gaussian integer lies above or below the diagonal separating the two corners; I add 1 to k when above the diagonal, and I do likewise for l.

Saved 10 bytes by using the "sign of the cross-product v x d of the diagonal d with the vector v joining the lower right corner and (a,b)" as the test for which side of the diagonal the point lies.
> 1 votes

# Answer
# Burlesque, 24 bytes

```
pe@3r@2././J2./x/.+CL)R_

```

Try it online!

Pretty sure this can be shorter. Input read as `a b`

```
pe      # Parse input to two ints
@3r@2./ # sqrt(3)/2
./      # Divide b by sqrt(3)/2
J2./    # Duplicate and divide by 2
x/.+    # swap stack around and add to a
CL      # Collect the stack to a list
)R_     # Round to ints

```
> 1 votes

# Answer
# 05AB1E, 13 bytes

*Port of Bubbler's APL answer*

```
3t*ïx‚3/îRÎ‚+

```

Try it online!

Input and output are both y first, x second.
> 1 votes

---
Tags: code-golf, number, grid, hexagonal-grid, complex-numbers
---


title: Am I an engineer?

text:
# Question
Title: Am I an engineer?
Recently, an electrical engineer studying traffic light timings was fined $500 by the state of Oregon for referring to himself as an engineer.

Given a 2 letter string as input, representing a US state, output:

* `I am not an engineer` if the state is Oregon (`OR`)
* `I am an engineer` if the state is any other US state
* `What is an engineer?` given any other input

Output may not contain any *leading* whitespace, but may contain as much *trailing* whitespace as you wish.

You can assume the input will always be 2 uppercase letters.

Here is a list of all 50 US state abbreviations:

```
AL, AK, AZ, AR, CA, CO, CT, DE, FL, GA, HI, ID, IL, IN, IA, KS, KY, LA, ME,
MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, OH, OK, OR, PA,
RI, SC, SD, TN, TX, UT, VT, VA, WA, WV, WI, WY

```

## Scoring

This is , so fewest bytes **in each language** wins!

# Answer
> 17 votes
# C#, ~~311 309~~ ~~240~~ ~~237~~ ~~222~~ ~~195~~ ~~184~~ 183 bytes

```
s=>s=="OR"?"I am not an engineer":"MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY".Contains(s)?"I am an engineer":"What is an engineer?";

```

Try it online!

*Saved 2 bytes by adding the space before `an` to `b`*

*~~-69 (huehue)~~ -72 bytes thanks to TheLethalCoder*

*-15 bytes thanks to TotallyHuman's genius states string*

*-38 bytes cos more string compression*

Ungolfed:

```
public static string a(string s)
{
    var b = " an engineer";
    if (s == "OR")
    {
        return "I am not" + b;
    }
    else
    {
        if ("MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY".Contains(s))
        {
            return "I am" + b;
        }
        else
        {
            return $"What is{b}?";
        }
    }
}

```

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

```
s=>['I am'+(x=' an engineer'),`What is${x}?`,'I am not'+x][s=='OR'?2:'MNNMLATNAKALARAZCACOCTDEFLGAHIIAIDILINKSKYMAMDMEMIMOMSMTNCNDNENHNJNVNYOHOKPARISCSDTXUTVAVTWAWIWVWY'.search(s)&1]

```

### Demo

```
let f =

s=>['I am'+(x=' an engineer'),`What is${x}?`,'I am not'+x][s=='OR'?2:'MNNMLATNAKALARAZCACOCTDEFLGAHIIAIDILINKSKYMAMDMEMIMOMSMTNCNDNENHNJNVNYOHOKPARISCSDTXUTVAVTWAWIWVWY'.search(s)&1]

console.log(f("OR"))
console.log(f("NY"))
console.log(f("TX"))
console.log(f("YO"))
```

# Answer
> 8 votes
# C, ~~215~~ ~~208~~ 190 bytes

<sup>-7 thanks to Cool Guy</sup>

```
#define z" an engineer"
#define f(s)!strcmp(s,"OR")?"I am not"z:strstr("MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY",s)?"I am"z:"What is"z"?"

```

Used @totallyhuman's "genus string".

How it works:

* `"string"z` automatically concatenates `"string"` with `z` (`" an engineer"`). Yes, C does that.
* `!strcmp(s,"OR")` compares the string against "OR".
* `?"I am not"z` returns "I am not an engineer" if true. Otherwise...
* `:strstr(...,s)` checks if @totallyhuman's genius string contains the provided string.
* `?"I am"z` returns "I am an engineer" if so, and...
* `:"What is"z"?")` returns "What is an engineer?" otherwise.

Try it online!

# Answer
> 6 votes
# Python 2, ~~228~~ 168 bytes

```
lambda s:('What is%s?','I am'+' not'*(s=='OR')+'%s')[s in'MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH ORIA UT WVT WIL WY']%' an engineer'

```

Try it online!

# Answer
> 5 votes
# Python 2, ~~192~~ ~~186~~ ~~182~~ ~~178~~ 176 bytes

Could probably compress the state string more.

```
lambda s,e=' an engineer':'I am'+' not'*(s=='OR')+e if s in'MINCALAZ SCT FL GA WIAKSD ME MD MA MNMS MOKY MTNE NVTX NH NJ NY ND COHIDE OR PARIL UT VA WA WV WY'else'What is%s?'%e

```

Try it online!

# Answer
> 5 votes
# Java (JDK 10), 184 bytes

```
s->s.format(s.equals("OR")?"I am not%s":"MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY".contains(s)?"I am%s":"What is%s?"," an engineer")

```

Try it online!

I apologize for reusing the compressed string: I couldn't find anything better by myself... :(

# Answer
> 4 votes
# 05AB1E, ~~104~~ ~~103~~ 101 bytes

```
„€À€ˆ„I€Ü‚.•~Zµ∞/'—¶[@øl•Œ2ù.•9₆\|&×ƒΩ#àöF},cΓ páe;ð²∍₆jÌn#dÅ?DvĆ8A•2ôìuIå©è¹„ORQi'€–}„€¤©É)ðýª'?®_×J

```

Try it online!

Old 104 byte version in case that is more easily improved.

```
„€À€ˆ„I€Ü‚.•ÂkXñ…ΓVt€Ïè∍‡Λi„2¶’að=–½6™oÑþÁāõgO·ð~
λ†₃›;â&ÄFv¾‡1~ǝQa«;cS•u2ôIå©è¹„ORQi'€–}„€¤©É)ðýª'?®_×J

```

Not happy with the compression nor the special case for `?`.

# Answer
> 4 votes
# F#, 222 211 bytes

```
let f v=let(a,b)=if"OR"=v then("I am not",".")elif"WALAKSCARINMNVTNCTX NHIDE MOHIL COKY MSD PAZ WIA WVA FL GA MA MD ME MI MT NE ND NJ NY UT WY".Contains v then("I am",".")else("What is","?")in a+" an engineer"+b

```

Try it online!

Expanded:

```
let f v =
    let (a,b) =
        if "OR" = v then ("I am not",".")
        elif "WALAKSCARINMNVTNCTX NHIDE MOHIL COKY MSD PAZ WIA WVA FL GA MA MD ME MI MT NE ND NJ NY UT WY".Contains v then ("I am",".")
        else ("What is","?")
    a + " an engineer" + b

```

Given a two-letter state *v* passed to the function *f*, build a tuple *(a, b)* representing the head and tail of the "engineer" sentence.

Feel free to use the "compressed state string" freely; it's one whole byte shorter than the MINCALA one...

# Answer
> 4 votes
# , ~~109~~ 96 bytes

```
function(x)sub("#"," an engineer",c("I am not#","I am#","What is#?"))[2-x%in%state.abb+!x=="OR"]

```

Try it online!

13 bytes thanks to J.Doe - through use of regex and indexation.

# Answer
> 3 votes
# Japt, ~~136~~ ~~135~~ ~~131~~ ~~129~~ 128 bytes

More savings may be available by experimenting with the order of the state abbreviations - I'll come back to that in a while.

```
`mnnmlãGLÏz¯¬ct¸flgaá[9¨kyµmçpCijmsmtnhnvnyn¬kpÂÉcsdk¡x©vavt°±wvwy`ò øUv)?"I am {¥"OR"?"not ":P}"+` à¨\ `:`Wt   à¨\?

```

Try it online

---

## Explanation

* We take a compressed string of the lowercased abbreviations, decompress it, and split it into an array of 2 character strings using the `ò` method.
* We then use the `ø` method to see if the array contains `Uv`, which is the input string converted to lowercase.
* If we so, we build our output string, beginning with `"I am "`
* Checking if the input string `¥` (is equal to) `"OR"` allows us to append either `"not "` or the empty string variable `P`.
* And then we decompress and append the compressed string `"an engineer"`.
* If the input was not found in the array, then we output the decompression of compressed string `"What is an engineer?"`.

# Answer
> 3 votes
# CJam, 143 bytes

```
"ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY"q#g"I am not
I am
What is?"N/=)" an engineer"\

```

Try it online! or as a test suite

### Explanation

```
"ORIA...."       e# Push a string in which every state is a substring, but no non-state is
                 e# a substring.
q                e# Read the input.
#                e# Find the index of the input in the string. (-1 if not found)
g                e# Signum of the index: -1 for negative, 0 for 0, 1 for positive.
"I am.... "      e# Push this string. Note the trailing space on the first two lines of it.
N/               e# Split it on newlines.
=                e# Get the string at index given by the signum.
)                e# Pull out the last character.
" an engineer"\  e# Push " an engineer" and bring the other character to the TOS.
                 e# Implicit output.

```

Since Oregon (`OR`) is at the start of the string, finding the signum of the index of the input in that will be -1 if not found, 0 if `OR`, 1 if any other state. Which string to print can be decided by that.

# Answer
> 3 votes
# Python 3, ~~180~~ ~~179~~ 178 bytes

```
def f(s):e=" not"*(s=="OR")+" an engineer";return"I am"+e if s in"PALAKSCAZ CTNMINCOR FL GA MDE ME MND MA MSD MOKY NE NH NJ NY WA OHID UTX MTNVARIA WIL WVT WY"else"What is"+e+"?"

```

Try it online!

# Answer
> 2 votes
# Haskell, 220 214 210 209 bytes

```
s(a:b:c)=[a,b]:s(b:c)
s _=[]
a="I am "
e="an engineer "
i"OR"=a++"not "++e
i x|x`elem`s"MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY"=a++e
i _="What is "++e++"?"

```

Try it online!

# Answer
> 2 votes
# PHP, 188 Bytes

```
$e=" an engineer";echo strpos(_TNNMLAALAKAZARCACOCTDEFLGAHIIDILINIAKSKYMEMDMAMIMNMSMOMTNENVNHNJNYNCNDOHOKORPARISCSDTXUTVTVAWAWVWIWY,$argn)&1?"I am".($argn!="OR"?"":" not").$e:"What is$e?";

```

Try it online!

# Answer
> 2 votes
## C#, 178 bytes

```
s=>(s=="OR"?"I am notx":"MINCALA MSCTNMNVAKY WAZ PARIA FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY".Contains(s)?"I amx":"What isx?").Replace("x"," an engineer");

```

Run in C# Pad

Golf based on Mayube's solution; new here, so I don't have enough rep to comment.

# Answer
> 1 votes
## Javascript 204

```
s=>{h=/^(A[LKZR]|C[AOT]|DE|FL|[GPLV]A|[HR]I|I[DLNA]|K[SY]|M[EDAINSOT]|N[EVHJMYCD]|O[HK]|S[CD]|T[NX]|[VU]T|W[AVIY]|(OR))$/.exec(s);return(!h?"What is ":"I am "+(h[2]?"not ":""))+"an engineer"+(!h?'?':'')}

```

# Answer
> 1 votes
# Java, 173 bytes

```
s->(!"MINCALARIA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY OR".contains(s)?"What is":"I am"+(s.equals("OR")?" not":""))+" an engineer"

```

# Answer
> 1 votes
# AWK, 189 bytes

```
/A[LKZR]|C[AOT]|DE|FL|[GPV]A|HI|I[DLNA]|KS|KY|LA|M[EDAINSOT]|N[EVHJMYCD]|O[HKR]|RI|SC|SD|TN|TX|UT|VT|W[AVIY]/{print"I am "($0~OR?"not ":"")"an engineer";exit}
{print"What is an engineer?"}

```

If input matches a regex containing all the state abbreviations, print "I am an engineer" with a 'not' inserted in the middle if the state is Oregon, then exit.

If the input does not match the regex, it must not be a US state abbreviation.

# Answer
> 1 votes
# Python 3, 238 bytes

```
def f(x):s=x in('ALAKAZARCACOCTDEFLGAHIIDILINIAKSKYLAMEMDMAMIMNMSMOMTNENVNHNJNMNYNCNDOHOKORPARISCSDTNTXUTVTVAWAWVWIWY'[i:i+2]for i in range(0,100,2));o=x=='OR';q=(1-o)*(1-s);return q*'What is'+(1-q)*('I am'+o*' not')+' an engineer'+q*'?'

```

### Explanation

No compression techniques used.

```
def f(x):
    # Check if State
    s = x in ('ALAK...WIWY'[i:i+2]
              for i in range(0, 100, 2))

    # Check if Oregon
    o = x == 'OR'

    # Check if neither Oregon nor State
    q = (1-o) * (1-s)

    # Construct output string
    return q * 'What is' + \
        (1-q) * ('I am' + o * ' not') + \
        ' an engineer' + \
        q * '?'

```

# Answer
> 1 votes
# Stax, 100 bytes

This language postdates the challenge. But the author (me) didn't see it until now.

```
éë&W≈#W¬π█▐╜╣╟◙√a☻∞ZrπU♫ÿô♠▌⌠Që≡AûpI⌡ÄNAç¶µ↑╝╣òøΩ.¬É]╩Æ↓d∩é¡2Å²eB┼¼▬5∟┤sW♠♂↑q▐WMï╝|Ñ↑╫+3¼↔îûvlLΩ∟┬oë

```

Run and debug it

# Answer
> 1 votes
# JavaScript ES6, ~~175~~171 Bytes

```
x=>[`What is${e=" an engineer"}?`,`I am${x=="OR"?" not"+e:e}`][+!!'MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH ORIA UT WVT WIL WY'.match(x)]

```

Joined lots of good

# Or 152 bytes on ISO encoding

Generator:

```
'x=>[`What is${e=" an engineer"}?`,`I am${x=="OR"?" not"+e:e}`][+!!btoa`*`.match(x)]'.replace('*',atob('MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH ORIA UT WVT WIL WY '.replace(/ /g,'/')))

```

# Answer
> 1 votes
# C (gcc), 0+176 bytes

```
-Dz"=an engineer" -Df(s)*s-79|1[s]-82?strstr("MINCALA=MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY",s)?"I am"z:"What is"z"?":"I am not"z
```

Try it online!

pure translate

# Answer
> 1 votes
# Powershell, 175 bytes

```
(('I am'+' not'*!($i='ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY'.IndexOf($args))+($e=' an engineer')),"What is$e`?")[!++$i]

```

Test script:

```
$f = {

$e=' an engineer'
$i='ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY'.IndexOf($args)
(('I am'+' not'*!$i+$e),"What is$e`?")[!++$i]

# Important! OR is a first state in the modified @totallyhuman's genuis string

}

@(
    ,('OR', 'I am not an engineer')
    ,('AL', 'I am an engineer')
    ,('IL', 'I am an engineer')
    ,('ZZ', 'What is an engineer?')
) | % {
    $s,$e = $_
    $r = &$f $s
    "$($r-eq$e): $r"
}

```

Output:

```
True: I am not an engineer
True: I am an engineer
True: I am an engineer
True: What is an engineer?

```

# Answer
> 0 votes
# Python 3, ~~236~~ ~~182~~ 181 bytes

```
lambda s:'I am not'+e if s=='OR'else'I am'+e if s in'MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY'else'What is%s?'%e
e=' an engineer'

```

Try it online!

TIO contains test cases for all the states.
-54 bytes thanks to the string compression

# Answer
> 0 votes
# q/kdb+, 174 bytes

**Solution:**

```
{a:" an engineer?";$[(#:)l:ss["ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY";x];-1_"I am",$[l~(),0;" not";""],a;"What is",a]}

```

**Explanation:**

```
  {
  // save string into variable a
  a:" an engineer?";
  // try to find the input x in the condensed string, save location in variable l, $ is a if/else
  $[(#:)l:ss["ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY";x];
  // found a match, check if it was at index 0 ('OR') and inject " not" if so, drop the '?' off the end
  -1_"I am",$[l~(),0;" not";""],a;
  // otherwise return 'What is an engineer?'
  "What is",a]
  }

```

**Notes:**

Used the 'compressed' string from other answers, struggling to find a way to bring it into a single line in order to avoid assignment of the `a` variable (yet still add the `?` when input is not a state.

# Answer
> 0 votes
# Retina, 175 bytes

```
..
I am $&~MINCALAZ SCT FL GA WIAKSD ME MD MA MNMS MOKY MTNE NVTX NH NJ NY ND COHIDE PARIL UT VA WA WV WY
(..)~.*\1.*
~
OR~.*
not ~
I am ..~.*
What is ~?
~
an engineer

```

Try it online! Hopefully I've appropriated the best state list. Explanation:

```
..
I am $&~MINCALAZ SCT FL GA WIAKSD ME MD MA MNMS MOKY MTNE NVTX NH NJ NY ND COHIDE PARIL UT VA WA WV WY

```

Start building up the result. Also, insert the state list for use by the next stage.

```
(..)~.*\1.*
~

```

If it's one of the 49 states, delete the state and list.

```
OR~.*
not ~

```

If it's Oregon, replace the state with `not`, and delete the list.

```
I am ..~.*
What is ~?

```

If it's anything else, replace everything with the other output.

```
~
an engineer

```

Add these word in last to avoid repetition.

# Answer
> 0 votes
# Crystal, 232 207 205 Bytes

```
i="ORALAKAZARCACOCTDEFLGAHIIDILINIAKSKYLAMEMDMAMIMNMSMOMTNENVNHNJNMNYNCNDOHOKPARISCSDTNTXUTVTVAWAWVWIWY".split(/(..)/).index ARGV[0];p (i ?"I am ": "What is ")+(i==1 ?"not ": "")+"an engineer"+(i ?"": "?")

```

Try it online. (slightly modified due to an issue of ARGV)

# Answer
> 0 votes
# Factor, 135 bytes

```
USE: usa-cities [ " an engineer"swap [ "I am"swap string>state OR =
[ " not"append ] when ""] [ 2drop "What is" "?"] recover surround ]

```

More readable, and named:

```
: engineer? ( state-name -- str )
  [ " an engineer" ] dip ! put this below the input on the stack
  [
    [ "I am" ] dip       ! put this below the input too but above the other
    string>state OR =    ! string>state throws on a non-state name
    [ " not" append ] when ""  ! otherwise and if it is OR, append this
  ]
  [ 2drop "What is" "?" ] recover surround ; ! catch error, surround string

```

`[ x ] dip` and `x swap` are equivalent in stack effect but the first is shorter only when nested: `[ [ [ x ] dip ] dip ] dip`.

# Answer
> 0 votes
# Python 2, ~~213~~ ~~211~~ 194 Bytes

```
c="uTXnMSCORIDEwVAKYmTNHILfLAZpALmNEmOKSDwINCARmEwAnJnDmAmIAgAwYcTnVToHnYmD"
r=(lambda x:x in c or x[0].lower()+x[1]in c)(i)^1
u="What is "*r+("I am "+"not "*(i=="OR"))*(r^1)+"an engineer"+"?"*r

```

Try It Online

**Stuff i'm working on shortening:**

* `(i=="OR")`
* `or x[0].lower()+x[1]in c`

**Update:**

* Saved 2 Bytes by replacing `s=not r` with `s=r^1`
* Separated header and footer of code

# Answer
> 0 votes
# Ruby, 164 bytes

```
->s{r="What is an engineer?"
j=379
"##(*Q0'7q;N>%*$o(.F%#&'#&#5##%$%+%5%)5r@#P,B353*/%".bytes{|i|s==(j+=i-34).to_s(36).upcase&&r="I am not"[0,i==41?8:4]+r[7,12]}
r}

```

Uses a run length encoding, therefore magic string is 50 bytes long, one per state. In order to build this, it was first necessary to put the state codes in alphabetical order of state code, rather than state name. Unfortunately 7 bytes are needed to convert the base36 representation of `j` from a lowercase statecode into an uppercase statecode.

**Ungolfed in test program**

```
f=->s{                                                  #s is the input string.
  r="What is an engineer?"                              #Set r to "What is an engineer?"
  j=379                                                 #Set j to one less than 380, which in base36 becomes AK, the first statecode alphabetically
  "##(*Q0'7q;N>%*$o(.F%#&'#&#5##%$%+%5%)5r@#P,B353*/%". #Iterate through the run length encoded string
  bytes{|i|                                             #(each character represents how far in base 36 each state code is from the previous one)
    s==(j+=i-34).to_s(36).upcase&&                      #take the ascii value of the character and subtract 34 (example #=35-34=1) and add to j. Convert j to base36 to get a state code.
      r="I am not"[0,i==41?8:4]+r[7,12]                 #if the state code matches s, modify r. Take the first 4 characters of "I am not" (first 8 in the case of OR where i==41)
  }                                                     #and add r[7,12]==" an engineer" (12 characters of the existing value of r, starting at character 7
r}                                                      #return r

%w{AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY XX}.map{|i|p [i,f[i]]}

```

# Answer
> 0 votes
# **/// (Slashes), 2102 bytes**

```
/*/\/-\/\///$/\/,\/\///OR/_not .//AL*AK*AZ*AR*CA*CO*CT*DE*FL*GA*HI*ID*IL*IN*IA*KS*KY*LA*ME*MD*MA*MI*MN*MS*MO*MT*NE*NV*NH*NJ*NM*NY*NC*ND*OH*OK*PA*RI*SC*SD*TN*TX*UT*VT*VA*WA*WV*WI*WY*AA$AB$AC$AD$AE$AF$AG$AH$AI$AJ$AM$AN$AO$AP$AQ$AS$AT$AU$AV$AW$AX$AY$BA$BB$BC$BD$BE$BF$BG$BH$BI$BJ$BK$BL$BM$BN$BO$BP$BQ$BR$BS$BT$BU$BV$BW$BX$BY$BZ$CB$CC$CD$CE$CF$CG$CH$CI$CJ$CK$CL$CM$CN$CP$CQ$CR$CS$CU$CV$CW$CX$CY$CZ$DA$DB$DC$DD$DF$DG$DH$DI$DJ$DK$DL$DM$DN$DO$DP$DQ$DR$DS$DT$DU$DV$DW$DX$DY$DZ$EA$EB$EC$ED$EE$EF$EG$EH$EI$EJ$EK$EL$EM$EN$EO$EP$EQ$ER$ES$ET$EU$EV$EW$EX$EY$EZ$FA$FB$FC$FD$FE$FF$FG$FH$FI$FJ$FK$FM$FN$FO$FP$FQ$FR$FS$FT$FU$FV$FW$FX$FY$FZ$GB$GC$GD$GE$GF$GG$GH$GI$GJ$GK$GL$GM$GN$GO$GP$GQ$GR$GS$GT$GU$GV$GW$GX$GY$GZ$HA$HB$HC$HD$HE$HF$HG$HH$HJ$HK$HL$HM$HN$HO$HP$HQ$HR$HS$HT$HU$HV$HW$HX$HY$HZ$IB$IC$IE$IF$IG$IH$II$IJ$IK$IM$IO$IP$IQ$IR$IS$IT$IU$IV$IW$IX$IY$IZ$JA$JB$JC$JD$JE$JF$JG$JH$JI$JJ$JK$JL$JM$JN$JO$JP$JQ$JR$JS$JT$JU$JV$JW$JX$JY$JZ$KA$KB$KC$KD$KE$KF$KG$KH$KI$KJ$KK$KL$KM$KN$KO$KP$KQ$KR$KT$KU$KV$KW$KX$KZ$LB$LC$LD$LE$LF$LG$LH$LI$LJ$LK$LL$LM$LN$LO$LP$LQ$LR$LS$LT$LU$LV$LW$LX$LY$LZ$MB$MC$MF$MG$MH$MJ$MK$ML$MM$MP$MQ$MR$MU$MV$MW$MX$MY$MZ$NA$NB$NF$NG$NI$NK$NL$NN$NO$NP$NQ$NR$NS$NT$NU$NW$NX$NZ$OA$OB$OC$OD$OE$OF$OG$OI$OJ$OL$OM$ON$OO$OP$OQ$OS$OT$OU$OV$OW$OX$OY$OZ$PB$PC$PD$PE$PF$PG$PH$PI$PJ$PK$PL$PM$PN$PO$PP$PQ$PR$PS$PT$PU$PV$PW$PX$PY$PZ$QA$QB$QC$QD$QE$QF$QG$QH$QI$QJ$QK$QL$QM$QN$QO$QP$QQ$QR$QS$QT$QU$QV$QW$QX$QY$QZ$RA$RB$RC$RD$RE$RF$RG$RH$RJ$RK$RL$RM$RN$RO$RP$RQ$RR$RS$RT$RU$RV$RW$RX$RY$RZ$SA$SB$SE$SF$SG$SH$SI$SJ$SK$SL$SM$SN$SO$SP$SQ$SR$SS$ST$SU$SV$SW$SX$SY$SZ$TA$TB$TC$TD$TE$TF$TG$TH$TI$TJ$TK$TL$TM$TO$TP$TQ$TR$TS$TT$TU$TV$TW$TY$TZ$UA$UB$UC$UD$UE$UF$UG$UH$UI$UJ$UK$UL$UM$UN$UO$UP$UQ$UR$US$UU$UV$UW$UX$UY$UZ$VB$VC$VD$VE$VF$VG$VH$VI$VJ$VK$VL$VM$VN$VO$VP$VQ$VR$VS$VU$VV$VW$VX$VY$VZ$WB$WC$WD$WE$WF$WG$WH$WJ$WK$WL$WM$WN$WO$WP$WQ$WR$WS$WT$WU$WW$WX$WZ$XA$XB$XC$XD$XE$XF$XG$XH$XI$XJ$XK$XL$XM$XN$XO$XP$XQ$XR$XS$XT$XU$XV$XW$XX$XY$XZ$YA$YB$YC$YD$YE$YF$YG$YH$YI$YJ$YK$YL$YM$YN$YO$YP$YQ$YR$YS$YT$YU$YV$YW$YX$YY$YZ$ZA$ZB$ZC$ZD$ZE$ZF$ZG$ZH$ZI$ZJ$ZK$ZL$ZM$ZN$ZO$ZP$ZQ$ZR$ZS$ZT$ZU$ZV$ZW$ZX$ZY$ZZ$-/_.//_/I am //./an engineer//,/What is .?/

```

**Try it online**

## Somewhat ungolfed

```
/OR/_not ./

/AL/-//AK/-//AZ/-//AR/-//CA/-//CO/-//CT/-//DE/-//FL/-//GA/-//HI/-//ID/-//IL/-//IN/-//IA/-//KS/-//KY/-//LA/-//ME/-//MD/-//MA/-//MI/-//MN/-//MS/-//MO/-//MT/-//NE/-//NV/-//NH/-//NJ/-//NM/-//NY/-//NC/-//ND/-//OH/-//OK/-//PA/-//RI/-//SC/-//SD/-//TN/-//TX/-//UT/-//VT/-//VA/-//WA/-//WV/-//WI/-//WY/-/

/AA/,//AB/,//AC/,//AD/,//AE/,//AF/,//AG/,//AH/,//AI/,//AJ/,//AM/,//AN/,//AO/,//AP/,//AQ/,//AS/,//AT/,//AU/,//AV/,//AW/,//AX/,//AY/,//BA/,//BB/,//BC/,//BD/,//BE/,//BF/,//BG/,//BH/,//BI/,//BJ/,//BK/,//BL/,//BM/,//BN/,//BO/,//BP/,//BQ/,//BR/,//BS/,//BT/,//BU/,//BV/,//BW/,//BX/,//BY/,//BZ/,//CB/,//CC/,//CD/,//CE/,//CF/,//CG/,//CH/,//CI/,//CJ/,//CK/,//CL/,//CM/,//CN/,//CP/,//CQ/,//CR/,//CS/,//CU/,//CV/,//CW/,//CX/,//CY/,//CZ/,//DA/,//DB/,//DC/,//DD/,//DF/,//DG/,//DH/,//DI/,//DJ/,//DK/,//DL/,//DM/,//DN/,//DO/,//DP/,//DQ/,//DR/,//DS/,//DT/,//DU/,//DV/,//DW/,//DX/,//DY/,//DZ/,//EA/,//EB/,//EC/,//ED/,//EE/,//EF/,//EG/,//EH/,//EI/,//EJ/,//EK/,//EL/,//EM/,//EN/,//EO/,//EP/,//EQ/,//ER/,//ES/,//ET/,//EU/,//EV/,//EW/,//EX/,//EY/,//EZ/,//FA/,//FB/,//FC/,//FD/,//FE/,//FF/,//FG/,//FH/,//FI/,//FJ/,//FK/,//FM/,//FN/,//FO/,//FP/,//FQ/,//FR/,//FS/,//FT/,//FU/,//FV/,//FW/,//FX/,//FY/,//FZ/,//GB/,//GC/,//GD/,//GE/,//GF/,//GG/,//GH/,//GI/,//GJ/,//GK/,//GL/,//GM/,//GN/,//GO/,//GP/,//GQ/,//GR/,//GS/,//GT/,//GU/,//GV/,//GW/,//GX/,//GY/,//GZ/,//HA/,//HB/,//HC/,//HD/,//HE/,//HF/,//HG/,//HH/,//HJ/,//HK/,//HL/,//HM/,//HN/,//HO/,//HP/,//HQ/,//HR/,//HS/,//HT/,//HU/,//HV/,//HW/,//HX/,//HY/,//HZ/,//IB/,//IC/,//IE/,//IF/,//IG/,//IH/,//II/,//IJ/,//IK/,//IM/,//IO/,//IP/,//IQ/,//IR/,//IS/,//IT/,//IU/,//IV/,//IW/,//IX/,//IY/,//IZ/,//JA/,//JB/,//JC/,//JD/,//JE/,//JF/,//JG/,//JH/,//JI/,//JJ/,//JK/,//JL/,//JM/,//JN/,//JO/,//JP/,//JQ/,//JR/,//JS/,//JT/,//JU/,//JV/,//JW/,//JX/,//JY/,//JZ/,//KA/,//KB/,//KC/,//KD/,//KE/,//KF/,//KG/,//KH/,//KI/,//KJ/,//KK/,//KL/,//KM/,//KN/,//KO/,//KP/,//KQ/,//KR/,//KT/,//KU/,//KV/,//KW/,//KX/,//KZ/,//LB/,//LC/,//LD/,//LE/,//LF/,//LG/,//LH/,//LI/,//LJ/,//LK/,//LL/,//LM/,//LN/,//LO/,//LP/,//LQ/,//LR/,//LS/,//LT/,//LU/,//LV/,//LW/,//LX/,//LY/,//LZ/,//MB/,//MC/,//MF/,//MG/,//MH/,//MJ/,//MK/,//ML/,//MM/,//MP/,//MQ/,//MR/,//MU/,//MV/,//MW/,//MX/,//MY/,//MZ/,//NA/,//NB/,//NF/,//NG/,//NI/,//NK/,//NL/,//NN/,//NO/,//NP/,//NQ/,//NR/,//NS/,//NT/,//NU/,//NW/,//NX/,//NZ/,//OA/,//OB/,//OC/,//OD/,//OE/,//OF/,//OG/,//OI/,//OJ/,//OL/,//OM/,//ON/,//OO/,//OP/,//OQ/,//OS/,//OT/,//OU/,//OV/,//OW/,//OX/,//OY/,//OZ/,//PB/,//PC/,//PD/,//PE/,//PF/,//PG/,//PH/,//PI/,//PJ/,//PK/,//PL/,//PM/,//PN/,//PO/,//PP/,//PQ/,//PR/,//PS/,//PT/,//PU/,//PV/,//PW/,//PX/,//PY/,//PZ/,//QA/,//QB/,//QC/,//QD/,//QE/,//QF/,//QG/,//QH/,//QI/,//QJ/,//QK/,//QL/,//QM/,//QN/,//QO/,//QP/,//QQ/,//QR/,//QS/,//QT/,//QU/,//QV/,//QW/,//QX/,//QY/,//QZ/,//RA/,//RB/,//RC/,//RD/,//RE/,//RF/,//RG/,//RH/,//RJ/,//RK/,//RL/,//RM/,//RN/,//RO/,//RP/,//RQ/,//RR/,//RS/,//RT/,//RU/,//RV/,//RW/,//RX/,//RY/,//RZ/,//SA/,//SB/,//SE/,//SF/,//SG/,//SH/,//SI/,//SJ/,//SK/,//SL/,//SM/,//SN/,//SO/,//SP/,//SQ/,//SR/,//SS/,//ST/,//SU/,//SV/,//SW/,//SX/,//SY/,//SZ/,//TA/,//TB/,//TC/,//TD/,//TE/,//TF/,//TG/,//TH/,//TI/,//TJ/,//TK/,//TL/,//TM/,//TO/,//TP/,//TQ/,//TR/,//TS/,//TT/,//TU/,//TV/,//TW/,//TY/,//TZ/,//UA/,//UB/,//UC/,//UD/,//UE/,//UF/,//UG/,//UH/,//UI/,//UJ/,//UK/,//UL/,//UM/,//UN/,//UO/,//UP/,//UQ/,//UR/,//US/,//UU/,//UV/,//UW/,//UX/,//UY/,//UZ/,//VB/,//VC/,//VD/,//VE/,//VF/,//VG/,//VH/,//VI/,//VJ/,//VK/,//VL/,//VM/,//VN/,//VO/,//VP/,//VQ/,//VR/,//VS/,//VU/,//VV/,//VW/,//VX/,//VY/,//VZ/,//WB/,//WC/,//WD/,//WE/,//WF/,//WG/,//WH/,//WJ/,//WK/,//WL/,//WM/,//WN/,//WO/,//WP/,//WQ/,//WR/,//WS/,//WT/,//WU/,//WW/,//WX/,//WZ/,//XA/,//XB/,//XC/,//XD/,//XE/,//XF/,//XG/,//XH/,//XI/,//XJ/,//XK/,//XL/,//XM/,//XN/,//XO/,//XP/,//XQ/,//XR/,//XS/,//XT/,//XU/,//XV/,//XW/,//XX/,//XY/,//XZ/,//YA/,//YB/,//YC/,//YD/,//YE/,//YF/,//YG/,//YH/,//YI/,//YJ/,//YK/,//YL/,//YM/,//YN/,//YO/,//YP/,//YQ/,//YR/,//YS/,//YT/,//YU/,//YV/,//YW/,//YX/,//YY/,//YZ/,//ZA/,//ZB/,//ZC/,//ZD/,//ZE/,//ZF/,//ZG/,//ZH/,//ZI/,//ZJ/,//ZK/,//ZL/,//ZM/,//ZN/,//ZO/,//ZP/,//ZQ/,//ZR/,//ZS/,//ZT/,//ZU/,//ZV/,//ZW/,//ZX/,//ZY/,//ZZ/,/

/-/_./
/_/I am /
/./an engineer/
/,/What is .?/

```

**TIO, with some examples**

# Answer
> 0 votes
# Python 2, 277 275 201 bytes

Here's one where I've compressed the list to 70 characters. But the compression is complex enough that my decompression makes the code uncompetitively heavy. Perhaps someone else has a better decompression idea.

\[edit:\] You could do this in binary compressed data pretty trivially and save another 25% on the list size. You only need 6 bits/char to do upper and lower case letters. And it'd probably be even more wordy to decode.

The list is lowercase first letter, followed by upper case second letters of everything with that first letter. Order doesn't matter; I used one extra lowercase at the end to make the regular expression work this way.

Using the lambda cleverness from above, it's 201 bytes, but is still too fattened by that regex:

```

lambda s,e=' an engineer':'I am'+' not'*(s=='OR')+e if re.match('.*%s[A-Z]*%s[A-Z]*[a-z]'%(s[0].lower(),s[1]),'aLKZRcAOTdEfLgAhIiDLNAkSYlAmEDAINSOTnEVHJMYCDoHKRpArIsCDtNXuTvTAwAVIYz')else'What is%s?'%e

```

```
def m(t):
 p='I am'
 e=' an engineer'
 if t=='OR':print(p+' not'+e);return()
 else:
  w='What is'
  if re.match('.*%s[A-Z]*%s[A-Z]*[a-z]'%(t[0].lower(),t[1]),'aLKZRcAOTdEfLgAhIiDLNAkSYlAmEDAINSOTnEVHJMYCDoHKRpArIsCDtNXuTvTAwAVIYz')==None:print(w+e+'?');return()
  print(p+e)

```

Try it online!

# Answer
> 0 votes
# Excel VBA, ~~261~~ 254 Bytes

an anonymous vbe immediate window function that takes input as expected type `Variant\String` from cell `[A1]` and outputs my status as an engineer in the given US state to the VBE immediate window.

## Golfed

```
e=" an engineer":i="I am":?IIf(UBound(Filter(Split("AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK PA RI SC SD TN TX UT VT VA WA WV WI WY"),[A1])),IIf([A1]="OR",i+" not"+e,"What is"+e+"?"),i+e)

```

## Ungolfed

```
Function AmIAnEngineer(ByVal state As String) As String

    Dim i As String, _
        e As String

    Let i = "I am"
    Let e = " an engineer"

    Let AmIAnEngineer = _
        IIf(UBound(Filter( _
                Split("AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK PA RI SC SD TN TX UT VT VA WA WV WI WY"), _
                state)), IIf(state = "OR", i & " not" & e, "What is" & e & "?"), i & e)
End Function

''# Usage:
''#
''#     ?AmIAnEngineer("VA")
''#     I am an engineer

```

# Answer
> 0 votes
# Jq 1.5, 186 bytes

```
if.=="OR"then"I am not X"elif inside("MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH RIA UT WVT WIL WY")then"I am X"else"What is X?"end|sub("X";"an engineer")

```

Expanded

```
  if   . =="OR"                                then "I am not X"
  elif inside("@totallyhuman's genius string") then "I am X"
  else                                              "What is X?"
  end
| sub("X";"an engineer")

```

Try it online!

# Jq 1.5, 195 bytes

```
if.=="OR"then"I am not X" elif test("A[LKRZ]|I[ADLN]|M[ADEINOST]|N[CDEHJMVY]|W[AIVY]|[GCLPV]A|[CUV]T|CO|DE|FL|HI|KS|KY|OH|OK|RI|SC|SD|TN|TX")then"I am X"else"What is X?"end|sub("X";"an engineer")

```

Expanded

```
  if   . =="OR"          then "I am not X"
  elif test("big regex") then "I am X"
  else                        "What is X?"
  end
| sub("X";"an engineer")

```

Try it online!

# Answer
> 0 votes
# Python 3, 227 bytes

```
lambda i:['What is an engineer?','I am '+'not '*(i>'OR')+'an engineer'][i in'AL&AK&AZ&AR&CA&CO&CT&DE&FL&GA&HI&ID&IL&IN&IA&KS&KY&LA&M&MD&MA&MI&MN&MS&MO&MT&NE&NV&NH&NJ&NM&NY&NC&ND&OH&OK&OR&PA&RI&SC&SD&TN&TX&UT&VT&VA&WA&WV&WI&WY']

```

Try it online!

# Answer
> 0 votes
# JavaScript (Node.js), 180 bytes

```
x=>[`What is${e=" an engineer"}?`,`I am${x=="OR"?" not"+e:e}`][+!!/A[LKZR]|CO|DE|FL|[GPVCL]A|[HR]I|I[DLNA]|K[SY]|M[EDAINSOT]|N[EVHJMYCD]|O[HKR]|S[CD]|T[NX]|[UVC]T|W[AVIY]/.exec(x)]

```

Try it online!

Somehow the combination of the previous 2 JS answers.

# Answer
> 0 votes
# Python 3, 161 bytes

```
o=('What is%s?','I am'+' not'*(i=='OR')+"%s")[i in'MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH ORIA UT WVT WIL WY']%' an engineer'

```

Try it online!

# Answer
> 0 votes
# Pyth, 145 bytes

I wish I could do stack manipulation in Pyth. *Overly* late to the party...

```
X_1@c"I am not
I am
What is?"b._x"ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY"Q" an engineer"

```

Try it online!

## Explanation

<pre><code>"ORIA MINCALA MSCTNMNVAKY WAZ PAR FL GA NHID COKSD ME MDE MA MTX NE NJ NY ND MOH UT WVT WIL WY"

The magic string from @BusinessCat's answer

x↑Q

What is the string's index in the above magic string? -1 for nonexistent.

._↑

Find the sign, yielding 1, 0, -1.

c"I am not
I am
What is?"b

Split the string into a list of newlines.

@↑ ↑↑

Index the sign into the above splitted list

X_1↑" an engineer"

Insert the string " an engineer" before the last character
```
</code></pre>

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


title: WTF.js Obfuscator

text:
# Question
Title: WTF.js Obfuscator
# Background

One of the commonly meme'd aspects of javascript is its incredibly loose type coercion that allows for `+!![]+[+[]] == '10'` this technique can also be used to create letters as seen in the following example:

```
[[][[]]+[]][+[]][-~[]] == 'n'
[undefined+[]][+[]][-~[]] // [][[]] -> undefined
['undefined'][+[]][-~[]]  // undefined+[] -> 'undefined'
['undefined'][0][-~[]]    // +[] -> 0
'undefined'[-~[]]         // ['undefined'][0] -> 'undefined'
'undefined'[1]            // -~[] -> -(-1) -> 1
'n'

```

Some examples of js coercions:

```
[][[]] = undefined        // out of bounds array access returns undefined
+[][[]] = NaN             // the unary + operator coerces to numbers +undefined is NaN
+[] = 0                   // empty arrays coerce to the number 0
~[]/[] = -Infinity        // ~ coerces any value to a number then does bitwise negation and / coerces the second value to a number
[]+{} = '[Object object]' // plus coerces both values into strings if it can't do numeric addition
![] = false               // ! coerces empty arrays to false
!![] = true               // negation of previous coercion
+!![] = 1                 // number coercion of true
-~[] = 1                  // ~ coerces [] to 0 and the bitwise negation of 0 is -1, -(-1)=1
true+[] = 'true'          // adding an empty array to a primitive coerces it to a string
'true'[+[]] = 't'         // strings are treated as arrays by js
'true'[-~[]] = 'r'

```

Here's a reference table of js coercions using different operators

Note: blue shaded cells in the table are strings while yellow cells are literals.

# Task

Given a string with only the letters `abcdefijlnorstuy` , convert it to valid javascript containing only the characters `[]+-~/{}!` that evaluates to the original string. **Note that this is not JSFuck** but is instead focused purely on a subset of strings that can be (relatively) concisely translated.

# Input

Any lowercase string that can be written with the letters `abcdefijlnorstuy`  (can include spaces)

# Output

Valid javascript containing only the characters `[]+-~/{}!` that will evaluate to the original word in a js environment.

# Examples

```
f('u') -> [[][[]]+[]][+[]][+[]]

f('a') -> [+[][[]]+[]][+[]][-~[]]

f('t') -> [-~[]/[]+[]][+[]][-~[]-~[]-~[]-~[]-~[]-~[]]

f('o') -> [[]+{}][+[]][-~[]]

f('l') -> [![]+[]][+[]][-~[]-~[]]

f('r') -> [!![]+[]][+[]][-~[]]

f('defined') -> [[][[]]+[]][+[]][-~[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]]+[[][[]
]+[]][+[]][-~[]-~[]-~[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]-~[]-~[]]+[[][[]]+[]][
+[]][-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]]

f('aurora borealis') -> [+[][[]]+[]][+[]][-~[]]+[[][[]]+[]][+[]][+[]]+[!![]+[]][
+[]][-~[]]+[[]+{}][+[]][-~[]]+[!![]+[]][+[]][-~[]]+[+[][[]]+[]][+[]][-~[]]+[[]+{
}][+[]][-~[]-~[]-~[]-~[]-~[]-~[]-~[]]+[[]+{}][+[]][-~[]-~[]]+[[]+{}][+[]][-~[]]+
[!![]+[]][+[]][-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]]+[+[][[]]+[]][+[]][-~[]]+[![]
+[]][+[]][-~[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]-~[]-~[]]+[![]+[]][+[]][-~[]-~[
]-~[]]

f('code tennis') -> [[]+{}][+[]][-~[]-~[]-~[]-~[]-~[]]+[[]+{}][+[]][-~[]]+[[][[]
]+[]][+[]][-~[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]]+[[]+{}][+[]][-~[]-~[]-~[]-~[
]-~[]-~[]-~[]]+[-~[]/[]+[]][+[]][-~[]-~[]-~[]-~[]-~[]-~[]]+[[][[]]+[]][+[]][-~[]
-~[]-~[]]+[[][[]]+[]][+[]][-~[]]+[[][[]]+[]][+[]][-~[]]+[[][[]]+[]][+[]][-~[]-~[
]-~[]-~[]-~[]]+[![]+[]][+[]][-~[]-~[]-~[]]

f('js bad') -> [[]+{}][+[]][-~[]-~[]-~[]]+[![]+[]][+[]][-~[]-~[]-~[]]+[[]+{}][+[
]][-~[]-~[]-~[]-~[]-~[]-~[]-~[]]+[[]+{}][+[]][-~[]-~[]]+[+[][[]]+[]][+[]][-~[]]+
[[][[]]+[]][+[]][-~[]-~[]]

f('obfuscate') -> [[]+{}][+[]][-~[]]+[[]+{}][+[]][-~[]-~[]]+[[][[]]+[]][+[]][-~[
]-~[]-~[]-~[]]+[[][[]]+[]][+[]][+[]]+[![]+[]][+[]][-~[]-~[]-~[]]+[[]+{}][+[]][-~
[]-~[]-~[]-~[]-~[]]+[+[][[]]+[]][+[]][-~[]]+[-~[]/[]+[]][+[]][-~[]-~[]-~[]-~[]-~
[]-~[]]+[[][[]]+[]][+[]][-~[]-~[]-~[]]

```

# Rules

Lowest byte count wins.

The solution can be written in any language, but the generated code must evaluate in either chrome, firefox, or a node.js repl.

Don't abuse any common loopholes.

# Answer
> 19 votes
# JavaScript (ES6),  ~~139~~  135 bytes

```
s=>[...s].map(c=>`[{},!![,[][[],![,~[]/[`.split`,`.some(s=>i=~eval(S=`[${s}]+[]][+[]]`).search(c))&&S+`[${'-~[]'.repeat(~i)}]`).join`+`

```

Try it online!

### How?

The following code snippets are used:

```
 code             | string            | used for
------------------+-------------------+-------------------------------------
 [[{}]+[]][+[]]   | '[object Object]' | space, 'b', 'c', 'e', 'j', 'o', 't'
 [!![]+[]][+[]]   | 'true'            | 'r', 'u'
 [[][[]]+[]][+[]] | 'undefined'       | 'd', 'f', 'i', 'n'
 [![]+[]][+[]]    | 'false'           | 'a', 'l', 's'
 [~[]/[]+[]][+[]] | '-Infinity'       | 'y'

```

We pick the appropriate character in the resulting string with `[-~[]-...-~[]]`.

We can't access index \\$0\\$ this way, so we make sure that the snippets are ordered in such a way that this is never required. For instance, '*u*' is taken from '*true*' rather than from '*undefined*'.

# Answer
> 17 votes
I have a solution which works if you have infinite time and memory. I'm not 100% sure whether that's allowed within the rules here; I searched on codegolf.meta.SE and didn't find anything saying that code-golf answers have to run in a reasonable length of time using a reasonable amount of memory. I also didn't find it forbidden in the "common loopholes" thread. If it makes my solution invalid, please let me know.

# JavaScript (ES6), ~~112, 110, 107~~ 106 bytes

```
s=>{for(q=[''];;c=q.shift(),q.push(...[...'[]+-~/{}!'].map(x=>c+x)))try{return eval(c)===s?c:d}catch(e){}}

```

It isn't restricted to string inputs, and can find short solutions in reasonable times, but unfortunately it's not feasible to solve for non-empty strings, even just single-characters like `'o'`. Here it is working on some inputs for which it is feasible.

```
> f(0)
"+[]"
> f(1)
"-~[]"
> f(-1)
"~[]"
> f(true)
"!+[]"
> f(false)
"![]"
> f('')
"[]+[]"

```

### How?

It's a breadth-first search. `q` is the queue, `c` is the current string. The breadth-first search algorithm will iterate through every possible string formed from the given alphabet, in order of length, so if a solution exists, it will be found.

We try evaluating `c` with the `eval` function, and return it if it evaluates to `s`. This comparison is done with `===` to avoid e.g. returning `+[]` which evaluates to 0 when we're looking for an expression which evaluates to the empty string. The variable `c` is uninitialised on the first iteration of the loop, but that's OK because it's only used within the `try` block.

We need `try`/`catch` because most candidate strings have syntax errors; as a bonus, instead of guarding the `return` with an `if` statement, we can return the non-existent name `d` because the error will get caught, allowing the loop to continue searching. This saves one byte, but it means the function stops working if you declare a variable named `d`, which is mildly amusing.

# Answer
> 11 votes
# Python 2, 125 bytes

Using a single code snippet.

```
print[]
for c in input():print'+[{}+!![]+![]+~[]/[]+[][[]]][+[]]['+'-~[]'*(ord('#2??;"?4?9 &?/5%03!$B'[ord(c)%59%21])-31)+']'

```

Try it online!

Try the output in JS!

---

# Python 2,  ~~167~~  150 bytes

*Saved 2 bytes thanks to @JonathanAllan*

```
print[]
for c in input():i=ord(".@C1A83J42/K70DIY"[ord(c)*91%211%23]);print'+['+"[{} !![ [][[] ![ ~[]/[".split()[i/9-5]+']+[]][+[]]['+'-~[]'*(i%9)+']'

```

Try it online!

Try the output in JS!

### How?

This is based on the same code snippets as my JS answer, but a lookup string is used to retrieve the snippet ID and the position of the character.

Given the ASCII code \\$c\\$ of the character to be converted, the position in the lookup string is given by:

$$i=((c\times91)\bmod211)\bmod23$$

Given the ASCII code \\$n\\$ of the \\$i\\$-th character in the lookup string `".@C1A83J42/K70DIY"`:

* the snippet ID is \\$\lfloor(n-45)/9\rfloor=\lfloor n/9\rfloor-5\\$
* the position of the character is \\$(n-45)\bmod9=n\bmod9\\$

This is summarized in the following table.

```
 char. | ASCII code | -45 | //9 | mod 9 | character lookup     | output
-------+------------+-----+-----+-------+----------------------+--------
  '.'  |     46     |   1 |  0  |   1   | '[object Object]'[1] |  'o'
  '@'  |     64     |  19 |  2  |   1   | 'undefined'[1]       |  'n'
  'C'  |     67     |  22 |  2  |   4   | 'undefined'[4]       |  'f'
  '1'  |     49     |   4 |  0  |   4   | '[object Object]'[4] |  'e'
  'A'  |     65     |  20 |  2  |   2   | 'undefined'[2]       |  'd'
  '8'  |     56     |  11 |  1  |   2   | 'true'[2]            |  'u'
  '3'  |     51     |   6 |  0  |   6   | '[object Object]'[6] |  't'
  'J'  |     74     |  29 |  3  |   2   | 'false'[2]           |  'l'
  '4'  |     52     |   7 |  0  |   7   | '[object Object]'[7] |  ' '
  '2'  |     50     |   5 |  0  |   5   | '[object Object]'[5] |  'c'
  '/'  |     47     |   2 |  0  |   2   | '[object Object]'[2] |  'b'
  'K'  |     75     |  30 |  3  |   3   | 'false'[3]           |  's'
  '7'  |     55     |  10 |  1  |   1   | 'true'[1]            |  'r'
  '0'  |     48     |   3 |  0  |   3   | '[object Object]'[3] |  'j'
  'D'  |     68     |  23 |  2  |   5   | 'undefined'[5]       |  'i'
  'I'  |     73     |  28 |  3  |   1   | 'false'[1]           |  'a'
  'Y'  |     89     |  44 |  4  |   8   | '-Infinity'[8]       |  'y'

```

# Answer
> 8 votes
# Prolog (SWI), 269 bytes

It's not a particularly short solution, but made this challenge interesting because it is able to use backtracking to automatically select which string and index into that string to use for each character.

```
`fals`^`![]+[]`.
`[object `^`[]+{}`.
`und`^`[][[]]+[]`.
`-Infinity`^`~[]/[]+[]`.
`tr`^`!![]+[]`.
[]-`[]`.
[H|T]-S:-B^C,nth0(I,B,H),length(L,I),foldl([_,V]>>append(`-~[]+`,V),L,` +[]`,J),T-U,append([`[`,C,`][+[]][`,J,`]+`,U],S).
S/W:-S+A,A-B,W+B.
A+B:-string_codes(A,B).

```

Try it online!

# Ungolfed Code

```
% Declaration of strings we can generate with their corresponding JS.
base_str(`undefined`,`[[][[]]+[]][+[]]`).
base_str(`[object Object]`, `[]+{}`).
base_str(`Infinity`, `[-~[]/[]+[]][+[]]`).
base_str(`NaN`, `[+[][[]]+[]][+[]]`).
base_str(`true`, `!![]+[]`).
base_str(`false`, `![]+[]`).

% Construct JS used to index into strings
wtf_index(0,`+[]`).
wtf_index(1,`-~[]`).
wtf_index(N, S0) :-
  N > 1,
  wtf_index(1, S1),
  M is N - 1,
  wtf_index(M, S2),
  append([S1,`+`,S2],S0).

% Construct JS used for single char
wtf_char(C, WC) :-

  % Find known string with desired character at some index
  base_str(S, WS),
  nth0(I, S, C),

  % JS for this index
  wtf_index(I, WI),

  % JS to select index from string
  append([`(`,WS,`)[`,WI,`]`],WC).

% Map wtf_char over string, reducing to single string
wtf_list([], `[]`).
wtf_list([H|T], WS) :-
  wtf_char(H, WH),
  wtf_list(T, WT),
  append(WH, [0'+|WT], WS).

wtf_str(S, W) :-
  string_codes(S, SC),
  wtf_list(SC, WC),
  string_codes(W, WC).

```

# Answer
> 5 votes
# JavaScript (Node.js), 104 bytes

```
s=>[...s].map(c=>(p=`[{}+!![]+![]+~[]/[]+[][[]]][+[]]`)+`[${'-~[]'.repeat(eval(p).search(c))}]`).join`+`

```

Try it online!

**Explanation**

Each letter is converted to a string of the form

```
[{}+!![]+![]+~[]/[]+[][[]]][+[]][x]

```

Where `x` is a number of `-~[]`

`[{}+!![]+![]+~[]/[]+[][[]]][+[]]` evaluates to the string `[object Object]truefalse-Infinityundefined`, which contains all of our letters. We then index into it by using this snippet:

```
`[${'-~[]'.repeat(eval(p).search(c))}]`

```

It evaluates `[{}+!![]+![]+~[]/[]+[][[]]][+[]]` (stored in variable p), then finds the first index of the current letter we are processing. We repeat the string `+~-[]` (evaluates to 1) that number of times. That is wrapped around with square brackets, and appended to `p`.

Finally, everything is joined with `+`.

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 156 bytes

```
x=>string.Join('+',x.Select(l=>"[{}+!![]+![]+~[]/[]+[][[]]][+[]]["+new StringBuilder().Insert(0,"-~[]",$"[object {0,8}ru fals{0,9}y nd fi".IndexOf(l))+"]"))

```

Try it online!

**Explanation**

Each letter is converted to a string of the form

```
[{}+!![]+![]+~[]/[]+[][[]]][+[]][x]

```

Where `x` is a number of `-~[]`

`[{}+!![]+![]+~[]/[]+[][[]]][+[]]` evaluates to `[object Object]truefalse-Infinityundefined`, which contains all the letters. We index into the string `$"[object {0,8}ru fals{0,9}y nd fi"`, which expands to

```
[object        0ru fals        0y nd fi

```

We take the current letter and get the first index of it in that string. We then repeat the string `-~[]` that number of times, and replace the `x` with that.

Repeating a string is rather verbose in C#, as there is no builtin for it. Instead, a `StringBuilder` is created, and taking advantage of the `StringBuilder.Insert(int, string, int)` overload (which inserts the string `n2` times at index `n1`) to created a `StringBuilder` containing a repeated string. It is implicitly converted to a string due to the magic of the `+` operator.

```
new StringBuilder().Insert(0,"+-~[]",$"[object {0,8}ru fals{0,9}y nd fi".IndexOf(l))

```

Finally, the converted strings are joined together with `+`.

# Answer
> 2 votes
# Charcoal, 95 bytes

```
≔⪪“<≦ω≕ε…(Ｂς´Ｂ⌈ＹWγ№Φξ⌕IY¦l ”,ηＦＳ«≔⊟Φ⁵№§ηκιζ⊞υ⪫[]⁺⁺§⪪“"∧｜⌊AuüQ⁷～⊙<⁷≕u?ψμ”,ζ×+[]][²×-~[]⌕§ηζι»⪫υ+

```

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

```
≔⪪“<≦ω≕ε…(Ｂς´Ｂ⌈ＹWγ№Φξ⌕IY¦l ”,η

```

Split the compressed string `"\n\nd,\nals,\nru,\\nnfi\n\n\ny,\nobject "` on commas. This is the array `["undefined", "false", "true", "Infinity", "[object Object]"]` keeping only the space and unique letters and truncated at the last remaining letter to improve the compression.

```
ＦＳ«

```

Loop over the input string.

```
≔⊟Φ⁵№§ηκιζ

```

Find the entry that contains the current input character.

```
⊞υ⪫[]⁺⁺§⪪“"∧｜⌊AuüQ⁷～⊙<⁷≕u?ψμ”,ζ×+[]][²×-~[]⌕§ηζι

```

Split the compressed string `"[][[]],![],!![],~[]/[],{}"` on commas and take the matching entry, then concatenate it with `"+[]]["` doubled and a suitable number of repetitions of `"-~[]"` before finally wrapping everything inside a final set of `[]`.

```
»⪫υ+

```

Join everything together with `+`s.

---
Tags: code-golf, javascript, obfuscation
---