title: Analyse your Chair

text:
# Question
Title: Analyse your Chair
This challenge is based on Downgoat's Adjust your chair.

## Challenge

You just adjusted your new chair! It fits you perfectly. However, the wheel is squeaky and you know the repair people will change the adjustment. Problem is, you don't have a ruler, so you'll have to write a program to measure it for you.
The repair people can only wait for so long. So your code needs to be as short as possible.

## Examples

```
O
|
|
| _
| |
|_|_
  |
  |
  O

5,3,2,2,1

```

```
O
|  _
|  |
|__|__
   |
   |
 __|__
 OOOOO

3,5,2,3,5

```

```
O
|      _
|______|______
 ______|______
 OOOOOOOOOOOOO

2,13,1,1,13

```

## Chair parts

The chair has various components:

```
O  <- Headrest
|
|  <- Backrest
|  _  <- Armrest
|  |
|__|__ <- Seat
   |
   |   <- Leg
  _|_
  OOO  <- Wheels

```

## Detailed Chair Descriptions

The parts of the chair are:

---

**Headrest:** There will always be one headrest above the backrest

```
O
|

```

**Backrest:** The number of `|` is the **Backrest Height**

```
O
|
|

```

**Seat:** The number of `_` is the **Seat Width**, there is a `|` in the middle for the armrest.

```
__|__

```

**Armrest:** The number of `|` is the **Armrest Height**. This will be inserted in the middle of the seat.

```
_
|
|

```

**Leg:** The number of `|` is the **Leg Height**

```
|
|

```

**Wheels:** The wheels are centred below the legs. If they are more than one, all but the centre wheel will have `_` in the line above them.

```
_ _
OOO

```

## Output

Given a chair, you will be outputting various variables.

The output should be in the following order:

1. Backrest Height
2. Seat Width **always odd**
3. Armrest Height **Always less than backrest height**
4. Leg Height
5. Wheel count **Always less than or equal to seat width** and **Always odd**

The output may have a trailing newline, or be in an array / list form if it is a function.

## Leaderboard

```
/* Configuration */

var QUESTION_ID = 67522; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 43394; // This should be the user ID of the challenge author.

/* App */

var answers = [],
  answers_hash, answer_ids, answer_page = 1,
  more_answers = true,
  comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function(data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function(data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+(?:[.]\d+)?)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if (OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function(a, b) {
    var aB = a.size,
      bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function(a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
      .replace("{{NAME}}", a.user)
      .replace("{{LANGUAGE}}", a.language)
      .replace("{{SIZE}}", a.size)
      .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {
      lang: a.language,
      user: a.user,
      size: a.size,
      link: a.link
    };
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function(a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i) {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
      .replace("{{NAME}}", lang.user)
      .replace("{{SIZE}}", lang.size)
      .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

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

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr>
        <td></td>
        <td>Author</td>
        <td>Language</td>
        <td>Size</td>
      </tr>
    </thead>
    <tbody id="answers">

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

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

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

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

```

# Answer
> 3 votes
## Lua, 187 Bytes

I think I might be able to golf it some more, but I think this is good at the moment. Also, if the output needs to be comma-separated I can fix that, but this still meets the requirements methinks.

Also, input is fed in one line at a time. After the wheels are input, press enter with an an empty line to finalize input.

```
c={}i=1t=""while c[i-1]~=""do c[i]=io.read():gsub("%s+","")t=t..c[i]a=(not a and c[i]:find("_")and i or a)s=(not s and c[i]:find("_|_")and i or s)i=i+1 end print(s-1,c[s]:len()-1,s-a,#c-s-2,c[#c-1]:len())

```

**Ungolfed**

```
c={}
i=1
while c[i-1]~=""do
    c[i]=io.read():gsub("%s+","")          --remove spaces
    a=(not a and c[i]:find"_"and i or a)   --armrest position
    s=(not s and c[i]:find"_|_"and i or s) --seat position
    i=i+1
end
print(s-1, c[s]:len()-1, s-a, #c-s-2, c[#c-1]:len())

```

(Positions are measured top-to-bottom, so the top 'O' is position 1, and the wheels are the largest position.

* Backrest height is the position of the seat minus one, compensating for the 'O' at the top.
* Seat size is the length of th string at the seat's position minus one, compensating for the backrest.
* Armrest height is the position of the seat minus the position of the armrest.
* Leg height is the height of the chair (`#c`) minus the position of the seat minus 2, to compensate for the wheels and seat.
* Wheel count is the length of the final string.

# Answer
> 3 votes
# Groovy, 161 bytes!!!

Yay!! Not in last!!

```
f={s->a=s.split(/\n/)
b=a.findIndexOf{it.contains('|_')}
d=b-a.findIndexOf{it.contains('_')}
print"$b,${a[b].count('_')+1},$d,${a.size()-b-2},${s.count('O')-1}"}

```

Ungolfed:

```
f={String s ->
    split = s.split(/\n/)
    bottomOfChairBack = split.findIndexOf {it.contains('|_')}
    armHeight = bottomOfChairBack-split.findIndexOf {it.contains('_')}
    width = split[bottomOfChairBack].count('_')+1
    height = split.size() - bottomOfChairBack - 2

    wheelCount = s.count('O')-1
    return [bottomOfChairBack, width, armHeight, height, wheelCount]
}

```

Tests of ungolfed program:

```
assert f('''O
|
|
| _
| |
|_|_
  |
  |
  O''') == [5, 3, 2, 2, 1]

assert f('''O
|  _
|  |
|__|__
   |
   |
 __|__
 OOOOO''') == [3,5,2,3,5]

assert f('''O
|  _
|  |
|__|__
   |
   |
 __|__
 OOOOO''') == [3,5,2,3,5]

assert f('''O
|      _
|______|______
 ______|______
 OOOOOOOOOOOOO''') == [2,13,1,1,13]

```

# Answer
> 2 votes
# Pyth, 57 54 53 50 bytes

Probably can be golfed further. -3 bytes thanks to issacg for the single character string trick.

```
=kjb.z
=H/k+b\|
-/k\_=G-/k\O2
--/k\|H=Nt/k+bd
N
hG

```

Explanation:

```
=kjb.z
=k              Assign k
     z          Input
  jb.           Join list by newlines

=H/k+b\|
=H              Assign H
  / +b\|        Count occurrences of "\n|"
   k            In input
                (Implicit: print backrest height)

-/k\_=G-/k\O2
     =G         Assign G
       -/k\O2   The number of wheels minus 1
-/k\_           Count the number of "_"
                (Implicit: print seat width)

--/k\|H=Nt/k+bd
       =N       Assign N
          /k+bd Count the number of lines starting with " "
         t      Subtract 1 (N is now the leg height)
  /k\|          Count the number of "|"
 -    H         Subtract the "|" for the backrest
-               Subtract leg height
                (Implicit: print armrest height)

N               Print leg height

hG              Print the number of wheels

```

# Answer
> 2 votes
# Perl, ~~93+2=95~~ ~~90+1=91~~ 83+1= 84 bytes

*Apparently the output doesn't need comma-separating*

Invoke with `perl -n chair.pl chairInput` (1B penalty for the flag).

```
END{print$b,2+$u-$o,$a,$.-$b-2,$o-1}$u+=s/_//g;$o+=s/O//g;s/^\|//&&$b++&&/\|/&&$a++

```

Ungolfed:

```
END{         # Put the END block first to save 1 ;
    print
        $b,
    2+$u-$o,
    $a,
    $.-$b-2, # $. is the number of lines total
    $o-1
}
$u+=s/_//g; # count _s incrementally
$o+=s/O//g; # count Os incrementally
s/^\|// && $b++ # it's backrest if it starts with |
    && /\|/ && $a++ # and it's armrest if it has another one

```

---

## Previous version:

Invoke with `perl -0n chair.pl < chairInput`

```
s/^\|//&&$b++?/\|/&&$a++:$h++for split"
",$_;$,=",";print$b,2+s/_//g-($o=s/O//g),$a,$h-3,$o-1

```

Explanation:

```
s/^\|// && $back++   # the backrest is all lines starting with |
    ? /\|/ && $arm++ # the armrest is all of those lines with another |
    : $height++      # otherwise it counts for the seat height
    for split"
",$_;       # literal newline for 1 byte saved
$,=",";     # output separator
print
    $back,
    2+s/_//g-($o_count=s/O//g),  # you can find the seat size
                                 # from the different between the number
                                 # of Os and _s
    $arm,
    $height-3,
    $o_count-1

```

# Answer
> 1 votes
# Python 3, ~~160~~ 158 bytes

This code works but only on the following conditions: 1) `armrest height > 0` otherwise the `_` count breaks and 2) `seat width > 1` otherwise the armrest blocks the width-one seat and the `_` count breaks.

```
def f(s):
 a=s.split("\n");x=[];y=[];l=len(a)
 for i in range(l):
  m=a[i].count("_")
  if m:x+=i,;y+=m,
 return x[1],y[1]+1,x[1]-x[0],l-x[1]-2,s.count("O")-1

```

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


title: Drawing 3d nets - Platonic solids

text:
# Question
Title: Drawing 3d nets - Platonic solids
This is a basic version of the rather more difficult Drawing 3d nets - Archimedean solids .

I have a weakness for 3d nets which when cut out and folded allow you to make 3d shapes out of paper or card. The task is simple, write the shortest program you can that draws nets for the 5 Platonic solids. The output should be an image file in any sensible format of your choosing (png, jpg, etc.).

All five shapes are described at http://en.wikipedia.org/wiki/Platonic\_solid . Their nets looks like this (taken from http://www.newscientist.com/gallery/unfolding-the-earth/2 ).

**Input:** An integer from 1 to 5. Assume the shapes are numbered in order of the number of sides they have. So, 1 would be a tetrahedron and 5 the icosahedron.

**Output:** An image file containing the net for that shape. Just the outline including the internal lines is OK. There is no need to fill it in with colors

You can use any programming language you like as well as any library that was not made especially for this competition. Both should be available freely however (in both senses) online.

I will accept the answer with the smallest number of characters in exactly one week's time.

**Winner.** Only one entrant but it was wonderful. The winner is ... Raufio for what is my favourite piece of code golf ever.

# Answer
> 8 votes
## Python, 456 429 381

```
import turtle as t
L="fl"
R="fr"
d=L*3+R*3
b=(d+R)*3
a=[b,120,L*3+"fflflffflflfrflflfffl"+R*4+"flf",90,b+"ffrfrflffrffrfrfrflflf",120,(R*5+L*5+R+L)*5+"rrfr"+L*5+R*2+L*2+R*4+"f",72,(d+"f")*5+"rfl"+((d+"b")*5)[:-1],120]
l=t.lt
f=t.fd
b=t.bk
r=t.rt
p=input()*2-2
t.setup(.9,.9)
t.goto(-200,150)
t.clear()
for c in a[p]:exec c+"(a[p+1])"
t.getscreen().getcanvas().postscript(file="o")

```

I implemented a primitive interpreter with `l r f b` as operators that move the turtle cursor around at the angle of the shapes. At one time, it turns only one angle. I compressed the strings by reusing strings (kind of like psuedo-subroutines), other than that, I didn't check to see if I was using the best path. It outputs to a postscript file.

A little explanation of un-golfed code:

```
import turtle as t
Left="fl"
Right="fr"
diamond= Left*3 + Right*3
tetrahedron=(d+R)*3 #used to be b

```

Imports the built-in turtle module and defines the macros that shorten the strings. The turtle module uses commands to move a 'turtle' around the screen (ie forward(100), left(90))

```
netList=[
   #tetrahedron
   tetrahedron,120,
   #cube
   Left*3+"fflflffflflfrflflfffl"+Right*4+"flf",90,
   #octohedron, builds off the tetrahedron
   tetrahedron+"ffrfrflffrffrfrfrflflf",120,
   #dodecahedron
   (Right*5 + Left*5 + Right + Left)*5
    +"rrfr"+
    Left*5 + Right*2 + Left*2 + Right*4 + "f",72,
   #icosahedron
   (diamond+"f")*5 +"rfl"+((diamond+"b")*5)[:-1],120
]

```

This list holds the angles and movement sequences. The tetrahedron was saved to reuse with the octohedren.

```
l=t.left
f=t.forward
b=t.back
r=t.right

```

This is the part that i like, it makes single character local functions so the calls can be shortened and automated through pre-defined strings.

```
input=int(raw_input())*2-2
t.setup(.9,.9)
t.goto(-200,150)
t.clear()

```

This starts by taking the input (between 1 and 5), and converting that to an index that points to the shape string in the netList. These setup turtle to show the whole net. These could be left out if the task was just to draw them, but since we need a picture output they are needed.

```
for command in netList[input]:
    exec command+"(netList[input+1])"
t.getscreen().getcanvas().postscript(file="o")

```

The for loop takes the commands in the command sequence string and executes them, so for a string like "fl", this executes "forward(angle);left(angle);" by calling the newly created local functions. the last line outputs a file called 'o' that is in postscript format format using turtle function.

**To run**:

Copy it into a file and run it from there. When you run it, it will wait for a number input between 1 and 5 (i just changed it so that it asks before setting up turtle). When you input a number, a window pops up and draws the net. if you want it to go faster you can add `t.speed(200)` before `setup`.

You can copy-paste it into the interpreter, but when `raw_input()` is called it consumes the next string you input `"t.setup(.9,.9)"` instead of a number. So if you do this, copy up until `raw_input()`, input a number, than copy paste the rest. It is intended to be run as a whole. Or you could copy it into a function and call it.

Here are it's outputs (converted from postscript):

Note: the position of these in the window has changed, but their overall shape is the same.

It's a little brute force for code golf, but I got tired of trying to find a consistent pattern between the shapes.

# Answer
> 6 votes
## Mathematica

Out of competition, not a free language (unless a free trial counts as free)

```
f[n_] := PolyhedronData[ Sort[PolyhedronData["Platonic", {"FaceCount","StandardName"}]][[n,2]],
                                                                                "NetImage"]

```

Usage:

```
f /@ Range@5

```

# Answer
> 5 votes
# Python 2 (with cairo) - 239

```
from cairo import*
s=PSSurface(None,99,99)
g=Context(s)
g.move_to(30,20)
a=str([34,456,3455,568788,3454445555][input()-1])
f=6.28
for c in a+a[::-1]:exec'g.rel_line_to(8,0);g.rotate(f/int(a[0]));'*int(c);f=-f
g.stroke()
s.write_to_png('o')

```

Results:

# Answer
> 2 votes
# Logo, 199 bytes

```
TO p:d:n:s
rt :n*45 for[i 1 :n/8][pu setxy :d*:i 0 pd repeat 2[for[k 1 :s*2+2][fd 40 rt (360-720*(:k>:s))/:s] rt 720/:s]]END
TO q:j
apply "p item :j [[70 9 3][56 23 4][70 16 3][105 26 5][40 42 3]]END

```

Reading this back I see my original version did not comply with the spec as written (take a numerical argument and draw one shape) but rather as interpreted by some of the other answers (draw all shapes.) The new version fixes this. It expects to be called as for example `q 5`. `cs` should be done before to clear the screen and point the turtle north.

`q` calls the main function `p` with 3 arguments. The syntax for this is pretty bloated, so to beat my previous score I had to shave off bytes elsewhere.

the new version of `p` takes 3 arguments. There is no need for `x` and `y` because we only plot one net, but `d` the pitch between subunits remains. `s` is still the number of sides per polygon, and `n` now encodes for two different things\> `n/8` is the number of subunits to be plotted, and `n*45` is an angle through which the turtle must be turned before starting (taking advantage of the natural mod 360 for rotations.)

Improved looping accomplishes drawing `s` lines with righthand rotation and `s+2` lines with lefthand rotation in a single loop.

the calormen interpreter seems to be less tolerant of missing whitespace now than at the time of my first post, but the code runs fine on http://turtleacademy.com/playground/en

# Logo, 200 bytes

```
TO p:x:y:d:n:s
for[i 1:n][pu setxy:x:y-:d*:i if:i<>6[pd]repeat 2[repeat:s[fd 40 rt 360/:s]repeat:s+2[fd 40 lt 360/:s]rt 720/:s]]END
p 0 200 40 7 3
p 70 0 80 2 3
p -200 200 105 3 5
rt 45
p 90 90 56 2 4

```

Interpreter at http://www.calormen.com/jslogo/# It is assumed the turtle is pointing North before the program is run. Use the `cs` command to clear the screen, point the turtle north, and place it at the origin in the centre of the screen.

The basic unit of all the above nets is a pair of back to back polygons. These are arranged in 2 staggered rows, making a subunit of 4 polygons which can be translated vertically to make all the nets (except the octahedron, which hitches a ride on the drawing of the icosahedron and tetrahedron). The subunit forms 1 tetrahedron net, 1/5 of the icosahedron net, 1/3 of the dodecahedron net and 2/3 of the cube net (two subunits are drawn, with the middle two squares overlapping.)

**Ungolfed code**

```
TO p :x :y :d :n :s                 ;x,y=starting point d=negative vertical offset for each iteration n=#of iterations s=# of sides on polygon
  for[i 1 :n][                      ;iterate n times
    pu                              ;pen up
    setxy :x :y- :d* :i             ;move pen to start of iteration
    if :i<>6[pd]                    ;pen down (supressed for i=6 to enable part of octahedron to be drawn with icosahedron)
    repeat 2[                       ;draw lower row of 2 polygons, then upper row of 2 polygons
      repeat :s[fd 40 rt 360/ :s]   ;starting at lower left of polygon facing up, draw righthand polygon
      repeat :s+2[fd 40 lt 360/ :s] ;starting at lower right of polygon facing up, draw lefthand polygon, duplicating last two sides
      rt 720/ :s                    ;return turtle to upwards facing in order to draw second row
    ]
  ]
END
cs
p 0 200 40 7 3                      ;draw icosahedron and left side of octahedron (6th iteration is suppressed)
p 70 0 80 2 3                       ;draw right side of octahedron, and tetrahedron
p -200 200 105 3 5                  ;draw dodecahedron
rt 45                               ;turn turtle in preparation for drawing cube
p 90 90 56 2 4                      ;draw cube

```

---
Tags: code-golf, graphical-output, geometry
---


title: In a string or not?

text:
# Question
Title: In a string or not?
Recently I've been having some trouble with the new TeaScript interpreter. The biggest problem is identifying whether or not a string contains any special characters.

---

# Challenge

A special character is defined as a character with codepoint 160 to 255. You will be given an input which is a string of characters with codepoints 0 to 255, at most one of which is a special character. The input will consist of a prefix of zero or more characters, a quoted string, and a suffix of zero or more characters. If there is a special character in the quoted string you should output a truthy value, otherwise a falsey value.

## Details

* The characters `"'` are considered quotes.
* Inside the quoted string, a backslash `\` will be used to escape the following character. In the prefix and suffix, it has no special meaning.
* Quotes will always be balanced.
* There will only be one quoted string.

## Examples

```
"Hello, World¡"
true

"Hello, World"¡
false

"Hello' Wo\"rld\\"¡
false

ab"cd\"ef\\gh\i\\"£
false

\"foo¡"
true

```

# Answer
> 5 votes
## Retina, ~~19~~ 17 bytes

*Thanks to user81655 for saving 2 bytes.*

Byte count uses ISO 8859-1.

```
['"].*[¡-ÿ].*['"]

```

Output is 0 or 1.

Try it online.

### Explanation

Due to the assumptions of the challenge, the first `'` or `"` will start the only string of the input and the last `'` or `"` ends it. We also don't need to worry about them being the same because they are guaranteed to be the same anyway.

Therefore, the regex just tries to find a character with code point 161 to 255, inclusive, which is preceded by one quote and followed by another. There will always be either 0 or 1 match.

# Answer
> 4 votes
**Note:** This can be done with a simple regular expression. `s=>s.match`['"].*[¡-ÿ].*['"]`` is 29 bytes in JavaScript, but it's more fun without regular expressions:

# JavaScript (ES6), ~~84~~ 82 bytes

```
s=>[...s].map((c,i)=>q?i<s.lastIndexOf(q)&c>" "?r=1:s:c=="'"|c=='"'?q=c:0,q=r=0)|r

```

## Explanation

Returns `1` for `true` and `0` for `false`. The `" "` in the code below is a `U+00A0 NO-BREAK SPACE` (code point 160).

```
s=>
  [...s].map((c,i)=>     // for each character c in the string
    q?
      i<s.lastIndexOf(q) // if we are still inside the string
        &c>" "?r=1       // and c is a "unicode character", set the result to 1 (true)
      :s                 // returning s for false guarantees that the array returned by map
                         //     will cast to NaN, which allows us to use |r instead of &&r
    :c=="'"|c=='"'?      // if we are starting a string
      q=c                // set the end of string character
    :0,
    q=                   // q = end string character
      r=0,               // initialise r to 0 (false)
  )|r                    // return r

```

## Test

```
var solution = s=>[...s].map((c,i)=>q?i<s.lastIndexOf(q)&c>" "?r=1:s:c=="'"|c=='"'?q=c:0,q=r=0)|r
```

```
<input type="text" id="input" value='ab"cd\"ef\\gh\i\\"£' />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

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


# Question
Title: Write a function that tells you which of its lines has been removed
Write a function that contains five lines.

If you run the function as-is, it should return 0.

If you remove any one of the five lines and run the function, it should tell you which of the lines has been removed (e.g., if you remove the final line it should return 5).

Brevity, novelty, and elegance all deserve consideration. Highest upvoted solution (after a reasonable amount of time) wins.

# Answer
## Ruby

Eschewing magic numbers since it's not code golf.

```
def f
  r=2^3^4^5
  defined?(r) ? r^=2 : r=1^3^4^5
  r^=3
  r^=4
  r^=5
end

```

Each line strips its own number out of `1^2^3^4^5`. It's Ruby, so the last line defines the return value.
> 19 votes

# Answer
## JavaScript ( ~~134~~   ~~77~~   ~~69~~   ~~65~~  60 chars)

## → live demo ←

```
function(n){
a=n-=1
n-=2
+3
+4;if(this.a)return 5
return n;var a
}

```

call this function with n = 10.

* If no line is missing, line 5 returns n == 0.
* If line 1 is missing, line 5 returns n == 1.
* If line 2 is missing, line 5 returns n == 2.
* If line 3 is missing, line 5 returns n == 3.
* If line 4 is missing, line 5 returns n == 4.
* If line 5 is missing, the var "a" becomes global and line 4 detects that to return "5".
* If line 5 is present, the JS engine performs "variable hoisting", "a" becomes a local var, and line 4 doesn't return "5".

## Previous versions:

## 65 chars

```
function(n){
a=n-=1
n-=2
+3
+4;if(this.a)return 5
n-=5;return n;var a
}

```

(must be called with n = 15)

## 69 chars

```
function(n){
n-=1
n-=2
n-=3
a=n-=4;if(this.a)return 5
n-=5;return n;var a
}

```

(must be called with n = 15)

## 77 chars

```
function(){
a=
b=
c=
d=1;if(this.a)return 5
1;var a,b,c,d;return d?c?b?a?0:1:2:3:4
}

```

## 134 chars

```
function w(){
a=1;e=1;if(this.e)return 5
b=1;if(!a)return 1
c=1;if(!b)return 2
d=1;if(!c)return 3
var a,b,c,d,e;return d?0:4
}

```

## non-golfed

```
  function whichlineisremoved(){
    /* 1 */ var a = 1; e = 1; if(window.e) return 5;
    /* 2 */ var b = 1, a; if(!a) return 1;
    /* 3 */ var c = 1, b; if(!b) return 2;
    /* 4 */ var d = 1, c; if(!c) return 3;
    /* 5 */ var e = 1, d; if(!d) return 4; return 0;
  }

```
> 13 votes

# Answer
## Python

If parameters are allowed, then this will work:

```
def f(n=10):
    n -= 1
    n -= 2
    n -= 3
    if n == 4: return 0 if f(7) else 5
    return n - 4 or 4

```
> 6 votes

# Answer
## R

```
f <- function() {
  T <- FALSE
  F <- TRUE
  month.abb <- TRUE
  (pi <- 5)
  T + (!F) * 2 + (!isTRUE(month.abb)) * 3 + (pi != 5) * 4
}

```

The function uses built-in "constants" and assigns another value to each of them. If all of these variables are equal to the new value, the function returns 0. Logical values are transformed to numeric ones because of the mathematical operators. The parentheses around the 4th line allow visibly returning its result (if it's the last command).
> 4 votes

# Answer
# Lua 5.2+

55 chars in the function body excluding newlines. I couldn't come up with anything better but this:

```
function f()
return 7--[[
return 1--[=[]]-2
--[[
-2--[=[]]
-5--]=]--]]-1
end

```

Hoping to get extra points for comments abuse :P

The reason it does not work in 5.1 is that nested `[[]]` were removed, and in 5.1 it gives a compilation error instead of ignoring it like 5.2 does.

* If none of the lines are removed, the function body is eqivalent to `return 7-2-5`
* If the first line is removed, `return 1`
* If the second, `return 7-5`
* If the third, `return 7-2-2`
* If the fourth, `return 7-2-1`
* If the fifth, `return 7-2`
> 3 votes

# Answer
## Ruby

I tried doing it with bitwise operations and then I realized there is a much simpler solution using lists! This challenge is best served by a programming language that automatically returns the last value it sees, such as Ruby.

```
def tellMe(x=[1,2,3,4,5])
    x.delete(1)
    x.delete(2)
    x.delete(3)
    x.delete(4);x[0]
    x.delete(5);x==[]?0:x[0]
end

```
> 2 votes

# Answer
Befunge doesn't have explicit functions, but here is what I'd call a function in Befunge:

```
v^    <
>v
1>v
 2>v
##3>5v
$0v4 >
>>>>>>^

```

The first and last lines are function start and function end. It does the closest thing to "return", that is, it pushes the correct value onto the stack.
> 2 votes

# Answer
# New Answer

I found another solution. That's so bad, I liked the math one so much. This solution uses recursion and global variables (yuck!) to tell if every line has been run or not. I wanted to do something different from the other solutions, so this isn't much elegant, but it works properly :)

### PHP

```
function LOL($a) {
    if (!$a) { LOL(true); if (!$GLOBALS['b']) return 2; if (!$GLOBALS['c']) return 3; if (!$GLOBALS['d']) return 4; if (!$GLOBALS['e']) return 5; return 0; }
    if ($a) $GLOBALS['b'] = true; else return 1;
    $GLOBALS['c'] = true;
    $GLOBALS['d'] = true;
    $GLOBALS['e'] = true;
}

```

I really enjoyed this challenge, thank you! :)

---

# Old Answer

I solved it using maths. If each variable is seen as an unknown, and we do one declaration per line, there are five unknowns and five lines of code: this leads us to the following 5x5 system:

```
b+c+d+e = 1;
a+c+d+e = 2;
a+b+d+e = 3;
a+b+c+e = 4;
a+b+c+d = 5;
//Solutions are displayed in the code below.

```

Once I found the values, I hardcoded them and added some basic stuff.

### PHP

```
function LOL(){
    $a = 2.75;
    $b = 1.75;
    $c = 0.75;
    $d = -0.25; if ($a+$b+$c+$d == 5) return $a+$b+$c+$d;
    $e = -1.25; return $a+$b+$c+$d+$e;
}

```

**Note:** The Old Answer won't work if left as-is.
> 2 votes

# Answer
# Bash, 131 chars

```
#!/bin/bash

# the function:
function f(){
  a=1;
  b=2;
  c=3;
  d=4;[ ! $1 ]&&f 1&&return 5||true
  [ $1 ]&&return 6;e=5;s=$((a+b+c+d+e));return $((15-$s))
}

# call it:
f
# report the result:
echo Removed line $?

```

It's all straightforward up to line 5. Then it needs to detect if the final line is gone. This takes advantage of permitted function parameters by calling itself recursively, once, to test its own success value when it's being told to fail on line 5, and if line 5 is removed, line 4 returns `5` instead.

(Note: it's down to a minimum of 131 characters if stripping out everything but the function, ditching whitespace, and changing /bin/bash to /bin/sh)
> 1 votes

# Answer
# beeswax, 86 bytes

Trying out my first invented esolang. After initial confusion I found that the solution is so simple.

```
_1 p
_^v>~2+p
   >   >~3+p
       >   >~4+X@7~8+~@$^^{;
           >    >~5+@7~8+~@${;

```

Explanation:

**beeswax** programs work on a 2D hexagonal grid. Programs are stored in a rectangular format.

```
    a — b — c — d
   / \ / \ / \ /
  e — f — g — h
 / \ / \ / \ /
i — j — k — l

```

is stored as

```
abcd
efgh
ijkl

```

The instructions for moving in certain directions are:

```
    b — d
   / \ / \                                  bd
  < —IP — >    or in compact form (β=IP):   <β>
   \ / \ /                                   pq
    p — q

```

Short explanation

`_1 p` Create an IP, add 1, then redirect IP to line 2

`_^v>~2+p` Create another IP, just in case line 1 is missing, slow down IP to make sure IP from line one is ahead, then add 2, then redirect to line 3

`> >~3+p` Add 3, then redirect to line 4

`> >~4+X@7~8+~@$^^{;` Add 4, then set 2nd lstack value to 15, then XOR lstack top and 2nd values, slow down IP (to make sure IP in line 5 is ahead, if line 5 exists) and output the result, then terminate the program.

`> >~5+@7~8+~@${;` Add 5, then do the same as in line 4, except the slow down.

Basically the program just calculates a sum xor 15

* Program intact: (1+2+3+4+5) xor 15 = 0
* Line 1 missing: (2+3+4+5) xor 15 = 1
* Line 2 missing: (1+3+4+5) xor 15 = 2
* Line 3 missing: (1+2+4+5) xor 15 = 3
* Line 4 missing: (1+2+3+5) xor 15 = 4
* Line 5 missing: (1+2+3+4) xor 15 = 5

The additional `>` in lines 3 to 5 just guarantee that if one of lines 2 to 4 are missing, the IP still gets redirected properly and doesn’t leave the program.

You can clone my beeswax interpreter, written in Julia, from **my GitHub repository**

The readme on GitHub is more up to date and better structured than the esolangs page.
> 1 votes

# Answer
## MuPAD, 57 chars

```
subs(()->
-d(1)
-d(2)
-d(3)
-d(4)
-d(5)
,d=Dom::IntegerMod(15))

```
> 0 votes

# Answer
Common LISP:

```
(defun which-line-is-removed (&aux (x 30))
  (decf x 2)
  (decf x 4)
  (decf x 8)
  (decf x 16) 5
  (if (zerop x) 0 (log x 2))
)

```

NB: Having ending parenthesis on it's own line is considered bad style, but since other languages has `end` and `}` I assume it is allowed.
> 0 votes

# Answer
# Javascript

```
function(){
/*aa*/if(arguments.callee.toString().indexOf("*"+"a".repeat(6)+"*")==-1)return 5;
/*aaa*/if(arguments.callee.toString().indexOf("*"+"a".repeat(5)+"*")==-1)return 4;
/*aaaa*/if(arguments.callee.toString().indexOf("*"+"a".repeat(3)+"*")==-1)return 2;
/*aaaaa*/if(arguments.callee.toString().indexOf("*"+"a".repeat(4)+"*")==-1)return 3;
/*aaaaaa*/return +!~arguments.callee.toString().indexOf("*"+"a".repeat(2)+"*");
};

```
> 0 votes

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


# Question
Title: Is it an integer, a string, or a decimal?
Your challenge is to determine whether the given input is an integer, a string, or a decimal.

# Rules

* A string is any input that is not an integer or a float
* An integer must contain only numeric characters and must not start with a zero
* A decimal is any input that contains the period (`.`) and the period is surrounded by numeric characters.

**Note:** .01 is **not** considered a valid decimal.

* The program should output a raw string either "string", "integer", or "decimal".
* You may assume only printable ASCII characters are used

Cases:

```
asdf -> string
asdf3.4 -> string
2 -> integer
2.0 -> decimal
02 -> string
40. -> string
. -> string
.01 -> string
0.0 -> decimal
.9.9.9 -> string
[empty space] -> string

```

EDIT: Fixed the typo. I meant .01 without the leading zero, not with. If that made it unclear, its fixed now!

**This is , so shortest answer wins.**

# Answer
# Pyth, 33 bytes (39 without packed string)

```
@_c."at%¸Ã`9hàãáÊ"7.x/`MsB+vz0z0

```

Some bytes are stripped due to Markdown. Official code and test suite.

Without packed string:

```
@_c"integerdecimalstring"7.x/`MsB+vz0z0

```

It passes all of above test cases. Basically, to check if a string is a integer or decimal, it checks whether the string can be evaluated as a python literal (`v`), and if so, if you can add 0 to it and covert it back to its string representation, and get the input string. If so, it's an integer or a decimal. If you can also cast it to an int and still get the original string back, it's an integer.
> 3 votes

# Answer
# Javascript, ~~112~~ ~~121~~ 87 bytes

*Thanks to @edc65 for saving 34 bytes by converting the original code (in the explanation) to ES6. I didn't change the explanation because it shows the logic better.*

```
b=a=>/^[1-9]\d*$/.test(a)?"integer":/^([1-9]\d+|\d)\.\d+$/.test(a)?"decimal":"string"

```

This basically converts the rules for an integer and decimal in the question into regex checks, and tests them against the given input. If the input doesn't match, then it must be a string. It passes all of the tests given in the question.

## Ungolfed + explanation

```
function b(a) {
    if(/^[1-9]\d*$/.test(a)) // regex check for the rules of an 'integer':
        return"integer";     // ^[1-9] - check to make sure the first digit
                             // \d* - check to make sure that it is followed by zero or more digits
                             // $ - ensures that the previous check continues to the end of the word
    if(/^([1-9]\d+|\d)\.\d+$/.test(a)) // regex check for the rules of a 'decimal', starting from the middle
        return"decimal";     // \. checks for a '.' in the word
                             // the ([1-9]\d+|\d) and \d+ check to make sure the '.' is surrounded by
                             // one or more numerical characters on each side.
                             // the ^,$ ensure that the match is for the whole word
return"string";              // none of the others match, so it must be a string.

```

}
> 2 votes

# Answer
# Java, 133 bytes

```
String t(String v){if(v.matches("[1-9]\\d*"))return "integer";if(v.matches("(0|[1-9]\\d+)\\.\\d+"))return "decimal";return "string";}

```
> 1 votes

# Answer
# Perl 5, 59 bytes

With the `-p` argument on the command line (which is calculated into the byte count):

```
chop;$_=!/\D|^0/?"integer":/^\d+\.\d+$/?"decimal":"string"

```
> 1 votes

# Answer
# JavaScript (ES6), 74 ~~75~~

**Edit** 1 byte saved thx Zequ

```
f=i=>(i=i.match(/^(0|[1-9]\d*)(\.\d+)?$/))?i[2]?'decimal':'integer':'string'

```

**Test**

```
f=i=>(i=i.match(/^(0|[1-9]\d*)(\.\d+)?$/))?i[2]?'decimal':'integer':'string'

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

// test cases from the question and some more
s=['asdf','asdf3.4','02','40.','.','.01','.9.9.9','','0.0.0','00.00','02.00']
i=['2', '11', '1000']
d=['2.0','0.0', '1.009', '911.1','123.4567890']

console.log('Strings:')
s.forEach(x=>console.log('<'+x+'> -> '+f(x)))
console.log('Integers:')
i.forEach(x=>console.log('<'+x+'> -> '+f(x)))
console.log('Decimals:')
d.forEach(x=>console.log('<'+x+'> -> '+f(x)))
```

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

# Answer
# Perl 6, 61 bytes

```
{<string integer decimal>[?/^[(\d+\.\d+)|<[1..9]>\d*]$/+?$0]} # 61

```

Usage:

```
say «asdf asdf3.4 2 2.0 02 40. . .01 0.0 .9.9.9 ''».map: {...}

```

```
(string string integer decimal string string string string decimal string string)

```
> 0 votes

# Answer
# Python 2, 148 bytes

```
def f(s):
 try:
  t=float(s);assert s[0]!='0'
  if `t+0`==s:return'decimal'
  if `int(t)`==s:return'integer'
  return'string'
 except:return'string'

assert f('asdf') == 'string'
assert f('asdf3.4') == 'string'
assert f('2') == 'integer'
assert f('2.0') == 'decimal'
assert f('.') == 'string'
assert f('.01') == 'string'
assert f('.9.9.9') == 'string'
assert f(' ') == 'string'
assert f('40.') == 'string'
assert f('02') == 'string'
assert f('0.0') == 'string'
assert f('00.00') == 'string'

```
> 0 votes

# Answer
## JavaScript ES6, ~~74~~ 70 bytes

```
w=>w.match(/^\d+\.\d+$/)?"decimal":w.match(/^\d+$/)?"integer":"string"

```
> 0 votes

---
Tags: code-golf, parsing
---


# Question
Title: Print the QWERTY keyboard using keys that are as close together as possible
Normally, challenges are scored in bytes, or sometimes Levenshtein distance, but for this one we're using keyboard distance -- the number of keys between the keys used to type the program (use the above keyboard as the definitive reference). For example, the distance between `A` and `F` is 3, because the path is `A`=\>`S`=\>`D`=\>`F`. The distance between `N` and `5` is 4, because no matter what path you take, it requires at least 4 steps. Your task is to output the following (not including trailing spaces), with as small a keyboard distance as possible:

```
Q W E R T Y U I O P
 A S D F G H J K L
  Z X C V B N M

```

## Wrapping:

To make your life easier, certain keys can wrap around the keyboard. `Left Shift` wraps to `Right Shift`, `Caps Lock` wraps to `Enter`, `Tab` wraps to `\` and `~` wraps to `Backspace`. For example, the distance between `Q` and `P` is 5, because `Q`=\>`Tab`=\>`\`=\>`]`=\>`[`=\>`P`.

**Note:** Wrapping only works horizontally -- you can not step from, say, `\` to `Caps Lock`

## Scoring:

**Score = Keyboard distance + byte count**

## Example Calculation:

`print(5);`

* `p`=\>`r` == 6
* `r`=\>`i` == 4
* `i`=\>`n` == 2
* `n`=\>`t` == 3
* `t`=\>`(` == 4
* `(`=\>`5` == 4
* `5`=\>`)` == 5
* `)`=\>`;` == 2

**Total:** 30 + 9 = **39**.

## Notes:

1. Lowercase and uppercase letters count as the same key. If a key has two symbols on it (like `7` and `&`), they also count as the same key, no need to include pushing shift.
2. Unfortunately, if your code requires symbols that are not on the keyboard you cannot use it.
3. On the keyboard image, the top row can be ignored. The only key you can use on the bottom row is `Space`
4. Keys must be inputted in order, you can't use the arrow keys to move the caret and then input a key.

## Score Calculator:

* **Updated on 12/27 to fix ```=\>`]` and related miscalculations. Check your scores again, and they will likely be smaller (hopefully not bigger!)**

Paste in your code here to calculate the score. Let me know if you ever get an error or it prints out the wrong number.

```
var keys = ["~1234567890-=←","\tqwertyuiop[]\\","↑asdfghjkl;\'\n","Lzxcvbnm,./R",
"AB      CDEF"];
var con =["`!@#$%^&*()_+{}|:\"<>?","~1234567890-=[]\\;\',./"];
function hexagon(k) {
  if(k === " ") return ["x","c","v","b","n","m",","];
  var p = pos(k);
  if(p === -1) return false;
  var row = p[0],col = p[1];
  var hexagon = [char(row,col-1,1),char(row-1,col),char(row-1,col+1),char(row,col+1,1),char(row+1,col),char(row+1,col-1)];
  return hexagon;
}

function char(r,c,wrap) {
  if(r < 0 || r >= keys.length) return "";
  if(r === keys.length-1 && 1 < c && c < 8) return " ";
  if(wrap) {
    if(c === -1) c = keys[r].length-1;
    if(c === keys[r].length) c = 0;
  }
  return keys[r].charAt(c);
}

function pos(c) {
    var row = -1, col = -1;
  for(var i = 0;i<keys.length;i++) {
    col = keys[i].indexOf(c)
    if( col != -1) { row = i; break;}
  }
  if(row === -1) return -1;
  return [row,col];
}

function dist(a,b,s,w) {
  if(typeof a === "object") {
    var list = [];
    for(var i = 0;i<a.length;i++) {
      list[i] = dist(a[i],b,s,w);
    }
    return list;
  }

 if(a==="") return Infinity;
  if(a===b) return 0;

  var p = pos(a);
  var q = pos(b);

  if(!w && a!==" ") {
    var chars = keys[p[0]].length;
    var opp = char(p[0],p[1] < chars/2 ? chars-1 : 0);
    return Math.min(dist(a,b,s,true),dist(a,opp,s,true)+dist(opp,b,s,true));
  }

   if(!s) { return Math.min(dist(a,b,true,w),dist(a," ",true,w)+dist(" ",b,true,w));}

   var h = hexagon(a);
  if(a === " ") return 1 + Math.min(...dist(h,b,true,w));
 if(p[0]<q[0]) {
  return 1 + Math.min(dist(h[4],b,s,w),dist(h[5],b,s,w));
  }
  else if(p[0] > q[0]) {
  return 1 + Math.min(dist(h[1],b,s,w),dist(h[2],b,s,w));
    }
   if(b===" ") return Math.min(Math.abs(p[1]-7),Math.abs(2 - p[1]));
    var d = Math.abs(p[1]-q[1]);
    return Math.min(d,keys[p[0]].length-d);

}

function getTotalDistance(str) {
 for(var i = 0;i<con[0].length;i++)
   str = str.replace(new RegExp("\\"+con[0].charAt(i),"g"),con[1].charAt(i));
  str = str.toLowerCase();
  var total = 0;
  for(var i = 0;i<str.length-1;i++) {
   total += dist(str[i],str[i+1]);
  }
  return total;
}
enter.onclick = function() {
 var a = getTotalDistance(program.value);
 var b = program.value.length;
 len.textContent = a;
 count.textContent = b;
 total.textContent = a+b;
};
```

```
<textarea rows=15 cols=40 id="program"></textarea>
<input type="submit" id="enter"/>

Key distance:

Byte count:

Total:

```

### Related:

# Answer
# Pyth, score ~~107~~ ~~106~~ 102

```
:jd"QWERTYUIOP
ASDFGHJKL
]XCVBNM""]"" Z

```

Try it online.
> 5 votes

# Answer
# Unary, score ~6.1\*10<sup>618</sup>

`6103247739090735580402225797524292167653462388595033897325606983093527722629493568418069722646005695215642120674994001348606253869287599178270707482456199630901069511698694317195626565008736452130034232375778047932461822258369348260249011643486476832847755830117284465136723525376668555270734061914837886192012601522703308221225195058283657800958507281265116257152529161080096092081620384043514820427911786442536988705847468796481108000358361636640985892696216392434604543586511103835032034494033598102606339253132146827455065586119645920456668064941286708686113567081095434338440184737976711767750474398662381256908308 zeros`

Not the most "creative" solution but it took my computer ~3 minutes to convert the base 2 representation of this to base 10

---

This *used to* have a **score of 0**, but the scoring rules changed.

Code Length: ~6.1\*10<sup>618</sup>

Key Distance: 0
> 34 votes

# Answer
# JavaScript (ES6), score 188

```
alert([...`QWERTYUIOP
ASDFGHJKL
`," Z",..."XCVBNM"].join` `)

```

Only just barely gets a better score than `alert`ing the output string but it's the best approach I could find... : /

Bytes: `60`

Key Distance: `128`
> 6 votes

# Answer
# Japt, score ~~123~~ ~~119~~ ~~118~~ ~~116~~ 106

~~42~~ ~~41~~ 40 bytes + ~~81~~ ~~78~~ ~~77~~ ~~75~~ 66 distance

```
"QWERTYUIOP
ASDFGHJKL
'ZXCVBNM"q qS r''"

```

(proper output in the "output" box)
> 6 votes

# Answer
# Bash + Sed, 151

```
sed 'sb *.b& bg'<<<'QWERTYUIOP
 ASDFGHJKL
  ZXCVBNM'

```
> 5 votes

# Answer
# Python, ~~157~~, ~~156~~, ~~211~~, 221 points

Key Distance: 157

Bytes: 64

Ergo, total score is 221.

```
l=' '.join('QWERTYUIOP\nASDFGHJKL\nZXCVBNM')
print l[:42],l[42:]

```

Prints the string but has to add an extra space. :( now longer.

Why @Pietu, why did you do this to me?
> 5 votes

# Answer
# JavaScript, score 156 ~~187~~

```
[...`QWERTYUIOP
ASDFGHJKL`].join` `+`
  Z X C V B N M`

```

Not bad for JavaScript

Try it online

---

With alert, **score 186**

```
alert([...`QWERTYUIOP
ASDFGHJKL`].join` `+`
  Z X C V B N M`)
```
> 5 votes

# Answer
# Bash + sed, score ~~202~~ 200

```
sed 's/\([^ ]\)/\1 /g'<<F
QWERTYUIOP
 ASDFGHJKL
  ZXCVBNM
F

```
> 4 votes

# Answer
# Jolf, 118 + 51 = 169

Try it here! (underscores in explanation used to denote a used space)

```
R m{"QWERTYUIOP'ASDFGHJKL'ZXCVBNM"#DN+*S' RH' }"\n"
 _m                                                 map
   {"QWERTYUIOP'ASDFGHJKL'ZXCVBNM"#                  that array
                                   DN         }      with this function
                                     +*S'_            that concats (index many) spaces
                                          RH'_         with the inner array joined by spaces
R                                                    and join that
                                                      "\n"  with newlines

```

# Jolf, update post-question, 76 + 21 = 97

Try it here! Again, I don't often update my code until relevant. Still fun.

```
R mpHDN+*S' RH' }"\n"
 _m                   map
   pH                 the keyboard array [["Q","W",...,"P"],["A",...,"L"],["Z",...,"M"]]
     DN         }      with this function
       +*S'_            that concats (index many) spaces
            RH'_         with the inner array joined by spaces
R                     and join that
                 "\n"  with newlines

```
> 4 votes

# Answer
# Python, score 185

```
print" ".join("QWERTYUIOP\nASDFGHJKL\n")+"  Z X C V B N M"

```
> 0 votes

---
Tags: code-challenge, restricted-source, keyboard
---


title: Parenthesize an expression

text:
# Question
Title: Parenthesize an expression
Recently I've been writing a new language, to avoid needing to handle *order of operations*, I simply parenthesize each expression properly to avoid this entirely.

Because parenthesis are at char-codes 40-41, your code will need to be as short as possible.

---

## Examples

```
1+2*3
(1+(2*3))

2*(3+4)
(2*(3+4))

2*3/4+3
(((2*3)/4)+3)

342*32/8
((342*32)/8)

```

## Rules

The only operations you'll need to handle are: `*` (multiplication), `/` (division), `+` (addition), and `-` (subtraction).

* The **order of operations** is:
    + Parenthesis
    + Multiplication, Division
    + Adition, Subtraction
* You should prefer to go left-right
* The input numbers will always be positive integers (see bonuses)

## Bonuses

**-20%** if you handle negation:

```
3+-5
(3+(-5))

```

**-5%** if you allow spaces to be placed inside the input:

```
3  + 4
(3+4)

```

**-10%** if you can handle decimals in the input:

```
1+.12
(1+.12)
1+0.21/3
(1+(0.21/3))

```

**500 bounty:** if you manage to write an answer in Unnamed/Blocks

# Answer
> 2 votes
# Python, 153 * 0.9 = 137.7 bytes

```
def p(e):
 for o in"+-*/":
    for i,c in enumerate(e):
        if(c==o)*(0==sum([(d=="(")-(d==")")for d in e[:i]])):return"("+p(e[:i])+o+p(e[i+1:])+")"
 return e

```

This program handles decimal input.

The second line begins with a space, the second begins with a tab, the third with two tabs and the third with a space. This saved one byte. Here's a hexdump (`xxd`p p):

```
0000000: 6465 6620 7028 6529 3a0a 2066 6f72 206f  def p(e):. for o
0000010: 2069 6e22 2b2d 2a2f 223a 0a09 666f 7220   in"+-*/":..for
0000020: 692c 6320 696e 2065 6e75 6d65 7261 7465  i,c in enumerate
0000030: 2865 293a 0a09 0969 6628 633d 3d6f 292a  (e):...if(c==o)*
0000040: 2830 3d3d 7375 6d28 5b28 643d 3d22 2822  (0==sum([(d=="("
0000050: 292d 2864 3d3d 2229 2229 666f 7220 6420  )-(d==")")for d
0000060: 696e 2065 5b3a 695d 5d29 293a 7265 7475  in e[:i]])):retu
0000070: 726e 2228 222b 7028 655b 3a69 5d29 2b6f  rn"("+p(e[:i])+o
0000080: 2b70 2865 5b69 2b31 3a5d 292b 2229 220a  +p(e[i+1:])+")".
0000090: 2072 6574 7572 6e20 650a                  return e.

```

Here's a program I used for testing: (Save the program above as `paren.py`)

```
import paren

cases = {
        "2+3*4": "(2+(3*4))",
        "(2+3)*4": "((2+3)*4)",
        "1+2+3+4": "(1+(2+(3+4)))",
        "3/2+5": "((3/2)+5)",
        "1+2-3": "(1+(2-3))",
        "2-1+2": "((2-1)+2)",
        "3+-5": "(3+(-5))",
        "1+.12": "(1+.12)",
        "1+0.21/3": "(1+(0.21/3))",
}

for num, case in enumerate(cases):
    print "\n\n\033[1m\033[38;5;14mCase #%d: %s" % (num + 1, case)
    result = paren.p(case)
    print "\033[38;5;4mParenthesize returned: %s" % (result)
    solution = cases[case]
    if result == solution:
        print "\033[38;5;76mCorrect!"
    else:
        print "\033[38;5;9mNot correct!"

```

Make sure that your terminal uses the `\033[38;5;<COL>m` escape code for colors.

# Answer
> 3 votes
# JavaScript (ES6) 179 (263 -20% -5% -10%)

```
(x,W=[],Q=['('],z=1,w=v='',h=p=>'*/+-))('.indexOf(p)|1,C=n=>{for(;h(q=Q.pop())<=h(n);)W[0]=`(${W[1]+q+W.shift()})`;z&&Q.push(q,n)})=>(x+')').replace(/[\d.]+|\S/g,t=>t>'('?t>')'?~h(t)?z?(w+='('+t,v+=')'):C(t,z=1):W=[w+t+v,...W,z=w=v='']:C(t,z=0):z=Q.push(t))&&W[0]

```

As the other two answers are currently both wrong, I'll post mine. It's a variation of the expression parser that I used here and here and somewhere else. Look there for more detailed algorithm explanations.

It's quite bulky but it should work.

**Test snippet**

```
f=(x,W=[],Q=['('],z=1,w=v='',h=p=>'*/+-))('.indexOf(p)|1,C=n=>{for(;h(q=Q.pop())<=h(n);)W[0]=`(${W[1]+q+W.shift()})`;z&&Q.push(q,n)})=>(x+')').replace(/[\d.]+|\S/g,t=>t>'('?t>')'?~h(t)?z?(w+='('+t,v+=')'):C(t,z=1):W=[w+t+v,...W,z=w=v='']:C(t,z=0):z=Q.push(t))&&W[0]

// More readable
x=(x,W=[],Q=['('],z=1,w=v='',
  h=p=>'*/+-))('.indexOf(p)|1,
  C=n=>{
    for(;h(q=Q.pop())<=h(n);)W[0]=`(${W[1]+q+W.shift()})`;
    z&&Q.push(q,n)
  }
)=>(
  (x+')')
  .replace(/[\d.]+|\S/g,t=>
       t>'('
       ?t>')'
       ?~h(t)
       ?z
       ?(w+='('+t,v+=')')
       :C(t,z=1)
       :W=[w+t+v,...W,z=w=v=''] // overfill W to save 2 chars ()
       :C(t,z=0)
       :z=Q.push(t)
  ),
  W[0]
)

console.log=(...x)=>O.textContent+=x.join` `+'\n'

// TEST
;[
  ['1+2*3','(1+(2*3))'],['2*(3+4)','(2*(3+4))'],['2*3/4+3','(((2*3)/4)+3)'],['342*32/8','((342*32)/8)'],
  ['3+-5','(3+(-5))'],['-3+-4*7','((-3)+((-4)*7))'], // bonus 20%
  ['3  + 4','(3+4)'], // bonus 5%
  ['1+.12','(1+.12)'],['1+0.21/3','(1+(0.21/3))'] // bonus 10%
].forEach(t=>{var k=t[1],i=t[0],r=f(i); console.log(i+' : '+r+(r==k? ' OK':' Fail expecting '+k))})
```

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

# Answer
> 1 votes
## Python, 241 * 0.8 * 0.95 * 0.9 = 164.84 characters

I'm using the ast (Abstract Syntax Trees) library, and a homebrew string replacement dict. The string replacement costs a lot, but the bonus helps in keeping the score somewhat low. Maybe (the string replacement part) can be golfed further.

Note that this solution adds an extra set of parenthesis around each number, but I think that's within the spirit of the question

```
import ast;def p(e):
 r,s={"Module([":"",")])":"","Expr(":"","BinOp":"","Num":"",", Add(), ":"+",", Sub(), ":"-",", Div(), ":"/",", Mult(), ":"*"},ast.dump(ast.parse(e),annotate_fields=False)
 for f,t in r.iteritems():s=s.replace(f,t)
 return s

```

Test suite:

```
cases = {
    "2+3*4",
    "(2+3)*4",
    "1+2+3+4",
    "3/2+5",
    "1+2-3",
    "2-1+2",
    "3+-5",
    "1+.12",
    "1+0.21/3"
}

for num,case in enumerate(cases):
    result = p(case)
    print "Case {}: {:<16} evaluates to: {}".format(num+1,case,result)

```

Output of the test suite:

```
Case 1: 3+-5             evaluates to: ((3)+(-5))
Case 2: 3/2+5            evaluates to: (((3)/(2))+(5))
Case 3: 2+3*4            evaluates to: ((2)+((3)*(4)))
Case 4: 1+2+3+4          evaluates to: ((((1)+(2))+(3))+(4))
Case 5: 1+0.21/3         evaluates to: ((1)+((0.21)/(3)))
Case 6: (2+3)*4          evaluates to: (((2)+(3))*(4))
Case 7: 2-1+2            evaluates to: (((2)-(1))+(2))
Case 8: 1+.12            evaluates to: ((1)+(0.12))
Case 9: 1+2-3            evaluates to: (((1)+(2))-(3))

```

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


# Question
Title: Electrostatic potential of a simple system
In physics, like electric charges repel, and unlike charges attract.

The potential energy between two unit charges separated by a distance `d` is `1/d` for like charges and `-1/d` for unlike charges. The potential energy of a system of charges is the sum of the potential energies between all pairs of charges.

## Challenge

Determine the potential energy of a system of unit charges represented by a string.

This is , so the shortest solution in bytes wins.

---

### Input

A nonempty multiline string, consisting of only `+`, `-`,  and newlines, with each line a constant width. The `+` and `-` represent charges of +1 and -1 respectively. For example, the following string:

```
    + -
 +

```

(considering the top-left to be the origin) represents a system with positive charges at (4,0) and (1,-1) and a negative charge at (6,0).

Alternatively, you may take input as a list of lines.

### Output

A signed real number representing the potential energy of the system of charges. Output should be correct to four significant figures or 10<sup>-4</sup>, whichever is looser.

### Test cases:

```
   -

```

Should output `0`. There are no pairs of charges to repel or attract, and the whitespace doesn't change anything.

```
+
  -

```

There are only two charges; they are 1 unit away in the vertical direction and 2 units away in the horizontal direction, so their distance is sqrt(5). Output should be -1/sqrt(5)=`-0.447213595`.

```
+       -
-       +

```

Should give `-2.001930531`.

```
 - -- -+ - - -+-++-+
 +-- + +-- + ++-++ -
---++-+-+- -+- - +-
-- - -++-+  --+  +
-   + --+ ++-+  +-
--  ++- + +  -+--+
+ +++-+--+ +--+++ +
-+- +-+-+-+  -+ +--+
- +-+- +      ---+
-     - ++ -+- --+--

```

Should give `-22.030557890`.

```
---+--- ++-+++- -+ +
-+ ---+++-+- +- +  +
---+-+ - ----  +-- -
 -   + +--+ -++- - -
--+ - --- - -+---+ -
+---+----++ -   +  +
-+ - ++-- ++-  -+++
 +----+-   ++-+-+  -
++- -+ -+---+  -- -+
+-+++ ++-+-+ -+- +-

```

Should give `26.231088767`.

# Answer
> 3 votes
# Pyth, 34 bytes

```
smc*FhMd.atMd.cs.e+RkCUBxL" +"b.z2

```

Demonstration

First, we convert each character to +1 for `+`, -1 for `-`, and 0 for . Then, each number is annotated with its position in the matrix. At this point, we have a matrix that looks like:

```
[[[-1, 0, 0], [-1, 1, 0], [-1, 2, 0], [1, 3, 0], [-1, 4, 0], [-1, 5, 0], [-1, 6, 0]],
 [[1, 0, 1], [1, 1, 1], [-1, 2, 1], [-1, 3, 1], [0, 4, 1], [1, 5, 1], [0, 6, 1]]]

```

The code that reaches this point is `.e+RkCUBxL" +"b.z`

Then, we flatten this matrix into a list and take all possible pairs, with `.cs ... 2`.

Then, he find the distance between the pair with `.atMd`, and the sign of the potential with `*FhMd`, divide, and sum.

# Answer
> 6 votes
# CJam, 51 chars

Counting all pairs, filtering `Inf/NaN` out and dividing by two:

```
q_N#:L;N-" +"f#ee2m*{z~:*\Lfmd2/:.-:mh/}%{zL<},:+2/

```

Alternatively, filtering coordinates first so we count each pair once and don't run into `Inf/NaN`:

```
q_N#:L;N-" +"f#ee2m*{0f=:<},{z~:*\Lfmd2/:.-:mh/}%:+

```

## Explanation (old)

```
q                        Get all input.
 _N#:L;                  Store the line width in L.
       N-                Flatten it into one long line.
         :i              Get all ASCII values.
           :(3f%:(       Map space to 0, + to 1, - to -1.
                  ee     Enumerate: list of [index, sign] pairs.
                    2m*  Get all possible pairs.

{                        }%     For each pair:
 e_~                              i1 s1 i2 s2
    @*                            i1 i2 s        (multiply signs)
      \aa@aa+                     s [[i2] [i1]]  (put indices in nested list)
             Lffmd                s [[x2 y2] [x1 y1]]  (divmod by L)
                  :.-             s [xD yD]      (point diff)
                     :mh          s d            (Euclidean dist.)
                        /         s/d            (divide)

{zL<},                   Filter out infinite results.
      :+2/               Sum all charges, and divide by two.
                           (We counted each pair twice.)

```

# Answer
> 4 votes
## Haskell, ~~149~~ 144 bytes

```
z=zip[0..]
g n|f<-[(x,y,c)|(y,r)<-z$lines n,(x,c)<-z r,c>' ']=sum[c%d/sqrt((x-i)^2+(y-j)^2)|a@(x,y,c)<-f,b@(i,j,d)<-f,a/=b]/2
c%d|c==d=1|1<2= -1

```

Usage example:

```
*Main> g " - -- -+ - - -+-++-+\n +-- + +-- + ++-++ -\n---++-+-+- -+- - +- \n-- - -++-+  --+  +  \n-   + --+ ++-+  +-  \n--  ++- + +  -+--+  \n+ +++-+--+ +--+++ + \n-+- +-+-+-+  -+ +--+\n- +-+- +      ---+  \n-     - ++ -+- --+--"
-22.030557889699853

```

`f` is a list of all triples `(x-coord, y-coord, unit charge)`. `g` calculates the potential energy for all combinations of two such triples which are not equal, sums them and divides the result by `2`.

# Answer
> 3 votes
## Lua, 293 255 246 228 Bytes

```
e=0l={}p={}i=1while l[i-1]~=""do l[i]=io.read()for k=1,#l[i]do c=l[i]:sub(k,k)if(c>" ")then for h,v in ipairs(p)do e=e+(v.s==c and 1 or-1)/math.sqrt((v.y-i)^2+(v.x-k)^2)end table.insert(p,{s=c,x=k,y=i})end end i=i+1 end print(e)

```

Ouch, 228 bytes...I can probably golf this significantly, but I'll post it here for now. Probably update it later tonight with a few more musings and (hopefully) some improvements to the length.

**Ungolfed**

```
e=0l={}p={}i=1
while l[i-1]~=""do
    l[i]=io.read()
    for k=1,#l[i]do
        c=l[i]:sub(k,k)
        if(c>" ")then
            for h,v in ipairs(p) do
                e=e+(v.s==c and 1 or-1)/math.sqrt((v.y-i)^2+(v.x-k)^2)
            end
            table.insert(p,{s=c,x=k,y=i})
        end
    end
    i=i+1
end

print(e)

```

*Update 255 Bytes:* Removed old bottom two for loops, processing is now done as strings are added to string array.

*Update 246 Bytes:* Replaced `c=="+"or"-"==c` with `c>" "` as per nimi's suggestion. Great idea, thanks!

*Update 228 Bytes:* If statement could be removed completely by inserting in table after the for loop, saving quite a few bytes.

# Answer
> 3 votes
# MATL, 39 ~~42~~ bytes

```
`jt]N$v'- +'FT#m2-I#fbbhtZPwt!**1w/XRss

```

Works in current release (5.1.0). The compiler runs on Matlab or Octave.

Each line is a separate input. End is signalled by inputting an empty line.

### Examples

```
>> matl
 > `jt]N$v'- +'FT#m2-I#fbbhtZPwt!**1w/XRss
 >
> +       -
> -       +
>
-2.001930530821583

>> matl
 > `jt]N$v'- +'FT#m2-I#fbbhtZPwt!**1w/XRss
 >
>  - -- -+ - - -+-++-+
>  +-- + +-- + ++-++ -
> ---++-+-+- -+- - +-
> -- - -++-+  --+  +
> -   + --+ ++-+  +-
> --  ++- + +  -+--+
> + +++-+--+ +--+++ +
> -+- +-+-+-+  -+ +--+
> - +-+- +      ---+
> -     - ++ -+- --+--
>
-22.03055788969994

```

### Explanation

```
`jt]           % keep inputting lines until an empty one is found
N$v            % concatenate all inputs vertically. This removes the last empty line
'- +'FT#m      % replace '-', ' ', '+'  by numbers 1, 2, 3
2-             % transform into -1, 0, 1 for '-', ' ', '+'
I#f            % find rows, columnss and values of nonzeros
bbh            % concatenate rows and columns into 2-col matrix or coordinates
tZP            % compute pair-wise distances for those coordinates
wt!*           % generate matrix of signs depending on signs of charges
*              % multiply distances by signs, element-wise
1w/            % invert element-wise
XR             % keep part over the diagonal
ss             % sum along colums, then rows
               % (output is implicitly printed)

```

# Answer
> 3 votes
# Ruby, 133

```
->n{t=i=j=0.0
c=[]
n.tr(' ',?,).bytes{|e|e-=44
z="#{j}+#{i}i".to_c
i+=1
e<-1?i=0*j+=1:(c.map{|d|t+=d[0]*e/(d[1]-z).abs};c<<[e,z])}
t}

```

Maintains an array of previous charges in the form of tuples `[charge, location(complex number)]` and compares each new charge with this list, before appending it to the list.

All spaces in the input are replaced with commas. This enables the following assignment by subtracting 44 from their ascii code:

```
symbol  charge (internal representation)
+        -1
,         0
-        +1

```

The fact that the program considers `+` to be -1 and `-` to be +1 makes no difference to the final result. The fact that the program goes to the effort of calculating the influence of the charges of 0 for the spaces makes no difference, apart from slowing it down a bit :-)

Ungolfed in test program

```
g=->n{
  t=i=j=0.0                           #t=total potential; i and j are coordinates of charge.
  c=[]                                #array to store tuples: charge + location (complex number).
  n.tr(' ',?,).bytes{|e|              #replace all spaces with commas, then iterate through characters.
    e-=44                             #subtract 44 from ascii code: + -> -1; comma -> 0; - -> 1
    z="#{j}+#{i}i".to_c               #position of current character as complex number
    i+=1                              #advance x coordinate to next character.
    e<-1?i=0*j+=1:                    #if current character is newline, set i to zero and advance j instead,
    (c.map{|d|t+=d[0]*e/(d[1]-z).abs};#else add up the contribution for interaction of the current charge with all previous charges,
    c<<[e,z])}                        #and append the current charge to the list of previous charges.
t}                                    #return t

p g[
'+       -
-       +'
]

p g[
' - -- -+ - - -+-++-+
 +-- + +-- + ++-++ -
---++-+-+- -+- - +-
-- - -++-+  --+  +
-   + --+ ++-+  +-
--  ++- + +  -+--+
+ +++-+--+ +--+++ +
-+- +-+-+-+  -+ +--+
- +-+- +      ---+
-     - ++ -+- --+--'
]

```

# Answer
> 2 votes
# Mathematica 223 bytes

Still golfing to do.

```
f[{{c1_,p1_},{c2_,p2_}}]:=N[(c1 c2)/EuclideanDistance[p1,p2],13];
h[charges_]:=Tr[f/@Subsets[DeleteCases[Flatten[Array[{r[[#,#2]],{#,#2}}&,Dimensions[r=Replace[Characters[charges],{"+"-> 1,"-"->-1," "->0},2]]],1],{0,_}],{2}]]

```

---

Last test case:

```
h[{" - -- -+ - - -+-++-+", " +-- + +-- + ++-++ -",
  "---++-+-+- -+- - +- ", "-- - -++-+  --+  +  ",
  "-   + --+ ++-+  +-  ", "--  ++- + +  -+--+  ",
  "+ +++-+--+ +--+++ + ", "-+- +-+-+-+  -+ +--+",
  "- +-+- +      ---+  ", "-     - ++ -+- --+--"}]

```

> -22.030557890

---
Tags: code-golf, string, physics
---


title: Unvisualize Parsons code

text:
# Question
Title: Unvisualize Parsons code
# Introduction

The **Parsons code** is just a simple way to describe *pitch variations* in a piece of music, whether a note is higher or lower than the previous one.

Even if you suck at remembering tunes, you can still pretty much remember if a note goes up or down, thus the *Parsons code* can help you to identify a music using a search engine.

---

### Description

Each variation is represented by a single character, which is one of the following:

* `R` if the note is **the same** than the previous one (stands for *"**R**epeat"*)
* `U` if the note is **higher** than the previous one (stands for *"**U**p"*)
* `D` if the note is **lower** than the previous one (stands for *"**D**own"*)

The initial note is written as `*`.

---

### Example

Here is an example of Parsons code (beginning of *"Ode to Joy"*):

```
*RUURDDDDRUURDR

```

You can actually *visualize* it, like this:

```
      *-*
     /   \
    *     *
   /       \
*-*         *         *-*
             \       /   \
              *     *     *-*
               \   /
                *-*

```

We'll call that a **contour** from now on.

The rules for drawing such countours are considered *self-explained* by the above example.

---

---

# Challenge

Now comes the real challenge.

### Write a program that, given a contour as input, outputs its corresponding Parsons code.

You are not asked to draw the contour, but the opposite actually.
From the contour, find the original Parsons code.

---

### Rules

* The usual rules for code golfing apply
* **The shortest program in number of bytes wins**
* The input is a contour, and the output shall be a valid Parsons code
* Details about extra whitespace for the input are irrelevant, do whatever works best for you
* You are not allowed to hardcode, one way or another, parts of the output and / or the program using extra whitespace because of the previous rule

### Notes

# Answer
> 4 votes
# Pyth - ~~28~~ ~~25~~ ~~27~~ 25 bytes

*2 byes saved thanks to @Jakube.*

```
s+\*@L"RDU"-VFtBxR\*%2C.z

```

Try it online here.

# Answer
> 24 votes
# CJam, 21 bytes

```
qN/:.e>(o2%:i"DRXU"f=

```

Fold the lines (`:`) by vectorizing (`.`) a character-wise maximum operation `e>`. Since there is only one non-space character in each column, this one will be the result, as space has a smaller ASCII code than all printable non-space characters.

Unshift and print the first asterisk `(o`, then map every other (`2%`) remaining char to `UDR` using modular indexing.

## Old solution (29 bytes)

```
'*qN/z2%'*f#0+2ew);::-"RDU"f=

```

`qN/` gets input lines. `z` transposes this character matrix. `2%` drops every odd row. `'*f#` finds the index of the asterisk in each row. `0+2ew);` gets all successive pairs of indices. `::-` computes their differences, and `"RDU"f=` maps them to letters (via modular indexing: `0 → R`, `2 → U`, `-2 ≡ 1 → D`). The leading `'*` prepends the asterisk.

**EDIT**: I changed `2ew` to `0+2ew);` to work around CJam not handling `ew` (successive slices) on lists that are too short. This makes the code work for the input string `*`.

Try it here, or watch it in action:

```

```

# Answer
> 4 votes
# Python 3, ~~129~~ ~~108~~ ~~98~~ 86 bytes

There are probably several ways to golf this, but I rather like that I got it all down to one line.

**Edit:** Now using `''.translate()`

**Edit:** With many thanks to wnnmaw.

**Edit:** I changed the input format to an array of strings instead of a newline-separated string to save bytes. Also, in the last edit, I mixed up `U` and `R`, so I fixed that.

```
lambda a:'*'+"".join(('UR'[j<'/']+'D')[j>'/']for l in zip(*a)for j in l if j in'-/\\')

```

Input must be an array of strings. For the example above, this looks something like:

```
["      *-*                    ","     /   \                   ","    *     *                  ","   /       \                 ","*-*         *         *-*    ","             \       /   \   ","              *     *     *-*","               \   /         ","                *-*          "]

```

Ungolfed:

```
def f(a):
    s = ''
    for c in zip(*a):           # transpose
        for d in c:             # for each letter in column c
            if e in "-/\\":     # if that letter is either -,/,\
                if e < '/':     # if < '/' (same as if == '-')
                    s += "R"
                elif e > '/':   # if > '/' (same as if == '\')
                    s += "D"
                else:           # if == '/'
                    s += "U"
        return "*" + s          # in the code we ''.join() it all together
                                # in this ungolfing, we add to an empty string

```

# Answer
> 3 votes
# Ruby, 87 bytes

Requires trailing spaces in the input so that all lines are the same length.

```
$><<?*+$<.readlines.map(&:chars).transpose.join.gsub(/./,{?-=>:R,?/=>:U,?\\=>:D}).strip

```

# Answer
> 3 votes
# Japt, 38 bytes ~~40 41 45 46 48~~

*Saved 2 bytes thanks to @ETHproductions*

```
'*+U·y £Yu ?"RUD"g1+(XrS c -47 g):P} q

```

If there was a trim command this would be only 38 bytes ;-; will add explanation when I'm done golfing. The `:P` is not the program trying to be funny, it's actually the program ignoring characters that aren't important.

Try it online

# Answer
> 3 votes
## Haskell, 89 bytes

```
import Data.List
m '/'="U"
m '-'="R"
m '\\'="D"
m _=""
('*':).(>>=(>>=m)).transpose.lines

```

Usage example:

```
*Main> ('*':).(>>=(>>=m)).transpose.lines $ "      *-*                    \n     /   \\                   \n    *     *                  \n   /       \\                 \n*-*         *         *-*    \n             \\       /   \\   \n              *     *     *-*\n               \\   /         \n                *-*          "
"*RUURDDDDRUURDR"

*Main> ('*':).(>>=(>>=m)).transpose.lines $ "*"
"*"

```

Transpose the input and replace the characters `/`/`-`/`\` with singleton strings `"U"`/`"R"`/`"D"`. All other chars are replaced by empty strings `""`, which later disappear by concatenating everything. Finally, prepend the asterisk `*`.

# Answer
> 2 votes
## Mathematica, 103 bytes

```
"*"<>(Differences@Position[Thread@Characters@StringSplit[#,"
"],"*"][[;;,2]]/.{-2->"U",0->"R",2->"D"})&

```

Quite short, considering that this is a string-processing challenge.

# Answer
> 2 votes
# JavaScript (ES6) 90

An anonymous function. It scans the input string char by char, taking into accout the position in the current line. Doing this, it builds an output array subsituting `U D R` for `/ \ -` at the right place

```
c=>[...c].map(c=>c>'*'?t[i++]=c>'/'?'D':c<'/'?'R':'U':c<' '?i=0:++i,t=['*'],i=0)&&t.join``

```

# Answer
> 2 votes
# Matlab, 62 bytes

```
r=@(s)[85-(s<14)*3-(s>59)*17,''];@(p)r(sum(p(:,2:2:end)-32))

```

This requires the input to be a rectangular (same number of characters in each row). E.g.

```
    ['      *-*                    ';    '     /   \                   ';    '    *     *                  ';    '   /       \                 ';    '*-*         *         *-*    ';    '             \       /   \   ';    '              *     *     *-*';    '               \   /         ';    '                *-*          '];

```

### Explanation

```
sum(p(:,2:2:end)-32)        % exctract every second column, substract 32 (spaces->zeros)
                            % and sum column wise (results in a vector of 3 different values)
[85-(s<14)*3-(s>59)*17,'']  % map each of the values to the corresponding value of the letter and convert back to characters

```

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


title: I-Ching pair binary computer

text:
# Question
Title: I-Ching pair binary computer
### Introduction

I Ching is an ancient divination text and the oldest of the Chinese classics. It uses a type of divination called cleromancy, which produces apparently random numbers.

The basic unit of the Zhou yi is the hexagram (卦 guà), a figure composed of six stacked horizontal lines (爻 yáo). Each line is either broken or unbroken. The received text of the Zhou yi contains all 64 possible hexagrams

The King Wen sequence present the 64 hexagrams, grouped into 32 pairs. For 28 of the pairs, the second hexagram is created by turning the first upside down (i.e. 180° rotation). The exception to this rule is for symmetrical hexagrams that are the same after rotation. Partners for these are given by inverting each line: solid becomes broken and broken becomes solid.

> ```
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>     1        2        3        4            5        6        7        8
>
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>     9       10       11       12           13       14       15       16
>
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>    17       18       19       20           21       22       23       24
>
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>    25       26       27       28           29       30       31       32
>
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>    33       34       35       36           37       38       39       40
>
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>    41       42       43       44           45       46       47       48
>
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>    49       50       51       52           53       54       55       56
>
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄      ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
>  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
>    57       58       59       60           61       62       63       64
>
> ```

### Request

The goal of this is to create a little tool that compute pair for a given hexagram value.

* For translating this into binary, I use: `broken line = 0, unbroken line = 1`, so *`hexagram Number 1`* has *`binary value 63`*.
* The tool take exactly one argument, a number between 1 to 64, as hexagram pair request and produce two exagram containing requested number and his *oposite* (explanation: if arg is odd, the output must contain hexagram from *arg* and *arg + 1*, but if arg is even, the output must contain hexagram from *arg - 1* and *arg*).
* The tool have to *rotate* by 180° requested hexagram while **not symetric**, **or** invert them when **symetric**.
* No map are authorized except this one, wich could be stored in any form you'll find usefull

```
 {  1:63,    3:34,    5:58,    7:16,    9:59,   11:56,   13:47,   15: 8,
   17:38,   19:48,   21:37,   23: 1,   25:39,   27:33,   29:18,   31:14,
   33:15,   35: 5,   37:43,   39:10,   41:49,   43:62,   45: 6,   47:22,
   49:46,   51:36,   53:11,   55:44,   57:27,   59:19,   61:51,   63:42 }

```

This map hold *binary* value of each 1st exagram from pairs. So for each pair, 1st has to be taken from this map, but second have to be computed conforming to previous rule.
* Ouput must contain two hexagram and his numbers. Sample:

```
iChingHexaPair 1
 ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
 ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
 ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
 ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
 ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
 ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
    1        2

iChingHexaPair 14
 ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄
 ▄▄▄▄▄▄▄  ▄▄▄ ▄▄▄
 ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄
 ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄
 ▄▄▄ ▄▄▄  ▄▄▄▄▄▄▄
 ▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄
   13       14

```
* Standard loophole applies
* Please avoid non-free language or post output for full test cases.

This is a , so the shortest answer in **characters** wins.

### Shortest by language

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = document.referrer.split("/")[4]; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 0; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
> 5 votes
# Python 2, ~~65~~ 61

Generates unicode I-Ching hexagram pairs

```
def t(a):
 b=a+a%2
 for c in b-1,b:
  print unichr(19903+c),c

```

(saved 4 thanks to @Sherlock9)

Example input and output:

```
>>> t(1)
䷀ 1
䷁ 2
>>> t(14)
䷌ 13
䷍ 14

```

# Answer
> 3 votes
# Python 2, ~~252~~ ~~245~~ 244

Now including binary computation (saving 8 chars thanks to @Sherlock9):

```
d='?":\x10;8/\x08&0%\x01\'!\x12\x0e\x0f\x05+\n1>\x06\x16.$\x0b,\x1b\x133*'
k=lambda l:'\n'.join("{:06b}".format(l)).replace('1',u'▄▄▄▄▄▄▄').replace('0',u'▄▄▄ ▄▄▄')
def t(a):
 j=a+a%2-1;m=ord(d[j/2]);b=k(m);r=b[::-1];print b,j,'\n\n',r if r!=b else k(63-m),j+1

```

Example input and output:

```
>>> t(1)
▄▄▄▄▄▄▄
▄▄▄▄▄▄▄
▄▄▄▄▄▄▄
▄▄▄▄▄▄▄
▄▄▄▄▄▄▄
▄▄▄▄▄▄▄ 1

▄▄▄ ▄▄▄
▄▄▄ ▄▄▄
▄▄▄ ▄▄▄
▄▄▄ ▄▄▄
▄▄▄ ▄▄▄
▄▄▄ ▄▄▄ 2
>>> t(3)
▄▄▄▄▄▄▄
▄▄▄ ▄▄▄
▄▄▄ ▄▄▄
▄▄▄ ▄▄▄
▄▄▄▄▄▄▄
▄▄▄ ▄▄▄ 3

▄▄▄ ▄▄▄
▄▄▄▄▄▄▄
▄▄▄ ▄▄▄
▄▄▄ ▄▄▄
▄▄▄ ▄▄▄
▄▄▄▄▄▄▄ 4

```

# Answer
> 2 votes
# Pure bash 252

```
u=(▅▅▅{' ',▅}▅▅▅);m=_yWgXUL8CMB1Dxief5HaN@6mKAbIrjPG;s=$[($1-1)/2];r=$[64#${m:s:1}];for i in {0..5};do echo ${u[(r>>i)&1]} ${u[((r>>5)%2==r%2)&((r>>4)%2==(r>>1)%2)&((r>>3)%2==(r>>2)%2)?1^(r>>i)&1:(r>>(5-i))&1]};done;echo $[s*2+1] $[s*2+2]

```

with 2 more linebreak:

```
u=(▅▅▅{' ',▅}▅▅▅);m=_yWgXUL8CMB1Dxief5HaN@6mKAbIrjPG;s=$[($1-1)/2];r=$[64#${m:s
:1}];for i in {0..5};do echo ${u[(r>>i)&1]} ${u[((r>>5)%2==r%2)&((r>>4)%2==(r>>
1)%2)&((r>>3)%2==(r>>2)%2)?1^(r>>i)&1:(r>>(5-i))&1]};done;echo $[s*2+1] $[s*2+2]

```

Tests:

```
for k in 1 15 28 34;do set -- $k;echo request: $k;
u=(▅▅▅{' ',▅}▅▅▅);m=_yWgXUL8CMB1Dxief5HaN@6mKAbIrjPG;s=$[($1-1)/2];r=$[64#${m:s
:1}];for i in {0..5};do echo ${u[(r>>i)&1]} ${u[((r>>5)%2==r%2)&((r>>4)%2==(r>>
1)%2)&((r>>3)%2==(r>>2)%2)?1^(r>>i)&1:(r>>(5-i))&1]};done;echo $[s*2+1] $[s*2+2]
done;echo $[s*2+1] $[s*2+2]; done
request: 1
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
1 2
request: 15
▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅
▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅
▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅
▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅
15 16
request: 28
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅
▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅
▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅
▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
27 28
request: 34
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅
▅▅▅▅▅▅▅ ▅▅▅▅▅▅▅
▅▅▅▅▅▅▅ ▅▅▅▅▅▅▅
▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅
▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅
33 34

```

---
Tags: code-golf, ascii-art, binary, unicode
---


title: Boxed character regions

text:
# Question
Title: Boxed character regions
Given an input string, determine the number of regions that a page will be split into.

Consider the letter `P`. It has one enclosed region within the letter. Assume that each letter splits the page by one or more regions (i.e. a box is drawn around the character).

## Input

A string of 0 or more characters. You may assume that the string contains only characters from the following sets:

* +0 regions: Spaces , tabs `\t`, and new lines `\n`
* +1 region: `CEFGHIJKLMNSTUVWXYZcfhijklmnrstuvwxyz12357~!^*()-_=+[]{}\'|:;",.?/<>`
* +2 regions:`ADOPQRabdeopq469@#`
* +3 regions: `Bg08$%&`

You may take the input as a function argument, standard input, command-line argument, whatever works best for your language.

## Output

An integer representing the number of regions split by the given input. Output can be a return value or standard output (but not stderr).

This is , so shortest solution in bytes win.

## Test cases

* (empty string or only whitespace) === 1
* `-1` === 3
* `100%` === 11
* `Hello world!` === 16
* `May the force be with you` === 28
* `do {$busTickets-=2;} while ($transit != false)` === 54
* `return @$_GET['foo'] ?? $$var % $var || $g8 << ; //# Syntax error` === 80

Feel free to use the demo in my JavaScript answer (with a compatible browser of course) to run test cases.

## Visual representation

Note: The visual representation for the characters `g` and `0` (zero) may not be entirely correct depending on the monospaced font that your computer has installed.

For the purposes of this challenge, assume that the bottom of the `g` has a closed loop and the `0` has a slash through it.

```
(function() {
  'use strict';
  [
    'CEFGHIJKLMNSTUVWXYZcfhijklmnrstuvwxyz12357~!^*()-_=+[]{}\\\'|:;"<,>.?/`',
    'ADOPQRabdeopq469@#',
    'Bg08$%&'
  ].forEach(function(set, i) {
    set.split('').sort().forEach(function(letter) {
      var p = document.querySelectorAll('section[data-letter-regions="' + (i + 1) + '"]')[0];
      console.log(p)
      var el = document.createElement('span');
      el.setAttribute('class', 'letter');
      el.textContent = letter;
      p.appendChild(el);
    });
  });

}());
```

```
h1 {
  font-family: sans-serif;
}
section + section {
  border-top: medium solid purple;
}
.letter {
  font-family: Consolas, 'Droid Sans Mono', monospace;
  font-size: 3em;
  line-height: 1;
  padding: 3px;
  margin: 3px;
  display: inline-block;
  border: thin solid darkgray;
}
```

```
<section data-letter-regions=1>
  <h1>1 region</h1>
</section>
<section data-letter-regions=2>
  <h1>2 regions</h1>
</section>
<section data-letter-regions=3>
  <h1>3 regions</h1>
</section>
```

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

```
f=x=>[...x].reduce((p,z)=>p+!!z.trim()+2*/[Bg08$%&]/.test(z)+/[ADOPQRabdeopq469@#]/.test(z),1)

```

### Demo

As the code is in ES6, the demo only works in ES6-compatible browsers. At time of writing, this includes Firefox, Edge, and Chrome/Opera with experimental JavaScript features enabled.

```
f = x => [...x].reduce((p, z) => p + !!z.trim() + 2 * /[Bg08$%&]/.test(z) + /[ADOPQRabdeopq469@#]/.test(z), 1)

// Snippet stuff
var v = function() {document.getElementById('Z').textContent = f(this.value)};
document.getElementById('I').addEventListener('keyup', v, false);
document.getElementById('I').addEventListener('change', v, false);
```

```
textarea {width: 100%}
```

```
<p><label>Input: <textarea id=I></textarea></label></p>

<p>Output: <output id=Z>1</output></p>
```

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


title: Return prime factorization of a number

text:
# Question
Title: Return prime factorization of a number
Yes, this is old and probably very simple, but I really want to be mindblown by things that I thought were obvious, so here's the **challenge**:

You're given a positive integer as the input and you need to output the **exponents** of all of the prime factors **up to the highest factor** in base 36 ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c ... z ). If there are some primes in between that are no factors, they have exponent 0. The output must be ordered can be either an array or a string separated by `\n`,  (space) or just outputs from different calls. The program should calculate correctly the output for exponents bigger than 36, but it's not required

Say you're given `42` as the input, its prime factorization is `2*3*7`, all of which have `1` as the exponent, but there is also `5` with an exponent of `0`, so your output would be `[ 1, 1, 0, 1 ]` because `2` is the first prime and has an exponent of `1`, `3` is the second and has an exponent of `1`, `5` is the third and has an exponent of `0` and so on. Here are the correct input/outputs for the first 30 numbers

```
2   1
3   0 1
4   2
5   0 0 1
6   1 1
7   0 0 0 1
8   3
9   0 2
10  1 0 1
11  0 0 0 0 1
12  2 1
13  0 0 0 0 0 1
14  1 0 0 1
15  0 1 1
16  4
17  0 0 0 0 0 0 1
18  1 2
19  0 0 0 0 0 0 0 1
20  2 0 1
21  0 1 0 1
22  1 0 0 0 1
23  0 0 0 0 0 0 0 0 1
24  3 1
25  0 0 2
26  1 0 0 0 0 1
27  0 3
28  2 0 0 1
29  0 0 0 0 0 0 0 0 0 1
30  1 1 1

```

and you can find a working expanded version of this on codepen

The solution with the lowest number of bytes wins. Feel free to send in languages who have built-in prime factorization functions, but I won't accept them as answers for pretty obvious reasons. If you send in a solution that doesn't use such functions I'll consider it. It's kind of a grey area, but we'll figure it out.

### Edit:

If it's unclear what do I mean by "base", consider the number `3072`. Its prime factors are `2` and `3`. `2` has an exponent of `10`, so in base 36 that's `a`. That means that the output would look like this:

```
a 1

```

or the number `732421875000` whose factorization is `2^3 * 3^1 * 5^15`, whose output would be

```
3 1 f

```

# Answer
# Octave, 51 bytes

```
@(n)dec2base(histc(factor(n),unique(factor(n))),36)

```

This defines an anonymous function that takes a number and returns a char array. Explanation to come.
> 2 votes

# Answer
# Pyth, 15 bytes

```
VheSPQIP_NC/PQN

```

Try it here

Outputs in base 256.

(Base36 version, 33 bytes)

```
VheSPQIP_NjjkmC++48d*>hdT7j/PQN36

```

Try it here

(Base 10 version, 14 bytes)

```
VheSPQIP_N/PQN

```

Try it here

All versions are separated by newlines. There is some unclearness over whether not base 36 outputs are allowed so I included many versions. Uses factorisation functions and is\_prime functions.
> 1 votes

# Answer
## Mathematica, 80 bytes

```
#~IntegerExponent~Prime@Range@PrimePi@FactorInteger[#][[-1,1]]~IntegerString~36&

```

I tried. Without factorization:

## Mathematica, 90 bytes

```
#~IntegerExponent~Prime@Range@PrimePi@Select[Divisors@#,PrimeQ][[-1,1]]~IntegerString~36&

```
> 0 votes

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