title: [Br]eaking Code Golf [Ba]d

text:
# Question
Title: [Br]eaking Code Golf [Ba]d
Consider the following string:

```
Tin Snips

```

This string contains several atomic symbols on the periodic table. We could rewrite this string to identify several of them:

```
[Ti][N] [Sn][I][P][S]

```

Of course, we could also write it this way:

```
T[In] [S][Ni][P][S]

```

The rules for rewriting the input are as follows:

1. The case of the input does not matter in terms of matching atomic symbols.
2. If an element is used in an atomic symbol, its case must change so the symbol is correct. Ex: `h` would become `[H]`.
3. All element symbols are encased in ASCII square brackets, `[` and `]`.
4. Whitespace is preserved: `Big ego` cannot combine the "g" and "e" into `[Ge]`.
5. Not all input characters need be combined into an atomic symbol: if an input character is not put into a symbol, it is passed through as-is (case does not matter).
6. If a symbol can be made, it *must* be made. In other words, it is not allowed to output `Tin` in the above example because it is possible to create at least one symbol in that word. The only time a character may be passed through unused is when it cannot be used to construct an atomic symbol.
7. For the purposes of this challenge, all elements from Hydrogen (1) to Oganesson (118) are valid. No higher elements are valid.
8. Some of the higher elements have ambiguous names and symbols: for the purposes of this challenge, the version at Wikipedia shall be used. For convenience, the allowable atomic symbols are here: H, He, Li, Be, B, C, N, O, F, Ne, Na, Mg, Al, Si, P, S, Cl, Ar, K, Ca, Sc, Ti, V, Cr, Mn, Fe, Co, Ni, Cu, Zn, Ga, Ge, As, Se, Br, Kr, Rb, Sr, Y, Zr, Nb, Mo, Tc, Ru, Rh, Pd, Ag, Cd, In, Sn, Sb, Te, I, Xe, Cs, Ba, La, Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb, Lu, Hf, Ta, W, Re, Os, Ir, Pt, Au, Hg, Tl, Pb, Bi, Po, At, Rn, Fr, Ra, Ac, Th, Pa, U, Np, Pu, Am, Cm, Bk, Cf, Es, Fm, Md, No, Lr, Rf, Db, Sg, Bh, Hs, Mt, Ds, Rg, Cn, Nh, Fl, Mc, Lv, Ts, Og.

Write a program or function that generates all possible outputs from a single provided input. Both input and output may be in any form of your choosing. This could be a string, array of characters, or some other data structure: whatever is both convenient and clearly represents the input and output. Both input and output may be passed in/out of your code however you choose: standard in/out, function argument/return, or something else.

* Input shall be a string (see previous paragraph) of positive length containing only ASCII characters of arbitrary case and the space (`0x20`) character.
* Your code must generate all output strings that can be created using the input rules above.
* The order of the output is implementation-defined. The only requirement is that *all* output strings are present.
* If presented with a valid input string that does not contain any atomic symbols, simply output the input string.
* If presented with an input string that is not valid per the rules above (null, zero characters, contains illegal characters, etc.) your program may do anything (crash, blank output, etc.)
* Output is case-insensitive other than atomic symbols needing to match the periodic table.
* Standard loopholes not allowed.

Test cases:

```
Tin Snips
[Ti][N] [Sn][I][P][S]
[Ti][N] [S][Ni][P][S]
[Ti][N] [S][N][I][P][S]
T[In] [Sn][I][P][S]
T[In] [S][Ni][P][S]
T[In] [S][N][I][P][S]
T[I][N] ...

Quack
Q[U][Ac][K]
Q[U]a[C][K]

hehe
[H]e[H]e
[H]e[He]
[He][H]e
[He][He]

Stack Exchange
[S][Ta][C][K] Ex[C][H]a[N][Ge]
[S]t[Ac][K] Ex[C][H]a[N][Ge]

```

This is code golf, so let me see your shortest code!

# Answer
> 5 votes
# Python 3, ~~289~~ 263 bytes

Found a more complete library on Pypi: `mendeleev`

```
from mendeleev import*
Z={element(i).symbol for i in range(1,119)}
L,R='[]'
def f(h,r=''):t=h.title();return((Z&{t[0]}and f(h[1:],r+L+t[0]+R)or[])+(Z>{(t+L)[:2]}and f(h[2:],r+L+t[:2]+R)or[])+(not{(r[-1:]+t[0]).title(),t[0]}&Z and f(h[1:],r+h[0])or[]))if h else[r]

```

Old answer:

```
from elements import*
Z={e.symbol for e in ELEMENTS}|{*'Cn Ds Fl Lv Mc Nh Og Rg Ts'.split()}
L,R='[]'
def f(h,r=''):t=h.title();return((Z&{t[0]}and f(h[1:],r+L+t[0]+R)or[])+(Z>{(t+L)[:2]}and f(h[2:],r+L+t[:2]+R)or[])+(not{(r[-1:]+t[0]).title(),t[0]}&Z and f(h[1:],r+h[0])or[]))if h else[r]

```

Uses a library `elements.py` from http://www.lfd.uci.edu/~gohlke/code/elements.py.html. It is missing elements 110 to 118, but it was the most up to date library I could find. Cost 40 bytes to add the missing elements.

The trickiest part was the logic for when a character can be passed through without being part of an element symbol.

# Answer
> 3 votes
# Jelly,  ~~192~~  191 bytes

-1 by use of `Ɗ` (a since-developed quick)

```
“¦UV2ḤF2ı½ṅḶḊ⁼5JI5MẇvẋẊẊ¬Ḥḳ'ƈ<ḷėƤ7*⁾ṾxMæS⁺`?^Ƭb¦ɗDß⁼pþɲOṃ⁽2Ė>,Ḣ(ḞŒƊOGƤ×⁺ṇṂ®ȤT0y°^Ẇ⁺:Þ]ṢṬ¶ịṪḂƇ ñAƬCṫ$wÆĿĖỴỴƇẓƊqḌ@;ẏ`ṃFƥḣ⁽²»ḟ⁶s2;“¤²R.ȯ7ŒL£ɦ»Œt
Œte¢
ŒṖµL€=1oÇ€ṂµÐfµṡ2;€ÇÐfÇ€€S€¬SµÐḟ⁾[]jŒtƊ¹Ç?€€

```

**Try it online!** \- Too inefficient for the "Stack Exchange" test case to complete within the 60s limit (running it offline gives the correct result within 2 minutes).

### How?

The first line of code is a niladic link to create a list containing all 118 element symbols. To do so it concatenates two lists, the first containing all length 2 lists of characters (i.e. strings) the second a list of characters and title cases the resulting list. The two lists themselves are created mostly by looking up words in Jelly's dictionary to make single strings.

The first of these compressions is:

```
“¦UV2ḤF2ı½ṅḶḊ⁼5JI5MẇvẋẊẊ¬Ḥḳ'ƈ<ḷėƤ7*⁾ṾxMæS⁺`?^Ƭb¦ɗDß⁼pþɲOṃ⁽2Ė>,Ḣ(ḞŒƊOGƤ×⁺ṇṂ®ȤT0y°^Ẇ⁺:Þ]ṢṬ¶ịṪḂƇ ñAƬCṫ$wÆĿĖỴỴƇẓƊqḌ@;ẏ`ṃFƥḣ⁽²»

```

which yields

```
" biznagas sepmag ratbag catchflies paracmes mdse bharal ramcat monopteros irrepressibilities lunarnauts geniculate hopbinds rutabaga potlache broghs bergamas crossbirth purblind xebecs nonhardy classism fleurets moneybag scarce corf Mg Sr Zr CD HG CF FM Lr SG TM Gd Bk Fr Rh Fe Sn lv cndbmnnbkrmtpdnp"

```

Where all but the final entry (split by spaces) are entries in Jelly's dictionary. The spaces are filtered out with `ḟ⁶`, and then the result is split into twos:

```
["bi","zn","ag","as","se","pm","ag","ra","tb","ag","ca","tc","hf","li","es","pa","ra","cm","es","md","se","bh","ar","al","ra","mc","at","mo","no","pt","er","os","ir","re","pr","es","si","bi","li","ti","es","lu","na","rn","au","ts","ge","ni","cu","la","te","ho","pb","in","ds","ru","ta","ba","ga","po","tl","ac","he","br","og","hs","be","rg","am","as","cr","os","sb","ir","th","pu","rb","li","nd","xe","be","cs","no","nh","ar","dy","cl","as","si","sm","fl","eu","re","ts","mo","ne","yb","ag","sc","ar","ce","co","rf","Mg","Sr","Zr","CD","HG","CF","FM","Lr","SG","TM","Gd","Bk","Fr","Rh","Fe","Sn","lv","cn","db","mn","nb","kr","mt","pd","np"]

```

The second,

```
“¤²R.ȯ7ŒL£ɦ»

```

is formed from the concatenation of the words "finch", "pub", "sky", and "vow" (without spaces), and as such is a list of characters:

```
['f','i','n','c','h','p','u','b','s','k','y','v','o','w']

```

The two lists are concatenated with `;` and every entry is title-cased using `Œt`, yielding:

```
["Bi","Zn","Ag","As","Se","Pm","Ag","Ra","Tb","Ag","Ca","Tc","Hf","Li","Es","Pa","Ra","Cm","Es","Md","Se","Bh","Ar","Al","Ra","Mc","At","Mo","No","Pt","Er","Os","Ir","Re","Pr","Es","Si","Bi","Li","Ti","Es","Lu","Na","Rn","Au","Ts","Ge","Ni","Cu","La","Te","Ho","Pb","In","Ds","Ru","Ta","Ba","Ga","Po","Tl","Ac","He","Br","Og","Hs","Be","Rg","Am","As","Cr","Os","Sb","Ir","Th","Pu","Rb","Li","Nd","Xe","Be","Cs","No","Nh","Ar","Dy","Cl","As","Si","Sm","Fl","Eu","Re","Ts","Mo","Ne","Yb","Ag","Sc","Ar","Ce","Co","Rf","Mg","Sr","Zr","Cd","Hg","Cf","Fm","Lr","Sg","Tm","Gd","Bk","Fr","Rh","Fe","Sn","Lv","Cn","Db","Mn","Nb","Kr","Mt","Pd","Np","F","I","N","C","H","P","U","B","S","K","Y","V","O","W"]

```

A list containing all 118 element symbols as required (there are duplicates, but that's fine).

The second line of code is a monadic link (a helper function designed to take one input) that returns a 1 if the input, titled-cased exists in the list created above and a 0 otherwise.

The third line of code is the main link, a monadic function that takes a string and returns a list of lists of characters (i.e. strings) as required:

```
ŒṖµL€=1oÇ€ṂµÐfµṡ2;€ÇÐfÇ€€S€¬SµÐḟ⁾[]jŒtƊ¹Ç?€€ - Main link: s
ŒṖ                                           - all partitions of s
  µ        µÐf                               - filter keep:
   L€=1                                      -     length €ach equals (vectorises) 1
       o                                     -     or
        Ç€                                   -     last link as a monad (is an element when title-cased)
          Ṃ                                  -     minimum
                                             - (i.e. all partitions that are all single characters OR are strings that when title-cased are elements)
              µ              µÐḟ             - filter discard:
               ṡ2                            -     slices of length 2
                 ;€                          -     concatenate €ach
                    Ðf                       -     filter keep:
                   Ç                         -         last link as a monad (is an element when title-cased)
                      Ç€€                    -     last link as a monad for €ach for €ach
                         S€                  -     sum €ach
                           ¬                 -     logical not
                            S                -     sum
                                             - (i.e. discard any partitions that contain a run of two that joined together and title-cased ARE an element but separately NEITHER are)
                                         ?€€ - if then else for €ach (partition) for €ach (part):
                                        Ç    -     IF: last link as a monad (is an element when title-cased)
                                             -   THEN:
                                      Ɗ      -         last three links as a monad:
                                ⁾[]                      "[]"
                                   j         -           joined by:
                                    Œt       -           title case the part
                                             -   ELSE:
                                       ¹     -         the part itsef (¹ is the identity atom)

```

# Answer
> 1 votes
# C++11, ~~944~~ 928 bytes

Here's a piece of truly terrible code, but it should work. Could still be made a lot shorter probably.

```
#import<iostream>
#import<set>
using namespace std;int r,i;set<string>O;S(string&s){s[0]-=s[0]>90?32:0;if(s[1])s[1]+=s[1]<91?32:0;char*l="HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg";for(r=0;*l++;)if(*l>90){if(*(l++-1)==s[0]&&*(l-1)==s[1])r=1;}else if(*(l-1)==s[0]&&!s[1])r=1;}P(set<string>*V,string s,string o,int b,int l=0,int m=0){if(!s[b])O.insert(o);else if(l)P(V,s,o,b+1);else if(V[b].size()==0)P(V,s,o+s[b],b+1);else for(auto t:V[b]){P(V,s,o+"["+t+"]",b+1,t.length()-1);if(t.length()>1&&V[b].size()==1&&V[b+1].size()>0&&!m)P(V,s,o+s[b],b+1,0,1);}}F(string s){set<string>V[s.length()];for(i=0;s[i++];){string t="";t+=s[i-1];S(t);if(r)V[i-1].insert(t);t+=s[i];S(t);if(r&&s[i])V[i-1].insert(t);}P(V,s,"",0);for(auto o:O)cout<<o<<"\n";O.clear();}

```

Call with:

```
int main()
{
    F("Tin Snips");cout << "\n";
    F("Quack");cout << "\n";
    F("hehe");cout << "\n";
    F("Stack Exchange");
}

```

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


title: Back-To-Front Permutation Index

text:
# Question
Title: Back-To-Front Permutation Index
### The Challenge

Given the number of items, `n`, in a non-empty, sorted list output the index, `i(n)`, at which its
"*Back-To-Front Permutation*"
would reside in a list of all permutations if said permutations were sorted lexicographically.

Results may be 0 or 1-based, just say which (that is `i`, not `n`).

### The Back-To-Front Permutation

...is the result of building a list of items by repeatedly taking the back (right) then front (left) of a forward sorted (left-to-right) list until all items have been moved to the new list, like so:

```
Input being consumed     Output being built
----------------------+----------------------
[1,2,3,4,5,6,7]       |   []
[1,2,3,4,5,6]         |   [7]
  [2,3,4,5,6]         |   [7,1]
  [2,3,4,5]           |   [7,1,6]
    [3,4,5]           |   [7,1,6,2]
    [3,4]             |   [7,1,6,2,5]
      [4]             |   [7,1,6,2,5,3]
       []             |   [7,1,6,2,5,3,4]
----------------------+----------------------
                Result:   [7,1,6,2,5,3,4]

```

### The Permutation Index

If `n` is `7` (as the above Back-To-Front example) there are `7! = 5040` possible permutations of the (distinct) items.

The first (or zeroth if you prefer) item in the lexicographically sorted list of all those permutations would be `[1,2,3,4,5,6,7]` itself.
The second item would be `[1,2,3,4,5,7,6]`.
The penultimate item would be `[7,6,5,4,3,1,2]`.
The final item would be `[7,6,5,4,3,2,1]`.

Somewhere in the list is `[7,1,6,2,5,3,4]` \- the Back-To-Front permutation.
In fact it resides at index 4421 (or 4420, 0-based).

The first 100 terms of the (1-based) series of `i(n)` stating with `n=1` are:

```
[1, 2, 5, 20, 101, 620, 4421, 35900, 326981, 3301820, 36614981, 442386620, 5784634181, 81393657020, 1226280710981, 19696509177020, 335990918918981, 6066382786809020, 115578717622022981, 2317323290554617020, 48773618881154822981, 1075227108896452857020, 24776789629988523782981, 595671612103250915577020, 14915538431227735068422981, 388375922695377900515577020, 10500493527722974260252422981, 294387851083990886241251577020, 8547374142655711068302364422981, 256705485669535347568006115577020, 7966133168508387470157556764422981, 255164703765185142697060455395577020, 8428152915046701352821133945884422981, 286804646124557439494797475697635577020, 10046343320261587490171853861825564422981, 361946983469639629977827594289009635577020, 13401806107756705416338151987291892764422981, 509620811358844406343669072112782398435577020, 19888261269838598952296612667790114958364422981, 796027021978059135393314656928325779313635577020, 32656499591185747972776747396512425885838364422981, 1372349618161694150570365858847999144050545635577020, 59042913445212141486784766209665998363213966364422981, 2599228661343236626556841044804949891956424561635577020, 117022992204136957935406320450852765172427309198364422981, 5385599167607951991914899108349402127789224443761635577020, 253237642343560228651049456045262577841408407945358364422981, 12160677950192512442211239591328112460680077946732401635577020, 596121186084075048430040923729967264426872753432477838364422981, 29817972015629302995182567242334801579950768815528034161635577020, 1521300781271752977229060449226968409483308951201458077838364422981, 79136874389672125594431576407176798565806196489681819746161635577020, 4195746409670353438703582176982222851124537591877131904925838364422981, 226647950929571027033389160506045358232154026979930809227362161635577020, 12469755402728704898931711687060471601348167024469505953048477838364422981, 698528832402134746955113935776664478135149811856698952734398562161635577020, 39828390672475082008725487969655657656845234984369903192450082717838364422981, 2310732940610403489820749422545419026172017083196773021228249831522161635577020, 136372385605079432248118270297843987319730859689490659519593045108637838364422981, 8184614727136310712028222912925520393434441746671755292929684651300962161635577020, 499395599150088488088828589263699706832570087241364247806476254829684637838364422981, 30970577661237849037564293765687064381179710710016867944356691992991422562161635577020, 1951637737743202215078582414596211073163593979517251760161922907619738331037838364422981, 124935294448140961888354806920565269729701922195027940438639971467594965899362161635577020, 8122715297634329704834815499864930982456556629150409552483483162921360809076637838364422981, 536222223779808734298894424747977821661836507759648464980376643706749720339339362161635577020, 35934888694408876553950964671857486605505798806289876128721251856561212716604532637838364422981, 2444100653742421723047039453897314094441893402549077796242989486161660232995578763362161635577020, 168678351774398889649421299427375524997828651490971291597405051437095619521145068660637838364422981, 11809893318195492906423362422261723211461109491055454565957957813190913963268700251019362161635577020, 838668695249666824614744281817664287077123498629740781320472805575397766414810317446260637838364422981, 60395789681636420036909326103457008453700968286067588202502542158402987220806878956757899362161635577020, 4409719671831047920854347812021594101623099731996837427616577550212019116846376438060145780637838364422981, 326378824480107593305098680409232188044060152088938133742995349285199216584125189021190726539362161635577020, 24482761986915290498641378436184801472882183734481184704052899163370643460988742220422624697460637838364422981, 1861011939679134964489290882424961756757512351644848150968435083798473400034549180897307347526539362161635577020, 143322080088606734669581493203883323226982866872563510695813139604263517949121870899167900513721460637838364422981, 11180959098117691096787939665528162905504766712615688479353149686064571807285078895345918312663622539362161635577020, 883437253980179837588356231874303489164303450066956218734514913541773418886216781638015892528346553460637838364422981, 70686019792283622457223177491312228676420353892298796358374930144685265836593932061030928974752467526539362161635577020, 5726440000955084363422511054086796876735936890839327162387490119571704913857298124195153605274993472953460637838364422981, 469637893700329090478715695935318149767077357177154001454773443957172289821041850488811978203204173646406539362161635577020, 38985601803506257421418755484185292421669426050466292273769584084412579273175587484390779961900566697260473460637838364422981, 3275254532761847009577968823645945995578996860191583194845076448298646552018541276645494943006816186458917446539362161635577020, 278435156905293180685369975402415213484477637470382623210256836304261379607777392174394791509334107831816205753460637838364422981, 23948660226767439201080153228038844501800392914958999127628507660415900870134672884615069843391985357739844389446539362161635577020, 2083808638152760278012520365471350750727983345146397213195344003554238214857458501196068353393022808146994627392953460637838364422981, 183398833619245678836784325280074933629492985604252949471226236983335323969170740817904072891411479020269638889458246539362161635577020, 16324556327289215402380134937173544376210173250892288905442294470849835710409338998582008497896189183708810744110298553460637838364422981, 1469391408154472281907142598683652193509359788033796478036774569234135557383656537547410122872987870461908423725867813446539362161635577020, 133730761359685823973259426160811489954077506688872881313704960027919535214176338228137873831877461557289259913042140378553460637838364422981, 12304683293281621431502064899712741587623914209186541475526534622910218175769343180214908250005163885795818227069614613285446539362161635577020, 1144467823788359953327703097406527694627129315367226993710615746590336588945697972034988381266839681418043178062317463477466553460637838364422981, 107592147841885948074037582159380073309559674264815645313786758687454863280472229658194120833316575777142822473140067877053221446539362161635577020, 10222386340397173314525664517235347022088186665852557223898463812546839124314230895213571254552107892786139414391086539473362138553460637838364422981, 981455548530552515895045737024658454136095461985415238220477591025945383684777269092475904782448641089288955324574667766166512421446539362161635577020, 95211304133951567337433380212539040258207718457187560919883999728307800228797098229713403270806624010171995234355103499880901319898553460637838364422981, 9331679144749296178288752362844703433551486045621764102574354777566399269794426700653262755936922495813433855354253356929531746247461446539362161635577020, 923930475294692230638703636199822301473608196598194450583355284174609600662504729388761377005628260366723545352917984225582320362921178553460637838364422981, 92402284968649460451060535220066878189242360067783427018009608611042990392567410879552702599150890025886974375474305774025602890553942821446539362161635577020

```

(`i(0)=i(1)=1`, but the challenge itself only deals with non-empty lists)

At the time of posting this sequence did not appear in the OEIS.

Output must only need to work in theory (don't worry about overflowing integers, or running out of resources for example).

This is , so the shortest answer in bytes wins.

However, don't let code-golf languages dissuade you - good solutions should get upvotes too!

# Answer
# Haskell, 32 bytes

```
f 1=1
f n=product[1..n]+1-f(n-1)

```

Try it online!

Uses the relationship `f(n-1) + f(n) = n! + 1`. Adjacent members of the sequences add to factorials plus one:

```
1,   2,   5,   20,   101,   620,   4421, ...
  3     7    25    121    721   5041  ...
 2!+1  3!+1  4!+1  5!+1   6!+1  7!+1

```
> 8 votes

# Answer
# Jelly, 6 bytes

```
R!ḅ-_Ḃ

```

0-based. Try it online!

Heavily inspired by @Neil's ES6 answer.

### Explanation

```
R!ḅ-_Ḃ
R       Create the range [1..N].
 !      Take the factorial of each.
  ḅ-    Convert from base -1; that is, sum, but alternate between adding and subtracting.
    _Ḃ  Subtract N%2.

```

### But how?

I explain in my ES6 answer a related technique for calculating each number. The formula is this:

```
(n-1)(n-1)! + (n-3)(n-3)! + (n-5)(n-5)! + ...

```

A realization struck me while reading @Neil's ES6 answer. This formula can be simplified like so:

```
(n-1)(n-1)!        + (n-3)(n-3)!            + (n-5)(n-5)!            + ...
(n(n-1!) - (n-1)!) + ((n-2)(n-3!) - (n-3)!) + ((n-4)(n-5)! - (n-5)!) + ...
(n!      - (n-1)!) + ((n-2)!      - (n-3)!) + ((n-4)!      - (n-5)!) + ...
n! - (n-1)! + (n-2)! - (n-3)! + (n-4)! - (n-5)! + ...

```

The Jelly code `R!ḅ-` calculates this formula. However, each odd value of `n` will have an extra `+ 0!` at the end, which we take care of by subtracting `n%2`.
> 6 votes

# Answer
## JavaScript (ES6), 38 bytes

```
f=(n,x=n%2,y=1)=>n-x&&f(n,++x,y*=-x)+y

```

0-indexed. (No explanation because I don't actually know why it works, sorry.)
> 4 votes

# Answer
# JavaScript (ES6), 44 bytes

```
f=(x,n=0,g=1)=>x-n&&(x-n&1)*g*n+f(x,++n,g*n)

```

0-based. This takes advantage of the fact that the numbers can be represented as sums of factorials in the following pattern:

```
       1   2   6  24 120 720
   0:
   1:  1
   4:      2
  19:  1       3
 100:      2       4
 619:  1       3       5
4420:      2       4       6

```

Why? The permutations can be represented nicely in the factorial base: taking the **n**th item out of the remaining list corresponds to a digit of **n** at that position. We're alternating between taking the *last* item (highest digit) and the *first* item (zero); therefore, in the factorial base, these numbers can be represented as:

```
0
10
200
3010
40200
503010
6040200

```

and so on.
> 3 votes

# Answer
# MATL, 17 bytes

```
:t"&0)P]vG:Y@!=Af

```

Output is 1-indexed.

Try it online!

### Explanation

The code appplies the definition: builds the back-to-front permutation, generates all permutations, compares the former with all of the latter, and outputs the index of the matching.

```
:        % Input n implicitly. Push [1 2 ... n]
t        % Duplicate
"        % For each: do the following n times
  &0)    %   Push the last element and then the rest of the array
  P      %   Reverse
]        % End
v        % Concatenate the whole stack vertically. This produces into a column vector
         % with the back-to-front permutation
G:       % Push [1 2 ... n] again
Y@!      % Permutations of [1 2 ... n]. Gives a matrix. Each column is a permutation
=        % Test for equality, element-wise with broadcast
A        % All: true for columns that have all entries equal to true. Gives a row vector
f        % Find: index of non-zero value. Implicitly display

```
> 2 votes

# Answer
# Jelly, ~~10~~ 8 bytes

```
RṚżRFQŒ¿

```

*Thanks to @ais523 for golfing off 2 bytes and a tremendous speed-up!*

Try it online!

### How it works

```
RṚżRFQŒ¿  Main link. Argument: n

R         Range; yield [1, ..., n].
 Ṛ        Reverse; yield [n, ..., 1].
   R      Range; yield [1, ..., n] again.
  ż       Zip; yield [[n, 1], ..., [1, n]].
    F     Flatten.
     Q    Unique; deduplicate the results.
      Œ¿  Compute the permutation index of [n, 1, n-1, 2, ...].

```
> 2 votes

# Answer
# Jelly, 9 bytes

```
RU;¥/ỤUŒ¿

```

Try it online!

Huh, I was trying to FGITW this. Turns out @Dennis posted first, but this is shorter.

## Explanation

```
RU;¥/ỤUŒ¿
R           List of numbers from 1 to {the input}
   ¥/       Left-fold the list by
 U;         prepending the reverse of the list to the next element
     Ụ      Invert permutation
      U     Reverse the list
       Œ¿   Find index of permutation

```

Having `Œ¿` as a built-in is fairly handy here letting us convert a permutation to its index, so the other 7 bytes are responsible for constructing the back-to-front permutation.

The way we do this is first to construct a different permutation, via the following pattern:

```
1
1 2
2 1 3
3 1 2 4
4 2 1 3 5
5 3 1 2 4 6
6 4 2 1 3 5 7

```

Each time, we're reversing the list we have so far, then appending the next integer. That doesn't produce the back-to-front permutation, but it's clearly related.

The permutation we're *trying* to get is `7 1 6 2 5 3 4`. How is this related? Well, the element in the 7th position of the permutation we have is a 7; the element in the 1st position is a 6; the element in the 6th position is a 5; the element in the 2nd position is a 4, and so on. In other words, it's the inverse of the permutation we have (with the elements in reverse order). As such, after the reduce, we can invert the permutation with  and reverse the result with `U` to get the back-to-front permutation we want.

It's possible that there are savings here, because it was written in a hurry and feels like it has at least some potential to rearrange things. I'm not sure it's possible to save a whole byte, though.
> 2 votes

# Answer
# PHP, 86 bytes

```
for($i=$argv[1];$i>0;$i--)$o+=gmp_strval(gmp_fact($i))*($i%2==$argv[1]%2?1:-1);echo$o;

```

Uses the GNU Multiple Precision extension.

This function takes advantage of the fact that `i(n)` is equal to `n! - (n-1)! + (n-2)! - (n-3)! etc`

**Breakdown**

```
for($i=$argv[1];$i>0;$i--) {        // Simple decreasing for loop (added { for readability)
    $o+=                            //  increment output with
        gmp_strval(gmp_fact($i))    //      $i!
    * ($i%2 == $argv[1]%2 ? 1 : -1) //      multiplied by -1 if ($i is odd when the input is even) or (if $i is even when the input is odd), else by 1
    ;
}
echo $o;                            // echoes output

```
> 0 votes

# Answer
## Batch, 79 bytes

```
@set/ax=%1%%2-1,y=z=1
@for /l %%i in (-%1,1,%x%)do @set/az+=y*=x-=1
@echo %z%

```

0-indexed.
> 0 votes

# Answer
# Pyth, 12 bytes

```
x.pQ<Q.i_UQU

```

0-indexed.

### Explanation

```
x.pQ<Q.i_UQU
      .i       Interleave
        _UQUQ  Reversed range and range
    <Q         Take first n
x              Find the index
 .pQ           In the list of permutations

```
> 0 votes

---
Tags: code-golf, sequence, sorting, permutations
---


title: Grids can be curvy. How long is yours?

text:
# Question
Title: Grids can be curvy. How long is yours?
Consider depicting a simple, open, two-dimensional curve on a W wide by H high grid of text where `X` represents part of the curve and `.` represents empty space and no other characters are used.

Every grid space has 8 neighboring grid spaces, its Moore neighborhood. Grid spaces beyond the borders are considered empty.

A grid contains a *curve* if it has exactly one `X` *OR* if it has more than one `X` where:

* Exactly two `X`s have only one neighboring `X`. These are the curve's endpoints.
* Every `X` besides the endpoints neighbors exactly two `X`s. These form the bulk of the curve.

> For example, this grid where W = 9 and H = 4 contains a curve:
>
> ```
> ....X....
> .X.X.X.X.
> X..X..X.X
> .XX.....X
>
> ```
>
> Likewise, these grids (W = 4, H = 3) have curves:
>
> ```
> ....  .X..  ....  ....  .X.X
> ....  X..X  ..X.  XX..  X.X.
> ..X.  .XX.  .X..  ....  ....
>
> ```
>
> These grids, however, do not contain a curve:
>
> ```
> ....  .XX.  ...X  XX..  ....  X.X.
> ....  X..X  ..XX  XX..  .X.X  .X..
> ....  .XX.  .X..  ....  ...X  X.X.
>
> ```

We can find the length of a curve by summing the distances between all neighboring pairs of `X`s:

* The distance between two orthogonally neighboring `X`s is 1 unit.

```
XX
```

```
X
X
```
* The distance between two diagonally neighboring `X`s is √2 units.

```
X.
.X
```

```
.X
X.
```

> For example, the length of the curve in the grid
>
> ```
> XXX.
> ...X
> ..X.
>
> ```
>
> can be visualized as
>
> so we can see it is 1 + 1 + √2 + √2 = 4.828427...

The length of a curve with only one `X` is zero.

When a grid does not form a curve its length is not well defined.

# Challenge

**Given a grid of text of `X`s and `.`s, output the length of the curve it contains, or else output something such as `-1` or `Null` to indicate the grid has no curve.**

For input you may use other characters than `X` and `.` if desired, and H and W may be taken as input if needed. Input as a nested list or matrix filled with 1s and 0s instead of a string is also fine.

You may output a float for the curve length or alternatively two integers A and B where `length = A + B*√2`.

**The shortest code in bytes wins.**

# Test Cases

```
XXX.
...X
..X.
2 + 2*√2 = 4.828427...

....X....
.X.X.X.X.
X..X..X.X
.XX.....X
3 + 8*√2 = 14.313708...

....
....
..X.
0 + 0*√2 = 0

.X..
X..X
.XX.
1 + 3*√2 = 5.242640...

....
..X.
.X..
0 + 1*√2 = 1.414213...

....
XX..
....
1 + 0*√2 = 1

.X.X
X.X.
....
0 + 3*√2 = 4.242640...

....
....
....
....
-1

.XX.
X..X
.XX.
-1

...X
..XX
.X..
-1

....
.X.X
...X
-1

X.X.
.X..
X.X.
-1

```

# Answer
> 3 votes
# MATL, ~~52~~ 51 bytes

```
t2Y6~Z+*ssGt3Y6Z+*tt1=z2=wssGzqE=*Gz1=+?}_q]ssy-h2/

```

Input is a matrix of zeros and ones.

Output is `B`, then `A`. Non-curves give a negative `A`.

Try it online! Or verify all test cases.

### Explanation

**Computing the length of the curve** uses two 2D convolutions1: one with the Moore mask, and another with a mask containing only the diagonal neighbours. The results are two matrices with the same size of the input, which will be denoted as *M* and *D* respectively. *M* gives the total number of neighbours for each point, whereas *D* gives the number of diagonal neighbours.

The results in *M* and *D* must be filtered to discard points that don't belong to the curve. Also, they must be divided by 2, because "being neighbour of" is a a symmetric relation, so each point in the curve is counted twice.

**Determining if the curve is valid** is more cumbersome than I expected. To do this, the code tests three conditions:

1. Does the number of ones in *M* equal `2`? (That is, are thre exactly two points with a single neighbour?)
2. Does the total sum of *M* equal the number of points in the input curve times `2` minus `2`? (Together with condition 1, this tests if all non-zero values in *M* except two of them equal `2`)
3. Does the input curve contain a single point?

The curve is valid if conditions 1 and 2 are true, or if condition 3 is.

```
t       % Implicit input matrix of zeros and ones. Duplicate
2Y6~    % Push [1 0 1; 0 0 0; 1 0 1]
Z+      % 2D convolution, keeping size
*       % Multiply to zero out results for non-curve points. Gives matrix D
ss      % Sum of matrix D
Gt      % Push input again wtice
3Y6     % Push [1 1 1; 1 0 1; 1 1 1]
Z+      % 2D convolution, keeping size
*       % Multiply to zero out results for non-curve points. Gives matrix M
tt      % Duplicate twice
1=z     % Number of ones
2=      % Does it equal 2? This is condition 1
wss     % Swap. Sum of matrix
G       % Push input again
zqE     % Number of nonzeros values minus 1, and then multiplied by 2
=       % Are they equal? This is condition 2
*       % Multiply. This is a logical AND of conditions 1 and 2
G       % Push input again
z1=     % Does it contain exactly one nonzero value? This is condition 3
+       % Add. This is a logical OR with condition 3
?}      % If result was false
  _q    %   Negate and subtract 1. This makes sure we get a negative value
]       % End
ss      % Sum of matrix M
y       % Duplicate sum of matrix D from below
-       % Subtract
h       % Concatenate horizontally
2/      % Divide by 2. Implicitly display

```

---

1 Convolution is the key to success.

# Answer
> 1 votes
# Python 3, ~~316~~ ~~315~~ 311 bytes

I think this covers all cases; at least the test cases work.

Also, there surely is still a lot to golf down, probably in the beginning where the edge cases are handled.

```
def f(d,R,C):
 s=sum;d=[0]*(C+2),*[[0,*r,0]for r in d],[0]*(C+2);o=-1,0,1;k=[[[(1,0),(0,1)][i*j]for i in o for j in o if d[r+i][c+j]and i|j]for c in range(1,-~C)for r in range(1,-~R)if d[r][c]];w=[x/2for x in map(s,zip(*s(k,[])))]or[0,0];print([w,-1][s(w)!=s([s(z)for z in d])-1or[len(t)for t in k].count(1)>2])

```

Try it online!

How it works:

1. `d,R,C` are 1. a list of lists with 1 as curve and 0 as background, 2. row and column count
2. Insert a row of 0's before and after and a column of 0's before and after `d` so we don't have to worry about the edge of the 2d array
3. For every 1 in the 2d array, scan the neighbourhood for 1's and add (1,0) to a list if the relation is diagonal, else add (0,1)
4. Sum all tuples, so that (n,m) represents the number of diagonal and non-diagonal neighbours, respectively
5. Check if the number of relations is exactly the number of 1's minus one; if not, not a curve.

Thanks to @Helka Homba for pointing out a missing case. Thanks to @TuukkaX and @Trelzevir for the golfing tips.

# Answer
> 0 votes
# Mathematica, ~~153~~ 150 bytes

```
Switch[Sort[Join@@BlockMap[If[#[[2,2]]<1,Nothing,Tr[Tr/@#]]&,#~ArrayPad~1,{3,3},1]],{1},0,{2,2,3...},1/.#~ComponentMeasurements~"PolygonalLength",_,]&

```

Takes a 2D array, with `0`s for `.`s and `1`s for `X`s. Outputs `Null` for non-curves.

```
1/.#~ComponentMeasurements~"PolygonalLength"&

```

Mathematica has a 45-byte built-in for this, but it outputs some numbers for non-curves and 1/sqrt(2) for input `{{1}}`. Correcting these cost 105 bytes (could be golfed?).

---
Tags: code-golf, arithmetic, geometry, grid, graph-theory
---


title: Filter this string!

text:
# Question
Title: Filter this string!
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.

Let's say we received the string "123456781234567812345678", and the second string is "314159".

First, we put a pointer on the second string:

```
314159
^

```

So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:

```
##3456781234567812345678

```

We then move the pointer to the next character until we have iterated through the string.

# Specs

* You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).
* The second string will always be longer than enough.
* Both strings will only contain ASCII printable characters (U+0020-U+007F).

# Testcases

```
input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###

input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############

```

# Answer
# C#6, 112 bytes

```
string c(string h,string n)=>h==""?"":h[0]==n[0]?h[0]+c(h.Substring(1),n.Substring(1)):"#"+c(h.Substring(1),n);

```

Recursive function, takes haystack h (input1) and needles n (input2).

* If Haystack is empty, return it.
* if first characters of haystack and needle are equal, keep the first character and call recursively while skipping the first char on both parameters
* else return the replacement character (fixed to # here) followed by a recursive call again skipping the first character from haystack only.

Major factor for the length is the long name of Substring, but it's not long enough (compared to the number of usages) that a wrapping function would help to reduce further.
> 2 votes

# Answer
# Javascript ES6, 46 bytes

```
a=>b=>a.replace(/./g,x=>x==b[i]?(i++,x):0,i=0)

```

Uses `0` as the replacement char.
> 2 votes

# Answer
# Python 3, 69

```
def f(a,b,c=''):
 for x in a:y=x==b[0];c+=x*y or'#';b=b[y:]
 return c

```

Uses the hash for the replacement char, and take the original and replacement as a and b respectively.

Test case:

```
assert f('123456781234567812345678', '314159') == '##3#####1##4####1###5###'

```
> 2 votes

# Answer
# Python, 115 Bytes

```
n,f=input()
for a in str(f):
 x,r=0,""
 for b in str(n):
  if x==0and b==a:c,x="#",1
  else:c=b
  r+=c
 n=r
print n

```
> 1 votes

# Answer
# Ruby, 44 bytes

If someone helps me golf it down by any amount, then I can say crossed-out 44 is still 44

```
->s,r{s.gsub(/./){$&==r[0]?(r[0]='';$&):?#}}

```
> 1 votes

# Answer
# Perl, 77 bytes

```
sub _{$p=substr$f,0,1,''}($_,$f)=@ARGV;_;print map{$_ eq$p?_&&$_||$_:'#'}/./g

```
> 1 votes

# Answer
# , 18 chars / 23 bytes

```
îⓢ⒨≔í⟨Ḁ?(Ḁ⧺,$):0)⨝

```

`Try it here (Firefox only).`

Ayyy not bad. Uses 0 as the replacement char. It's just the same algorithm that I used in my JS answer.
> 1 votes

# Answer
I realize that there's already another JS-based solution posted using the `.replace` method that's shorter, but I'd like to submit my answers anyways...

## CoffeeScript, 55 bytes

Builds a string and returns it:

```
f=(a,b,i=0,s='')->s+=c==b[i]&&b[i++]||'#'for j,c of a;s

```

## JavaScript, 53 bytes

Operates on an array of characters from the original string:

```
f=(a,b,i=0)=>[...a].map(c=>c==b[i]?b[i++]:`#`).join``

```
> 1 votes

# Answer
# C, 81 bytes

```
A[99];char*b=A,*a=A+50;main(){gets(a),gets(b);while(*a)putchar(*a++^*b?35:*b++);}

```
> 1 votes

# Answer
# Haskell, 56 bytes

```
""%_="";(a:b)%l|a==head(l++"é")=a:b%(tail l)|0<1='#':b%l

```
> 0 votes

# Answer
## Mathcad, \[tbd\] bytes

---

Mathcad byte equivalence to be determined. Note that the programming operators "while", "break" and "on error" only require 1 key-combination to enter (ctl-\], ctl-{ and ctl-', respectively) - they cannot be typed verbatim. What you see in the image is exactly what gets entered onto the Mathcad worksheet and the results are live - change a or b, or the function arguments, and the results update accordingly.
> 0 votes

# Answer
# Java, 136 bytes

```
void i(int[]a,int[]b){int i=0,j=0,n=a.length;for(;i<b.length;i++)for(;j<n;j++)if(a[j]==b[i]){j++;break;}else a[j]=0;for(;j<n;)a[j++]=0;}

```

### Ungolfed

```
void i(int[] a, int[] b) {
    int i = 0, j = 0, n = a.length;
    for (; i < b.length; i++)
        for (; j < n; j++)
            if (a[j] == b[i]) {
                j++;
                break;
            } else a[j] = 0;
    for (; j < n; ) a[j++] = 0;
}

```

### Notes

* Uses the `NUL` character as replacement, any of the first 10 would do. If you wanted a visible replacement character, this would be one byte longer.
* Input are two integer arrays of charcodes. `int[]` is one byte shorter than `char[]`.

### Outputs

```
Input 1:    123456781234567812345678
Input 2:    314159
Output:       3     1  4    1   5
Input 1:    abcdefghijklmnopqrstuvwxyz
Input 2:    dilemma
Output:        d    i  l
Input 1:    314asd159asdasd
Input 2:    314159
Output:     314   159

```
> 0 votes

# Answer
## PowerShell v2+, 72 bytes

```
param($a,$b)$i=0;-join([char[]]$a|%{if($_-ceq$b[$i]){$_;$i++}else{'#'}})

```

Takes input `$a` and `$b`, sets `$i` to `0` (our pointer). Then, we cast `$a` as a char-array and pump it through a loop `|%{...}`. Each iteration, we check if the current character is case-sensitive-equal to the character in `$b` under the pointer. If it is, add it to the pipeline with `$_` and increment our counter. Otherwise, add a `'#'` to the pipeline. All of those characters are then gathered up `(...)` and `-join`ed into one string, which is then re-placed onto the pipeline. Output is implicit.

### Example

```
PS C:\Tools\Scripts\golfing> .\filter-this-string.ps1 "Programming Puzzles & Code Golf" "PPCG"
P###########P#########C####G###

```
> 0 votes

# Answer
## PHP(271)

This is my first php code so it is stronly likely that it can be golfed more

```
    function g($s,$b){$r='';foreach(str_split(strrev($b))as $i) $r='([^'.$i.']*?)(?:([^'.$i.']$)|'.$i.$r.')';$line=preg_replace_callback('/'.$r.'/',function ($m) {$a='';for($i=1;$i<count($m);$i=$i+2)$a=$a.$m[$i].$m[$i+1].'#';return $a;},$s);echo substr($line,0,strlen($s));}

```
* I used non-recursive regex where I am certain that a recursive breakthrough is available.
* Test it

```
<?php
g("uuuuaaaaavabbbbccccd","abcd");
function g($s,$b){$r='';foreach(str_split(strrev($b))as $i) $r='([^'.$i.']*?)(?:([^'.$i.']$)|'.$i.$r.')';$line=preg_replace_callback('/'.$r.'/',function ($m) {$a='';for($i=1;$i<count($m);$i=$i+2)$a=$a.$m[$i].$m[$i+1].'#';return $a;},$s);echo substr($line,0,strlen($s));}

```

+ In/Outputs

    ```
     uuuuaaaaavabbbbccccd
     abcd

     uuuu#aaaava#bbb#ccc#

    ```
> 0 votes

# Answer
# 05AB1E, 5 bytes

Code:

```
.o²g£

```

Explanation:

```
.o     # Overlap function.
         12345 and 1456 yields:
         1  456
  ²    # Get the second input.
   g   # Take the length.
    £  # Take the substring [0:length] and implicitly output.

```

Uses **CP-1252** encoding. Try it online!
> 0 votes

# Answer
# Python 3, 197 bytes

I was determined to solve this with regex, and I did. I did not really think it would be short.

```
def f(n,h):r=re.match(("([^{}]*)(.)"*len(n)).format(*n),h).groups();return"".join([i if i in n else"#"for i in"".join(["".join(d)for d in zip(["#"*len(i)for i in r[::2]],r[::-1][::2][::-1])])])

```

Ungolfed:

```
def fs(needle, haystack):
    rx = "([^{}]*)(.)"
    rx *= len(needle)
    rx = rx.format(*needle)
    r  = re.match(rx, haystack).groups()
    nd = r[::-1][::2][::-1]
    hs = r[::2]
    hs = ["#" * len(i) for i in hs]
    nh = "".join([i if i in needle else "#" for i in "".join(["".join(d) for d in zip(hs, nd)])])
    return nh

```

I wanted to do it with regex so I can do it again in Factor which, as a point-free functional language, does not do explicit looping. Haskell also does not do explicit looping and the Haskell solution does not use pattern matching but I don't understand the Haskell solution.

Here's what I used to come up with the regex.
> 0 votes

# Answer
# Python 3.5, 67

```
def f(a,b):b=[*b];return"".join(y==b[0]and b.pop(0)or"#"for y in a)

```

Ungolfed:

```
def f(a, b):
    b = [*b] #Convert string to list; yeah Python 3.5
    c = []
    for y in a:
       if y==b[0]:
          c.append(b.pop(0))
       else:
          c.append("#")
    return "".join(c)

```

Try it here
> 0 votes

# Answer
# PHP, 65 bytes

```
function f($s,$t){for(;a&$c=$s[$i++];)echo$c==$t[$k]?$t[$k++]:_;}

```
> 0 votes

# Answer
## REXX, 97 bytes

```
arg a b
o=
do while b>''
  parse var b n+1 b
  parse var a p (n)h+1 a
  o=o||translate(p,,p)h
  end
say o

```

As usual, readability is severely hampered by skipping every possible whitespace and abuttal operator.
> 0 votes

---
Tags: code-golf
---


title: Anagram Quines (Cops' Thread)

text:
# Question
Title: Anagram Quines (Cops' Thread)
*This is a challenge the Robbers' Thread can be found here*

Your challenge is to write a program that outputs an anagram of its source code but not the original source code itself.

For example the following Python program,

```
print`'print*2``'*2`

```

prints

```
'print*2``print*2``'

```

which has all of the same characters as its original source but in a different order.

Once you have found such a program, include the output of the program as an answer omitting the program that generates it. As you might have guessed, robbers will seek to discover the program you have hidden, or any program that fits the specifications. Your goal is to make the shortest program that the robbers cannot crack.

## Rules

* As with most challenges, if your answer remains uncracked for a week you may add the intended solution to your answer and mark it as **Safe**. Once safe an answer cannot be cracked by robbers.
* You do not need to include the language of the intended solution, however if you do not include the language robbers can crack it in any language predating the challenge, while if you specify the language they may only crack it in the one provided.
* Standard rules for Quines apply.

# Answer
# Brain-Flak, 231 bytes Cracked by Wheat Wizard

```
}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{][][][][][][][)()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(

```

The original program uses the `-A` argument.

Here are the counts:

```
( -> 74
) -> 74
{ -> 34
} -> 34
[ -> 7
] -> 7

```
> 12 votes

# Answer
# Python 2, 96 bytes, cracked by math\_junkie

Output:

```
B97.off]xo) wnd[ri0'of{r1({r6-{r{rri) {r1(xo0'sjD;0'0'qhF=1({r{r2)4+}twnri2)wnlcof) yp) ) xomd2)

```

First time code golfing! Hope it's not too easy.
> 5 votes

# Answer
# Unspecified langauge, 124 bytes,

In the theme of DJMcMayhem's answer this is the first 32 ASCII characters (aside from `0x00`) printed four times each. Since none of these are visible, I have not included the actual code in my answer.

Here is the hexdump:

```
00000000: 0101 0101 0202 0202 0303 0303 0404 0404  ................
00000010: 0505 0505 0606 0606 0707 0707 0808 0808  ................
00000020: 0909 0909 0a0a 0a0a 0b0b 0b0b 0c0c 0c0c  ................
00000030: 0d0d 0d0d 0e0e 0e0e 0f0f 0f0f 1010 1010  ................
00000040: 1111 1111 1212 1212 1313 1313 1414 1414  ................
00000050: 1515 1515 1616 1616 1717 1717 1818 1818  ................
00000060: 1919 1919 1a1a 1a1a 1b1b 1b1b 1c1c 1c1c  ................
00000070: 1d1d 1d1d 1e1e 1e1e 1f1f 1f1f            ............

```

Here however is some Python that prints it (and a newline) if you would like:

```
print"".join(chr(x)*4for x in range(1,32))

```
> 4 votes

# Answer
# , 21 bytes (Safe!)

```

"&./124ipq|ÍÓÚîñòÿ

```

Note the leading newline.

Since this contains unprintables, here is a hexdump:

```
00000000: 0a16 1b22 262e 2f31 3234 6970 717c cdd3  ..."&./124ipq|..
00000010: daee f1f2 ff                             .....

```

To help people out some, here is a link to the Standard extensible V quine

---

Here is the original version:

```
ñi241"qp|Ó./ò&
ÚÍîÿ

```

Try it online!

The readable version is:

```
ñi<C-v>241<esc>"qp|Ó./ò&
ÚÍîÿ

```

The way this works is by embedding *sort* into the default extensible quine. As I was thinking about V-quines because of this answer, I realized that the standard extensible quine can be shortedn by three bytes, so this solution could have been:

```
ñiéÑ~"qp|Ó./ò&
ÚÍîÿ

```

Explanation:

```
ñi<C-v>241<esc>"qp  " Standard V-quine. Everything after this is recorded into register 'q'
                    " so we can do whatever we want without ruining it's "quine-ness"

|       " Go the first character on the line (I just realized now that this is pointless)
 Ó./ò&  " Put every character on a newline
Ú       " Sort every line
 Íî     " Join all lines together
   ÿ    " Necessary for V-quines

```
> 4 votes

# Answer
# Pyth, 32 bytes, Cracked by math\_junkie

```
J+J=JJ 1-2#pTN%"J+J=JJ 1-2#pTN%"

```

Original solution

```
J2#p+"J+J=JJ 1-2#pTN%"N=J-J1 %TJ

```

Try it online!

```
J2                               # Assign 2 to the variable J
  #                              # Infinite loop, break on error
    +"J+J=JJ 1-2#pTN%"N          # appending a '"' to the string 'J+J=JJ 1-2#pTN%'
   p                             # print the string above
                       =J-J1     # subtract 1 from J and assign back to J
                             %TJ # calculated 10%J, with a blank space before to supress output,
                                 # on the 3rd iteration this will be 10%0 that will generate an
                                 # erro and will break out the loop

```
> 4 votes

# Answer
# CJam, 46 bytes, cracked by math\_junkie

```
3658:93]93]]]95_959599c101101$::]]]]]]____ccee

```
> 4 votes

# Answer
# Haskell, 107 bytes, Cracked by nimi

```
"$$$$'''''''',,----....::<<<<<<<<========>>>>[[[[[[[[]]]]]]]]aaddddddddddddiiiiiiiiiiiimmnnnnpprrtt||||||"

```

There is an additional trailing newline.

---

**Original solution:**

```

main=print$id=<<[[id|i<-"main=print$id=<<[[id|i<-,i==d]>>d:[d]|d<-['$'..'|']]",i==d]>>d:[d]|d<-['$'..'|']]

```

Try it online!

My main idea was to write a quine which sorts its own source code before outputting it without using a library `sort` function. Only after an initial cracking try by nimi it occurred to me that the program code could be manually sorted, hard coded into the program and then printed out while doubling each letter. However the limited available characters make this approach more cumbersome and nimi's successful crack is quite similar to my original program.

**Explanation:**

```
main=print$                                      -- full program which prints the following string
  id=<<[[id|i<-"...",i==d]>>d:[d]|d<-['$'..'|']]
                                 |d<-['$'..'|']  -- for each char d in "$%&'()*+,-./012 ... xyz{|"
        [id|i<-"...",i==d]                       -- build a list with as many elements as d is contained in the string
                          >>d:[d]                -- replicate the string "dd" as often as the previous list is long
  id=<<[                                       ] -- concatenate the resulting list of srings to one single string

```
> 4 votes

# Answer
# Unspecified language, 254 bytes Cracked by @Dennis!

I doubt this will win for brevity, but it'll be a pain to crack, so it's still worth making.

Due to a bug, the order of `0x0b, 0x0c, 0x0a` got a little bit mixed up, but this is definitely the real output.

I figured I wouldn't specify the language just so I could see what different languages this is possible in. Since the output is mostly non-ASCII, here is a hexdump of the output:

```
00000000: 0102 0304 0506 0708 090b 0c0a 0e0f 1011  ................
00000010: 1213 1415 1617 1819 1a1b 1c1d 1e1f 2021  .............. !
00000020: 2223 2425 2627 2829 2a2b 2c2d 2e2f 3031  "#$%&'()*+,-./01
00000030: 3233 3435 3637 3839 3a3b 3c3d 3e3f 4041  23456789:;<=>?@A
00000040: 4243 4445 4647 4849 4a4b 4c4d 4e4f 5051  BCDEFGHIJKLMNOPQ
00000050: 5253 5455 5657 5859 5a5b 5c5d 5e5f 6061  RSTUVWXYZ[\]^_`a
00000060: 6263 6465 6667 6869 6a6b 6c6d 6e6f 7071  bcdefghijklmnopq
00000070: 7273 7475 7677 7879 7a7b 7c7d 7e7f 8081  rstuvwxyz{|}~...
00000080: 8283 8485 8687 8889 8a8b 8c8d 8e8f 9091  ................
00000090: 9293 9495 9697 9899 9a9b 9c9d 9e9f a0a1  ................
000000a0: a2a3 a4a5 a6a7 a8a9 aaab acad aeaf b0b1  ................
000000b0: b2b3 b4b5 b6b7 b8b9 babb bcbd bebf c0c1  ................
000000c0: c2c3 c4c5 c6c7 c8c9 cacb cccd cecf d0d1  ................
000000d0: d2d3 d4d5 d6d7 d8d9 dadb dcdd dedf e0e1  ................
000000e0: e2e3 e4e5 e6e7 e8e9 eaeb eced eeef f0f1  ................
000000f0: f2f3 f4f5 f6f7 f8f9 fafb fcfd feff       ..............

```

That is every single ASCII character except for `0x00` and `0x0D` because they both caused strange behavior on TIO. Have fun cracking! \>:D

---

The original code was in V.

Try it online

Hexdump:

```
00000000: ee02 0304 0506 0708 090b 0c0e 0f10 1112  ................
00000010: 1314 1516 1718 191a 1b1c 1d1e 1f20 2122  ............. !"
00000020: 2324 2526 2728 292a 2b2c 2d2e 2f30 3132  #$%&'()*+,-./012
00000030: 3334 3536 3738 393a 3b3c 3d3e 3f40 4142  3456789:;<=>?@AB
00000040: 4344 4546 4748 494a 4b4c 4d4e 4f50 5152  CDEFGHIJKLMNOPQR
00000050: 5455 5657 5859 5a5b 5c5d 5e5f 6061 6263  TUVWXYZ[\]^_`abc
00000060: 6465 6667 6869 6a6b 6c6d 6e6f 7071 7273  defghijklmnopqrs
00000070: 7475 7677 7879 7a7b 7c7d 7e7f 8081 8283  tuvwxyz{|}~.....
00000080: 8485 8687 8889 8a8b 8c8d 8e8f 9091 9293  ................
00000090: 9495 9697 9899 9a9b 9c9d 9e9f a0a1 a2a3  ................
000000a0: a4a5 a6a7 a8a9 aaab adae afb0 b1b2 b3b4  ................
000000b0: b5b6 b7b8 b9ba bbbc bdbe bfc0 c1c2 c3c4  ................
000000c0: c5c6 c7c8 c9ca cbcc cdce cfd0 d1d2 d3d4  ................
000000d0: d5d6 d7d8 d9da dbdc ddde dfe0 e1e2 e3e4  ................
000000e0: e5e6 e7e8 e9ea ebec edef f0f1 f2f3 f4f5  ................
000000f0: f6f7 f8f9 fafb fcfd feff 0a53 ac01       ...........S..

```

Basically, everything up to the `S` just inserts garbage into the buffer. The `0xEE` at the beginning is just to insure that everything after the newline doesn't happen in part of a loop or macro. Then, we do

```
¬<C-a>   "Insert every character in the range 0x01-0xFF

```
> 3 votes

# Answer
# Octave, 91 bytes

```
a=['111111111123666667eeegggkkknnszEEGn};:;:'];
''''''''''(),,,,,-[[[]]]aaaddip;;=ds1010]);

```
> 2 votes

# Answer
# PHP, 130 Bytes (Safe)

```
    $$$$$$''''(((((((()))))))),,22;;;;;;<<==??\\\\____aaccddeeeeeeeehhhhiiiillllmmoooooopppppppppprrrrrrrrssssssssttttttttttvvvvvv

```

## Original Solution

I could not understand that it was not cracked

```
<?php $v=str_split(str_repeat('<?php\ $v=str_split(str_repeat(\'\',2));sort($v);echo\ implode($v);',2));sort($v);echo implode($v);

```
> 2 votes

# Answer
# Guess, 43 bytes

```
{4"2)4q):)u(4o'{4t:q(e)(",(t22(u()o)?,?'2e

```

It was a tough call whether or not to share what language it was, but I think this option is better. Note that there's a trailing newline.
> 0 votes

---
Tags: code-golf, quine, cops-and-robbers, permutations
---


# Question
Title: Simple code golf challenge: Character patterns!
In this challenge, you receive a string as input containing a string of X's, Y's and Z's eg. "XYZZ". X, Y and Z represent a particular character. This pattern is then compared with a second string input. If the pattern exists as a substring in the second input, return `True`, otherwise, return `False`. Once a pattern is found in the word, the program stops searching and returns `True`.

## Examples

Pattern: "XXYY"

```
succeed ---> True (pattern found: ccee)
success ---> False (pattern not matched)
balloon ---> True (pattern found: lloo)

```

Pattern: "XYXYZ"

```
bananas ---> True (pattern found: nanas)
banana  ---> False (pattern not found)

```
* Note: This is not the actual input. This is an example of how the program should work. Your program should output `True` or `False`, or other Truthy/Falsy values.

## Other important/useful information

* The pattern does not need to contain an X, Y and a Z, it could contain X's and Y's or even (although somewhat pointless) just X's.
* The pattern cannot be empty, but this will not be used as a test case.
* The search string will not be empty, and will be lowercase.
* The alphabetic order of X, Y and Z in the pattern does not matter.
* X, Y and Z *must* be unique characters.
* You may use any library you wish.
* The score is determined by the **code size**, in bytes. Lowest score wins.

Good luck!

# Answer
# Perl 5, 85 bytes

*Saved 40 bytes thanks to Peter Taylor's suggestion! (see my older version bellow to see the differences)*

83 bytes of code + `-pl` flag.

```
s/./$h{$&}?"\\$h{$&}":($h{$&}=$.,join("",map"(?!\\$_)",1..$.++)."(.)")/ge;$_=<>=~$_

```

Try it online!

XYXYZ is transformed into `((?!\1).)((?!\1)(?!\2).)\1\2((?!\1)(?!\2)(?!\3).)` (yup, some of the tests can't be true, but it's shorter that way), and the second input is then checked against that regex. (see the explanations of my older version to get more intuition of how it works)

---

My older version:
*Thanks to Arnauld for pointing out a mistake I made in my first version.*
113 bytes of code + `-pl` flags, and `-Mre=eval`.

```
s/./$h{$&}?"\\$h{$&}":($h{$&}=++$i,"(.)")/ge;$_.='(?{++$c;$\=1if!grep$v{$c}{${$_}}++,1..'.(keys%h).'})^';<>=~$_}{

```

Try it online!

On the example XYXYZ: the first regex will convert the pattern to (.)(.)\1\2(.), and add at the end a test to check if `$1`, `$2` and `$3` are different: if so, `$\` is set to one. Then, the second input is testes against this regex, and `$\` is implicitely printed at the end.
The regex generated for XYXYZ is `(.)(.)\1\2(.)(?{++$c;$\=1if!grep{$v{$c}{${$_}}++}1..3})^`.
*(I'll to add a bit more details to the explanations when I have a moment)*
> 12 votes

# Answer
# Jelly, 9 bytes

```
=þ
ẆÇ€ċÇ}

```

Returns the number of times the pattern was found, non-zero being truthy and zero being falsy.

Try it online!

### How it works

```
ẆÇ€ċÇ}  Main link. Left argument: s (string). Right argument: p (pattern)

Ẇ       Window; generate all substrings of s.
 Ç€     Map the helper link over the substrings.
    Ç}  Apply the helper link to p.
   ċ    Count the number of times the right result appears in the left result.

=þ      Helper link. Argument: t (string)

=þ      Compare all characters of t for equality with all characters of t, yielding
        a square matrix of Booleans.

```
> 10 votes

# Answer
## JavaScript (ES6), 94 bytes

```
f=
(p,s)=>s.match(p.replace(/./g,c=>m[c]||(t=r,r=`(?!\\${++g})`+r,m[c]=`\\`+g,t),g=m=[],r=`(.)`))
```

```
<div oninput=o.textContent=!!f(p.value,s.value)><input id=p placeholder=Pattern><input id=s placeholder=String><span id=o>
```

Works by transforming the pattern into a regexp, e.g. for `XYXYZ` it generates `/(.)(?!\1)(.)\1\2(?!\2)(?!\1)(.)/`.

I notice an interesting distinction between PCRE and JavaScript regexp: in PCRE, `\<n>` fails (and therefore `(?!\<n>)` succeeds) before the capture group is defined, while JavaScript it succesfully matches the empty string (and therefore `(?!\<n>)` fails).
> 8 votes

# Answer
# Python 2, 70 bytes

```
f=lambda p,s:s>''and(map(s.find,s[:len(p)])==map(p.find,p))|f(p,s[1:])

```

Try it online!

Checks if a string matches a pattern using the method in this answer. Uses a prefix of the search string whose length equals the pattern. Chops off the first character of the string string until a match is found, or `False` if it becomes empty

---

**73 bytes:**

```
f=lambda p,s:s>''and(map(s.find,s)==map(p.find,p))|f(p,s[1:])|f(p,s[:-1])

```

Try it online

Checks if a string matches a pattern using the method in this answer. Recursively checks all substrings by branching into removing the first or last character until the string is empty.
> 7 votes

# Answer
# Python 3, 100 bytes

```
l=len
f=lambda p,s:l(p)<=l(s)and(l({*zip(p,s)})==l({*p})==l({s for _,s in{*zip(p,s)}})or f(p,s[1:]))

```

Try it online!
> 6 votes

# Answer
# PHP, 89 Bytes

A Gift from @Christoph and @Titus

```
for(;$v=$argv[1][$i++];)$r.=$$v?"\\".$$v:"(.)".!$$v=++$j;echo preg_match("#$r#",$argv[2]);

```

# PHP, 105 Bytes

A Gift from @Christoph

```
foreach(str_split($argv[1])as$v)$r.=$x[$v]?"\\$x[$v]":"(.)".!$x[$v]=++$y;echo preg_match("#$r#",$argv[2]);

```

# PHP, 167 Bytes

```
[,$a,$b]=$argv;foreach($s=str_split($a)as$v)$r[]=$k++>strpos($a,$v)?"\\".(1+array_search($v,array_keys(array_count_values($s)))):"(.)";echo preg_match(_.join($r)._,$b);

```
> 4 votes

# Answer
# Java 7, ~~177~~ ~~176~~ 173 bytes

```
Object c(String p,String s){int i=p.length();if(s.length()<i)return 0>1;for(;i-->0;)if(p.indexOf(p.charAt(i))!=s.indexOf(s.charAt(i)))return c(p,s.substring(1));return 1>0;}

```

**Explanation:**

```
Object c(String p, String s){                             // Method with two String parameters and Object return-type
  int i = p.length();                                     //  Index that starts at the length of the pattern
  if(s.length() < i)                                      //  If the length of the input is smaller than the length of the pattern
    return 0>1;//false                                    //   Simply return false
  for(;i-->0;)                                            //  Loop from 0 to length_of_pattern
    if(p.indexOf(p.charAt(i)) != s.indexOf(s.charAt(i)))  //   If the index of the characters of the pattern and input aren't matching
     return c(p, s.substring(1));                         //    Return the recursive-call of pattern and input minus the first character
                                                          //  End of loop (implicit / single-line body)
  return 1>0;//true                                       //  If every index of the characters are matching: return true
}                                                         // End of method

```

**Test code:**

Try it here.

```
class M{
  static Object c(String p,String s){int i=p.length();if(s.length()<i)return 0>1;for(;i-->0;)if(p.indexOf(p.charAt(i))!=s.indexOf(s.charAt(i)))return c(p,s.substring(1));return 1>0;}

  public static void main(String[] a){
    System.out.println(c("XXYY", "succeed"));
    System.out.println(c("XXYY", "success"));
    System.out.println(c("XXYY", "balloon"));

    System.out.println(c("XYXYZ", "bananas"));
    System.out.println(c("XYXYZ", "banana"));
  }
}

```

**Output:**

```
true
false
true
true
false

```
> 4 votes

# Answer
## C#, 184 165 155 bytes

thanks aloisdg!

```
bool c(string p,string n){for(int l=p.Length,i=0,j;i<l;i++)for(j=i;j>=0;)if(p[i]==p[j]==(n[i]!=n[j--]))return l!=n.Length&&c(p,n.Substring(1));return 2>1;}

```

backtracking solution, as a bonus it works with a pattern with any characters!

```
    public static bool c(string p,string n)
    {
        for (int l = p.Length, i = 0, j; i < l; i++)
            for (j = i; j >= 0;)
                if (p[i]==p[j]==(n[i]!=n[j--]))
                    return l != n.Length && c(p,n.Substring(1));
        return 2>1;
    }

```
> 4 votes

# Answer
# 05AB1E, ~~19~~ 16 bytes

```
ÙœJv¹y…XYZ‡²åi1q

```

Try it online!

---

```
ÙœJ              # Get powerset of all unique characters in string.
   v             # Loop through each...
    ¹            # Push input word.
     y           # Push current set of letters in powerset.
      …XYZ‡      # Replace each of the 3 letters in the original word with XYZ.
           ²å    # Check if second input is in this string, push 1 if it is.
             i1q # If 1, push 1 and quit.

```

Will return 1 if true, null if not true.

---

This can be 14 bytes if returning the possible values of XYZ is allowed:

# 05AB1E, 14 bytes

```
ÙœJv¹y…XYZ‡²å—

```

Try it online 2!
> 4 votes

# Answer
# Ruby, ~~63~~ 61 bytes

```
->a,b{a.chars.permutation.any?{|w|a.tr((w|[])*'','XYZW')[b]}}

```

Instead of searching for a regex pattern, just try substituting 'X','Y' and 'Z' in all possible ways, and find a literal match.

(Actually the same concept as carusocomputing's 05AB1E answer)
> 3 votes

# Answer
## JavaScript (ES6), ~~92~~ ~~89~~ ~~87~~ 86 bytes

Takes input `p` (pattern) and `s` (string) in currying syntax `(p)(s)`. Returns `0` / `1`.

```
p=>g=s=>s&&g(s.slice(1))|[...p].every((C,i,x)=>C==(x[c=s[i]]=x[c]||'XYZ'[c&&j++]),j=0)

```

### Formatted and commented

```
p =>                             // main function: takes pattern p as input, returns g
  g = s =>                       // g = recursive function: takes string s as input
    s &&                         // if s is not empty:
      g(s.slice(1))              //   do a recursive call, starting at the next character
    |                            // merge the result with this iteration
    [...p].every((C, i, x) =>    // for each character C at position i in p:
      C ==                       //   check whether C is matching the next expected
      (                          //   character, which is either:
        x[c = s[i]] = x[c] ||    //   - a substitution character already associated to s[i]
        'XYZ'[c && j++]          //   - the next substitution character ('X', 'Y' or 'Z')
      ),                         //   - undefined if c = s[i] doesn't exist or j > 2
      j = 0                      //   initialize j = pointer in 'XYZ'
    )                            //

```

### Test cases

```
let f =

p=>g=s=>s&&g(s.slice(1))|[...p].every((C,i,x)=>C==(x[c=s[i]]=x[c]||'XYZ'[c&&j++]),j=0)

console.log(f("XXYY")("succeed"))   // 1
console.log(f("XXYY")("success"))   // 0
console.log(f("XXYY")("balloon"))   // 1
console.log(f("XYXYZ")("bananas"))  // 1
console.log(f("XYXYZ")("banana"))   // 0
```
> 2 votes

# Answer
# Mathematica 18 characters (not counting string & pattern)

```
StringContainsQ[string,pattern]

```

Examples:

```
StringContainsQ["succeed", x_ ~~ x_ ~~ y_ ~~ y_]

```

`True`

```
StringContainsQ["bananas", x_ ~~ y_ ~~ x_ ~~ y_ ~~ z_]

```

`True`
> 0 votes

---
Tags: code-golf
---


# Question
Title: Most Compact Code For A Simulated Explosion
Can you write a program that renders to screen a group of pixels exploding apart (as in a simple particle engine) and can you do this in any remarkably small number of characters (key strokes)? (Recall the game lemmings, when those little guys would explode and their little pixel pieces fly apart.)

Someone programmed a simple particle system here as a Processing sketch and it is pretty hefty compared to what I think others should be able to accomplish if they tried. But I'd be much more impressed if it someone could do the same in c++ and sdl, or even java or c#.

# Answer
## Python, 245 chars

```
import random,time
R=lambda:random.randrange(-999,999)/1e3
P=[(40+20j,R()+1j*R())for i in' '*20]
for i in' '*20:
 C=([' ']*80+['\n'])*40
 for p,v in P:C[int(p.real)+81*int(p.imag)]='*'
 print''.join(C);P=[(p+v,v*.95)for p,v in P];time.sleep(.1)

```
> 13 votes

# Answer
## C#, WPF – 1523

Not terribly serious; this was mainly an attempt whether it actually worked.

What I'm doing here is using an ItemsControl (Menu, since it's shorter) in WPF to display particles via data binding and templating. A data template controls how the particles look like (in this case a simple circle) and data binding controls color and position of the particles.

Each particle has a position, a color and a direction which get updated by a timer. Initially a bunch of particles are generated in the center of the window with (normal-distributed) random directions. That collection gets data-bound to the ItemsControl which then handles displaying the particles automatically, whenever the properties are updated. Particles are dragged down a bit due to gravity.

It got a little lengthy, admittedly. But at least it looks nice:

It can surely be made shorter by omitting:

* gravity, causing particles to expand uniformly to all sides;
* the normal distribution for the initial vectors, causing the particles to expand in a sparse »box«;
* the brightness variation, leaving particles black.

I opted not to do so in the interest of aesthetics. This solution is way longer than almost anything else regardless. The data-binding and templating approach might be elegant but it's also quite verbose compared with simply updating a bitmap. (Note: I got it down to **1356** by leaving all of the above out, but it looks horrible then.)

The code is distributed in three files, which are given here in formatted form for legibility:

**App.xaml**

```
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" StartupUri="W.xaml"/>

```

**W.xaml**

```
<Window x:Class="W" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Menu Name="i">
        <Menu.ItemTemplate>
            <DataTemplate>
                <Ellipse Width="2" Height="2" Fill="#000" Opacity="{Binding O}">
                    <Ellipse.RenderTransform>
                        <TranslateTransform X="{Binding X}" Y="{Binding Y}"/>
                    </Ellipse.RenderTransform>
                </Ellipse>
            </DataTemplate>
        </Menu.ItemTemplate>
        <Menu.Template>
            <ControlTemplate>
                <ItemsPresenter/>
            </ControlTemplate>
        </Menu.Template>
        <Menu.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </Menu.ItemsPanel>
    </Menu>
</Window>

```

**W.xaml.cs**

```
using M = System.Math;
using T = System.Timers.Timer;
using System;
using System.ComponentModel;

partial class W
{
    int a;
    T t = new T(99);

    public W()
    {
        InitializeComponent();
        Height = Width = 500;
        var r = new Random();
        Func<double> n = () => 2 * (M.Sqrt(-2 * M.Log(r.NextDouble())) * M.Sin(6 * r.NextDouble()));
        var l = new System.Collections.Generic.List<P>();
        for (; a++ < 300; )
            l.Add(new P { X = 250, Y = 250, f = n(), g = n() });
        i.ItemsSource = l;
        t.Elapsed += delegate
        {
            foreach (P x in l)
            {
                x.X += x.f;
                x.Y += x.g += .2;
                x.O = M.Max(1 - M.Sqrt(M.Pow(250 - x.X, 2) + M.Pow(250 - x.Y, 2)) / 250, 0);
            }
        };
        t.Start();
    }
}

class P : System.Windows.ContentElement, INotifyPropertyChanged
{
    public double y, f, g;
    public double X { get; set; }
    public double O { get; set; }
    public double Y
    {
        get { return y; }
        set
        {
            y = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(""));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

```
> 10 votes

# Answer
# postscript - 287 244 chars

```
currentpagedevice/q{exch def}def/PageSize get/z{dup 3 1 roll add exch 4 2 roll}def{2
div}forall/y/r{rand 2 27 exp div 8 sub}def q/x q[99{[x r y r]}repeat]50{dup{aload/t q
3 index 2 index 4 4 rectfill 1 sub z z t astore pop}forall showpage}repeat

```

run with `gs -dNOPAUSE asplode.ps`

You could even print it out and make a flipbook
> 7 votes

# Answer
# Javascript - 268 chars

Here's a 1 dimensional, 2 particle, explosion:

```
javascript:d=document;c=d.createElement('canvas');d.body.appendChild(c);g=c.getContext("2d");function e(x,y,m){g.arc(x,y,m,0,2*Math.PI,false);g.fill()}function s(a,b,v,t){c.width=c.width;e(50+t*v,50,b);e(50+t*b*v/(b-a),50,a-b);setTimeout(function(){s(a,b,v,t+1)},100)};s(9,5,1,0)

```

To run it, open an about:blank page in a good web browser, paste into the url bar and press enter. You can modify the explosion by editing the values at the end in `s(10,5,1,0)`. The first value is the size of the particle that is exploded. The second value is the size of the particle that is exploded out of it. The third value is the speed of the particle exploded out of it. Leave the '0' as it is.
> 5 votes

# Answer
## APL (~~120~~ 118)

It has the same kind of output as the Python entry (i.e. it just outputs the states on a character grid). Only the grid is 30x15 and the particle origin is at 15x7.

```
⍎⊃,⌿(9⍴⊂'(⎕DL.1)⊢{{(A+2↑⍵),0.95×A←2↓⍵}¨⍵⊣⎕←'' ⍟''[1+(⍳15 30)∊2↑¨⌊⍵]}'),⊂',⌿⍉10 4⍴⍎''⍬'',420⍴'',(7 15,.01×99-?2⍴199)'''

```
> 4 votes

# Answer
### JavaScript ~~502~~ ~~500~~ 496

This is a combination of the Joey's and david4dev's answers (it's a shameless copy of Joey's algorithm implemented using Javascript/canvas ☺):

```
W=500;H=250;function r(){return 2*m.sqrt(-2*m.log(m.random()))*m.sin(6*m.random())}function n(){z=[];for(i=W;i;i--){s={};s.x=s.y=H;s.f=r();s.g=r();z.push(s)}}function w(){x.clearRect(0,0,W,W);z.forEach(function(a){a.x+=a.f;a.y+=a.g+=.2;x.fillStyle="rgba(0,0,0,"+m.max(1-m.sqrt(m.pow(H-a.x,2)+m.pow(H-a.y,2))/H,0)+")";x.fillRect(a.x,a.y,2,2)})}z=[];m=Math;d=document;c=d.createElement("canvas");c.width=c.height=W;d.body.appendChild(c);x=c.getContext("2d");n();setInterval(n,2e3);setInterval(w,10)

```

JSFiddle preview: http://jsfiddle.net/GVqFr/60/ (you can press the TidyUp button to format the code nicely)
> 2 votes

# Answer
### Bash 380

```
C="4443311177"
t=".-xxXMXxx-."
alias c='echo -e "\e[2J"'
g(){
echo -e "\e[1;$4\e[$2;$1H$3"
}
f(){
x=$1
y=$2
p=$((2-RANDOM%5))
q=$((2-RANDOM%5))
for i in {-5..5}
do
x=$((x+p))
y=$((y+q))
n=$((5+i))
c=$((5+i))
g $x $y ${t:n:1} 3${C:c:1}m
w=$(printf "%04i\n" $((5*i*i)))
sleep ${w/0/0.}
g $x $y " " 3${C:c:1}m
done
}
e(){
c
for i in {1..10}
do
f $((COLUMNS/2)) $((LINES/2)) &
done
}

```

Call e like explode.

### update: colorized

t=text, c=cls, g=gotoxy, f=fly, C=COLOR
> 1 votes

# Answer
## C with SDL, 423 chars

Since the original problem description explicitly mentioned SDL, I felt it was past time that an SDL solution was submitted. Unfortunately, the names of the SDL function and structs aren't particularly terse, so this program is a little long. In fact, I can't even leave out the `#include`.

```
#include<math.h>
#include"SDL.h"
SDL_Surface*s;SDL_Event e;SDL_Rect p;int i,n;double q[256];main(){
SDL_Init(SDL_INIT_VIDEO);s=SDL_SetVideoMode(320,320,32,0);
for(srand(time(0));e.type-SDL_QUIT;n=-~n%64){
for(i=256*!n;i;q[--i]=rand()%65536*9.5874e-5);
for(SDL_FillRect(s,0,i=0);++i<256;SDL_FillRect(s,&p,-n*67372036))
p.x=160+cos(q[i])*q[i-1]*n,p.y=160+sin(q[i])*q[i-1]*n,p.w=p.h=1;
SDL_Flip(s);SDL_Delay(50);SDL_PollEvent(&e);}}

```

(Since the code is already so huge, I left in some extra bits so that it would compile without warnings. I miss compiling without warnings sometimes. Removing them would save about 30 or so chars.)

The animation runs in an infinite loop. Close the window to exit the program. Each explosion uses a new set of random particles.

I would also like to point out the number`67372036` in the code. It appears in the expression for the last argument in the second call to `SDL_FillRect()`. As the code stands, the explosion is rendered entirely in grays. Changing this number slightly will add a very subtle but pleasant color effect to the explosion. The number `67372032` colors the particles at the start of the explosion, while the number `67372034` provides a color effect as they fade out at the end. Other numbers can produce less subtle color-cycling effects. I encourage you to try them out.
> 1 votes

# Answer
After seeing some of the other great examples here, I decided to give it a go, and make a particle function that fits in **140byt.es**

# Javascript, 282 chars

(*138* chars particle function and *150* chars basic canvas drawing boilerplate)

```
p=function(a,t,x,y,n,g,s,i,d){with(Math)for(i=n;i--;d=cos(i*sin(i*s)),a.globalAlpha=n/t/i,a.fillRect(x+t*sin(i)*d, y+t*cos(i)*d+t*g,2,2));};d=document;a=d.body.appendChild(d.createElement('canvas')).getContext('2d');t=setInterval("a.clearRect(0,0,300,150);p(a,t++, 50,50,1e3,.2,1)")

```

**Live JSFiddle example here**

By making the code fully procedural I no longer needed any array or object-assignment code, reducing the size a lot. Making a procedural effect also has some other nice side-effects.

The code could be made smaller by ommitting Gravity, Seeds, Number of Particles, etc, but I think these features are too nice to remove ;).

# Features

* Configurable X,Y center of explosion.
* Configurable number of particles
* Gravity in the vertical direction: Have your particles fall down or fly up!
* Seedable, each seed has its own explosion and will show exactly that explosion each time, across computers.
* Slowmotion, Fast Forward and playing explosions Backwards is all possible, due to the procedural way the effect is created.
* Size:138 bytes.

Also check it out on GitHub, for an annotated version.
> 1 votes

# Answer
# Python with PyGame, 240 chars

I realize that there is already a solution in python, but since that one just prints characters, I thought it would be worthwhile to make one that draws a nice animation.

Ungolfed, what I started with:

```
import math
import random
import pygame
pygame.init()

screen = pygame.display.set_mode((800, 800))
particles = [(random.gauss(0,.5), random.uniform(0,6.28318)) for i in range(2000)]

for i in range(399):
    screen.fill((255,255,255))
    for speed, angle in particles:
        distance = i * speed
        x = 400 + distance * math.cos(angle)
        y = 400 + distance * math.sin(angle)
        screen.set_at((int(x), int(y)), (0,0,0))
    pygame.display.flip()

```

After much hackery. Fullscreen to save some characters. Not using sound or fonts, so I think `init()` is unnecessary (it works for me).

```
import math as m,random,pygame
d,x,g=pygame.display,range(999),random.gauss
s,e=d.set_mode(),[(g(0,.2),g(0,9))for i in x]
for i in x:
 d.flip(),s.fill([255]*3)
 for v,a in e:
        y=400+i*v*m.cos(a),400+i*v*m.sin(a)
        s.set_at(map(int,y),[0]*3)

```
> 0 votes

# Answer
# Python -- 327 chars

Intresting things:

* Use complex number as 2D vector
* `(v * cos(a), v * sin(a))` implemented as `v*e**(1j*a)`
* Looks like a 3D explosion.
* Gravity.

.

```
import pygame as P,random as R,math
R=R.random
D=P.display
D.init()
W=800
S=D.set_mode((W,W))
T=P.time.Clock()
C=lambda v:map(int,(v.real,v.imag))
X=[(8+R())*math.cos(R()*1.57)*2.7**(1j*R()*6.28) for i in range(999)]
for t in range(250):
 D.flip();T.tick(30);S.fill(2**24-1)
 for v in X:S.set_at(C(v*t+.005j*t*t+W/2*(1+1j)),0)

```
> 0 votes

# Answer
# dwitter 112

```
c.width^=0
t?o.push({X:1e3,Y:500,U:S(99*t),V:C(9*t)}):o=[]
o.map(a=>{a.X+=a.U,a.Y+=a.V,x.fillRect(a.X,a.Y,9,9)})

```

try it out by copy/pasting the code to dwitter.net
> 0 votes

---
Tags: code-golf
---


# Question
Title: Sign change, loop and display with minimal padding
### Input:

Two integers: one negative, one positive.

### Output:

On the first line output lowest to highest. On the second line we've removed the highest and lowest numbers and sign-changed all individual numbers. On the third line we've removed the highest and lowest numbers again and sign-changed all individual numbers again. etc. (The example below should make the challenge clearer.)

**Important:** In addition, we add spaces so the numbers in a column are all aligned (to the right).
The minimal alignment is the *main* part of this challenge, this means that you can't just make every single number the same width. The width of a column is based on the largest number-width of that specific column (and the sequence with sign-change is to give the numbers some variety in width per column).

---

**For example:**

```
Input: -3,6

Output:
-3,-2,-1, 0, 1, 2, 3, 4,5,6   // sequence from lowest to highest
 2, 1, 0,-1,-2,-3,-4,-5       // -3 and 6 removed; then all signs changed
-1, 0, 1, 2, 3, 4             // 2 and -5 removed; then all signs changed again
 0,-1,-2,-3                   // -1 and 4 removed; then all signs changed again
 1, 2                         // 0 and -3 removed; then all signs changed again
                              // only two numbers left, so we're done

```

As you can see above, spaces are added at the positive numbers, when they share a column with negative numbers to compensate for the `-` (the same would apply to 2-digit numbers).

### Challenge rules:

* Input must be two integers
    + You can assume these integers are in the `-99`-`99` (inclusive) range.
    + The first integer will be negative, and the other will be positive.
* Output can be in any reasonable format, as long as it's clear there are rows and rightly aligned columns: I.e. STDOUT; returning as String with newlines; returning as list of Strings; etc. Your call.
* The output must also contain a delimiter of your own choice (except for spaces, tabs, new-lines, digits or `-`): I.e. `,`; and `;` and `|`; and `X`; etc. are all acceptable delimiters.
* The output lines may not contain a leading or trailing delimiter.
* The output may contain ONE trailing new-line, and any line may contain any number of trailing spaces.

### General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

### Test cases:

```
Input: -3,6

Output:
-3,-2,-1, 0, 1, 2, 3, 4,5,6
 2, 1, 0,-1,-2,-3,-4,-5
-1, 0, 1, 2, 3, 4
 0,-1,-2,-3
 1, 2

Input: -1,1

Output:
-1,0,1
 0

Input: -2,8

Output:
-2,-1, 0, 1, 2, 3, 4, 5, 6,7,8
 1, 0,-1,-2,-3,-4,-5,-6,-7
 0, 1, 2, 3, 4, 5, 6
-1,-2,-3,-4,-5
 2, 3, 4
-3

Input: -15,8

Output:
-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6,7,8
 14, 13, 12, 11, 10,  9, 8, 7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7
-13,-12,-11,-10, -9, -8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6
 12, 11, 10,  9,  8,  7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5
-11,-10, -9, -8, -7, -6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4
 10,  9,  8,  7,  6,  5, 4, 3, 2, 1, 0,-1,-2,-3
 -9, -8, -7, -6, -5, -4,-3,-2,-1, 0, 1, 2
  8,  7,  6,  5,  4,  3, 2, 1, 0,-1
 -7, -6, -5, -4, -3, -2,-1, 0
  6,  5,  4,  3,  2,  1
 -5, -4, -3, -2
  4,  3

Input: -3,15

Output:
-3,-2,-1, 0, 1, 2, 3, 4,  5, 6,  7,  8,  9, 10, 11, 12, 13,14,15
 2, 1, 0,-1,-2,-3,-4,-5, -6,-7, -8, -9,-10,-11,-12,-13,-14
-1, 0, 1, 2, 3, 4, 5, 6,  7, 8,  9, 10, 11, 12, 13
 0,-1,-2,-3,-4,-5,-6,-7, -8,-9,-10,-11,-12
 1, 2, 3, 4, 5, 6, 7, 8,  9,10, 11
-2,-3,-4,-5,-6,-7,-8,-9,-10
 3, 4, 5, 6, 7, 8, 9
-4,-5,-6,-7,-8
 5, 6, 7
-6

Input: -12,12

Output:
-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8,  9, 10,11,12
 11, 10,  9, 8, 7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11
-10, -9, -8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10
  9,  8,  7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7,-8,-9
 -8, -7, -6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8
  7,  6,  5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7
 -6, -5, -4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6
  5,  4,  3, 2, 1, 0,-1,-2,-3,-4,-5
 -4, -3, -2,-1, 0, 1, 2, 3, 4
  3,  2,  1, 0,-1,-2,-3
 -2, -1,  0, 1, 2
  1,  0, -1
  0

```

# Answer
> 7 votes
# Jelly, ~~25~~ ~~24~~ 20 bytes

```
rµḊṖNµÐĿZbȷG€Ỵ€Zj€”,

```

This is a dyadic link that returns an array of rows.

Try it online!

### How it works

```
rµḊṖNµÐĿZbȷG€Ỵ€Zj€”,  Dyadic link. Arguments: a, b

r                      Range; yield [a, ..., b].
 µ   µÐĿ               Apply the enclosed chain until the results are no longer
                       unique. Return the array of results.
  Ḋ                      Dequeue; remove the first item.
   Ṗ                     Pop; remove the last item.
    N                    Negate; multiply all remaining integers by -1.
       Z               Zip; transpose rows and columns.
        bȷ             Base 1000; map each n to [n].
          G€           Grid each; in each row, pad all integers to the same length,
                       separating the (singleton) rows by linefeeds.
            Ỵ€         Split each result at linefeeds.
              Z        Zip to restore the original layout.
               j€”,    Join each row, separating by commata.

```

# Answer
> 7 votes
# Java 8, ~~483~~ ~~480~~ ~~486~~ 467 bytes

```
(a,b)->{int f=0,l=b-a+3,z[][]=new int[l][l],y[]=new int[l],i,j,k=0;for(;b-a>=0;k++,a++,b--,f^=1)for(j=0,i=a;i<=b;i++)z[k][j++]=f<1?i:-i;String r="",s;for(i=0;i<l;y[i++]=k)for(j=0,k=1;j<l;k=f>k?f:k)f=(r+z[j++][i]).length();for(i=0;i<l;i++){k=z[i][0];if(i>0&&k==z[i][1]&k==z[i-1][2])break;for(j=0;j<l;){k=z[i][j];s="";for(f=(s+k).length();f++<y[j];s+=" ");f=z[i][++j];if(k==f){r+=(i>0&&z[i-1][1]==z[i][1]?s+0:"")+"\n";j=l;}else r+=s+k+(f==z[i][j+1]?"":",");}}return r;}

```

*Bytes raised due to bug-fix..*

Ok, this took *A LOT* more time (and bytes) than I thought (in Java that is..). This can definitely be golfed some more, probably by using a completely different approach instead of creating an NxN grid-array to fill and then 'strip out' the zeros (with an annoying edge case for the test-case of `-1,1`, as well as `-12,12`).

Try it online.

**Explanation:**

```
(a,b)->{        // Method with two integer parameters and String return-type
  int f=0,      //  Flag-integer, starting at 0
      l=b-a+3,  //  Size of the NxN matrix,
                //  plus two additional zeros (so we won't go OutOfBounds)
      z[][]=new int[l][l],
                //  Integer-matrix (default filled with zeros)
      y[] = new int[l],
                //  Temp integer-array to store the largest length per column
      i,j,k=0;  //  Index-integers
  for(;b-a>=0   //  Loop as long as `b-a` is not negative yet
      ;         //    After every iteration:
       k++,     //     Increase `k` by 1
       a++,     //     Increase `a` by 1
       b--,     //     Decrease `b` by 1
       f^=1)    //     Toggle the flag-integer `f` (0→1 or 1→0)
    for(j=0,i=a;i<=b;i++)
                //   Inner loop `i` in the range [`a`, `b`]
      z[k][j++]=//    Set all the values in the matrix to:
        f<1?    //     If the flag is 0:
         i      //      Simply use `i`
        :       //     Else (flag is 1):
         -i;    //      Use the negative form of `i` instead
  String r="",  //  The return-String
         s;     //  Temp-String used for the spaces
  for(i=0;i<l;  //  Loop `i` over the rows of the matrix
      ;y[i++]=k)//    After every iteration: Set the max column-width
    for(j=0,k=1;j<l;
                //   Inner loop `j` over the cells of each row
        k=f>k?f:k)
                //     After every iteration: Set `k` to the highest of `k` and `f`
      f=(r+z[j++][i]).length();
                //    Determine current number's width
                //    (NOTE: `f` is no longer the flag, so we re-use it as temp value)
  for(i=0;i<l;i++){
                //  Loop `i` over the rows of the matrix again
    k=z[i][0];  //   Set `k` to the first number of this row
    if(i>0      //   If this isn't the first row
       &&k==z[i][1]&k==z[i-1][2])
                //   and the first number of this row, second number of this row,
                //   AND third number of the previous row all equal (all three are 0)
      break;    //    Stop loop `i`
    for(j=0;j<l;){
                //   Inner loop `j` over the cells of each row
      k=z[i][j];//    Set `k` to the number of the current cell
      s="";     //    Make String `s` empty again
      for(f=(s+k).length();f++<y[j];s+=" ");
                //    Append the correct amount of spaces to `s`,
                //    based on the maximum width of this column, and the current number
      f=z[i][++j];
                //    Go to the next cell, and set `f` to it's value
      if(k==f){ //    If the current number `k` equals the next number `f` (both are 0)
        r+=     //     Append result-String `r` with:
          (i>0  //      If this isn't the first row
           &&z[i-1][1]==z[i][1]?
                //      and the second number of this and the previous rows
                //      are the same (both are 0):
            s+0 //       Append the appropriate amount of spaces and a '0'
           :    //      Else:
            "") //       Leave `r` the same
          +"\n";//     And append a new-line
         j=l;}  //     And then stop the inner loop `j`
      else      //    Else:
       r+=s     //     Append result-String `r` with the appropriate amount of spaces
          +k    //     and the number
          +(f==z[i][j+1]?"":",");}}
                //     and a comma if it's not the last number of the row
  return r;}    //  Return the result `r`

```

# Answer
> 7 votes
# 05AB1E, 59 bytes

Once again I'm screwed over by the same bug I wrote a fix for months ago but never pushed...
Golfing should still be possible though.

```
Ÿ[Ðg1‹#ˆ¦(¨]\\¯vy€g}})J.Bvyð0:S})øvyZs\})U¯vyvyXNèyg-ú}',ý,

```

Try it online!

# Answer
> 6 votes
# Javascript (ES6), 269 bytes

```
(a,b,d=~a+b+2,o=Array(~~(d/2)+1).fill([...Array(d)].map(_=>a++)).map((e,i)=>e.slice(i,-i||a.a)).map((e,i)=>i%2==0?e:e.map(e=>e*-1)))=>o.map(e=>e.map((e,i)=>' '.repeat(Math.max(...[...o.map(e=>e[i]).filter(e=>e!=a.a)].map(e=>[...e+''].length))-`${e}`.length)+e)).join`
`

```

### Explained:

```
(                                     // begin arrow function

  a,b,                                // input

  d=~a+b+2,                           // distance from a to b

  o=Array(~~(d/2)+1)                  // create an outer array of
                                      // (distance divided by 2
                                      // floored + 1) length

    .fill(                            // fill each outer element
                                      // with the following:

      [...Array(d)]                   // create inner array of the
                                      // distance length and
                                      // fill with undefined

        .map(_=>a++)                  // map each inner element
                                      // iterating from a to b
    )
    .map(                             // map outer array

      (e,i)=>e.slice(i,-i||a.a)       // remove n elements from each end
                                      // of the inner array corresponding
                                      // to the outer index with a special
                                      // case of changing 0 to undefined
    )
    .map(                             // map outer array

      (e,i)=>i%2==0?e:e.map(e=>e*-1)  // sign change the inner elements
                                      // in every other outer element
    )
)=>                                   // arrow function return

  o                                   // outer array

    .map(                             // map outer array

      e=>e.map(                       // map each inner array

        (e,i)=>' '.repeat(            // repeat space character the
                                      // following amount:

          Math.max(...                // spread the following array to
                                      // max arguments:

            [...                      // spread the following to an
                                      // array:

              o                       // outer array

                .map(e=>e[i])         // map returning each element of
                                      // the same inner index from the
                                      // outer array

                .filter(e=>e!=a.a)    // remove undefined elements
            ]
            .map(e=>[...e+''].length) // map each element to the
                                      // length of the string

          )                           // returns the max string
                                      // length of each column

          -`${e}`.length              // subtract the current
                                      // element's string length
                                      // from the max string length

      )                               // returns the appropriate amount
                                      // of padding

      +e                              // add the element to the padding
    )
  ).join`
`                                     // join each element of outer
                                      // array as string with newline

```

```
const f = (a,b,d=~a+b+2,o=Array(~~(d/2)+1).fill([...Array(d)].map(_=>a++)).map((e,i)=>e.slice(i,-i||a.a)).map((e,i)=>i%2==0?e:e.map(e=>e*-1)))=>o.map(e=>e.map((e,i)=>' '.repeat(Math.max(...[...o.map(e=>e[i]).filter(e=>e!=a.a)].map(e=>[...e+''].length))-`${e}`.length)+e)).join`
`
console.log('Test Case: -1,1')
console.log(f(-1,1))
console.log('Test Case: -3,6')
console.log(f(-3,6))
console.log('Test Case: -2,8')
console.log(f(-2,8))
console.log('Test Case: -15,8')
console.log(f(-15,8))
console.log('Test Case: -3,15')
console.log(f(-3,15))
console.log('Test Case: -12,12')
console.log(f(-12,12))
```

# Answer
> 4 votes
## QBIC, 46 bytes

```
::[0,-1*a+b,2|[a,b|?d*q';`]q=q*-1┘a=a+1┘b=b-1?

```

How it works:

```
::           Read the negative and positive ints as a and b
[0,-1*a+b,2| FOR(c = 0; c < range(a, b); c+=2) {} This creates the proper amount of lines.
  [a,b|      For each line, loop from lower to upper
    ?d*q     Print the current point in the range, accounting for the sign-switch
     ';`     And suppress newlines. The ' and ` stops interpreting special QBIC commands.
  ]          NEXT line
  q=q*-1┘    Between the lines, flip the sign-flipper
  a=a+1┘     Increase the lower bound
  b=b-1?     Decrease the upper bound, print a newline
             The outermost FOR loop is auto-closed at EOF.

```

Fortunately, when printing a number, QBasic auto-adds the necessary padding.

# Answer
> 3 votes
# Perl 6, 146 bytes

```
{$_:=(($^a..$^b).List,{-«.[1..*-2]}...3>*).List;$/:=[map {"%{.max}s"},roundrobin($_)».chars];map {join ',',map {$^a.fmt: $^b},flat($_ Z $/)},$_}

```

Try it

Produces a sequence of strings

## Expanded:

```
{  # bare block lambda with placeholder parameters ｢$a｣ and ｢$b｣

  # generate the data
  $_ := (                 # bind to $_ so it isn't itemized

                          # produce a sequence
    ( $^a .. $^b ).List,  # seed the sequence, and declare parameters
    { -«\ .[ 1 .. *-2 ] } # get all the values except the ends and negate
    ...                   # keep producing until
    3 > *                 # the length of the produced list is less than 3

  ).List;                 # turn the Seq into a List

  # generate the fmt arguments
  $/ := [                 # bind an array to ｢$/｣ so it isn't a Seq
    map
      { "%{ .max }s" },   # turn into a ｢.fmt｣ argument ("%2s")

      roundrobin($_)\     # turn the "matrix" 90 degrees
      ».chars             # get the string length of each number
  ];

  # combine them together
  map
    {
      join ',',
        map
          { $^a.fmt: $^b }, # pad each value out
          flat(
            $_ Z $/         # zip the individual number and it's associated fmt
          )
    },
    $_                      # map over the data generated earlier
}

```

# Answer
> 3 votes
# PHP 7.1, 277 Bytes

```
for([,$a,$b]=$argv,$c=count($r=range($a,$b))/2;$c-->0;$r=range(-$r[1],-$r[count($r)-2]))$y[]=array_map(strlen,$x[]=$r);for($i=0;$i<count($y[0]);$i++)$z[$i]=max(array_column($y,$i));foreach($x as $g){$o=[];foreach($g as$k=>$v)$o[]=sprintf("%$z[$k]d",$v);echo join(",",$o)."\n";}

```

Online Interpreter

# Answer
> 3 votes
**C# console application 196 Bytes**

```
static void p(int a,int b){string S="",d ="";int c=-1;for(int i=b;i >=a;i--){c=c==1?c=-1:c=1;for(int j = a;j<=i;j++){S=j!=a?",":S="";d=d+S+(j*c);}d+= "\r\n";a++;}Console.Write(d);Console.Read();}

```

# Answer
> 2 votes
## Javascript - ~~196~~ ~~185~~ 176 bytes

```
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}l.shift();l.pop()}return h}

```

I'm not really up to speed with some of the newer JS techniques so this could probably be golfed much more.

Simply creates a good old-fashioned HTML table with no width defined for the cells so the first row defaults to the width of each entry hense optimal spacing. It also (ab)uses HTML's "feature" of not requiring closing tags if a new opening tag comes along first.

```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}l.shift();l.pop()}return h}
document.write(f(-1,1))
</script>
```

```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}l.shift();l.pop()}return h}
document.write(f(-3,6))
</script>
```

```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-2,8))
</script>
```

```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-15,8))
</script>
```

```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-3,15))
</script>
```

```
<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-12,12))
</script>
```

# Answer
> 2 votes
## Python 2 - 208 bytes

Try it online

```
d,u=input()
l=[x for x in range(d,u+1)]
M=map(lambda x:~9<x<21-u-u%2and 2or 3,l)
M[-1]-=1
M[-2]-=1
while len(l)>0:print','.join(map(lambda i:('%'+'%d'%M[i]+'d')%l[i],range(len(l))));l=map(lambda e:-e,l[1:-1])

```

Creates array of padding values and then use it to construct needed formated strings

Explanation:

```
d,u=input()
# create list of all values
l=[x for x in range(d,u+1)]
# create array of padding values
# by default, padding 2 used for numbers in [-9;9] and 3 for all other (limited with -99 and 99)
# but contracting list moves numbers larger that 9 under ones, that are <=9
# so upper limit of padding 2 is limited with 21-u-u%2
# (~9 == -10)
M=map(lambda x:~9<x<21-u-u%2and 2or 3,l)
# last two elements should have lower padding as there won't be any other numbers it their columns
M[-1]-=1
M[-2]-=1
while len(l)>0:
    # create formatted string for every element in l
    # join all strings with comma
    print','.join(map(lambda i:('%'+'%d'%M[i]+'d')%l[i],range(len(l))))
    # get slice without first and last element and change sigh
    l=map(lambda e:-e,l[1:-1])

```

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