title: Implement a URL shortener

text:
# Question
Title: Implement a URL shortener
URLs are getting too long. So, you must implement an algorithm to shorten a URL.

## i. The Structure of a URL

A URL has 2 main parts: a **domain** and a **path**. A domain is the part of the URL before the first slash. You may assume that the URL does not include a protocol. The path is everything else.

## ii. The Domain

The domain of a URL will be something like: `xkcd.com` `meta.codegolf.stackexcchhannnge.cooom`. Each part is period-seperated, e.g. in `blag.xkcd.com`, the parts are "blag", "xkcd", and "com". This is what you will do with it:

* If it contains more than two parts, put the last two aside and concatenate the first letter of the rest of the parts.
* Then, concatenate that to the first letter to the second-to-last part.
* Add a period and the second and third letter of the second-to-last part.
* Discard the last part.

## iii. The Path

The path will be like: `/questions/2140/` `/1407/`. As before, "parts" are seperated by slashes. For each part in the path, do:

* Add a slash
* If it is completely made of base-ten digits, interpret it as a number and convert to a base-36 integer.
* Otherwise, add the first letter of the part.

At the end, add a slash.

## iv. Misc.

* This is , so shortest code wins.
* The path can be empty, but the URL will always end with a slash.
* There will not be a protocol (e.g. `http://`, `file:///`)
* There will never be less than two parts in the domain.
* Standard loopholes apply.

## Examples

In: `xkcd.com/72/`
Out: `x.kc/20/`

In: `math.stackexchange.com/a/2231/`
Out: `ms.ta/a/1pz/`

In: `hello.org/somecoolcodeintrepreteriijjkk?code=3g3fzsdg32,g2/`
Out: `h.el/s/`

# Answer
## Pyth, 93 85 bytes

```
Lsm@+jkUTGdjb36J<zxz\/KP>zhxz\/=cJ\.pss[mhd<J_2hePJ\.<tePJ2\/;=cK\/sm+?-djkUThdysd\/K

```

Hand-compiled to pythonic pseudocode:

```
                z = input()                     # raw, unevaluated
                G = "abcdefghijklmnopqrstuvwxyz"
                k = ""
                T = 10
L               def y(b):                       # define y as base10to36
 sm                 join(map(lambda d:
  @+jkUTGd            (join(range(T),interleave=k)+G)[d],
                                                # the join(..)+G makes "0...9a...z"
  jb36                 convert(b,36)            # returns a list of digit values in base10
J<zxz\/         J = z[:z.index("\/")]           # domain portion
KP>zhxz\/       K = z[1+z.index("\/"):][:-1]    # path portion
=cJ\.           J = J.split(".")                # splits domain into parts
pss[            no_newline_print(join(join[     # 1 join yields a list, the other a string
 mhd<J_2            map(lambda d:d[0],J[:-2]),
 hePJ               J[:-1][-1][1],
 \.                 ".",
 <tePJ2             J[:-1][-1][1:][:2],
 \/                 "\/"
;               ])
=cK\/           K = K.split("\/")
sm              print(join(map(lambda d:
 +?-djkUThdysd\/    "\/"+(d[0] if filterOut(d,join(range(T),interleave=k)) else y(int(d))),
                    # the filter will turn pure number into empty string, which is False
 K                  K)))

```

Finally, the excruciation ends...
> 1 votes

# Answer
# JavaScript (ES6), 149 bytes

```
u=>u.split`/`.map((p,i)=>i?/^\d+$/.test(p)?(+p).toString(36):p[0]:(d=p.split`.`).slice(0,-1).map((s,j)=>s[l=j,0]).join``+"."+d[l].slice(1,3)).join`/`

```

## Explanation

I made this independent of @Neil's solution but it ended up looking *very* similar.

```
u=>
  u.split`/`.map((p,i)=>       // for each part p at index i
    i?                         // if this is not the first part
      /^\d+$/.test(p)?         // if p is only digits
        (+p).toString(36)      // return p as a base-36 number
      :p[0]                    // else return the first letter
    :
      (d=p.split`.`)           // d = domain parts
      .slice(0,-1).map((s,j)=> // for each domain part before the last
        s[l=j,0]               // return the first letter, l = index of last domain part
      ).join``
      +"."+d[l].slice(1,3)     // add the 2 letters as the final domain
  )
  .join`/`                     // output each new part separated by a slash

```

## Test

```
var solution = u=>u.split`/`.map((p,i)=>i?/^\d+$/.test(p)?(+p).toString(36):p[0]:(d=p.split`.`).slice(0,-1).map((s,j)=>s[l=j,0]).join``+"."+d[l].slice(1,3)).join`/`
```

```
<input type="text" id="input" value="math.stackexchange.com/a/2231/" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 4 votes

# Answer
## JavaScript ES6, 157 bytes

```
u=>u.split`/`.map((p,i)=>i?/^\d+$/.test(p)?(+p).toString(36):p[0]:p.split`.`.reverse().map((h,i)=>i--?i?h[0]:h[0]+'.'+h[1]+h[2]:'').reverse().join``).join`/`

```

Edit: Saved 4 bytes thanks to Doᴡɴɢᴏᴀᴛ.
> 1 votes

# Answer
# Python 2, ~~378~~ 365 Bytes

**Update**

Golfed it down by a bit. The ~150 Bytes for the base36-function are annoying, but I can't get rid of it until python has a builtin for that...

```
def b(n):
 a=abs(n);r=[];
 while a :
    r.append('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'[a%36]);a//=36
 if n<0:r.append('-')
 return''.join(reversed(r or'0'))
u=raw_input();P=u.split("/")[0].split(".")
print"".join([p[0] for p in P[0:-2]]+[P[-2][0]]+["."]+list(P[-2])[1:3]+["/"]+[b(int(p))+"/"if p.isdigit()else p[0]+"/" for p in u.split(".")[-1].split("/")[1:-1]])

```

**Old version**

```
def b(n):
 a=abs(n)
 r=[]
 while a:
    r.append('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'[a%36])
    a//=36
 if n<0:r.append('-')
 return''.join(reversed(r or'0'))
u=raw_input()
P=u.split("/")[0].split(".")
s=""
if len(P)>2:
 for p in P[:-2]:s+=p[0]
s+=P[-2][0]+"."+P[0][1:3]
P=u.split(".")[-1].split("/")[1:-1]
for p in P:
 s+="/"+(b(int(p)) if p.isdigit() else p[0])
print s+"/"

```

Since Python does not have a builtin way to convert ints to a base36-String, I took the implementation from numpy and golfed it down. Rest is pretty straightforward, I will golf it down more after work. Suggestions always appreciated in the meantime!
> 1 votes

# Answer
**Pyhton 2, ~~336~~ 329 bytes**

**update**

fixed and shorter thanks to webwarrior

```
def b(a):
 r=''
 while a:
  r+=chr((range(48,58)+range(65,91))[a%36])
  a//=36
 return ''.join(reversed(r or '0'))
u=raw_input()
P=u.split('/')[0].split('.')
s=''
if len(P)>2:
 for p in P[:-2]: s+=p[0]
s+=P[-2][0]+'.'+P[0][1:3]
P=u.split('.')[-1].split('/')[1:]
for p in P: s+='/'+(b(int(p)) if p.isdigit() else p[0])
print s+'/'

```

**original**

DenkerAffe's version with some mods : correctly handle "foo/bar?baz" scheme, plus, no need for negative case in the base36 conversion function.

```
 def b(a):
 r=''
 while a:
  r+=('0123456789ABCDEFGHUKLMNOPQRSTUVWXYZ'[a%36])
  a//=36
 return ''.join(reversed(r or '0'))
u=raw_input()
P=u.split('/')[0].split('.')
s=''
if len(P)>2:
 for p in P[:-2]: s+=p[0]
s+=P[-2][0]+'.'+P[0][1:3]
P=u.split('.')[-1].split('/')[1:]
for p in P: s+='/'+(b(int(p)) if p.isdigit() else p[0])
print s+'/'

```
> 0 votes

---
Tags: code-golf, string, compression
---


title: What's the Language?

text:
# Question
Title: What's the Language?
Recently, the PPCG design leaderboard has been having some trouble parsing answer **html headers**.

In this challenge you'll be taking your own shot at parsing answer headers.

---

## Example Test Cases

These **example inputs** (**NOT** actual test cases), just so you can get the idea of how inputs **might** be like

```
Input: <h1>Python 3, 32 bytes</h1>
Desired Output: Python 3

Input: <h1>JavaScript, 13 chars / 32 bytes</h1>
Desired Output: JavaScript

Input: <b>VeryBadlyFormattedHeader v3 : (32 bytes)</b>

```

## Spec

**Your program should be 150 bytes or below**

You will be given a line of an answer header's html, you'll need to try to do your best to successfully extract the language. Input may contain unicode characters.

Output case matters.

## Tests

**Github Gist with test cases**

There is one test case per line. The format is:

```
<lang_name> - <rest_of_the_line_is_the_header>

```

## Scoring

Your score is:

```
 Number Correct
----------------
  Total Number

```

(which is a percent)

Tie-breaker is shortest code.

# Answer
> 11 votes
# Retina 0.8.2, 100%, ~~75~~ ~~71~~ ~~70~~ ~~68~~ ~~67~~ ~~64~~ ~~59~~ ~~53~~ 51 bytes

```
<.*?>

(,| [-&(–5]| [0-7]\d)(?! W|...\)).*

2 |:

```

This is essentially code golf now, so I had to switch languages.

Try it online!

### Verification

```
$ wget -q https://gist.githubusercontent.com/vihanb/1d99599b50c82d4a6d7f/raw/cd8225de96e9920db93613198b012749f9763e3c/testcases
$ grep -Po '(?<= - ).*' < testcases > input
$ grep -Po '^.*?(?= - )' < testcases > output
$ mono retina/Retina.exe headers.ret < input | head -n -1 | diff -s - output
Files - and output are identical

```

### How it works

The code consists of three simple substitutions (or eliminations). Instead of trying to match the language name, we get rid of all parts of the input string that do form part of it.

1. `<.*?>` will match all HTML tags, so the substitution will eliminate them from the input.

`.*?` matches any amount of characters, but since `?` makes the quantifier *lazy*, it will match the least amount possible that still allows the entire pattern to match. This avoid deleting the entire input, which will always begin with a `<` and end with a `>`.

The language name now begins with the first character of the remaining modified input string.
2. After the language's name, we will almost always find one of the following endings:

`,`, `-`, `&`, `(`, , `5`, or a space followed by two digits.

The first two endings are rather common, and `Python 2 & PuLP...` should be parsed as `Python 2`, `Ruby (2.2.2p95)...` as `Ruby`, `>PHP – 3302 bytes` as `PHP`, and `Perl 5...` as `Perl`.

`(,| [-&(–5]| \d\d).*` would match all these endings (and all characters after them), but it will result in a few false positives:

* `,` will match the comma in the language name `Help, WarDoq!`.
    * `(` will match the version of `JavaScript (ESx)` and `Java (1.8)`.
    * `\d\d` will match the version in `Ti-Basic 84`.

We can fix the third problem case by using `[0-7]\d` instead of `\d\d`, to avoid matching the `8` in `84`.

For the other problem cases, we use the negative lookahead `(?! W|...\))` that will prevent the preceding pattern from matching if it is followed by `W` (as in `Help, WarDoq!`) or by exactly three characters and a closing parenthesis (as in `(ES6)` or `(1.8)`).

Putting it all together, `(,| [-&(–5]| [0-7]\d)(?! W|...\)).*` matches everything after the language name.
3. We're left with two problem cases:

```
<h1>Python <s>2</s> 3, <s>255</s> <s>204</s> <s>180</s> 178 bytes</h1>
<h1><a href="http://sylwester.no/zozotez/" rel="nofollow">Zozotez Lisp</a>: 73</h1>

```

gets parsed as

```
Python 2 3
Zozotez Lisp:

```

We can fix the first by removing  and the second one by removing `:` from the output.

This is achieved by replacing `2 |:` with the empty string.

# Answer
> 16 votes
# Bash, 100%, 100 bytes

```
sed sX..s.2./s.XX|grep -Po '(?<=>)[^<]+?(?=(,(?! W)| [-&–5]| ?<| [0-79]\d| ?\((?!E|1\.)))'|head -1

```

Try it online on Ideone.

### Verification

```
$ wget -q https://gist.githubusercontent.com/vihanb/1d99599b50c82d4a6d7f/raw/cd8225de96e9920db93613198b012749f9763e3c/testcases
$ grep -Po '(?<= - ).*' < testcases > input
$ grep -Po '^.*?(?= - )' < testcases > output
$ while read line; do bash headers.sh <<< "$line"; done < input | diff -s - output
Files - and output are identical

```

# Answer
> 4 votes
# CJam, 78.38% (76 bytes)

```
l{_'>#)>_c'<=}g_'<#<_{",-"&}#)_{_1$=',=+(<}{;}?

```

Try it online! or count the correct headers.

# Answer
> 4 votes
# Jolf, 13 bytes, 85.94%, noncompeting

```
ρΥpΔid=',H',E
  pΔi         remove all HTML tags from input, preserving content
 Υ   d=',H     slice from beginning until a member is a comma
ρ         ',E  replace said comma with the empty string

```

I had this update on my computer. It was to my chagrin that I had forgotten to update the respective code for the interpreter. I don't feel like shooting for 100%. Maybe everyone should format their headers the same ¯\\\_(ツ)\_/¯

---
Tags: code-challenge, parsing, test-battery
---


# Question
Title: Equivalence classes on the Transitive Closure of a Reflexive Relation
The goal of this challenge is to compute the set of equivalence classes over the transitive closure of a symmetric, reflexive relation. For those who don't know what that means, here is a brief introduction into the relevant terms:

A relation ◊ is *symmetric* if *a**b**b**a*. It is *reflexive* if each object is related to itself, i.e. *a**a* always holds. It is *transitive* if *a**b**b**c**a**c*, i.e. if *a* is related to *b* and *b* is related to *c*, then *a* is related to *c*. An *equivalence relation* is a relation that is symmetric, reflexive and transitive.

The *transitive closure* ◊\* of ◊ is a transitive relation such that *a* ◊\* *b* holds if and only if there is a (possibly empty) series of objects *c*1, *c*2, ..., *c**n* such that *a**c*1*c*2 ◊ ··· ◊ *c**n**b*. The transitive closure of a symmetric, reflexive relation is an equivalence relation.

Let ≡ be an equivalence relation over the set *S*. An *equivalence class* *a* of an object *a* over the relation ≡ is the largest subset of *S* such that *a**x* for all *x**S* or formally: *a* = { *x* | *x**S*, *a**x* }. All elements of *a* are equivalent to one another.

The *set of equivalence classes* *S*/≡ of ≡ over *S* is the set of equivalence classes of all members of *S*.

## Constraints

In this task, your objective is to write a function that takes a binary relation ≅ and a finite non-empty set *S*. You may take input in a suitable way and choose a suitable data-structure for *S* (e.g. an array or a linked list). Assume that ≅ is a symmetric, reflexive relation over *S*. Your function should return or print out the set of equivalence classes over *S* of the transitiveclosure of ≅. You may choose a suitable output format or data structure for the result. As the result is a set, each object in *S* may appear only once.

You may not use library routines or other builtin functionality to find the components of a graph or related things.

## Winning condition

The shortest answer in octets wins. The most elegant answer is chosen in case of a tie.

## Sample input

The reflexive and symmetric members of ≅ have been omitted for brevity.

*S*1 = {A, B, C, D, E, F, G, H}
1 = {(A, B), (B, C), (B, E), (D, G) (E, H)}
*S*1/≅1* = {{A, B, C, E, H}, {D, G}, {F}}.

*S*2 = {α, β, γ, δ, ε, ζ, η, θ, ι, κ}
2 = {(α, ζ), (α, ι), (β, γ), (β, ε), (γ, δ), (γ, ε), (ζ, θ), (η, κ), (θ, ι)}
*S*2/≅2* = {{α, ζ, θ, ι}, {β, γ, δ, ε}, {η, κ}}

*S*3 = {♠, ♣, ♥, ♦}
3 = {}
*S*3/≅3* = {{♠}, {♣}, {♥}, {♦}}

*S*4 = {Α, Β, Γ, Δ, Ε, Ζ, Η, Θ, Ι, Κ, Λ}
4 = {(Α, Ε), (Β, Ζ), (Γ, Η), (Δ, Θ), (Ε, Ι), (Ζ, Κ), (Η, Λ), (Θ, Α), (Ι, Β), (Κ, Γ), (Λ, Δ)}
*S*4/≅4* = {{Α, Β, Γ, Δ, Ε, Ζ, Η, Θ, Ι, Κ, Λ}}

# Answer
# Pyth, ~~50~~ 29 bytes

```
JchQ1FNeQAmf/@JTd0N XGJ.(JH;J

```

Input is expected to be a list of two elements where the first element is a list of all the objects in S, and the second element is a list of all the members in ≅, represented as lists. So for the first example, the input is

```
[["A", "B", "C", "D", "E", "F", "G", "H"], [["A", "B"], ["B", "C"], ["B", "E"], ["D", "G"], ["E", "H"]]]

```

Explanation:

```
                               Implicit assignment of Q to input, so head(Q) is S and end(Q) is ≅
JchQ1                          Assign J to chop(head(Q),1) e.g. [1,2,3] => [[1],[2],[3]]
     FNeQ                      For N in end(Q)
         A                       Assign [H,G] to following list
          m       N                Map following function over N
           f     0                   Return first T where following function of T starting at 0,1,2... is truthy
            /@JTd                      lambda d: true if d is J[T]
                    XGJ.(JH;     Append J[H] to J[G] and pop J[H]
                            J  Print J

```

Note that if transitive or reflexive members (i.e. redundant) members of ≅ are included, my code should output junk.

You can try it out here.
> 1 votes

---
Tags: code-golf, math, graph-theory
---


title: Create an interpreter for "Counter"

text:
# Question
Title: Create an interpreter for "Counter"
"Counter" is a language I've created for the purpose of this question.

**Rules**

* Commands are read from left to right from the first character.
* Each command may be executed as it is read, or you may execute all commands together at the end.
* In case of an error, all commands up till the error must be executed.
* A program is written in exactly one line.
* Data is stored in counters. At the start, there is exactly one counter. More can be created and deleted.
* A counter holds an integer value between -100 and 100 (limits inclusive).
* Exactly one counter is the selected counter at any point in time.
* Counters are arranged in a 1d array, so one can move left (previous) or right (next) to change selected counter.

**Commands**

* **Any number between -100 and 100** \- Set the currently selected counter to that value.
* **c** \- Create a counter immediately after the currently selected counter, make it the selected counter, and set it to 0.
* **d** \- Delete the currently selected counter, and make the previous one selected. If it is the first one, this is an error.
* **+** \- Make the next counter the selected one.
* **-** \- Make the previous counter the selected one. (Ensure that this command is not immediately followed by a number.)
* **o** \- Output the value in the selected counter, followed by a space.
* **?** \- If the value in the selected counter is 0, apply the **d** command on it.
* **#** \- If the value in the selected counter is 0, ignore the next command.
* (space) - No meaning, but is to be treated like a command, if preceded by a #. Used to demarcate numbers.

**Errors**

* Going left of the leftmost counter, or right of the rightmost counter.
* Deleting the first counter.
* Encountering a `#` as the last command. (Of course, this means all commands will get executed anyways)
* A command that does not exist.
* A number that's too long.

**Task**

Create an interpreter in any language. Code will be in a file or given as input (your choice). Shortest code wins.

**Lengthy example**

Consider the code:

```
7cc--13 12do?+?#0#o3od-7o

```

Here is a breakdown of the program. `[]` indicates the selected counter.

```
Cmd   Memory    Output

7     [7]
c     7 [0]
c     7 0 [0]
-     7 [0] 0
-13   7 [-13] 0
      7 [-13] 0
12    7 [12] 0
d     [7] 0
o     [7] 0     7
?     [7] 0
+     7 [0]
?     [7]
#     [7]
0     [0]
#     [0]
o     [0]
3     [3]
o     [3]       3
d     This is an error. Program terminates here.

```

Total output `7 3`

# Answer
## Python3, 403 ~~530~~ bytes

~~This is seriously golfable, but I can't think of how...~~

Thanks to @cat for 127 bytes!!! (I'm really bad at golfing in Python)

```
c=input()
a=[0]
s=0
i=0
def g(i,n):
 p=i
 if n:i+=1
 while c[i].isdigit():i+=1
 a[s]=int(c[p:i]);return i-1
def e():
 a.pop(s);s-=1
while i<len(c):
 d=c[i]
 if d.isdigit():i=g(i,0)
 elif d=='c':s+=1;a.insert(s,0)
 elif d=='d':e()
 elif d=='+':s+=1
 elif d=='-':
  if c[i+1].isdigit():i=g(i,1)
  else:s-=1
 elif d=='o':print(a[s],end=' ')
 elif d=='?':
  if a[s]==0:e()
 elif d=='#':
  if a[s]==0:i+=1
 i+=1

```
> 1 votes

# Answer
# JavaScript ES6, 300 bytes

Hey look, a nice round number!

```
x=>x.match(/-\d*|\d+|./g).map(c=>e?0:q?q--:c-101?Math.abs(c)>100?e++:s[p]=+c:c=="c"?s.splice(++p,0,0):c=="d"?s.length>1?s.splice(p--,1):e++:c=="o"?o+=s[p]+" ":c=="-"?--p<0&&e++:c=="+"?++p>=s.length&&e++:c=="?"?s[p]||(s.length>1?s.splice(p--,1):e++):c=="#"?s[p]||q++:c==" "?0:e++,s=[],e=p=q=0,o="")&&o

```

It doesn't error on `#` at the end of a program because that wouldn't affect anything at all. Let me know if I need to anyway.
> 1 votes

# Answer
# JavaScript (ES6) 228

```
s=>s.replace(/-?(\d+)|./g,(t,n)=>i?++i:C[k]&&(u='?-+# odc'.indexOf(t),n<101?C[k]=t:u>6?C[S='splice'](++k,0,'0'):u>5?C[S](k--,1):u>4?o+=C[k]+' ':u>2?+C[k]?0:i=-(u<4):u>1?k++:u>0?k--:~u?+C[k]||C[S](k--,1):i=1),i=o='',C=[k='0'])&&o

```

**Less golfed**

```
s=>(
  i=o='',
  C=[k='0'], // C: counters, k: current counter index
  s.replace(/-?(\d+)|./g,
    (t,n)=>( // tokenize, n is eventually the number, unsigned
      i?++i:C[k] && ( // i>0 or C[k] undefined -> error found
      u='?-+# odc'.indexOf(t),
      n<101?C[k]=t // n present and < 101
      :u>6?C.splice(++k,0,'0') //c add counter
      :u>5?C.splice(k--,1) // d remove counter
      :u>4?o+=C[k]+' ' // o output
      :u>3?0 // space == NO OP
      :u>2?+C[k]?0:i=-1 // set i to -1 to skip the next command
      :u>1?k++
      :u>0?k--
      :~u?+C[k]||C.splice(k--,1) // ? conditional remove counter
      :i=1) // invalid command error
    )
  ),
  o // return output
)

```
> 1 votes

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


title: Find our neighbors

text:
# Question
Title: Find our neighbors
You live in a rectangular neighborhood which is completely partitioned into N rectangular plots, i.e. there are no gaps or overlaps. Plots do not necessarily have the same width/height as other plots. All widths/heights are positive integers. Your goal is to output all shared edges between plots.

# Inputs

The input may come from any source desired (stdio, file, function parameters, etc.). The input is a list-like sequence of rectangles. Inputs for rectangles may be any form desired, for example `(min_x, max_x, min_y, max_y)`, `(min_x, min_y, width, height)`, `(min_x, min_y, max_x, max_y)`, etc.

The neighborhood is bounded by `min_x = 0` and `min_y = 0`. You may assume `max_x` and `max_y` of the neighborhood both fit in your language's native integer type.

You may flatten the input data into a 1D sequence if desired.

The id of a plot is a sequentially incremented integer based on the order of input, where the first plot may have any id desired.

# Outputs

The output may be to any desired target (stdio, file, return value, output parameter, etc.).

The output is a list of lists of neighbors for each plot. A neighbor is defined as the id of the neighboring plot and the min/max bounds of the shared corner/edge. Shared corners/edges with the corner/edge of the neighborhood are not considered a neighbor relation and should not be outputted.

When printing out make some distinction between each list, for example using a newline to separate the neighbors of plot `i` from the neighbors of plot `i+1`.

The order of the neighbors of plot `i` is not important.

# Example Test Cases

All listed test case inputs are of the format `min_x, max_x, min_y, max_y` and plot IDs start with 0. Outputs are formatted as `(id, min_x, max_x, min_y, max_y)`.

**Input:**

```
0, 1, 0, 1

```

**Output:**

```
no output, empty list, list containing a single empty list, or anything similar such as null

```

**Input:**

```
0, 1, 0, 1
0, 1, 1, 2

```

**Output:**

```
(1, 0, 1, 1, 1)
(0, 0, 1, 1, 1)

```

**Input:**

```
0, 2, 1, 2
0, 2, 0, 1

```

**Output:**

```
(1, 0, 2, 1, 1)
(0, 0, 2, 1, 1)

```

**Input:**

```
0, 1, 0, 1
0, 1, 1, 2
0, 1, 2, 3

```

**Output:**

Regions with no neighbor relationships may be omitted.

```
(1, 0, 1, 1, 1)
(0, 0, 1, 1, 1), (2, 0, 1, 2, 2)
(1, 0, 1, 2, 2)

```

It is also ok to output the id of the other region with some indication of "no shared boundary".

```
(1, 0, 1, 1, 1), (2)
(0, 0, 1, 1, 1), (2, 0, 1, 2, 2)
(1, 0, 1, 2, 2), (0, falsy)

```

**Input:**

```
0, 1, 0, 1
0, 1, 1, 2
1, 2, 0, 2

```

**Output:**

```
(1, 0, 1, 1, 1), (2, 1, 1, 0, 1)
(0, 0, 1, 1, 1), (2, 1, 1, 1, 2)
(0, 1, 1, 0, 1), (1, 1, 1, 1, 2)

```

One possible alternative output (switched order of neighbors for plot 0):

```
(2, 1, 1, 0, 1), (1, 0, 1, 1, 1)
(0, 0, 1, 1, 1), (2, 1, 1, 1, 2)
(0, 1, 1, 0, 1), (1, 1, 1, 1, 2)

```

**Input:**

You may have corner neighbors.

```
0, 1, 0, 1
0, 1, 1, 2
1, 2, 0, 1
1, 2, 1, 2

```

**Output:**

```
(1, 0, 1, 1, 1), (2, 1, 1, 0, 1), (3, 1, 1, 1, 1)
(0, 0, 1, 1, 1), (2, 1, 1, 1, 1), (3, 1, 1, 1, 2)
(0, 1, 1, 0, 1), (1, 1, 1, 1, 1), (3, 1, 2, 1, 1)
(0, 1, 1, 1, 1), (1, 1, 1, 1, 2), (2, 1, 2, 1, 1)

```

# Scoring

This is code golf; shortest code wins.

**edit clarification that corner neighbors should be outputted as well. Also clarified that if two regions don't share any corners/edges the relation may be completely omitted, or a relation with a falsy edge bounds may be outputted. Both have test cases added.**

# Answer
# Mathematica, 179 171 bytes

```
If[Depth@#2>2,Flatten/@(Thread@{##}/.Line->List)]&~MapThread~{Range@Length@#~Subsets~{2}-1,RegionIntersection/@Subsets[Line@{{##3},{#,#4},{#,#2},{#3,#2},{##3}}&@@@#,{2}]}&

```

---

**Test cases**

Inputs and outputs are list of elements in form `{x1, y1, x2, y2}`.

```
%[{{0, 0, 1, 1}, {0, 1, 1, 2}, {1, 0, 2, 2}}]
(*
   {{{0, 0, 1, 1, 1}, {1, 0, 1, 1, 1}},
    {{0, 1, 0, 1, 1}, {2, 1, 0, 1, 1}},
    {{1, 1, 1, 1, 2}, {2, 1, 1, 1, 2}}}
 *)

```
> 2 votes

# Answer
# Mathematica ~~123~~ 134 bytes

```
g@d_:=Subsets[MapIndexed[List,Apply[Rectangle,d,1]],{2}]/.{{a_,{i_Integer}},
{b_,{j_}}}:>{{i-1,r=RegionIntersection[a,b][[1]]},{j-1,r}}

```

---

I prefer this version, at 123 bytes, which returns graphics objects instead of mere coordinates. It also avoids redundancy, using by MartinBüttner's suggestion, by listing two rectangle numbers followed by a `Line[{{x1,y1},{x2,y2}}]` in the case of a shared edge, and `Point[{x,y}]` in the case of a shared corner.

```
f@d_:=Subsets[MapIndexed[List,Apply[Rectangle,d,1]],{2}]/.
{{a_,{i_Integer}},{b_,{j_}}}:>{{i,j}-1,r=RegionIntersection[a,b]}

```

---

```
f[{{{0, 0}, {1, 1}}}]

```

> {}

---

```
f[{{{0, 0}, {1, 1}}, {{0, 1}, {1, 2}}}]

```

> {{{0, 1}, Line\[{{0, 1}, {1, 1}}\]}}

---

```
f[{{{0, 1}, {1, 2}}, {{0, 0}, {2, 1}}}]

```

> {{{0, 1}, Line\[{{0, 1}, {1, 1}}\]}}

---

Shared edges, corners, areas, formatted to a grid for clarity.

```
f[{{{0, 0}, {1, 1}}, {{0, 1}, {1, 2}}, {{.5, .5}, {1.3, 1.5}}, {{1,
 0}, {2, 1}}, {{1, 1}, {2, 2}}}] // Grid

```
> 1 votes

# Answer
# Python, 189 characters

```
for p in i:
    for q in i:
        for t in 0,2:
            v,a,b=p[3-t],min(p[1+t],q[1+t]),max(p[t],q[t])
            w,z=[v,v],[b,a]
            if v==q[2-t]and a>b:
                for d in p,q:
                    print[i.index(d)]+(w+z,z+w)[t/2]

```

The input is given as a list like

```
i = [[0, 1, 0, 1], [0, 1, 1, 2], [1, 2, 0, 2]]

```
> 0 votes

# Answer
# JavaScript (ES6), 228

Input / output as an array of arrays. Format as in OP testcases:

* inputs min\_x, max\_x, min\_y, max\_y.
* outputs id (0 based), min\_x, max\_x, min\_y, max\_y.

```
l=>l.map(([x,r,y,s],i)=>l.map(([t,v,u,w],j)=>i-j&&(n=x-t&&x-v,m=r-t&&r-v,u>=s|w<=y||n&&m||q.push([j,z=m?x:r,z,y>u?y:u,s<w?s:w]),n=y-u&&y-w,m=s-u&&s-w,t>=r|v<=x||n&&m||q.push([j,x>t?x:t,r<v?r:v,z=m?y:s,z])),o.push(q=[])),o=[])&&o

```

This can probably be shortened merging the horizontal and vertical check

**TEST**

```
f=l=>
  l.map(([x,r,y,s],i)=>
    l.map(([t,v,u,w],j)=>
      i-j&&(
        n=x-t&&x-v,m=r-t&&r-v,u>=s|w<=y||n&&m||q.push([j,z=m?x:r,z,y>u?y:u,s<w?s:w]), // vertical
        n=y-u&&y-w,m=s-u&&s-w,t>=r|v<=x||n&&m||q.push([j,x>t?x:t,r<v?r:v,z=m?y:s,z])  // horizontal
      )
    ,o.push(q=[]))
  ,o=[])&&o

ArToStr=(a,s)=>a.map?(s?'[':'[\n ')+a.map(x=>ArToStr(x,1)).join(s?',':',\n ')+(s?']':'\n]\n'):a

console.log=x=>O.textContent+=x+'\n';

console.log(ArToStr(f([[0,1,0,1]])))
console.log(ArToStr(f([[0,1,0,1],[0,1,1,2]])))
console.log(ArToStr(f([[0, 2, 1, 2],[0, 2, 0, 1]])))
console.log(ArToStr(f([[0, 1, 0, 1],[0, 1, 1, 2],[1, 2, 0, 2]])))
```

```
<pre id=O></pre>
```
> 0 votes

---
Tags: code-golf, geometry
---


title: List Prime Numbers

text:
# Question
Title: List Prime Numbers
# Introduction

Prime numbers are simple, right? Well, now you get your chance to find out!

# Challenge

You must write a program or function that takes an input `n` and outputs the first `n` prime numbers.

# Example Input and Output

Input: `10`
Output: `2,3,5,7,11,13,17,19,23,29`

# Rules

1. You must not include any of the following builtin functions:

* A list of prime numbers
    * Primality testing
    * Next prime
    * Prime factorization
    * List of divisors
2. Your output must be in a convenient, unambiguous list format.

This is , so the shortest answer in bytes wins.

# Answer
> 20 votes
# Jelly, ~~14~~ 11 bytes

```
‘²R©’!²%®Oḣ

```

Uses Wilson's theorem for the primality test. Try it online!

### How it works

```
‘²R©’!²%®Oḣ     Main link. Input: n

‘               Increment. Yields n + 1.
 ²              Square. Yields (n + 1)².
  R             Range. Yields [1, ..., (n + 1)²].
                This range will always contain max(n,2) or more prime numbers.
   ©            Store the range in the register.
    ’           Decrement. Yields [0, ..., (n + 1)² - 1].
     !          Factorial. Yields [0!, ..., ((n + 1)² - 1)!].
      ²         Square. Yields [0!², ..., ((n + 1)² - 1)!²].
       %®       Mod by the range in the register.
                This yields [0!² % 1, ..., ((n + 1)² - 1)!² % (n + 1)²].
                By Wilson's theorem this gives 1 for primes and 0 for non-primes.
         O      Find the indices of 1's. This yields all prime number in the range.
          ḣ     Keep the first n items.

```

# Answer
> 16 votes
# Java, ~~116~~ 113 bytes

Saved 3 bytes thanks to @CamilStaps in a regex reduction!

```
void x(int c){for(int i=2;c>0;i++)if(!new String(new char[i]).matches("(..+?)\\1+")){System.out.println(i);c--;}}
```

Uses regex to test primality, prints if it is, else, it continues. Call on an instance of your class as `.x(10)`.

Output for `x(10)`:

```
2
3
5
7
11
13
17
19
23
29
```

# Answer
> 7 votes
# C, 125 bytes

Most likely I'm not going to win against the Jelly solution haha. Anyway here's my solution in C. It's not commented and it's very compact to reduce the size of the program. 125 bytes.

```
c,h,i,j;g(n){for(j=2;j*j<=n;j++)if(n%j<1)return 1;return 0;}main(){scanf("%i",&h);for(i=2;c<h;i++)g(i)?:printf("%i ",i,c++);}

```

# Answer
> 6 votes
## Pyth, 12 bytes

```
.fq2/%LZSZ0Q

```

This uses trial division to check primality.

```
.f         Q   find first Q positive integers that satisfy lambda Z:
    /     0      the number of zeroes
     %LZ         in map modulo-Z-by
        SZ       over inclusive range 1 to Z
  q2             equals 2

```

Try it here.

# Answer
> 5 votes
# MATL, 16 bytes

```
2iq:"t`Qtt:\~z2>

```

This uses current release (10.1.0) of the language/compiler.

**Try it online!**

### Explanation

This uses two nested loops. The outer one produces each prime, and the inner one increases 1 by 1 from latest found prime until the next prime is found.

To test for primality a modulo operation is used: x is prime if computing `mod(x,k)` for `k=1,2,...,x` produces no more than *two* zeros; that is, if only *two* numbers of the set `1,2,...,x` divide `x`.

```
2        % push 2 (first prime) to the stack
i        % input number, "n"
q:       % generate vector [1,2,...,n-1]
"        % "for" loop. This runs n-1 times, to find the n-1 primes after 2
  t      % duplicate top of the stack, which contains the latest found prime, "p"
  `      % "do...while" loop. This searches for the next prime
    Q    % increament top of stack by 1. This is the current candidate for next prime, "x"
    t    % duplicate top of the stack (x)
    t:   % produce vector [1,2,...,x]
    \    % compute mod(x,k) for k=1,2,...,x
    ~2>  % if that gives more than two zeros: x is not prime: we need another iteration
         % implicitly end "do...while" loop
         % implicitly end "for" loop
         % implicitly display stack contents

```

# Answer
> 5 votes
## Dyalog APL, 18 bytes

```
{⍵↑(⊢~∘.×⍨)1↓⍳2*⍵}

```

Generates a multiplication table from `2` to `2^n`. The prime numbers are those that don't occur, so we take the first `n` of those.

Try it here.

# Answer
> 4 votes
## Haskell, 46 bytes

```
(`take`[x|x<-[2..],mod(product[1..x-1]^2)x>0])

```

Using @Mauris'/@xnor's prime checker.

# Answer
> 4 votes
# Perl 6,  ~~39~~  37 bytes

```
{(2..*).grep({![+] $_ X%%2..^$_})[^$_]} # 39 bytes
{(2..*).grep({none $_ X%%2..^$_})[^$_]} # 39 bytes
{(2..*).grep({all $_ X%2..^$_})[^$_]}   # 37 bytes

```

Usage:

```
say {(2..*).grep({all $_ X%2..^$_})[^$_]}( 10 );
# (2 3 5 7 11 13 17 19 23 29)

```

# Answer
> 3 votes
# AppleScript (through osascript), ~~201~~ 158 bytes

If you're wondering how I saved that many bytes: I changed it from AppleScript to osascript (AppleScript from the command line) and used the main method equivalent (`on run x`) to grab arguments at *way* less bytes.

It's back. The most annoyingly verbose yet awesome language that I've used...

AppleScript.

```
on run x
set b to 1
repeat while x>0
set b to b+1
set c to 1
repeat while c<b
set c to c+1
if b mod c=0 then exit
end
if b=c
log c
set x to x-1
end
end
end
```

# Answer
> 3 votes
## Chapel, 108 bytes

This is the simple trial division method. I tried Wilson's theorem but came up with something slightly longer.

```
var n=0;read(n);var f=0;var q=0;while(f<n){q+=1;for i in 2..q{if(i==q){writeln(q);f+=1;}if(q%i==0){break;}}}

```

Chapel is a language designed to run on Cray supercomputers, but I installed it on my laptop. I literally downloaded the language and learned how to write the above program in a total of 2 hours.

The language has some interesting features, there is a pretty through X in Y minutes page about it. I'm sure there's some list-based features I haven't seen yet which could cut down on my byte count.

As a bonus stat, this compiles into a 519858-byte executable (based on `wc -c`).

# Answer
> 3 votes
## Python 2, 60 bytes

```
n=input()
k=P=1
while n:
 if P%k:print k
 n-=P%k;P*=k*k;k+=1

```

Same method as here, Wilson's Theorem, computing the factorial-squared iteratively.

54 bytes as a function:

```
f=lambda n,k=1,P=1:n*[0]and P%k*[k]+f(n-P%k,k+1,P*k*k)

```

# Answer
> 3 votes
## C#, 207 bytes

```
using s=System.Console;using System.Linq;class P{static void Main(){int n=int.Parse(s.ReadLine());s.Write(string.Join(",",Enumerable.Range(2,n*n).Where(x=>!Enumerable.Range(2,x-2).Any(y=>x%y<1)).Take(n)));}}

```

# Answer
> 2 votes
## Retina, 43 bytes

Byte count assumes ISO 8859-1 encoding.

```
+m`^((::+)\2+|:?)1
$1:1
)`(:+)1
$1¶$1:
:+$

```

The trailing linefeed is significant. Input and output in unary (input using `1` and output using `:` but any other two printable ASCII characters would work for the same byte count).

Try it online!

# Answer
> 2 votes
# Pyth - 13 bytes

Wilson's Theorem

```
j.f!%h.!tZZQ2

```

Test Suite.

# Answer
> 2 votes
# Python, 72 bytes

To avoid while statements, it simply computes all the prime numbers up to `3**n` and then it returns only the fist `n`. It works, but it is extremely slow for `n >= 7` because of the `3**n`.

```
lambda n:filter(lambda x:all(x%d for d in range(2,x)),range(2,3**n))[:n]

```

# Answer
> 2 votes
# Befunge 93, 60 bytes

```
&00p1v<_@#`0p00:-1g00.:<
210pv>1+:
`g01<_v#  %p01+1:g01::_^#

```

I didn't feel motivated enough to install Befunge 98 to try and use its features to golf this more, but this works quite well in Befunge 93. Try it here. Interestingly, this method also leaves all non-prime numbers on the stack. It works by the method of trial division.

# Answer
> 1 votes
# 05AB1E, 17 bytes

Uses the same algorithm as Bob's answer. Note that also for this, input greater than 7 will take a while to compute. If you aren't really patient, you can also change the `3` into a `2` in the code.

Code:

```
3WmGN<!nN%iN}})Z£

```

Explanation:

```
3Wm                # 3 ^ input
   G         }     # For N in range(1, 3 ^ input)
    N<!n           # Compute (N - 1)!²
        N%         # mod N
          i }      # If 1
           N       # Place N onto the stack
              )Z£  # Keep the first Z (auto-assigned to input) elements

```

Uses CP-1252 encoding

# Answer
> 1 votes
# Pyth, 14 bytes

```
.f!}0m%Zdr2ZQ2

```

Explanation

```
               - Autoassign Q = eval(input())
.f          Q2 - First Q where ... returns True, starting from 2
         r2Z   - range(2, Z)
     m%Zd      - [Z%d for d in ^]
  !}0          - 0 not in ^

```

Try it here.

# Answer
> 1 votes
## AutoIt, 155 bytes

RegEx to the rescue.

```
Func _($n,$i=0,$0=2)
Do
$1=''
For $2=1 To $0
$1&='1'
Next
$0+=1
ContinueLoop StringRegExp($1,'^(1?|(11+?)\2+)$')
$i+=1
MsgBox(0,0,$0-1)
Until $i=$n
EndFunc

```

# Answer
> 1 votes
## C#, 316 315 bytes

```
using System;class P{static void Main(string[]a){int x=int.Parse(Console.ReadLine()),i=0;List<int>b=G(~(2<<30));for(;i<x;i++)Console.WriteLine(b[i]);}static List<int> G(int n){var p=new List<int>();for(var i=2;i<n;i++){var o=0<1;foreach(var k in p){if(k*k>i)break;if(i%k==0){o=1<0;break;}}if(o)p.Add(i);}return p;}}

```

'Cleaner' & ungolfed version that shows what's happening.

```
    static void Main(string[]a)
    {
        int x=int.Parse(Console.ReadLine()), i=0;
        List<int> b=G(~(2 << 30));
        for(;i<x;i++)Console.WriteLine(b[i]);
    }
    static List<int> G(int n)
    {
        var p = new List<int>();
        for(var i=2;i<n;i++)
        {
            var o = 0<1;
            foreach (var k in p)
            {
                if (k * k > i)
                    break;
                if (i%k==0)
                {
                    o = 1<0;
                    break;
                }
            }
            if (o)
                p.Add(i);
        }
        return p;
    }

```

Takes the input from STDIN and prints N primes, each to a new line.

Couple tricks used here are ~(2 \<\< 30), shortened way of saying 2147483647. True and false words have been replaced with 0\<1 and 1\<0, they'll evaluate accordingly.

# Answer
> 1 votes
## Ceylon, 93 bytes

```
void p(Integer n)=>loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(n).each(print);

```

This is a function which takes an Integer `n` and prints the first `n` primes, each in one line.

Here formatted and with comments:

```
// Print the first n primes.
//
// Question:  https://codegolf.stackexchange.com/q/70001/2338
// My answer: https://codegolf.stackexchange.com/a/70021/2338

void p(Integer n) =>
        // the infinite sequence of integers, starting with 2.
        loop(2)(1.plus)
        // filter by primality (using trial division)
        .filter((c) => !  (2 : c-2).any((d) => c%d < 1) )
        // then take the first n elements
        .take(n)
        // print each element
        .each(print);

```

This uses the same basic prime check as my answer to the "Is this number prime" question (without the special-casing for 1, which is unnecessary here).

If a full program is needed, we need to incorporate some input, too. With a command line argument it becomes 138 bytes:

```
shared void run(){loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(parseInteger(process.arguments[0]else"")else 0).each(print);}

```

With reading a line from standard input we get 136 bytes:

```
shared void run(){loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(parseInteger(process.readLine()else"")else 0).each(print);}

```

# Answer
> 1 votes
# Brachylog, 63 bytes

```
:2{h0|[N:X],X+1=Y,('(X-1=:2reI,X%I=0),Xw,@Nw,N-1=:Y:1&;N:Y:1&)}

```

`'(X-1=:2reI,X%I=0)` is the part that checks that a number is prime. the rest is basically setting up a recursive predicate that stops after `n` primes founds (the `h0` part).

# Answer
> 1 votes
# Ruby, ~~75~~ 55 bytes

```
->n{a=[]
t=2
(a<<t if(2...t).all?{|i|t%i!=0}
t+=1)while !a[n-1]
a}

```

Works by trial division

# Answer
> 1 votes
# Japt, 23 bytes

```
U+1 ²o f_o2 eY{Z%Y}} ¯U

```

Test it online!

# Answer
> 1 votes
# Javascript ES6, ~~82~~ 67 Bytes

```
n=>{for(p=[],i=2;n;i++)!p.some(c=>!(i%c))&&p.push(i)&&n--;return p}

```

Ungolfed version :

```
n=>{
    for(p=[],i=2;n;i++)                   //Loop until n prime found
        !p.filter(c=>(i/c|0)==i/c).length //Test if i is not divisible by previous primes
        &&
        p.push(i)                         // If prime add to the list
        &&
        n--;                              // If a prime found, one less to find.
    return p;                             // Return list of primes
}

```

Changed the function to detect prime number thanks to @neil output.

# Answer
> 1 votes
# Perl 5 - 75

This is actually adapted and golfed from an old perlmonks post.

```
sub p{for(@n=(2..2**20);@p<@_[0]&&push@p,shift@n;){@n=grep{$_%$p[-1]}@n}@p}

```

The output is an array containing the prime numbers, so usage can be:

```
print join(',',p(100));

```

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


title: HelloWorld error

text:
# Question
Title: HelloWorld error
# Introduction

Everyone's first program outputs `Hello World!`. This program should be very simple, that's all you have to do.

# Challenge

Output the string `Hello World!` to the `STDERR`.

# Rules

1. If your language doesn't support `STDERR` or `STDERR` doesn't exist for it, you can output it to it's corresponding error system.
2. You can't output anything else to `STDERR` except for `Hello World!`.
3. You can't output anything to `STDOUT` or take any input from `STDIN`
4. You can't read any content from files.

This is , so the shortest answer in bytes wins.

# Answer
# Japt, 17 bytes

Currently winning! Let's hope Jelly doesn't pop in with an 11-byte answer...

```
Ox`È*w'HÁM W?ld!'

```

The `?` should be the literal byte 8E. Test it online!

(STDERR is found below the "Upload a file" line in red text.)

### How it works

```
  `È*w'HÁM W?ld!'  // Decompress this string. Returns "throw'Hello World!'"
Ox                 // Evaluate as JavaScript code. Throws the error.
                   // Implicit: Error is caught by interpreter and sent to STDERR.

```

Alternate version:

```
$throw$`HÁM W?ld!

```
> 6 votes

# Answer
## zsh, ~~21~~ ~~20~~ 19 bytes

```
<<<Hello\ World!>&2

```

This is a zsh-specific feature; won't work in bash.

Thanks to @FlagAsSpam and @Dennis for a byte each!
> 8 votes

# Answer
# JavaScript, 30 bytes

```
console.error("Hello, World!")

```

An alternative JavaScript answer, using `console.error`.
> 5 votes

# Answer
# Java 8, ~~75~~ 37 bytes

Thanks to @GamrCorps for slicing the code size almost exactly in half and showing me how to use lambda!

```
()->System.err.print("Hello World!");
```

Using interface because it makes the main declaration shorter. c:
> 4 votes

# Answer
# JavaScript, 19 bytes

```
throw"Hello World!"

```

Yes. It's that simple. Try it in the browser console on any page.
> 4 votes

# Answer
## C, 35 bytes

```
main(){write(2,"Hello World!",12);}

```

`write` writes to a file descriptor. STDERR is file descriptor 2, and 12 is the length of the string `"Hello World!"`.
> 4 votes

# Answer
## AutoIt, 33 bytes

```
ConsoleWriteError("Hello World!")

```
> 3 votes

# Answer
# Bash, ~~24~~ ~~21~~ 20 bytes

Saved 3 bytes thanks to @Neil, then another from @Dennis!

```
echo Hello World!>&2
```

\>&2 pushes the output to STDERR.
> 3 votes

# Answer
# Python 2, 36 bytes

```
import os
os.write(2,'Hello World!')

```

Despite being based on a Unix syscall, this works as well on Windows.
> 3 votes

# Answer
# Matlab, 21 bytes

```
error('Hello World!')

```
> 3 votes

# Answer
# R, 23 bytes

```
message("Hello World!")

```

The `message` function writes to STDERR.
> 3 votes

# Answer
## Ruby, 18 bytes

```
warn"Hello World!"

```

This only works if warnings are on (which is the default).
> 3 votes

# Answer
# C++, 53 bytes

```
#include<iostream>
main(){std::cerr<<"Hello World!";}

```

You can try it online if you feel so inclined.
> 3 votes

# Answer
## Rust, ~~73~~ 72 bytes

```
use std::io::Write;fn main(){std::io::stderr().write(b"Hello, World!");}

```

Rust is as long as ever...

Thanks to @ICanHazHats for saving a byte!
> 3 votes

# Answer
# Julia, 28 bytes

```
print(STDERR,"Hello World!")

```

Does what it looks like it does. `STDERR` is a built-in constant that refers to the standard error stream and `print` takes an optional argument specifying the stream.

Note that using `error()` prints out a bunch of extra garbage.
> 2 votes

# Answer
# AppleScript, 19 bytes

```
error"Hello World!"
```

...pretty self-explanatory.
> 2 votes

# Answer
# PHP, 36 bytes

I don't know much PHP, but here goes...

```
<?php fwrite(STDERR,"Hello World!");

```

Tested on ideone.com.
> 2 votes

# Answer
## Chapel, 29 bytes

```
stderr.write("Hello World!");

```

This language is probably overkill.
> 2 votes

# Answer
# Python 3, 33 bytes

```
open(2,'w').write('Hello World!')

```
> 2 votes

# Answer
# C#, 95 bytes

```
using System;class M{public static void Main(string[]a){Console.Error.Write("Hello World!");}}

```

I'm trying to learn this langauge but god, it's verbose.

Ungolfed:

```
using System;

class MainClass {
    public static void Main (string[] args) {
        Console.Error.Write ("Hello World!");
    }
}

```
> 2 votes

# Answer
# Pike, 35 bytes

```
int main(){werror("Hello World!");}

```

Looks like C, isn't C. Is interpreted.

---

We can make this compile as ANSI C like this:

```
#include <stdio.h>
# ifndef __PIKE__
#   define werror(x) fputs(x, stderr)
# endif

int main() {
  werror("Hello World!");
}

```
> 1 votes

# Answer
# Pascal (FP/GP), 51 bytes

```
program h;begin writeln(StdErr,'Hello World!');end.

```
> 1 votes

# Answer
## Perl, ~~25~~ 24 bytes

```
say stderr"Hello World!"

```

Requires version 5.10 or later.

Thanks to @FlagAsSpam for a byte!
> 1 votes

# Answer
# Forth, 65 bytes

Shorter than factor!

```
outfile-id stderr to outfile-id ." Hello World!" cr to outfile-id

```
> 1 votes

# Answer
# Moonscript, 40 bytes

```
io.stderr.write io.stderr,"Hello World!"

```

CoffeeScript for Lua... because Lua is ugly as hell!
> 1 votes

# Answer
# Lua5.2, 41 bytes

```
io.stderr.write(io.stderr,"Hello World!")

```

Cheeky golfed version of the transpilation of my Moonscript answer.
> 1 votes

# Answer
# Go, ~~39~~ ~~38~~ ~~37~~ ~~70~~ 69 bytes

```
package m;import."os";func main(){Stderr.WriteString("Hello World!")}

```
> 0 votes

# Answer
# Mathematica, 35 bytes

```
"stderr"~WriteString~"Hello World!"

```

Quite simple.
> 0 votes

# Answer
# Microsoft Windows Batch (also works in Wine), 22 bytes

```
echo Hello World! 1>&2

```
> 0 votes

# Answer
# Perl 6, ~~19~~ 21 bytes

```
note("Hello World!");

```
> 0 votes

# Answer
# Factor, 67 bytes

"Let's use a modernisation of Forth", I said. "It will be fun!" I said.

Yea, the whitespace is needed.

```
error-stream get [ "Hello World!" print flush ] with-output-stream*

```
> 0 votes

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


title: Calculate Doppelkopf Score

text:
# Question
Title: Calculate Doppelkopf Score
# Introduction

Doppelkopf is a traditional German card game for 4 players. The deck consists of 48 cards (9, 10, Jack, Queen, King, Ace of each suit while every card is in the game twice), so each player gets 12 at the start of a round.

There are always 2 teams which are determined by the distribution of the Queens of Clubs. The 2 players who are holding the Queens form a team and play against the other 2 players. The team with the Queens of Clubs are called the "Re"-team, the one without is the "Contra"-team.
At the start of the round noone knows who is on which team. The team distribution will be revealed in the progress of the round, which adds a lot of strategy to the game.

The game consists of 12 tricks. The players who wins a trick gets all the 4 cards in it. Every card has a certain value (King counts 4, Ace counts 11 for example), all cards together sum up to 240 points which is the highest possible result.

At the end of a round the points are counted and the team with the highest amount of points wins the round. Then then next round starts...

# The Challenge

Every round has a certain score which is determined by the amount of points the winning team got and potential announcements. You will have to write a program that takes the point distribution and potential announcements (see explanation below) as input and outputs the score of the round and the winner.

# The score calculation

As mentioned there is a Re- and a Contra-team. Also there is a maximum of 240 points possible in one round. The Re-team has to get 121 points to win, while the Contra-team only needs 120. There is also the possibility to announce "Re" or "Contra" at the start of the round if you think that you will win the game. By doing this you are raising the score.

Here are the scoring rules:

* +1 for winning the game
* +1 if the losing team has **less** than 90 points ("Keine 90")
* +1 if the losing team has **less** than 60 points ("Keine 60")
* +1 if the losing team has **less** than 30 points ("Keine 30")
* +1 if the losing team has 0 points ("Schwarz")
* +2 for an announcement of Contra
* +2 for an announcement of Re
* +1 if the Contra team won ("Gegen die Alten")

**Note:** Re/Contra-Announcements always apply, regardless of the winner. See examples in the testcases below.

# Input and Output

The input to the program will be the score of the Re-team and potential announcements of Re or Contra. Since there are always 240 points in the game you can easly calculate the score of the Contra-team.

The input will be a single string which has the score of the Re-team first, followed by the potential announcements, while "R" is for Re and "C" is for Contra. If both got announced, Re will always come first.

Output will be the score of the game followed by the winning team ("C" for Contra, "R" for Re)

# Rules

* Your submission can be a full program or a function. If you choose the latter include an example on how to invoke it.
* Input can be provided by function- or command line arguments or user input.
* Output can be provided as return value or printed to the screen.
* Standard loopholes apply.
* Lowest Byte-Count wins!

# Testcases

```
Input -> Output (Explanation)

145R  -> 3R  (Re won, +1 for winning, +2 for Re-Announcement)
120   -> 2C  (Contra won, +1 for winning, +1 for winning as Contra)
80C   -> 5C  (Contra won, +1 for winning, +1 for no 90, +1 for winning as Contra, +2 for Contra-Announcement)
240R  -> 7R  (Re won, +1 for winning, +1 for no 90, +1 for no 60, +1 for no 30, +1 for no points for the losing team, +2 for Re-announcedment)
90    -> 2C  (Contra won, +1 for winning, +1 for winning as Contra)
110RC -> 6C  (Contra won, +1 for winning, +1 for winning as Contra, +2 for Re-Announcement, +2 for Contra-Announcement)
110R  -> 4C  (Contra won, +1 for winning, +1 for winnins as Contra, +2 for Re-Announcement)
184C  -> 5R  (Re won, +1 for winning, +1 for no 90, +1 for no 60, +2 for Contra-Announcement)

```

*Short note: I left out some rules (like solos and bonus points) on purpose to keep the challenge simple. So if you are already familiar with the game, don't be confused :)*

Happy Coding!

# Answer
> 4 votes
## CJam, ~~47~~ 46 bytes

```
L~]_,2*\0=:S121<:AS240S-e<_g3@30/-Te>--+A"RC"=

```

Run all test cases.

Hmm, conceptually this challenge is really simple, but it's surprisingly tricky to golf.

# Answer
> 4 votes
## Labyrinth, ~~136~~ ~~103~~ ~~94~~ ~~92~~ ~~87~~ ~~84~~ ~~76~~ ~~74~~ ~~69~~ 61 bytes

```
 (}?
;)
,)
`
2
0:
 {
_-+}}82"
}"     {{"(#0/#--!.@
 -=-)}67 )

```

Try it online!

Ahh, it's been way too long since I used Labyrinth. It's always quite a joy to golf it. :)

### Explanation

*This is a bit outdated now. The overall structure of the program is still the same, but a few details have changed. I'll update this later. This is the previous solution, for reference:*

```
 (}?
;)
,)
`
2
0 }82{_240{- ("
{ ;        #;`"~#0/#--!.@
:}-"-))}67{{
  ;#

```

Let's break down the score a bit:

* If we count the characters after the number in the input, let's call it `M`, then there will be `2M+1` points in the final score, for winning, Re, and Contra.
* If the score is 120 or less, Contra wins and the score is incremented by `1`.
* Looking at the losing score, we can (integer) divide it by 30 to determine the additional points. That has three problems though: 1. the value increases in the wrong direction, so we need to subtract it from the score (and add 3 to it to correct for that). 2. This gives an additional point for a result of exactly 120, which we need get rid of. 3. It doesn't handle a result of 0 (for the losing side) yet, but we can include it by turning 0 into -1 (since Labyrinth's integer division rounds towards `-∞`).

That's pretty much how the code works. Sp3000 posted a good primer for Labyrinth today, so I decided to steal it. :)

* Labyrinth is stack-based and two-dimensional, with execution starting at the first recognised character. There are two stacks, a main stack and an auxiliary stack, but most operators only work on the main stack. Both stacks are bottomless, filled with zeroes.
* At every branch of the labyrinth, the top of the stack is checked to determine where to go next. Negative is turn left, zero is straight ahead and positive is turn right.
* Digits don't push themselves (as they do in Befunge, \>\<\> or Prelude) - instead they "append themselves" to the top of stack, by multiplying the top by 10 and adding themselves.

So execution starts on the `(` in the first row, with the instruction pointer (IP) going right. `(` just turns the top of the main stack into `-1` and `}` shifts it off to the auxiliary stack, where we can forget about it. The program really starts with the `?` which reads the integer from STDIN. The IP then hits a dead end and turns around.

`}` shifts the input to the auxiliary stack and `(` decrements another zero to `-1`. This will be the final score. We now enter a very tight clockwise loop:

```
;)
,)

```

The `))` increments the score by two (so the first time we go through the loop, the score becomes `1`, the score for winning). Then `,` reads a character. As long as that's not EOF, the loop continues. `;` discards the character, because we don't care if it was `R` or `C` and `))` adds two to the score again. This will repeat 0, 1 or 2 times depending on the input.

We leave the loop, when we've hit EOF, the top of the stack will be `-1`. We then run this linear part:

```
`20{:}-

```

The ``` is unary negation, so we get `1`, then `20` turns it into a `120`. `{:}` gets a copy of the input integer from the auxiliary stack and `-` computes the difference with `120`. We can use the sign of this result to determine who won.

1. If the result is negative, Re won and we take the northern path, executing:

```
;}82{_240{-#;

```

`;` discards this result, `}` shifts the score away, `82` puts itself (character code of `R`) at the bottom of the main stack, `{` gets the score back on top, `_240{-` subtracts the integer input from 240 so we can work with Contra's (the losing side's) points.

The `#;` is just to ensure that we have a non-zero value on the stack so we can join up both paths reliably.
2. If the result is positive, Contra won and we take the southern path, executing:

```
;#"-))}67{{#;

```

The `#` pushes the stack depth which is `1`. This gets subtracted from the score before we add `2` with `))`. `67` puts itself (character code of `C`) at the bottom of the main stack. `{{` gets the other values back.
3. If the result is zero, Contra still won. However, that's the 120/120 case for which we need add an extra point to the final score (see above). That's why this path doesn't push a 1 with `#`, but instead just leaves the zero such that the `-` simply removes that zero from the stack.

The stacks are now joined back together and we've accounted for everything except the part where we divide by 30. But first, we need to turn a zero-score into -1. That's what this little detour does:

```
("
`"~

```

The ``` doesn't affect a zero, `"` is a no-op and `~` is bitwise negation. The bitwise NOT of `0` is `-1` as required. If the score was positive instead, then ``` makes it negative, `(` decrements it by `1` and `~` undoes both of those operations in one go.

```
#0/#--!.@

```

The stack depth is now 3 (the winning side's character, the total score so far, and the losing side's points), so `#` pushes `3`. `0` turns it into a `30`, `/` does the division. `#` pushes another `3` which is subtracted and that result is in turn subtracted from the final score. `!` prints it as an integer, `.` prints the winning side as a character and `@` terminates the program.

# Answer
> 3 votes
# JavaScript (ES6), 106

Around 100 bytes with a non golfing language.

```
x=>([,r,t]=x.match`(\\d+)(.*)`,t=1+t.length*2,w=r>120?(r=240-r,'R'):(++t,'C'),t+!r+(r<30)+(r<60)+(r<90)+w)

```

**Test**

```
f=x=>(
  [,r,t]=x.match`(\\d+)(.*)`,
  t=1+t.length*2,
  w=r>120?(r=240-r,'R'):(++t,'C'),
  t+!r+(r<30)+(r<60)+(r<90)+w
)

console.log=x=>O.textContent+=x+'\n'

test=[
['145R', '3R'], //(Re won, +1 for winning, +2 for Re-Announcement)
['120',  '2C'], //(Contra won, +1 for winning, +1 for winning as Contra)
['80C',  '5C'], //(Contra won, +1 for winning, +1 for no 90, +1 for winning as Contra, +2 for Contra-Announcement)
['240R', '7R'], //(Re won, +1 for winning, +1 for no 90, +1 for no 60, +1 for no 30, +1 for no points for the losing team, +2 for Re-announcedment)
['90',   '2C'], //(Contra won, +1 for winning, +1 for winning as Contra)
['110RC','6C'], //(Contra won, +1 for winning, +1 for winning as Contra, +2 for Re-Announcement, +2 for Contra-Announcement)
['110R', '4C'], //(Contra won, +1 for winning, +1 for winnins as Contra, +2 for Re-Announcement)
['184C', '5R'], //(Re won, +1 for winning, +1 for no 90, +1 for no 60, +2 for Contra-Announcement)
]

test.forEach(t=>{
  var i=t[0],k=t[1],r=f(i)
console.log((k==r?'OK ':'KO ')+i+' -> '+r+(k!=r?' (expected: '+k+')':''))
})
```

```

```

# Answer
> 2 votes
## ES6, 92 bytes

```
s=>(p=s.match(/\d+|./g),n=+p[0],r=n>120,p.length*2-r+!(n%120)+3-((r?240-n:n)/30|0)+"CR"[+r])

```

`p.length*2` overestimates the score by 1 if Re wins so I have to subtract `r` again. `!(n%120)+3-((r?240-n:n)/30|0)` is what I came up with to encapsulate the rules for scoring "Keine"; I so wish the boundaries had been 31, 61 and 91 as that would have made the formula `4-((r?269-n:29+n)/30|0)`.

---
Tags: code-golf, card-games
---


title: How many votes does a state get?

text:
# Question
Title: How many votes does a state get?
Given a list of the populations of each state, output, from greatest to least, the number of votes that state gets in the electoral college.

**Input:** The first number represents the total number of votes to distribute; it is followed by a list of and populations. In this example, abbreviations for states are used, but any name containing uppercase and lowercase letters could be used. You can take this in any format you like, as long as the only information contained is the state's abbreviation and its population.

Input may be taken as arguments to a function, or any way you want.

Example (possible) input: `538 [[CA 38000000], [NH 1300000] etc.]`

**Output:** Output, in some format, the number of votes each state gets. Order the states from greatest to least. If two states have the same number of votes, order by whichever name would come first in a dictionary (which comes first alphabetically).

Before finding the number of votes, first check if there is a state named DC in the list of inputs, and if there is, give the state 3 votes, regardless of its population. Then, remove it from the list and assign the rest of the votes as though DC didn't exist.

The number of votes in the electoral college is defined to be the sum of the number of senators and representatives. Every state gets two senators, so subtract twice the number of states from the total (538, in the example input) to get the number of representatives. Assign every state one representative to start. Then, perform the following process:

1. Assign each state a number, `A`, defined to be `P/sqrt(2)` where `P` is the population.
2. Sort the states according to their values of `A`.
3. Assign the first state (the one with the largest `A`) one more representative.
4. Reassign values of `A`, as `A = P/(sqrt(n)*sqrt(n + 1))`, where `n` is the current number of representatives assigned to the state.
5. Go back to step 2. Repeat until all representatives have run out.

Example (possible) output: `{CA: 518, NH: 20}`. The output doesn't have to be in this format, but must contain the same information.

Note that if it is not possible to assign votes legally because there are less than `3*(# of states)` votes, print whatever you want. You can crash, throw an error, etc.

**Test cases:**

```
538 [['CA' 38000000], ['NH' 1300000]] --> CA: 518, NH: 20
538 [['NH' 1300000], ['CA' 38000000]] --> CA: 518, NH: 20 (must be in order from greatest to least!)
538 [['DC' 1000000], ['RH' 1]] --> RH: 535, DC: 3
100 [['A', 12], ['B', 8], ['C', 3]] --> A: 51, B: 35, C: 14
100 [['A', 12], ['B', 8], ['C', 3], ['D', 0]]: --> [49, 34, 14, 3] (yes, even states with no population get votes)
2 [['A', 1]] --> aasdfksjd;gjhkasldfj2fkdhgas (possible output)
12 [['A', 1], ['B', 2], ['C', 3], ['D', 4]] --> A: 3, B: 3, C: 3, D: 3
42 [['K', 123], ['L', 456], ['M', 789]] --> M: 23, L: 14, K: 5
420 [['K', 123], ['L', 456], ['M', 789]] --> M: 241, L: 140, K: 39
135 [['C', 236841], ['D', 55540], ['G', 70835], ['K', 68705], ['M', 278514], ['Ms', 475327], ['Nh', 141822], ['Nj', 179570], ['Ny', 331589], ['Nc', 353523], ['P', 432879], ['R', 68446], ['Sc', 206236], ['Ve', 85533], ['Vi', 630560]] --> Vi: 20, Ms: 16, P: 14, Nc: 12, Ny: 12, M: 10, C: 9, Sc: 8, Nj: 7, Nh: 6, Ve: 5, D: 4, G: 4, K: 4, R: 4

```

# Answer
# Clean, 263 244 222 bytes

```
v n s=sortBy(\(a,b)(c,d).b>d)([(t,3.0)\\t<-s|fst t=="DC"]++w(n-3*(length s))[(t,1.0)\\t<-s|fst t<>"DC"])
w 0s=w 0 s=[(p,r+2.0)\\(p,r)<-s]
w n s#s=sortBy(\a b.A a>A b)s
#(p,r)=hd s
=w(n-1)[(p,r+1.0):tl s]
A((_,p),r)=p/sqrt(r*r+r)

```

Call like

```
Start = v 538 [("DC", 1000000.0), ("RH", 1.0)]

```

Ungolfed version, full program (`census.icl`):

```
module census

import StdEnv

Start = votes 538 [("DC", 1000000.0), ("RH", 1.0)]

votes n states
# dc = filter (((==)"DC")o fst) states
= sortBy (\(a,b)(c,d).b>d) ([(t,3.0) \\ t <- dc] ++ votes` (n-3*length states) [(t,1.0)\\t<-removeMembers states dc])
where
    votes` 0 states = map (\(p,r).(p,r+2.0)) states
    votes` n states
    # states = sortBy (\a b.A a > A b) states
    # (p,r) = hd states
    = votes` (n-1) [(p,r+1.0):tl states]

    A ((_,p),r) = p / sqrt(r*r+r)

```
> 3 votes

# Answer
# JavaScript ES6, ~~249 bytes~~ 244 bytes

```
(r,s)=>{r-=s.length*3;s=s.map(t=>({s:t[0],p:t[1],a:t[1]/(q=Math.sqrt)(2),r:1}));while(r--)(t=>t.a=t.p/q(++t.r)/q(t.r+1))(s.filter(t=>t.s!='DC').sort((a,b)=>b.a-a.a)[0]);return''+s.sort((a,b)=>(r=b.r-a.r)?r:a.s>b.s?1:-1).map(t=>t.s+':'+(t.r+2))}

```

## Test cases

```
d = (r, s) => {
  r -= s.length * 3;
  s = s.map(t => ({
    s: t[0],
    p: t[1],
    a: t[1] / (q = Math.sqrt)(2),
    r: 1
  }));
  while (r--)(t => t.a = t.p / q(++t.r) / q(t.r + 1))(s.filter(t => t.s != 'DC').sort((a, b) => b.a - a.a)[0]);
  return '' + s.sort((a, b) => (r = b.r - a.r) ? r : a.s > b.s ? 1 : -1).map(t => t.s + ':' + (t.r + 2))
};

document.write(
  '<pre>' +
  d(135, [
    ['C', 236841],
    ['D', 55540],
    ['G', 70835],
    ['K', 68705],
    ['M', 278514],
    ['Ms', 475327],
    ['Nh', 141822],
    ['Nj', 179570],
    ['Ny', 331589],
    ['Nc', 353523],
    ['P', 432879],
    ['R', 68446],
    ['Sc', 206236],
    ['Ve', 85533],
    ['Vi', 630560]
  ]) +
  '</pre>'
);
```

Credit to @Neil for saving 5 bytes!
> 2 votes

# Answer
## Python 2, 219 bytes

```
v,s=input()
n={k:1 for k in s}
v-=3*len(s)
l=lambda x:-x[1]
if'DC'in s:del s['DC']
while v:A,_=sorted([(a,s[a]/(n[a]**2+n[a])**.5)for a in s],key=l)[0];n[A]+=1;v-=1
for a in n:n[a]+=2
print sorted(list(n.items()),key=l)

```

Takes input as

```
420,{'K':123,'L':456,'M':789}

```

Prints:

```
[('M', 241), ('L', 140), ('K', 39)]

```
> 1 votes

---
Tags: code-golf
---


title: Triangular Ulam spiral

text:
# Question
Title: Triangular Ulam spiral
We've had a couple of challenges about the Ulam spiral. But that's not enough.

In this challenge we will plot a triangular Ulam spiral (as opposed to the usual, square Ulam spiral). Here's a sketch of what the spiral looks like.

As we know, the Ulam spiral arranges all natural numbers in an outward spiral, and marks only those that are prime. So in the above sketch only the numbers that appear in black (the primes) would be shown.

## The challenge

Accept a number *N* as input and display the triangular Ulam spiral up to that number.

* Input can be stdin or function argument.
* The spiral should turn in the positive direction (that is, counter-clockwise), as in the above figure.
* Any of the 120-degree turns of the above figure would be valid, and the turn may be different for different inputs. But the lowest side of the implied triangles should be horizontal, as the only allowed turns are (multiples of) 120 degrees.
* The code should run theoretically (given enough time and memory) for any *N* up to what is allowed by any intermediate calculations you do with your default data type. `double` is enough; no need for large integer types.
* All built-in functions allowed.
* I won't accept my own answer (not that I think it would be the shortest anyway...).

## Output formats

Choose any of the following.

1. **Display a graph** with a marker (dot, circle, cross, whatever you prefer) at prime numbers, and nothing at non-prime numbers. Scale need not be the same for the two axes. That is, the implied triangles need not be equilateral. Axes, grid lines and axis labels are optional. Only the markers at the prime numbers are required.

An example output for *N* = 12 would be as follows (compare with the above sketch). The second plot is a more interesting example, corresponding to *N* = 10000.

2. Produce an **image file** with the above, in any well known image format (such as png, tiff, bmp).
3. Display the spiral as **ASCII art**, using a single character of your choice for primes and blank space for non-primes, with a blank space to separate number positions in the same row. Leading or trailing spaces or newlines are allowed. For example, the *N* = 12 case using `o` as character would be

```
             o
            · ·
           · o ·
            o · ·
           · o · o

```

where of course only the `o` mark at primes would actually be displayed. The `·` at non-primes is shown here for reference only.

# Winning criterion

~~The actual reward is seeing for yourself those amazing patterns~~ Code golf, shortest code wins.

# Answer
> 13 votes
## CJam, ~~49~~ 42 bytes

```
Lri{)mp0S?}%{1$,)/(a@Wf%z+\L*}h;eeSff*W%N*

```

Input as a single integer in STDIN. Output as an ASCII grid with `0` for primes. The rotation of the spiral is not consistent: the largest number of the spiral will always be on the bottom row.

Test it here.

### Explanation

The basic idea is to represent the triangle as a ragged 2D array while doing the computation. You get this array by reversing the lines and aligning all rows to the left:

```
   4
  5 3
 6 1 2
7 8 9 A

```

Would be represented as

```
[[7 8 9 A]
 [6 1 2]
 [5 3]
 [4]]

```

Since we've mirrored the line, we want to roll up the spiral in a *clockwise* manner. That's convenient, because all we need to do is rotate the triangle counter-clockwise and prepend the next sublist in order. We can rotate the ragged array by reversing all lines and transposing it:

```
                                                           [[B C D E F]
[[7 8 9 A]         [[A 9 8 7]           [[A 2 3 4]          [A 2 3 4]
 [6 1 2]   reverse  [2 1 6]   transpose  [9 1 5]   prepend  [9 1 5]
 [5 3]      ---->   [3 5]      ------>   [8 6]      ---->   [8 6]
 [4]]               [4]]                 [7]]               [7]]

```

So here is the code. One detail I'd like to draw attention to is the last bit that creates the triangular layout. I think that's rather nifty. :)

```
L     e# Push an empty array. This will become the spiral.
ri    e# Read input and convert to integer N.
{     e# Map this block over 0 to N-1...
  )   e#   Increment to get 1 to N.
  mp  e#   Test for primality.
  0S? e#   Select 0 or a space correspondingly.
}%
{     e# While the list we just created is not empty yet...
  1$  e#   Copy the spiral so far.
  ,)  e#   Get the number of lines and increment.
  /   e#   Split the list into chunks of that size.
  (a@ e#   Pull off the first chunk, wrap it in an array, pull up the spiral.
  Wf% e#   Reverse the lines of the spiral.
  z   e#   Transpose the spiral.
  +   e#   Prepend the new line.
  \L* e#   Swap with the remaining chunks and join them back together into a single list.
}h
;     e# Discard the empty list that's left on the stack.
ee    e# Enumerate the spiral. This turns each line into a pair of 0-based index
      e# and the line itself.
Sff*  e# Multiply each element of each pair with a space. For the enumeration index i,
      e# this produces a string of i spaces - the required indentation (keeping in
      e# mind that our spiral is still upside down). For the line itself, this
      e# riffles the cells with spaces, creating the required gaps between the cells.
      e# All of this works because we always end the spiral on the bottom edge.
      e# This ensures that the left edge is always complete, so we don't need
      e# different indentation such as in the N=12 example in the challenge.
W%    e# Reverse the lines to make the spiral point upwards.
N*    e# Join the lines with linefeeds.

```

# Answer
> 10 votes
# MATL, ~~48~~ 36 bytes

```
:1-H*X^.5+Y[2j3/*YP*ZeYsG:Zp)'.'2$XG

```

Uses current release (9.3.0).

**Try it online!** ~~No idea how the online compiler manages to translate graphic output to ASCII, but it does~~ This produces an approximate ASCII plot thanks to an Octave feature that is supported by the online compiler!

*Edit (April 4, 2016): the function `Y[` has been renamed to `k` since release 13.0.0. The link to the online compiler incorporates this change, so that the code can be tested.*

### Example

```
>> matl
 > :1-H*X^.5+Y[2j3/*YP*ZeYsG:Zp)'.'2$XG
 >
> 20000

```

produces the graphical output (MATLAB version shown):

### Explanation

The code uses complex numbers to trace the path followed by the spiral. As can be seen from the first figure in the challenge, each straight leg of the spiral is a segment with increasing length 1, 2, 3, 4 ... and cyclically increasing orientation 120 degrees, 240 degrees, 0 degress, 120 degress...

The code first generates the individual complex displacements from each integer number to the next. These complex displacements have magnitude 1 and angle `2*pi/3`, `4*pi/3` or `0` (in radians). Thus they can be easily generated as imaginary exponentials. For that, the integer sequence 0,1,2,2,3,3,3,4,4,4,4... is used first.

This integer sequence is almost like the "n appears n times" sequence (OEIS A002024), and can be obtained as `floor(sqrt(2*n)+.5)` where `n` is 0,1,2,3,... . Multiplying by `2j*pi/3`, where `j` is the imaginary unit, produces the desired complex displacements.

The displacements are accumulated to compute the positions corresponding to the integer numbers in the spiral. The first integer number in the spiral, which is `1`, is arbitrarily located at position `1` in the complex plane.

Finally, the positions corresponding to non-prime numbers are discarded, and the rest are plotted in the complex plane.

```
:1-H*X^.5+Y[     % floor(sqrt(2*n)+.5) for n from 0 to N-1, where N is implicit input
2j3/*YP*Ze       % exp(2j*pi/3* ... )
Ys               % cumulative sum. Produces complex positions
G:               % vector 1,2...,N, where N is previous input
Zp               % logical index to select only prime numbers
)                % use that index to keep only complex positions of primes
'.'2$XG          % plot using marker '.'

```

# Answer
> 8 votes
Drawing should be done with

# LaTeX / PGF, 527 ~~594~~ bytes

```
\documentclass{standalone}\usepackage{pgf}\let\z\let\z\e\advance\z\f\ifnum\z\h\the\z\a\newcount\a\i\a\j\a\l\a\x\a\y\a\p\a\q\a\n\i=1\l=1\p=-1\q=1\def\m#1{\e\i by1\e\j by1\e\x by\h\p\e\y by\h\q\pgfmathparse{isprime(\h\i)}\f\pgfmathresult=1\pgfpathcircle{\pgfpoint{\h\x cm}{\h\y cm}}3pt\fi\f\j=\l\e\l by1\j=0\f\p=1\p=-1\q=1\else\f\p=-1\p=0\q=-1\else\p=1\q=0\fi\fi\fi\f#1>0\e#1by-1\m#1\fi}\begin{document}\begin{pgfpicture}\pgftransformcm10{cos(60)}{sin(60)}\pgfpointorigin\n=4000\m\n\pgfusepath{fill}\end{pgfpicture}\end{document}

```

527 bytes is the full document as above, i.e. including preamble and parameter (here 4000, so ~523 without parameter). Produces a PDF file.

Basic idea: well, just draw. Uses a matrix transformation for a triangular grid. Only problem is that also the dots are affected (and stretched) out by the transformation. So I choose for ellipse markers :) what I mean by that is clear in the second image (n=250, 5pt).

Another caveat: can only handle up to a bit less than 5000 because of TeX's maximum stack size. The first image is for n=4000. Apparently it is possible to increase the stack size, I didn't try it.

Uses PGF's `isprime()`.

Ungolfed:

```
\documentclass[border=10cm]{standalone}

\usepackage{pgf}

\newcount\ulami
\newcount\ulamj
\newcount\ulamlen

\newcount\ulamx
\newcount\ulamy
\newcount\ulamdx
\newcount\ulamdy

\ulami=1 %
\ulamj=0 %
\ulamlen=1 %
\ulamdx=-1 %
\ulamdy=1 %
\ulamx=0 %
\ulamy=0 %

\def\ulamplot#1{%
  \advance\ulami by 1 %
  \advance\ulamj by 1 %

  \advance\ulamx by \the\ulamdx %
  \advance\ulamy by \the\ulamdy %

  \pgfpathmoveto{\pgfpoint{\the\ulamx cm}{\the\ulamy cm}}

  \pgfmathparse{isprime(\the\ulami)}
  \let\r=\pgfmathresult
  \ifnum\r=1
    \pgfpathcircle{\pgfpoint{\the\ulamx cm}{\the\ulamy cm}}{5pt}
  \fi

  \ifnum\ulamj=\the\ulamlen %
    \advance\ulamlen by 1 %
    \ulamj=0 %
    \ifnum\ulamdx=1 %
      \ulamdx=-1 %
      \ulamdy=1 %
    \else%
      \ifnum\ulamdx=-1 %
        \ulamdx=0 %
        \ulamdy=-1 %
      \else%
        \ulamdx=1 %
        \ulamdy=0 %
      \fi
    \fi
  \fi

  \ifnum#1>0 %
    \advance#1 by -1 %
    \ulamplot{#1}%
  \fi
}

\begin{document}

\begin{pgfpicture}
  \pgfmathsetmacro{\x}{cos(60)}
  \pgfmathsetmacro{\y}{sin(60)}
  \pgftransformcm{1}{0}{\x}{\y}{\pgfpointorigin}

  \pgfpathmoveto{\pgfpointorigin}
  \color{blue}
  \newcount\ulamn
  \ulamn=400
  \ulamplot{\ulamn}
  \pgfusepath{stroke,fill}
\end{pgfpicture}

\end{document}

```

# Answer
> 2 votes
# Mathematica, 94 bytes

```
ListPlot@Accumulate[Join@@Table[ReIm@Exp[2i Pi/3I],{i,2#^.5},{i}]][[Prime@Range@PrimePi@#-1]]&

```

**Result**

```
%[10000]

```

# Answer
> 2 votes
# Python, 263 bytes

Being new to Python, there is surely room for improvement :)

```
from matplotlib.pyplot import*
from math import*
def f(m):
 s=[];X=[];Y=[];i=x=y=0
 while len(s)<m:i+=1;s+=[i%3*pi*2/3]*i
 for i in range(m):
  x+=cos(s[i]);y+=sin(s[i]);j=i+2
  if all(map(lambda a:j%a>=1,range(2,int(j**.5+1)))):X+=[x];Y+=[y]
 scatter(X,Y);show()

```

Example:

```
f(100000)

```

# Answer
> 1 votes
# R, 137 bytes

Uses only built-in functions, even for prime numbers. Given its vectorized approach instead of iterative, it is fast, but cannot handle huge numbers.

Golfed:

```
g=function(m){M=1:m;s=rep(M,M)[M]%%3*pi*2/3;k=cumsum;j=sapply(seq(s)+1,function(n)n<4|all(n%%2:n^.5>=1));plot(k(cos(s))[j],k(sin(s))[j])}

```

Ungolfed:

```
g=function(m) {
  M = 1:m
  s = rep(M,M)[M] %% 3 * pi * 2/3
  k=cumsum
  j=sapply(seq(s)+1,function(n)n<4|all(n%%2:n^.5>=1)) # primes
  plot(k(cos(s))[j],k(sin(s))[j])    # cumulated coordinates
}

```

Example:

```
g(10000)

```

---
Tags: code-golf, ascii-art, graphical-output, primes, hexagonal-grid
---


# Question
Title: Strategies for representing a given large integer using arithmetic expression
I have a specific number in mind, but it's part of a challenge I'm doing, and I don't want people to do (all) the work for me.

Here is a number which has the same digits, but shuffled:

```
5713167915926167134578399473447223554460066674314639815391281352328315313091488448321843
8892917486601064146636679920143691047671721184150386045081532202458651561779976236919751
5521854951599379666116678853267398393892536121049731949764192014193648608210652358947001
6332620900065461061195026191178967128001712341637591690941978871368243245270800684616029
6679555942849366434586090627998161441134473428845367022486230724219981658438108844675033
4461550796750244527407413996606134735852639191026103378962082622204359677030054592798927
4145951979523473408718011778751084514127053772614511042703365596651912104541233491744530
87457854312602843967491787086250478422477028164189

```

The number has 666 digits (decimal). Because I'm using Python, integers (or technically longs) are automatically bignums.

I have 255 chars to use, and I need to describe the same number. The description is meant to be run through eval() to produce the original number.

What strategies should I be looking into?

# Answer
## Base Encoding

A standard technique for compressing numbers is to express them in a big base and encode the digits as characters. E.g. if you encode the number in base 256, it would have only 277 digits:

```
[12 24 156 48 101 149 235 32 96 92 20 203 202 164 144 71 193 127 112 77 141 79 210 183 98 155 16 151 65 198 26 236 83 221 220 129 169 254 43 124 245 25 176 182 167 124 95 191 77 25 233 139 190 7 135 2 149 90 163 163 106 193 220 253 109 129 57 219 91 157 218 18 223 11 171 113 209 173 207 123 110 220 79 139 176 143 171 7 30 35 231 151 172 83 120 114 119 47 217 227 50 105 236 91 161 226 112 16 170 57 162 147 36 89 26 9 122 164 15 15 243 108 30 14 233 139 103 137 82 169 2 57 54 71 154 136 23 203 137 10 219 153 24 168 42 218 165 125 185 183 241 91 193 85 195 71 186 18 98 34 196 78 6 193 252 8 177 94 5 24 137 183 127 129 9 77 149 73 148 193 62 220 146 33 130 21 209 153 229 105 100 188 87 235 203 104 207 161 20 17 102 150 252 120 242 222 233 248 114 217 142 31 196 42 161 173 0 244 9 213 178 152 122 170 136 230 135 132 245 69 9 196 231 147 8 175 48 98 101 23 162 144 190 200 62 226 61 27 200 15 232 12 105 187 184 4 121 252 171 240 230 94 161 151 131 209 205 130 193 9 4 155 92 48 59 130 93]

```

Or expressed as a string

```
"0eë `\ËÊ¤GÁpMOÒ·bAÆìSÝÜ©þ+|õ°¶§|_¿Mé¾Z££jÁÜým9Û[Úß«qÑÏ{nÜO°«#ç¬Sxrw/Ùã2iì[¡âpª9¢$Y  z¤ólégR©96GË
Û¨*Ú¥}¹·ñ[ÁUÃGºb\"ÄNÁü±^· MIÁ>Ü!Ñåid¼WëËhÏ¡füxòÞéørÙÄ*¡ô  Õ²zªæõE Äç¯0be¢¾È>â=Èèi»¸yü«ðæ^¡ÑÍÁ  \0;]"

```

(Plus some unprintable characters which are stripped by SE.)

Of course, that's still too long for your 255 character allowance. If you're actually talking about *characters* though (as opposed to bytes), you can go into Unicode and use a much bigger base. How about 216? That's only 139 digits:

```
[12 6300 12389 38379 8288 23572 52170 42128 18369 32624 19853 20434 46946 39696 38721 50714 60499 56796 33193 65067 31989 6576 46759 31839 48973 6633 35774 1927 661 23203 41834 49628 64877 33081 56155 40410 4831 2987 29137 44495 31598 56399 35760 36779 1822 9191 38828 21368 29303 12249 58162 27116 23457 57968 4266 14754 37668 22810 2426 41999 4083 27678 3817 35687 35154 43266 14646 18330 34839 52105 2779 39192 43050 55973 32185 47089 23489 21955 18362 4706 8900 19974 49660 2225 24069 6281 46975 33033 19861 18836 49470 56466 8578 5585 39397 26980 48215 60363 26831 41236 4454 38652 30962 57065 63602 55694 8132 10913 44288 62473 54706 39034 43656 59015 34037 17673 50407 37640 44848 25189 6050 37054 51262 57917 7112 4072 3177 48056 1145 64683 61670 24225 38787 53709 33473 2308 39772 12347 33373]

```

(I can't include the actual string here, because it contains some CJK characters that are banned by SE.)

Now that seems more doable. You just need to be able to decode it in 116 characters. If you can't, Unicode has a lot more than 216 characters, so you could try using an even larger base.
> 11 votes

# Answer
**Prime Factorization**

If the number has no interesting features, base encoding is the best way to do it. The next thing to do is look for interesting features of the number. The first one that comes to mind is that it may have factors of small primes (2,3,5,7, etc) raised to quite large powers. IF you have nothing else to go on, keep trying to divide by small primes and see what happens. If its factors include `2**4`, `3**4`, and `7**4`, you can write `big number *42**4` which is a few bytes shorter than `big number * 3111696`
> 4 votes

# Answer
# Recursive removal of largest square

This approach removes the largest square number from N, repeatedly, until there's no value in continuing.

```
while(n>999*999):
    s = sqrt(n,2)
    print s,"** 2 +"
    n = n - s**2
print n

```

If you ignore the "\**2+" characters, this one comes out to approximately the same number of digits as the original number, on average. Making up for those 4 extra characters per iteration requires a bit of luck. In the case of your number, the result has 670 digits of square numbers, plus 7x"\**2+", another failure:

```
755855006990505232214298076833020140623897728341856142793250050184099570268569900389346192358073922001480310798643405893673501405667458785677166605919485512157948819102093414848159820683798554799982163455753292781944741934237780592730586508786425528910736750640071037094033497266578109597923654387813828207885510302579581252831537751**2+
33300095205899066129442737321270515378501483166974896029394675779096351509514355500527819871697116193238261137790928953798777695127752032484956608505929119246433389165**2+
187763197402063683206154659623192450644818397963460986292088297442441704645626089130**2+
278760215056365252005927060531480627653626**2+
639191600506542558482**2+
25777519523**2+
106673**2+
103405

```

By almost breaking even on average, this algorithm lends itself well to being used in conjunction with other algorithms (or even itself) to further reduce the numbers in the expression (at the cost of some parentheses). Those other algorithms can be more expensive, as they will be operating on significantly smaller numbers than the original. In the given example, a net gain could be had if a more expensive and effective algorithm could cut out 25% of the characters of `33300095205899066129442737321270515378501483166974896029394675779096351509514355500527819871697116193238261137790928953798777695127752032484956608505929119246433389165` (the second large value in the result)
> 3 votes

# Answer
# Nearby large powers

This approach looks for \[relatively\] small numbers raised to some power that come close to the target number. In most cases restating N as A\**B+C will not be an improvement, but in some cases it will be.

```
def nearest_power(n):
    mindiff = 1
    best = (n,1)
    for a in xrange(2,10000):
        b = math.log(n,a)
        if math.ceil(b)-b<mindiff:
            mindiff = math.ceil(b)-b
            print a,"**",b
            best = (a,b)
        if b-math.floor(b)<mindiff:
            mindiff = b-math.floor(b)
            print a,"**",b
            best = (a,b)
    return best

```

`10000` is an arbitrary constant. The bail-out condition could also be based on some target `mindiff`.

In the case of your sample number N with 666 digits, this function (with the 10k cap increased a bit) finds that `N ~= 165661162**81.0000000025`, so `N-165661162**81` is a 659 digit number, cutting 7 digits off the number to be handled at a cost of 14 characters of expression, a failure.
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, tips, python, compression
---


title: Print The Formula

text:
# Question
Title: Print The Formula
## Introduction

In chemistry there is a type of extension, .xyz extension,(https://en.wikipedia.org/wiki/XYZ\_file\_format), that prints in each line a chemical element, and the coordinates in the plane of the element. This is very useful for chemists to understand chemical compounds and to visualize the compounds in 3D. I thought it would be **fun** to, given a .xyz file, print the chemical formula.

## Challenge

Given an .xyz file, print the chemical formula of the compound in **any** programming language in the smallest possible number of **bytes**. Note:

* Originally, the input was to be given as a file. As I have been pointed out, this constraints the challenge. Therefore **you may assume** the input is a list/array of strings, each representing a line of the .xyz file.
* There are no restrictions in the ordering of the elements.
* Each element should be printed with an underscore "\_" delimiting the element and the number of times it appears
* The first two lines of any .xyz file is the number of elements, and a comment line (keep that in mind).

## Example Input and Output

Suppose you have a file *p.xyz* which contains the following (where the first line is the number of elements, and the second a comment), input:

```
5
A mystery chemical formula...
Ba      0.000   0.000  0.000
Hf      0.5     0.5    0.5
O       0.5     0.5    0.000
O       0.5     0.000  0.5
O       0.000   0.5    0.5

```

---

> **Output:**
> Ba\_1Hf\_1O\_3

---

## Testing

A quick test is with the example mentioned. A more thorough test is the following: since the test file is thousands of lines, I'll share the .xyz file:
https://gist.github.com/nachonavarro/1e95cb8bbbc644af3c44

# Answer
> 2 votes
# Pyth - 18 bytes

```
sjL\__MrShMcR;ttQ8

```

Try it online here.

# Answer
> 2 votes
# Japt, 21 bytes

```
U=¢m¸mg)â £X+'_+Uè_¥X

```

Test it online! Input is given as an array of strings (which can be formatted as in the link).

### Ungolfed and explanation

```
U=¢   m¸  mg)â £    X+'_+Uè_  ¥ X
U=Us2 mqS mg)â mXYZ{X+'_+UèZ{Z==X

          // Implicit: U = input array of strings
Us2       // Slice off the first two items of U.
mqS mg    // Map each item by splitting at spaces, then taking the first item.
U=    )   // Set U to the result.
â mXYZ{   // Uniquify, then map each item X to:
UèZ{Z==X  //  Count the number of items Z in U where Z == X.
X+'_+     //  Prepend X and an underscore.
          // Implicit output

```

# Answer
> 1 votes
# AWK, 44

```
NR>2{a[$1]++}END{for(i in a)printf i"_"a[i]}

```

Try it online.

# Answer
> 0 votes
# Shell + GNU Utilities, 67

```
sed '1d;2d;s/ .*//'|sort|uniq -c|sed -Ez 's/\s*(\S+) (\S+)/\2_\1/g'

```

Try it online.

# Answer
> 0 votes
# Mathematica, ~~79~~ 53 bytes

```
StringRiffle[Tally@StringExtract[#[[3;;]],1],"","_"]&

```

Quite simple.

---
Tags: code-golf, string, chemistry
---


title: Draw and label an ASCII hexagonal grid

text:
# Question
Title: Draw and label an ASCII hexagonal grid
In my previous challenge, I drew the first diagram mostly by hand (with the help of vim's visual block mode). But surely there must be a better way...

---

Given an input of two dimensions, a width and a height, output a hexagonal grid with those dimensions in ASCII art.

Here's the diagram referenced in the intro (with minor edits), which should be your output for the input `width=7, height=3`:

```
         _____         _____         _____
        /     \       /     \       /     \
  _____/ -2,-1 \_____/  0,-1 \_____/  2,-1 \_____
 /     \       /     \       /     \       /     \
/ -3,-1 \_____/ -1,-1 \_____/  1,-1 \_____/  3,-1 \
\       /     \       /     \       /     \       /
 \_____/ -2,0  \_____/  0,0  \_____/  2,0  \_____/
 /     \       /     \       /     \       /     \
/ -3,0  \_____/ -1,0  \_____/  1,0  \_____/  3,0  \
\       /     \       /     \       /     \       /
 \_____/ -2,1  \_____/  0,1  \_____/  2,1  \_____/
 /     \       /     \       /     \       /     \
/ -3,1  \_____/ -1,1  \_____/  1,1  \_____/  3,1  \
\       /     \       /     \       /     \       /
 \_____/       \_____/       \_____/       \_____/

```

Notice several things:

* The width and height are essentially equivalent to how many hexagons there are for a given y and x coordinate respectively. These will *always* be odd numbers.
* Each hexagon is represented by the ASCII art

```
  _____
 /     \
/       \
\       /
 \_____/

```

but borders are "shared" between neighboring hexagons.
* The comma in the coordinates is *always* exactly two characters below the center of the top edge. The x-coordinate is then positioned directly before the comma, and the y-coordinate directly after.

You may assue that the coordinates will never be too large such that they would overlap the hexagon's borders.

Input may be taken as a whitespace-/comma-separated string, an array of integers, or two function/commandline arguments. Output must be a single string (to STDOUT, as a return value, etc.).

Since this is , the shortest code in bytes will win.

The grid above can be used as a test case. The maximum-sized `width=199, height=199` grid is obviously impractical to include here, but the first few rows and columns should look like the following:

```
         _____         ___
        /     \       /
  _____/-98,-99\_____/-96,
 /     \       /     \
/-99,-99\_____/-97,-99\___
\       /     \       /
 \_____/-98,-98\_____/-96,
 /     \       /     \
/-99,-98\_____/-97,-98\___
\       /     \       /
 \_____/-98,-97\_____/-96,
 /     \       /     \
/-99,-97\_____/-97,-97\___
\       /     \       /

```

# Answer
> 2 votes
# Ruby, 221 bytes

```
->w,h{s=' '
a=(s*9+?_*5)*(w/2)+$/
(2-h*2).upto(h*2+3){|y|c=y<4-h*2
a+=[b=c ?s:?\\,s+b,s,''][y%4]
(0-w/2).upto(w/2){|x|a+=["/#{h<y/2?s*7:"%3d,%-3d"}\\",s*7,?_*5,"/     \\"][(y+x*2+w)%4]%[x,y/4]}
a+='//  '[c ?3:y%4]+$/}
a}

```

**Ungolfed in test program**

```
f=->w,h{
  s=' '                                #set s to space for golfing reasons
  a=(s*9+?_*5)*(w/2)+$/                #start building the output with a row of just _ and space

  (2-h*2).upto(h*2+3){|y|              #iterate 4 times for each row of hexagons, plus an extra 2 at the end to finish last row
    c=y<4-h*2                          #condition for first two rows
    a+=[b=c ?s:?\\,s+b,s,''][y%4]      #string to be output before main set of hexagons (spaces for top row, \ for certain other rows

    (0-w/2).upto(w/2){|x|              #iterate through hexagons on each row, 4 lines for each with the following printf type string
      a+=["/#{h<y/2?s*7:"%3d,%-3d"}\\",#line 1:contains ends / \ and numbers
         s*7,                          #line 2 padding spaces
         ?_*5,                         #line 3 padding ___
         "/     \\"][(y+x*2+w)%4]%     #line 0 top of hexagon / \; formula to select string to be printed
           [x,y/4]                     #numbers to be printed (if format for current line does not require them they are ignored)
    }

    a+='//  '[c ?3:y%4]+$/             #ending alternates between / and space; / are suppressed for first two rows
  }
  a
}

puts g[7,3]
puts g[5,5]

```

**Output**

As I was finishing debugging, I noticed an ambiguity in the spec. Where `w+1` is divisible by 4, the first and last x coordinates are odd, and there is no ambiguity. But where `w-1` is divisible by 4 the first and last x coordinates are even. I assumed that the first and last columns should be offset below the next ones. But then I read the previous question and noted in that case it was the odd columns that should be offset below the even ones (note for `w-1` divisible by 4 it is not possible to do both.)

That distinction was not made in this question, however. I will leave this up to OP's judgement and rework if necessary, though I'd prefer not to have to.

```
         _____         _____         _____
        /     \       /     \       /     \
  _____/ -2,-1 \_____/  0,-1 \_____/  2,-1 \_____
 /     \       /     \       /     \       /     \
/ -3,-1 \_____/ -1,-1 \_____/  1,-1 \_____/  3,-1 \
\       /     \       /     \       /     \       /
 \_____/ -2,0  \_____/  0,0  \_____/  2,0  \_____/
 /     \       /     \       /     \       /     \
/ -3,0  \_____/ -1,0  \_____/  1,0  \_____/  3,0  \
\       /     \       /     \       /     \       /
 \_____/ -2,1  \_____/  0,1  \_____/  2,1  \_____/
 /     \       /     \       /     \       /     \
/ -3,1  \_____/ -1,1  \_____/  1,1  \_____/  3,1  \
\       /     \       /     \       /     \       /
 \_____/       \_____/       \_____/       \_____/
         _____         _____
        /     \       /     \
  _____/ -1,-2 \_____/  1,-2 \_____
 /     \       /     \       /     \
/ -2,-2 \_____/  0,-2 \_____/  2,-2 \
\       /     \       /     \       /
 \_____/ -1,-1 \_____/  1,-1 \_____/
 /     \       /     \       /     \
/ -2,-1 \_____/  0,-1 \_____/  2,-1 \
\       /     \       /     \       /
 \_____/ -1,0  \_____/  1,0  \_____/
 /     \       /     \       /     \
/ -2,0  \_____/  0,0  \_____/  2,0  \
\       /     \       /     \       /
 \_____/ -1,1  \_____/  1,1  \_____/
 /     \       /     \       /     \
/ -2,1  \_____/  0,1  \_____/  2,1  \
\       /     \       /     \       /
 \_____/ -1,2  \_____/  1,2  \_____/
 /     \       /     \       /     \
/ -2,2  \_____/  0,2  \_____/  2,2  \
\       /     \       /     \       /
 \_____/       \_____/       \_____/

```

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