title: Match the Stack Exchange URLs

text:
# Question
Title: Match the Stack Exchange URLs
## Prologue

After installing an anti-XSS browser extension, Stack Snippets suddenly stopped working all across the Stack Exchange network. I could no longer learn from Stack Overflow, see working demos on User Experience and, worst of all, could not test JavaScript answers on Programming Puzzles and Code Golf! Desperately I searched for a remedy, and found a small input box in the settings, in which could place a single regex. I couldn't fit all of the Stack Exchange sites in this one, small box, so I asked for help. This is that question.

## Task

Your task is to create a regular expression that matches all of the Stack Exchange website URLs, without matching any domains not owned by Stack Overflow Inc..

Your regular expression must match all URLs with the following parts:

* `protocol`: this will either be `http://` or `https://`.
* `domain`: this will be an item from this list:

```
stackoverflow.com
www.stackoverflow.com
facebook.stackoverflow.com
serverfault.com
superuser.com
meta.stackexchange.com
webapps.stackexchange.com
nothingtoinstall.com
meta.webapps.stackexchange.com
meta.nothingtoinstall.com
gaming.stackexchange.com
arqade.com
thearqade.com
meta.gaming.stackexchange.com
meta.arqade.com
meta.thearqade.com
webmasters.stackexchange.com
webmaster.stackexchange.com
meta.webmasters.stackexchange.com
meta.webmaster.stackexchange.com
cooking.stackexchange.com
seasonedadvice.com
meta.cooking.stackexchange.com
meta.seasonedadvice.com
gamedev.stackexchange.com
meta.gamedev.stackexchange.com
photo.stackexchange.com
photography.stackexchange.com
photos.stackexchange.com
meta.photo.stackexchange.com
meta.photography.stackexchange.com
meta.photos.stackexchange.com
stats.stackexchange.com
statistics.stackexchange.com
crossvalidated.com
meta.stats.stackexchange.com
meta.statistics.stackexchange.com
math.stackexchange.com
maths.stackexchange.com
mathematics.stackexchange.com
meta.math.stackexchange.com
diy.stackexchange.com
meta.diy.stackexchange.com
meta.superuser.com
meta.serverfault.com
gis.stackexchange.com
meta.gis.stackexchange.com
tex.stackexchange.com
meta.tex.stackexchange.com
askubuntu.com
ubuntu.stackexchange.com
meta.askubuntu.com
meta.ubuntu.stackexchange.com
money.stackexchange.com
basicallymoney.com
www.basicallymoney.com
meta.money.stackexchange.com
english.stackexchange.com
elu.stackexchange.com
meta.english.stackexchange.com
stackapps.com
ux.stackexchange.com
ui.stackexchange.com
meta.ux.stackexchange.com
meta.ui.stackexchange.com
unix.stackexchange.com
linux.stackexchange.com
meta.unix.stackexchange.com
meta.linux.stackexchange.com
wordpress.stackexchange.com
meta.wordpress.stackexchange.com
cstheory.stackexchange.com
meta.cstheory.stackexchange.com
apple.stackexchange.com
askdifferent.com
meta.apple.stackexchange.com
rpg.stackexchange.com
meta.rpg.stackexchange.com
bicycles.stackexchange.com
bicycle.stackexchange.com
cycling.stackexchange.com
bikes.stackexchange.com
meta.bicycles.stackexchange.com
meta.bicycle.stackexchange.com
programmers.stackexchange.com
programmer.stackexchange.com
meta.programmers.stackexchange.com
electronics.stackexchange.com
chiphacker.com
www.chiphacker.com
meta.electronics.stackexchange.com
android.stackexchange.com
meta.android.stackexchange.com
boardgames.stackexchange.com
boardgame.stackexchange.com
meta.boardgames.stackexchange.com
physics.stackexchange.com
meta.physics.stackexchange.com
homebrew.stackexchange.com
homebrewing.stackexchange.com
brewadvice.com
meta.homebrew.stackexchange.com
meta.homebrewing.stackexchange.com
security.stackexchange.com
itsecurity.stackexchange.com
meta.security.stackexchange.com
meta.itsecurity.stackexchange.com
writers.stackexchange.com
writer.stackexchange.com
writing.stackexchange.com
meta.writers.stackexchange.com
video.stackexchange.com
avp.stackexchange.com
meta.video.stackexchange.com
meta.avp.stackexchange.com
graphicdesign.stackexchange.com
graphicsdesign.stackexchange.com
graphicdesigns.stackexchange.com
meta.graphicdesign.stackexchange.com
dba.stackexchange.com
meta.dba.stackexchange.com
scifi.stackexchange.com
sciencefiction.stackexchange.com
fantasy.stackexchange.com
meta.scifi.stackexchange.com
codereview.stackexchange.com
meta.codereview.stackexchange.com
codegolf.stackexchange.com
meta.codegolf.stackexchange.com
quant.stackexchange.com
meta.quant.stackexchange.com
pm.stackexchange.com
meta.pm.stackexchange.com
skeptics.stackexchange.com
skeptic.stackexchange.com
skepticexchange.com
meta.skeptics.stackexchange.com
fitness.stackexchange.com
meta.fitness.stackexchange.com
drupal.stackexchange.com
meta.drupal.stackexchange.com
mechanics.stackexchange.com
garage.stackexchange.com
meta.mechanics.stackexchange.com
meta.garage.stackexchange.com
parenting.stackexchange.com
meta.parenting.stackexchange.com
sharepoint.stackexchange.com
sharepointoverflow.com
www.sharepointoverflow.com
meta.sharepoint.stackexchange.com
music.stackexchange.com
guitars.stackexchange.com
guitar.stackexchange.com
meta.music.stackexchange.com
sqa.stackexchange.com
meta.sqa.stackexchange.com
judaism.stackexchange.com
mi.yodeya.com
yodeya.com
yodeya.stackexchange.com
miyodeya.com
meta.judaism.stackexchange.com
german.stackexchange.com
deutsch.stackexchange.com
meta.german.stackexchange.com
japanese.stackexchange.com
meta.japanese.stackexchange.com
philosophy.stackexchange.com
meta.philosophy.stackexchange.com
gardening.stackexchange.com
landscaping.stackexchange.com
meta.gardening.stackexchange.com
travel.stackexchange.com
meta.travel.stackexchange.com
productivity.stackexchange.com
meta.productivity.stackexchange.com
crypto.stackexchange.com
cryptography.stackexchange.com
meta.crypto.stackexchange.com
meta.cryptography.stackexchange.com
dsp.stackexchange.com
signals.stackexchange.com
meta.dsp.stackexchange.com
french.stackexchange.com
meta.french.stackexchange.com
christianity.stackexchange.com
meta.christianity.stackexchange.com
bitcoin.stackexchange.com
meta.bitcoin.stackexchange.com
linguistics.stackexchange.com
linguist.stackexchange.com
meta.linguistics.stackexchange.com
hermeneutics.stackexchange.com
meta.hermeneutics.stackexchange.com
history.stackexchange.com
meta.history.stackexchange.com
bricks.stackexchange.com
meta.bricks.stackexchange.com
spanish.stackexchange.com
espanol.stackexchange.com
meta.spanish.stackexchange.com
scicomp.stackexchange.com
meta.scicomp.stackexchange.com
movies.stackexchange.com
meta.movies.stackexchange.com
chinese.stackexchange.com
meta.chinese.stackexchange.com
biology.stackexchange.com
meta.biology.stackexchange.com
poker.stackexchange.com
meta.poker.stackexchange.com
mathematica.stackexchange.com
meta.mathematica.stackexchange.com
cogsci.stackexchange.com
meta.cogsci.stackexchange.com
outdoors.stackexchange.com
meta.outdoors.stackexchange.com
martialarts.stackexchange.com
meta.martialarts.stackexchange.com
sports.stackexchange.com
meta.sports.stackexchange.com
academia.stackexchange.com
academics.stackexchange.com
meta.academia.stackexchange.com
cs.stackexchange.com
computerscience.stackexchange.com
meta.cs.stackexchange.com
workplace.stackexchange.com
meta.workplace.stackexchange.com
windowsphone.stackexchange.com
meta.windowsphone.stackexchange.com
chemistry.stackexchange.com
meta.chemistry.stackexchange.com
chess.stackexchange.com
meta.chess.stackexchange.com
raspberrypi.stackexchange.com
meta.raspberrypi.stackexchange.com
russian.stackexchange.com
meta.russian.stackexchange.com
islam.stackexchange.com
meta.islam.stackexchange.com
salesforce.stackexchange.com
meta.salesforce.stackexchange.com
patents.stackexchange.com
askpatents.com
askpatents.stackexchange.com
meta.patents.stackexchange.com
meta.askpatents.com
meta.askpatents.stackexchange.com
genealogy.stackexchange.com
meta.genealogy.stackexchange.com
robotics.stackexchange.com
meta.robotics.stackexchange.com
expressionengine.stackexchange.com
meta.expressionengine.stackexchange.com
politics.stackexchange.com
meta.politics.stackexchange.com
anime.stackexchange.com
meta.anime.stackexchange.com
magento.stackexchange.com
meta.magento.stackexchange.com
ell.stackexchange.com
meta.ell.stackexchange.com
sustainability.stackexchange.com
meta.sustainability.stackexchange.com
tridion.stackexchange.com
meta.tridion.stackexchange.com
reverseengineering.stackexchange.com
meta.reverseengineering.stackexchange.com
networkengineering.stackexchange.com
meta.networkengineering.stackexchange.com
opendata.stackexchange.com
meta.opendata.stackexchange.com
freelancing.stackexchange.com
meta.freelancing.stackexchange.com
blender.stackexchange.com
meta.blender.stackexchange.com
mathoverflow.net
mathoverflow.stackexchange.com
mathoverflow.com
meta.mathoverflow.net
space.stackexchange.com
thefinalfrontier.stackexchange.com
meta.space.stackexchange.com
sound.stackexchange.com
socialsounddesign.com
sounddesign.stackexchange.com
meta.sound.stackexchange.com
astronomy.stackexchange.com
meta.astronomy.stackexchange.com
tor.stackexchange.com
meta.tor.stackexchange.com
pets.stackexchange.com
meta.pets.stackexchange.com
ham.stackexchange.com
meta.ham.stackexchange.com
italian.stackexchange.com
meta.italian.stackexchange.com
pt.stackoverflow.com
br.stackoverflow.com
stackoverflow.com.br
meta.pt.stackoverflow.com
meta.br.stackoverflow.com
aviation.stackexchange.com
meta.aviation.stackexchange.com
ebooks.stackexchange.com
meta.ebooks.stackexchange.com
alcohol.stackexchange.com
beer.stackexchange.com
dranks.stackexchange.com
meta.alcohol.stackexchange.com
meta.beer.stackexchange.com
softwarerecs.stackexchange.com
meta.softwarerecs.stackexchange.com
arduino.stackexchange.com
meta.arduino.stackexchange.com
cs50.stackexchange.com
meta.cs50.stackexchange.com
expatriates.stackexchange.com
expats.stackexchange.com
meta.expatriates.stackexchange.com
matheducators.stackexchange.com
meta.matheducators.stackexchange.com
meta.stackoverflow.com
earthscience.stackexchange.com
meta.earthscience.stackexchange.com
joomla.stackexchange.com
meta.joomla.stackexchange.com
datascience.stackexchange.com
meta.datascience.stackexchange.com
puzzling.stackexchange.com
meta.puzzling.stackexchange.com
craftcms.stackexchange.com
meta.craftcms.stackexchange.com
buddhism.stackexchange.com
meta.buddhism.stackexchange.com
hinduism.stackexchange.com
meta.hinduism.stackexchange.com
communitybuilding.stackexchange.com
moderator.stackexchange.com
moderators.stackexchange.com
meta.communitybuilding.stackexchange.com
meta.moderators.stackexchange.com
startups.stackexchange.com
meta.startups.stackexchange.com
worldbuilding.stackexchange.com
meta.worldbuilding.stackexchange.com
ja.stackoverflow.com
jp.stackoverflow.com
meta.ja.stackoverflow.com
emacs.stackexchange.com
meta.emacs.stackexchange.com
hsm.stackexchange.com
meta.hsm.stackexchange.com
economics.stackexchange.com
meta.economics.stackexchange.com
lifehacks.stackexchange.com
meta.lifehacks.stackexchange.com
engineering.stackexchange.com
meta.engineering.stackexchange.com
coffee.stackexchange.com
meta.coffee.stackexchange.com
vi.stackexchange.com
vim.stackexchange.com
meta.vi.stackexchange.com
musicfans.stackexchange.com
meta.musicfans.stackexchange.com
woodworking.stackexchange.com
meta.woodworking.stackexchange.com
civicrm.stackexchange.com
meta.civicrm.stackexchange.com
health.stackexchange.com
meta.health.stackexchange.com
ru.stackoverflow.com
hashcode.ru
stackoverflow.ru
meta.ru.stackoverflow.com
meta.hashcode.ru
rus.stackexchange.com
russ.hashcode.ru
russ.stackexchange.com
meta.rus.stackexchange.com
mythology.stackexchange.com
meta.mythology.stackexchange.com
law.stackexchange.com
meta.law.stackexchange.com
opensource.stackexchange.com
meta.opensource.stackexchange.com
elementaryos.stackexchange.com
meta.elementaryos.stackexchange.com
portuguese.stackexchange.com
meta.portuguese.stackexchange.com
computergraphics.stackexchange.com
meta.computergraphics.stackexchange.com
hardwarerecs.stackexchange.com
meta.hardwarerecs.stackexchange.com
es.stackoverflow.com
meta.es.stackoverflow.com
3dprinting.stackexchange.com
threedprinting.stackexchange.com
meta.3dprinting.stackexchange.com
ethereum.stackexchange.com
meta.ethereum.stackexchange.com
latin.stackexchange.com
meta.latin.stackexchange.com
languagelearning.stackexchange.com
meta.languagelearning.stackexchange.com
retrocomputing.stackexchange.com
meta.retrocomputing.stackexchange.com
crafts.stackexchange.com
meta.crafts.stackexchange.com
korean.stackexchange.com
meta.korean.stackexchange.com
monero.stackexchange.com
meta.monero.stackexchange.com
ai.stackexchange.com
meta.ai.stackexchange.com
esperanto.stackexchange.com
meta.esperanto.stackexchange.com
sitecore.stackexchange.com
meta.sitecore.stackexchange.com

```
* `page`: this will either be the empty string, `/` or `/` followed by any string

The url will be the string created by appending `protocol`, `domain` and `page` to each other, in that order.

## Testcases

Your regex must match:

```
https://codegolf.stackexchange.com/
http://retrocomputing.stackexchange.com
https://facebook.stackoverflow.com/questions/1234
http://meta.nothingtoinstall.com/thisisa404.php?file=command.com

```

Your regex must not match:

```
http//codegolf.stackexchange.com/
https://meta.stackoverflow.com.fakesite.dodgy/cgi-bin/virus.cgi?vector=apt
file://www.stackoverflow.com/
http://ripoff.com/stackoverflow.com/q/1234/

```

Your regex may match:

```
http://panda.stackexchange.com/
https://www.meta.codegolf.stackexchange.com
http://alpha.beta.charlie.delta.chiphacker.com
https://stackexchange.com/sites/

```

because these are owned by Stack Exchange Inc. and so will not be vulnerable to XSS attacks.

This is a challenge, so the shortest regular expression wins!

# Answer
# 337 336 333 327 bytes

```
^https?://([^/]+\.)*(stackoverflow\.(com(\.br)?|ru)|mathoverflow\.(com|net)|hashcode\.ru|((the)?arqade|chiphacker|(mi)?yodeya|ask(ubuntu|different|patents)|(seasoned|brew)advice|s(erverfault|(tack|keptic)exchange|uperuser|tackapps|harepointoverflow|ocialsounddesign)|nothingtoinstall|crossvalidated|basicallymoney)\.com)(/.*)?$

```

Doesn't use any fancy regex features, so it should work in any regex flavour.
> 16 votes

# Answer
## ~~359~~ 348 bytes

```
https?:\/\/(([^/]+\.)*((stack(overflow|apps|exchange)|ask(ubuntu|different|patents)|(the)?arqade|serverfault|superuser|nothingtoinstall|(seasoned|brew)advice|crossvalidated|basicallymoney|chiphacker|skepticexchange|(sharepoint|math)overflow|(mi)?yodea|socialsounddesign)\.com)|(stackoverflow(\.com\.br|\.ru)|hashcode\.ru|mathoverflow\.net))(\/.*)?$

```

Test it out on regexr
> 6 votes

# Answer
# 2179 2092 1966 bytes

```
https?:\/\/((((www|facebook|jp|(meta\.?)?(es|ru|ja|pt|br)?)\.)?stackoverflow\.com)|(stackoverflow\.(ru|com\.br))|(((russ|meta)\.)?hashcode\.ru)|(crossvalidated|socialsounddesign|mathoverflow|(mi\.?)?yodeya|(www\.)?(sharepointoverflow|basicallymoney)|skepticexchange|brewadvice|(www\.)?chiphacker|ask(different|ubuntu)|stackapps|(meta\.)?(nothingtoinstall|arqade|thearqade|seasonedadvice|superuser|serverfault|ask(ubuntu|patents)))\.com|((meta\.)?mathoverflow\.net)|(((meta\.)?((3|three)dprinting|(ask)?patents|(community|world)building|(econo|acade)mics|(it)?security|(reverse|network)?engineering|a(cademia|i|lcohol|ndroid|nime|pple|rduino|stronomy|viation|vp)|b((e|lend)er|i(cycles?|kes|ology|tcoin)|oardgames?|ricks|uddhism)|c(h(emistry|ess|inese|ristianity)|ivicrm|o(de(review|golf)|ffee|gsci|mputer(science|graphics)|oking)|r(aftcms|afts|ypto(graphy)?)|s(50)?|stheory)|d(ba|eutsch|iy|ranks|rupal|sp)|(earth|data)science|e(books|l(ectronics|ementaryos|l|u)|macs|nglish|spanol|speranto|thereum|xp(at(s|riates)|ressionengine))|f(antasy|itness|re(elancing|nch))|g(a(medev|ming|rage|rdening)|erman|enealogy|is|raphics?designs?|uitars?)|h(am|ealth|ermeneutics|induism|istory|omebrew(ing)?|sm)|(hard|soft)warerecs|islam|italian|j(apanese|oomla|udaism)|korean|l(a((ndscap|nguagelearn)ing|tin|w)|i(fehacks|nguist(ics)?|nux|))|m(a(gento|rtialarts|th(educators|ematica|ematics|s|overflow)?)|eta|echanics|o(derators?|nero|ney|vies)|usic(fans)?|ythology)|o(pen(data|source)|utdoors)|(cycl|parent|retrocomput)ing|p(ets|h(ilosophy|oto(graphy|s)?|ysics)|m|o(ker|litics|rtuguese)|roductivity|rogrammers?|uzzling)|quant|r(aspberrypi|obotics|pg|us(s|sian)?)|s(alesforce|ci(comp|encefiction|fi)|harepoint|ignals|itecore|keptics?|ound(design)?|p(ace|anish|orts)|qa|tartups|tat(s|istics)|ustainability)|t(ex|hefinalfrontier|or|ravel|ridion)|u(buntu|i|nix|x)|vi(deo|m)?|w(eb(apps|masters?)|indowsphone|o(odworking|rdpress|rkplace)|rit(ers?|ing))|(yodeya)))\.stackexchange\.com))(\/|$)

```

Matches exactly the domains listed and nothing else. I did most of the compressing by hand. I'm a bit embarrassed that I spent this much time on it.
> 3 votes

# Answer
# ~~142~~ ~~140~~ 334 bytes

```
#^https?:\/\/([^\/]*\.)?(hashcode\.ru|mathoverflow\.(com|net)|stackoverflow\.(ru|com(\.br)?)|((stack|skeptic)exchange|stackapps|ask(different|patents|ubuntu)|(brew|seasoned)advice|(the)?arqade|basicallymoney|chiphacker|crossvalidated|nothingtoinstall|serverfault|sharepointoverflow|socialsounddesign|superuser|(mi)?yodeya)\.com)(/|$)#

```
* matches everything on the specified second level domains, path or no path
* uses `#` as delimiter so `/` needs no escaping (saved two bytes)
* compressed manually
> 2 votes

---
Tags: code-golf, regular-expression
---


title: Checkers: King Me?

text:
# Question
Title: Checkers: King Me?
### Challenge:

Given a checkerboard, output the smallest amount of moves it would take (assuming black does not move at all) to king a red piece, if possible.

**Rules**:

Red's side will always be on the bottom, however their pieces may start in any row (even the king's row they need to get to). Black pieces are **stationary**, meaning they do not move in between red's movements, but they are removed from the board when captured. Note that pieces can start on *any* space on the board, including right next to each other. This is not how normal checkers is played, but your program must be able to solve these. (See input 5) However, checker pieces must only move **diagonally** (see input 3). Backward-capturing is allowed if the first capture is forward in the chain (see input 7).

**Input:**

An 8x8 checkerboard, with board spaces defined as the following characters(feel free to use alternatives as long as they're consistent):

. - Empty

R - Red piece(s)

B - Black piece(s)

**Output:**

The *smallest* number of moves it would take a red piece to be 'kinged' by entering the king's row on the top row of the board (black's side), 0 if no moves are required (a red piece started on king's row), or a negative number if it is impossible to king a red piece (ie black occupies it's entire first row).

Input 1:

```
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
R . . . . . . .

```

Output 1:

```
7

```

Input 2:

```
. . . . . . . .
. . . . . . . .
. . . . . B . .
. . . . . . . .
. . . B . . . .
. . . . . . . .
. B . . . . . .
R . . . . . . .

```

Output 2:

```
2

```

Input 3:

```
. B . B . B . B
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
R . . . . . . .

```

Output 3:

```
-1

```

Input 4:

```
. . . . . . . R
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
R . . . . . . .

```

Output 4:

```
0

```

Input 5:

```
. . . . . . . .
. . . . . . . .
. . . . . . . .
. B . . B . . .
B . . . . B . .
. B . B . . . .
. . B . . B . .
. . . R R . . .

```

Output 5:

```
4

```

Input 6:

```
. . . . . . . .
. . . . . . . .
. B . . . . . .
. . B . . . . .
. B . B . . . .
. . . . R . . .
. . . B . . . .
. . . . R . . .

```

Output 6:

```
2

```

Input 7:

```
. . . . . . . .
. . . . . . . .
. . B . . . . .
. . . . . . . .
. . B . . . . .
. B . B . B . .
. . . . B . . .
. . . . . R . R

```

Output 7:

```
4

```

**Scoring:**

This is , so shortest code in bytes wins.

# Answer
> 3 votes
## JavaScript (ES6), ~~354~~ 322 bytes

Takes an array as input with:

* 0 = empty square
* 1 = red piece
* 2 = black piece

Returns the optimal number of moves, or 99 if there's no solution.

It's very fast but could be golfed much more.

```
F=(b,n=0,C=-1,i)=>b.map((v,f,X,T,x=f&7,y=f>>3)=>v-1||(y&&n<m?[-9,-7,7,9].map(d=>(N=c=X=-1,r=(d&7)<2,T=(t=f+d)>=0&t<64&&(x||r)&&(x<7||!r)?(!b[t]&d<0)?t:b[t]&1?N:b[t]&2&&(d<0&y>1|d>0&C==f)?(X=t,x>1||r)&&(x<6|!r)&&!b[t+=d]?c=t:N:N:N)+1&&(b[f]=b[X]=0,b[T]=1,F(b,n+!(C==f&c>N),c,1),b[f]=1,b[X]=2,b[T]=0)):m=n<m?n:m),m=i?m:99)|m

var test = [
  [ 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    1,0,0,0,0,0,0,0
  ],
  [ 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,2,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,2,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,2,0,0,0,0,0,0,
    1,0,0,0,0,0,0,0
  ],
  [ 0,2,0,2,0,2,0,2,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    1,0,0,0,0,0,0,0
  ],
  [ 0,0,0,0,0,0,0,1,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    1,0,0,0,0,0,0,0
  ],
  [ 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,2,0,0,2,0,0,0,
    2,0,0,0,0,2,0,0,
    0,2,0,2,0,0,0,0,
    0,0,2,0,0,2,0,0,
    0,0,0,1,1,0,0,0
  ],
  [ 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,2,0,0,0,0,0,0,
    0,0,2,0,0,0,0,0,
    0,2,0,2,0,0,0,0,
    0,0,0,0,1,0,0,0,
    0,0,0,2,0,0,0,0,
    0,0,0,0,1,0,0,0
  ],
  [ 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,2,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,2,0,0,0,0,0,
    0,2,0,2,0,2,0,0,
    0,0,0,0,2,0,0,0,
    0,0,0,0,0,1,0,1
  ]
];

test.forEach((b, n) => {
  console.log("Test #" + (n + 1) + " : " + F(b));
});
```

---
Tags: code-golf, grid, game, path-finding, board-game
---


# Question
Title: Shortest way to strip the commas from column n given a .csv file/input
Ok, so the input here is going to be a .csv file and so is the output. Now, given a .csv file/input like so

```
"apple","banana","apple,banana","orange"
"grape","orange","grape,orange","sprout"
# 0       1        2              3

```

strip out all commas for a given nth column's entries (index starts at 0). So, for the input above, the program would output a .csv file like so for `n = 2`:

```
"apple","banana","applebanana","orange"
"grape","orange","grapeorange","sprout"

```

If the particular column's entries do not have commas, then it does nothing. Could have any allowable/manageable number of columns, and if you somehow find that creating a program that takes more than one argument, say, `a, b, c, ..., z` like this

```
program(a=1,b=4,c=65, ..., z=0, mycsv.csv)

```

for respective columns 2, 5, and 66, which all strip out commas for each, to be shorter, then do that.

---

Shortest code measured in bytes wins, and it doesn't have to be a file that is output/input.

# Answer
> 3 votes
# 05AB1E, 27 bytes

```
U|vy“","“©¡vyNXQi","-}})®ý,

```

**Explanation**

```
U                           # store index in X
 |v                         # for each line
   y“","“©¡                 # split on ","
           v          }     # for each in the split list
            yNXQi","-}      # if it's index equals X, remove any commas
                       )    # wrap in list
                        ®ý, # merge on "," and print

```

Try it online!

# Answer
> 4 votes
## JavaScript (ES6), ~~95~~ ~~93~~ 90 bytes

Takes the content of the CSV file as its first parameter and the column index as its second parameter, with currying syntax.

```
let f =

s=>n=>s.split(/("[^"]*")/).map(c=>(c<' '?(k=0,c):k++-n*2?c:c.split`,`.join``),k=-1).join``

console.log(f(
`"apple","banana","apple,banana","orange"
"grape","orange","grape,orange","sprout"
`)(2));
```

# Answer
> 4 votes
# Ruby, 80 bytes

```
require'csv'
->n,x{CSV.read(x).map{|a|a[n].delete!',';a.to_csv(force_quotes:1)}}

```

A lambda that takes `n` and a file path argument, and returns a list of CSV rows.

# Answer
> 3 votes
# Python 2, ~~129~~ ~~126~~ ~~125~~ ~~98~~ ~~96~~ ~~94~~ 92 bytes

```
lambda n,f:''.join(c*((r[:i].count('"')-n*2)*','!=c)for r in open(f)for i,c in enumerate(r))

```

This is a lambda expression; to use it, prefix `lambda` with `s=`.

Iterates through each character of each line, filtering characters based on whether it's a comma and it's in a double-quoted string.

Now doesn't use the `csv` module at all!

Example run:

```
>>> s=lambda n,f:''.join(c*((r[:i].count('"')-n*2)*','!=c)for r in open(f)for i,c in enumerate(r))
>>> print s(2, 'test.csv')
"apple","banana","applebanana","orange"
"grape","orange","grapeorange","sprout"

```

# Answer
> 2 votes
# Sh + GNU Sed ~~GNU Sed~~, 36 ~~28 + 1~~ bytes

Run with `-r` flag.

```
sed -r 's/(,?"\w*),?(\w*")/\1\2/'$1

```

One argument to select proper column (1-indexed). This uses a GNU-specific sed extension.

---

Old version: `s/(,?\"\w*),?(\w*\")/\1\2/3`

This required replacing the last 3 to select the proper column (1-indexed), which I'm not sure is allowed.

# Answer
> 1 votes
# NodeJS, 129 bytes

```
(f,n)=>(require("fs").readFileSync(f)+"").split`
`.map(a=>a.match(/".*?"/g).map((b,i)=>i-n?b:b.replace(/,/g,"")).join`,`).join`
`

```

Defines an anonymous function that takes a file path and a number as input. It is no longer required to take input as a file, but I will leave this here for comparison.

# Answer
> 1 votes
## Vim, 32 keystrokes (excluding column index)

This uses 1-based column indices (which might make this answer invalid).

The problem here is that Vim does not start from the current character but rather from the following one... So it's not "easy" to match the 1st set of quotes. Instead, it finds the *closing* quotes and selects backwards.

### Solution

`qq` \+ the column index + `/\v"(,"|$)<cr>vF":s/\%V,//<cr><cr>@qq@q`

### Explanation

* `qq` starts recording macro `q`
* `/\v"(,"|$)<cr>` searches for the next ending quote or end if line. Preceded by the input column number, it finds the nth occurrence
* `vF"` visually selects the previous quote
* `":s/\%V,//<cr>` substitutes in the visual selection (`\%V`) every comma by nothing
* `<cr>` goes to the next line
* `@qq@q` makes the macro recursive, stops it and then play it until the end of the file.

### Gotchas

* If a column only contains commas, it will be detected as a column end and will break. This is a gray zone, I will adapt the answer is the question adds this to the test cases.

# Answer
> 0 votes
# Haskell, 56 bytes

```
n!x=Math.FFT.Base.adjust(filter(/=','))n.read$'[':x++"]"

```

Without `adjust` you'd have to do something crazy like this:

```
n#(a,b)|a==n|filter(/=',')b|1<2=b; .. (n#)=<<zip ..

```

# Answer
> 0 votes
# R, 59 bytes

```
 function(f,n){x=read.csv(f,h=0);x[,n]=gsub(",","",x[,n]);x}

```

A simple function that takes `f`, the location of the csv file, and `n`, the column number to replace. Reads in the file, removes all commas from the `n`th column, returns the resulting data frame. R indexes from `1`, not from `0`.

# Answer
> 0 votes
# PHP, 81 bytes

```
while($r=fgetcsv(STDIN)){$r[$n=argv[1]]=strtr($r[$n],",","");fputcsv(STDOUT,$r);}

```

Run with `php -r '<code>' <n> < <csvsource> > <csvtarget>`.

---
Tags: code-golf
---


title: Number Triangles

text:
# Question
Title: Number Triangles
## Credit

My thanks to Rand Al'Thor's letter-based question for the inspiration for this code-golf challenge.

## Background

The nature of this challenge is based off the algorithm mentioned by Rand in his "A Triangle Formed of Three Letters":

> * Start with a sequence of 10 letters each of which is X, Y, or Z.
> * Under each row, construct the next row as follows. If two adjacent letters are the same, write the same letter beneath them; if they're different, write the third letter beneath them.

You would then repeat the previous step until you have one letter in your tenth row.

## Challenge

We're going to put a mathematical spin on the above algorithm:

* Let's start with a sequences of 10 digits, each separated by a space, and each of which is either 1, 2 or 3.
* Under each row, construct the next row as follows. If two adjacent digits are the same, write the same digit beneath them; if they're different, write the third digit beneath them.
* Repeat the previous step until you have one final number.

So, following this algorithm, if starting with the row `1 2 3 3 1 3 1 3 1 2`, for example, the following triangle is generated:

```
Input: 1 2 3 3 1 3 1 3 1 2

Output:

1 2 3 3 1 3 1 3 1 2
 3 1 3 2 2 2 2 2 3
  2 2 1 2 2 2 2 1
   2 3 3 2 2 2 3
    1 3 1 2 2 1
     2 2 3 2 3
      2 1 1 1
       3 1 1
        2 1
         3

```

I'm also curious to know the sum of all the digits in the number triangle, so add all these digits, and put this total in an eleventh row, right-justified to the last digit in the first row. So, our number triangle will look something like the following (spaces in my example are represented below by the `.` character to show formatting.)

```
Input: 1 2 3 3 1 3 1 3 1 2

Output:

1.2.3.3.1.3.1.3.1.2
.3.1.3.2.2.2.2.2.3.
..2.2.1.2.2.2.2.1..
...2.3.3.2.2.2.3...
....1.3.1.2.2.1....
.....2.2.3.2.3.....
......2.1.1.1......
.......3.1.1.......
........2.1........
.........3.........
................109

```

Your challenge is to write code that can start with an inputted string/array/etc. of ten digits, as per my example, and then apply the algorithm to generate the ten rows that would create the number triangle, followed by an 11th row that would display the total of all digits with right-justification.

## Testing

Testing of this string can be performed with a randomly generated string of ten digits of your choosing, or one generated from the snippet below...

```
c1=()=>('1331123221'+(Math.random()*(1<<24)|0).toString(4)).replace(/0/g, "").slice(-10).split("").join(" ");

$("#btn").click(function(){
  $("#str").val(c1());
});
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="str"><button id="btn">Get numbers</button>
<br>
Please use this snippet to generate a starting row for testing your code. Alternatively, you can also use a string of your choice, so long as it's ten digits (ranging from 1 to 3), separated by single spaces.
```

## Rules

1. Code-golf rules apply, so lowest number of bytes wins the challenge. In the event that there are two entries with the same low score, the winner will be awarded based on the number of up-votes.
2. What we're basically after is 11 rows, 19 characters long... How you render your final output is entirely up to you: array, console, file output, STDOUT, etc., so please use whatever output method you like that will work to your advantage. The only rule in the output is that we have 11 rows with 19 characters in each row in a similar format to above...
3. If it helps your code, use whatever separator for the digits... Just remember that legibility may be a contributing factor.
4. No silly loopholes.
5. Hard-coding of the input is not allowed. The purposes of this code is such that it can be used to produce different results each time with varying input. Hard-coding of `1 1 1 1 1 1 1 1 1 1` for example, completely negates the whole point of the algorithm.

Look forward to seeing what you all can come up with!

# Answer
# 05AB1E, ~~32~~ 26 bytes

```
DvÐOˆðýðN×.ø,ü+3%3^}\¯O19j

```

**Explanation**

```
D                 # duplicate input
v                 # for y,N in input,len(input): (10 times do)
 Ð                # triplicate current list
 Oˆ               # sum one copy and add it to global array
 ðý               # merge one copy on spaces
   ðN×.ø          # surround it with N spaces
        ,         # and print it
 ü+               # reduce one copy by addition
   3%             # modulus 3
     3^           # XOR 3
                  # this is the list sent to the next iteration
}                 # end loop
\                 # drop empty list left over from last iteration of loop
 ¯O               # sum the global array giving the triangles total sum
   19j            # join with spaces up to 19 chars

```

Try it online!
> 1 votes

# Answer
# Mathematica, ~~104~~ ~~97~~ ~~90~~ 94 bytes

```
{Grid[List@*Row/@#],#~Total~2}~Column~Right&[NestList[3-Mod[+##,3]&@@@Partition[#,2,1]&,#,9]]&

```

# Explanation

```
Partition[#,2,1]

```

Partitions the input into length 2, offset 1 partitions.

```
3-Mod[+##,3]&@@@

```

Takes each partition, and calculates the corresponding output.

A trick involved here. I added up the two numbers, took mod 3, and subtracted that result from 3. That gives the desired number. (e.g. 3 - ((2 + 1) mod 3) = 3)

```
NestList[ ... ,9]

```

Repeats the above process nine times, giving all iterations as the output.

```
Grid[List@*Row/@#]

```

Format each iteration into rows, and put the entire thing in one column (center aligned), creating a triangle.

```
#~Total~2

```

Take the total of all numbers.

```
{...}~Column~Right

```

Combine the triangle and the total, and right align the entire thing (triangle is already aligned, so its alignment is not affected).
> 7 votes

# Answer
# JavaScript (ES6), ~~143~~ 142 bytes

*Saved 1 byte thanks to @Neil*

```
a=>a.map((_,i)=>(q=" ".repeat(i))+(a=a.map(c=>(x+=r=i&&p^(p=c)||c,r),p=i&&a.shift())).join` `+q,x=0).join`
`+`
`+(" ".repeat(18)+x).slice(-19)

```

I tried combining various parts, but it ended up 5 bytes longer:

```
a=>[...a.map((_,i)=>(a=a.map(c=>(x+=r=i&&p^(p=c)||c,r),p=i&&a.shift())).join` `+" ".repeat(i),x=0),x].map(q=>(" ".repeat(18)+q).slice(-19)).join`
`

```
> 3 votes

# Answer
# Ruby, ~~134~~ 101 bytes

Using JHM's modulo trick.

```
->a{b=*a
(0..8).map{|i|[" "*i,a=a.each_cons(2).map{|x,y|b<<n=3-(x+y)%3
n}]*" "}<<"%19d"%b.reduce(:+)}

```

See it on eval.in: https://eval.in/649993
> 2 votes

# Answer
## CJam,  ~~44~~  40 bytes

```
l~{S*\_S*\2ew{:+3%3^}%2$N@}A%_s:~:+sJSe[

```

Try it online!

### Explanation

```
l~       e# Read and evaluate input.
{        e# Map this block over i in the range [0 1 ... 9].
  S*     e#   Get a string of i spaces (the indentation).
  \_     e#   Swap with the current line of trits and duplicate it.
  S*     e#   Join the trits with spaces.
  \2ew   e#   Swap with the other copy of the trits and get all consecutive pairs.
  {      e#   Map this block over the pairs...
    :+   e#     Sum the pair.
    3%   e#     Modulo 3.
    3^   e#     XOR 3.
         e#     This expression (x+y)%3 ^ 3 computes the required mapping.
  }%     e#   Now this is the next line.
  2$     e#   Copy the indentation (to pad the lines to equal length).
  N      e#   Push a linefeed.
  @      e#   Pull up the next line.
}A%      e# The result of this is a nested array whose string representation is
         e# the required triangle.
_s       e# Duplicate and flatten into a string.
:~       e# Eval each character which gives a list of all the trits.
:+       e# Sum that.
s        e# Turn the sum into a string.
JSe[     e# Left-pad it with spaces to width 19.

```
> 2 votes

# Answer
## JavaScript (ES6), ~~112~~ ~~100~~ 96 bytes

Takes an array as input and recursively builds a comma-separated triangle.

```
f=(s,p=`
`,S=0)=>p+(s[0]?s+f(s.map((v,i)=>(S+=v,v^s[i-1]||v)).slice(1),p+' ',S):(p+S).slice(-9))

console.log(f([1,2,3,3,1,3,1,3,1,2])); // reference example
console.log(f([3,3,2,1,3,1,2,1,2,1])); // random example
console.log(f([1,1,1,1,1,1,1,1,1,1])); // all ones (test case for sum < 100)
```
> 1 votes

# Answer
# Python 2, 164 bytes

A relatively simple iterative solution.

```
L=input()
s=0
for i in range(len(L)):
    print" "*-~i+" ".join(`L`[1::3]);s+=sum(L);N=L;L=[]
    for a,b in zip(N,N[1:]):L+=[list({1,2,3}-{a,b}),[a]][a==b]
print"%19s"%s

```

**Try it online**
> 1 votes

# Answer
# PHP, 143 Bytes

```
<?for($t=$_GET[t];$i<181;$s+=$v,$i+=2)$t[$i+20]=($v=$t[$i])*($z=$t[$i+2])>0&$i!=18?($v+$z)%3^3:" ";echo chunk_split($t.str_pad($s,8," ",0),19);

```
> 1 votes

---
Tags: code-golf, algorithm
---


title: List all ordered partitions of n

text:
# Question
Title: List all ordered partitions of n
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer `n`. These are the lists of numbers from `1` to `n` whose sum is `n`. For example, given input `n = 4`, the result should be:

> 4
> 1, 3
> 3, 1
> 2, 2
> 2, 1, 1
> 1, 2, 1
> 1, 1, 2
> 1, 1, 1, 1

The result can be in any order, but must contain each ordered partition once. This means that for `n = 4`, `[1, 1, 2]`, `[1, 2, 1]` and `[2, 1, 1]` must all be part of the result.

Here's my own JavaScript code which achieves this:

```
function range(n) {
    for (var range = [], i = 0; i < n; range.push(++i));
    return range;
}

function composition(n) {
    return n < 1 ? [[]] : range(n).map(function(i) {
        return composition(n - i).map(function(j) {
            return [i].concat(j);
        });
    }).reduce(function(a, b) {
        return a.concat(b);
    });
}

```

Golfed, ES6 (**~~169~~ ~~167~~ ~~119~~ ~~109~~ ~~105~~ ~~89~~ 85 bytes**):

```
n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]

```

# Answer
> 7 votes
# Pyth, ~~7~~ 6 bytes

7 byte solution:

Pyth has an integer partition builtin `./`, so 5 of the 7 bytes is getting the orderings.

```
{s.pM./

```

Try it online!

Explanation:

```
     ./  Integer partition (sorted by default)
  .pM    get all the orderings of each of the partitions as a nested list of lists of orderings
 s       Flatten by one layer
{        Remove duplicates

```

6 byte solution:

If you have a list, `./` will compute with orderings; all that remains is to make the lists numbers again.

```
lMM./m

```

Try it online!

Explanation:

```
     m  Get lists by gathering a list of [0, 1,...input] (I could use U as well)

   ./   Partition with orderings
 MM     Map an operation across each of the orderings lists of elements
l       where that operation is the length of the sublists

```

# Answer
> 12 votes
# Haskell, 37 bytes

```
f 0=[[]]
f n=[a:x|a<-[1..n],x<-f$n-a]

```

xnor saved two bytes.

# Answer
> 10 votes
## Python, 56 bytes

```
f=lambda n:[x+[n-i]for i in range(n)for x in f(i)]or[[]]

```

A recursive solution: The ordered partitions of `n` are a partition of some smaller `i` with `0<=i<n`, followed by the remainder `n-i` as the last element. For a base case, `n=0` only has the empty partition.

# Answer
> 10 votes
## Python 2, 61 bytes

```
f=lambda n,s='1,':1/n*[eval(s)]or f(n-1,'1+'+s)+f(n-1,'1,'+s)

```

This isn't the shortest, but I really like the method because it's so weird.

Recursively generates and evaluates `2**(n-1)` strings, like

```
1+1+1+1,
1,1+1+1,
1+1,1+1,
1,1,1+1,
1+1+1,1,
1,1+1,1,
1+1,1,1,
1,1,1,1,

```

for `n=4`. These strings evaluate to tuples representing all the partitions. Between any two 1's is either a `+`, joining them into a single number, or a `,`, splitting adjacent sections.

# Answer
> 8 votes
## JavaScript (Firefox 30-57), 63 bytes

```
f=n=>n?[for(i of Array(n).keys())for(a of f(i))[n-i,...a]]:[[]]

```

# Answer
> 6 votes
## Mathematica, 40 bytes

```
Join@@Permutations/@IntegerPartitions@#&

```

Mathematica's built-in for integer partitions doesn't give all *ordered* partitions, so we have to generate all possible permutations of each of them, and then flatten the result.

# Answer
> 6 votes
# CJam, ~~17~~ 14 bytes

```
ri"X)"m*{~]p}/

```

Try it online!

### Explanation

I know I said that using the Cartesian product is longer, but I ended up finding a way to use it more efficiently. I think that both approaches are interesting in their own right, so I'm putting them in separate posts.

This is still based on the idea that, we can choose `n` times between appending a `1` to the current partition or to increment the last element of the current partition. In this solution, we do this by generating 2n-1 different programs which correspond to these different choices.

```
ri      e# Read input and convert to integer N.
        e# Decrement.
"X)"m*  e# Get all strings of length N which consist of 'X' and ')'. If
        e# we treat these strings as CJam code then 'X' pushes a 1 and ')'
        e# increments the top of the stack.
        e# Note that some of these strings will begin with an increment that
        e# doesn't have anything on the stack to work with. This will result in
        e# an error and terminate the program. Luckily, the programs are ordered
        e# such that all programs starting with 'X' are first in the list, so
        e# we get to print all the 2^(N-1) permutations before erroring out.
{       e# For each of these programs (well for the first half of them)...
  ~     e#   Evaluate the string as CJam code. This leaves the partition as
        e#   individual integers on the stack.
  ]p    e#   Wrap the stack in a list and pretty-print it.
}/

```

# Answer
> 6 votes
# Jelly, ~~7~~ 6 bytes

-1 byte thanks to @Dennis (convert from unary `ḅ1`, rather than sum for each for each `S€€`)

```
1ẋŒṖḅ1

```

**TryItOnline**

How?

```
1ẋŒṖḅ1 - Main link: n          e.g. 4
1ẋ     - repeat 1 n times          [1,1,1,1]
  ŒṖ   - partitions of a list     [[[1],[1],[1],[1]], [[1],[1],[1,1]], [[1],[1,1],[1]],
                                   [[1],[1,1,1]],     [[1,1],[1],[1]], [[1,1],[1,1]],
                                   [[1,1,1],[1]],     [[1,1,1,1]]]
    ḅ1 - from base 1 (vectorises)  [[1,1,1,1],        [1,1,2],         [1,2,1],
                                   [1,3],             [2,1,1],         [2,2],
                                   [3,1],             [4]]

```

# Answer
> 5 votes
# Pure Bash, 51

This is a port of @xnor's brilliant answer, using multiple levels of bash expansions to achieve the desired result:

```
a=$[10**($1-1)]
eval echo \$[${a//0/{+,']\ $[}1'}],

```

Ideone.

* The first line is simply an arithmetic expansion to create a variable `$a` containing `1` followed by `n-1` zeros.
* The first expansion `${a//0/{+,']\ $[}1'}` replaces each `0` in `$a` with copies of the string `{+,']\ $[}1'`. Thus n=4 we get the string `1{+,']\ $[}1'{+,']\ $[}1'{+,']\ $[}1'`
* This is prefixed with `$[` and postfixed with `],` to give `$[1{+,']\ $[}1'{+,']\ $[}1'{+,']\ $[}1]`
* This is a brace expansion that expands to `$[1+1+1+1], $[1+1+1] 1, $[1+1] $[1+1], $[1+1] 1 1,...`
* This is finally arithmetically expanded to give the required result.

Careful use of quotes, backslash escaping and `eval` ensures that the expansions occur in the correct order.

# Answer
> 4 votes
## Ruby, 61 bytes

```
f=->n{n<1?[[]]:(1..n).map{|i|f[n-i].map{|x|x<<i}}.flatten(1)}

```

### ungolfed

```
f=->n{
  n < 1 ?
    [[]]
  :
    (1..n).map { |i|
      f[n-i].map { |x|
        x << i
      }
    }.flatten(1)
}

```

### usage

```
p f[4]
# => [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]]

```

# Answer
> 3 votes
# 05AB1E, ~~14~~ 12 bytes

Saved 2 bytes thanks to Adnan

```
>G¹LNãvyO¹Q—

```

**Explanation**

```
>G              # for N in range(1..input)
  ¹L            # range(1, input)
    Nã          # cartesian product with N (all combinations of length N)
      v         # for each resulting list
       yO¹Q—    # if it's sum equals the input print it

```

Try it online!

The corresponding solution is 2 bytes shorter in **2sable**.

# 2sable, 10 bytes

```
>GLNãvyOQ—

```

Try it online!

# Answer
> 3 votes
# Brachylog, 20 bytes

```
~lL#++?,L:=f:{:0x}ad

```

Try it online!

### Explanation

This is a situation where you would think declarative languages would do well, but because of the overloading of `+` and the difficutly in writing a summing predicate which propagates constraints properly, they do not.

```
~lL                     L is a list of length Input
  L#+                   L is a list of non-negative integers
  L  +?,                The sum of the elements of L results in the Input
        L:=f            Find all values for the elements of L which satisfy those constraints
            :{:0x}a     Remove all 0s from each sublist of the result of Findall
                   d    Remove all duplicate sublists

```

# Answer
> 3 votes
## CJam, 19 bytes

```
Lari{_1af.+1@f+|}*p

```

Try it online!

### Explanation

CJam doesn't have a useful combinatorics built-in for integer partitions. So we'll do this manually. To find all the *ordered* partitions of an integer `n`, we can look at a list of `n` ones and consider every possible way to insert separators. Then we'll sum the `1`s in each section. Example for `n = 3`:

```
1 1 1 => 3
1 1|1 => 2|1
1|1 1 => 1|2
1|1|1 => 1|1|1

```

I tried using a Cartesian product to generate all of these separators, but that ended up at 21 bytes. Instead I went back to this old technique for generating power sets (this is based on an old answer of Dennis's but I can't find it right now). The idea is this: to generate all partitions we can start from an empty list. Then `n` times we can make a binary decision: either we append a `1` (corresponds to a separator in the above example) or we increment the last value of the list (corresponds to not having a separator). To generate all partitions, we simply perform both operations at each step and keep all possible outputs for the next step. It turns out that in CJam, prepending and incrementing the first element is shorter, but the principle remains the same:

```
La       e# Push [[]] onto the stack. The outer list will be the list of
         e# all possible partitions at the current iteration, and we initialise
         e# it to one empty partition (basically all partitions of 0).
ri       e# Read input and convert to integer N.
{        e# Repeat this N times...
  _      e#   Duplicate the list of partitions of i-1.
  1af.+  e#   Increment the first element in each of these. This is done
         e#   by performing a pairwise addition between the partition and [1].
         e#   There is the catch that in the first iteration this will turn
         e#   the empty array into [1], so it's equivalent to the next step.
  1@f+   e#   Pull up the other copy of the list of partitions of i-1 and
         e#   prepend a 1 to each of them.
  |      e#   Set union. This gets rid of the duplicate result from the first
         e#   iteration (in all other iterations this is equivalent to concatenating
         e#   the two lists).
         e#   Voilà, a list of all partitions of i.
}*
p        e# Pretty-print the result.

```

# Answer
> 3 votes
## Julia, 113 Bytes

```
f(N)=unique(reduce(vcat,(map(x->[permutations(x)...],[vcat([1 for _=i+1:N],sum([1 for _=N-i:N-1])) for i=1:N]))))

```

Non-recursive solution

**Explained:**

1. `[vcat([1 for _=i+1:N],sum([1 for _=N-i:N-1])) for i=1:N]` build a set of lists that sum to N, whose permutations will resemble the solution (e.g. for N=4: \[\[1,1,1,1\],\[1,1,2\],\[1,3\],\[4\]\])
2. `map(x->[permutations(x)...],)` Calculate all permutations
3. `reduce(vcat,)` combine them into a list of lists
4. `unique()` filter duplicates

# Answer
> 3 votes
# T-SQL, 203 bytes

**Golfed:**

```
USE master
DECLARE @ INT=12

;WITH z as( SELECT top(@)cast(number+1as varchar(max))a FROM spt_values WHERE'P'=type),c as(SELECT a*1a,a b FROM z UNION ALL SELECT c.a+z.a,b+','+z.a FROM c,z WHERE c.a+z.a*1<=@)SELECT b FROM c WHERE a=@

```

**Ungolfed:**

```
USE master --needed to make sure it is executed from the correct database
DECLARE @ INT=12

;WITH z as
(
  SELECT top(@)cast(number+1as varchar(max))a
  FROM spt_values
  WHERE'P'=type
),c as
(
  SELECT a*1a,a b
  FROM z
  UNION ALL
  SELECT c.a+z.a,b+','+z.a
  FROM c,z
  WHERE c.a+z.a*1<=@
)
SELECT b
FROM c
WHERE a=@

```

**Fiddle**

# Answer
> 3 votes
# Mathematica 10.0, 44 bytes

An attempt without using partition-related builtins. From each ordered partition of size *k*, two successor partitions of *k + 1* are generated: one by prepending 1, and the other by incrementing the first value.

```
Nest[##&[{1,##},{#+1,##2}]&@@@#&,{{1}},#-1]&

```

A funnier, but sadly 2 bytes longer way of implementing the same idea:

```
#@{1}&/@Tuples[Prepend[1]@*MapAt[#+1&,1],#-1]&

```

# Answer
> 3 votes
## Haskell, 41 bytes

```
f 1=[[1]]
f n=do a:b<-f$n-1;[1:a:b,a+1:b]

```

Not the shortest Haskell solution, but I like that it doesn't use `[..]` ranges. Instead, it recursively computes the partitions of `n` as the partitions of `n-1` with either a new 1 at the start or the first value one higher. This makes explicit why there's `2^(n-1)` of them.

# Answer
> 3 votes
# Mathematica, 53 bytes

Doesn't beat Martin Ender's answer, which uses the built-in `IntegerPartitions` function (and built-ins are totally fine by me). (Nor does it beat feersum's answer, which I didn't see until too late.) But I wanted to practice a golfed recursive function.

```
If[#<1,{{}},Join@@Table[#~Append~j&/@#0[#-j],{j,#}]]&

```

Recursively generates all compositions, by generating all possible final numbers `j` and then calling itself on `#-j` where `#` is the input.

# Answer
> 3 votes
## Retina, 32 bytes

Byte count assumes ISO 8859-1 encoding.

```
.+
$*
+%1`1
!$'¶$`,!
!+
$.&
A`^,

```

Try it online!

### Explanation

This works similar to my CJam answer. We go through a list `N` ones and at each position we take both branches of the binary decision a) increment the last value or b) start a new value at 1.

**Stage 1**

```
.+
$*

```

Convert the input to unary.

**Stage 2**

```
+%1`1
!$'¶$`,!

```

The `+` tells Retina to execute this stage in a loop until the output stops changing. The `%` tells it to split the input into lines before applying the stage and join them back together afterwards. By putting the `%` after the `+`, Retina splits and rejoins after each iteration. One iteration of the stage makes one of those decisions I mentioned and thereby bifurcates the current set of partitions.

How it actually works is that it matches a `1` (but only the first one as indicated by the `1` in front of the backtick), and replaces it with `!` (which we'll use as the unary digit of our output), followed by the remaining `1`s on this row (this increments the last value). Then on another line () it prints the prefix of the current line, followed by `,!`, which inserts a separator and then starts the next value at `1`.

**Stage 3**

```
!+
$.&

```

This converts the runs of `!` to decimal integers by replacing them with their length.

**Stage 4**

```
A`^,

```

And finally, we notice that we've generated twice as many lines as we wanted, and half of them start with a `,` (those where we initially made the decision of splitting, even though there wasn't anything to split after yet). Therefore, we discard all lines that start with a `,`.

# Answer
> 3 votes
# Perl, 44 bytes

Includes +3 for `-n` (code uses `$'` and `$0` so it can't be run as a `-e` commandline)

Give number to partition on STDIN:

```
partitions.pl <<< 4

```

`partitions.pl`

```
#!/usr/bin/perl -n
$_=$&-$_.",$_$'",do$0for/\d+/..$&-1;print

```

If you don't mind extra spaces at the end of a line and an extra newline this 42 byte solution works too (run as `perl -M5.010 partitions.pl`):

```
#!/usr/bin/perl -n
$_=$`-$_." $_ $'",do$0for/\s/..$_-1;say

```

# Answer
> 2 votes
# MATL, 15 bytes

```
:"G:@Z^t!XsG=Y)

```

Try it online!

### Explanation

Given input `n`, this computes the Cartesian power with increasing exponents `k` from `1` to `n`; and for each exponent `k` selects the tuples that have a sum equal to the input.

```
:       % Take input n implicitly and push range [1 2 ... n]
"       % For each k in that range
  G:    %   Push [1 2 ... n] again
  @     %   Push k
  Z^    %   Cartesian power. Gives 2D array, say A, with each k-tuple in a row.
  t     %   Duplicate
  !     %   Transpose
  Xs    %   Sum of each column. Gives a row vector
  G=    %   True for entries that equal the input
  Y)    %   Use as logical vector into the rows of array A
        % End implicitly
        % Display stack implicitly

```

# Answer
> 1 votes
# PHP, 125 Bytes

```
for($i=$n=$argv[1];$i<=str_repeat(1,$n);$i++)if(array_sum($a=str_split($i))==$n&!strpos($i,"0"))$r[]=$a;echo json_encode($r);

```

-4 Bytes for `print_r($r);` instead of `echo json_encode($r);` for the output

a recursive solution with 250 Bytes

```
function f($n){global$a;foreach($a as$x)foreach(range(1,$n)as$y)$a[]=array_merge((array)$x,[$y]);if(--$n)f($n);}$a=range(1,$w=$argv[1]);f($w-1);foreach($a as$z)if(array_sum((array)$z)==$w)$c[join("-",(array)$z)]=$z;echo json_encode(array_values($c));

```

# Answer
> 1 votes
# Lua 214 203 182 bytes

```
function g(m, l, n,c)for i=1,m do if i+n < m then l[#l+1]=i;g(m,l,n+i,c+1)elseif i+n == m then l[#l+1]=i;print(unpack(l))end end for k=c,#l do l[k]=nil end end g(io.read()*1,{},0,0)

```

Ungolved version.

```
function g(m, l, n,c)
    for i=1,m do
        if i+n < m then
            l[#l+1]=i
            g(m,l,n+i,c+1)
        elseif i+n == m then
            l[#l+1]=i
            print(unpack(l))
        end
    end
    for k=c,#l do
        l[k]=nil
    end
end
g(io.read()*1,{},0,0)

```

Found a stray whitespace and removed an unnecessary variable to safe 11 bytes. as it turns out, table.insert() is byte inefficient

# Answer
> 1 votes
## Prolog, 81 bytes + 6 bytes to call

```
L*L.
[H|T]*L:-H>1,M is H-1,[M,1|T]*L.
[H,K|T]*L:-H>1,M is H-1,N is K+1,[M,N|T]*L.

```

Try it online!
Call with `[4]*L.`, repeat with `;` until all solutions have been presented.

Alternatively, if repeatedly pressing `;` is not okay (or should be added to the byte count), call with `bagof(L,[4]*L,M).` which adds 17 bytes for the call.

# Answer
> 1 votes
# , ~~30~~ 26 bytes

```
#&1<@(+/;.1)~2#:@(+i.)@^<:

```

Works by splitting the list of unary *n* by using the binary values of 2*n*.

Try it online!

## Explanation

```
#&1<@(+/;.1)~2#:@(+i.)@^<:  Input: n
                        <:  Decrement n
             2         ^    Compute 2^(n-1)
                 (   )@     Operate on that
                   i.         Make the range [0, 1, ..., 2^(n-1)-1]
                  +           Add 2^(n-1) to each in that range
              #:@           Convert each in that range to binary
#&1                         Make n copies of 1 (n in unary)
     (     )~               Operate over each row on RHS and unary n on LHS
        ;.1                   Chop unary n starting at each 1
      +/                        Reduce by addition on each chop
   <@                           Box the sums of each chop

```

# Answer
> 0 votes
# Actually, ~~17~~ 16 bytes

This answer is partially based on Luis Mendo's MATL answer. Golfing suggestions welcome. Try it online!

```
;╗R`╜R∙i`M`Σ╜=`░

```

**Ungolfing**

```
         Implicit input n.
;╗       Duplicate n and save a copy of n to register 0.
R        Take the range of [1..n].
`...`M   Map the following function over the range. Variable k.
  ╛R       Push n from register 0 and take the range [1..n] again.
  ∙        Take the k-th Cartesian power of the range.
  i        Flatten that product.
`...`░   Push values of the previous map where the following function returns a truthy value.
          Variable L.
  Σ        Push sum(L).
  ╜        Push n from register 0.
  =        Check if sum(L) == n.
         Implicit return.

```

# Answer
> 0 votes
# Actually, ~~17~~ ~~16~~ 15 bytes

This is an interesting fork of Martin Ender's CJam answer (the one with the Cartesian product), with a difference in implementation that I thought was interesting. When one of Martin's strings start with an increment, the errors prevent that string from being evaluated. In Actually, the error is suppressed and the string is evaluated anyway. This ends up giving the compositions of every `k` in the range `[1..n]`.

Rather than try to remove the extra compositions, I took the `n-1`th Cartesian power of `"1u"` appended a `"1"` to the beginning of each string. This trick gives only the compositions of `n`. It is, unfortunately, longer than Martin's answer.

Golfing suggestions welcome. Try it online!

```
D"1u"∙`1@Σ£ƒk`M

```

**Ungolfing**

```
         Implicit input n.
D        Decrement n.
"1u"∙    Take the (n-1)th Cartesian power of the string "1u".
          In Actually, 1 pushes 1 to the stack and u is increment.
`...`M   Map the following function over the Cartesian power. Variable s.
  1@       Push a 1 to be used later.
  Σ        Summing a list of chars joins the chars into one string.
  £ƒ       Turn s into a function and call it immediately on the 1 in the stack.
  k        Take the whole stack and wrap in a list. This is a composition of n.
         Implicit return.

```

---
Tags: code-golf, arithmetic, combinatorics, permutations, integer-partitions
---


title: Write a Chat Ping Counter

text:
# Question
Title: Write a Chat Ping Counter
Your task is to write a program, that given a list of chat messages, count how many times each person gets pinged, so I can know how popular everyone is. But, since I have to do it surreptitiously, I need it to be as small as possible so I can hide the code.

# Specs

* The input comes in a list of 2-tuples, with each item being of the form `("username", "message")`.
* A ping to another user is defined as an `@` followed by 3 or more letters that unambiguously refers to that user.
* However, you also have to consider replies, which have to start with `:messageid` followed by a space.
* Assume the first message has id `0` and proceed sequentially.
* Output each user and say how many times each one got pinged.
* The output can be in any order/reasonable format.
* This is , so shortest code in **bytes** wins!

# Test Cases

```
[["AlexA.", "I am wrong"], ["Quartatoes", "@Alex you are very wrong"], ["AlexA.", ":1 I am only slightly wrong"]]
AlexA.: 1
Quartatoes: 1

[["Doorknob", "I have never eaten an avocad."], ["AquaTart", ":0 I will ship you an avocad"], ["AlexA.", ":0 this is shocking"]]
Doorknob: 2
AquaTart: 0
AlexA.: 0

[["Geobits", "I like causing sadness through downvotes."], ["Flawr", "I want to put random message ids in my chat messages :0 askjdaskdj"]]
Geobits: 0
Flawr: 0

[["Downgoat", "goatigfs.com/goatgif"], ["Downotherthing", "@Downgoat cool gifs"], ["Dennis", "@Down cool gifs this is an ambiguous ping"]]
Downgoat: 1
Downotherthing: 0
Dennis: 0

```

# Answer
> 2 votes
# JavaScript (ES6), ~~245~~ 210 bytes

```
a=>(p={},a.map(b=>p[b[0]]=0),(a.map(b=>b[1].match(/@[a-z]{3,}|^:\d+/gi)||[]).map(c=>c.map(d=>(z=(d[0]=='@'?(y=Object.keys(p).filter(e=>e.startsWith(d.slice(1)))).length<2?y:0:a[d.slice(1)[0]]))&&p[z[0]]++))),p)

```

Uses an object to create a unique list of names alongside pings. Then it looks through the messages for matches to either ping condition. If a name, it looks through the list of names to find if there is only one match, and then increments. If a reply, it simply references that index in the message array and pulls the name to be incremented. Finally, it returns the object.

# Answer
> 0 votes
# PHP, 227 Bytes

```
foreach($_GET[a]as $c){$r[]=&$n[$c[0]]??$n[$c[0]]=0;preg_match("#^(:(\d+)|@(\w+))#",$c[1],$m);$m[2]==""?!$m[3]?:count($a=preg_grep("#^{$m[3]}#",array_keys($n)))>1?:$n[end($a)]++:$r[$m[2]]++;}foreach(($n)as$k=>$v)echo"$k: $v\n";

```

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


# Question
Title: Praming Puzles & Colf: Condense a String
Having spend some time on this site I have come to enjoy things being as short as possible. That may be the reason why I'm recently kind of offended by strings containing the same characters more than once. Your job is to write a function or program which *condenses* a given string according to the following rules:

* Start with a *0-condensation*, that is look for the first (leftmost) pair of the same characters with 0 other characters between them. If such a pair is found, remove one of the two characters and restart the algorithm by performing another *0-condensation*. If no such pair is found, proceed with the next step. Examples:
`programming` -C0-\> `programing`
`aabbcc` -C0-\> `abbcc`
`test` -C0-\> `test`
* Then perform a *1-condensation*, that is look for the first pair of same characters with 1 other character between them. If such a pair is found remove one of them **and all characters between them** and restart with a *0-condensation*. If no such pair is found, proceed with the next step. Examples:
`abacac` -C1-\> `acac`
`java` -C1-\> `ja`
* Continue with a *2-condensation* and so on up to a *n-condensation* with *n* being the length of the original string, each time restarting after a condensation removed some letters. Examples:
`programing` -C2-\> `praming`
`abcdafg` -C3-\> `afg`

The resulting string is called *condensed* and contains each character at most once.

---

**Input:**

A lower case string of printable ascii-characters.

**Output:**

The *condensed* string according to the rules above.

**Examples:**

```
examples     -> es
programming  -> praming
puzzles      -> puzles
codegolf     -> colf
andromeda    -> a
abcbaccbabcb -> acb
if(x==1):x++ -> if(x+
fnabnfun     -> fun
abcdefae     -> abcde

```

Detailed examples to clarify how the algorithm works:

```
fnabnfun -C0-> fnabnfun -C1-> fnabnfun -C2-> fnfun -C0-> fnfun -C1-> fun -C0-> fun
 -C1-> fun -C2-> ... -C8-> fun

abcbaccbabcb -C0-> abcbacbabcb -C0-> abcbacbabcb -C1-> abacbabcb -C0-> abacbabcb
 -C1-> acbabcb -C0-> acbabcb -C1-> acbcb -C0-> acbcb -C1-> acb -C0-> acb
 -C1-> ... -C12-> acb

```

Your approach doesn't have to implement the algorithm from above as long as your solution and the algorithm return the same output for all allowed inputs. This is a challenge.

---

Thanks to @Linus for helpful sandbox comments!

# Answer
## JavaScript (ES6), 74 bytes

```
f=
(s,n=0,m=s.match(`(.).{${n}}\\1`))=>s[n]?m?f(s.replace(...m)):f(s,n+1):s
;
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
> 6 votes

# Answer
# Perl, ~~38~~ ~~31~~ ~~30~~ 29 bytes

This should should leave the non-golfing languages far behind...

-1 for `$-[0]` thanks to Riley

-1 for `@{-}` thanks to Dada

Includes +1 for `-p`

Give input on STDIN

`condense.pl`:

```
#!/usr/bin/perl -p
s/(.)\K.{@{-}}\1// while/./g

```

This 27 byte version should work but it doesn't because perl doesn't interpolate `@-` in a regex (see https://stackoverflow.com/questions/39521060/why-are-etc-not-interpolated-in-strings)

```
#!/usr/bin/perl -p
s/(.)\K.{@-}\1// while/./g

```
> 5 votes

# Answer
# CJam, 35 bytes

```
rL{_,{{(_@_@#I={I)>]sj}*}h]s}fI}j

```

Try it online!

---

```
rL{                            }j   | run recursion on input
   _,{                      }fI     | for I from 0 to length(input)
      {                 }h]s        | one pass & clean up
       (_@                          | slice and store leading element A
          _@#I={      }*            | if next A is I steps away
                I)>                 | slice off I+1 element
                   ]sj              | clean up & recursion

```

You can see the individual condensations by inserting `ed`
> 3 votes

# Answer
# Python 2, ~~117~~ ~~104~~ 101 bytes

Recursively do the necessary replacements. I build the regex dynamically.

```
import re
def f(s,i=0):t=re.sub(r"(.)%s\1"%("."*i),r"\1",s);e=s==t;return i>len(t)and t or f(t,i*e+e)

```

**Try it online**
> 2 votes

# Answer
# Perl 53 52

Includes +1 for -p

```
for($i=0;$i<length;){$i=(s/(.).{$i}\1/\1/)?0:$i+1;}

```

Try it on ideone.
> 1 votes

# Answer
# PHP, 90 Bytes

```
for($s=$argv[$c=1];$s[$i=++$i*!$c];)$s=preg_replace("#(.).{{$i}}\\1#","$1",$s,1,$c);echo$s;

```

or 92 Bytes

```
for($s=$argv[1];$s[$i];$i=++$i*!$c)$s=preg_replace("#(.).{".+$i."}\\1#","$1",$s,1,$c);echo$s;

```
> 1 votes

# Answer
# Mathematica, 101 bytes

```
NestWhile[i=0;StringReplace[#,a_~~_~RepeatedNull~i++~~a_:>a,1]&,#,SameQ,2,ByteCount@#]&~FixedPoint~#&

```

There should be a way to make this shorter...
> 1 votes

# Answer
# Haskell, ~~97~~ 88 bytes

```
(0?)
(a:s)!(b:t)|a==b=a:t|1<3=a:s!t
s!_=s
m?s|length s<m=s|a<-s!drop m s=sum[m+1|a==s]?a

```

Try it online!

---

### Old 97 byte bersion:

```
(a:s)!(b:t)|a==b=a:t|1<3=a:s!t
s!_=s
m?s|length s==m=s|a<-s!drop m s=(last$0:[m+1|a==s])?a
c=(0?)

```

Try it on ideone.

**Explanation:**

```
(a:s)!(b:t)|a==b = a:t         --perform condensation
           |1<3  = a:s!t       --recursively compare further
 s   ! _         = s           --no condensation performed

```

The `(!)` function performs one n-condensation when given a string once whole and once with the first n characters removed, e.g. `abcdbe` and `cdbe` for a 2-condensation, by recursively comparing the two leading characters.

```
m?s|length s==m   = s         --stop before performing length-s-condensation
   |a <- s!drop m s           --a is the m-condensation of s
    = (last$0:[m+1|a==s])?a   --disguised conditional:
                              -- if a==s       if the m-condensation did not change s
                              -- then (m+1)?a  then perform m+1-condensation
                              -- else 0?a      else restart with a 0-condensation

c=(0?)                        -- main function, initialise m with 0

```
> 1 votes

# Answer
# Ruby, ~~75~~ ~~64~~ 57 bytes

(56 bytes of code + `p` command line option.)

Using string interpolation inside a regex to control the length of the matches that are replaced.

```
i=0
~/(.).{#{i}}\1/?sub($&,$1)&&i=0: i+=1while i<$_.size

```

Test:

```
$ ruby -p condense.rb <<< fnabnfun
fun

```
> 1 votes

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


# Question
Title: "Hello world!", repeating each character n times
In your language of choice, write a program that outputs exactly `Hello world!`. Each character in your program must be repeated *n* times - you choose *n*.

For example, you might choose 2 for *n*. This means that every character used in your source code *must* be repeated that many times, or 0.

If I were to choose 3 for *n*, this program would be valid:

```
ab(b(b(aa)));;;

```

Rules:

* You cannot use any external resources
* No user input can be provided
* You must output *exactly* `Hello world!`, no more, no less. Newlines are the exception, they are optional.
* *n* must be \>= 2, to keep things interesting
* It's highly discouraged to use comments to accomplish your goal.

Popularity contest, ending in 14 days. Highest score answer at the end wins!

# Answer
# Brainfuck

n=57. 45 newlines removed thanks to ratchet freak

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

```

A more readable version:

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

```

The last line (on the readable version) is for filling up the character count. They are not comments. The `[]` are `while(0)`s, and the `><`s are in essence no-ops
> 24 votes

# Answer
## JavaScript

```
alert(("aaaeerrttt((,,,HHHoo   wwwddd!!!))","Hello world!"))

```

This seemed a little too easy.
> 11 votes

# Answer
# Python 3, n = 3, no comments

```
dwwppHottedHen =print((("H[e]l1l1o\\ !w!orrilidn!\""[::2][:12])))== 2

```

Not too hard for a Pythonist to understand. ;) (Hint: try `"abcdefghijk"[::2]` and see what it results in)

By the way, a `HottedHen` is a warmed up chicken, if you were wondering. (The `dwwpp` before it stands for `drinking water with purple pancakes`, because that's what the hens were doing when I was writing it. Everyone knows that purple pancakes go well with water. Obviously.)
> 11 votes

# Answer
## C, 54

```
main(Hadmeinwurst015p){{!puts("Hello\40wor\154d!");;}}

```
> 10 votes

# Answer
## Golfscript - 32

New version with 2 of each used character - 32 - Test online

```
;"Hello wor\x6cd!" '\Hewrx6cd!';

```

Old version - 39 - Test online

```
;;'Hello world!'  "'HHeewworrdd!!\\\"";

```

EDIT: Updated since rules was updated saying it was discouraged with the use of comments
> 4 votes

# Answer
# Java - 1221 chars

Each character is repeated `(int)'!'` number of times.

```
public class ncharacterHelloworld {
    public static void main(String[] args){
        {;
{;
{;
{;
{;
{;
{;
{;
{;
{;
{;
{;
{;
{;
{;
{;
{;
{;
{;
{;{;{;{;{;{;{;{;{;{;{;{
String pppppppppppppppuuuuuuuuuuuuuubbbbbbbbbbbbbbbllllllllllliiiiiiiiiiicccccccccccccaaaaaaaaaaaassssssssssssssnnnnnnnnnnnnnhhhhhhhhhhhhhhhhrrrrrrrrrrrrttttttttttteeeeeeeeeeeeeeHHHHHHHHHHHHHHHooooooooooooowwwwwwwwwwwwwwwdddddddddddddddvvvvvvvvvvvvvvvvmmmmmmmmmmmmmmmSSSSSSSSSSSSSSSgggggggggggggggyyyyyyyyyyyyyyyy="Hello world!",
a=pppppppppppppppuuuuuuuuuuuuuubbbbbbbbbbbbbbbllllllllllliiiiiiiiiiicccccccccccccaaaaaaaaaaaassssssssssssssnnnnnnnnnnnnnhhhhhhhhhhhhhhhhrrrrrrrrrrrrttttttttttteeeeeeeeeeeeeeHHHHHHHHHHHHHHHooooooooooooowwwwwwwwwwwwwwwdddddddddddddddvvvvvvvvvvvvvvvvmmmmmmmmmmmmmmmSSSSSSSSSSSSSSSgggggggggggggggyyyyyyyyyyyyyyyy,
u="\"=============================,,,,,,,,,,,,,,,,,,,,,,...............................",b="\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\\\\\\a",i,l,c,t,H,o,w,m;int[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]ffffffffffffffffffffffffffffffff;
        if(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!!true)))))))))))))))))))))))))))))))
System.out.println(a);
}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
    }

}
```

I got tired of putting all the `=` and `,` and the like in the code, so I ended dumping them all in a String; not a comment, a string. Every valid character is used for a variable name.
> 4 votes

# Answer
## Windows Command Script - 33 bytes

3 of everything:

```
ecHo Hello world!% eHccwwrrdd!!%%

```
> 3 votes

# Answer
# Windows Command Line - 42 Bytes

n=3

```
ecHo.Hello world! 2>^>2cceHwwrrdd!.. 2>^^!

```

## Batch - 45 Bytes

```
@ecHo.Hello world! 2>^>2cceHwwrrdd@@..! 2>^^!

```

`2>` redirects stderr to a file called `>22cceHwwrrdd` \- `>` is an invalid character for a file name - redirect the output of that error to a file called `^!`.

Realized that I completely ignored `!` and `>`. Dang.
> 3 votes

# Answer
# **Ruby - 40 Chars** (n=2)

```
print "Hel\x6co World!"||'pintHe\x6cWd!'

```
> 3 votes

# Answer
## PHP - 30 bytes, *n = 2*

```
Hell<?='=s?<;^2s'^RSHSI2VReIV;

```

Shortest solution thus far. I may be able to reduce this by *2-4* more bytes.
> 3 votes

# Answer
## PHP

```
<?print"H\145llo wor\154d!"; $Hwpintd<>!'$';?>

```

Shorter version (42 char):

```
<?print"H\145llo wor\154d!"; 'Hwd<pint?!';

```

Online page with that source
> 1 votes

# Answer
# Perl (51 bytes)

```
print'Hello world!'; ppriinnttHHeeowwdd; "'\"\\!!";

```
> 1 votes

# Answer
# C, ~~75~~ ~~56~~ 54

2 of everything

```
main(HWacdeimnprstux6) {{!puts("Hel\x6co\ World!");;}}

```

---

```
main( ){puts("Hello Wor\x6cd!\0!;HWacdeimnprstux06{}");}

```

---

3 of everything.

```
main(){puts("Hello World!\000!!;;HHWWaaddeeiimmnnpprrssttuu{}{}\"\()o");}

```

`Puts` stops reading after the first null byte (`\000`), and only outputs everything before it.
> 1 votes

# Answer
# JavaScript 40 (n=2)

I took a slightly different approach to @eithedog, using the left over letters to act as a logic trigger, so that it was absolutely essential to use it to activate the `alert` function.

`('Hawtd !')&&alert("He\x6c\x6co world!")`
> 1 votes

# Answer
**Python 2, 38**

```
deinptw=H=5; print"Hel\154o world\41";

```
> 1 votes

# Answer
## R, 346 characters, *n* = 12

```
cat((((((((((intToUtf8(c(40,69,76,76,79,0,55,79,82,76,68,1)+31+1+0+0+0+0+0+0+0+0++0*11111111[1]*22222222222[1]*33333333333[1]*44444444444[1]*5555555555[1]*6666666[1]*7777777[1]*888888888[1]*999999*9[1]*9[1]*9[1])))))))))),"\"\"\"\"\"\"\"\"\"\"\\aaaaaaaaaaaccccccccccfffffffffffiiiiiiiiiiinnnnnnnnnnnoooooooooootttttttttTTTTTTTTTTTUUUUUUUUUUU"[0])

```

Characters used in this code:

```
,"()[]*\+0123456789acfinotTU

```
> 1 votes

# Answer
# Jelly, 16 bytes (non-competing)

```
“⁸ƒẹI4»
“⁸ƒẹI4»

```

(+trailing newline)

Try it online! (n = 2)

NO COMMENTS AT ALL. I assure you. Just Link 1 and the Main Link.
> 1 votes

# Answer
## Golfscript, 42

```
."Hello world!"'\\\'"  HHeeowwrrdd!!'..;;;

```

Test online
> 0 votes

# Answer
**Javascript, 40**

```
alert("Hel\x6Co wor\x6Cd!", !('adtHw,'))

```

If I'm not mistaken every character appears twice (though I started seeing double, so I'm not sure)

edit: And, if abusing the rules - **36**:

```
alert("Hel\x6Co wor\x6Cd!")( !wdatH)

```

(abuse = while output is given as a prompt, the console displays the error - don't know how to treat this).
> 0 votes

# Answer
# Python:

With 3 characters each.

```
print 'Hello world!'#He's aware#paints#Hipos!nddwt!

```

`nddwt` is a rhino!
> 0 votes

# Answer
# Bash, 39

```
echo -e "H\r--w\"!wccdd!\rHello world!"

```

This *displays* exactly Hello world!, and is 39 chars if you omit the trailing newline (bash doesn't seem to need it).

If you need a case-sensitive version, it becomes 42 chars:

```
echo -e "HhhH\r--w\"!wccdd!\rHello world!"

```
> 0 votes

# Answer
# JavaScript (52 characters)

```
alert(['He\x6C\x6Co world!'][(!1,0)-0], +-1+"Hadtw")

```

Each character is used 2 times, and it doesn't use any comments!

**Note:** *I posted this answer here first.*
> 0 votes

# Answer
# Golfscript x4 -- No extra symbols -- Using all possible commands

```
'HHHeeelWWWrrrd'!!! do do 'Hello world!'

```

I tried to do one that didn't have any extra symbols beyond what was absolutely necessary (though I could have chosen `"` instead of `'` or `"`)

As a secondary goal I also wanted to put as few characters as possible into a string as possible, so I used the `!` operator as such, and I also squeezed in to `do` operators.
> 0 votes

# Answer
# Classic ASP (VBScript; 62 characters)

```
Hel<%REspOnsE.wRite Chr((0<0>-.6&"!")+&H6C+h-dinptO)%>o world!

```

Uses each character exactly 2 times!

---

**Edit:** This code is a bit shorter:

```
Hel<%= Chr((0<0>we=6&"!")+&H6C+hd)%>o world!

```

And so is this:

```
Hel<%= CHr((0<1>wedC=8&"!&")++108)%>o world!

```
> 0 votes

# Answer
# Turtlèd, n=3, (noncompeting)

N=3, because of "Hello world!" having three `l`s.

```
'!' ' HHeeowwrrdd"Hello world!""!

```

**Try it online**

## Explanation:

```
'!                                write exclamation mark
  ' '                             write space twice on the same cell as exclamation mark
      HHeeowwrrdd                 balances chars in Hello world!, moves the pointer
                 "Hello world!"   Write Hello world! to grid
                               "! Write the exclamation mark again, on top of the last one

```
> 0 votes

# Answer
# Befunge 98 - 26 bytes

Since I had to duplicate the `r` anyway, I figured I may as well make the source text read left-to-right rather than typical `gnirts` Befunge style. There's nothing particularly notable about this; I'm not sure if having code that simply isn't executed counts as a comment, but the six characters `Hel w!` are just ignored.

```
rHel w!@,dk"Hello, world!"

```
> 0 votes

---
Tags: popularity-contest, hello-world, restricted-source
---


title: Convert pointfree to pointful

text:
# Question
Title: Convert pointfree to pointful
Being a Haskell hacker, I prefer pointfree notation over pointful. Unfortunately some people find pointfree notation hard to read, and I find it hard to get the correct number of parentheses when I write in pointful. Help me convert code written in pointfree to pointful notation!

## About

In pointfree notation we use points (yes, really) to feed the output of one function into another. Say, if you had a function `succ` that takes a number and adds 1 to it, and you wanted to make a function that adds 3 to a number, instead of doing this:

```
\x -> succ(succ(succ(x)))

```

you could do this:

```
succ.succ.succ

```

Pointfree only works with functions that take a single parameter however (in this challenge anyway), so if our function wasn't `succ` but rather `add` which take 2 numbers and adds them together, we would have to feed it arguments until there is only one left:

```
pointful:  \x -> add 1(add 1(add 1 x))
pointfree: add 1 . add 1 . add 1

```

Lastly, functions may take other functions as arguments:

```
Pointfree: map (f a . f b) . id
Pointful:  \x -> map (\x -> f a (f b x)) (id x)

Javascript equivalent: x => map (x => f(a,f(b,x)), id(x))

```

## Input and expected output

```
f . f . f
\x -> f (f (f x))

f a . f b . f c
\x -> f a (f b (f c x))

f (f a . f b) . f c
\x -> f (\x -> f a (f b x)) (f c x)

a b c . d e . f g h i . j k l . m
\x -> a b c (d e (f g h i (j k l (m x))))

a.b(c.d)e.f g(h)(i j.k).l(m(n.o).p)
\x->a(b(\y->c(d y))e(f g h(\z->i j(k z))(l(\q->m(\w->n(o w))(p q))x)))

```

## Rules

* Your output may have more spaces or parentheses than required, as long as they are balanced
* You don't have to make sure that the name of the variable you create `\x` isn't already used somewhere else in the code
* It is your choice whether to create a function or a full program
* This is `codegolf`, shortest code in bytes win!

You might find blunt useful, it converts between the two notations (but also factorizes the code when possible): https://blunt.herokuapp.com

# Answer
# Haskell, ~~163 142~~ 133 bytes

```
p(x:r)|[a,b]<-p r=case[x]of"("->["(\\x->"++a++p b!!0,""];"."->['(':a++")",b];")"->[" x)",r];_->[x:a,b]
p r=[r,r]
f s=p('(':s++")")!!0

```

Try it on Ideone.

Ungolfed:

```
p('(':r)|(a,b)<-p r = ("(\\x->"++a++(fst(p b)),"")
p('.':r)|(a,b)<-p r = ('(':a++")",              b)
p(')':r)            = (" x)",                   r)
p(x  :r)|(a,b)<-p r = (x:a,                     b)
p _                 = ("",                     "")

f s=fst(p('(':s++")"))

```
> 4 votes

# Answer
# Haskell, ~~402~~ 289 bytes

Quite long, but I think it works..

```
(!)=elem
n%'('=n+1
n%')'=n-1
n%_=n
a?n=a!"."&&n<1
a#n=a!" ("&&n<1||a!")"&&n<2
q a='(':a++")"
p s o n[]=[s]
p s o n(a:b)|o a n=[t|t@(q:r)<-s:p""o(n%a)b]|0<1=p(s++[a])o(n%a)b
k=foldr((++).(++" ").f)"".p""(#)0
f t|not$any(!"(. ")t=t|l@(x:r)<-p""(?)0t=q$"\\x->"++foldr((.q).(++).k)"x"l|0<1=k t

```
> 2 votes

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


title: Translate number pairs to guitar notes

text:
# Question
Title: Translate number pairs to guitar notes
A guitar fretboard diagram looks like this:

```
  0  1  2  3  4  5  6  7  8  9 10 11 12   <- Fret number (0 means it's open)
|-E--F--F#-G--G#-A--A#-B--C--C#-D--D#-E
|-B--C--C#-D--D#-E--F--F#-G--G#-A--A#-B
|-G--G#-A--A#-B--C--C#-D--D#-E--F--F#-G
|-D--D#-E--F--F#-G--G#-A--A#-B--C--C#-D
|-A--A#-B--C--C#-D--D#-E--F--F#-G--G#-A
|-E--F--F#-G--G#-A--A#-B--C--C#-D--D#-E

```

As you can see, the first string (from the top) open is an `E`. The first fret on the first string is an `F`. The fourth fret on the third string is a `B`. Note that the first note is the zeroth fret, not the first.

This can be written with numbers on the format `string, fret`. The strings are numbered from 1 to 6 from top to bottom. The frets are numbered from 0 to 12 from left to right. The first `E` is therefore `1, 0`. Some other examples:

```
1, 0 --> E
1, 1 --> F
3, 5 --> C
5, 1 --> A#
6, 6 --> A#

```

**Challenge:**

Take `N` pairs of numbers (`s` and `f`), and output a delimited note succession.

* The input may be on any suitable format. tuples, 2D-matrix, two separate lists, an interweaved list (string,fret,string,fret...) etc.
* The output tone should be separated, but the delimiter is optional (comma, space, dash...). The output can be in either upper or lower case.
* `s` (for string) will be in the range `[1, 6]` (you may choose to have i 0-indexed)
* `f` (for fret) will be in the range `[0, 12]`

**Test cases and examples:**

```
1 4 5 2 1 3   <- String
4 2 6 3 5 1   <- Fret
G# E D# D A G#

6 2 3 1 4 2 3 2 2 2 6 5 2
0 1 2 3 4 5 6 7 8 9 10 11 12
E C A G F# E C# F# G G# D G# B

3 3 3 3 3 3 3 3 3 3 3 3 3   <- String
0 3 5 0 3 6 5 0 3 5 3 0 0   <- Fret
G A# C G A# C# C G A# C A# G G

// The same test case, but different input and output format:
(3,0)(3,3)(3,5)(3,3)(3,6)(3,5)(3,0)(3,3)(3,5)(3,3)(3,0)(3,0)
G,A#,C,G,A#,C#,C,G,A#,C,A#,G,G

```

Good luck, and happy golfing!

# Answer
> 4 votes
# 05AB1E, ~~48~~ ~~47~~ ~~43~~ 40 bytes

Uses CP-1252 encoding.

Both strings and frets are 0-based.

```
v7YT5¾7)y`Šè+•™ÎÚ,Ülu•žh'#A«‡•7V3•3BS£è,

```

**Explanation**

```
v                                # for each pair in input
 7YT5¾7)                         # the list [7,2,10,5,0,7]
 y`                              # flatten the pair [string, fret] and places on stack
 Šè                              # index into the list above using the string
 +                               # add the fret
 •™ÎÚ,Ülu•žh'#A«‡•7V3•3BS£       # list of accords
 è                               # index into the string using the number calculated above
 ,                               # print

```

Try it online!

Saved 7 bytes thanks to Adnan

# Answer
> 9 votes
## JavaScript (ES6), ~~79~~ 70 bytes

```
a=>a.map(([s,f])=>"AA#BCC#DD#EFF#GG#".match(/.#?/g)[(s*7+(s>2)+f)%12])

```

Requires 1-based strings. Edit: Saved 9 bytes by directly calculating the string to fret conversion, based on @nimi's old answer.

# Answer
> 7 votes
# Mathematica, 62 bytes (non-competing)

```
<<Music`;MusicScale[100(#2+{24,19,15,10,5,0}[[#]])&@@@#,E2,9]&

```

The `{24,19,15,10,5,0}` and the `E2` represent the open-string tones of the six guitar strings (for example, the top string is 24 semitones above the note E2). Non-competing because it doesn't print the names of the notes—it *plays* the sequence of notes! (only if you have Mathematica, unfortunately) For example,

```
<<Music`;MusicScale[100(#2+{24,19,15,10,5,0}[[#]])&@@@#,E2,9]&@
 {{4,0},{3,2},{2,3},{1,2},{5,0},{4,2},{3,2},{2,2},
  {5,2},{4,4},{2,0},{2,3},{6,2},{4,4},{3,2},{2,2},
  {6,3},{4,0},{3,0},{2,0},{4,0},{4,4},{3,2},{2,3},
  {6,3},{3,0},{2,0},{2,3},{5,0},{4,2},{3,2},{2,2},{4,0}}

```

plays the opening 4 bars or so from Pachelbel's Canon. (which is about as much of Pachelbel's Canon as I can stand)

# Answer
> 7 votes
# MATL, ~~48~~ ~~47~~ 45 bytes

*Thanks to @Emigna for a correction regarding input format.*

Guitar and code golf... I had to answer this one!

```
'$)-27<'i)-'F F# G G# A A# B C C# D D#

```

Input format is: an array of (1-based) string, then an array of (0-based) frets.

Try it online!

### Explanation

Some language features used in this answer:

* A string is *automatically converted* to a numerical array of ASCII code points when some arithmetic operation is applied to it.
* Arithmetical operations work *element-wise*, i.e. vectorized. So the subtraction of a string and a numerical array of the same size gives an array with the subtraction of corresponding entries.
* Indexing is 1-based and *modular*.
* A *cell array* is like a list in other languages. It can contain arbitrary elements, possibly arrays of different types or sizes. Here a cell array will be used to store strings of different lengths (the notes' names).

Commented code:

```
'$)-27<'                       % Push this string
i                              % Take first input (array of guitar strings)
)                              % Index into the string. For example, input [1 3] gives
                               % the string '$-' (indexing is 1-based)
-                              % Implicitly take second input (array of guitar frets).
                               % Subtract element-wise. This automatically converts the
                               % previous string into an array of ASCII codes. For
                               % example, second input [1 5] gives a result [-35 -40],
                               % which is [1 5] minus [36 45], where 36 and 45 are the
                               % ASCII codes of '$-'
'F F# G G# A A# B C C# D D# E' % Push this string
Yb                             % Split at spaces. Gives a cell array of 12 (sub)strings:
                               % {'F', 'F#', 'G', ..., 'E'}
w)                             % Swap and index into the cell array of strings.
                               % Indexing is 1-based and modular. In the example, since
                               % the cell array has 12 elements, the indexing array
                               % [-35 -40] is the same [1 8], and thus it gives a
                               % (sub-)array formed by the first and eighth cells:
                               % {'F', 'C'}. This is displayed as the cells' contents,
                               % one per line

```

# Answer
> 4 votes
# Java, 174

```
String f(int[]s,int[]f){String o="";for(int i=0;i<s.length;++i){int n =(7*s[i]-7+f[i]+(s[i]>2?1:0))%12*2;o+="E F F#G G#A A#B C C#D D#".substring(n,n+2).trim()+" ";}return o;}

```

Ungolfed:

```
  String f(int[] s, int[] f) {
    String o = "";
    for (int i = 0; i < s.length; ++i) {
      int n = (7 * s[i] - 7 + f[i] + (s[i] > 2 ? 1 : 0)) % 12 * 2;
      o += "E F F#G G#A A#B C C#D D#".substring(n, n + 2).trim() + " ";
    }
    return o;
  }

```

# Answer
> 3 votes
# C, 104 103 bytes

```
main(s,f){for(;~scanf("%d%d",&s,&f);printf("%.2s\n",
"E F F#G G#A A#B C C#D D#"+(f+7*~-s+(s>2))%12*2));}

```

Takes numbers as `string fret` pairs on stdin, and outputs the note after every pair. E.g.:

```
1 4
G#
4 2
E
5 6
D#
2 3
D

```

# Answer
> 3 votes
# Ruby, 63 bytes

takes an array of 2-element arrays, in the order `[string,fret]`.

```
->x{x.map{|i|"BEADGCF"[6-n=((i[0]-3)%5+2+i[1]*7)%12]+?#*(n/7)}}

```

**Explanation**

In standard tuning the guitar is one of the few stringed instruments (bowed or fretted) that has inconsistent intervals between its strings. Most have either a consistent 5-semitone interval between all pairs of adjacent strings (a "fourth") or a consistent 7-semitone interval between all pairs of adjacent strings (a "fifth.") These correspond to frequency ratios of 3:4 and 2:3 respectively, and are second in importance only to the "octave" with frequency ratio 1:2.

The guitar has mostly 5-semitone intervals. If it had 5 of these it would have a difference of 25 semitones between the 1st and 6th string. Instead, the interval between the 2nd and 3rd string is reduced to 4 semitones, giving a difference of 24 semitones (2 octaves) which is better for playing chords.

This is inconvenient for the program, so we start by changing the 1-indexed guitar intonation into a 0 indexed 5-string-bass intonation, which has all intervals of 5 semitones:

```
formula (i[0]-3)%5
Before                            After
String      6 5 4 3 2 1           String 4 3 2 1 0
Note        E A D G B E           Note   B E A D G

```

Next we add 2, and give the tuning of a fictitious 12 string bass, with intonation of the open strings as follows, and all intervals being 5 semitones (12 string "basses" do exist but I am not sure there are many with precisely this tuning.)

```
String       11 10 9  8  7  6  5  4  3  2  1  0
Note         A# D# G# C# F# B  E  A  D  G  C  F

```

As can be seen, all the sharps are grouped together. This pattern can be repeated ad infinitum. It is known as the "circle of fifths" and is fundamental to the Western musical scale (with a bit of tuning adjustment the circle can be closed due to the fact that `(3/2)**12` and `2**7` are very similar numbers.

Now we deal with the fret parameter. Unlike many other answers here, which translate the string parameter into a number of frets, I translate the fret parameter into a number of strings. In the table above it can be seen that adding 7 to the string number puts us on a string whose note name is one semitone higher. (It's in a completely different octave but that does not matter.) So we add `i[1]*7` to the string number, and take it modulo 12:

```
n=(i[0]-3)%5+2+i[1]*7)%12

```

We subtract this from 6 to get a number in the range 6 to -5 and look up the letter in `BEADGCF` (Ruby allows negative indices to wrap around back to the end of the array.) If `n>=7` we need to add a `#` symbol to complete the output.

**Test program**

```
f=->x{x.map{|i|"BEADGCF"[6-n=((i[0]-3)%5+2+i[1]*7)%12]+?#*(n/7)}}

z=[[6, 2, 3, 1, 4, 2, 3, 2, 2, 2, 6,5,2],[0, 1, 2, 3, 4 ,5 ,6 ,7, 8, 9, 10, 11, 12]].transpose

puts f[z]

```

**Output**

```
E
C
A
G
F#
E
C#
F#
G
G#
D
G#
B

```

# Answer
> 3 votes
# C#, 131 bytes

```
string n(int[]s,int[]f){return string.Join(" ",s.Zip(f,(x,y)=>"E,F,F#,G,G#,A,A#,B,C,C#,D,D#".Split(',')[(7*x-7+y+(x<3?0:1))%12]));}

```

Input two separate lists, strings are 1 based.

# Answer
> 1 votes
# Java 7 ~~197~~,163 bytes

```
void f(int[]s,int[]f){String[]l={"A","A#","B","C","C#","D","D#","E","F","F#","G","G#"};int[]d={0,7,2,10,5,0,7};int j=0;for(int i:s)out.print(l[(d[i]+f[j++])%12]);}

```

# Ungolfed

```
  void f(int[]s,int[]f){
 String[]l={"A","A#","B","C","C#","D","D#","E","F","F#","G","G#"};
int[]d={0,7,2,10,5,0,7};
    int j=0;
    for(int i:s)
        out.print(l[(d[i]+f[j++])%12]);

}

```

# Answer
> 1 votes
# Clora, 55 bytes

`@T[0,7,2,10,5,0,7]+N%12@T[,A,A#,B,C#,D,D#,E,F,F#,G,G#]!`

Explanation

`@` numeric mode (read input as numbers)

`T[0,7,2,10,5,0,7]` Transform input using the array, ex array\[Input\]

`+N` Add N (Next input value) to current Input

`%12` Modulo 12 the current input value

`@` Flag numeric mode off

`T[,A,A#,B,C#,D,D#,E,F,F#,G,G#]` Translate the input into an array

`!` Use input as output value

# Answer
> 0 votes
## Haskell, ~~83~~ 82 bytes

```
zipWith$(!!).(`drop`cycle(words"A# B C C# D D# E F F# G G# A")).([6,1,9,4,11,6]!!)

```

Takes a list of strings and a list of frets, both 0-indexed. Usage example:

```
Prelude >  ( zipWith$(!!).(`drop`cycle$words"A# B C C# D D# E F F# G G# A").([6,1,9,4,11,6]!!) ) [0,1,2,3,4,5] [0,0,0,0,0,0]
["E","B","G","D","A","E"]

```

From the infinite list of notes starting with `A#`, drop the number of notes given by the list `[6,1,9,4,11,6]` at index of the string and pick the note at index of the fret from the remaining list.

# Answer
> 0 votes
# JavaScript (ES6), ~~82~~ 81 bytes

```
a=>a.map(b=>(q=(b[0]+.3+b[1]*7.3|0)%12/1.7+10.3).toString(17)[0]+(q%1>.5?"#":""))

```

I wanted to try an all-math answer, but it turned out a little long. Maybe there's a way to golf it...

### Test snippet

```
f=a=>a.map(b=>(q=(b[0]+.3+b[1]*7.3|0)%12/1.7+10.3).toString(17)[0]+(q%1>.5?"#":""))
console.log(f([[4,1],[2,4],[6,5],[3,2],[5,1],[1,3]]))
```

# Answer
> 0 votes
# Python 2, ~~94, 91~~, 88 bytes

```
for s,f in input():print"A A# B C C# D D# E F F# G G#".split()[([7,2,10,5,0,7][s]+f)%12]

```

There are probably some obvious improvements to be made. Input is a list of pairs, and the strings are 0-indexed, e.g:

```
[0, 4], [3, 2], [4, 6]...

```

# Answer
> 0 votes
# PHP, 102 Bytes

```
<?foreach($_GET[i]as$t)echo[E,F,"F#",G,"G#",A,"A#",B,C,"C#",D,"D#"][[0,7,3,10,5][$t[0]%5]+$t[1]%12]._;

```

Input as multiple array both 0 based for example '\[\[2,0\],\[5,3\],\[2,12\],\[3,8\],\[0,3\]\]'

Nice alternative 106 Bytes to set the # based on mod 7 congruent

```
<?foreach($_GET[i]as$t)echo EFFGGAABCCDD[$d=[0,7,3,10,5][$t[0]%5]+$t[1]%12].["","#"][$d%7?$d%7%2?0:1:0]._;

```

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


title: Leibniz golf in C#

text:
# Question
Title: Leibniz golf in C#
I'm starting with golf code. But im only do C# so I know wont be a breaking record, but I want give it a try. Leibniz

Challenge is here

The first line contains the number of test cases (N) which is less than 100. Each additional line is a test case for a positive integer value (T) less than 10^7.

I format the code to easy the reading, removing spaces I reduce it to 210 chars. The best code submit for this problem is 54 char, but For C# lenguaje the best is 172 chars.

My guess is should remove reading the N, but couldn't make it stop properly.

```
using System;
class S
{
    static void Main()
    {
        int n=Convert.ToInt32(Console.ReadLine()),i=0;
        for (;i++<n;)
        {
            double r=0,t=Convert.ToInt32(Console.ReadLine()),j=0;
            for(;j<t;)
                r+=(1-j%2*2)/(2*j+++1);
            Console.WriteLine(r);
        }
    }
}

```

**NOTE**

Mono C# compiler 3.2.8.0 .NET 4.0 CLR
So `using C=System.Console` doesn't work.

# Answer
As I suggested in a comment on VisualMelon's answer, the second `for` loop is being underutilised. By changing some variable scopes it's possible to use the `for`s in such a way that we save one set of curly brackets and one variable, and perform the sum in the correct order, fixing the bug in the supplied code.

Golfed:

```
using C=System.Console;class S{static void Main(){for(double n=int.Parse(C.ReadLine()),r,t;n-->0;C.WriteLine(r))for(r=0,t=2*int.Parse(C.ReadLine());t>0;t--)r-=(1-t%4)/--t;}}

```

Online demo

Ungolfed:

```
using C = System.Console;
class S {
    static void Main() {
        for (double n=int.Parse(C.ReadLine()), r, t; n-- > 0; C.WriteLine(r))
            for (r=0, t=2*int.Parse(C.ReadLine()); t>0; t--)
                r -= (1-t%4) / --t;
    }
}

```
> 7 votes

# Answer
Couple of simple things that apply in lots of places:

1. You've got a free semi-colon in your first for loop which you can make use of
2. You keep track of `i` against `n`, but you as you never use the value of `n`, you can use it as the counter itself.
3. As someone else said, you can use `int.Parse` (or `double.Parse`) instead of the Convert namespace/class/whatever it is - this makes your `using System` directive less helpful, and you are better of using the classic `using C=System.Console` (unless C# 6 has come out, I can't say I'm sure, in which case you can `using System.Console` directly)
4. There is an unneeded space after the first for (not sure if you'd accounted for this or not)

I haven't tested this code, but hopefully it will at least help:

```
using C=System.Console; // 3

class S
{
    static void Main()
    {
        for(int n=int.Parse(C.ReadLine()); // 1, 3, 4
            n-->0;) // 2
        {
            double r=0,t=int.Parse(C.ReadLine()),j=0; // 3
            for(;j<t;)
                r+=(1-j%2*2)/(2*j+++1);
            C.WriteLine(r); // 3
        }
    }
}

```

Is it possible that the shorter C# solution disregards the first line, and just assumes the input is clean? May well be cheaper to do that if it is allowed.

This is just a quick reply, I might have a better bash at this tomorrow when I have less going on.
> 3 votes

# Answer
* Instead of `Convert.ToInt32`, use `int.Parse`; it saves a few characters.
* Unless you really need a double, use a `float`; it's one char shorter than `double`.
> 2 votes

# Answer
## 172 Characters

The permanent version of the challenge can be found here. I have the shortest solution for C#, which is 172 characters.

### Golfed

```
using R=System.Console;class C{static void Main(){R.ReadLine();for(double s,n,j;;){for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;){s+=(j%2<1?1:-1)/(2*j+++1);}R.WriteLine(s);}}}

```

### Ungolfed

```
using R=System.Console;
class C
{
    static void Main()
    {
        R.ReadLine();
        for(double s,n,j;;)
        {
            for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;)
            {
                s+=(j%2<1?1:-1)/(2*j+++1);
            }
            R.WriteLine(s);
        }
    }
}

```

It does error out on the last loop, but it's after outputting all test cases.

# Edit

Seeing it ungolfed like this, just realized I can inline the for loop.

## 170 characters

### Golfed

```
using R=System.Console;class C{static void Main(){R.ReadLine();for(double s,n,j;;){for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;)s+=(j%2<1?1:-1)/(2*j+++1);R.WriteLine(s);}}}

```

### Ungolfed

```
using R=System.Console;
class C
{
    static void Main()
    {
        R.ReadLine();
        for(double s,n,j;;)
        {
            for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;)
                s+=(j%2<1?1:-1)/(2*j+++1);
            R.WriteLine(s);
        }
    }
}

```

# Edit 2

@PeterTaylor's answer has some fantastic logic. Cleaned it up a bit, and I'm still using exceptions for control flow.

## 155 characters

### Golfed

```
using R=System.Console;class C{static void Main(){R.ReadLine();for(double s,n;;R.WriteLine(s))for(s=0,n=2*int.Parse(R.ReadLine());n>0;n--)s-=(1-n%4)/--n;}}

```

### Ungolfed

```
using R = System.Console;
class C
{
    static void Main()
    {
        R.ReadLine();
        for(double s, n;; R.WriteLine(s))
            for(s = 0, n = 2 * int.Parse(R.ReadLine()); n > 0; n--)
                s -= (1 - n % 4) / --n;
    }
}

```

I really wish I could get rid of the extra ReadLine().
> 1 votes

---
Tags: code-golf, tips, c#
---