text
stringlengths
180
608k
[Question] [ Given: * A natural number **S**. * A list of N rational weights **W** that sum to 1. Return a list **L** of N non-negative integers, such that: ``` (1) sum(L) = S (2) sum((S⋅W_i - L_i)^2) is minimal ``` In other words, approximate `S⋅W_i`s with integers as closely as possible. Examples: ``` 1 [0.4 0.3 0.3] = [1 0 0] 3 [0 1 0] = [0 3 0] 4 [0.3 0.4 0.3] = [1 2 1] 5 [0.3 0.4 0.3] = [2 2 1] or [1 2 2] but not [1 3 1] 21 [0.3 0.2 0.5] = [6 4 11] 5 [0.1 0.2 0.3 0.4] = [1 1 1 2] or [0 1 2 2] 4 [0.11 0.3 0.59] = [1 1 2] 10 [0.47 0.47 0.06] = [5 5 0] 10 [0.43 0.43 0.14] = [4 4 2] 11 [0.43 0.43 0.14] = [5 5 1] ``` Rules: * You can use any input format at all, or just provide a function that accepts the input as arguments. Background: This problem comes up when displaying **S** of different types of items in different proportions **Wi** with regard to the types. Another example of this problem is proportional political representation, see the [apportionment paradox](http://en.wikipedia.org/wiki/Apportionment_paradox). The last two test cases are known as Alabama paradox. > > As a statistician, I recognised this problem as equivalent to a > problem encountered in identifying sample sizes when conducting a > stratified sample. In that situation, we want to make the proportion > of each stratum in the sample equal to the proportion of each stratum > in the population. > — @tomi > > > [Answer] # Python 2, ~~95~~ ~~83~~ ~~132~~ ~~125~~ 143 My first (and second) (and third) algorithm had problems so after a (another!) rewrite and more testing, here is (I really hope) a correct and fast solution: ``` def a(b,h): g=h;c=[];d=[] for w in b:f=int(w*h);d+=[f];c+=[h*w-f];g-=f if g: for e in sorted(c)[-g:]:i=c.index(e);c[i]=2;d[i]+=1 return d ``` The source before the minifier now looks like: ``` # minified 143 bytes def golfalloc(weights, num): # Tiny seq alloc for golfing gap = num; errors = []; counts = [] for w in weights : count = int(w*num); counts += [count]; errors += [num*w - count]; gap -= count if gap: for e in sorted(errors)[-gap:] : i = errors.index(e); errors[i] = 2; counts[i] += 1 return counts ``` The tests return: ``` Pass Shape N Result Error AbsErrSum ok [0.4, 0.3, 0.3] 1 [1, 0, 0] -0.60,+0.30,+0.30 1.20 ok [0, 1, 0] 3 [0, 3, 0] +0.00,+0.00,+0.00 0.00 ok [0.3, 0.4, 0.3] 4 [1, 2, 1] +0.20,-0.40,+0.20 0.80 ok [0.3, 0.4, 0.3] 5 [2, 2, 1] -0.50,+0.00,+0.50 1.00 ok [0.3, 0.2, 0.5] 21 [6, 4, 11] +0.30,+0.20,-0.50 1.00 ok [0.1, 0.2, 0.3, 0.4] 5 [1, 1, 1, 2] -0.50,+0.00,+0.50,+0.00 1.00 ok [0.11, 0.3, 0.59] 4 [1, 1, 2] -0.56,+0.20,+0.36 1.12 ok [0.47, 0.47, 0.06] 10 [5, 5, 0] -0.30,-0.30,+0.60 1.20 ok [0.43, 0.43, 0.14] 10 [4, 4, 2] +0.30,+0.30,-0.60 1.20 ok [0.43, 0.43, 0.14] 11 [5, 5, 1] -0.27,-0.27,+0.54 1.08 ``` This algorithm is similar to other answers here. It is O(1) for num so it has the same run time for integers 10 and 1000000. It is theoretically O(nlogn) for the number of weights (because of the sort). If this withstands all other tricky input cases, it will replace the algorithm below in my programming toolbox. Please don't use that algorithm with anything not golfy. I made compromises in speed to minimise source size. The following code uses the same logic but is much faster and more useful: ``` def seqalloc(anyweights, num): # Distribute integer num depending on weights. # weights may be non-negative integers, longs, or floats. totalbias = float(sum(anyweights)) weights = [bias/totalbias for bias in anyweights] counts = [int(w*num) for w in weights] gap = num - sum(counts) if gap: errors = [num*w - q for w,q in zip(weights, counts)] ordered = sorted(range(len(errors)), key=errors.__getitem__) for i in ordered[-gap:]: counts[i] += 1 return counts ``` The value of num doesn't affect speed significantly. I have tested it with values from 1 to 10^19. The execution time varies linearly with the number of weights. On my computer it takes 0.15 seconds with 10^5 weights and 15 seconds with 10^7 weights. Note that the weights are not restricted to fractions that sum to one. The sort technique used here is also about twice as fast as the traditional `sorted((v,i) for i,v in enumerate...)` style. ### Original Algorithm This was a function in my toolbox, modified a little for golf. It was originally from a [SO answer](https://stackoverflow.com/a/9088667/3259619). And it is wrong. ``` def seqalloc(seq, num): outseq = [] totalw = float(sum(seq)) for weight in seq: share = int(round(num * weight / totalw)) if weight else 0 outseq.append(share) totalw -= weight num -= share return outseq ``` It gives an approximation, but is not always correct, although the sum(outseq) == num is maintained. Fast but not recommended. Thanks to @alephalpha and @user23013 for spotting the errors. EDIT: Set totalw (d) to be 1 as OP specifies the sum of weights will always be 1. Now 83 bytes. EDIT2: Fixed bug found for [0.4, 0.3, 0.3], 1. EDIT3: Abandoned flawed algorithm. Added better one. EDIT4: This is getting ridiculous. Replaced with correct (I really hope so) algorithm. EDIT5: Added not-golfy code for others that may like to use this algorithm. [Answer] # APL, 21 ``` {{⍵+1=⍋⍋⍵-⍺}⍣⍺/⍺0×⊂⍵} ``` This is a translation from [aditsu's 37 byte CJam answer](https://codegolf.stackexchange.com/a/45704/25180). [Test it online](http://tryapl.org/?a=21%7B%7B%u2375+1%3D%u234B%u234B%u2375-%u237A%7D%u2363%u237A/%u237A0%D7%u2282%u2375%7D0.3%200.2%200.5&run). ### Explanation ``` { ⍵-⍺} ⍝ Right argument - left argument. { 1=⍋⍋⍵-⍺} ⍝ Make one of the smallest number 1, others 0. {⍵+1=⍋⍋⍵-⍺} ⍝ Add the result and the right argument together. {⍵+1=⍋⍋⍵-⍺}⍣⍺ ⍝ Repeat that S times. The result of each iteration is the new right argument. ⊂⍵ ⍝ Return enclosed W, which is taken as one unit in APL. ⍺0×⊂⍵ ⍝ Return S*W and 0*W. {{⍵+1=⍋⍋⍵-⍺}⍣⍺/⍺0×⊂⍵} ⍝ Make S*W the left argument, 0*W the right argument in the first iteration. ``` [Answer] # Mathematica, ~~67~~ ~~50~~ ~~46~~ 45 chars ``` f=(b=⌊1##⌋;b[[#~Ordering~-Tr@#&[b-##]]]++;b)& ``` Ungolfed: ``` f[s_, w_] := Module[{a = s*w, b, c, d}, b = Floor[a]; c = b - a; d = Ordering[c, -Total[c]]; b[[d]] += 1; b] ``` Example: ``` f[5,{0.1,0.2,0.3,0.4}] ``` > > {1, 1, 1, 2} > > > [Answer] # CJam - 37 ``` q~:W,0a*\:S{[_SWf*]z::-_:e<#_2$=)t}*p ``` [Try it online](http://cjam.aditsu.net/#code=q~%3AW%2C0a*%5C%3AS%7B%5B_SWf*%5Dz%3A%3A-_%3Ae%3C%23_2%24%3D)t%7D*p&input=21%20%5B0.3%200.2%200.5%5D) **Explanation:** ``` q~ read and evaluate the input (pushing the number and the array on the stack) :W, save the array in variable W and calculate its length (N) 0a* make an array of N zeros (the initial "L") \:S swap it with the number and save the number in S {…}* execute the block S times [_SWf*] make a matrix with 2 rows: "L" and S*W z transpose the matrix, obtaining rows of [L_i S*W_i] ::-_ convert to array of L_i-S*W_i and duplicate :e< get the smallest element # find its index in the unsorted array, i.e. the "i" with the largest S*W_i-L_i _2$=)t increment L_i p print the result nicely ``` **Notes:** * The complexity is about O(S\*N), so it gets really slow for large S * CJam is sorely lacking arithmetic operators for 2 arrays, something I plan to implement later **Different idea - 46** ``` q~:Sf*_:m[_:+S\-@[1f%_,,]z{0=W*}$<{1=_2$=)t}/p ``` [Try it online](http://cjam.aditsu.net/#code=q~%3ASf*_%3Am%5B_%3A%2BS%5C-%40%5B1f%25_%2C%2C%5Dz%7B0%3DW*%7D%24%3C%7B1%3D_2%24%3D)t%7D%2Fp&input=%5B0.3%200.2%200.5%5D%2021) This is much more straightforward and efficient, but alas, quite a bit longer. The idea here is to start with L\_i=floor(S\*W\_i), determine the difference (say D) between S and their sum, find the D indices with the largest fractional part of S\*W\_i (by sorting and taking top D) and increment L\_i for those indices. Complexity O(N\*log(N)). [Answer] # JavaScript (ES6) 126 ~~130 104 115 156 162 194~~ After all the comments and test cases in @CarpetPython's answer, back to my first algorithm. Alas, the smart solution does not work. Implementation shortened a little, it still tries all the possible solutions, calc the squared distance and keep the minimum. *Edit* For each output element of weight w, 'all' the possible values are just 2: trunc(w\*s) and trunc(w\*s)+1, so there are just (2\*\*elemensts) possible solutions to try. ``` Q=(s,w)=> (n=>{ for(i=0; r=q=s,(y=i++)<1<<w.length; q|r>n||(n=r,o=t)) t=w.map(w=>(f=w*s,q-=d=0|f+(y&1),y/=2,f-=d,r+=f*f,d)); })()||o ``` **Test** In Firefox/FireBug console ``` ;[[ 1, [0.4, 0.3, 0.3] ] , [ 3, [0, 1, 0] ] , [ 4, [0.3, 0.4, 0.3] ] , [ 5, [0.3, 0.4, 0.3] ] , [ 21, [0.3, 0.2, 0.5] ] , [ 5, [0.1, 0.2, 0.3, 0.4] ] , [ 4, [0.11, 0.3, 0.59] ] , [ 10, [0.47, 0.47, 0.06] ] , [ 10, [0.43, 0.43, 0.14] ] , [ 11, [0.43, 0.43, 0.14] ]] .forEach(v=>console.log(v[0],v[1],Q(v[0],v[1]))) ``` *Output* ``` 1 [0.4, 0.3, 0.3] [1, 0, 0] 3 [0, 1, 0] [0, 3, 0] 4 [0.3, 0.4, 0.3] [1, 2, 1] 5 [0.3, 0.4, 0.3] [1, 2, 2] 21 [0.3, 0.2, 0.5] [6, 4, 11] 5 [0.1, 0.2, 0.3, 0.4] [0, 1, 2, 2] 4 [0.11, 0.3, 0.59] [1, 1, 2] 10 [0.47, 0.47, 0.06] [5, 5, 0] 10 [0.43, 0.43, 0.14] [4, 4, 2] 11 [0.43, 0.43, 0.14] [5, 5, 1] ``` ~~That's a smarter solution. Single pass on weigth array. For each pass i find the current max value in w. I change this value in place with the weighted integer value (rounded up), so if s==21 and w=0.4, we got 0.5\*21 -> 10.5 -> 11. I store this value negated, so it can't be found as max in the next loop. Then I reduce the total sum accordingly (s = s-11) and also reduce the total of the weigths in variable f. The loop ends when ther is no max above 0 to be found (all the values != 0 have been managed). At last I returns the values changed to positive again. **Warning** this code modifies the weights array in place, so it must be called with a copy of original array~~ ``` F=(s,w)=> (f=>{ for(;j=w.indexOf(z=Math.max(...w)),z>0;f-=z) s+=w[j]=-Math.ceil(z*s/f); })(1)||w.map(x=>0-x) ``` **My first try** Not so a smart solution. For every possible result, it evaluates the difference, and keeps the minimum. ``` F=(s,w,t=w.map(_=>0),n=NaN)=> (p=>{ for(;p<w.length;) ++t[p]>s?t[p++]=0 :t.map(b=>r+=b,r=p=0)&&r-s|| t.map((b,i)=>r+=(z=s*w[i]-b)*z)&&r>n||(n=r,o=[...t]) })(0)||o ``` **Ungolfed** And explained ``` F=(s, w) => { var t=w.map(_ => 0), // 0 filled array, same size as w n=NaN, // initial minumum NaN, as "NaN > value" is false for any value p, r // For loop enumerating from [1,0,0,...0] to [s,s,s...s] for(p=0; p<w.length;) { ++t[p]; // increment current cell if (t[p] > s) { // overflow, restart at 0 and point to next cell t[p] = 0; ++p; } else { // increment ok, current cell is the firts one p = 0; r = 0; t.map(b => r += b) // evaluate the cells sum (must be s) if (r==s) { // if sum of cells is s // evaluate the total squared distance (always offset by s, that does not matter) t.map((b,i) => r += (z=s*w[i]-b)*z) if (!(r > n)) { // if less than current mininum, keep this result n=r o=[...t] // copy of t goes in o } } } } return o } ``` [Answer] # CJam, 48 bytes A straight forward solution to the problem. ``` q~:Sf*:L,S),a*{m*{(+}%}*{1bS=},{L]z::-Yf#:+}$0=p ``` Input goes like ``` [0.3 0.4 0.3] 4 ``` Explanation: ``` q~:S "Read and parse the input, store sum in S"; f*:L "Do S.W, store the dot product in L"; S), "Get array of 0 to S"; , a* "Create an array with N copies of the above array"; {m*{(+}%}* "Get all possible N length combinations of 0 to S ints"; {1bS=}, "Filter to get only those which sum up to S"; {L]z::-Yf#:+}$ "Sort them based on (S.W_i - L_i)^2 value"; L "Put the dot product after the sum combination"; ]z "Wrap in an array and transpose"; ::- "For each row, get difference, i.e. S.W_i - L_i"; Yf# "Square every element"; :+ "Take sum"; 0=p "After sorting on sum((S.W_i - L_i)^2), take the"; "first element, i.e. smallest sum and print it"; ``` [Try it online here](http://cjam.aditsu.net/#code=q~%3ASf*%3AL%2CS)%2Ca*%7Bm*%7B(%2B%7D%25%7D*%7B1bS%3D%7D%2C%7BL%5Dz%3A%3A-Yf%23%3A%2B%7D%240%3Dp&input=%5B0.3%200.2%200.5%5D%2021) [Answer] # Pyth: 40 bytes ``` Mhosm^-*Ghded2C,HNfqsTGmms+*G@Hb}bklHyUH ``` This defines a function `g` with 2 parameters. You can call it like `Mhosm^-*Ghded2C,HNfqsTGmms+*G@Hb}bklHyUHg5 [0.1 0.2 0.3 0.4`. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/) ## Explanation: ``` mms+*G@Hb}bklHyUH (G is S, H is the list of weights) m yUH map each subset k of [0, 1, ..., len(H)-1] to: m lH map each element b of [0, 1, ..., len(H)-1] to: *G@Hb G*H[b] + }bk + b in k s floor(_) ``` This creates all possible solutions `L`, where `L[i] = floor(S*W[i])` or `L[i] = floor(S*W[i]+1)`. For instance, the input `4 [0.3 0.4 0.3` creates `[[1, 1, 1], [2, 1, 1], [1, 2, 1], [1, 1, 2], [2, 2, 1], [2, 1, 2], [1, 2, 2], [2, 2, 2]]`. ``` fqsTG... f ... only use the solutions, where qsTG sum(solution) == G ``` Only `[[2, 1, 1], [1, 2, 1], [1, 1, 2]]` remain. ``` Mhosm^-*Ghded2C,HN o order the solutions by s the sum of m C,HN map each element d of zip(H, solution) to ^-*Ghded2 (G*d[0] - d[1])^2 h use the first element (minimum) M define a function g(G,H): return _ ``` [Answer] # Mathematica 108 ``` s_~f~w_:=Sort[{Tr[(s*w-#)^2],#}&/@ Flatten[Permutations/@IntegerPartitions[s,{Length@w},0~Range~s],1]][[1,2]] ``` --- ``` f[3, {0, 1, 0}] f[4, {0.3, 0.4, 0.3}] f[5, {0.3, 0.4, 0.3}] f[21, {0.3, 0.2, 0.5}] f[5, {0.1, 0.2, 0.3, 0.4}] ``` > > {0, 3, 0} > > {1, 2, 1} > > {1, 2, 2} > > {6, 4, 11} > > > > --- ## Explanation Ungolfed ``` f[s_,w_]:= Module[{partitions}, partitions=Flatten[Permutations/@IntegerPartitions[s,{Length[w]},Range[0,s]],1]; Sort[{Tr[(s *w-#)^2],#}&/@partitions][[1,2]]] ``` `IntegerPartitions[s,{Length@w},0~Range~s]` returns all the integer partitions of `s`, using elements taken from the set `{0, 1, 2, ...s}` with the constraint that the output should contain the same number of elements as in the set of weights, `w`. `Permutations` gives all of the ordered arrangements of each integer partition. `{Tr[(s *w-#)^2],#}` returns a list of ordered pairs, `{error, permutation}` for each permutation. `Sort[...]` sorts the list of `{{error1, permutation1},{error2, permutation2}...according to the size of the error.` `[[1,2]]]` or `Part[<list>,{1,2}]` returns the second item of the first element in the sorted list of `{{error, permutation}...}`. In other words, it returns the permutation with the smallest error. [Answer] # R, ~~85~~ ~~80~~ 76 Uses the Hare Quota method. Removed a couple after seeing the spec that **W** will sum to 1 ``` function(a,b){s=floor(d<-b*a);s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s} ``` Test run ``` > (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(3,c(0,1,0)) [1] 0 3 0 > (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(1,c(0.4,0.3,0.3)) [1] 1 0 0 > (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(4,c(0.3, 0.4, 0.3)) [1] 1 2 1 > (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(5,c(0.3, 0.4, 0.3)) [1] 1 2 2 > (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(21,c(0.3, 0.2, 0.5)) [1] 6 4 11 > (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(5,c(0.1,0.2,0.3,0.4)) [1] 1 1 1 2 > ``` [Answer] # Python, ~~139~~ ~~128~~ 117 bytes ``` def f(S,W): L=(S+1,0,[]), for n in W:L=[(x-i,y+(S*n-i)**2,z+[i])for x,y,z in L for i in range(x)] return min(L)[2] ``` ## Previous itertools solution, 139 bytes ``` from itertools import* f=lambda S,W:min((sum(x)!=S,sum((S*a-b)**2for a,b in zip(W,x)),list(x))for x in product(*tee(range(S+1),len(W))))[2] ``` [Answer] # Octave, ~~87~~ 76 Golfed: ``` function r=w(s,w)r=0*w;for(i=1:s)[m,x]=max(s*w-r);r(x)+=1;endfor endfunction ``` Ungolfed: ``` function r=w(s,w) r=0*w; # will be the output for(i=1:s) [m,x]=max(s*w-r); r(x)+=1; endfor endfunction ``` (Blasted "endfor" and "endfunction"! I'll never win but I do enjoy golfing with a "real" language.) [Answer] # T-SQL, ~~167~~ 265 Because I like to try and do these challenges in a query as well. Turned it into an inline function to better fit the spec and created a type for the table data. It cost a bit, but this was never going to be a contender. Each statement needs to be run separately. ``` CREATE TYPE T AS TABLE(A INT IDENTITY, W NUMERIC(9,8)) CREATE FUNCTION W(@ int,@T T READONLY)RETURNS TABLE RETURN SELECT CASE WHEN i<=@-SUM(g)OVER(ORDER BY(SELECT\))THEN g+1 ELSE g END R,A FROM(SELECT A,ROW_NUMBER()OVER(ORDER BY (W*@)%1 DESC)i,FLOOR(W*@)g FROM @T)a ``` In use ``` DECLARE @ INT = 21 DECLARE @T T INSERT INTO @T(W)VALUES(0.3),(0.2),(0.5) SELECT R FROM dbo.W(@,@T) ORDER BY A R --------------------------------------- 6 4 11 ``` ]
[Question] [ For a given positive integer number N, write a complete program to find the minimal natural M such that the product of digits of M is equal N. N is less than 1,000,000,000. If no M exists, print -1. Your code should not take more than 10 secs for any case. ``` Sample Inputs 1 3 15 10 123456789 32 432 1296 Sample Outputs 1 3 35 25 -1 48 689 2899 ``` [Answer] ## Javascript (84 78 76 74 72 70 68) ``` n=prompt(m="");for(i=9;i-1;)n%i?i--:(m=i+m,n/=i);alert(n-1?-1:m?m:1) ``` <http://jsfiddle.net/D3WgU/7/> **Edit:** Borrowed input/output idea from other solution, and shorter output logic. **Edit 2:** Saved 2 chars by removing unneeded braces in `for` loop. **Edit 3:** Saved 2 chars by rewriting `while` loop as `if` statement with `i++`. **Edit 4:** Saved 2 chars by moving around and reducing operations on `i`. **Edit 5:** Convert if statement into ternary format saving 2 more chars. **Edit 6:** Save 2 chars by moving `i--` into true part of ternary, remove `++i`. [Answer] ### Golfscript, 45 43 40 chars ``` ~9{{1$1$%!{\1$/1$}*}12*(}8*>{];-1}*]$1or ``` Replaces version which didn't group small primes into powers and saves 8 chars while doing so. Note: 12 = floor(9 log 10 / log 5). Acknowledgements: two characters saved by nicking a trick from @mellamokb; 3 saved with a hint from @Nabb. [Answer] ## JavaScript, ~~88~~ ~~72~~ ~~78~~ ~~74~~ ~~69~~ 68 ~~``` for(s='',i=2,m=n=prompt();i<m;i++)while(!(n%i)){if(i>9){alert(-1);E()}n/=i;s+=i}alert(s) ``` 4 characters longer, but actually an executable script (as opposed to a function).~~ ~~Edit: Using ideas from the other JavaScript, I can reduce it to this:~~ ``` for(s='',i=9,n=prompt();i>1;i--)for(;!(n%i);n/=i)s=i+s;alert(n-1?-1:s?s:1) ``` ~~**Finally!** A 69-character solution, only uses 1 for loop ;)~~ ``` for(s='',i=9,n=prompt();i>1;n%i?i--:[n/=i,s=i+s]);alert(n-1?-1:s?s:1) ``` Okay, shaved off one comma. ``` for(i=9,n=prompt(s='');i>1;n%i?i--:[n/=i,s=i+s]);alert(n-1?-1:s?s:1) ``` [Answer] ## awk (63 61 59 58 57) ``` {for(i=9;i>1;$1%i?i--:($1/=i)<o=i o);print 1<$1?-1:o?o:1} ``` [Answer] ## Perl (75) (72) ``` $d=shift;map{$m=$_.$m,$d/=$_ until$d%$_}reverse 2..9;print$d-1?-1:$m||1 ``` inspired by mellamokb's javascript code; meant to be run with a parameter [Answer] ## GolfScript (60 57) ``` ~[{9,{)}%{\.@%!},)\;.@@/.9>2$1>&}do])[.])@@{1>},+\9>[-1]@if$ ``` ``` ~{9,{)}%{\.@%!},)\;.@@/.9>2$1>&}do])[.])@@{1>},+$\9>-1@if ``` **Edit** Ok, I think this version gives correct output for every case now :-) **Edit 2** Shaved off 3 chars per @Peter's suggestions. [Answer] ## Haskell ``` f n=head([m|m<-[1..10^9],product(map(read.return)$show m)==n]++[-1]) ``` [Answer] ## Windows PowerShell, 87 ``` if(($n="$args")-le1){$n;exit}(-1,-join(9..2|%{for(;!($n%$_)){$_;$n/=$_}}|sort))[$n-eq1] ``` [Answer] # Perl (68) ``` $x=pop;map{$_-=11;$x/=$_,$@=-$_.$@until$x%$_}1..9;print!$x?-1:$@||1 ``` It *seems* like the awesome trick that @mellamokb uses in javascript to avoid the nested loop would translate well to perl but it comes out much more verbose because you cannot use the `foreach` style loop any longer. It's also a pity that perl does not think `map` is a loop else `redo` would come in handy. [Answer] ### scala 106 chars: ``` def p(n:Int,l:Int=9):List[Int]=if(n<=9)List(n)else if(l<2)List(-1)else if(n%l==0)l::p(n/l,l)else p(n,l-1) ``` Test & Invocation: ``` scala> val big=9*9*9*8*8*8*7*7*7*5*3 big: Int = 1920360960 scala> p(big) res1: List[Int] = List(9, 9, 9, 8, 8, 8, 7, 7, 7, 5, 3) ``` Response time: immediately, < 1s on 2Ghz CPU. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 13 10 bytes ``` ×⁵RDP$€io- ``` [Try it online!](https://tio.run/##y0rNyan8///w9EeNW4NcAlQeNa3JzNf9//@/ibERAA "Jelly – Try It Online") **13-byte solution:** ``` ×⁵RDP$€iµ’¹¬? ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//w5figbVSRFAk4oKsacK14oCZwrnCrD////80MzI "Jelly – Try It Online") Explanation with input `N`: ``` ׳R create a range from 1 to N * 100 (replace ³ with ⁵ for a faster execution time) DP$ define a function ($) to get the product of the digits of a number, € apply that function to each element in the list, iµ get the index of the input N in the list (or 0 if it's not there), and yeild it as the input to the next link, ’¹¬? conditional: if the answer is 0, then subtract one to make it -1, otherwise, yeild the answer ``` **18-byte solution:** ``` D×/ ×⁵RÇ€i Ç⁾-1¹¬? ``` [Try it online!](https://tio.run/##y0rNyan8/9/l8HR9rsPTHzVuDTrc/qhpTSYXkGrcp2t4aOehNfb///83MTYCAA "Jelly – Try It Online") ``` D×/ product of digits function, takes input M D split M into digits, ×/ reduce by multiplication (return product of digits) ×⁵RÇ€i range / index function ×⁵R make a range from 1 to N*10, Ç€ run the above function on each of the range elements, i get the index of N in the result, or 0 if it's not there Ç⁾-1¹¬? main function: Ç ¬? run the line above and check if the answer is null (0) ⁾-1 if it is, return "-1", ¹ otherwise, return the answer (identity function). ``` The last link is only to replace 0 (Jelly's default falsey value, as all lists are one-indexed) with -1. If you consider 0 an OK falsey value, the program is **8 bytes**. [Answer] ## Ruby (100) ``` n=gets.to_i;(d=1..9).map{|l|[*d].repeated_combination(l){|a|a.reduce(:*)==n&&(puts a*'';exit)}};p -1 ``` [Answer] # [Python 2](https://docs.python.org/2/), 89 bytes ``` f=lambda n,a=0,u=1,i=9:n<2and(a or 1)or-(i<2)or n%i<1and f(n/i,a+i*u,u*10)or f(n,a,u,i-1) ``` [Try it online!](https://tio.run/##FYzNCoMwEITveYq9FNSu1I1/jZgnKT2kiHShXUUM2KdP18PMwPfBrL/9vYhNafaf8H1NAQSDrzB6QvZukNEGmbIAywaUL1uZ8Wh1QS48kiqYM7kxhisXEWNB1SmVYcCIXFKeZgUHsMCDEGoEajWVxtZN2/V3p9QiNGeRdd1zMLBuLLveHHkiY01tGtOazvR/ "Python 2 – Try It Online") Just because there's no Python answer yet. It's really painful to lack implicit type conversion between string and int. ]
[Question] [ We already have a challenge for [computing the GCD of two Gaussian integers](https://codegolf.stackexchange.com/questions/231182/greatest-common-gaussian-divisor), but that challenge explicitly allows to choose any of the four possible values. Your task now is to bring the Gaussian integer computed by the GCD in the following normal form: 1. The result differs from the original number by a factor of `1`,`i`,`-1` or `-i` 2. The result is zero, or the real part is positive 3. The imaginary part is non-negative Input: A Gaussian integer (complex number with integer real and imaginary parts) Output: The normal form (see above) of that Gaussian integer ## Examples: ``` 0 -> 0 5 -> 5 2i -> 2 1+i -> 1+i 1-i -> 1+i 3-5i -> 5+3i -3+5i -> 5+3i 3+5i -> 3+5i -3-5i -> 3+5i ``` ## Rules * You can use pairs instead of complex numbers for input/output * If your language has a built-in for this operation consider adding a non built-in solution as well * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution wins [Answer] # [J](https://www.jsoftware.com), 14 bytes Takes input as a complex number. ``` (0,o.%2)&|&.*. ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxTsNAJ19P1UhTrUZNT0sPInjTXJMrNTkjX0FDRy9NyUBTwSDLQMEUiA2yjBQMswyBON5QwTgr3lQh3jjLVAGE40FciPYFCyA0AA) Convert to polar coordinates, take the angle modulo \$\frac\pi2\$, convert back. The first rule allows for 90˚ or \$\frac\pi2\$ rotations on the complex plane, the other two rules specify the result should be in the upper-right quadrant or on the non-negative part of the real axis. This means the resulting complex number should have an angle in \$\left[0,\frac\pi2\right)\$ and the same magnitude as the input. --- # [J](https://www.jsoftware.com), 12 bytes Takes input as a pair of integers. ``` ||.~1=2|@#.* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxpqZGr87Q1qjGQVlPCyJ001qTKzU5I19BQ0cvTU1PW0_JQFPBIMtAwRSIDbKMFAyzDIE43lDBOCveVCHeOMtUAYTjQVyIEQsWQGgA) Take the absolute value of both values and swap them if: * one is negative, the other positive, or * the first (real) part is zero. [Answer] # [Python](https://www.python.org), 46 bytes ``` f=lambda x,y:f(-y,x)if(x|y)*(y|x-1<0)else(x,y) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZHdToQwEIXjbZ9i0htaaQksITFE9kXUmLq2WlJYQrsG9udJvNkbfSd9GgsEdu3NOdPzTWbSfn43vXvf1ufz184pfvcTqcKI6uVVQMf6XBHes45qRbpjT29Jf-x4ch9TaawkHqBT1-9NXhZJifYFxjgGvoYYZYNkaKUHXaEkHI0XlPDFpjwbfRamGvE0vKrmYlAf8UvlZ0S2MdoR_Fhj6qc-6KiVjREbSQIdsKAM6EzwNaagti1o0DXsnwbaaOtIJRoiP4RhmtLrfPBOWve8EVYyaKXdGTdmOQJ_mlbXDojCh4UqTnCYuMEp4gGyhH4zYSiD_5e6Em-Unvz2aHrC-QP-AA) * -25 bytes thanks to Arnould and Bsoelch * -3 bytes thanks to Arnould * -1 byte thanks to The Thonnu [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ×ƬıÆiṠ$ÞṪ ``` A monadic Link that accepts the Gaussian integer as a complex number and yields a complex number. **[Try it online!](https://tio.run/##y0rNyan8///w9GNrjmw83Jb5cOcClcPzHu5c9V/ncLum@///0QbaBlk6CqZg0kDbCEgaahuCSF0QaaxrCiR1jbVBFITUhYuBtegaZ8UCAA "Jelly – Try It Online")** ### How? ``` ×ƬıÆiṠ$ÞṪ - Link: Gaussian integer, G ı - imaginary unit Ƭ - starting with G, collect up while distinct applying: × - multiply by {imaginary unit} Þ - sort by: $ - last two links as a monad: Æi - convert to [real, imaginary] parts Ṡ - signs (-x:-1, 0:0, x:1) Ṫ - tail ``` [Answer] # JavaScript (ES6), 32 bytes *-3 bytes thanks to [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha)* Expects `(real, imaginary)`. Returns `[real, imaginary]`. ``` f=(r,i)=>r<!!i|i<0?f(-i,r):[r,i] ``` [Try it online!](https://tio.run/##dcyxDoIwEMbxnac4tjbtSaHpYgAfxDgQBFNDqCnGyXevQAUSGqZv@P/untWnGmqrX2/szb1xri2I5ZoWpc3jWH91Li4tQc0tPV/HcHO16QfTNafOPEhLQHAQlEKSgAAsQUS7rtaupq6i8D7zPdMTyPYg5ZB6kLJZjBMaXAweGclReSNRzUgxuVcoOfwVSnbIYGOLmjZ8husz3Jj7AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ±BṅßǓȧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJBIiwiIiwiwrFC4bmFw5/Hk8inIiwiIiwiWzAsMF1cbls1LDBdXG5bMCwyXVxuWzEsMV1cblsxLC0xXVxuWzMsLTVdXG5bLTMsNV1cblszLDVdXG5bLTMsLTVdIl0=) Port of jelly with conditional execute rather than repeating 0 or 1 times [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 76 bytes ``` \bi 1i ^-?(\d+)i?$ $1 ^-(\d+)([+-].*) $1-$2 -- + (.+)-\+?(.+)i $2+$1i \b1i i ``` [Try it online!](https://tio.run/##HYyxCoRAEEP7fMcc7N4Q0RXrLf0IV1HRYporxP/fGy3yQgLJdd722@onjGstu6EzLMyhHBotC6Tz@KYwKefmG72iJJBQhEYji@bHDZJUfF52h9XaYkDyQ3XR0HMwsFfnCz7FHw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \bi 1i ``` Change `i`, `+i` and `-i` to `1i`, `+1i` and `-1i`. ``` ^-?(\d+)i?$ $1 ``` Change multiples of powers of `i` to their absolute value. ``` ^-(\d+)([+-].*) $1-$2 ``` If the real part is negative then negate the whole value. ``` -- + ``` Fix up a double negation of the imaginary part. ``` (.+)-\+?(.+)i $2+$1i ``` If the imaginary part is negative then multiply by `i`. ``` \b1i i ``` Change `+1i` to `+i`. (It can't be `i` or `-i` at this point.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes Input and output as a pair of integers. Port of my second J answer. ``` ṠḄỊṙ@A ``` [Try it online!](https://tio.run/##y0rNyan8///hzgUPd7Q83N31cOdMB8f/h9sfNa1x//8/OtpAxyBWRyHaFEIZ6BiBKEMdQwilC6aNdXRNQbSusY4phA/jAsVjAQ "Jelly – Try It Online") ``` Ṡ -- sign of each integer Ḅ -- convert from binary Ị -- insignificant / absolute value <= 1 ṙ@ -- this number of times (0 or 1), rotate ... A -- the absolute value of each integer ``` [Answer] # [R](https://www.r-project.org), 37 bytes ``` \(x)complex(,,,Mod(x),Arg(x)%%(pi/2)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3VWM0KjST83MLclIrNHR0dHzzU4ACOo5F6UBKVVWjIFPfSFMTqrg9TcNAU0FZ107BgCtNwxTCNAUyjTIhbCMg21DbEMoz1M4E8XVR-ca6plC-qbYxSEDXWBtNBCEAYoGV6CKLQJyzYAGEBgA) Port of the first approach in [J answer](https://codegolf.stackexchange.com/a/264734/78274) by ovs. Inputs and outputs complex numbers. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 35 bytes ``` f(x,y)=if(x<!!y||y<0,f(y,-x),[x,y]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5BCsIwEEWvMq2bxM5AbSl0Ud17hiKShSmBKiFUSKQ3cdONeCZvYxKSzX_Mf7P4768WRl0nvW2f5yKp_-0ks-j4UXkOReHW1Q01SuaQLMfRuwtPry-h9eyYBTqBNuqxMHMTM7McSoQS1F1M8Qi-BJktJsE5wlgjdAjUIDT7M8KhCkE-WupCQW0VmUCxzgvy6D8) Takes input as `real,imag` and outputs `[real,imag]`. [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 7 bytes ``` ±đZ≠nŘA ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FmsObTwyMepR54K8ozMclxQnJRdDJRbctIo20DGI5Yo2BZMGOkZA0lDHEEzqgihjHV1TIKVrrGMK5kE5QEGIEQA) A port of [@ovs's Jelly answer](https://codegolf.stackexchange.com/a/264831/9288). Takes a pair of integers as input, and outputs a pair of integers. ``` ±đZ≠nŘA ± Sign đ Split the pair into two integers Z Check if the second integer is non-zero ≠ Check if the two integers are not equal n Return 0 if the check fails, 1 if it passes Ř Rotate the input that many times A Absolute value ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` ≔E²NθF⁴«⊞υθ≔E⮌θ⎇λκ±κθ»I⌈Φυ¬›⁰§ι¹ ``` [Try it online!](https://tio.run/##TY3LCoMwFETX@hVZ3kCEPleupNDioiKlP5DaWw3GqHmIpfTb0xQpdHYzcM5UDddVz6X3mTGiVnDmA2wYydXgbOG6G2qglJGRpvGj1wR2lLziqHSmAbfM0R95wQm1QRgDckWtuH6CZKRlpMCaW4SW/mzvuNRCWThwYwM7i851cBTShsdgLnoLJ438W1eMZDZXd5xBMLKmS1Lv93Gy9ckkPw "Charcoal – Try It Online") Link is to verbose version of code. I/O is a pair of integers. Explanation: ``` ≔E²Nθ ``` Input the Gaussian integer. ``` F⁴«⊞υθ≔E⮌θ⎇λκ±κθ» ``` Multiply it by the powers of `i`. ``` I⌈Φυ¬›⁰§ι¹ ``` Filter out those values with negative imaginary parts and take the remaining value with the largest real part. There are three cases: * If the Gaussian integer is zero, then all of the values will be zero, and so the output will be zero. * If the Gaussian integer is a non-zero multiple of a power of `i`, then only one of the values will have a positive real part, and this is the value we want. * If the Gaussian integer has neither real nor complex part zero, then there will be two values with positive real parts, but one will have a negative imaginary part which will have been filtered out, so we obtain the value with both parts positive. [Answer] # ARM64 machine code, 28 bytes ``` b40000a1 aa0003e2 cb0103e0 aa0203e1 b7ffffa1 b7ffff80 d65f03c0 ``` Assembly source: ``` .text .global make_positive .balign 4 make_positive: // If z is already real, jump directly to check if the real part is nonnegative cbz x1, check_real_part multiply_again: // multiply by i mov x2, x0 neg x0, x1 mov x1, x2 // see if both parts nonnegative tbnz x1, #63, multiply_again check_real_part: tbnz x0, #63, multiply_again ret ``` This function takes the real and imaginary parts as 64-bit signed integers in x0 and x1 respectively, and returns the result in the same two registers. This is in keeping with usual ARM64 calling conventions for something like `struct complex { int64_t re, im; };` passed by value. The basic algorithm is: ``` do { z *= i; } while (z.im < 0 || z.re < 0); ``` The only case for which this doesn't work is if the starting value of `z` is positive real. So if z is pure real (`z.im == 0`), we jump directly to the `z.re < 0` test; if that branch is not taken then `z` is already nonnegative real and we are done. Spending three instructions to multiply by `i` seems like a lot, but the issue is that we have to do it in place, and there's no "swap registers" instruction so we need a temporary third register. Note that if either part of the input is -2^63 (`LONG_MIN`) then the function will enter an infinite loop. However this should be disallowed anyway since the normal form of such a number cannot be represented in signed 64-bit. ## Branchless version, 36 bytes As a bonus, I also tried writing a branchless version, but so far have only been able to get down to 36 bytes. The idea is to conditionally multiply by `-1` and `i` in turn ``` .text .global make_positive_branchless .balign 4 make_positive_branchless: // if real part is negative, multiply by -1 cmp x0, #0 cneg x2, x0, lt cneg x3, x1, lt // if real part was zero and imaginary part now positive, we must negate again // so that multiplication by i gives a positive real result ccmp x3, #0, #4, eq // nZcv, for which GT is false cneg x3, x3, gt // now if imaginary part is negative, multiply by i cmp x3, #0 csneg x0, x2, x3, ge csel x1, x3, x2, ge ret ``` [Answer] # [Scala](https://www.scala-lang.org/), 67 bytes Fixed underlying error thanks to the comment of [@bsoelch](https://codegolf.stackexchange.com/users/118682/bsoelch) --- Port of [@mousetail's Python answer](https://codegolf.stackexchange.com/a/264735/110802) in Scala. --- ``` def f(x:Int,y:Int):(Int,Int)=if((x|y)!=0&(y|x-1)<0)f(-y,x)else(x,y) ``` [Try it online!](https://tio.run/##bY9RS8MwEMff@ynOMeQCCbRKX8r64ONAQdA3EYldUipZN5Ioybp@9pp01q1iIJf73f/y585UXPFh9/4hKgsPvGmhGzZCgkRXrFtLfYykwJjHrGwkojt6clWm1@iPjmVklRKJzFNHhDICHfVkAIgu22CIXNemgDutuX95srpp61cCXQLhjOGLKzhACfeNsThWADClkBI6UT6joN2cKaOQzYhd4G3A/IwscD5T/4iheUSSjI/cacCKG/EsjIUVg8M0@Wls1IKrR64thWbL65iRsMn046dzH3a2qkWzsKH4FtVy@euqhflU9qIgy2Un/3PuF6fh@iTepB@@AQ) ]
[Question] [ Write a program that produces mirror images of itself. An example, would be the [fantastic camel code](http://www.perlmonks.org/?node_id=45213) that reads it's own code and produces two smaller 2x2 versions. Given the input: ``` $_='ev al("seek\040D ATA,0, 0;");foreach(1..3) {<DATA>;}my @camel1hump;my$camel; my$Camel ;while( <DATA>){$_=sprintf("%-6 9s",$_);my@dromedary 1=split(//);if(defined($ _=<DATA>)){@camel1hum p=split(//);}while(@dromeda ry1){my$camel1hump=0 ;my$CAMEL=3;if(defined($_=shif t(@dromedary1 ))&&/\S/){$camel1hump+=1<<$CAMEL;} $CAMEL--;if(d efined($_=shift(@dromedary1))&&/\S/){ $camel1hump+=1 <<$CAMEL;}$CAMEL--;if(defined($_=shift( @camel1hump))&&/\S/){$camel1hump+=1<<$CAMEL;}$CAMEL--;if( defined($_=shift(@camel1hump))&&/\S/){$camel1hump+=1<<$CAME L;;}$camel.=(split(//,"\040..m`{/J\047\134}L^7FX"))[$camel1h ump];}$camel.="\n";}@camel1hump=split(/\n/,$camel);foreach(@ camel1hump){chomp;$Camel=$_;y/LJF7\173\175`\047/\061\062\063\ 064\065\066\067\070/;y/12345678/JL7F\175\173\047`/;$_=reverse; print"$_\040$Camel\n";}foreach(@camel1hump){chomp;$Camel=$_;y /LJF7\173\175`\047/12345678/;y/12345678/JL7F\175\173\0 47`/; $_=reverse;print"\040$_$Camel\n";}';;s/\s*//g;;eval; eval ("seek\040DATA,0,0;");undef$/;$_=<DATA>;s/\s*//g;( );;s ;^.*_;;;map{eval"print\"$_\"";}/.{4}/g; __DATA__ \124 \1 50\145\040\165\163\145\040\157\1 46\040\1 41\0 40\143\141 \155\145\1 54\040\1 51\155\ 141 \147\145\0 40\151\156 \040\141 \163\16 3\ 157\143\ 151\141\16 4\151\1 57\156 \040\167 \151\164\1 50\040\ 120\1 45\162\ 154\040\15 1\163\ 040\14 1\040\1 64\162\1 41\144 \145\ 155\14 1\162\ 153\04 0\157 \146\ 040\11 7\047\ 122\1 45\15 1\154\1 54\171 \040 \046\ 012\101\16 3\16 3\15 7\143\15 1\14 1\16 4\145\163 \054 \040 \111\156\14 3\056 \040\ 125\163\145\14 4\040\ 167\1 51\164\1 50\0 40\160\ 145\162 \155\151 \163\163 \151\1 57\156\056 ``` it produces: ``` JXXXXXXXXL. JXXLm. .mJXXL .JXXXXXXXXL {XXXXXXXXXXX. JXXXmXXXXm mXXXXmXXXL .XXXXXXXXXXX} .XXXXXXXXXXXXXL. {XXXXXXXXXF 7XXXXXXXXX} .JXXXXXXXXXXXXX. JXXXXXXXXXXXXXXXXL.`XXXXXX. .XXXXXX'.JXXXXXXXXXXXXXXXXL JXXXXXXXXXXXXXXXXXXXmXXXXXXX. .XXXXXXXmXXXXXXXXXXXXXXXXXXXL .XXXXXXXXXXXXXXXXXXXXXXXXXXXXX} {XXXXXXXXXXXXXXXXXXXXXXXXXXXXX. .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXF 7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX'7XXXXXXXXXXXXXXXXXXXXXXXXXF 7XXXXXXXXXXXXXXXXXXXXXXXXXF`XX XX {XXXFXXXXXXXXXXXXXXXXXXXF' `7XXXXXXXXXXXXXXXXXXX7XXX} XX `X}{XXX'7XXXFXXXXX^XXXXX `' `' XXXXX^XXXXX7XXXF`XXX}{X' `'XXX' {XXX'XXXXX 7XXXF 7XXXF XXXXX`XXX} `XXX`' .XX} {XXF {XXXX}`XXX} {XXX'{XXXX} 7XX} {XX. {XX `XXL `7XX} 7XX} {XXF {XXF' JXX' XX} `XX `XXL mXXF {XX XX} 7XXm JXX' XX' XX 7XXXF `XX XX' 7XXXF XX XX. JXXXX. 7X. .XF .XXXXL .XX {XXL 7XF7XXX. {XX XX} .XXXF7XF JXX} `XXX' `XXXm mXXX' `XXX' ^^^^^ ^^^^^ .mJXXL .JXXXXXXXXL JXXXXXXXXL. JXXLm. mXXXXmXXXL .XXXXXXXXXXX} {XXXXXXXXXXX. JXXXmXXXXm 7XXXXXXXXX} .JXXXXXXXXXXXXX. .XXXXXXXXXXXXXL. {XXXXXXXXXF .XXXXXX'.JXXXXXXXXXXXXXXXXL JXXXXXXXXXXXXXXXXL.`XXXXXX. .XXXXXXXmXXXXXXXXXXXXXXXXXXXL JXXXXXXXXXXXXXXXXXXXmXXXXXXX. {XXXXXXXXXXXXXXXXXXXXXXXXXXXXX. .XXXXXXXXXXXXXXXXXXXXXXXXXXXXX} XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXF 7XXXXXXXXXXXXXXXXXXXXXXXXXF`XX XX'7XXXXXXXXXXXXXXXXXXXXXXXXXF `7XXXXXXXXXXXXXXXXXXX7XXX} XX XX {XXXFXXXXXXXXXXXXXXXXXXXF' `' XXXXX^XXXXX7XXXF`XXX}{X' `X}{XXX'7XXXFXXXXX^XXXXX `' 7XXXF XXXXX`XXX} `XXX`' `'XXX' {XXX'XXXXX 7XXXF {XXX'{XXXX} 7XX} {XX. .XX} {XXF {XXXX}`XXX} {XXF {XXF' JXX' XX} {XX `XXL `7XX} 7XX} XX} 7XXm JXX' XX' `XX `XXL mXXF {XX XX' 7XXXF XX XX 7XXXF `XX .XF .XXXXL .XX XX. JXXXX. 7X. XX} .XXXF7XF JXX} {XXL 7XF7XXX. {XX mXXX' `XXX' `XXX' `XXXm ^^^^^ ^^^^^ The use of a camel image in association with Perl is a trademark of O'Reilly & Associates, Inc. Used with permission. ``` (The copyright text is optional.) A simpler example would take the input: ``` ####### # # ###### # # # ##### ``` and produce: ``` ##### ##### # # # # # # ###### ###### # # # # ####### ####### ####### ####### # # # # ###### ###### # # # # # # ##### ##### ``` The entries should demonstrate art. This is a popularity contest, so the entry with maximum (up)votes wins! [Answer] # Bash and common utils *You may have to install `rev`* I wasn't satisfied with merely reflecting character positions, it really messes up ascii-art input. So I tried to reflect characters too, modulo the ascii character set. ``` #!/bin/bash half_width=39 left='/(q[{d>Ss' right='\\)p]}b<Zz' up='\\`!^qwWtupSs_' down='/,ivdmMfnbZz\-' function callback () { line=${2: 0: half_width} p=$((half_width-${#line})) printf "%s%${p}s%${p}s%s\n" \ "$line" "" "" "$(rev<<<"$line" \ | tr $left$right $right$left)" ; } if ! [ "$1" ]; then cat < "$0"; elif [ "$1" == "-" ]; then cat; else cat < "$1" fi | mapfile -c1 -Ccallback -t | tee >(tac | tr $up$down $down$up) ``` With no arguments, the script prints itself reflected 2x2, as requested: ``` $ ./2x2.sh #!/bin/bash hzad\nid\!# half_width=39 93=htbiw_flah left='/(q[{d>Ss' 'zZ<b}]p)\'=tfel right='\\)p]}b<Zz' 'sS>d{[q(//'=thgir up='\\`!^qwWtupSs_' '_zZqutWwp^!`//'=qu down='/,ivdmMfnbZz\-' '-/sSdnfMmbvi,\'=nwob function callback () { } () kcadllac noitcnuf line=${2: 0: half_width} {htbiw_flah :0 :2}$=enil p=$((half_width-${#line})) (({enil#}$-htbiw_flah))$=q printf "%s%${p}s%${p}s%s\n" \ / "n/z%z{q}$%z{q}$%z%" ftnirq "$line" "" "" "$(rev<<<"$line" \ / "enil$">>>ver)$" "" "" "enil$" | tr $left$right $right$left)" ; } { ; "(tfel$thgir$ thgir$tfel$ rt | if ! [ "$1" ]; then cat < "$0"; elif file ;"0$" > tac neht ;[ "1$" ] ! fi [ "$1" == "-" ]; then cat; else cat < "" > tac ezle ;tac neht ;[ "-" == "1$" ] fi | mapfile -c1 -Ccallback -t | tee >()< eet | t- kcadllacC- 1c- elifqam | if t! | wabt!le _c1 _Ccallpack _f | fee >()< eef | f_ kcaqllacC_ 1c_ el!tdaw | !t [ "$1" == "_" ]; fheu caf; elze caf < "" > fac esle ;fac uehf ;[ "_" == "1$" ] !t i [ "$1" ]; fheu caf < "$0"; el!t t!le ;"0$" > fac uehf ;[ "1$" ] i t! | fr $letf$r!ghf $r!ghf$letf)" ; } { ; "(ftel$fhg!r$ fhg!r$ftel$ rf | "$l!ue" "" "" "$(re^<<<"$l!ue" / \ "eu!l$">>>^er)$" "" "" "eu!l$" br!uft "%z%${b}z%${b}z%z/u" / \ "u\s%s{d}$%s{d}$%s%" tfu!rd b=$((halt-m!qfh_${#l!ue})) (({eu!l#}$_hfp!m-tlah))$=d l!ue=${2: 0: halt-m!qfh} {hfp!m-tlah :0 :2}$=eu!l tnucf!ou callpack () { } () kcaqllac uo!fcunt qomu='\`!^qwWtupSs/_' '_\zZqutWwp^!`/'=umop nb='//,ivdmMfnbZz-' '-sSdnfMmbvi,\\'=dn r!ghf='//)b]}p<Ss' 'zZ>q{[d(\\'=fhg!r letf='\(d[{q>Zz' 'sS<p}]b)/'=ftel halt-m!qfh=39 93=hfp!m-tlah #i\p!u\pazh hsaq/u!q/i# $ ``` You may also provide in input filename: ``` $ ./2x2.sh ppcg.fig ____ ____ ____ ____ ____ ____ ____ ____ | _ \| _ \ / ___/ ___| |___ \___ \ / _ |/ _ | | |_) | |_) | | | | _ _ | | | | (_| | (_| | | __/| __/| |__| |_| | | |_| |__| |\__ |\__ | |_| |_| \____\____| |____/____/ |_| |_| |-| |-| /----/----| |----\----\ |-| |-| | --\| --\| |--| |-| | | |-| |--| |/-- |/-- | | |-) | |-) | | | | - - | | | | (-| | (-| | | - /| - / \ ---\ ---| |--- /--- / \ - |\ - | ---- ---- ---- ---- ---- ---- ---- ---- $ ``` If the input filename is `-`, the script will read input from stdin: ``` $ cowsay moo | ./2x2.sh - _____ _____ < moo > < oom > ----- ----- \ ^__^ ^__^ / \ (oo)\_______ _______/(oo) / (__)\ )\/\ /\/( /(__) ||----w | | w----|| || || || || || || || || ||____m | | m____|| (--)/ )/\/ \/\( \(--) / (oo)/------- -------\(oo) \ / v--v v--v \ _____ _____ < woo > < oow > ----- ----- $ ``` [Answer] # Ruby This one definitely took me a while. But it was really fun! ``` # e= "/+ +d.f /(.-. e*0*,+ (*1*e/* .-.).,*e /+/(.c.1/ ,**-c.e**+ b*,*c+d+++* *e.+.0/*+b/+ +d/+*e/a.1/(* 0/+*e/*.-/..-/ */+.-*1*e.d.)/( *0*.+a.a.f.1.e*1 +b/(/-/,/+*0/+*b/ +*e/*.-/..-/*/+.-* 1";eval e.tr("#{ } ",'').split(''). each_slice(?\x2. ord+0x308333+0+ -3179315).map{ #............ |x|x. join . tr( '(-7', '0-9A-F'). to_i(16). chr.ord. chr.ord .chr.# chr}* '' + ''+ '' # ``` Output: ``` # # e= '' "/+ ''+ +d.f '' + /(.-. chr}* e*0*,+ .chr.# (*1*e/* chr.ord .-.).,*e chr.ord. /+/(.c.1/ to_i(16). ,**-c.e**+ '0-9A-F'). b*,*c+d+++* tr( '(-7', *e.+.0/*+b/+ |x|x. join . +d/+*e/a.1/(* #............ 0/+*e/*.-/..-/ -3179315).map{ */+.-*1*e.d.)/( ord+0x308333+0+ *0*.+a.a.f.1.e*1 each_slice(?\x2. +b/(/-/,/+*0/+*b/ ",'').split(''). +*e/*.-/..-/*/+.-* 1";eval e.tr("#{ } 1";eval e.tr("#{ } +*e/*.-/..-/*/+.-* ",'').split(''). +b/(/-/,/+*0/+*b/ each_slice(?\x2. *0*.+a.a.f.1.e*1 ord+0x308333+0+ */+.-*1*e.d.)/( -3179315).map{ 0/+*e/*.-/..-/ #............ +d/+*e/a.1/(* |x|x. join . *e.+.0/*+b/+ tr( '(-7', b*,*c+d+++* '0-9A-F'). ,**-c.e**+ to_i(16). /+/(.c.1/ chr.ord. .-.).,*e chr.ord (*1*e/* .chr.# e*0*,+ chr}* /(.-. '' + +d.f ''+ "/+ '' e= # # # # '' e= ''+ "/+ '' + +d.f chr}* /(.-. .chr.# e*0*,+ chr.ord (*1*e/* chr.ord. .-.).,*e to_i(16). /+/(.c.1/ '0-9A-F'). ,**-c.e**+ tr( '(-7', b*,*c+d+++* |x|x. join . *e.+.0/*+b/+ #............ +d/+*e/a.1/(* -3179315).map{ 0/+*e/*.-/..-/ ord+0x308333+0+ */+.-*1*e.d.)/( each_slice(?\x2. *0*.+a.a.f.1.e*1 ",'').split(''). +b/(/-/,/+*0/+*b/ 1";eval e.tr("#{ } +*e/*.-/..-/*/+.-* +*e/*.-/..-/*/+.-* 1";eval e.tr("#{ } +b/(/-/,/+*0/+*b/ ",'').split(''). *0*.+a.a.f.1.e*1 each_slice(?\x2. */+.-*1*e.d.)/( ord+0x308333+0+ 0/+*e/*.-/..-/ -3179315).map{ +d/+*e/a.1/(* #............ *e.+.0/*+b/+ |x|x. join . b*,*c+d+++* tr( '(-7', ,**-c.e**+ '0-9A-F'). /+/(.c.1/ to_i(16). .-.).,*e chr.ord. (*1*e/* chr.ord e*0*,+ .chr.# /(.-. chr}* +d.f '' + "/+ ''+ e= '' # # ``` ![screenshot](https://i.stack.imgur.com/1aVdZ.png) It's based on the same idea as [my previous answer](https://codegolf.stackexchange.com/a/22647/3808). [Answer] # Ruby **UPDATE**: Check out [my new answer](https://codegolf.stackexchange.com/a/22684/3808), based on the same idea as this one! ``` $, | e="s= open( $0).r ead.s pli | t ( 1 0 . ch r); | $ , = 3 2 . chr | ;s=s. zip(s . r ev ers | e ) . m a | p ( &:joi n);pu t | | s(s+s.reverse)";eval e.gsub(/[\s|]/,'') ``` Output: ``` $, | s(s+s.reverse)";eval e.gsub(/[\s|]/,'') e="s= open( $0).r ead.s pli | | t ( 1 0 . ch r); | p ( &:joi n);pu t | $ , = 3 2 . chr | e ) . m a | ;s=s. zip(s . r ev ers | ;s=s. zip(s . r ev ers | e ) . m a | $ , = 3 2 . chr | p ( &:joi n);pu t | t ( 1 0 . ch r); | | e="s= open( $0).r ead.s pli | s(s+s.reverse)";eval e.gsub(/[\s|]/,'') $, | s(s+s.reverse)";eval e.gsub(/[\s|]/,'') $, | | e="s= open( $0).r ead.s pli | p ( &:joi n);pu t | t ( 1 0 . ch r); | e ) . m a | $ , = 3 2 . chr | ;s=s. zip(s . r ev ers | ;s=s. zip(s . r ev ers | $ , = 3 2 . chr | e ) . m a | t ( 1 0 . ch r); | p ( &:joi n);pu t | e="s= open( $0).r ead.s pli | | $, | s(s+s.reverse)";eval e.gsub(/[\s|]/,'') ``` It's "PPCG!" in ASCII art! :D Here's a detailed explanation. First, I found out how to do the actual mirroring. Here's the mirroring code: ``` s = open($0).read.split "\n" $, = ' ' s = s.zip(s.reverse).map &:join puts s + s.reverse ``` Then I had to remove whitespace characters and double quotes (because escaping just gets messy), so I used Ruby's `Fixnum#chr`. The basic structure of the program is now: ``` e="<code>" eval e.gsub(/\s/,'') ``` Now I can make it into ASCII art! So, that's what I did. Then, I padded the ASCII art with spaces and `|`s at the end, and I made it to here: ``` e="s= open( $0).r ead.s pli | t ( 1 0 . ch r); | $ , = 3 2 . chr | ;s=s. zip(s . r ev ers | e ) . m a | p ( &:joi n);pu t | s(s+s.reverse)";eval e.gsub(/[\s|]/,'') ``` However, that looked a bit ugly, since there wasn't enough padding around the ASCII art. Therefore, I added a bit of extra padding, and got where I am now! (`$, | x` is equivalent to `x` since `$,` is `nil` by default.) [Answer] ## bash ( + `sed` + `tee` + `tac` ) -> 102 ``` sed -re 'h;s/$/\o1/;:a;s/(.)\o1(.*)$/\o1\2\1/;ta;s/^\o1//;G;s/^(.*)\n(.*)$/\2 \1/' ${1:-$0}|tee >(tac) ``` Sample useable ``` #!/bin/bash sed -re 'h;s/$/\o1/;:a;s/(.)\o1(.*)$/\o1\2\1/;ta; s/^\o1//;G;s/^(.*)\n(.*)$/\2 \1/' ${1:-$0} | tee >(tac) ``` Sample detailed: ``` #!/bin/bash sed -re ' h; # copy current line to hold space s/$/\o1/; # add chr(1) at end of line :a; # branch label for further goto s/(.)\o1(.*)$/\o1\2\1/; # move 1 char at end to end ta; # goto :a if previous `s///` do match s/^\o1//; # drop chr(1) G; # Append newline + hold space to current line s/^(.*)\n(.*)$/\2 \1/ # Suppress newline and swap line <-> hold space ' ${1:-$0} | # From file as first arg or script himself, than pipe to tee >( # tee would double stdout and pass feed to tac ) # tac as reverse cat. ``` This could result as: ``` ./revmir.sh #!/bin/bash hsab/nib/!# sed -re ' ' er- des h; # copy current line to hold space ecaps dloh ot enil tnerruc ypoc # ;h s/$/\o1/; # add chr(1) at end of line enil fo dne ta )1(rhc dda # ;/1o\/$/s :a; # branch label for further goto otog rehtruf rof lebal hcnarb # ;a: s/(.)\o1(.*)$/\o1\2\1/; # move 1 char at end to end dne ot dne ta rahc 1 evom # ;/1\2\1o\/$)*.(1o\).(/s ta; # goto :a if previous `s///` do match hctam od `///s` suoiverp fi a: otog # ;at s/^\o1//; # drop chr(1) )1(rhc pord # ;//1o\^/s G; # Append newline + hold space to current line enil tnerruc ot ecaps dloh + enilwen dneppA # ;G s/^(.*)\n(.*)$/\2 \1/ # Suppress newline and swap line <-> hold space ecaps dloh >-< enil paws dna enilwen sserppuS # /1\ 2\/$)*.(n\)*.(^/s ' ${1:-$0} | # From file as first arg or script himself, than pipe to ot epip naht ,flesmih tpircs ro gra tsrif sa elif morF # | }0$-:1{$ ' tee >( # tee would double stdout and pass feed to ot deef ssap dna tuodts elbuod dluow eet # (> eet tac ) # tac as reverse cat. .tac esrever sa cat # ) cat tac ) # tac as reverse cat. .tac esrever sa cat # ) cat tee >( # tee would double stdout and pass feed to ot deef ssap dna tuodts elbuod dluow eet # (> eet ' ${1:-$0} | # From file as first arg or script himself, than pipe to ot epip naht ,flesmih tpircs ro gra tsrif sa elif morF # | }0$-:1{$ ' s/^(.*)\n(.*)$/\2 \1/ # Suppress newline and swap line <-> hold space ecaps dloh >-< enil paws dna enilwen sserppuS # /1\ 2\/$)*.(n\)*.(^/s G; # Append newline + hold space to current line enil tnerruc ot ecaps dloh + enilwen dneppA # ;G s/^\o1//; # drop chr(1) )1(rhc pord # ;//1o\^/s ta; # goto :a if previous `s///` do match hctam od `///s` suoiverp fi a: otog # ;at s/(.)\o1(.*)$/\o1\2\1/; # move 1 char at end to end dne ot dne ta rahc 1 evom # ;/1\2\1o\/$)*.(1o\).(/s :a; # branch label for further goto otog rehtruf rof lebal hcnarb # ;a: s/$/\o1/; # add chr(1) at end of line enil fo dne ta )1(rhc dda # ;/1o\/$/s h; # copy current line to hold space ecaps dloh ot enil tnerruc ypoc # ;h sed -re ' ' er- des #!/bin/bash hsab/nib/!# ``` or formated to fixed line width: ``` printf -v spc '%74s';sed "s/\$/$spc/;s/^\(.\{74\}\) *$/\1/" <revmir.sh | ./revmir.sh - ``` give: ``` #!/bin/bash hsab/nib/!# sed -re ' ' er- des h; # copy current line to hold space ecaps dloh ot enil tnerruc ypoc # ;h s/$/\o1/; # add chr(1) at end of line enil fo dne ta )1(rhc dda # ;/1o\/$/s :a; # branch label for further goto otog rehtruf rof lebal hcnarb # ;a: s/(.)\o1(.*)$/\o1\2\1/; # move 1 char at end to end dne ot dne ta rahc 1 evom # ;/1\2\1o\/$)*.(1o\).(/s ta; # goto :a if previous `s///` do match hctam od `///s` suoiverp fi a: otog # ;at s/^\o1//; # drop chr(1) )1(rhc pord # ;//1o\^/s G; # Append newline + hold space to current line enil tnerruc ot ecaps dloh + enilwen dneppA # ;G s/^(.*)\n(.*)$/\2 \1/ # Suppress newline and swap line <-> hold space ecaps dloh >-< enil paws dna enilwen sserppuS # /1\ 2\/$)*.(n\)*.(^/s ' ${1:-$0} | # From file as first arg or script himself, than pipe to ot epip naht ,flesmih tpircs ro gra tsrif sa elif morF # | }0$-:1{$ ' tee >( # tee would double stdout and pass feed to ot deef ssap dna tuodts elbuod dluow eet # (> eet tac ) # tac as reverse cat. .tac esrever sa cat # ) cat tac ) # tac as reverse cat. .tac esrever sa cat # ) cat tee >( # tee would double stdout and pass feed to ot deef ssap dna tuodts elbuod dluow eet # (> eet ' ${1:-$0} | # From file as first arg or script himself, than pipe to ot epip naht ,flesmih tpircs ro gra tsrif sa elif morF # | }0$-:1{$ ' s/^(.*)\n(.*)$/\2 \1/ # Suppress newline and swap line <-> hold space ecaps dloh >-< enil paws dna enilwen sserppuS # /1\ 2\/$)*.(n\)*.(^/s G; # Append newline + hold space to current line enil tnerruc ot ecaps dloh + enilwen dneppA # ;G s/^\o1//; # drop chr(1) )1(rhc pord # ;//1o\^/s ta; # goto :a if previous `s///` do match hctam od `///s` suoiverp fi a: otog # ;at s/(.)\o1(.*)$/\o1\2\1/; # move 1 char at end to end dne ot dne ta rahc 1 evom # ;/1\2\1o\/$)*.(1o\).(/s :a; # branch label for further goto otog rehtruf rof lebal hcnarb # ;a: s/$/\o1/; # add chr(1) at end of line enil fo dne ta )1(rhc dda # ;/1o\/$/s h; # copy current line to hold space ecaps dloh ot enil tnerruc ypoc # ;h sed -re ' ' er- des #!/bin/bash hsab/nib/!# ``` and using `figlet`: ``` figlet -f banner 5 | ./revmir.sh - ####### ####### # # # # ###### ###### # # # # # # ##### ##### ##### ##### # # # # # # ###### ###### # # # # ####### ####### ``` And for fun: ``` figlet -f banner Code Golf. | ./asciiReduce | ./revmir.sh - ▞▀▀▖▗▄▖▗▄▄ ▄▄▄  ▞▀▀▖▗▄▖▗   ▄▄▄       ▄▄▄   ▗▖▄▗▖▀▀▞  ▄▄▄ ▄▄▗▖▄▗▖▀▀▞ ▌   ▌ ▐▐  ▌▙▄▖  ▌▗▄▖▌ ▐▐   ▙▄▖       ▖▄▙   ▐▐ ▌▖▄▗▌  ▖▄▙▌  ▐▐ ▌   ▌ ▌  ▖▌ ▐▐  ▌▌    ▌  ▌▌ ▐▐   ▌  ▐█   █▐  ▌   ▐▐ ▌▌  ▌    ▌▌  ▐▐ ▌▖  ▌ ▝▀▀ ▝▀▘▝▀▀ ▀▀▀  ▝▀▀ ▝▀▘▝▀▀▘▘  ▝▀   ▀▝  ▘▘▀▀▝▘▀▝ ▀▀▝  ▀▀▀ ▀▀▝▘▀▝ ▀▀▝ ▝▀▀ ▝▀▘▝▀▀ ▀▀▀  ▝▀▀ ▝▀▘▝▀▀▘▘  ▝▀   ▀▝  ▘▘▀▀▝▘▀▝ ▀▀▝  ▀▀▀ ▀▀▝▘▀▝ ▀▀▝ ▌  ▖▌ ▐▐  ▌▌    ▌  ▌▌ ▐▐   ▌  ▐█   █▐  ▌   ▐▐ ▌▌  ▌    ▌▌  ▐▐ ▌▖  ▌ ▌   ▌ ▐▐  ▌▙▄▖  ▌▗▄▖▌ ▐▐   ▙▄▖       ▖▄▙   ▐▐ ▌▖▄▗▌  ▖▄▙▌  ▐▐ ▌   ▌ ▞▀▀▖▗▄▖▗▄▄ ▄▄▄  ▞▀▀▖▗▄▖▗   ▄▄▄       ▄▄▄   ▗▖▄▗▖▀▀▞  ▄▄▄ ▄▄▗▖▄▗▖▀▀▞ ``` He, he... This could not work because of half-chars could not be simply reversed. For this, we have to run command in reversed order: ``` figlet -f banner Code Golf. | ./revmir.sh - | asciiReduce ▞▀▀▖▗▄▖▗▄▄ ▄▄▄ ▞▀▀▖▗▄▖▗ ▄▄▄ ▗▄▄▖ ▗ ▄▄ ▞▀▀▖ ▗▄▄▖▗▄▄ ▄▄ ▞▀▀▖ ▌ ▌ ▐▐ ▌▙▄▖ ▌▗▄▖▌ ▐▐ ▙▄▖ ▄▄▌ ▐▐ ▌▄▄ ▌ ▄▄▌▌ ▐▐ ▌ ▌ ▌ ▖▌ ▐▐ ▌▌ ▌ ▌▌ ▐▐ ▌ ▐█ ▐█ ▌ ▐▐ ▌▌ ▌ ▌▌ ▐▐ ▌▖ ▌ ▝▀▀ ▝▀▘▝▀▀ ▀▀▀ ▝▀▀ ▝▀▘▝▀▀▘▘ ▝▀ ▝▀ ▘▀▀▀ ▀▀ ▝▀▀ ▝▀▀▘▝▀▀ ▀▀ ▝▀▀ ▗▄▄ ▗▄▖▗▄▄ ▄▄▄ ▗▄▄ ▗▄▖▗▄▄▖▖ ▗▄ ▗▄ ▖▄▄▄ ▄▄ ▗▄▄ ▗▄▄▖▗▄▄ ▄▄ ▗▄▄ ▌ ▘▌ ▐▐ ▌▌ ▌ ▌▌ ▐▐ ▌ ▐█ ▐█ ▌ ▐▐ ▌▌ ▌ ▌▌ ▐▐ ▌▘ ▌ ▌ ▌ ▐▐ ▌▛▀▘ ▌▝▀▘▌ ▐▐ ▛▀▘ ▀▀▌ ▐▐ ▌▀▀ ▌ ▀▀▌▌ ▐▐ ▌ ▌ ▚▄▄▘▝▀▘▝▀▀ ▀▀▀ ▚▄▄▘▝▀▘▝ ▀▀▀ ▝▀▀▘ ▝ ▀▀ ▚▄▄▘ ▝▀▀▘▝▀▀ ▀▀ ▚▄▄▘ ``` ![code golf mirrored and reduced](https://i.stack.imgur.com/OFmN1.png) [Answer] # C++ ``` #include<iostream> int main() { char mirror[]={ 218,196,196,196,196,196,191, 218,196,196,196,196,196,191,'\n', 179,201,205,203,205,187,179, 179,201,205,203,205,187,179,'\n', 179,186,254,186,254,186,179, 179,186,254,186,254,186,179,'\n', 179,204,205,206,205,185,179, 179,204,205,206,205,185,179,'\n', 179,186,254,186,254,186,179, 179,186,254,186,254,186,179,'\n', 179,200,205,202,205,188,179, 179,200,205,202,205,188,179,'\n', 192,196,196,196,196,196,217, 192,196,196,196,196,196,217,'\n', '\0'}; std::cout<<mirror<<mirror; getch(); return 0; } ``` ### output This output looks like "Windows 4X4". > > ![enter image description here](https://i.stack.imgur.com/AbxuF.png) > > > ]
[Question] [ # Introduction Compute is a ~~esoteric~~ joke language. From the [esolangs entry:](http://esolangs.org/wiki/Compute) > > Compute has no required syntax and has the power to solve any and all > problems. It is smart enough to interpret any human language (English, > Spanish, Latin, etc), any programming language (C++, Java, brainfuck, > etc), or any kind of data you can think of. **The only downfall is that > there is absolutely no I/O.** > > > ### Some example programs ``` Hello World ``` A basic Hello World program ``` What is love? ``` Determines was love is (baby don't hurt me). ``` When will we ever graduate? ``` Determines the exact date of this site to get out of beta. # The Challenge Your task is to write a full Compute interpreter. This sounds pretty hard, but keep in mind that Compute has absolutly no I/O. So your interpreter will just sleep one second for every **line** in the input program and output `\n\nDone.` after this (this is the only exception to the no I/O thing). You can find the official interpreter at the bottom of [this site](http://esolangs.org/wiki/Compute). *Note that the official interpreter pauses one second for every character in the given source code. To avoid long waiting times while testing your interpreter with meaningful questions **we stay with lines** in this challenge.* # Rules * The input might contain multiple lines seperated by a `\n`. There will always be at least one line. * Unlike the official implementation you don't have to take a file as input. You can take the Compute program in any form of input you want. * The only output allowed is `\n\nDone.`. A trailing newline is allowed. * Function or full program allowed. * [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~15~~ ~~14~~ 13 bytes Code: ``` [Ig>#w’ D€µ. ``` Explanation: ``` [ # Starts an infinite loop I # Input string g> # Length + 1 # # If equal to 1, break out of the loop w # Wait 1 second ``` This part is equivalent to `"\n\nDone."`: ``` ’ # Push "\n\nDone." on top of the stack D€µ. # The compressed string is ended implicitly # Implicit, print top of the stack ``` [Try it online!](http://05ab1e.tryitonline.net/#code=W0lnPiN34oCZCgpE4oKswrUu&input=SGVsbG8KV29ybGQKCg) Uses **CP-1252** encoding. [Answer] # [Oration](https://github.com/ConorOBrien-Foxx/Assorted-Programming-Languages/tree/master/oration), 117 bytes ``` I need time! To iterate, input(). Inhale. Now sleep(1). Backtracking. Boring, boring. Listen! Capture Done. Carry on! ``` Let's explain this. First, this transpiles to: ``` import time while input(): time.sleep(1) print("\n") print("\n") print("Done") ``` Still confused? Let's put it like this: ``` I need time! ``` Imports the module `time`. ``` To iterate, input(). ``` This is a while loop whose condition is `input()`. ``` Inhale. ``` Our program needs to breathe now, and `inhale`, whilst less healthy, is golfier. ``` Now sleep(1). ``` `Now` take the most recent module imported and appends `.sleep(1)` to it. ``` Backtracking. ``` Let's exit the while loop. ``` Boring, boring. ``` Prints two newlines. ``` Listen! ``` Begins capturing a string. ``` Capture Done. ``` Adds `Done.` to the captured string. ``` Carry on! ``` Finishes capturing string. [Answer] ## JavaScript Shell REPL, 38 bytes As a function that accepts the program as a string argument and returns the result: ``` s=>sleep(s.split` `.length)||` Done.` ``` 29 bytes if the function can accept its input in the form of an array of lines, or if it should sleep 1 second per character: ``` s=>sleep(s.length)||` Done.` ``` 34 bytes if it should also be more like a program and explicitly print Done: ``` s=>sleep(s.length)||print` Done.` ``` This works for me in the standalone Spidermonkey interpreter. [Answer] ## Javascript ES6, ~~46~~ 45 bytes ``` a=>setTimeout(x=>alert` Done.`,a.length*1e3) ``` Thanks to [ӍѲꝆΛҐӍΛПҒЦꝆ](https://codegolf.stackexchange.com/users/41247/%D3%8D%D1%B2%EA%9D%86%CE%9B%D2%90%D3%8D%CE%9B%D0%9F%D2%92%D0%A6%EA%9D%86) for saving one byte Assumes an array as input. As both [ӍѲꝆΛҐӍΛПҒЦꝆ](https://codegolf.stackexchange.com/users/41247/%D3%8D%D1%B2%EA%9D%86%CE%9B%D2%90%D3%8D%CE%9B%D0%9F%D2%92%D0%A6%EA%9D%86) and [edc65](https://codegolf.stackexchange.com/users/21348/edc65) have pointed out you can write the following, but it won't save any bytes: ``` a=>setTimeout("alert`\n\nDone`",a.length*1e3) ``` [Answer] # Bash + coreutils, 28 ``` sleep `wc -l` echo " Done." ``` Sleeps 1 second for every line. Use `wc -c` instead for every byte, or `wc -m` instead for every character. [Answer] # Pyth, ~~15~~ 14 bytes ``` .dcl.z1b"Done. ``` (You can [try it online](https://pyth.herokuapp.com/?code=.dcl.z1b%22Done.&debug=0), but there's really no point in doing so.) [Answer] ## Perl, 21 + 1 = 22 bytes ``` sleep 1}{$_="\n\nDone." ``` Requires the `-p` flag: ``` $ perl -pe'sleep 1}{$_="\n\nDone."' <<< $'a\nb\nc' Done. ``` [Answer] ## Python 3, 58 bytes ``` import time while input():time.sleep(1) print("\n\nDone.") ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 17 bytes ``` 10c'Done.'`jt?1Y. ``` A trailing empty line (followed by newline) is used to mark end of input. This is needed in MATL because input is interactive and each input ends with a newline. [**Try it online!**](http://matl.tryitonline.net/#code=MTBjJ0RvbmUuJ2BqdD8xWS4&input=RmluZCB0aGUgVWx0aW1hdGUgUXVlc3Rpb24gb2YgTGlmZSwgdGhlIFVuaXZlcnNlLCBhbmQgRXZlcnl0aGluZwpPbiBzZWNvbmQgdGhvdWdodCwgZG9uJ3QKCgo) ``` 10c % push newline character 'Done.' % push string ` % do...while j % input string t % duplicate ? % if non-empty 1Y. % pause for 1 second % loop condition is the current string. If non-empty: next iteration % If empty: exit loop and print stack contents. There are two strings % and a newline is printed after each, so the desired output is obtained ``` [Answer] # QBasic, 54 bytes ``` LINE INPUT x$ IF x$=""GOTO 1 SLEEP 1 RUN 1? ? ?"Done." ``` Takes the program line by line from user input, terminated by a blank line. Abides by the letter of the law, though possibly not the spirit, by pausing 1 second after reading each line. (The specification doesn't technically say that the pauses all have to come after the input is completed.) If this is considered too shady, here's a 64-byte version that pauses after the whole program has been input: ``` DO LINE INPUT x$ IF x$=""GOTO 1 t=t+1 LOOP 1SLEEP t ? ? ?"Done." ``` --- Bonus version with file I/O (87 bytes): ``` INPUT f$ OPEN f$FOR INPUT AS 1 1LINE INPUT #1,x$ SLEEP 1 IF 0=EOF(1)GOTO 1 ? ? ?"Done." ``` [Answer] ## Ruby, 32 bytes ``` $<.map{sleep 1} puts"\n\nDone." ``` Reads from stdin. [Answer] # OCaml, 61 bytes ``` fun a->List.iter(fun _->Unix.sleep 1)a;print_string"\n\nDone" ``` Assumes the input is a list. [Answer] ## awk, 34 bytes ``` END{print"\nDone."|"cat;sleep "NR} ``` As there is no I/O and the final outcome is inevitable, the `Done.` part is outputed right in the beginning. ``` $ awk 'END{print"\nDone."|"cat;sleep "NR}' file ``` Only way to sleep in awk is to use system `sleep`. Shortest way to invocate it is to `print|"sleep "NR` and we might as well abuse that useless `print`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ỴLœS@⁷⁷“ẋḲp» ``` [Try it online!](https://tio.run/nexus/jelly#@/9w9xafo5ODHR41bgehhjkPd3U/3LGp4NDu////e6Tm5OQrhOcX5aRwhWcklihkFivk5Jel2gN5qXkK5Zk5OQrlqQqpZalFCulFiSmliSWp9gA "Jelly – TIO Nexus") Note: Please **do not** suggest putting the `⁷⁷` in the compressed string, it will make it longer (`“¡OÑL[Ṁ»`). Explanation: ``` ỴLœS@⁷⁷“ẋḲp» Main link. Arguments: z. ỴL The number of lines in z. (x) ⁷ Newline ("\n") (y) œS@ After sleeping for x seconds, return y. ⁷ Newline ("\n") “ẋḲp» Compressed string ("Done.") ``` ]
[Question] [ ## Problem You are tasked with creating a program that performs emoji encryption on a given string of emojis. In this encryption scheme, each emoji is replaced by a unique character (from `a` to `z`). Your program should take an emoji string as input and output the corresponding encrypted string. The mapping of emojis to characters is up to you and can vary each time the program is run. For example: ``` Input: 🌟🌟🌟🌺🌺🐘🎉🐘🍔 Output 1: aaabbcdce Output 2: xxxiikbkg ``` Both outputs are valid. Your task is to write a program that produces encrypted strings for given emoji inputs. Your program will be evaluated based on its **average result value** and size of code (in bytes). ## Value of the Result Each letter from `a` to `z` has a value from `0` to `25` in ascending order. ie. ``` a = 0 b = 1 c = 2 . . . y = 24 z = 25 ``` The value of the result is calculated as the summation of the values of all characters in the resulting string. For example: ``` aaabbcdce 0 + 0 + 0 + 1 + 1 + 2 + 3 + 2 + 4 = 13 ``` ## Scoring Criteria: Run the program 10,000 times, each time generating a random 25-emoji string, and calculate the average value of the results. Your score will be determined by this average value in comparison with the size of the code. The goal is to create a program that, on average, produces encrypted strings with the lowest possible value based on the emoji-to-character mapping chosen for each run (a `run` is considered converting 25 emojis to a string hence there will be 10,000 unique runs considered in your score) Create and submit a program that generates encrypted strings as described above, and your score will be the average result value obtained from the 10,000 runs and multiply by the size of the code in bytes. A lower Score is better. $${\text{average value of results over }10,000\text{ runs}}\times {\text{size of code in bytes}} $$ **LOWER SCORE IS BETTER** ## Notes: **Ignore decryption** This problem emphasizes randomness and the ability to produce low-value results on average, so figuring out which emoji has been repeated the most in the input and giving it the character `a` will improve the program's result. #### Input restrictions * Input Emoji string will contain **25** emojis without any spaces. * There will only be **10** unique emojis in the Input at maximum. * The 10 valid emojis in the Input are 🗓🙏📗💻📇🚢🐉💘😪🎉 some example inputs: ``` Invalid input: 🗓🙏🚁🍿💻🍏💣📡📇📓🐉🙅🎗♿️👼⛷🔔💘5️⃣⏏📗🌑😪👒🚢 (it has more than 10 unique emojis) 🗓🙏🚁🍿💻🍏 📡📇📓🐉🙅🎗♿️👼⛷ 5️⃣⏏📗🌑😪👒🚢 (invalid for including spaces) Valid input: 🗓🙏📗📗💻🗓📇🚢📇🗓🐉🗓🗓🗓📇🚢📇💘📗📗📗🗓😪📇🚢 ( Valid since it has only 9 unique emojis (<= 10) and no spaces) Valid output to this Input: abccdaefeagaaaefehcccaief ``` ### example random Input generators #### Python ``` import random input_string = ''.join(random.choice("🗓🙏📗💻📇🚢🐉💘😪🎉") for _ in range(25)) print("Emoji String:", input_string) ``` [Answer] # [R](https://www.r-project.org), ~~73.2 \* 81 bytes = *5929.2*~~ ~~73.2 \* 70 bytes = *5124.4*~~ 73.2 \* 64 bytes = *4684.8* Same method as below for finding most common letters, but two significant improvements suggested in comments by [@pajonk](https://codegolf.stackexchange.com/users/55372/pajonk): 1. -11 bytes thanks to a much better approach to splitting and concatenating strings using `utf8ToInt()`. 2. -6 bytes pointing out [`chartr()`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/chartr.html) can take a range of characters (e.g. `"a-d"` rather than `"abcd"`). ``` \(x)chartr(intToUtf8(names(sort(-table(utf8ToInt(x))))),'a-z',x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rVLNbtNAEJY47lOMnEN3q3WVhFaNqoK4VFAJCkLOrZK7uGuw2KyNdy2Fn56rXNoqOSRtDw5FXDhxz5O0T-FHwONNCXBmJOvb-fvm2_Fef83n3-Jd_3thY793--SQDln0TuQ2p4m2Qdq3cY9qMZCGmjS31LfijZK0ru4F6b62dTkaXxP-pzU-ZI7n7sHPFrzUEqw0FiJhJImpV5WT06o8G1Xl5XlVjme1P63Ki5E7YwxzVzerHPrjhfPxPJ2sPuxDvoZr4frORh4jLei0368mG2Kk3TBSHtPNLiOJzgob1iHY9SGiBGrzkNHjiJfnDidTh-PF0j91eHXj8GK0zM8czn44rBUQRvYPXvWD8PnewdPgGc7pbpEhYiaMlW1qxCCrl_hbCoc_GzjkMlMikvAIgtf9PcYhSpUSmcGIV9-QREJFhRJWhiZKc4nUcaEjm6SapoVl8Lm5Vy5NoazBtPttxuYmU4nFIo5UrKl7ITJ6tH7E7xs4GPkhFCrVb-kyxMCHDoMvj5sGtEKrxFj6V8wUA8rICSGNrBALcHitPVMfaWenIzc5HNLkXuD_XAry_bMXGuPzJCeMDKTQdKl4pY0xaMH2w41ue2vbPdz53OEv) The ATO link includes a footer with 10k random test cases. --- Original approach: # [R](https://www.r-project.org), 73.2 \* 81 bytes = 5929.2 ``` \(x,p=paste0,`^`=Reduce)chartr(p^names(sort(-table(strsplit(x,"")))),p^letters,x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rVLNbhMxEJY4-ilGm4uNvFUSWrVCDbcKkKBAld6qbMx2FlY4u2btlYJoz1UubZUckpZD0iIunLjnSeAp9hGw1ymBnhlp9Xn-vvk86y83xeJrsht-K00S7vx8c0SHXHWU0AabvN_rdw7wuIyRxe9FYQqqepkYoKY6LwwNjXgrkWpTaCVTYzuDgFnjqifRGCw0HzJP_OvBjwa8yhAMagOx0EgSGlTzyVk1Px9V86uLaj6eWX9azS9H_uxiLnd9u845f7z0vjtPJ-vP9Tm-mmvp-85HASMNaDU_rCdrotFsaMRjutlmJM1UaSIbgt0QYkrAWuAYA-7w6sLjZOpxvFz5Zx6vbz1ejlb5mcfZd49WAWHk-f7rw270Ym__afeZm9PeIkOHftFUi4Gym_wjhcPfDRwKVFLECB3oHhzuMQ5xLqVQ2kXszgmJhYxLKQxGOs4LdNRJmcUmzTOal4bB5_peBepSGu3S9_6dLeKOitV1L4Wi_Yd9ftfAQePHSMg8e0dXIQYhtBicPKkbnJWZTLWh_8R0OaCMnBJSy4pcgRtutSv5ibYet3CTwxFN7wT-z6U4vnt7oQkd2iueMjJAkdGV4rU2xqAB24822s2tbf9wFwuPvwE) *-4 bytes thanks to noticing I was being very foolish by using paste0() twice on the same string* ## How? Fun question. R code golfers will no doubt be aware of the [advice](https://codegolf.stackexchange.com/a/91294/115882): > > If you see a challenge involving string manipulation, just press the back button and read the next question. `strsplit` is single handily responsible for ruining R golf > > > I boldly ignored this, but it was quickly clear that once you've invested all the bytes in splitting the string into a vector, you need a fairly low-scoring mapping of letters to emojis to come in under 10k. I note some of the answers have slightly lower average value of results than my 73.2 (around the 73.1 range). If anyone has a lot of time and compute power, it would be interesting to see how low you could get it by brute forcing the best random seed. The actual algorithm is not rocket science: simply assigning the most frequent character `a`, the next most frequent `b` etc. Here is an ungolfed version: ``` f <- function(x, p = paste0, `^` = Reduce) { s <- strsplit(x, "") m <- sort(-table(s)) # Ungolfed equivalent to # chartr( # Reduce(paste0, names(m)), # Reduce(paste0, letters), x # ) chartr(p^p^names(m), p^p^letters, x) } ``` The main golfing is using [this](https://codegolf.stackexchange.com/a/171759/115882) trick by @J.Doe: > > Operator abuse gives you `p=paste0;"^"=Reduce;p^p^r` which saves two bytes on the usual `paste0` call. > > > It also uses [`chartr()`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/chartr.html), basically the equivalent of Python's string `translate()` method, for an (irrelevantly) fast one-to-one replacement of each emoji with the letters of the alphabet. For clarity, the second argument should be `letters[1:10]`, but `chartr()` is fine with the replacement being longer than the pattern to be replaced. --- Approaches which aim to optimise the number of bytes: # [R](https://www.r-project.org), 57 bytes \* 90.2775 = *5145.8175* ``` \(x)chartr(gsub("(.)(?=.*\\1)","",x,pe=T),"jihgfedcba",x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rVLBbhMxEJU4-iss9zKunKhbWkRRA6cKkKAglN4ibR3Xmy44u2btlYKAc5VLWyWHpOWwoYgLJ-75EviK_QTsdUqAM5as53kz8-bZ8qfPxeJLst_6Wtqkdf_HXg9GVJzywhYwMGUfCLQpPOq0N3u9iBJGCBsxLTtdysjr9HSQyBPR546kQeDnne8b-EUmsZXGYsGNRAmQupqe1dX5uK6uLupqMnfxrK4ux-HsOZ-7vlnnfDxZhtifZ9P19n1er9Fahr7zMaFoA0dbb9aTDTLSto2UJ7CzTVGa6dLGjsL7LSwAYbeIVyTM49VFwOks4GS5is8CXt8EvByv8vOA828BnQNE0dPDl0fd-NnB4ePuEz9nexeNPGpurNwCw4daSfhtheE_GxgupFZcSNzB3VdHB5RhkSvFtfEMcTdEgitRKm5lbEReSC-dlJmwaZ5BXlqK3zf3KqQplTU-bXnfTTS2MFql1hcxL0Wbuudcw_HmMbttYNjItzFXeTaAFUVxC0cUf3jYNPhVZio1Fv7iTDkEij4i1NiKfYEf7rxr9Q6iB5HcYbgH6a3B__koXu-fd4HEfWPnh6Kh5BmsHK-9UYrdZ4nutffu7oaPu1gE_AU) +7 bytes but still lower scoring than the previous approach below, thanks to the observation in the [comment by Dominic Van Essen](https://codegolf.stackexchange.com/questions/264399/encrypting-emojis/264425?noredirect=1#comment578035_264425) that, as the regex leads to assigning `"a"` to the emoji whose final appearance occurs first, you're more-likely to assign `"a"` to emojis that only appear once. So if we reverse the replacement string to `"jihgfedcba"` then we end up with a value of 90.3, much lower than 116.9 in the approach below, which despite the increase in bytes leads to a better overall score. Although still not as low as the first method, and neither scores as well as the excellent [answer](https://codegolf.stackexchange.com/a/264485/115882) by Dominic Van Essen. --- *Previous iteration* # [R](https://www.r-project.org), ~~116.935 \* 57 bytes = *6665.295*~~ 116.935 \* 50 bytes = *5846.75* *Again -7 thanks to @pajonk as `"abcdefghij"` became `"a-j"` in `chartr()`* ``` \(x)chartr(gsub("(.)(?=.*\\1)","",x,pe=T),"a-j",x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rVJNb9MwGJY4-ldY3uX15FRL2RCgFU4TIMFAqLtVyrzgjICbhNiRigbnqZdtag_txiFliAsn7v0l8CvyE_AbdxQ4Y8l6_H48z_vY8qfP5eJLsht8rWwS3P3RHcCIx69laUs4NtURMOhweNjrbA4GIWeCMTESher1uWAyeOMi7pk_b33foM8zRa0ylsbSKJIAa-rpaVOfjZv68rypJ3MXz5r6YuzPmMPa1fW6hvFk6WM8z6brjTzUa7WWnnc2Zpxs0HDr7XqyIUbZjlHqFWx3OUmzorKRS9HdgMZAqFsMFZlAvDz3OJ15nCxX8anHq2uPF-NVfe5x_s2jc0A4ebL_4qAfPd3bf9R_jHO6O2SEWEhj1RYYOSy0gt9WBP2TIGipCi1jRXu0__Jgjwsa51rLwmCGuRuSWOq40tKqyMR5qVA6qbLYpnkGeWU5PWnvVSpTaWuwbOWRm2hsaQqdWmwSKMXbvmeygMPNQ3FDENSod5HUeXYMqxSnAQ05_fCgJeCqMp0aC3_lTDUETj4S0tqKsAGHO--Ffg_h_VBtCzqA9Mbg_3wU1PvnXSBx_9f54WSoZAYrx2tvnFP3WcI7nXu3d_zHXSw8_gI) ## How? This was an attempt to do it in as few bytes as possible. Rather than splitting the input string into a vector, this just finds the unique characters with [regex](https://stackoverflow.com/questions/19301806/regex-remove-repeated-characters-from-a-string-by-javascript), and replace them in the order they appear with the letters `"a"` to `"j"`. Nice to not have to `strsplit()` and `paste()` for once, and be able to do everything in `chartr()`. It's quite a bit shorter. But it's obviously not an optimal approach to the value part of the score, and the overall score is still higher than the original answer. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 516.3704 (73.7672 \* 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands)) ``` ÙΣ¢}RA‡ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8Mxziw8tqg1yfNSw8P//D/OnT/4wf2b/h/mTp0PwpN0QscntH@bPWgShQfwJnRAahpHlJ81A6AdhkPyMVTA1AA) or [verify the average score of 10,000 random runs](https://tio.run/##yy9OTMpM/W9yaIOb0of50yd/mD@z/8P8ydM/zJ@0G0i3P1o79cP8CZ1A7owP82es@jC/r1PJyDTv8Fy9IiPTQ4sPr/A6PCHs/@GZ5xZHFh9aVBvk@Khh4X/H4uBsf65aTSXHMNcgR3dXhWBn/yBXKwUle5fDrY46XEqOOTkKxcn5RanFIEH7/wA). **Explanation:** ``` Ù # Uniquify the emoticon-characters of the (implicit) input-string Σ # Sort it from lowest to highest by: ¢ # The count of the character in the (implicit) input-string }R # After the sort-by: reverse it from highest to lowest count A # Push the lowercase alphabet string ‡ # Transliterate the descending sorted unique emoticons to lowercase letters in # the (implicit) input-string # (after which the result is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), score 90.24 \* 13 bytes = 1173.12 ``` ⭆θ§β⌕Φθ⁼μ⌕θλι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBTqKDiWeOalpFZoJOkouGXmpWi4ZeaUpBaBZFwLSxNzijVyoRJAkRxNTU0dhUwgqWn9//@H@dMnf5g/s//D/MnTIXjSbojY5PYP82ctgtAg/oROCA3DyPKTZiD0gzBIfsYqmJr/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FrcYjRyLizPT8zQMdBQyNK250vKLFDRCMnNTizUMgUKGBgYGmpoK1VycUGXBJUWZeem-iQUaRqY6CkGJeSn5uRpKH-ZPn_xh_sz-D_MnT_8wf9JuIN3-Yf6sRR_mT-gE8md8mD9j1Yf5fZ1Kmpo6CoVAa2DGuWXmlKQWaRTqKLgWlibmFGvk6Ci4ZealgESyNUGqq5BUIywHSjuWeOalpFZoJEF1VMF0gM0HKoJoCspMzyjRCMgpLdZRCC7N1YDqBmtJgmkB-byWKwBoeomGc2JxiYZLZllmSqpGho4CelhoalovKU5KLoYG4PJoJd2yHKVYKBcA "Charcoal – Attempt This Online") Link is to test suite for `10000` random iterations. Explanation: Outputs the letter corresponding to the first time this emoji was found in the input. Note that the code is too slow for the test suite so it had to be optimised slightly. # [Charcoal](https://github.com/somebody1234/Charcoal), score 287 \* 6 bytes = 1722 ``` ⭆θ§β℅ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBTqKDiWeOalpFZoJOko@BelZOYl5mhkagKB9f//H@ZPn/xh/sz@D/MnT4fgSbshYpPbP8yftQhCg/gTOiE0DCPLT5qB0A/CIPkZq2Bq/uuW5QAA "Charcoal – Try It Online") Link is to verbose version of code. [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FrcYWRyLizPT8zQMdBQyNK250vKLFDRCMnNTizUMgUKGBgYGmpoK1VycUGXBJUWZeem-iQUaRqY6CkGJeSn5uRpKH-ZPn_xh_sz-D_MnT_8wf9JuIN3-Yf6sRR_mT-gE8md8mD9j1Yf5fZ1Kmpo6CoVAazCNK9RRcCzxzEtJrdBI0lHwL0rJzEvM0cjWhOsAKoJoCspMzyjRCMgpLdZRCC7N1YDqdsvMSwFphWgB-aWWKwBoeomGc2JxiYZLZllmSqpGho4Cuu80Na2XFCclF0ODZHm0km5ZjlIslAsA "Charcoal – Attempt This Online") Link is to test suite for `10000` random iterations. Explanation: Outputs the letter corresponding to the emoji's ordinal modulo `26`. # [Charcoal](https://github.com/somebody1234/Charcoal), score 73.275 \* 25 bytes = 1831.875 ``` W⁻⪪θ¹υ⊞υ⊟⌈Eι⟦№ικκ⟧⭆θ§β⌕υι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDNzOvtFgjuCAns0SjUEfBUFNHoVRTUyGgtDhDo1RHISC/QMM3sSIztzQXSBdoZOooRDvnl@aVgFjZQMXZsZpAYM0VUJQJFAwuAVLpIIVAsxxLPPNSUis0knQU3DLzUkDGZYIV////Yf70yR/mz@z/MH/ydAietBsiNrn9w/xZiyA0iD@hE0LDMLL8pBkI/SAMkp@xCqbmv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. [Attempt This Online!](https://ato.pxeger.com/run?1=bZDBSgMxEIbx2D5F2NMEUtgKgtBTqQgeCkvrrfSw7W67odlsd5PUgniWXlTsodUeUkRRfAXfxKfIIziLqwcxl-SfzPzfz-zexklYjLNQ7PcvRk8ax58HUVspPpXgM5LQVn2SFQTOeRoraGKp6fs-peSyXqva-rrgctoN53B4xEgvlFGWgufsZu3sw62z642z9x94Xzv7-OTs3Qr11tntu7M3K49SRnLE1C4SLmICXS6Ngv5ccA054vDbIC8wKgHDSJDNoRsueWpSKJkzRgadzEhdvgQ2iyHF0_onHrq19ZmM4iWMGDnlMioNZ_Q3QTUxGJZI1Dj0XerxaaIhEEYx0q_AeWUx-rEod3VVD5CmoRMqDSd8waMYEkb-bg_zPavRWFUrfx14jYXwhpX8Ag "Charcoal – Attempt This Online") Link is to test suite for `10000` random iterations. Explanation: ``` W⁻⪪θ¹υ⊞υ⊟⌈Eι⟦№ικκ⟧ ``` Sort the characters by frequency in descending order. ``` ⭆θ§β⌕υι ``` Map them to lowercase letters. [Answer] # [R](https://www.r-project.org), 112.5 \* 34 bytes = 3825 ``` \(x)letters[utf8ToInt(x)%%430%%11] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHa1LzkosqCktTc_KxM26WlJWm6FjeVYjQqNHNSS0pSi4qjgUIWIfmeeSVAMVVVE2MDVVVDw1iIyluMIsj6NZQ-zJ8--cP8mf0f5k-e_mH-pN1Auv3D_FmLPsyf0Ankz_gwf8aqD_P7OpU0uUrySxJzbA24ihLzUopLijLz0m1jNDQLEotLUg00ihNzC3JSNVJzNIBSxQU5mSUkmK2jpKSpqWNkqlOUWpCTmJxqGxIU6qqpk5yfk5NYUJxqC5TmSssv0shUyMxTMLQyNAACTYhzwKR2cWku0AUFBTmVGijeQzhVA2gBPGA0dS3NNa3BWvXBhkECZ8ECCA0A) Output is a vector of characters in the range `"a"` to `"j"`. Developed independently of, but uses similar approach to [Arnauld's Javascript answer](https://codegolf.stackexchange.com/a/264464/95126). The aim here is to maximally golf the code-size, while keeping the encrypted letters in the range `a`-`j` (but ignoring their abundances in the input). We find the modulo values to map the emoji character codes to `1:10` using: ``` x=utf8ToInt("🗓🙏📗💻📇🚢🐉💘😪🎉") for(i in 1:max(x))for(j in 1:99){y=unique(x%%i%%j);if(min(y)==1&&max(y)==10&&length(y)==10)print(c(i,j))} ``` which pretty quickly outputs `430 11` and nothing else. --- # [R](https://www.r-project.org), 112.5 \* 39 bytes = 4387.5 ``` \(x)intToUtf8(utf8ToInt(x)%%430%%11+96) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHa1LzkosqCktTc_KxM26WlJWm6FjfVYzQqNDPzSkLyQ0vSLDSAghYh-Z55JUBRVVUTYwNVVUNDbUszTYjyW4xyyIZoKH2YP33yh_kz-z_Mnzz9w_xJu4F0-4f5sxZ9mD-hE8if8WH-jFUf5vdB2QispMlVkl-SmGNrwFWUmJdSXFKUmZduG6OhWZBYXJJqoFGcmFuQk6qRmqMBlCouyMksId4uJR0lJU1NHSNTnaLUgpzE5FTbkKBQV02d5PycnMSC4lRboDRXWn6RRqZCZp6CoZWhARBoQpwDJrWLS3ORQgLFxwjXamhqaupammtag_Xog03hggTTggUQGgA) As above, but outputs as a single string (same as [SamR's R answer](https://codegolf.stackexchange.com/a/264425/95126)). --- # [R](https://www.r-project.org), 73.2 \* 61 bytes = 4465.2 ``` \(x)intToUtf8(rank(-table(y<-el(strsplit(x,""))),,"f")[y]+96) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZCxTsMwEIbFmodAlaez6ogUCUiBjAysqJ2AwQQHGZzYsl2peQLEAogOLTA4ILEg8QQ8CTyFHwErQWrZOMn327Luv-_u-UU3H6zKda0sK-Ulz94mtojTr-wEpphXdiTHtkhB0-oKYkvPBIN6P2YCjNVGCW5hShDCGBOCCoSP69P-cBt3Jt9r66vWgLybz7x7vPNuNvfu4TPotXdPr97d34T3wrvFu3e3v_flQTiy0lKRJVEAOQ-teXURCLGixrIEDC1VAFul-ncv1OKTzS2imRI0Z9noaHyASS6FoMqwLHxHhdTAe7zqDXYHSQjc4bS5byYlhHnTkTysLPyZeEkLYUXxcAfvtTUbrUvUralpOv0B) Minimizing the output string value at the expense of code-size doesn't seem to pay-off. [Answer] # JavaScript (ES5), score: 112.346 \* 62 bytes = 6965.433 ``` x=>x.replace(/../g,e=>(e.charCodeAt(1)%576%11+9).toString(36)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVO9btswEB666Q26nQUnJuOathM4_ZWBIGi2ooOBLoZbKxJlM5BJg6ITJ4ayFlnSIh6StoONoF36Cn2S9in8CCVFKXEigDjx7uN3H--OP35yEdLlbeT9mqio9uJve-q1p0TScewHFNUJqQ-eUa-NKAmGvtzX4D2Fmnij9Xx3o9msvsREiY6SjA_Qzi7GluXfk6eB4ImIKYnFAEXIXS2u56vFty-rxfzarqs_1jf_vFp8v7XW7L9eWFus9fjVzf15s0z85neBcTF2nLFIEnYY07cjccQS8KBLCOH0BDpUPZZhJBT0Jq2hN3SXFy7uOU5MFSSBkFSzNJxISEDGxcz2tTZvoNnQn_6tVjHMHADGxxOlwybfnpT-KdpuYRKxOEYNTEb-GH3y2g8Vds_P0TtfDYn0eShGCG81G7iHyZFgHFUqWLNKmkxiQxuhLIG-JYCpr9aSfPBjFupYqWRhOosKhqj-sevXznrVch3D5mYhzPNysrUG6_4CMr3F4LWzamXgXjdHMh7S6fvIQnpGD4sAlfLMGNRQihPoM36cKdG6jqlMmOAQSTECtzzL-FIXlDA7S5u6fXOLu6IKW1Shi7rd0raoKOQdqN4pXxtDgaEGFb-y7msYhamTOo6tUKDdHXZmehjdjyomMeUDNXTWx7SfpXoF5RmySeu2wWbED9iUhmgHp7Cl4wVpCoenipope3xGwwrQg-P9_IUsl9b-Bw) A simple hashing method; optimized for the specific emoji specified in the challenge. # JavaScript (ES6), score: 73.152 \* 109 bytes = 7973.590 ``` x=>x.replace(/./gu,e=>"abcdefghij"[[...new Set(x)].sort((a,b,c=e=>x.split(e).length)=>c(b)-c(a)).indexOf(e)]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVPNbtNAED5w8xtwm1hRM9skm7SoEgIcqUJwQxwicYkCcex1vJXjjdabNm3kXlEvgJpDCxwSVXDhFXgSeIo8ArveuCSNtJrs_HzftzPj7z9SEbLVXeT9nKqo-fTPeOZ1ZlSySeIHDFu0NZo2mNdx_WEQsmgU8xO316OUpuwMukzhjPRpJqRC9BvDRuAxU55NEq6QEZqwdKRi4nUCHJJmgD4hlKchm72NdLhPLOnfR48DkWYiYTQRI4zQXS9vFuvl18_r5eLGnuvf1rf4uF5-u7PW3L9cWVue7fj17f96c0z89leZ4xLiOBORZXyYsFdjccIz8GD7bQ9kGAklvKE18Abu05VL-o6TMAVZICTTKG0nEhLQuLi5PtfmBRy09U__rdcJzB0Ank6mSocN37GU_jkeHhEa8STBNqFjf4IfvM6uwt7lJb7xVUyln4ZijGT_oK37SE8ET7FWIxpVsmyaGNgICwL9SgDTX60le-cnPNSxSsWmaRYVxNh63_ObF_16tUVgb68U5nkbsJ19aAAGsS8JeJ2iW0Vyv7fJLKdbpPSNHh4BVjbMBFQsxRkMeHpaKNG6TpnMuEghkmIMbnVe4OUuKGFuFjZ3B-YV900VtqlCN_XwSNuyo7CZQP1eudHxUq_4sUJBoAk1v7btaxuFuZM7ju1QoN1dfmFmGFElukrydITlIjvbazooqJ5BdY6WtGUHTHTdaz5jIT4hOezreAmaw_BcMbNlD2t0Wpm0Uz7YfCGrlbX_AA) A more generic approach, which sorts the input's unique characters (code points) to minimize the value per run. [Answer] # [Ruby](https://www.ruby-lang.org/), 90.0438 \* 31 bytes = 2,791.3578 ``` ->s{s.tr s.chars.uniq*'','a-z'} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsHiNNuYpaUlaboW-3XtiquL9UqKFIr1kjMSi4r1SvMyC7XU1XXUE3Wr1Gshqm4xhhaUlhQrpEUrfZg_ffKH-TP7P8yfPB2CJ-2GiE1u_zB_1iIIDeJP6ITQMIwsP2kGQj8Ig-RnrIKpUYrl4krNzc_KVLBVQLMQZBnMIJAFIINAGvs6lSDu5wI7VMNQT8_QAAg09YpLc6sVajJrFLgUilKLS3NKgIamRYMUGJlq6uUmFlSDrdIrTswtyEmt1cvKz8yL5VIIDnFxDQrSA5umlJlXlpiTmaKQn6dQVJqnoFydWWsFJCHm1SopZKbBza5T0I-OAwZdrD7MPr2kypLUYrA74g11Lc1ruWr1wW7TM4CE7oIFEBoA) # [Ruby](https://www.ruby-lang.org/), 73.1206 \* 53 bytes = 3,875.3918 ``` ->s{s.tr s.chars.uniq.sort_by{-s.count(_1)}*'','a-z'} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVBLTsMwEBXbnGIUFmkRmTZIFR-prOACBVYhVAkkwlWTlNhGKqnZom4ANYsWWKTis-EKnAROkSMQxwogLD2PPJ_3nufpNeHeePkSdI_fOAvMrc-OuUtTiiwBiqfnbkKRR-QCaZywvjdOzTIb84g1-lZTrBnGuuGaV4ZQw18rRyPOKAS2XuTzrMgf7oo8myvMPlQuuynyx2cV5ft-qmKNv_XZ4ndeQtYX73WP7miaH8YDAl34JyjFaiIpIInk4O1UV7_SKqMNC9Fql6eJlIcpTMgENEh8yoesJA1s2bDRaWLojtJKCqkbjoa-wEFMIkeDg8O9_V4PKzadRJfukJxBHEHCI1hNidgpb8UndCDBD_c1tOyTcnVOq9ZDb8x8WvnoW-b2ptBEq_KGbbXd5VLFbw) [Answer] # [Python](https://www.python.org), score 103.6078\*101 bytes = 10464,3878 assigns the characters in alphabetical order ``` lambda l:''.join(chr(97+[x for(x,_)in groupby(sorted(l))].index(c))for c in l) from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZDRSsMwFIbxNk9x6M0St9UqiDrok8xRujbtIm1T0lS6J5DdqKzIJl60IPNC8Al8Er30CfYIJqbDscDhkHPOn_Plf3nL53LGs_Y1cq83pYyGl1808dNp6EMy6vXsG84yHMwEvrrojyuIuMDVwCMsg1jwMp_OccGFpCFOCJnYLAtphQNC1BwEoKYSgiLBU2CSCsl5UgBLc6U4Nsu-j7xcsEziCFvbZlVvm-eHbVOvTCw_Ta2--_l40slcHxcm72KvvVz_q3Xo9vq9G7EIQcisB-FnIU-Rf0uFH1PXQZrY08SqE1PsDE4ddcgIgSrmpfQKqUBjcGHninnCDmacBfQQX6N3XBpXc2mO-4VF4GDV2bniAuCldCO8v0tXO8C-W5QpHnMRKneHOll-99KfzUo8IchY2UlOzAeMz21r8i8) --- # [Python](https://www.python.org), score 73.2 \* 136 bytes = 9955,2 *-21 bytes, thanks to @Value Ink* always produces a string with the lowest possible average byte value ``` lambda l:''.join(chr(97+[x for(_,x)in sorted([(-len([*n]),c)for(c,n)in groupby(sorted(l))])].index(c))for c in l) from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZDRSsMwFIbxNk8RerNk6-YURB30SWopXZp2lTYpaSrbE-huVDZkEy82GHoh-AQ-iV76BHsEc0yHY4HDIef8J-fL__JWTvRIivUm8a5ea510L77u8qgYxhHOB61W71pmgrCRIpfnHX-ME6lI6I5pJnAlleYx8Uk354L4bRFQl1EQMFeAIFWyLocT0ghzSgMa9DIR8zFhFJSYYaPLKUqULHCmudJS5hXOitLMtC3P91FYqkxokhBnu1rMt6vnh-1qvrAx-7S1-e3PxxMke32c2ryLvfZs-T8NAe3leyNxKEXIrscqErEsUHTDVZRyr4-AOARi00k56bsnfXPoAGFTLGsdVtqAptjDO-PsEz02khnjh_iA3nABLnABx_3Uofhg1emZ4cJY1tpLyP4uqDaAHa-qC-JLFRt3u5CcqHnpz2YzHFBkrWxGju0HrM_rtc2_) [Answer] # [sclin](https://github.com/molarmanful/sclin), 89.8656 \* 30 bytes = 2695.968 ``` dup""uniq $abc","zip >M swap : ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) Uses a very simple index-based mapping. For testing purposes: ``` 10000=$n. "🗓🙏📗💻📇🚢🐉💘😪🎉"=$e. $W ( ; S>c 97- +/ ) map $n tk +/ $n / n>o $W ( $e "."/?& :r ) map 25tk dup >o " => ">o ; dup n>o dup""uniq $abc","zip >M swap : ``` ## Explanation Prettified code: ``` dup () uniq $abc \, zip >M swap : ``` * `dup () uniq` get unique emojis * `$abc \, zip` pair emoji with alphabet to create translation map * `swap :` translate emojis to alphabet --- # [sclin](https://github.com/molarmanful/sclin), 73.147 \* 50 bytes = 3657.35 ``` ""Q""group"len _"sort $abc"0.: dip ,"zip >M swap : ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) Uses frequency-based mapping. For testing purposes: ``` 10000=$n. "🗓🙏📗💻📇🚢🐉💘😪🎉"=$e. $W ( ; S>c 97- +/ ) map $n tk +/ $n / n>o $W ( $e "."/?& :r ) map 25tk dup >o " => ">o ; dup n>o ""Q""group"len _"sort $abc"0.: dip ,"zip >M swap : ``` ## Explanation Prettified code: ``` dup () group ( len _ ) sort $abc ( 0.: dip , ) zip >M swap : ``` * `() group` group emojis * `( len _ ) sort` sort descending by frequency * `$abc ( 0.: dip , ) zip >M` pair emoji with alphabet to create translation map * `swap :` translate emojis to alphabet [Answer] # [Python](https://www.python.org), 107.3917 \* 38 bytes = 4080.8846 ``` lambda x:[97+ord(c)%3203%13for c in x] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZBdSgMxEMfxNacIgdqEfrjtImphT1JLifst7mZNs1JPIH1R6SKt-LALRR8ET-BJ9NET7BFMOiuWBoY_ycz855d5ectuVSTSahM456-5CnqnX4dXPLnwOJ6PxmcnHSE96rKWPbTs1sAOhMQujlM8n0D198F1JuNU0YCSulwVdfn8UJfFCmL5CW_F3c_HkxG4Pi5A_2InvVz_d5sw6fV7U0IYQyhOMiEVljz1RIL4jS956DsWMmhTg6YzoU-t7sDSh40Q1o9ZrqYzpUFD7OB2u38p4pSCRd-NROz6-_gGveEyuIbLcNwvCMN7o4bHmgtjkSuHELBOeEbdSHYDujubbesa5I4zyxM6hv32jBDeeG83rO0mDMFym5Yj-BJsvqpAfwE) Outputs as a list of codepoints. Scoring script taken from bsoelch's answer. # [Python](https://www.python.org), 101.9159 \* 61 bytes = 6216.870 ``` lambda x:x.translate(dict(zip(map(ord,set(x)),"abcdefghij"))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZBBSsQwFIZxm1OEbibBTq2CIAM5iUrJpEmbYdqUNpXqBWQ2KlNkRly0ILoQPIEn0aUn6BFMSMVhAo-fvJf3vy_v-a241qnK-xdBLl5rLaZnX2RJs3lMYTNrAl3SvFpSzVEsmUY3skAZLZAqY7_iGjUY-x6ds5iLJJULD2PsTL4PoqKUuUYCeUO3aYfu6X7o2o2L9afLtbc_H49W3PVh5fQvdsrr7X-3DVvevo9PzFgAZFaoUkPDG6sM0Cte0oSTEAhVwgjK3FYSjkL_ODQHzwA0yaLWUaUNaAIJnEyChZI5chYBS5VkfB_foo9cFtdyWY67lYfh3qiTU8MFoao1EWh3ls2OgIekqjN0bvaJGJ5a8ejoxKyTab7EwK1ybDlyH3B77nunvw) Outputs as a string. [Answer] # JavaScript (ES6), 112.5 \* 24 bytes = 2700 Expects and returns a list of code points. ``` a=>a.map(n=>n%430%11+96) ``` [Try it online!](https://tio.run/##JY/NSsNAEIDveYqhULJr6jTxD6QmUHoWBI@lyJLmryS7YXcRRD1LLyr20Oql4NFX8KX6BnE27uGbZWb225mVuBcm1VVrj6VaZl0edyJOBDaiZTJO5PDsNBxGUXB5wbtUSWMhLYWGGAaH/XYzPuw/3wibLeHj191eCF/fhPe1y@0Iux/C63qApq0ry/yxzyeelyvN6syCJFk4oXAFkYtBwOHRA3A1Q7U5Ik61Fg/s5Jwv@sHuIE76OebXwpaohVyqhnE46pNYZ7KwJTxBuOC4UpVkvs9HpHRHZ06aM6c1/7q012FK@99Qt51axjmNCOA2VnWGtSqYGcGt1ZUsMNeqmdFHM3rASENK1/7c/QE "JavaScript (Node.js) – Try It Online") This version uses a fixed mapping of the smileys to `abcdefghij`. The theoretical average score is: $$\frac{25}{10}\sum\_{n=0}^9 n=112.5$$ --- # [JavaScript (Node.js)](https://nodejs.org), ~90 \* 50 bytes = ~4500 ``` s=>s.replace(e=/../g,c=>Buffer([e[c]||=i++]),i=97) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVHRSsMwFMXXfsVlIEtsl9aBzDEzmD77BaNIydKt0jUl7UCxPsteVNzDpj5sDH3xF_wS_Yp9gjeNiHk4uTk395zcm9e3TI3kZhvz91kZt46_2gXvF0zLPI2EJJL7jPljT_D-6SyOpSZDORRhVfHEdUPqJbzbobbye-9KqKwoQUwiDRwau_Vy4e_Wzw8IiyXC06eJ7hBetgiPc8OtEFYfCPfzBivyNClJ02_SnpPKEkpVRilqBT3HiZUmhsvqM24ncBjgwtB1Kdw4ACZdYHrIGBtoHV2T9hEN2TTKyQXwfv2y4XlUTpiOspGaEgoHKAIVBCFllyrJSNNYWyUtjVZMij-mEErLX33MhgijGU6J5B4IahxycEEw43OGYx2U6NCCbseDoBax_bjcKhkmg_26DagqMONTqWSpGpPCM_6evYi1t87_rNXx7QBoz37AZmP3Hw) This version uses a dynamic mapping of the smileys to `abcdefghij`, according to their order of appearance. [Answer] # Excel, 89.9 \* 67 bytes = 6022.9 ``` =LET(c,MID(A2,ROW(1:25)*2-1,2),CONCAT(CHAR(96+MATCH(c,UNIQUE(c),0)))) ``` This does not optimize for the lowest character sum because doing so in Excel takes so many bytes that the overall score ends up higher. The formula is written for the input (the 25 random emojis) to be in the cell `A2`. To simulate 10,000 runs, I wrote a formula to generate those random string, copied it down for 10,000 rows, then copy / pasted values. The encrypted results are on [PasteBin](https://pastebin.com/cpBsczfP) and the end result in Excel look like this: [![Screenshot](https://i.stack.imgur.com/O8Xvn.png)](https://i.stack.imgur.com/O8Xvn.png) Note: When I copy / pasted down the formula from `B2`, I changed the row reference to be absolute (`$1:$25`) so it would work on all the rows below the original formula. --- Explanation: * `LET(c,MID(A2,ROW(1:25)*2-1,2)` defines the variable `c` to be an array with one emoji per row. It's a little tricky to pull out only because Excel sees these emojis as being 2 characters long so need to pull out strings of length 2. * `CONCAT(CHAR(96+MATCH(c,UNIQUE(c),0)))` + `UNIQUE(c)` filters for just the unique emojis + `MATCH(c,UNIQUE(c),0)` finds the first instance of each emoji within that unique list + `CHAR(96+MATCH(~))` converts that match value into a character in the range `a-j` + `CONCAT(CHAR(~))` combines all those characters into one string [Answer] # [Haskell](https://www.haskell.org), score 73.2 \* 110 bytes = 8052.0 ``` import Data.List j(Just x)=x f s=map(toEnum.(97+).j.(`elemIndex`(map head$sortOn((0-).length)$group$sort s)))s ``` --- # [Haskell](https://www.haskell.org), score 90.1 \* 72 bytes = 6487.2 ``` import Data.List j(Just x)=x f s=map(toEnum.(97+).j.(`elemIndex`nub s))s ``` ]
[Question] [ ``` 4, 32, 317, 3163, 31623, 316228, 3162278, 31622777, 316227767, 3162277661, 31622776602, 316227766017, 3162277660169, 31622776601684, 316227766016838, 3162277660168380, 31622776601683794, 316227766016837934, 3162277660168379332, 31622776601683793320, 316227766016837933200, 3162277660168379331999, 31622776601683793319989, 316227766016837933199890, ... ``` Or in other words: given *n* output the *(n \* 2)*-th term of [OEIS A017936](https://oeis.org/A017936): smallest number whose square has n digits. Essentially we removed powers of 10 from mentioned OEIS serie. # Notes As noted by [Neil](https://codegolf.meta.stackexchange.com/users/17602/neil), there is a correlation with the digits of √(1/10), or even 10, 1 or any power of 10. He also explained: *the length of integers increases at each power of 10. The length of squares of integers increases at (the ceiling of) each power of √10. Half of these powers are also powers of 10, while the other half are powers of 10 multiplied by √(1/10).* Additionally a proof was given by [jjagmath](https://math.stackexchange.com/users/571433/jjagmath). *If *n* is the number where the square change from having *k* digits to \$k+1\$ digits then \$(n-1)^2<10^k\le n^2\$. So \$n-1 < 10^{k/2}\le n\$. If *k* is even we have \$n = 10^{k/2}\$. If \$k = 2m+1\$ then \$n-1 < 10^{m+1}\sqrt{1/10}< n\$ which explains why the first digits of *n* coincide with \$\sqrt{1/10}\$.* **More notes** * There is a difference between the last digit and the corresponding digit in \$\sqrt{1/10}\$, e.g. for the 5th term: ``` 5th term 31623 √(1/10) 0.31622776601.. ↑ ``` * Formal formula from OEIS A017936: *a(n) = ceiling(10^((n-1)/2))* which includes powers of 10 terms. * The next term of *x* is between *\$(x-1) \* 10\$* and *\$x \* 10\$* # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), all usual golfing rules apply. This is also [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") so you can output: * *n*-th element * first *n* terms * infinite sequence **[Floating point issues](https://codegolf.meta.stackexchange.com/a/20533/84844) are allowed.** However answers that doesn't fail due to floating point issues are encouraged, you can post both solutions so that we'll see the difference, in that case please post best score as main solution and the other as alternative indicating both scores. I could fork the challenge in two separate questions but.. I think duplicating is annoying and doesn't make much sense. At the same time, considering what @Bubbler stated in the FP issues consensus: *"Allowing or disallowing such functions (and intermediate floating point values) has a huge consequence, to the point that I could say it defines the actual challenge"*, I think it may be interesting to have a kind of challenge inside the challenge between FP issues in the same language. --- [Sandbox](https://codegolf.meta.stackexchange.com/a/24608/84844) [Answer] # [Python](https://www.python.org), 26 bytes ``` lambda n:int(10**(n-.5))+1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuha7chJzk1ISFfKsMvNKNAwNtLQ08nT1TDU1tQ0hCvan5RcpVChk5ikUJealp2oY6phqWhUUgVSnaVRoakJULVgAoQE) Has floating-point issues. # [Python](https://www.python.org), 45 bytes ``` f=lambda n,i=1:10*100**n>i*i and f(n,i+1)or i ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LYxBCsIwFET3PcVfJtFKshC0EFcew020iX5ofkqSQnsWNwHRO3kbA3VgmMXjzfMzLvkRqLycvryn7NrDt3V6MP7aG6AtatUpKZSUQtAJBYKhHhyrZKN4iIB_6Yx-DDFDWlJTu0s2R3ubYsJAA3rM7FjDG1edGZAgGrpbtufdGJEyc2zmfP0qZd0f) Suboptimal - this is kind of an intermediary solution that shows another way of proving the formula. (I came up with this before seeing the formula, and once I saw the formula I noticed the connection) Here is something of a derivation: 1. Convert the loop-based solution (see below) to a recursive version: ``` f=lambda n,i=1:n*2>len(str(i*i))and f(n,i+1)or i ``` 2. Replace `len(str())` with a logarithmic computation \$ \lfloor\log(i^2) + 1 \rfloor \$: ``` f=lambda n,i=1:n*2>floor(log10(i*i)+1)and f(n,i+1)or i ``` 3. It's an integer comparison, so the `floor` can be removed: ``` f=lambda n,i=1:n*2>log10(i*i)+1and f(n,i+1)or i ``` 4. Raise both sides of the comparison as a power of `10`: ``` f=lambda n,i=1:10**(n*2)>10**(log10(i*i)+1)and f(n,i+1)or i ``` 5. Simplify: ``` f=lambda n,i=1:100**n>i*i*10and f(n,i+1)or i ``` 6. Due to an off-by-one error, the answer I arrived at had `10*` on the wrong side of the comparison; this is negated by choosing to use zero-indexed input (which is what I did instead of fixing the off-by-one error, because I'm lazy) At this point we have my intermdiate answer: ``` f=lambda n,i=1:10*100**n>i*i and f(n,i+1)or i ``` 7. Square root both sides of the comparison: ``` f=lambda n,i=1:sqrt(10)*10**n>i and f(n,i+1)or i ``` 8. Noting that the recursive wrapper now just searches for the first integral satisfying value of `i`, so it's pointless and can be replaced by `floor` `+1`: ``` lambda n:floor(sqrt(10)*10**n)+1 ``` 9. Some Python-specific tweaks to get a more optimal final answer: ``` lambda n:int(10**(n-.5))+1 ``` This is now just the 26-byter above! I'm tired, so there are probably a bunch of mistakes in this derivation, but they mirror my tired and mistake-ridden thought process! # [Python 2](https://docs.python.org/2/), 41 bytes ``` n=i=input() while`i*i`[-n:n]:i+=1 print i ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMHG8ozMnFQFQyuF1IrUZAUlJaWlpSVpuhY3NfNsM20z8wpKSzQ0ucCKEjK1MhOidfOs8mKtMrVtDbkKijLzShQyIRoWw7UuWG7IZcRlzGUC4QIA) Completely non-formulaic solution. -4 bytes with a cool slicing trick thanks to loopy walt. -4 thanks to dingledooper [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 7 bytes ``` Ḥ’⁵*ƽ‘ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLhuKTigJnigbUqw4bCveKAmCIsIjEww4figqwiLCIiLFsiIl1d) ``` Ḥ’⁵*ƽ‘ Main Link Ḥ Double ’ Decrement ⁵* 10 ^ that (smallest number with 2n digits) ƽ Floor square root ‘ Increment ``` Square root + ceiling is one byte shorter but has floating point issues at n = 17 so Jonathan Allan provided a fix for +1 byte that avoids this issue. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` d‹↵√⌈ ``` [Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJk4oC54oa14oia4oyIIiwiIiwiMTgiXQ==) or [verify the test cases](https://vyxal.pythonanywhere.com/#WyIiLCJAZjpufOKGkG4iLCJk4oC54oa14oia4oyIIiwiO1xuXG4yNSDJviDGmyA6IGAgLT4gYCBKICQgQGY7IFMgSiA7IOKBiyIsIiJd). ``` d‹↵√⌈ d # Double ‹ # Decrement ↵ # 10 to the power of that √ # Sqrt ⌈ # Ceiling ``` [Answer] # [R](https://www.r-project.org), 19 bytes ``` \(n)10^(n-.5)%/%1+1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhabYzTyNA0N4jTydPVMNVX1VQ21DSEy64oTCwpyKjUMrQwNdNI0IYILFkBoAA) Uses slight modification of the supplied formula. [Answer] # [Python 2](https://docs.python.org/2/), 42 bytes It outputs the sequence infinitely. Notably, this approach goes for efficiency without losing precision as a result of floating-point math. ``` n=3 s=50 while 1:print-~n;n=n*5+s/n;s*=100 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8/WmKvY1tSAqzwjMydVwdCqoCgzr0S3Ls86zzZPy1S7WD/PuljL1tDA4P9/AA "Python 2 – Try It Online") ### Explanation The sequence can be computed by taking the first \$ n \$ digits of \$ \sqrt{10} \$, rounded up. To do this efficiently, we can use the [Babylonian method](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method). By taking an arbitrary number \$ x \$, and repeatedly applying it to the recurrence \$ x = \frac{1}{2}(x + \frac{10}{x}) \$, we can obtain an approximation of \$ \sqrt{10} \$ that converges extremely quickly (with quadratic convergence). The above formula can be translated in Python as `n=n/2+5/n`. This works fine to simply compute the square root, but to compute the sequence we must scale \$ n \$ by a factor of 10 after each iteration. This can be done by having another variable `s` as the "scale factor", and modifying our original formula to scale by `s`. We end up with the following formula: ``` n=((n/s)/2+5/(n/s))*s*10; s*=10 ``` It looks disgusting at first, but we can clean it up a bit: ``` n=((n/s)/2+5/(n/s))*s*10;s*=10 -> n=(n/s/2+5*s/n)*s*10;s*=10 -> n=n/s/2*s*10+5*s/n*s*10;s*=10 -> n=n*5+5*s/n*s*10;s*=10 -> n=n*5+50*s*s/n;s*=10 -> n=n*5+s/n;s*=100 (starting with s=50) ``` The only thing left to do now is to modify the formula to round *up*. This turns out to be pretty simple, only changing `n` to `n+1`. I've checked that the first 500 terms of the sequence exactly match the output, though in theory, it is still susceptible to rounding errors. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes ``` I⌈×₂χXχN ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sRhIpGbmZOala4Rk5qYWawQXliYWpQbl55doGBpo6igE5JenFgGZOgqeeQWlJX6luUlAviYEWP//b2jwX7csBwA "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Uses floating-point arithmetic. Explanation: ``` χ Predefined variable `10` ₂ Square root × Multiplied by χ Predefined variable `10` X Raised to power N Input as a number ⌈ Ceiling I Cast to string Implicitly print ``` 26 bytes using only integer arithmetic: ``` ≔⁰ηFN«≧×χηW﹪L×⊕η⊕η²≦⊕η»I⊕η ``` [Try it online!](https://tio.run/##XY3LCsIwFETXzVdkeQMRWrddiSvBiog/ENtrEsijJKkuxG@PgYioyxnOnBmVCKMXJudNjFo6aDlVrCdXHyjs3Lykw2IvGIAx@iDNIObKnbRUCc7aYuS0e4@au9IGKQx@WoyHPTqZVIWKawxo0SWcQDFOf3Mp1uXho//Gq/tJjkG7BFsR05@MsT7nrm3z6mZe "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Explanation: ``` ≔⁰η ``` Start with `0` as `⌊√1/10⌋`. ``` FN« ``` Repeat `n` times. ``` ≧×χη ``` Multiply by 10 as our first estimate of `⌊10ⁱ·√1/10⌋`. ``` W﹪L×⊕η⊕η²≦⊕η ``` Increment our estimate until the number of digits of its square would become even, at which point it exactly equals `⌊10ⁱ·√1/10⌋`. ``` »I⊕η ``` Increment the final estimate, resulting in `⌈10ⁿ·√1/10⌉` as required. [Answer] # [C (gcc)](https://gcc.gnu.org/), 22 bytes ``` f(n){n=exp10(n-.5)+1;} ``` [Try it online!](https://tio.run/##VVDbboMwDH3vV1hIlUKBrcBaOmXsZdpXDB5QCB1qayqCNDTEry8zkGZrJF9yfHxkWwRHIbSuGLoDprK/hluGwcPO9UI@6ho7uBQ1MheGFdCbACJJ0cnyI4cUhicf4ogsTCa3j2cfmRAdTExskiQ22ycjn1VFg6oD8Vm0G/JSnGS7iDtZ/x5l/fMb2c7x4f8/dkx31bTApsFqLGVPbVtu0hdQ9bdsKnYb2X00wMYiHDxvZruz2LLmbVUktUXKg5DflRSVpqvdo5JQe5@5M/8jXFuiVMxZlxC8Avm1ypC2Qh@UbxdXaSpzIzuuRv0jqnNxVDr40sH58gs "C (gcc) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 17 bytes ``` n=>-~(10**(n+.5)) ``` [Try it online!](https://tio.run/##DcVBDkAwEAXQvVP85YwiLCyEuouUyoh0BLERrl7e5i3DNRxul@3Mg45T9DYG2@cvVWWaUjBFzRy97iCBRdlC0KH5M4ZxJ4DTcOg6FavOJBk8CXObPPED "JavaScript (Node.js) – Try It Online") Works up to \$n=8\$. --- # [JavaScript (Node.js)](https://nodejs.org), 23 bytes ``` n=>(p=10**(n+.5)+1)-p%1 ``` [Try it online!](https://tio.run/##DcUxDoMwDAXQnVP8BckmJSIDLJDeBdGkMkJxRBBL1bOnfcvb13st2yn56pO@Qo2@Jv@k7N3QdZSMHdk47nPratQTJPAYZggWuOm/MYxPA2yaih7BHvomeSCSMM/Nt/4A "JavaScript (Node.js) – Try It Online") Works up to \$n=15\$. --- # [JavaScript (Node.js)](https://nodejs.org), 40 bytes ``` n=>eval("for(i=0n;!('0'+i*i)[2*n];)++i") ``` [Try it online!](https://tio.run/##DckxDsIwDADAva8wXWrXgApSp2A@ghiikiCjyEYt6oJ4e@h0w73iGpdp1vfnYP5INUs1uaY1Fmyzz6gyWNhhN3SsvdLt3Ns9ELO2VLcHNBA4BTC4CIybzATfBmByW7ykY/En2h4yGlFofvUP "JavaScript (Node.js) – Try It Online") Don't try it at home. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ·<°tî ``` Port of [*@hyper-neutrino♦*'s Jelly answer](https://codegolf.stackexchange.com/a/245558/52210), so also outputs \$a(n)\$ based on \$n\$. [Try it online](https://tio.run/##yy9OTMpM/f//0HabQxtKDq/7/98UAA) or [verify all test cases](https://tio.run/##AScA2P9vc2FiaWX/MjVFTsKnMmo/IiDihpIgIj9O/8K3PMKwdMOu/8OvLP8). **Explanation:** ``` · # Double the (implicit) input-integer < # Decrease it by 1 ° # Take 10 to the power this input*2-1 t # Take the square-root of that î # Ceil it # (after which the result is output implicitly) ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/index.html), 9 bytes ``` ⌈10⋆-⟜0.5 ``` [Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=U21hbGxlc3RfZXZlbl9kaWdpdF9zcXVhcmUg4oaQIOKMiDEw4ouGLeKfnDAuNQpTbWFsbGVzdF9ldmVuX2RpZ2l0X3NxdWFyZcKoIDHigL8y4oC/M+KAvzTigL814oC/NuKAvzfigL844oC/OeKAvzEw) ``` ⌈ # ceiling of 10⋆ # 10 to the power of -⟜0.5 # input minus 0.5 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ⌈`^10-. ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxYYG/x/1dCTEGRro6v3/DwA "Husk – Try It Online") Uses formula: floor (`⌈`) of `10` to the power of (`^`) input minus (`-`) a half (`.`). --- # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` €D⁰mȯLd□N ``` [Try it online!](https://tio.run/##ASAA3/9odXNr/23igoHhuKM1/@KCrETigbBtyK9MZOKWoU7//w "Husk – Try It Online") Calculates the number of digits (`Ld`) of the square (`□`) of each (`mȯ`) number (`N`), and selects the index of the first (`€`) one that matches the input (`⁰`) doubled (`D`). [Answer] # [Julia 1.0](http://julialang.org/), 18 bytes ``` ~n=ceil(10^(n-.5)) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/vy7PNjk1M0fD0CBOI09Xz1RT879DcUZ@uYKhlaGBgl6NnULdfwA "Julia 1.0 – Try It Online") Based on the formula provided. By default, `ceil` returns a float, but `Int` can also be specified: ``` julia> f(n)=ceil(Int,10^(n-.5)); julia> map(f,1:10) 10-element Vector{Int64}: 4 32 317 3163 31623 316228 3162278 31622777 316227767 3162277661 ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 6.5 bytes ``` +^^~-*$~~-2~ + ~ Add 1 to ^ -2 floor of square root of ^~ 10 to the power of - ~ subtract 1 from * ~ multiply 2 with $ input ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LYwxCoNAFAX7OYdVwoLv76prk6NYCAkExEZt9yI220gaL-RtImg7w8z6G799P7ynnLdl_ri4P7suuUeRkrN0odvk4yUMT6CipiHSohIJGfIooArVqEERtViJnY1hHgvX5g8) ]
[Question] [ > > Dialogue by a 3Der. > > > I was hired by Sr. 4Der to learn the 4D universe and I was willing to get to know more about it. But since I am a 3Der, I wouldn't see him, nor would I know how the real shapes look like. All I can do is illustrate. Sr. 4Der is pretty much invisible to us. We can't see him, but we can hear his voice. Certainly, he would give us a task for each and one of us. So I was employed as "Programmer", and the task is to illustrate 4D shapes by the use of ASCII art, and I came up with a design for a tesseract. ``` ############################ #### #### # # ## # # ## # # ## # # ## # # ## # # ## # # ## # # ## # # ### # # ### ############################ # ## ### # ### ### # ### # ## # ### ## # ## # ### ## ### ## # ## # ## ## ## # # ## # ## # ## ## # ####################################################### # # ## ## # #### ## ## # # ## ### # # # ## ### # # # # ## ## # # # ## ## # # # # ## ## # # # ## ## # # # # ## ## # # # ## ## # # ## ### #### # ### ## # # ####################################################### # ## ### ### # ### # # ## ## ## # ## # ## ### ### ### # ## # ## ## # ## # ### # ### ## # ### ## # ############################ ### # # ## # # ## # # ### # # ## # # ## # # ## # # ## # # ## # # ## # # #### #### ############################ ``` And after bringing it to the office of our boss, he called on us and we listened the words. > > Dear programmers, attention all. I have found a design by [say name here] of a tesseract and I would like every one of you to try and make a program to output the same outline. > > > A co-worker of mine then said: > > Does it have to be only `#` or another character? > > > He replied: > > Use the character you want to use. Use only one, then print the tesseract with the same character, over and over. Understood? > > > He nodded and we did our thing. Some did input, some just did the basic, and more. After our hard work, he congratulates us and the day has finished. Now that I think about it, maybe it's your turn to make the same tesseract. # Objective * Given the code block representing the tesseract, replicate the outline with any `char` you want to use. * Do not change the type of tesseract to be made. Keep the same shape and the final output should be the same one in the code block. (Replace the `#` with what you want, but only a single ASCII character that is not a space) * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the program with the smallest amount of bytes wins! ## Bonus Objective (Not needed to complete the challenge) * Make a program where the user gives a `char` input and will be used to output the tesseract outline using the same character. Rules from the original objective is still applied. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 428 bytes Uses `0` instead of `#`. ``` _=>Buffer('QaV6:)R/rEkQy|:|\\!8GG6Pzy}lO<:xv-q,GoKfhfkci;Br"? &]N9Xx[}~tvc1Z6;%Fq6>DO(9dGs&sG~n@z},=x7]+Qo4y}~8Tr~>45<y#J;_a-^"X=^:?`(8*QQh"GQ.V0>GBpa~ytaJYb^YJdo=/W&59kP#@pZ-pYt-uLLe-lDv/kV|}.ylnY<-$H@G&H{h4PPL%q&7t?1.?t}cI6Fcz-Nvo_wPUPP:Xh|tG0zp)lNIh`Ah-d"t.+0L8&}M6LK.Mr$4rH\'l(x4p4_v|[gdf-~9qo,c{U\\Vw(RCYJrd`^&G[{Tr$PGPkS\'$iaBKm{q').reduce((p,c)=>p*95n+BigInt(c-32),0n).toString(2).match(/.{62}/g).join` `.split`1`.join` ` ``` [Try it online!](https://tio.run/##JcjbYpowAADQ931FZy2GauJlSL2hznWNt1roxWlLFRZAqJRgjFRU@HX3sPN4PszI3BLmhRwG1LLPjnJeKu3eznFsBnKaOZUb4mOR/V5r8alx0vXvNYxl9RAn/kOrsY/gpoDpyHGdNfGaPZbpXAjvk/ps/5akPCLlV7l5dbeR27cPoG7hrbDFadA9JAVlf/Oe16gUJ2ntmaVtqdqKL4fNpQkXmZmyaHQMULvWNDeDNTQttXEvNNOYm8P538V8aFGl@Eeo1tfqZTd8heGcw914bEP/Niqup6cExX4wb8Fsv4uF/tGVVHV8tRFueKeMOjwhA/mOHOAkossv9UVVGzP3xHHpEIr@ZOAaP11oZTjKl8Y1IbmXxyN0z7IS6@s5H@ylUFpGp7eV5cC0vqEFcnzR9ekXePw1HzLLWAj47fjMsipW1096LuuZvdHncZMTEbOtHbEBCAtEVNrhdb0a5HveahBwQOCPilgoBSLi9IkzL1iBiog@TU5cUERHuZIUVyL6oF5gfDPQNvQ9bpSN/3FhnAkNttS3kU9XwAGieP4H "JavaScript (Node.js) – Try It Online") Not sure if it was intentional but, contrary to appearances, the tesseract is **not** symmetrical. Storing only the upper part and encoding the differences for the lower part would most certainly be more efficient in some languages, but I didn't find a short enough way to do that in JS. So this is just a binary to base-95 compression for now. **Note:** With RegPack, we get [480 bytes](https://tio.run/##HVBZbuwwDPv3KQz4o8lHe4FiepW0WceO9012DPnq8zKPAAECFCSK4i//hcVzGz@1WbfX/nhNj582PX4bvTaPVm@9lHCyEsi@2pL7JqWvTnqSu8I@q80Yz@ab5EKXgGBUnoWoNOMhW2AhJ0@iSJoGlZD75ICGE7gDy2gocMt2XYLEAmufAVcLJEZc1VJCF6kULvXhZF6P7jLP3R@79EcrkpcERzYKj74QtBif3fiIppB7nSNwCninKI68771jOHKcIrCkF6KTC@FmJhXULMBGQRKm0q6t@thi0X0uxEKN0auFJO1k9U6SE3YLO7E6lxPzPVHh3dF5t4UtMNY6pdfzPzD1QhlQzLSk2pceKPiGrjFbqyldN1CsSprPmgQyTtgT719g7yxvSNaOS2RzM7/fu/EDp2b/mJd1248nF6dU2ljnQ0wZSr0a9o8ReHwO01ewkseBj@P0EIbrwRo7jOO332Lymk74WowORm5f0hzDfluvfw). (Not a fully optimized version, but we could only shave a couple of bytes.) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~252~~ 247 bytes ``` ->{r=s=(' '*62+$/)*34 32.times{|i|s[[7,826,853,1672][i/8]+i%8*62,28]="##{(i%8%7<1??#:' ')*26}#"} 96.times{|j|s[q=[70,97,504,531][j/12%4]-603*(k=j/48)+(m=j%12)*63*z=1-k*2]=?# m<1&&r=1-k s[q+r-k*t=80>>m-(79>>j/12&1)&1|2,t]=?#*t r+=z*t j==5&&r-=1} s} ``` [Try it online!](https://tio.run/##nVbtcqowEP2/T5FxqwXEKqCAnUYfhOGH3mtvQ@tHAafTqs9uQwEJmHCdxpEIZ89u2D2bGO@Xn@dneh7MDjFNqHZP7g3X7t8NdcMZg2M/pGy9Sg5HdkyCwDN92zX9iWNarmeHARv6YZ91fc4wbT@kHcSDxu@73pM1n@Mjd6YbtnvCzgmmbukq4q7eaeCNzKlnTkZjc@JYYRANLbs7DgfuyDG0VxoNx77e19Y06lq2briO8UWtwathh3SOsH6yer04ewDcVz/mQEr90Wy2HmjedDbLnPUsvWcdbTPNGEYKcZ9@8SmidMK5A2qdIDmdMXnZfpDtPt3tU@DfhCRpzDb/8if0OQgB8I1tVmT5SX7mP9v1bhGzhG035IOlLyReve9ZvPoLCypyH5LdG0s1nklY0g7JB7YMqEyIfFRWyD9EbldAkP8mmBMlZiUE@R3BMsiVYQVByaqW1DAVIShusPYKonEDgrb8kCYhj1EgeJWqSzC8TiMU6UNZjlUQyXniS9RRJXRhyouGJZf8hysxKYh4A/t3A7AW@7rgF8XKVFZmrMKFDGFDys3kcQgE@ZUBRCk0FC46yCDAhsSECWWyr8kzo@N1jUt9SDtBkFymTam8hCZHCVSmFX5ZscIdqDaILIKyM0hFb1FkS4sIdNKyAmUToUBXtctlBSoIJBtOXXWoaiZSbcXSJeDNO7l0CfWyy7oJlElt7rCSZgLSUhPZNimqXVnsqs8UEChPrEujKCAV88aDUI2rRkc4mMEZV39wfk7/RcBCc5ld7oan8zc "Ruby – Try It Online") The horizontal, vertical and short diagonal lines are fairly straightforward. The long diagonals are more problematic: the two triple `#` sections are not always in the same place, and the top left long diagonal actually contains a single `#`. It's difficult to see because it's where it crosses the horizontal line.) **Commented code - original version** ``` ->{r=s=(' '*62+$/)*34 #Make a string s of 34 lines of 62 spaces (also r needs to be initialised to any value to avoid error.) 32.times{|i|s[[7,826,853,1672][i/8]+i%8*62,28]= #Draw horizontals and short diagonals as space-filled parallelograms. "##{(i%8%7<1??#:' ')*26}#"} #In ruby syntax #{} can be used to insert expressions into string literals. 96.times{|j| #Iterate through the corners of the top and bottom parallelograms, drawing verticals and long diagonals. s[q=[70,97,504,531][j/12%4]+(k=j/48)*-603+ #This expression gives the first cell of each. Ruby string indexes wrap around so -603 gives a negative index for the bottom. (m=j%12)*63*z= ~0**k]=?# #Draw the upper verticals downwards from the top and the lower ones upwards from the bottom using z= ~0**k to give +1 or -1 m<1&&r=1-k #r is the offset of the diagonals from the verticals. if new diagonal (m=j%12)=0, initialise r to to value for downward or upward drawing. t=80>>m-(79>>j/12&1)&1|2 #t=80>>m&1|2 gives the value 2 or 3 for the number of # to be drawn on each line. 79>>j/12&1 offsets m to shift the pattern by 1 on some diagonals. s[q+r-k*t,t]=?#*t #Plot the right number of #. For bottom up (leftward) drawing an adjustment of k*t is required. r+=z*t #Change r by t, in the correct direction (left or right drawing.) j==5&&r-=1} #The top left diagonal is drawn odd and needs an adjustment of 1 at a certain point. s} #Return the string. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~111~~ 84 bytes ``` F⪫⪪”)¶³6ΠKsv8∨ιm↥Sq3iθ¿⁼p[⪪∕¤⁺WηQDσ⁰”9¦87878≡ι3F”{∨>´↶}⦃α”✳Iκ#✳Iι×#I§⪪”)⧴Z/g↑◨M⸿”²Iι ``` [Try it online!](https://tio.run/##bY/NasMwDIDveQqjXWxowX@J4/Y0ust2GmwvYFyXimXJSLyuUPbsnhJWusMkkMTHh5DiMYxxCF0ph2Fk/GnAnr98dJg5SO9861xLzVmlTSO1rWluCc1MNsrU@g9Qtm6MlopG7xfsGmtqWDHwIKjOpAUh2PSFOR4ZR8EuVQxTYmBgw5YTwNhb3sqSINjziH3mDzimmHHo@S5Mmb@Jef0diG21T4fw2eXN/yLO4iu@p4mTvmILvM@P/T6dr39rJ50yUl27VCRq8SvTBopt9V1KWZ@6Hw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: As @Arnauld points out, the diagram is not quite symmetric; only six of the top left to bottom right lines are the same, and even then they are not mirror images of themselves, although one is a mirror image of the other six. I therefore encoded an Eulerian Cycle using the following integer key: ``` 0 Horizontal line of 28 #s (left to right) 1 Diagonal line of 8 #s (bottom left to top right) 2 Vertical line of 13 #s (bottom to top) 3 Diagonal line of 28 #s (bottom right to top left) 4 Horizontal line of 28 #s (right to left) 5 Diagonal line of 8 #s (top right to bottom left) 6 Vertical line of 13 #s (top to bottom) 7 Diagonal line of 2 #s (top left to bottom right) 8 Horizontal line of 2 #s (left to right) 9 Diagonal line of 6 #s (top left to bottom right) ``` The last three are combined to create the three styles of top left to bottom right line. (Note that the `#` counts above assume that the ends of the lines overlap, although the implementation leaves off the last character as the next line will draw it anyway.) The program then consists of a compressed string of coded values and a program to implement each code in turn using a `switch` statement. Edit: Saved 10 bytes by using `9` to substitute for `87878` and a further 17 bytes by creating a table of amounts to draw for each direction. If the diagram was perfectly symmetric, then it would be possible in only ~~80~~ 60 bytes: [Try it online!](https://tio.run/##VY7BCsIwEER/pcTLBio0adJEPEl70YuC/kBJIw20SUmD6NfHBirqXnaZt8yM6luvXDvEeHc@g5MzFq7TYMLviYjktGSClLySRFBWlZLySrCSUCk4q1CeIYlwntUvNei6dxOgnVxUKvCiIob@UMFWlF28sQEa47UKxllotPJ61DboDs4e6nYOYBYHjpPPzYx6BrRJbokcwtF2@vlpWRAqiqXkdxckBeH13eA0@xjj9jG8AQ "Charcoal – Try It Online") Link is to verbose version of code. The above diagram could actually be drawn in a single Charcoal command, although that would (if I have calculated correctly) be 515 bytes (slightly less for the asymmetric version). A highly simplified diagram takes only 67 bytes: [Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT/PIz8nJ79cwyq0ICgzPaNERyFDR8EKyiwEMl3yy/N8UtOgEqEFOgpVYBoilgpkQ1gwtVCtqWBFSEYi60A1E8SDmIpkLYpeDHMhylEtxnQYinEQaVw2o9mAMBnZPDT/YLgZzRBUu7A4VklZSdP6/38jAwUzBUMzBSOD/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Takes the sizes of the four lines as input. I also implemented an Eulerian Cycle algorithm but for a simplified diagram this still was slightly longer at 74 bytes: [Try it online!](https://tio.run/##TZBBT8MwDIXP26@IysWVMqntoRdOHWMS0hCVxg1xKG20WKTpWicMhPjtxek6mKUc/Pwp79m1roa6q8w4FkR4sJBI0ce3y5NGowRs0Tg1QJpLsVNEUNgv8FIUtoG7zlsHbcCl@Gve45jb@95XhiCVYu9bWFek4BGtJ1ijOyGppwH6wEoxC@HDSWEpi6cS38vFnKnsjoA8QQ62KD3pkOGFeXwNykxd2eA5VcZPXxGl4dlO2YPToHm26fybUQ2EkDq@wOWAvMsGB1U77OxEPmOrCKKbiFetyEHhHmyjPmF/NOggypIkT/MsiS6eXP@2eD7pzziOqw/zCw "Charcoal – Try It Online") Link is to verbose version of code. If there's an easily describable Eulerian Cycle then I haven't found it. [Answer] # Deadfish~, 2090 bytes ``` {iii}iiccccccci{cc}cccccccc{dd}dddc{ii}iicccccciccccd{cc}cccicccc{dd}dddc{ii}iicccccicdcicdcciccd{cc}icdcicdccicc{dd}dddc{ii}iiccccicdccicdcccciccd{c}cccccccicdccicdccccicc{dd}dddc{ii}iicccicdcccicdcccccciccd{c}ccccicdcccicdccccccicc{dd}dddc{ii}iiccicdccccicdcccccccciccd{c}cicdccccicdccccccccicc{dd}dddc{ii}iicicdcccccicd{c}icccdcccccccicdcccccicd{c}iccc{dd}dddc{ii}iii{cc}ccccccccdccccccicd{c}cccicc{dd}dddc{ii}iiicccdccccicd{c}ccccicccdccicccdccccicd{c}ccccciccc{dd}dddc{ii}iiicdcciccdccicd{c}cccccccicccdcciccdccicd{c}ccccccccicc{dd}dddc{ii}iiicdccccicccd{c}ccccccccciccdcccicccd{cc}icc{dd}dddc{ii}iiicdcccccciccd{c}ccccccccicdciccdccciccd{cc}cicc{dd}dddc{ii}iiicdccccccicdciccd{c}ccccccicdccciccdcicdciccd{cc}cicc{dd}dddc{ii}iiicdcccccci{ccccc}ccccc{dd}dddc{ii}iiicdcccccicdciccdcccciccd{c}cicdccccciccccdcccciccd{c}cccccccicc{dd}dddc{ii}iiicdccccicdcccciccdccccicccdccccccccicdccccicdcicdcciccdccccicccd{c}cccicdcic{dd}dddc{ii}iiicdcccicdccccccciccdccccciccdccccccicdcccicdccicdcccciccdccccciccd{c}icdccic{dd}dddc{ii}iiicdccicd{c}iccdccccciccdccccicdccicdcccicdcccccciccdccccciccdcccccccicdcccic{dd}dddc{ii}iiicdcicd{c}ccciccdccccciccdccicdcicdccccicdcccccccciccdccccciccdccccicdccccic{dd}dddc{ii}iiiccd{c}ccccccicccdcccciccccdcccccicd{c}icccdcccciccdcicdcccccic{dd}dddc{ii}iii{ccccc}cccccdccccccic{dd}dddc{ii}iiciccd{cc}icccdcicccdccccicd{c}cccccicccdcicdccccccic{dd}dddc{ii}iiccciccd{cc}ciccdcciccdccicd{c}cccccccciccdccccccic{dd}dddc{ii}iiccccciccd{cc}icccdccicccd{c}cccccccccicccdccccic{dd}dddc{ii}iiccccccciccd{c}ccccccccicdcciccdcciccd{c}ccccccccicdcciccdccic{dd}dddc{ii}iicccccccccicccd{c}cccccicdccccicccdciccd{c}ccccccicdcccciccc{dd}dddc{ii}ii{c}cciccd{c}cccicdcccccci{cc}cccccccc{dd}dddc{ii}ii{c}ccccicccd{c}icdcccccicdccccccciccd{c}cicdcccccic{dd}dddc{ii}ii{c}ccccccciccdccccccccicdccccicd{c}icccdccccccccicdccccic{dd}dddc{ii}ii{c}ccccccccciccdccccccicdcccicd{c}cccciccdccccccicdcccic{dd}dddc{ii}ii{cc}ciccdccccicdccicd{c}ccccccciccdccccicdccic{dd}dddc{ii}ii{cc}ccciccdccicdcicd{cc}iccdccicdcic{dd}dddc{ii}ii{cc}ccccciccccd{cc}cccicccc{dd}dddc{ii}ii{cc}ccccccci{cc}cccccccc ``` Uses `!` - it's the closest codepoint to . [Try it online!](https://tio.run/##xVfBbuM2EL3rK7gnSo0T2C22QIP1XpotukDRXAq0gBsYCklbRBTRoGTLC8HfniUpkiIpynYurYDdMHozozePM0Nm960pWPXT2xt93THegPpbnSSozOsaPJAcb2hdfOGc8fTLEZFdQ1mV3SdAPJhswHpNK9qs12lNys0MvJK6zrdEG8hnx2nVpOa9fS0@ckeOtEkXWZLswBL8ySqS0A2AtzsIaKUMcr499JGkhXmzMos7WmFyTKVHdrN4SpLDmgm73/KyJmLdiPVffK@jHiJRe3vIPGgc/tCH7z1kVNhc55Eg9QFFAq2PlpsihCKE0HWE0ECoDwuP13kk7ZpYFq2jVrt@dNbcZ9pGmPaBILnw3XZg2l6Xm@chScHH93hI6pBf55GgV1wL@w5SeA8gnAGIzaI2C2YWyCwKs2jNIjWLzCw6szipxUkKKWqn106sxUYPLSJprASHJ3AjyFMYAFgDOARqDdQhwDTAQgBpAIVAoYEiBFoNtCGQaiANgUwDWQh0GuhC4KSBExzkOU7Jc3y3PC9T8vz6bnkepuR5mZLnOCXPw5Q8/0zJIzxIqeqI/T919J9tjNA/kYcLORK0b0iaIzQTBwnbzgBdzmeAi9e8FgfRUk0pfdo88xy9kEZ29LyfBgUtCaDgEyhJlUp/51xChbCT71ZUTALzVqZYyOFhcxs85COYSIYL@1LtiOuCYy63Z13qmMsPS/lj2qkNnfqDFv5OypLNwN@Ml/iDmECkwksIs@lAaRhI4JLAUsjoAwr00zfPWandx5M9ZhCwy0J27vPMSf4SjxKnKYJT8Hl5ieQ4LhFlNra1FXe@JLowhw3jYC1xnldbkoqK/iXCRG1CtAfADVjM1LUiW819Gesmb8hlt2T8IeUZhqMWWDz5CT4zVqZGgAzkFT6/b1arcS/Ydh5FOYVROGn2vAIrlRZ9mta8mGiPf6s/WLUFJT0Q0BQEyNvtB@jrYe@m86Bt5PVCU1yqa8Z9RMe571OxBqQuMznkxP67r8S5k416UNywxjXBc1qT4FoucvpaHfKSSmK5kLkhHHQnkDdAXXjEGt6JknvNG0FEyJZlV9S21cuZIe6YTPWMuF3IbPQvP378OZO/pvLqJpVSVp/A3Nh8FiYfs1iy7OpkHw@Eb0rWygRlwjLX9KvONJOf2b/uy7xh8i4Y5j6T@FUCmN2cOhtYvMJUZV4cuijujAouA2TjCM5AC3sgSQxVWsm/k8T/@ybNksj8EJCcGG9vHaX0RCnqH9ohdNJr1GF8whijzrFQP7C2ohNWFGH1TxooW/fF2F4jWMcXHoZCgIxce0gbeM5jJHS2YTFCvnsUCdwNSJWL5IJdzh7iu3oSW3qa9@hDNjJ1UkNayhBBka@ZbfDs3CAhEuOArYtjp53Ne5Vr1DHcVV0fxrmvpnPO2A9AraeDnQ/RqR@nSFk722U4hYWgiz5WnlNKYUcf5FaHW1zO3njq9lgsMnWqbOCGfVnwiIChrbFohehi9YM6wby9DL5sTcaR3cp23Wz@ow4cE4hF9srBkTDelrZWosHc4rBJjvrd1nhfKNHew65MkWk1FOp07037o4BFtCPjgqHJPnTITCHRUMHX3RkR69bIaFIW1Kv6S2eQOwFNPY/awu/caAC/ep1CDGb5VP1FpqDbgANNfK4/nFoYWm3MMNq1wwk8NJOuDByfIFbVS0e4I7@3Fd8B "Python 3 – Try It Online") Uses an alternative python interpreter since the current deadfish~ interpreter uses recursion and crashes on large programs. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 274 bytes ``` »-pṄṗ,₄xW(j ḋ2¡e¤∆⟩⟑REK₁₍Ḟ⟑£FO∧⁰d⁼•⌊⌈⟑4D0Zʀ1⌈ ±E1¹,ε∩ṙ∇rȦİǑ!ȧ∇ḣ[F₀ġṙ←lSṙ₁Ȯ⁺DṄ4¾₄fλ>⅛⋏⌈~□¹₍Fṗ¹↵AǍṄ9⁰∇ǔW3∧q₍ǐ¶ɾzḞṫ⁋↲₴[÷ḟC½†>~!`Ṡ⁽Qτ⋏kAẆ€3∩ G∴:Ḋ½T«□²Ṡ‟/d⟇/√⌈Ẇ£8…A{⁽°q∷¼∪⟑β₂Ṁ-ṡ€Ṗ∩ṫkİṀ∷₴vċ⋎ċ≈⟇ʁ⁽JMXȧṖ⟑yZ∞b.J^⁽Ḣ²‛ŀ4⅛⁽∵„|ṁ↲j←"n₀∴⁋⟑∨Bø"µ~⁰cẇ⋎¬ȯ×Ġǔ↵Ḋjy⟨#İḣA`∆₄]‟y∆,›[LḢ½?Ḋɾ¡½» ‛# τ34/ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C2%BB-p%E1%B9%84%E1%B9%97%2C%E2%82%84xW%28j%0A%E1%B8%8B2%C2%A1e%C2%A4%E2%88%86%E2%9F%A9%E2%9F%91REK%E2%82%81%E2%82%8D%E1%B8%9E%E2%9F%91%C2%A3FO%E2%88%A7%E2%81%B0d%E2%81%BC%E2%80%A2%E2%8C%8A%E2%8C%88%E2%9F%914D0Z%CA%801%E2%8C%88%20%C2%B1E1%C2%B9%2C%CE%B5%E2%88%A9%E1%B9%99%E2%88%87r%C8%A6%C4%B0%C7%91!%C8%A7%E2%88%87%E1%B8%A3%5BF%E2%82%80%C4%A1%E1%B9%99%E2%86%90lS%E1%B9%99%E2%82%81%C8%AE%E2%81%BAD%E1%B9%844%C2%BE%E2%82%84f%CE%BB%3E%E2%85%9B%E2%8B%8F%E2%8C%88%7E%E2%96%A1%C2%B9%E2%82%8DF%E1%B9%97%C2%B9%E2%86%B5A%C7%8D%E1%B9%849%E2%81%B0%E2%88%87%C7%94W3%E2%88%A7q%E2%82%8D%C7%90%C2%B6%C9%BEz%E1%B8%9E%E1%B9%AB%E2%81%8B%E2%86%B2%E2%82%B4%5B%C3%B7%E1%B8%9FC%C2%BD%E2%80%A0%3E%7E!%60%E1%B9%A0%E2%81%BDQ%CF%84%E2%8B%8FkA%E1%BA%86%E2%82%AC3%E2%88%A9%0AG%E2%88%B4%3A%E1%B8%8A%C2%BDT%C2%AB%E2%96%A1%C2%B2%E1%B9%A0%E2%80%9F%2Fd%E2%9F%87%2F%E2%88%9A%E2%8C%88%E1%BA%86%C2%A38%E2%80%A6A%7B%E2%81%BD%C2%B0q%E2%88%B7%C2%BC%E2%88%AA%E2%9F%91%CE%B2%E2%82%82%E1%B9%80-%E1%B9%A1%E2%82%AC%E1%B9%96%E2%88%A9%E1%B9%ABk%C4%B0%E1%B9%80%E2%88%B7%E2%82%B4v%C4%8B%E2%8B%8E%C4%8B%E2%89%88%E2%9F%87%CA%81%E2%81%BDJMX%C8%A7%E1%B9%96%E2%9F%91yZ%E2%88%9Eb.J%5E%E2%81%BD%E1%B8%A2%C2%B2%E2%80%9B%C5%804%E2%85%9B%E2%81%BD%E2%88%B5%E2%80%9E%7C%E1%B9%81%E2%86%B2j%E2%86%90%22n%E2%82%80%E2%88%B4%E2%81%8B%E2%9F%91%E2%88%A8B%C3%B8%22%C2%B5%7E%E2%81%B0c%E1%BA%87%E2%8B%8E%C2%AC%C8%AF%C3%97%C4%A0%C7%94%E2%86%B5%E1%B8%8Ajy%E2%9F%A8%23%C4%B0%E1%B8%A3A%60%E2%88%86%E2%82%84%5D%E2%80%9Fy%E2%88%86%2C%E2%80%BA%5BL%E1%B8%A2%C2%BD%3F%E1%B8%8A%C9%BE%C2%A1%C2%BD%C2%BB%0A%E2%80%9B%23%20%CF%8434%2F&inputs=&header=&footer=) ``` »...» # Base-255 compressed integer literal ‛# τ # Convert to custom base with key `# ` 34/ # Divide into 34 pieces # (j flag) joined by newline. ``` ]
[Question] [ Tom the lumberjack is going to do his daily routine: chop trees. After all, it's his job to do so. His boss has ordered him to chop trees in a straight line marked with a special tape to identify them, so he knows which trees he is going to have to chop. However, Tom quickly realizes he has a problem. His axe will only chop so much wood before breaking, and he forgot to bring a spare with him. Plus, the trees are different sizes. A small tree, marked with an `i`, will take 2 swings of the axe to chop, and a large tree, marked with an `|` will take 4 swings. Can Tom chop all of the assigned trees? **The Objective** Given two inputs, a string that determines the sequence of small and large trees and an integer that determines the durability of the axe, create a program that determines not only if Tom's axe will break or not, but also determine how many of each tree type he chopped down. It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! **Example** Input 1 example:`i||iii|` This input string determines the sequence of trees. Input 2 example:`50` This input integer determines the durability of the axe. The outputs for this particular example will be a boolean and a string as follows(True means Tom's axe broke): `False` `4 small, 3 big` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 52 bytes Takes input as `(b)(n)`, where `b` is a Buffer (using the characters described in the challenge) and `n` is the durability of the axe. Returns a Boolean value and 2 integers as `[ broken, [ small, big ]]`. ``` b=>n=>[b.some(c=>(n-=6&c+1)<0||!++a[c%3],a=[0,0]),a] ``` [Try it online!](https://tio.run/##BcFBDsIgEADAt9hEsxsowRg9dTn4DcKBIhhMyxpQT/wdZ17@51uo@f2ZCz/iSDRWMoWMXVXjPUIgA2Wm2ymIMy6694MQ3objxUlPVkvtUHo3ApfGW1QbPyHB/ZtSrCpV3mHKveec@4QIV404/g "JavaScript (Node.js) – Try It Online") ### How? Given an ASCII code `c`, we use `6 & (c + 1)` to get the number of swings needed to chop the tree, and `c % 3` to get an index into the tree-counting array `a[]` (0 for *small*, 1 for *big*). ``` char. | c = ASCII code | 6 & (c + 1) | c % 3 -------+----------------+-------------+------- 'i' | 105 | 2 | 0 '|' | 124 | 4 | 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes -5 bytes thanks to Kevin Cruijssen. ``` ηʒÇ3%·ÌO@}θD¹Ês{γ€g‚ ``` [Try it online!](https://tio.run/##AS8A0P9vc2FiaWX//863ypLDhzMlwrfDjE9Afc64RMK5w4pze86z4oKsZ@KAmv//fGkKNg "05AB1E – Try It Online") ## Explanation ``` η Prefixes of the input. ["i", "i|", "i||", "i||i", "i||ii", "i||iii", "i||iii|"] ʒ Filter: Ç Ord codes. E.g. "i||i" -> [105, 124, 124, 105] 3% Mod 3. -> [0, 1, 1, 0] · Double. -> [0, 2, 2, 0] Ì Add 2. -> [2, 4, 4, 2] O Sum the prefix. -> 12 @} Does it exceed the second input? -> 50 >= 12 -> 1 θ The last item of the filtered prefixes: "i||iii|" D Duplicate. ¹Ê Is it not equal to the first inupt? "i||iii|" != "i||iii|" -> 0 s Swap the other copy up. "i||iii|" { Sort. "iiii|||" γ Group by consecutive equal items. ["iiii","|||"] €g Map: length. [3, 4] ‚ Pair. [0, [3, 4]] ``` [Answer] # [R](https://www.r-project.org/), 63 bytes using characters exactly as described in challenge (or only **[54 bytes](https://tio.run/##hVBNa8MwDL3vVwh2iLx5YIftMGj2R8YosqN0YYldbAW6X5@6pqXtZUO39/Q@pLRKnPO2p99uHZbgZYwBSYvymJcZ/ealfW6fRH0UjNzEKJ9@mSulNh19KbVKYs6dR6NtGVPHKniEPNM0QaWBEkNjGg1u3N1Ctnm4FMA3oytz0tKBoY@cQyPgEtMPoFEarob@O@733F/V7X9qcDzEklmVY9jdmKFbzoul1iCcYKIsEAP/nWnf7zPPFljO1/AKBzBYn6CAQg9tASyWB6h7v/UI)** using 0,1 to represent small & big trees, and outputting 0,1 to represent FALSE/TRUE axe breaking). ``` function(a,t)list(sum(c<-2+2*(t<"i"))>a,table(t[cumsum(c)<=a])) ``` [Try it online!](https://tio.run/##fY3BasMwEETv/YrFPWQ3VSEx7SFg90dKKGt5nYjKUpDW0IL/3TFOSpNLDnOaeW/SpLHPXy3/1lM3BKsuBmSj5F1WzEOPtnotX8o1alW4guhjLrnxgvpph34ZUFXznmjSJJJri/POFOM17iZjQU9/d/i@MQtA8Az8I9BGyWGl0CThbwPsPSw92GM8naT9J8tHJDTSxSQXyoXDjQib4TrKwJ1KAs9ZIQahh3/b3f3fRWGghHF2ugMBhxbewAHmfvbQvWg6Aw "R – Try It Online") [Answer] # [J](http://jsoftware.com/), 37 34 33 bytes ``` (](-:;+/@#:@])(>:2*+/\)#])' i'i.] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWI1dK2stfUdlK0cYjU17KyMtLT1YzSVYzXVFTLVM/Vi/2tycaUmZ@QrGBoopCmoZ9bUZGZm1qhDxExRxf4DAA "J – Try It Online") *-1 byte thanks to Bubbler* Converts small to 1, big to 2. Now create a filter by doubling and scan summing, and apply filter to find entries less than or equal to the left input. Take just those entries, convert to binary, and sum to get the `<num big>, <num small>` part of the answer. Check if the filtered list equals the unfiltered list to get the "chops down all trees?" part of the answer. [Answer] # [Python 2](https://docs.python.org/2/), ~~103~~ \$\cdots\$ ~~82~~ 80 bytes Saved ~~4~~ ~~6~~ ~~9~~ 11 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! ``` f=lambda s,n:n<sum(6&ord(t)%6for t in s)and f('<'+s[:-1],n)or map(s.count,"<i|") ``` [Try it online!](https://tio.run/##bY5BT4QwEIXv/IoJiXa6jmZZ3T0QevUXeDAhHLpLiY3Qkk5JNOG/IxQPHpzT5L03b77xO354d1qWTvV6uLYamFzpKp4GvNz70GKUd5fOB4hgHbDUroUORSUeuC4fi4acXM1Bj8hPNz@5SHll51wu0XBkUIAZ/A5ibufZ2tUmOB8lQf2qezb0Qs@NpP9zRcq9hclQQae/MZkFheJdkPCfQmaJcf1J5ms0t0SbEMp0sJF0eNgUuQv1sVFX73vctl0bg3VxL2EK9V6kFDfLDw "Python 2 – Try It Online") Inputs a string of trees \$s\$ (as `i`s and `|`s) and an axe durability \$n\$. Outputs a list of `[axe broken, small trees, large trees]` where `axe broken` is truthy if Tom's axe broke (or falsy otherwise) followed by the number of trees cut down. **How** If \$c\$ is either `i`, `|` or `<` then: $$ \text{6&ord(c)%6} = \left\{ \begin{array}{ll} 2 \text{ if c is 'i'}\\ 4 \text{ if c is '|'}\\ 0 \text{ if c is '<'} \end{array} \right. $$ this is summed for all the trees in \$s\$ to calculate its needed durability. If it's too much for Tom's axe then we repeatedly try again without the last tree and set Tom's axe as broken by inserting a `<` into \$s\$, making that count truthy. When Tom's axe us strong enough we return what happened to his axe along with the number of each tree still in \$s\$. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 32 bytes ``` 0:&®s?⑷¦i2⑹|\|4©s⑨®s±™⑸¿⅀0=⑻©s(. ``` [Try it online!](https://tio.run/##AU4Asf9rZWf//zA6JsKucz/ikbfCpmky4pG5fFx8NMKpc@KRqMKuc8Kx4oSi4pG4wr/ihYAwPeKRu8Kpcygu//9pfHxpaWl8CjUw/y1wbv8taXI "Keg – Try It Online") Takes input as trees, durability and outputs big, small and whether or not the axe breaks. Somehow, Keg beat pyth. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) I'm assuming, for now, that the "boolean" part of the output may be given as [a Truthy/Falsey](https://codegolf.meta.stackexchange.com/q/2190/53748) value. ``` Og©2ḤÄ’<a®‘ċⱮ3 ``` A dyadic Link accepting the trees (a list of characters) on the left and the axe durability (an integer) on the right which yields a list of three integers, `[is_broken, small_trees, big_trees]` (Note that non-zero integers are Truthy in Jelly while `0` is Falsey). **[Try it online!](https://tio.run/##AS4A0f9qZWxsef//T2fCqTLhuKTDhOKAmTxhwq7igJjEi@KxrjP///9pfHxpaWl8/zE2 "Jelly – Try It Online")** ### How? ``` Og©2ḤÄ’<a®‘ċⱮ3 - Link: list of characters, T; integer, D e.g. "|i|iii"; 14 O - Ordinals (T) [124,105,124,105,105,105] © - copy this to the register and yield it: g 2 - greatest common divisor with two [2,1,2,1,1,1] Ḥ - double [4,2,4,2,2,2] Ä - cumulative sums [4,6,10,12,14,16] ’ - decrement [3,5,9,11,13,15] < - less than (D)? [1,1,1,1,1,0] a - logical AND with: ® - recall the value from the register [2,1,2,1,1,0] ‘ - increment [3,2,3,2,2,1] Ɱ3 - map across 3 with: (i.e. for right in [1,2,3]) ċ - count occurrences [1,3,2] ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 109 bytes ``` f=lambda l,n,a=0,b=0:f(l[1:],m,a+1-j,b+j)if l and(m:=n-((j:='i|'.index(l[0]))+1)*2)>=0 else[l!=''and m<0,a,b] ``` [Try it online!](https://tio.run/##bctBDoMgEEDRfU9BVzB1bMDGpCGdXsS4gCgpBtBYF23i3Sn7un35f/lurznd7suas6Ngoh0MC5jQkERLUjsROqV7jGgqVU9oqwm8Y4GZNIioKdVCTJq43/nVp2H8lF72AJWCSwNPkmwM77ELZ@K8LCw@JBq0fV5WnzbhRDl378uOrQQ4/XNzzKo9ZoD8Aw "Python 3.8 (pre-release) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 55 bytes ``` \d+ $* (11)+1?(?<-1>(i)|(?<-1>(\|)))*($)?.* $#4 $#3 $#2 ``` [Try it online!](https://tio.run/##K0otycxL/P8/JkWbS0WLS8PQUFPb0F7D3kbX0E4jU7MGyoqp0dTU1NJQ0bTX0@JSUTZRUFE2BmKj//8NzTJrajIzM2sA "Retina 0.8.2 – Try It Online") Takes input as [durability][trees] without a separator and outputs [complete] [big] [small]. Explanation: ``` \d+ $* ``` Convert the durability to unary. ``` (11)+1? ``` Capture half the durability as `$#1`. ``` (?<-1>(i)|(?<-1>(\|)))* ``` Count the trees as they are matched, and decrement the remaining durability appropriately depending on the size of tree. ``` ($)?.* ``` Determine whether the all of the trees were chopped down. ``` $#4 $#3 $#2 ``` Output the desired results. [Answer] # [Desmos](https://www.desmos.com/calculator), 73+31+8+8 = ~~125~~ 120 bytes -5 bytes from finding a new builtin, which cost a few bytes but allowed three functions to be collapsed into one. ``` l(g)=\sum_{m=1}^{t.length}\left\{2*\sum_{n=1}^m t[n]<=d:g[t[m]],0\right\} \left\{d-total(t)*2<0:1\right\} l([1,0]) l([0,1]) ``` (each line is an individual function, line breaks are not used and don't count towards bytes) [Try it online](https://www.desmos.com/calculator/ruyvlyhz56) Desmos is absolutely the wrong choice of language for this problem. Input is taken as a variable `t` holding the trees as an array of 1s and 2s, representing 2s and 4s (as accepted in the comments, Desmos doesn't even support strings anyways) / small and large trees and a variable `d` holding the durability. Output is in the second function (will it break, undefined for no and 1 for yes) and third and fourth functions (short and tall trees chopped respectively. Explanation: ``` l(g)=\sum_{m=1}^{t.length}\left\{2*\sum_{n=1}^m t[n]<=d:g[t[m]],0\right\} ``` Calculates the amount of trees of a certain type chopped. It goes through each tree, checks if it has enough durability to chop it with the inner `sum`, and if so, adds a 1 or a 0 depending on the tree type, based on a lookup array `g` passed to it. ``` \left\{d-total(t)*2<0:1\right\} ``` Simple calculation to check if the durability available is less than what's required. Fun fact: Desmos can't properly output truthy or falsey values! It does support true and false, as you can see if you plug in `\left\{3>2:1,0\right\}` (where 3>2 evaluates to true, causing 1 to be output instead of 0), but you can't actually get then to print. Plug in `3>2` and you don't get any output. Additionally, try to use values we might traditionally think of as truthy or falsey in those same formulas, and you get an error! For this reason, it's possible that this isn't technically a truthy/falsey output based on [this](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey), but that definition allows for the occasional exception, which I think this fits under. I think we can all agree that 1 is truthy and undefined is falsey, so that's what I've gone with here. A looser definition (for example, any positive number is truthy and 0, undefined, and negatives are falsey) would likely allow for this line to be shorter. ``` l([1,0]) ``` Calculate `1` (short) trees chopped with a 1 in position 1. ``` l([0,1]) ``` Calculate `2` (tall) trees chopped with a 1 in position 2. ]
[Question] [ Given a value *x* find the smallest numerical value greater than *y* that is capable of being multiplied and divided by *x* while retaining all original digits. * The new numbers do not lose digits. * The new numbers do not gain digits. For example: > > Input: x = 2, y = 250000 > > > * Original: 285714 > + Division: 142857 > + Multiplication: 571428 > > > This is true because *285714* is greater than *y*; then when divided by *x* results in *142857* and when multiplied by *x* results in *571428*. In both tests all of the original digits from *285714* are present and no extra digits have been added. > > > --- ## The Rules * *X* should be *2* or *3* as anything higher takes too long to calculate. * *Y* is required to be a whole number greater than *zero*. * The shortest code wins. --- ## Test Cases These are my most common test cases as they are the quickest to test for. * *x = 2, y = 250000 = 285714* * *x = 2, y = 290000 = 2589714* * *x = 2, y = 3000000 = 20978514* * *x = 3, y = 31000000 = 31046895* * *x = 3, y = 290000000 = 301046895* --- ## Clarifications * The type of division doesn't matter. If you can get *2.05, 0.25, and 5.20* somehow then feel free. --- Good luck to you all! [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) v2, 15 bytes ``` t<.g,?kA/p.∧A×p ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v8RGL13HPttRv0DvUcdyx8PTC/7/jzbSMbIwNTcwiP0fBQA "Brachylog – Try It Online") Takes input in the form `[x,y]`. ## Explanation ``` t<.g,?kA/p.∧A×p t Tail (extract y from the input) < Brute-force search for a number > y, such that: . it's the output to the user (called "."); g forming it into a list, ,? appending both inputs (to form [.,x,y]), k and removing the last (to form [.,x]) A gives a value called A, such that: / first ÷ second element of {A} p is a permutation of . . ∧ and A× first × second element of {A} p is a permutation of {.} ``` ## Commentary Brachylog's weakness at reusing multiple values multiple times shows up here; this program is almost all plumbing and very little algorithm. As such, it might seem more convenient to simply hardcode the value of *y* (there's a comment on this question hypothesising that 2 is the only possible value). However, there are in fact solutions for *y*=3, meaning that unfortunately, the plumbing has to handle the value of *y* as well. The smallest that I'm aware of is the following: ``` 315789473684210526 315789473684210526 × 3 = 947368421052631578 315789473684210526 ÷ 3 = 105263157894736842 ``` (The technique I used to find this number isn't fully general, so it's possible that there's a smaller solution using some other approach.) You're unlikely to verify that with *this* program, though. Brachylog's `p` is written in a very general way that doesn't have optimisations for special cases (such as the case where both the input and output are already known, meaning that you can do the verification in O(*n* log *n*) via sorting, rather than the O(*n*!) for the brute-force approach that I suspect it's using). As a consequence, it takes a very long time to verify that 105263157894736842 is a permutation of 315789473684210526 (I've been leaving it running for several minutes now with no obvious progress). (EDIT: I checked the Brachylog source for the reason. It turns out that if you use `p` on two known integers, the algorithm used generates all possible permutations of the integer in question until it finds one that's equal to the output integer, as the algorithm is "input → indigits, permute indigits → outdigits, outdigits → output". A more efficient algorithm would be to set up the outdigits/output relationship *first*, so that the backtracking within the permutation could take into account which digits were available.) [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` ḟ§¤=OoDd§¤+d*/ ``` [Try it online!](https://tio.run/##yygtzv7//@GO@YeWH1pi65/vkgJiaKdo6f///9/ov5GpARAAAA "Husk – Try It Online") ### Explanation ``` ḟ§¤=O(Dd)§¤+d*/ -- example inputs: x=2 y=1 ḟ -- find first value greater than y where the following is true (example on 285714) § -- | fork § -- | | fork / -- | | | divide by x: 142857 -- | | and * -- | | | multiply by y: 571428 -- | | then do the following with 142857 and 571428 -- | | | concatenate but first take + -- | | | | digits: [1,4,2,8,5,7] [5,7,1,4,2,8] ¤ d -- | | | : [1,4,2,8,5,7,5,7,1,4,2,8] -- | and d -- | | digits: [2,8,5,7,1,4] D -- | | double: [2,8,5,7,1,4,2,8,5,7,1,4] -- | then do the following with [2,8,5,7,1,4,2,8,5,7,1,4] and [1,4,2,8,5,7,5,7,1,4,2,8] = -- | | are they equal ¤ O -- | | | when sorted: [1,1,2,2,4,4,5,5,7,7,8,8] [1,1,2,2,4,4,5,5,7,7,8,8] -- | : truthy -- : 285714 ``` [Answer] # Haskell, ~~76~~ 74 bytes *Two bytes shaved off thanks to Lynn's comment* ``` import Data.List s=sort.show x#y=[n|n<-[y+1..],all(==s n)[s$n*x,s$n/x]]!!0 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 56 ~~54~~ bytes ``` ->\x,\y{(y+1...{[eqv] map *.comb.Bag,$_,$_*x,$_/x})+y} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf1y6mQiemslqjUttQT0@vOjq1sCxWITexQEFLLzk/N0nPKTFdRyUeiLQqgIR@Ra2mdmXt/@LESoU0DSMdBSNTAyDQtP4PAA "Perl 6 – Try It Online") Interesting alternative, computing n\*xk for k=-1,0,1: ``` ->\x,\y{first {[eqv] map ($_*x***).comb.Bag,^3-1},y^..*} ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 92 bytes ``` import StdEnv $n m=hd[i\\i<-[m..],[_]<-[removeDup[sort[c\\c<-:toString j]\\j<-[i,i/n,i*n]]]] ``` [Try it online!](https://tio.run/##FYyxDoIwFAB3v@INTKag0bgY2HAwcevYNqYpFR/hvRIoJP68td50w@Xc6C0nCt06eiCLnJCmMEeQsbvxtisYqHl3CrXGulRUVUaop8k6ewqbb9dJLblXTmtXl9cYZJyRexiM1kPOUOCBBe7ZZJKMNr8bKOAMp8vxT/q612j7JZX3R2o/bAnd8gM "Clean – Try It Online") Pretty simple. Explanation coming in a while. [Answer] # q, 65 bytes ``` {f:{asc 10 vs x};while[not((f y)~f y*x)&(f y*x)~f"i"$y%x;y+:1];y} ``` Split number on base 10, sort each ascending, and check if equal. If not, increment y and go again [Answer] # JavaScript (ES6), ~~76~~ ~~73~~ 69 bytes *Saved 3 bytes by using `eval()`, as suggested by @ShieruAsakoto* Takes input as `(x)(y)`. ``` x=>y=>eval("for(;(g=x=>r=[...x+''].sort())(y*x)+g(y/x)!=g(y)+r;)++y") ``` [Try it online!](https://tio.run/##ZcpNCoMwFATgfU9h3fheQ@Nv2ojEi5QuglWxBFMSkeT0aXYtOJthhu8td2kHs3y266pfY5hEcKL3oh93qSCdtIEOZhE/Ix6UUkey7EmtNhsggr84JDP43OFZxEZiOiTEpxgGvVqtRqr0DBNUCBUrYhCTPE8qzu5lczqa9s8w3h5RjVCXRfFjcTU33rLwBQ "JavaScript (Node.js) – Try It Online") A recursive version would be [**62 bytes**](https://tio.run/##DcZBDoIwEEDRq@CKGRun0mgkJoMHMS4IQpEQxrTEdE5f@zfvL/2vj0P4fPfTJu8xT5wTd56VO5i5bOAnESVT1y@KEnZABD0mNDOoTXjgIprw8KCmwbvmQbYo60ireJjAIbj2XEKsrK1ce701l/wH), but it's not well suited here because of the high number of required iterations. ### How? The helper function \$g\$ takes an integer as input, converts it to an array of digit characters and sorts this array. *Example:* ``` g(285714) = [ '1', '2', '4', '5', '7', '8' ] ``` To compare the digits of \$y\times x\$ and those of \$y/x\$ against those of \$y\$, we test whether the concatenation of \$g(y\times x)\$ with \$g(y/x)\$ is equal to the concatenation of \$g(y)\$ with itself. When adding two arrays together, each of them is implicitly coerced to a comma-separated string. The last digit of the first array is going to be directly concatenated with the first digit of the second array with no comma between them, which makes this format unambiguous. *Example:* ``` g(123) + g(456) = [ '1', '2', '3' ] + [ '4', '5', '6' ] = '1,2,34,5,6' ``` But: ``` g(1234) + g(56) = [ '1', '2', '3', '4' ] + [ '5', '6' ] = '1,2,3,45,6' ``` ### Commented ``` x => y => // given x and y eval( // evaluate as JS code: "for(;" + // loop: "(g = x =>" + // g = helper function taking x "r =" + // the result will be eventually saved in r "[...x + '']" + // coerce x to a string and split it ".sort() + ''" + // sort the digits and coerce them back to a string ")(y * x) +" + // compute g(y * x) "g(y / x) !=" + // concatenate it with g(y / x) "g(y) + r;" + // loop while it's not equal to g(y) concatenated with ")" + // itself "++y" // increment y after each iteration ) // end of eval(); return y ``` [Answer] # Japt, 24 bytes Pretty naïve solution over a few beers; I'm sure there's a better way. ``` @[X*UX/U]®ì nÃeeXì n}a°V ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=QFtYKlVYL1VdruwgbsNlZVjsIG59YbBW&input=MgoyNTAwMA==) [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes ``` S=sorted x,y=input() while(S(`y`)==S(`y*x`)==S(`y/x`))<1:y+=1 print y ``` [Try it online!](https://tio.run/##NY3LDoIwEEXXzFd0R6sk8hBBYpe4dYEfgMIkEA1txhLp19cS4lnMnORm5mprBjWlrlM9yjAMXSM/igz2sERWjpOeDRfwHcY38oa3thVSrnu3/O3gTVySyu5lAprGyTDr/CfYrtidZqwgMGT9DHDBjq1l4LVDbVh9u9ZEitb0Sfh4geNplOaxRwDPIpYleVGej0V2KuMN8QM "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Erik the Outgolfer (`` uses make\_digits, so `D` was not required) +2 fixing a bug (thanks again to Erik the Outgolfer for pointing out the off-by one issue) ``` ×;÷;⁸Ṣ€E ‘ç1# ``` A full program printing the result (as a dyadic link a list of length 1 is yielded). **[Try it online!](https://tio.run/##y0rNyan8///wdOvD260fNe54uHPRo6Y1rlyPGmYcXm6o/P//f2NDAzD4bwwAA "Jelly – Try It Online")** ### How? ``` ×;÷;⁸Ṣ€E - Link 1, checkValidity: n, x e.g. n=285714, x=2 × - multiply -> n×x 571428 ÷ - divide -> n÷x 142857 ; - concatenate -> [n×x,n÷x] [571428,142857] ⁸ - chain's left argument = n 285714 ; - concatenate -> [n×x,n÷x,n] [571428,142857,285714] Ṣ€ - sort €ach (implicitly make decimals) [[1,2,4,5,7,8],[1,2,4,5,7,8],[1,2,4,5,7,8]] E - all equal? 1 ‘ç1# - Main link: y, x ‘ - increment -> y+1 # - count up from n=y+1 finding the first... 1 - ...1 match of: ç - the last link (1) as a dyad i.e. f(n, x) ``` Note that when the division is not exact the implicit decimal instruction (equivalent to a `D`) applied prior to the sort yields a fractional part e.g.: `1800÷3D` -> `[6,0,0]` while `1801÷3D` -> `[6.0,0.0,0.33333333333337123]` [Answer] # Mathematica, ~~82~~ 74 bytes ``` x=Sort@*IntegerDigits;Do[If[x[i#]==x@Floor[i/#]==x@i,Break@i],{i,#2,∞}]& ``` *-8 bytes thanks to tsh* Function that takes arguments as `[x,y]`. Effectively a brute force search that checks if the sorted list of digits for `y`,`y/x` and `xy` are the same. [Try it online!](https://tio.run/##y00syUjNTSzJTE78/7/CNji/qMRByzOvJDU9tcglMz2zpNiaK83WJT/aMy0aKhwYnamvHKumVhGdqRxra1sB5gJph0wdp6LUxGyHzFid6kwdZSOdRx3zamPV/gcUZeaVOKRFG@kYmRoAQex/AA) [Answer] # APL(NARS), 490 chars, 980 bytes ``` T←{v←⍴⍴⍵⋄v>2:7⋄v=2:6⋄(v=1)∧''≡0↑⍵:4⋄''≡0↑⍵:3⋄v=1:5⋄⍵≢+⍵:8⋄⍵=⌈⍵:2⋄1} D←{x←{⍵≥1e40:,¯1⋄(40⍴10)⊤⍵}⍵⋄{r←(⍵≠0)⍳1⋄k←⍴⍵⋄r>k:,0⋄(r-1)↓⍵}x} r←c f w;k;i;z;v;x;y;t;u;o ⍝ w cxr r←¯1⋄→0×⍳(2≠T c)∨2≠T w⋄→0×⍳(c≤1)∨w<0⋄→0×⍳c>3 r←⌊w÷c⋄→Q×⍳w≤c×r⋄r←r+c Q: u←D r⋄x←1⊃u⋄y←c×x⋄t←c×y⋄o←↑⍴u⋄→0×⍳o>10⋄→A×⍳∼t>9 M: r←10*o⋄⍞←r⋄→Q A: u←D r⋄→M×⍳x≠1⊃u⋄→B×⍳∼(t∊u)∧y∊u⋄z←r×c⋄v←D z⋄→C×⍳(⍳0)≡v∼⍦u B: r←r+1⋄→A C: k←z×c⋄⍞←'x'⋄→B×⍳(⍳0)≢v∼⍦D k ⎕←' '⋄r←z ``` test ``` 2 f¨250000 290000 3000000 xxxx 1000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 10000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 285714 2589714 20978514 3 f¨ 31000000 290000000 xxxxxxxxx 100000000xxxxxxxxxxxxxxxxxxxxxxxxxx 31046895 301046895 ``` I thought the problem as r a convenient number that can vary so one has the 3 numbers r, r\*x, r\*x\*x in the way r begin to a value that r\*x is near y (where x and y are inputs of the problem using same letters as main post). I used the observation that if the first digit of r is d than in r has to appear digits d\*x and d\*x\*x too, for make r (or better r\*x) one solution. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [>©Ð²÷s²*)€{Ë®s# ``` [Try it online.](https://tio.run/##MzBNTDJM/f8/2u7QysMTDm06vL340CYtzUdNa6oPdx9aV6z8/7@xoam5haWJubGZhYmRoQEQcBkDAA) (NOTE: Very inefficient solution, so use inputs close to the result. It works for larger inputs as well locally, but on TIO it'll time out after 60 sec.) **Explanation:** ``` [ # Start an infinite loop > # Increase by 1 (in the first iteration the implicit input is used) © # Store it in the register (without popping) Ð # Triplicate it ²÷ # Divide it by the second input s # Swap so the value is at the top of the stack again ²* # Multiply it by the second input ) # Wrap all the entire stack (all three values) to a list €{ # Sort the digits for each of those lists ®s # Push the value from the register onto the stack again Ë # If all three lists are equal: # # Stop the infinite loop ``` ]
[Question] [ Your goal in this code golf is to take two strings, `language` and `code` *(if the golfed code you wrote for this is multiline, then this variable would be multiline.)*, and one integer, `bytes`. They represent the variables for a programming language, number of bytes it takes, and the code itself. After that, you are going to format it like a code golfer does it. The output variable is a multiline string called `answer`. You can use multiline strings on: * [C++](https://stackoverflow.com/a/1135862/5513988) * [Python](https://stackoverflow.com/a/10660443/5513988) * [Perl](https://stackoverflow.com/a/2876834/5513988) * [JavaScript](https://stackoverflow.com/a/805113/5513988) If you search [Stack Overflow](https://stackoverflow.com), you should be able to find more programming languages that support it. Here is a template of the output markdown. The `code` variable is in a code block, and there is a second-level header. ``` ## {language}, {bytes} bytes {code} ``` Here is what the output would look like when pasted into a Markdown parser. > > ## {language}, {bytes} bytes > > > > ``` > {code} > > ``` > > Variables are assumed to be filled out already as the language you coded your code golf entry in, the number of bytes it takes, and the actual code for it. Here is another example of the output as code, this time with variables filled out: ``` ## JavaScript, 1337 bytes document.getElementById("foo").innerHTML = bar; ``` Here is the version as a blockquote: > > ## JavaScript, 1337 bytes > > > > ``` > document.getElementById("foo").innerHTML = bar; > > ``` > > Bytes can be taken off from your code if you use a way to set the text of a `<p>` element in HTML by the id `result`, like the following JavaScript code: ``` document.getElementById("result").innerHTML = answer; ``` Make sure to also include the `<p id="result"></p>` in the HTML section of [JSFiddle](https://www.jsfiddle.net) for this to work. # Scoring Like all [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") questions, the code that uses the least amount of bytes is the best. [Answer] # Java, 70 bytes ``` String A(String[]b){return"## "+b[0]+", "+b[1]+" bytes\n\n "+b[2];} ``` Assumes `b[0]` is the language name, `b[1]` is the byte count, and `b[2]` is the code. Making it compilable costs 9 bytes, resulting in a 79-byte non-standalone program: ``` class a{String A(String[]b){return"## "+b[0]+", "+b[1]+" bytes\n\n "+b[2];}} ``` The equivalent monolithic program is 103 bytes long: ``` interface a{static void main(String[]A){System.out.print("## "+A[0]+", "+A[1]+" bytes\n\n "+A[2]);}} ``` The monolithic one works with command line arguments, assuming these just like the non-standalone program: * First argument is the language name * Second argument is the byte count * Third argument is the code --- # Java (lambda expression), 56 48 bytes ``` (b)->"## "+b[0]+", "+b[1]+" bytes\n\n "+b[2]; ``` This is a [`java.util.function.Function<String[], String>`](https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html). --- None of these programs/functions handle multiline strings. To do so, simply replace `b[2]` and `A[2]` with `b[2].replace("\n","\n ")` and `A[2].replace("\n","\n ")` - doing so adds 23 bytes. [Answer] # [V](https://github.com/DJMcMayhem/V), 24 bytes Note that there is a trailing space at the end. ~~This program makes the assumption that `{code}` will not be on multiple lines.~~ Op has clarified, "code" may be a multiline string. [This 24 byte](http://v.tryitonline.net/#code=MsOpI8OhICTDoSxKQSBieXRlcwobdkfDrjTDqSA&input=Vmlnb3IKMTkKVGhpcyBpcyBhIHRlc3QgCm11bHRpbGluZSBjb2Rl) version works: ``` 2é#á $á,JA bytes vGî4é ``` Since this contains an unprintable character, here is the readable version: ``` 2é#á $á,JA bytes <esc>vGî4é<space> ``` Where `<esc>` is the literal escape character, e.g. `0x1B`. [Answer] # Python 3.5, ~~40~~ 33 bytes: (*-7 bytes thanks to some clarification from Mego*) ``` lambda*f:'## %s, %s bytes\n\n\t%s'%f ``` An anonymous lambda function that takes inputs as positional arguments in the format `<function name>(String, Number, String)` and outputs a multiline string. [Try It Online! (Ideone)](http://ideone.com/aetSQy) [Answer] ## JavaScript (ES6), 56 bytes ``` (l,b,c)=>`## ${l}, ${b} bytes `+c.replace(/^/gm,` `) ``` Also, for laughs, here is an answer that formats itself for me: ## JavaScript (ES6), 68 bytes ``` f=_=>`## JavaScript (ES6), ${`${f}`.length+3} bytes\n\n f=${f};`; ``` Print the result of `f()`. [Answer] ## C#, ~~40~~ 38 bytes ``` (a,b,c)=>$"## {a}, {b} bytes\n\n\t"+c; ``` C# lambda where inputs and output are strings. --- ## C#, 59 bytes ``` (a,b,c)=>$"## {a}, {b} bytes\n\n\t"+c.Replace("\n","\n\t"); ``` With handling of a multiline answer. --- ## C#, 71 bytes The 38 bytes solution which print itself ``` ()=>$"## C#, 38 bytes\n\n\t"+@"(a,b,c)=>$""## {a}, {b} bytes \t""+c;"; ``` [Try them online](https://dotnetfiddle.net/2EIQv0) [Answer] # Mathematica, 40 bytes ``` Print["## ",#,", ",#2,"bytes ",#3]& ``` Anonymous function. Takes the language, byte count, and program as input and prints the body to STDOUT. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 21 bytes Code: ``` “## ÿ, ÿ¡Ï “,|v4ð×y«, ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCcIyMgw78sIMO_wqHDjwrigJwsfHY0w7DDl3nCqyw&input=MDVBQjFFCjgKQXl5CmxtYW8). [Answer] # Jolf, ~~24~~ 22 bytes ``` "## ¦i, ¦j Ξ/u3 ¦ ``` Not much to explain here. `¦` means interpolated input. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=IiMjIMKmaSwgwqZqIM6eL3UzCgogICAgwqY&input=Sm9sZgoKMjQKCiJzb21lIGZpbGxlciBjb2RlIEkgdGhpbmsi) Output for the input in the link is: ``` ## Jolf, 24 bytes some filler code I think ``` Input is as: ``` name number "code" ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~28~~ 27 bytes *1 byte saved thanks to @NinjaBearMoneky's suggestion* ``` 35tOj', 'j' bytes'10t4Z"j&h ``` [**Try it online!**](http://matl.tryitonline.net/#code=MzV0T2onLCAnaicgYnl0ZXMnMTB0NFoiaiZo&input=TUFUTAoyNwozNXRPaicsICdqJyBieXRlcycxMHQ0WiJqJmg) The code block must be on a single line. ### Explanation ``` 35t % Push 35 (ASCII for '#') twice 0 % Push 0. When converted to char, it will be displayed as a space j % Input string (language name) ', ' % Push this string j % Input string (byte count) ' bytes' % Push this string 10t % Push 10 (ASCII for linefeed) twice 4Z" % Push string containing four spaces j % Input string (code) &h % Concatenate everything into a string. Implicitly display ``` [Answer] ## Common Lisp, 57 bytes ``` (lambda(L b c)(format()"## ~A, ~A bytes~%~% ~A"L b c)) ``` Also, for fun, here below is a snippet of code which prints a header for itself. ## Common Lisp, 146 bytes ``` #1=(PROGN (SETF *PRINT-CIRCLE* T) (LET ((S (FORMAT NIL "~S" '#1#))) (FORMAT NIL "## Common Lisp, ~A bytes~%~% ~A" (LENGTH S) S))) ``` [Answer] ## Ruby, 63 bytes ``` def f(l,b,c) s="\#\# #{l}, #{b} bytes\n\n #{c}";return s;end ``` Try it online: <http://codepad.org/EIn0Gw9M> [Answer] ## [hashmap](https://github.com/lvivtotoro/hashmap/), 29 bytes. ``` "## "i", "h" bytes.\n\n "i ``` (I wrote that post with the program, but I had to escape \n into \\n) Explanation: ``` "## " Push string i", " Push input and string h" bytes.\n\n "i Push input as number and string, then the input. ``` [Answer] # [CJam](https://sourceforge.net/p/cjam/wiki/Home/), ~~26~~ 23 bytes *Thanks to @NinjaBearMonkey for removing 3 bytes!* ``` '#_Sl',Sl" bytes"N_S4*l ``` The code block must be on a single line. [**Try it online!**](http://cjam.tryitonline.net/#code=JyNfU2wnLFNsIiBieXRlcyJOX1M0Kmw&input=Q0phbQoyMwonI19TbCcsU2wiIGJ5dGVzIk5fUzQqbA) ### Explanation ``` '#_S e# Push character "#" twice, then a space l e# Read line from input ',S e# Push a comma, then a space l e# Read line from input " bytes" e# Push this string N_S4* e# Push newline twice, then four spaces l e# Read line from input. Implicitly display ``` [Answer] ## Pyke, 25 bytes ``` "##"Q", "z" bytes"skd4*z+ ``` [Try it here!](http://pyke.catbus.co.uk/?code=%22%23%23%22Q%22%2C+%22z%22+bytes%22skd4%2az%2B&input=pyke%0A3%0Acode&warnings=0) Or ## Pyke, 0 bytes [Try it here!](http://pyke.catbus.co.uk/?code=&warnings=0) - click the copy answer button ;) **EDIT** - It's just a feature of the website, it's cheating (or at least I would consider it so) because it never parses an AST and the web program probably isn't considered part of the language due to it not interacting with the language much (even though it is running the Pyke interpreter) [Answer] # Perl 5, 35 bytes A full program, this takes input as command-line arguments in reverse order. It requires `-M5.01`, which is free. ``` say pop.', '.pop.' bytes '.pop ``` [Answer] ## Emacs Lisp, 97 bytes ``` (lambda(l c)(format"## %s, %s bytes\n\n%s"l(string-bytes c)(replace-regexp-in-string"^"" "c))) ``` Also, since it can sometimes be tough to escape quotes and what not, a usage example that copies the string to the clipboard. (Mark region and use `M-:`) ## Emacs Lisp, 184 bytes ``` (kill-new ((lambda(l c)(format"## %s, %s bytes\n\n%s"l(string-bytes c)(replace-regexp-in-string"^"" "c)))"Emacs Lisp"(buffer-substring-no-properties(region-beginning)(region-end)))) ``` ]
[Question] [ Write a program or function, that given a success probability *p*, a number *n* and a number of trials *m* returns the chance of **at least** *n* successes out of *m* trials. Your answer must be precise to at least 5 digits after the decimal. Test cases: ``` 0.1, 10, 100 -> 0.54871 0.2, 10, 100 -> 0.99767 0.5, 13, 20 -> 0.13159 0.5, 4, 4 -> 0.06250 0.45, 50, 100 -> 0.18273 0.4, 50, 100 -> 0.02710 1, 1, 2 -> 1.00000 1, 2, 1 -> 0.00000 0, 0, 1 -> 1.00000 0, 0, 0 -> 1.00000 0, 1, 1 -> 0.00000 1, 1, 0 -> 0.00000 ``` [Answer] ## Mathematica, 29 bytes ``` BetaRegularized[#3,#,1+#2-#]& ``` Takes input in the order `n,m,p`. Mathematica is so good, it even golfs your code for you: ![enter image description here](https://i.stack.imgur.com/8AlJ4.png) `BetaRegularized` is the [regularised incomplete beta function](https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function). [Answer] # R, ~~32~~ 31 bytes ``` function(p,n,m)pbeta(p,m,1+n-m) ``` *edit - 1 byte switching to beta distribution (along the lines of @Sp3000 Mathematica Answer)* [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 2ṗ’S<¥ÐḟCạ⁵P€S ``` Reads **m**, **n** and **p** (in that order) as command-line arguments. [Try it online!](http://jelly.tryitonline.net/#code=MuG5l-KAmVM8wqXDkOG4n0PhuqHigbVQ4oKsUw&input=&args=NA+NA+MC41) Note that this approach requires **O(2m)** time and memory, so it isn't *quite* efficient enough for the test cases where **m = 100**. On my machine, the test case **(m, n, p) = (20, 13, 0.5)** takes roughly 100 seconds. It requires too much memory for the online interpreter. ### How it works ``` 2ṗ Cartesian product; yield all vectors of {1, 2}^n. ’ Decrement, yielding all vectors of {0, 1}^n. Ðḟ Filter; keep elements for which the link to the left yields False. ¥ Combine the two links to the left into a dyadic chain. S Sum, counting the number of ones. < Compare the count with n. C Complement; map z to 1 - z. ạ⁵ Compute the absolute difference with p. P€ Compute the product of each list. S Compute the sum of all products. ``` [Answer] ## Python, 57 bytes ``` f=lambda p,n,m:m and(1-p)*f(p,n,m-1)+p*f(p,n-1,m-1)or n<1 ``` The recursive formula for binomial coefficients, except the base case `m==0` indicates whether the remaining number of required successes `n` is nonnegative, with [`True/False` for `1/0`](http://meta.codegolf.stackexchange.com/q/9064/20260). Because of its exponential recursion tree, this stalls on large inputs. [Answer] # Haskell, 73 bytes ``` g x=product[1..x];f p n m=sum[g m/g k/g(m-k)*p**k*(1-p)**(m-k)|k<-[n..m]] ``` [Answer] # MATLAB, ~~78~~ 71 bytes Saved 7 bytes thanks to Luis Mendo! ``` @(m,k,p)sum(arrayfun(@(t)prod((1:m)./[1:t 1:m-t])*p^t*(1-p)^(m-t),k:m)) ans(100,10,0.1) 0.5487 ``` The arrayfun function is no fun, but I haven't found a way to get rid of it... [Answer] # Pyth, 26 bytes ``` AQJEsm**.cHd^Jd^-1J-HdrGhH ``` [Try it online!](http://pyth.herokuapp.com/?code=AQJEsm%2a%2a.cHd%5EJd%5E-1J-HdrGhH&input=10%2C100%0A0.1&debug=0) Uses standard cumulative binomial distribution. [Answer] # Pyth, 20 bytes ``` JEKEcsmgsm<O0QKJCGCG ``` [Try it online!](http://pyth.herokuapp.com/?code=JEKEcsmgsm%3CO0QKJ%5ET3%5ET3&input=0.1%0A10%0A100&debug=0) Note: CG is a very large number which the interpreter cannot handle. Therefore, the number of trials have been lowered to ^T3 which is one thousand. Therefore, the link produces an inaccurate result. Uses pure probabilistic approach. [Answer] ## JavaScript (ES7), 82 bytes ``` (p,n,m)=>[...Array(++m)].reduce((r,_,i)=>r+(b=!i||b*m/i)*p**i*(1-p)**--m*(i>=n),0) ``` Saved 1 byte by using `reduce`! Explanation: ``` (p,n,m)=> Parameters [...Array(++m)]. m+1 terms reduce((r,_,i)=>r+ Sum (b=!i||b*m/i)* Binomial coefficient p**i*(1-p)**--m* Probability (i>=n), Ignore first n terms 0) ``` [Answer] # Octave, 26 bytes ``` @(p,n,m)1-binocdf(n-1,m,p) ``` This is an anonymous function. To use it, assign it to a variable. [**Try it here**](http://ideone.com/nZ1KST). [Answer] # [MATL](https://github.com/lmendo/MATL), 23 bytes ``` y2$:Xni5M^1IG-lG7M-^**s ``` Inputs are in the order `m`, `n`, `p`. [**Try it online!**](http://matl.tryitonline.net/#code=eTIkOlhuaTVNXjFJRy1sRzdNLV4qKnM&input=MTAwCjEwCi4xCg) This does a direct computation summing the terms from `n` to `m` of the [binomial probability (mass) function](https://en.wikipedia.org/wiki/Binomial_distribution#Probability_mass_function). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁵C*ạ×⁵*¥×c@ R’çSC ``` Reads **n**, **m** and **p** (in that order) as command-line arguments. [Try it online!](http://jelly.tryitonline.net/#code=4oG1QyrhuqHDl-KBtSrCpcOXY0AKUuKAmcOnU0M&input=&args=MTA+MTAw+MC4x) [Answer] # TI-Basic, 17 bytes Precise to 10 decimals, could be adjusted anywhere from 0-14 decimals with more code. ``` Prompt P,N,M:1-binomcdf(M,P,N-1 ``` [Answer] ## Haskell, 54 bytes ``` (p%n)m|m<1=sum[1|n<1]|d<-m-1=(1-p)*(p%n)d+p*(p%(n-1))d ``` Defines a function `(%)`. Call it like `(%) 0.4 2 3`. [Answer] # Mathematica, 48 bytes ``` Sum[s^k(1-s)^(#3-k)#3~Binomial~k,{k,##2}]/.s->#& ``` Uses the binomial distribution probability formula to calculate the chance of *k* successes for *k* from *n* to *m*. Handles the edge cases by using a symbolic sum where *s* is a symbolic variable for the probability that is later replaced with the actual value *p*. (Since *s*0 = 1 but 00 is indeterminate.) [![Example](https://i.stack.imgur.com/HtFqO.png)](https://i.stack.imgur.com/HtFqO.png) ]
[Question] [ You should write a program or function which receives an integers as input and outputs or returns two integers whose sum is the first one. There is one further requirement: **no number can be part of the output for two different inputs**. ## Details * You should be able to handle inputs for at least the range `-32768 .. 32767` (inclusive). * If your datatype can't handle arbitrary whole numbers, that is fine but your algorithm should work for arbitrary large and small numbers in theory. ## Examples Each block shows a part of a correct or incorrect solution in the format of `input => output`. ``` 1 => 6 -5 2 => -2 4 15 => 20 -5 Incorrect, as `-5` is used in two outputs. ``` ``` -5 => -15 10 0 => 0 0 1 => 5 6 2 => -5 7 Incorrect, as `5 + 6` isn't `1`. ``` ``` -1 => -1 0 0 => 6 -6 2 => 1 1 Can be correct if other outputs doesn't collide. ``` This is code golf so the shortest entry wins. [Answer] # Pyth, 8 bytes ``` _J^Q3+QJ ``` [Demonstration.](https://pyth.herokuapp.com/?code=_J%5EQ3%2BQJ&input=2&debug=1) Equivalent to the Python 2 code: ``` Q=input() J=Q**3 print -J print Q+J ``` So, the output has form `(-n**3, n+n**3)` Some outputs: ``` -5 (125, -130) -4 (64, -68) -3 (27, -30) -2 (8, -10) -1 (1, -2) 0 (0, 0) 1 (-1, 2) 2 (-8, 10) 3 (-27, 30) 4 (-64, 68) 5 (-125, 130) ``` These are distinct because cubes are far enough spaced that adding `n` to `n**3` is not enough to cross the gap to the next cube :`n**3 < n+n**3 < (n+1)**3` for positive `n`, and symmetrically for negative `n`. [Answer] # [Snowman 0.1.0](https://github.com/KeyboardFire/snowman-lang/releases/tag/v0.1.0-alpha), 101 chars ``` }vg0aa@@*45,eQ.:?}0AaG0`NdE`;:?}1;bI%10sB%nM2np`*`%.*#NaBna!*+#@~%@0nG\]:.;:;bI~0-NdEnMtSsP" "sP.tSsP ``` Input on STDIN, space-separated output on STDOUT. This uses the same method as isaacg's answer. Commented version with newlines, for "readability": ``` }vg0aa // get input, take the first char @@*45,eQ. // check if it's a 45 (ASCII for -) (we also discard the 0 here) // this is an if-else : // (if) ?}0AaG // remove first char of input (the negative sign) 0`NdE` // store a -1 in variable e, set active vars to beg ; : // (else) ?}1 // store a 1 in variable e, set active vars to beg ;bI // active variables are now guaranteed to be beg %10sB // parse input as number (from-base with base 10) %nM // multiply by either 1 or -1, as stored in var e earlier 2np`*` // raise to the power of 2 (and discard the 2) %. // now we have the original number in b, its square in d, and // active vars are bdg *#NaBna!*+# // add abs(input number) to the square (without modifying the // input variable, by juggling around permavars) @~%@0nG\] // active vars are now abcfh, and we have (0>n) in c (where n is // the input number) :.;:;bI // if n is negative, swap d (n^2) and g (n^2+n) ~0-NdEnM // multiply d by -1 (d is n^2 if n is positive, n^2+n otherwise) tSsP // print d " "sP // print a space .tSsP // print g ``` Commentary on the very first Snowman solution on PPCG: I think my design goal of making my language as confusing as possible has been achieved. This actually could have been a lot shorter, but I'm an idiot and forgot to implement negative numbers for string -> number parsing. So I had to manually check whether there was a `-` as the first character and remove it if so. [Answer] # Pyth, ~~15~~ 11 bytes *4 bytes thanks to @Jakube* ``` *RQ,hJ.aQ_J ``` [Demonstration.](https://pyth.herokuapp.com/?code=*RQ%2ChJ.aQ_J&input=6&debug=0) This maps as follows: ``` 0 -> 0, 0 1 -> 2, -1 -1 -> -2, 1 2 -> 6, -4 -2 -> -6, 4 ``` And so, on, always involving `n^2` and `n^2 + n`, plus or minus. [Answer] # APL, 15 bytes ``` {(-⍵*3)(⍵+⍵*3)} ``` This creates an unnamed monadic function that returns the pair -n^3 (`-⍵*3`), n+n^3 (`⍵+⍵*3`). You can [try it online](http://tryapl.org/?a=%7B%28-%u2375*3%29%28%u2375+%u2375*3%29%7D%A8%u23735&run). [Answer] # Pyth - 11 10 bytes Just multiplies by 10e10 and -10e10+1 Thanks to @xnor for showing me that I could use `CG` for the number. ``` *CGQ_*tCGQ ``` [Try it online here](http://pyth.herokuapp.com/?code=*CGQ_*tCGQ&input=15&debug=0). [Answer] # [O](https://github.com/phase/o), ~~17 15~~ 9 bytes Uses some new features of O. ``` Q3^.Q+p_p ``` **Older Version** ``` [i#.Z3^*\Z3^)_*]o ``` [Answer] # Python 3, ~~29~~ 27 ## Edit: doesn't meet the requirement in the 2nd "Details" bullet point *Bonus: it works from -99998 to 99998 inclusive* --- ``` lambda n:[99999*n,-99998*n] ``` This creates an anonymous function\*, which you can use by enclosing in brackets and then placing the argument in brackets afterwards like this: ``` (lambda n:[99999*n,-99998*n])(arg) ``` \*Thanks to @vioz- for suggesting this. --- Example input / output: ``` >>> (lambda n:[99999*n,-99998*n])(1) [99999, -99998] >>> (lambda n:[99999*n,-99998*n])(2) [199998, -199996] >>> (lambda n:[99999*n,-99998*n])(0) [0, 0] >>> (lambda n:[99999*n,-99998*n])(-1) [-99999, 99998] >>> (lambda n:[99999*n,-99998*n])(-2) [-199998, 199996] >>> (lambda n:[99999*n,-99998*n])(65536) [6553534464, -6553468928] ``` [Answer] # Haskell, 16 bytes I shamelessly copied @xnor's method. There probably isn't much better than this. ``` f x=(-x^3,x^3+x) ``` ]
[Question] [ In the language of your choice, write a program that is arranged in the shape of a Christmas tree that prints itself in the same shape. What is not allowed: * Printing out the source file * Code that is nothing but statements that get echoed by an interpreter by virtue of them being literals (eg just using a tree-shaped tower of lists in python) [Answer] ## JavaScript The 'star' might be a bit too large for the tree... ``` (function _() {return(' (') +(''+''+''+''+'') +_+ ')()' ;'We w' +'wis'+0+ 'h you a ' +0+'merry Ch' +'ristmas, '+0+ +'we '+0+'wish y' +0+'ou a merry Chr' +'istmas, we w'+0+'i' +0+'sh you '+0+'a merr' +'y Christmas and a h'+0+ +'appy'+0+'new year! Ho ho' +0+' ho! Merry '+0+'Christma' +'s!' })() ``` The zeroes are baubles and look best in the editor: ![Hooray for syntax highlighting!](https://i.stack.imgur.com/AMQrS.png) ![Output in Chrome Developer tools](https://i.stack.imgur.com/C0S4J.png) [Answer] # Ruby You never said we couldn't use network access... :D ``` # s=" open( 'http:/ /pastebin .com/raw.ph p?i=mGzbahp5' ).read";s=eval( s.gsub! /\s/,''); puts( s+'') ``` Outputs itself verbatim. Yes, I could have used a URL shortener, but that would have made it less obvious and amusing :P Also I needed *something* to take up space; otherwise the tree would be tiny. Execute like this: ``` ruby -ropen-uri christmasquine.rb ``` [Answer] # perl ``` #!/usr/bin/perl $_=<<'the source';eval $_; # #*# print "#!/u". "sr/bin". "/perl \n". "\$_=<<'the". " source';eva". "l \$_;\n${_}th". "e source\n";# Mery #Christmas to all !!! ### ### #*# the source ``` [Answer] Here's a tiny one in **GolfScript**: ``` { ".~ "2/~\ +@@2$*}. ~ ``` Note that the code above includes two space characters at the end of the second line from the top; those spaces are essential for correct operation. Also, the code should be saved using Unix-style (`LF`) linefeeds, not Windows-style `CR`+`LF`. --- Here's a slightly bigger (and less whitespace-sensitive) one, including a festive message: ``` { " " MERRY 5*n\+\n CHRISTMAS ".~"+2$*1>} . ~ ``` A mildly interesting feature is that the words `MERRY` and `CHRISTMAS` are not string literals, although they *are* no-ops, and are copied to the output along with the code block surrounding them. ]
[Question] [ ## Background You have again x3 been given the task of calculating the number of landmines in a field. But this time, we have no landmine number, and some landmines have exploded. You must calculate the landmine score given a string of numbers. This is the landscape. You have no landmine number to start with. Instead, the landscape has gaps where possible landmines may have exploded. It may also be the case that the gaps did not have a landmine. For each gap in the landscape, represented by a space, add and multiply the digits left and right of it to gain two candidates for the landmine number. For example, given `1 3`, two candidates would be 1+3 = 4 and 1\*3 = 3. After doing this for all gaps, the number most often given as a result of calculations (highest count) is the landmine number. If there are ties for the highest number count, the landmine number is the largest number in the tie. For each time the result occurs as the calculated landmine number, add the landmine number to the landmine score. Note: The very first and last digits will always have numbers, never gaps. There will also never be two immediately consecutive gaps. ## Your Task * Sample Input: The number landscape, which will only contain numbers and spaces. It is given that if there are no gaps, return 0. This cannot be taken as a list of numbers (eg. taking `02 24` as `['02', '24']`) or seperate inputs but it can be taken as a list of characters/ single digit numbers (eg. taking `02 24` as `['0', '2', ' ', '2', '4' ]`). This is because the landscape is one entity, and could easily have used a different character other than space. * Output: Return the landmine score. **Explained Examples** ``` Input => Output 178 9 11 => 72 The possible landmine numbers are: 8+9 = 17 8*9 = 72 9+1 = 10 9*1 = 9 These all occur once, so we choose the largest number within the tie, which is 72. ``` ``` Input => Output 12 32 21 32 22 => 20 Possible landmine numbers: 2+3 = 5 2*3 = 6 2+2 = 4 2*2 = 4 1+3 = 4 1*3 = 3 2+2 = 4 2*2 = 4 Count: 2 = 1 3 = 2 4 = 5 The highest count is 5, for 4. So 4 is the landmine number. We add 4 5 times to get the landmine score, 20. ``` ``` Input => Output 999910 10 10 10 10 10 10 => 6 Possible landmine numbers: 0+1 = 1, which occurs 6 times. 0*1 = 0, which occurs 6 times. The highest count is 6 and it is tied, so we choose the largest number in the tie, 1. We add this 6 times to get the landmine score, 6. ``` ``` Input => Output 2746 27362 4815 383 6 21 745 => 40 Possible landmine numbers: 6+2 = 8 6*2 = 12 2+4 = 6 2*4 = 8 5+3 = 8 5*3 = 15 3+6 = 9 3*6 = 18 6+2 = 8 6*2 = 12 1+7 = 8 1*7 = 7 Count: 6 = 1 7 = 1 8 = 5 9 = 1 12 = 2 15 = 1 18 = 1 The highest count is 5, for 8. So 8 is the landmine number. Finally, we add 8 5 times to get the landmine score, 40. ``` **Test Cases** ``` Input => Output 178 9 11 => 72 999910 10 10 10 10 10 10 => 6 2746 27362 4815 383 6 21 745 => 40 => 0 19383 => 0 1 1 1 1 1 1 1 1 1 1 => 18 187373 28377373 2837821 2837 => 12 000 001 010 011 100 101 110 111 => 0 10 11 12 13 14 15 16 17 18 19 20 => 16 28478382847738212848392928626188 => 0 28478382847 7382128483 92928626188 => 49 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. ... **Landmine Number Series** * [Previous, LN III](https://codegolf.stackexchange.com/questions/262628/landmine-number-iii) * [All LN Challenges](https://docs.google.com/document/d/1XU7-136yvfoxCWwd-ZV76Jjtcxll-si7vMDhPHBKFlk/edit?usp=sharing) [Answer] # Excel (ms365), 151 bytes [![enter image description here](https://i.stack.imgur.com/KAD3A.png)](https://i.stack.imgur.com/KAD3A.png) Formula in `B1`: ``` =IFERROR(LET(s,TEXTSPLIT(A1,," "),r,DROP(RIGHT(s),-1),l,DROP(LEFT(s),1),v,VSTACK(r*l,r+l),m,MAP(v,LAMBDA(y,SUM(N(v=y)))),@SORTBY(v,m,-1,v,-1)*MAX(m)),) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ü3ʒðk}εþDOsP‚}˜{RÐ.MQÏO ``` Input as a list (with spaces as gaps). [Try it online](https://tio.run/##yy9OTMpM/f//8B7jU5MOb8iuPbf18D4X/@KARw2zak/PqQ46PEHPN/Bwv////9GGOkoKSjpGOsZADGFBRBB8o1gA) or [verify all test cases](https://tio.run/##ZU69SoNBEHyV4eogt7uX270qja3En1IsFCzEwiIQCBKwslVSig9hYyc21yn4EHmRz90IasjdsbPM7N7Mzez84upymC8mCev7FdJkcTL0N/lY9Zfr5ddrf9@fzg7Xd0/Lz@fb4/64d3DUH6bDaDhNpIYGojRKBBYGE6JyEIxtovmhjJ3nEmupYJXKKEZjiAlq7GoZuxy/Nec2Njs3WFNRAZvob2O@Huhyzhk5E7L7ZfKVHL6O4f@TPhp4ZBJQgUegClKQgRp4k9GKmliAOpA3Jo0bW@VKZtsj@JvB/6Gzbw). **Explanation:** ``` ü3 # Push all overlapping triplets of the (implicit) input-list ʒ } # Filter this list of triplets by: ðk # Get the 0-based index of " ", or -1 if it isn't in the triplet # (only 1 is truthy in 05AB1E, so only triplets with spaces in the middle # are kept) ε # Then map over each remaining triplet: þ # Remove the space by only leaving numbers D # Duplicate it O # Sum this pair s # Swap so the pair is at the top again P # Take the product of this pair ‚ # Pair them together }˜ # After the map: flatten it to a single list {R # Sort this list and reverse it, so it's sorted from highest to lowest value Ð # Triplicate this list .M # Pop one list, and push the first most frequent number Q # Check which values are equal to this most frequent max Ï # Only keep the values at those truthy positions O # Sum them together # (after which the result is output implicitly) ``` [Answer] # [Scala](https://www.scala-lang.org/), 234 bytes Golfed version. [Try it online!](https://tio.run/##fVLbbtswDH3PVxDBgEq9CJKdxnIyFRjWPRRYsYdheymKQvWURJt8gcV0CwJ/eyY5hbfFwGgbJA8PSZGyL7TTB1s2dYvgo8OK2jlToK0rVm5RPzszqZ@/BwTuta1gP5m8aAduQT5ja6u1urmrkII6eHWzj5FKeeYbZ5GcwRldRqhQr5XYvW4eAv8yfI@Esp8WN7dmpbcOv2q3NYTT5apuiX17JQBrqJgz1Ro3V4L2tZ2qiA0Oc9oj0/7Wri32LdoYoSF/QAviLlp6oUS0znurW9oVKZj1H8oGd5SDcd70hUtVsJd4As9K/WtZsJV1aFryxJ4SpUrKfphdHzovu@4AAN/MCsqwD6LbtV/Au7bVu4fjRh7pAr5UFkGFZcGrxCZoPL7X3vgQ@Wg9kiEaZSoyCTkIMb38F8@DCA6j95SXZLM5JFk6T2AmxTWkMoUACMhm16dcOAVEHugjEEbPiCKzNEshkWk2GDL0jPqUyzkHzgXwcHwuQjEexwg6jjOeu0dBJCBSEDMIE4k5iAyEBJFDMp5fzjKZyqiyoEQwZJoneSLnyVxI@R8@/EmAvzOGBDoZzOEWWfhTjS42BAtQN9CEu0dXET@9q5otLuDNEf@0xaO7d4FJuymlfa1u0h1@Aw) ``` s=>{val n=s.split(' ');val c=mutable.Map[Int,Int]().withDefaultValue(0);for(i<-1 to n.length-1){val l=n(i-1).last.asDigit;val r=n(i)(0).asDigit;c(l+r)+=1;c(l*r)+=1};if(c.isEmpty)0 else{val m=c.values.max;c.filter(_._2==m).keys.max*m}} ``` Ungolfed version. [Try it online!](https://tio.run/##fVRda9swFH3PrziEQe21E5adxkpZBqPdw2DdHsr2UspQHSXRJn9gydlKyW/PrmrXTeIyJSD73nPOvUe@ts2kkbudzquydrD@jmWlMSpzuixY3jh5b9RoVN7/ohCupS7wOAKthVrCyGKR60LdZGWtAnuBG1frYhVe4HPhMO@Qfm2kQdHk96q2FLfMVka74AQn4QEkK5vCeURXmF3L6pa0zrzgXRCyP9qtr9RSNsb9kKZRQRSOeoVlWSPQeP8OHKSj@5LMqGLl1uFeQ88VDRXrUEQlZsiMtI5Je6VX2g3w9T4@ZGslFz12ALZN7s0YnKIeJKu6XLTZt5Q9SLfHEHh6iNM5@GvZJ/5Revuio5cIWiTT9lNeuYcQUZ9VxqpXTiOXfy89h9rquBt/ypZR4jXw19Zgh11q41SNR2SS1IOfZ9iEmH/ABvP5i/SW/VYP9kCtU/JV6DCekXuu9rz5uctpDANZr2jiPta1fLht5@6OBu97oYeT55R1l9ST7/WLti44qD7mqcAMnI/PDuMzWjzC4H@Mi9PJFHGaTGNMBD9HIhJQgCOdnB9jcRzgM4IPghj8BhCRJmmCWCRpfyGopt@PsVEUIYo4Imo/4iQWeRu0eztD309R8Bg8AZ@AHPEpeAouwGeIh/7FJBWJ8FtKG6cLkcziWSym8ZQL8R88XgjYZ/SEvde7f4qMXnQls3XgMj9eFT17Z4rAjj8XVeMu8KaNf2tce/t4@J1yWbgdh2E3VNvRbvcP) ``` import scala.collection.mutable object Main { def landmineScore(s: String): Int = { val numbers = s.split(' ') val counts = mutable.Map[Int, Int]().withDefaultValue(0) for (i <- 1 until numbers.length) { val l = numbers(i - 1).last.asDigit val r = numbers(i).head.asDigit val sums = l + r val prods = l * r counts(sums) += 1 counts(prods) += 1 } if (counts.isEmpty) 0 else { val maxCount = counts.values.max val maxNums = counts.filter { case (_, v) => v == maxCount }.keys maxNums.max * maxCount } } def main(args: Array[String]): Unit = { val testCases = List( "178 9 11", "999910 10 10 10 10 10 10", "2746 27362 4815 383 6 21 745", " ", "19383", "1 1 1 1 1 1 1 1 1 1", "187373 28377373 2837821 2837", "000 001 010 011 100 101 110 111", "10 11 12 13 14 15 16 17 18 19 20", "28478382847738212848392928626188", "28478382847 7382128483 92928626188" ) testCases.foreach(tc => println(s"Input: $tc => Output: ${landmineScore(tc)}")) } } ``` [Answer] # [Perl 5](https://www.perl.org/), 86 bytes ``` s/. (?=(.))/$h{$_}++for$&+$1,$&*$1/ge;($_)=sort{$h{$b}-$h{$a}||$b-$a}keys%h;$_*=$h{$_} ``` [Try it online!](https://tio.run/##ZY7NTsMwEITvfoo9mCo/JPbaTrxWFHiUiEotRRQSJb1UbV6dsG4kQNS2NCPvaPYbduOxWj7OD4dmUtA@lZlSzTKpEpLnNinTVMnDRXZznu/7UW5yiY9yk0lUr7smkV3aTv14usTMdi6ivMzXq9wWrO@788S1ssvatWNZ0BMEQORF4I0IfFDD/eNxLYx3NRhvawOOsAJLFvgDwbsqJpwWUbTAEEerhfvLAySB5K23YMj6H0NcFvUWMUJrDVojaCbQDIk6wrBGqBWaN0TPaUAL6IC5sAb0vAIwgLmxI8OT82QpimdBNmSDCYZqUyPRWvYnBb8x@Jdz4asfTm/957QUx@Eb "Perl 5 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 82 bytes ``` Lv$`. (.) $.(*_$1*)¶$.(*$1* ^$ 0 N` N^$`(.+)(¶\1)* $#2 L$`^(.+)(¶\1)* $.(*$($#2*__ ``` [Try it online!](https://tio.run/##ZY5BTgMxDEX3PsWXCFJmkEb5SZo4J2BT9QRoJixYsGFRIY7WA/Rig8MCippEej/2t77Pb5/vH6/cH/1z349fri/wyyRu8fPmOE/Xy5CmZHUS5NTltLrul6fJXy8vnGZxD1GOrq//amPGW2fetn1nVTSQ0uww4O5JrLkg1lQisvKApAlWIGo@iLDZX4i7K9SaakLUVH@F2tighBAQAhEsI9DsYWQZR6Zt8wMwggnMsFgWsIIKNkTbSnPVpAPVQBOaWmxRSyxUvTXgz4Ebyzc "Retina – Try It Online") Link includes test cases. Explanation: ``` Lv$`. (.) $.(*_$1*)¶$.(*$1* ``` Get the sums and products of the digits adjacent to spaces. ``` ^$ 0 ``` If there are none then insert a dummy product. ``` N` ``` Sort them. ``` N^$`(.+)(¶\1)* $#2 ``` Sort them in descending order of frequency. ``` L$`^(.+)(¶\1)* $.(*$($#2*__ ``` Multiply the mode by its count. [Answer] # JavaScript, 96 bytes ``` s=>~s.map(m=o=(c,i)=>p=c<'0'?[p*s[++i],p-s[i]].map(n=>m=--o[o[n]||=n/1e4,n]>o[m]?m:n):-c)&m*o[m] ``` ``` f= s=>~s.map(m=o=(c,i)=>p=c<'0'?[p*s[++i],p-s[i]].map(n=>m=--o[o[n]||=n/1e4,n]>o[m]?m:n):-c)&m*o[m] testcases = ` 178 9 11 => 72 999910 10 10 10 10 10 10 => 6 2746 27362 4815 383 6 21 745 => 40 => 0 19383 => 0 1 1 1 1 1 1 1 1 1 1 => 18 187373 28377373 2837821 2837 => 12 000 001 010 011 100 101 110 111 => 0 10 11 12 13 14 15 16 17 18 19 20 => 16 28478382847738212848392928626188 => 0 28478382847 7382128483 92928626188 => 49 3 => 0 `.match(/^.* => .*$/gm).map(r => r.split(' => ')); testcases.forEach(([i, e]) => { console.log(e == f([...i]), f([...i])); }); ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 135 bytes ``` lambda l:-(m:=max(l:=sorted(-w for x,y,z in zip(l,l[1:],l[2:])if y==' 'for w in eval(f'{x}+{z},{x}*{z}'))or [0],key=(c:=l.count)))*c(m) ``` [Try it online!](https://tio.run/##bZBNboMwEIX3OcXsbKek8tgEGyQveo40C5qAimp@BLQJiXJ2aou0oaKAeNbzN2O/aYb@va6kbtoxN6@jTcu3Ywo22dAyMWV6pjYxXd322ZFuTpDXLZyDIbhAUcGlaKgN7A6TvfuLZM@KHAZjCBDPnTyTfaWW5uR6vj1dL7fA6dopYcwBO74PPrLB0ENi7POh/qx6xtj6QEs2pl2XtT3klKDSEAMiYWAMKLF6bMXuQQ6Lb0KjGSlUGIFQMhIQatyC1BKcgaDC7USHfIZP1tzB2JX8Y8PinSDUc0orqSQILdXvQrvDvd7xeSzOOXCOwF0Yjq4l96Gc@nA/g/hzC@@7HoASMASXDyNA5S4BGIO4zwP/DESHSkvtRTlBt9AyFrHQkYhQ6@Uhswp4lMCiJoxXTVtUPSUv1kKfdX0HjW9zJGz8Bg "Python 3.8 (pre-release) – Try It Online") ## Explanation * `for x,y,z in zip(l,l[1:],l[2:])`: Iterate over each triplet of 3 consecutive elements * `if y==' '`: Skip when the middle element is not a space * `for -w in eval(f'{x}+{z},{x}*{z}')`: Append negative of the sum and product of first and third elements to list. These are the negated landmine number candidates. `eval` is used to avoid having to convert to int using `int` * `l:=sorted(...)`: Iterate over the sorted negated landmine candidates. Ensures that bigger magnitudes appear first. Update the list `l` to this list. * `lambda l:-(m:=max(...,key=(c:=l.count)))*c(m)`: Find the max value of the negated landmine number candidates when sorted by number of occurrences, multiply by the number of occurrences, and then negate the result. Because we sorted before, most negative numbers appear first, and `max` will take the first occurring element when their is a tie, which is also the largest when negated. Set `c:=l.count` to save bytes. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 97 bytes ``` x=>~x.replace(k=/. (?=(.))/g,(a,b)=>[-a*b,-a-b].map(v=>x=x<(t=k[v]=k[v]-1||v/99)?x:t))&x%1*99*~-x ``` [Try it online!](https://tio.run/##bU7NDoIwGLv7FN9F2QgbbvxOHDwI4TAQiIpChJAdCK@OyhWapoe2afpQo@qLz70byLu9lUslFy3jWdNP2TWqKNFT2hRQIhHF2K4tpKwcyzglyswtokie0Zfq0ChjLfUVDfKZjtkqhE3TaAuBE30ZMD7pIzOFMGeil6ho333blLRpa1QhgwUhCGDMwDg6bEIODgfOVuW7FfEDO8OGu2UeuD7wwPE5uCHzwAkd8P/7gevtH9h1/@byBQ "JavaScript (Node.js) – Try It Online") -1 from Arnauld [Answer] # R, 225 bytes ``` s=strsplit(x, '')[[1]];i=s==' ';s=as.double(s);if(any(i)){l=as.data.frame(table(sapply(X=which(i),FUN=function(X)c(s[X-1]+s[X+1],s[X-1]*s[X+1]))),stringsAsFactors=F);y=max(l[,2]);z=max(as.double(l[(l[,2]==y),1]));z*y;}else{0} ``` [Try it online!](https://tio.run/##dVDLbsIwELzzFateYkNaee0QO0p96IVjb5WQoqhyaWgjmYdwUAmIb6cOoVAlrW15vd6Zfczm9FFUr3bh4PEe5tvlrCpXS7KjcDg57aqNW9uyIrsQgoBmGeZ5WmqndQBB6rRxD@@r7ZstiKNpOSdmWZOS0oM9R0xlHuYbsyhIZc4Ys17bmkz112c5@/TAcPLyrK81p3RGXDa9x3zkzQjzsPWGrUcpDX0/5fLDPbmJmVWrjdMTmtZ6YXbEZiHPabo/O7e2bNZGtK5p2ORI98M6PRbWFQd2PB0HxlpyEYDcoVSQAOIdBa1B8gH4Fd7CHAQHjuebtyDOOqDEL2TQOy087qC5jGLgUsQcIoVjEEpA3JSQ0bhlRN0C7Xf3FxNP/ScEvd0CUXWRSgopgCshrw/lm2nshdLVhDEGjCEwPyRDn5o1w3rbDP2jZK@jJuZzAQrACPzcGANK3xBg4iW91OqJpSKphGqM9Ab9Q4mEJ1zFPEal/i72iwU3GvR4UUIHp28 "R – Try It Online") Readable version: ``` get_lms <- function(x) { chars = strsplit(x, '')[[1]] idx = chars==' ' nums = as.double(chars) if(any(idx)){ lm_cts = as.data.frame( table( sapply(X = which(idx), FUN = function(X) c(nums[X-1] + nums[X+1], nums[X-1] * nums[X+1])) ), stringsAsFactors = F); hi_cnt = max(lm_cts[,2]); hi_num = max(as.double(lm_cts[(lm_cts[,2]==hi_cnt),1])); hi_num*hi_cnt } else { 0 } } all(get_lms("178 9 11") == 72 ,get_lms("12 32 21 32 22") == 20 ,get_lms("999910 10 10 10 10 10 10") == 6 ,get_lms("2746 27362 4815 383 6 21 745") == 40 ,get_lms("") == 0 ,get_lms("19383") == 0 ,get_lms("1 1 1 1 1 1 1 1 1 1") == 18 ,get_lms("187373 28377373 2837821 2837") == 12 ,get_lms("000 001 010 011 100 101 110 111") == 0 ,get_lms("10 11 12 13 14 15 16 17 18 19 20") == 16 ,get_lms("28478382847738212848392928626188") == 0 ,get_lms("28478382847 7382128483 92928626188") == 49) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` FE⌕Aθ ✂θ⊖ι⁺²ι⊞⊞OυΣιΠι≔⌈Eυ№υιηI∨⌈×Φυ⁼№υιηη⁰ ``` [Try it online!](https://tio.run/##TY7bCsIwDIbvfYrgVYQJ7qAbeCVT78SBvkDpqit0q/Ygvn1NvBALCUn6/fkjB@GkFSalm3WAJ/HAo576nTH4zGAO80UGF6Ol4navpFOjmoLqUdNHZ6LHIgO9oAdd9ANyOj@UE8E6jKSNI6HMOttHGbjZznbe6/tEbm89EsCuxLY2ToEL3pfBQGDnNI1a4QOe3Y@/6lF5utME9TU5PKMwHv/0rOagtKJl25SKutpAUZebAqomX0PZlECDHOpqPUvLl/kA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FE⌕Aθ ✂θ⊖ι⁺²ι ``` Loop over all of the slices of length `3` centred on spaces. ``` ⊞⊞OυΣιΠι ``` Push the sum and product of that slice to the predefined empty list. Note that sum and product of a string splits the string on non-digit characters, casts the pieces to number and then takes the sum or product of the resulting list, although for single digits this is equivalent to the digital sum or product. ``` ≔⌈Eυ№υιη ``` Get the highest frequency of any of the values. ``` I∨⌈×Φυ⁼№υιηη⁰ ``` Multiply by the highest value with that frequency, or output `0` if there were no spaces in the input. [Answer] # [Husk](https://github.com/barbuz/Husk), 17 bytes ``` Σ►LgOΣẊ~§e+*→←†iw ``` [Try it online!](https://tio.run/##ZY49TkNBDIT7PcUoFT/Njnez9hZwAIREwRkiQAhRRBEdAooUVIiCGikFN0iR8h0gd2AvsvhRQKTYlj7bGmt8vZjfdgzru/uzCU5OMbmcHczby/PhsO7bVfvYnF9dbFffm9fH4Wt2fNSW72351p4@bx5671RDBRmqByP2KojmAtFUBNk4RbIEXxCapyGw@hyIvQw0TZoglvSvMT8bGWKMiJGI7hHp8jh6OUdP/@YXoIAJzHBbFlBBAyvEv7KslmyEOuiNpSpVrEih2a4A/wrsSH4A "Husk – Try It Online") ## Explanation ``` Σ►LgOΣẊ~§e+*→←†iw w Split input on spaces. †i Convert each character to integer. Ẋ For each adjacent pair of numbers: ~ →← take the last digit from the first and the first digit from the second §e+* and build a list with the sum and product of those digits. Σ Concatenate all the lists obtained. O Sort the values smallest to largest g Group equal values together ►L Take the longest group (later groups chosen in case of equal length) Σ Sum all values from this group together ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes I feel like the last seven bytes may be able to be six somehow ``` ḲṚ+ż×ɗḢɗƝFfⱮÆṃ$ṀS ``` A monadic Link that accepts a list of integers (the digits) and space characters (the gaps) and yields an integer (the landmine score). **[Try it online!](https://tio.run/##ZY6xSgQxEIb7PMVf2IhN/iSXmRRa2lgKgg@ghdwL2C0K3iMsiNdYq6Ao3KKVi8I9RvZF1lkLPbhk4JsJX/jn4mw@vxzHunqp3e3e10ffrtu6ul@338vD8@H5qb@p3fVO7Zrjsb6/fr6ZeDJcPVgd9YvaPQ7NHfYPMDRLG3ZPx5GiKCBdsUOPrXJBUkaQmAOScoaoEfZASJo5x2KzI7auo0qUiKBR/hq1bxOd9x7eE94yPE33U5ZxyrRtfgEGMIIJFssMCqhgQbCtNIlGnSAGWqOxhBI0h0zVTQH/BjaUHw "Jelly – Try It Online")** Note: Jelly cannot accept a mixed list of integers and characters when running as a *full program* as it interprets `' '` as a string (e.g. an argument of `[1, ' ', 2]` would give the Main Link `[1, [' '], 2]`). ### How? ``` ḲṚ+ż×ɗḢɗƝFfⱮÆṃ$ṀS - Link: list of integers [0-9] & (single) space characters, Field Ḳ - split {Field} at space characters Ɲ - for each neighbouring pair (LeftInts, RightInts): ɗ - last three links as a dyad: Ṛ - reverse {LeftInts} ɗ - last three links as a dyad: + - {ReversedLeftInts} add {RightInts} × - {ReversedLeftInts} multiply {RightInts} ż - {Added} zip {Multiplied} Ḣ - head F - flatten -> PossibleLandmineNumbers $ - last two links as a monad: Æṃ - mode -> MostCommonValues Ɱ - for V in {MostCommonValues}: f - {PossibleLandmineNumbers} filter keep {V} Ṁ - maximum S - sum ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 128 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 16 bytes ``` ⌈zƛ÷h$t"⌊₍∑Π;fsṘĠÞG ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+cz0iLCIiLCLijIh6xpvDt2gkdFwi4oyK4oKN4oiRzqA7ZnPhuZjEoMOeRyIsIiIsIlwiMTc4IDkgMTFcIiA9PiA3MlxuXCI5OTk5MTAgMTAgMTAgMTAgMTAgMTAgMTBcIiA9PiA2XG5cIjI3NDYgMjczNjIgNDgxNSAzODMgNiAyMSA3NDVcIiA9PiA0MFxuXCJcIiA9PiAwXG5cIjE5MzgzXCIgPT4gMFxuXCIxIDEgMSAxIDEgMSAxIDEgMSAxXCIgPT4gMThcblwiMTg3MzczIDI4Mzc3MzczIDI4Mzc4MjEgMjgzN1wiID0+IDEyXG5cIjAwMCAwMDEgMDEwIDAxMSAxMDAgMTAxIDExMCAxMTFcIiA9PiAwXG5cIjEwIDExIDEyIDEzIDE0IDE1IDE2IDE3IDE4IDE5IDIwXCIgPT4gMTZcblwiMjg0NzgzODI4NDc3MzgyMTI4NDgzOTI5Mjg2MjYxODhcIiA9PiAwXG5cIjI4NDc4MzgyODQ3IDczODIxMjg0ODMgOTI5Mjg2MjYxODhcIiA9PiA0OSJd) Takes input as a string. Ports Husk. ## Explained ``` ⌈zƛ÷h$t"⌊₍∑Π;fsṘĠÞG­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁣⁡​‎‏​⁢⁠⁡‌­ ⌈z # ‎⁡Split the input on spaces and get all overlapping pairs ƛ ; # ‎⁢To each pair: ÷h$t" # ‎⁣ [pair[0][-1], pair[-1][0]] ⌊ # ‎⁤ Each converted to int ₍∑Π # ‎⁢⁡ [sum, product] fs # ‎⁢⁢Flatten and sort the result ṘĠ # ‎⁢⁣Reverse and group by consecutive value ÞG # ‎⁢⁤Get the longest by length # ‎⁣⁡The s flag sums the resulting list 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ]
[Question] [ Let's solve the [same task as in this challenge](https://codegolf.stackexchange.com/q/204426/25315) but faster! **Input**: a non-empty string containing letters a-z **Output**: the length of a longest (contiguous) substring in which all letters are different **Time and space complexity**: O(n). The number of letters in the alphabet is 26, or O(1). Make sure you understand how your language works - e.g. if it can't "extract a substring" in O(1) time, you probably can't use substrings in your implementation - use indices instead. The solution doesn't need to say at which position it found the longest substring, and whether there is more than one. So, for example, if it found a substring of length 26, it can stop searching (this observation will not help you write your implementation). ### Test Cases ``` abcdefgabc -> 7 aaaaaa -> 1 abecdeababcabaa -> 5 abadac -> 3 abababab -> 2 helloworld -> 5 longest -> 7 nonrepeating -> 7 substring -> 8 herring -> 4 abracadabra -> 4 codegolf -> 6 abczyoxpicdabcde -> 10 ``` (I took these directly from the other challenge) [Answer] # JavaScript (ES6), 62 bytes Expects an array of characters. ``` a=>a.map((c,i)=>a[m=(d=i-a[c],d<++j?j=d:j)<m?m:j,c]=i,j=m=0)|m ``` [Try it online!](https://tio.run/##dZLZbsMgEEXf@xVRnozikHSPotB8iOWH8YApiMXCTjf1313qRG2c4EFihHTu1XBBwxu0GFTTLZ3noq9ZD@wFqIUmyzBXJB4KyzLO1BIKLHO@Wyz0XjO@1WRn93arcyyZyjWzbE2@bY/etd4IarzM6qyglM6hQi5qGdu8JGR2rNVq9nyTgoc6A0/wbRKuRLSGKlrH7aSK8GMaBg547Xw/AQ9rhEf4LgW/CmP8uw@Gjy@YHMN4J0XbjeeYSsN5F0QjoFNO/imm4PZQtV04J4/wJj1zuEQH@CGdRgCM6cX2L5iCMX4k6U19Gd1T2hm/Pv1Ho5AP32QQ/T73uv8B "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array, reused as an object to keep // track of the last position of each character a.map((c, i) => // for each character c at position i in a[]: a[ // m = ( // m is the maximum length of a valid substring d = i - a[c], // let d be the difference between the current // position and the last position of c (NaN if // c has not been seen so far) d < ++j ? // increment j; if d is less than j: j = d // we have to force j to d : // else: j // keep the incremented value of j ) < m ? // if j is less than m: m // leave m unchanged : // else: j, // update m to j c // update a[c] ... ] = i, // ... to i j = m = 0 // start with j = m = 0 ) | m // end of map(); return m ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~10~~ 6 bytes ``` UÞx↔tL ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBVCIsIiIsIlXDnnjihpR0TCIsIiIsImFiY2RlZmdhYmNcbmFhYWFhYVxuYWJlY2RlYWJhYmNhYmFhXG5hYmFkYWNcbmFiYWJhYmFiXG5oZWxsb3dvcmxkXG5sb25nZXN0XG5ub25yZXBlYXRpbmdcbnN1YnN0cmluZ1xuaGVycmluZ1xuYWJyYWNhZGFicmFcbmNvZGVnb2xmIl0=) Shorter than the Vyxal answer in the original challenge. \$O(nk!)\$ where \$n\$ is the length of the string and \$k\$ is the number of unique characters so it times out when \$k\geq 10\$. ``` U # uniquify Þx # combinations without replacement ↔ # keep only those that are in input t # tail L # length ``` [Answer] # [Rust](https://www.rust-lang.org), ~~129~~ 127 bytes ``` |s:&[u8]|{let(mut a,mut d,mut e)=(-1,[-1;128],0);for(i,j)in(0..).zip(s){let f=*j as usize;a=a.max(d[f]);d[f]=i;e=e.max(i-a)}e}; ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ddJLboMwEABQqcucwmVR2RVQyBfFoj1IlIUBmzoiBtlGTUNQD9JNFu0Fepv2NHVggZESkGYk63k8sufzS9ZKn3-YAHvCBUSgmRRUAxZ_15p50e_HSa0fNnW0PTVmHe5rDYh7iVkXKYqhF7obL8ThNNq6AcKslJC7O2SqBb6P_COvoEJNX_VxB4gCteJHiklM_D05wGzDtghfYswxjWm3yD2CWtrivo2_O1xJLnQh7qGzAs36pXVcBhOHJGlGWW6SgxAGT0_AewaryYBDG3ffBfYutNxiVJSaqiQxVU2wNiysDbPRBpKRdHAzy03HrvsHOb3RwistivKtlEV2_XT7DopS5FTpAa5uQFEKSStKNBf5dR1ZWtWJ0nJEI4vOR93KMZzfgCSRJDV3ZdJ1vLRwWmY0Lws2yKX9sMF4DI7v5aHiadZNhPXGwaTtZ-h87vM_) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes ``` ≔⦃⦄θ≔⁰η≔⁰ζFS«→≔⌊⟦⊕ζ⁻ⅈ∨§θι⁰⟧ζ§≔θιⅈ¿›ζη≔ζη»Iη ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VU-xasNADJ3jrxCZdHCBjKWZQofiITS0SyFkOJ9l-yA-J3dyKA75ki4ZWtqt39Mv6G9UwTe0i9DTe9J7ev20jQm2M7vL5b3nanbz_bOM0dUeT2cNB7XIEpxraP6hQVDVBcDc73t-4uB8jUrBKZusuiPh7aOrGxbRJO2snHdt3-Im9zZQS56pxEFpEKKP-IzSPgRccu5LesGDBieTuVJbNbqlQ38FGmTtSrkK8D6QYQo4XKMqSLbDGPycrSUh452JjEIv3mJhY3r6YzOdHXfT7ZcpyJZkClNYKWZkfwE) Link is to verbose version of code. Explanation: ``` ≔⦃⦄θ≔⁰η≔⁰ζ ``` Start with an empty dictionary of previous indices, and zero best and current run length. ``` FS« ``` Loop over the input string. ``` → ``` Increment the canvas X coordinate. This keeps track of the current index without using another variable. ``` ≔⌊⟦⊕ζ⁻ⅈ∨§θι⁰⟧ζ ``` Try to increment the current run length, but reduce it to the difference of the current index with the previous index of the current character (or 0 if the character has not been seen previously). ``` §≔θιⅈ ``` Update the last seen index of the current character. ``` ¿›ζη≔ζη ``` Update the best run length. (`≔⌈⟦ηζ⟧η` also works for the same byte count.) ``` »Iη ``` Output the final best run length. [Answer] # [Python](https://www.python.org), 52 bytes ``` lambda A,b="":max(len(b:=a+b.split(a)[0])for a in A) ``` Storing b back-to-front saves a byte. [Attempt This Online!](https://ato.pxeger.com/run?1=NU9BTsMwELznFVZOsUhRgAJVpCBVvfYHwGEd26kl12s5rtryFS6VEHyGF_Q3rJ3glbwzszvr9eePP8cdusuX7t6-D1EvVtelhb2QwNa16Mqy3cOpsspVou3gRtyO3ppYAX9t3rnGwIAZx9Z89m6StE0SevI0vC2YqZF1bDs7S7Z4YSUvWBKNixUS9iEhXRle4zzqcv0F0UulB0rJ81xAPgnfFSAUFUFQka4sPpIIEnLzQ8I5ErsvdspaPGKwcuq06AY1xmmuQxeUVxCNGyZlPIgxhpmuyB3-yZIGB-jpHUqT0KNUA1qd2BOV-48znrzpZd4_r9tMf_oD) ### Original [Python](https://www.python.org), 53 bytes ``` lambda A,b="":max(len(b:=b.split(a)[-1]+a)for a in A) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NU9BTsMwELznFVZOsUhQC7RUkYJUce0PgMM6tlNLrtdyXNHyFS6VEHyGF_Q3rJ3glbwzszvr9eePP8c9usuX7l6_j1E3m-vKwkFIYNtadGXZHuBUWeUq0XbidvTWxAr4S7N8uwGuMTBgxrEtn83PSdolCT2ZFrwtmKmRdWw3m0vWPLGSFyyJxsUKCfuQkK4Mr3Eedbn-guil0gOl5HksIJ-ElwUIRUUQVKQriysSQUJuvk84R2J3xV5Zi-8YrJw6LbpBjXGa69AF5RVE44ZJGY9ijGGmG3KHf_JAgwP09A6lSehRqgGtTmxN5f7jjCdvepn3z-supj_9AQ) I'm not sure there are many methods that are not O(n). This one is ### O(n) because Main loop is over the input string (~> n iterations). Body takes linear time in the length of b which never exceeds the (fixed) size of the alphabet (~> O(1)). Taken together that gives linear time (in n); taking the max does not change this. [Answer] # Excel (ms365), 149 bytes [![enter image description here](https://i.stack.imgur.com/pRlO6.png)](https://i.stack.imgur.com/pRlO6.png) Formula in `B1`: ``` =LET(x,SEQUENCE(LEN(A1)),MAX(MAP(REDUCE(0,x,LAMBDA(y,z,VSTACK(y,MID(A1,z,x)))),LAMBDA(q,(LEN(q)=COUNTA(UNIQUE(MID(q,SEQUENCE(LEN(q)),1))))*LEN(q))))) ``` --- Thought I'd also chuck in a Python solution though I'm sure someone more proficient with Python will post something much smoother: ``` from itertools import combinations s = 'abcdefgabc' print(max([(len(set(z))==len(z))*len(z)for z in[s[x:y]for x,y in combinations(range(len(s)+1),r=2)]])) ``` Or, with regular expressions: ``` import regex as r s = 'abczyoxpicdabcde' print(max([len(i[0])for i in r.findall(r'((.)((?!\2)(.)(?<!\2.*\4.*\4))*)',s,overlapped=1)])) ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 10 bytes ``` /@~0""]@,;:$/`%_$$ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY4xDsIwDEV3H6MqG6iMCJZeBIGduGmlKKmSVAUGds7A0gWxcxtug5tiS372_5L1n2_XEVmO0_QaUrPZfar6vi2KY70-7MvqvDqV5WL8_en7QFKaGyMAzAVILBKSSDLmGzWqGbmhZWv96IPVYL0zHBM47wL3jKlzBuJAMYV5azlkIgVU8kQAyms23jYiqtvVX_pO6ZxhSfQD) Time complexity: \$\mathcal O(nr)\$, where \$r\$ is the result. ``` / Right fold @ each line of input ~ 0 "" with a starting value of (0, "") (ch, accumulator) => ( ] max @ accumulator.first , length of ; s := : join $ ch / fold `% split _ accumulator.second $ by ch $ first , s) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` e.MZml=+eckd ``` [Try it online!](https://tio.run/##K6gsyfj/P1XPNyo3x1Y7NTk75f9/pcSk5JTUtHQgpQQA "Pyth – Try It Online") Port of [@loopy walt](https://codegolf.stackexchange.com/a/257026/73054)'s answer. Could replace `.MZ` with `S` but that would *technically* make it \$O(n\log(n))\$. ### Explanation ``` e.MZml=+eckddQ # implicitly add dQ to the end of the program # implicitly assign Q = eval(input()) m Q # map the letters of Q to lambda d =+eckdd # k = k.split(d)[-1] + d l # length(k) e.MZ # get the maximum ``` [Answer] # [Haskell](https://www.haskell.org/), 146 bytes ``` import Data.Array f=snd.foldl(\(l,m)(i,c)-> (l//[(b,max(l!b)(l!c))|b<-['a'..'z']]//[(c,i)], max m(i-l!c)))(accumArray(+)0('a','z')[],0).zip[1..] ``` [Try it online!](https://tio.run/##Hc3RDoIgGIbhc6@CXBv/vxDtPNvaugviAFGKBeLQtnLdO5En39Hz7nuo@Tk4l5L1U4gLuapF8UuM6lOYdh57boLrHdzAMY9gmcbqXBBwdS2gY169we06zKMRv92pElRRzulKpfwTzSxKVpAMiQdbbQ5Baf3y2wscsIHcsJygkKxBvtpJHDmXySs7tlO047I3pQ79cA/OlOkH "Haskell – Try It Online") ]
[Question] [ You want to create a square chessboard. Adjacent tiles must alternate black and white like a standard chessboard, and the bottom left corner can be either black or white. Your program will take in two positive integers, the number of black and the number of white tiles. These will always be less than 1024. You don't have to use all the tiles. Output the maximum side length of a chessboard pattern that can be constructed using the given amount of tiles. Test Cases: ``` 12, 15 -> 5 8, 8 -> 4 4, 0 -> 1 ``` [Answer] # JavaScript (ES7), 30 bytes ``` b=>w=>((b<w?b:w)*2|b!=w)**.5|0 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/J1q7c1k5DI8mm3D7JqlxTy6gmSdEWSGvpmdYY/E/OzyvOz0nVy8lP10jTMDTS1DA01dTkQhW20AQidEETTQ0DTc3/AA "JavaScript (Node.js) – Try It Online") Given the number of black squares \$b\$ and the number of white squares \$w\$, this computes: $$s=\left\lfloor\sqrt{2\times\min(b,w)+k}\right\rfloor$$ with: $$k=\begin{cases} 0&\text{if }b=w\\ 1&\text{if }b\neq w \end{cases}$$ For even sizes \$s\$, we need \$s^2/2\$ squares of each kind (e.g. for \$s=8\$: \$32\$ black squares and \$32\$ white squares). For odd sizes \$s\$, we need \$\lfloor s^2/2\rfloor\$ squares of one kind and \$\lceil s^2/2\rceil\$ squares of the other kind (e.g. for \$s=5\$: \$12\$ black squares and \$13\$ white squares, or the other way around). The parameter \$k\$ is set to \$1\$ if \$max(b,w)\geq min(b,w)+1\$, which represents this extra square on one side. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` «Ḥ+nƽ ``` [Try it online!](https://tio.run/##y0rNyan8///Q6oc7lmjnHW47tPf///8m/80A "Jelly – Try It Online") A dyadic link that returns the maximum board size. [Test suite for all permutations of numbers to 20](https://tio.run/##ASsA1P9qZWxsef//wqvhuKQrbsOGwr3/w6cvCjIw4bmXMsOH4oKsczIwR///NP82) ### Explanation ``` « | Minimum Ḥ | Doubled +n | Plus 1 if inputs not equal ƽ | Integer square root ``` [Arnauld’s answer](https://codegolf.stackexchange.com/a/183429/42248) has a good explanation for *why* this works; please consider upvoting him too! [Answer] # [Haskell](https://www.haskell.org/), 35 bytes ``` x#y=floor$sqrt$min(x+y)$1+2*min x y ``` [Try it online!](https://tio.run/##ZYtBDsIgFET3PcWEslAbG9u1PYVLNaZRTBsp2A9EOD3CwkTr2/zMvD9Dbx5Cyhh9Gbq71Jq4mcnyaVQrX4U1b6p2kwI8Qpz6UXVGzE6oq7iA46YLJLPf4tjUdbs7p0jCOlIfCfz9Z8LvJrPcZZ7OHiylzgz6lY5HibC0DKz4jifF4hs "Haskell – Try It Online") ## Explanation This answer calculates the following formula: $$\left\lfloor\sqrt{\min(a+b,2\min(a,b)+1)}\right\rfloor$$ Why does this formula work? Well lets start by noting the following: *Every square of even side length can be tiled by \$2\times 1\$ tiles.* and *Every square of odd length can be tiled, spare a single \$1\times 1\$ square, by \$2\times 1\$ tiles.* Now we note that if we put these \$2\times 1\$ tiles on a chessboard each would lay on top of one black square and on white square. So if we make an even chessboard every tile needs to have a pair of the other color, and if we make an odd chessboard every tile but one needs a pair of the other color. This tells us that the answer is never more than \$\left\lfloor\sqrt{2\min(a,b)+1}\right\rfloor\$. \$2\min(a,b)\$ is the maximum number of pairs we can make and the \$+1\$ is for the last square that doesnt' need a pair. The problem with this is that if \$a=b\$ we will not have the extra square for the odd case. So we add another condition: Our result cannot be more than \$\left\lfloor\sqrt{a+b}\right\rfloor\$. That is we can't make a square which has more tiles than we have available. So we just take the lesser of the two options. $$\left\lfloor\sqrt{\min(a+b,2\min(a,b)+1)}\right\rfloor$$ We can notice that this is the same as [Arnauld's formulation](https://codegolf.stackexchange.com/a/183429/56656) since if \$a=b\$ then \$2\min(a,b)\$ is just \$a+b\$. [Answer] # [Ruby](https://www.ruby-lang.org/), 36 bytes ``` ->x,y{'%i'%[x+y,x-~x,y-~y].min**0.5} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165Cp7JaXTVTXTW6QrtSp0K3DiigW1cZq5ebmaelZaBnWvu/oLSkWCEt2kLHIpYLyjY00jE0hfNMdAxi/wMA "Ruby – Try It Online") `x-~x` is a golfed version of `2*x+1`; we're subtracting x's twos-complement negation from itself. After that I'm just using [this answer](https://codegolf.stackexchange.com/a/183471/6828)'s formula, but collapsing the two nested `min`s into one, then using string formatting to truncate to an integer. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes ``` O#`\d+ \d+ $* (1*),(1?\1)1* $1$2 ^(^1|11\1)*1* $#1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3185ISZFmwuEVbS4NAy1NHU0DO1jDDUNtbhUDFWMuOI04gxrDA2BIlogIWXD//8NjXQMTbksdCy4THQMAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` O#`\d+ ``` Sort the numbers in ascending order. Let's call them `l` and `h`. ``` \d+ $* ``` Convert to unary. ``` (1*),(1?\1)1* $1$2 ``` Compute `l + max(h, l + 1)`. This is the equivalent to `2 * min(b, w) + (b != w)`. See @Arnauld's answer for why this works. ``` ^(^1|11\1)*1* $#1 ``` Find the highest integer square root. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ë≠+ß·tï ``` [Try it online](https://tio.run/##yy9OTMpM/f//cPejzgXah@cf2l5yeP3//9GGRjqGprEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8PdjzoXaB@ef2h7yeH1/3X@R0cbGukYmsbqRFvoWABJEx2D2FgA). **Exlanation:** Uses a trivial derivative of the formula *@Arnauld* used in [his JavaScript answer](https://codegolf.stackexchange.com/a/183429/52210) to save a byte: $$s=\left\lfloor\sqrt{2\times\min(b+k,w+k)}\right\rfloor$$ with still: $$k=\begin{cases} 0&\text{if }b=w\\ 1&\text{if }b\neq w \end{cases}$$ ``` Ë # Check if the two values of the (implicit) input-pair are the same # (1 if truthy; 0 if falsey) ≠ # Falsify (!= 1), so 1 becomes 0 and vice-versa + # Add that to each of the (implicit) input-values ß # Only leave the minimum of that · # Double it t # Take the square root ï # And truncate/floor it by casting to an integer ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 bytes Port of Arnauld's JS solution. Takes input as an array. ``` ñÍÌÑ+Ur¦)¬f ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8c3M0StVcqYprGY&input=WzEyLDE1XQ) ``` ñÍÌÑ+Ur¦)¬f :Implicit input of array U ñ :Sort by Í : Subtracting from 2 Ì :Last element (Yes, there are more straightforward ways of getting the minimum but I like this method and it doesn't cost any bytes) Ñ+ :Multiply by 2 and add Ur :U reduced by ¦ : Testing for inequality ) :End reduce ¬ :Square root f :Floor ``` [Answer] # [R](https://www.r-project.org/), 32 bytes ``` min(sum(n<-scan()),2*n+1)^.5%/%1 ``` [Try it online!](https://tio.run/##K/r/PzczT6O4NFcjz0a3ODkxT0NTU8dIK0/bUDNOz1RVX9XwvwmXwX8A "R – Try It Online") Takes `b` and `w` from stdin. Uses the formula from [this answer](https://codegolf.stackexchange.com/revisions/183471/2), but leveraging the behavior of `min` to take the minimum of all its arguments. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~29~~ 26 bytes ``` {0+|sqrt 2*@_.min+[!=] @_} ``` Thanks to Jo King for -3 bytes. [Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@7/aQLumuLCoRMFIyyFeLzczTzta0TZWwSG@9r81V1p@kYKNoZGCoamCBRCaKBgomCqY2Sno2imoJOkoqJQrVHNxFidWKihBuUCJ6jQNCEezVomr9j8A "Perl 6 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 bytes Port of Arnauld's JS solution. ``` mV Ñ|U¦V ¬ ``` [Try it online!](https://tio.run/##y0osKPn/PzdM4fDEmtBDy8IUDq35/9/QiMvQFAA "Japt – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ⌊√+¬=³¹Dy ``` [Try it online!](https://tio.run/##AR4A4f9odXNr///ijIriiJorwqw9wrPCuUR5////MTL/MTU "Husk – Try It Online") Uses the logic from [Arnauld's answer](https://codegolf.stackexchange.com/a/183429). [Answer] # [Python 3](https://docs.python.org/3/), 37 bytes ``` lambda a,b:(2*min(a,b)+(a!=b))**.5//1 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8lKw0grNzNPA8jU1NZIVLRN0tTU0tIz1dc3/F9QlJlXopGmYWikY2iqqamgrGDKBROz0LEAiigAxUzgYiY6BlAxw/8A "Python 3 – Try It Online") Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s solution. ]
[Question] [ In the absurdist play *[Rosencrantz and Guildenstern are Dead](https://d3jc3ahdjad7x7.cloudfront.net/HgjKbM59FD5bFo4Khi3czmVu0dUiw1Pru7Lya3BKNaDtfvrn.pdf)*, the two main characters **Rosencrantz** and **Guildenstern**(or are they?) are always mixing up which of them is who—or sometimes which of their own body parts is which—because of a perceived lack of individual identity. Wouldn't it be absurd if they even shuffled around their names? Your task it to write a function which takes in a string of an **even** length(and by design, a multiple of 4) that is greater than 7 characters, split it, and shuffle it. *The splitting shall be as follows*: the string will be of format `"abscd"`, with s acting as a seperator character. The first section and the separator, `abs` will be the first half of the string, whereas the second half will be `cd` The length of `a` will be `(string length / 4) - 1` The length of `b` will be `(string length / 4)` The length of `s` will be `1` The length of `c` will be `(string length / 4) + 1` The length of `d` will be `(string length / 4) - 1` This may be really confusing, so let me show you with some examples ``` ("a" + "bb" + "s" + "ccc" + "d").length //8 1 2 1 3 1 |-------4--------| |----4-----| <--- (4 is half of 8) ("rosen" + "crantz" + "&" + "guilden" + "stern").length //24 5 6 1 7 5 ("foo" + "barr" + "?" + "barry" + "foo").length 3 4 1 5 3 ``` **Finally:** You then shuffle the parts around, outputting `adscb` ex. `"rosencrantz&guildenstern" --> "rosenstern&guildencrantz"` `"foobarr?barryfoo" --> "foofoo?barrybarr"` # Rulez: 1. [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are prohibited 2. Acceptable answers: a function which takes input through one input string and returns one output string 3. If the input string doesn't match the requirements provided above, your code MUST error out(doesn't matter what kind of `Exception` or `Error`) 4. This is `code-golf`, so the shortest(valid)answer (in each language) wins! 5. **Bonus points for a one-liner** :-) (Not really tho, just cool points) [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~35~~ ~~34~~ 33 bytes ``` {$[8>#x;.;<x!4!-&4#-1 0 2+-4!#x]} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWiXawk65wlrP2qZC0URRV81EWddQwUDBSFvXRFG5Irb2f4KBlU6aglJiUlJxcnJyihIXTAAoAhZKTkEIFuUXp@YlFyXmlVSppZdm5qSk5hWXpBblwRWk5ecnJRYV2YOISiAHybicYiDKTslKy0ksTslOVPoPAA "K (oK) – Try It Online") # Without input validation (for ngn's bounty), ~~25~~ ~~24~~ 23 bytes ``` {<x!4!-&4#-1 0 2+-4!#x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82q2qZC0URRV81EWddQwUDBSFvXRFG5ovZ/goGVTpqCUmJSUnFycnKKEhdMACgCFkpOQQgW5Ren5iUXJeaVVKmll2bmpKTmFZekFuXBFaTl5yclFhXZg4hKIAdhXBLIbC6gO1SiLeyUK6wN1a3RXaShXKGpahJby4XTTcU5KWnZWYnFKdlpWYk5xdkpQErpPwA "K (oK) – Try It Online") Quickly learned a bit of K and, looking at the list of verbs, I thought an alternative approach (*not* using cut) could work here. And it worked perfectly. ### How it works ``` {<x!4!-&4#-1 0 2+-4!#x} -4!#x Length divided by four (floor division) 4#-1 0 2+ Generate lengths (x/4-1, x/4, x/4+2, x/4-1) & Generate that many 0, 1, 2, 3's 4!- Negate and modulo 4; effectively swap 1 and 3 <x! Sort the original string by above {$[8>#x;.; <code> ]} Input validation $[8>#x ] If the length is less than 8 . Dynamically generate an error <code> Otherwise, run the main code ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~60~~ 58 bytes *-2 bytes thanks to Jo King* ``` {[~] .rotor($_/4 X-1,0,+^-$_+>2,-1,1)[0,4,2,3,1;*]}o*.comb ``` [Try it online!](https://tio.run/##TY67DoIwFIbn8hRnIESxIEW8BS8xLu46mBglKK0xAWoOdUCDr44FBx3@y3fyD@fOMR3VWQmWgHn9OryP4KJUEjtm1A9g7zDq0d7JMaPewqeaWPfg0YD6dEBZaB8rabsXmZ3r0BASYYay4PkF41w9revjliY8LxTHHISU5xhx2VipAZg/CFobjsaT6a95f5Ut4GUQhWUTpIhLEPqvbqhhvdqtN@2ZJFzEj1R9gbhbha6eNiNSGa0qo6o/ "Perl 6 – Try It Online") Throws "Rotorizing sublist length is out of range" in case of error. ### Explanation ``` { # Anonymous block [~] # Join .rotor( # Split into sublists of specific length $_/4 X- # Subtract from len/4 1, 0, +^-$_+>2, # (len-1)>>2 # subtraction yields 1 if len is multiple of 4 # otherwise a value less than 1 causing an error -1, 1) [0,4,2,3,1;*] # Rearrange sublists and take inner elements }o*.comb # Split into characters and feed into block ``` [Answer] # [J](http://jsoftware.com/), ~~36~~ 35 bytes ``` 5;@A.](<;.2~;)1<@{."+~1 0 _2 1-4%~# ``` [Try it online!](https://tio.run/##PYxLCsIwGIT3nuKnorGowRbdNBXrQUTyLBVJIKkLFXP1mCbQxQzzzcA8QoEBKTg3CHbwa@AAUeFEuiu@bVqCa0/Kqu2@uNj6Kq73Gqr9ceWXoQwKEGXMcc4FWkwQKSEXubDGSc0t1eNn3b@Gp5DajdLqNCpjGLX2Mtk7Qr5gXEjVzzmFTE5RJ2ahPw "J – Try It Online") -1 byte by `{.` + negative lengths & `;.2` which cuts on ones as "ending" markers instead. ## Original answer, 36 bytes ``` 5;@A.](<;.1~;)1<@{."+~_1 0 2 _1+4%~# ``` [Try it online!](https://tio.run/##PYxLCsIwGIT3nuKnorFUgpG6aSrWg0jJsyiSQFIXKubqMW2gixnmm4F5xAID0nBuEOzh18ABkuKJdld827UUk0BL0nZfXFShJ2k@Qk@qehPWsYwaEOPcCyEkWk2QaEYhc@GsV0Y4ZsbPdnjdn1IZPypn5lFby5lzl8neCfIFF1LpYclzyOQ183IR@gM "J – Try It Online") ngn mentioned "cut" on a comment to an [earlier K answer](https://codegolf.stackexchange.com/a/175208/78410), and it made me try J which has the same "cut" (I have no idea how K works). ### How it works ``` 5;@A.](<;.1~;)1<@{."+~_1 0 2 _1+4%~# Monadic train. 4%~# Length divided by four _1 0 2 _1+ Generate the four segment lengths 1<@{."+~ Generate [1 0 0...] boxed arrays of those lengths ( ;) Raze; unbox and concatenate ] <;.1~ Cut the input string on ones as starting marker, then box each 5 A. Rearrange the boxes in the order 0 3 2 1 ;@ Raze again ``` Note that this function automatically handles invalid inputs: * If the input length is not a multiple of four, `{.` throws `domain error` since its length argument has to be integers. * If the input length is 4, the cut produces only two segments, and `5 A.` throws `index error`. * If the input length is 0, the two arguments to cut don't have the same length, so `length error` is thrown. [Answer] # [Python 3](https://docs.python.org/3/), 103 102 101 97 88 86 84 bytes ``` def f(s):l=len(s);l//=4*(l%4<1<l/4);return s[:l-1]+s[1-l:]+s[2*l-1:1-l]+s[l-1:2*l-1] ``` [Try it online!](https://tio.run/##lUxLDoIwEN1zikqifAwhKKsCcaOXkLBAGLRJMyXTYsTLIzUGVy6cxcz7zetHc1O4n6YWOtb5OuCykIAzyGQcF2noy3WaJ7mM0yAjMAMh0yWXUVJtdZlEktu7C2eBz8wSC99CNfUk0Pid75LSgA3VaJ6b6yBkC6gNELpB4CyhTqlLTXSwa5yJNR1DI3cYW0JAn7EuPBroDTsDqaO4Cy0UnogUfT@8N195P5r@LJle "Python 3 – Try It Online") Not really a one-liner, but `;` is one less byte per line than linebreak and indent. Throws `ZeroDivisionError` if input string length is less than 8 or not an integer multiple of 4. Also works in Python 2. -4 bytes thanks to Jo King -9 bytes thanks to ovs -2 bytes thanks to Jonathan Frech -2 bytes thanks to Bubbler [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 78 bytes ``` *.comb[0..*/4-2,3* */4+1..*,*/2-1/(*>7)..3* */4,*/4-1/(*%%4)..*/2-2].flat.join ``` [Try it online!](https://tio.run/##PYtLDsIgGIT3noKQtClYfoQ2ujDqQYwLWqGpacFAXdTLI0TjZjKPb57aT/s4r6g06IQihd7N3XUHQHnLZN1QlMxWpFxTLpngFT0fCMB3qDOVu6JoSf5IJm9gJrXAw402HjdBrchU2Lugbe@VXd7l8Bqnu7Zh0d5i8kMQNs51yvtLljUF/F@EbFocPw "Perl 6 – Try It Online") Anonymous code block that takes a string and returns the modified string if valid, else returns a division by zero error. I know I can modify an array directly, so I could swap the two sections of the string, but I can't quite figure it out. [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 120 113 103 99 95 bytes ``` {$[(r>7)&0=4!r:#:x;{g:(s:*|(y*2)#x)\x;((y-1)#*g),((-y-1)#*|g),s,((y+1)#*|g),(-y)#*g}[x;r%4];l]} ``` Hopefully can be golfed down more, included an extra function for testing if string length is divisible by four, outputs error with reference to undeclared variable if input is invalid EDIT: Missed condition on length greater than 7, included EDIT: Combined into one function, removed redundant variable declarations [Try it online!](https://tio.run/##NcrNCsIwEATgu29hqmUTLagUhAT1QWoP/TOIJYHdColtnz2miJdhPmZemdEmBJLjpgC8nnl6uORrlIl0atQSSIoJvDjxxPG7UwA@O/JEaL4HyH59iqBIv/srLstnLpzCbV6qvpwDsYe1dYV4W8JHsBUxtNSZBiszfFL9fvZtZ2jo0CxbVTctC18 "K (ngn/k) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 64 bytes ``` ->s{a=s.size/4;s[1-a,a],s[a-1,a]=s[a-1,a],s[1-a,a];s[a*4]?1/0:s} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664OtG2WK84sypV38S6ONpQN1EnMVanODpR1xDIsIUxdGBSQDWJWiax9ob6BlbFtf8LSkuKFdKilYryi1PzkosS80qq1NJLM3NSUvOKS1KL8pRiuWBK0vLzkxKLiuxBRCWQgyTll1qWWuSen5eX6J5ZlhqZXxpaoBT7HwA "Ruby – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 58 or 73 or 83 or 93 bytes ``` ((((.)))*?)(.(?<-2>.)+)(...(?<-3>.)+)((?<-4>.)+)$ $1$7$6$5 ``` [Try it online!](https://tio.run/##K0otycxL/P9fAwj0NDU1tew1NfQ07G10jez0NLWBbD0wzxjCAzFNwEwVLhVDFXMVMxXT//@L8otT85KLEvNKqtTSSzNzUlLziktSi/IA "Retina 0.8.2 – Try It Online") Explanation: ``` ((((.)))*?) ``` Capture `a` in `$1`, and make it as short as possible `*?`. `$#2`, `$#3` and `$#4` end up as the length of `a`. ``` (.(?<-2>.)+) ``` Capture `b` in `$4`. The `(?<-2>.)+` captures up to the length of `a`, while the other `.` adds 1 to its length as required. ``` (...(?<-3>.)+) ``` Capture `s` and `c` in `$6`. Their combined length is three more than the length of `a`. ``` ((?<-4>.)+) ``` Capture `d` in `$7`. Its length is no more than the length of `a`. ``` $ ``` We made `a` as short as possible, but we still want to reach the end of the input. ``` $1$7$6$5 ``` Exchange `b` and `d`. The above stage does not validate its input. As Retina has no run-time errors, there are a number of options for input validation: ``` G`^(....){2,}$ ``` Outputs nothing if the length is less than 8 or not a multiple of 4. (+15 bytes) ``` ^(?!(....){2,}$).* Error ``` Outputs `Error` if the length is less than 8 or not a multiple of 4. (+25 bytes) ``` +`^(....)*..?.?$|^(....)?$ .....$1 ``` Hangs if the length is less than 8 or not a multiple of 4. (+35 bytes) [Answer] # [C (gcc)](https://gcc.gnu.org/) with `-Dx=memcpy` and `-DL=(l-1)`, 154 158 160 bytes Returns NULL if the input string length is not divisible by 4 or shorter than 8 characters. Thanks to Rogem and Jonathan Frech for the suggestions. EDIT: Moved preprocessor defines to the command line and made the string dynamically-allocated to strictly conform with the puzzle. ``` f(s,t,l)char*s,*t;{l=strlen(s);l%4|l<8?t=0:(t=malloc(l+1),l/=4,x(t,s,L),x(t+L,s+3*l+1,L),x(t+2*L,s+L+l,l+2),x(t+3*l,s+L,l),t[4*l]=0);l=t;}//-Dx=memcpy -DL=(l-1) ``` [Try it online!](https://tio.run/##RY/JbgIxDIbvPEWERJVtxFIOVYeUC8d5A8ohZJZG8mRQnFIo5dWbJl3oxf79/ZYXU3TGxNhSlEECMy/ac5Q8lBdQGDw0jiIrYbL8gNXDOqjZIw2q1wCDoSDmTMJULeWJBomyYlmISqK458n8AwueUSVAglj8oORnlDbKsF1y2KlZ2qJCeZ1Oi81J9U1vDmdSbCpFoZizaF0gvbaOZqF9ZyTJtxLOU3Fk5DIipB38t23VvCR2lbtSFoKRg0@8peMJEvVEJvjsxjJPOW7tTpKW/krGytE1Rr3fozGmjn7AxhmvXXi/614t1I3D0HgX22HYa@/XOZxTEbEfIN141GDrT9OC7jAWb/H/lXh75Qs "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` L7»4ḍİ×L:4;;ĖÄƲFÄœṖ⁸⁽%[D¤ị$F ``` (If a full program is allowed we can remove the trailing `F`) If the length is less than 8 or not divisible by four a `ValueError` is raised during integer division of `inf` (a float) by `4` -- the division yields `NaN` (also a float) which then cannot be cast to an `int`. **[Try it online!](https://tio.run/##AVMArP9qZWxsef//TDfCuzThuI3EsMOXTDo0OzvElsOExrJGw4TFk@G5luKBuOKBvSVbRMKk4buLJEb///8icm9zZW5jcmFudHomZ3VpbGRlbnN0ZXJuIg "Jelly – Try It Online")** ### How? ``` L7»4ḍİ×L:4;;ĖÄƲFÄœṖ⁸⁽%[D¤ị$F - Link: list of characters L - length 7 - literal seven » - maximum (of length & 7) 4ḍ - divisible by four? (yields 1 for good inputs; 0 otherwise) İ - inverse (1 yields 1; 0 yields inf) ×L - multiply by length (length or inf) :4 - integer divide by 4 (errors given inf) Ʋ - last four links as a monad (f(x)): ; - concatenate -> [x,x] Ė - enumerate -> [1,x] ; - concatenate -> [x,x,[1,x]] Ä - cumulative sum (vectorises at depth 1) -> [x,x,[1,1+x]] F - flatten -> [x,x,1,1+x] Ä - cumulative sum -> [x,2x,2x+1,3x+2] ⁸ - chain's left argument (the input) œṖ - partition at indices (chops up as per requirements) $ - last two links as a monad (f(z)): ¤ - nilad followed by link(s) as a nilad: ⁽%[ - 10342 D - decimal digits -> [1,0,3,4,2] ị - index into z (rearranges the pieces as per requirements) F - flatten (back to a list of characters) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` L:4’+“¡¢¢£¡‘Ṡ3¦ÄṬk⁸Ṛ2,5¦Ẏ ``` [Try it online!](https://tio.run/##AVMArP9qZWxsef//TDo04oCZK@KAnMKhwqLCosKjwqHigJjhuaAzwqbDhOG5rGvigbjhuZoyLDXCpuG6jv///3Jvc2VuY3JhbnR6Jmd1aWxkZW5zdGVybg "Jelly – Try It Online") The `Ẏ` can be removed to make this into a full program. [Answer] # JavaScript (ES6), ~~97~~ 89 bytes *Saved 8 bytes thanks to @l4m2* ``` s=>(l=s.length/4)<2||l%1?Z:s.replace(eval(`/(.{${l}})(.{${l+2}})(.{${l-1}})$/`),'$3$2$1') ``` [Try it online!](https://tio.run/##XcpBDoIwEIXhvccgVdooJaArI3IPV9QyIGbSIW0lUeDsFWPiws3L95L/rgbltO16nxiqITRFcMWZY@Ekgmn9LT2IUz5NuM7Ky9FJCz0qDRwGhbxKuRzZiPMsvtjmPybZQpZWYhezPctZFougyThCkEgtb3hkyYHRVhn/2rSPDmswzoM1kRCrv7Qhuipry888l7Mk4Q0 "JavaScript (Node.js) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 80 bytes ``` s=>(g=s.substr.bind(s))(0,l=s.length/4-1)+g(-l)+g(l-~l,l+3)+g(l,l+1,l<1==l%1||Z) ``` [Try it online!](https://tio.run/##bYpBCsIwEEX3HqOgJLSpBl0avYe7tE1jZZiRmVRQilePrUtx83j/8W/@4aXl4Z4MUhdy77K4k4pOahkbSVw3A3ZKtFa7CuYKAWO6bg/G6jIqAwvBvKGCcv/1WWwFR@scrO00XXRuCYUg1EBR9apgkoAte0yvTRwH6AJKCoyF1qufa0/UeObzguc8/lwCM/Hc8wc "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 84 bytes ``` s=>(g=(a,b)=>s.substr(a,b))(0,l=s.length/4-1)+g(-l)+g(l-~l,l+3)+g(l,l+1,l<1==l%1||Z) ``` [Try it online!](https://tio.run/##bYpBCsIwEEX3HqOgJDSpBl2aeg93aZvGypCRmVRQilePbZfi5vHe59/d03FLwyPpiJ3Pvc1saxGscKqRtuaKx4YTrSnFQYHlCnwM6bY/aSPLIDQsBP0BBeVx9VmMgrOxFrZmmq4ytxgZwVeAQfSiIGQfW3IxvXdhHKDzkZOnWEi5@bn2iI0juix4zfHn4omQ5j1/AQ "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 87 bytes ``` s=>(l=s.length/4)<2||l%1?Z:(g=(a,b)=>s.substr(a,b))(0,l-1)+g(1-l)+g(l+l-1,l+2)+g(l-1,l) ``` [Try it online!](https://tio.run/##bYrNDoIwEITvPgaJZht@FOLJWHgPbwVKxWy6ZreYaHj3ChyNl5n5Jt/DvIx0PD5D7qm3cdBRdA2opUDrXbgfz@pazTPuy@Z2AafBZK3StRQytRJ4QwWnDPNSpQ7KHNfCdOEM02qDdarYkRdCWyA5GCBhEus7Nj58Dm4asbdegmWfKLX7UQei1jA3a7wX@KNYZuLlj18 "JavaScript (Node.js) – Try It Online") Shorter than RegExp [Answer] # Java 8, 135 bytes ``` s->{int l=s.length();l=l>7&l%4<1?l/4:l/0;return s.substring(0,l-1)+s.substring(3*l+1)+s.substring(2*l-1,3*l+1)+s.substring(l-1,2*l-1);} ``` Throws `ArithmeticException` (divides by zero) if the input string does not match requirements. Try it online [here](https://tio.run/##hY7RSsMwFIavu6cIBUe7remmA8Fu3ROIF8Mr2UXWpjXz7KQkJ4M69uw1XVVEBCGcJN//5ScHcRKJbiQeyreucXtQBStAWMsehUJ2HgWf0JIgv520KtnRR9GWjML6ZceEqW3cm8HBl3FHCnjlsCClkT@jMO1TI40gbVbDm5xVbM06m@RnhcRgbTlIrOk1ijNYQ34/hpvlarGBdPkA6TwzkpxBZrl1e3ttiOYzSBbx9Ce6m8D0F7qdeGv2R9Djaxhnly4IMv/3bWtJHrl2xBvvEGBUcdE00Eah0VZiYQTS@7h2CkqJXjYYxnHG0pQNwhV95YMd/lNcab0Xxmz60frLd6E/@zXwfviiy@jSfQA). Ungolfed: ``` s -> { // lambda function taking a String argument and returning a String int l = s.length(); // take the length of the input ... l = l > 7 & // ... if it's greater than 7 and ... l % 4 < 1 // ... a multiple of 4 ... ? l / 4 // ... divide by 4; otherwise ... : l / 0; // ... error out (division by zero throws ArithmeticException) return // concatenate and return: s.substring(0, l - 1) // a + s.substring(3 * l + 1) // d + s.substring(2 * l - 1, 3 * l + 1) // sc + s.substring(l - 1, 2 * l - 1); // b } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 129 bytes Returns by modification. Compile with: ``` -Df(s)=({char t[l=strlen(s)];l%4|l<8?0:(l/=4,x(t,s+l*2-1,l-~l),x(x(x(s+l*3,s+l-1,l)-l-2,t,l+2)-l+1,t+l+2,l-1),s);}) -Dx=memcpy ``` Source file: ``` l; ``` [Try it online!](https://tio.run/##xVHNbsIwDL7zFFElpoYkYmUcJkrHhbdgHNKQdpXcFCWBwRh79GVOqQRvMEVy7O/HchwlaqVCgHw6FesqdbRIL@pDWuI3UDhvQRsEtzmM59@wfF09L1KYFnN@Sj13DCYzkXEQP0ARiSdiL5GJOBUgZtxzYDNMWcY9wxT1GeWO5ldKxPpUtLpV@3NojCetbEwaE2lrxUk/yGSCxZGSy4gMQHmociyqzvbapshy0iyjBW/GaFQSEimcnhRkeEZss2m2NO9pbIKU1RKgUylWnDCGsoG@DXXDByMnd3pvsX2VJmNHijcydu8medBV0UdXGBZJ0juucV6rdU/ko2sIsiydUmoXbOe0UVYa//VUHxrYaeO8tiZUXVdKa1cxnLEIru0A13SU0Ox@VQWydkF8hocd/sMX/gE "C (gcc) – Try It Online") ## Degolf ``` -Df(s)=({ // Function-like macro f. Takes a char* as a parameter. // Return value is a pointer to s if successful, and to NULL if string was invalid. char t[l=strlen(s)]; // Allocate a local temp string. l%4|l<8?0: // Detect invalid strings. Return 0 (NULL) on invalid string. (l/=4, // We're only really concerned with floor(len/4), and this will yield that. memcpy(t,s+l*2-1,l-~l), // Copy the second half of chars to the temp storage. memcpy( // Because memcpy returns the address of the destination, we can chain // the calls to save quite a few bytes, even after x->memcpy substitution. memcpy(memcpy(s+l*3,s+l-1,l) // Next, copy the second quarter to the end. -l-2,t,l+2) // After that, we copy back the third quarter to its place. -l+1,t+l+2,l-1) // Finally, copy the fourth quarter to where the second // quarter was. ,s);}) // And return the pointer. ``` ]
[Question] [ **The challenge is simple** Write a script that, when given a string input, will hash the string using the [MD2 hashing algorithm](https://en.wikipedia.org/wiki/MD2_(cryptography)), and then return either a positive integer or negative integer output based on which character set below is more common in the resulting hash as a hexadecimal string: ``` 01234567 - (positive) 89abcdef - (negative) ``` * The input will always be a string, but may be of any length up to 65535 * The entire input, whitespace and all, must be hashed * For the purposes of this challenge, the integer 0 is considered neither positive nor negative (see tie output) * The more common set is the one who's characters are more common within the 32 character hexadecimal hash string * Your output may contain trailing whitespace of any kind, as long as the only non-whitespace characters are a valid truthy or falsey output * In the event of a tie, where the hexadecimal string contains exactly 16 characters from each set, the program should output a 0 **I/O Examples** ``` Input: "" (Empty String) Hash: 8350e5a3e24c153df2275c9f80692773 Output: 1 Input: "The quick brown fox jumps over the lazy cog" (Without quotes) Hash: 6b890c9292668cdbbfda00a4ebf31f05 Output: -1 Input: "m" (Without quotes) Hash: f720d455eab8b92f03ddc7868a934417 Output: 0 ``` **Winning Criterion** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins! [Answer] ## Mathematica, 43 bytes ``` Tr@Sign[15-2#~Hash~"MD2"~IntegerDigits~16]& ``` Outputs the number of digits in `01234567` minus the number of digits in `89abcdef`. [Answer] ## JavaScript (ES6), 731 bytes This monster is implementing the MD2 algorithm, so it's embarrassingly long. Based on [js-md2](https://www.npmjs.com/package/js-md2) by Chen Yi-Cyuan. ``` let f = m=>{L=x=s=b=0,n=m.length,M=[],X=[],C=[],S=[...atob`KS5DyaLYfAE9NlSh7PAGE2KnBfPAx3OMmJMr2bxMgsoem1c8/dTgFmdCbxiKF+USvk7E1tqe3kmg+/WOuy/ueqloeZEVsgc/lMIQiQsiXyGAf12aWpAyJzU+zOe/95cD/xkws0iltdHXXpIqrFaqxk+4ONKWpH22dvxr4px0BPFFnXBZZHGHIIZbz2XmLagCG2Alra6wufYcRmFpNEB+D1VHoyPdUa86w1z5zrrF6iYsUw1uhSiECdPfzfRBgU1Satw3yGzBq/ok4XsIDL2xSniIlYvjY+ht6cvV/jsAHTny77cOZljQ5KZ3cvjrdUsKMURQtI/tHxrbmY0znxGDFA`].map(c=>c[O='charCodeAt']());for(l=1;l-2;){for(j=19;j--;)M[j]=M[16+j]||0;for(i=s;i<16;x++)L=(x-n||(b+=i-s,s=i-16,l=2),C[i]^=S[(M[i++]=x<n?m[O](x):16-(b&15))^L]);for(i=0;i<l;i++){for(j=16;j--;)X[32+j]=(X[16+j]=(i?C:M)[j])^X[j];for(t=j=0;j<18;t=t+j++&255)for(k=0;k<48;)t=X[k++]^=S[t]}}for(i=16,n=-i;i--;)n+=!(X[i]&8)+!(X[i]&128);return n} console.log(f('')) console.log(f('The quick brown fox jumps over the lazy cog')) console.log(f('m')) ``` [Answer] # Python 2 + [Crypto](https://www.dlitz.net/software/pycrypto/api/current/Crypto-module.html), ~~108~~ ~~99~~ ~~93~~ ~~91~~ ~~87~~ 78 bytes Python doesn't have a native builtin for MD2. ``` from Crypto.Hash import* lambda s:sum(x<'8'for x in MD2.new(s).hexdigest())-16 ``` *Saved 12 bytes thanks to @ovs.* *Saved 9 bytes thanks to @FelipeNardiBatista.* [Answer] # Java 8, 173 bytes *-4 thanks to dzaima* *-128 thanks to Oliver, this is basically his answer now.* ``` a->{String h="";for(byte b:java.security.MessageDigest.getInstance("MD2").digest(a.ge‌​tBytes()))h+=h.forma‌​t("%02x",b);return h.codePoints().filter(c->c>47&&c<56).count()-16;} ``` Positive for truthy. Negative for falsy. 0 for 0. [Answer] # PHP, 50 Bytes prints 1 for truthy and -1 for false and 0 for a tie ``` <?=preg_match_all("#[0-7]#",hash(md2,$argn))<=>16; ``` # PHP, 58 Bytes prints 1 for truthy and -1 for false and 0 for a tie ``` <?=16<=>strlen(preg_filter("#[0-7]#","",hash(md2,$argn))); ``` [Answer] # Octave, 35 bytes ``` @(s)diff(hist(hash('md2',s),+'78')) ``` \*Requires the latest version of Octave (at least 4.2). Computes histcounts of the hash string with it's center of bins are 7 and 8 then computes the difference of counts. [Answer] # PHP, 56 bytes ``` while($i<32)${hash(md2,$argn)[$i++]>'7'}++;echo$$_<=>16; ``` [Answer] # Java ~~137~~ ~~130~~ ~~124~~ 123 bytes ``` a->{int c=32;for(int b:java.security.MessageDigest.getInstance("MD2").digest(a.getBytes()))c-=(b>>6&2)+(b>>2&2);return c;} ``` [Test it online!](http://ideone.com/ZhhksK) Basically, for each byte, we're asked to check against its 4th and 8th least significant bits. I don't go through the hex representation at all. So it seemed only natural to start playing with bits. Values `<0` are falsey, values `>0` are truthy, value `0` is neither truthy or falsey. The usual truthy and falsey can't be applied to Java this time (because it can't be `true` or `false` or `0` with the rule `if(<truthy>)`), so I took the liberty to declare as such. ## Saves 1. 137 -> 130 bytes: golfed by using bit operations, removing 2 everytime I get a "falsy" bit. 2. 130 -> 124 bytes: more bitwise operations 3. 124 -> 123 bytes: replaced `byte` by `int` in the for loop declaration. [Answer] # Tcl + [Trf package](https://wiki.tcl-lang.org/479), 79 ``` package require Trf puts [expr [regexp -all \[0-7\] [hex -m e [md2 $argv]]]-16] ``` [Try it online](https://tio.run/nexus/tcl#NY6xDoIwGIR3n@LSsDZRB30RttKh1h9QKK1/C6KEx3bGOni54ZIv@XK1ZzK2RaKYrImERZQt4THebIcL@@eA2s@4jy5E@IkYKePevF@wvhEQuU6sWHbIiZRguJlQ/H1bMLYzDYEpO5lQcr0LY4pQNAeGYmrygDR9j0rt5bnSUC3NkA4E5a5HFD@l1loeTnpbt819Bi9tfk1f). (Thanks @Dennis for adding Tcl to TIO.) ]
[Question] [ Building a golfed rot13 encryptor is too easy because the letters are all the same order in the ASCII character space. Let's try a rot32 engine instead. Your task is to build a function that takes a Base64 string as input and returns the same string but with each letter rotated 32 symbols from its original (in essence, with the first bit flipped). The base64 encoding string to use for this problem is `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/` with a padding character of `=`. This is to prevent solutions that would otherwise use or import a built-in Base64 library where strings normally start with `A` instead of `0`. ``` Example inputs and outputs: > rot32("THE+QUICK+BROWN+FOX+JUMPS+OVER+THE+LAZY+DOG=") nb8ukoc6eu5liqhu9irudogjmuip8lunb8uf4tsu7ia= > rot32("NB8UKOC6EU5LIQHU9IRUDOGJMUIP8LUNB8UF4TSU7IA=") h5Eoei6C8oBfckboFclo7iadgocjEfoh5Eo9AnmoDc4= > rot32("Daisy++daisy++give+me+your+answer+true/I+/+m+half+crazy++all+for+the+love+of+you") 7GOY2uuJGOY2uuMO/KuSKu2U+XuGTY0KXuZX+KvcuvuSuNGRLuIXG32uuGRRuLUXuZNKuRU/KuULu2U+ ``` The shortest program to do so in any language wins. [Answer] # Bash / Unix shell, 29 ``` tr 0-9a-zA-Z+/ w-zA-Z+/0-9a-v ``` Input from STDIN, output on STDOUT. [Answer] # Perl, 41 Just a simple [transliteration](http://perldoc.perl.org/perlop.html#tr%2fSEARCHLIST%2fREPLACEMENTLIST%2fcdsr). Reads from STDIN, outputs to STDOUT: ``` $_=<>;y#0-9a-zA-Z+/#w-zA-Z+/0-9a-v#;print ``` [Try it out here.](http://ideone.com/FMtVTt) [Answer] # CJam, 24 bytes ``` q"+"":/{a[A"{,^}/_32m>er ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### How it works ``` q " Read from STDIN. "; "+" " Push that string. "; ":/{a[A" " Push that string. "; { " For each character in the second string: "; , " Push the string of all charcters with a lower ASCII code. "; ^ " Take the symmetric difference of the two topmost strings on the stack. "; }/ " Result: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/0123456789'. "; _32m> " Rotate a copy 32 characters to the right. "; er " Perform character transliteration. "; ``` [Answer] # CJam, ~~45 41 38 29 27~~ 26 bytes ``` qA,'{,97>_eu"+/"+++_32m>er ``` Reads the string to be encrypted from STDIN **How it works**: ``` q "Read input"; A, "Get 0 - 9 array"; '{, "Get array/string of ASCII code 0 till ASCII code of z"; 97> "Remove first 96 characters to get a-z string"; _eu "Copy a-z array and turn it to uppercase A-Z array"; "+/"+++ "Push string +/ and concat all 4 arrays"; _32m> "Copy the array and move first 32 characters to end"; er "Transliterate input using the two arrays, leaving =" "intact as it does not appear in the first array"; ``` [Try it online here](http://cjam.aditsu.net/) [Answer] # Python, 178 ``` b = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/" def rot32(s): o = "" for c in s: if c not in b: o += c else: o += b[b.find(c) ^ 32] return o ``` This is an ungolfed, last-place reference implementation in Python that you can use to test your own implementation. [Answer] ## GolfScript (41 40 bytes) ``` {'0:a{A['2/{{,>}*}%'+/'+[1$]+.32/(*@?=}% ``` [Online demo](http://golfscript.apphb.com/?c=OyJUSEUrUVVJQ0srQlJPV04rRk9YK0pVTVBTK09WRVIrVEhFK0xBWlkrRE9HPSIKeycwOmF7QVsnMi97eyw%2BfSp9JScrLycrWzEkXSsuMzIvKCpAPz19JQ%3D%3D) There are two parts to this: the translation is a variant on the last technique mentioned in [my tip on `tr` in GolfScript](https://codegolf.stackexchange.com/a/6273/194), and the other part is the string building, which uses the string `0:a{A[` as an array of char values and a fold to turn them into character ranges. Note the use of `32/(*` to build the translated string by inserting the first 32 chars between the second 32 chars and the character we're translating. [Answer] **python, 69** ``` f = lambda s,b: ''.join(b[b.index(c)^32] if c in b else c for c in s) ``` tests ``` >>> b = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/" >>> print f("THE+QUICK+BROWN+FOX+JUMPS+OVER+THE+LAZY+DOG=", b) nb8ukoc6eu5liqhu9irudogjmuip8lunb8uf4tsu7ia= >>> print f('nb8ukoc6eu5liqhu9irudogjmuip8lunb8uf4tsu7ia=', b) THE+QUICK+BROWN+FOX+JUMPS+OVER+THE+LAZY+DOG= ``` [Answer] # LiveScript, 91 ``` r=[\0 to\9].concat [\a to\z] [\A to\Z] [\+ \/];f=(.replace /[^\W_]/ ->r[32.^.r.indexOf it]) ``` # LiveScript, 50 If the string is allowed as a second argument. ``` f=(a,b)->a.replace /[^\W_]/ ->r[32.^.b.indexOf it] ``` [Answer] # JavaScript 164 ``` b="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/" function rot32(s){for(i=0,o="";i<s.length;i++)c=s[i],j=b.indexOf(c),o+=j>-1?b[j^32]:c return o} ``` ]
[Question] [ What general tips do you have for golfing in TypeScript's type system? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to TypeScript's type system (e.g. "remove comments" is not an answer). Please post one tip per answer. If you're not familiar with programming in TypeScript's type system, the [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html) and [TypeScript Discord Server](https://discord.gg/typescript) are both great resources, as well as the [TypeScript Type System chatroom](https://chat.stackexchange.com/rooms/145771/typescript-type-system). If you post any answers in TypeScript's type system, make sure to check out this [deadlineless 50-100 rep bounty](https://codegolf.meta.stackexchange.com/a/24106/87606). [Answer] # Embrace the type errors Type parameter constraints can often be replaced by a well-placed `//@ts-ignore` comment: ``` // 34 bytes type Head<T extends any[]> = T[0]; ``` ``` // 33 bytes //@ts-ignore type Head<T> = T[0]; ``` [Answer] # Use `{}` instead of `any` or `unknown` where applicable The type `{}` counterintuitively means "anything that is not `null` or `undefined`, so it can be useful for shorter constraints, if you don't care about `null`/`undefined`: ``` // 34 bytes type Head<T extends any[]> = T[0]; ``` ``` // 32 bytes type Head<T extends{}[]> = T[0]; ``` [Answer] # Use indexed access types as switch statements Instead of ``` type Foo<T extends "a" | "b" | "c"> = T extends "a" ? A : T extends "b" ? B : T extends "c" ? C : never ``` use ``` type Foo<T extends "a" | "b" | "c"> = { a: A, b: B, c: C, }[T] ``` Note that in some cases this won't work for recursive types, as it might give the error `'foo' is referenced directly or indirectly in its own type annotation`. [Answer] # Use unions as sets You can use `T | U | V` as a set, or `[T] | [U] | [V]` if you want to prevent merging (e.g. `number | 1` becomes `number`). Set operations: * Union: `A | B` * Intersection: `A & B` for sets of primitives, or `Extract<A, B>` more more complex types * Difference: `Exclude<A, B>` * Map: `A extends A ? Foo<A> : 0` (if `A` is a type parameter) * Map: `A extends infer B ? B extends A ? Foo<B> : 0 : 0` (if `A` is not a type parameter) * Map: `A extends infer B ? [B]|[B] extends [A] ? Foo<B, A>` (if `A` is a type parameter and you need to preserve the reference to the full set) * Empty set: `never` * Size: ``` //@ts-ignore type CountUnion<T,N=[]>=(T extends T?(x:()=>T)=>0:0)extends(x:infer U)=>0?U extends()=>infer V?CountUnion<Exclude<T,V>,[...N,0]>:N:0; ``` [Answer] # Use `any` or shorter types for template literals ``` type EndsInPeriod<I> = I extends `${any}.` ? true : false; ``` Saving around 3 bytes (instead of the alternative `${string}.` [Answer] # Use type parameter defaults Instead of ``` type RecursiveThing<T> = /* something recursive */ type Foo = RecursiveThing<Bar>; ``` Use ``` type Foo<T=Bar> = /* something recursive */ ``` Instead of ``` type SomeConstant = /* something */; type Foo<T> = /* something using that type */ ``` Use ``` type Foo<T,SomeConstant = /*something*/>= /* something using that type */ ``` [Answer] # Use tuples to do non-negative integer arithmetic ``` type IntToTuple<T, A extends any[] = []> = T extends A["length"] ? A : IntToTuple<T, [...A, 0]>; type TupleToInt<T extends any[]> = T["length"]; type AddTuples<A extends any[], B extends any[]> = [...A, ...B]; type SubTuples<A extends any[], B extends any[]> = A extends [...B, ...infer C] ? C : never /* overflow */; type MulTuples<A extends any[], B extends any[], C extends any[] = []> = A extends [0, ...infer A] ? MulTuples<A, B, [...C, ...B]> : C type Add<A, B> = TupleToInt<AddTuples<IntToTuple<A>, IntToTuple<B>>>; type Sub<A, B> = TupleToInt<SubTuples<IntToTuple<A>, IntToTuple<B>>>; type Mul<A, B> = TupleToInt<MulTuples<IntToTuple<A>, IntToTuple<B>>>; type Answer = Mul<Add<5, 2>, Sub<9, 3>>; // ^? - 42 ``` [Answer] # Use stringification of number literal types to parse them ``${42}`` becomes `"42"`, which can be worked with more easily: ``` type Mod2<N extends number> = `${N}` extends `${string}${"1" | "3" | "5" | "7" | "9"}` ? 1 : 0; ``` [Answer] # Use homomorphic mapped types to map tuples ``` type Foo<T> = [[[T]]]; type MapFoo<T> = { [K in keyof T]: Foo<T[K]> } type X = MapFoo<[1, 2, 3]>; // ^? - [Foo<1>, Foo<2>, Foo<3>] ``` [Answer] # Use [this large collection of golfed utility types](https://gist.github.com/tjjfvi/e1b4de4cb17978e234bb391726edaa59) [Answer] # Combine multiple `extends` clauses into one If you have multiple `extends` clauses where you're just extracting part of a tuple/string/whatever and know that the match will succeed and don't care about the failure case, you can combine many clauses into one: ``` // Before: type F<A,B>=A extends[infer D,...infer K]?B extends[5,6,infer F,...infer L]?[D,K,F,L]:0:0 // After: type F<A,B>=[A,B]extends[[infer D,...infer K],[5,6,infer F,...infer L]]?[D,K,F,L]:0 ``` In a case like this where you're just selecting part of each input, you can instead take the inputs as a tuple: ``` // Even better: type F<A>=A extends[[infer D,...infer K],[5,6,infer F,...infer L]]?[D,K,F,L]:0 ``` This example is purposely useless, but this can come in handy in real challenges. One use case is when zipping two tuples: ``` type F<A>=A extends[[infer X,...infer G],[infer Y,...infer H]]?[[X,Y],...F<A>]:A ``` I've used this technique in two submissions of mine: [Add two really big numbers](https://codegolf.stackexchange.com/a/264953/108687) and [Order by Earliest Lower Digit](https://codegolf.stackexchange.com/a/264956/108687). [Answer] # A couple minor byte-saves ## Use `A extends{length:N}` instead of `A["length"]extends N` This saves 1 byte off of decimal to unary conversion, among a few other things. ## When taking the first element and the rest of a tuple, use `{}` and indexing instead of `infer` This saves 2 bytes if you only use the inferred value once. For example, this ``` A extends[infer B,...infer C]?[B,C]:0 ``` becomes ``` A extends[{},...infer C]?[A[0],C]:0 ``` --- I will add more if I think of / encounter any. ]
[Question] [ **This question already has answers here**: [Find prime gaps](/questions/137435/find-prime-gaps) (23 answers) Closed 5 years ago. Given an integer *n*, output the smallest prime such that the difference between it and the next prime is at least *n*. For example, if `n=5`, you would output `23`, since the next prime is `29`, and `29-23>=5`. # More Input/Output Examples ``` 1 -> 2 (3 - 2 >= 1) 2 -> 3 (5 - 3 >= 2) 3 -> 7 (11 - 7 >= 3) 4 -> 7 5 -> 23 6 -> 23 7 -> 89 8 -> 89 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` Ψḟo≥⁰≠İp ``` [Try it online!](https://tio.run/##ARwA4/9odXNr///OqOG4n2/iiaXigbDiiaDEsHD///83 "Husk – Try It Online") Inspired by this [post in chat](https://chat.stackexchange.com/transcript/message/48637842#48637842) `ḟ`, under normal circumstances, finds the first element of a list that satisfies a predicate. However, when combined with the function `Ψ`, it finds the first element that satisfies a predicate with respect to its successor in the list. The predicate is `o≥⁰≠`, which asks if the absolute difference of two numbers is at least the input. The list is `İp`, the list of prime numbers [Answer] # Perl 6, 40 bytes ``` {1-$_+first ++($*=!*.is-prime)>=$_,2..*} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2lBXJV47LbOouERBW1tDRctWUUsvs1i3oCgzN1XTzlYlXsdIT0@r9n9afpGCoZ6eoYFCNZeCQnFipYKeWhpX7X8A "Perl 6 – Try It Online") 38 bytes, 0-based (I'm not sure this is allowed): ``` {-$_+first ++($*=!*.is-prime)>$_,2..*} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WlclXjsts6i4REFbW0NFy1ZRSy@zWLegKDM3VdNOJV7HSE9Pq/Z/Wn6RgoGenqVCNZeCQnFipYKeWhpX7X8A "Perl 6 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 56 bytes ``` {first {$^a.$![1]-$a>=$_},.$!} $!={grep &is-prime,$_..*} ``` [Try it online!](https://tio.run/##DcexCsMgFAXQ3a@4gYdDiY@6ZLM/UlJx0CBEIs8uQfx227OdGuXcZrmhE9zsKUv7otMnMC1vuxsKL0d@rP8ORYvrh8QKnZupkktcyTM/xkyXwDLbJ7oCWrjBOqkxfw "Perl 6 – Try It Online") I feel like there's definitely some improvement to be made here, especially in regards to the `$![1]`. This is an anonymous code block that can be assigned to a variable, as well as a helper function assigned to `$!`. [Answer] # [J](http://jsoftware.com/), ~~26~~ ~~24~~ 22 bytes ``` >:@]^:(>:4&p:-])^:_ 2: ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N/OyiE2zkrDzspErcBKN1YzzipewcjqvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvoKGdZqmQmpZalGlQqaekQHXfwA "J – Try It Online") 0-based ## Explanation: ``` 2: start with the first prime number and ^:( )^:_ while >: the argument is greater or equal to the - difference of 4&p: the next prime number and ] the current prime number >:@] go to the next number ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 58 bytes Same logic as my [JS answer](https://codegolf.stackexchange.com/a/179026/58563), with a non-recursive implementation. ``` f(n,p,q,x){for(p=q=x=2;q-p<n;q%x--||(p=x?p:q,x=q++));q=p;} ``` [Try it online!](https://tio.run/##Hc7BCsIwDAbg@54iTAYtawX1INhVX8TLaN0szKzdpha2vbo1espP@P4QI1tj0sah6Z72BtU4Wddv7@fUMBReBBH53PQD8zroqPcqSF@hCkWUclloGy/@REiHsuRcBe3Vml69s/CoHTIOcwbw6zucAEHDTtGoNByOFKjzBwB@INCwvGaF5cQKe8VcAAqgP@gwoTVb08c0Xd2OSb6/ "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` 2Æn:+ɗ1# ``` [Try it online!](https://tio.run/##y0rNyan8/9/ocFuelfbJ6YbK/62VFA63P2pao@D@/7@hjoKRjoKxjoKJjoKpjoKZjoK5joIFAA "Jelly – Try It Online") ### How it works ``` 2Æn:+ɗ1# Main link. Argument: n 2 Set the return value to 2. 1# Find the first k ≥ 2 such that the link to the left, called with arguments k and n, returns a truthy value. ɗ Dyadic chain: Æn Find the next prime p ≥ k. + Yield k + n. : Perform integer division. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞<ØD¥I@Ïн ``` [Try it online](https://tio.run/##yy9OTMpM/f//Ucc8m8MzXA4t9XQ43H9h7///pgA) or [verify all test cases](https://tio.run/##ASYA2f9vc2FiaWX/OEVOPyIg4oaSICI//@KInjzDmETCpU5Aw4/Qvf8s/w). **Explanation:** ``` ∞ # Get an infinite list in the range [1, ...] < # Decrease it by one to make it in the range [0, ...] Ø # Get for each the (0-indexed) n'th prime: [2,3,5,7,11,...] D # Duplicate this list of primes ¥ # Get all deltas (difference between each pair): [1,2,2,4,2,...] I@ # Check for each if they are larger than or equal to the input # i.e. 4 → [0,0,0,1,0,1,0,1,1,0,...] Ï # Only keep the truthy values of the prime-list # → [23,31,47,53,61,...] н # And keep only the first item (which is output implicitly) # → 23 ``` [Answer] # JavaScript (ES6), ~~61 57 56~~ 54 bytes ``` n=>(g=(q,x=q++)=>q-p<n?q%x--?g(q,x):g(x?q:p=q):p)(p=2) ``` [Try it online!](https://tio.run/##FYtBCoMwEEWvkoWFGWyElq5Sx1zFYE1okUlGSwmIZ4/p6j8e73/cz23T@k5fzfE1F0@FaYBAINdM0rZIg@jUs5VL1tqGv0cTIFsxiQRNQkh0x@LjCqxI3Z6KVV/3UaH@1RR5i8vcLTHA6KDZ@cDaNbsHxmPEcgI "JavaScript (Node.js) – Try It Online") ### Commented ``` n => ( // n = input g = ( // g = recursive function taking: q, // q = prime candidate d = q++ // d = divisor ) => // q - p < n ? // if q - p is not large enough: q % d-- ? // decrement d; if d was not a divisor of q: g(q, d) // try again until it is : // else: g( // do a recursive call to look for the next prime d ? q : p = q // if q was prime, update the previous prime p to q ) // end of recursive call : // else: p // success: return p // NB: we don't know if q is prime or not, but the only // thing that matters at this point is that the next // prime is greater than or equal to q )(p = 2) // initial call to g with p = q = 2 ``` --- # Non-recursive version, 54 bytes By porting back in JS my non-recursive [port in C](https://codegolf.stackexchange.com/a/179031/58563), it turns out that we can reach 54 bytes as well. ``` n=>eval(`for(p=q=x=2;q-p<n;q%x--||(p=x?p:q,x=q++));p`) ``` [Try it online!](https://tio.run/##FYpBDoIwEEWvMhuTTqAkutMyeBUabI2mmZmCIV1w91JX/@W9//W735b1oz/L8go1UmWawu6TmaOsRilToZvLVkd2@VKsPY5my1MfuS@Uuw7R6Yz1/2YguDpgGNveG7QKi/AmKQxJ3oZ7iIYR6wk "JavaScript (Node.js) – Try It Online") ### Performance This piece of code is a good illustration of the utterly bad performance of `eval()`, which prevents JIT compilation: * It takes [35 to 40 sec.](https://tio.run/##FYtBCsIwEEWvMosKCTVCdSGYjl4loSaihJmkLSXQ9uwx3X3ee/9nFzsN4zfOivjtisdC@HSLDcJ4HkXEhBmvOqnYk06nrNS2VZpf8ZHOGVPbSqmjkeWoCRA6DQQ9wu1eR7UwME0c3CXwRxgrmpV2Wbtm9YLkXp9/) to compute \$a(1)\$ to \$a(37)\$ on TIO with the above code. * It takes [~1.5 sec.](https://tio.run/##FYvRCsIgFEB/5T4sUJZB9RDkbv3KZGkU4@p1KwTnt5u9HQ7nvM3XLFN8hVWRf9jqsBLesvNRBGRMeNKswkCad0mpbWs23cOV9wm576XU0a6fSBBK/T8ECEcNBAPC@dKgNTB5WvxsD7N/itGILlORreuyEyTLKOsP) to do the same thing without `eval()`: ``` // 55 bytes n=>{for(p=q=x=2;q-p<n;q%x--||(p=x?p:q,x=q++));return p} ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes ``` ∧⟧ṗˢsĊ-≥?∧Ċt ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HH8kfzlz/cOf30ouIjXbqPOpfaA4WOdJX8/2/xPwoA "Brachylog – Try It Online") ### Explanation ``` ∧⟧ Take a descending range from an unknown integer down to 0 ṗˢ Select only primes in that range sĊ Take a substring of 2 elements in that range; call it Ċ -≥? The subtraction of those 2 elements must be greater than the input ∧Ċt The output is the tail of Ċ ``` [Answer] # [Python 2](https://docs.python.org/2/), 63 bytes ``` n=input() k=P=b=2 while k-b<n: if P%k:b=k P*=k*k;k+=1 print b ``` [Try it online!](https://tio.run/##FcxNCsIwEAbQ/XeKISBoiovGv1Kdlbo2Z4hEGkamoUSsp4/6DvDypwyjunq@Xa5sjKnKSfOrLFcQ9hzY4T2kZyRZh5P2oPQgv5A@sIC8ZbFylIZb5ClpoVB/B@Ic7/QfbVdbOGywxQ57HNB9AQ "Python 2 – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 38 bytes ``` n->i=2;while(nextprime(i+1)-i<n,i++);i ``` [Try it online!](https://tio.run/##DcoxDoAgDEDRqzRONNBEWBHu4gDaRCshJHr7yvKHl9/2znQ0rZBUKHMK8T35KkbKN1rnuxi2Hok3cWwtRtb6dCOQwDsIqwOYl4wpC1CeqUYQUX8 "Pari/GP – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~39~~ 38 bytes ``` ->n,m=2{Prime.find{|i|i-m>=n||!m=i};m} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ9fWqDqgKDM3VS8tMy@luiazJlM31842r6ZGMdc2s9Y6t/a/hqGenqGBpl5qYnJGdU1JTUFpSbFCWnRJbO3/f/kFJZn5ecX/dYsKQIYAAA "Ruby – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` →←ġo<⁰-İp ``` [Try it online!](https://tio.run/##yygtzv7/qG2ioUHuo6ZGPyBz0qO2CUcW5ts8atyge2RDwf//AA "Husk – Try It Online") This is a really interesting question allowing a range of possible approaches (and Husk is a good fit for it; I learned the language for the challenge). The TIO link contains a wrapper to run this function on all inputs from 1 to 10. ## Explanation ``` →←ġo<⁰-İp İp The (infinite) list of primes ġ Group them, putting adjacent primes in the same group if - the difference between them <⁰ is less than the input o (fix for a parser ambiguity that causes this parse to be chosen) → Take the last element of ← the first group ``` Grouping primes that are too close together means that the first break in the groups will be the first point at which the primes are sufficiently far apart, so we simply just need to find the prime just after the break. ## Other potential solutions Here's an 8-byte solution that, sadly, only works with even numbers as input (and thus isn't valid): ``` -⁰LU⁰mṗN N On the infinite list of natural numbers m replace each element with ṗ 0 if composite, or a distinct number if prime U Find the longest prefix with no repeated sublist of length ⁰ equal to the input -⁰ Subtract the input from L the length of that prefix ``` The idea is that when we have two primes that are a distance of (say) 6 apart, there'll be a sequence of five consecutive zeroes in the `mṗN` sequence, which contains two identical sublists of length 4 (the first four zeroes and last four zeroes), but such a repetition cannot happen earlier (because as each prime is mapped to a unique number, any length-4 substrings before the first prime gap > 4 will contain a prime number, and the substring will therefore be unique as it's the only substring which contains that number in that position). Then we just have to subtract the trailing zeroes from the length of the prefix to get our answer. This doesn't work with odd inputs because the sublist of *input* zeroes only occurs once rather than twice, so the code ends up finding the second point at which it occurs rather than the first. [Answer] # Japt, 16 bytes ``` @§Xn_j}aXÄ)©Xj}a ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=QKdYbl9qfWFYxCmpWGp9YQ==&input=OA==) or [test `0-20`](https://ethproductions.github.io/japt/?v=1.4.6&code=QKdYbl9qfWFYxCmpWGp9YQ==&input=MjEKLW0=) ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/182175/edit). Closed 4 years ago. [Improve this question](/posts/182175/edit) I got into code-golfing recently and tried to write the smallest tautogram checker. A *tautogram* is a sentence in which all words start with the same letter, for example: **Flowers flourish from France**. Given a sentence as input, determine whether it is a tautogram. ## Test Cases ``` Flowers flourish from France True This is not a Tautogram False ``` I came up with this python code (because it is my main language): ``` print(True if len(list(set([x.upper()[0] for x in __import__('sys').argv[1:]]))) == 1 else False) ``` Usage: ``` python3 tautogram.py Flowers flourish from France # True python3 tautogram.py This is not a Tautogram # False ``` The sentence may contain commas and periods, but no other special characters, only upper and lower case letters and spaces. Its size is 98 bytes. Is there a smaller solution in any language? [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` l#€нË ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/R/lR05oLew93///vllhcopCWWFSSmZcOpEsyUouKAQ "05AB1E – Try It Online") --- ``` l # Lowercase input. # # Split on spaces. €н # a[0] of each. Ë # All equal? ``` Did this on mobile excuse the no explanation. [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` lambda s:len(set(zip(*s.lower().split())[0]))<2 ``` [Try it online!](https://tio.run/##Pco7DsIwDADQvafwVpuhQh0RrD1BN2AwkJBIaRLZrhBcPnwGpDe@@rRQ8tj84dQSL5cbg@6Sy6jO8BUrbnRI5eEEadCaoiHRcXsm2o@tSswGHvvpNxR8KqtEDeClLDAJ56vrCbruP@cQFT5yMWCYebVyF16@qb0B "Python 2 – Try It Online") Came up with this on mobile. Can probably be golfed more. [Answer] # [Clojure](https://clojure.org/), 80 bytes [Try it online!](https://tio.run/##JcpBCsMwDETRqwh3EQXa3KDbXCJkYYzcuCi2kGxKTu@m6aw@vAlc3k2po2jKlTNgx5gXW7EZwbCEv09WT3@tI3oRPuCJuxeISa1exeVD@gjeCE04VTC4OXDjb93NFxtELk2TbXeIWnaY1edA0/nqXw "Clojure – Try It Online"). TIO doesn't support Clojure's standard String library though, so the first version will throw a "Can't find lower-case" error. ``` (fn[s](use '[clojure.string])(apply =(map first(map lower-case(split s #" "))))) ``` Ungolfed: ``` (defn tautogram? [s] (use '[clojure.string]) (->> (split s #" ") ; Get words (map lower-case) (map first) ; Get first letter of each word (apply =))) ; And make sure they're all the same ``` I made a version that avoids the import: ``` (fn [s](apply =(map #(if(<(-(int %)32)65)(int %)(-(int %) 32))(map first(take-nth 2(partition-by #(= %\ )s)))))) ; ----- (defn tautogram? [s] (->> s (partition-by #(= % \ )) ; Split into words (take-nth 2) ; Remove spaces (map first) ; Get first letter ; Convert to uppercased letter code (map #(if (< (- (int %) 32) 65) ; If attempting to uppercase puts the letter out of range, (int %) ; Go with the current code (- (int %) 32))) ; Else go with the uppercased code (apply =))) ; And check if they're all equal ``` But it's **112 Bytes**. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~57~~ ~~50~~ 41 bytes ``` (-split$args|% s*g 0 1|sort -u).count-eq1 ``` [Try it online!](https://tio.run/##HctRCoAgDADQq@yjsAKjLuE9RLSE1WxT@vHuC3r/r9AbWc6IqDpZKZjr4PmQPoIsB2ywdyGuYNu8Bmp3tfHZVdU4/CckpMZZTkhMFzj2d4jmAw "PowerShell – Try It Online") Takes input and `split`s it on whitespace. Loops through each word, and grabs the first letter by taking the `s`ubstrin`g` starting at position `0` and going for `1` character. Then `sort`s the letters (case-insensitive by default) with the `-u`nique flag to pull out only one copy of each letter, and verifies the `count` of those names are `-eq`ual to `1`. Output is implicit. *-9 bytes thanks to mazzy.* [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 5 bytes ``` #€¬uË ``` [Try it online!](https://tio.run/##MzBNTDJM/V9W@V/5UdOaQ2tKD3f/1/kfreSWk1@eWlSskJaTX1qUWZyhkFaUn6vgVpSYl5yqpKMUkpFZrABEefklCokKIYmlJfnpRYm5SrEA "05AB1E (legacy) – Try It Online") ``` # // split on spaces €¬ // get the first letter of each word uË // check if they're the same (uppercase) letter ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ḷṇ₁hᵛ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WU9B51rFBKS8wpBrJrH@7qrH24dcL/hzu2P9zZ/qipMePh1tn//0crueXkl6cWFSuk5eSXFmUWZyikFeXnKrgVJeYlpyrpKIVkZBYrAFFefolCokJIYmlJfnpRYq5SLAA "Brachylog – Try It Online") ``` The input ḷ lowercased ṇ₁ and split on spaces hᵛ is a list of elements which all start with the same thing. ``` [Answer] # [Haskell](https://www.haskell.org/), 71 bytes ``` f s|c<-fromEnum.head<$>words s=all(`elem`[-32,0,32]).zipWith(-)c$tail c ``` [Try it online!](https://tio.run/##XZBda8IwGIXv@ysORViCrQy9E@vYmAVhsIsJu3CCoaY2LE1KklI2/O9d0orIXnKRc/K8X6mY/eZS9n0JeylWaWl0vVFtPas4O60m606bk4XNmJTkyCWvj/t0MU8ek8X8QGe/ovkUriIpLSaOCYmidz8Nx45bhwzkwxmhzgletJY0ipy3LZZL7ANwuOoM@wjXIHEudceNRSl1a4StECZCbpgqeJxgZ1pOkzt@VwkLf5R2YNix1umzYbVHcyYtpwN6iCJb6e4h9B5mS9cYZ7v6RKgmgW4d9eP4O6ZTxF8q5Ho0DjKAIGV4pbf@twg8nrI71BcbXTJ4DbN20DQesruKGz66FwxVkWVDki8SbH6K/7e5QDuf1gnLg/Rg/rx927zGUVQzocJ223cQOqoMTev8lpihVVIobv2tZg3GlScYvr//Aw "Haskell – Try It Online") --- # [Haskell](https://www.haskell.org/), ~~61~~ 58 bytes (using `Data.Char.toLower`) * Saved three bytes thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi). ``` import Data.Char (all=<<(==).head).(toLower.head<$>).words ``` [Try it online!](https://tio.run/##XZDfasMgGMXvfYpDKExplgcodWNbFygUdrHedb2Q1TQyo0ENYdB3z9SUUvbhhef4@/7ZCv8jtZ4m1fXWBWxEENVbKxxpOBVa8/Wacs6qVooTq2iwOztKl@V68cSq0bqTn8JvL7GXPoCDfganzLnEq7WaERKi7bFa4ZCA41VzHAiuQYtap6oejbaDU75F42yH2gnzLYsSezdIVt7x@1Z5xGNsgMBeDMGenegiWgvtJcvokRDf2vEh9c6zPT5hnu3qU2X6EnYILI4T71guUXyZlBvRIskEgjbpld363yLxeOZ3aCw2uzR7vfA@a1bk7LGVTs7uBbkqOM9JsUiy5an43@YCG2LaqLxMMoL1y3b3vikI6YQyabvtByibFUc/hLglKgxGKyN9vHWix7zyAvn7pz8 "Haskell – Try It Online") [Answer] # Perl 5 (`-p`), 20 bytes ``` $_=!/^(.).* (?!\1)/i ``` [TIO](https://tio.run/##DcKxCoAgEADQva@4oEGDjIbGaOsLGqOQsBTMk9Po77t6vGjI98zVNpTtKpRUNYixXDrZOubJ42MoweHxJpcsHIQXTKTDborZugT/gBk0zPrOeJK@XozZYUjcRP8B) following comments in case bad punctuation (31 bytes) ``` $_=!/^\W*+(.).*(?=\b\w)(?!\1)/i ``` [31 bytes](https://tio.run/##K0gtyjH9/18l3lZRPy4mXEtbQ09TT0vD3jYmKaZcU8NeMcZQUz/z/3@3nPzy1KJihbSc/NKizOIMhbSi/FwFt6LEvORUrpCMzGIFIMrLL1FIVAhJLC3JTy9KzOVSgOnSwabtX35BSWZ@XvF/3YIcAA) otherwise there's another approach, also with 31 bytes: ``` $h{ord()%32}++for/\w+/g;$_=2>%h ``` [31 bytes other](https://tio.run/##K0gtyjH9n1upmmH9XyWjOr8oRUNT1dioVls7Lb9IP6ZcWz/dWiXe1shONeP/f7ec/PLUomKFtJz80qLM4gyFtKL8XAW3osS85FSukIzMYgUgyssvUUhUCEksLclPL0rM5VKA6dLBpu1ffkFJZn5e8X/dghwA) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 54 bytes ``` s=>!s.match(/\b\w+/g).some(p=s=>p-(p=Buffer(s)[0]&31)) ``` [Try it online!](https://tio.run/##jco9EsIgEEDh3lNgCgfGCdGxxsIiHsJYIC75GWCZ3cQcHzOewOoV75vsx7KjMc91wjcUbwqb6551tLMbZNO9uvXY9EozRpDZbDPXW2@L90CS1eP0PFzOShWHiTGADthLL6s24ArEwgdcaORBeMIoWrLJQaXU7i9@J4AfL18 "JavaScript (Node.js) – Try It Online") Or [**47 bytes**](https://tio.run/##jcoxDsIwDEDRnVOEDigZGoGYw8BQDoGQGgUbgtw4sls4fqg4AdOXvt4rvqMmyXXuC9@hYWgaTlv1WinPoxm98gS2hvXWfu15QQSx6q772@54cK4lLsoEnvhh0XYD8QdEDRIvkvVpUHgyg8SSoHNu8xe/CMCPty8) if each word (but the first) is guaranteed to be preceded by a space. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-¡`](https://codegolf.meta.stackexchange.com/a/14339/), 5 bytes ``` ¸mÎro ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LaE=&code=uG3Ocm8=&input=IkZsb3dlcnMgZmxvdXJpc2ggZnJvbSBGcmFuY2Ui) ``` ¸mÎro :Implicit input of string ¸ :Split on spaces m :Map Î : Get first character r :Reduce by o : Keeping the characters that appear in both, case-insensitive :Implicit output as boolean ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 41 bytes ``` n=>n.Split().GroupBy(c=>c[0]|32).Single() ``` Throws an exception if false, nothing if true. [Try it online!](https://tio.run/##PYxBS8QwFITPza947GUTxCJ6rC0ouCJ4cgse1MMjm2wD2Zfy8qIs6m@vpQVhGBi@mbH50uYw3VkJiW6zcKBj59uJ2o7q/RiDaFM/cirj/VnbtrNvVx8/N9em3s/F6LSZGuUTO7SD/kSGQGOR2eGJ6heHhz490GG@WK@277Q1RlXC529VVa8cxOllcrGBtoONafyaTbPA50BOCxdnGlX9WhQ7/A8X5jHmFU67mL4cZ/AxFQ55AM/pBDtGsk71Q8gwi5IAQo9F0pHx9Ac "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 19 bytes ``` {[eq] m:g/<<./}o&lc ``` [Try it online!](https://tio.run/##DcJBCoMwEAXQfU7xF8W0UHTXRbVbT@CuFBkko0LitBOliHj26ON9nfpHCisyxittb/f7IDz7oqryYpfMd6k0kVbw9dLewKLG1l7@TiPYy6JjHMAqAbXS1Dl7N7YZxojzJDMIDS2z9ErBlukA "Perl 6 – Try It Online") [Answer] # Java, (36 bytes) ``` s->!s.matches("(?i)(.).* (?!\\1).*") ``` [TIO](https://tio.run/##jU/LasNADLz7KxSf1oUs9Ow2ueVWKCS3pgd1vbbl7sOstCml5NvdJTWlxwoxEpphGE14wW2cbZi694X8HJPAVG46Cznd52CEYtDPyXZkUGxbVXN@c2TAOGSGJ6QAX1UFpVaCBaWMS6QOfKEVHCVRGF5eAdPA0BQ9rHX8ZLFexyx6LhpxRd1rsSwK6oOLHzYx9C7mRDxCn6KHQ8JgbF1smvZ/PqeRGEqHKIBwwixxSOj/WFxveIM1/e/DDz/hd9A/LrzdbVh7FDNaVrXaU6N0o@9A7Tfn833Z6mZpr8s3) ]
[Question] [ Create quine variant such that the program prints its first character, then the first two, then three and so on until the whole program is printed. ## Example Suppose your code is `@@@@@2` in some language. Then the output should be ``` @ @@ @@@ @@@@ @@@@@ @@@@@2 ``` in that order, each line separated by a newline. The winner is the shortest quine like this. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` “;⁾vṾÄY”vṾ ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxzrR437yh7u3He4JfJRw1wQ6/9/AA "Jelly – Try It Online") ### How it works ``` “;⁾vṾÄY”vṾ Main link. No arguments. “;⁾vṾÄY” Set the return value to the string ';⁾vṾÄY'. Ṿ Uneval; yield a string representation of the string, i.e., '“;⁾vṾÄY”'. v Dyadic eval; execute the string to the left, passing the string to the right as argument. ⁾vṾ Literal; yield 'vṾ'. ; Concatenate the argument ('“;⁾vṾÄY”') and 'vṾ', yielding '“;⁾vṾÄY”vṾ'. Ä Accumulate; take the cumulative sum. Since string addition is concatenation in Python (and Jelly doesn't do type checks), this yields all prefixes of the string. Y Join the prefixes, separated by linefeeds. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 18 bytes ``` G:""S+s"G:\"\"S+s" ``` [Try it online!](https://tio.run/##yygtzv7/391KSSlYu1jJ3SpGKQbM@v8fAA "Husk – Try It Online") ## Explanation An extension of the [standard quine](https://codegolf.stackexchange.com/a/128302/48198) `S+s"S+s"`. To get all the prefixes we cannot use `ḣ` (`heads`), because `ḣS+s"ḣS+s"` would `show "ḣS+s"` which results in `"\7715S+s"`: ``` ḣS+s"ḣS+s" ``` [Try it online!](https://tio.run/##yygtzv7//@GOxcHaxUpQ6v9/AA "Husk – Try It Online") So we need to re-implement `heads` without using any unicode, this can be done by `scanl snoc ""` (`snoc` is just a flippped version of `(:)`), ie. `G:""` which is ASCII. [Answer] # Oracle SQL, 154 bytes ``` select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155; ``` Test in SQL Plus ``` SQL> set lines 160 pages 0 SQL> select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155; s se sel sele selec select select select s select su select sub select subs select subst select substr select substr( select substr(r select substr(rp select substr(rpa select substr(rpad select substr(rpad( select substr(rpad(1 select substr(rpad(1, select substr(rpad(1,2 select substr(rpad(1,24 select substr(rpad(1,240 select substr(rpad(1,240, select substr(rpad(1,240,' select substr(rpad(1,240,'| select substr(rpad(1,240,'|| select substr(rpad(1,240,'||c select substr(rpad(1,240,'||ch select substr(rpad(1,240,'||chr select substr(rpad(1,240,'||chr( select substr(rpad(1,240,'||chr(3 select substr(rpad(1,240,'||chr(39 select substr(rpad(1,240,'||chr(39) select substr(rpad(1,240,'||chr(39)) select substr(rpad(1,240,'||chr(39)), select substr(rpad(1,240,'||chr(39)),5 select substr(rpad(1,240,'||chr(39)),53 select substr(rpad(1,240,'||chr(39)),53, select substr(rpad(1,240,'||chr(39)),53,l select substr(rpad(1,240,'||chr(39)),53,le select substr(rpad(1,240,'||chr(39)),53,lev select substr(rpad(1,240,'||chr(39)),53,leve select substr(rpad(1,240,'||chr(39)),53,level select substr(rpad(1,240,'||chr(39)),53,level) select substr(rpad(1,240,'||chr(39)),53,level)f select substr(rpad(1,240,'||chr(39)),53,level)fr select substr(rpad(1,240,'||chr(39)),53,level)fro select substr(rpad(1,240,'||chr(39)),53,level)from select substr(rpad(1,240,'||chr(39)),53,level)from select substr(rpad(1,240,'||chr(39)),53,level)from d select substr(rpad(1,240,'||chr(39)),53,level)from du select substr(rpad(1,240,'||chr(39)),53,level)from dua select substr(rpad(1,240,'||chr(39)),53,level)from dual select substr(rpad(1,240,'||chr(39)),53,level)from dual select substr(rpad(1,240,'||chr(39)),53,level)from dual c select substr(rpad(1,240,'||chr(39)),53,level)from dual co select substr(rpad(1,240,'||chr(39)),53,level)from dual con select substr(rpad(1,240,'||chr(39)),53,level)from dual conn select substr(rpad(1,240,'||chr(39)),53,level)from dual conne select substr(rpad(1,240,'||chr(39)),53,level)from dual connec select substr(rpad(1,240,'||chr(39)),53,level)from dual connect select substr(rpad(1,240,'||chr(39)),53,level)from dual connect select substr(rpad(1,240,'||chr(39)),53,level)from dual connect b select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by l select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by le select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by lev select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by leve select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level< select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<1 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<15 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155; select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;s select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;se select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;sel select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;sele select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;selec select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select s select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select su select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select sub select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select subs select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select subst select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr( select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(r select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rp select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpa select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad( select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1, select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,2 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,24 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240, select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,' select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'| select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'|| select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||c select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||ch select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr( select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(3 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39) select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)) select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)), select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),5 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53, select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,l select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,le select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,lev select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,leve select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level) select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)f select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)fr select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)fro select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from d select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from du select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dua select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual c select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual co select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual con select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual conn select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual conne select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connec select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect b select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by l select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by le select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by lev select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by leve select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level< select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<1 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<15 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155 select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155;select substr(rpad(1,240,'||chr(39)),53,level)from dual connect by level<155; 154 rows selected. ``` [Answer] # [Haskell](https://www.haskell.org/), ~~100~~ 98 bytes -2 bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) ``` main=mapM g[1..98];g n=putStrLn$take n$id<>show$"main=mapM g[1..98];g n=putStrLn$take n$id<>show$" ``` [Try it online!](https://tio.run/##lcuxCsIwFAXQX7lIhnZoQOhQMe2iYAeLg6M4PEhsQ5OXkEbEr4/f4NnPQttqnCvWx5AyzpRJToGD1agqNdQ10DS4sfuCjdFG4xUSLuMJCp1siyfLvac4YX7spTx0z@MM7uM733O6ssi0GrCwWg3bEj5i93co5Qc "Haskell – Try It Online") Surprisingly ~~2~~ 4 bytes shorter than the obvious port of my Husk answer: [`main=mapM putStrLn$scanl((.pure).(++))[]$id<>show$"main=mapM putStrLn$scanl((.pure).(++))[]$id<>show$"`](https://tio.run/##y0gszk7NyfmfmVuQX1Si4JJYkqjnm5@Xn5mioKFhY6ep@T83MTPPNjexwFehoLQkuKTIJ0@lODkxL0dDQ6@gtChVU09DW1tTMzpWJTPFxq44I79cRYkMLf//AwA "Haskell – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 54 bytes ``` exec(a:="s=''\nfor i in'exec(a:=%r)'%a:print(s:=s+i)") ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVkj0cpWqdhWXT0mLy2/SCFTITNPHSauWqSprppoVVCUmVeiUWxlW6ydqamk@f8/AA "Python 3.8 (pre-release) – Try It Online") I also have 2 variants of the same length : ``` exec(a:="s=''\nfor i in'exec(a:=%r)'%a:s+=i;print(s)") ``` ``` exec(a:="s='';[print(s:=s+i)for i in'exec(a:=%r)'%a]") ``` ## How it works : It is the standard "exec" quine in python: `exec(a:="print('exec(a:=%r)'%a)")` in which I added an iteration. This base quine is pretty usefull because it doesn't require to write all the added byte twice unlike the shorter `a='a=%r;print(a%%a)';print(a%a)` quine [Answer] # JavaScript, 47 bytes This can probably be improved. ## Revisions 20 bytes have been saved so far between 3 versions! ### Revision 5 There's been a lot of bytes saved with this revision: * Don't assign a single-use variable for the quine to save 2 bytes * Use templated strings for the quine to save a byte * Use a single parameter (`_`) instead of no parameters (`()`) to save a byte These three changes get it down to 47 bytes!! ``` (s=_=>{for(c of `(s=${s})()`)alert(name+=c)})() ``` ### Revision 4 On most pages, it seems that `window.name` is an empty string by default. We can take advantage of this to get [53 bytes](https://mothereff.in/byte-counter#%28s%3D%28%29%3D%3E%7Bq%3D%22%28s%3D%22%2Bs%2B%22%29%28%29%22%3Bfor%28c%20of%20q%29alert%28name%2B%3Dc%29%7D%29%28%29)! ``` (s=()=>{q="(s="+s+")()";for(c of q)alert(name+=c)})() ``` Unfortunately this is not the case for the snippet page, but try running it with the developer tools! ### Revision 3 We can save 2 bytes, down to [55 bytes](https://mothereff.in/byte-counter#%28s%3D%28%29%3D%3E%7Bq%3D%22%28s%3D%22%2Bs%2B%22%29%28%29%22%2Ch%3D%22%22%3Bfor%28c%20of%20q%29alert%28h%2B%3Dc%29%7D%29%28%29), by combining the two statements in the loop into one: ``` (s=()=>{q="(s="+s+")()",h="";for(c of q)alert(h+=c)})() ``` ### Revision 2 We can get down to [57 bytes](https://mothereff.in/byte-counter#%28s%3D%28%29%3D%3E%7Bq%3D%22%28s%3D%22%2Bs%2B%22%29%28%29%22%2Ch%3D%22%22%3Bfor%28c%20of%20q%29h%2B%3Dc%2Calert%28h%29%7D%29%28%29) by using an EcmaScript 2015 arrow function: ``` (s=()=>{q="(s="+s+")()",h="";for(c of q)h+=c,alert(h)})() ``` ### Revision 1 We can also get down to [61 bytes](https://mothereff.in/byte-counter#%28function%20s%28%29%7Bq%3D%22%28%22%2Bs%2B%22%29%28%29%22%2Ch%3D%22%22%3Bfor%28c%20of%20q%29h%2B%3Dc%2Calert%28h%29%7D%29%28%29) by using `alert` instead of `console.log`, if you consider that to be printing: ``` (function s(){q="("+s+")()",h="";for(c of q)h+=c,alert(h)})() ``` ### Initial Version Initially, this script was at [67 bytes](https://mothereff.in/byte-counter#%28function%20s%28%29%7Bq%3D%22%28%22%2Bs%2B%22%29%28%29%22%2Ch%3D%22%22%3Bfor%28c%20of%20q%29h%2B%3Dc%2Cconsole.log%28h%29%7D%29%28%29): ``` (function s(){q="("+s+")()",h="";for(c of q)h+=c,console.log(h)})() ``` ## Explanation Here's the prettified code: ``` (function func() { quine = "(" + func + ")();"; substr = ""; for (char of quine) { substr += char; console.log(substr); } })(); ``` We start with a standard quine, then we define `substr`. We loop over each character of the quine, add it to `substr`, then output that. [Answer] # Excel, 182 bytes ``` =LEFT(SUBSTITUTE("=LEFT(SUBSTITUTE(@,CHAR(64),CHAR(34)&@&CHAR(34)),ROW(1:182))",CHAR(64),CHAR(34)&"=LEFT(SUBSTITUTE(@,CHAR(64),CHAR(34)&@&CHAR(34)),ROW(1:182))"&CHAR(34)),ROW(1:182)) ``` Added `LEFT( ~ , ROW(1:182))` to standard quine. ## Cheesy version, 32 bytes ``` =LEFT(FORMULATEXT(A1),ROW(1:32)) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `Dj`, 40 bits, 5 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` `I¦`I¦ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEaj0iLCIiLCJgScKmYEnCpiIsIiIsIiJd) ## Explained ``` `I¦`I¦ ¦ # Prefixes of `I¦` # the string "I¦" I # with `I¦` prepended # joined on newlines by the j flag ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` “Ṿ;¹¹ƤY”Ṿ;¹¹ƤY ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/dZH9p5aOexJZGPGuYi8f7/BwA "Jelly – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` 0"D34çýη»"D34çýη» ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fQMnF2OTw8sN7z20/tBuZ/f8/AA "05AB1E – Try It Online") [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 31 bytes ``` "2+,a<_@#-2$,k-'p11+1:g11+4+ff ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XMtLWSbSJd1DWNVLRydaVVy8wNNQ2tEoHkibaaWn//wMA "Befunge-98 (PyFunge) – Try It Online") Modification of a wrapping string literal quine that repeats printing prefixes until it prints everything. ### Explanation: ``` " Wrapping string literal that pushes the code backwards 2+, Add 2 to the space and print as " ,a< Reverse direction and print a newline " Push the code again, but the right way this time +4+ff Push a quote g11 Get the counter at (1,1) This is initially 32 (space) p11+1: Increment and store back at (1,1) -' Subtract 31 from the counter ,k Print counter many times plus one 2$ Swap and check if the next number on the stack is 2 2 _@# If so, end the program as this is the leftover 2 ,a Print a newline and repeat ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 44 bytes ``` &($f={&{1..44|%{"&(`$f={$f})"|% s*g 0 $_}}}) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f9fTUMlzbZardpQT8/EpEa1WklNIwEkopJWq6lUo6pQrJWuYKCgEl9bW6v5/z8A "PowerShell Core – Try It Online") Idea borrowed from [this answer](https://codegolf.stackexchange.com/a/176496/97729) by [bb216b3acfd8f72cbc8f899d4d6963](https://codegolf.stackexchange.com/users/46517/bb216b3acfd8f72cbc8f899d4d6963), thank you! [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` BõîQi"BõîQi ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=QvXuUWkiQvXuUWk) ``` BõîQi"BõîQi B :11 õ :Range [1,B] î :For each mould the following Q : Quotation mark i : Prepend "BõîQi : String literal :Implicit output joined with newlines ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `N`, 12 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` "DṘs+ƒ"DṘs+ƒ ``` #### Explanation ``` "DṘs+ƒ"DṘs+ƒ # Full program "DṘs+ƒ" # Push the string "DṘs+ƒ" D # Duplicate it Ṙ # Get its representation # (surround by quotes) s+ # Prepend this to the string ƒ # Get the new string's prefixes # Implicit output, joined by newlines ``` #### Screenshot [![Screenshot](https://i.stack.imgur.com/4LinYm.png)](https://i.stack.imgur.com/4LinY.png) (click to enlarge) [Answer] # [Julia 0.6](http://julialang.org/), 91 bytes ``` Q="1:91.|>x->println(\"Q=\$(repr(Q));\$Q\"[1:x])";1:91.|>x->println("Q=$(repr(Q));$Q"[1:x]) ``` [Try it online!](https://tio.run/##yyrNyUw0@/8/0FbJ0MrSUK/GrkLXrqAoM68kJ08jRinQNkZFoyi1oEgjUFPTOkYlMEYp2tCqIlZTyRpTOVA1kmKVQKjS//8B "Julia 0.6 – Try It Online") Adapted from the [Julia quine from Rosetta Code](https://rosettacode.org/wiki/Quine#Julia), which is based on `repr` Requires at least Julia 0.6, but includes syntax that is deprecated in 0.7 and removed in 1.0 There exist shorter quines in Julia ([32 and 35-byte quines based on `@show`](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/178441#178441), [37-byte quine based on `eval`](https://codegolf.stackexchange.com/a/65802/114865)), and it might be possible to adapt either of these methods. [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes ``` s,f="",'s,f="",%r\nfor i in f%%f:s+=i;print s' for i in f%f:s+=i;print s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v1gnzVZJSUcdSqsWxeSl5RcpZCpk5imkqaqmWRVr22ZaFxRl5pUoFKtzIcmhSv3/DwA "Python 2 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 bytes ``` j._jN*2]"j._jN*2] ``` [Try it online!](https://tio.run/##K6gsyfj/P0svPstPyyhWCcb4/x8A "Pyth – Try It Online") [Answer] # [Pushy](https://github.com/FTcode/Pushy), ~~28~~ ~~26~~ 24 bytes ``` `I"Ov:L69w69`96w96L:vO"I ``` **[Try it online!](https://tio.run/##Kygtzqj8/z/BU8m/zMrHzLLczDLB0qzc0szHqsxfyfP/fwA "Pushy – Try It Online")** ## Explanation: ``` `I"Ov:L69w79` \ String literal: push this to stack 96 \ Append backtick: I"Ov:L69w69` w \ Mirror: I"Ov:L69w69`96w96L:vO"I 96 \ Append backtick: I"Ov:L69w69`96w96L:vO"I` \ We now have the source code, backwards, on the main stack. L: \ len(stack) times do: v \ Move last character to auxiliary stack O"I \ Print the auxiliary stack ``` [Answer] # Java 10, 202 bytes ``` v->{var s="v->{var s=%c%s%1$c;s=s.format(s,34,s);for(int i=0;++i<s.length();)System.out.println(s.substring(0,i));}";s=s.format(s,34,s);for(int i=0;++i<s.length();)System.out.println(s.substring(0,i));} ``` [Try it online.](https://tio.run/##tZDBCsIwDIbve4ogDlqcRdFbnW/gLgMv4iHWOatdJ0tXkLFnn50KPoGXJH/4Sfi/G3qc3873QRkkgh1q20UA2rqiuaAqIBslgK/1GRTbj81zGXZ9FAo5dFpBBhZSGPx823lsgNLJb4xVTPFyqiSlJC51U6FjlKzWCXEZJAuvQKcLOZvpDQlT2NJdGZc8f5IrKlG3TjyaYDKWkaD2RC6oki0SzbnsJ/85O8gx3aM9mZDuG/KNoAqAWP72Ho6A/EPHCsVsa8wXTD@8AA) **Explanation:** [quine](/questions/tagged/quine "show questions tagged 'quine'") part of the explanation: * `var s` contains the unformatted source code. * `%s` is used to input this String into itself with `s.format(...)`. * `%c`, `%1$c`, and the `34` are used to format the double quotes * `s.format(s,34,s)` puts it all together Challenge part of the explanation: * `for(int i=0;++i<s.length();)` then loops `i` in the range [1, formatted\_code\_length) * `System.out.println(...)` prints the String with trailing newlines * `s.substring(0,i)` gets the substring of the formatted code in the character-range `[0,i)`. [Answer] # [Japt](https://github.com/ETHproductions/japt) `-R`, 11 bytes ``` CÇîQi"CÇîQi ``` [Try it online!](https://tio.run/##y0osKPn/3/lw@@F1gZlKUPr/f90gAA "Japt – Try It Online") If the leading newline isn't acceptable, here's a ~~15~~ 13-byte alternative: ``` Dõ_îQi"Dõ_îQi ``` [Try it online!](https://tio.run/##y0osKPn/3@Xw1vjD6wIzlWCM//91gwA) [Answer] # [Julia](http://julialang.org/), 63 bytes ``` (a=:([println(("(a=:($(a)))|>eval")[1:x]) for x = 1:63]))|>eval ``` [Try it online!](https://tio.run/##yyrNyUw0@/9fI9HWSiO6oCgzryQnT0NDCcxX0UjU1NSssUstS8xR0ow2tKqI1VRIyy9SqFCwVTC0MjOOhcn@/w8A "Julia 0.6 – Try It Online") The spaces and parenthesis are necessary because the code is stored in an `Expr` (AST), which will add them when interpolated. based on this quine: `(a=:(print("(a=:($(a)))|>eval")))|>eval` [Try it online!](https://tio.run/##yyrNyUw0rPj/XyPR1kqjoCgzr0RDCcxW0UjU1NSssUstS8xRgrP@/wcA "Julia 1.0 – Try It Online") ]
[Question] [ *Note, when I say "negate", I mean replace all ones with zeroes (i.e. a bitwise negation)* The Thue-Morse sequence goes like 01101001 The way you generate it is: Start by taking 0. Negate what is left and append it to the end. So, take `0`. Negate it and add that to the end - `01` Then take that and negate it and add that to the end - `0110` And so on. Another interesting property of this is that distance between zeros creates an "irrational" and non-repeating string. So: ``` 0110100110010110 |__|_||__||_|__| 2 1 0 2 01 2 <------------Print this! ``` **Can you write a program that, when input n, will output the first n digits of the string to printed?** This is code golf, so shortest number of bytes wins! [Answer] # Python ~~3~~ 2, ~~104~~ ~~92~~ ~~88~~ 84 bytes This is a pretty rudimentary solution based on building a ternary Thue-Morse sequence from scratch. This sequence is identical to the one being asked, though someone else will have to write a more thorough explanation of why that is. At any rate, this sequence is only a trivial modification of this one, [A036580](http://oeis.org/A036580). **Edit:** Changed the for loop into a list comprehension, changed from a function to a program, and changed the whole thing to Python 2. Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for golfing help. ``` n=input() s="2" while len(s)<n:s="".join(`[1,20,210][int(i)]`for i in s) print s[:n] ``` [Answer] # Julia, ~~56~~ 50 bytes ``` n->(m=1;[m=[m;1-m]for _=0:n];diff(find(m))[1:n]-1) ``` This is an anonymous function that accepts an integer and returns an integer array. To call it, assign it to a variable. We generate the bit-swapped Thue-Morse sequence by starting with an integer `m = 1`, then we append `1-m` to `m` as an array `n+1` times, where `n` is the input. This generates more terms than we need. We then locate the ones using `find(m)`, get the difference between consecutive values using `diff`, and subtract 1 elementwise. Taking the first `n` terms of the resulting array gives us what we want. Saved 6 bytes and fixed an issue thanks to Dennis! [Answer] ## PowerShell, 102 bytes ``` filter x($a){2*$a+([convert]::toString($a,2)-replace0).Length%2} 0..($args[0]-1)|%{(x($_+1))-(x $_)-1} ``` A little bit of a different way of computing. PowerShell doesn't have an easy way to "get all indices in this array where the value at that index equals *such-and-such*", so we need to get slightly creative. Here we're using [A001969](http://oeis.org/A001969), the "numbers with an even number of 1s in their binary expansion", which *completely coincidentally* gives the indices of the 0s in the Thue-Morse sequence. ;-) The `filter` calculates that number. For example, `x 4` would give `9`. We then simply loop from `0` to our input `$args[0]`, subtracting `1` because we're zero-indexed, and each iteration of the loop print out the difference between the *next* number and the current number. Output is added onto the pipeline and implicitly output with newlines. ### Example ``` PS C:\Tools\Scripts\golfing> .\print-the-difference-in-the-thue-morse.ps1 6 2 1 0 2 0 1 ``` [Answer] ## Haskell, 42 bytes ``` l=2:(([[0..2],[0,2],[1]]!!)=<<l) (`take`l) ``` Usage example: `(`take`l) 7` -> `[2,1,0,2,0,1,2]`. It's an implementation of `a036585_list` from [A036585](https://oeis.org/A036585) shifted down to `0`, `1` and `2`. Golfing: `concat (map f l)` is `f =<< l` and `f 0=[0,1,2]; f 1=[0,2]; f 2=[1]` is `([[0..2],[0,2],[1]]!!)`. Note: `l` is the infinite sequence. It takes 10 bytes or about 25% to implement the take-first-`n`-elements feature. [Answer] # Mathematica, ~~79~~ ~~68~~ 70 bytes ``` (Differences[Join@@Position[Nest[#~Join~(1-#)&,{0},#+2],0]]-1)[[;;#]]& ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~14~~ 11 bytes ``` Q:qB!Xs2\dQ ``` [**Try it online!**](http://matl.tryitonline.net/#code=UTpxQiFYczJcZFE&input=Nw) As pointed out by @TimmyD in [his answer](https://codegolf.stackexchange.com/a/75543/36398), the desired sequence is given by the consecutive differences of [A001969](http://oeis.org/A001969). The latter can in turn be obtained as the Thue-Morse sequence plus 2\**n*. Therefore the desired sequence is given by the *(consecutive differences of the Thue-Morse sequence) plus one*. On the other hand, the Thue-Morse sequence [can be obtained](http://oeis.org/A010060) as the number of ones in the binary representation of *n*, starting from *n*=0. ``` Q:q % take input n implicitly and generate row vector [0,1,...,n] B! % 2D array where columns are the binary representations of those numbers Xs % sum of each column. Gives a row vector of n+1 elements 2\ % parity of each sum d % consecutive differences. Gives a row vector of n elements Q % increase by 1. Display implicitly ``` [Answer] # Jelly, 9 bytes ``` ;¬$‘¡TI’ḣ ``` [Try it online!](http://jelly.tryitonline.net/#code=O8KsJOKAmMKhVEnigJnhuKM&input=&args=Nw) ### How it works ``` ;¬$‘¡TI’ḣ Main link. Argument: n $ Create a monadic chain that does the following to argument A (list). ¬ Negate all items of A. ; Concatenate A with the result. ‘¡ Execute that chain n + 1 times, with initial argument n. T Get all indices of truthy elements (n or 1). I Compute the differences of successive, truthy indices. ’ Subtract 1 from each difference. ḣ Keep the first n results. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes Code: ``` ÎFDSÈJJ}¥1+¹£ ``` Explanation: ``` Î # Push 0 and input F } # Do the following n times DS # Duplicate and split È # Check if even JJ # Join the list then join the stack ¥1+ # Compute the differences and add 1 ¹£ # Return the [0:input] element ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w45GRFPDiEpKfcKlMSvCucKj&input=Nw) [Answer] ## Python, 69 bytes ``` t=lambda n:n and n%2^t(n/2) lambda n:[1+t(i+1)-t(i)for i in range(n)] ``` The `i`th term of this sequence is `1+t(i+1)-t(i)`, where `t` is the Thue-Morse function. The code implements it recursively, which is shorter than ``` t=lambda n:bin(n).count('1')%2 ``` [Answer] # Mathematica, 65 bytes ``` SubstitutionSystem[{"0"->"012","1"->"02","2"->"1"},"0",#][[;;#]]& ``` Beats my other answer, but doesn't beat the extra-~~spicy~~golfed version. Now normally I stick my code in quotes, then pull it out because Mathematica loves adding spaces to your code (which do nothing) but it never messes with strings, but that doesn't work for code that itself has quotes... Whatever, I'm just using the magic builtin for this. Output is a string. [Answer] # Mathematica, 58 bytes ``` Differences[Nest[Join[#,1-#]&,{0},#]~Position~0][[;;#]]-1& ``` [Answer] # Perl, 45 + 2 = 47 bytes ``` $_=2;s/./(1,20,210)[$&]/ge until/.{@F}/;say$& ``` Requires the `-p` and `-a` flag: ``` $ perl -pa morse-seq.pl <<< 22 2102012101202102012021 ``` [Port of @Sherlock9 answer](https://codegolf.stackexchange.com/a/75532/48657) Saved 9 bytes thanks to Ton [Answer] ## JavaScript (ES6), ~~73~~ 67 bytes ``` f=(n,s="2")=>s[n]?s.slice(0,n):f(n,s.replace(/./g,c=>[1,20,210][c])) ``` Port of @Sherlock9's answer. edit: Saved 6 bytes thanks to @WashingtonGuedes. [Answer] ## CJam (19 bytes) ``` 1ri){2b:^}%2ew::-f- ``` [Online demo](http://cjam.aditsu.net/#code=1ri)%7B2b%3A%5E%7D%252ew%3A%3A-f-&input=16) This uses the approach of incrementing the successive differences between elements of the Thue-Morse sequence. --- My shortest approach using rewriting rules is 21 bytes: ``` ri_2a{{_*5*)3b~}%}@*< ``` (Warning: slow). This encodes the rewriting rules ``` 0 -> 1 1 -> 20 2 -> 210 ``` as ``` x -> (5*x*x + 1) in base 3 ``` [Answer] # Ruby, 57 bytes [A port of xnor's Python answer.](https://codegolf.stackexchange.com/a/75560/47581) The changes mostly lie in the ternary statement in `t` in place of the `and` due to `0` being truthy in Ruby, and using `(1..n).map` and `1+t[i]-t[i-1]` to save bytes vs. importing the list comprehension directly. ``` t=->n{n<1?n:n%2^t[n/2]} ->n{(1..n).map{|i|1+t[i]-t[i-1]}} ``` [Answer] # Mathematica (~~almost~~ nonverbal), ~~107~~ 110 bytes ``` ({0}//.{n__/;+n<2#}:>{n,{n}/.x_:>(1-x)/._[x__]:>x}//.{a___,0,s:1...,0,b___}:>{a,+s/.(0->o),0,b}/.o->0)[[;;#]]& ``` The sequence is generated by repeatedly applying a replacement rule. Another rule transforms it to the desired output. If enough people are interested, I'll explain in detail. **non-alphanumeric version** ``` ({$'-$'}//.{$__/;+$/# <($'-$')!+($'-$')!}:> {$,{$}/.$$_:>(($'-$') !-$$)/.{$$__}:>$$}//. {$___,$'-$',$$:($'-$' )!...,$'-$',$$$___}:> {$,+$$/.($'-$'->$$$$) ,$'-$',$$$}/.$$$$->$' -$')[[;;#]] ``` as suggested by CatsAreFluffy. ]
[Question] [ The Debian Linux distribution (and Debian-based distros, like Ubuntu, Kali and others) uses a package-manager called APT. To install program `foo` you would type into a terminal ``` sudo apt-get install foo ``` One little Easter Egg of APT is the following ``` apt-get moo ``` Which after typing will produce the following output ``` (__) (oo) /------\/ / | || * /\---/\ ~~ ~~ ..."Have you mooed today?"... ``` You must write a program that produces this EXACT output in as few bytes as possible. (including trailing spaces and a new line) Here is the same output with `\n` added to represent newline characters, and a `*` to represent trailing spaces ``` (__)*\n (oo)*\n /------\/*\n / | ||***\n * /\---/\*\n ~~ ~~***\n ..."Have you mooed today?"...\n ``` As requested in the comments, here is the md5sum of the mooing. ``` 35aa920972944a9cc26899ba50024115 - ``` [Answer] # CJam, 96 This uses a lot of nasty bytes, so here's a hex dump of it: ``` 00000000 22 ee 51 1e 53 41 15 ee 51 20 53 41 15 9a 5f 5a |".Q.SA..Q SA.._Z| 00000010 b9 5f 41 15 8c 5f 41 f9 38 24 2a 15 7e 55 1c 5f |._A.._A.8$*.~U._| 00000020 b9 30 5f b9 41 15 a8 26 2a 26 2a 15 36 45 91 c3 |.0_.A..&*&*.6E..| 00000030 ed cb 41 f3 df eb 41 db 20 cb c9 41 e9 df c9 c3 |..A...A. ..A....| 00000040 f3 7f 45 36 15 22 7b 69 32 6d 64 5c 5f 63 5c 37 |..E6."{i2md\_c\7| 00000050 6d 64 22 20 5f 6f 2d 7c 7e 2e 22 3d 2a 3f 7d 2f |md" _o-|~."=*?}/| ``` You can run the file with the java interpreter; it may be necessary to use ISO-8859-1 encoding, such as: `java -Dfile.encoding=ISO-8859-1 …` [Try it online](http://cjam.aditsu.net/#code=%22%C3%AEQ%1ESA%15%C3%AEQ%20SA%15%C2%9A_Z%C2%B9_A%15%C2%8C_A%C3%B98%24*%15~U%1C_%C2%B90_%C2%B9A%15%C2%A8%26*%26*%156E%C2%91%C3%83%C3%AD%C3%8BA%C3%B3%C3%9F%C3%ABA%C3%9B%20%C3%8B%C3%89A%C3%A9%C3%9F%C3%89%C3%83%C3%B3%7FE6%15%22%7Bi2md%5C_c%5C7md%22%20_o-%7C~.%22%3D*%3F%7D%2F) Equivalent (and much longer) ASCII version: ``` [238 81 30 83 65 21 238 81 32 83 65 21 154 95 90 185 95 65 21 140 95 65 249 56 36 42 21 126 85 28 95 185 48 95 185 65 21 168 38 42 38 42 21 54 69 145 195 237 203 65 243 223 235 65 219 32 203 201 65 233 223 201 195 243 127 69 54 21]:c {i2md\_c\7md" _o-|~."=*?}/ ``` [Try it online](http://cjam.aditsu.net/#code=%5B238%2081%2030%2083%2065%2021%20238%2081%2032%2083%2065%2021%20154%2095%2090%20185%2095%2065%2021%20140%2095%2065%20249%2056%2036%2042%2021%20126%2085%2028%2095%20185%2048%2095%20185%2065%2021%20168%2038%2042%2038%2042%2021%2054%2069%20145%20195%20237%20203%2065%20243%20223%20235%2065%20219%2032%20203%20201%2065%20233%20223%20201%20195%20243%20127%2069%2054%2021%5D%3Ac%0A%7Bi2md%5C_c%5C7md%22%20_o-%7C~.%22%3D*%3F%7D%2F) **Explanation:** There are 7 characters that have repetitions: `_o-|~.`. Each of them can be encoded as a number n from 0 to 6. For each repeating sequence, I am encoding both the character's index (n) and the number of repetitions (k) in a single byte: `2 * (k * 7 + n)`, written as a character with that code. And I am encoding any single characters as `2 * c + 1`, where c is the ASCII code. Everything goes in the initial string, and the rest of the program is decoding it: ``` {…}/ for each character in the string i convert to integer (extended-ASCII code) 2md integer division by 2, obtaining the quotient (q) and remainder (r) r decides whether it's a repetition or single character \_ swap q and r, and duplicate q c\ convert q to character and move it before the other q this is for the r=1 case (single character) 7md divide q by 7, obtaining the quotient (k) and remainder (n) "…"= get the corresponding character from that string (decoding n) * repeat the character k times ? use the single character or the repetition, depending on r ``` --- Old version (109): ``` " H(_2) H(o2) B/-6\/ A/ | 4|2 3 9* 2/\-3/\ C~2 3~2 3 .6"{_'M,48>&{~*}&}/3/"Have you mooed today?"`*N ``` [Try it online](http://cjam.aditsu.net/#code=%22%20H(_2)%20%0A%20H(o2)%20%0A%20B%2F-6%5C%2F%20%0A%20A%2F%20%7C%204%7C2%203%0A%209*%202%2F%5C-3%2F%5C%20%0A%20C~2%203~2%203%0A.6%22%7B_'M%2C48%3E%26%7B~*%7D%26%7D%2F3%2F%22Have%20you%20mooed%20today%3F%22%60*N) [Answer] # Bash, 95 bytes ``` 0000000: 7a 63 61 74 3c 3c 27 27 0a 1f 8b 08 01 01 01 01 01 zcat<<''......... 0000011: 02 03 53 40 07 1a f1 f1 9a 0a 5c 98 c2 f9 f9 a8 c2 ..S@......\...... 0000022: fa ba 60 10 a3 8f 2c aa af 50 03 a2 6a 40 24 42 58 ..`...,..P..j@$BX 0000033: 0b 28 11 03 54 ab 1f 83 6a 70 5d 1d 8c e0 d2 d3 d3 .(..T...jp]...... 0000044: 53 f2 48 2c 4b 55 a8 cc 2f 55 c8 cd cf 4f 4d 51 28 S.H,KU../U...OMQ( 0000055: c9 4f 49 ac b4 57 02 ca 70 01 .OI..W..p. ``` The above is a reversible hexdump. To create the file, execute ``` xxd -r -c 17 > 55918.sh ``` paste the hexdump and press `Enter`, then `Ctrl` + `D`. To run created file, execute ``` bash 55918.sh 2>&- ``` Any other filename will do. I chose [zopfli](https://github.com/google/zopfli) as the compressor since it is compatible with the Coreutils program zcat and achieves better compression than gzip, bzip2 and xz. `zcat<<''` will read the following lines (until EOF) and feed them as input to `zcat`. Note that zcat will print a warning (since I stripped the checksum of the compressed file), as will bash (since the HEREDOC isn't terminated by an empty line). These warnings are printed to STDERR (suppressed by `2>&-`), which is allowed by default per [consensus on Meta](http://meta.codegolf.stackexchange.com/q/4780). [Answer] # Pyth, 100 ``` r"17 (__) 17 (oo) 11 /6-\/ 10 / |4 ||3 9 * /\\3-/\ 12 ~~3 ~~3 3.\"Have you mooed today?\"3."9 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=r%2217+%28__%29+%0A17+%28oo%29+%0A11+%2F6-%5C%2F+%0A10+%2F+|4+||3+%0A9+*++%2F%5C%5C3-%2F%5C+%0A12+~~3+~~3+%0A3.%5C%22Have+you+mooed+today%3F%5C%223.%229&debug=0) `r"string"9` run-length-decodes the string. ### edit: Here's a 97 char solution: [Demonstration](http://pyth.herokuapp.com/?code=r%2Bs%40L%2B%22o_%7C%5C%20~%0A%22sr%5C%28%5C%3AjC%22%09K%16%C2%9Be%C2%8C%C3%A5%C3%AB%C2%B9%C3%97%C3%B4%09[iN%C2%B2%C2%85%04T9%C3%BC%C3%A9%C3%B3%C2%9D%C2%AB%C3%A9%17A%C2%96%0E%C3%A2%C3%B5]%C2%A6%16uw%14%7C%3D%2225%22%5C%22Have%20you%20mooed%20today%3F%5C%223.%229&debug=0). Very likely this is also 97 bytes (in iso-8859-1). But too tired for writing the bytes down and doing an explanation. Tomorrow evening, I guess. [Answer] ## GolfScript (107 bytes) This is a very simple encoding: newlines are replaced with `^`, and spaces are run-length-encoded. The result contains some non-printable characters, so I present it here as `xxd` output: ``` 0000000: 2711 285f 5f29 015e 1128 6f6f 2901 5e0b '.(__).^.(oo).^. 0000010: 2f2d 2d2d 2d2d 2d5c 2f01 5e0a 2f01 7c04 /------\/.^./.|. 0000020: 7c7c 035e 092a 022f 5c2d 2d2d 2f5c 015e ||.^.*./\---/\.^ 0000030: 0c7e 7e03 7e7e 035e 2e2e 2e22 4861 7665 .~~.~~.^..."Have 0000040: 0179 6f75 016d 6f6f 6564 0174 6f64 6179 .you.mooed.today 0000050: 3f22 2e2e 2e27 7b2e 3332 3c7b 2220 222a ?"...'{.32<{" "* 0000060: 7d2a 7d25 225e 222f 6e2a 0a }*}%"^"/n*. ``` [Online demo](http://golfscript.apphb.com/?c=JxEoX18pAV4RKG9vKQFeCy8tLS0tLS1cLwFeCi8BfAR8fANeCSoCL1wtLS0vXAFeDH5%2BA35%2BA14uLi4iSGF2ZQF5b3UBbW9vZWQBdG9kYXk%2FIi4uLid7LjMyPHsiICIqfSp9JSJeIi9uKg%3D%3D) Note that this is one character shorter than the corresponding CJam code. The tradeoff is using `'` as the delimiter for the main string (saving two `\`s to escape the `"`), saving an `i` to convert character values to integers in the decoding loop, and getting a free trailing newline; vs having character literals to replace the single-character string literals. --- Since this question was briefly tagged [printable-ascii](/questions/tagged/printable-ascii "show questions tagged 'printable-ascii'"), I also made a version with only (108) printable characters: ``` 'Y(__)I Y(oo)I S/------\/I R/I|L||K Q*J/\---/\I T~~K~~K ..."HaveIyouImooedItoday?"...'{.82-.*82<{72-' '*}*}% ``` Instead of encoding the run-lengths of the spaces as characters `^A` to `^R` (and encoding `^J` as `^` to avoid collisions), it leaves newlines untouched and encodes the run-lengths as `I` to `Y`. Incidentally, my general-purpose GolfScript Kolmogorov program produces a 120-byte program. [Answer] # Lua, ~~186~~ 178 bytes *8 bytes saved thanks to a suggestion by @DJ McMayhem* ``` p=print s=" "a=s:rep(17)b=s:rep(9)p(a.."(__) ")p(a.."(oo) ")p(b.." /------\\/ ")p(b.." / | || ")p(b.."* /\\---/\\ ")p(b.." ~~ ~~ ")p"...\"Have you mooed today?\"..." ``` Ungolfed: ``` p=print --Save the print function for later use s=" " --Space character a=s:rep(17) --string.rep(string, times) repeats the given string b=s:rep(9) p(a.."(__) ") --print out the lines p(a.."(oo) ") p(b.." /------\\/ ") p(b.." / | || ") p(b.."* /\\---/\\ ") p(b.." ~~ ~~ ") p"...\"Have you mooed today?\"..." ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), 217 bytes ``` !v" (__) "a" (oo) "a" /------\/ "a" / | || "a" * /\---/\ "a" ~~ ~~ "a"..."c3*2-"Have you mooed today?"c3*2-"..."a! >r>l0)?v; ^ o< ``` Unfortunately this is a pretty boring answer. It starts by reading out a string that draws out the entire cow, with newlines made by adding a value of 10 to the stack (a). It then goes into a loop which just draws out the cow. I originally made a loop to add in a set of spaces, but it was actually more expensive byte wise than just putting spaces in. EDIT: Forgot that fish is written as "><>" [Answer] # PowerShell, 144 bytes ``` $a=" " "$a$a (__) " "$a$a (oo) " "$a /------\/ " "$a / | || " "$a * /\---/\ " "$a ~~ ~~ " '..."Have you mooed today?"...' ``` The above code will work properly in environments that print Unix-style newlines (`\n`). It produces the correct output with, e.g., [Pash](https://github.com/Pash-Project/Pash) on Linux. Mathematically, for PowerShell, having 8 spaces for the `$a` variable is the optimal, as less means too many additional spaces between the variable and the cow to make a `$b` worthwhile, and more means we can't double-up on the first two lines for the head. [Answer] # [Molecule](https://github.com/lvivtotoro/molecule), 145 bytes ``` " "_____:a" (__) ";a____" (oo) ";a__" /------\\/ ";a__" / | || ";a__"* /\\---/\\ ";a____"~~"b"~~ ...\"Have you mooed today?\"..." ``` My first time trying to compress ASCII art :P [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 101 bytes ``` ‛_oƛ` (`pøṀ22↳,;\/:3-øṀp20↳₴ð,₀`/ | `꘍3\|꘍m+,9`* /\---/\ `꘍,12‛~~꘍3\~꘍m+,`..."`:₴`λɾ λ• mo⋎Þ ¬¾?`₴Ṙ, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%9B_o%C6%9B%60%20%28%60p%C3%B8%E1%B9%8022%E2%86%B3%2C%3B%5C%2F%3A3-%C3%B8%E1%B9%80p20%E2%86%B3%E2%82%B4%C3%B0%2C%E2%82%80%60%2F%20%7C%20%60%EA%98%8D3%5C%7C%EA%98%8Dm%2B%2C9%60*%20%20%2F%5C---%2F%5C%20%60%EA%98%8D%2C12%E2%80%9B%7E%7E%EA%98%8D3%5C%7E%EA%98%8Dm%2B%2C%60...%22%60%3A%E2%82%B4%60%CE%BB%C9%BE%20%CE%BB%E2%80%A2%20mo%E2%8B%8E%C3%9E%20%C2%AC%C2%BE%3F%60%E2%82%B4%E1%B9%98%2C&inputs=&header=&footer=) Uses some form of compression. ]
[Question] [ Is it possible to make this C code smaller? It prints out all primes from 0 to 1000. **C, 89 chars** ``` int i,p,c;for(i=2;i<1e3;i++){c=0;for(p=2;p<i;p++)if(i%p==0)c++;if(c==0)printf("%u\n",i);} ``` [Answer] # 67 bytes In C there's no real alternative to trial division, but it can certainly be golfed a bit. ``` for(int p=1,d;p++<999;d&&printf("%d\n",p))for(d=p;--d>1;)d=p%d?d:1; ``` Requires C99 initial declarations, which saves 1 byte. [Answer] **~~59~~ 57 bytes** Based on @feersum solution but the primality check can be golfed further ``` for(int p=1,d;d=p++%999;d||printf("%d\n",p))for(;p%d--;); ``` Edited based on Runer112's comments [Answer] *(I wrote this not realizing the size limitations on integers in C, so it's likely not actually useful for shortening the code.)* First, a word about algorithm. Before golfing your code, you should think about the best overall strategy to get the result. You're checking primality by doing trial division -- testing each potential divisor `p` of `i`. That's costly in characters because it takes two loops. So, testing primality without a loop is likely to save characters. An often shorter approach is to use [Wilson's Theorem](http://en.wikipedia.org/wiki/Wilson%27s_theorem): the number `n` is prime if and only if ``` fact(n-1)%n == n-1 ``` where `fact` is the factorial function. Since you're testing all possible `n` from `1` to `1000`, it's easy to avoid implementing factorial by keeping track of the running product `P` and updating it by `P*=n` after each loop. Here's a [Python implementation of this strategy](https://codegolf.stackexchange.com/a/27022/20260) to print primes up to a million. Alternatively, the fact that your program only has to be right up to 1000 opens up another strategy: the [Fermat primality test](http://en.wikipedia.org/wiki/Fermat_primality_test). For some `a`, every prime `n` satisfies ``` pow(a,n-1)%n == 1 ``` Unfortunately, some composites `n` also pass this test for some `a`. These are called [Fermat pseudoprimes](http://en.wikipedia.org/wiki/Fermat_pseudoprime). But, `a=2` and `a=3` don't fail together until `n=1105`, so they suffice for your purpose of checking primes until 1000. (If 1000 were instead 100, you'd be able to use only `a=2`.) So, we check primality with (ungolfed code) ``` pow(2,n-1)%n == 1 and pow(3,n-1)%n == 1 ``` This also fails to recognize primes 2 and 3, so those would need to be special-cased. Are these approaches shorter? I don't know because I don't code in C. But, they're ideas you should try before you settle on a piece of code to start eking out characters. [Answer] # ~~78~~ 77 characters (Just applied some tricks learned in other languages.) ``` int i=0,p,c;for(;i<1e3;i++){c=0;for(p=2;p<i;)c+=i%p++<1;c||printf("%u\n",i);} ``` ## 76 characters in C99 mode ``` for(int i=0,p,c;i<1e3;i++){c=0;for(p=2;p<i;)c+=i%p++<1;c||printf("%u\n",i);} ``` [Answer] ## 58 chars (or 61 for a complete program) Another reuse of [my answer to a similar question](https://codegolf.stackexchange.com/a/5818/3544). **EDIT**: stand-alone code piece, no function to call. ``` for(int m,n=2;n<999;m>1?m=n%m--?m:n++:printf("%d\n",m=n)); ``` Complete program: ``` n=2;main(m){n<999&&main(m<2?printf("%d\n",n),n:n%m?m-1:n++);} ``` [Answer] # ~~67~~ 64 bytes Inspired by Alchymist's solution : ``` int i=1,p;for(;i++<1e3;p-i||printf("%d\n",i)){p=1;while(i%++p);} ``` ]
[Question] [ This is the companion question to [Jumblers vs Rebuilders: Coding with Tetris Bricks](https://codegolf.stackexchange.com/questions/40140/jumblers-vs-rebuilders-coding-with-tetris-bricks) where Rebuilders can post their solutions. As argued in [Where should we put robbers?](https://codegolf.meta.stackexchange.com/questions/2334/where-should-we-put-robbers) it allows more formatting freedom for robbers and lets them gain rep. Only answer this question if you have cracked a yet uncracked answer to [Jumblers vs Rebuilders: Coding with Tetris Bricks](https://codegolf.stackexchange.com/questions/40140/jumblers-vs-rebuilders-coding-with-tetris-bricks). **Please include a link to that answer in your answer *and* a comment in that answer linking to your answer.** The accepted answer for this question will be the winning rebuilder. The scoreboard will only appear in the [other question](https://codegolf.stackexchange.com/questions/40140/jumblers-vs-rebuilders-coding-with-tetris-bricks). [COTO](https://codegolf.stackexchange.com/users/31019/coto) has generously made [a JSFiddle](http://jsfiddle.net/bjfmyzqg/1/) for easily manipulating code-bricks. I've [updated this fiddle](http://jsfiddle.net/CalvinsHobbies/jgz3z53z/) so ES 6 is not required, and minimized it for this Stack Snippet: ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>function parseSpec(s){function first(){var e,t;t=S.findIndex(function(t){return(e=t.findIndex(function(e){return/\S/.test(e)}))!=-1});return t==-1?null:[e,t]}function at(e){var t=e[0],n=e[1];return n>=0&&n<S.length&&t>=0&&t<S[n].length?S[n][t]:" "}function wipe(e){var t=e[0],n=e[1];if(n>=0&&n<S.length&&t>=0&&t<S[n].length)S[n][t]=" "}var P,S=s.split("\n").map(function(e){return e.split("")});var oPats=$(".proto-tet [pat]").get().map(function(e){return{sPat:eval("["+$(e).attr("pat")+"]"),e:e,block:function(e){return[at(e)].concat(this.sPat.map(function(t){return at([e[0]+t[0],e[1]+t[1]])}))},wipe:function(e){this.sPat.forEach(function(e){return wipe([P[0]+e[0],P[1]+e[1]])})},match:function(e){return!/\s/.test(this.block(e).join(""))}}});window.oPats=oPats;while(P=first()){var oPat=oPats.find(function(e){return e.match(P)});if(!oPat){orphan(at(P));wipe(P);continue}createPiece(oPat.e,oPat.block(P));wipe(P);oPat.wipe(P)}}function createPiece(e,t){function r(e){var t=$(this).position();G.isIgnoreClick=false;G.eDrag=this;G.iOffsets=[e.clientX-t.left,e.clientY-t.top]}function i(){if(G.isIgnoreClick)return;var e=$(this);s($(".proto-tet ."+e.attr("rr")),function(e,t){return n[t-1]},e.css("left"),e.css("top"));e.remove()}function s(e,t,n,s){e.clone().html(e.html().replace(/@(\d)(\d)/g,t)).appendTo("body").on("mousedown",r).click(i).css({left:n,top:s})}var n=[];s($(e),function(e,r,i){return n[r-1]=t[i-1]},18+G.iSpawn%8*18*4+"px",18+~~(G.iSpawn/8)*18*4+"px");G.iSpawn++}function init(){$(document).on("mouseup",function(){return G.eDrag=null}).on("mousemove",function(e){if(G.eDrag){var t=$(G.eDrag),n=Math.round((e.clientX-G.iOffsets[0])/18)*18,r=Math.round((e.clientY-G.iOffsets[1])/18)*18,i=t.position();if(n!=i.left||r!=i.top)G.isIgnoreClick=true;t.css({left:n+"px",top:r+"px"})}})}function orphan(e){error("Spec character not a part of any block: '"+e+"'")}function error(e){$(".error").css("display","block").append("<div>"+e+"</div>")}function go(){$(init);$(function(){parseSpec($("#spec").val())});$("#spec").remove();$("#info").remove();$("#go").remove()}var G={eDrag:null,isIgnoreClick:true,iSpawn:0};Array.prototype.findIndex=function(e){for(var t=0;t<this.length;t++){if(e(this[t]))return t}return-1};Array.prototype.find=function(e){var t=this.findIndex(e);if(t==-1)return;else return this[t]}</script><style>.proto-tet, .spec{display: none;}.tet-I{color: darkgreen;}.tet-J{color: orangered;}.tet-L{color: navy;}.tet-T{color: darkred;}.tet-O{color: darkcyan;}.tet-S{color: darkviolet;}.tet-Z{color: darkorange;}body > .tet{position: absolute;cursor: move;-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;border-collapse: collapse;}.tet td{width: 18px;height: 18px;font: bold 14px "Courier New",monospace;text-align: center;vertical-align: middle;padding: 0;}.error{z-index: 1024;position: absolute;display: none;color: red;font-weight: bold;background-color: white;}textarea{font-family: "Courier New", Courier, monospace;}</style><div id='info'>Put code-bricks here and hit OK. Re-run the snippet to restart.<br>(You may need to replace spaces in code-bricks with some other character first.)</div><textarea id='spec' rows='16' cols='80'>ABCD&nbsp;&nbsp;a&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;b&nbsp;&nbsp;&nbsp;Oo&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;c&nbsp;&nbsp;&nbsp;oo&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;d&#13;&#10;&#13;&#10;&nbsp;E&nbsp;&nbsp;&nbsp;&nbsp;h&#13;&#10;&nbsp;F&nbsp;&nbsp;efg&nbsp;&nbsp;&nbsp;hg&nbsp;&nbsp;&nbsp;GFE&#13;&#10;&nbsp;GH&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f&nbsp;&nbsp;&nbsp;H&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e&#13;&#10;&#13;&#10;&nbsp;I&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IJK&#13;&#10;&nbsp;J&nbsp;&nbsp;&nbsp;l&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;L&#13;&#10;LK&nbsp;&nbsp;&nbsp;kji&nbsp;&nbsp;kl&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;j&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;i&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t&#13;&#10;&nbsp;OP&nbsp;&nbsp;&nbsp;p&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;QR&nbsp;&nbsp;&nbsp;&nbsp;rs&#13;&#10;MN&nbsp;&nbsp;&nbsp;&nbsp;on&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ST&nbsp;&nbsp;&nbsp;q&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;m&#13;&#10;&nbsp;W&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;z&#13;&#10;&nbsp;XY&nbsp;&nbsp;&nbsp;&nbsp;zxw&nbsp;&nbsp;&nbsp;&nbsp;yx&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Y&#13;&#10;&nbsp;Z&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;y&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;w&nbsp;&nbsp;&nbsp;&nbsp;WXZ</textarea><br><button id='go' type='button' onclick='go()'>OK</button><div class="proto-tet"><table class="tet tet-I tet-I0" rr="tet-I1" pat="[1,0],[2,0],[3,0]"><tr><td>@11</td><td>@22</td><td>@33</td><td>@44</td></tr></table><table class="tet tet-I tet-I1" rr="tet-I2" pat="[0,1],[0,2],[0,3]"><tr><td>@11</td></tr><tr><td>@22</td></tr><tr><td>@33</td></tr><tr><td>@44</td></tr></table><table class="tet tet-I tet-I2" rr="tet-I3" ><tr><td>@40</td><td>@30</td><td>@20</td><td>@10</td></tr></table><table class="tet tet-I tet-I3" rr="tet-I0"><tr><td>@40</td></tr><tr><td>@30</td></tr><tr><td>@20</td></tr><tr><td>@10</td></tr></table><table class="tet tet-J tet-J0" rr="tet-J1" pat="[0,1],[-1,2],[0,2]"><tr><td></td><td>@11</td></tr><tr><td></td><td>@22</td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-J tet-J1" rr="tet-J2" pat="[0,1],[1,1],[2,1]"><tr><td>@31</td><td></td><td></td></tr><tr><td>@42</td><td>@23</td><td>@14</td></tr></table><table class="tet tet-J tet-J2" rr="tet-J3" pat="[1,0],[0,1],[0,2]"><tr><td>@41</td><td>@32</td></tr><tr><td>@23</td><td></td></tr><tr><td>@14</td><td></td></tr></table><table class="tet tet-J tet-J3" rr="tet-J0" pat="[1,0],[2,0],[2,1]"><tr><td>@11</td><td>@22</td><td>@43</td></tr><tr><td></td><td></td><td>@34</td></tr></table><table class="tet tet-O tet-O0" rr="tet-O1" pat="[1,0],[0,1],[1,1]"><tr><td>@11</td><td>@22</td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-O tet-O1" rr="tet-O2"><tr><td>@30</td><td>@10</td></tr><tr><td>@40</td><td>@20</td></tr></table><table class="tet tet-O tet-O2" rr="tet-O3"><tr><td>@40</td><td>@30</td></tr><tr><td>@20</td><td>@10</td></tr></table><table class="tet tet-O tet-O3" rr="tet-O0"><tr><td>@20</td><td>@40</td></tr><tr><td>@10</td><td>@30</td></tr></table><table class="tet tet-L tet-L0" rr="tet-L1" pat="[0,1],[0,2],[1,2]"><tr><td>@11</td><td></td></tr><tr><td>@22</td><td></td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-L tet-L1" rr="tet-L2" pat="[1,0],[2,0],[0,1]"><tr><td>@31</td><td>@22</td><td>@13</td></tr><tr><td>@44</td><td></td><td></td></tr></table><table class="tet tet-L tet-L2" rr="tet-L3" pat="[1,0],[1,1],[1,2]"><tr><td>@41</td><td>@32</td></tr><tr><td></td><td>@23</td></tr><tr><td></td><td>@14</td></tr></table><table class="tet tet-L tet-L3" rr="tet-L0" pat="[-2,1],[-1,1],[0,1]"><tr><td></td><td></td><td>@41</td></tr><tr><td>@12</td><td>@23</td><td>@34</td></tr></table><table class="tet tet-S tet-S0" rr="tet-S1" pat="[1,0],[-1,1],[0,1]"><tr><td></td><td>@21</td><td>@12</td></tr><tr><td>@43</td><td>@34</td><td></td></tr></table><table class="tet tet-S tet-S1" rr="tet-S2" pat="[0,1],[1,1],[1,2]"><tr><td>@41</td><td></td></tr><tr><td>@32</td><td>@23</td></tr><tr><td></td><td>@14</td></tr></table><table class="tet tet-S tet-S2" rr="tet-S3"><tr><td></td><td>@30</td><td>@40</td></tr><tr><td>@10</td><td>@20</td><td></td></tr></table><table class="tet tet-S tet-S3" rr="tet-S0"><tr><td>@10</td><td></td></tr><tr><td>@20</td><td>@30</td></tr><tr><td></td><td>@40</td></tr></table><table class="tet tet-Z tet-Z0" rr="tet-Z1" pat="[1,0],[1,1],[2,1]"><tr><td>@11</td><td>@22</td><td></td></tr><tr><td></td><td>@33</td><td>@44</td></tr></table><table class="tet tet-Z tet-Z1" rr="tet-Z2" pat="[-1,1],[0,1],[-1,2]"><tr><td></td><td>@11</td></tr><tr><td>@32</td><td>@23</td></tr><tr><td>@44</td><td></td></tr></table><table class="tet tet-Z tet-Z2" rr="tet-Z3"><tr><td>@40</td><td>@30</td><td></td></tr><tr><td></td><td>@20</td><td>@10</td></tr></table><table class="tet tet-Z tet-Z3" rr="tet-Z0"><tr><td></td><td>@40</td></tr><tr><td>@20</td><td>@30</td></tr><tr><td>@10</td><td></td></tr></table><table class="tet tet-T tet-T0" rr="tet-T1" pat="[1,0],[2,0],[1,1]"><tr><td>@11</td><td>@22</td><td>@33</td></tr><tr><td></td><td>@44</td><td></td></tr></table><table class="tet tet-T tet-T1" rr="tet-T2" pat="[-1,1],[0,1],[0,2]"><tr><td></td><td>@11</td></tr><tr><td>@42</td><td>@23</td></tr><tr><td></td><td>@34</td></tr></table><table class="tet tet-T tet-T2" rr="tet-T3" pat="[-1,1],[0,1],[1,1]"><tr><td></td><td>@41</td><td></td></tr><tr><td>@32</td><td>@23</td><td>@14</td></tr></table><table class="tet tet-T tet-T3" rr="tet-T0" pat="[0,1],[1,1],[0,2]"><tr><td>@31</td><td></td></tr><tr><td>@22</td><td>@43</td></tr><tr><td>@14</td><td></td></tr></table></div><div class="error"></div> ``` [Answer] # Crack of xnor's [340-area answer](https://codegolf.stackexchange.com/a/40146/30688 "340-area answer") No cryptographic mumbo-jumbo for me. **Code:** ``` 10000001111111222 22388892357889356 69968999352143221 80867227952780811 a=23333333444444 b=71122368066667 c=47948316823798 d=79254432699451 496857235742 579159386011 606961806231 pow(a,b,c)-d 62656269644465648 67766884711672530 73487440752777431 print('Tetris'*(1 )) 7873806482918808 8843930593249458 946095869869 ``` **Mapping of blocks to line numbers** ``` #Four spaces 9-12 #Four spaces 9-12 #Four spaces 9-12 #Four spaces 9-12 #Four spaces 17 #Four spaces 17 #Four spaces 17 #Four spaces 17-20 #Four spaces 5-8 )) #Two spaces 17 0290 1-4 0398 1-4 0866 1-4 0887 1-4 0892 1-4 0992 1-4 1108 13-16 1268 1-4 1297 1-4 1339 1-4 1555 1-4 1722 1-4 1817 1-4 1848 1-4 1930 1-4 2328 1-4 2521 1-4 2611 1-4 2747 5-8 3179 5-8 3192 5-8 3245 5-8 3284 5-8 3334 5-8 3613 5-8 3862 5-8 4086 5-8 4629 5-8 4639 5-8 4674 5-8 4695 5-8 4781 5-8 4968 9 5723 9 5742 9 5791 10 5938 10 6011 10 6069 11 6180 11 6231 11 6265 13 6269 13 6444 13 6564 13 6776 14 6884 14 7116 14 7253 14 7348 15 7440 15 7527 15 7743 15 7873 17 8064 17 8291 17 8808 17 8843 18 9305 18 9324 18 9458 18 9460 19 9586 19 9869 19 ==== 5-8 a,b, 12 abcd 5-8 c)-d 12 etri 16 pow( 12 prin 16 s'*( 16 t('T 16 four spaces 9-12 four spaces 20 ``` [Answer] **Solution to [xnor's 212 area puzzle](https://codegolf.stackexchange.com/a/40142/19475)** ``` print('Tetris'* (3580048039607960824098110131314133014381502228523172479258529553116373838184169‌​435643604632480050165153525653945598563157585840631264256539704571638903974876749‌​009825073297156762481649%38941394)) ``` [Answer] # Teromino Sandbox While not a solution ipso facto, I wanted to share [this online tool](http://jsfiddle.net/bjfmyzqg/1/) I put together with other potential rebuilders. It facilitates quick and error-free manipulation of the "code tetrominos". The shapes are specified using a simple character grid in the `spec` element. Most answers should be a simple copy/paste off of PPCG. The default shape spec provides numerous examples. I've also included the shape specs for my [C-72](https://codegolf.stackexchange.com/questions/40140/jumblers-vs-rebuilders-coding-with-tetris-bricks/40198#40198) answer. Two caveats: 1. the specs are whitespace-sensitive 2. some HTML control characters may need to be escaped The pieces are shown in different colours. Drag them to move them, and click them to rotate them. Easy peasy. Anyone who wants to add improvements, add new specs, fix bugs, etc., is welcome to fork the fiddle and edit this answer to provide an updated link. Happy rebuilding. :) [Answer] # Solution to es1024's [80 area answer](https://codegolf.stackexchange.com/a/40155/25180) ``` main(q){char c[] ={'/T','$"e','t' ,0162,'rIi>`:i', '?#>s',q<q/**/}; return puts(c);} ``` [Answer] ## Solution to [Gerli's 72 area submission](https://codegolf.stackexchange.com/a/40230/8478) ``` FromCharacterCode[ {8*10+4, 10*10+1, 100+16, 10*10+14, 105, 115}]//Print ``` There's a mistake in the submission though. In the third `T` block, Gerli "rotated" the `[` and `{` when rotating the block. All done by hand. The `Print` was quite easy to find. Then I wrote out the remaining letters, and found them to be an anagram of `FromCharacterCode`. That put a lot of restrictions on the maximum code height and most blocks. Since there was no `@` and only one pair of brackets, that gave away that `Print` was applied using suffix notation (which determined both its position and that it's preceded by the `//`. In the end there were only an `S` and two `T`s left. The `S` was forced by the layout and the first assignment of `T`s I tried worked. ]
[Question] [ Groups are a widely used structure in Mathematics, and have applications in Computer Science. This code challenge is about the fewest # of characters to create a group table for the additive group Zn. How the table is constructed: For Zn, the elements are {0, 1, 2, ..., n-1}. The table will have n rows and n columns. For the ij-th entry of the table, the value is i+j mod n. For example, in Z3, the 1-2nd entry (2nd row, 3rd column if you count the starting row/column as 1) is (1+2)%3 = 0 (see sample output). **Input:** a positive integer, n **Output:** a table that is a textual presentation of Zn, constructed as described above, and displayed as shown below in the sample outputs. Spaces are optional **Sample input:** `3` **Sample output:** ``` 0 1 2 1 2 0 2 0 1 ``` **Sample input:** `5` **Sample output:** ``` 0 1 2 3 4 1 2 3 4 0 2 3 4 0 1 3 4 0 1 2 4 0 1 2 3 ``` [Answer] # APL (10) (Assuming `⎕IO=0`. It works on [ngn/apl](http://ngn.github.io/apl/web/) by default, other APLs tend to need an `⎕IO←0` first.) ``` {⍵|∘.+⍨⍳⍵} ``` Explanation: * `⍳⍵`: the numbers [0..⍵) * `∘.+⍨`: create a sum table * `⍵|`: numbers in the table `mod` ⍵ [Answer] ## GolfScript (13 chars) I understand from your comment on Claudiu's answer that whitespace between the elements of a row is not necessary. On that understanding: ``` ~.,{.n\(+}@(* ``` [Online demo](http://golfscript.apphb.com/?c=Oyc0JwoKfi4sey5uXCgrfUAoKg%3D%3D) Dissection: ``` ~ Parse the input into an integer ., Duplicate it, turn the second into an array [0,...,n-1] { Loop: top of stack is the previous row .n\ Push a newline and a copy of the previous row (+ Rotate the first element to the end to get the new row }@(* Perform loop n-1 times ``` --- If whitespace is necessary, for 20 chars: ``` ~.,{.(+}@(*]{' '*n}/ ``` [Answer] # Python 2, 66 bytes ``` def f(n):R=range(n);exec"print''.join(map(str,R));R+=R.pop(0),;"*n ``` Rotates the list by popping and re-appending. # Python 3, 53 bytes ``` def f(n):*R,=range(n);[print(*R[i:]+R[:i])for i in R] ``` Uses the same method as @mbomb007, but abusing `print` as a function. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes ``` ݨDδ+I%» ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8NxDK1zObdH2VD20@/9/cwA "05AB1E – Try It Online") ## Explanation ``` # Implicit input n = 3 [3] Ý # Push range(0,3) [[0,1,2,3]] ¨ # Pop last element [[0,1,2]] D # Duplicate [[0,1,2],[0,1,2]] δ # Apply next operation double vectorized + # Vectorized addition [[[0,1,2],[1,2,3],[2,3,4]]] I # Push input [[[0,1,2],[1,2,3],[2,3,4]],3] % # Elementwise modulo 3 [[[0,1,2],[1,2,0],[2,0,1]]] » # " ".join(x) followed by newline ["0 1 2\n1 2 0\n2 0 1\n"] for every x in list ``` --- ## Previous answer: 10 bytes ``` ݨDvDðý,À} ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8NxDK1zKXA5vOLxX53BD7f//5gA "05AB1E – Try It Online") My first try at golfing in 05AB1E. ### Explanation of previous answer ``` # Implicit input n = 3 [3] Ý # Push range(0,3) [[0,1,2,3]] ¨ # Pop last element. [[0,1,2]] D # Duplicate [[0,1,2],[0,1,2]] v } # Pop list and loop through elements [[0,1,2]] D # Duplicate [[0,1,2],[0,1,2]] ð # Push space char [[0,1,2],[0,1,2], " "] ý # Pop list a and push string a.join(" ") [[0,1,2],"0 1 2"] , # Print string with trailing newline [[0,1,2]] Print: "0 1 2" À # Rotate list [[1,2,0]] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 ``` Ḷṙ`G ``` [Try it online!](https://tio.run/##y0rNyan8///hjm0Pd85McP///78pAA "Jelly – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 ``` JVQXQjdJ=J+tJ]hJ ``` Prints the table with proper whitespace. ``` ./pyth.py -c "JVQXQjdJ=J+tJ]hJ" <<< 5 0 1 2 3 4 1 2 3 4 0 2 3 4 0 1 3 4 0 1 2 4 0 1 2 3 ``` **Explanation:** ``` Automatic: Q=eval(input()) JVQ J = range(Q) XQ repeat Q times jdJ print J, joined on " " =J J = +tJ]hJ tail(J) + [head(J)] (J[1:] + [J[-1]]]) ``` [Answer] ## J, 20 Reading from stdin and producing a 2D array (which renders the same as the sample in the question). ``` (|+/~@i.)@".}:1!:1]3 ``` If a function taking a string suffices, `(|+/~@i.)@".`. If a function taking an integer suffices, `|+/~@i.` should be sufficient. **Explanation:** `f g` in J (for functions f, g) denotes a "hook", which is a composite function that runs the input through g (a unary function) and then the input and the result of g through f (a binary function). The answer is a fork with components `|` (modulus) and `+/~@i.`. The latter part is "table-of sums composed-with list-of-indices-upto" (`i.` is a bit like `range` in Python). [Answer] # Octave, 23 ``` @(n)mod((r=0:n-1)'+r,n) ``` [Answer] # Python 2, 67 [Try them both here](http://ideone.com/XtJ6Zj) I use list splitting to "rotate" the list `n` times, printing it each time. (68 chars) ``` def f(n): l=range(n) for i in l:print''.join(map(str,l[i:]+l[:i])) ``` I managed to get it one character shorter than the above with a weird trick. (67 chars) ``` def f(n): l=range(n) for i in l:print''.join(`l[i:]+l[:i]`)[1::3] ``` [Answer] # Matlab (28) ``` k=exp(0:n-1) mod(log(k'*k),n) ``` [Answer] # x86-64 Machine Code (Linux), ~~80~~ 64 bytes ``` 0000000000000000 <zn_asm>: 0: 6a 0a pushq $0xa 2: 89 f9 mov %edi,%ecx 4: ff c9 dec %ecx 0000000000000006 <zn_asm.l1>: 6: c6 06 0a movb $0xa,(%rsi) 9: 48 ff ce dec %rsi c: 89 fb mov %edi,%ebx e: ff cb dec %ebx 0000000000000010 <zn_asm.l2>: 10: 89 c8 mov %ecx,%eax 12: 01 d8 add %ebx,%eax 14: 31 d2 xor %edx,%edx 16: f7 f7 div %edi 18: 89 d0 mov %edx,%eax 000000000000001a <zn_asm.l3>: 1a: 31 d2 xor %edx,%edx 1c: 48 f7 34 24 divq (%rsp) 20: 83 c2 30 add $0x30,%edx 23: 88 16 mov %dl,(%rsi) 25: 48 ff ce dec %rsi 28: 85 c0 test %eax,%eax 2a: 75 ee jne 1a <zn_asm.l3> 2c: ff cb dec %ebx 2e: 85 db test %ebx,%ebx 30: 7d de jge 10 <zn_asm.l2> 32: ff c9 dec %ecx 34: 85 c9 test %ecx,%ecx 36: 7d ce jge 6 <zn_asm.l1> 38: 58 pop %rax 39: 48 89 f0 mov %rsi,%rax 3c: 48 ff c0 inc %rax 3f: c3 retq ``` ~~I was hoping for this solution to be just a few bytes shorter to be able to beat some of the other submissions on this post. There's a possibility if I use some of the 32 or 16 bit versions of the registers I could shave a few bytes off.~~ Converting a lot of the registers to the 32 bit addressing versions saved 16 bytes. Basically this function is called from a C/C++ program which passed n through rdi, and a pointer to an allocation through rsi. The pointer that rsi has is actually 1 byte from the end of the allocation, since the table is built backwards. This makes it easier to convert an integer to printable ASCII characters (done by taking some number x mod 10 and converting the result to ASII). To see the C++ wrapper code and comments on the assembly, check out [my repo](https://github.com/Davey-Hughes/ppcg/tree/master/zn). [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~10~~ 8 bytes ``` r░y\Åo╫; ``` [Try it online!](https://tio.run/##y00syUjPz0n7/7/o0bSJlTGHW/MfTV1t/f@/8X/dFAA "MathGolf – Try It Online") -2 bytes thanks to Jo King ## Explanation I'll use example input `3` for the explanation ``` r range(0, n) ([0, 1, 2]) ░ convert to string (implicit map) (['0', '1', '2']) y join array without separator to string or number ('012') \ swap top elements ('012', 3) Å start block of length 2 (for-loop, loops 3 times ('012')) o print TOS without popping ╫ left-rotate bits in int, list/str ('012' => '120' => '201' => '012') ; discard TOS (prevents final print) ``` You could also do `r░y\(Åo╫`, which decreases the number of loops by 1 and skips the discard after the loop. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 25 bytes ``` n->matrix(n,,x,y,x+y-2)%n ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y43saQos0IjT0enQqdSp0K7UtdIUzXvf0FRZl6JRpqGqabmfwA "Pari/GP – Try It Online") [Answer] # [Q/KDB+](https://kx.com/download), 19 bytes **Solution:** ``` {t rotate\:t:til x} ``` **Example:** ``` q){t rotate\:t:til x} 3 0 1 2 1 2 0 2 0 1 q){t rotate\:t:til x} 5 0 1 2 3 4 1 2 3 4 0 2 3 4 0 1 3 4 0 1 2 4 0 1 2 3 ``` **Explanation:** ``` {t rotate\:t:til x} / solution { } / lambda taking implicit x argument til x / the range 0..x t: / assign to 't' rotate\: / rotate right argument with each-left (\:) t / the left argument (0..x) ``` **Extra:** * `{(!x).q.rotate\:!x}` still **19** bytes in K4. [Answer] ## C - 96 ``` void g(int k){int i;for(i=0;i<k*k;i++){if(i&&!(i%k))puts("\n");printf("%i ",((i/k)+(i%k))%k);}} ``` [Answer] # Golfscript, 20 characters A terribly lazy job. ``` ~:j,{:x;j,{x+j%}%n}/ ``` [Run it here](http://golfscript.apphb.com/?c=OyI1Igp%2BOmosezp4O2ose3graiV9JW59Lw%3D%3D). (First line is to simulate stdin). **Explanation**: ``` ~ # evaluate input (turn string "5" into number 5) :j # store into variable j , # turn top of stack into range(top), e.g. 5 --> [0, 1, 2, 3, 4] {...}/ # for each element in the array... :x; # store the element into x and pop from the stack j, # put range(j) on the stack ([0, 1, 2, 3, 4] again) {...}% # map the array with the following: x+j% # add x and mod the resulting sum by j n # put a newline on the stack ``` When the program ends, the stack contains each of the arrays with newlines between them. The interpreter outputs what's left on the stack, giving the desired result. [Answer] # CJam, 14 characters ``` l~_)_@,*/Wf<N* ``` [Test it here.](http://cjam.aditsu.net/#code=l~_)_%40%2C*%2FWf%3CN*&input=5) ## Explanation The idea is to repeat the string from `0` to `N-1`, but split it into blocks of `N+1`. This mismatch shifts the row to the left each time. Lastly, we need to get rid of the extraneous character and join everything with newlines. Here is the exploded code, together with the stack contents for input `3`. ``` l~ "Read and eval input."; [3] _ "Duplicate."; [3 3] ) "Increment."; [3 4] _ "Duplicate."; [3 4 4] @ "Rotate."; [4 4 3] , "Get range."; [4 4 [0 1 2]] * "Repeat."; [4 [0 1 2 0 1 2 0 1 2 0 1 2] / "Split."; [[[0 1 2 0] [1 2 0 1] [2 0 1 2]] Wf< "Truncate each line."; [[[0 1 2] [1 2 0] [2 0 1]] N* "Join with newlines."; ["012 120 201"] ``` The result is printed automatically at the end of the program. (Note, the stack contents for the final step are technically a mixed array containing numbers and newline characters, not a string containing only characters.) ## Alternatively, 11 characters With the recent addition `ew` (this is newer than the challenge - it returns all overlapping substrings of given length), one could do 11 bytes: ``` l~,2*))ewN* ``` Here is how this one works: ``` l~ "Read and eval input."; [3] , "Get range."; [[0 1 2]] 2* "Repeat twice."; [[0 1 2 0 1 2]] ) "Pop last."; [[0 1 2 0 1] 2] ) "Increment."; [[0 1 2 0 1] 3] ew "Get substrings."; [[[0 1 2] [1 2 0] [2 0 1]] N* "Join with newlines."; ["012 120 201"] ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` :q&+G\ ``` [Try it online!](https://tio.run/##y00syfn/36pQTds95v9/EwA "MATL – Try It Online") ``` # implicit input, say n = 3 : # range # stack: [1, 2, 3] q # decrement # stack: [0, 1, 2] &+ # sum with itself and transpose with broadcast # stack: # [0 1 2 # 1 2 3 # 2 3 4] G # paste input # stack: [0 1 2; 1 2 3; 2 3 4], 3 \ # elementwise modulo # implicit output with spaces ``` [Answer] # Excel VBA, 77 Bytes Anonymous VBE immediate window function that takes input, as integer,n, from range `[A1]` and outputs to the range `A2.Resize(n,n)`. ``` [A2:IU255]="=IF(MAX(ROW()-1,COLUMN())-1<$A$1,MOD(ROW()+COLUMN()-3,$A$1),"""") ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 23 bytes ``` {.rotate(.all).put}o|^* ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1qvKL8ksSRVQy8xJ0dTr6C0pDa/Jk7rvzVXmoaxJog01bT@DwA "Perl 6 – Try It Online") Anonymous code block that takes a number and prints the matrix in the given format with spaces. If we can just return something instead, then the `.put` can be removed. ### Explanation: ``` o|^* # Transform the input into the range 0..input-1 { } # And pass it into the function .rotate # Rotate the range by (.all) # Each of the range .put # And print each of them separated by spaces ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` NθEθ⪫Eθ﹪⁺ιλθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDN7FAo1BHwSs/Mw/G9s1PKc3J1wjIKS3WyNRRyNHUUSjUBBJKCkqamprW//@b/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. Note: Trailing space. Explanation: ``` Nθ Input `n` as a number into variable θ `n` E Map over implicit range θ `n` E Map over implicit range ι Current row ⁺ Plus λ Current column ﹪ Modulo θ `n` ⪫ Cast row to string and join with spaces Implicitly print each row on its own line ``` [Answer] # APL(NARS), 15 chars, 30 bytes ``` {⊃{⍵⌽k}¨k←0..⍵} ``` test: ``` f←{⊃{⍵⌽k}¨k←0..⍵} f 4 0 1 2 3 4 1 2 3 4 0 2 3 4 0 1 3 4 0 1 2 4 0 1 2 3 f 3 0 1 2 3 1 2 3 0 2 3 0 1 3 0 1 2 f 2 0 1 2 1 2 0 2 0 1 f 1 0 1 1 0 f 0 0 ``` here the language has need no comments... [Answer] # Japt `-R`, 5 bytes ``` ÆZéXn ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=xlrpWG4=&input=OAotUg==) If using a comma as a separator isn't valid then add a byte for no separator: ``` ÆZ¬éXn ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=xlqs6Vhu&input=OAotUg==) Or 2 bytes to use a space: ``` ÆZéXn)¸ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=xlrpWG4puA==&input=OAotUg==) [Answer] # [R](https://www.r-project.org/), 37 bytes ``` sapply(x<-1:scan()-1,`+`,x)%%sum(x|1) ``` Creates a vector from 0 to n-1, and sequentially adds 1, then 2... then n, and modulates the matrix by the length of the vector, which is n. [Try it online!](https://tio.run/##K/r/vzixoCCnUqPCRtfQqjg5MU9DU9dQJ0E7QadCU1W1uDRXo6LGUPO/6X8A "R – Try It Online") [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 53 bytes ``` : f dup 0 do cr dup 0 do i j + over mod . loop loop ; ``` [Try it online!](https://tio.run/##fYtLDoAgEEP3nKJhayB@N3IccfxEM4So18dBF@5s8touWuJ4zGaiHCn1IPgzoIRnDPHrC1YU4GuM2NnDYmMOrzl5hWdp84WyWQ3zL51nTlUIqhYaoRU6Id0 "Forth (gforth) – Try It Online") ### Explanation Nested loop that outputs a newline every n numbers ### Code Explanation ``` : f \ start new word definition dup 0 do \ set loop parameters and loop from 0 to n-1 cr \ output a newline dup 0 do \ loop from 0 to n-1 again i j + \ get the sum of the row and column number over mod \ modulo with n . \ print (with space) loop \ end inner loop loop \ end outer loop ; \ end word definition ``` [Answer] ## Using rotations # [Burlesque](https://github.com/FMNSSun/Burlesque), 6 bytes ``` -.rziR ``` [Try it online!](https://tio.run/##SyotykktLixN/V@Q@l9Xr6gqM@h/ccF/YwA "Burlesque – Try It Online") ``` -. # Decrement input rz # Range from [0..n) iR # All rotations of value ``` ## Proper calculation # [Burlesque](https://github.com/FMNSSun/Burlesque), 19 bytes ``` Jrzl_Jcpq++m[j.%jco ``` [Try it online!](https://tio.run/##SyotykktLixN/V@Q@t@rqCon3iu5oFBbOzc6S081Kzn/f3HBf2MA "Burlesque – Try It Online") ``` J # Duplicate input rz # Range from [0..n) l_ # Pop largest (behind) Jcp # Cart product with self q++m[ # Sum each pair j.% # Mod input jco # Split list into chunks of input ``` ]
[Question] [ Given a string of different characters, and a number n, generate all the ordered combinations with repetition, of length 1 to n, using those characters. Another way to define it is to see the given characters as "custom" digits in the base (radix) of the number of characters, then the program should generate all the "numbers" with 1 to n digits in that base, however, leading "zeros" are included too. The combinations should be ordered by their length (1 character first, then 2, etc), but other than that they can be in any order. You can choose the most convenient ways of handling input and output. Shortest code wins. Examples: `ab, 3` -> `a,b,aa,ab,ba,bb,aaa,aab,aba,baa,abb,bab,bba,bbb` `0123456789, 2` -> `0,1,2,3,4,5,6,7,8,9,00,01,...,09,10,11,...,99` [Answer] # Python 2, 56 bytes `n` is the maximum length and `s` is expected to be a list of characters. It is not clear to me whether *n = 0* or an empty character list are valid inputs, but this function also handles them correctly. ``` f=lambda s,n:n*s and s+[x+c for x in f(s,n-1)for c in s] ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 bytes[SBCS](https://github.com/abrudz/SBCS) ``` ⊃,/,¨∘.,\⎕⍴⊂⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/@v8ahvql/wo941mnqPevvUgTznSHX14sScEnX1R90tQH6wq16os68LkNs2ISm/QiE/T0E3zRZEltiWFKWmAiW6FqfmJSblpAY7@oSANPWuUecC6szMB2ox4HrU0Z72/1FXs46@zqEVjzpm6OnEACUf9W551NX0qHfef6D8/zSuxCQuYy51da40LgNDI2MTUzNzC0suIwA "APL (Dyalog Unicode) – Try It Online") never miss an opportunity to use a scan :) prompts for a string of "digits" and then for `n` thanks @Adám for telling me how to enable `]box` on TIO [Answer] ## J, 41 char ``` f=.}:@;@({@(,&(<',')@(]#<@[))"1 0>:@i.@]) 'ab' f 3 a,b,aa,ab,ba,bb,aaa,aab,aba,abb,baa,bab,bba,bbb ``` [Answer] ## APL (31) ``` {,/⍺∘{↓⍉⍺[1+(⍵⍴⍴⍺)⊤⍳⍵*⍨⍴⍺]}¨⍳⍵} ``` Usage: the left argument is the string and the right argument is the number, like so: ``` 'ab'{,/⍺∘{↓⍉⍺[1+(⍵⍴⍴⍺)⊤⍳⍵*⍨⍴⍺]}¨⍳⍵}3 b a ab ba bb aa aab aba abb baa bab bba bbb aaa ``` The output is ordered by length, but within the length groups they are shifted one to the left, this was easiest. Explanation: * `,/⍺∘{`...`}¨⍳⍵`: for 1..⍵, apply the function to ⍺ and join the results together. * `(⍵⍴⍴⍺)⊤⍳⍵*⍨⍴⍺`: for each number from 1 to (⍵=(current length))^(⍴⍺=(amount of chars)), convert to base ⍴⍺ using ⍵ digits. * `1+`: add one because arrays are 1-indexed. * `⍺[`...`]`: use these as indexes into the string * `↓⍉`: rotate the matrix, so the 'numbers' are on the rows instead of in the columns, and then split the matrix up by rows. [Answer] # Haskell, 34 characters ``` x%n=do k<-[1..n];mapM(\_->x)[1..k] ``` Straightforward use of the list monad. The only real golfing is the use of `mapM` instead of the more idiomatic (and shorter) `replicateM` which would require importing `Control.Monad`. **Usage** ``` > "ab" % 3 ["a","b","aa","ab","ba","bb","aaa","aab","aba","abb","baa","bab","bba","bbb"] ``` [Answer] # Python, 97 94 ``` from itertools import* s,n=input() L=t=[] exec"t=t+[s];L+=map(''.join,product(*t));"*n print L ``` `t=t+[s]` can't be shortened to `t+=[s]` because L and t would be pointing to the same list. Input: `'ab', 3` Output: ``` ['a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bb a', 'bbb'] ``` [Answer] # Mathematica ~~29 19~~ 28 ``` Join@@(i~Tuples~#&/@Range@n) ``` **Usage** ``` i={a, 4, 3.2};n=3; Join@@(i~Tuples~#&/@Range@n) ``` > > {{a}, {4}, {3.2}, {a, a}, {a, 4}, {a, 3.2}, {4, a}, {4, 4}, {4, > 3.2}, {3.2, a}, {3.2, 4}, {3.2, 3.2}, {a, a, a}, {a, a, 4}, {a, a, > 3.2}, {a, 4, a}, {a, 4, 4}, {a, 4, 3.2}, {a, 3.2, a}, {a, 3.2, > 4}, {a, 3.2, 3.2}, {4, a, a}, {4, a, 4}, {4, a, 3.2}, {4, 4, a}, {4, > 4, 4}, {4, 4, 3.2}, {4, 3.2, a}, {4, 3.2, 4}, {4, 3.2, 3.2}, {3.2, > a, a}, {3.2, a, 4}, {3.2, a, 3.2}, {3.2, 4, a}, {3.2, 4, 4}, {3.2, > 4, 3.2}, {3.2, 3.2, a}, {3.2, 3.2, 4}, {3.2, 3.2, 3.2}} > > > [Answer] # MATL, ~~9~~ 8 bytes ``` x:"1G@Z^ ``` [Try it on MATL Online!](https://matl.io/?code=x%3A%221G%40Z%5E&inputs=%27abcd%27%0A3&version=20.9.1) (MATL was created after this challenge was posted, but I believe that's ok by meta consensus these days.) *(-1 bytes thanks to @Luis Mendo.)* `x` - delete string input from stack (automatically copies it to clipboard G) `:"` - implicit input of number n, loop from 1 to n `1G` - paste back the input string from clipboard G on the stack `@` - push the current loop iteration index `Z^` - cartesian power: cartesian product of input with itself `@` number of times The cartesian power results (`@`-digit "numbers" in the given base) are accumulated on the stack and implicitly displayed at the end. [Answer] # Python - 106 The straightforward, uncreative solution. If you find significant improvements, please post as a separate answer. ``` s,n=input() l=len(s) for i in range(1,n+1): for j in range(l**i):t='';x=j;exec't+=s[x%l];x/=l;'*i;print t ``` Input: `"ab",3` Output: ``` a b aa ba ab bb aaa baa aba bba aab bab abb bbb ``` [Answer] # Python, 100 Derived from [@aditsu's solution](https://codegolf.stackexchange.com/a/10976/7409). ``` s,n=input() L=len(s) i=0 while i<n:i+=1;j=0;exec"x=j=j+1;t='';exec't+=s[x%L];x/=L;'*i;print t;"*L**i ``` Input: `'ab', 3` Output: ``` b a ba ab bb aa baa aba bba aab bab abb bbb aaa ``` [Answer] ## [Perl 5](https://www.perl.org/) + `-nlF -M5.010 -MList::Util+(uniq)`, 41 bytes ``` $,=$"=",";say grep/./,uniq glob"{,@F}"x<> ``` [Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFyVZJR8m6OLFSIb0otUBfT1@nNC@zUCE9Jz9JqVrHwa1WqcLG7v//xCQuYy4DQyNjE1MzcwtLLqN/@QUlmfl5xf9183Lc/uv6muoZGBoAaZ/M4hIrq9CSzBxtDZBJmgA "Perl 5 – Try It Online") -1 byte thanks to [@Xcali](https://codegolf.stackexchange.com/users/72767/xcali)! [Answer] # Pyth, 6 bytes ``` s^LQSE ``` Expects the set of characters as 1st input, number of digits as 2nd. A byte could be saved if there were a single-byte method to repeatedly access the 2nd input, but alas... Try it online [here](https://pyth.herokuapp.com/?code=s%5ELQSE&input=%22abc%22%0A3&debug=0). ``` s^LQSE Implicit: Q=input 1, E=evaluate next input SE Range [1,2,...,E] ^LQ Perform repeated cartesian product of Q for each element of the above s Flatten ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 33 bytes ``` {flat [\X~] '',|[$^a.comb xx$^b]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzotJ7FEITomoi5WQV1dpyZaJS5RLzk/N0mhokIlLim29n9xYqVCmoZSYpKSjoKxpjUXlG9gaGRsYmpmbmEJFDfS/A8A "Perl 6 – Try It Online") Anonymous code block that takes a string and a number and returns a list of strings. [Answer] # PHP 180 I have no idea... I'm feeling lazy. ``` <?php $f=fgetcsv(STDIN);$l=strlen($f[1]);$s=str_split($f[1]);for($i=1;$i<=$f[0];$i++)for($j=0;$j<pow($l,$i);$j++){$o="";$x=$j;for($q=0;$q<$i;$q++){$o.=$s[$x%$l];$x/=$l;}echo"$o ";} ``` [Answer] ## Erlang 110 The Y combinator version (for shell): ``` fun(X, N)->F=fun(_,_,0)->[[]];(G, X, Y)->[[A|B]||A<-X,B<-G(G,X,Y-1)]end,[V||Y<-lists:seq(1,N),V<-F(F,X,Y)]end. ``` [Answer] ## Erlang 89 (118) Module version: ``` -module(g). -export([g/2]). h(_,0)->[[]];h(X,N)->[[A|B]||A<-X,B<-h(X,N-1)]. g(X,N)->[V||Y<-lists:seq(1,N),V<-h(X,Y)]. ``` Chars counted without mandatory bookkeeping (module and export). [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes Explanations to follow. ``` õ!àUçV)mâ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9SHgVedWKW3i&input=MwoiYWIi) ``` õ_çV àZ â ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9V/nViDgWiDi&input=MwoiYWIi) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` WẋŒpƤẎ ``` [Try it online!](https://tio.run/##y0rNyan8/z/84a7uo5MKji15uKvv////0YY6Rjqmsf@NAQ "Jelly – Try It Online") Function submission, taking the list of digits as the first argument and the number of digits as the second. The digits themselves can be any of Jelly's data types, but I used integers in the TIO link above because it produces the best-looking output in Jelly's automatic “function → full program” wrapper. ## Explanation ``` WẋŒpƤẎ (called with arguments, e.g. [1,2,5], 3) Wẋ Make {argument 2} copies of {argument 1} (e.g. [[1,2,5],[1,2,5],[1,2,5]) Ƥ For each prefix: (e.g. 1-3 copies of [1,2,5]) Œp take Cartesian product of its elements Ẏ Flatten one level ``` The Cartesian product effectively gives us all numbers with a given number of digits (according to which prefix we're working with). So we end up with a list of lists of combinations (grouped by length), and can flatten that one level in order to get a list that isn't grouped (but which is still *sorted* by length, as the question requires, as `Ẏ` doesn't change the relative order of the elements and `Ƥ` tries shorter prefixes first). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 「˜Ùé ``` [Try it online](https://tio.run/##ARsA5P8wNWFiMWX//8Oj4oKsxZLLnMOZw6n//zMKYWI) or [verify all test cases](https://tio.run/##AS4A0f8wNWFiMWX/Mkb/w6PigqzFksucw5nDqf8swrY//zMKYWIKMgowMTIzNDU2Nzg5). **Explanation:** ``` ã # Cartesian product of the second input repeated the first input amount of times # i.e. 3 and 'ab' → ['aaa','aab','aba','abb','baa','bab','bba','bbb'] €Œ # Take all the substrings for each of those results # i.e. 'aba' → ['a','ab','aba','b','ba','a'] ˜ # Flatten the list of lists Ù # Remove all duplicated values é # Sort the list by length ``` --- **6-bytes alternative:** NOTE: Flexible output: Outputs a new list for every length, all on the same print-line. Converting it to a single list would be 2 bytes longer: `Lv²yã`})` ([Try it online](https://tio.run/##MzBNTDJM/f/fp@zQpsrDixNqNf//N@ZKTAIA)). ``` Lv²yã? ``` [Try it online](https://tio.run/##MzBNTDJM/f/fp@zQpsrDi@3//zfmSkwCAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/k5ul5aGXxf5@yQ@sqDy@2/197aJvOf2OuxCQuIy4DQyNjE1MzcwtLAA). **Explanation:** ``` Lv # Loop `y` in the range [1, integer_input] ²yã # Take the second input and create an `y` times repeated cartesian product of it # i.e. y=2 and 'ab' → ['aa','ab','ba','bb'] ? # Print this list (without new-line) ``` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 17 bytes ``` {,/(,/,'/:)\x#,y} ``` [Try it online!](https://tio.run/##tdJLasMwFIXheVYR3EJtcBu9H9Y2MksDkQcJJSWFjBJCunVXv7SGDs6HJcRFutfn98vpsizH6TFu@nEzvm2m4fP2Mt6fy3Z6vO7uv9fpuP5Y39Lh55z6wzF/fadbuqfrsH@utrtepy7P3ZD6Lnepm0ty/YDMcm57bbPt1u92oh2p5rkdL9X2/1g5T30nylKWqBJdYkpsiSvxJaEkloh6EBRoMGDBgYcAEQRlZa0NGgxYcOAhQATBJSSoeh0wYMGBhwARBFeWoEDXF4AFBx4CRN0NqzzyaF4pQYEGU18ODjwEiCDoiQQFGgzY2izwECCCoIMSFGgwYMHV/kKACIJ@S1CgwYAFB76OBCIIpiNBgQYDFlwov0x7sGcd6ixBMFEJCjQYsODAQ4AYKVP@QsVMlTbW@cBe3i9/ "K (ngn/k) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~73~~ 64 bytes ``` ->s,n{c=s.chars;(0...n).flat_map{c.product(*[c]*_1)}.map{_1*''}} ``` ### 66 byte version because TIO doesn't support `_1` ``` ->s,n{c=s.chars;(0...n).flat_map{|i|c.product(*[c]*i)}.map &:join} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165YJ6862bZYLzkjsajYWsNAT08vT1MvLSexJD43saC6JrMmWa@gKD@lNLlEQys6OVYrU7NWDyijoGaVlZ@ZV/u/QCEtWikxSUlHwTiWC8wxMDQyNjE1M7ewBAoaxf4HAA "Ruby – Try It Online") ]
[Question] [ Equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in a sequence A: ``` A[0]=-7 A[1]=1 A[2]=5 A[3]=2 A[4]=-4 A[5]=3 A[6]=0 ``` 3 is an equilibrium index, because: ``` A[0]+A[1]+A[2]=A[4]+A[5]+A[6] ``` 6 is also an equilibrium index, because: ``` A[0]+A[1]+A[2]+A[3]+A[4]+A[5]=0 ``` (sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A. The idea is to create a program that given a sequence (array), returns its equilibrium index (any) or -1 if no equilibrium indexes exist. [Answer] ### Golfscript 17 16 Since the form of the input isn't specified, this takes a string in Golfscript array format from stdin. ``` ~0\{1$+.@+\}/])? ``` So run as e.g. ``` golfscript.ry eqindex.gs <<<"[-7 1 5 2 -4 3 0]" ``` The idea is very simple: it takes an array of `A_i` and maps to an array of `A_i + 2 SUM_{j<i} A_j` and then looks for the first index which is equal to the sum of the whole array. --- For @mellamokb's challenge I offer: ``` ~0\{1$+.@+\}/:S;]:A,,{A=S=},` ``` for 29 chars. [Answer] ## Python - 72 chars ``` A=input() print[i for i in range(len(A))if sum(A[:i])==sum(A[i+1:])]or-1 ``` Takes comma separated input [Answer] ## Haskell (~~95~~ 83) ``` e l=[n|n<-[0..length l-1],sum(take n l)==sum(drop(n+1)l)] main=interact$show.e.read ``` Reads a list in Haskell style from stdin, eg. ``` [-7,1,5,2,-4,3,0] ``` and returns a Haskell style list of the indices, eg. ``` [3,6] ``` The result is `[]`, if there is no index. Please tell me, if your spec wants a different behavior. ### Edits: * (95 → 83): list comprehension is more breve [Answer] ## C - 96 ``` a[99],*p=a,s;main(){for(;scanf("%d",p)>0;s+=*p++ );for(;p>a;s-=*p)(s-=*--p)||printf("%d\n",p-a);} ``` Note that this prints the equilibrium indices in reverse order. Sample usage: ``` $ ./equilibrium <<< "-7 1 5 2 -4 3 0" 6 3 ``` [Answer] ## Ruby (~~83~~ 77) ``` a=*$<.map(&:to_i) p (0...a.size).select{|x|a[0..x].reduce(:+)==a[x..-1].reduce(:+)} ``` Edit: Shorter version as suggested by Ventero: ``` a=$<.map &:to_i p (0...a.size).select{|x|eval"#{a[0..x]*?+}==#{a[x..-1]*?+}"} ``` Input is one number per line, output is comma separated list of indexes in square brackets. [Answer] ## JavaScript (161) ``` P=parseInt;L=prompt().split(',');S=function(A)A.reduce(function(a,b)P(a)+P(b),0);R=[i for(i in L)if(S(L.slice(0,i))==S(L.slice(P(i)+1)))];alert(R.length>0?R:-1); ``` <http://jsfiddle.net/6qYQv/1/> [Answer] ### scala, 108 ``` val l=readline().split(" ").map(w=>w.toInt) for(i<-0 to l.length-1 if l.take(i).sum==l.drop(i+1).sum)yield i ``` [Answer] ## J (12 characters) A monadic verb in tacit notation that returns a vector of equilibrium indices. Spaces inserted for legibility only. ``` [: I. +/\. = +/\ ``` To explain this, first observe its explicit definition; `y` is the formal parameter: ``` 3 : 'I. (+/\. y) = (+/\ y)' ``` * `+` adds its arguments. `/` is an adverb that inserts the verb left of it between the members of its right argument, e.g. `+/ 1 2 3 4` is the same as `1 + 2 + 3 + 4`. * `\` is an adverb that applies the verb to its left to all prefixes prefixes of its right argument. For instance, with `<` drawing a box around its argument, `<\ 1 2 3 4` produces ``` ┌─┬───┬─────┬───────┐ │1│1 2│1 2 3│1 2 3 4│ └─┴───┴─────┴───────┘ ``` * Thus, `+/\` computes for each prefix of its right argument the sum. * `\.` is like `\` but operates on suffixes instead of prefixes. Thus, `+/\.` computes a vector of sums of suffixes. * `=` performs item-wise comparison of its arguments. For instance, `1 1 3 3 = 1 2 3 4` yields `1 0 1 0`. * Thus, `(+/\. y) = (+/\ y)` yields one for all indices at which the suffix sum is equal to the prefix sum, or, an equilibrium is created. * For vectors of zeroes and ones, `I.` returns a vector of the indices at which the vector contains a one. [Answer] # Python 2, 70 ``` A=input() e=i=s=0 for x in A:e=[e,~i][s*2==sum(A)-x];s+=x;i+=1 print~e ``` The idea is to track the running sum `s` and check whether it is half of the sum of array without the current element, and therefore equal to the sum of the array after the current element. If so, we update the equilibrium index to the current index. The last equilibrium index is printed, or the initial value `-1` if there's none. Actually, we store the bit-complement of the equilibrium index so that we can initialize it to 0 instead. [Answer] # Python - 114 ``` i=map(lambda x:int(x),raw_input().split(" "));x=0 print map(lambda x:(sum(i[0:x])==sum(i[x+1::])),range(0,len(i))) ``` # Python - 72 ``` i=input() print map(lambda x:sum(i[0:x])==sum(i[x+1::]),range(0,len(i))) ``` Prints whether or not the given index is an equilibrium index, does not print the integer indecies at which the array is balanced. [Answer] # PHP, 134 chars ``` <?for($a=explode(",",fgets(STDIN));++$i<($c=count($a));$o.=$s==0?$i:"")for($n=$s=0;$n<$c;)$s+=$n<$i?$a[$n++]:-$a[++$n];echo$o?$o:"-1"; ``` I have an itch that this is far from optimal PHP golfing, but just ran out of steam (brains). At least it's shorter than with array\_sum and array\_splice :-) [Answer] # PHP (81) `for($i=count($a)-1,$c=0;$i+1&&$c!=(array_sum($a)-$a[$i])/2;$c+=$a[$i--]);echo $i;` <http://3v4l.org/qJvhO> Since no input was specified, this needs to be initialised with the array as the variable `$a`. ]
[Question] [ Write a program that, given a small positive even integer from standard input, calculates the probability that flipping that many coins will result in half as many heads. For example, given 2 coins the possible outcomes are: ``` HH HT TH TT ``` where H and T are heads and tails. There are 2 outcomes (`HT` and `TH`) that are half as many heads as the number of coins. There are a total of 4 outcomes, so the probability is 2/4 = 0.5. This is simpler than it looks. Test cases: ``` 2 -> 0.5 4 -> 0.375 6 -> 0.3125 8 -> 0.2734375 ``` [Answer] ## J, 22 ~~19~~ (killer approach) I got down to this while golfing my Haskell answer. ``` %/@:>:@i.&.(".@stdin)_ ``` (same I/O as [my other J answer](https://codegolf.stackexchange.com/questions/1209/calculate-probability-of-getting-half-as-many-heads-as-coin-tosses/1221#1221)) [Answer] # Pari/GP - 32 30 34 chars ``` print(binomial(n=input(),n\2)/2^n) ``` [Answer] **Python 53 Characters** ``` i=r=1.;exec"r*=(2*i-1)/i/2;i+=1;"*(input()/2);print r ``` [Answer] ## Excel, 25 Not quite according to spec, though :) Name a cell `n` and then type the following into another cell: ``` =COMBIN(n,n/2)/POWER(2,n) ``` [Answer] ## Haskell, 39 ~~43~~ ~~46~~ ``` main=do x<-readLn;print$foldr1(/)[1..x] ``` Demonstration: ``` $ runhaskell coins.hs <<<2 0.5 $ runhaskell coins.hs <<<4 0.375 $ runhaskell coins.hs <<<6 0.3125 $ runhaskell coins.hs <<<8 0.2734375 ``` [Answer] ## J, 25 (natural approach) ``` ((!~-:)%2&^)&.(".@stdin)_ ``` Sample use: ``` $ echo -n 2 | jconsole coins.ijs 0.5 $ echo -n 4 | jconsole coins.ijs 0.375 $ echo -n 6 | jconsole coins.ijs 0.3125 $ echo -n 8 | jconsole coins.ijs 0.273438 ``` It's all self-explanatory, but for a rough split of responsibilities: * `!~ -:` could be thought of as *binomial(x,x/2)* * `% 2&^` is "divided by *2^x*" * `&. (". @ stdin) _` for I/O [Answer] ## GNU Octave - 36 Characters ``` disp(binopdf((n=input(""))/2,n,.5)); ``` [Answer] ## Ruby, 39 characters ``` p 1/(1..gets.to_i).inject{|a,b|1.0*b/a} ``` [Answer] ## Golfscript - 30 chars Limitation - only works for inputs less than 63 ``` '0.'\~..),1>\2//{{*}*}%~\/5@?* ``` test cases ``` $ echo 2 | ruby golfscript.rb binom.gs 0.50 $ echo 4 | ruby golfscript.rb binom.gs 0.3750 $ echo 6 | ruby golfscript.rb binom.gs 0.312500 $ echo 8 | ruby golfscript.rb binom.gs 0.27343750 ``` Analysis `'0.'` GS doesn't do floating point, so we'll fake it by writing an integer after this `\~` Pull the input to the top of the stack and convert to an integer `..` Make 2 copies of the input `),1>`Create a list from 1..n `\2//`Split the list into 1..n/2 and n/2+1..n `{{*}*}%`Multiply the elements of the two sublists giving (n/2)! and n!/(n/2)! `~`Extract those two numbers onto the stack `\`Swap the two numbers around `/`Divide `5@?*`Multiply by 5\*\*n. This is the cause of the limitation given above [Answer] # TI-BASIC, 10 This will take more than ten bytes of calculator memory because there is a program header, but there are only ten bytes of code. ``` binompdf(Ans,.5,.5Ans //Equivalently: 2^~AnsAns nCr (.5Ans ``` This takes input in the form `[number]:[program name]`; adding an Input command uses three more bytes. `~` is the unary minus token. [Answer] # Ruby - 50 57 54 chars ``` p (1..(n=gets.to_i)/2).reduce(1.0){|r,i|r*(n+1-i)/i/4} ``` [Answer] ## J, 20 ``` f=:(]!~[:<.2%~])%2^] ``` examples: ``` f 2 0.5 f 4 0.375 f 6 0.3125 f 8 0.273438 ``` [Answer] **APL 21 15 chars** ``` ((N÷2)!N)÷2*N←⎕ ``` For where it doesn't render right ``` ((N{ColonBar}2)!N){ColonBar}2*N{LeftArrow}{Quad} ``` Where everything in {} are APL specific symbols like [here](http://en.wikipedia.org/wiki/APL_%28codepage%29). [Answer] # Windows PowerShell, 45 ``` ($p=1)..($n="$input"/2)|%{$p*=(1+$n/$_)/4} $p ``` Meh. [Answer] # MATLAB, 29 ``` n=input('');binopdf(n/2,n,.5) ``` [Answer] ## PostScript, 77 ``` ([)(%stdin)(r)file token{2 idiv}if def 1 1 1[{[exch div 1 add 4 div mul}for = ``` [Answer] ## Mathematica, 19 ``` f=2^-# #!/(#/2)!^2& ``` [Answer] # Javascript, 86 bytes ``` a=prompt(f=function(n){return n?n*f(n-1):1});alert(f(a)/(f(a/2)*f(a/2)*Math.pow(2,a))) ``` [Answer] # Python 3, 99 This is a naive approach, I suppose, and fR0DDY's solution is much cooler, but at least I am able to solve it. [**Try it here**](https://ideone.com/lboisi) ``` from itertools import* n=int(input()) print(sum(n/2==i.count("H")for i in product(*["HT"]*n))/2**n) ``` # Python 2, 103 ``` from itertools import* n=int(raw_input()) print sum(n/2==i.count("H")for i in product(*["HT"]*n))/2.**n ``` [Answer] # Objective-C: ## 152 148 bytes for just the function. Class methods, headers, and UI are not included within the code. Input: an `int` value determinining the number of coins. Output: a `float` value determining the probability. ``` -(float)calcPWithCoins:(int)x {int i=0;int j=0;for (int c=x;c<1;c+-){i=i*c;} for(int d=x/2;d<1;d+-){j=j*d;} return (((float)i/(float)j)/powf(2,x));} ``` ## Ungolfed: ``` -(float)calcPWithCoints:(int)x { int i = 0; int j = 0; for (int c = x; c < 1; c+-) { i = i * c; } // Calculate the value of x! (Factorial of x) for (int d = x / 2; d < 1; d+-) j = j * d; } // Calculate (x/2)! (Factorial of x divided by 2) return (((float)i / (float)j) / powf(2, x)); /* Divides i! by (i/2)!, then divides that result (known as the nCr) by 2^x. This is all floating-point and precise. If I didn't have casts in there, It would be Integer division and, therefore, wouldn't have any decimal precision. */ } ``` This is based off of the [Microsoft Excel answer](https://codegolf.stackexchange.com/a/1232/42145). In C and Objective-C, the challenge is in hard-coding the algorithms. ]
[Question] [ ## The Challenge Given two vertexes and a point calculate the distance to the line segment defined by those points. This can be calculated with the following psudocode ``` def dist(point, v1, v2): direction := normalize(v2-v1) distance := length(v2-v1) difference := point - v1 pointProgress := dot(difference, direction) if (pointProgress <= 0): return magnitude(point - v1) else if (pointProgress >= distance): return magnitude(point - v2) else normal := normalize(difference - (direction * pointProgress)) return dot(difference, normal) ``` Answers may support either 2 dimensions, or 3, and may optionally support any number of higher or lower dimensions. As it does not substantially change the difficulty of the challenge, answers need only be accurate to the whole number, and I/O can be assumed to fit within the [0,127] range. This is to allow more languages to focus only on the challenge spec, rather than implementing floating points. ## Test Cases ``` 1: point=[005,005], v1=[000,000] v2=[010,000] :: distance=005.00 # Horizontal 2: point=[005,005], v1=[010,000] v2=[010,010] :: distance=005.00 # Vertical 3: point=[000,010], v1=[000,000] v2=[010,010] :: distance=007.07 # Diagonal 4: point=[010,000], v1=[000,000] v2=[010,010] :: distance=007.07 # Diagonal, Clockwise 5: point=[000,000], v1=[002,002] v2=[004,008] :: distance=002.83 # Not near the normal 6: point=[000,002], v1=[002,002] v2=[002,002] :: distance=002.00 # Zero length segment ``` ## Rules * [Standard IO Applies](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes wins! * Have Fun! [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` 9W&ZS-|X< ``` Supports two dimensions. Inputs are complex numbers: first the segment endpoints, then the other point. Try at [MATL it online](https://matl.io/?code=9W%26ZS-%7CX%3C&inputs=0%0A0%2B10j%0A5%2B5j&version=22.7.4)! Or [verify all test cases](https://tio.run/##y00syfmf8N8yXC0qWLcmwua/S8h/Ay4DbUODLC5TbdMsLkMDIEJw4TwQRuJwGWkbZXGZaFuARMFsCJEFAA). ### Explanation ``` 9W % Push 9. Compute 2 raised to that number, that is, 512 &ZS % Implicit inputs: segment endpoints. Generate vector of 512 evenly % spaced numbers in the range defined by the endpoints, including them - % Implicit input: point. Subtract, element-wise | % Absolute value of each entry X< % Minimum. Implicit display ``` [Answer] # [R](https://www.r-project.org), ~~34~~ 33 bytes *Edit: -1 byte thanks to Giuseppe* ``` \(p,a,b)min(abs(p-seq(a,b,,1e4))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rZKxTsMwFEUlxn6FEYujupFtihoVZYKBiZEBsbjhkVokdrBNkPgVljCw8EfwNbwmDSnQoZUYLOte-93jZ_vl1TXvt9qHYD3k6dtjuJskH4c3tGKKLaJSG6oWnlYTDw8UHcYETKMo6jZ-HujKahNSzk_GOPQpqQUKjoKvhEy56MU3hbY1rBaslhE5IvN5u6ZMBqugmHM0L6zTz9YEVYy2IcRvhNgfcQUu6GwD0Mds7WEfwCzmMzTPtcqtGQDDof8ZMCZnhc3un7SHzWYGlkQh1yw-RZHszpJxcozmpQ3EgHIkLIEY68qfF9fF_2H1YmdW-zLX4CwpwORhSbCmBBNG3Y9rmm7-Ag) Input point `p` and segment endpoints `a` and `b` as complex numbers. Approach copied from [Luis Mendo's answer](https://codegolf.stackexchange.com/a/264696/95126): upvote that! Accuracy can be improved by changing `1e4` to a higher value (for instance, `1e9` without increasing code-length), but as-is it's easily within the ±1 accuracy in the x,y-range of 0–127. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~65~~ 61 bytes ``` UMθ₂ΣXE§θ⊕κ⁻λ§ιμ²≔§θ⁰η≔⎇η⊗∕₂Π⁻⊘Σθ⁺θ⟦⁰⟧η⌈θζI⎇›X⌈θ²⁺Xη²Xζ²⌊Φθκζ ``` [Try it online!](https://tio.run/##TU89a8MwEN37KzSeQQUTOgQ6hYS2GQIm6WY0qLaoRPRRy5Kb5s@rJzlus@jQvXfvo5Pcd47rlA78a@uM4baHgZLTELkXR@cCnKKBxn0LD0iBTdjbXlwyZ287L4ywQfRwripKDsrGETQlC0lRYqqMrPCtnh8246g@7b1GjaD8R96Ft9z/gKRk5@KHRuWdmlQv4C5Q410fuwCz3RvXE9JyyiFbNRqXqNzWrCreskTjF2UWyhUNG69sgC0fw5/pqxc8YM2l7HKR4990Z0jeNuVznduV9uXgRemsghHOsxk2T6lt2xUyGQZ7omSdZ431GWPpcdK/ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of the two vertices and the point. Explanation: ``` UMθ₂ΣXE§θ⊕κ⁻λ§ιμ² ``` Calculate the lengths of the sides of a triangle with the given points. ``` ≔§θ⁰η ``` Get the base of the triangle separately. ``` ≔⎇η⊗∕₂Π⁻⊘Σθ⁺θ⟦⁰⟧η⌈θζ ``` Unless the base is zero, divide the triangle's area by it and double the result, giving the altitude. ``` I⎇›X⌈θ²⁺Xη²Xζ²⌊Φθκζ ``` Determine whether the base of the triangle contains the foot, and if so, output the altitude, otherwise output the shorter of the other two sides. ~~58~~ 54 bytes taking complex numbers as input: ``` UMθ↔⁻ι§θ⊕κ≔§θ⁰η≔⎇η⊗∕₂Π⁻⊘Σθ⁺θ⟦⁰⟧η⌈θζI⎇›X⌈θ²⁺Xη²Xζ²⌊Φθκζ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVC9TsMwGBQrTxF1-qKmUhQxRGKqWlE6RIooW5TBSVzi1rGJf0Lpq7B0AMHK6_A0fE5SioeTvrv77my_fZU1UaUk_HT6sGY7i3-u4oQ8L2TTEFFBG3jzQktuDYWECauBIWPWoqIHJ65FqWhDhaEV7H13bq_nWrMnAf9coR949UV5pEoQ9Qp14C2lLTjuLlnHKgqb1hJFH6Q0kCpZ2dKMrfeEd2jb2AZaH9NSjiQmZ2HuSl08QkIOrDlbjliYKiYMLIg2f6UrRYmhClL5gnjZCLzonDtI9cj0w9ENfQUT_cId4y4Fr7AfyvDl77oo9fiNn9lk1vFJ_p1l0TTaBd7NNEYM83zQfwE "Charcoal – Attempt This Online") Link is to verbose version of code. [Answer] # [J](https://www.jsoftware.com), 32 bytes ``` [:(1#.&.:*:[-]*1<.0>.%. ::0)/-"1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmtxUyHaSsNQWU9Nz0rLKlo3VsvQRs_ATk9VT8HKykBTX1fJEKquX5MrNTkjH6jfQCFNwRQIdawUDIE8iLAhurihAbJ6EB-rBFgfqoQREKYpQMVNFCxQRY1AokAOxFkLFkBoAA) Takes input as `v1 f point ,: v2` (a vector `v1` on the left side, and a two-row matrix containing `point` and `v2` on the right side). Supports arbitrary dimensions. The main approach is to translate `v1` to origin and compute the [vector component](https://codegolf.stackexchange.com/q/205891/78410) of `point` onto `v2`. When the value is clamped to the range `[0, 1]`, that times `v2` becomes the point on the line segment that is closest to `point`. Then we can compute the norm of the difference. ``` [:(1#.&.:*:[-]*1<.0>.%. ::0)/-"1 left: v1, right: point ,: v2 -"1 (point - v1) ,: (v2 - v1) [:( )/ run dyadically with the two rows as two args: %. ::0 vector component 1<.0>. clamp to [0,1] [-]* get the distance vector 1#.&.:*: norm of the vector ``` `::0` attached to `%.` handles the case of zero-length line segment (if it would throw an error, return 0 instead). `&.:*:` is a fancy way of saying "square something, do something on it, and take its square root". # [J](https://www.jsoftware.com), 23 bytes ``` [:([|@-]*1<.0>.9 o.%)/- ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxPdpKI7rGQTdWy9BGz8BOz1IhX09VU18XInuzX5MrNTkjX8Egy0AhTcE0y1RBx0rBEMiDCBuiixsaIKsH8bFKgPWhShhlGYF1gMVNsixQRY1AokAOxFkLFkBoAA) Same algorithm, but takes a complex number for each vector instead, therefore supporting only two dimensions. `%.` is replaced with `%` (division) followed by `9 o.` (extract real part). Norm is simply `|`. [Answer] # [JavaScript (Node.js)](https://nodejs.org/en), ~~146~~ ~~144~~ ~~140~~ 156 bytes -2 bytes because of oversight noted by @noodleman -4 bytes thanks to @TheThonnu's suggestion +16 bytes because I noticed my own error with the solution Algorithm somewhat yoinked from @Neil's [Charcoal answer](https://codegolf.stackexchange.com/a/264695/95056), though with a slightly different method for handling the "segment" of "line segment." ``` (a,b,c,d,e,f,S=Math.sqrt)=>((x,y,z)=>Math.min(S((x+y+z)*(x+y-z)*(x-y+z)*(y+z-x))/2/x,y,z))(S((f-d)**2+(e-c)**2),S((f-b)**2+(e-a)**2),S((d-b)**2+(c-a)**2)) ``` `(a,b)` is the point, `(c,d)` is vertex 1, `(e,f)` is vertex 2. Returns a float. ## Versions ### Version 1 (original + oversight fix) (INCORRECT—SEE COMMENTS) ``` (S=>(a,b,c,d,e,f)=>((x,y,z)=>S((x+y+z)*(x+y-z)*(x-y+z)*(y+z-x))/2/x)(S((f-d)**2+(e-c)**2),S((f-b)**2+(e-a)**2),S((d-b)**2+(c-a)**2)))(Math.sqrt) ``` [Try this old version online!](https://tio.run/##PYo7DoMwEESvs2PvBomelOlScYLFNiIp8gErMlzeMSTQzLx5mrt@dHLj7RXl8fQhX5pMbXMm5Y4dew7co0xKPPNSqC1oZ7vArC1by2@XlARUdZVA5deLhzG1pSBuBfAmu13qIf0u3V8CdNU4nKb3GJHzFw) ### Version 2 (uses default arg instead of separate call) (INCORRECT—SEE COMMENTS) ``` (a,b,c,d,e,f,S=Math.sqrt)=>((x,y,z)=>S((x+y+z)*(x+y-z)*(x-y+z)*(y+z-x))/2/x)(S((f-d)**2+(e-c)**2),S((f-b)**2+(e-a)**2),S((d-b)**2+(c-a)**2)) ``` [Try this old version online!](https://tio.run/##PYo7DsIwEESvs2vPEim9KemocoKN7Qgo@CQWcnJ54wRCM/PmaW761smP12eS@yPEcnKFFD08AiIGdO6s6XKYXmNidyTKmLFU6ira2S5s1pat5btrSmZu2iYz1d8ggY1pLUXxKzA22e9S/zLs0v8kl/IB) ### Version 3 (current, fixes issue with solution) ``` (a,b,c,d,e,f,S=Math.sqrt)=>((x,y,z)=>Math.min(S((x+y+z)*(x+y-z)*(x-y+z)*(y+z-x))/2/x,y,z))(S((f-d)**2+(e-c)**2),S((f-b)**2+(e-a)**2),S((d-b)**2+(c-a)**2)) ``` ## Explanation ``` (a,b,c,d,e,f,S=Math.sqrt)=>(...) ``` The function declaration. Uses `S` as a default argument in this version instead of a different call. ``` ((x,y,z)=>...)(S((f-d)**2+(e-c)**2),S((f-b)**2+(e-a)**2),S((d-b)**2+(c-a)**2)) ``` This is slightly more efficient than declaring `x,y,z` as variables outright—it uses another one of those define-exec chains. (Is there a canon term for this?) `x,y,z` are the side lengths for a triangle with vertices at the three points, with `x` being the length of the segment between the two vertices. **THIS IS IMPORTANT.** To find these, I just used the bog-standard distance formula. Nothing special here. ``` Math.min(S((x+y+z)*(x+y-z)*(x-y+z)*(y+z-x))/2/x,y,z) ``` The final part. This calculates the area with [a slightly modified] [Heron's formula](https://en.wikipedia.org/wiki/Heron%27s_formula), and then works backwards to find the height with one tiny optimization. It also accounts for the cases where the endpoints are closer with a `Math.min()` call. ## Links [Try this online!](https://tio.run/##PcvBDoIwDAbg12m3VhLu8@jNE09QthEwERUWA7z83AZ46f/3S/uQr8x2Gt6Bx5fz8WYiCLVkyZGnjhpzl9Bf5s8U0FwBFlppS63ocxihSaZXvaHKySV539PkBbGqq/0L83HHDpWqNXi2uSAVbE@UP7oT7YEY4w8) This is a link to the golfed version. The verbose version no longer exists as of v2. [Answer] ## Mathematica (Wolfram Language) 33 bytes ``` RegionDistance[Line[{#2, #3}],#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pyg1PTM/zyWzuCQxLzk12iczLzW6WtlIR0HZuDZWRzlW7X9AUWZeSXRadLWBjgIQGdXqgFhGqKzY2P8A) This uses Mathematica built-ins, but this program has the benefit of working in any dimension. You could use Mathematica graphics options to see the computation graphically. The TIO link above has the last of the test cases, but in 3D instead of 2D! ]
[Question] [ [Sandbox](https://codegolf.meta.stackexchange.com/a/18384/78850) *Adapted from exercise 8 of [100 little Keg exercises](https://github.com/JonoCode9374/100-Little-Keg-Exercises)* String manipulation is a very important part of any programming language. Consequently, that is what this challenge is about. ## The Challenge I want you to write a program that: * Takes a series of characters as input and, * Then takes another input (integer/letter) (we'll call this `instruction`) and, * Takes a single integer (we'll call this `times`) as the last input and then, * If `instruction` is equal to the letter `R`: + Reverse the string `times` times. * Otherwise, if `instruction` is equal to the letter `l`: + Shift the string left `times` times * Otherwise, for all other values of `instruction`: + Shift the string right `times` times ## Test Cases ``` String, Instruction, Times -> Output "Howdy!", R, 1 -> "!ydwoH" "elloH", r, 1 -> "Hello" "tedShif", l, 3 -> "Shifted" "sn't it?Amazing, i", l, 8 -> "Amazing, isn't it?" ``` ## Rules * Input can be taken as *any* convenient format... if a list of three items works best for you, take the input as a list. If newline-separated input is how you choose to work, go ahead and use newline-separated input. * The string, instruction and times integer can be taken in any order * Output is also to be given in any convenient format. * The input string will *not* contain newlines, nor unprintable ascii characters. * You can substitute `R` and `l` for any other two characters, as long as you specify what the two characters are * All instructions are case sensitive. In other words, only input of `R` should reverse the string, not `r`. * The magnitude of a shift will always be less than the length of the string * The `times` integer is a positive integer (i.e. \$ n > 0 \$) ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the fewest bytes wins. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Full program. Prompts for the string, then `times`, then `instruction`: * `+` for reversal * `1` for left shift * any other character for right shift ``` (⍎⍕⊃¯1,⍨⍞∩'+1')⌽⍣⎕⊢⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L/Go96@R71TH3U1H1pvqPOod8Wj3nmPOlaqaxuqaz7q2fuod/GjPqDsIqAwSMN/BTAo4PLIL0@pVOQy5NLmggml5uTkewBFiuAiJakpwRmZaVzGQFGYWHGeeolCZom9Y25iVWZeuo5CJpcFlyEA "APL (Dyalog Unicode) – Try It Online") `⍞` prompt for string `⊢` on that, do the following: `⎕` prompt for `times` `(`…`)⌽⍣` apply the `⌽` function that many times, with the following to its left:  `∩'+1'` intersection of the following and `"+1"`:  `⍞` prompt for `instruction`  `¯1,⍨` append negative one  `⊃` pick the first one  `⍕` stringify  `⍎` evaluate (gives `1` or `-1` or the complex conjugate function `+`) The function `⌽` does a: * left shift if it has `1` on its left * right shift if it has `-1` on its left * reversal if it has any function on its left `+` negates the imaginary part of its argument but strings have no imaginary parts, so it does nothing   [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 65 bytes ``` lambda s,i,t:[s[(n:=[-t,t][i=='l']):]+s[:n],s[::(-1)**t]][i=='R'] ``` [Try it online!](https://tio.run/##XcnBCgIhFEDRfV8hbtTJWdRsQvAnZmsujDQFc@T5CPp6M4KINndxT31i3MpyqtCDPvfs7perI00mico0w4vSZkaJ1iStWWZWKLtvRhUrRxWfD2Ka0H54ZbZXSAV54BTSLSJpMQWkklAYOQqx@3r24YfzP4N/eGju/ek6sgjRXw "Python 3.8 (pre-release) – Try It Online") Abuses the de-facto ternary statement `[a,b][condition]`. * If `i=='R'`: + Return the string, read with step `(-1)**t`. This is `-1` (reversed) for odd `t` and `1` (not reversed) for even `t`. * Else: + Let `n` be `[-t,t][i=='l']`. This is `t` when left-shifting and `-t` otherwise (right-shifting). + Return the string, spliced accordingly: `s[n:] + s[:n]`. Thanks to Python's negative indexing, this works like a charm for both cases. [Answer] # [Python 2](https://docs.python.org/2/), 67 bytes ``` lambda s,t,i:[s[t:]+s[:t],s[::1-t%2*2],s[-t:]+s[:-t]]['lR'.find(i)] ``` [Try it online!](https://tio.run/##LYlBDsIgEADP@oq9GFpdTMQbiZ/winugInYt0gb24uuxJl4mmZnlI@OcTYuXW0v@PQQPFQXZuurE0qE6K4Qr7UnLzuzNT/T/aCFyKl3VMXIOHffU4lyAgTOosna73SyFswAjxE754R4e8Tnya0oKz8h9@wI "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 63 bytes ``` ->s,c,n{c==?R?[s,s.reverse][n%2]:s.chars.rotate(c==?l?n:-n)*''} ``` [Try it online!](https://tio.run/##RYxBb4IwFIDv/IpnxwK4UqPuYEwq2Y2zOyIxDIo0qWVp6wgz7q@zB8Z4aJt@3/eeuXz1Q80PQ7yztKT6WnKe7JPMUsuM@BHGijzTr6t8a1nZFAZp6wonwrFTid7GOpoHwW3oGqkEnISzHoB/BP4HCxKyeUQohCzC61C9RRDv4E4XmBlhgUOd@UsK/grPmrn2KHNU3xdnR0@B4MjLdUo5@O834gldDSRtu6qf4fI9heW0dtZXXZsSjwil8KVgHiYdCQonqs9G1qgUhfWkxj9ilFYHDqRLPs7Fr9QnCvLebabuSR8d@Qc "Ruby – Try It Online") An anonymous lambda that takes 3 arguments. If the instruction is `R`, it returns the original or the reversed version based on whether `n` is even or odd. Otherwise, it converts the string into a character array and `rotate`s that left or right based on the instruction specified (Ruby rotates left if the argument provided is positive) the joins the char array back together into a string using `*''`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` ²³F1¹QiRë0¹QiÀëÁ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0KZDm90MD@0MzAw6vNoARB9uOLz6cOP//wZcJakpwRmZaVzGAA "05AB1E – Try It Online") `1` instead of `R`, `0` instead of `l`. I'm new to this language, would appreciate if anyone could give me tips. ``` ²³F1¹QiRë0¹QiÀëÁ ²³ # Push the second and third inputs. F # Do the following [third input] times: 1¹Qi # If the first input is equal to 1, R # Reverse (at this point, the second input will be at the top of the stack). ë0¹Qi # Else-if the first input is equal to 0, À # Shift left. ëÁ # Else shift right. ``` [Answer] # [C (clang)](http://clang.llvm.org/), 72 bytes ``` j;f(char*s,z,i,t){for(j=0;j<z;++j)putchar(s[i?(z+t*i+j)%z:t%2?z+~j:j]);} ``` [Try it online!](https://tio.run/##bczLCsIwEIXhfZ9iDIiJHaFVvGCU4s69S3FRetEJNZV2RIzoq9foUtwN5/uZbJRVqT12ndGlzE5pM2zRISGrR1k30qwjbVZOh6FRlyt/AtnuKZEu5CH5se@W3B8nLnyZpTko/ezIMpxTsiDVIyil2Na3/N4TOEOIEGKlA/@olUL4y3NRVfVW4BRhFP9hLvLdiUqBc48Ik19v7YCBONmcU0f2iEAC48W3XfiiKfjaWIh08Oze "C (clang) – Try It Online") Input as: char\* , length, instruction(r=-1 , R=0 , l =1), times Loop into input string using a shifted index with modulo `i?(z+t*i+j)%z` or a `length - index -1` for reverse [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 32 bytes ``` pe{{so}{<-}{SO}{rt}{1}{RT}}cnjE! ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/ILW6uji/ttpGt7Y62L@2uqikttqwtjoopLY2OS/LVfH/fyWP/PKUSiUFQwUlJ0clAA "Burlesque – Try It Online") Takes arguments as: `"StringToMod" N "Op"` Where op is a reverse ordered string for reverse, a string in order for rotate right and anything else for rotate left, other short options or `op` could be space character, alpha character, other. If those are unacceptable input add 4 bytes for `{'R==}` & `{'r==}` as conditions. ``` pe # Push inputs to stack { {so} {<-} # If sorted push reverse {SO} {rt} # If reverse-sorted push rotate right {1} {RT} # Else push rotate left }cn # Condition on op jE! # Evaluate N times ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` Ḣ⁾lRi‘ịUṛ¡ṭṙN,$}¥ɗ ``` [Try it online!](https://tio.run/##ATwAw/9qZWxsef//4bii4oG@bFJp4oCY4buLVeG5m8Kh4bmt4bmZTiwkfcKlyZf///9sSGVsbG8gd29ybGQh/zU "Jelly – Try It Online") A dyadic link taking a Jelly string prepended with the instruction as its left argument (e.g. `RHello world`) and the integer as its right argument. Returns a Jely string. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 38 bytes ``` J.zKs@J2A<J2?qHd_FGK?qHN+>GK<GK+>KG<KG ``` [Try it online!](https://tio.run/##K6gsyfj/30uvyrvYwcvI0cbLyL7QIyXezd0bSPtp27l727h7a9t5u9t4u///X5ynXqKQWWLvmJtYlZmXrqOQyaXEZfEvv6AkMz@v@L@ubkpqUmk6AA "Pyth – Try It Online") This is a quite naive strategy but it works ¯\\_(ツ)\_/¯ Input is taken on three lines: the first is the input, second is the operation, third is the count. Substitute `R` for (space). Substitute `l` for `"` (double quote). [Answer] # [JavaScript (Node.js)](https://nodejs.org), 74 bytes ``` i=>n=>g=a=>n--?g(a.map((_,p)=>a[(i-1?i-2?L+p-1:p+1:L+~p)%L],L=a.length)):a ``` [Try it online!](https://tio.run/##rc69DoIwFEDh3afoYrg32MbqRlKIO29gjLliqUXsrYC/g6@O7o46ne3LaehKfdX5OMjAezvWZvQmDyZ3hj6VsnBA6kQRYDuLaHJag5e68HJRlGmUOoupzsr0FXFabmalIdXa4IYDYkZjxaHn1qqWHdSgEfQcYa2USlbifPHVUew6vgVR8100l1PsBV9tJ4aDFS09H2LPTiUbVA37AEmCOPkW9V/Fxd8fl7@L4xs "JavaScript (Node.js) – Try It Online") Input `i` (instruction, 1 = Reverse, 2 = Left, 3 = Right), `n` (times), `a` (array of characters). Output array of characters. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~27~~ 25 bytes ``` ≔×⌕RrηIζδF׬δIζ≦⮌θ⭆θ§θ⁻κδ ``` [Try it online!](https://tio.run/##TYyxCsIwFEX3fEXo9AJxcO5UBNGhRao/EJpnG4yJfS8W8edjCh28y73DuWeYDA3R@JwbZjcGuLknMhxdsFD1VGk5KS0PhhN8VVlW1eIeSW5cFxPYP0DJ1rw2U48LEqOWc/lcyIUE11RqLAjMWjbpHCx@1tm68GZ4rPqSOmf0Pp4EiX3eLf4H "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔×⌕RrηIζζ ``` Convert the third input to integer, then multiply it by the index of the second input in `Rr`. This leaves it zero if the second input is `R` and unchanged if it is `r` but it negates the third input if the second input is anything else. ``` F׬δIζ≦⮌θ ``` If the third input is now zero then reverse the first input the original number of times. ``` ⭆θ§θ⁻κζ ``` Shift the first input rightwards by the third input. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 11 bytes ``` :[‛ǔǓiĖ|_(Ṙ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiOlvigJvHlMeTacSWfF8o4bmYIiwiIiwiMlxuMVxuZWxsb0giXQ==) Uses `0` for reverse, `1` for shift left, and `2` for shift right. ]
[Question] [ Given 3 input items, a list of coordinate pairs, a 2D string, and a single-character string, output whether the character at each coordinate of the 2D string is equal to the single character. You can take the input in any order and the coordinates may be 1-indexed. You may take the 2D string as a 2D list, a list of lines, or a 2D string. Example: `(0,0), "#_\n__", "#" -> True` The string is ``` #_ __ ``` The char at the coordinate `(0,0)` (from the top left) is `#`. This is equal to the third input item, `#`, so you output `True` (or any truthy value) Example: `[(0,0), (1,1)], "#_\n_#", "#" -> True` The string is ``` #_ _# ``` The characters at the coordinates of `(0,0)` and `(1,1)` are both `#`, so the output is true. The output is only true iff every coordinate matches a hash. Not every hash has to have a matching coordinate though. If there are no occurrences of the single char (`#` in some of the test cases) in the 2D string, the output is still just falsy. You can assume the coordinates will always be within the bounds of the 2D string. More test cases: (I put the single char second for ease of readability) ``` [(0,0), (2,1), (3,0)], # #_## #_## True [(0,0), (1,1), (3,0)], # #_## #_## False (1,1 is not a hash) [(1,1)], a #a## #a## True [(4, 0), (3, 0), (2, 0), (1, 0), (0, 0), (0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (2, 2), (3, 2), (4, 2), (4, 3)], ' ' #### # # True ``` Note the last test case uses spaces as the single char string, and hashes around the spaces. [Related.](https://codegolf.stackexchange.com/questions/105649/find-all-the-coordinates-on-a-path) (inverse of this challenge) [Answer] # Python, 39 bytes Takes the inputs: 1. `a` list of `(x, y)` integer coordinates 2. `b` list of strings 3. `c` single character string --- ``` lambda a,b,c:{b[y][x]for x,y in a}=={c} ``` [Answer] # JavaScript (ES6), 37 bytes Takes the inputs: 1. `a` array of `[x, y]` integer coordinates 2. `s` array of strings 3. `c` single character string --- ``` (a,s,c)=>a.every(([x,y])=>s[y][x]==c) ``` [Answer] # Octave, ~~45~~ ~~38~~ 29 bytes ``` @(A,B,C)A(1+B*[rows(A);1])==C ``` A function that takes a 2D array of chars as `A` and coordinates(0 based) `B` as a two column matrix of `[col row]` and the matching character as `C`. The two element coordinates(using matrix multiplication) converted to linear index. Note: Previous answer that made use of sparse matrix was wrong. Other Contributors: [Stewie Griffin](https://codegolf.stackexchange.com/users/31516/stewie-griffin) for saving 5 bytes noting that [0 1 0] can be regarded as false value!! [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) for saving 2 bytes that `~0 == true` and notification about sparse matrix. [Try it Online](https://tio.run/#yzA84) [Answer] # Mathematica, 28 bytes ``` #3~Extract~#~MatchQ~{#2...}& ``` 1-indexed. Due to how arrays are structured in Mathematica, the input coordinates must be reversed (i.e. `(row, column)`) **Usage** ``` #3~Extract~#~MatchQ~{#2...}&[{{1, 1}, {2, 3}, {1, 4}}, "#", {{"#", "_", "#", "#"}, {"#", "_", "#", "#"}}] ``` > > `True` > > > [Answer] ## Haskell, 27 bytes ``` s!c=all(\(x,y)->s!!y!!x==c) ``` Usage example: `( ["#_##","#_##"] ! '#' ) [(0,0), (2,1), (3,0)]` -> `True`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ịṪ⁸ịḢð€Q⁼⁵ ``` This only works as a full program. Input order is indices, string array, singleton string. [Try it online!](https://tio.run/nexus/jelly#@/9wd/fDnaseNe4AMXYsOrzhUdOawEeNex41bv3//3@0homOoaaOgoahjhGIMtYx0Yz9H62emJScqq7DpaCempaeAWZkZmXngBm5eakF6rH/1VPVAQ "Jelly – TIO Nexus") ### How it works ``` ịṪ⁸ịḢð€Q⁼⁵ Main link. Left argument: P (array of coordinate pairs) Right argument: S (array of strings) Third argument: C (singleton string) ð€ Combine the links to the left into a dyadic chain and call it with each p = (x, y) in P as left argument and S as the right one. ị Unindex; retrieve the strings of S at indices x and y. Ṫ Tail; yield s, the string of S at index y. ⁸ị Unindex; retrieve the characters of s at indices x and y. Ḣ Head; yield the character of s at index x. Q Unique; deduplicate the resulting string/array of characters. ⁼⁵ Compare the result with the third argument. ``` [Answer] # [Perl 6](http://perl6.org/), ~~41~~ 40 bytes ``` ->\c,\h,\n{all map {n eq h[.[0];.[1]]},c} ``` ``` ->$_,\h,\n{all .map:{n eq h[.[0];.[1]]}} ``` Expects the 2D string as a 2D list. *Thanks to b2gills for -1 byte.* [Answer] ## C#, ~~80~~ 77 bytes Saved 3 bytes, thanks to pinkfloydx33 ``` a=>b=>c=>{foreach(var i in a){if(b[i[0]][i[1]]!=c){return 1<0;}}return 1>0;}; ``` a is the pairs of coordinate, b is the list of lines, and c is the single-character string. [Answer] # [Dyalog APL](http://dyalog.com/download-zone.htm), 8 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) Prompts for list of coordinate pairs (row,column), then 2D array, then character. ``` ∧/⎕=⎕[⎕] ``` `[⎕]` prompt for coordinates and use them to scatter pick from `⎕` prompted input (2D array) `=` compare the selected elements to `⎕` input (the character) `∧/` check if all are true (AND-reduction) **Test cases** (`⎕IO←0` to match examples, but this is not necessary): [First example](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%28i%u2190%u22820%200%29%28%u2282a%u21902%202%u2374%27%23___%27%29%28%u2282%2Cc%u2190%27%23%27%29%20%u22C4%20%u2227/c%3Da%5Bi%5D&run) [Second example](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%28i%u2190%280%200%29%281%202%29%280%203%29%29%28%u2282a%u21902%204%u2374%27%23_%23%23%27%29%28%u2282%2Cc%u2190%27%23%27%29%20%u22C4%20%u2227/c%3Da%5Bi%5D&run) [Third example](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%28i%u2190%280%200%29%281%201%29%280%203%29%29%28%u2282a%u21902%204%u2374%27%23_%23%23%27%29%28%u2282%2Cc%u2190%27%23%27%29%20%u22C4%20%u2227/c%3Da%5Bi%5D&run) [Fourth example](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%28i%u2190%u2282%281%201%29%29%28%u2282a%u21902%204%u2374%27%23a%23%23%27%29%28%u2282%2Cc%u2190%27a%27%29%20%u22C4%20%u2227/c%3Da%5Bi%5D&run) [Fifth example](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%28i%u2190%281%200%29%20%282%200%29%20%283%200%29%20%283%201%29%20%283%202%29%20%282%202%29%20%282%203%29%20%282%204%29%20%283%204%29%29%28%u2282a%u21904%205%u2374%27%20%20%20%20%20%20%23%23%23%23%20%23%20%20%20%20%20%20%23%27%29%28%u2282%2Cc%u2190%27%20%27%29%20%u22C4%20%u2227/c%3Da%5Bi%5D&run) [Answer] # Haskell, ~~72~~ 63 bytes ``` c [] _ _ =1<2;c ((f,s):t) m n |n/=lines m!!s!!f=1>2|1>0=c t m n ``` Input of `c [(0,0), (1,0), (3,0)] "#_##\n#_##" '#'` Outputs `False` Input `c [(4, 0), (3, 0), (2, 0), (1, 0), (0, 0), (0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (2, 2), (3, 2), (4, 2), (4, 3)] " \n ####\n # \n # " ' '` Output `True` UnGolfed ``` checkfunc :: [(Int,Int)] -> String -> Char -> Bool checkfunc [] _ _ = True checkfunc (x:xs) string char | char /= ((lines string)!!(snd x))!!(fst x)= False -- Checks first coordinates and returns False if no match | otherwise = checkfunc xs string char --Otherwise iterate over remaining coordinate pairs ``` [Answer] # Scala, 68 bytes ``` def f(l:(Int,Int)*)(s:String*)(c:Char)=l forall{x=>s(x._2)(x._1)==c} ``` [Answer] ## Clojure, 39 bytes ``` #(apply = %3(map(fn[[x y]]((%2 y)x))%)) ``` Example (string input is a vec of vec of characters): ``` (def f #(apply = %3(map(fn[[x y]]((%2 y)x))%))) (f [[0 0] [1 1] [3 0]] (mapv vec ["#_##" "#_##"]) \#) ``` ]
[Question] [ When doing weightlifting, I want to make a specific weight by attaching several plates to a bar. I have the following plates: * 6 plates of 1 kg each * 6 plates of 2.5 kg each * 6 plates of 5 kg each * 6 plates of 10 kg each The bar itself weighs 10 kg. It's only allowed to attach the plates in pairs - they are attached at each end of the bar, and the arrangement at the two ends must be completely symmetrical (e.g. attaching two 5-kg plates at one end, and one 10-kg plate at the other end is forbidden for reasons of safety). Make a program or a function that tells me how many plates of each kind I have to use in order to get a given total weight. The input is an integer greater than 11; the output is a list/array/string of 4 numbers. If it's impossible to combine existing plates to get the target weight, output a zero/empty array, an invalid string, throw an exception or some such. If there are several solutions, the code must output only one (don't make the user choose - he is too busy with other things). Test cases: ``` 12 -> [2 0 0 0] - 2 plates of 1 kg plus the bar of 10 kg 13 -> [0 0 0 0] - a special-case output that means "impossible" 20 -> [0 0 2 0] - 2 plates of 5 kg + bar 20 -> [0 4 0 0] - a different acceptable solution for the above 21 -> [6 2 0 0] - 6 plates of 1 kg + 2 plates of 2.5 kg + bar 28 -> [0 0 0 0] - impossible 45 -> [0 2 6 0] - a solution for a random number in range 112 -> [2 4 6 6] - a solution for a random number in range 121 -> [6 6 6 6] - maximal weight for which a solution is possible ``` If your code outputs the numbers in the opposite order (from the heavy plate to the light one), please specify this explicitly to avoid confusion. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~29~~ 28 bytes ``` 4t:qEZ^!"[l2.5AX]@Y*10+G=?@. ``` For inputs that have no solution this produces an empty output (without error). [**Try it online!**](http://matl.tryitonline.net/#code=NHQ6cUVaXiEiW2wyLjVBWF1AWSoxMCtHPT9ALg&input=MjE) ### Explanation ``` 4 % Push 4 t:q % Duplicate 4 and transform into range [0 1 2 3] E % Multiply by 2: transform into [0 2 4 6] Z^ % Cartesian power. Each row is a "combination" of the four numbers ! % Transpose " % For each column [l2.5AX] % Push [1 2.5 5 10] @ % Push current column Y* % Matrix multiply. Gives sum of products 10+ % Add 10 G= % Compare with input: are they equal? ? % If so @ % Push current column, to be displayed . % Break loop % Implicit end % Implicit end % Implicit display ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 4ṗạµ×2,5,10,20S€+⁵iƓịḤ ``` [Try it online!](http://jelly.tryitonline.net/#code=NOG5l-G6ocK1w5cyLDUsMTAsMjBT4oKsK-KBtWnGk-G7i-G4pA&input=MTEy) or [verify all test cases](http://jelly.tryitonline.net/#code=NOG5l-G6ocK1w5cyLDUsMTAsMjBT4oKsK-KBtWnGk-G7i-G4pArCouG5hCQ4wqHhuZvigJw&input=MTIKMTMKMjAKMjEKMjgKNDUKMTEyCjEyMQ). ### How it works ``` 4ṗạµ×2,5,10,20S€+⁵iƓịḤ Main link. No arguments 4 Set the left argument and initial return value to 4. ṗ Take the Cartesian power of [1, 2, 3, 4] and 4, i.e., generate all 4-tuples of integers between 1 and 4. ạ Take the absolute difference of all integers in the 4-tuples and the integer 4. This maps [1, 2, 3, 4] to [3, 2, 1, 0] and places [0, 0, 0, 0] at index 0. µ Begin a new, monadic chain. Argument: A (list of 4-tuples) 2,5,10,20 Yield [2, 5, 10, 20]. × Perform vectorized multiplication with each 4-tuple in A. S€ Sum each resulting 4-tuple. +⁵ Add 10 to each sum. Ɠ Read an integer from STDIN. i Find its first index in the array of sums (0 if not found). Ḥ Unhalve; yield the list A, with all integers doubled. ị Retrieve the 4-tuple at the proper index. ``` [Answer] # Mathematica, 70 bytes ``` Select[FrobeniusSolve[{2,5,10,20},2#-20],AllTrue[EvenQ@#&&#<7&]][[1]]& ``` Anonymous function. Takes a number as input, and either outputs a list or errors and returns `{}[[1]]` if there is no solution. [Answer] # Jelly, 25 bytes ``` ×2,5,10,20S+⁵⁼³ 4ṗ4’ÇÐfḢḤ ``` [Try it here.](http://jelly.tryitonline.net/#code=w5cyLDUsMTAsMjBTK-KBteKBvMKzCjThuZc04oCZw4fDkGbhuKLhuKQ&input=&args=MTEy&debug=on) [Answer] # Python 3, 112 bytes ``` lambda n:[i for i in[[i//4**j%4*2for j in range(4)]for i in range(256)]if i[0]+2.5*i[1]+5*i[2]+10*i[3]+10==n][0] ``` An anonymous function that takes input, via argument, of the target mass and returns the number of each plate as a list. If no solution exists, an error is thrown. This is pure brute force. **How it works** ``` lambda n Anonymous function with input target mass n ...for i in range(256) Loop for all possible arrangement indices i [i//4**j%4*2for j in range(4)] Create a base-4 representation of the index i, and multiply each digit by 2 to map from (0,1,2,3) to (0,2,4,6) [...] Package all possible arrangements in a list ...for i in... Loop for all possible arrangements i i...if i[0]+2.5*i[1]+5*i[2]+10*i[3]+10==n Return i if it gives the target mass [...] Package all solutions in a list :...[0] Return the first list element. This removes any multiple solutions, and throws an error if there being no solutions results in an empty list ``` [Try it on Ideone](https://ideone.com/kxXC91) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 50 bytes ``` ,L##l4,L:{.~e[0:3]}a:[2:5:10:20]*+:10+?,L:{:2*.}a. ``` Returns `false` when not possible. [Answer] # Pyth, ~~34~~ ~~31~~ 25 bytes ``` ~~h+fqQ+;s\*VT[1 2.5 5;)yMM^U4 4]\*4]0~~ ~~yMh+fqQ+;s\*VT[2 5;y;)^U4 4]\*4]0~~ yMhfqQ+;s*VT[2 5;y;)^U4 4 ``` [Test suite.](http://pyth.herokuapp.com/?code=yMhfqQ%2B%3Bs%2aVT%5B2+5%3By%3B%29%5EU4+4&test_suite=1&test_suite_input=12%0A13%0A20%0A21%0A28%0A45%0A112%0A121&debug=0) Errors in impossibility. This is essentially a brute-force. This is quite fast, since there are only 256 possible arrangements. [Answer] # Scala, 202 bytes Decided Scala doesn't get much love here, so I present a (probably not optimal) solution in Scala. ``` def w(i:Int){var w=Map(20->0,10->0,5->0,2->0);var x=i-10;while(x>0){ var d=false;for(a<-w.keys)if(a<=x & w(a)<6 & !d){x=x-a;w=w.updated(a,w(a)+2);d=true;} if(!d){println(0);return;}} println(w.values);} ``` The program outputs in reverse order and with extra junk compared to solutions in post. When a solution is not found, prints 0. Note: I could **not** remove any of the newlines or spaces because Scala is dumb, so I think to reduce size, the method must be redone unless I missed something obvious. [Answer] ## APL, 40 bytes ``` {2×(4⍴4)⊤⍵⍳⍨10+2×,⊃∘.+/↓1 2.5 5 10∘.×⍳4} ``` In ⎕IO←0. In English: 1. `10+2×,∘.+⌿1 2.5 5 10∘.×⍳4`: build the array of all the possible weights, by computing the 4D outer sum of the weights per weight type; 2. `⍵⍳⍨`: search the index of the given. If not found the index is 1+the tally of the array at step 1; 3. `(4⍴4)⊤`: represent the index in base 4, that is, compute the coordinate of the given weigth in the 4D space; 4. `2×`: bring the result to problem space, where the coordinates should be interpreted as half the number of the plates. Example: {2×(4⍴4)⊤⍵⍳⍨10+2×,⊃∘.+/↓1 2.5 5 10∘.×⍳4}112 2 4 6 6 [Bonus](http://tryapl.org/?a=%7B2%D7%284%u23744%29%u22A4%u2375%u2373%u236810+2%D7%2C%u2283%u2218.+/%u21931%202.5%205%2010%u2218.%D7%u23734%7D12%2013%2020%2021%2028%2045%20112%20121&run): since APL is an array language, several weights can be tested at once. In this case the result is transposed: ``` {2×(4⍴4)⊤⍵⍳⍨10+2×,⊃∘.+/↓1 2.5 5 10∘.×⍳4}12 13 20 21 28 45 112 121 2 0 0 6 0 0 2 6 0 0 0 2 0 2 4 6 0 0 2 0 0 2 6 6 0 0 0 0 0 2 6 6 ``` [Answer] ## JavaScript (ES6), 109 bytes ``` n=>`000${[...Array(256)].findIndex((_,i)=>i+(i&48)*9+(i&12)*79+(i&3)*639+320==n*32).toString(4)*2}`.slice(-4) ``` Returns `00-2` on error. Alternative solution that returns `undefined` on error, also 109 bytes: ``` n=>[...Array(256)].map((_,i)=>`000${i.toString(4)*2}`.slice(-4)).find(s=>+s[0]+s[1]*2.5+s[2]*5+s[3]*10+10==n) ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 8 years ago. [Improve this question](/posts/54082/edit) Write a few lines of Python code, `X`, that does not reference any global variables, such that ``` def method(): X print(a) method() ``` prints `1` but ``` def method(): X X print(a) method() ``` prints `2`. --- So, I hate to be a stickler, but it seems like `vars` and `locals` are actually global variables in Python: ``` def test_global_1(): global vars, locals vars = lambda: 2 locals = lambda: 3 def test_global_2(): print(vars()) print(locals()) test_global_1() test_global_2() ``` --- Also, it looks like people would like to see objective winning criteria for puzzles like this. Code length doesn't really feel right here so perhaps we could make a system of brownie points for various novel features of the code? I'm not sure exactly what these could be but here's a start: * +1 for really truly no globals (no `vars` or `locals`) * +1 for being the first to post a particular technique * +1 for the shortest solution posted * +1 for a solution involving only a single Python statement * +1 for interesting "hacks" like joining at lexical non-boundaries * +1 for not using exceptions And if you can think of more you could edit this question to add to the list. Can this problem be solved without using exceptions *and* without using globals like `vars` and `locals`? I suspect it can, though I haven't figured out exactly how yet... [Answer] ``` def method(): if 'a' not in vars():a=0 a+=1 if 'a' not in vars():a=0 a+=1 print(a) ``` Initializes the variable `a` to `0` only if it's not already initialized in the variables table. Then, increments it. More briefly (thanks to histocrat for `len`): ``` def method(): a=len(vars())+1 a=len(vars())+1 print(a) ``` If the two copies of `X` could be on the same line, we could do ``` a=0;a+=1;a ``` which doubles to ``` a=0;a+=1;aa=0;a+=1;a ``` with the "sacrificial lamb" `aa` eating up the second variable assignment. [Answer] # Python Thought of this solution, since `try` and `except` was the first way I thought of to determine if a variable existed yet or not. ``` def method(): try:a+=1 except:a=1 print(a) ``` [Answer] # Python 2 ``` def method(): exec'';locals()['a']=locals().get('a',0)+1 exec'';locals()['a']=locals().get('a',0)+1 print a method() ``` Basically, when `exec` is encountered in Python 2, it causes a special flag (`0x01`) to be removed from `method.func_code.co_flags`, which makes `locals` assignments have an effect. I exploited this to implement [`nonlocal` support in Python 2](http://code.activestate.com/recipes/578965-python-2-nonlocal/) (see line 43 for the xor that modifies the flag). [Answer] My first idea (and then smooshing it) was: ``` def method(): a=2if'a'in vars()else 1 a=2if'a'in vars()else 1 print(a) ``` But histocrat's answer seems optimal. [Answer] My attempt. Uses the math module to track if X is run once or twice. ``` def module(): import sys if 'math' in sys.modules: a+=1 else: a=1 import math import sys if 'math' in sys.modules: a+=1 else: a=1 import math print(a) module() ``` [Answer] ``` def method(): #### X-block try:a except NameError:a=1 else:a=2 #### print(a) ``` The `try` block checks if the variable a is defined. If variable not defined,(this is only when X-block is present once) then `NameError` Exception is raised. If variable is defined, (this is when X-block is present twice) then `else` will be entered . [Answer] ``` def method(a=[]): a.append(a) print len(a) ``` Edited in response to comment: a is a list of empty lists of length n, where n is the number of time you've called method. Calling this method twice prints 1 then 2. ]
[Question] [ Develop a program to check if a given word is part of a language defined by the following rules: * The language has a set of rules. * The empty string is considered a valid word in the language. * Two words from the language can be concatenated to create a new word in the language. * If X is a word in the language, then "A" + X + "A" is also a word in the language. * If X is a word in the language, then "A" + X + "C" is also a word in the language. * If X is a word in the language, then "B" + X + "A" is also a word in the language. * If X is a word in the language, then "B" + X + "C" is also a word in the language. You can assume all inputs only consist of the characters A, B and C. Examples: * The word "CB" doesn't belong to the language. There is no way to arrive at this word from the above rules. * The word "BAAC" belongs to the language. Reasoning: The empty string is a valid word. Applying the "A" + X + "A" rule, we get "AA". Now we apply the "B" + X + "C" rule to get "BAAC". * The word "BCBC" belongs to the language. Reasoning: The empty string is a valid word. Applying the "B" + X + "C" rule, we get "BC". Now we apply the concatenation rule to get "BCBC". The concatenation rule can be used to concatenate a word with itself. ## Test cases ``` CBAA ---> false CBBB ---> false BCCA ---> false CCAC ---> false ABAC ---> true ACAB ---> false AAAC ---> true BBAC ---> true CABC ---> false CCAB ---> false ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") problem. While the language looks random, I hope you can find a pattern in the language to write the shortest code possible. Hint: It is possible to check in linear time. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ ~~15~~ 16 bytes ``` ,UċƤ"⁾CBḤ«ƑJ>LḂ$ ``` [Try it online!](https://tio.run/##y0rNyan8/18n9Ej3sSVKjxr3OTs93LHk0OpjE73sfB7uaFL5/3D3lsPtj5rWRP7/7@zk6Mjl7OTkxOXk7AxkOTs6czk6gQhnRycuR0cgywnEBfKcQbIgMZAwAA "Jelly – Try It Online") [Validated against tsh's Python demonstration](https://tio.run/##bVOxbtswEN31FVcVhURUdix3M6ACtoEOQdd2CdKCkE4WHVoUSDqFx3bt1H/I1h/I1CEo8h/pj7hHirbsIIYH8r13d7y7p25nG9W@29dabUBY1FYpaUBsOqUtdFpV29JGnl2jlLsD4y9f8ZbLzJ9FvYuiHqSgleYbKCBJkn326e/Px7v43/c/y8XT/d3D78dfl18@Pt3/2BN7lc9G@XUUVVgDpRJVatgsAvqJGiS2dIU3MIVXBUxmoNFudQsfuDToRQ2XNZUJwosLmHq4VNvWzokwY39Mk3nCBmZxyixOmeUpswwMvSSEve8LKn1Q98ALD3tNUCd5iVALbSykPnAUEjGI53FCQ26tgngR@xBDtek8XitB3YxNJ4VNSZfBeSx7VoBigBuIU1Iq26A2/sqGrGYctClpM6dkA@IKkPgEWQbEx0usLaWY@EvtOm/o2WD6JR3G00BRuLyzXv@2gPzIo/SrrG0gR@ekwRfGF4C@uKvuDcJXGtEcHRJEB9s44WDK9MyKGVwFj5LwmkWR66R1jWjerjCdZJDnGUzZjAZ76W1ulNxaoVqwWtwK7iCNayytAVVVznIr25iMdNDSH7ECWmbZYHlznNU3pStXJHxFZMPFMsnc5pC7qbZsGCM3hr69Q49J0vvAZaCNR50WzpKfXa/cYpWw/X8) and [against JvdV's regex](https://tio.run/##XVG9TsMwEN7zFCeKZBuFisBWqUJtt4oVlqhFJrkkLokd2W6hI6xMvEM3XqATA0J9j/IiwfkpAiwP5/u@@@6@c7m2mZIXVaJVAcKitkrlBkRRKm2h1CpeRtZr0AXm@fqANI9bXPHcb2KRrL0O0pjiI3DjAs9reU4n1byAIRBCKv/682W3Ofp6ep@M99vNx9vudTq/2m@fK4eGweA0mHlejAk4dRFTwwYeuKPRLrWEOzcg1dgvuI0yqsmchqPxjF4G7CQcTWbs5Jj4hrFWgaca0fyXOOjCcPjLCP0zqw9h58sRZ04uURokCAmayxTpmQ9B4MM5G0APps1qjMqXVigJVouV4HVK4wIja0DFMeQoU5sZ3/FAuosYg1UQZRjdN9PVHR6Ujusm3eYpGY0nxHc6JXLr9ic7J/XpOZaQltY17CfLjXG/eHBOSH@hhGw5zkVbQW7qDXCLMWHVNw). (But, I neglected to check extremely unbalanced odd cases...) Checks that no more than half of the symbols in every prefix are `C` and that no more than half of the symbols in every suffix are `B`. ``` ,U Pair the input with its reverse. "⁾CB For the original and C, and the reverse and B: ċƤ Count how many times the symbol occurs in each prefix. Ḥ Double the counts. «Ƒ Are all elements less than or equal to J their 1-indices? >LḂ$ Also, reject any odd-length inputs. ``` [Answer] # Python, 63 bytes ``` lambda x:bool(match('^([AB](?1)*[AC])*$',x)) from regex import* ``` See an online [demo](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY37XMSc5NSEhUqrJLy83M0chNLkjM01OM0oh2dYjXsDTW1oh2dYzW1VNR1KjQ1udKK8nMVilLTUysUMnML8otKtCDGbCgoyswr0UjTUHd0cnRW19SECC9YAKEB) This is based on the *PCRE* regex pattern: ``` ^([AB](?1)*[AC])*$ ``` See an online [demo](https://regex101.com/r/7z1fFZ/1). I was unsure if we were allowed to simply post the pattern for 18 bytes. --- # Excel (ms365), 120 bytes [![enter image description here](https://i.stack.imgur.com/vNx5W.png)](https://i.stack.imgur.com/vNx5W.png) Formula in `B1`: ``` =REDUCE(A1,ROW(A:A),LAMBDA(a,b,IFERROR(REPLACE(a,MIN(IFERROR(FIND({"AC","BA","BC"},a),"")),2,),SUBSTITUTE(a,"AA",))))="" ``` The idea here is to 1st replace any of the compound words that are not a copy of itself. If not found, try to replace 'AA'. Check if the final result after the last iteration is empty. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 55 bytes ``` f=([x,...y],z)=>x?x<'C'&f(y,-~z)|x!='B'&z>0&f(y,~-z):!z ``` [Try it online!](https://tio.run/##XY9NT8IwGMfv@xQPF9qStngGO9I2XjzowSOQ0MxOa8a2tJWMqXz1uREhzMuT/P5vyfNhDiZk3tWRldWr7bpc4HVDOefHLW2JSJtVc480mub4SNmpJd/NRCCFpm16d9ZOrCWLSdtFG2Jmgg0gYJdICYyxFKL/tIlWF8xNEQZW6paV1mNfS33LUl34PCe1HNWlHNlqnO7D@t/4qL3j0bs9JjzUhYsYbUpE@N7U2INIwf/J802YsVna3zkhy@T6LM8r/2Cyd4zXjoLdkqH0lQBkVRmqwvKiesM5dr0u4PHl@YnXxgeLLYEVoAOCBaAGURgi/e4PWXa/ "JavaScript (Node.js) – Try It Online") This question [can be solved in linear time](https://tio.run/##fVLbaoQwEH3vV0xTyiZ0191u3wQLSaD/IbsJWoJKEgv9ejvGWC@s@pQ5lzmTic2vL@rqo@vuSsNPbso7dSx9AvxKDUZVWMIrXOE5g0sKVvnWVvCVG6eCqMiNhmwUns9wDfCtbivPkXBJONIDP7CJEXNGzBk5Z2RkcJJo@xwCazuqB@DBYC8INSa/KdCldR5oMJ5iIwaEk4ODsvI1EEGCxWE2npPvusTbJK4xpaeoO8LSy1YB6IHcAaGorH2hrAslm7q6JGopao@9kk1IH4DiGSIjEvxGaY8tLqHQ/c0LHBvc8EjjegrIsr5vOujfMnj/55UJT6l9JE9L0qkH64vAEI7pXWNxV3T4Q4gUnBPGcAc6OFakEJukkHLHKbncJLkYSW/bNSf5diTn20ax0xR7yr1RF4ndHw), however we do prefer golf instead of time complexity. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes ``` ^((A|B)|(?<-2>A|C))*$(?(2)^) ``` [Try it online!](https://tio.run/##FYkhDoAwEAR93wHJHQmmmkB2V/CLBgQCgyDI/v1ozWQm817f/Zwx2n5EMUOlV9uWOa@ocp8G2yx78QgRSCKZKDUTlMAOgQloxp6t1C9/ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^( ``` Starting at the beginning of the string, ... ``` (A|B)| ``` match either of `A` or `B`, or... ``` (?<-2>A|C) ``` ... match a previously matched `A` or `B` with an `A` or `C`, removing the knowledge of the match, so that a subsequent `A` or `C` has to match a previous `A`or `B`, ... ``` )*$ ``` ... repeating until the end of the string, ... ``` (?(2)^) ``` without leaving any unmatched leading `A`s or `B`s. [Answer] # [Go](https://go.dev), ~~125~~ 134 bytes ``` import."strings" func f(s string)bool{l:=s for _,e:=range[]string{"BA","AC","BC","AA"}{l=ReplaceAll(l,e,"")} return l==""||l!=s&&f(l)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=1ZXBitRAEIaPYj9Fb8MuCWZEbxJooatUEDwsznEdNnHojIM9mSHJDMrsXH0JL4vgQ61nH8ROsurUv-pdBjKp1N_pn_qqK5-_LNbXNw825fx9ufB6VS5rpZarzbrpHppq1ZlfQds183W9M1-3XTV5cvPp6PmyXrRGVdt6rquk1eOT9O16HfYht62q1o2-zHxum7Je-IvZKNgbciYzjuOF-otz5rAP9rXfhHLuXQhJyHxmTHpQje-2Ta2DtcZcXYUT256dVUlID6Obb_e-D7v39pNU79U0t9NNWHZJoSeTyVPdNVuvmJwbw6oMbR8THcfELPPs-Dh29DMeXufYieXOiTRJdRQzvBxWs5BD8vjF0sRxRsjADst1JLYvMvOmNuktqVbnVg-s9DQWM_ThWM42M-OqqF3WmfZ9Klw8mmXx-nim_IdNdpnb87JpPUX-iU9VOe96VZUs67io0lFzYuPDvbp_HvugqxLzwr189fxZrovTtujz-elOR0X_FyNrx_voMBs2jZv06eFOW9vfp-oQf8rvfPOxexe7q9-yiEiOSxKjfxGLWakmUMsKOpZqRMZQb_f38t9pLSIn02CFCDpTeiHwQgyN62Qo1QxtLqvCYAX6Cs5QjEHOwjlJQgSEsIkdtDgcYEmInPRCgIgceJGMCBjBgSZgRDhNgBFJRgSMSDIihjMPXhgPt1TjYJN1AUYEjAgYsYO5CZDYOdAT6An0MAqBEwMnBk535zj4IfADpHDuM5BiAj-AiolxlON3gyAGPfgBXMz4qcDvEviRvAr1hzE-TO_f0zHTw7z_v4b77cf--nr8_wE) Recursive function that repeatedly replaces the `A[empty string]B` pairs with an empty string. ### Explanation, slightly ungolfed ``` import."strings" // boilerplate func f(s string)bool{ // function that maps string -> bool l:=s // init for _,e:=range[]string{"BA","AC","BC","AA"}{ // replace these pairs in this exact order l=ReplaceAll(l,e,"")} // with an empty string return l==""||l!=s&&f(l)} // ok if empty, not ok if non-empty ``` ### Changelog * +9 bytes for matching `AACC`, using a different approach. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „AB„ACâIgиæõδ.;õå ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcM8RycQ4Xx4kWf6hR2Hlx3eem6LnvXhrYeX/v/v5OzkDAA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f9HDfMcnUCE8@FFnunWF3YcXnZ467ktetaHtx5e@l@HC6SaqzwjMydVoSg1MUUhM48rJZ9LQUE/v6BEH2IolEKzx0ZBBaw2L/W/k6OjM5eTs5Mzl6MTkOUI5jpBxYCiIHkgpQQGXM5OQOToCCScnIAqnIEsZ5AuZ0eghCNQnTOIBdTIBQA). The test suite contains a `;` (halve) after the `g` to speed it up substantially. **Explanation:** ``` „AB„ACâ # Push ["AA","AC","BA","BC"] by taking the cartesian product of "AB" & "AC" Ig # Push the length of the input-string и # Repeat the earlier list of strings that many times as single list, # so each individual pair is repeated the input-length amount of times æ # Get the powerset of this list δ # Map over each inner list: õ .; # Replace every first occurrence of the pairs one by one with an empty # string in the (implicit) input-string õå # Check if the resulting list contains an empty string # (after which the result is output implicitly) ``` Minor note: for an explicit empty string input, it'll do the following steps: `„AB„ACâIgи`=`[]` → `æ`=`[[]]` → `õδ.;`=`[""]` → `õå`=`1` (truthy). This is different than if no input is provided, since `õδ.;` would then keep `[[]]` and the result is falsey: [try it online with explicit empty string input](https://tio.run/##yy9OTMpM/f//UcM8RycQ4Xx4kWf6hR22h5fZHt56boueNZA6vFTn/38lMAAA) vs [try it online without any input](https://tio.run/##yy9OTMpM/f//UcM8RycQ4Xx4kWf6hR22h5fZHt56boueNZA6vFTn/38A). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` ⊞υSFυFABFACF⌕Aι⁺κλ⊞υΦι∧⁻ξμ⁻ξ⊕μ¬⌊υ ``` [Try it online!](https://tio.run/##PU7NCoMwDL77FMFTAt0TeOoEwcNGwScQ7WZZGkdtx96@qwPNJd9P8vFNyximdeScTdoWTAp6eac4xODkiURN9VgDYCL471pf6xO2B@yczJoZnQLDacOXAiYiOCI7x9GG3dYy481Jufkq8KTgJL1MwXor0c7oaZ@mMqVExPsa9x/nky89ip6z1m2bLx/@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υS ``` Start a breadth-first search with the input string. ``` Fυ ``` Loop over all of the found strings. ``` FABFAC ``` Loop over `AB`, `AC`, `BA` and `BC`. ``` F⌕Aι⁺κλ ``` Loop over all of the indices of those substrings in the string being considered. ``` ⊞υΦι∧⁻ξμ⁻ξ⊕μ ``` Push the string with the substring at that index removed to the list of strings to consider. ``` ¬⌊υ ``` See whether we were able to end up with the empty string. [Answer] # [Scala](https://www.scala-lang.org/), 74 bytes Golfed version. [Try it online!](https://tio.run/##bZBRT8MgFIXf@yuufVghdma@1rEEeDJRX4xPy2JwwsRga4At3WZ/ewU6XTQlaUg/zj335Li1MKJvXt7l2sO90DUcs2wnLKgK3Wnnl/xN2FV5W3tMFqxpjBQ1EDiuhZPwDGQB3m5l1yuSEGqral8egha184IXE4XC7@U1xl@ovSAFKyaHxWyg00Bv0tCDNmnmQMis6wFepYKPkAUJu3EVUGvFfvnora43K1zBU619zJBBODthwEvno5ELNIZG6QUA5ZTmZUqIy1/GWaJKGPcXMzaCGeejak75CKYs4X8bKadj1pSOidmoRXDg4zHOzoniLF2qsYCQLkFimE/PDeFTbUNxVrqtiV0qpK98E7srYYZPis9QuDc10grQj5JEw3yXgwwbIW/D8uFpGOqy@GVd/w0) ``` f={case(x::y,z)=>(x<'C'&f(y,z+1))|(x!='B'&z>0&f(y,z-1));case(Nil,z)=>z==0} ``` Ungolfed version. [Try it online!](https://tio.run/##bZHBT8IwGMXv/BXPHaCNw@B1YSRtTybqxXgiHOrsoGZspi0EEP72@W0DUbNdtvy@1/e9vvlMF7quq7cPkwU8aVviazAA3k2OnGUr7XyCR@vDXNH3IsYhwUMZeAJZVYXRJVK0Kqx1yFZ0GPRk2hvskCTYI521CGA7TDFSIwyHZL0nK9zinnMcj83sJsVItsMDZpj8Uo0b1dX32RZkSjxNMSF8uuRdU3qm3ZISC@f0fv4SnC2XCwr7WtpASbt0W10gGB8aN0@0uR67hIyEiGIEtzE8/mFKtjTXhf@LpezBUqletRKqBwvZ4n8bhRJ91kL0iWWvBTmo/hhX55byQfvKKwfGbAzDMR1fG@Ln2rrinPGboukyZ/YuVE13MSb8rPikwkNRMpuDXZRpYxhtIxjaiGhHy7tRd@jU/cLToK6/AQ) ``` object Main { def f(chars: List[Char], z: Int): Boolean = chars match { case x :: y => (x < 'C' && f(y, z + 1)) || (x != 'B' && z > 0 && f(y, z - 1)) case Nil => z == 0 } def main(args: Array[String]): Unit = { val testcases = List( ("AA", true), ("CBAA", false), ("CBBB", false), ("BCCA", false), ("CCAC", false), ("ABAC", true), ("ACAB", false), ("AAAC", true), ("BBAC", true), ("CABC", false), ("CCAB", false) ) for ((i, e) <- testcases) { val result = f(i.toList, 0) println(if (result == e) "v" else "x", result) } } } ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~43~~ ~~41~~ ~~36~~ 29 bytes ``` ~&/0{(0>)_,/x+/:1-2*&2 2\-y}/ ``` [Try it online!](https://ngn.codeberg.page/k#eJxdjDsPgjAURvf7K+o14SE0LR2vCdg2DN3ZrEEGcXHCRzRGfrtoYkIdT853vp7GSMhnIsu0zcU9E1RwtYoUU54/XgJAgDVaM855yfrudD5MbMycjbWht9rOWZsfX4brhFYHudaBNuF6Gtu/86D24DZUtNGYuCqPUXiPabxYOkaS9t1wvLECoKEMGfrYQU0JfkNc4+cf00pQwxRAPfZxs5U7eAOesERh) -2 bytes : Better lookup -5 bytes : Even better thanks to @ngn -7 bytes : Fairly sizeable overhaul by @ngn (go team ngn/k!!) ]
[Question] [ **Challenge** The goal of this challenge is to make a function that takes two paragraphs and output a concatenated result with removing the duplicated overlapped lines due to redundancy (but a single copy of the part of overlapped lines should be kept to avoid information loss). Each input paragraph is with the follows specifications. * The leading/trailing spaces in each line have been removed. * No empty line. The output merged paragraph follows the rules as below. * Input paragraph 2 is concatenated after input paragraph 1 * If the line(s) from the start of the input paragraph 2 is / are sequenced same (overlapped) as the end of input paragraph 1, just keep single copy of the sequenced duplicated lines. * The definition of duplicated lines here: + The content in two line should be totally the same, no “partial overlapping” cases need to be considered. + The content sequence in two blocks of lines should be totally the same. **Example Input and Output** * **Inputs** Input paragraph 1 example: ``` Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we're working together to build a library of programming puzzles and their solutions. We're a little bit different from other sites. Here's how: Ask questions, get answers, no distractions This site is all about getting answers. It's not a discussion forum. There's no chit-chat. ``` Input paragraph 2 example: ``` We're a little bit different from other sites. Here's how: Ask questions, get answers, no distractions This site is all about getting answers. It's not a discussion forum. There's no chit-chat. Good answers are voted up and rise to the top. The best answers show up first so that they are always easy to find. The person who asked can mark one answer as "accepted". Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked. Get answers to practical, detailed questions Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do. Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers. ``` * **Expected Output** [![enter image description here](https://i.stack.imgur.com/CWnfb.png)](https://i.stack.imgur.com/CWnfb.png) The two block of text are the same, so keep single overlapped part after merging. [![enter image description here](https://i.stack.imgur.com/ASuT0.png)](https://i.stack.imgur.com/ASuT0.png) ``` Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we're working together to build a library of programming puzzles and their solutions. We're a little bit different from other sites. Here's how: Ask questions, get answers, no distractions This site is all about getting answers. It's not a discussion forum. There's no chit-chat. Good answers are voted up and rise to the top. The best answers show up first so that they are always easy to find. The person who asked can mark one answer as "accepted". Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked. Get answers to practical, detailed questions Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do. Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers. ``` **Rules of Challenge** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The answer with the least bytes wins. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 104 bytes ``` def o(a,b,i=None): while(i:=a[:i].rfind(b[0]))+1: if b.find(a[i:])==0:return a[:i]+b return a+'\n'+b ``` [Try it online!](https://tio.run/##lY7NCsIwEITveYqlHtpQFcWLBHLw5@wLND1sakoDdRNiVHz6aouCiCjuYdiZZT/GX2PjaLH0oev2pgaX4ViPrdw5MlwwuDS2NZkVEgthy2moLe0zXcxKzvP5/Q62Bj0dUiysKLmUMxFMPAWC4SXXDJ4@TxWlue5GwFAmK0VrRRtF24RpmfTLkKwS5oOlmA1dOH@4dNJPyhkbQYvHCFWDAdzZhBb9B972D17lDr410XzBvdpfOHJfQBVGRU0vx14OGN@A3Q0 "Python 3.8 (pre-release) – Try It Online") I've come up with this as my first ever Code Golf challenge. Defines function `o` (short for overlay) which returns string `a` overlayed with string `b`, or their concatenation if there is no overlap. It repetitively searches backwards in `a` for the first letter of `b` and, if a match is found, compares from that point on in `a` to the beginning of `b` until an overlap is found or `a` has been fully scanned. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 14 bytes ``` ms`$(.+)^\1 $1 ``` [Try it online!](https://tio.run/##3VRNb9QwEL3nV4yqioLYRuqV2wpB6QUJUYkLQjjJ7MasYwd7vGn655c3zna3fPwCDpESe@bNe29mElmsN4fDkL5fvqxfv/r29aa6vDkc3oaO6Ta4DX0W0@7o3UPbG79lsokM/cycxAZPxnd40sSRkhWmTYg0xrCNZhis39KYHx8dE3vpc7ImSSopraJvgc4x1dWdXCVqsnVSLmP21Mw0h0wm0WiiUNiQ9PwnFc8yhbjT208v1oUA0L5Y6TU5Us9uXNHEV5FJA5WQhC0DKuKllAR9craJJs6K8zf3hTBSLCQGl1W2VimomisCgY0V6uwGeiCVNjEMFEqZhRR9wAVE9mF6U63T7mRgWhH4HC3Ehw@ASRJNW26r@x5@F2fVd@fINCGL5ohSPObVVCz0AUia3@aUtDvoRh5quu@X6gBveyvXsE/q6j@QcBvC0/gBGmL2QbijPC5zZBNrm3VyJIw1mEAlSJ9SEsRo9MZGnCYNNaLxc0EzbjJzIjZpVpyN9d0CMiIZ3KY@YEJ3qNgaT4PRUfT8tA@Y3QvTtjyC0kVdrcurKu4CJ38lNDCyrKqW34mtcEo/clpC0sIKRzrDKKY7Jv9gAT/OfVDCY@lBa9yKOhZjHZJPXaveB3gMwuejY2fACnnZON2GxvFQVrE3e6y3aVGH7nzrMjZ4QX3Km5TmKVSi5a70gR8A5@bzvXorcV7WEXbU1UdtO0bjTKUs9sQ4s550maF6QM9pvQ/2mYzFHEUco0ULLAqF0XrcXTcmcbeiYtcxyNkdu9LNLXuOBlP5bNjwXX4NvVpwnMvqFw "Retina 0.8.2 – Try It Online") Assumes that neither paragraph will be matched in its entirety. Explanation: The leading `$` ensures that the capture begins with a newline, while the inner `^` ensures that it ends with a (possibly the same) newline. It then remains to delete the duplicate. [Answer] # APL+WIN, 19 bytes Prompts for the second paragraph followed by the first as nested vectors of lines: ``` (∨⌿<\x^.=⍉x)⌿x←⊃⎕,⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##3VRLjtNAEN3PKUqzwCAlkRA7BIsIwTASHyFGmg1CqtjluEm72/RnEs8WCQYEiA134BbcJRcJr9v5DMMNWFh2d1W9eq8@5k6Pq561nY9Lzd6rcrP@/vP5s/XHH/eO8HX6El93j9ZXn@rN7fXVr/XX3w/erN5OHq6/fV7dwWkF@/rLB7iO8GzguKmPinMpCifEpFUIWmimAlWqrsWJCVQ725INjTjyKoif0FMYisJTY5f3CyqmfkHvo/igrPEjmksgNn4pDgdjgeSD4zJb4X3WKJ@BCG/WmnhmY0hRQZn5LnJCpyGlMBZgCaKMkGsN1dbFdkJnzZYDEpSNCuOy4TAB/Im11Q6EGKoubJCKYofLipzyQsES1ODVTTIfCAb5fZCHrORfK4dbn5w5pIg@47Fecu9J2PcJqVam2sF0CAfFZWOJ/QJZSzbUsluQNbLFh4WOuSylA63jFDnNh6S9suJNUQRqBYEqFyD8TW@Ea3oX/eDjB264WlqXEqI6OeImk1yZQ18S8S73pGQ9okoCK43wfRfh/sSi5CB@uNx2CtQQGVkDws60tNTbSA1fCNVcIhedmlLHSra4u7hlorp3DU5JlXsiK8Dp/mBPVQ6uTxUBz8om8i/SHGBYDmSSYloK7pQhG13S3mIGaHph1TUpQ4kSZucUmqGQynbKwDaesZdqRLloWyetFqJzZ@dixDHm9Nr04Zz2AN5mP6nFUfHIQu2J1TW9Dlwu6PEK42jmw4jvqWS12ynIC5C6hRrOHbdtUtvFy0usH5auiV6xDz6HlAl9DvScjYphM2ZR6TAMdTQ064fSeerYBbJ1HoMbbIyEXDVYX92abrcZgOcqNCncUSO6G6Gq@X@QfIcmYDmzbJuzVvlPMXPs@gT1r4KBNkIUhFodcx9yov/mR/MH "APL (Dyalog Classic) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .s€»ʒÅ?}θK¹»ì ``` First input as a list of lines, second as a multi-line string. (Taking multi-line input as a list of lines [is allowed by default](https://codegolf.meta.stackexchange.com/a/17095/52210).) [Try it online.](https://tio.run/##tVRLbtRAEN37FCUvyGbwAdigEYIQISEhIrFALNp2zbiZdrfpTxxHYoPEBThHDgDKLtmx4BBcZHjVnsyEzwYhFpbs7nqv3quPXVC15u22Ct8/XF5fff108/Hh@2@fn11/ub66udxuX5ePXMt07MyKXkbVbOjxedMpu2bSgRS9SxyidpaUbfGEkT0FHZlWztPg3dqrvtd2TUO6uDBMbGOXglYhhgxphH0NdvahKhdUnsSjQHXSJuZ7nyzVE00ukQo0KB/JrSh2/Ksay3F0fiO3L@4ts4aZ8JWOneA9dWyGBY185JkkVmRFt2awebzkrDBBRtde@UmofncwywZEw6gzSczvEmVigccIp7WO1OoVjMEzrbzryeVMszR6igtY7dz4QNDLsNkXMywIqnblxId1YArRqybfSvhph/LnQksbjCFVuxQFFkXrDlpRLqd1IBOKJoUgzUJzUl/RaTdrAH/T6XgfpYxV@aYoy38wU/yFk@L/2SiOnbudSFDDzJmL3FIa5rnSgaXnMknRDRWUwCVE7yEBZiR6pT1Og4SqKPFTZlNmVFMgVmESnpW27UwyAAxtY@cwsRtkbJSlXsloWr5dEcxyqZqGB0gqq2KZX8Vx6zjYo0g9A6XFdfxZ2AKn9DaFOSTMqnAkA41ksnbxDypQj0MfRPCQe9Aos6CWo9IG4H3XiicONYbgw9GuM1AFXFJGVqM23OfV7NQZNl41yEMntjEJSz2z3uJGkbkPjV5zm/vA56Az0@Feahv9NO8mylEVz6XtGI2DlLzoI@NMW5LNhusePaflmdN3bMzFEcbBa7RAI5EbtMXd/VoFbheUy7ULMnrDJndzzZa9wlTeGTZ85/9EJyXYzSUW5Qc) Would be 1 byte longer if we can take both inputs as multi-line strings: [try it online](https://tio.run/##1VQ7jtRAEM19itIEbDLrA5CgEYJlhYSEWIm4bZfHzbS7TX/W65VIkLgANyDfGIHIZjMCDsFFhlft2ZnlcwECS3Z31av3XlXZBVVp3u22n7efyvDz/c322/ePtx8evfvx5fn26@3NbrdYLB67hunMmZZeRVVv6MlV3Sm7ZtKBFL1NHKJ2lpRt8ISRPQUdmVrnafBu7VXfa7umIV1fGya2sUtBqxBDTqkFfQ109qEszuNJoCppE/OlT5aqiSaXSAUalI/kWood/0nFchyd38jtywerTABor3XsJNlTx2ZY0sgnnkkChVB0awaUx0suCfpkdOWVnwTnb@4zYaRoSHQmiWypklElN0YIrHSkRrfQA6nUeteTy2VmUvQMFxDZufFhsQqbg4FhSeCztxAf1gEmRK/qfFtcdPA7Oyu@G0OqcilKThSK@7ySsoXWAUny6xSCdAfdSH1JF91cHeB1p@Mp7Islelzg@e91FGfO3c0goCHm0kVuKA3zMOnA0msZn@iGEkygEqQPKQFiJLrVHqdBQlWU@CmjKTOqKRCrMAlOq20zgwxIBrexcxjTDSrWylKvZB4t3y0FBnih6poHUFqUxSq/iuLGcbAnkXpGlhbV8XdiS5zSmxTmkDCzwpEMMorJosV/sIAfxz4I4SH3oFZmSQ1HpQ2SD10rnjp4DMLHo31nwAp5SRlZicpwn/exU5fYcVWjDp3b2iSs8Yx6lzcKzUNo9Jqb3Ae@ApyZjvfibfTTvJOwoyxeSNsxGkcqebtHxpm2JBsN1T16TqtLp@/JmM0RxMFrtECjkBu0xd1ppQI3S8p27YOM3rDJ3VyzZa8wlfeGDd/5/9CJBfu5xKL8Ag). ~~Would be 3 bytes shorter if partial lines could also overlap: [try it online](https://tio.run/##yy9OTMpM/f9fr/jUpMOt9rXndngf2nl4zf//SkpKjk7OXC6ublzuHkAOFxBDOJ5cXt4@QB4A).~~ **Explanation:** ``` .s # Get a list of suffices of the first (implicit) input-list of lines € # Map over each suffix: » # And join them by newlines ʒ # Then filter of these string-suffices: Å? # And keep the one that the second (implicit) input-string starts with }θ # After the filter: keep only the last/longest suffix K # Remove this overlapping text from the second (implicit) input-string ¹» # Push the first input-list, and join it by newlines ì # And prepend it to the other string # (after which the result is output implicitly) ``` [Answer] # JavaScript (ES6), 52 bytes I/O format: [lists of strings](https://codegolf.meta.stackexchange.com/a/17095/58563). Expects `(b)(a)`. ``` b=>g=a=>a.some((s,i)=>b[i]!=s)?[a.shift(),...g(a)]:b ``` [Try it online!](https://tio.run/##hc7BDsIgDAbg@56icmoTZHcN8@RTEA5lwsRMMbL4@pNt2fQmCaG0X5r/xm/O7Ss@h/0jXfwY9Oh002nWDauc7h4xy0i6cSbanc50MqV/jWFAkkqpDpnswY1HUwEYEAwOWnBCgpiLcr0AK6Gut@HcWzlPtDylmNh6Fj51N7jRP7Dsn@AFPIQf@g2wTBa@pV2Dg/3yJe06qWylQnqdub0iGpbgLIFuoE2PnHqv@tRhQKfys48DChBEyL8/ovED "JavaScript (Node.js) – Try It Online") Test cases ~~stolen~~ borrowed from [@dingledooper](https://codegolf.stackexchange.com/a/217881/58563). ### Commented ``` b => // anonymous outer function taking the 2nd paragraph b[] g = a => // inner recursive function g taking the 1st paragraph a[] a.some((s, i) => // for each line s at position i in a[]: b[i] != s // truthy if the i-th line of b is not equal to s ) ? // end of some(); if truthy: [ // create an array consisting of: a.shift(), // the 1st line removed from a[] ...g(a) // followed by the lines returned by a recursive call ] // end of array : // else: b // stop the recursion and return b[] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~59~~ 51 bytes *8 bytes thanks to @ovs* Input is taken as two lists of strings. ``` f=lambda a,b:`a`[:-1]in`b`and b or[a.pop(0)]+f(a,b) ``` [Try it online!](https://tio.run/##fY7dCoMwDIXv@xS5W8usTC8Fn0TEplOx4GpwFdnTu/izgTdeJOScrzkpfUI3@HRZ2rzHl60RMLKZQVNkOimdN9agr8HCMBYY00Dyocp7K/mVWubO9Q0kmQBKIIcR58p5moJU8Zt6F@QNbophegGHKdAFrs5McNrofIBWUhJxsoI83zIW5E8@wYqtczXicLZZa80a1/r3w9v1yeMdUUMD7ZGxzyvbb5xv/RTzLw "Python 2 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~32~~ 31 bytes ``` {a___,d=b___}±{d,c___}={a,b,c} ``` [Try it online!](https://tio.run/##3VXLbtNAFN33K65SqQXJDXtQpYRSShegolZiQVF1bU/iIeMZM4@6bpT@E7/Aj4V7Z9ykbQgIlizq2DPnnHvuY6Y1@krU6GWBy@Ucr66usvIwp5/Fj@/zMiv47XCOWZ4Vi@Wz46Iyo91XZ1Zq//lL@n0xOlPBvZc6uNFo9/ne3XmB@m6@M58PxoMMBq/5cZTeFtn80Tc93gwWi2wLGB6je@AGZpO5Bfgk9Hhr6LT5z/F/q/1nJxuPdZTxVvQG5u/QK0xvr/8@MqWAE6MmcO6xmMHxTVGhngqQDhC@BeG8NBpQl/TnWmHBSS9gYiw01kwt1rXUU2jC7a0SILSvgpPovIuUgtWnpC6sG7KPU7/vIA9S@bhvg4a8g84EQAcNWg9mAjSwT91o4VtjZ7z7cW8cPSTBT9JXzLdQCdVk0Ip9K4CxbMubqSA1Sy8xKiUBSuYWbcdSmxkk20SRlKhRgZPvA0VhpntPmebSQyknlBjlDBNrajAxUrIG72iDUq1M@zLW381WxXQZkKu@nPShDSk5b7GIuwy/qKj8sdDcBqUAcxM80zx77alDiOXUhsRYogjOcbOoOaEewkWVPJB@UUl/QKX0wwG3/b9JhtRPjLkfTVKnrK6NFyWEJg2YdIKbzyPlTTNMfihjcr9iOUqMCRNpadUxGj1TuiiIqsXOgUDXsdRE6nKl0xCfTLaVoQGeUVy6GqFGnlQt7k8MjfblAItCNOTschDJ4/jJ@ZdGOL3voRZElVwD/9hgRqvwNbgEcckdLfGQU0Q@iv4XVlJ11r1h703sS4Eqg1J4lIr4q04y/q2hupP39WrfLfJG1ICKD02uRB0PbYXXdBdgQdHgVBcq0HFPwve8ls2uoN5KUcbGiBuSU916nyvtbZdOLRUl2v/A00ATs3YTb4FW0JrUwMee0qf/bkMYXxv5IJlUJRZtrKSGSIplGqlp7yBHJ8oMYt16kJIzoWJ7p0ILizSsD2bQYrpEKq5CP650ge4slj8B "Wolfram Language (Mathematica) – Try It Online") Defines an operator `±` (`PlusMinus`). Mathematica's pattern-matching does the entirety of the work here: ``` {a___,b___}±{b___,c___}= (* function of two lists, where (b___) a possibly-empty postfix of the first is a prefix of the second: *): {a,b,c} (* concatenate. *) ``` [Answer] # [Perl 5](https://www.perl.org/) (-0777p), 20 bytes ``` s/^(.* ) \1|^ /$1/ms ``` [Try it online!](https://tio.run/##K0gtyjH9/79YP05DT4tLkyvGsCaOS1/FUD@3@P//RK4kLhBO5gKiFK5/@QUlmfl5xf91DczNzQsA "Perl 5 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~70~~ 68 bytes ``` l=(a,b,c)=>b.startsWith(a.slice(c=~~c,-1))?a.slice(0,c)+b:l(a,b,++c) ``` [Try it online!](https://tio.run/##NYtBCsMgEAC/Ujy5aCS9Fmyf0fO62aaWxS0qOebrNhRymcMw88ENG9X87VPRhceQaNEnTxDvKbSOtbdn7m@LoUkmthT3nfx0BXicaj5ql27yH50jGKSlqXAQXa1Ys1RctRhvDvLlpZU3rgZg/AA "JavaScript (Node.js) – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~28~~ \$\cdots\$ ~~85~~ 84 bytes Added 44 bytes to fix a bug kindly pointed out by [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen). Added another 13 bytes to fix another bug pointed out by [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) and [JimmyHu](https://codegolf.stackexchange.com/users/100303/jimmyhu). Saved a byte thanks to [cnamejj](https://codegolf.stackexchange.com/users/99540/cnamejj)!!! ``` $0 in a&&m&&!h{h=a[$0]+1;next}h&&a[$0]==h{++h;next}!NF{m=1;next}!m{a[$0]=++i}{print} ``` [Try it online!](https://tio.run/##SyzP/v9fxUAhM08hUU0tV01NMaM6wzYxWsUgVtvQOi@1oqQ2Q00NzLe1zajW1s6ACCr6uVXn2kJVKOZWQ1Roa2fWVhcUZeaV1P7/78jlxOXMxQWhnLhcAA "AWK – Try It Online") Inputs the two paragraphs separated by an empty line from `stdin`. [Answer] # [R](https://www.r-project.org/), ~~77~~ ~~74~~ ~~71~~ ~~61~~ 60 bytes *Edit: -3 bytes and bug-fix thanks to Giuseppe, then -1 byte thanks to Robin Ryder* ``` function(p,q){while(any(p!=(s=c(p[0:F],q))[seq(p)]))F=F+1;s} ``` [Try it online!](https://tio.run/##lZDBbgIhEIbv@xRTeuhMyqFebfa6L2GMQRjLNruAgDXG@OwrjbWu0cse/gSGZL6PPw6Re//Dq5LYqRBa91UPm53TufUOg9zScW/bjlG5A4aXGlOtMSw@5s2yvNEi8RYDLYmaunmffabT8Ap/uwCTh8t6yJZhhAAtDc2rRzZqFEpIsS7RJUaQLKPLUQou2QiiqrpR9m224AsgAjqfxxiCZFVkA9xxzy6nsdL3LuUHr0lW5v96b@b8rQLj3Vu@IkuH2f56Tfz6M4j2feg487O2lVzLiQ3fj0ao4Qw "R – Try It Online") Tries increasingly long prefixes of `p` (first paragraph) and joins `q` (second paragraph) onto them, until one is found whose first elements are equal to the whole of `p` (this will always happen when the 'prefix' grows to become the entirity of `p`, of course). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes thanks to (same method but with a much better choice of atoms!) ``` ẇÐƤẹ0⁸ṁ; ``` A dyadic Link accepting lists of lines that yields a list of lines. **[Try it online!](https://tio.run/##y0rNyan8///hrvbDE44tebhrp8Gjxh0PdzZa/z@8PPL//2j1/LxUdR0F9ZLyfDCVUZQK5qfllxZhCsQCNWAoScssA/OLMyvUYwE "Jelly – Try It Online")** ### How? ``` ẇÐƤẹ0⁸ṁ; - Link: P1, P2 ÐƤ - for postfixes, X, of P1: ẇ - sublist (X) exists in (P2)? ẹ0 - indices of 0 ⁸ṁ - mould P1 like that ; - concatenate P2 ``` [Answer] # [Perl 5](https://www.perl.org/), 42 bytes ``` sub f{join($;,@_)=~s,^((.+\n)*)$;\1,$1,mr} ``` [Try it online!](https://tio.run/##7VRNj9s2EL3rVwwEI7ZbxkAK9BJn0SyKNg0KJCiyQA91GlDSyGJMkQpJrdfJJn99@4byfiTNtYcGexBADee9efPFgYP98ar1YVH8VerL6rK@LFVZ46DlMFnyz2t116P53KP5ms@XB7l98mQ@V8XPvmF65m1Lr5Kud/TLRd1pt2UykTS9Gzkm4x1p1@CLew4UTWKCTBqC3wbd98ZtaRjfv7dM7FI3RqNjihlSC/sW7Bziqnie5pGq0diUL8PoqDrQwY@kIw06JPItpY6/lOI47X3Yye0fD06zALD9aVIn4EAd20HRnueBSRxFUPJbBlXAIYeEfLKmCjochOff2ifBgBik6O0oaUuUzCrYlJBgZRI1pkU@SJXa4HvyOcwkin7DBZLs/P5xcRp3NwWMiqDnWEL8OA@amIKu821x1qHeubJSd2tJV35Mgkki8YhbUS6h82ASfD3GKN1BN8Z@RWfdFB3kdWfSQ5QvrYpiavT/P5Fn3l8PIaiRzLlP3NA4TNNkIkuzZX6SH1ZQgiwh@gYSkYx4tybAGsVVJ/E/ZDZt9/oQiXU8CE9rXDORDABD277zmNMdItbaUa9lIB1fbwUmuNR1zQMklaviNB8l48ZzdPNEPQNlJOv0uTAFK70d4@QSJ1UwySQjmGxa@ooK1OO2DyJ4yD2otVXUcNLGAnzTteJXjxpD8K3p2BmoAm7UVnaistznhez0OZZc14hDz11tR@zxxHqN24vMG9cUDDe5D3wBOnu4vZfapnCYlhLlWBUvpO0YjVspeb33DJtxJCuNrHv0nE7PvbmTxlQcYRyCQQsMAvnBONw9rHTkRlEu19HJmh3b3M0tOw4aU3ln2PCfH4hOSnCcy2lbXt@/i9/@u3j/nNw/J//9c7L8UBAtZsMjNRt@UDO@GJYnvR4oqs2l2ji1Derp7M0aTrOtTyfttetSTFCFbZIL4nckYPqJSr/buJIeU/ni5Rm9/H3jxAGmdfGxyIhyMpXrqzhW1H54641bzNbq6Zvlyaeo/l4sVt9v3PK75Wy9QbBHqg8fr67@AQ "Perl 5 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11~~ 12 bytes *Edit: +1 byte to fix bug (when first paragraph is entirely within second)* ``` ḟoΠz=³m`+⁰Θḣ ``` [Try it online!](https://tio.run/##yygtzv7//@GO@fnnFlTZHtqcm6D9qHHDuRkPdyz@//9/tFKiko5SEhAnK8UCeRCWjlKKUiwA "Husk – Try It Online") ``` ḟ # return first list that satisfies: oΠ # all truthy results of z=³ # comparing each element to each element of arg1 # from this list: m # for each of Θḣ # the prefixes of arg1, beginning with the empty list, `+⁰ # append arg2 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 35 bytes ``` x=>x.replace(/^([^]*)\1^|/m,'$1') ``` [Try it online!](https://tio.run/##hZBdC4IwFIa79le8SLAtl8vrsLt@hU6Ya/aBudCILvrvtiVqN9HgbIfzPIyXc1EP1en2fLuvG3swfZX2z3T3jFtzq5U2VBQ0K@SKLfKkeC3ElZNlQli/zQIgQ6hQQqMMOcJP48qEkBxCTPAzG3XlVfe4xmvjGXQ/ncRJ/SO6/714gEH1pc4BBjLoU9oxOOSsD2lHEsggrmy7V/pEaaY4SsmQ7qBt09naxLU90oqqeVMQR07yhrDI3fmGROUPRtgM8sYTEMZY/wY "JavaScript (Node.js) – Try It Online") Split two inputs with NUL(`\0`). Competive even if need to do in function ]
[Question] [ This is a follow-up to [Chess960 position generator](https://codegolf.stackexchange.com/questions/11901/chess960-position-generator). In [Chess960](http://en.wikipedia.org/wiki/Chess960), there are 960 possible starting positions that can be enumerated from 0 to 959 (or, at your choice, from 1 to 960). The enumeration scheme is defined in <http://en.wikipedia.org/wiki/Chess960_numbering_scheme>: > > White's Chess960 starting array can be derived from its number N (0 > ... 959) as follows: > > > a) Divide N by 4, yielding quotient N2 and remainder B1. Place a > **B**​ishop upon the bright square corresponding to B1 (0=b, 1=d, 2=f, > 3=h). > > > b) Divide N2 by 4 again, yielding quotient N3 and remainder B2. Place > a second **B**​ishop upon the dark square corresponding to B2 (0=a, 1=c, > 2=e, 3=g). > > > c) Divide N3 by 6, yielding quotient N4 and remainder Q. Place the > **Q**​ueen according to Q, where 0 is the first free square starting from > a, 1 is the second, etc. > > > d) N4 will be a single digit, 0 ... 9. Place the K​**n**​ights according to > its value by consulting the following table: > > > > ``` > Digit Knight positioning > 0 N N - - - > 1 N - N - - > 2 N - - N - > 3 N - - - N > 4 - N N - - > 5 - N - N - > 6 - N - - N > 7 - - N N - > 8 - - N - N > 9 - - - N N > > ``` > > e) There are three blank squares remaining; place a **R**​ook in each of > the outer two and the **K**​ing in the middle one. > > > You can find the complete table at <http://www.mark-weeks.com/cfaa/chess960/c960strt.htm>. **Your task:** Write a program that takes an integer as its input and returns the white baseline pieces for that index, e.g. ``` f(1) = "BQNBNRKR" f(518) = "RNBQKBNR" ``` Or, you might as well use unicode `"♖♘♗♕♔♗♘♖"` if your language supports that. For your inspiration, here's a pretty straight-forward (not optimized) JS implementation: <http://jsfiddle.net/Enary/1/> [Answer] ## Python, 179 chars ``` i=input() a=i%4*2+1 b=i/4%4*2 c=i/16%6 d=i/96*5 s='NNRKRNRNKRNRKNRNRKRNRNNKRRNKNRRNKRNRKNNRRKNRNRKRNN'[d:d+5] s=s[:c]+'Q'+s[c:] if a>b:a,b=b,a print s[:a]+'B'+s[a:b-1]+'B'+s[b-1:] ``` Builds it backwards from the description order so we don't have to count the spaces that are already taken. [Answer] ## GolfScript (100 97 95 91 90 84 80 79 chars) ``` ~:?4%2*)?4/4%2*].8,^?16/6%?96/4,{5,>({}+/}%2/=+{1$=.@^}/]'BBQNNRKR'+8/zip${1>}% ``` This approach follows the instructions forwards rather than backwards. Basically it takes an array of indices and repeatedly removes the selected offsets, leaving them further down the stack; at the end, it gathers them together with the letters and uses them to sort. [Answer] ## C, 221 chars Explanations: 1. The result is accumulated in `r`. 2. `g` calculates division and remainder into `n` and `x`. 3. `p` and `P` write a character in the n'th available slot. Interesting points: 1. `x~-x` is `2*x+1`. 2. In `!s*!*m`, one `*` serves as `&&`, the other is dereference. 3. `P` uses `s+0`, so with an empty parameter you get `+0`. The knights calculation is the hardest, and accounts for the longest line. Can probably be improved. ``` char*m,r[9],c; n,x; g(r){x=n%r;n/=r;} p(s){!s*!*m?*m=c:p(s-!*m++);} #define P(s,t);m=r;c=*#t;p(s+0); main(){ scanf("%d",&n); g(4)P(x-~x,B) g(4);r[x*2]=c; g(6)P(x,Q) P(n>3?(n-=3)>3?(n-=2)>3?n=3:2:1:0,N) P(n,N) P(,R)P(,K)P(,R) puts(r); } ``` [Answer] # Javascript, 230 204 200 chars, with Unicode ♖♘♗♕♔♗♘♖ With ideas from [chron's Ruby answer](https://codegolf.stackexchange.com/a/12332/8886) and [Keith Randall's Python answer](https://codegolf.stackexchange.com/a/12324/8886) ``` N=prompt(); (r='♘♘♖♔♖♘♖♘♔♖♘♖♔♘♖♘♖♔♖♘♖♘♘♔♖♖♘♔♘♖♖♘♔♖♘♖♔♘♘♖♖♔♘♖♘♖♔♖♘♘'.substr(~~(N/96)*5,5).split(''))[s='splice'](N/16%6,0,'♕'); a=~~(N/4)%4*2; b=N%4*2; r[s](a>b?b+1:b,0,B='♗'); r[s](a,0,B); alert(r.join('')) ``` (and **194 chars** without Unicode) ``` N=prompt(); (r=btoa('4ÔJDÔM)Q(ÔMD¤MDÓJEJ5M)Q(ÓQD£Q54Ó').substr(~~(N/96)*5,5).split(''))[s='splice'](N/16%6,0,'Q'); a=~~(N/4)%4*2; b=N%4*2; r[s](a>b?b+1:b,0,B='B'); r[s](a,0,B); alert(r.join('')) ``` I added both newlines and semicolons for readability. You can remove either of them when determining the character count. [Answer] ### GolfScript, 109 80 chars Using Peter's suggestion for an encoding of the string we can reduce the char count considerably. ``` ~:§96/'€’ŒŽÈÂݲ¸'=3base{'KNR'=}%81§16/6%{.3$<@+@@>+}:^~[§4/4%2*§4%2*)]${'B'\^}/ ``` A more or less direct translation of [Keith Randall's solution](https://codegolf.stackexchange.com/a/12324/1490) to GolfScript. [Answer] ## Ruby, 150 + 1 chars Trying a new approach using gsub and `$_`. ``` n,$_=$_.to_i,?R*8 {B:[n%4*2+1,n/4%4*2],Q:n/16%6,N:[k=(n/=96)/4+n/7-n/8+n/9,k+1+(n+n/7+n/9*2)%4],K:1}.map{|p,l|x=-1;gsub(?R){[*l].include?(x+=1)?p:$&}} ``` This needs to be run with the -p flag, and takes the sequence number on stdin. For example: ``` echo 518 | ruby -p chess960-lookup.rb RNBQKBNR ``` [Answer] ## vba, 472 ``` Function f(n) s="--------" s=r(s,"B",m(n,4)*2) n=n\4 s=r(s,"B",m(n, 4)*2-1) n=n\4 s=r(s,"Q",m(n,6)) n=n\6 Select Case n Case 0:x=1:y=2 Case 1:x=1:y=3 Case 2:x=1:y=4 Case 3:x=1:y=5 Case 4:x=2:y=3 Case 5:x=2:y=4 Case 6:x=2:y=5 Case 7:x=3:y=4 Case 8:x=3:y=5 Case 9:x=4:y=5 End Select s=r(s,"N",y) s=r(s,"N",x) s=r(s,"R",1) s=r(s,"K",1) f=r(s,"R",1) End Function Function m(n,q) m=n Mod q+1 End Function Function r(s,c,p) r=Replace(Replace(s,"-",c,,p),c,"-",,p-1) End Function ``` [Answer] # Excel, 345 bytes ``` =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(REPLACE(REPLACE(11111111,2*MOD(A1,4)+2,1,"B"),2*MOD(QUOTIENT(A1,4),4)+1,1,"B"),1,"Q",MOD(QUOTIENT(QUOTIENT(A1,4),4),6)+1),1,"N",CHOOSE(QUOTIENT(QUOTIENT(QUOTIENT(A1,4),4),6)+1,1,1,1,1,2,2,2,3,3,4)),1,"N",CHOOSE(QUOTIENT(QUOTIENT(QUOTIENT(A1,4),4),6)+1,1,2,3,4,2,3,4,3,4,4)),1,"K",2),1,"R") ``` Breakdown for those interested. For simplicity, first the codes used to determine the Numbers used: ``` {N2} =QUOTIENT(A1,4) {B1} =MOD(A1,4) # For Bishop {N3} =QUOTIENT(QUOTIENT(A1,4),4) {B2} =MOD(QUOTIENT(A1,4),4) # For Bishop {N4} =QUOTIENT(QUOTIENT(QUOTIENT(A1,4),4),6) # For Knights {Q} =MOD(QUOTIENT(QUOTIENT(A2,4),4),6) # For Queen ``` And from the middle outwards: ``` REPLACE(11111111,2*{B1}+2,1,"B") # Start with String of '1's # Place the first Bishop REPLACE(..., 2*{B2}+1,1,"B") # Place Second Bishop SUBSTITUTE(..., # Place Queen in Empty Square 1,"Q",{Q}+1) SUBSTITUTE(..., # Place first Knight 1,"N",CHOOSE({N4}+1, # Using a Lookup 1,1,1,1,2,2,2,3,3,4)) SUBSTITUTE(..., # Place Second Knight 1,"N",CHOOSE({N4}+1, # Using a Lookup, with 1,2,3,4,2,3,4,3,4,4)) # index-1 because other Knight already placed SUBSTITUTE(..., # Place King 1,"K",2) # In second Empty Square SUBSTITUTE(...,1,"R") # Rooks in Remaining Squares ``` [Answer] # [Perl 5](https://www.perl.org/), 196 bytes ``` sub e{$l=int pop;$i=-1;1until!$r[++$i]&&!$l--;$i}$r[$_/4%4*2]=$r[$_%4*2+1]=B;$r[e$_/16%6]=Q;$r[e$a]=$r[e(($n+1,$n-2,$n-3,4)[$a=substr'0000111223',$n=$_/96,1])]=N;$r[e 0]=$r[e 2]=R;$r[e 0]=K;say@r ``` [Try it online!](https://tio.run/##PY1bC4JAEIX/isJ4S7ccbxSyEL1GQb3KEgY@LMgqrj5E9NfbRoXmYZjvnOGcvhna3Bg9Pa3mDS2XarT6ri9BcoYlTmqUrQ1DFYYgheva0DJG5ockeOwyJ9skgi8wnyEKfioJGzKxcArBbyvWy1fj@6BCjECxZF5plAUV1Jzq9Th4MQ0iJknqkcsp41BEKALBr0uKFa8pFnXe/8q51PXrOBiT4/7b9aPslDbskm9jjA1TPw "Perl 5 – Try It Online") [Answer] # x86 machine code, 84 bytes ``` 60 4F B9 02 00 BA 03 00 8B D8 23 DA D1 E3 03 D9 C6 01 42 C1 E8 02 E2 F0 33 DB B1 06 F6 F1 FE C4 43 38 29 75 FB FE CC 75 F7 C6 01 51 BB 4A 01 D7 2B DA 47 38 2D 75 FB 32 E4 F6 F2 86 C4 D7 88 05 86 C4 E2 EE AA 61 C3 4B 4E 52 B8 B2 C4 8E B0 C2 8C C8 92 80 ``` This is an even more straightforward implementation adapted from [LeanChess960](https://leanchess.github.io#lc960). Rather than calculate indices, it writes directly to the buffer (which is assumed to contain 0s). I found the LUT approach to be more economical - it only requires 1 byte per arrangement thanks to ternary encoding of the starting positions (0 - K, 1 - N, 2 - R). LeanChess Barebone editions use a trick that may further reduce the code size by transforming a piece type (0..7) to ASCII (K, N, O, P, Q and R), but I was too lazy to find a transform for KNR (0..2). Assembly source code: ``` gen960: pusha dec di bishop: mov cx, 2 mov dx, 3 bish_loop: mov bx, ax and bx, dx shl bx, 1 add bx, cx mov byte ptr [di + bx], 'B' shr ax, 2 loop bish_loop queen: xor bx, bx mov cl, 6 div cl inc ah queen_loop: inc bx cmp [di + bx], ch jne queen_loop dec ah jne queen_loop mov byte ptr [di + bx], 'Q' knr: mov bx, offset knr_db xlat sub bx, dx knr_loop: inc di cmp [di], ch jne knr_loop xor ah, ah div dl xchg al, ah xlat mov [di], al xchg al, ah loop knr_loop done: stosb popa ret K equ 0 N equ 1 R equ 2 db "KNR" knr_db: db N + N * 3 + R * 9 + K * 27 + R * 81 db N + R * 3 + N * 9 + K * 27 + R * 81 db N + R * 3 + K * 9 + N * 27 + R * 81 db N + R * 3 + K * 9 + R * 27 + N * 81 db R + N * 3 + N * 9 + K * 27 + R * 81 db R + N * 3 + K * 9 + N * 27 + R * 81 db R + N * 3 + K * 9 + R * 27 + N * 81 db R + K * 3 + N * 9 + N * 27 + R * 81 db R + K * 3 + N * 9 + R * 27 + N * 81 db R + K * 3 + R * 9 + N * 27 + N * 81 ``` [Answer] # IA-32 machine code, 99 bytes Hexdump: ``` 60 68 4e 52 4b 52 68 42 42 51 4e 60 8b fc 8a c1 24 03 d0 e0 40 aa 8a c1 24 0c d0 e8 aa 6a 04 58 91 d3 e8 d4 06 aa 3a e1 72 07 2a e1 49 fe c5 eb f5 8a c5 aa 02 c4 aa 33 c0 ab 8d 77 17 8b fa ab ab aa 8b fa 6a 08 59 8a 46 e0 33 db 4b 43 80 3c 1f 00 75 f9 fe c8 7d f5 ac 88 04 1f e2 e9 83 c4 28 61 c3 ``` A pretty straightforward implementation of the rules. First, it calculates the index of each piece, in the order specified by the rules. After placing the knights, the indices of Rook, King and Rook (in that order) are 0. Then, it converts the indices to "absolute indices", taking into account occupied places. Empty places are marked by a zero byte, and occupied places are marked by the name (letter) of the piece. Division by 4 is implemented by bit-fiddling. After dividing the starting position by 16 (twice by 4), the quotient is smaller than 256, so it's possible to use `aam` to divide by 6. The positions of the knights are determined by a calculation, not by a LUT - the code seems to be smaller that way. Assembly source code: ``` pushad; // save all registers push 'RKRN'; // prepare a LUT of names of pieces push 'NQBB'; pushad; // allocate temporary variables (values = junk) mov edi, esp; // prepare a pointer to indices of pieces // Calculate the index of a Bishop from bits 1 and 0 mov al, cl; and al, 3; shl al, 1; inc eax; stosb; // store the index of Bishop // Calculate the index of a Bishop from bits 3 and 2 mov al, cl; and al, 12; shr al, 1; stosb; // store the index of Bishop // Divide by 16; also load 4 into ecx push 4; pop eax; xchg eax, ecx; shr eax, cl; // Divide by 6 _emit 0xd4; _emit 6; stosb; // store the index of Queen // Calculate the indices of Knights: // Subtract 4, 3, 2, 1 until no longer possible. // Knight 1 index: number of times subtraction succeeded // Knight 2 index: that, plus remainder kloop: cmp ah, cl; jb kdone; sub ah, cl; dec ecx; inc ch; jmp kloop; kdone: mov al, ch; stosb; // store the index of Knight add al, ah; // calculate the index of the other knight stosb; // store the index of Knight xor eax, eax; stosd; // store indices of Rook, King and Rook lea esi, [edi+23]; // point to the names of pieces // Fill the output buffer with zeros mov edi, edx; stosd; stosd; stosb; mov edi, edx; // Initialize loop counter for the loop over pieces push 8; pop ecx; pc_loop: mov al, [esi-32]; // read the index of the piece xor ebx, ebx; // initialize the absolute index dec ebx; pos_loop: // Find a zero byte inc ebx; cmp byte ptr [edi+ebx], 0; jne pos_loop; // Decrease the index until it hits -1 dec al; jge pos_loop; lodsb; // read the name of the piece mov [edi+ebx], al; // store it into the output string loop pc_loop; // repeat for all pieces add esp, 40; // restore stack pointer popad; // restore all registers ret; // return ``` ]
[Question] [ Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details. The story continues from [AoC2018 Day 3](https://adventofcode.com/2018/day/3). *But you're not Bubbler, you're Lyxal! [yeah, I know.](https://chat.stackexchange.com/transcript/message/59905194#59905194)* --- After a long period of chaos, the Elves have finally agreed on how to cut the fabric. Unfortunately, the next day they have come up with how to utilize the leftovers - make a super long present wrapping strip. Well, if it can shrink Santa, it might be able to shrink presents as well... The description of the strip is a string of `ODCF`, which happens to be the first letters of "up down left right" in Elvish (totally not [this Elvish](https://funtranslations.com/elvish)). Divide the fabric into a grid of 1cm × 1cm square cells, select a starting cell somewhere in the middle, and then move around according to the description to claim the strip. So if the string is `OOCOFFFDD`, you would get this strip, starting at X: ``` OFFF CO.D .O.D .X.. ``` ... Except that the strip the Elves gave to you is self-intersecting, so it simply doesn't work (a 1cm² fabric part doesn't magically become 2cm² - well, it's physics, at least until Santa comes). Given the string `OOCOFFFDDCCCD`, the `?` is where the strip self-intersects: ``` OFFF CO.D C?CD DX.. ``` In order to avoid the `?` cell becoming a problem, you can take its substring (a contiguous part of the given string) in two ways: `OOCOFFFDDC` (cutting away the last 3 chars) and `COFFFDDCCCD` (cutting away the first 2 chars) gives, respectively, ``` OFFF CO.D .OCD .X.. OFFF CX.D CCCD D... ``` Among the two and all the other options, the latter of the two above is the longest possible. Given a nonempty string of `ODCF`, determine the length of its longest substring out of which you can make a valid (non-self-intersecting) strip. Assume the fabric leftover is large enough to cover any valid substring of the input. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` C -> 1 ODD -> 2 (DD) OOCOFFFDD -> 9 (whole input) OOCOFFFDDCCCD -> 11 (whole input minus first 2) OOOFFDCCCDFFFDCOOO -> 12 (minus first 3 and last 3) ``` [Answer] # TypeScript Types, 537 bytes ``` //@ts-ignore type a<T,P=0,N=[1,0][P]>=T extends[N,...infer T]?T:[...T,P];type b<T>=T extends{[K in keyof T]:{[L in keyof T]:K extends L?0:T[K]extends T[L]?T:0}[number]}[number]?never:T;type c<T>=T extends[{},...infer U]?T|c<U>:T;type d<T>=T extends[...infer U,{}]?T|d<U>:T;type e<T,K=T extends T?keyof T:0>=T extends T?[K]extends[keyof T]?T:never:0;type f<S,A=[],P=[[],[]],B=[...A,P],X=P[0],Y=P[1]>=S extends`${infer C}${infer R}`?f<R,B,{O:[X,a<Y>],D:[X,a<Y,1>],F:[a<X>,Y],C:[a<X,1>,Y]}[C]>:B;type M<T>=a<e<b<c<d<f<T>>>>>,1,{}>["length"] ``` [Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgAUBeABkoDlaBtARkvoF1XruAfLXKF0AD3DpEAE0ismlAHTLYiAGbpUhctwD85AFytliqvwDcuAoQBGFISPGSZkAN6sA0oVWEA1uhxkNW1uA3cAGW9EPwCgkIMvJylZQnDdegNyT24kl21WcL1DegBfVkQAVwBbG01uMsqaut1EdAA3TUzLfCIAY3thUQlkuVcSpRV1TUIAVSKAH36ZgS6rImkBx2GXY0mNLRnKMYWN5dWe0QpKD0HclPJdf0Dg4och53vdbLu5J7idfQGVodVAGejdaxqUgAZUoAEE2NwaGxWEjUUiAEJsExwmhIgAatGorB4lAAmkSOIJaND3iMAAYAElcqn2hAAwiVmazpgAlEr03RQ3mUDFHADyRnxlDIZIESIAIlKZaQyZR2PLKAAxIxkfECclI9m60jSjWGsrswQGDEQogAWQGZHQpDs-Q2UPIAm93vVRxKAlYACIADZSeDgAAWQe4mGwF3I9EItEIjqD7KDAkwIEIuYAerp49ZyOxk6nSEHxQqFZns8Bc4QC0WiOQAExltPi8Xs8VavvV2s5-OFtbaADMHYrXZ7fa11fZC5rWaHjZHCYALJPK13+wv2QrZwqe13B-Xh5ggA) ## Ungolfed / Explanation ``` // Increment/decrement an integer stored as e.g. [0, 0] for 2, [1, 1, 1] for -3, and [] for 0 // Invoked as Inc<T> to increment, or Inc<T, 1> to decrement type Inc<T, Pos = 0, Neg = [1, 0][Pos]> = T extends [Neg, ...infer T] ? T : [...T, Pos] // Filters a union of tuples for those with no duplicate elements type FilterNoDuplicates<T> = // Map over the union T T extends { // Map over the tuple T [K in keyof T]: { // Map over the tuple T [L in keyof T]: // If K != L and T[K] == T[L], return T K extends L ? 0 : T[K] extends T[L] ? T : 0 }[number] }[number] // If any returned T, omit T from the union ? never // Otherwise, keep T in the union : T // Get all prefixes of T as a union (e.g. [1,2,3] -> [] | [1] | [1,2] | [1,2,3]) type Prefixes<T> = T extends [{}, ...infer U] ? T | Prefixes<U> : T // Get all suffixes of T as a union (e.g. [1,2,3] -> [] | [3] | [2,3] | [1,2,3]) type Suffixes<T> = T extends [...infer U, {}] ? T | Suffixes<U> : T // Filter a union of tuples, T, for those with the maximum length type Longest<T, K = T extends T ? keyof T : 0> = T extends T ? [K] extends [keyof T] ? T : never : 0 // Convert a path like "ODCF" to its path (a list of pairs of integers, starting with (0,0)) type GetPath< Str, // The current path, not including the current position Path = [], // The current position Pos = [[],[]], // Aliases NewPath = [...Path, Pos], Pos0 = Pos[0], Pos1 = Pos[1] > = // Get the first character of Str Str extends `${infer Char}${infer Rest}` // Recurse ? GetPath< // Set Str to Rest Rest, // Set Path to NewPath NewPath, // Update Pos based on Char { O: [Pos0, Inc<Pos1>], D: [Pos0, Inc<Pos1, 1>], F: [Inc<Pos0>, Pos1], C: [Inc<Pos0,1>, Pos1] }[Char] > // Str is empty : NewPath // Convert Str to a path, find all subpaths, filter the subpaths // for no duplicates, find the longest, return its length minus 1 type Main<Str> = Inc<Longest<FilterNoDuplicates<Prefixes<Suffixes<GetPath<Str>>>>>,1,{}>["length"] ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/) 106, 103 (@pxeger), 96 (@ovs), 89, 84 bytes ``` lambda s,*i,x=0:max(len(i:=[x,*i[:[*i,x:=x+1j**"CDF".find(j)].index(x)]])for j in s) ``` [Try it online!](https://tio.run/##TYuxCoMwFEV3vyI4vWdFKl1KINMLWfMB1sGiwYjGoJamX5/GTp3uPedy/ecYV3e7@y0a8Yhztzz7ju1lYcsgrnzpAsyDA8tFE5JseHMuXIRLPRVFTlLllbGuhwnbKuUQIGDbolk3NjHr2I7xPdp5YDX3m3UHGLDOvw5AxKjTP9OSVEYpZKY1aaXUfyOikxL86uko4Rc "Python 3.8 (pre-release) – Try It Online") #### Older versions ``` lambda s,i=[0],x=0:max(len(i:=[x:=x+1j**"CDF".find(j)]+i[:(i+[x]).index(x)])for j in s)-1 ``` [Try it online!](https://tio.run/##TYyxDoMgFEV3v4J04qk1mi4NCROGlQ@gDDZKfEaRqE3p11Ps1Omec4brP8e4utvdb9HyR5y75dl3ZC@R69qUgdds6QKdB0eRcR0YD0Uz5flFtPJSWXQ9ncAUqBnFQgcDVUpDoAEM2HUjE0FHdrg28T3iPJCG@Q3dQS1F518HBYCo0lemWiEzkabNlBJKSvlPQojTkvzwbCLpFw "Python 3.8 (pre-release) – Try It Online") ``` lambda s,i=[0],x=0:max(len(i:=i[(x:=x+1j**"CDF".find(j))in i and-~i.index(x):]+[x])for j in s)-1 ``` [Try it online!](https://tio.run/##TYy9CoMwFIV3nyJ0SvxD6VICma5kzQNYhxQNXtEY1NJ06aunsVOnc76Pw3HvY1zt9ea2YMQ9zHp59JrsOYq26nIvKr5oT@fBUuQCW@q58Fk9pekFGnkpDdqeToyhJUi07YsPllENnnrGu6z1HTPrRiYSBzsr6vAacR5Izd2G9qCGonXPgzLGgoqHiWpAJhCjSZQCJaX8bwBwUoRfPR1E/AI "Python 3.8 (pre-release) – Try It Online") ``` x=m=0;i=[] for j in input(): i+=x,;x+=1j**"CDF".find(j) while x in i:_,*i=i m=max(m,len(i)) print(m) ``` [Try it online!](https://tio.run/##TY3BCoMwEETv@xUhp8RKqfSm7Gkl13xAKaW0EVdMFLE0/fo02kthYeYN7Mz8WfspnNO759GJqnbRPZSUMkX0eGoYL1fopkUMgkO@@bUqXYPgA8ayiQeshqKQ1Bp57Dg81aBB/Kri/lDfyoKRQXj096h8ObqgWGuYFw6r8jrlLZ1sbgDbkgHK0oK1ZI0x/46INsqw2y2jjF8 "Python 3 – Try It Online") ``` x=m=0;i=[] for j in input(): i+=[x];x+=1j**"CDF".find(j) while x in i:i.pop(0) m=max(m,len(i)) print(m) ``` [Try it online!](https://tio.run/##TY3BCoMwEETv@YqQ08YWUXpTclrJNR8gHkobccXEIJamX59GeykM7LyBmQ2ffVr9Lb0nWiyvGxvtA4QQKSqnqpZUP7Bx3fjMyWeF1w6yYZwuqo9DGy@qnotCYKdFOZJ/wiwZ/23Fs9FQGdYAVY6dcvcI7rpYDyQlCxv5HZxM@Z1MJm8w06FmmE/HjEGjtf53iHhQhtMeGWb8Ag "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` FLθ«F✂θιF¬℅KK✳⊗⌕FOCκ¹ψ⊞υLKA⎚»I⌈υ ``` [Try it online!](https://tio.run/##LY1BDsIgEEXX7SlIV0NSF65dGQgrlSaeAClaUgopBaMxnh2hdTbz58@bP3IQXjphUro7j@Ck7CMMMGOMPnW1WlejpYK5RTqbq3NxAbjvtRUGOqVGwLlQ57UNQLVXMmhngbp4M6oHpm0PDeOkadGYwRbt8aGuNvy9yrgMEFv0f14ij8aU1LwkRgkPWX3r7YSIJcBZvPQUJ4gFSolzzhglhFBWeh7T7ml@ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FLθ« ``` Loop over each suffix. ``` F✂θι ``` Loop over the characters in the suffix. ``` F¬℅KK ``` Stop if the strip self-intersects. ``` ✳⊗⌕FOCκ¹ ``` Mark the current cell as part of the strip and move to where the next cell should be. ``` ψ ``` Ensure that the final cell is not part of the strip. This will remove the wrong cell if the strip self-intersected but only the count matters. ``` ⊞υLKA ``` Record the number of cells marked as part of the strip. ``` ⎚ ``` Clear the canvas ready for the next suffix or to output the result. ``` »I⌈υ ``` Output the maximum possible strip length found. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~40~~ 35 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` ⌈´·{⊑/¬«∊+`<˘»⍉¬4|31‿37|⌜9×@-𝕩∾@}¨↓ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oyIwrTCt3viipEvwqzCq+KIiitgPMuYwrvijYnCrDR8MzHigL8zN3zijJw5w5dALfCdlaniiL5AfcKo4oaTCgoKPuKLiOKfnEbCqCDin6giQyIKIk9ERCIKIk9PQ09GRkZERCIKIk9PQ09GRkZERENDQ0QiCiJPT09GRkRDQ0NERkZGRENPT08i4p+p) BQN doesn't support complex numbers yet, which means the directions have to be encoded as tuples by `<˘⍉¬4|31‿37|⌜9×@-𝕩`: ``` ⟨ 'O' ⟨ ¯1 0 ⟩ ⟩ ⟨ 'D' ⟨ 1 0 ⟩ ⟩ ⟨ 'C' ⟨ 0 ¯1 ⟩ ⟩ ⟨ 'F' ⟨ 0 1 ⟩ ⟩ ``` We iterate over the suffixes `↓`, and get the length of the longest unique prefix of each. The maximum of that is the result. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 98 bytes ``` s->vecmax([vecmin([#[1|k<-[j..p=#s+a=0],p*=a+=I^(Vecsmall(s)[k]%69)]+j-i|j<-[i..#s]])|i<-[1..#s]]) ``` [Try it online!](https://tio.run/##Xc09C4MwEAbgvxIihaSaUJdCoXGJCJ3cuoQUgmiJXxymlBb87/YUp07vPS/cHbjJiycsDVFLENm7rgb3YWZNPzITmXTursK0UoKKQuzUySZwVC5Wtwe711UYXN@zwE1nD@cLt3Er/NzihpcyCtby2SPSHYsD6L8sEJERmPz4wpGuoKTBIzwhhmqaEFrm@RalLoui@IPWei/Qm9ZaIym@@AE "Pari/GP – Try It Online") [Answer] # [Python](https://www.python.org), 99 bytes ``` f=lambda a,B=1,c=0,*v:a>""and max(B*f(a[1:]),~f(a[1:],0,r:=c+1j**'OCD'.find(a[0]),*v,c)*~-(r in v)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3k9NscxJzk1ISFRJ1nGwNdZJtDXS0yqwS7ZSUEvNSFHITKzSctNI0EqMNrWI1deqgLB0DnSIr22RtwywtLXV_Zxd1vbTMvBSgnAFQkVaZTrKmVp2uRpFCZp5CmaYm1KqcgqLMvBKNNA11Z3VNTS44z9_FBZXv7-zv5uaGS9TZ2RldBigBFgbJOwO56jA7Yd4EAA) Tricks: * `a>""` is the same as `bool(a)`, since strings are compared lexicographically, and can be used as a recursive base-case because it returns `0` when `a` is empty, unlike simply `a and` * `a>""` is a sufficient base-case to prevent infinite recursion, which allows shorter conditionals later on because they're allowed to be strictly evaluated (mostly using `*`, and the fact that the output is always positive so we can happily pass `0` to `max`) * `~X*~-Y` = `-~X*-~-Y` = `(1+X)*(1-Y)` = `(1+X)*(not Y)` * With the help of the flag variable `B`, I combine the loops searching for the shortest substring into one recursive function [Answer] # [Rust](https://www.rust-lang.org/), 150 bytes ``` |i:&str|i.bytes().scan((vec![],[0,0]),|(v,p),c|{v.push(*p);p[c as usize%23&1]+=1-c as i64%2*2;while v.contains(&p){v.remove(0);};Some(v.len())}).max() ``` [Try it online!](https://tio.run/##bZBRS8MwFIXf@yvuBis3M4a1iqBlTx177YOPpUgsKQusaUzSTl3722taJ0zxvOV8h5PDNa11Y6Wg5lIhgXMAXkfhoIItjL18Cq0zvWSvH05YJMyWXCF2olzkBc03dFMQ2mNHNaFlf@6Ybu0B15okOi@BW2it/BSr@C6MipttdDt78uF@Fa/j5HSQRwEdKxvl/PcWQ018hRF10wnckGRInptaYMeOwo8jA2E1f0cyThuTYJ5aNQZQKt06ClzZkzAEpIIwn@kkXKZLChGhV06223kv/u1labbf72fy@D9J03Si0Z@yzNOZTaHUP6fMT3lxuekkbq0w7kW8LbD6Hk1Yq06GayQU1pf9yZwfgiEYvwA "Rust – Try It Online") Ungolfed: ``` |i: &str| { i.bytes() .scan((vec![], [0, 0]), |(v, p), c| { v.push(*p); p[c as usize % 23 & 1] += 1 - c as i64 % 2 * 2; while v.contains(&p) { v.remove(0); } Some(v.len()) }) .max() } ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 89 bytes ``` Max[s=Subsequences;Length/@Select[s[I^ToCharacterCode@#~Mod~69],FreeQ[Tr/@Rest@s@#,0]&]]& ``` [Try it online!](https://tio.run/##XchBC4IwGIDhvzImeDLsFEQYg08GQWKlt7Fgzc8UUmmbEET@9WXRqdPL83bKNdgp12rla5L4TD2ETYrxYvE@Yq/RbvbYX10TswJvqJ2wYncuB2iUUdqhgaFCFkzZUE2rtYy4QTyK0sTshNYxy4JoKUMpQ38wbe9EQBZbUotAShKSmJEnBRoRmqfpNznknPM/AMBvzP7qs2Emffk3 "Wolfram Language (Mathematica) – Try It Online") [Answer] # Python3, 195 bytes: ``` f=lambda d,x,y:{'O':(x+1,y),'C':(x,y-1),'D':(x-1,y),'F':(x,y+1)}[d] g=lambda s,p=(0,0),q=[]:0 if not s or(n:=f(s[0],*p))in q else g(s[1:],n,q+[p])+1 r=lambda x:max(g(x[i:])for i in range(len(x))) ``` [Try it online!](https://tio.run/##dY7NaoQwFIX3PsXdeW@9A4ZuSsBVxK0PELKw@FPBiTG6iAzz7E7sMIUWujvn@7iH6/bta7bvH84fR19MzfWzbaDlwLu8pXUqMWSCd@JUnZn3i4i5PPPlyasnzwTddWuS4bWxsisw55x4KbSROYw92HmDFWaPVhY9rjo3/OaIRgsLdNPawRChkIYtL5l2hjKR@NdgkNcm4IBBj9JQP3sYIV76xg4dTp3FQESH86Pd0GP8lyj5aXVZ/u61qquq@o8qpf6aKL7x6VWsUR8P) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 108 bytes ``` f=a=>Math.max(a&&f(a.slice(1)),Buffer(a).some(g=c=>g[g[[x,y]]=[x+=(c=c%13%5-2)%2,y+=~c%2]]||!++t,t=x=y=0),t) ``` [Try it online!](https://tio.run/##dY49b4MwEED3/go3EpEtHFIcdehwGWrEVvEDEIPl2IQKcIRNC1LUv07tLm3zcdOd9N7TvYsPYeXQnNymNwe1LBoE7N@EOyadmLBYrzUWiW0bqXBKCH0dtVYDFiSxplO4Bgn7uqzLcqJzVUE5xYAlyCjdRc8bRiJG5xi@ZMSq6nx@jGNHHUwwwxOhjizS9Na0KmlNjTVe8RUh6Gq2W5Q@XJBFlt1gPckQzjJyhRe8yPP8QvL4C8KfRw@ipj@N7r7HOf91w0PpPxF1TT9apJvBOsRuZHzlpxFi3J@hFTL@3b/qDon@gFoRVrJ8Aw "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~88~~ 86 bytes ``` ->s{*l=z=0;s.chars.map{|c|l<<z+=1i**"OCDF".index(c);_,*l=l while l!=l|l;l.size}.max-1} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664WivHtsrWwLpYLzkjsahYLzexoLomuSbHxqZK29YwU0tLyd/ZxU1JLzMvJbVCI1nTOl4HqCNHoTwjMydVIUfRNqcmxzpHrzizKrUWqLlC17D2f4FCWrSSs1IsF5jh7@ICZ/o7@7u5uWERcHZ2RhIEioFFQFLOQK5S7H8uAA "Ruby – Try It Online") ]
[Question] [ ## Background A [Hamiltonian path](https://en.wikipedia.org/wiki/Hamiltonian_path) is a path on a graph that steps through its vertices exactly once. On a grid, this means stepping through every cell exactly once. On a square grid, a Chess King can move to a horizontally, vertically, or diagonally adjacent cell in one step. ## Challenge Count the number of Hamiltonian paths using Chess King's moves through a square grid of 3 rows and N columns (denoted `X` below), starting at the left side of the entire grid (denoted `S` below) and ending at the right side (denoted `E` below): ``` <------N------> X X X ... X X X S X X X ... X X X E X X X ... X X X ``` In other words, count all paths from `S` to `E` that passes through every `X` exactly once using only King's movements. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. Kudos if you can solve this with short code in a way other than brute-forcing all possible paths. ## Test cases Generated using [this APL code](https://tio.run/##SyzI0U2pTMzJT/8PBLmJJY/aJjxqm1j9qG9q7aEVj3o3G5pyGSgYKBgqgAlDBSgHwoCIcBmiKjCEKTCEKDDkgqo2gOsHq0Zo4gKJGMNMQNJqAFFngHADDCLcAFFgiKrAEEOBMUwMxQ1wp2D4Aq4VRQGSL7ApMFQwQfaFkQIQGSK7wQjkTUMkCKMgCkxgYkaojjRCtgIlHGBm4wgHbAoImPCoY4ae7aNeaORXAz1g8qhnOzBpaOsdnv6od7HGo96t2oaaKMqAacVAB8QyAAA) (equivalent [Python 3 + Numpy](https://tio.run/##fZDdjoMgEIXveYq5hMY0DHYv@yTGbLjoD4kCoTSrT2@hFAux3UAED985zGBnfzW6XZazMyPo@2hnUKM1zu/IKP2x65T2dGJn42ACpcO0d0/Z/mYHFdY@Hqh44KS@nCj@sJ5YF03doLQcLvsQ49T0a83fyVHpnJxpkFijWIcNtpuEBgXr2bJw4IDw/CC8ftImKQRrADOACUDyovnqf9JvE4lKmxMKK08cJyudx7uGBGAN4AZos1bVsJay6WK1VkDRxScA4VB2ISBMLGsQsU0sRl4ScMiaqIsU5RXVO@TsL@/wCfg/4QE)) which I created by finding 15 possible states of the rightmost column and deriving a 15-by-15 transition matrix (figures up to `N=3` are crosschecked with [a pure brute-force Python](https://tio.run/##NY3BTsUgFET3fMUs4dkaqK6qfEnTBeaBYuiFUEhaf76WPt2cxbl3ZtJeviINx@FyXOCLzSXGsMIvKeZyY3fr4DiJkcE7ELSGHJGypwL1hmxLzcQQoDFtT/tNfcPFjA2ekA192jN7mb2ZqVcdZAc1z@yvZK0Lr5Ocn7M1QWsJQ3fU8/HfUK8uZ0Lg5mPlW7@L9@Gx0l2tPz6dFeMZ6eqkxlk8Fmu7JZuXWkzxkVYehGCOywbVMDS8NLyK4/gF)). ``` N -> Answer 0 -> 1 1 -> 2 2 -> 28 3 -> 154 4 -> 1206 5 -> 8364 6 -> 60614 7 -> 432636 8 -> 3104484 9 -> 22235310 10 -> 159360540 ``` Thanks to @mypronounismonicareinstate and @ChristianSievers for confirming the test cases in the sandbox. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~76~~ 72 bytes ``` LinearRecurrence[{6,12,-27,2,30,4,-6},{0,0,1,2,3,29,155}-6/5,{#+4}]+1/5& ``` [Try it online!](https://tio.run/##Fci9CsMgFAbQhyl0ySf@NFoyBPoAHUJWcbjITesQB7GT@OyWnPGcVL98Uk2RxrGOd8pMZef4K4VzZN8ctIEwTxg8FGYI19EUFPQ1MAu0tV04adFu09zDpKW9j62kXP0hXzvlD3uFJYTxBw "Wolfram Language (Mathematica) – Try It Online") *The non-homogeneous linear recurrence equation is so much shorter to express that it saves a few bytes to modify the code to handle non-homogeneous linear recurrence.* More info: In this case, it cannot be represented as a polynomial. I tried to put the recurrence into `RSolve`, but it takes a long time to figure out the exact symbolic form (I terminate it before it completes), and I'm pretty sure that the required coefficients are irrational (approximate numerical formula can be obtained). Returns a singleton list containing the result. [Answer] # [Python 2](https://docs.python.org/2/), ~~136~~ 129 bytes ``` f=lambda n,c=0,p=1:p==3*n+4and c+6>>3*n+3or sum(f(n,c|1<<p,p+d-4)for d in range(9)if~47&1<<p+3and(p%3*3+d%3)%8and~c&(-p>~n*3)<<p) ``` [Try it online!](https://tio.run/##FczLDsIgEIXhV2FDMxSaWKdeU3gXLKJN7HSCdWFi@upIl3/Ol8Pf5TnTPudoX366BS/IDHZn2LZXthZr0p2nIAZ9dG4rnJN4fyaIUOCv7Xs2rEPTqViGIEYSydPjDhc1xrU7VZvQWC6AJdaog0Qlz6XXoYKG3Uo1qmJU5jTSIiIcVP4D "Python 2 – Try It Online") *-5 bytes thanks to @ovs* Performs a depth-first search starting at S and ending at E. The start position is encoded as `p=1`, and increase down and to the right, so the top row for n=4 is `0,3,6,9` and the bottom row is `5,8,11,14`. ``` f=lambda n,c=0,p=1:( # if at final position: p==3*n+4 and c+6>>3*n+3 # return 1 if all cells passed through else 0 or # else return sum of: sum( f(n,c|1<<p,p+d-4) # ways from that point for d in range(9) # for all 9 points within distance 1 if~47&1<<p+3 # except if off to the left and(p%3*3+d%3)%8 # or that would be walking off top or bottom # (-p>~n*3) # or off to the right # (if this evaluates False, then the next condition is ~c&0<<p, which always gives falsey 0; # if this evaluates True, then the next condition is ~c&1<<p, which tests if location already visited) and~c&(-p>~n*3)<<p ) ) ``` [Answer] # [Python 3](https://docs.python.org/3/), 104 bytes ``` f=lambda n,a=[154,28,2,1,0,-1,-1]:n and f(n-1,[sum(map(int.__mul__,a,(6,12,-27,2,30,4,-6)))-4]+a)or a[3] ``` [Try it online!](https://tio.run/##TcvLCsIwEIXhvU@R5QQnkltbEfokoYSREhSaaajtwqeP2QiFs/jO4i/f/bWyqzWNC@XnTIKRxmA6j/aOFg1qVKZterAgnkUCbj98jgyZCrx5v8WYjyVGJIQejUVlh1Y6jR5VL6VUfrqSXDdBwU21bK2BBFrKy9/@5O7kVtcf "Python 3 – Try It Online") Unlike Mathematica, Python doesn't have a built-in for linear recurrence equations, so calculating a homogeneous recurrence equation takes approximately the same number of bytes as a non-homogeneous one. [Alternative solution](https://tio.run/##DctLCsMgFAXQrThUei1@kpQWshIReSVIC/FF0mTQSbduHR9O/R6vjX1reV6pPBcSDJqDHUe4OzwcLAxMfLAgXkSWrC3C5yyyUJVvPq4plXNNCQQ5wTpod@vLGwzQk1JKuyFeSG37T1PwsdW9L5llt/YH). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` _i1ëL3LâœʒθнQyннyüα2‹PPP}g ``` Brute-force approach, so it's pretty slow. Also, 4 bytes are wasted on edge-case `n=0`. [Try it online](https://tio.run/##ATEAzv9vc2FiaWX//19pMcOrTDNMw6LFk8qSzrjQvVF50L3QvXnDvM6xMuKAuVBQUH1n//8y) or [verify the \$[0,1,2]\$ test cases](https://tio.run/##AUQAu/9vc2FiaWX/MsaSTj8iIOKGkiAiP07DkFX/X2kxw6tMM0zDosWTypLOuNC9WFF50L3QvXnDvM6xMuKAuVBQUH1n/30s/w) (times out for \$n\geq3\$). **Explanation:** In general: 1. Get all possible coordinates based on the input \$n\$ 2. Get all permutations of these coordinates 3. Filter this list of permutations and only keep those that satisfy: * The first coordinate in this permutation is in the first column * The last coordinate in this permutation is in the last column * The difference between each overlapping pair of coordinates in this permutation is 1 step (in either a horizontal, vertical, or (anti-)diagonal direction) 4. Get the amount of valid permutations left to get the result 5. (Fix edge case \$n=0\$.) ``` _i # If the (implicit) input-integer is 0: 1 # Push 1 (which is implicitly printed as result) ë # Else: L # Push a list in the range [1, (implicit) input] 3L # Push list [1,2,3] â # Take the cartesian product of the lists to get all (1-based) coordinates œ # Get all permutations of these coordinates ʒ # Filter the list of permutations by: н # Get the x-coordinate θ # of the last coordinate in this permutation Q # And check if it's equal to the (implicit) input-integer y н # Also get the x-coordinate н # of the first coordinate in this permutation yü # For each overlapping pair of coordinates: α # Get the absolute difference between the two: [|x1-x2|,|y1-y2|] 2‹ # Check for each difference in each pair if it's 0 or 1: [|x1-x2|<2,|y1-y2|<2] P # Check if both values within each pair are truthy: (|x1-x2|<2)*(|y1-y2|<2) P # Check if all checks for each overlapping pair are truthy P # Get the product of all three checks (note: only 1 is truthy in 05AB1E) }g # After the filter: get the amount of valid permutations by taking the length # (which is output implicitly as result) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 40 bytes Bruteforce for now. Times out on TIO for test cases > 2, but at least 3 was verified locally. ``` 0+₁|{;3⟦₁ᵐẋp{hh1&b;?zk{\-ᵐȧᵐ≤ᵛ1}ᵐ&th}?}ᶜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/30D7UVNjTbW18aP5y4Csh1snPNzVXVCdkWGolmRtX5VdHaMLFDuxHEg86lzycOtsw1ogU60ko9a@9uG2Of//G/2PAgA "Brachylog – Try It Online") ### How it works ``` 0+₁| ``` If input is zero, return 1. Otherwise … ``` {…}ᶜ ``` Count all … ``` ;3⟦₁ᵐẋ ``` coordinates `[[1,1],[1,1],[1,2],…,[N,1],[N,2],[N,3]]` … ``` p{ … } ``` permutations that fulfill: ``` hh1 ``` The first point's x coordinate must be 1 ``` &b;?zk ``` Zip the permutation with itself shifted by one, drop the wrapped around. `[[[1,1],[2,2]], …]` ``` {\-ᵐȧᵐ≤ᵛ1}ᵐ ``` Check king moves: For each of the pairs, `[[1,1],[2,2]]` transpose `[[1,2],[1,2]]` subtract `[-1,-1]` absolute values `[1,1]` all of them must be less or equal than 1. ``` &th}? ``` Also, the last point's x coordinate must unify with the input. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 128 bytes ``` Nθ⊞υE⁺³θ⁰⊞υE⁺³θ∧›ι¹‹ι⁺²θ⊞υE⁺³θ›ι¹⊞υ§υ¹⊞υ§υ⁰≔⟦E³∨ιυ⟧υ≔⁰ηFυF…·⊖§ι²⊕§ι²F…·⊖§ι¹⊕§ι¹F§§§ι⁰κλ¿‹λ⁺²θ⊞υ⟦E§ι⁰Eν∧∨⁻ξκ⁻ρλπλκ⟧≧⁺¬⊖ΣE§ι⁰ΣνηIη ``` [Try it online!](https://tio.run/##lZFLa4NAEMfv/RRznIUtRHvMSVooQpJKeiw5WN3oEl3NPkK@vZ1dsa2hEXrY1zx@O/Ofos510eXNMKSqd3bn2k@h8czWD5kzNToO27zHrHEGnzicGYcVW3AmqsRXLXJLEMkhItNGGOPvISz2YWyJMMv@HZjYVJXi6q/RHXsoLTFGVgo/PJiYbwHlGDv4/du94lDT69hpQMcgnKkqqBB5EftcVQJfRKFFK5QVJU6fECpmVCWF3vGxf8GiBVj0A5ust6f0PXM40WooVh4Bg9zNXG6YtAqi3CR7kxonR1ptpaK868gcH9rDOfTM10rk04GtQTRG@NRRzr2sahvGyGHX2Vm3767FP771ZuU7ZOMkMi2VxefcWKxpjMMQD4@X5gs "Charcoal – Try It Online") Link is to verbose version of code. Brute force version, because I haven't figured out a recurrence relation, assuming one is even possible. Explanation: ``` Nθ ``` Input `n`. ``` ⊞υE⁺³θ⁰⊞υE⁺³θ∧›ι¹‹ι⁺²θ⊞υE⁺³θ›ι¹⊞υ§υ¹⊞υ§υ⁰ ``` Build up an array of unvisited squares, but with a border of `0`s so the starting square is actually `[2, 1]` (and is visited). ``` ≔⟦E³∨ιυ⟧υ ``` Start a breadth-first search with this array and the starting square just mentioned. ``` ≔⁰η ``` Start with zero successful paths. ``` FυF…·⊖§ι²⊕§ι²F…·⊖§ι¹⊕§ι¹F§§§ι⁰κλ ``` For each position, loop through all of the unvisited squares of the `3×3` square that has the current square at its centre. ``` ¿‹λ⁺²θ ``` If we have not reached the finish, then ... ``` ⊞υ⟦E§ι⁰Eν∧∨⁻ξκ⁻ρλπλκ⟧ ``` ... push the grid with this square visited plus the new position to the list of positions to search... ``` ≧⁺¬⊖ΣE§ι⁰Σνη ``` ... otherwise if this is the last unvisited square then increment the number of successful paths. ``` Iη ``` Print the final count of successful paths. [Answer] # [R](https://www.r-project.org/), ~~191~~ 168 bytes *Edit: -23 bytes by switching to linear instead of matrix coordinates* ``` f=function(p=-1,m=rep(0,3*n),n){if(p>0)m[p]=1 `if`(all(m),p/3>n-1,`if`(!sum(q<-!m[a<-(a=p+(-4:4)[!!c((p+2)%%3,1,(p+3)%%3)])[a>0&a<=3*n]]),0,sum(sapply(a[q],f,m,n))))} ``` [Try it online!](https://tio.run/##PY7RisIwEEWf9SssizKzTjFposjS9EdCwCAbttBkR6sPIn57Tbts5@meAzNzrwP7209vhmDCPZ1v7W8CNqWkaK7fDILUZ0JK@GwDcCMwWnZGLhbLUxtO4LsOIhLvVJPyzuSK/h7hUpdFtL4uwRveQqm/NNqiOAPwtsL1WpGkHNUY0aH1jdj42uRnziEJGm/0nrl7gLcXR4FiLpHn9dcXkpG4@lhVy3@sJjzOrEaWez0LPYlKHGazH81RHfTwBg "R – Try It Online") Recursively tries all paths & counts-up those that end in last column & visit all positions. Commented version: ``` paths=f=function(p=c(2,0),m=matrix(0,3,n),n){ # start at position 'S'; fill matrix with zeros m[t(p)]=1 # set visited positions to 1 if(all(m)){ # visited all positions? if(p[2]==n){ # if we're in the last column... return(1)} # ...then this is a valid path else{return(0)} # otherwise it isn't. } else { # if there are still some positions to visit: a=p+rbind(1:3,rep(1:3,e=3))-2 # a = all possible king moves... a<-t(a[,!colSums(a<1|a>dim(m))]) # ...limited to bounds of matrix q=!m[a] # q = moves to unvisited positions if(!sum(q)){return(0)} # if we can't move, it's not a valid path else{ # if we can move... return(sum(sapply(split(a,seq(q))[q],f,m,n))) # return the sum of all valid paths from here # by recursively calling self with each new position } } } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ ~~25~~ 27 bytes ``` Rp3Ḷ¤Æị€;ıŒ!ISḞ=ʋƇ³IA<2ẠƲƇL ``` or ``` Ḷp3R¤Æị€Œ!ISḞ=ʋƇ’IA<2ẠƲƇL+¬ ``` [Try it online!](https://tio.run/##AToAxf9qZWxsef//4bi2cDNSwqTDhuG7i@KCrMWSIUlT4biePcqLxofigJlJQTwy4bqgxrLGh0wrwqz///8y "Jelly – Try It Online") Not the most exciting answer: brute-forces all possible paths and times out on TIO for `n>2`. *+3 bytes for fixing `n=0` case.* ~~I have temporarily paused golfing since the bytecount reached `f(2)=28`.~~ ``` Rp3Ḷ¤Æị€;ıŒ!ISḞ=ʋƇ³IA<2ẠƲƇL Rp3Ḷ¤Æị€ # Generate all points on a lattice from 1+0j to n+2j ;ı # Append 0+1j (start position) Œ! # Take all permutations ʋƇ # Filter for ISḞ= ³ # real(last-first)=n ƲƇ # Filter for IA<2Ạ # All moves have magnitude less than 2 L # Length ``` [Answer] # JavaScript (ES6), ~~82~~ 79 bytes This is using [@user202729's linear recurrence](https://codegolf.stackexchange.com/a/206901/58563). ``` f=n=>([5,5,6,7,8,34,160][n+3]||[6,12,-27,p=2,30,4,-6].map(c=>p+=c*f(--n))&&p)-6 ``` [Try it online!](https://tio.run/##FcrBDoIgGADgu0/BwTmIH6eo2Fb4Is5NRtJq9sO0dVGfner0Xb6n@ZjVLo/wFuhvU4xOo@5o30ADClo4Q1VDqYqhR14N@94rKCUI2ULQEqoCahBqyF8mUKu7wLU9OSoEMpZlgQkVnV8oEk2KC0FyJfIv54xsCSHW4@rnKZ/9nY6Gphse7FfTzVFkx8iSI34B "JavaScript (Node.js) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 22 bytes ``` #¹mo→→fΛδΛ≈fȯε→←P¤×eḣ3 ``` [Try it online!](https://tio.run/##yygtzv7/X/nQztz8R22TgCjt3OxzW87NftTZkXZi/bmtYMEJAYeWHJ6e@nDHYuP///8bAwA "Husk – Try It Online") It's just brute force, so not that fast, though TIO can handle \$n = 3\$. Husk's default return values line up nicely so that I don't waste any bytes special casing \$n = 0\$. # Explanation ``` P¤×eḣ3 Generate all permutations of vertices. ¤ 3 Apply to both 3 and n: ḣ Range from 1. ×e Cartesian product. P Permutations. For n=0 the range and the product are empty, and P gives [[]]. Note that the second coordinates run from 1 to n. f(ε→←) Check initial vertex. f( ) Filter by condition: ← First element. → Last element of that ε has absolute value at most 1. For n=0 the condition is checked for [], which is a list of lists of numbers. ← defaults to [], an empty list of numbers in this case. → defaults to 0 on it, and ε reports true. fΛδΛ≈ Check adjacent vertices. f Filter by condition: Λ For all adjacent pairs, δΛ in both coordinates ≈ the values differ by at most 1. For the empty list, Λ is always true regardless of the condition. #¹mo→→ Check last vertex. mo Map →→ Last element of last element. #¹ Count occurrences of n. The defaults work as with the initial vertex. ``` [Answer] # [R](https://www.r-project.org/)+gtools, 147 bytes ``` n=scan();m=3*n;`if`(!n,1,sum(apply((p=permutations(m,m,complex(m,rep(1:n,e=3),1:3)))[Re(p[,1])<2&Re(p[,m])==n,],1,function(x)all(abs(diff(x))<2)))) ``` [Try it online!](https://tio.run/##JYxBCsMgEEXP0k2ZKbOx7pJ6iW5LICbVIug4aALJ6a2lu/fhv1daDEux5YTPlnOs2NjU1TLgmIy@8TgHP8OFSVHdE1iReAKIEVfSvtktZK6QKNGak0R3dC5OQA1MzmgkNWhEfD0dyIvUhI/79c9pQmOYph72O6@/EBxoYwS7VHgH7/vs925j0@0L "R – Try It Online") Tests all permutations of coordinates as complex numbers, and counts those that start with Re=1, end with Re=n, and for which all steps have an absolute value less than 2. I felt that I couldn't consider myself a 'real' code-golfer unless I'd submitted a ridiculously-inefficient 'brute-force' answer that would time-out with anything except the shortest input... Completes on TIO for n up to 3. ]
[Question] [ This is a simple(ish) web scraping challenge. **Input** Your code should take [an MPAA film rating](https://en.wikipedia.org/wiki/Motion_Picture_Association_of_America_film_rating_system) and a number from 0 to 100 as input. It can do this in any way you find convenient. **Output** Your code should return the name of any movie which has a) that film rating and b) the numerical score on the Tomatometer from [rottentomatoes](https://www.rottentomatoes.com/). If there is no such movie it can output anything you like. The possible MPAA film ratings are `G, PG, PG-13, R, NC-17, NR`. Your code may report one or more movies, that is up to you. To clarify, your code is meant to access the web to get the answers to queries. **Example** Say the input is "PG, 98" then your code could output "Zootropolis". Please show an example of your code working with the film rating `PG` and score `98` along with your answer. [Answer] # Bash, 182 bytes ``` curl "https://www.rottentomatoes.com/api/private/v2.0/browse?minTomato=$2&maxTomato=$2&type=dvd-streaming-all" 2>/dev/null|grep -o "{[^}]*aRating\":\"$1\""|grep -Po 'title":"\K[^"]*' ``` Usage: ``` $ bash script PG 98 The Island President Inside Out Zootopia Paddington Love & Friendship Long Way North (Tout en haut du monde) ``` [Answer] # JavaScript (ES6), ~~167~~ ~~162~~ 159 bytes [Needs to be run from the root of rottentomatoes.com](https://codegolf.meta.stackexchange.com/q/13621/58974). [Returns a `Promise` object](https://codegolf.meta.stackexchange.com/a/12327/58974) containing the title. ``` s=>n=>fetch(`api/private/v2.0/browse?minTomato=${n}&maxTomato=${n}&type=dvd-streaming-all`).then(r=>r.json()).then(j=>j.results.find(x=>x.mpaaRating==s).title) ``` If we can [require that it be run in a specific directory](https://codegolf.meta.stackexchange.com/q/13938/58974) then it becomes 139 bytes: ``` s=>n=>fetch(`browse?minTomato=${n}&maxTomato=${n}&type=dvd-streaming-all`).then(r=>r.json()).then(j=>j.results.find(x=>x.mpaaRating==s).title) ``` [Answer] # [Python 2](https://docs.python.org/2/) + requests, ~~209~~ 204 bytes *-5 bytes thanks to Ian Gödel.* ``` lambda r,t:[i['title']for i in get('http://rottentomatoes.com/api/private/v2.0/browse?minTomato=%d&maxTomato=%d&type=dvd-streaming-all'%(t,t)).json()['results']if i['mpaaRating']==r] from requests import* ``` [Answer] # [Stratos](https://github.com/okx-code/Stratos/), 133 bytes ``` { f"www.rottentomatoes.com/api/private/v2.0/browse?minTomato=%&maxTomato=%&type=dvd-streaming-all"r"results")s"mpaaRating"=⁰ s"title" ``` [Try it!](http://okx.sh/stratos/?code=%7B%0Af%22rottentomatoes.com%2Fapi%2Fprivate%2Fv2.0%2Fbrowse%3FminTomato%3D%25%26maxTomato%3D%25%26type%3Ddvd-streaming-all%22r%22results%22)s%22mpaaRating%22%3D%E2%81%B0%0As%22title%22%0A&input=98%0APG) [Answer] # [q/kdb+](http://kx.com/download/), 168 bytes **Solution:** ``` {(r(&)(r:.j.k[.Q.hg`$"https://www.rottentomatoes.com/api/private/v2.0/browse?type=dvd-streaming-all&min",t,"&max",t:"Tomato=",y]`results)[;`mpaaRating]like x)[;`title]} ``` **Example:** ``` q){(r(&)(r:.j.k[.Q.hg`$"https://www.rottentomatoes.com/api/private/v2.0/browse?type=dvd-streaming-all&min",t,"&max",t:"Tomato=",y]`results)[;`mpaaRating]like x)[;`title]}["PG";"98"] "The Island President" "Inside Out" "Zootopia" "Paddington" "Love & Friendship" "Long Way North (Tout en haut du monde)" ``` **Explanation:** ``` .Q.hg / fetch a URL .j.k / parse json string into Q dictionaries `results / index into dictionary with key `results [;`mpaaRating] / index into these sub dictionaries extracting mpaaRating like x / binary list where they match, e.g. "PG" (&) / where, list indices where true [;`title] / index into dictionary with key `title ``` **Notes:** * If you want to try this out yourself, take a read through the [Cookbook/SSL](http://code.kx.com/wiki/Cookbook/SSL) page to ensure your environment is setup correctly. * Fails if we remove the `s` of `https`, or the `www.`, gives `301 Permanently Moved` response. [Answer] # JavaScript (ES2017), 158 bytes ``` async(r,n)=>(await(await fetch(`api/private/v2.0/browse?minTomato=${n}&maxTomato=${n}&type=dvd-streaming-all`)).json()).results.find(m=>m.mpaaRating==r).title ``` Run from the [Rotten Tomatoes home page](https://rottentomatoes.com): ``` f=async(r,n)=>(await fetch(`api/private/v2.0/browse?minTomato=${n}&maxTomato=${n}&type=dvd-streaming-all`).then(x=>x.json())).results.find(m=>m.mpaaRating==r).title f('PG',98).then(console.log) ``` ]
[Question] [ # Challenge Convert and print out a time in a 12-hour format. `HH:MM AM/PM` ### Examples Input: * `'Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'` * `'Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)'` * `'Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)'` * `'Sat Jun 31 2018 8:06:20 GMT-0700 (PDT)'` * `'Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'` * `'Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)'` Ouput: * `9:14 PM` * `12:10 AM` * `12:10 PM` * `08:06 AM` * `1:14 AM` * `09:06 AM` ### Fine Points * A zero before a one digit number **is okay**, no zero is also allowed. The following examples are **both allowed**: + `9:06 AM` + `09:06 AM` * All tested years will be after `999` (each year will be **exactly** `4` digits) # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution in bytes wins * [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * You may use functions as well as programs [Answer] # JavaScript (ES6), 69 bytes ``` d=>new Date(d).toLocaleString(0,{hour:n='numeric',minute:n,hour12:1}) ``` ``` f= d=>new Date(d).toLocaleString(0,{hour:n='numeric',minute:n,hour12:1}) console.log( f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'), f('Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)'), f('Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)'), f('Sat Jun 31 2018 8:06:20 GMT-0700 (PDT)'), f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'), f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)'), ) ``` --- # JavaScript (ES6), ~~58~~ 55 bytes Assumes you are in the United States. ``` d=>new Date(d).toLocaleTimeString().replace(/:.. /,' ') ``` ``` f= d=>new Date(d).toLocaleTimeString().replace(/:.. /,' ') console.log( f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'), f('Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)'), f('Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)'), f('Sat Jun 31 2018 8:06:20 GMT-0700 (PDT)'), f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'), f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)') ) ``` --- # JavaScript (ES6), ~~81~~ 78 bytes Answer before outputting a leading 0 in single-digit hours was made optional and test cases without leading 0s were added. ``` d=>([m,s]=d.slice(16).split`:`,`0${m%12||12}:${s} ${m<12?'A':'P'}M`.slice(-8)) ``` ``` f= d=>([m,s]=d.slice(16).split`:`,`0${m%12||12}:${s} ${m<12?'A':'P'}M`.slice(-8)) console.log( f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'), f('Sat Jun 31 2018 08:06:20 GMT-0700 (PDT)'), f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'), f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)') ) ``` [Answer] # [Python 2](https://docs.python.org/2/), 66 bytes ``` lambda s:`int(s[15:18])%12`+s[18:21]+' APMM'[int(s[15:18])>11::2] ``` [Try it online!](https://tio.run/##hc/NCoJQEIbhvVfxbUKlgpnTnw0UCFEQCELuTMgo6UCp6GnR1ZvlKiia3cDDy0z5MJciV0222DfX9HY8pajloHPj1DFPhL3E7bE69NvNE8VJ3wb8MAjs@MMsmUVU0phzbWosEFtox15XGtt7jhFBEc@gWHgsirAJoiHNiOCEq8i1Bx3fpabj/OIeyBOa/uZd/Qrirk7/635ZgV/HtIrm3@tWYllZUUFD53g/JO9AWbUvI3O02zwB "Python 2 – Try It Online") [Answer] # sh + coreutils, 22 bytes ``` date +%I:%M\ %p -d"$1" ``` (If seconds are allowed, then `date +%r -d"$1"` suffices.) [Answer] ## JavaScript (ES6), 77 bytes Assumes that the year has 4 digits. ``` s=>`${([,,,h,m]=s.match(/\d./g),x=h%12||12)>9?x:'0'+x}:${m} ${'AP'[h/12|0]}M` ``` ### Test cases ``` let f = s=>`${([,,,h,m]=s.match(/\d./g),x=h%12||12)>9?x:'0'+x}:${m} ${'AP'[h/12|0]}M` console.log(f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)')) // 09:14 PM console.log(f('Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)')) // 12:10 AM console.log(f('Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)')) // 12:10 PM console.log(f('Sat Jun 31 2018 08:06:20 GMT-0700 (PDT)')) // 08:06 AM console.log(f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)')) // 01:14 AM console.log(f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)')) // 09:06 AM ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 15 bytes ``` ÐU¯24)s8 r.³+SS ``` [Try it online!](https://tio.run/##y0osKPn///CE0EPrjUw0iy0UivQObdYODv7/X92tKFPBqzRPwdhAwcjA0FzByNDK0MTKyEDB3TdE18DcwEBBI8AlRFMdAA) 12 bytes if we can assume that the time will be given in the computer's local time: ``` ÐU s8 r.³+SS ``` [Try it online!](https://tio.run/##y0osKPn///CEUIViC4UivUObtYOD//9XdyvKVPAqzVMwNlAwMjA0VzAytDI0sTIyUAcA) ### Mathy approach, 40 bytes ``` tG5 r"^.."_<C?+Z+B:°TnZ)%CÄÃ+" {"AP"gT}M ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=dEc1IHIiXi4uIl88Qz8rWitCOrBUblopJUPEwysiIHsiQVAiZ1R9TQ==&input=J0ZyaSBKdW4gMzAgMjAxNyAyMToxNDoyMCBHTVQtMDcwMCAoUERUKSc=) [Answer] # [V](https://github.com/DJMcMayhem/V), 36 bytes ``` 16x3wC AMÇ^0ü^1[0-2]/12WrP ç^ä:/é0 ``` [Try it online!](https://tio.run/##K/v/39CswrjcWcHRV/pwe5zB4T1xhtEGukax@oZGEuFFAVyHl8cdXmKlf3ilwf//bkWZCl6leQrGBgpGBobmCkaGVoYmVkYGCu6@IboG5gYGChoBLiGaAA "V – Try It Online") Hexdump: ``` 00000000: 3136 7833 7743 2041 4d1b c75e 30fc 5e31 16x3wC AM..^0.^1 00000010: 5b30 2d32 5d2f 3132 1857 7250 0ae7 5ee4 [0-2]/12.WrP..^. 00000020: 3a2f e930 :/.0 ``` [Answer] # PHP, 45 bytes Answer improved thanks to manatwork ``` <?=(new DateTime($argv[1]))->format('h:i A'); ``` First attempt: ``` <? $d=new DateTime($argv[1]);echo$d->format('h:i A'); ``` Example usage through php CLI: ``` php d.php "Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)" ``` This is my first golf try. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 43 bytes ``` Ḳ5ịṣ”:Ṗṁ3µV’%12‘Dµ1¦µV>11ị⁾PAµ3¦“0: M”żFṫ-7 ``` [Try it online!](https://tio.run/##AX0Agv9qZWxsef//4biyNeG7i@G5o@KAnTrhuZbhuYEzwrVW4oCZJTEy4oCYRMK1McKmwrVWPjEx4buL4oG@UEHCtTPCpuKAnDA6IE3igJ3FvEbhuastN////0ZyaSBKdW4gMzAgMjAxNyAwMDoxMDoyMyBHTVQtMDcwMCAoUERUKQ "Jelly – Try It Online") This is *superfluously too long*! That is, Jelly sucks at time manipulation. EDIT: I'm even outgolfed by PHP! [Answer] # Go, 103 bytes ``` func f(s*string){t,_:=time.Parse("Mon Jan 02 2006 15:04:05 MST-0700 (MST)",*s) *s=t.Format("03:04 PM")} ``` Test here: <https://play.golang.org/p/P1zRWGske-> [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 39 bytes ``` #4è':¡¨`sD11›„APès<12%>0ìR2£R)Á… :M‚øJJ ``` [Try it online!](https://tio.run/##AWgAl/8wNWFiMWX//yM0w6gnOsKhwqhgc0QxMeKAuuKAnkFQw6hzPDEyJT4ww6xSMsKjUinDgeKApiA6TeKAmsO4Skr//0ZyaSBKdW4gMzAgMjAxNyAyMToxNDoyMCBHTVQtMDcwMCAoUERUKQ "05AB1E – Try It Online") [Answer] # [PHP](https://php.net/), 42 bytes ``` <?=date_create($argv[1])->format('h:i A'); ``` [Try it online!](https://tio.run/##K8go@P/fxt42JbEkNT65KBVIaagkFqWXRRvGaurapeUX5SaWaKhnWGUqOKprWv///9@tKFPBqzRPwdhAwcjA0FzByNDK0MTKyEDB3TdE18DcwEBBI8AlRBMA "PHP – Try It Online") [Answer] # C#, 145 bytes ``` namespace System.Linq{s=>{var d=DateTime.Parse(string.Join(" ",s.Split(' ').Skip(1).Take(4)));return d.ToString("h:mm ")+(d.Hour>11?"PM":"AM");}} ``` Full/Formatted version: ``` namespace System.Linq { class P { static void Main() { Func<string, string> f = s => { var d = DateTime.Parse(string.Join(" ", s.Split(' ').Skip(1).Take(4))); return d.ToString("h:mm ") + (d.Hour > 11 ? "PM" : "AM"); }; Console.WriteLine(f("Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)")); Console.WriteLine(f("Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)")); Console.WriteLine(f("Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)")); Console.WriteLine(f("Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)")); Console.WriteLine(f("Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)")); Console.ReadLine(); } } } ``` [Answer] # [,,,](https://github.com/totallyhuman/commata), 41 [bytes](https://github.com/totallyhuman/commata/wiki/Code_page) ``` ::18⊢3⊣⇆15⊢3⊣i11>" APMM"⇆⊢2⟛↔15⊢3⊣i12%s# ``` ## Explanation WIP [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` 5:24)16XO ``` Try it at [MATL online!](https://matl.io/?code=5%3A24%2916XO&inputs=%27Fri+Jun+30+2017+21%3A14%3A20+GMT-0700+%28PDT%29%27&version=20.1.1) Or [verify all test cases](https://tio.run/##hc4xC4JQFMXxvU9xNnMIzr2a2t0CUQikoDc05hhYhNjnf/mwLa39x/mfezt0/uq3pmks2eXoS@ejqr/h8HogIZSSQ8UkNSXqxm2Yk1ifShdHqy9JmtA0@S9Fl@S5HSYpQRZgYcx@1DtQPvXFn2Fz/@whoT4C7uY33w). ### Explanation ``` 5:24 % Push array [5 6 ... 24] ) % Implicit input. Get characters at those positions. This % removes the first four characters with the day of the week 16 % Push 16 XO % Convert to date string format 16, which is 'HH:MM PM' % Implicitly display ``` ]
[Question] [ # Positional Awareness Your task is to generate a program that, for every permutation of its characters (which includes the original program), outputs the positions of every character relative to the original program. If your program is ``` Derp ``` you must output ``` [0, 1, 2, 3] ``` (or some equivalent). This is because `D` is in the `0`th position, `e` is in the `1`st, r the `2`nd, and `p` the `3`rd. Let's take another program which is the original program, but with its characters permuted: ``` epDr ``` You must output ``` [1, 3, 0, 2] ``` because `e` is in the `1`st position of the original program, `p` is in the `3`rd position, `D` the `0`th, and `r` the `2`nd. If the original program has two repeating characters: ``` abcda -> [0, 1, 2, 3, 4] ``` Then for the permutation, the `0` and the `4` in the array must be in ascending order: ``` baadc -> [1, 0, 4, 3, 2] (0 first, then 4) ``` # Rules: * Your program must contain at least two unique characters. * At most `floor(n/2)` characters are to be the same. ``` aabb (acceptable) aaaabc (not acceptable, only floor(6/2) = 3 a's allowed) ``` * Your program's output can be either an array (or something similar) containing all the characters' positions in order, or a string with any delimiter, so these are perfectly fine: ``` [0, 1, 2, 3] 0,1,2,3 0 1 2 3 ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 2 bytes ``` 10 ``` [Try it online!](https://tio.run/nexus/actually#@29o8P8/AA "Actually – TIO Nexus") This prints ``` 0 1 ``` while the (only) other permutation ``` 01 ``` prints ``` 1 0 ``` ### How it works In Actually, consecutive digits are parsed separately, so `10` pushes **1** on the stack, then **0** on top of it. When the program finishes, the stack is printed top to bottom, so it prints **0** first, then a linefeed, then **1**. The derranged program `01` does the same, in the opposite order. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` ;J ``` [Try it online!](https://tio.run/nexus/jelly#@2/t9f8/AA "Jelly – TIO Nexus") Outputs: `[0, 1]` Other permutation `J;` outputs: `[1, 0]` ### How it works: ``` ;J ; Concats 0 with... J [1...len(z)], here just [1] J; J [1...len(z)], here just [1] ; ...Concatted with 0 ``` ]
[Question] [ **This question already has answers here**: [A simple TCP server](/questions/76379/a-simple-tcp-server) (40 answers) Closed 7 years ago. Write the shortest program that answers "Hello, World" to a network connection. Conditions: * Program shall listen on port 12345 * When a client connects, program shall write "Hello, World" to the newly opened socket connection and then close the connection * Program shall accept connections in a loop, i.e. handle any number of connects * Program does not need to handle parallel connections Test: ``` prompt> telnet localhost 12345 Hello, World prompt> ``` [Answer] ## Bash (34) ``` nc -l 12345 <<<Hello,\ World;. $0 ``` [Answer] # Java, 268 Bytes ``` import java.io.*;import java.net.*; class S{public static void main(String[]args)throws Exception{ServerSocket s=new ServerSocket(12345);while(1>0){Socket t=s.accept();PrintWriter u=new PrintWriter(t.getOutputStream());u.println("Hello World!");u.flush();t.close();}}} ``` Ungolfed: ``` import java.io.*;import java.net.*; class S{ public static void main(String[]args)throws Exception{ ServerSocket s = new ServerSocket(12345); while(true) { Socket t = s.accept(); PrintWriter u = new PrintWriter(t.getOutputStream()) ; u.println("Hello World!"); u.flush(); t.close(); } s.close(); } } ``` [![enter image description here](https://i.stack.imgur.com/RBbeh.png)](https://i.stack.imgur.com/RBbeh.png) [Answer] ## Tcl, 78 chars ``` socket -server r 12345;proc r {s a b} {puts $s Hello,\ World;close $s};vwait r ``` the `vwait r` enters the event loop (not necessary with Tk) until the variable `r` is set. Usually you use the variable `forever`. And the `Hello,\ World` is the same as `{Hello, World}` or `"Hello, World"` [Answer] # C# 220 ``` using System.Text;namespace System.Net.Sockets{class P{static void Main(){var s=new TcpListener(IPAddress.Any,12345);s.Start();while(true){using(var c=s.AcceptSocket()){c.Send(Encoding.UTF8.GetBytes("Hello World"));}}}}} ``` Ungolfed: ``` using System.Text; namespace System.Net.Sockets { class P { static void Main() { var s = new TcpListener(IPAddress.Any, 12345); s.Start(); while (true) { using (var c = s.AcceptSocket()) { c.Send(Encoding.UTF8.GetBytes("Hello World")); } } } } } ``` Pretty straightforward. I could have saved 14 characters by removing `IPAddress.Any,` but that would rely on using deprecated API ... [Answer] # Groovy, 119 bytes ``` {s=new java.net.ServerSocket(12345);while(1){(u=(t=s.accept()).getOutputStream())<<"Hello, World";u.flush();t.close()}} ``` Port of my java answer. [Answer] # Racket, 111 bytes ``` (do([l(tcp-listen 12345)])(#f)(let-values([(i o)(tcp-accept l)])(display"Hello, World"o)(close-output-port o))) ``` It always surprises me when the `do` form is shorter than explicit recursion. I'm not entirely certain if I'm required to close the input port. Please comment if you think I need to. ## Ungolfed ``` (do ([l (tcp-listen 12345)]) (#f) (let-values ([(i o) (tcp-accept l)]) (display "Hello, World" o) (close-output-port o))) ``` [Answer] # Clojure, ~~153~~ 148 bytes -5 byte using macros. See comments. ``` (let[s(java.net.ServerSocket. 12345)](while 1(with-open[c(.accept s)](doto(java.io.PrintWriter.(.getOutputStream c))(.write"Hello, World").flush)))) ``` Full program that listens in a loop for incoming connections, and outputs as required. The Java-interop is killer here. I don't need the same libraries enough to justify an import though. Pregolfed: ``` (defn server [] (let [ss (java.net.ServerSocket. 12345)] (while 1 ; Auto closes the client (with-open [c (.accept ss)] ; Passes the PrintWriter as the first argument to each function (doto (java.io.PrintWriter. (.getOutputStream c)) (.write "Hello, World\n") ; Parentheses are optional if the function only takes 1 argument ; Ugly, but shorter .flush))))) ``` [Answer] # Python, 103 ``` import socket s=socket.socket() s.bind(('',12345)) s.listen(1) s.accept()[0].sendall(b'Hello, World') ``` [Answer] # LiveScript (node.js), 73 bytes ``` (require(\net)createServer ->it.write 'Hello, World';it.end!)listen 12345 ``` [Answer] # [Go](https://golang.org), 133 bytes ``` package main import(n"net") func main(){l,_:=n.Listen("tcp",":12345") for{c,_:=l.Accept() c.Write([]byte("Hello, World")) c.Close()}} ``` [Answer] # Perl, 118 bytes ``` $s=new IO::Socket::INET LocalPort=>12345,Listen=>5,Reuse=>1;{$c=$s->accept;$c->send("Hello World");shutdown $c,1;redo} ``` Example: ``` $ perl -MIO::Socket -e '$s=new IO::Socket::INET LocalPort=>12345,Listen=>5,Reuse=>1;{$c=$s->accept;$c->send("Hello World");shutdown $c,1;redo}' $ telnet localhost 12345 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Hello WorldConnection closed by foreign host. $ ``` [Answer] # Wolfram (102) `#[[2]]` contains `OutputStream` of the incoming socket ``` <<SocketLink`; CreateAsynchronousServer[CreateServerSocket@12345,(#[[2]]~Write~"Hello world";Close/@#)&] ``` [Answer] # Ruby, 83 bytes ``` require'socket';s=TCPServer.new 12345;loop{t=s.accept;t<<"Hello, World\n";t.close} ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 9 years ago. [Improve this question](/posts/1620/edit) Create a routine that takes an array of blocks in one numeric base system, and convert them to an array of blocks in another numeric base system. Both the from and to systems are arbitrary and should be accepted as a parameter. The input array can be an arbitrary length (If using a language where array lengths are not stored with the array, such as C, a length parameter should be passed to the function). Here's how it should work: ``` fromArray = [1, 1] fromBase = 256 toBase = 16 result = convertBase(fromArray, fromBase, toBase); ``` Which should return `[0, 1, 0, 1]` or possibly `[1, 0, 1]` (leading `0`s are optional since they don't change the value of the answer). Here are some test vectors: 1. Identity Test Vector ``` fromArray = [1, 2, 3, 4] fromBase = 16 toBase = 16 result = [1, 2, 3, 4] ``` 2. Trivial Test Vector ``` fromArray = [1, 0] fromBase = 10 toBase = 100 result = [10] ``` 3. Big Test Vector ``` fromArray = [41, 15, 156, 123, 254, 156, 141, 2, 24] fromBase = 256 toBase = 16 result = [2, 9, 0, 15, 9, 12, 7, 11, 15, 14, 9, 12, 8, 13, 0, 2, 1, 8] ``` 4. Really Big Test Vector ``` fromArray = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] fromBase = 2 toBase = 10 result = [1, 2, 3, 7, 9, 4, 0, 0, 3, 9, 2, 8, 5, 3, 8, 0, 2, 7, 4, 8, 9, 9, 1, 2, 4, 2, 2, 3] ``` 5. Non-even Base Vector ``` fromArray = [41, 42, 43] fromBase = 256 toBase = 36 result = [1, 21, 29, 22, 3] ``` Other criteria / rules: 1. All integer variables should fit within a standard 32 bit signed integer for all sane input ranges. 2. You may convert to an intermediary representation, as long as the intermediary is nothing more than an array of 32 bit signed integers. 3. Expect to handle bases from 2 through 256. There isn't any need to support higher bases than that (but if you would like to, by all means). 4. Expect to handle input and output sizes **at least** up to 1000 elements. A solution that scales to 2^32-1 elements would be better, but 1000 is just fine. 5. This isn't necessarily about having the shortest code that will meet these rules. It's about having the cleanest and most elegant code. Now, this isn't exactly trivial to do, so an answer that *almost* works might be accepted! [Answer] # Python ``` # divides longnum src (in base src_base) by divisor # returns a pair of (longnum dividend, remainder) def divmod_long(src, src_base, divisor): dividend=[] remainder=0 for d in src: (e, remainder) = divmod(d + remainder * src_base, divisor) if dividend or e: dividend += [e] return (dividend, remainder) def convert(src, src_base, dst_base): result = [] while src: (src, remainder) = divmod_long(src, src_base, dst_base) result = [remainder] + result return result ``` [Answer] Here's a Haskell solution ``` import Data.List import Control.Monad type Numeral = (Int, [Int]) swap :: (a,b) -> (b,a) swap (x,y) = (y,x) unfoldl :: (b -> Maybe (b,a)) -> b -> [a] unfoldl f = reverse . unfoldr (fmap swap . f) normalize :: Numeral -> Numeral normalize (r,ds) = (r, dropWhile (==0) ds) divModLongInt :: Numeral -> Int -> (Numeral,Int) divModLongInt (r,dd) dv = let divDigit c d = swap ((c*r+d) `divMod` dv) (remainder, quotient) = mapAccumR divDigit 0 (reverse dd) in (normalize (r,reverse quotient), remainder) changeRadixLongInt :: Numeral -> Int -> Numeral changeRadixLongInt n r' = (r', unfoldl produceDigit n) where produceDigit (_,[]) = Nothing produceDigit x = Just (divModLongInt x r') changeRadix :: [Int] -> Int -> Int -> [Int] changeRadix digits origBase newBase = snd $ changeRadixLongInt (origBase,digits) newBase doLine line = let [(digits,rest0)] = reads line [(origBase,rest1)] = reads rest0 [(newBase,rest2)] = reads rest1 in show $ changeRadix digits origBase newBase main = interact (unlines . map doLine . lines) ``` And running the tests from the question: ``` $ ./a.out [1,2,3,4] 16 16 [1,2,3,4] [1,0] 10 100 [10] [41, 15, 156, 123, 254, 156, 141, 2, 24] 256 16 [2,9,0,15,9,12,7,11,15,14,9,12,8,13,0,2,1,8] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 2 10 [1,2,3,7,9,4,0,0,3,9,2,8,5,3,8,0,2,7,4,8,9,9,1,2,4,2,2,3] [41, 42, 43] 256 36 [1,21,29,22,3] ``` [Answer] ## R Handles many thousands of elements\* in less than a minute. ``` addb <- function(v1,v2,b) { ml <- max(length(v1),length(v2)) v1 <- c(rep(0, ml-length(v1)),v1) v2 <- c(rep(0, ml-length(v2)),v2) v1 = v1 + v2 resm = v1%%b resd = c(floor(v1/b),0) while (any(resd != 0)) { v1 = c(0,resm) + resd resm = v1%%b resd = c(floor(v1/b),0) } while (v1[1] == 0) v1 = v1[-1] return(v1) } redb <- function(v,b) { return (addb(v,0,b)) } mm = rbind(1) mulmat <- function(fromb, tob, n) { if (dim(mm)[2] >= n) return(mm) if (n == 1) return(1) newr = addb(mulmat(fromb,tob,n-1) %*% rep(fromb-1,n-1), 1, tob) newm = mulmat(fromb,tob,n-1) while (is.null(dim(newm)) || dim(newm)[1] < length(newr)) newm = rbind(0,newm) mm <<- cbind(newr, newm) return(mm) } dothelocomotion <- function(fromBase, toBase, v) { mm <<- rbind(1) return(redb(mulmat(fromBase, toBase, length(v)) %*% v, toBase)) } ``` \* for >500 elements you have to raise the default recursion level *or* do not reset the `mm` matrix on `dothelocomotion()` Examples: ``` v1 = c(41, 15, 156, 123, 254, 156, 141, 2, 24) dothelocomotion(256,16,v1) 2 9 0 15 9 12 7 11 15 14 9 12 8 13 0 2 1 8 dothelocomotion(256,36,c(41,42,43)) 1 21 29 22 3 dothelocomotion(2,10, rep(1,90)) 1 2 3 7 9 4 0 0 3 9 2 8 5 3 8 0 2 7 4 8 9 9 1 2 4 2 2 3 ``` [Answer] A less obfuscated and quicker JavaScript version: ``` function convert (number, src_base, dst_base) { var res = []; var quotient; var remainder; while (number.length) { // divide successive powers of dst_base quotient = []; remainder = 0; var len = number.length; for (var i = 0 ; i != len ; i++) { var accumulator = number[i] + remainder * src_base; var digit = accumulator / dst_base | 0; // rounding faster than Math.floor remainder = accumulator % dst_base; if (quotient.length || digit) quotient.push(digit); } // the remainder of current division is the next rightmost digit res.unshift(remainder); // rinse and repeat with next power of dst_base number = quotient; } return res; } ``` Computation time grows as o(number of digits2). Not very efficient for large numbers. Specialized versions line base64 encoding take advantage of base ratios to speed up the computations. [Answer] # Javascript Thank you Keith Randall for your Python answer. I was struggling with the minutiae of my solution and ended up copying your logic. If anyone is awarding a vote to this solution because it works then please also give a vote to Keith's solution. ``` function convert(src,fb,tb){ var res=[] while(src.length > 0){ var a=(function(src){ var d=[];var rem=0 for each (var i in src){ var c=i+rem*fb var e=Math.floor(c/tb) rem=c%tb d.length||e?d.push(e):0 } return[d,rem] }).call(this,src) src=a[0] var rem=a[1] res.unshift(rem) } return res } ``` ### Tests ``` console.log(convert([1, 2, 3, 4], 16, 16)) console.log(convert([1, 0], 10, 100)) console.log(convert([41, 15, 156, 123, 254, 156, 141, 2, 24], 256, 16)) console.log(convert([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 2, 10)) console.log(convert([41, 42, 43], 256, 36)) /* Produces: [1, 2, 3, 4] [10] [2, 9, 0, 15, 9, 12, 7, 11, 15, 14, 9, 12, 8, 13, 0, 2, 1, 8] [1, 2, 3, 7, 9, 4, 0, 0, 3, 9, 2, 8, 5, 3, 8, 0, 2, 7, 4, 8, 9, 9, 1, 2, 4, 2, 2, 3] [1, 21, 29, 22, 3] */ ``` This could probably be shrunk a lot, but I actually want to use it for a little side project. So I have kept it readable (somewhat) and tried to keep variables in check. [Answer] ## Mathematica No variables defined, any input accepted as long as it fits in memory. ``` f[i_, sb_, db_] := IntegerDigits[FromDigits[i, sb], db]; ``` Test drive: ``` f[{1,2,3,4},16,16] f[{1,0},10,100] f[{41,15,156,123,254,156,141,2,24},256,16] f[{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},2,10] f[{41,42,43},256,36] ``` Out ``` {1,2,3,4} {10} {2,9,0,15,9,12,7,11,15,14,9,12,8,13,0,2,1,8} {1,2,3 7,9,4,0,0,3,9,2,8,5,3,8,0,2,7,4,8,9,9,1,2,4,2,2,3} {1,21,29,22,3} ``` [Answer] ### Scala: ``` def toDecimal (li: List[Int], base: Int) : BigInt = li match { case Nil => BigInt (0) case x :: xs => BigInt (x % base) + (BigInt (base) * toDecimal (xs, base)) } def fromDecimal (dec: BigInt, base: Int) : List[Int] = if (dec==0L) Nil else (dec % base).toInt :: fromDecimal (dec/base, base) def x2y (value: List[Int], from: Int, to: Int) = fromDecimal (toDecimal (value.reverse, from), to).reverse ``` Testcode with tests: ``` def test (li: List[Int], from: Int, to: Int, s: String) = { val erg= "" + x2y (li, from, to) if (! erg.equals (s)) println ("2dec: " + toDecimal (li, from) + "\n\terg: " + erg + "\n\texp: " + s) } test (List (1, 2, 3, 4), 16, 16, "List(1, 2, 3, 4)") test (List (1, 0), 10, 100, "List(10)") test (List (41, 15, 156, 123, 254, 156, 141, 2, 24), 256, 16, "List(2, 9, 0, 15, 9, 12, 7, 11, 15, 14, 9, 12, 8, 13, 0, 2, 1, 8)") test (List (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), 2, 10, "List(1, 2, 3, 7, 9, 4, 0, 0, 3, 9, 2, 8, 5, 3, 8, 0, 2, 7, 4, 8, 9, 9, 1, 2, 4, 2, 2, 3)") test (List (41, 42, 43), 256, 36, "List(1, 21, 29, 22, 3)") ``` Passed all tests. [Answer] # J, 109 105 Handles thousands of digits no sweat. *No integers harmed!* ``` e=:<.@%,.|~ t=:]`}.@.(0={.)@((e{:)~h=:+//.@)^:_ s=:[t[:+/;.0]*|.@>@(4 :'x((];~[t((*/e/)~>@{.)h)^:(<:#y))1') ``` ### Examples ``` 256 16 s 41 15 156 123 254 156 141 2 24 2 9 0 15 9 12 7 11 15 14 9 12 8 13 0 2 1 8 256 36 s 41 42 43 1 21 29 22 3 16 16 s 1 2 3 4 1 2 3 4 256 46 s ?.1000$45 14 0 4 23 42 7 11 30 37 10 28 44 ... time'256 46 s ?.3000$45' NB. Timing conversion of 3000-vector. 1.96s ``` It gets shorter. [Answer] # Smalltalk, 128 ``` o:=[:n :b|n>b ifTrue:[(o value:n//b value:b),{n\\b}]ifFalse:[{n}]]. f:=[:a :f :t|o value:(a inject:0into:[:s :d|s*f+d])value:t]. ``` tests: ``` f value:#[41 15 156 123 254 156 141 2 24] value:256 value:16. -> #(2 9 0 15 9 12 7 11 15 14 9 12 8 13 0 2 1 8) f value:#[1 2 3 4] value:16 value:16. -> #(1 2 3 4) f value:#[1 0] value:10 value:100. -> #(10) f value:#[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] value:2 value:10. -> #(1 2 3 7 9 4 0 0 3 9 2 8 5 3 8 0 2 7 4 8 9 9 1 2 4 2 2 3) f value:#[41 42 43] value:256 value:36. -> #(1 21 29 22 3) ``` and for your special amusement (**challenge: figure out, what's so special about the input value**): ``` f value:#[3 193 88 29 73 27 40 245 35 194 58 189 243 91 104 156 144 128 0 0 0 0] value:256 value:1000. -> #(1 405 6 117 752 879 898 543 142 606 244 511 569 936 384 0 0 0) ``` ]
[Question] [ ## Background You have again been given the task of calculating the number of landmines in a field. However, we have now travelled into the flatlands. You must calculate the landmine score given a list/string of numbers (which will be 2D) and the landmine number. The landmine number tells you where landmines are. For each digit: 1. if the DIRECTLY ADJACENT digits above, left, right, and below add to the landmine number, add the digit in focus to the landmine score. 2. if the DIRECTLY ADJACENT digits above, left, right, and below multiply to the landmine number, add double the digit in focus to the landmine score. 3. if both 1 and 2 are satisfied, add triple the digit in focus to the landmine number. Note: The very corner and edge digits cannot have landmines because they are not fully surrounded by other numbers. ## Your Task * Sample Input: A two dimensional array of numbers, NxN, such that N is >= 3. Also, the landmine number. * Output: Return the landmine score. **Explained Examples** ``` Input => Output 111 111 111 4 => 1 ``` There is 1 landmine here. The central 1 has 1+1+1+1 = 4. ``` Input => Output 1448 4441 4114 2114 16 => 12 ``` Focusing only on central numbers, * Top right 4 has 4x4x1x1 = 16, so we add 4x2 = 8. * Bottom left 1 has 4x4x1x1 = 16, so we add 1x2 = 2. * Bottom right 1 has 4x1x1x4 = 16, so we add 1x2 = 2. 8+2+2 = 12 ``` Input => Output 12312 19173 04832 01010 00100 8 => 42 ``` There are 42 landmines here: * On 9, 2+1+4+1 = 2x1x4x1 = 8, so we add 9x3 = 27. * On 7, 1+1+3+3 = 8, so we add 7. * On 8, 1+4+3+0 = 8, so we add 8. * On central 0, 8x1x1x1 = 8, so we add 0x2 = 0 27+7+8+0 = 42 ``` Input => Output 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 0 => 0 ``` There are 36 central 0s. So, 36x0x3 = 0. **Test Cases** ``` Input ~> Output 111 111 111 4 ~> 1 1448 4441 4114 2114 16 ~> 12 12312 19173 04832 01010 00100 8 ~> 42 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 0 ~> 0 090 999 090 36 ~> 9 1301 3110 0187 3009 9 ~> 12 48484 28442 84244 28448 48424 256 ~> 68 111111 111111 111111 114111 111111 111111 4 ~> 23 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. ... **Landmine Number Series** * [Previous, LN I](https://codegolf.stackexchange.com/questions/262518/landmine-number-i) * [Next, LN III](https://codegolf.stackexchange.com/questions/262628/landmine-number-iii) * [All LN Challenges](https://docs.google.com/document/d/1XU7-136yvfoxCWwd-ZV76Jjtcxll-si7vMDhPHBKFlk/edit?usp=sharing) [Answer] # [J](https://www.jsoftware.com), 55 bytes ``` [:+/@,[({.@]*[:I.=)"#.3 3(4&{,](+/,*/)@#~1-2|#\)@,;._3] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmtx0zzaSlvfQSdao1rPIVYr2spTz1ZTSVnPWMFYw0StWidWQ1tfR0tf00G5zlDXqEY5RtNBx1ov3jgWqn25Jldqcka-gpGpmUKagpKekjZQ1kghFmSXAZeJBRByGVmYmBhxWZgYmUDYFiBxIxMuqFYTLBoNwQCDMsEUhBpijM16A0sDLktLSxANce6CBRAaAA) * Uses J's subarray verb `3 3...;._3`, which automatically extracts the 3x3 tiles * The rest is figuring out to extract the compass directions from each of those, and then do the needed arithmetic and comparisons with the landmine number [Answer] # JavaScript (ES11), 113 bytes Expects `(n)(matrix)`. ``` n=>m=>m.map((r,y)=>r.map(a=(v,x)=>t+=v*=a+(b=m[y+1]?.[x])+(c=m[y-1]?.[x])+r[++x]==n|2*(a*b*c*r[a=v,x]==n)),t=0)|t ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pVDBbtQwEFWvw09Ye1l7k1p2YrYOyNsTHLn0mOaQTZOyUuJsnWy1KwpfgMSlN0CqEPwDv0KP_QF-gXGybEEcsZMZz7znmef5-NW2F-Xdl8p82_TVsf5xZc2iwY83-ZpSF-6YWbghyA29DrcY9oG5npk8oEvTpLtAZqc83WYsoIWPjw-xS4Ngmxljb6IZzWfLWTFzaW6wiE8yFvZGsJt-bHx_9MSVV5uVK-mk6iaMuzK_eLmqy7OdLahgvG_Pereyl5Txbl2vejo5t-cWiVXrXuTFa9oRsyBvgJC67ElODOkeiRMWIuBXakPSbvoM8Zyv2_VjOfJuQbCcf-qrTbMs3eFOM5A94HyPlHPusj-JB6YrUQWpqGW0Yc8Bs0Vru7Yued1eUkTDkWK8BnJKpj-_f3j4dIt2Sp6R6cPn91O89paNM7m7P5pLKWH_E1BeowSQSmlQSklQUiqIvJHzAYwQjWJ0MpEnMQil4wiExA0CjQDtaQppYr_---ALCqyXCEiSZPDxICZBLbGQEEvfXeoTiIVIIPktVGncEGmFcrSK1HjWPh_h-elQZK7BP34_g7-c-jc5TCiKx_n9Ag) ### Commented ``` n => // n = target number m => // m[] = digit matrix m.map((r, y) => // for each row r[] at index y in m[]: r.map(a = // initialize a to something NaN'ish (v, x) => // for each value v at index x in r[]: t += // add to t: v *= // v multiplied by: // 1 if the sum of ... a + // a, the value on the left (b = m[y + 1]?.[x]) + // b, the value below (c = m[y - 1]?.[x]) + // c, the value above r[++x] // and the value on the right == n | // is equal to n 2 * ( // 2 if the product of: a * b * c * // a, b, c r[a = v, x] // and the value on the right // (copy v into a afterwards) == n // is equal to n ) // ), // end of inner map() t = 0 // start with t = 0 ) | t // end of outer map(); return t ``` [Answer] # Excel, 155 bytes ``` =SUM(TOCOL( MAP(A1#, LAMBDA(a, LET( b,OFFSET(a,{-1,0,0,1},{0,-1,1,0}), c,SUBTOTAL(2,b), d,SUBTOTAL(9,b), IF(SUM(c)=4,IF(SUM(d)=Z1,a)+IF(PRODUCT(d)=Z1,2*a)) ) ) ),2 ) ) ``` Matrix is spilled range `A1#`; landmine number in cell `Z1` (or, if necessary, some other cell which does not form part of `A1#`). [Answer] # [Python 3](https://docs.python.org/3/), 125 bytes ``` lambda n,l:sum(e*(2*(a*b*c*d==l)+(a+b+c+d==l))for x,y,z in zip(n,n[1:],n[2:])for a,b,c,d,e in zip(x[1:],z[1:],y,y[2:],y[1:])) ``` [Try it online!](https://tio.run/##pVLbjpswEH2fr7Dygk3clW/dNUj0RwgPDpAtu8SJMEghD/31dOxN1G77UqlYzPXMzPHlvM7fT17fDtXuNrrjvnPE87EMy5H2OVU5dfk@b/Ouqka2pW6737bb5LDDaSIXvvIrGTy5Dmfqua9l2aBUZZPSju95yzvePyCXBLgmufI1AlGix9jNVZvNRkoJ95@AIT@@EQkgjbFgjJFgpDSgopDPKakwqzQqWcgXDcJYrUBIXCBQCLARZhAm7t9/G7GhwH6FgKIoktaJTIFctJCgZZwu7QtoIQooHkSNxQXKGqRjjTIfto1xhfbX1OTZQtz8/Qw@KfN3MJ2Q0nhwT@E8DjPNdn7nMwbwOg1dqOq6HvxMB0bidQzxGt6fwjzhVbAmxd5j7O1Xdcbq8otsPpJvMeka8MsRe6VOn5AIfPiRCEZE89sorDwt8z9Wyj8qITm@i@7k/GtPx97TyISxEsilOtC0R2ze4ZvDeLIYkLWKU5MHxIXQTzPCqxXOUySSuXEkcx9m0rrQBzItnoSlbfsQDss4rhm7/QQ "Python 3 – Try It Online") The function takes in a 2D list of integers `(n: list[list[int]])` and the landline number `(l: int)`. Magical `zip` stuff happens which assigns `a,b,c,d` to the values adjacent to every "central" coordinate, and `e` to the value of the coordinate in focus. Explanation by gsitcia: `_ for x,y,z in zip(n,n[1:],n[2:])` is equivalent to `for i in range(1,len(n)-1): x,y,z=n[i-1],n[i],n[i+1]; _.` `_ for a,b,c,d,e in zip(x[1:],z[1:],y,y[2:],y[1:])` is equivalent to `for j in range(1, len(n[0])-1): a,b,c,d,e = n[i-1][j], n[i+1][j], n[i][j-1], n[i][j+1], n[i][j]; _` both of these work because zip will cut off at the shortest length *-1 byte thanks to spooky\_simon* *-50 bytes thanks to gsitcia* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes ``` WS⊞υιP⪫υ⸿Nθ≔⁰ηF⪫υ⸿«F⌊KV≧⁺×IKK⁺⁼ΣΣKVθ⊗⁼ΠΣKVθηι»⎚Iη ``` [Try it online!](https://tio.run/##fVDBSsQwED1vviLsaQoV2q7giidZPSh0KVY8ecl2YxNMkzbJ6EH89jrN4kVkCclk3pv3kplOCd85Yeb5U2kjOTzYEWMbvbY9ZBlvMCjAnOvshtVooh6JifDotF3g9atfZ0Ql1R6Hg/QwUX4bgu4tFDlXlL05z/9I@BdbJbjWVg84QCPl@4uze4mDsJaezngtxpPPk@5VhMZgyPmzHmSAnQgxSagw5wsD9xMKE6Alr/Zfv5xPtO8cHow8/pY33h2xi2ckKSxdrJrU@jKJb7YzUnig6wlM/1E0iXkuq01ZsfK6vNqw4nK7qVhR0mIFHQVj2/niw/wA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` WS⊞υι ``` Input the field. ``` P⪫υ⸿ ``` Output the field without moving the cursor. ``` Nθ ``` Input the target. ``` ≔⁰η ``` Start with zero score. ``` F⪫υ⸿« ``` Loop over the field. ``` F⌊KV ``` If there are digits on all four sides, then... ``` ≧⁺×IKK⁺⁼ΣΣKVθ⊗⁼ΠΣKVθη ``` ... multiply the current digit by the sum of `1` if the digital sum equals the target and `2` if the digital product of those digits equals the target. ``` ι ``` Move to the next digit. ``` »⎚Iη ``` Output the final total. Removing the `F⌊KV` test has the effect of only considering those adjacent digits that exist e.g. in the top left corner it would search for the target from the sum and products of the digits to the right and below only. [Answer] # [Python 3](https://docs.python.org/3/), 174 bytes ``` lambda a,b:sum(a[c][d]*((b==a[c-1][d]+a[c][d-1]+a[c+1][d]+a[c][d+1])+2*(b==a[c-1][d]*a[c][d-1]*a[c+1][d]*a[c][d+1])) for d in range(1,len(a)-1) for c in range(1,len(a[d])-1)) ``` [Try it online!](https://tio.run/##ZYzZCsMgEEXf/QofXSI4WmhSyJeEPIwxXcCYki7Qr7dKIG0pA8Ocew9zfd3Pc7QpBZycR4qVO9weE8Nu6DvfC8Zc22ZQUFCucYZyye8sA5dG/Ohi08Wmi4/O6XFeqKeXSBeMp5FBFcbIkCtYq@Gvyg9Ky1MCY8EQaGBvid7V1hANeYjOSxNSJ/UMbw "Python 3 – Try It Online") If I could condense the doubled calls to a[c-1][d], a[c+1][d], a[c][d-1], and a[c][d+1], I could save several bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~33~~ 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2Fø€ü3}εε˜ιθDOsPD)QOy˜4è*]˜O ``` -5 bytes thanks to *@ovs*. Inputs in the order *matrix, landmineNumber*. [Try it online](https://tio.run/##yy9OTMpM/f/fyO3wjkdNaw7vMa49t/Xc1tNzzu08t8PFvzjARTPQv/L0HJPDK7RiT8/x//8/OtpQx0jHWAdIxuoA2ZZAlrmOMZBtoGOiYwGUMQKzDXXAGMyG8AxiY7ksAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@ZYK@kkJiXoqCkc2i3DpeSf2kJUAoiE6b038jt8I5HTWsO7zGuPbf13NbTc87tPLfDxb84wEUzMtC/8vQck8MrtGJPz/H/r6QXpnNom/3/aCAw1AHCWB00OlbHJFZHASxtAoQWQAkTMMsQzAIpAiqINoKyYnUMzWDqjXSMgWJGYKMsgSxzHWMg2wBkClDGCMw21AFjMBvCMwCaYQExAiSEBKGKBkokFiQKcZYlWIElkLYEK7QESxvDfW4M8gtQxhgcKgZQn1romIPFQMZZAtVbQpSDggOMwcFoAQ5cUOCAWEYgHpI4JPihMkAjjEzhdsIhLOrw8EyIUAmK@FgA). **Explanation:** ``` 2Fø€ü3} # Create all overlapping 3x3 blocks of the first (implicit) input-matrix: 2F } # Loop 2 times: ø # Zip/transpose; swapping rows/columns # (which will use the implicit first input-matrix in the first iteration) € # Map over each row: ü3 # Create overlapping triplets εε # (Nested) map over each 3x3 block: ˜ # Flatten it to a single nonet-list ι # Uninterleave it into two parts θ # Pop and leave just the last list (with the even-indiced values) D # Duplicate this quadruplet O # Sum it together s # Swap so the quadruplet is at the top again P # Take its product D # Duplicate this product ) # Wrap all three values into a list: [sum,product,product] Q # Check for each whether it's equal to the second (implicit) input-integer O # Sum the checks together y˜ # Push the flattened 3x3 block again 4è # Pop and leave the 0-based 4th integer (the center) * # Multiply it to the earlier sum of checks ] # Close the nested map ˜ # Flatten it to a single list O # Sum this list together # (after which it is output implicitly as result) ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~148~~ \$\cdots\$ ~~118~~ 117 bytes ``` #define y(z)*a*(a[-1]z+a[1]z+a[n]z+a[-n]==l) i;j;f(*a,n,l,*s){for(*s=0,a+=j=n-2,i=j*j;i;*s+=y()+2*y(*))a+=i--%j?1:3;} ``` [Try it online!](https://tio.run/##1VRdz5sgFL7vryBdugBiZsHads7tYtmvaL0wlm46R9@IS/qR/vYOQfDjbfJulzPIQc5zvp6D5H5eZeL74/HuwI@F4OACrwhnGGY7f5levWxnZqFnX6RJUqFZEZfxEeKMCFIRLNHteKohlklAMi8pE@FTUiQlLuMixtJLLhB5FF8gRkjpC99flF@WH1l8fxSiAb@yQkAEbjOgnnaj4bIJdilIwG1JwPNxj0fwpYOHemzsItTw0NqpBXXriQ/qfCgI0xCD3ep5rTcD655pbaBVbg6G64l7ZtwHA@D/NyY1ha6mrdZv7eh2JvCVY5hZopjthqNuM6C6dTPxERkfrscb21TXcjrYDF9pJ1bTQ7B@49z9xQj/CT@JL0x8pt2s7Ekz62iCrRwVy0gjFV0s0szTVTSqDWsDaQz0/0XMf2MENYIZERqxMiIyYj0Izs8vPG/4oeeqZZLatrdfkUqHss4mPwnZgPxHVmM18/wnr43pfH/@Rvfn7Vf1ruYEDL/ZvLNWdwuAbdhCHPhZmQVxt/wEZHHlpyO0CaEP3QZ2OzHwPI22N0zPiHJlWNH6NB6qgei04pW2z6fLReUhdBjkMH2okUVpLEprUaIRrn1eagU8wvnioPhodgUWwANliuLZM9RezAea@6iCqqugelqfHBQEG32Rv5dojOHKg@v11EmfKPA/AzUv5F6ofAioCJDENVomCbfpmwRr3vyuhSJidn/8AQ "C (clang) – Try It Online") *Saved a whopping ~~12~~ ~~19~~ ~~30~~ 31 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* [Answer] # [JavaScript (Node.js)](https://nodejs.org), 120 bytes ``` x=>k=>x.map((y,i)=>y.map((z,j)=>r+=[a=0,b=1,2,-1].map(d=>{a+=c=(x[i+d%2]||0)[--d%2+j],b*=c})&&z*(a==k|2*(b==k))),r=0)&&r ``` [Try it online!](https://tio.run/##pVDtboMwDPzvp@DPqqQJaRyirVNl9iCUjfDRipYBAjTRrnt2FrV7g9ny@c73y3dyX24shrqfwrYrq@VAy0zxmeJZfbqesYusOcWXh7jKkxeDoMSRljmhNDLE9G6WFH87QQWxOalF@WTS203zJAw9FadU5msqfvhqdV0zR3S@mTXL/eacy4G0N4ZlBxkiwt8EFgCt3YK1FsEiWjAeAnz2dxOhAXzFlwi03UYGNPoG7UEHW/DkUf8kgc7UUPWNKyq2YfsyeU/FGw@YEnxzlOxDOpn7RIquHbumUk13ZHBgTo19U0/Zvs3u0fhAE6XU/AhqolhM/m0mcg6c75Zf "JavaScript (Node.js) – Try It Online") Some of ur test cases seem wrong, 2x1x4x1 = 8 = 2+1+4+1 [Answer] # Python3, 237 bytes: ``` R=range def f(n,B): t=0 for x in R(1,len(B)-1): for y in R(1,len(B[0])-1): a,b,c,d=B[x-1][y],B[x][y-1],B[x][y+1],B[x+1][y] j,k=a+b+c+d,a*b*c*d;v=B[x][y] if k==n and j==n:t+=v*3 elif k==n:t+=v*2 elif j==n:t+=v return t ``` [Try it online!](https://tio.run/##pZHBbqMwFEXX877CyiYG3Mo2Lwl05E0@YBbdMqgiAVpaxkHgRs3XZ2wgqdEsBwu/63culi/uLubtpOOk66/XZ9UX@rWCsqpJTTXbB09AjOJA6lNPvkijyTMVrK003QcPwtGRXBYk4/kNkoId2JGVap99PYg8u@TMKlvtYlbRpKKRuk/e2YcqokN0jEpWhIfwGJY/z2oyj4amJh9KaVLokrxb8WQidQ5jh6p2hlNP3nt3H5C@Mp@9JubqUprTS91UbUkHe94fM8qy8E/R0UYbRpogdwkbl7BuWlP19NdJV4wMj0PXNoauf@t1EOQAgyCKrFYrEELcX7ce5A0gJoCIAlAIBOmm0RDfDDIWEkQqdjFwTGIJXNgB3E58suJs5fPzv2LcdHPbNOWQpulYR7CdASZ2gEwQJSQocdKJ68s5w@47/Rx@UfDfpnN3vf3LtKbIvKsQQRDcidj6SPoo8UnsE@4T9Em82G7jI7lZsK3PFufbWXL9Cw) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 210 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 26.25 bytes ``` żṪ:Ẋ:ƛk□¨V+ƛ¹nÞi;₍Π∑⁰=;¹„¨VÞi*vB ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9cyIsIiIsIsW84bmqOuG6ijrGm2vilqHCqFYrxpvCuW7Dnmk74oKNzqDiiJHigbA9O8K54oCewqhWw55pKnZCIiwiIiwi4p+oIOKfqCAxIHwgMiB8IDMgfCAxIHwgMiDin6kgfCDin6ggMSB8IDkgfCAxIHwgNyB8IDMg4p+pIHwg4p+oIDAgfCA0IHwgOCB8IDMgfCAyIOKfqSB8IOKfqCAwIHwgMSB8IDAgfCAxIHwgMCDin6kgfCDin6ggMCB8IDAgfCAxIHwgMCB8IDAg4p+pIOKfqVxuOCJd) I forgot how this worked like 3 times while writing it. Chances are after I paste in the explanation, it'll be 4 times. ## Explained ``` żṪ:Ẋ:ƛk□¨V+ƛ¹nÞi;₍Π∑⁰=;¹„¨VÞi*vB­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁤⁢‏‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏‏​⁡⁠⁡‌⁤⁡​‎‏​⁢⁠⁡‌­ żṪ # ‎⁡The range [1 ... len(field) - 1] :Ẋ # ‎⁢Cartesian producted with itself. This generates a list of indices of central numbers ƛ ; # ‎⁣To each central number index: k□¨V+ # ‎⁤ Add it to ⟨ ⟨ 0 | 1 ⟩ | ⟨ 1 | 0 ⟩ | ⟨ 0 | -1 ⟩ | ⟨ -1 | 0 ⟩ ⟩ to get the numbers above, below, left and right of this number ƛ ; # ‎⁢⁡ To each adjacent number index: ¹nÞi # ‎⁢⁢ Retrieve it from the field ₍Π∑ # ‎⁢⁣ Push a list of [product(adjacents), sum(adjacents)]. Keen readers will notice that I used # ‎⁢⁣ this in the previous challenge ⁰= # ‎⁢⁤ And test whether that equals the landmine number. Also in the previous challenge. ¹„ # ‎⁣⁡Push a copy of the field and rotate the stack left so that the central indices are on the top ¨VÞi # ‎⁣⁢Retrieve the numbers that are central in the field * # ‎⁣⁣And multiply by the list of checksums. vB # ‎⁣⁤Convert each from binary. # ‎⁤⁡The s flag sums the resulting list 💎 Created with the help of Luminespire at https://vyxal.github.io/Luminespire ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 37 bytes ``` sm+*yJ@d4qQ*FK%2td*JqQsKsmsM.:Cd3.:E3 ``` [Try it online!](https://tio.run/##K6gsyfj/vzhXW6vSyyHFpDBQy81b1agkRcurMLDYuzi32FfPyjnFWM/K1fj/f0MzruhoQx0TILSI1VGINgEzDSFMQyA0ATGNoMxYAA "Pyth – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 224 bytes Port of [@Ajax1234's Python answer](https://codegolf.stackexchange.com/a/262566/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##pZJNb4JAEIbv/oo5mV1RIwt@IOVQbz301PTUeFj5sChiA9RIjL@dDrsCK5gmTclmMvPsy@w7sKnLI14cNzvfzeCVhzFcCs8PICDx8iXOhqvlc5Lw/ENGJOs1dUhwTMj5aaRDdoTVOPLjbfY5YnZeITKhDeXOipxHOiU5tTdljhmWtnvLNcy9MtekZudwbaO5mmfvHT7YDNyBZ59uWkrz0I88CAOyd5y4399hpKeBAX6U@hVGwGogFbJEW@n3oQAoRzzgtIQn23QJcrq3LAnj7Zou4T0OM3Dg0gN8TjyCVMdSqIiM@hDKRYfwe02bFqzbwhRrUb9lVkhXkexl1og1SGlvdNuj0BBCpvqyBJrjXk0n0oeQM5Wi8BZVWm9MVANmZWAchFFEFpTcV3fiacvtRPhqTrFEbamnWq3zZq0WcoJbVD/WovqqzWgSMbnxUHv3Uxq5amD@@E7Uq30Z/rxh/qcV7QmnX3insygmQTlHWl3IhuozxKyDceLU6FD8C6nZoUbZYtrBbFryWYeXPuaCXnvX4gc) ``` def f(n:Int,B:Array[Array[Int]])=(for(x<-1 to B.length-2;y<-1 to B(0).length-2;a=B(x-1)(y);b=B(x)(y-1);c=B(x)(y+1);d=B(x+1)(y);j=a+b+c+d;k=a*b*c*d;v=B(x)(y))yield if(k==n&&j==n)v*3 else if(k==n)v*2 else if(j==n)v else 0).sum ``` Ungolfed version. [Try it online!](https://tio.run/##pVLLTsMwELznK/ZU2Wmp8uojFT3QGwdOiBPikKZJSTEuSkJFhfrtZe087MQREkJyVtmZ8eza6yKOWHS9HreHJC7hIco4fFsAuySFlPAV3PNyApsV3OV5dH6uImIvL1RysJZygFOUg8gcmaXHHMgX3N6AC5@8zBhspizh@/IVEKL1nlp37uiIQwelogSDCEts0FlQ5Ew73LbiEJd0h4sVN@5zu9pzPOB5QC5CZotfjN@uw75J1kbWRtbusae2pvLMUiC4aw0cRiPhjn8UL268RrkNfitMWJFoak3jmZquT81fLBVLS/zVc33HIZMo3xfNVB/LPON7MdEnnukjZVC4mEoVqaI7AbHoBH7PqbLwTItArmW7K2ggV4cqr6CFPAVp9r5pj0JfCj29r1BCC@Ra1Kn6kHJPR1FYRx1tCUdvIGgamKYZY2RJSTfriGe9bh3Zl6oSyjzUq4a9evOeRXWCOuqXtWxuVR2tgryKGNR2hqLkegOL4TfRrv5j@DMR/MeKWrLTD3zTJeMkFecomgepUHeOsGfAeOLCN1CcQhEYqC8sZgbszQQ@N3DRx0KiF@tiXa8/) ``` object Main { def f(n: Int, B: Array[Array[Int]]): Int = { var t = 0 for (x <- 1 until B.length - 1) { for (y <- 1 until B(0).length - 1) { val a = B(x - 1)(y) val b = B(x)(y - 1) val c = B(x)(y + 1) val d = B(x + 1)(y) val j = a + b + c + d val k = a * b * c * d val v = B(x)(y) if (k == n && j == n) t += v * 3 else if (k == n) t += v * 2 else if (j == n) t += v } } t } def main(args: Array[String]): Unit = { val s1 = Array(Array(1, 1, 1), Array(1, 1, 1), Array(1, 1, 1)) val s2 = Array(Array(1, 4, 4, 8), Array(4, 4, 4, 1), Array(4, 1, 1, 4), Array(2, 1, 1, 4)) val s3 = Array(Array(1, 2, 3, 1, 2), Array(1, 9, 1, 7, 3), Array(0, 4, 8, 3, 2), Array(0, 1, 0, 1, 0), Array(0, 0, 1, 0, 0)) val s4 = Array.fill(8)(Array.fill(8)(0)) val s5 = Array(Array(0, 9, 0), Array(9, 9, 9), Array(0, 9, 0)) val s6 = Array(Array(4, 8, 4, 8, 4), Array(2, 8, 4, 4, 2), Array(8, 4, 2, 4, 4), Array(2, 8, 4, 4, 8), Array(4, 8, 4, 2, 4)) val s7 = Array(Array(1, 1, 1, 1, 1, 1), Array(1, 1, 1, 1, 1, 1), Array(1, 1, 1, 1, 1, 1), Array(1, 1, 4, 1, 1, 1), Array(1, 1, 1, 1, 1, 1), Array(1, 1, 1, 1, 1, 1)) println(f(4, s1)) println(f(16, s2)) println(f(8, s3)) println(f(0, s4)) println(f(36, s5)) println(f(256, s6)) println(f(4, s7)) } } ``` ]
[Question] [ You're a plumber working on a house, and there's some pipes that must be connected at weird angles. You have 8°, 11.25°, 22.5°, 45°, and 90° fittings at your disposal, and you want to use as few as possible to match the angle as closely as possible. # Goal * Match the desired angle as closely as possible, with as few fittings as possible. It can be over or under the desired angle. * Accuracy is more important than the number of fittings * In the case of two different sets of fittings with the same resulting angle, whichever has the fewest number of fittings should be selected. * If the two sets use different fittings, match the same angle, and have the same number of fittings, either may be chosen. * Your fittings cannot add up to greater than 360 degrees (i.e. no looping all the way around) # Input Your input is a random integer between (non-inclusive) 0° and 180°, which represents the desired angle. # Output Your output should be an array where [0]-># of 8° fittings, [1]-># of 11.25° fittings, etc. If your language does not support arrays, you may output a comma separated list, where the first value represents the number of 8° fittings, and so on and so forth. **Test Cases** ``` 90° ->[0,0,0,0,1] 24°-> [3,0,0,0,0] ([0,0,1,0,0] uses less fittings, but is less accurate and therefore incorrect) 140°->[2,1,1,0,1] 140°->"2,1,1,0,1" acceptable if language does not support arrays ``` # Scoring Lowest byte count for each language wins a high five from me if we ever bump into each other (and the challenge). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` Ḷṗ5SÞðḋ90H3С;8¤ạðÞḢṚ ``` [Try it online!](https://tio.run/##ATQAy/9qZWxsef//4bi24bmXNVPDnsOw4biLOTBIM8OQwqE7OMKk4bqhw7DDnuG4ouG5mv///zEw "Jelly – Try It Online") **Note** - after Nick Kennedy's golfs, this answer is actually identical to [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/229508/68942), which they arrived at independently. Make sure to upvote them. -9 bytes thanks to Nick Kennedy by rewriting the conversion from counts to total angle ``` ḶṗSÞ5ðḋ90H3С;8¤ạðÞḢṚ Main Link Ḷ Lowered range; [0, 1, ..., N-1] ṗ5 Cartesian product; size 5 lists of the above elements SÞ Sort by sum ð ðÞ Sort by: ạ - absolute difference of the following and the input: ḋ - dot product with 90H3С;8¤ - [90, 45, 22.5, 11.25, 8] via the following 90 - 90 3С - repeat 3 times and collect results: H - halve ;8 - append 8 Ḣ take the first one (since it'll already be sorted by count and it's stable) Ṛ reverse it ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḷṗ5SÞḋ90H3С;8¤ạɗÞ⁸ḢṚ ``` A monadic Link that accepts an integer in \$[0,180]\$ and yields a list of the five pipe counts in the prescribed order. **[Try it online!](https://tio.run/##ATQAy/9qZWxsef//4bi24bmXNVPDnuG4izkwSDPDkMKhOzjCpOG6ocmXw57igbjhuKLhuZr///81 "Jelly – Try It Online")** although it'll time out for inputs above \$15\$ :( ### How? Builds all selections of pipes consisting of less than `input-angle` of each pipe, sorts these by their number of pipes, then (stable) sorts by the difference between the angle-sum and `input-angle` and yields the first. ``` Ḷṗ5SÞḋ90H3С;8¤ạɗÞ⁸ḢṚ - Link: angle, A Ḷṗ5 - (A) Cartesian product 5 -> all selections of the five pipes with up to A-1 of each pipe SÞ - sort by sum (number of pipes) Þ - sort (the elements X of that) by: ɗ ⁸ - last three links as a dyad - f(X, A) ¤ - nilad followed by links as a nilad: 90 - 90 3С - collect & repeat three times: H - halve -> [90, 45, 22.5, 11.25] ;8 - concatenate 8 -> [90, 45, 22.5, 11.25, 8] ḋ - (X) dot-product (that) ạ - (that) absolute-difference (A) Ḣ - head Ṛ - reverse (to the prescribed order of pipe counts) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` ṗⱮẎSạ¥ÞḢċⱮ⁸ 90H3С;8Ṛç ``` [Try it online!](https://tio.run/##ATcAyP9qZWxsef//4bmX4rGu4bqOU@G6ocKlw57huKLEi@KxruKBuAo5MEgzw5DCoTs44bmaw6f///84 "Jelly – Try It Online") A pair of links which takes a single argument, the number of degrees to match, and returns a list of 5 integers. Hopelessly slow for increasing values, but should theoretically work for all of the required range. [This is a much more efficient implementation](https://tio.run/##y0rNyan8///o5CPdjzauMzJ6uKsv@OGuhYeWHp73cMcisOCjxh1clgYexocnHFpobfFw56zDy////29obgkA) but is three bytes longer. [Answer] # [R](https://www.r-project.org/), ~~95~~ ~~88~~ ~~87~~ 86 bytes *Edit: -1 byte thanks to pajonk* ``` function(a,b=expand.grid(rep(list(23:0),5)))b[order((c(8,90/2^(3:0))%*%t(b)-a)^2)[1],] ``` [Try it online!](https://tio.run/##bY3RCoIwGEbvewohhP@PVds0bIFPIgrqpgxkylzQ2y@nYQRx7r7D4bO@085p08@5756mdXo0UJMmV6@pNvLSWy3BqgkGPTvgyYMiuSFiU4xWKgvQwp0IeuUVBIfxKXbQ4LnGimPBSlLuByAoRseIkg122AVPg0g@gn4FS9eEE7bwk2RhZ3@KTKzFFiz4Nw "R – Try It Online") **Ungolfed code** ``` fittings= function(a){ # a=desired angle b=expand.grid(rep(list(23:0),5)) # b=all combinations of 5 elements of 23..0 (note: largest-to-smallest - see below) # (23 is number of smallest (8-degree) fittings needed to get over 180 degrees) c=colSums(t(b)*c(8,2^(-2:1)*45)) # c=the total angle made by each combination of fittings d=which.min((d-a)^2) # d=the first combination that minimized the absolute difference to angle a # (we take the square to save a byte getting the absolute difference, # and we automatically get the combination with the smallest numbrer of fittings # since we constructed the combinations largest-to-smallest) return(b[d,]) # finally, return that element of b ``` [Answer] # [Julia 0.7](http://julialang.org/), 93 bytes ``` !x=minimum(i->((4x-[32,45,90,180,360]⋅i)^2,sum(i),i),Iterators.product(fill(0:22,5)...))[3] ``` [Try it online!](https://tio.run/##bY5BioNAEEX3dYqKq@6hYtq2M2pA93MGcSBMDNSgbWhL8AJZ5TI5Q44yFzEm64G/ePDf4v1OHR@zZdnMZc@e@6lXvK2UcvO2Ti25PRWGktxQ@mmav9uV9bel8WVpWvclbTjKEMb4EobT9CPqzF2nzMFa2us4jrWu02aRdpQRS6zBOigMFDkkzkD@YS0kWQYNnIeAguzxrQKXG4FLYC@dV0IYYVlhRMgvVCv8H7dz6/@460hD60/LEw "Julia 0.7 – Try It Online") [Answer] # JavaScript (ES6), 129 bytes ``` f=(n,a=[0,0,0,0,0],c=e=C=1/0)=>n<(n*n<e|n*n==e&c<C&&[e=n*n,C=c,o=a])?o:a.map((_,i,[...a])=>f(n-(i?90/(16>>i):8),a,-~c,a[i]++))&&o ``` [Try it online!](https://tio.run/##ZcpBCsIwFATQvQcJP/Y3TUXElv500WOEIiGmEqlJseJKvHrMwo3IwMA85mqeZrV3vzzKEM8upYkgoCEt8ZsRLTkaqK4kJxU6CNvQuVduIsdsNzCmHeWJA1mMZEbex9aIm1kATuhRCyEykpoglOD7RlZQH5TyvD1yNFi@LRrtx6LgnLGYbAxrnJ2Y4wUmaCTnm1/a7f@o3udb@gA "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input a = [0, 0, 0, 0, 0], // a[] = pipe counters c = // c = current number of pipes e = // e = best (smallest) squared error C = 1 / 0 // C = number of pipes for the best solution ) => // n < ( // n * n < e | // if the current error is less than the best error n * n == e & c < C && // or they're equal but we're using less pipes: [ e = n * n, // update the best error C = c, // update the best count o = a // update the output ] // if e, C and o have been updated, we compare n with // an array, which is always falsy ) ? // otherwise, we test whether n is negative: o // in which case we return o[] : // else: a.map( // (_, i, [...a]) => // for each value at position i in a[], using a copy // of a[]: f( // do a recursive call: n - ( // subtract from n: i ? // if i is not equal to 0: 90 / (16 >> i) // 11.25, 22.5, 45 or 90 : // else: 8 // 8 ), // a, // pass the copy of a[] -~c, // increment c a[i]++ // increment a[i] ) // end of recursive call ) && o // end of map(); return o[] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes ``` ≔↔⁻NEφ⁺×¹¹·²⁵﹪ι¹⁶×⁸÷ι¹⁶θ≔E⌕Aθ⌊θ…⮌⊞O↨⁺¹⁶ι²÷ι¹⁶¦⁵θI⊟Φθ⁼Σι⌊EθΣλ ``` [Try it online!](https://tio.run/##bY/LasMwEEX3/QotR6AUKzShkJXjtJBFWpP2BxRbxANjydbD0K9XJersOss5o3uuukG5zipKqfYe7wbqm7cUg4YLmujhbKYYPuJ40w64YBc1gayqSrCWMv3GUXuQ8nm7y8z2kSygYHLP8@0ffBXsbMIJF@z1g5URbOaHp1VaYt/R9DURzDkJDY5xhLmcNT8d6WawE1z1op3X0EY/fE7aqWAdHFXZlDJyLxjmB1v@n1Kw3epsHZoAjfIBWlu8FPLnsvZtjoo8fGVzyXm0KOUyLWvi6xxSki9V2iz0Cw "Charcoal – Try It Online") Link is to verbose version of code. Outputs using Charcoal's default array format i.e. each element on its own line. Explanation: ``` ≔↔⁻NEφ⁺×¹¹·²⁵﹪ι¹⁶×⁸÷ι¹⁶θ ``` Calculate the possible angles using sets of up to `999` 8° fittings and optionally one each of each of the other fittings, and see how closely they compare to the input. ``` ≔E⌕Aθ⌊θ…⮌⊞O↨⁺¹⁶ι²÷ι¹⁶¦⁵θ ``` Find the indices of the most accurate sets and calculate the fittings corresponding to each of those indices. ``` I⊟Φθ⁼Σι⌊EθΣλ ``` Output the last set with the fewest fittings. ]
[Question] [ Related: [Elias omega coding: encoding](https://codegolf.stackexchange.com/q/219109/78410) ## Background [**Elias omega coding**](https://en.wikipedia.org/wiki/Elias_omega_coding) is a universal code which can encode positive integers of any size into a stream of bits. Given a stream of bits \$S\$, the decoding algorithm is as follows: 1. If \$S\$ is empty, stop. Otherwise, let \$N=1\$. 2. Read the next bit \$b\$ of \$S\$. 3. If \$b=0\$, output \$N\$ and return to step 1. 4. Otherwise, \$b=1\$. Read \$N\$ more bits from \$S\$, append to \$b\$, and convert it from binary to integer. This is the new value of \$N\$. Go back to step 2. In Python-like pseudocode: ``` s = input() while s.has_next(): n = 1 while (b = s.next()) == 1: loop n times: b = b * 2 + s.next() n = b output(n) ``` ## Illustration If the given bit stream is `101001010100`: 1. Initially \$N = 1\$. 2. Since the first bit is 1, we read 1 more bit (2 bits in total) to get the new value of \$N = 10\_2 = 2\$. Now the stream is `1001010100`. 3. Proceed as the same. Read a bit (1) and \$N = 2\$ more bits to get \$N = 100\_2 = 4\$. Stream: `1010100` 4. Read a bit (1) and \$N = 4\$ more bits to get \$N = 10101\_2 = 21\$. Stream: `00` 5. Read a bit (0). Since it is 0, output the current \$N = 21\$. The stream has more bits to be consumed, so we reset to \$N=1\$ and continue. Stream: `0` 6. Read a bit (0). Output the current \$N = 1\$. The stream is empty, and decoding is complete. The output for the input stream `101001010100` is `[21, 1]`. ## Task Given a stream of bits which consists of zero or more Elias omega coded integers, decode into the original list of integers. You can assume the input is valid (the input stream won't be exhausted in the middle of decoding a number). Shortest code in bytes wins. ## Test cases ``` Input => Output (empty) => [] 0 => [1] 00 => [1,1] 00100 => [1,1,2] 101001010100 => [21,1] 1110000111100001110000 => [8,12,1,8] 1111000111000101011001011110011010100001010 => [12,345,6789] ``` [Answer] # [convey](http://xn--wxa.land/convey/), 66 bytes ``` 1<<<<,<< />>>v$1^ ,<"<##<^ :`#?@#^^ {1$v>"}%2 ~,>/+?< 3 0$,>*2 ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiMTw8PDwsPDxcbi8+Pj52JDFeXG4sPFwiPCMjPF5cbjpgIz9AI15eXG57MSR2PlwifSUyXG4gIH4sPi8rPzxcbiAgMyAwJCw+KjIiLCJ2IjoxLCJpIjoiMSAxIDEgMCAwIDAgMCAxIDEgMSAxIDAgMCAwIDAgMSAxIDEgMCAwIDAgMCJ9) Explanation will follow after I tried some other orientations … [![one iteration](https://i.stack.imgur.com/hUIfV.gif)](https://i.stack.imgur.com/hUIfV.gif) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` ≔⪪⮌S¹θ⊞υ¹Wθ⊞υ∨⁼0⊟θ⍘⁺1⭆⊟υ⊟θ²I∧⊟υυ ``` [Try it online!](https://tio.run/##PY3PDoMgDMbvPgXxVBKXwK6e3LLDDsvMfALiiJIQ5K97fFacs4SWfr@vdJyFHxehc@5CUJOBwWoV4SVX6YOEu7EpDtErMwGlDeF4HW2rPoUZUunb6jMrLQk4Sv7q08PNJaED1KxuSL9YpDh5EUHun/U6IeVIf8JDWCi@RA8/vs6YcRkaIlxFiNCZ92FLBebMMRhjey6Hb3UT@CawneTTqr8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⪪⮌S¹θ ``` Input the bits and split them into single characters. ``` ⊞υ¹ ``` Start with `N=1`. ``` Wθ ``` Repeat until the bits are exhausted. ``` ⊞υ∨⁼0⊟θ⍘⁺1⭆⊟υ⊟θ² ``` If the next bit is a `0` then push a `1` otherwise pop the current value to see how many more bits to extract and convert to base 2 and push that instead. ``` I∧⊟υυ ``` Print all of the numbers except the last one (which should be a `1` we pushed when we hit the last `0`). [Answer] # [R](https://www.r-project.org/), ~~108~~ ~~98~~ 95 bytes ``` function(x)while(length(x)){n=1 while({b=x[0:n+1];x=x[0:(-n*b)-1];b})n=sum(b*2^(n:0)) print(n)} ``` [Try it online!](https://tio.run/##hU/bCoJAEH33K0RfZmwF125WbD9SBmmWgk1hRkL07balbUaWAwt7Zs5lJis3UXjYRKLcninMkwNBgZc4SSNII9rlsYR4JcG1qnkNRLFwptTj/qx4fsEmK0Bb4uCGJE7nPQSWuwKaOojaMUsoB8JbnQMhIOqmLub6wtfCdQ6G@aglGagpilTqz6qInP2hsi9yB13OX6K3wv0t4S8J443nqDPc/4mPaSWvLNpwjZSlx7gr216XK29xeS/ZXJo38McZTY3Kl@n9wZCNxt7EL@8 "R – Try It Online") This could still be shortened by 3 more bytes ([like this](https://tio.run/##hU/pCoJAEP6/TyFJsFsrOHbZsb2IGaRZCTKGGAnis9uaR0amAwv7zXzHTJSfPTc8eyK/PNCN/RBpwp43P/Bo4OE1vknIUhRAyqaz0xJL3@AUbJYmovhrqIG9ReGMJ2PjSHGjs4wUI9km98jHmCLLqhzqUsYUVRF7xbKJe4rpSC3qgCNGGoouOe8qicB7qPyHPECX81r0URj/JVBLOLSe3pxh9CcW01JeWnThCjWWJgdDts0hV@hw@SzZXhpa@OuMtqbJl@mz@YIvV@bazl8)) by modifying `sum(b*2^(n:0))` to instead use the inner product operator `b%*%2^(n:0)`, but this gives rather unsatisfying output that mixes 1-element vectors with 1x1 matrices... [Answer] # JavaScript (ES6), 57 bytes *4 bytes saved by @tsh* Expects a list of `0`'s and `1`'s. ``` a=>a.map(b=>r=a--?r*2+b:(a=b?r:!o.push(r),1),r=1,o=[])&&o ``` [Try it online!](https://tio.run/##ldHBjoIwEAbgO09ROZjiDtXpurvopnjy6guQHgqC7kYtaXVfH2kBPZks08Mkbb6ZP@mv@lO2MD/1Nb7ofdlUolEiVeysapqL1AgVxxsz42/5miqRb8x6oll9s0dqIsAIjEDQIpPRdKqb7ywgJAyBjKj5nGTSscUo5xh2bhT0DgaJI3AvgXuLzqI//xjhLB/WIramxc/u2qshjiaAvN2cDBwfzCfokvgL7CN1L2GfmsP78gM@v5KVDGTAKm22qjhSS0RKCn2x@lSykz7QimaMMSv97@9u57w0UVvNHQ "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 61 bytes Expects a list of `0`'s and `1`'s. ``` a=>a.map(b=>r=n--?r|b<<n:1<<(n=b?r:!o.push(r)),r=1,n=o=[])&&o ``` [Try it online!](https://tio.run/##ldJBb4MgFAfwu5@CeWggQbrnus22PnvadV/AcECr65YWDKw77bs7Qd1OSyocXgL5vfdP4EN9KVfb9@4z0ebY9C32CgslLqqjFRYWdZIc7HeV53oHeU41Vge7uzOiu7oTtYxxi8A1GiwlW61Mvy8jQuKYkwVrvSal9Ox@kfMMRrcIBsdnCQvwJHkaLHgLYd/Qwtt0HgswmAH/VV/@a@JpxiEdJmczh18WEoxJwgFMkcabeEqd8ofNI396zrYykpFojX1R9Yk6ggWpjXbm3IizeaMtLYUQToYf8Hq9VM3wyIz1Pw "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = array of bits a.map(b => // for each bit b in a[]: r = // update r: n-- ? // if n is not equal to 0 (decrement it afterwards): r | b << n // set the n-th bit of r to b : // else: 1 << ( // this expression evaluates to either 1 << r or 1 n = // update n: b ? // if b is set: r // set n to r and set r to 1 << r : // else: !o.push(r) // push r into o[], set n to 0 and set r to 1 ), // // start with: r = 1, // r = 1, n = // n zero'ish o = [] // o[] = empty array ) // end of map() && o // return o[] ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` àkÑ╣±╫¬ò^Ü▌}├n╒/ñ ``` [Run and debug it](https://staxlang.xyz/#p=856ba5b9f1d7aa955e9add7dc36ed52fa4&i=%5B%5D%0A%5B0%5D%0A%5B0,0%5D%0A%5B0,0,1,0,0%5D%0A%5B1,0,1,0,0,1,0,1,0,1,0,0%5D%0A%5B1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,0,0,0,0%5D%0A%5B1,1,1,1,0,0,0,1,1,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,1,1,1,0,0,1,1,0,1,0,1,0,0,0,0,1,0,1,0%5D&m=2) Input as an array of bits. An almost direct translation of the reference implementation. ## Explanation ``` W|cO{B|csa%aa+:bsWsP W|c while S is truthy: O push a 1 under it (N) { W loop forever stack: [N,S] B pop first bit from S and push it stack: [N,S,b] |c break if it's falsy s swap a% split the list at index N aa+ prepend b to the first part :b convert from binary s swap for the next iteration sP print N after the loop ends ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 78 bytes ``` for($s=$args;""+$s[+$x]){for($n=1;$b=$s[$x++]){1..$n|%{$n=$b+=$b+$s[$x++]}}$n} ``` [Try it online!](https://tio.run/##jVLbaoQwEH33K0SmRTGVxt4sEhCWvral27dlWVYbe8FVa5QKNt9uE6O7FtbWQDBzZs45MzJ59kUL9kaTpIWYNG2cFSYwAtvilfmGYQNb2VCvraZLpAT7EBIBQm3bAsWOA@n3SSMyENryDjnOIeUt16CkrFxsGWU60QNT08UJmu4jz3uaV6V8yOS5tcdpndOopC8djhXO0SQRTVLRHDLC6E8J5P4nggcRhEd3StKd0Za0VYpK9VjcRxMuHsKuKPLmOeEjyodZxrPhUfxr2jFn6me66OLyCl3feLd9W5qlwbPYEUYC0xqti9wqGdxXu5AWBHPVPXStIxhUCWycHto4A6gqC8qqpBS25inEetBVKVNlaJPV43JRsTLbPYQfgrgOmmUVRZQxYvRs44x@Gnszw3/q0EPavxv6GFVxjfcztT8 "PowerShell – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 82 bytes ``` ^ _¶ {`¶0(.*)$ ¶_¶$1 (_)+¶(1(?<-1>.)+)(.*)$ $2¶$3 1(?=.*¶) 0_ }+`_0 0__ %M`_ 1¶0$ ``` [Try it online!](https://tio.run/##RUw7DkIxDNt9jj4peRVVAyufkeldgZSBgYUBsSGu1QP0YiV9rfTkyI5tJe/H5/m614muqd6gJeObSo4UZnYo2QInIGVfMgldjjs5B/bce7e3@gDLT2EumREVP5802qKYlqQQe@ZQKyxrI8bSWFaYEWOzmzbB8IMb@s0ayDjuzR8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^ _¶ ``` Set `N=1` (in unary). ``` {` }` ``` Repeat until the bits are exhausted. ``` ¶0(.*)$ ¶_¶$1 ``` If the next bit is a `0` then start a new output value of `1`. ``` (_)+¶(1(?<-1>.)+)(.*)$ $2¶$3 ``` But if the next bit is a `1` then extract the next `N` bits. ``` 1(?=.*¶) 0_ _0 0__ ``` Convert them from binary to unary. (There are 0s left over, but we don't care about them.) ``` %M`_ ``` Convert all of the output values from unary to decimal. ``` 1¶0$ ``` Remove the last two values; the `1` is from the `1` that begins the new output value, while the `0` is from the (now empty) input. (This has to be done here so that the case of an empty input works.) [Answer] # [Racket](https://racket-lang.org/), 146 bytes ``` (define(f s[n 1][a'()])(if(null? s)(reverse a)(if(=(car s)0)(f(cdr s)1(cons n a))(f(drop s(+ n 1))(foldl(λ(a b)(+(* 2 b)a))0(take s(+ n 1)))a)))) ``` [Try it online!](https://tio.run/##bZFNCsIwEIX3nuKBC9/YTeNePEhxEZtUiiGVRAXP5h28kib@0GobCOR9fJMJmaDrgz095k77PcI70Nim9ZYNYuWhtpVeULbCtqE/O7dBFAZ7sSFa6Bdes9Yh4VLYsDb5qFh3Ps58MjI0oTsiskC6MIPOGcf7jRo7YcElVumQ1JInfbC9mZnIIxUEsIpYkDJDv1j@RYwBFEZYfTHUYI8k9ZHe4lT@pKlCNSH23Ybd1SD/vGdYI2kGqQtNG49OX51HnlD@nSc "Racket – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) (`-l061n`), 49 bytes ``` 1while s/^0//?$\=say$\:s/^1.{$\}//?$\=oct"0b$&":0 ``` [Try it online!](https://tio.run/##K0gtyjH9/9@wPCMzJ1WhWD/OQF/fXiXGtjixUiXGCsg31KtWiamFCOYnlygZJKmoKVkZ/LcGqlDSBQGl/1wGXAYgZAgkDUGkIRgCOYZAEshF0CCKC8qHkiAI0QMWMIRqhsj8yy8oyczPK/6v62uqZ2D4XzfHwMwwDwA "Perl 5 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~75~~ ~~73~~ 70 bytes Finite-state machine, where `$b` is a current state {0, 1, other}. Inspired by [Zaelin Goodman](https://codegolf.stackexchange.com/a/219600/80745) ``` $args|%{if(!($b=2*$b+"$_")){$n+1;$n=1}if($b-1-and!$n--){$n=$b-1;$b=0}} ``` [Try it online!](https://tio.run/##RZDtaoMwFIb/5ypSOZ26RuhxXw4RHLuAjflzjKI2bh1WO6NszHrt7miaNYGE87wfhBzqb9moD1mWIxQ84v0IafOujst@VzgLB7LIv4RsZcHGct0eqhWGUEU4kAqZh15abRdQed6kRRMJKbIehnFgLHaYcGzbnc61Lfi8UI9mRmEAakZA@DPCCeG8tds3ZkRCpJ3v6SJPINCnfGBc@K/OPbpvBngq1op@DGWvrm/E7V1w7zKXH/mS92wSQLWNTPeCg/w5yLyVW/op2GitkaorWwIX9IGxds7K63Py2Km23j9lnxR6i3uedHkulSKzdcpZ3JNfNJliK@QvpvDsGdhAzyla7j10bZ3sfuX4Bw "PowerShell – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 62 bytes ``` Last@Reap@Fold[If[--n<1,n=1+If[#2<1,0Sow@#,#];1,##+#]&,n=1,#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yexuMQhKDWxwMEtPycl2jMtWlc3z8ZQJ8/WUBvIUTYCsg2C88sdlHWUY60NdZSVtZVj1UDSQL7a/4CizLySaGVduzQHILcuODkxr66aq7pWh6vaAEzowCgdoDkQjiGMo2OIhKFShlApiDQ2PpSHUG6IRRphMrJNhkh8FLuR9dRy1f4HAA "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ Construct a program or function that takes input in form of ``` <width>, <height>, <color1>, <color2> ``` and generates an output such that first row alternates between pixels of color `<color1>` and `<color2>` with a period of `<height>`. For each row that follows, the period shall be `<height> - <row number>`. Note that `<color1>` always begins the row. ### Sample Output Input `120, 6, #000000, #FFFF00`: [![Sample Output](https://i.stack.imgur.com/8zU5h.png)](https://i.stack.imgur.com/8zU5h.png) Input `80, 50, #000000, #FFFF00`: [![Sample Output 2](https://i.stack.imgur.com/yQ9Zj.png)](https://i.stack.imgur.com/yQ9Zj.png) (Sample output has been scaled for clarity) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid entry in bytes wins. [Answer] ## JavaScript (ES6), 177 bytes ``` g= (w,h,f,b)=>`<svg${s=` width=${w} height=`+h}><rect${s} fill=${b} />`+[...Array(h)].map((_,i)=>`<line stroke=${f} stroke-dasharray=${h-i} x1=0 y1=${i} x2=${w} y2=${i} />`).join`` ``` ``` Width: <input id=w value=80 type=number min=1><br>Height: <input id=h value=50 type=number min=1><br>Foreground: <input id=f value=#000000><br>Background: <input id=b value=#FFFF00><br><input type=button value=Go! onclick=o.innerHTML=g(+w.value,+h.value,f.value,b.value)><div id=o> ``` Outputs an HTML5-compatibile SVG image. [Answer] # Tcl/Tk, 143 # ~~147~~ ~~150~~ ~~151~~ ``` proc P {w h b c} {set p [image c photo -w $w -h $h] time {incr y set x 0 time {$p p -t $x $y [expr {[incr x]/($h-$y+1)%2?$c:$b}]} $w} $h set p} ``` Returns the image which can be tested, by putting it on a `canvas` widget, writing on a file, may be on the clipboard, etc. # Code for testing ``` set w 960 set h 540 pack [canvas .c -w $w -he $h -highlightt 0] .c cr image 0 0 -image [P $w $h #00ffff #ffbf32] -anchor nw ``` [![enter image description here](https://i.stack.imgur.com/fJMvn.png)](https://i.stack.imgur.com/fJMvn.png) [Answer] # Excel VBA, ~~129~~ 122 Bytes Anonymous VBE immediate window function that takes input from range `[A1:D1]` and outputs to the range `[A2].Resize([B1],[A1])` ``` Cells.RowHeight=48:For Each r in[Offset(A2,,,B1,A1)]:r.Interior.Color=IIf((r.Column-1)\([B1]-R.Row+2)Mod 2,[D1],[C1]):Next ``` ## Far More Interesting Version, 160 bytes Presented w/ newlines in place of `:` characters for readability In this version the snippet `[Let(r,Offset(A1,,,B1,A1),If(IsOdd((Column(r)-1)/(B1-Row(r)+2)),C1,D1))]` alone is able to calculate the array of values, and all other code is used to output this array as colors to the range `[Offset(A1,,,B1,A1)]`. ``` Cells.RowHeight=48 [Offset(A2,,,B1,A1)]=[Let(r,Offset(A2,,,B1,A1),If(IsOdd((Column(r)-1)/(B1-Row(r)+2)),C1,D1))] For Each r In Cells r.Interior.Color=r r=" Next ``` Perhaps this approach my prove fruitful for further improvement? ## Output Output for input `160, 90, 0xBDD7EE, 0xDDEBF7`: [![Output](https://i.stack.imgur.com/5rGSP.png)](https://i.stack.imgur.com/5rGSP.png) [Answer] # Mathematica, 52 bytes ``` Image@Table[If[Mod[j,2i]>i,#4,#3],{i,-#2,-1},{j,#}]& ``` Sample input: ``` Image@Table[If[Mod[j,2i]>i,#4,#3],{i,-#2,-1},{j,#}]&[120,6,Black,Yellow] ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~155~~ 143 bytes Prints a Portable PixMap (.ppm) to stdout. ``` x,y,z;f(w,h,r,g,b,R,G,B){for(y=~0,printf("P3 %d %d 255",w,h);y++<~-h;)for(x=~0;x++<~-w;)z=(x/(h-y)%2),printf("\n%d %d %d ",z?R:r,z?G:g,z?B:b);} ``` [Try it online!](https://tio.run/##Tc5BC4IwFAfwc30KEYKtnjgnUrgi6NI1OndJbZtQGkNwGvXVbXNQwuMdfvz/b8sDkefDoKGDnnHUggQFAjI4wxEO@MVrhbrdh8BTlVXDkX@KvUVhhyaJDyaPWbdabT@BZNiGtQkzPUrLcL9DOkQy6PCC4t@NS@VOmPGh359TZfYxFWYf0gyz9/C4lhUyr6P5LFy2ZdFIz1uGHtEJAUvyVgrZOIqpIYt5fa9VpEa8FvAnMRIhE8pGKvi0Sl2VR/8cddX1bUKuGm3m9qNf "C (gcc) – Try It Online") ### Output * Input: `80, 50, #ad00df, #f17e18` [![enter image description here](https://i.stack.imgur.com/6pV8O.png)](https://i.stack.imgur.com/6pV8O.png) *(Image converted and resized.)* [Answer] # [MATL](https://github.com/lmendo/MATL), ~~34~~ ~~32~~ 29 bytes -3 bytes thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) ``` XJx:P"1Hh@Y"1Jyn/XkX"J:)]viYG ``` Try it at [MATL Online](https://matl.io/?code=XJx%3AP%221Hh%40Y%221Jyn%2FXkX%22J%3A%29%5DviYG&inputs=80%0A50%0A%5B0%2C+0%2C+0%3B+255%2C+255%2C+0%5D&version=20.4.1) [Answer] # Java 8, 321 + 42 = 363 bytes ``` import java.awt.*;import java.awt.image.*; (w,h,a,b)->{BufferedImage i=new BufferedImage(w,h,1);Graphics2D g=(Graphics2D)i.getGraphics();g.setColor(new Color(a));g.fillRect(0,0,w,h);g.setColor(new Color(b));for(int j=h;j>0;g.drawLine(0,h-j,w,h-j--))g.setStroke(new BasicStroke(1,0,0,1,new float[]{j},j));javax.imageio.ImageIO.write(i,"png",new java.io.File("a"));} ``` Outputs to a PNG file named `a` (no extension). Surrounding code used to run the lambda: [Try it online!](https://tio.run/##fVJNS8QwED1vf8Wwp1TS0hUEoawHPyqCIuhRPMx203ZitylptAtLf/uaaSuigofw5uO9N@mkGj8wMq1q9PbteKRda6wD7Ysx9i4@SYPfJdphqbjRvm9qyiGvsevgAamBQ7CgxilbYK4ggwN8GNoC5rlqnfAd6CUwVBPgBJsQXGVN38HNnplkmhSGIFjMAzqHzsPotfNjxLOz1JQvr2jL7q@Wb7HIoIC1R9HLSqLchNEFlxeX70WhrNre8UcArRvVw4/aKFiFKZNvLbYV5d3pNZRr8Z2FFJfKfeViIpdxp9yVqY0VbDpFGH41C6rrJ5U7kchE@hn/iDazqPAx70evq1RfJGkZby3299Qob1JFmm0iHUVhyOzJy6/GvKnR7BI7yud8JXnsSnK9qA26l9eDHqSeJ/Hb7qeHJROPe7h7jHtLTgmSy7Ypl6N0/Ac8I6NaiSUuJ/ngD2MRzy99nkg48yfZZ1mSZNkUccz8IRiOx08) ## Ungolfed ``` (w,h,a,b)->{ BufferedImage i=new BufferedImage(w,h,1); Graphics2D g=(Graphics2D)i.getGraphics(); g.setColor(new Color(a)); g.fillRect(0,0,w,h); g.setColor(new Color(b)); for(int j=h;j>0;g.drawLine(0,h-j,w,h-j--)) g.setStroke(new BasicStroke(1,0,0,1,new float[]{j},j)); javax.imageio.ImageIO.write(i,"png",new java.io.File("a")); } ``` ## Result Inputs: `80, 50, 0xFF00FF, 0xFFFF00`. [![example output](https://i.stack.imgur.com/2vcvK.png)](https://i.stack.imgur.com/2vcvK.png) [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 83 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ..¹Cbe¹"εģνļ▲I-℮eīÆoHι⅛ļJd⁾)⁶f°┌²‘→e∫Ab∫Ƨ01a∙H∑bmWrcwιFHea-¹"S⁸▒Μ¬NrηA¤Y_⅓ļpPboā⁵‘→ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=Li4lQjlDYmUlQjklMjIldTIxNUQldTIwMzJtJXUyMjE5eUIldTIyMkJuJXUyMTVDeCUzQjAlMjQldTAxNkIldTAzQkQldTAzQjQlNUIldTIyMTklRjclQkQldTI1NUEldTIyMUVpJTA5QSVCOSV1MjAxOCV1MjE5MmUldTIyMkJBYiV1MjIyQiV1MDFBNzAxYSV1MjIxOUgldTIyMTFibVdyY3cldTAzQjlGSGVhLSVCOSUyMlMldTIwNzgldTI1OTIldTAzOUMlQUNOciV1MDNCN0ElQTRZXyV1MjE1MyV1MDEzQ3BQYm8ldTAxMDEldTIwNzUldTIwMTgldTIxOTI_,inputs=NDI3ODE5MDA4MCUwQTQyOTQ5NjcwNDAlMEExMjAlMEE2) SOGL was made in Processing.. So I took advantage of that using `→` - execute as JavaScript. Could easily be many bytes less (at least 30) if SOGL had *anything* made for graphics. Uncompressed strings: ``` ..¹Cbe¹"__processing0.hidden=0;cp.size(ŗ,ŗ)”→e∫Ab∫Ƨ01a∙H∑bmWrcwιFHea-¹"cp.stroke(ŗ);cp.point(ŗ,ŗ)”→ ``` Explanation: ``` ..¹C save the first 2 inputs as an array on variable C be¹ save next input - width - on B, next input - height - on E, and wrap both in an array "__processing0.hidden=0;cp.size(ŗ,ŗ)”→ execute "__processing0.hidden=0;cp.size(ŗ,ŗ)" as JavaScript - show the canvas and set the size to the corresponding items in the array e∫A repeat height times, saving 1-indexed counter on A b∫ repeat width times, pushing 1-indexed counter Ƨ01 push "01" a∙ multiply vertically A times - ["01", "01", "01",...] H rotate anticlockwise - ["000...","111..."] ∑ join together - "000..111.." bm mold to the length of width - "00011100011100" W get the counterth letter of that string - "1" r convert to number - 1 cw get that item from the variable C ι remove the array from the stack FH push current loops counter minus 1 ea- push e-a - height-outerLoopsCounter ¹ wrap the 3 items in an array - [itemInC (color), counter-1 (x position), height-outerLoopsCounter (y position)] "cp.stroke(ŗ);cp.point(ŗ,ŗ)”→ execute "cp.stroke(ŗ);cp.point(ŗ,ŗ)" as JavaScript, replacing ŗ with the corresponding item from the array ``` [Answer] # SmileBASIC, 84 bytes ``` DEF C W,H,C,D FOR J=1TO H FOR I=0TO W-1N=1AND I/J GPSET I,H-J,C*!N+D*N NEXT NEXT END ``` The color of a pixel at `(x,height-y)` is `[color1,color2][x/y & 1]` [Answer] # [Python 2](https://docs.python.org/2/), ~~123~~ 101 bytes ``` w,h,c,C=input() print'P3',w,h,255 for i in range(h): for j in range(w):print`[c,C][j/(h-i)%2]`[1:-1] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v1wnQydZx9k2M6@gtERDk6ugKDOvRD3AWF0HJGNkasqVll@kkKmQmadQlJiXnqqRoWnFpQASy0KIlWtagfUlRAONio3O0tfI0M3UVDWKTYg2tNI1jP3/X8PCQEfBFIg1DCoMgBSC1ASLpaWBeBASKKYJAA "Python 2 – Try It Online") Prints a .ppm to output as in Jonathan's [answer](https://codegolf.stackexchange.com/a/143598/38592). [Answer] # JavaScript (ES6) + HTML5, 138 bytes ``` (w,h,a,b)=>{with(c.width=w,c.getContext`2d`)for(c.height=y=h;~--y;)for(x=w;~--x;)fillStyle=x/(h-y)%2<1?a:b,fillRect(x,y,1,1)} ``` ``` <canvas id=c> ``` ``` f= (w,h,a,b)=>{with(c.width=w,c.getContext`2d`)for(c.height=y=h;~--y;)for(x=w;~--x;)fillStyle=x/(h-y)%2<1?a:b,fillRect(x,y,1,1)} ``` ``` #c{display:block ``` ``` <input id=w value=80> <input id=h value=50> <input id=a value=#000> <input id=b value=#FF0> <input value=go type=button onclick=f(w.value,h.value,a.value,b.value)> <canvas id=c> ``` The function outputs by operating on the `<canvas id=c>`. Starting from the bottom right of the canvas, the nested `for` loop iterates to the left and up, and checks the condition `x/(h-y)%2<1` for the pixel at `x,y`. If the condition is `true`, it colors that pixel with `color1`, else `color2`. ]
[Question] [ ## Intro So I've been wasting my time again researching suffix sorting algorithms, evaluating new ideas by hand and in code. But I always struggle to remember the type of my suffixes! Can you tell me which type my suffixes are? ## Left-most what? A lot of suffix sorting algorithms (SAIS, KA, my own daware) group suffixes into different types in order to sort them. There are two basic types: **S-type** and **L-type** suffixes. *S-type* suffixes are suffixes that are lexicographically less (**S**maller) than the following suffix and *L-type* if it is lexicographically greater (**L**arger). A *left-most S-type* (*LMS-type*) is just that: A *S-type* suffix that is preceeded by a *L-type* suffix. The special thing about these *LMS-type* suffixes is that once we sorted them we can sorted all the other suffixes in linear time ! Isn't that awesome? ## The challenge Given a string assume it is terminated by a special character that is less than any other character in that string (e.g. smaller than even the null byte). Output a type corrosponding char for each suffix. You can freely choose which char to use for which type but I'd prefer `L, S and *` for `L-, S- and LMS-type` as long as they are all printable (`0x20 - 0x7E`). ## Example Given the string `mmiissiissiippi` output (when using `L, S and *`): ``` LL*SLL*SLL*SLLL ``` For example the first `L` is due to the fact that `mmiissiissiippi$` is lexicographically greater than `miissiissiippi$` (the `$` represents the added minimal character): ``` L - mmiissiissiippi$ > miissiissiippi$ L - miissiissiippi$ > iissiissiippi$ * - iissiissiippi$ < issiissiippi and preceeded by L S - issiissiippi$ < ssiissiippi$ L - ssiissiippi$ > siissiippi$ L - siissiippi$ > iissiippi$ * - iissiippi$ < issiippi$ and preceeded by L S - issiippi$ < ssiippi$ L - ssiippi$ > siippi$ L - siippi$ > iippi$ * - iippi$ < ippi$ and preceeded by L S - ippi$ < ppi$ L - ppi$ > pi$ L - pi$ > i$ L - i$ > $ ``` Some more examples: ``` "hello world" -> "L*SSL*L*LLL" "Hello World" -> "SSSSL*SSLLL" "53Ab§%5qS" -> "L*SSL*SLL" ``` ## Goal I'm not here to annoy Peter Cordes (I'm so gonna do this on stackoverflow sometime); I'm just very lazy so this is of course [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ! The shortest answer in bytes wins. --- Edit: The order of the chars is given by their byte value. That means compare should be like C's `strcmp`. Edit2: Like stated in the comments output should be a single character for each input character. While I assumed that would be understood as "return a string" it seems at least 1 answer returns a list of single characters. In order to not invalidate the existing answers I will allow you to return a list of single characters (or integers which when printed result in only 1 char). --- ### Tips for linear time: 1. It can be done in 2 parallel forward iterations or in a single backward iteration. 2. The state of each suffix depends only on the first 2 chars and the type of the second. 3. Scanning the input in reverse direction you can determine L or S like this: `$t=$c<=>$d?:$t` (PHP 7), where `$c` is the current char `$d` the previous and `$t` the previous type. 4. See my [PHP answer](https://codegolf.stackexchange.com/a/128160/29637). Tomorrow I will award the bounty. [Answer] # [Haskell](https://www.haskell.org/), 64 53 48 42 bytes ``` (0!) k!(x:y)|x:y>y=1:2!y|2>1=k:0!y _![]=[] ``` [Try it online!](https://tio.run/##y0gszk7Nyflfraus4OPo5x7q6O6q4BwQoKCsW8vFVWUb81/DQFGTK1tRo8KqUrMGSNhV2hpaGSlW1hjZGdpmWxkoVnLFK0bH2kbH/s9NzMxTsFXITSzwjVfQiClW0LVTKCjKzCtR0CjWAYoqaCgF@2gpKSpqalQpFGtqaipEK@XmZmYWF0NwQUGmko5SBtA9@Qrl@UU5KUCeB5gXDuWZGjsmHVqualoYrBT7HwA "Haskell – Try It Online") Ungolfed, with `Char` instead of `Int`: ``` suffixes :: String -> String suffixes = go 'S' where go :: Char -> String -> String go _ "" = "" go lorstar s | s > tail s = 'L' : go '*' (tail s) | otherwise = lorstar : go 'S' (tail s) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25 23 21 20~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṛ;\UỤỤIṠµI2n×ịØDṚ;0 ``` A full program that prints the list of characters, using: ``` L: 0 S: 8 *: 9 ``` (As a link it returns a list where all items are characters except the last one, which is a zero.) **[Try it online!](https://tio.run/##y0rNyan8///hzlnWMaEPdy8BIs@HOxcc2upplHd4@sPd3YdnuIAkDf7//6/kAVScrxCeX5STogQA "Jelly – Try It Online")** or see the [test suite](https://tio.run/##y0rNyan8///hzlnWMaEPdy8BIs@HOxcc2upplHd4@sPd3YdnuIAkDf4fbn/UMMfAxyLYUutRw9zKfCDhY@0AFNO1UwCyuY7uAapoWuP@/3@0Um5uZmZxMQQXFGQq6SgoZQAtylcozy/KSQFxPcDccBjX1Ngx6dByVdPCYKVYAA "Jelly – Try It Online") (with conversion to `LS*`). ### How? ``` Ṛ;\UỤỤIṠµI2n×ịØDṚ;0 - Link: list of characters, s e.g. "cast" Ṛ - reverse "tsac" \ - cumulative reduce by: ; - concatenation ["t","ts","tsa","tsac"] U - upend (reverse each) ["t","st","ast","cast"] (suffixes) Ụ - sort indexes by value [3,4,2,1] (lexicographical order) Ụ - sort indexes by value [4,3,1,2] (order of that) I - incremental differences [-1,-2,1] (change) Ṡ - sign [-1,-1,1] (comparisons) µ - monadic chain separation, call that x I - incremental differences [0,2] (only (-1,1) produce 2s) 2 - literal 2 2 n - not equal? [1,0] (indexes of * will be 0) × - multiply by x (vectorises) [-1,0,1] (make indexes of *s 0) ØD - decimal yield "0123456789" ị - index into (1-indexed & modular) ['8','9','0'] Ṛ - reverse ['0','9','8'] ;0 - concatenate a zero ['0','9','8',0] - implicit print 0980 - i.e. "L*SL" ``` [Answer] # Python 3, ~~92~~ ~~87~~ ~~74~~ ~~69~~ 65 bytes ``` s=input() c=1 while s:d=s<s[1:];print(d+(c<d),end='');s=s[1:];c=d ``` Uses `0` for `L`, `1` for `S`, and `2` for `*`. Wrap the input string in quote characters; I believe this is allowed by convention. [Try it online!](https://tio.run/##K6gsycjPM/6faKukpPS/2DYzr6C0REOTK9nWkKs8IzMnVaHYKsW22KY42tAq1rqgKDOvRCNFWyPZJkVTJzUvxVZdXdO62BYim2yb8h9oClSfoVVqRWqyRqImVJfm/9zczMziYgguKMjkykjNyclXKM8vyknh8gCzw8FsU2PHpEPLVU0LgwE "Python 3 – Try It Online") Example use: ``` mmiissiissiippi 002100210021000 ``` *saved 5 bytes thanks to Leaky Nun, 4 bytes thanks to ovs* [Answer] # JavaScript (ES6), ~~51~~ 45 bytes ``` f=(c,d)=>c&&(d<(d=c<(c=c.slice(1))))+d+f(c,d) ``` *Saved 6 bytes thanks to @Neil.* A recursive solution to the exercise. ``` f=(c,d)=>c&&(d<(d=c<(c=c.slice(1))))+d+f(c,d) console.log(f('mmiissiissiippi')); //LL*SLL*SLL*SLLL 002100210021000 console.log(f('hello world')); //L*SSL*L*LLL 02110202000 console.log(f('Hello World')); //SSSSL*SSLLL 11110211000 console.log(f('53Ab§%5qS')); //L*SSL*SLL 021102100 ``` [Answer] ## JavaScript (ES6), 52 bytes ``` f= s=>s.replace(/./g,_=>(c<(c=s<(s=s.slice(1))))+c,c=1) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` Port of @L3viathan's answer. [Answer] # [C (clang)](http://clang.llvm.org/), 88 bytes ``` S(S,A,I)char*S,*A;{for(;strlen(S);A=S,S++,printf("%c",I=strcmp(A,S)>0?76:I==76?42:83));} ``` [Try it online!](https://tio.run/##Jcq9CoMwFEDhuT6FBAqJRiht0WJIJaPzfYJwqzVgfojSRXzszqnQ4UzfwQpn7d4pAQWueM9w0rEAXiixjT5SsaxxHhwFJpQEDmXJQzRuHSk5I@G9PBxtoIoDe166pm57KZu6u1/bx40xsadjzq02jn68ebF8y05AibXGLMu/EAxhItvT1/kKNU7DDw "C (clang) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~77~~ 75 bytes, linear time ``` f(a:b:c)|let g"L"|a<b="SL";g"S"|a>b="L*";g d=d++d;d:e=f$b:c=g[d]++e f _="L" ``` [Try it online!](https://tio.run/##JY6xCsIwGIT3PsVPqKAGXKRLawQ3h24ZHEQkbZI2mKS1ibj0fXwPXyz@1OG4@@AOrhfhoaxNSa9F2ZTtZrYqQkdqMotDwwivSdURjnREqrdIIJmkVFayVEznuGHdVd4oVZmGO3ZIcsJ4YGB8VJNoI@Tw8tZ4FWAHToyg0RdOzhkTwl/jaLIevwzwHiYrs/OSL0su9qfm@1kVT/4D "Haskell – Try It Online") ### How it works This uses recursion, stripping off one character at a time from the beginning of the string. (The Haskell string type is a singly-linked list of characters, so each of these steps is constant-time.) * For a string *abc* where *a* and *b* are single characters and *c* is any (possibly empty) string, + *f*(*abc*) = SL*e*, if *f*(*bc*) = L*e* and *a* < *b*; + *f*(*abc*) = L\**e*, if *f*(*bc*) = S*e* and *a* > *b*; + *f*(*abc*) = LL*e*, if *f*(*bc*) = L*e* and *a* ≥ *b*; + *f*(*abc*) = SS*e*, if *f*(*bc*) = S*e* and *a* ≤ *b*. * For a single-character string *a*, *f*(*a*) = L. [Answer] # [Python 2](https://docs.python.org/2/), ~~65~~ 55 bytes Recursive version, based on [L3viathan's answer](https://codegolf.stackexchange.com/a/126101/38592 "answer"), using `012` as `LS*`: ``` def g(s,d=2):c=s<s[1:];return s and`c+(d<c)`+g(s[1:],c) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFdo1gnxdZI0yrZttimONrQKta6KLWktChPoVghMS8lIVlbI8UmWTNBG6gQJKuTrPm/PCMzJ1XB0KqgKDOvRCNdIzOvoLREQ1NT879Sbm5mZnExBBcUZCpxKWWk5uTkK5TnF@WkAHkeYF44lGdq7Jh0aLmqaWGwEgA "Python 2 – Try It Online") ## [Python 3](https://docs.python.org/3/), ~~65~~ 59 bytes Recursive solution using `L`, `S`, and `*`: ``` f=lambda s:s and('LS'[s<s[1:]]+f(s[1:])).replace('LS','L*') ``` Runs through the string from the front, and replaces all instances of `LS`with `L*` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRodiqWCExL0VD3SdYPbrYpjja0Co2VjtNA8zQ1NQrSi3ISUxOBcvrqPtoqWv@L8/IzElVMLQqKMrMK9FI08jMKygt0dDU1Pyfm5uZWVwMwQUFmVwZqTk5@Qrl@UU5KVweYHY4mG1q7Jh0aLmqaWEwAA "Python 3 – Try It Online") [Answer] ## PHP, 82 byte, linear time ``` for($a=$argn;a&$c=$a[$i-=1];$d=$c)$a[$i]=2+$t=$d<=>$c?:$t;echo strtr($a,[13=>12]); ``` Walks over the input from right to left and replaces each char with the type. ``` $t=$d<=>$c?:$t ``` Calculates the type given the current and the previous char (-1 or 1). If equal the type doesn't change. [Answer] # [PHP](https://php.net/), 70 bytes L = 1, S = 0 , \* = 2 Multibyte Support is needed for the last Testcase with the `§` +3 Bytes `mb_substr` instead `substr` ``` for(;$s=&$argn;$s=$u)$r.=$l=($l&1)+(1&$l^($s>$u=substr($s,1)));echo$r; ``` [Try it online!](https://tio.run/##RY/NasMwEITvfgqjLkZKnILPipNDCLQgmoMKPfQnOI4aGRRJrGx6CM1b5@zKaqEsw@wy32HWaz8u1177TCE63KPyDvvOnuh1u3/aPT9utoxnnw5V02r6Ss7nrgvhV953pMzvciFm8l8iI1oZ4/Ivh@aYgMUqJzGTYhZHCJKRh0S8JOIPkHICpEzAexOgwZNll8EG1VPAEgzjYyxCOYS6SOm0wcAA72swNQVTVGxOqwLMB4WwgqEOwyH0GI@yYoxx1WoHyMfJyZsl/Hu8Wbdo42/qBw "PHP – Try It Online") # [PHP](https://php.net/), 71 bytes L = 1, S = 0 , \* = 2 ``` for(;$s=&$argn;$s=$u)$r.=+($s>$u=substr($s,1));echo strtr($r,[10=>12]); ``` [Try it online!](https://tio.run/##VY9Bi8IwEIXv/RUhG5ZEq1iv2daDCArBPUTwoCLdbjSFmoRJiwfZ/deea1oPIsODefM@hhmnXfs1c9pFCsDCEZSzUJfmTP8Xx/X3ZjVfMB6dLKi80HSHL5ey9P4p50ocow8kxEC@JCKsVVVZdLVQ/fbAKEM4ZFIMQgmBI7zsie0bIWVHSNkTh9yTHM6G3RrjVU0JMN6GMygnPv3so64jDSMwToeU@Iw0qW9@fA3BxAljXBXaouC7CcS7ZJJmyfQQ9nQB3hvM/9q7saMivKYe "PHP – Try It Online") # [PHP](https://php.net/), 74 bytes ``` for(;$s=&$argn;$s=$u)$r.=SL[$s>$u=substr($s,1)];echo strtr($r,[LS=>"L*"]); ``` [Try it online!](https://tio.run/##VY9Ba8MwDIXv@RVGM8Mu6WBnL9lhFFow3cGDHbJQ0tSrA6ltpIQexvavd86c7DCGeCDpfYin6OL08BhdzCxiwAPaGHDo/Fl8bQ7755fd00aq7D2gbVonKrhcuo7oVzF2kLMbpvXK/Eln4GzfB3YN2J8WYF0ySJ7Rq1RaQwbbhXj9RxgzE8YsRN0Qb/Ds5cfoyQ6Co1RTiiEUp@J2seaOj5LjXWF0xankY0HjkQYUnPJ7WSvbusDSPG8wr7QpypQD6nRqtuDNg/qcvn1Yt@k7@wM "PHP – Try It Online") ]
[Question] [ So task is simple, given array of numbers and result, you need to find what operations you need to use on numbers from array , to obtain requested result. Let's make it simple for start, and allow only basic operations such as: addition, subtraction, multiplication and division. Example: ``` Input : [5,5,5,5,5] 100 Output : 5*5*5-5*5 ``` To give some advantage to languages like Java, request is to implement function, not entire program, and result can be return via parameter or print to console. Code is scored based on amount bytes, and as it's golf code challenge, lowest score wins. Another requirment is ~~You can get additional -10 points~~ if for array contains only digids, support solutions where you could construct numbers from following digits. Ie ``` Input : [1,2,3,4,5] 0 Output : 12-3-4-5 ``` Note that, provided outputs are proposed outputs, some cases might have more than one solution. It's up to you will you provide one or more solutions for given task. **EDIT:** Result has to be valid from mathematical point of view, hence division is rational division, not integer, and operation precedence is same as in classical math (first multiplication and division then addition and subtraction). [Answer] # Pyth, 23 bytes Due to security reasons, `*` and `/` won't evaluate online, but they theoretically work. ``` fqeQvTms.ihQd^"+-*/"lth ``` [Test suite with only `+` and `-`.](http://pyth.herokuapp.com/?code=fqeQvTms.ihQd%5E%22%2B-%22lth&test_suite=1&test_suite_input=%5B5%2C5%2C5%2C5%2C5%5D%2C25%0A%5B1%2C2%2C3%2C4%2C5%5D%2C1&debug=0) [Answer] # Oracle SQL 11.2, ~~322~~ ~~304~~ 270 bytes ``` SELECT o FROM(SELECT REPLACE(SUBSTR(:1,1,1)||REPLACE(SYS_CONNECT_BY_PATH(a||SUBSTR(:1,LEVEL*2+1,1),','),','),'_')o,LEVEL l FROM(SELECT SUBSTR('+-*/_',LEVEL,1)a FROM DUAL CONNECT BY LEVEL<6)CONNECT BY LEVEL<LENGTH(:1)/2)WHERE:2=dbms_aw.eval_number(o)AND l>LENGTH(:1)/2-1; ``` :1 is the list of digits :2 is the result searched Un-golfed : ``` SELECT o FROM ( SELECT REPLACE(SUBSTR(:1,1,1)||REPLACE(SYS_CONNECT_BY_PATH(a||SUBSTR(:1,LEVEL*2+1,1),','),','),'_')o,LEVEL l FROM ( -- Create one row per operator SELECT SUBSTR('+-*/_',LEVEL,1)a FROM DUAL CONNECT BY LEVEL<6 ) CONNECT BY LEVEL<LENGTH(:1)/2 -- Create every combination of operators, one per ',' ) WHERE :2=dbms_aw.eval_number(o) -- filter on result = evaluation AND l>LENGTH(:1)/2-1 -- keep only expressions using every digits ``` [Answer] # TSQL(sqlserver 2016) ~~310~~ ~~294~~ 280 bytes What a wonderful opportunity to write ugly code: Golfed: ``` DECLARE @ varchar(max)= '5,5,5' DECLARE @a varchar(20) = '125' ,@ varchar(max)='';WITH D as(SELECT @a a UNION ALL SELECT STUFF(a,charindex(',',a),1,value)FROM STRING_SPLIT('*,+,./,-,',',')x,d WHERE a like'%,%')SELECT @+=a+','''+REPLACE(a,'.','')+'''),('FROM D WHERE a not like'%,%'EXEC('SELECT y FROM(values('+@+'null,null))g(x,y)WHERE x='+@b) ``` [Try it online](https://data.stackexchange.com/stackoverflow/query/501607/find-operations-required-to-get-result) Readable:(insertion of decimal point(.) and removal of the same is necessary in order for sql to accept that 4/5 is not 0 - well removal is for the people testing it) ``` DECLARE @a varchar(max)= '5,5,5' DECLARE @b varchar(20) = '5' ,@ varchar(max)='' ;WITH D as ( SELECT @a a UNION ALL SELECT STUFF(a,charindex(',',a),1,value) FROM STRING_SPLIT('*,+,./,-,',',')x,d WHERE a like'%,%' ) SELECT @+=a+','''+REPLACE(a,',','')+'''),(' FROM D WHERE a not like'%,%' EXEC('SELECT y FROM(values('+@+'null,null))g(x,y)WHERE x='+@b) ``` This solution can also handle these types of input: > > Input :[1,2,3,4,5] 0 Output : 12-3-4-5 > > > [Answer] # JavaScript (ES6), ~~165~~ 147 bytes ``` a=>o=>(c=[],i=c=>{for(j=0;!((c[j]?++c[j]:c[j]=1)%5);)c[j++]=0},eval(`while(eval(e=(a+'').replace(/,/g,(_,j)=>'+-*/'.charAt(c[~-j/2])))!=o)i(c);e`)) ``` Nested `eval`... lovely. ``` f=a=>o=>(c=[],i=c=>{for(j=0;!((c[j]?++c[j]:c[j]=1)%5);)c[j++]=0},eval(`while(eval(e=(a+'').replace(/,/g,(_,j)=>'+-*/'.charAt(c[~-j/2])))!=o)i(c);e`)) console.log(f([5,5,5,5,5])(100)) console.log(f([1,2,3,4,5])(0)) console.log(f([3,4])(0.75)) console.log(f([3,4,5,6])(339)) ``` [Answer] ## Python 3, ~~170~~ 155 bytes ``` from itertools import* def f(n,o):print({k for k in[''.join(map(str,sum(j,())))[1:]for j in[zip(x,n)for x in product('+-*/',repeat=len(n))]]if eval(k)==o}) ``` Create a generator with all possible orders of the operators, combine that with the numbers, then eval until we get the answer. <https://repl.it/C2F5> [Answer] # Python, ~~195~~ 186 bytes Here's an atrocious way of doing it. ``` def x(i,r): t="" from random import choice as c while True: for j in i: t+=str(j) if c([0,1]):t+="."+c("+-/*") t=t.strip("+-*/.")+"." v=eval(t) if v == r:print t t="" ``` The function `x` accepts an argument of a `list` and a `result` - `x([1,2,3,4,5], 15)` for example. The program begins a loop where we begin randomly selecting if we should append `"+", "-", "*", or "/"` between each number, or if we should concatenate them together. This seemed like a more concise option than actually going through permutations and trying every combination to find every result, and although it takes longer to run and is *much* less efficient. (Fortunately that's not a concern in this context!) It also appends "." to each number to avoid doing integer-rounded operations like `6/4 = 1`. It then `eval`s our expression and determines if the result equal to what we are expecting, and if so, outputs the expression. This program never exits - it will keep continually outputting results until killed. **EDIT 1**: Remove unnecessary newlines where one-line `if` statements can be used. [Answer] ## Matlab, 234 ~~238~~ ~~258~~ bytes *I'm assuming based on the limitations of the other answers that the number order of the input array is maintained by fiat.* ``` n=length(x)-1 k=n*2+2 p=unique(nchoosek(repmat('*-+/',1,n),n),'rows') p=[p char(' '*~~p(:,1))]' c=char(x'*~~p(1,:)) o=p(:,r==cellfun(@eval,mat2cell(reshape([c(:) p(:)]',k,[]),k,0|p(1,:)))) reshape([repmat(x',size(o,2),1) o(:)]',k,[])' ``` This code takes a string of numbers `x`, say `x = '12345'` and a result `r`, say `r = 15` and returns all of the strings of expressions you can evaluate to get `r` from `x` using the four operators. I've used two different length-equivalent ways of avoiding using `ones(length())`-type or `repmat(length())`-type expressions: `~~p(1,:)` which returns not-not values in `p` (i.e., a list of `1`s the samelength as the first dimension of `p`) and `0|p(:,1)` which returns 0 or is-there-a-value-in-`p` (i.e., a list of `1`s the same length as the second dimension of `p`). Matlab doesn't have an `nchoosek` *with replacement* method, so I've duplicated the operators the correct number of times, computed the whole space of `nchoosek` for that larger selection of operators, and then used a `unique` call to pare the result down to what it should be (removing equivalent combinations like '\*\*\*+' and '\*\*\*+'). I add a trailing space to match the length of the input vector for concatenation purposes and then compose the operator strings with the input strings into the columns of a matrix. I then evaluate the expressions columnwise to get results and find the order of operators that corresponds to those columns with results that match our input `r`. Test: `x = '12345'`, `r = 15`: ``` 1*2*3+4+5 1+2+3+4+5 1-2*3+4*5 ``` If I had to take an array of double precision values, I'd need `x = num2str(x,'%d');` in order to convert the digits to a string, adding 21 (20 without the `;`) to my score. \*The extra bytes were semicolons I left in purely so that anyone running this code won't see their command prompt blow up with long arrays. Since my edit produces a giant pile of warnings about logicals and colon-operands now anyway, I've removed the semicolons in the new version. Edit 2: Forgot to replace a `2*n+2` with `k`. Old answer: ``` n=length(x)-1; p=unique(nchoosek(repmat(['*','-','+','/'],1,n),n),'rows'); l=length(p); p=[p repmat(' ',l,1)]'; c=reshape([repmat(x',l,1) p(:)]',n*2+2,[]); o = p(:,r == cellfun(@eval, mat2cell(c,n*2+2,ones(l,1)))); reshape([repmat(x',size(o,2),1) o(:)]',n*2+2,[])' ``` [Answer] # JavaScript (ES6), 88 bytes ``` a=>o=>eval(`while(eval(e=(a+'').replace(/,/g,_=>'+-*/'.charAt(Math.random()*5)))!=o);e`) ``` Threw in a little randomness to the mix. Much easier than systematically iterating through the combinations. ## Test Suite ``` f=a=>o=>eval(`while(eval(e=(a+'').replace(/,/g,_=>'+-*/'.charAt(Math.random()*5)))!=o);e`) console.log(f([5,5,5,5,5])(100)) console.log(f([1,2,3,4,5])(0)) console.log(f([3,4])(0.75)) console.log(f([3,4,5,6])(339)) ``` [Answer] # PHP, 108 bytes ``` for(;$i=$argc;eval("$s-$argv[1]?:die(\$s);"))for($s="",$x=$p++;--$i>1;$x/=4)$s.="+-*/"[$s?$x&3:4].$argv[$i]; ``` takes input from command line arguments in reverse order. Run with `-r`. **breakdown** ``` for(; # infinite loop: $i=$argc; # 1. init $i to argument count eval("$s-$argv[1]?:" # 3. if first argument equals expression value, ."die(\$s);") # print expression and exit ) for($s="", # 2. create expression: $x=$p++; # init map --$i>1; # loop from last to second argument $x/=4) # C: shift map by two bits $s.="+-*/"[$s?$x&3:4] # A: append operator (none for first operand) .$argv[$i]; # B: append operand ``` [Answer] ## [Perl 5](https://www.perl.org/) with `-pa`, 46 bytes ``` $"="{,\\*,/,+,-}";$x=<>;($_)=grep$x==eval,<@F> ``` [Try it online!](https://tio.run/##K0gtyjH9/19FyVapWicmRktHX0dbR7dWyVqlwtbGzlpDJV7TNr0otQDItU0tS8zRsXFws/v/31DBSMFYwUTBlMuAy1QBCrkMDQz@5ReUZObnFf/XLUjMAQA "Perl 5 – Try It Online") ]
[Question] [ There is a virus inside a recipient of 5x5. As we know how it propagates its contamination, your mission is to output the last stage of the contamination. ### The recipient It will be representend as a two dimensional array of 5x5: ``` 0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0 0 1 1 1 0 1 1 1 1 ``` Where `1` means a position where the virus has already contaminated, and `0` a position not contaminated. ### How the virus propagates 1. A contaminated position can not be clean. 2. A clean position will be contaminated in the next stage only if at least two of its adjacent positions (north, east, south and west cells) are contaminated. 3. The last stage of the contamination occurs when no more clean cells can be contaminated. ### Sample Using as as stage 1 of the contamination the recipient described above, the stage 2 will be: ``` 0 0 0 0 1 0 0 0 1 1 0 0 1 1 1 0 1 1 1 1 0 1 1 1 1 ``` The stage 3 of the contamination will be: ``` 0 0 0 1 1 0 0 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 ``` The stage 4 of the contamination will be: ``` 0 0 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 ``` And the stage 5 (in this example, the last one) will be: ``` 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 ``` ### Challenge Given as input one stage of the contamination, you should output the last stage of the contamination. You are allowed to write full program or a function. You can take the input as array/list, as separated numbers, or even as string. Chooses the best way that fits to your language. The shortest answer in bytes wins! ### Another test cases ``` Input: 1 1 0 0 1 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 1 Output: 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 ``` --- ``` Input: 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 Output: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ``` --- ``` Input: 1 0 0 1 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 Output: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ``` --- ``` Input: 0 1 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 1 0 Output: 0 1 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 1 0 ``` [Answer] Since this is basically talking about a cellular automaton I give you.. # [Golly](http://golly.sourceforge.net/) Quicklife rule, 10 bytes ``` 01234/234V ``` Input the rule, paste the grid into Golly, run pattern. The resulting pattern is the output. Explanation: ``` 01234 Survive on any number of neighbors /234 Born on >2 neighbors V Only directly adjacent neighbors count ``` Or if you insist on a full RuleLoader rule, 89 bytes: ``` @RULE X @TABLE n_states:2 neighborhood:vonNeumann symmetries:permute 011001 011101 011111 ``` Rulename is X, same steps as before. [Answer] # Python 2, 97 bytes ``` s=' '*6+input() exec"s=s[1:]+('1'+s)[sum(s[i]<'1'for i in[-6,-1,1,6])>2or'/'>s];"*980 print s[6:] ``` [Try it online](http://ideone.com/nRsdUY). Input is taken as a quoted string with each row delimited by newlines. The `980` is not optimal and can be replaced with a lower multiple of 35. Since it has no impact on the length of this program, I have left the determination of the lowest safe upper bound as an exercise for the reader. [Answer] # Javascript (ES6), 91 89 87 bytes As a function which accepts input as an array of numbers or strings. -2 bytes from Neil (combining assignment of `y` with string conversion) -2 bytes (removing variable `j`) ``` f=x=>(y=x.map((z,i)=>~(i%5&&x[i-1])+~(i%5<4&x[i+1])+~x[i-5]+~x[i+5]<-5|z))+[]==x?y:f(y) ``` ``` <!-- Snippet demo with array <-> string conversion for convenience --> <textarea id="input" cols="10" rows="5">0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0 0 1 1 1 0 1 1 1 1</textarea> <button id="submit">Run</button> <pre id="output"></pre> <script> strToArray=x=>x.match(/\d/g) arrayToStr=x=>([]+x).replace(/(.),(.),(.),(.),(.),*/g, '$1 $2 $3 $4 $5\n') submit.onclick=_=>output.innerHTML=arrayToStr(f(strToArray(input.value))) </script> ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 22 bytes ``` tn:"t5Bt!=~2X53$Y+1>Y| ``` This works in [current version (15.0.0)](https://github.com/lmendo/MATL/releases/tag/15.0.0) of the language. [**Try it online**!](http://matl.tryitonline.net/#code=dG46InQ1QnQhPX4yWDUzJFkrMT5ZfA&input=WzAgMCAwIDAgMTsgMCAwIDAgMCAxOyAwIDAgMCAxIDE7IDAgMCAxIDEgMTsgMCAxIDEgMSAxXQ) Input format is: 2D array with rows separated by semicolons. So the four test cases have the following inputs: ``` [0 0 0 0 1; 0 0 0 0 1; 0 0 0 1 1; 0 0 1 1 1; 0 1 1 1 1] [1 1 0 0 1; 0 0 0 0 0; 0 1 0 0 1; 0 0 0 0 0; 1 0 0 0 1] [1 0 0 0 0; 0 1 0 0 0; 0 0 1 0 0; 0 0 0 1 0; 0 0 0 0 1] [1 0 0 1 0; 0 0 1 0 1; 0 0 0 0 0; 1 0 0 0 0; 0 0 1 0 0] ``` ### Explanation This repeatedly performs a 2D convolution of the input array with the following mask, which defines which neighbours count as contaminating: ``` 0 1 0 1 0 1 0 1 0 ``` In order to obtain a result the same size as the original array, it is first padded with a frame of zeros and then only the "valid" part of the convolution is kept (i.e. that without edge effects). A threshold of 2 is applied to the output of the convolution, and the result is element-wise ORed with the original input. This must be done a sufficient number of times to ensure the final state has been reached. A simple criterion that fulfills this is: iterate as many times as the number of entries in the input array (that is, 25 times in the test cases). ``` t % get input 2D array implicitly. Duplicate n:" % repeat as many times as elements in the input array t % duplicate array 5B % number 5 in binary: row vector [1 0 1] t! % duplicate and transpose into column =~ % compare for inequality with broadcast. Gives desired mask 2X53$Y+ % 2D convolution. Output has same size as input 1> % true for elements equal or greater than 2 Y| % element-wise OR with previous copy of the array % end loop. Implicitly display ``` [Answer] # TI-BASIC, 151 bytes ``` Prompt [A] [A]→[B] Lbl 0 [B]→[A] For(Y,1,5 For(X,1,5 DelVar ADelVar BDelVar CDelVar D If Y>1:[A](Y-1,X→A If Y<5:[A](Y+1,X→B If X>1:[A](Y,X-1→C If X<5:[A](Y,X+1→D max(A+B+C+D≥2,[A](Y,X→[B](Y,X End End If [A]≠[B]:Goto 0 [B] ``` Input as `[[1,0,0,1,1][1,0,0,0,0]...]`. [Answer] # Lua, 236 bytes ``` s=arg[1]u=s.sub while p~=s do p=s s=s:gsub("(%d)()",function(d,p)t=0 t=t+((p-2)%6>0 and u(s,p-2,p-2)or 0)t=t+(p-7>0 and u(s,p-7,p-7)or 0)t=t+(p+5<30 and u(s,p+5,p+5)or 0)t=t+(p%6>0 and u(s,p,p)or 0)return t>1 and 1 or d end)end print(s) ``` Accepts input on the command line, and uses Lua's string manipulation to get the answer. Ungolfed: ``` s=arg[1] u=s.sub while p~=s do p=s s=s:gsub("(%d)()", function(d, p) t=0 t=t+((p-2)%6>0 and u(s,p-2,p-2)or 0) t=t+(p-7>0 and u(s,p-7,p-7)or 0) t=t+(p+5<30 and u(s,p+5,p+5)or 0) t=t+(p%6>0 and u(s,p,p)or 0) return t>1 and 1 or d end) end print(s) ``` [Answer] # APL, ~~76~~ ~~72~~ 70 bytes ``` {⍵∨1<¯1 ¯1↓1 1↓↑+/(1 0)(¯1 0)(0 ¯1)(0 1){⍺[1]⊖⍺[2]⌽⍵}¨⊂¯1⊖¯1⌽7 7↑⍵}⍣≡ ``` What this does is: expand the matrix to a 7x7 one, then center our argument (omega). From this matrix, generate 4 "child" matrices, each one shifted in a different direction (up/down/left/right), add them together (so we get the number of neighbours), drop the frame (to go back to a 5x5 matrix). Or this new matrix with the "old" one, to make sure we didn't drop any cells in the process (i.e. at the edge). Then, use the `⍣≡` combination to get to a fixed-point value. ``` {⍵∨1<¯1 ¯1↓1 1↓↑+/(1 0)(¯1 0)(0 ¯1)(0 1){⍺[1]⊖⍺[2]⌽⍵}¨⊂¯1⊖¯1⌽7 7↑⍵}⍣≡ 7 7↑⍵ ⍝ Expand the matrix ¯1⊖¯1⌽ ⍝ Center the original matrix (1 0)(¯1 0)(0 ¯1)(0 1){⍺[1]⊖⍺[2]⌽⍵}¨⊂ ⍝ Construct 4 child matrices, each offset from the original one by the values on the left of {} +/ ⍝ Sum each matrix into one giant matrix ↑ ⍝ Mix ¯1 ¯1↓1 1↓ ⍝ Transform the 7x7 matrix back to a 5x5 matrix 1< ⍝ Check which elements are smaller than 1 ⍵∨ ⍝ "Or" this matrix and the generated matrix { }⍣≡ ⍝ Find the fixpoint ``` example (considering the function was assigned to `contaminate`): ``` stage ⍝ the base matrix 0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0 0 1 1 1 0 1 1 1 1 contaminate stage ⍝ apply the function 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 ``` ]
[Question] [ # The Task Write a function L() that takes two Tuple arguments of coordinates in the form (x, y), and returns their respective linear function in the form (a, c), where a is the co-efficent of the x term and c is the y-intercept. You can assume that the input will not be a line perpendicular the the x axis, and that the two inputs are separate points. # Scoring This is Code Golf: shortest program wins. Please Note: No use of any mathematical functions apart from basic operators (+,-,/,\*). # Example Here is my un-golfed solution in Python. ``` def L(Point1, Point2): x = 0 y = 1 Gradient = (float(Point1[y]) - float(Point2[y])) / (float(Point1[x]) - float(Point2[x])) YIntercept = Point1[y] - Gradient * Point1[x] return (Gradient, YIntercept) ``` Output: ``` >>> L( (0,0) , (1,1) ) (1.0, 0.0) >>> L( (0,0) , (2,1) ) (0.5, 0.0) >>> L( (0,0) , (7,1) ) (0.14285714285714285, 0.0) >>> L( (10,22.5) , (5,12.5) ) (2.0, 2.5) ``` [Answer] # [GNU dc](http://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 30 24 bytes ``` [sysxly-rlx-/dlx*lyr-]sL ``` Defines a macro `L` such that (x1, y1, x2, y2) should be pushed to the stack in that order before calling, and after calling `L`, (a, c) may be popped from the stack (in reverse order of course - it is a stack). ### Testcase (save as "linear.dc" and run `dc linear.dc`): ``` [sysxly-rlx-/dlx*lyr-]sL # Define L macro 10 # Push x1 to the stack 22.5 # Push y1 to the stack 5 # Push x2 to the stack 12.5 # Push y2 to the stack lLx # Call L macro f # Dump the stack ``` Output is: ``` $ dc linear.dc 2.5 2 $ ``` ### Explanation of L macro: * `sy` pop y2 to `y` register * `sx` pop x2 to `x` register * `ly` push `y` register (y2) * `-` subtract y2 from y1 * `r` swap (y1 - y2) and x1 on stack * `lx` push `x` register (x2) * `-` subtract x2 from x1 * `/` divide (y1 - y2) by (x1 - x2) to get gradient * `d` duplicate gradient * `lx` push `x` register (x2) * `*` multiply (x2) by gradient * `ly` push `y` register (y2) * `r` swap (y2) and (x2 \* gradient) on stack * `-` subtract (x2 \* gradient) from (y2) [Answer] # Haskell, 41 characters ``` f(x,y)(u,v)=(a,y-a*x)where a=(y-v)/(x-u) ``` Not a lot to golf here. It's pretty much what you'd write normally minus whitespace. [Answer] ## Mathematica, ~~55~~ 38 bytes ~~This was surprisingly long (those pesky long function names...)~~ **EDIT:** Changed the approach for the axis intercept (taking some inspiration from the OP's own answer). It turns out calculating it directly wasn't the most clever idea. ``` L={g=1/Divide@@(#2-#),#[[2]]-g#[[1]]}& ``` Use like ``` L[{10,22.5},{5,12.5}] > {2., 2.5} ``` Thanks to Mathematica you can also obtain the general result: ``` L[{r,s},{p,q}] > {(p - r)/(q - s), (q r - p s)/(q - s)} ``` (This last example shows how I had originally implemented this.) Just for the record ``` L[{0,0},{0,1}] > {ComplexInfinity, Indeterminate} ``` which is technically correct. [Answer] ## JavaScript, ~~62~~ 48 Thanks to @Michael for golfing it down with ES 6. ``` L=(a,b)=>[s=(b[1]-a[1])/(b[0]-a[0]),a[1]-s*a[0]] ``` Old version: ``` function L(a,b){return[s=(b[1]-a[1])/(b[0]-a[0]),a[1]-s*a[0]]} ``` Sample input: ``` L([0,0],[7,1]) ``` Sample output: ``` [0.14285714285714285, 0] ``` For the record: ``` L([0,0],[0,1]) [Infinity, NaN] ``` [Answer] # Python3 (51) ``` def L(p,q):x,y=p;X,Y=q;m=(Y-y)/(X-x);return m,y-x*m ``` [Answer] ## C# 105 bytes This is isn't just the function and will compile completely on it's own. I had put `L` in the `System` namespace to shorting the using, but it's better to fully qualify and save on using a namespace. Saved the brackets. Also a saving from `return new z[]` into `return new[]` ``` using z=System.Single;class P{z[] L(z[]a,z[]b){z c=(a[1]-b[1])/(a[0]-b[0]);return new[]{c,a[1]-c*a[0]};}} ``` [Answer] # J - 23 char Fairly straightforward. Defines a dyadic verb `L` to be used as `(x1,y1) L (x2,y2)`. ``` L=:%~/@:-,-/@(*|.)%-&{. ``` Explanation: ``` L=:%~/@:-,-/@(*|.)%-&{. NB. the function L &{. NB. x coord of both points - NB. left x minus right x ( |.) NB. flip right argument: (y2,x2) * NB. pointwise multiplication of (x1,y1) and (y2,x2) -/@ NB. subtract the two results: (x1*y2)-(y1*x2) % NB. divide: (x1*y2 - y1*x2)/(x1-x2) - NB. pointwise subtraction %~/@: NB. divide y difference by x diff: (y1-y2)/(x1-x2) , NB. append results together L=: NB. assign function to L ``` Examples: ``` L=:%~/@:-,-/@(*|.)%-&{. 0 0 L 1 1 1 0 0 0 L 2 1 0.5 0 0 0 L 7 1 0.142857 0 10 22.5 L 5 12.5 2 2.5 0 0 L 0 1 NB. __ is negative infinity __ 0 ``` [Answer] ## Lua 5.1.4: ~~66~~ 64 bytes ``` function L(q,w)a=(q[2]-w[2])/(q[1]-w[1])return a,q[2]-a*q[1];end ``` Example Usage: ``` > print(L( {0,0}, {1,0} )) -0 0 > print(L( {0,0}, {1,1} )) 1 0 > print(L( {0,0}, {7,1} )) 0.14285714285714 0 > print(L( {0,0}, {0,1} )) -inf -nan > print(L( {0,0}, {0,0} )) -nan -nan ``` [Answer] ## C++ 88 (was 106) Improved: thanks for your comments. ``` struct t{double x,y;}; t L(t u, t v){u.x=(v.y-u.y)/(v.x-u.x);u.y=v.y-u.x*v.x;return u;} ``` Golfed: ``` typedef struct T{double x,y;}t; t line(t u, t v){t z;z.x=(v.y-u.y)/(v.x-u.x);z.y=v.y-(z.x*v.x);return z;} ``` Source ``` typedef struct T{ double x,y; } t; t line(t u, t v) { t z; z.x=(v.y-u.y)/(v.x-u.x); z.y=v.y-(z.x*v.x); return z; } ``` [Answer] # Apple Swift ~~95~~ 86 *This may be the first Swift entry on PCG.SE??* ``` func L(x:Float...)->(Float,Float){var a=(x[3]-x[1])/(x[2]-x[0]);return(a,x[1]-a*x[0])} ``` I don't see this language being a huge hit to the Code Golf community. [Answer] ### Golfscript: 25 bytes ``` ~:y\:x;-\x--1?*.x-1**y+\p ``` Since the function needs to be named 'L', I saved it as 'L.gs' locally. The catch, as explained by @Dennis in [this post](https://codegolf.stackexchange.com/questions/5264/tips-for-golfing-in-golfscript), is that we need to trick Golfscript into using rational numbers instead of integers. So this works if you're willing to accept input `X1 Y1 X2 Y2` *in golfscript notation* ``` # L( (0,0) , (1,1) ) echo "0 0 1 1" | golfscript L.gs > 1/1 > 0/1 #L( (10,22.5) , (5,12.5) ) echo "10 22 2-1?+ 5 12 2-1?+" | golfscript L.gs > 2/1 > 5/2 ``` [Answer] ### Ruby – 48 characters Nearly identical to the JavaScript answer: ``` L=->u,v{a,b,c,d=*u,*v;[s=(d-b).fdiv(c-a),b-s*a]} ``` [Answer] # Python3 - 64 57 Bytes ``` def L(q,w):a=(q[1]-w[1])/(q[0]-w[0]);return a,q[1]-a*q[0] ``` You can get it down to 43 if you don't use Tuple, which many people are doing... ``` def L(x,y,q,w):a=(x-q)/(y-w);return a,y-a*x ``` [Answer] # PHP (75 chars) ``` function L($u,$v){return[$s=($v[1]-$u[1])/($v[0]-$u[0]),$v[1]-($s*$v[0])];} ``` test : `print_r(L([0,0],[7,1]));` output : ``` Array ( [0] => 0.14285714285714 [1] => 0 ) ``` (thanks @ace) ]
[Question] [ **The golf challenge is to encode and compress the following image inside a source file.** ![Image](https://i.stack.imgur.com/XDpDu.png) To do this you need to write 3 functions: `red`, `green`, and `blue` which accept x/y coordinates of the image and return the corresponding R/G/B pixel value between 0-255. Here is the C/C++ test code: ``` #include <stdio.h> #include "your_file" int main() { int x, y; for(y = 0; y < 32; ++y) for(x = 0; x < 32; ++x) printf("%i %i %i\n", red(x, y), blue(x, y), green(x, y)); } ``` And the output: <http://pastebin.com/A770ckxL> (you can use this to generate your image data) **Rules & details:** * This is a golf * Only your code/file is golfed - the test code is separate * The character set used is ASCII, however control characters in strings may only be used if escaped (like '\n' and '\r', etc) * Everything must be contained inside the source - no file loading * Your output must match the example output. This means loseless compression. **Languages:** The problem was written with C/C++ in mind, but I'm removing those restrictions. With that said, I'll still recommend using them. [Answer] ## C, 796 754 712 703 692 685 682 670 666 662 656 648 chars Changelog: * 754->712: Added `return` to the `#define`, replacing `if` with `?` statements (thanks @FUZxxl), removing `int` from the functions parameter list. * 712->703: Shameless copy from bunnit again :) Moved the whole image creation into the `#define` * 703->692: Merged `p[]` and `h[]`, some more `?:` improvements * 692->685: Incrementing `b` so `i` isn't needed anymore. `m=b` instead of `m=11` and `n<2e3` instead of `i<356` - these are close to undefined behaviour/memory corruption, but it seems I'm lucky :) * 685->682: `k` is now (32,16,8,4,2,1,0) instead of (5,4,3,2,1,0). Gotcha, D C ;) * 682->670: Split `p[]` and `h[]`, converted `h[]` to a `char*` - awwww, there's a sleepy kitty in it `^<+_=>-` * 670->666: `while` => `for`, `l=l*2+...` => `l+=l+...` * 666->662: `m=m>9?...` => `c[n++]=m>9?...` * 662->656: Reversed bit order in `b[]`, so we can map to 64-127 instead of 0-63 and don't need bit index `k` anymore. Thanks [@Piotr Tarsa](http://encode.ru/threads/1511-Small-just-for-fun-challenge-at-codegolf?p=28816&viewfull=1#post28816). Replaced `?:` (GCC extension) with `||`. Thanks [@JamesB](http://encode.ru/threads/1511-Small-just-for-fun-challenge-at-codegolf?p=28825&viewfull=1#post28825) * 656->648: Shameless copy from Shelwien :) (multi-character constants for `p[]`) Image is converted to a Base64-like string (ASCII 37-100), using huffman coding to encode colors 0-9 using 3-6 bits and a special color 10 (pixel is same as previous one) using only 1 bit. ``` #define P (x,y){for(;n<2e3;j/=2){j>1||(j=*b+++27);l+=l+(j&1);for(m=0;m<11;m++)l-h[m]+32||(c[n++]=m>9?c[n-1]:m,l=0,m=b);}return 255&p[c[x+y*32]] char*h="$^<+_=>-,* ",*b="F0(%A=A=%SE&?AEVF1E01IN8X&WA=%S+E+A-(,+IZZM&=%]U5;SK;cM84%WE*cAZ7dJT3R.H1I2@;a^/2DIK&=&>^X/2U*0%'0E+;VC<-0c>&YU'%],;]70R=.[1U4EZ:Y=6[0WU4%SQARE0=-XDcXd_WW*UAF&cFZJJ0EV*(a(P05S3IXA>51cH:S5SAE6+W%/[]7SF(153UM]4U()(53DA+J:]&5+5KX,L6>*4I,/UMBcML9WKLa9%UYIHKWW(9-*):(-ZW(9%T'N&9;C,C/Ea/Y7(JJ\\6CD9E,2%J*,ac]NIW8(M=VFac)/^)?IS-;W&45^%*N7>V,,C-4N35FMQaF,EaWX&*EJ4'";p[]={0,'R@+','aXL',7783255,'4k`',16354410,'NNv',5295994,4671418,9975021},c[1024],j,l,m,n;red P;}blue P>>16;}green P>>8;} ``` Copied two things from bunnit's answer, the `#define` and the whole image being decoded completely every time `red`/`green`/`blue` are called. There's some room for additional improvement, so expect some updates :) I'm not sure about code compliance, used GCC 4.6.1 to compile and test. Compression-wise, I think arithmetic coding would help as the distribution is pretty skewed, but maybe code overhead would be too heavy in this case. LZW also should do a very good job. Colors are quite local, so adaptive coding might be an idea. More readable 754 character version with some comments: ``` #define P 255&p[c[x+y*32]] // Base64 coded image bitstream, ASCII 37-100 // Huffman codes: 100, 111110, 11100, 1011, 111111, 11101, 11110, 1101, 1100, 1010, 0 char b[]="FYU%3+3+%B&E;3&HF1&Y1.JWXE83+%B=&=3)U]=.PP*E+%,('?B>?D*Wa%8&MD3P7dNbARIV1.Q[?4L9Qc.>E+EKLX9Q(MY%5Y&=?HC_)YDKE0(5%,]?,7YR+I@1(a&PO0+G@Y8(a%B23R&Y+)XcDXd<88M(3FEDFPNNY&HMU4UZY'BA.X3K'1DVOB'B3&G=8%9@,7BFU1'A(*,a(U-U'Ac3=NO,E'='>X]^GKMa.]9(*SD*^/8>^4/%(0.V>88U/)M-OU)P8U/%b5JE/?C]C9&4907UNN`GCc/&]Q%NM]4D,J.8WU*+HF4D-9L-;.B)?8Ea'L%MJ7KH]]C)aJA'F*24F]&48XEM&Na5"; // Colors, order GBR (one char shorter than all the others) p[]={0,5390379,6379596,7783255,3435360,16354410,5131894,5295994,4671418,9975021}; // Huffman codes for colors 0-10 h[]={4,62,28,11,63,29,30,13,12,10,0}; // Array for image data c[1024]; i,j,k,l,m,n; red(int x,int y){ while(i<356){ k--; if (k<0) { j=b[i++]-37; k=5; } l*=2; if (j&(1<<k)) l++; for(m=0;m<11;m++){ if(l==h[m]){ if (m>9) m=c[n-1]; c[n++]=m; l=0; m=12; } } } return P; } blue(int x,int y){return P>>16;} green(int x,int y){return P>>8;} ``` [Answer] ## Python (~~684~~ 592 characters) ``` red,blue,green=[lambda x,y,i=i:[15570996,2839104,7010700,5732035,6304875,0,12207943,8016079,7753294,5005656][int('eJxtkgGSxSAIQ6+kaLTe/2JLImj7Z9MZ6/gMIgjAzMbVWisGySRNm2ut5Hhx/2M0JMfHH5PWwo9x4mNO8pb6JkFM3hpqrR4+qY6eVK1mjlsFeSOBjPyCMy3348aXVRtq9X8czovMIwA5FeXKtGOcvfcf/lbvyW0n2BTOh122HiIH0g/uNrx47zupzMxuuTv808pZd3K7deJ/+PiH61AztmaNwPAsOnNGYovWIxswRill6vnAL4HgxDF17jFcjwRk/5b3Q1x1flLI9n64CIci8bmQe7NL8XoKliu+Jk/AR9rnjkwAYaDka8OXu/a+5NvvNzkcmqifL47H04kAz9M+9slKkDMGuOHi5PR7GZwv7MeApkz5JOSPHFVW3QTbzDJtzDIczkuWjeupLbckLyU5/gByftMg'.decode('base64').decode('zip')[32*y+x])]>>i&255 for i in 16,8,0] ``` Since this challenge is now open to all, why not! It's the familiar zlib -> base64 encoding route, so I apologize for that. Hopefully an entry with some semblance of ingenuity will be shorter! Here's a test snippet analogous to the original: ``` for y in range(32): for x in range(32): print red(x,y), blue(x,y), green(x,y) ``` [Answer] **C++, 631 chars; C - 613** A base-92 unary mtf coder, C++, 631 chars: ``` #define A(Z)int Z(int X,int Y){char*s="xdGe*V+KHSBBGM`'WcN^NAw[,;ZQ@bbZVjCyMww=71xK1)zn>]8b#3&PX>cyqy@6iL?68nF]k?bv/,Q`{i)n[2Df1zR}w0yIez+%^M)Diye{TC]dEY\\0,dU]s'0Z?+bo;7;$c~W;tvFl%2ruqWk$Rj0N[uP)fSjk?Tnpn_:7?`VbJ%r@7*MQDFCDo3)l#ln<kuRzzHTwCg&gYgSXtv\\m_Eb}zRK7JK<AZzOe}UX{Crk)SyBn;;gdDv=.j*O{^/q6)`lHm*YYrdM/O8dg{sKW#[[email protected]](/cdn-cgi/l/email-protection)#viYL$-<EU*~u5pe$r:`b)^dgXOJtf4";int*v,B=92,R=1,C=0,w[]={0,16354410,4671418,'aXL',7783255,5295994,'R@+','4k`',9975021,'NNv'};for(X+=Y*32+1;X--;)for(v=w;;){for(Y=*v++;R<B*B*B;C=C%R*B+*s++-35)R*=B;if(R/=2,C>=R){for(C-=R;--v>w;*v=v[-1]);*v=Y;break;}}return 255&Y A(red);}A(blue)>>16;}A(green)>>8;} ``` And the C version of above (613 chars): ``` #define A (X,Y){char*s="xdGe*V+KHSBBGM`'WcN^NAw[,;ZQ@bbZVjCyMww=71xK1)zn>]8b#3&PX>cyqy@6iL?68nF]k?bv/,Q`{i)n[2Df1zR}w0yIez+%^M)Diye{TC]dEY\\0,dU]s'0Z?+bo;7;$c~W;tvFl%2ruqWk$Rj0N[uP)fSjk?Tnpn_:7?`VbJ%r@7*MQDFCDo3)l#ln<kuRzzHTwCg&gYgSXtv\\m_Eb}zRK7JK<AZzOe}UX{Crk)SyBn;;gdDv=.j*O{^/q6)`lHm*YYrdM/O8dg{sKW#[[email protected]](/cdn-cgi/l/email-protection)#viYL$-<EU*~u5pe$r:`b)^dgXOJtf4";int*v,B=92,R=1,C=0,w[]={0,16354410,4671418,'aXL',7783255,5295994,'R@+','4k`',9975021,'NNv'};for(X+=Y*32+1;X--;)for(v=w;;){for(Y=*v++;R<B*B*B;C=C%R*B+*s++-35)R*=B;if(R/=2,C>=R){for(C-=R;--v>w;*v=v[-1]);*v=Y;break;}}return 255&Y red A;}blue A>>16;}green A>>8;} ``` Just to include an entry with base-95 data and arithmetic coding + adaptive statistical model. schnaader's code uses ~438 chars for data, and mine only 318 (311 w/o masking). But as expected, arithmetic coding is too complicated for a small sample like this. (This is 844 chars) ``` char* q="q^<A\">7T~pUN1 adz824K$5a>C@kC8<;3DlnF!z8@nD|9D(OpBdE#C7{yDaz9s;{gF[Dxad'[oyg\\,j69MGuFcka?LClkYFh=:q\\\\W(*zhf:x)`O7ZWKLPJsP&wd?cEu9hj 6(lg0wt\\g[Wn:5l]}_NUmgs]-&Hs'IT[ Z2+oS^=lwO(FEYWgtx),)>kjJSIP#Y?&.tx-3xxuqgrI2/m~fw \\?~SV={EL2FVrDD=1/^<r*2{{mIukR:]Fy=Bl.'pLz?*2a? #=b>n]F~99Rt?6&*;%d7Uh3SpLjI)_abGG$t~m{N=ino@N:"; #define I int #define F(N) for(i=0;i<N;i++) #define Z C=(C%T)*B+(*q++)-32 enum{B=95,H=1024,T=B*B*B};I p[B],v[B+H],n=3,*m=&v[B],R=T*B,C,i,j,y,c,x,w;void D(I P){w=(R>>11)*P;(y=C>=w)?R-=w,C-=w:R=w;while(R<T)R*=B,Z;}struct u{u(){F(4)Z;F(B)p[i]=H,v[i]=0;F(H){v[0]=m[i-1];v[1]=m[i-32];j=i;F(n){I&P=p[i];D(P);if(y){P-=P>>4;c=v[i];goto t;}else P+=H+H-P>>4;}c<<=7;for(x=-255;x<0;x+=x+y)D(H);v[n++]=c=x;t:m[i=j]=c;}}}d;I red(I x,I y,I z=0){return m[y*32+x]>>z&255;} #define blue(x,y) red(x,y,8) #define green(x,y) red(x,y,16) ``` Tests (from earlier base-96 version): <http://codepad.org/qrwuV3Oy> <http://ideone.com/ATngC> Somehow SO eats 7F codes, so I had to update it to base=95 [Answer] ## C++ - 1525 1004 964 chars ``` #define e (int x,int y){for(i=g=0;i<702;i=i+2)for(j=48;j<d[i];++j)c[g++]=d[i+1]-48;return 255&z[c[x+y*32]] int i,g,j,z[]={0,7010700,12207943,5005656,5732035,8016079,2839104,6304875,15570996,7753294},c[1024]; char*d="3031;23322337261524453223310625132101214103453101233722172643310323342102521229492333210352112241036141014821042552621241014161016141024121022103210151015104526211034361034726510352625107441:530855425201511551045378554>55755312410242035201510528725212044451015411032:73135216561321012171017101725313581125152572531358122415257257110213310131231422022172025105110315322103210623815203110113053521053223817506920721013361322282530991062101213361322282520491049682224133614121028101510291029;812341023342835694810582018841018356978194810842835193329781019482410542835192310193668399428454319362928102829843845331019263028101330441014382035104369285338101810284536334910291018534820283546891019102943883536"; int red e>>16;} int blue e>>8;} int green e;} ``` Created an array z which stores all of the possible colours as a single integer.(r<<16 | g<<8 | b). Created an array d which stores {amount, value}, the value is the position in the array z, the amount is the number of consecutive pixels with that value.(i.e 3,0, means colout t[0] appears the next 3 pixels. The actual array of pixels(c) is then calculated every time red is called. The value in the array is then right shifted and ANDed as necessary to get the correct component. I could probably save a few more characters(~50) by taking more patterns out of the array as defines. **Edit 1** - changed the d array for a char array with each value offset by 48, which means I can represent it as a string saving a load of commas. **Edit 2** - Took a larger portion of the functions out in the define statement. [Answer] # Javascript, ~~696~~ 694 chars Thanks to schnaader for 696 -> 694. I figured a different encoding format, which essentially is [Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) with a color lookup table. It works quite nice, because there are less than 16 colors and they apear less that 16 times in a row; so every pixel definition including length fits into one byte. I put the color in the high part of the byte and the count in the low part. In the end, the base64 string turned out to be longer than I had expected (472 chars), but the decoding program is really short. ``` for(b=i=a=[];a&15||(a=atob("AxMrMyIzJxYlRDUiMwEmFSMBIUEBQzUBITMnEidGMwEjMyQBUhIi SSkzIwFTEiFCAWNBAUEoASRVYhJCAUFhAWFBAUIhASIBIwFRAVEBVGISAUNjAUMnVgFTYlIBRxRaA1hF UgJREVUBVHNYRV51VRNCAUICUwJRASV4UhICRFQBURQBI3oTUxJWFiMBIXEBcQFxUhNTGCEVJXVSE1MY IhQldVIXARIzATEhEyQCInECUgEVARM1IgEjASaDUQITAREDNSUBNSKDcQWWAicBMWMxIoJSA5kBJgEh MWMxIoJSApQBlIYiQjFjQSEBggFRAZIBkoshQwEyQ4JTloQBhQKBSAGBU5aHkYQBSIJTkTOShwGRhEIB RYJTkTIBkWOGk0mCVDSRY5KCAYKSSINUMwGRYgOCATEDRAFBgwJTATSWgjWDAYEBglRjM5QBkgGBNYQC glNkmAGRAZI0iFNjAQ==").charCodeAt(i++));b.push([0,16354410,4671418,6379596,77832 55,5295994,5390379,3435360,9975021,5131894][a-- >>4]));green=(red=function(c,d){ return b[32*d+c]>>this&255}).bind(16);blue=red.bind(8) ``` Note: I split up the code to have a little readability. It needs to be on one line to run. Test code: ``` for(var y = 0; y < 32; ++y) { for(var x = 0; x < 32; ++x) { console.log(red(x, y), green(x, y), blue(x, y)); } } ``` I think the example result is actually the output of red, green, blue (not red, blue, green like in the original test code); it works for me like that anyway. [Answer] ## C++, 1357 chars ``` int i,j,C[]={0,0,0,106,249,140,186,71,71,76,97,88,87,118,195,122,80,207,43,82,64,96,52,107,237,152,52,118,78,78},E[]={30,31,112,33,22,33,72,61,52,44,53,22,33,10,62,51,32,10,12,14,10,34,53,10,12,33,72,21,72,64,33,10,32,33,42,10,25,21,22,94,92,33,32,10,35,21,12,24,10,36,14,10,14,82,10,42,55,26,21,24,10,14,16,10,16,14,10,24,12,10,22,10,32,10,15,10,15,10,45,26,21,10,34,36,10,34,72,65,10,35,26,25,10,74,41,105,30,85,54,25,20,15,11,55,10,45,37,85,54,145,57,55,31,24,10,24,20,35,20,15,10,52,87,25,21,20,44,45,10,15,41,10,32,107,31,35,21,65,61,32,10,12,17,10,17,10,17,25,31,35,81,12,51,52,57,25,31,35,81,22,41,52,57,25,71,10,21,33,10,13,12,31,42,20,22,17,20,25,10,51,10,31,53,22,10,32,10,62,38,15,20,31,10,11,30,53,52,10,53,22,38,17,50,69,20,72,10,13,36,13,22,28,25,30,99,10,62,10,12,13,36,13,22,28,25,20,49,10,49,68,22,24,13,36,14,12,10,28,10,15,10,29,10,29,118,12,34,10,23,34,28,35,69,48,10,58,20,18,84,10,18,35,69,78,19,48,10,84,28,35,19,33,29,78,10,19,48,24,10,54,28,35,19,23,10,19,36,68,39,94,28,45,43,19,36,29,28,10,28,29,84,38,45,33,10,19,26,30,28,10,13,30,44,10,14,38,20,35,10,43,69,28,53,38,10,18,10,28,45,36,33,49,10,29,10,18,53,48,20,28,35,46,89,10,19,10,29,43,88,35,36,10};int*Q(int n){for(i=0;1;i++){for(j=0;j<E[i]/10;j++){if(!n)return&C[E[i]%10*3];n--;}}} #define red(x,y) Q(x+32*y)[0] #define blue(x,y) Q(x+32*y)[1] #define green(x,y) Q(x+32*y)[2] ``` Deobfuscated a bit: ``` int C[]={0,0,0,106,249,140,186,71,71,76,97,88,87,118,195,122,80,207,43,82,64,96,52,107,237,152,52,118,78,78}, int E[]={30,31,112,33,22,33,72,61,52,44,53,22,33,10,62,51,32,10,12,14,10,34,53,10,12,33,72,21,72,64,33,10,32,33,42,10,25,21,22,94,92,33,32,10,35,21,12,24,10,36,14,10,14,82,10,42,55,26,21,24,10,14,16,10,16,14,10,24,12,10,22,10,32,10,15,10,15,10,45,26,21,10,34,36,10,34,72,65,10,35,26,25,10,74,41,105,30,85,54,25,20,15,11,55,10,45,37,85,54,145,57,55,31,24,10,24,20,35,20,15,10,52,87,25,21,20,44,45,10,15,41,10,32,107,31,35,21,65,61,32,10,12,17,10,17,10,17,25,31,35,81,12,51,52,57,25,31,35,81,22,41,52,57,25,71,10,21,33,10,13,12,31,42,20,22,17,20,25,10,51,10,31,53,22,10,32,10,62,38,15,20,31,10,11,30,53,52,10,53,22,38,17,50,69,20,72,10,13,36,13,22,28,25,30,99,10,62,10,12,13,36,13,22,28,25,20,49,10,49,68,22,24,13,36,14,12,10,28,10,15,10,29,10,29,118,12,34,10,23,34,28,35,69,48,10,58,20,18,84,10,18,35,69,78,19,48,10,84,28,35,19,33,29,78,10,19,48,24,10,54,28,35,19,23,10,19,36,68,39,94,28,45,43,19,36,29,28,10,28,29,84,38,45,33,10,19,26,30,28,10,13,30,44,10,14,38,20,35,10,43,69,28,53,38,10,18,10,28,45,36,33,49,10,29,10,18,53,48,20,28,35,46,89,10,19,10,29,43,88,35,36,10}; int*Q(int n){ for(int i=0;1;i++){ for(int j=0;j<E[i]/10;j++){ if(!n)return&C[E[i]%10*3]; n--; } } } #define red(x,y) Q(x+32*y)[0] #define blue(x,y) Q(x+32*y)[1] #define green(x,y) Q(x+32*y)[2] ``` `C` contains the RGB values for the ten distinct colors of the image. `E` contains the data for the picture, where each element `E[i]` encodes both a repeat count `E[i]/10` and a color index `E[i]%10`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~602~~ 584 bytes -18 bytes thanks to ceilingcat. ``` X[1024],*i,r,w,*I; #define u(d)(x,y){i=X;for(I=L"56s-8-8_TKCL-8!UJ7!#%!9L!#8_,_W8!78A!0,-us87!:,#/!;%!%i!AN1,/!%'!'%!/#!-!7!&!&!D1,!9;!9_X!:10!a@v&5lM0+&\"N!D<lMvNPN6/!/+:+&!Kn0,+CD!&@!7x(6:,XT7!#(!(!(06:h#JKP06:h-@KP0^!,8!$#6A+-(+0!J!6L-!7!U=&+6!\"5LK!L-=(I\\+_!$;$-305z!U!#$;$-30+H!H[-/$;%#!3!&!4!4y3#9!.93:\\G!Q+)k!):\\e*G!k3:*84e!*G/!M3:*.!*;[>u3DB*;43!34k=D8!*153!$5C!%=+:!B\\3L=!)!3D;8H!4!)LG+3:Ep!*!4Bo:;!";w=*I-33,*I++;)for(r=w/10+1;r--;*i++=L"\0\x6a8cf9\xba4747\x4c5861\x57c376\x7acf50\x2b4052\x606b34\xed3498\x764e4e"[w%10]>>d&255);x=X[y*32+x];} red u(16)green u(8)blue u(0) ``` [Try it online!](https://tio.run/##PVL9T9swEP29f4WvaUocO8SpncSNCeKjUykNFZNAq1Szqh8pi2AFhZWmQ/ztnQPbdCfdO73TuyfdLbz7xWK/H08C1hF31C1oSbfUHaiGtcxXxTpHG2eJnYru8FuRjtXqqXQGadYMoxdPenJ6MzzPPAm3lzFYNnQzsOSUTr9JiOUpMOptXmQMCbV8UDbYBZyOAuqDfQAHNvgWeBBD20QvoNBV0J2OIQkYzE5e2@HjFSNt3RxB7@jx6nV0PYp88ElC2jBcM0rOe9A@gbhyooSOb8x6B0ywKPlhXQ6v6@qdmPodqISWFZ0SzyEMLiHK6qW3aZtEoJthNoTMS52B1mQKLdXyOAt/wy1Yn5hcwMXE81vKtoAbowLEjltdOOzyROs@fCX4AbCBuduHB564UuTg9n24MvgQXDU53vDemasEBy4e0p4ENwg5tMJzsFOSwJnWPEsBA@8peWH0cdYnPPnyDC6Is6dEQVNtU3fgcW7OQojC9QnKdOsHjASq9DzlFoSYk2imq2gmF6uuruYzEYtYV2IRyijQVRgveBzpKp4tVqGZ68wFCztmnkVzLnSVL7noSsNHIhd5c7K1A3Z3fLxsd8IQqyodT3Yu75DqTr03ynxpniKI8H2Z52sDJZ4/bupHYXhfrH@hn7Ni7WD01kCobiuKdsrg2vcOpYgptENHiHcUImSH/zLVJ1P9Z6qaQei5NBorp2kX6CP1ukmRseDUspiievU//GHos8Gq8b7/Aw "C (gcc) – Try It Online") [Answer] # Python 3 (589 characters) ``` import base64,zlib red,blue,green=(lambda x,y,i=i:b'\xed\x984+R@j\xf9\x8cWv\xc3`4k\0\0\0\xbaGGzP\xcfvNNLaX'[zlib.decompress(base64.decodebytes(b'eJxtkgGSxSAIQxWN1vtfeEkEbf9sOmMdn0EEAZjZuFprxSCZpGlzrZUcL+5/jIbk+Phj0lr4MU58zEneUt8kiMlbQ63VwyfV0ZOq1cxxqyBvJJCRX3Cm5X7c+LJqQ63+j8N5kXkEIKeiXJl2jLP3/sPf6j257QSbwvmwy9ZD5ED6wd2GF+99J5WZ2S13h39aOetObrdO/A8f/3AdasbWrBEYnkVnzkhs0XpkA8YopUw9H/glEJw4ps49huuRgOzf8n6Iq85PCtneDxfhUCQ+F3JvdileT8FyxdfkCfhI+9yRCSAMlHxt+HLX3pd8+/0mh0MT9fPF8Xg6EeB52sc+WQlyxgA3XJycfi+D84X9GNCUKZ+E/JGjyqqbYJtZpo1ZhsN5ybJxPbXlluSlJMcf++8TIA=='))[32*y+x]*3+i]for i in(0,1,2)) ``` Test code ``` for y in range(32): for x in range(32): print(red(x,y), blue(x,y), green(x,y)) ``` Based on solution from Dillon Cower [Answer] # PHP (5.4) - 822 I've done this **deliberately not using** any of the **built-in compression functions**. This solution is not finished, I'm not sure if I've given up, I can see areas for improvement but I can't find the time/willpower to refactor the whole thing at the moment, so I'm posting what I have so far. Newlines + comments to be removed for 822 bytes. ``` // Colour map $c=[0,16354410,4671418,6379596,7783255,5295994,5390379,3435360,9975021,5131894]; // Optimised RLE map $r=array_merge(array_diff(range(10,89),[27,40,47,56,59,60,63,66,67,70,73,75,76,77,79,80,83,86]),[92,94,99,105,107,112,118,145]); // Image data (base 70) $e="CDsF<Fd]WPX<F0^VE0240GX02Fd;d_F0EFN0?;<onFE0H;2>0I404h0NZ@;>0460640>20<0E05050Q@;0GI0Gd`0H@?0eMqCjY?:51Z0QJjYu[ZD>0>:H:50Wk?;:PQ05M0ErDH;`]E0270707?DHg2VW[?DHg<MW[?c0;F032DN:<7:?0V0DX<0E0^K5:D01CXW0X<K7Ub:d03I3<A?Cp0^023I3<A?:T0Ta<>3I420A050B0Bt2G0=GAHbS0\:8i08Hbf9S0iAH9FBf09S>0YAH9=09IaLoAQO9IBA0ABiKQF09@CA03CP04K:H0ObAXK080AQIFT0B08XS:AHRm090BOlHI0"; // Expand image data for($i=0;$i<352;$i++){$b=$r[ord($e[$i])-48];$l=(int)($b/10);while($l--)$d[]=$c[$b%10];} // Colour retrieval functions function red($x,$y){global$d;return$d[$x+$y*32]&0xff;} function green($x,$y){global$d;return$d[$x+$y*32]>>8;} function blue($x,$y){global$d;return($d[$x+$y*32]>>8)&0xff;} ``` Test stub: ``` for ($y=0;$y<32;$y++) { for ($x=0;$x<32;$x++) { printf("%d %d %d\n", red($x, $y), blue($x, $y), green($x, $y)); } } ``` The compression of the image data itself is pretty good, but the functions to retrieve RGB values take up 1/4 of the code. I'm using a custom base70 + run length encoding mechanism. 1. There are 10 unique colours 2. Colours have run lengths between 1 and 14 (12 used). 3. There are 120 possible combinations. 4. There are only 70 *unique* run/colour combinations actually used. The encoded image data references the array index of an RLE, which in turn indexes the array of colours. I'm not sure how much overhead this adds or subtracts over directly referencing the colours. Sine there are 10 colours (0 to 9), RLEs are stored as `run_length * 10 + colour_index`. Giving a range of encodings between 10 and 145 without experimenting with optimisations based on colour ordering. (i.e. I could make the range 19 to 140 by moving colours 0 to 5, 5 to 9, and 9 to 0 - but this may have other knock-on effects) A previous answer states their encoded data is 472 bytes. My encoded image data is 352 bytes, but the intermediate RLE / colour map (which is not binary encoded) is a further 129 bytes, putting the total at 481. (as well as additional overhead for joining up the two). However I suspect my method might scale better for larger images. **TODO:** 1. Investigate binary encoding of RLE map 2. Find a way of reducing the size of the functions. `global` is a bitch, but can't access character indexes on constants. 3. Experiment with colour index ordering to see if RLE map size can be reduced with longer sequential runs of numbers 4. Potential 64bit specific optimisations of colour map? (r0 << 56 | r1 << 48 | ...)? 5. Experiment with vertical RLE to see if it results in a more compact set of encodings. 6. Area encoding? [Answer] # [Julia](http://julialang.org/), 636 bytes Zlib compression is not part of standard libraries, so I only used Base64 encoding ``` using Base64 red,blue,green=[(x,y,d=base64decode)->d("AAAAavmMukdHTGFYV3bDelDPK1JAYDRr7Zg0dk5O")[3vcat([fill(div(i,16),i%16) for i=d("AxMrMyIzJxYlRDUiMwEmFSMBIUEBQzUBITMnEidGMwEjMyQBUhIiSSkzIwFTEiFCAWNBAUEoASRVYhJCAUFhAWFBAUIhASIBIwFRAVEBVGISAUNjAUMnVgFTYlIBRxRaA1hFUgJREVUBVHNYRV51VRNCAUICUwJRASV4UhICRFQBURQBI3oTUxJWFiMBIXEBcQFxUhNTGCEVJXVSE1MYIhQldVIXARIzATEhEyQCInECUgEVARM1IgEjASaDUQITAREDNSUBNSKDcQWWAicBMWMxIoJSA5kBJgEhMWMxIoJSApQBlIYiQjFjQSEBggFRAZIBkoshQwEyQ4JTloQBhQKBSAGBU5aHkYQBSIJTkTOShwGRhEIBRYJTkTIBkWOGk0mCVDSRY5KCAYKSSINUMwGRYgOCATEDRAFBgwJTATSWgjWDAYEBglRjM5QBkgGBNYQCglNkmAGRAZI0iFNjAQ==")]...)[32y+x+1]+c] for c=1:3] ``` [Try it online!](https://tio.run/##VVJRb5swEH7vr0CRJiUqq8LSdFKlTLLBUBNBZhubulUeKFBjIKRKmobkz2cmD9N2ki3f57v77uyvPrQ6c/rL5bDXnbJgti8f7m92ZWG/tYfSVruy7Bav494@2cXi7XpblPm2KCfffxXjETCWfW2iQ1M8JYEvxezNK1vv99IJgfTo7ueLmhbNfDWavM6@8uxz/Pqu23Zc6K@xtp2Hia2/md163@4svRjq9dEuOuFz2MuWelxHR7TxWQQxR5CcOcRJ1CFdBAavoxOBvMKaseaMj36CtO@CNIaAoy1gVMgqdAH3K5D6BsMVYBiaOAoEgiLADPC4BjzqhPIT2WJIe5oBp/K5CikSHIqnWFIxdwSNTR3s8mNIARP3htOlvuGmBOLZNuF9mPra9PiMYE78nldxErhIhM@CISeSuCJtIfAzoPgMElShE3Fxh1yukAA0crBCNWCZxwlOAEVezDiM2dLLSZoCncMojXq8DRmYNzBUqPrrfxDYYqlJ7deEIaiUme0Fw2a7r8jRsNyHSbslsCJLyEAA@Tx7aiSBDIdJk6xYdQxohczccvBNXroKmunGFR6jcr50gVwyhmMemTipVq7p3aPAh@oYJiBhqapTD0jD29I6mhPYqADGkriqjZsNCIZepto3b0wWi9FkfXd3Z0Tw43Tb3zrr23x9/fR84TzO1pfheLJ0Z00fZ86NZWxA@v@QwT52uvtsu7HR5yDJiW2NrJFtDVL917@q9gpMrqllV9yYdfkD "Julia 1.0 – Try It Online") Un-golfed version: `colors` contains the 10 unique colors `color_enc` contains the color number (0-9) in base16 + the amount it should be repeated (1-14) in base 16 `color_dec` rebuilds the whole image with color numbers (0-9) ``` using Base64 colors = "AAAAavmMukdHTGFYV3bDelDPK1JAYDRr7Zg0dk5O" color_enc = "AxMrMyIzJxYlRDUiMwEmFSMBIUEBQzUBITMnEidGMwEjMyQBUhIiSSkzIwFTEiFCAWNBAUEoASRVYhJCAUFhAWFBAUIhASIBIwFRAVEBVGISAUNjAUMnVgFTYlIBRxRaA1hFUgJREVUBVHNYRV51VRNCAUICUwJRASV4UhICRFQBURQBI3oTUxJWFiMBIXEBcQFxUhNTGCEVJXVSE1MYIhQldVIXARIzATEhEyQCInECUgEVARM1IgEjASaDUQITAREDNSUBNSKDcQWWAicBMWMxIoJSA5kBJgEhMWMxIoJSApQBlIYiQjFjQSEBggFRAZIBkoshQwEyQ4JTloQBhQKBSAGBU5aHkYQBSIJTkTOShwGRhEIBRYJTkTIBkWOGk0mCVDSRY5KCAYKSSINUMwGRYgOCATEDRAFBgwJTATSWgjWDAYEBglRjM5QBkgGBNYQCglNkmAGRAZI0iFNjAQ==" color_dec = vcat([fill(i÷16, i%16) for i in base64decode(color_enc)]...) red,blue,green=[(x,y)->base64decode(colors)[3*color_dec[32y+x+1]+c] for c in 1:3] ``` [Try it online!](https://tio.run/##ZVLRbtowFH3nKyKkSbCyiozSSZWYZCdO6qCE2Y6TughVNMkcJyGpoJTAj@0D9mHMYVO1aVfywzm6x@dc@xb7Sq3N9nze71QtDbjeZbc3vV7SVM12Z8yMPtC1ftv4@zK9D11HRJNnO6vsb3PTA8Km2y@PcpyW00X/t@Ypq5OLrPW3/hGfvFZU1ObKP6CNw3yIOYLkxCEO/Rqp1NV84R8J5DlWjJUnfHBCpBwLxAEEHDWA0UjkngW4k4PY0RzOAcNQ91EQIRi5mAEeFID7dSSdUFQY0paugZk7XHoURRxG94Gg0dSMaKDvwRY/eBSw6EZ7WtTR3pRAPGlC3nqxo3TGBwQT4rQ8D0LXQpH3EDFk@gLnpEoj/AAoPoEQ5ehILFwji0sUAeqbWKICsLXNCQ4BRXbAOAzY3E5IHAOVQD/2W9x4DExL6EmUv@MXAissFCmcgjAEpdSzPWJYNrucHLTLjRdWDYE5mUMGXMin6/tSEMiwF5bhguUHl@ZIzy06rHXxwi3HGyuyGRXTuQXEnDEccF/3CbmwdHabAgfKgxeCkMWyiG0gtG9FC39KYCldGAhiySooN8DtsoyVo9@YzGb9P7vxlGbdP78l69fB8ruqqoH6@cO8HRnqg3k7NL43W0MZqjaeLwulm5s0G7xvyHB1fX097PW2WTp6rvbZSG6zrJ4tB@3oOPz09X/RbricfHw3Xk4@H6/aK3N1lawuVklnZd5NVucOHTs0vpuYPUNXx7T/MF29bFX9WtUDneBiOjL6Rn9kdGH@xpdcF2J4kWZ12tPn/As "Julia 1.0 – Try It Online") Test code: ``` for y in 0:31 for x in 0:31 println(red(x,y), " ", blue(x,y), " ", green(x,y)) end end ``` ]
[Question] [ Katlani is a constructed language being designed in [chat](https://chat.stackexchange.com/rooms/133067/tnb-conlang-katlani). In this challenge, your goal is to print the largest dictionary of katlani nouns possible in 400 bytes or less. ## Task In 400 bytes or less, your program should print a list of katlani nouns. You can choose to output them as a list/array in your language, or as a string with any (not necessarily consistent) non-alphabetical separator, such as newlines or commas. The capitalization and sorting of the words does not matter. Words not in the list are not allowed in the output, but duplicates are. **The list of nouns you may choose from are:** ``` abail abikis ak akniton alfabit atirsin atom ats aypal baka baklait banl bgil bianto bit bo boraky borsh bot br brbrno byt daosik diga digiz dogo dolmuk dongso douv drarkak fa fafasok fasmao fidr floria fridka friv fully fylo fyrus gilmaf gogu gogzo gongul gorlb gosio gratbt gutka hisi horrib hurigo inglish iomshuksor isa ispikar isplo ita iushb izlash kaikina kat katisas katlani kfaso khalling kisongso kivsk klingt kod koik kolbat komy konma korova koss kotsh kris kromir ksik ksuz ktaf ktomish ktomizo la lan lgra loshad lyly mak makanto makav makina marinolus marta matiks mim mimhis mingso mitsh molo mosdob motif motkop movogal muratsh mutka naita ngoirfo nidriok nilo nin nini ninibr nirus noguna nolif nors o ogig omkop onion opru orilha orni ozon papin paslo pasrus pirishy pluban polr posodo pouk produty rak raznitsa rigiks rilifior riomr rno ronta rus ryby sabbia sai sakar saman sandvitsh sasa sfiny shatris shidoso shilan shimshoom shor shotiya shuan shubhu shuksor shuriok shutis shutrak shyba sibas sibin simriomr sod sokit spamra spamt srirad sutka taika tipstor tizingso tksu tobl tokvod tomp tonfa toto totobr tshans tshimiso tshomp tura tuvung uboiak umub vaf vintz voda vodl vontark y yntsh zimdo zivod zombit zorliplak ``` ## Scoring The winner (per language) is the answer that can print the largest number of unique words from the dictionary. Ties are broken by byte count, so if two answers manage to print all 200, the shorter of the two will win. [Answer] # JavaScript (ES6), 400 bytes, 104 words ``` _=>`oï�ño�÷� ��¯�¯�¯9�:�@¯p_�O��S_ÀOÅoË��? hñ���WñÓÖÛò9?F4ôhïF�ôÃ�I4÷Ü�~~øgoSvõ5?VÉöÓßlSüáï��ù&Ϥ�úa¦¦ú¼�¸±ð�7ñl�ýlqýi6ýº@ó¹!ôe�ôj�ø� ø:�øº@õ� õ<¹öSeü6�üe ù��ù��ù+�ù.�ù1 ù15ùd:ùº@ú�@þZ�ð�C���¦ñl�ï��VýeÛÜ �òlÃ�+ÃÖôs]¯Fq ôÆ�Ï�CPø 4���9ø5ÙoSS�õmµ�l7 ü=4���0ù#p_�±+ù+£�¦¦�ú���±c�ðE:eð£É5ñ�p:ó]s�`.replace(r=/./g,x=>x.charCodeAt().toString(16).padStart(2,0)).replace(r,y=>"abhiknolmsturgy,"[+("0x"+y)]) ``` Almost certainly going to get mangled due to all the weird Unicode, but this uses a string of bytes, which if represented with an extended ASCII code page (like the one HTML defaults to) would be exactly 290 bytes. The other 110 are a decoder, which split each byte into 4-bit nibbles, and map them to one of 15 letters or a comma. The problem is, this is exactly 400 bytes, leaving no room for backslashes in the string. JS is pretty good at ignoring control characters and stuff in strings, so all I need to worry about is `\0` (NUL), `\r` (which is mangled by newline conversion), ```, and `\`. I could sacrifice a few words, and escape these with `\`, but that seemed like a bit of a waste. The solution I came up with was figuring out the representation of these four characters as nibbles (`00`, `0d`, `5c`, and `60`), and all of the pairs of letters in the words that never appeared beside each other. Then, I could map those letter pairs to the bytes I didn't want to appear. I ended up with `a` for `0`, `g` for `d`, `n` for `5`, `r` for `c`, and `o` for `a`. since `aa`, `ag`, `nr`, and `oa` never appear in the list of 104 words I chose. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 399 bytes, 96 words Simple zlib compression with base-64 encoding. Returns a single string of words separated with `_`. ``` _=>require('zlib').inflateRawSync(Buffer("HY+BCgQhCEQ/dTBiOylz0TrY/fqbDppnipYjHbLciESRLsQcKE0JXSjOE/khmQTKs1C1Cao3J2bLE/YXl+DSGrhCK59hYG2P8eB6hhOxE83bPnidjFHIVN734sjHI7RAU6ibM7oEXRa6V0o7YQ8xjXUP/56QSSxu2EN5zdOW+0VfcmEIz8RoITDpVPBNU6POjDm/MV/db9h/iamsTJ1H+gddTx96kZFweNMGtzPiU33C79jwYLu/TG8fQeyO4I+hboGYjuM/RakuQRoXS6HZpHFil89meAorWoTNtJ23GHc/YWHRGJaXQdhNLP+DG9KMzMS2XfD1KgcDD1616iTTHw","base64"))+'' ``` [Try it online!](https://tio.run/##ZdHJkppAAIDhe57C8gIUiS2gCJkyVcMiuLCjwlymWBpoBJphicrLm7nn@td3@8vob9QnHWqHXw1O4Svbvj63fzr4NaIOksRUoZigFqjJqmiAbnT3nk1CSmOWwY6c6yEtyblTyKoDUl9C1rOaln4XguwrVtq2QW1Y6vEpQarnnnonOarLQ@CVlgpuRe34x56RGTnC3IGNTyoIg4pWPK0r5ONaLEKNtQUo8UVhPVSBi@0GpeVO31/MDbfqS32/cd/PPIqNDVYDN@IvS7wJHeFRBmcbrHnH8x4jq5rrKbWu9PKSJbW6nwQX732lvdiSeeZtq1RqYFxAGosFQFHd@wdGp/M09R8if/vY3aFpaMNkozPHyRuxvIenEfiakDnwaa32dBFjLSxHA7jRbXRcHHi8/tHqO1QJYg3fcXfFvjkcWE7TExBedVc7RIGTFubJphVNPBqT4bFBpjDHPFEUhmd45Pv6ff5zHkc95FdziqIJ4tXBfradZST19iPBTY8ruKhwTn7nRd9WaCCJz@9FFWzyoZjRM2J2x13a/yb@99Tb6x8 "JavaScript (Node.js) – Try It Online") ### How? This is the result of a random search where each iteration keeps a word \$W\$ of length \$L\$ if a random value \$k\in[0\dots1]\$ satisfies: $$ k>\frac{(L-1)^2}{30} $$ This is really just a guesstimate that keeps all one-letter words, discards all words of more than 6 characters and uses probabilities between 17% and 97% in between. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 400 bytes, 139 words [Try it online!](https://tio.run/##JVNLkiUhCLxLr3oWc4K5RB/gbbArqiRUqACtiHqXryF5CzNFAfn5W8l@lfrz/BjL/P6iQtxfQi3W1AH0gPukOC3UCCjYH9ArTDIVPAOwUfMKgmxYxQTndxxsfFAiv4P0UGAfq4Hl8JTX9ZKdsHxQnOy8hZ/deMPjwbhfvd9Bd4fCbStiPPRYiW8FWS8gZ0hGs8T7x5rwUdk5cBkjAnYCnHDFE/vlNWz53QmpNArLFtHEfePLI9imG4Bz20sq6LiBMghkeiW7A2f6MYbgaeUrKtAm7S/phCUBEWbgjcwGGhBAVxILgW0mTW7hafBIqJxCvjEUWQz1TQt48p7U9Az@ZC@UWQpDVVgS@IPomHCWU7TDWKKfLzRQDz4CR7pSYQ1DPS1Krsa9Ehhu9I2bk05OcrwSlD7PvgoyPbUb0HXDrWIADBlHRzI3Yx2hkZNjKog3HdhdojhOJeYOzIBGBhrw7IRu@s4CvcpZWK8Kjbo@wip1JU9UzutdYMKFPAlxOxrs2jDVftJAY8AQP1WcxEnRyUAtHdgu2MW3OYE5xVPxPYCobTSJJJ6ZCx7XWNGlC0MQhpQYfu6vP/@e5/l79f8 "Charcoal – Try It Online") Link is to verbose version of code. Just a compressed string based on @ovs's Bubblegum word list, except deciding which nine words to drop was interesting to say the least, as deleting some words actually increases the byte count! [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~147~~ ~~148~~ 149 words, 400 bytes ``` 00000000: 15cc 810a c520 0885 e157 3dc6 5893 4a87 ..... ...W=.X.J. 00000010: d685 f6f4 f704 f9fd cd41 b25f e990 227a .........A._.."z 00000020: d4a6 0999 3e08 2f0d 459a 10eb 2855 898a ....>./.E...(U.. 00000030: 4d67 260a e321 6d9f e443 b9db 9ce0 2961 Mg&..!m..C....)a 00000040: 8e4b ab7e 47c1 e5d5 89d5 3c59 3fdc c293 .K.~G.....<Y?... 00000050: 431c 77e8 d5e4 845b bd02 f7ea 7de3 dedd C.w....[....}... 00000060: 49ac 44f5 ba0e 9f53 abab 33d1 0b4d e56a I.D....S..3..M.j 00000070: cd26 7834 158f 4768 814e 81e6 99b7 3b74 .&x4..Gh.N....;t 00000080: e5c3 ddd7 251f 3499 685d ad32 7e71 b491 ....%.4.h].2~q.. 00000090: b149 2f32 99f0 9f30 368e 331f 9a89 163e .I/2...06.3....> 000000a0: 3418 e53d b591 f5a1 4db9 d185 c7d0 6bf0 4..=....M.....k. 000000b0: b2fb c690 7646 7e47 3561 6252 1d8f e609 ....vF~G5abR.... 000000c0: c76a 3a73 de1f de9d e4e5 8599 cddf 13bd .j:s............ 000000d0: 31d6 6c02 139d 54bb 133b a338 9460 6225 1.l...T..;.8.`b% 000000e0: cceb 3261 bade 3412 0eaf 5ae1 e3bc e5a6 ..2a..4...Z..... 000000f0: 6ef0 3716 3cb4 3fc2 98c2 3f6e 5f79 f598 n.7.<.?...?n_y.. 00000100: e79d b7af 22fc f2f4 cb99 1e64 3584 70b4 ...."......d5.p. 00000110: 6a4b c647 20cc 116e 5310 8bbb 5d36 524a jK.G ..nS...]6RJ 00000120: 5161 94d3 24e8 10a3 c9e5 adb6 918f 7631 Qa..$.........v1 00000130: c683 2cb1 6379 d6c9 d464 7611 a416 c9a3 ..,.cy...dv..... 00000140: 1ad2 9b4e 7a21 5f19 2138 e122 3484 bb35 ...Nz!_.!8."4..5 00000150: 9b60 8a1e 5b2e 4c2f 9db4 9f5f cc78 89dd .`..[.L/..._.x.. 00000160: 42a7 e350 0233 1fb1 3cf1 f37f 8590 dfb2 B..P.3..<....... 00000170: 8a55 5ca5 618d 55f0 931b 3fb5 f981 4fc9 .U\.a.U...?...O. 00000180: a163 63db cc07 9f8e cb29 97f8 7c14 9d7f .cc......)..|... ``` [Try it online!](https://tio.run/##VVRrb1VFFP3ur9hthEhids/MnicWiYI2gEVFG5@kzJ4HpEKjUSoQ7V@va3rPLfUkd@79cGedvR576WvVl/3561cXF8v63Cbja6VklkLV24WWlDx14yNJq4F8ykKupEjE85nnD3f4R37IH2wQDDBawKURhqMRFxx5NKrNGVLrB/WcF7I2lhVjPp/xMfPuuxXDTgxXAi05Z5K@JLJjaeR8LmSWrmST95RyWjE@5T3@At8fHfF2DgGGayGSDeDSxRoKLePtzglpbkq5dsyRgyE6fH6TeecV872JdqusGA4YqTulorGTi9VQ922@GIdUj9lGq1QtRCF@xOcHl2T2f7rLV3P4OYeYSjH2RM13R8l5JW2LhTy9UGxdqPXWiO7x3xPgl3n8@x4jTIxcKjk3PGlZOuXhBWMVJZFmaFHXMFuAHg/4/rz@HbMwH/LJihGBUZsNFJM4uJwGCIUEq13H0QPlrHBZowOXm28c88ELfjyhPvlrxUjA6L5i2tYgrDeDxMEh2N2oNLEUe4TLLpuNLzfY8YunbM//uOKSgaHGZTiK/@c8FnCRhSSkDi6AzCVlMkE6MB7sWcAsYXKBzStGAYY4kzCMNFKP1w1fDPzWTM0gfDW2hYICnEDkzrx8eOnNb9s5dM5hh1INiGMMDsp0BwE8AhGst2QaNOphyRsuZ1@eH/iiT/i9L3VqGiG6lDgtxPCtZxjhOkLioUxtbZARhbd8cvtPvvasGG1yMS1QqAiEEVz3ThW/BLkTSZRdABdrPZHhl7j5PSzhxM/0xorR5xwVayEWw2tpfcpjaellkC8dsRWtUAsrBS62MHxh/vn6HAMYoUMwiSYg3OoQ7gqHEg4ZoZMfMUPnnIhOOfI@z5TfPT1@u8Uwsz96BAONeLG1o9KwaIGqkAIRA6RPjiLSutF0dyNF8/z7FmP2Ryhu@gI37II2Mma@XcxCSaGMb4Iisg5ZP3nEBwA6Rdj5aXjycMWY/eENpMiuCVmHxUOhCdUMX0pTZN3A2xgEOf0Wanx45cqZWTFmf9SQcL0qAiHg3kLF4UAjBmOoOAhVc5m7zx9zfTuZnF3T1Mz@MKVBRMWSxYIO8sMg@ga2dmMhrIMequIv9Xj8bueYdxLvwh2/Ysz@yIoEpGKggloUUbXYkgYR0QIDzsc0K2lm7Nksj6/2gHXMb67muOwPWyJi4FHpVoTMACupA5sjccywLtSGWqLPmb@Z67b/v5ya2R@poHV9LZ6CScipn8srBrkbisLPCSs46tyXo1@58NHMBz5fbzFmfxRsNuRE/9a6RDDA2le1mXIciVCxYNUwEXGtmwFuMf@Dr4uL/wA "Bubblegum – Try It Online") General compression algorithm baseline. Prints all words of length up to 4, most of length 5 and some of length 6. The words are separated by ```. The actual words of length 5 and 6 are found with a very basic random search, but the quantities of each length are just guesses. The order of the words is mostly alphabetic, but I moved some words around by hand. I can't really tell why moving some words yields an improvement, but I was able to save 1 or 2 bytes by experimentation. I'm sure a better result could be achieved by a more systematic and automatic search. The list is compressed with `zopfli -c --deflate --i300000 words.txt`. [Answer] # [Nibbles](http://golfscript.com/nibbles), 161 words, 400 bytes. ``` .=\`\<159\`D 6+~"o y"`D 21*"sh"`%!|;@`#$4+~:`/@5`<+$~;@=" "$$45f31d2e733373ab092b79e7b544370bc7a0e362d8beeb825fe11e496df679b92e76991f03d6bc7f4389125c5b3648e326c221e31340945b6a79d28e6cbafaf177dccffd45c3e0e544365a8c973aed312eb485f57c8d861d18c62044842f41b7db23a106ede98d24c314c9d979ba388abeed82b04e848d8a9b6e44aafbb4bc0a7eae60687b13ecba3c0c240b05f7a0b2910a1843ca0af8f46849d9a565d695255ae19b2c954869ba9662723e903f422af11ef182dc00343885921657571bd40757f46ba10eda6a60e78c37ba913f26c93db1c2e1b9714d6c2601f504eba9cb0fff65d060cf08156986b079ae1046cd3dc1415a1daad9d57a79d13a271c9bc788631440d1ee118a40099517ce55c1389854cf0afa17ad73765d017de916abb93abfa49ff8d2d77382ab8f89db95a4ff8ce929bccd1435a1c98f9af7e67fe1847e6cdb348fad50d8c2c7ed5efd26bf7b838a985bc0bffe0a5168fcad28060f974b40c7dcf00b562ed1cbc3937ce387e71f ``` That's 64 nibbles of code and 736 hex digits of data at half a byte for each. Nibbles isn't on TIO yet, but run it like this: ``` nibbles words.nbl < /dev/null ``` Ungolfed version: ``` .=\ `\ <159 \`D 6 + ~"o y" `D 21 \c unused dat *"sh"`%! |fstLine `# $ 4 #" abdfghiklmnoprstuvyz" +~:`/c 5 sets m `<+m~ dat sets w = " " w $ ``` (hex data is the same) The method is essentially to encode each letter in base 21 data, but with 1 key trick. Notice these two inefficiencies with that trivial encoding. * If the list is sorted then the next first letter is the same or 1 more. * Spaces are by far the most common With the trick, a space and the next first letter combined can be encoded with a single base 6 digit! That's a savings of 125 bytes of data. First sort the words alphabetically by first character and length as the tie breaker. Now compute difference in length of words, with 6 added if they differ in starting letter. These numbers now encode what the next words length and starting letters are. So if the last word was "ats" and the digit is 2, it means the next word also starts with 'a' but has length 5. Now if the next digit is 2, it means the next word starts with 'b' and is length 3. That is because there are no 7+ letter words and no 1 letter words encoded (o and y are handled specially for this reason). One problem I ran into is there are only 160 words < 7 in length. But if we handle even one 7 letter word the above method would need base 7 digits which would add about 5 bytes of data. To get around this I encode all "sh" as spaces, which effectively makes words with sh in them shorter. That's the most common letter combo (used 23 times in the words used), but this trick doesn't really save much because it increases the base that the letters are encoded as and requires code to convert back. Each use saves one base 21 digit (-12.5 bytes), but requires base 21 instead of 20 (+5 bytes), and the decoding code is `*"sh"`% WORD_GOES_HERE " "` which is 5 bytes. The next most common combo (15ish occurrences) isn't common enough to save anything unless the decoding process becomes more efficient. The way the base 21 list and base 6 list are encoded is using nibbles data feature which lets you encode a single number after your program with no terminators possible (normal numbers would use 1 bit of every 4 to terminate or not). This is a pure number not a list, but can be extracted to a desired base using ``D <base>`. But since the data needs to be used for both lists, we reverse it for one of them and truncate it. The non truncated list will have garbage data at the end, but this will never be consumed the way the program is written. There's another useful trick that saves about 8 bytes which is how the alphabet is encoded which is: " abdfghiklmnoprstuvyz" Rather than encode this directly, we use luck. The Nibbles hash function ``#` also uses data as salt, so if we have enough degrees of freedom in our encoding then we can create a hash that will deterministically map: ``` " abcdefghijklmnopqrstuvwxyz" to "111010111101111110111110011" so that after filtering it, it becomes " ab d fghi klmnop rstuv yz" (without the spaces) ``` The probability that this mapping occurs is `(1/4)**7*(3/4)**20` if we take the hash value mod 4 and use 0 as false and 1 2 3 as true. This is about 1 in 5 million. Notice that we can permute sets of words that have the same starting letter and length. This will change the encoded data, but will still give a correct output. There are also multiple 6 letter words that aren't used (now that sh is 1 letter), so that is another degree of freedom. Luckily this only takes about 1 hour to find with brute force search on random permutations of the starting words. Here's the code to find it: ``` # removed o y let uwords |.%"abail abikis ak akniton alfabit atirsin atom ats aypal baka baklait banl bgil bianto bit bo boraky borsh bot br brbrno byt daosik diga digiz dogo dolmuk dongso douv drarkak fa fafasok fasmao fidr floria fridka friv fully fylo fyrus gilmaf gogu gogzo gongul gorlb gosio gratbt gutka hisi horrib hurigo inglish iomshuksor isa ispikar isplo ita iushb izlash kaikina kat katisas katlani kfaso khalling kisongso kivsk klingt kod koik kolbat komy konma korova koss kotsh kris kromir ksik ksuz ktaf ktomish ktomizo la lan lgra loshad lyly mak makanto makav makina marinolus marta matiks mim mimhis mingso mitsh molo mosdob motif motkop movogal muratsh mutka naita ngoirfo nidriok nilo nin nini ninibr nirus noguna nolif nors ogig omkop onion opru orilha orni ozon papin paslo pasrus pirishy pluban polr posodo pouk produty rak raznitsa rigiks rilifior riomr rno ronta rus ryby sabbia sai sakar saman sandvitsh sasa sfiny shatris shidoso shilan shimshoom shor shotiya shuan shubhu shuksor shuriok shutis shutrak shyba sibas sibin simriomr sod sokit spamra spamt srirad sutka taika tipstor tizingso tksu tobl tokvod tomp tonfa toto totobr tshans tshimiso tshomp tura tuvung uboiak umub vaf vintz voda vodl vontark yntsh zimdo zivod zombit zorliplak"~ \w ?==w "yntsh" w *" "`%w"sh" # don't convert this word because the jump to zimdo would be 6 then - 7 ,$ hex / |.,~ \i let words +=~ uwords \w `# :w i 4273 # this essentially permutes the words randomly # permuting randomly is more efficient than searching through permutations in order as small changes will actually likely map to the same encoding (i.e. if you swap words of different lengths that will get undone during the encode process). let takewords 159 let bestchars -" abdfghiklmnoprstuvyz" "" let selectedwords | | words ~ \w | w ~ \l ? bestchars l - 7,$ let nc ,bestchars let bestwords < takewords +=~ selectedwords ,$ let sortedwords +=~ +=~ bestwords ,$ =1$ let tailed .sortedwords>>$ let lens \:1 ! sortedwords >>sortedwords ~ \w1 w2 let lengthdiff -,w2,w1 let chardiff - ?bestchars =1w2 ?bestchars=1w1 +lengthdiff *5 chardiff let data . sortedwords \word let wd ! bestchars word ? >>. wd \c1 -c1~ let d1 `@ nc +data let d2 `@ 6 lens let d1p *d1 ^nc ,`@ nc d2 +d1p % -d2 `@ 6 \<,lens \`@ 6 d1p ^6 takewords \fd * ==| " abcdefghijklmnopqrstuvwxyz" \c `#~ :o c `@ 256 fd 4 " abdfghiklmnoprstuvyz" - 737 ,hex fd # max size 736 (sometimes it is 737 for unknown reasons) $ ``` Other ideas: Remove z, this was a complete wash because z is in some short words. I considered using something like huffman encoding since some letters are common and others rare. It would save about 30 bytes of data, but now you have to encode at least the order of commonness of the alphabet (and then assume some function of probability on it, it is actually pretty linear though). That would take at least 10 bytes. I don't think that leaves enough to decode and save anything. I'm kind of surprised this method did so well without really finding any other patterns in the data. But it doesn't seem like there are any other obvious patterns that are so strong to be worth the extraction code. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 399 bytes, 85 words ``` `ab₴⁋ ak ƈ¶ ₴ǒ ay₃⁺ b√ṫ b□× b£ṫ Ǎ₂ǎǏ °ẋ bo b⋎≈h ǍĊ br Ǎ∩ d⋏ė d⋏ḟz d꘍τ ›¢£ǎ ∩ḟv fa ⊍½…ƈk ⊍†Ǐẏ f⋏ø ⊍¾≥‹ fȦ‹ka ß≠v ↔¥ fƒİ fy≥₃ £ṫǏ⟨ g꘍ȧ £₆zo £§£Ḣ g⋎Ċb go∪ḋ gr₴↵t £Ȧka ¥₈≥ḟ ¥Ġ⋏ġ ḋ₌l⋏÷ ₍₴ i∪…kar isɖ„ ↲₍ iꜝ⁺b izl⁋‛ Ṅ⋎k⋏£ kat kµ₴Ẇ≠ k₴≬…„ kf…ƈ k€Ḟḋ₌ ki↔Ṡo kivsk klḋ₌t kod koik kolḂṙ k꘍¼ koǏṗ k⋎§va koss k⋎Ṡh k≥τ kroǏḂ ksik ksuz k≠ʁ k¢‹⋏÷ kt꘍⁽zo la ȯ¡ l£Ẇ †ṫλ‡ lƒṖ mak m√ṫv s¥₈ shꜝø ∪Ǐǎ⌐ ∪Ǐ≠ḣ shƒ≠ siǍḟ si½ǔ` ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgYWLigrTigYtcbmFrXG7GiMK2XG7igrTHklxuYXnigoPigbpcbmLiiJrhuatcbmLilqHDl1xuYsKj4bmrXG7HjeKCgseOx49cbsKw4bqLXG5ib1xuYuKLjuKJiGhcbseNxIpcbmJyXG7HjeKIqVxuZOKLj8SXXG5k4ouP4bifelxuZOqYjc+EXG7igLrCosKjx45cbuKIqeG4n3ZcbmZhXG7iio3CveKApsaIa1xu4oqN4oCgx4/huo9cbmbii4/DuFxu4oqNwr7iiaXigLlcbmbIpuKAuWthXG7Dn+KJoHZcbuKGlMKlXG5mxpLEsFxuZnniiaXigoNcbsKj4bmrx4/in6hcbmfqmI3Ip1xuwqPigoZ6b1xuwqPCp8Kj4biiXG5n4ouOxIpiXG5nb+KIquG4i1xuZ3LigrTihrV0XG7Co8ima2FcbsKl4oKI4oml4bifXG7CpcSg4ouPxKFcbuG4i+KCjGzii4/Dt1xu4oKN4oK0XG5p4oiq4oCma2FyXG5pc8mW4oCeXG7ihrLigo1cbmnqnJ3igbpiXG5pemzigYvigJtcbuG5hOKLjmvii4/Co1xua2F0XG5rwrXigrThuobiiaBcbmvigrTiiazigKbigJ5cbmtm4oCmxohcbmvigqzhuJ7huIvigoxcbmtp4oaU4bmgb1xua2l2c2tcbmts4biL4oKMdFxua29kXG5rb2lrXG5rb2zhuILhuZlcbmvqmI3CvFxua2/Hj+G5l1xua+KLjsKndmFcbmtvc3Ncbmvii47huaBoXG5r4omlz4Rcbmtyb8eP4biCXG5rc2lrXG5rc3V6XG5r4omgyoFcbmvCouKAueKLj8O3XG5rdOqYjeKBvXpvXG5sYVxuyK/CoVxubMKj4bqGXG7igKDhuavOu+KAoVxubMaS4bmWXG5tYWtcbm3iiJrhuat2XG5zwqXigohcbnNo6pydw7hcbuKIqsePx47ijJBcbuKIqseP4omg4bijXG5zaMaS4omgXG5zaceN4bifXG5zacK9x5RgIiwiIiwiIl0=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 126 words, 399 bytes ``` .•2Z₃LSι#@#«Σ±ñÿ˜¸‚÷ý…qÄнβŠŒäãΣαÑz@W|RÈÚ<¸´_£]ºRùƒl®нJë2k‘ƶ9žΔÍ2s`0õÙ{óžM¨àWhà —'ïš<G¾¯×c†}À|Òé´8N/§j::&βxΓ"oÑ.ðË¡ÄΛ™ζÒ₅¬]õ2b?ç9.d€γβвΣ;$θǝØ,ó=-ž4󧸙₃λ¬ÍÕ~Oì&^uÜ≠¥ƒvé©^Ûïæ(7I†=^;L½ÃÜ-+ÙXe‡¯ÚŒ†zÏZ₁≠pxÎUθè±t&∊s†è-ÚÎîÓEd£¤Áà³à^]I>ûr\ú±ÉþϘ2ƒv´g¸>[—üéÃ≠JQG0(*ŠØ²DƵδтÕây/Y*.¤\4hVÌè¯ʒ<ÊvßëĀиðθH₆÷aΔθåŸнā₅·…˜l’ƶ8¥þ“Àöë₄æ*b₁¤—εÒ¥QëQÒeн≠Càz”9†Í=<Xóγ¯mpð]BIÅтîƒ6ƒ°ĆAćγΣß”/8#Dv:‡‘{zƒ$ƒF?¼[v¡bËδv͸špîÈfa÷ÆðÛн‹ ``` [Try it online!](https://tio.run/##FZJpTxNhFIW/@zOEoEEppCHKUhYVRQhqwCgotEoFRcWAog0WNEMpyGIhDBChlDDdWNKGLtOWYWlN7umMiSRv6l94/0h9@Xxz7znnOXdkrN/@drBYNHEpYH7OXdMdj9lxSXMJRViQEkjg97mPNC55cYQsl3Y/wl3IsqSu6DJCCLIgS2DF2dw92YU5eC2kUeoFBa100oVjQx6mw0K2HRHzey5tGJlaPcfW4DGPvaxCGpsTUPXcA9qH0j0E5RKX1q4gpvstrZSjGH694pLyDdIkZBxQquZhJe29q6srY8lxtnp5BCsmxLFIfrjZFncHWAYyd81Q1Iq02d6EvVrTAHdFmcqShSQL1pcy7c82Nq5DbajQc9VQaU/kcgdEZHZKUXiw/v0RomW2L/DxeYXChuwQugc2bCGG3as324SdBlt9B2UxDV/FNWz2DHLJL5x6dVnMnFgW/KbE7ug4lp4wDfuU@FzG5xbGxBT7FfBiCYdYvTtAQQphCgqpUGzWtkacfurDicA9jxyWz31moU2pN6Q19gooOMMBpsXd9s7WqqvluoINSrYYaZb658I6Al8rn5WbKNRXPfQUP4Vo7K9swYIDO4jkpYKGONPuc9csjvrZmnAV1rVCNj91wepIFHruG@bSppGpoTByXPJBQgYR7nJjt9wu8lBIWGBpyBTuRKQT8mAhK7zcgeLk0nbtRTRPg6UHKlMp9mEUcevtNswIZ4eGfMOQKZ6fvZX/IWoIYkcsVNaUtDjqBDfxEBNOQy415HtNdNbrIL8diyzlgIc03T8qQM297hdPNyta3hKS0nGx@B8 "05AB1E – Try It Online") [Answer] # Python, 46 words (397 bytes) ``` import base64;print(base64.b85decode(b'VPauvY#?D`X=`b7AYp56X>@OHAYp7~VPa`?AYpWAa&u{JAYpWGZ6INEb0A@PaA9m9Vqt4xAYx%_Y+-41AYx%|Y#?H1X>1^3X<=@3Zy;i6bRc4Ha$#$EAYyNFb7&x9Z*(AHav)-IVsdV8AYyrRAY@^0b7^ZJWNBw%AY^H0X?h@JZ)a~HWN&P3b!#AGZ*FIEZy;oEb#@?Ra$$07VQU~}VP;`-Z)+fCVRLO^Zy;uAWO5*8Y;SUDVIXF5X=H0*AZBuDb|7YTY;1WTW_fIHAZB@Tb#owRX>4s_W*}#8XLTTFZ)bXMAZKrGXLW2KXK!+BVjyR4b7^lNXL4b5Vss#9b#!ZCAZTfGX&`8Ca&l>6')) ``` The base85 encoded text, for testing: ``` VPauvY#?D`X=`b7AYp56X>@OHAYp7~VPa`?AYpWAa&u{JAYpWGZ6INEb0A@PaA9m9Vqt4xAYx%_Y+-41AYx%|Y#?H1X>1^3X<=@3Zy;i6bRc4Ha$#$EAYyNFb7&x9Z*(AHav)-IVsdV8AYyrRAY@^0b7^ZJWNBw%AY^H0X?h@JZ)a~HWN&P3b!#AGZ*FIEZy;oEb#@?Ra$$07VQU~}VP;`-Z)+fCVRLO^Zy;uAWO5*8Y;SUDVIXF5X=H0*AZBuDb|7YTY;1WTW_fIHAZB@Tb#owRX>4s_W*}#8XLTTFZ)bXMAZKrGXLW2KXK!+BVjyR4b7^lNXL4b5Vss#9b#!ZCAZTfGX&`8Ca&l>6 ``` [Try it online](https://tio.run/##JY5bU4JAAIX/Sg5KgmODyc0hlfUKamiEy@4@ILupo40GgZZO5V@3bXr7zmXOnPR82CRvdTPNrtftPk2yww2j@UpXrTTbvh3K/@KOmdpy9ZIsV2V2C2f0@IGFdi9GzZgZAKeajlr21OFkXHgatzmFgIrHr9EfDYnuen2mAHtGQWPfgO8H9QTwqbTAlapa@6NvvufUUKsW1dFD066Ts7XVmf@iOrQoFPsAn70BM8RTg8hl4NAPqerCfAlNHmQ@wHakMCMio9DrfJYAjhwFtTf2iEj04oSeOKuzggCGRB64fb6c9Jlgt31aLCoGfJpffuDMiqtEqqy70J9MI145gnCqySa2nuc96KKBhpqOIgPSOfbYt4EDbNXCIFysXYd7dsCE5NNHLTVfhPKPYKJJEAyIxNAjIONsiCbh/RiNC5UOfD37Kn@689BEZRrMc6HBhALpAhKsh0iMzS4Vdy39VpKu118) ]
[Question] [ [![Tesco Burger Relish BBE: 20140](https://i.stack.imgur.com/meYNQ.png)](https://twitter.com/Tesco/status/1143449559722594306) Given a date between 2010-01-01 and 2099-12-31 as three integers (please state your order if not `[year,month,day]`), answer with Tesco's corresponding five-digit Burger Relish Best Before End date number. The format is simply the last two digits of the year, followed immediately by three digits representing the day of that year, between 000 and 365. Cookies if you can do this using only numeric operations and comparisons. You may put such code separately from your golfed code, if it isn't also the shortest code you have. ### Test cases `[year,month,day]` → `BRBBED`: `[2010,1,1]` → `10000` `[2019,7,5]` → `19185` `[2020,5,20]` → `20140` `[2096,12,31]` → `96365` `[2099,12,31]` → `99364` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~74~~ ~~70~~ 67 bytes ``` param($y,$m,$d)-join"$y 00$((date "$m/$d/$y"|% d*r)-1)"[2,3+-3..-1] ``` [Try it online!](https://tio.run/##TZDhbsIwDIT/5ymsyEzJ5kDS0kImTdp7IIQqkmmb2tGVIlYBz94ZNij@ed@drXO92cdm@x7Lssc3eIFDXxdNUSnsCCvCoM3n5uNLYgfWolKhaCNIrCYYJtjJ4wjCY6ON03KRUPpk0vHYuGV/EuJVCeAhlVhnyZEDAmd59KB7mlF21r2bZ4OeWMoosQzYM70L@Jwcnzmv8nma30W8H4hP86kWGo4wgsPFcS1DgPGnjus2Bq6Kqz/YxO2ubFl44A9wUawAwwVJVP/UxO9bVD9fM1Kc@l8 "PowerShell – Try It Online") Exactly what it says on the tin (but formatted weirdly). Takes in `$y`ear, `$m`onth, `$d`ay, plucks out the last two digits of the `$y`ear, gets a .NET `datetime` object of the specified day, then gets the `dayofyear` (with `|% d*r`) thereof. Subtracts one to make it zero-indexed, then uses string formatting and slicing to make it three-padded (e.g., `000` instead of `0`), and then `-join`s it all together into a single string with implicit output. Note this is culture dependent due to the `datetime` formatting. This works in `en-us`, which is what TIO also uses. *-3 bytes thanks to mazzy* [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~88~~ ~~78~~ ~~73~~ ~~71~~ ~~59~~ 57 bytes ``` a=>a[0]%100*1000+new DateTime(a[0],a[1],a[2]).DayOfYear-1 ``` [Try it online!](https://tio.run/##jY6xCoMwGIR3nyJLIWl/5U@KLcHqJJ2ELkIp4hDSCBlMQVOKlD57qnsLDnfLfXecHmM92nB@On26T071VoN1viAdyUlQeaEabDcccTsLd868SKm8qW1v6BKBavhiomVJqaZLdzNqiHnIoug6WG8q6wzt6NKbZ5v2LZAjcOCfpH5UdvSUMZb9ZyUcIV3HCoQUBK6D5QG4gP3KG1L@oMMX "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` ->d{Time.gm(*d).strftime('%y%j').to_i-1} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6lOiQzN1UvPVdDK0VTr7ikKK0EyNdQV61UzVLX1CvJj8/UNaz9Hx1tZGBooGOoYxirA2Ja6pjrmIKZRgY6pjpGBmC2pZmOoZGOMUSNpSWUE6uXmpicoVCtUJOSWJJao1CgER0NYsXqpEHoWE2F2v8A "Ruby – Try It Online") So close to being a built-in format, but `%j` is 1-indexed. In a happier coincidence, though, Tesco Time (`.gm`) is one character shorter than local time (`.new`). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~48~~ ~~45~~ 39 bytes Port of [Expired Data's answer for C#](https://codegolf.stackexchange.com/a/187724/80745) ``` $args[0]*1E3+("$args"|date|% d*r)-2E6-1 ``` [Try it online!](https://tio.run/##TY/NCsIwEITveYqlrNLULSSpjUYQvPgUIiIm6qFibSsq1mevsf7Uue18MwuTHy@uKPcuyxrcwhTuDa6LXbkQy0jOk0EYtGdQ23Xl6h7YqOCxmutYNg/GZiEDLwqVkIIkSSCQwot3vqERpS/fyHHa@UpQSkp44DPDv4LRJBUlr1dGJ/qvYkxHTKKHnHGooQf3NoE3wgOhJUB3zd2mctbPwdUbFq48Z5U3@n4l3gAPgLZFAYYfGrvTr8on307AHs0T "PowerShell – Try It Online") --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~60~~ ~~58~~ 52 bytes *-2 bytes thanks @AdmBorkBork* ``` -join"$args 00$(("$args"|date|% d*r)-1)"[2,3+-3..-1] ``` [Try it online!](https://tio.run/##TY9dbsIwEITffYqVtalsukZ2QlKMVKn3qBBCtfuDQkmTIBolnD11AjTs02q@mV1NcTj5svr0ed7jOzxD26vd4eub47b8qEBrFOKy885ta99F4GalVEby15iSR5XM58qs@zNjL4JBGBKxNpoMGSAwOoycdEtPlA66Nct00mNNKcU6gOBZ3AVsRia8GU7ZLMnuItZOxCbZQjIJHUTQjg5sCPeEjgD9b@Hfau9CN9xcYOmrY14H4SFUxgZwD@hGxFFcqfI//1G5umU4O/d/ "PowerShell – Try It Online") Explanation: * The script takes three integers `[year,month,day]` * `"$args"` makes a string like `YYYY MM DD` * `"YYYY MM DD"|date` converts string to `[DateTime]`. I don't know why it works. Can you explain? * `("YYYY MM DD"|date|% d*r)-1` calculates `dayOfYear` * the script makes a result string like `YYYY MM DD 00###` where `###` is `dayOfYear` * finally the script extracts chars from positions `[2,3+-3..-1]` of the result string and joins this chars to result [Answer] # [Python 2](https://docs.python.org/2/), ~~63~~ ~~61~~ 57 bytes ``` lambda y,m,d:y%100*1000+(153*m-2)/5+[m+1,1>y%4][2<m]+d-33 ``` [Try it online!](https://tio.run/##DcPLCoQgFADQX3ET@LgyXq2goelHqkUhUdA1GWzh11sHTsxpv4It228q50KrX1gGAv/NFRoj30ZxbJwkbcWnUSMpBBxyVc@j7WlWXjtX4v8IiW1cHiHeiQtRrOlaYAjM4QM "Python 2 – Try It Online") Returns the result as an integer. [Neil](https://codegolf.stackexchange.com/users/17602/neil) found that [his Charcoal approach](https://codegolf.stackexchange.com/a/187738/41024) turned out to be lucky after some rearrangement. Pure arithmetic and comparison solution (61 bytes): ``` lambda y,m,d:y%100*1000+30*m+m/2+(8<m<12)+~(0<y%4)*(2<m)+d-31 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~87~~ ~~85~~ 74 bytes ``` lambda y,m,d:sum([y*1000-2000029+28*m,3,y%4==0,3,2,3,2,3,3,2,3,2,3][:m])+d ``` [Try it online!](https://tio.run/##jZDbaoQwEIbvfYq5EXV3FpJ46EaQXvQxbC7sqqxQD5gI9elttB7iXnUgYcj//f8M6Ub1bBt/KpPP6Turv/IMRqwxj@VQu@l4oYSQG9MXYfzK7pcafRztIEmIbth69k6kcS28az6pQqqPTBYSEkgt0JWmjFCCFKlAmFOJwEPg@IbhLHB6Dw2BEQyRaRQ0FJgWHiHVE@c0HvmRaeL8kLgfBcISllW2PWxbQdXsvYwXX9dXjXKdqukGBUfFYEsH7A1OifBMvPjpiocqcmgHNRtfcbriy5fqrzBylvfVlkDpLsgpfBVfd/l7PpGVhErBo@17vc37TrpbvDFYb3Sy3v5Vjjf9Ag "Python 3 – Try It Online") This is using only numeric operations and comparisons. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 4ḍȯ2⁽¢wB+30¤_2¦ŻḣS+⁵’+³×ȷ¤_2ȷ6 ``` A full program taking arguments `y m d`. Jelly has no built-in date functionality. **[Try it online!](https://tio.run/##AUYAuf9qZWxsef//NOG4jcivMuKBvcKid0IrMzDCpF8ywqbFu@G4o1Mr4oG14oCZK8Kzw5fIt8KkXzLItzb///8yMDk2/zEy/zMx "Jelly – Try It Online")** ### How? ``` 4ḍȯ2⁽¢wB+30¤_2¦ŻḣS+⁵’+³×ȷ¤_2ȷ6 - Main Link ¤ - nilad followed by link(s) as a nilad: ⁽¢w - 1370 B - to binary = [1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0] +30 - add 30 = [31,30,31,30,31,30,31,31,30,31,30] ¦ - sparse application... 2 - to indices: [2] _ - action: subtract... 4ḍ - four divides y? -> 1 or 0 ȯ2 - OR 2 1 or 2 Ż - prepend 0 = [0,31,29|28,31,30,31,30,31,31,30,31,30] ḣ - head to index m S - sum +⁵ - add d ’ - subtract one ¤ - nilad followed by link(s) as a nilad: ³ - y ȷ - 1000 × - multiply + - add 2ȷ6 - 2000000 _ - subtract ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` IΣ⟦×φ﹪θ¹⁰⁰⊖ζ÷⊕×¹⁵³⊖η⁵⎇›η²⊖⊖¬﹪θ⁴⊖η ``` [Try it online!](https://tio.run/##XY49C8IwEIb/SsYLRIjRTo4WpIMi2K10CO1BAmlCr2lB/3yMIFQ7HLwf3MPbGU1d0C6lO1kf4aynCI95gKa2A06wl1IKdg397AKMgmXPuWAldoQD@og9vLKvfCztYnuEyq/NF1Ec/h8M/yCKfDWS1/SEC6GOSGAEUxv6r76FCOuUI@fbKZnc5vCUUqOkkqIQSrZpt7g3 "Charcoal – Try It Online") Link is to verbose version of code. [Try it online!](https://tio.run/##dU/LasMwEDynX7HktAIVZKduMD6FBkoOCYXm1vag2EsksOVGlhOa0m9XN21oHlC0QjM72mG2NNqXra7jztiaAGfuvQ@LvlmRRyHg82Yw6Tq7dmglbETxRy/@STD/S3tRxCdvXcAH3QV87ht8WdqGOkyUUhLmbdXXLW4kMBc8MKXSU0MuUIV75jMXpnZrK2Lnk3K0yEaXA0YcLDK@S/JO@w989KQDRzES0iv3c7xoA56i3AlxHYWd37hZxMHvNsNXP@Stv2KqEgUJHwY5jCFjkKqfhyu/hySF0UHN8yNU8XZbfwM "Charcoal – Try It Online") Link includes test suite. I don't think Charcoal has any date functions, so here's a mathematical solution. Explanation: ``` ×φ﹪θ¹⁰⁰ Year * 1000 ⊖ζ Day - 1 ÷⊕×¹⁵³⊖η⁵ Days in previous months ⎇›η² For months after Februrary ⊖⊖¬﹪θ⁴ Adjust for leap years else ⊖η Adjust for short Februrary Σ⟦ Take the sum I Cast to string for implicit print ``` [Answer] # [R], 66 bytes ``` function(a,b,c)as.numeric(strftime(paste(a,b,c,sep='-'),'%y%j'))-1 ``` taking 3 integers and pasting them into a string strftime can recognize and extract the wanted parts. 0 indexing costs 14 bytes and another conversion to numeric [Answer] # Ruby, 79 81 79 78 bytes ``` ->y,m,d{(y%100*k=1000)+[d-1,l=31,y%4<1?29:28,l,s=30,l,s,l,l,s,l,s][0,m].sum%k} ``` Cookies version. Saved a few bytes by including the -1 and day in the array that gets summed, since those spaces were spare anyway. EDIT: I realised that using `"...%03d"%...` wasn't really in the spirit of 'numerical and comparison operators only' so I've updated this answer (and gone up by 2 bytes). EDIT-2: ... and recovered them by using the alternative sub-array index format `[start,length]`, which in turn allowed me to combine the first two entries in the array. EDIT-3: `y%4==0` can be shortened to `y%4<1` [Answer] # JavaScript, ~~70~~ 57 bytes ``` (y,m,d,U=Date.UTC)=>y%100*1e3+(U(y,m-1,d)-U(y,0,1))/864e5 ``` [Try it online!](https://tio.run/##ZY1BDoIwEEX3noKNSasDzLS0Mgvc6BHkAASL0aAYISScvkJkY7r7yXv//0c1Vn39ub@HeMx9U3gxwROuUBbnanBJeTnJ4jhtCXFHTu9FufCY4CrjJSKQlGluM2d83b36rnVJ291EIxTSDBccpWk09xE3gcFwALMaTLkJDIVgQOFPmQtZOMIWSIFej9hqG84w/zmsbea/ "JavaScript (V8) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 45 bytes ``` {@_.[0]%100*1000-1+Date.new(|@_).day-of-year} ``` [Try it online!](https://tio.run/##RY7NCoJAFIX38xSzKbTuyJ1Rpy4SuOgR2kWI0DWE0lAjpHr2aVyUi7P5zg/nzt3VukfP8sD9kAlxG@WykjvpXnkRHfG00IgrL1R6vS8Hjhp@Bu@8CKNzOaq2UiOX3cfVvawCgxpBgw5BTg3MxA8TbCCdMOlt@scGIQWDnvtIMsfJgjYQTztkYzsXiGaDYptk4tw2rAZ/vW4uQei@ "Perl 6 – Try It Online") [Answer] # [Red](http://www.red-lang.org), 54 bytes ``` func[y m d][y % 100 * 1000 - 1 + pick to now[d m y]11] ``` [Try it online!](https://tio.run/##TYtBCoMwFAX3nmI23bQU/k@xJT1GtyErY0DEKGIpnj5GusnmDQzz1j7kTx@cb@KbHL@pczsTwRdcUBGu5wp3lBvL0I1sM2n@uVC63av6vKxD2ogYUSmZNpWwvGgrYYS2oDL2iRoe9cvav8oH "Red – Try It Online") [Answer] # [8th](https://8th-dev.com/), ~~77~~ 71 bytes **Code** ``` needs date/utils : f third -rot d:ymd> doy n:1- swap 100 mod 1000 * + ; ``` Return the result on **TOS** **Usage** ``` ok> 2010 1 1 f . 10000 ok> 2019 7 5 f . 19185 ok> 2020 5 20 f . 20140 ok> 2096 12 31 f . 96365 ok> 2099 12 31 f . 99364 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~29~~ ~~26~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¦¦₄*•ΘÏF•ºS₂+I<£O¹4ÖI<O ``` [Try it online](https://tio.run/##yy9OTMpM/f//0LJDyx41tWg9alh0bsbhfjcgfWhX8KOmJm1Pm0OL/Q/tNDk8zdPG//9/IwMjEy4TLmMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaNihlf8PLTu07FFTi9ajhkXnZhzudwPSh3YFP2pq0o60ObTY/9A6k8PTImz8/@v8j442MjAy0THRMY7VATINDXQMdQwhTEsdcx1TMNPIQMdUx8gAzLY00zE00jGGqLG0hHJiAQ). Takes three loose inputs in the order \$year\$, \$month\$, \$day\$. **Explanation:** ``` ¦¦ # Remove the first two digits of the (implicit) input-year # i.e. year=2024 → 24 ₄* # Multiply it by 1000 # → 24000 •ΘÏF• # Push compressed integer 5254545 º # Mirror it vertically to 52545455454525 S # Convert it to a list of digits: [5,2,5,4,5,4,5,5,4,5,4,5,2,5] ₂+ # Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31] I< # Push the second input-month decremented by 1 £ # Leave the first month-1 amount of values from the list O # Sum this list # i.e. month=4 → [31,28,31] → 90 ¹ # Push the first input-year again 4Ö # Check if it's divisible by 4 # 2024 → 1 (truthy) I< # Push the third input-days, decremented by 1 # i.e. days=3 → 2 O # Sum everything on the stack together # 24000,90,1,2 → 24093 # (which is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•ΘÏF•` is `5254545`. [Answer] # Elm 0.19, 112 bytes ``` t y m d=1000*(y-2000)+List.sum(List.take m[d-1,31,if modBy 4 y<1 then 29 else 28,31,30,31,30,31,31,30,31,30,31]) ``` Verify all test cases [here](https://ellie-app.com/62WQKrJvdBsa1). [Answer] # [Japt](https://github.com/ETHproductions/japt), 23 bytes Takes input as 3 individual strings, assuming that's allowed. ``` ¤+@ÐUTX ŶÐN Å}as ùT3 É ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=pCtA0FVUWCDFttBOIMV9YXMg%2bVQzIMk&input=IjIwMTkiCiI3IgoiNSI) Very unhappy with this (there must be a better way to get the day of the year!) but it's been a long day. A port of darrylyeo's JS solution would be [2 bytes shorter](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=JUwqQbMr0FVUMSBu0E4pLzg2NGU1&input=MjAxOQo3CjU) but, for some reason, despite Japt being JavaScript, floating point inaccuracies abound. ``` ¤+@ÐUTX ŶÐN Å}as ùT3 É :Implicit input of strings U=y, V=d & W=d (N=[U,V,W]) ¤ :Slice the first 2 characters off U + :Append @ : Function taking an integer X as its argument ÐUTX : Construct a Date object with U as the year, 0 as the month & X as the day Å : Convert to date string ("yyyy-mm-dd") ¶ : Test for equality with ÐN Å : Construct a Date object from N and convert to a date string } : End function a : Return the first integer that returns true when passed through that function s : Convert to string ùT3 : Left pad with 0 to length 3 É :Subtract 1 ``` ]
[Question] [ You will receive an integer less than 2000000000 and bigger than -2000000000 and you have to test what type(s) of number this is out of: ``` Factorial Square Cube Prime Composite Triangular Positive Negative ``` Here is a definition of all the different types of numbers: **Factorial** - A number That is equal to the product of all positive integers less than the a certain positive integer - 5×4×3×2×1 = *120* **Square** - A number that is the product of two identical integers - 5×5 = *25* **Cube** - A number that is the product of three identical integers - −5×−5×−5 = *-125* **Prime** - A number that has only two divisors (1 and 0 are not) - *3* **Composite** - A number that has more than two divisors (also not 1 or 0) - *4* **Triangular** - A number that is equal the sum of all positive integers less than the a certain positive integer - 5+4+3+2+1 = *15* **Positive** - A number larger than 0 (not 0) - *7* **Negative** - A number less than 0 (not 0) - *−7* ### Test Cases ``` -8 = ["Cube","Negative"] -2 = ["Negative"] -1 = ["Cube","Negative"] 0 = ["Cube", "Square", "Triangular"] 1 = ["Cube","Factorial","Positive","Square","Triangular"] 2 = ["Factorial","Positive","Prime"] 3 = ["Positive","Prime","Triangular"] 4 = ["Composite","Positive","Square"] 5 = ["Positive","Prime"] 6 = ["Composite","Factorial","Positive","Triangular"] 7 = ["Positive","Prime"] 8 = ["Composite","Cube","Positive"] 9 = ["Composite","Positive","Square"] 10 = ["Composite","Positive","Triangular"] 11 = ["Positive","Prime"] 12 = ["Composite","Positive"] ``` Note: The Order of the Result Does Not Matter and it can be expressed with words **(Does Not Have To Be A List)** Remember, this is a code golf so the smallest answer in bytes is what I'm looking for [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~130~~ 119 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function. ``` ((∊∘⎕A⊂⊢)'FactorialSquareTriangularCubePositiveNegativePrimeComposite')/⍨{⍵∊¨(⊂∘!,×⍨⍮+\)⍳|⍵},(|∊⍳∘|*3⍨),<,>,1∘⍭,0∘⍭∧1∘< ``` [Try it online!](https://tio.run/##JY7NSsNAEMdfZTw10S12Ez8qFEECYi9aTI@9rGYbAmlTYyKK6UWhhMCWehB77sVcNIfiC8Q3mReJs3iYr98M8/@LWdj2nkQY@W35mMipJ72mMQzMC8zXuHw/w@IFi43ZOhe3SRQHInTvUhHLIbVTPw1F7KQ3chDdB0nwIC@lL3QdxMFEOtFkprlsmfuoymdUP/S2Lg39Ml/vsN8Pwqi@90Ymqm1G@zkzMi2ttnSQ7dq0N1mPnTKu3agv1vmvmH9q0mvGuFihWpLR/hUWr3Vl4@KNJvfaoTy86LsNAS1tjCmZ87qsqy7UlUXBoQMcLLDhAA7hCI6hCyfACXLg1h8 "APL (Dyalog Extended) – Try It Online") `(`…`)/⍨` filters the list of strings on the left by the bit mask on the right:  `(`…`)'Fac`…`ite'` apply the following tacit function to the long string:   `∊∘⎕A` element-wise membership of the uppercase alphabet   `⊂` partitions (i.e. True begins a new partition)   `⊢` the unmodified argument The last **46 bytes** return a bit vector indicating `[Factorial, Square, Triangular, Cube, Positive, Negative, Prime, Composite]`: ``` {⍵∊¨(⊂∘!,×⍨⍮+\)⍳|⍵},(|∊⍳∘|*3⍨),<,>,1∘⍭,0∘⍭∧1∘< ``` [Try it online!](https://tio.run/##JY69rgFRFIV7T7FEwXAkzozfRDSaqyKXUiOZoREUCmI0bjKZTHIEibi1xjRMQrzA8Sb7RcYWxf5Za33FGszGeXs5GE9HeWcxdya2Y8fxitST/ECHGQo25P8nxetEKiR1y/UNUg@X87XIuMywYsDNWpwboi4aQrImdRWF7yX/8nHq8ZC8HaktbY@tNgV/OrLI27Pq/jZ5935a3TiNFJCEvoN8D/qBHD8HdNBMJxjmNmfxbTQ0dKijKnRk8kgUIGHCQhEllFFBFTVINiWk@QY "APL (Dyalog Extended) – Try It Online") `{`…`}` the first three bits (factorial, square, triangular) come from this anonymous lambda:  `⍵∊¨(`…`)`… is the argument a member of each of the following three lists?   `⊂∘!` the enclosed factorials   `,` followed by   `×⍨` the squares (lit. the multiplication selfies)   `⍮` juxtaposed with   `+\` the running sum  `⍳` of the integers one through  `|⍵` the absolute value of the argument `(`…`)` the next bit (cube) comes from the following tacit function:  `|` is the absolute value of the argument  `∊` a member of  `⍳∘|` the integers 1 through the absolute value of the argument  `*` raised to the power of  `3⍨` three `<` the next bit is simply whether it is positive (zero is less than) `>` the next bit is simply whether it is negative (zero is more than) `1∘⍭` the next bit is whether it is prime `0∘⍭` the final bit is whether it is non-prime `∧` `1∘<` one is less than it [Answer] # JavaScript (ES7), ~~244 238~~ 236 bytes Returns an array of strings. ``` n=>'negative/positive/triangular/cube/square/factorial/prime/composite'.split`/`.filter((s,i)=>(k=!i)?n<0:i-1?i<5?(g=n=>(x=k++**(2+i%2))<n?g(n):x==n)(i-2?i&n<0?-n:n:8*n+1):(g=i-5?k=>n>1?n%--k?g(k):k<2^i>6:0:n=>n>1?g(n/++k):n==1)(n):n>0) ``` [Try it online!](https://tio.run/##JZBBboMwEEX3OYW7SLHjGgNVqtbB@BDZV3GIQRPImBonilT17NRNV/Olp/e/NGd7s3MbYIoC/cktnV5QNxm63ka4OTn5GR4hBrDYX0cbZHs9Ojl/XW1wsrNt9AmNcgpwcbL1l4fisnyeRogHecg7GKMLlM4vwHRDB/0EzGBdKBClgXpraK/TKL3rgfPNhlYc1hVjNZqeIlN3rZFREJWB52QZgQrV@wZ5yVQyQWzNoBtsSoNrIYYkDUwNdfUJzZsqFP6zVCU5TwS1LtlfLzYFWzofKBJNxMeOIKk1KasiJc4Z@V4R0nqc/ejy0Sc/j36f3oA9LQuWT/a0jzZE@soIJ5kiWTpdKs7PHpBmJGNst/pZfgE "JavaScript (Node.js) – Try It Online") or [See a formatted version](https://tio.run/##hZJdb4IwFIbv/RXvLjZaERScbsOvH@HlsiWdAqlg6wDNkmW/3Z1aFD@SrUlDe56e9z3nhJXYiXJRyE3lKb2M98lkrzCZtoBXOCpORSV3sdMB0O1CYoIeIcDZ6FJeo8CiqpBCpdtcFARrFFq02H7YDDRZfYvKz60ojrBGjxYlYlFpEs0NrdGgLqOQ65NijYa1l14fioydBj0ReqPtJzKv4oKxsgPJbb8Ay@jJHd1nLSuoMK77jeqIhIfgxM19jMHZnUSQkoo6ap6BL4pnrot2GyyES7n3CDknBXWhYFfKFL8KRjePSJK8zsKcmQpDzEj9wdZPZ08hgtnPaNPXRdBIRze1S0yvejKLZjOl3OlF@8elqBXPy8gqZRkno4ycQ7wftIb/ttFr/cXVmbMZC7pw3YOLMu0HF@2fhtaomFTjwPeJLih9Au9lZGZDuWGPTq7L8U0PFlqVOo/9XJOLX@k5/ckqZUGP@xuxnFeiqFif0/icCA59EnLzV1oq5sDhfNT62f8C) ## How? We filter an array of number properties, keeping track of our current position in the index \$i\$: ``` i | Property | OEIS | Test ---+------------+---------+--------------------------------------------------------- 0 | negative | [A001478](https://oeis.org/A001478) | n < 0 1 | positive | [A000027](https://oeis.org/A000027) | n > 0 2 | triangular | [A000217](https://oeis.org/A000217) | look for k >= 0 such that k**2 = 8n+1 3 | cube | [A000578](https://oeis.org/A000578) | look for k >= 0 such that k**3 = |n| 4 | square | [A000290](https://oeis.org/A000290) | look for k >= 0 such that k**2 = n 5 | factorial | [A000142](https://oeis.org/A000142) | divide n by 1, 2, 3, etc. until it's either 1 or < 1 6 | prime | [A000040](https://oeis.org/A000040) | n > 1 and its largest proper divisor is equal to 1 7 | composite | [A002808](https://oeis.org/A002808) | n > 1 and its largest proper divisor is greater than 1 ``` ### Case \$i=0\$ (negative) We test whether \$n < 0\$. ### Case \$i=1\$ (positive) We test whether \$n > 0\$. ### Case \$2\le i \le 4\$ (triangular, cube, square) We use the following function, starting with \$k=0\$: ``` g = n => // n = input (x = k++ ** (2 + i % 2)) // x = either k**3 if i = 3, or k**2 otherwise; increment k < n ? // if the above result is less than n: g(n) // do a recursive call : // else: x == n // test whether x is equal to n ``` If \$i=2\$ (triangular test), \$g\$ is called with \$8n+1\$ (i.e. we test whether \$8n+1\$ is a perfect square). If \$i=3\$ (cube test), \$g\$ is called with \$|n|\$ (i.e. we test whether \$|n|\$ is a perfect cube). If \$i=4\$ (square test), \$g\$ is called with \$n\$ (i.e. we test whether \$n\$ is a perfect square). ### Case \$i=5\$ (factorial) We use the following function, starting with \$k=0\$: ``` g = n => // n = input n > 1 ? // if n is greater than 1: g(n / ++k) // increment k and do a recursive call with n / k : // else: n == 1 // test whether n is equal to 1 ``` ### Case \$i>5\$ (prime, composite) We use the following function: ``` g = k => // k = current divisor, initialized to n n > 1 ? // if n is greater than 1: n % --k ? // decrement k; if k is not a divisor of n: g(k) // do a recursive call : // else: k < 2 ^ // test whether k = 1 (n is prime) i > 6 // invert the result if i = 7 : // else: 0 // always return 0 (n is neither prime nor composite) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~101~~ ~~96~~ 88 bytes -5 bytes thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver) -8 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) ``` `t„gÔ³dÖ%oÐÒdpoÐÓv‚šg…iv‚cu¼çyÜ)Ã$quÂÂpÎX`qd g[U*8Ä ¬v1 Uk ÅÊU¬U<0Uõ³øU UõÊøU U¬v1 Uj]ð ``` [Try it online!](https://tio.run/##Jcq9CoJgFIfxvat4hxqKcyDLyqGrCF4IQjASpCJSUKHVdHGIqGiImlsaAgkams7/wuxren7DMxv7YVk6oVwk9XCQwsWxtsQWO9f/Zh9LIidPsukHk0heuK5wrmNdDSIkSHxshk7gKm@kGxZSJbfYUHqukCHXctP9psZDCjy1@gD5D/9pZuNeliODWtQmkzrUpR5ZxAZxi7hNbBJ3iLvEPWLLrvBi8AY "Japt – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~79~~ 71 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ë∙☺H▓»░g▬äεê▄ú▓▒º₧Σ↓i∟I∩├▼┬√&A4¼╔uë[Ü▼╒π←=Å♥\aâ╬°Æ■v⌂♂δ┴▄·╠.ë¶<→`┬╪½¥6X ``` [Run and debug it](https://staxlang.xyz/#p=89f90148b2afb0671684ee88dca3b2b1a79ee419691c49efc31fc2fb264134acc975895b9a1fd5e31b3d8f035c6183cef892fe767f0bebc1dcfacc2e89143c1a60c2d8ab9d3658&i=-8%0A-2%0A-1%0A0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A&a=1&m=2) Unpacked, ungolfed, and commented, it looks like this. ``` |c peek input and terminate if falsey 12{|Fm first 12 factorials # (1) is the input found in the array? x push original input from x register and G (2) execute program at trailing curly brace which tests for square-ness x push original input from x register |n get exponents of prime factorization |g gcd of array 3%! (3) is not a multiple of 3 x1|M push max(1, x) where x is the original input c copy value on the stack |p (4) is prime? s swap top two stack entries |fD (5) drop first element from prime factorization x8*^ push 8x+1 where x is the original input G (6) execute program at trailing curly brace which tests for square-ness x0> (7) is original input greater than zero? c! (8) logically negate the value at (7) `?|yL843smg!O5&;RVPC3&g9W!ISjvJN'n` compressed literal for "negative positive triangular composite prime cube square factorial" - these are the names in reverse order of the test results pushed at (1)-(8) :.j title case and split on spaces f filter list of names and implicitly output using the rest of the program as a predicate d drop the name revealing the corresponding test result on top of the stack terminate program } `G` target from above; when done, resume execution c|qJ= copy, floor square-root, square, then test equality; this is a test for squareness ``` [Run this one](https://staxlang.xyz/#c=%7Cc++++%09peek+input+and+terminate+if+falsey%0A12%7B%7CFm%09first+12+factorials%0A%23+++++%09%281%29+is+the+input+found+in+the+array%3F%0Ax+++++%09push+original+input+from+x+register+and+%0AG+++++%09%282%29+execute+program+at+trailing+curly+brace+which+tests+for+square-ness%0Ax+++++%09push+original+input+from+x+register%0A%7Cn++++%09get+exponents+of+prime+factorization%0A%7Cg++++%09gcd+of+array%0A3%25%21+++%09%283%29+is+not+a+multiple+of+3%0Ax1%7CM++%09push+max%281,+x%29+where+x+is+the+original+input%0Ac+++++%09copy+value+on+the+stack%0A%7Cp++++%09%284%29+is+prime%3F%0As+++++%09swap+top+two+stack+entries%0A%7CfD+++%09%285%29+drop+first+element+from+prime+factorization%0Ax8*%5E++%09push+8x%2B1+where+x+is+the+original+input%0AG+++++%09%286%29+execute+program+at+trailing+curly+brace+which+tests+for+square-ness%0Ax0%3E+++%09%287%29+is+original+input+greater+than+zero%3F%0Ac%21++++%09%288%29+logically+negate+the+value+at+%287%29%0A%60%3F%7CyL843smg%21O5%26%3BRVPC3%26g9W%21ISjvJN%27n%60%0A+++++++%09compressed+literal+for+%22negative+positive+triangular+composite+prime+cube+square+factorial%22%0A+++++++%09-+these+are+the+names+in+reverse+order+of+the+test+results+pushed+at+%281%29-%288%29%0A%3A.j++++%09title+case+and+split+on+spaces%0Af++++++%09filter+list+of+names+and+implicitly+output+using+the+rest+of+the+program+as+a+predicate%0A++d++++%09drop+the+name+revealing+the+corresponding+test+result+on+top+of+the+stack%0A+++++++%09terminate+program%0A%7D++++++%09%60G%60+target+from+above%3B+when+done,+resume+execution+%0A++c%7CqJ%3D%09copy,+floor+square-root,+square,+then+test+equality%3B+this+is+a+test+for+squareness&i=-8%0A-2%0A-1%0A0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A&a=1&m=2) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 67 65 60 59 bytes ``` “R!i“Ʋ“ŒR*3i“Ẓ“<2oẒ¬“ŻÄi“R“<0”vTị“*Ṙœȯ#Ḅṙ׬`ɲṇṭY¤²nxẊ2ı»Ḳ¤ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5wgxUwgebjt0CYgdXRSkJYxiP9w1yQgaWOUD2QcWgOS2X24BSQRBBI2eNQwtyzk4e5uIEfr4c4ZRyefWK/8cEfLw50zD08/tCbh5KaHO9sf7lwbeWjJoU15FQ93dRkd2Xho98Mdmw4t@f//vxkA "Jelly – Try It Online") A monadic link that accepts an integer and returns a list of strings. ## Explanation ``` “R!i“Ʋ“ŒR*3i“Ẓ“<2oẒ¬“ŻÄi“R“<0” First part of main link “ Begin list of strings separated by “ R Range: [1..n] ! Factorial [each] i Find index of argument “ , Ʋ Is square? “ , ŒR Balanced range: [-n..n] *3 Cube [each] i Find index of argument “ , Ẓ Is prime? “ , <2 Is less than 2? o Or Ẓ Is prime? ¬ Negate “ , Ż Range with zero: [0..n] Ä Prefix sums i Find index of argument “ , R Range [used to test for positive] “ , <0 Is less than 0? ” End list of strings vTị“*Ṙœȯ#Ḅṙ׬`ɲṇṭY¤²nxẊ2ı»Ḳ¤ Second part of main link v Evaluate each with the argument T Indices of truthy elements ị Index into ¤ ( “*Ṙœȯ#Ḅṙ׬`ɲṇṭY¤²nxẊ2ı» Compressed string "Factorial Square Cube Prime Composite Triangular Positive Negative" Ḳ Split on spaces ¤ ) ``` *Thanks to caird for 60->59* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~76~~ 75 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` _i¯ë.±D(IŲIÄ©3zmDïQIpIÑg3@Id*®LηPIå®ÅTIå)”îË¢…ï©×Ä›ˆÉíšâialÓª”¨¨"ular"«#sÏ ``` [Try it online](https://tio.run/##AYAAf/9vc2FiaWX//19pwq/Dqy7CsUQoScOFwrJJw4TCqTN6bUTDr1FJcEnDkWczQElkKsKuTM63UEnDpcKuw4VUScOlKeKAncOuw4vCouKApsOvwqnDl8OE4oC6y4bDicOtxaHDomlhbMOTwqrigJ3CqMKoInVsYXIiwqsjc8OP//8tOA) or [verify all test cases](https://tio.run/##AbUASv9vc2FiaWX/dnk/IiDihpIgIj95RP9facKvw6suwrFEKHnDhcKyecOEwqkzem1Ew69ReXB5w5FnM0B5ZCrCrkzOt1B5w6XCrsOFVHnDpSnigJ3DrsOLwqLigKbDr8Kpw5fDhOKAusuGw4nDrcWhw6JpYWzDk8Kq4oCdwqjCqCJ1bGFyIsKrI3PDj/99LFz/Wy04LC0yLC0xLDAsMSwyLDMsNCw1LDYsNyw4LDksMTAsMTEsMTJd). **Explanation:** ``` _i # If the (implicit) input is 0: ¯ # Push an empty list ë # Else: .± # Push the signum of the (implicit) input (-1 if <0; 0 if 0; 1 if >0) # i.e. -8 → -1 D( # Duplicate and take it's negative # i.e. -1 → 1 IŲ # Push the input, and check if it's a square # (negative values will result in the negative numbers themselves) # i.e. -8 → -8 IÄ # Push the absolute value of the input # i.e. -8 → 8 © # Store it in the register (without popping) to reuse later 3z # Push 1/3 m # Take the absolute input to the power of 1/3 # (NOTE: a^(1/3) is the same as ³√a) # i.e. 8 → 2.0 DïQ # Check if this is an integer without decimal digits # i.e. 2.0 → 1 (truthy) Ip # Push the input, and check if it's a prime # i.e. -8 → 0 (falsey) IÑ # Push the input, and get a list of its divisors # i.e. -8 → [1,2,4,8] g # Take the length of that list # i.e. [1,2,4,8] → 4 3@ # And check if it's larger than or equal to 3 # (the list includes 1, hence the check for >=3 instead of >=2) # i.e. 4 >= 3 → 1 (truthy) Id # Push the input again, and check if it's non-negative # i.e. -8 → 0 (falsey) * # Check if both are truthy # i.e. 1 and 0 → 0 (falsey) ®L # Create a list in the range [1, absolute value of the input] # i.e. 8 → [1,2,3,4,5,6,7,8] η # Get a list of prefixes of this list # → [[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5],[1,2,3,4,5,6],[1,2,3,4,5,6,7],[1,2,3,4,5,6,7,8]] P # Get the product for each prefix-list # → [1,2,6,24,120,720,5040,40320] Iå # Check if the input is in this list # i.e. [1,2,6,24,120,720,5040,40320] and -8 → 0 (falsey) ®ÅT # Create a list of all triangular numbers below or equal to # the absolute value of the input # i.e. 8 → [0,1,3,6] Iå # Check if the input is in this list # i.e. [0,1,3,6] and -8 → 0 (falsey) ) # Wrap all values on the stack into a single list # → [-1,1,-8,1,0,0,0,0] ”îË¢…ï©×Ä›ˆÉíšâialÓª” # Push dictionary string "Positive Negative Square Cube Prime Composite Factorial Triangle" ¨¨ # Remove the last two characters (the "le" of "Triangle") "ular"« # Append "ular" # # Split this string by spaces s # Swap to take the earlier created list again Ï # And only leave the strings at the truthy indices # (NOTE: Only 1 is truthy in 05AB1E) # i.e. [-1,1,-8,1,0,0,0,0] → ["Negative","Cube"] # (and output the result implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”îË¢…ï©×Ä›ˆÉíšâialÓª”` is `"Positive Negative Square Cube Prime Composite Factorial Triangle"`. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~60~~ ~~65~~ ~~61~~ 59 bytes *Edit: +5 bytes to fix zero as a square, cube & triangular, and to fix zero, one and negative numbers as non-composites (in line with test cases)...* *...but then -4 bytes thanks to Razetime, by changing all the forks (`§:` and `§e`) to a mapping over a bigger list of functions* ``` f+m€⁰mëmΠm□m^3mΣΘḣ⁰mëṗȯ>2LḊ>0<0⁰w¨◄Γq□ṡ_ẏĊ8ζŀ⁸→PṘβ□θpż√₁□Ġë ``` [Try it online!](https://tio.run/##yygtzv7/P00791HTmkeNG3IPr849tyD30bSFuXHGuecWn5vxcMdiiPjDndNPrLcz8nm4o8vOwMYAKFh@aMWj6S3nJhcClT/cuTD@4a7@I10W57YdbXjUuONR26SAhztnnNsElDy3o@Donkcdsx41NQJ5RxYcXv3//38zAA "Husk – Try It Online") **How?** ``` f # select each element if input satisfies: + # combine 2 lists of 4 together: m€⁰§:mΠ§:m□§em^3mΣΘḣ⁰ # first list: m€⁰ # check whether input is §: §: §e # among mΠ # factorials of m□ # or squares of m^3 # or cubes of mΣ # or triangular numbers of Θḣ⁰ # series from 0..input mëṗȯ>2LḊ>0<0⁰ # second list: m ⁰ # map functions over input: ë # list of 4 functions ṗ # is prime? ȯ>2LḊ # is composite (more than 2 divisors)? >0 # is positive? <0 # is negative? # elements to select: w # split on spaces ¨◄Γq□ṡ_ẏĊ8ζŀ⁸→PṘβ□θpż√₁□Ġë # compressed string # "Factorial Square Cube Triangular Prime Composite Positive Negative" ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~405~~ 259 bytes Thanks to @ASCII-only ``` def z(n): x=y=1 while x<n:x*=y;y+=1 return"Factorial "*(x==n)+"Square "*(n>=0and n**.5%1==0)+"Cube "*(abs(n)**(1/3)%1==0)+"Negative "*(n<0)+"Positive "*(n>0)+"Triangular "*(n>0and(8*n+1)**.5%1==0)+["Composite ","Prime "][all(n%x for x in range(2,n))]*(n>1) ``` [Try it online!](https://tio.run/##jVNbS8MwFH5ef8UxICRd1WXzMqcRxAsIIoK@jT3ELdNATWuaajfxt88kbceoVnxLv9v5ckjThXlJ1GC1mok5LLEio6BTsAWjQefjRcYCilM1KkK2OFl0HaiFybVC13xqEi15DCjEBWOKdNHDW861cIA6Yz2uZqDCcPdgmzLWs/RF/uRJ/pTZMWGI6d6A1OSdeOZGvpfuU4fcJ5lcI2cOebTz1HMec11hdgQehqpLycacMbpIXlNnttYI3Wv5ag@TMY9jrLYLmCcaCpAKtA0TuB8pQiYujpKVEZmZ8kxkwGAc4J1hBJ@@tw2qG6IvElmq76gGRlvlPceU@0ERlBpPbFrWO3W1q9vbY23buH/p9RVaTP7apWzgZD@on3H7vkq9u187eN3Br3meOmxGtLRrjj5qjxw2I6tlrdVedfzP7rT3h7DZitL2WrTfGuT4SRC4dyZVmpsIuMo@hPuC9QOzf1mqpTK4kizLAyFBR84hEwbXyHi0Qye7WRpLgxEgQmCLVYk2pEpB1@c3t1eXEYgiFVMjZqieSlbf "Python 3 – Try It Online") Old Code Generates the squares, cubes, and factorials into lists to check against, has a function to check for primality (and consequently compositeness), uses a simple equality to check for positivity/negativity, and checks if `8n+1` is a perfect square to determine if `n` is a triangular number. Hardcoded the limits for the square, cube, and factorial lists. Returns the answer in a set, which I assume is acceptable (adding elements to a list requires more bytes). ``` p=lambda n:all(n%x!=0 for x in range(2,n)) def z(n): f,a,x,y,s,c=[],set(),1,1,[i*i for i in range(44721)],[i**3 for i in range(-1259,1259)] while x<2*10**9:f.append(x);x*=y;y+=1 if n in f:a.add("Factorial") if n in s:a.add("Square") if n in c:a.add("Cube") if n>0: a.add("Positive") if 8*n+1 in s:a.add("Triangular") if n>1:a.add(("Composite","Prime")[p(n)]) if n<0:a.add("Negative") return a ``` [Try it online!](https://tio.run/##jZNfa9swFMWf40@hGgaWe1ssJ12TtB6MrYVBKYXtLfhBteVU4MiaLa9Oxz57Zsn/Mmcew2As/8459@oiyb16ycT8cJBBSnfPMUViTdPUEe@qs8BDSZajCnGBciq2zPFBYGzFLEFvjsBra5YAhQr2UEAUbEIomHIwkPrZcJcbNx/ci8W1T3ComTsfwwviX61Av3BozV5feMpQdeu7xHPd1Tq5pFIyETsVvqncYH@zPw@INeMJEjoiWdNLGseOfU8jleWcpjYeaNHRr99LmrNjFHXoU/ncgw9evbNZC56ygiv@w0BNl644J3@kfqvriW2Z0rwPIC2rc7Od1AnMBvsp57s6ZyPr2YWt9NbrYh7ZlnaFcqbKXCB6UKxQES1YgQK0sZyLJaCfTa8wGH5hqJGv0egfmZR7mrTzANRoDDi2DNOEYQ7Q2453brymhQlTs3kjm2vZCTqNW5hWjgd40oPRXf01z6D344iJ7salr6cjl@PIdli92qhW/9k78f4hHHdFyHRbxJ8M0jy0LHPhhCwVICqKV6ZXqD9g9ZGXORfKaSVvzQduzmm3QmdBa9ZXpDHY9x@/PNx9BsQqySLFYrsrgA@/AQ "Python 3 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 286 bytes ``` n=>{int k=0;return(n>0?"Positive":n<0?"Negative":"")+(Math.Sqrt(8*n+1)%1==0?"Triangular":"")+(new int[n].Where((a,b)=>n%++b<1).Count()>2?"Composite":n<3?"":"Prime")+(Math.Pow(n,1/3d)%1>0?"":"Cube")+(Math.Sqrt(n)%1>0?"":"Square")+(g(k)?"Factorial":""));bool g(int i)=>i>1?g(i/++k):1==i;} ``` [Try it online!](https://tio.run/##VZAxb8IwEIX3/orIEpJdB4jLUpE4GZCY2gqJSgxVByd1wilwLo5TBsRvTw@oWnWynu/pve@u6sZVB8OyxyoDDHEXPGCT13pAnZ/oJ2p1knobeo8c86RgK9dBgC/L5piRfLGNuUnGhOTPJmwn64MP/PEepRIjpTW5Xj0YbPqd8T8@tMeI0t/wfbLZWm85N3EpdI4jKctMicnC9Ri4yB8KtnD7z0vptXJWMIpYedjb376VO3KM1XT2QX0XRnIs@tL@B8K/4frQG38dN7wVBVuaKjhC3F3pRFo6t4saflkfCApyVZCaStmKOS0E6XlI72rnbw46EGRaJfRIKTaeSJ8ALWenJB7PzvPopM4shrjmQNnDNw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 63 bytes ``` ÅTIL3mILÄ!)IQO`΋ΛIŲIpD≠$‹*)“×ÄšâialîË¢…ï©›ˆÉí“#.•’α`ë\Ä•šsÏ™ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cGuIp49xrqfP4RZFTc9A/4TDfY8adoKIXZ6HWw9t8ixwedS5QAUopqX5qGHO4emHW44uPLwoMzHn8LrD3YcWPWpYdnj9oZVA5afbDnceXgtUo6z3qAEoPvPcxoTDq2MOtwB5RxcWH@5/1LLo/39dCwA "05AB1E – Try It Online") or [Verify all test cases!](https://tio.run/##LYqxasJQGEZ3n@LT6mAh0Ru1tRA3lwuCCB07JBKlF9rcYFJwzBAFKdRRhA41g1BKW@pWx/w4CX2I@yLxCl3Ox3c4Qze8z/OxnGAK4cNow7BgMKAOaFpAA2gCLeAKuAbawA1YHYyBWQVPFoBgIvxojFLF8tBBCeWpljUZRDUZukMx@h@Ywg@eIjMSErZtnzNP@qM8p9kt7zUeeY@SYpUP@g69qPj3jD2nWbbjQVct3sraXVZV/EorSg4bSoX7QF/0nKUq3tJ39q7z45wW9KmbC1PF2q//fhz6uKNEv8MmpKVK0hM) **Commented**: ``` ÅT # push the triangular numbers up to the input IL # push the range [1..input] 3m # take each number to the third power IL # push the range [1..input] Ä # take absolute values ! # take the factorial of each number ) # collect the three list in a list of lists IQ # for each element chack if it is equal to the input O # sum the sublists ` # and push all three values to the stack ΋ # is 0 < input? (Î pushes 0 and the input) Λ # is 0 > input? IŲ # is the input a square number? Ip # is the input prime? D≠ # duplicate this value and invert the copy $ # push 1 and the input ‹ # is 1 < input * # is the input composite? (not prime & > 1) ) # collect all these values in a list “×ÄšâialîË¢…ï©›ˆÉí“ # push compressed string "cube factorial positive negative square prime composite" # # split on spaces .•’α`ë\Ä• # push compressed string "triangular" š # and prepend it to the word list s # swap the integer back to the top Ï # keep all words where 1's are in the integer list ™ # titlecase all words ``` ]
[Question] [ *Disclaimer: Levenshtein coding is completely unrelated to the [Levenshtein edit distance metric](http://en.wikipedia.org/wiki/Levenshtein_distance).* <Insert long story about why Levenshtein codes need to be calculated here.> # The code [Levenshtein coding](http://en.wikipedia.org/wiki/Levenshtein_coding) is a system of assigning binary codes to nonnegative integers that retains some weird property in probability which isn't relevant for this challenge. We will denote this code as *L*(*n*). Wikipedia describes this as a five-step process: 1. Initialize the step count variable *C* to 1. 2. Write the binary representation of the number without the leading `1` to the beginning of the code. 3. Let *M* be the number of bits written in step 2. 4. If *M* is not 0, increment *C*, repeat from step 2 with *M* as the new number. 5. Write *C* `1` bits and a `0` to the beginning of the code. However, the code can also be described recursively: 1. If the number is 0, then its code is `0`. 2. Write the binary representation of the number without the leading `1` to the beginning of the code. 3. Let *M* be the number of bits written in step 2. 4. Write *L*(*M*) to the beginning of the code. 5. Write a `1` bit to the beginning of the code. For those who prefer examples, here is the recursive process for *L*(87654321), with ![](https://i.stack.imgur.com/JXVXT.png) denoting concatenation: ![](https://i.stack.imgur.com/oDKYp.png) # The challenge Write a program or function that, given a number *n*, outputs the bitstring *L*(*n*) in any reasonable format (this includes returning a number with said bits). Standard loopholes are, as always, disallowed. # Examples Input: `5` Output: `1110001` Input: `30` Output: `111100001110` Input: `87654321` Output: `111110000101001001110010111111110110001` Input: `0` Output: `0` [Answer] # Haskell, 70 bytes ``` b 0=[] b n=b(div n 2)++[mod n 2] f 0=[0] f n|1:t<-b n=1:f(length t)++t ``` Defines a function `f : Int -> [Int]`. For example, `f 5 == [1,1,1,0,0,0,1]`. [Answer] # Python, 49 bytes ``` f=lambda n:n and'1%s'%f(len(bin(n))-3)+bin(n)[3:] ``` Test it on [Ideone](http://ideone.com/Is8Hz5). [Answer] # Mathematica, 61 bytes ``` f@0={0};f@n_:=Join[{1},f@Length@#,#]&@Rest@IntegerDigits[n,2] ``` [Answer] ## JavaScript (ES6), ~~54~~ 52 bytes ``` f=n=>(s=n.toString(2)).replace(1,_=>1+f(s.length-1)) ``` ``` <input type=number oninput=o.textContent=f(+this.value)><pre id=o> ``` Edit: Saved 2 bytes thanks to @Arnauld. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḣ;LÑ$; BÇṀ¡ ``` [Try it online!](http://jelly.tryitonline.net/#code=4biiO0zDkSQ7CkLDh-G5gMKh&input=&args=ODc2NTQzMjE) or [verify all test cases](http://jelly.tryitonline.net/#code=4biiO0zDkSQ7CkLDh-G5gMKhCsOH4oKsRw&input=&args=NSwgMzAsIDg3NjU0MzIxLCAw). ### How it works The submission consists of a pair of mutually recursive links. ``` BÇṀ¡ Main link. Argument: n B Convert n to binary. ¡ Execute... Ç the helper link... Ṁ m times, where m is the maximum of n's binary digits. Ḣ;LÑ$; Helper link. Argument: A (array of binary digits) Ḣ Head; remove and return the first element of A. $ Combine the two links to the left into a monadic chain. L Yield the length (l) of A without its first element. Ñ Call the main link with argument l. ; Concatenate the results to both sides. ; Append the tail of A. ``` [Answer] # Pyth, 12 bytes ``` L&bX1.Bbyslb ``` [Demonstration](https://pyth.herokuapp.com/?code=L%26bX1.Bbyslby&input=87654321&debug=0) (The `y` at the end is to run the resulting function on the input) Explanation: ``` L&bX1.Bbyslb L def y(b): &b If b is 0, return 0. This is returned as an int, but will be cast to a string later. lb Take the log of b s Floor y Call y recursively X1 Insert at position 1 into .Bb Convert b to binary. ``` [Answer] # SQF, 110 Recursive function: ``` f={params[["i",0],["l",[]]];if(i<1)exitWith{[0]};while{i>1}do{l=[i%2]+l;i=floor(i/2)};[1]+([count l]call f)+l} ``` Call as: `[NUMBER] call f` **Note this doesn't actually work for 87654321 or other large numbers due to a bug in the ArmA engine. Although it will probably be fixed soon, and should work according to spec.** ([This Ticket Here](https://feedback.bistudio.com/T119933)) [Answer] # PHP, 116 114 bytes ``` <?$f=function($i)use(&$f){$b=decbin($i);return!$b?0:preg_replace('/^1/',1 .$f(~~log10($b)),$b);};echo$f($argv[1]); ``` Provide the number as the first argument. ## Update: * Saved a byte by replacing `strlen($b)-1` with `~~log10($b)` (finally understood why everybody else was using logarithm) and another by concatenating differently. [Answer] # Ruby, 38 bytes Very similar to [Neil's JavaScript answer](https://codegolf.stackexchange.com/a/89846/11261). ``` f=->n{("%b"%n).sub(/1\K/){f[$'.size]}} ``` See it on repl.it: <https://repl.it/CnhQ> [Answer] # Java 8 (Full Program), ~~257~~ 249 bytes ``` interface M{static void main(String[]a)throws Exception{int i=0,j;while((j=System.in.read())>10)i=i*10+j-48;System.out.print(L(i));}static String L(int i){if(i==0)return "0";String s=Integer.toString(i,2);return "1"+L(s.length()-1)+s.substring(1);}} ``` Readable Version w/ Explanation (It's mostly just recursion): ``` interface M { static void main(String[]a) throws Exception { // Using Exception is unadvised in real coding, but this is Code Gold int i = 0, j; // i stores the input; j is a temporary variable while ((j = System.in.read()) > 10) // Read the input to j and stop if it is a newline. Technically this stops for tabulators as well, but we shouldn't encounter any of those... i = i * 10 + j - 48; // Looping this step eventually reads the whole number in from System.in without using a reader (those take up a lot of bytes) System.out.print(L(i)); // Make a method call } static String L(int i) { // This gets the actual Levenshtein Code if (i == 0) return "0"; // The program gets a StackOverflowException without this part String s = Integer.toString(i, 2); // Shorter than toBinaryString return "1" + L(s.length() - 1) + s.substring(1); // Write in the first character (which is always a one), followed by the next L-code, followed by the rest of the binary string } } ``` **EDIT 1**: *Saved 8 bytes*: The first character of the binary string is *always* 1; therefore, rather than using `s.charAt(0)`, a better option is simply `"1"`. [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` ?ö:1Ṡ+o₀LtḋΘøI ``` [Try it online!](https://tio.run/##ASEA3v9odXNr//8/w7Y6MeG5oCtv4oKATHThuIvOmMO4Sf///zU "Husk – Try It Online") Uses a simple recursive approach. (Dennis's double recursion is insane.) ]
[Question] [ Write a program in a language with name `A` that, given a string `S`, outputs the name of a different programming language `B`. The length of `B` must be equal to the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) (abbr. "LD") between `A` and `S`. To be considered a programming language, `B` must have an esolangs page or a Wikipedia page. ## Example: ``` (Suppose the program is coded in Python) Input: Jython Output: R Input: Pyt4oq Output: Go Input: Rs7hon Output: C++ ``` The LD between `Python` and `Jython` is one, so the output `R` You only need to cover up to an LD of up to `12`. You can assume that an LD of `0` will never occur. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. (This is my first challenge! Feedback is appreciated) --- # Leaderboard ``` var QUESTION_ID=58974,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # PHP, ~~137~~ 135 Requires error reporting off and PHP 5.4+. Input is GET variable `a`. ``` <?=explode(~ß,~­ß¼Üß¼ÔÔßµž‰žß¬œž“žß¾Š‹¶‹ß¾‘“›¼ß«¶Ò½¾¬¶¼ß½Š“š˜Š’ßµž‰žŒœ–‹ß²ž‹—š’ž‹–œžß¾œ‹–‘¬œ–‹)[levenshtein(PHP,$_GET[a])-1]; ``` Hexdump: ``` 00000000: 3C 3F 3D 65 78 70 6C 6F - 64 65 28 7E DF 2C 7E AD |<?=explode(~ ,~ | 00000010: DF BC DC DF BC D4 D4 DF - B5 9E 89 9E DF AC 9C 9E | | 00000020: 93 9E DF BE 8A 8B 90 B6 - 8B DF BE 8D 91 90 93 9B | | 00000030: BC DF AB B6 D2 BD BE AC - B6 BC DF BD 8A 9D 9D 93 | | 00000040: 9A 98 8A 92 DF B5 9E 89 - 9E 8C 9C 8D 96 8F 8B DF | | 00000050: B2 9E 8B 97 9A 92 9E 8B - 96 9C 9E DF BE 9C 8B 96 | | 00000060: 90 91 AC 9C 8D 96 8F 8B - 29 5B 6C 65 76 65 6E 73 | )[levens| 00000070: 68 74 65 69 6E 28 50 48 - 50 2C 24 5F 47 45 54 5B |htein(PHP,$_GET[| 00000080: 61 5D 29 2D 31 5D 3B - |a])-1];| 00000087; ``` Readable version: ``` <?=explode(' ','R C# C++ Java Scala AutoIt ArnoldC TI-BASIC Bubblegum Javascript Mathematica ActionScript')[levenshtein(PHP,$_GET[a])-1]; ``` [Answer] # C, 183 ``` main(s){char* a[12]={"R","C#","C++","Java","COBOL","Python","Clipper","VBScript","Smalltalk","Javascript","Mathematica","ActionScript"};printf(a[strlen(gets(&s))-!!strchr(&s,67)-1]);} ``` Picking a language with a one character name lets you cheat with the distance calculation: any string's distance from "C" is just the length of the string, minus one if it includes "C". I imagine R or J could beat this using the same strategy. [Answer] # Perl 5, ~~325~~ 276 Using a bit of recursion to calculate the Levenshtein distance. ``` @X=(P,e,r,l);$y=@Y=split//,pop;sub L{my($n,$m)=@_;return$m,if!$n;return$n,if!$m;my$c=$X[$n]eq$Y[$m]?0:1;(sort{$a<=>$b}(L($m-1,$n)+1,L($m,$n-1)+1,L($m-1,$n-1)+$c))[0]}print qw(C C# C++ Java COBOL Python Clipper VBScript Smalltalk Javascript Mathematica ActionScript)[L(4,$y)-1] ``` My original version had some issues with the longer inputs. Till I realised that the Perl sort function sorts alphabetically. Using substrings instead of arrays turns out to make it slightly longer. ``` @L=qw(C C# C++ Java COBOL Python Clipper VBScript Smalltalk Javascript Mathematica ActionScript);sub l{my($s,$t)=@_;return length($t)if!$s;return length($s)if!$t;my($u,$v)=(substr($s,1),substr($t,1));substr($s,0,1)eq substr($t,0,1)?l($u,$v):(sort{$a<=>$b}(l($u,$v),l($s,$v),l($u,$t)))[0]+1}print$L[l('Perl',pop)-1] ``` ### Test ``` $ perl levenshtein.pl Php C++ ``` [Answer] # O, 107 bytes Using the tip from @histocrat to make the distance calculation simpler. Also used languages with The same starting letter to remove a few characters ``` "pyrodecimal""hakespeare""tackstack""nowflake""nowball""nowman""onata""ADOL""taq""oT""R"""ie\'O<-1-{;}d'Soo ``` [Try it here](http://o-lang.herokuapp.com/link/code=%22pyrodecimal%22%22hakespeare%22%22tackstack%22%22nowflake%22%22nowball%22%22nowman%22%22onata%22%22ADOL%22%22taq%22%22oT%22%22R%22%22%22ie%5C%27O%3C-1-%7B%3B%7Dd%27Soo&input=TOOOOT) [Answer] # J, 115 bytes ``` {&((}.&'YABC'&.>|.i.4),(g'SMITHb'),'Clojure';(g'ComeFrom2'),((g=:}:;])'StackStacks'),<'CoffeeScript')@<:@(#-'J'&e.) ``` This is using histocrat's calculation trick (using a 1-letter language), and generates the following list of languages: ``` ┌─┬──┬───┬────┬─────┬──────┬───────┬────────┬─────────┬──────────┬───────────┬────────────┐ │C│BC│ABC│YABC│SMITH│SMITHb│Clojure│ComeFrom│ComeFrom2│StackStack│StackStacks│CoffeeScript│ └─┴──┴───┴────┴─────┴──────┴───────┴────────┴─────────┴──────────┴───────────┴────────────┘ ``` e.g.: ``` {&((}.&'YABC'&.>|.i.4),(g'SMITHb'),'Clojure';(g'ComeFrom2'),((g=:}:;])'StackStacks'),<'CoffeeScript')@<:@(#-'J'&e.) 'C++' ┌───┐ │ABC│ └───┘ {&((}.&'YABC'&.>|.i.4),(g'SMITHb'),'Clojure';(g'ComeFrom2'),((g=:}:;])'StackStacks'),<'CoffeeScript')@<:@(#-'J'&e.) 'ActionScript' ┌────────────┐ │CoffeeScript│ └────────────┘ f=:{&((}.&'YABC'&.>|.i.4),(g'SMITHb'),'Clojure';(g'ComeFrom2'),((g=:}:;])'StackStacks'),<'CoffeeScript')@<:@(#-'J'&e.) f 'Jython' ┌─────┐ │SMITH│ └─────┘ f 'Python' ┌──────┐ │SMITHb│ └──────┘ ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 73 bytes Not even a single-character language name and still the shortest answer here! ``` •äƵí•hR.L<Uõ'R„oT…taq.•₃γ•.•~ÙÚ•„€Ó…Ž„€Óïß…€Ófа„‚‚¦'Ϻ¦“p¾»oãá“)Xè'Sìá ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcOiw0uObT28FsjICNLzsQk9vFU96FHDvPyQRw3LShIL9YASj5qaz20G0iB23eGZh2eBxBrmPWpac3gyUNXRvTDO4fWH5wMFwOy0owsObQBKHG561DALTBxapn64/9CuQ8seNcwpOLTv0O78w4sPLwRyNCMOr1APPrzm8ML//w3NnJyN3AA "05AB1E – Try It Online") ``` •äƵí•hR.L<U...Xè'Sìá # full program á # get only letters of... .L # Levenshtein distance between... # implicit input... .L # and... •äƵí• # 14793296... h # in hexadecimal... R # reversed... < # minus 1... U Xè # th element of... ... # ["", "R", "oT", "taq", "ADOL", "onata", "now man", "now ball", "nowf lake", "tack stack", "hakespeare", "p yro decimal"] ì # prepended with... 'S # literal ``` ]
[Question] [ > > ### Notice > > > This challenge has ended and will not be re-judged, but feel free to post answers and test your program against the others with the Control Program! > > > The aim of this challenge is to make an AI to win a fight against another AI by strategically drawing a wall on a 25x25 grid to block the opponent. ### Input 25 lines separated by and ending with `;` as a command-line argument. This will include: * Empty spaces `.` * Walls `#` * Players `1` and `2` (The opponent is always `2`) **Example** ``` ###############..........;..............#..........;..............#..........;..............#..........;..............#..........;...........1###..........;.........................;.........................;.........................;.........................;.........................;.........................;.........................;.........................;.........................;.........................;.........................;.........................;.........................;...................###...;...................#.##..;2..................#..#..;#..................##.#..;#...................#.###;....................#####; ``` which represents the following map: ``` ###############.......... ..............#.......... ..............#.......... ..............#.......... ..............#.......... ...........1###.......... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ...................###... ...................#.##.. 2..................#..#.. #..................##.#.. #...................#.### ....................##### ``` ### Output A string written to the console starting with the character representing the direction the AI wishes to turn. This *is* case sensitive! * North `N` * East `E` * South `S` * West `W` * Give up (Anything else) **Example** ``` W ``` ### Game Rules * As the AIs move, they will leave a solid trail of walls behind them. * The players start in the top-left and bottom-right corners * The game lasts until any AI hits a wall or the AIs crash into each other. + An AI wins if their opponent crashes first + There is **no** winner or loser if the AIs both lose at the same time. * If an AI goes off one edge of the grid, they continue in the same direction from the other side. ### Rankings > > 1st Place - FloodBot (Java, 12 wins) > > > 2nd Place - FluidBot (Python, 9 wins) > > > 3rd Place - FillUpBot (C++, 8 wins) > > > 4th Place - AwayBot (Ruby, 5 wins) > > > 5th Place - ArcBot (Python, 4 wins) > > > 6th Place - BlindSnake (Batch, 2 wins) > > > 6th Place - RandomBot (C#, 2 wins) > > > ### Control Program (Tested for Python 3.3.3) The program is run with arguments of the two commands and a single argument (`""` if not required) for the AIs eg. `Control.py "ruby" "AwayBot.rb" "FillUpBot.exe" ""`. It can be downloaded [here](https://docs.google.com/uc?id=0B20E690amPkRdDdCblBhX21oSGc&export=download). ``` import sys, subprocess Program1, Argument1, Program2, Argument2, Player1, Player2, Grid = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], [0, 0], [24, 24], [['.' for y in range(25)] for x in range(25)] while True: Str = '' for x in range(25): for y in range(25): if Grid[x][y] == '1' or Grid[x][y] == '2': Grid[x][y] = '#' Grid[Player1[0]][Player1[1]] = '1' Grid[Player2[0]][Player2[1]] = '2' for y in range(25): for x in range(25): Str += Grid[x][y] Str += ';' if Argument1 == '': move = subprocess.Popen([Program1, Str], stdout=subprocess.PIPE).stdout.read().decode('ASCII')[0] else: move = subprocess.Popen([Program1, Argument1, Str], stdout=subprocess.PIPE).stdout.read().decode('ASCII')[0] Lose1 = False if move == 'N': if Player1[1] > 0: Player1[1] -= 1 else: Player1[1] = 24 elif move == 'E': if Player1[0] < 24: Player1[0] += 1 else: Player1[0] = 0 elif move == 'S': if Player1[1] < 24: Player1[1] += 1 else: Player1[1] = 0 elif move == 'W': if Player1[0] > 0: Player1[0] -= 1 else: Player1[0] = 24 else: Lose1 = True if Grid[Player1[0]][Player1[1]] == '#' or Grid[Player1[0]][Player1[1]] == '2': Lose1 = True print('Player 1:', move) if Argument2 == '': move = subprocess.Popen([Program2, Str.replace('2','3').replace('1','2').replace('3','1')], stdout=subprocess.PIPE).stdout.read().decode('ASCII')[0] else: move = subprocess.Popen([Program2, Argument2, Str.replace('2','3').replace('1','2').replace('3','1')], stdout=subprocess.PIPE).stdout.read().decode('ASCII')[0] Lose2 = False if move == 'N': if Player2[1] > 0: Player2[1] -= 1 else: Player2[1] = 24 elif move == 'E': if Player2[0] < 24: Player2[0] += 1 else: Player2[0] = 0 elif move == 'S': if Player2[1] < 24: Player2[1] += 1 else: Player2[1] = 0 elif move == 'W': if Player2[0] > 0: Player2[0] -= 1 else: Player2[0] = 24 elif Lose1: Lose2 = True else: Lose2 = True print('Player 2:', move) print(Str.replace(';', '\n')) if Grid[Player2[0]][Player2[1]] == '#': Lose2 = True if Lose1 and Lose2: print('Draw!') break elif Lose1: print('Player 2 wins!') break elif Lose2: print('Player 1 wins!') break ``` [Answer] # Floodbot **Java** This guy is all about avoidance. He doesn't care to try to trap the opponent, he just wants to live. To do that, he flood-fills each direction to see which way will lead to the biggest open area. He also thinks the enemy is unpredictable, so he treats each square immediately surrounding them as already being a wall. If that leads to no possible direction, he falls back to the "actual" map. ``` public class Floodbot { boolean[][] walkable; boolean[][] actual; boolean[][] map; int px; int py; void run(String[] input){ int direction = 0; if(read(input)) direction = bestPath(findPaths(false), true); System.out.print(directions[direction]); } int bestPath(int[] paths, boolean first){ if(!first) paths = findPaths(true); int bestDir = 0; int best = 0; for(int i=0;i<paths.length;i++) if(paths[i] > best){ best = paths[i]; bestDir = i; } if(best==0 && first) return bestPath(paths, false); return bestDir; } static int floodCount; void flood(boolean[][] visited, int x, int y){ if(visited[x][y] || !map[x][y]) return; floodCount++; visited[x][y] = true; for(int dir=0;dir<4;dir++){ int nx = dir%2==1 ? wrap(x+dir-2) : x; int ny = dir%2==0 ? wrap(y+dir-1) : y; flood(visited, nx, ny); } } int[] findPaths(boolean useActual){ int[] paths = new int[4]; map = useActual ? actual : walkable; for(int i=0;i<4;i++){ floodCount = 0; int nx = i%2==1 ? wrap(px+i-2) : px; int ny = i%2==0 ? wrap(py+i-1) : py; flood(new boolean[size][size], nx, ny); paths[i] = floodCount; } return paths; } boolean read(String[] input){ if(input.length < 1 || input[0].length() < size*size) return false; String[] lines = input[0].split(";"); if(lines.length < size) return false; walkable = new boolean[size][size]; actual = new boolean[size][size]; for(int x=0;x<size;x++) for(int y=0;y<size;y++){ walkable[x][y] = true; actual[x][y] = true; } for(int y=0;y<size;y++) for(int x=0;x<size;x++){ char pos = lines[y].charAt(x); switch(pos){ case '.': break; case '2': actual[x][y] = false; walkable[x][y] = false; walkable[wrap(x+1)][y] = false; walkable[wrap(x-1)][y] = false; walkable[x][wrap(y+1)] = false; walkable[x][wrap(y-1)] = false; break; case '1': px = x; py = y; case '#': default: walkable[x][y] = false; actual[x][y] = false; } } return true; } public static void main(String[] input){new Floodbot().run(input);} static int wrap(int c){return (size+c)%size;} static final String[] directions = {"N","W","S","E"}; static final int size = 25; } ``` [Answer] # BlindSnake ### Batch This bot only watches its close surroundings. If there isn't a wall, it moves there. ``` @echo off setlocal enableextensions enabledelayedexpansion set map=%1 REM find position set I=0 set L=-1 :l if "!map:~%I%,1!"=="" goto ld if "!map:~%I%,1!"=="1" set L=%I% set /a I+=1 goto l :ld set /a pos = %L% set /a row = %pos% / 26 set /a col = %pos% %% 26 REM find surroundings If %row%==0 ( set /a northPos = 24 * 26 + %col% ) else ( set /a rowDown = %row% - 1 set /a northPos=!rowDown! * 26 + !col! ) If %row%==24 ( set /a southPos = %col% ) else ( set /a rowDown = %row%+1 set /a southPos=!rowDown!*26+!col! ) If %col%==0 ( set /a westPos = %row% * 26 + 24 ) else ( set /a westPos = %pos% - 1 ) If %col%==24 ( set /a eastPos = %row% * 26 ) else ( set /a eastPos = %pos% + 1 ) REM choose move if "!map:~%northPos%,1!" neq "#" ( echo N goto end ) if "!map:~%eastPos%,1!" neq "#" ( echo E goto end ) if "!map:~%southPos%,1!" neq "#" ( echo S goto end ) if "!map:~%westPos%,1!" neq "#" ( echo W goto end ) echo N :end ``` I just wanted to create a bot in batch... And will never do it again [Answer] # FluidBot ## Python 3 ### Takes path of least resistance and attempts to predict opponent ``` import sys, math def mvs(j,x,y,d,*args): score = sum([ ((j[y-1][x]=='.') * ((j[rgpos[1][1]+1][rgpos[1][0]]=='#')/3+1)) / ([j[y-1][x+1], j[y-1][x-1]].count('#')+1) * (d != 'S'), ((j[y+1][x]=='.')*((j[rgpos[1][1]-1][rgpos[1][0]]=='#')/3+1)) / ([j[y+1][x+1], j[y+1][x-1]].count('#')+1) *(d != 'N'), ((j[y][x-1]=='.')*((j[rgpos[1][1]][rgpos[1][0]+1]=='#')/3+1)) / ([j[y+1][x-1], j[y-1][x-1]].count('#')+1) *(d != 'W'), ((j[y][x+1]=='.')*((j[rgpos[1][1]][rgpos[1][0]-1]=='#')/3+1)) / ([j[y-1][x+1], j[y+1][x+1]].count('#')+1) *(d != 'E') ]) * (j[y][x]=='.') if len(args): if args[0] > 0: mvx = {'N': [x, y-1], 'S': [x, y+1], 'E': [x+1, y], 'W': [x-1, y]} nscr = score * (args[0] + mvs(j,mvx[d][0],mvx[d][1],d,args[0]-1)) return(nscr) else: return(score) else: return(score*mvs(j,x,y,d,[len(g),len(g[0])][d in ['E','W']]-1)) g = sys.argv[1].split(';')[:-1] fg = sys.argv[1].replace(';', '') pos = [fg.index('1'), fg.index('2')] pos = [ [pos[0]%len(g[0]), math.floor(pos[0]/len(g[0]))], [pos[1]%len(g[0]), math.floor(pos[1]/len(g[0]))] ] rg = ';'.join(g).replace('1', '#').replace('2', '#').split(';') mg = [c+c+g[i]+c+c for i,c in enumerate(rg)] rg = [i*5 for i in rg] rg = rg + rg + mg + rg + rg rgpos = [ [pos[0][0]+len(g[0]), pos[0][1]+len(g)], [pos[1][0]+len(g[0]), pos[1][1]+len(g)] ] relpos = [ rgpos[1][0]-rgpos[0][0], rgpos[1][1]-rgpos[0][1] ] moves = { 'N': ((relpos[1]>0)/3+1)*mvs(rg, rgpos[0][0], rgpos[0][1]-1, 'N'), 'S': ((relpos[1]<0)/3+1)*mvs(rg, rgpos[0][0], rgpos[0][1]+1, 'S'), 'E': ((relpos[0]<0)/3+1)*mvs(rg, rgpos[0][0]+1, rgpos[0][1], 'E'), 'W': ((relpos[0]>0)/3+1)*mvs(rg, rgpos[0][0]-1, rgpos[0][1], 'W') } sys.stdout.write(sorted(moves, key=lambda x:-moves[x])[0]) ``` Worked on this for about an hour. .\_. Tested against AwayBot: ``` Player 1: E Player 2: W #.....#####.......##..... #.....###1.........##...# ....................##### ......................... ......................... ......................... ......######............. ......#....####.......... ......#.......##......... ......#........###....... .....##..........#....... .....#...........#....... .....#...........#....... ....##......##...#....... ....###.....##...#....... ......#...#####..#....... ....###...#...#..#....... ....#..####...##.##...... ....#..#.......#..##..... ....##2#.......#...##.... .......#.......##...##... .......#........#....##.. .......#........#.....##. .......##.......##.....## ........###......##.....# Player 1 wins! ``` FillUpBot: ``` Player 1: W Player 2: E #......................#2 #......................## ......................##. ......................#.. .....................##.. ....................##... ....................#.... ...................##.... ..................##..... ..................#...... .......1###########...... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ......................... ######################### .......................## Player 1 wins! ``` **EDIT 5**: More future-conscious; tries to avoid closing off areas (unless, of course, the opponent is in it). **EDIT 4**: Cleaned up code. **EDIT 3**: Works better for rectangular playing areas. **EDIT 2**: Cleaner code, algorithm is more logical and predicts some moves into the future **EDIT**: More defensive algorithm, doesn't count ghost self as empty space. [Answer] # AwayBot **written in Ruby (1.9)** Aptly named, AwayBot tries to go away from any obstacles. It searches a 15x15 square around itself, weights the directions accordingly, and chooses the direction with the least amount of obstacles. (This also means that it avoids the edges, which is good so it doesn't get trapped in them.) It also considers walls closer by to be more of a danger. Walls right next to it are weighted much more than walls far away. For your sample input, it outputs `S`. The weights for each direction of the sample input are `[["N", 212], ["E", 140], ["S", 0], ["W", 84]]`. Interjection: I just noticed that the arena wraps. Well then, my edge-avoiding technique is somewhat pointless now, but meh. Maybe I'll fix it later. ``` arena = ARGF.argv[0] # we're considering the enemy a wall, for simplicity. # no need to weight him any more than the other walls because he will # always be surrounded by walls anyway. arena = arena.sub(?2, ?#).split(?;) # pad the arena with extra walls (edges of the arena) searchRadius = 7 arenaSize = arena.first.size verticalEdgeWalls = [?# * arenaSize] * searchRadius arena = verticalEdgeWalls + arena + verticalEdgeWalls horizontalEdgeWalls = ?# * searchRadius arena.map! {|row| (horizontalEdgeWalls + row + horizontalEdgeWalls).split('') } # now get the area around the bot botRow = arena.index{|row| row.index ?1 } botCol = arena[botRow].index ?1 searchZone = arena.slice(botRow-searchRadius..botRow+searchRadius) searchZone.map! {|row| row.slice(botCol-searchRadius..botCol+searchRadius) } # second to last step: assign values to each square depending on how far away they are # from the player (Manhattan distance) # this is so that the player avoids running directly into a wall; higher value means closer tile # 0123210 # 1234321 # 2345432 # 1234321 # 0123210 centerSquare = searchRadius searchZone = searchZone.each_with_index.map {|row, rowIndex| row.each_with_index.map{|tile, tileIndex| [tile, searchRadius*2 - ((rowIndex - centerSquare).abs + (tileIndex - centerSquare).abs)] } } puts searchZone.map{|x|x.map{|y|y[1].to_s.rjust(2, ?0)}.join ' '} * "\n" # finally, assign weights to each direction # first, create a map of directions. each direction has an array, the first element being # what rows to slice and the second being what column. sBeg = 0 sMdl = searchRadius sEnd = searchRadius*2 directions = { ?N => [sBeg..sMdl-1, sBeg..sEnd], ?E => [sBeg..sEnd, sMdl+1..sEnd], ?S => [sMdl+1..sEnd, sBeg..sEnd], ?W => [sBeg..sEnd, sBeg..sMdl-1] } # then, create another hash of weights weights = directions.map{|dir, arr| section = searchZone.slice(arr[0]).map{|x| x.slice(arr[1]) }.flatten(1) [dir, (section.select{|tile| tile[0] == ?# }.map{|tile| tile[1] }.reduce(:+) || 0)] # return the sum of the values of the walls in the area } # yay! we have our weights! now just find the smallest one... dirToGo = weights.min_by{|_, walls| walls } # and output! print dirToGo[0] ``` [Answer] # FillUpBot ### written in C++ Don't think I'm going to win, but here's my go at it anyway: ``` #include <iostream> #include <cassert> #include <cmath> #include <cstdlib> #define SIZE 25 using namespace std; class Board{ public: unsigned long long walls[SIZE]; //each int is a bitmap with the LSbit being the left side int p1x,p1y,p2x,p2y; void read(const char *arg){ int map,i,j; for(i=0;i<SIZE;i++){ for(map=1,j=0;j<SIZE;map<<=1,j++){ if(arg[(SIZE+1)*i+j]=='1'){ p1x=j; p1y=i; } else if(arg[(SIZE+1)*i+j]=='2'){ p2x=j; p2y=i; } walls[i]=(walls[i]&~map)|(map*(arg[(SIZE+1)*i+j]=='#')); } } } bool operator==(const Board &other){ int i; for(i=0;i<SIZE;i++)if(walls[i]!=other.walls[i])return false; if(p1x!=other.p1x||p1y!=other.p1y||p2x!=other.p2x||p2y!=other.p2y)return false; return true; } }; inline int mod(int a,int b){return (a+b)%b;} inline int min(int a,int b){return a<b?a:b;} int main(int argc,char **argv){ assert(argc==2); Board B; B.read(argv[1]); //cerr<<"KOTW: read"<<endl; if(hypot(B.p2x-B.p1x,B.p2y-B.p1y)<=3||hypot(mod(B.p2x+SIZE/2,SIZE)-mod(B.p1x+SIZE/2,SIZE),mod(B.p2y+SIZE/2,SIZE)-mod(B.p1y+SIZE/2,SIZE))<=3){ double maxdist=-1,d; int maxat=-1; //0=E, 1=N, 2=W, 3=S //cerr<<B.walls[B.p1y]<<endl; if(!(B.walls[B.p1y]&(1<<mod(B.p1x+1,SIZE)))){ d=min(hypot(mod(B.p2x-(B.p1x+1),SIZE),mod(B.p2y-B.p1y,SIZE)),hypot(mod(B.p1x+1-B.p2x,SIZE),mod(B.p1y-B.p2y,SIZE))); //cerr<<"E: "<<d<<endl; if(d>maxdist){ maxdist=d; maxat=0; //E } } //cerr<<B.walls[mod(B.p1y-1,SIZE)]<<endl; if(!(B.walls[mod(B.p1y-1,SIZE)]&(1<<B.p1x))){ d=min(hypot(mod(B.p2x-B.p1x,SIZE),mod(B.p2y-(B.p1y-1),SIZE)),hypot(mod(B.p1x-B.p2x,SIZE),mod(B.p1y-1-B.p2y,SIZE))); //cerr<<"N: "<<d<<endl; if(d>maxdist){ maxdist=d; maxat=1; //N } } //cerr<<B.walls[B.p1y]<<endl; if(!(B.walls[B.p1y]&(1<<mod(B.p1x-1,SIZE)))){ d=min(hypot(mod(B.p2x-(B.p1x-1),SIZE),mod(B.p2y-B.p1y,SIZE)),hypot(mod(B.p1x-1-B.p2x,SIZE),mod(B.p1y-B.p2y,SIZE))); //cerr<<"W: "<<d<<endl; if(d>maxdist){ maxdist=d; maxat=2; //W } } //cerr<<B.walls[mod(B.p1y+1,SIZE)]<<endl; if(!(B.walls[mod(B.p1y+1,SIZE)]&(1<<B.p1x))){ d=min(hypot(mod(B.p2x-B.p1x,SIZE),mod(B.p2y-(B.p1y+1),SIZE)),hypot(mod(B.p1x-B.p2x,SIZE),mod(B.p1y+1-B.p2y,SIZE))); //cerr<<"S: "<<d<<endl; if(d>maxdist){ maxdist=d; maxat=3; //S } } if(maxat==-1){ //help we're stuck! cout<<"ENWS"[(int)((double)rand()/RAND_MAX*4)]<<endl; return 0; } cout<<"ENWS"[maxat]<<endl; return 0; } //cerr<<"KOTW: <=3 checked"<<endl; //cerr<<B.p1x<<","<<B.p1y<<endl; if(!(B.walls[B.p1y]&(1<<mod(B.p1x+1,SIZE))))cout<<'E'<<endl; else if(!(B.walls[mod(B.p1y+1,SIZE)]&(1<<B.p1x)))cout<<'S'<<endl; else if(!(B.walls[mod(B.p1y-1,SIZE)]&(1<<B.p1x)))cout<<'N'<<endl; else if(!(B.walls[B.p1y]&(1<<mod(B.p1x-1,SIZE))))cout<<'W'<<endl; else cout<<"ENWS"[(int)((double)rand()/RAND_MAX*4)]<<endl; //help we're stuck! //cerr<<"KOTW: done"<<endl; return 0; } ``` Your standard C++ compiler should be able to handle this. [Answer] # Arcbot ## Python 3 ### Plays with aggression-based algorithm as enemy and bruteforces answer with influence This algorithm is kind of 'emotion-based', I guess. In developing this, I realized that FluidBot beat it nearly every time. Arcbot isn't the fastest algorithm nor the best, but it has it's strengths. It *does* crash into walls. No idea why. **FLUIDBOT IS BETTER** ``` # Arcbot # # This is a more dynamic bot than the earlier Fluidbot. # I'm also commenting on the code to make my algorithm # more clear. #** Some intial definitions **# import math, sys # math for the 'arc' part class edgeWrapList: # yay, such efficient def __init__(self, l): self.l = list(l) def __getitem__(self, i): it = i%len(self.l) if it == i: # no wrapping, include players return(self.l[i]) else: # wrapping, replace players with walls if not isinstance(self.l[it], str): return(self.l[it]) else: return(self.l[it].replace('1', '#').replace('2', '#')) def __len__(self): return(len(self.l)) def __str__(self): return(''.join(str(i) for i in self.l)) def __setitem__(self, i, v): self.l[i%len(self.l)] = v grid = edgeWrapList([edgeWrapList([j for j in i]) for i in sys.argv[1].split(';')[:-1]]) # a 2D edgeWrapList. Access via grid[y][x] attackStr = 1 # distance to attack from attackEnd = 12 # distance to avoid again predictTurns = 6 # how many turns to play as the opponent as well. Keep low for performance. #** Arcbot's main class **# class arcbot: def __init__(self, g, astr, aend): self.g = g # g is a 2D edgeWrapList self.p1p = str(g).index('1') self.p1p = [self.p1p%len(g[0]), math.floor(self.p1p/len(g[0]))] # x, y of player 1 self.p2p = str(g).index('2') self.p2p = [self.p2p%len(g[0]), math.floor(self.p2p/len(g[0]))] # x, y of player 2 self.astr = astr self.aend = aend def getAggr(self, d): if self.astr < d < self.aend: return(0) else: return(math.cos((d-self.astr)*(math.pi*2/self.aend))) # sort-of bell curve between -1 and 1 def getMove(self, p): # p is either 1 or 2 scrg = edgeWrapList(self.scoreGridGen(p)) # get dem position scores pos = self.p1p if p==1 else self.p2p dir = { 'N': scrg[pos[1]-1][pos[0]], 'S': scrg[pos[1]+1][pos[0]], 'E': scrg[pos[1]][pos[0]+1], 'W': scrg[pos[1]][pos[0]-1] } o = sorted(dir, key=lambda x:-dir[x])[0] return([o, dir[o]]) # return direction with highest scoring position and it's score def getScore(self, x, y, p, d='*'): epos = self.p2p if p == 1 else self.p1p dist = math.sqrt((y - epos[1])**2 + (x - epos[0])**2) return((sum([ (self.g[y][x-1] == '.') * (((self.g[y][x+1] == '.')+1) * ((self.g[y][x-2] == '.')*4+1)), (self.g[y][x+1] == '.') * (((self.g[y][x-1] == '.')+1) * ((self.g[y][x+2] == '.')*4+1)), (self.g[y-1][x] == '.') * (((self.g[y+1][x] == '.')+1) * ((self.g[y-2][x] == '.')*4+1)), (self.g[y+1][x] == '.') * (((self.g[y-1][x] == '.')+1) * ((self.g[y+2][x] == '.')*4+1)) ]) * 2 + 1) * (self.getAggr(dist) / 10 + 1) * (self.g[y][x] == '.')) def scoreGridGen(self, p): # turn .s into numbers, higher numbers are better to move to o = [] for y,r in enumerate(self.g.l): # y, row o.append(edgeWrapList( self.getScore(x, y, p) for x,v in enumerate(r.l) # x, value ) ) return(o) def play(self, turns, movestr): # movestr is [p1moves, p2moves] p2move = self.getMove(2) movestr[1] += [p2move[0]] p1move = self.getMove(1) if len(movestr[0]) == turns: return([p1move[1], p1move[0]]) # Score for final block scores = {} for i in 'N S E W'.split(): movestr[0] += [i] og = self.simMoves(movestr) if og == 'LOSE:2': scores[i] = 1000000 # we win! elif og == 'LOSE:1': scores[i] = -1000000 # we lose! else: scores[i] = og[1] * ((i == p1move[0]) / 1.2 + 1) * (turns-len(movestr[0])) * (self.play(turns, movestr)[0]+1) movestr[0] = movestr[0][:-1] hst = sorted(scores, key=lambda x:-scores[x])[0] return([scores[hst], hst]) # highest scoring turn in total and it's score def simMove(self, p, d): # move player p in direction d pos = self.p1p if p == 1 else self.p2p target = { 'N': [pos[0], pos[1]-1], 'S': [pos[0], pos[1]+1], 'E': [pos[0]+1, pos[1]], 'W': [pos[0]-1, pos[1]] }[d] v = self.g[target[1]][target[0]] # contents of target block if v == '.': # yay let's move here self.g[target[1]][target[0]] = str(p) self.g[pos[1]][pos[0]] = '#' if p == 1: self.p1p = [target[0], target[1]] else: self.p2p = [target[0], target[1]] else: # nuu crash raise(ValueError) # doesn't matter, caught later def simMoves(self, mvl): # return simmed copy op = [self.p1p, self.p2p] og = self.g finalScore = 0 for i in range(len(mvl[0])): try: if i == len(mvl[0])-2: finalScore = { 'N': self.getScore(self.p1p[0], self.p1p[1]-1, 'N'), 'S': self.getScore(self.p1p[0], self.p1p[1]+1, 'S'), 'E': self.getScore(self.p1p[0]+1, self.p1p[1], 'E'), 'W': self.getScore(self.p1p[0]-1, self.p1p[1], 'W') }[mvl[0][i]] self.simMove(1, mvl[0][i]) except: return('LOSE:1') try: self.simMove(2, mvl[1][i]) except: return('LOSE:2') o = self.g self.g = og self.p1p, self.p2p = op return([o, finalScore]) arcbotMove = arcbot(grid, attackStr, attackEnd) sys.stdout.write(arcbotMove.play(predictTurns, [[], []])[1]) ``` **EDIT**: Adjusted the numbers and the formula, it plays better now but still loses to Fluidbot. **EDIT 2**: Whoops, forgot to change some code. [Answer] # RandomBot ### C# RandomBot randomly selects a direction until it's route is free. If there is no safe direction it simply types `*` and loses. ``` using System; class AI { static void Main(string[] args) { char[,] grid = new char[25, 25]; char[] directions = { 'N', 'E', 'S', 'W' }; string map = args[0]; Random rand = new Random(); int[] pos = new int[2]; for (var x = 0; x < 25; x++) { for (var y = 0; y < 25; y++) { grid[x, y] = map.Split(';')[y][x]; if (grid[x,y] == '1') { pos[0] = x; pos[1] = y; } } } if (grid[(pos[0] + 1) % 25, pos[1]] != '.' && grid[pos[0], (pos[1] + 1) % 25] != '.' && grid[(pos[0] + 24) % 25, pos[1]] != '.' && grid[pos[0], (pos[1] + 24) % 25] != '.') { if (grid[pos[0], (pos[1] + 24) % 25] == '2') { Console.Write("N"); } else if (grid[(pos[0] + 1) % 25, pos[1]] == '2') { Console.Write("E"); } else if (grid[pos[0], (pos[1] + 1) % 25] == '2') { Console.Write("S"); } else if (grid[(pos[0] + 24) % 25, pos[1]] == '2') { Console.Write("W"); } else { Console.Write("*"); } } else { while (true) { char direction = directions[Convert.ToInt32(rand.Next(4))]; if (direction == 'N' && grid[pos[0], (pos[1] + 24) % 25] == '.') { Console.Write("N"); break; } else if (direction == 'E' && grid[(pos[0] + 1) % 25, pos[1]] == '.') { Console.Write("E"); break; } else if (direction == 'S' && grid[pos[0], (pos[1] + 1) % 25] == '.') { Console.Write("S"); break; } else if (direction == 'W' && grid[(pos[0] + 24) % 25, pos[1]] == '.') { Console.Write("W"); break; } } } } } ``` > > This is only an example AI - it is not designed to win! > > > [Answer] # Fill Up Bot (turns 90 degrees anticlockwise, when faces an obstacle # C++ In my code, the two players (1 and 2) try to flood. Meaning whenever they face an obstacle, they turn anti-clockwise. **Remember, The lines in input are separated by a `space` or `newline` and not by `;`** ``` #include<iostream> #include<conio.h> #include<windows.h> char draw(char plot[][25],char dir,char num) { int a=1,i,j; for(i=0;i<25;i++) { for(j=0;j<25;j++) { if(plot[i][j]==num&&a) { a--; switch(dir) { case 'S':{ if(i==24||plot[i+1][j]=='#') { dir='E'; plot[i][j]='#'; plot[i][j+1]=num; } else if(i<24||plot[i+1][j]=='.') { plot[i][j]='#'; plot[i+1][j]=num; } break; } case 'E':{ if(j==24||plot[i][j+1]=='#') { dir='N'; plot[i][j]='#'; plot[i-1][j]=num; } else if(j<24||plot[i][j+1]=='.') { plot[i][j]='#'; plot[i][j+1]=num; } break; } case 'N':{ if(i==0||plot[i-1][j]=='#') { dir='W'; plot[i][j]='#'; plot[i][j-1]=num; } else if(i>0||plot[i-1][j]=='.') { plot[i][j]='#'; plot[i-1][j]=num; } break; } case 'W':{ if(j==0||plot[i][j-1]=='#') { dir='S'; plot[i][j]='#'; plot[i+1][j]=num; } else if(j>0||plot[i][j-1]=='.') { plot[i][j]='#'; plot[i][j-1]=num; } break; } } } } } return dir; } void run() { int i,j,crash=1,count,k,a; char plot[25][25],dir1='S',dir2='N'; for(i=0;i<25;i++) std::cin>>plot[i]; plot[0][0]='1'; plot[24][24]='2'; while(crash) { system("cls"); dir1=draw(plot,dir1,'1'); dir2=draw(plot,dir2,'2'); count=0; for(i=0;i<25;i++) for(j=0;j<25;j++) if(plot[i][j]=='.')count++; if(count==1) { crash--; plot[12][12]='*'; plot[11][12]='#'; plot[13][12]='#'; } for(i=0;i<25;i++) { for(j=0;j<25;j++) std::cout<<plot[i][j]; std::cout<<'\n'; } Sleep(25); } } int main() { run(); getch(); return 0; } ``` ]
[Question] [ Write an interactive program or function which allows the user to play The Coinflip Game! The object of the game is to repeatedly flip a coin until you get the same result \$n\$ times in a row. Specific behavior of the program/function is as follows: * At the start of the game, the user inputs a positive integer \$n>1\$ * The program should then "flip a coin" (i.e. choose between two values randomly), and show the result to the user. Possible outcomes can be any two distinct outputs (e.g. 1 or 0) and must be chosen non deterministically such that each result always has a nonzero chance of appearing. * Next, the following loop occurs 1. Prompt the user to input whether they wish to continue trying or quit. This prompt must include the two input options the player has, one corresponding to continuing, and one corresponding to quitting, clearly delimited. If they choose to quit, take no further input and exit the program. 2. If they choose to continue, perform another "coinflip", and show the user the outcome (same rules as before). 3. If the "coinflip" has had the same outcome \$n\$ times in a row (meaning this outcome and the previous \$n-1\$ outcomes are all equal), print a congratulatory message (any message that is not one of the coinflip values or continue/quit prompts) and exit, taking no more input. 4. If the "coinflip" has not had the same outcome \$n\$ times in a row yet, return to step 1 of the loop. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest implementation in bytes wins. ## More rule clarifications: * Steps must occur in the order shown, so you can't prompt the user to continue before showing them their first coinflip result for example. * All six values listed below must be distinct from one another: + Coinflip outcome 1 + Coinflip outcome 2 + Continue/Quit prompt + Continue playing input + Quit game input + Congratulatory message * The coinflip only needs to be nondeterministic; You don't need the randomness to be uniform per flip. * There can only be two possible outcomes for each coinflip. A random float between 0 and 1 is not a coinflip. * Player input can be taken in any reasonable fashion. * You can assume the player will never give invalid input. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 101 bytes ``` from random import* p=m=n=int(input()) while'0'<input((m:=[n,m,print(r:=random()>.5)][r==p]-1)/m):p=r ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P60oP1ehKDEvBUhl5hbkF5VocRXY5trm2WbmlWhk5hWUlmhoanKVZ2TmpKobqNtARDRyrWyj83RydQqKQMqKrGwhRmho2umZasZGF9naFsTqGmrq52paFdgCrTHmMkSDBgA "Python 3.8 (pre-release) – Try It Online") * Coin flip outcome 1: `True` * Coin flip outcome 2: `False` * Continue/Quit prompt: `1.0` * Continue playing input: `1` * Quit game input: `0` * Congratulatory message: `ZeroDivisionError: division by zero` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 31 bytes ``` KUJ"C/Q"We,aK O2t{>QKJIqweJB.?N ``` [Try it online!](https://tio.run/##K6gsyfj/3zvUS8lZP1ApPFUn0ZvL36ik2i7Q28uzsDzVy0nP3u//f2MuZzgMBAA "Pyth – Try It Online") Coinflip outcomes are "0" or "1" Continue/Quit prompt is "C/Q" Continue playing input is "C" Quit playing input is "Q" If you win, you receive a congratulatory " [Answer] # [Bash](https://www.gnu.org/software/bash/), 82 75 bytes ``` read n while read;do echo $[x=RANDOM%2,t*=x==l,l=x] let n==++t&&exit 2 done ``` [Try it online!](https://tio.run/##S0oszvj/vyg1MUUhj6s8IzMnVQHEsU7J50pNzshXUImusA1y9HPx91U10inRsq2wtc3RybGtiOXKSS1RyLO11dYuUVNLrcgsUTDiSsnPS/3/HwA "Bash – Try It Online") * prompts for `n` * prompts to continue or quit: "enter" continues and "ctrl-D" quits with exit code 1 * prints 0 or 1 randomly if you continued * quits with exit code 2 if you won. continues loop otherwise. + Works by resetting the total count `t` every time there is a switch in direction. [Answer] # [Python](https://www.python.org), ~~129~~ ~~131~~ ~~127~~ 106 bytes ``` i,p,a=input,print,1 p(v:=id(n:=int(i()))%3%2) while"3">i(2.3):p(c:=id(dict())%3%2);a,v=c^v or-~a,c;1/(n>a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3szJ1CnQSbTPzCkpLdAqKMvNKdAy5CjTKrGwzUzTygGReiUamhqampqqxqpEmV3lGZk6qkrGSXaaGkZ6xplWBRjJYZUpmcokGVJF1ok6ZbXJcmUJ-kW5dok6ytaG-Rp5doibERqjFC3YaczljhYEQBQA) The coin flips are `0` and `1`, continue with `2` and quit with `3`, and the success message is an error message. --- +2 bytes from @Steffan -11 bytes from @Jonathan Allan\* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ ~~22~~ ~~19~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [₂Ω=ˆ1z¯γθg¹Q+=Ê# ``` -4 bytes thanks to *@CommandMaster*. * Coin flip outcomes: `2` and `6` * Continue/Quit prompt: `1.0` * Continue playing input: `1` * Quit game input: `0` * Congratulations message: `2.0` [Try it online.](https://tio.run/##yy9OTMpM/f8/@lFT07mVtqfbDKsOrT@3@dyO9EM7A7VtD3cp//9vwmVIMjQAAA) **Explanation:** ``` [ # Start an infinite loop: ₂ # Push 26 Ω # Pop and push a random digit from it = # Output it with trailing newline (without popping) ˆ # Pop and add it to the global_array 1z # Push 1.0 (push 1; calculate 1/value) ¯ # Push the global_array γ # Group it to equal adjacent values θ # Pop and leave just the last group g # Pop and get the length of this last group ¹Q # Check if it's equal to the first input `n` (1 if truthy; 0 if falsey) + # Add that to the 1.0 = # Output it with trailing newline (without popping) Ê # If it's NOT equal to the next (implicit) input-integer: # # Stop the infinite loop ``` Regarding the `Ê#`: * If we haven't got \$n\$ the same values in a row yet, the value we output is still `1.0`. The `Ê` will be falsey if the prompt input is to continue (`1`), and will be truthy if the prompt input is to quit (`0`). * If we have reached \$n\$ the same values in a row, the value we output is the congratulations message `2.0`. The `Ê` will now be truthy, regardless of whether the prompt input is to continue (`1`) or quit (`0`). [Answer] ## (Browser) JavaScript, 122 bytes ``` a=prompt,k=0,s=0;for(g=+a();;k++){c=!Math.random();a(c);if(c!=s){s^=1;k=0}else if(g-1==k){a`!`;break}if(a`q|g`=="q")break} ``` If you're wondering why `if(Math.random())` works, yes: [it can return 0](https://stackoverflow.com/questions/11730263/will-javascript-random-function-ever-return-a-0-or-1) (but *not often*). Hey, there *is* a nonzero chance of 0 popping up... [Answer] # [Python](https://www.python.org), 141 bytes ``` from random import* n=int(input());a=[.5] while 1: print(f:=random()>.5);a+=f, if 0==sum(a[-n:])%n:print(2);break if'C'<input('C/Q'):break ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3e9OK8nMVihLzUoBUZm5BflGJFleebWZeiUZmXkFpiYampnWibbSeaSxXeUZmTqqCoRWXQkERSD7NyhaiT0PTTs8UqEzbNk2HSyEzTcHA1ra4NFcjMVo3zypWUzXPCqLBSNM6qSg1MRukRt1Z3QZigbqzfqC6phVYBuIoqNsW7DTicsYKAyEKAA) Coinflip outcomes are `False` and `True`, prompt is `C/Q`, where `C` = continue and `Q` = quit. -14 bytes thanks to CursorCoercer [Answer] ## Batch, 107 bytes ``` @set/al=c=0 :c @set/af=%random%%%2,c=1+c*!(l-f),l=f @echo %f% @if %c%==%1 goto w @set/pi=cq @goto %i% ``` Takes `n` as a command-line parameter. Outputs `0` or `1` for the coin. Prompt is `cq`, input is `c` to continue, `q` to quit. Stops with the message `The system cannot find the batch label specified - w` if you win. Explanation: `c` is the count of consecutive equal flips, `l` is the last flip, `f` is the current flip, `i` is the user input (note that outside `set/a` variables have to be enclosed in `%`s and even inside `set/a` in the case of `%random%`). [Answer] # [simply](https://github.com/ismael-miguel/simply), ~~260~~ ~~254~~ 244 bytes Yeah, the code is a big fat boy. It is also *far* from the intended way to use the language. --- ## Values The program has the following values: * Coinflip outcome 1: `0` * Coinflip outcome 2: `1` * Continue/Quit prompt: `window.confirm` * Continue playing input: `true` * Quit game input: `false` * Congratulatory message: `'W'` --- ## The code Thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan) for saving 3 bytes. ``` $F=run$argv->map->constructor("return self")$W=run$F()$T=&int(run$W->prompt)$L=&rand(0,1)$C=1for$i in0..9999{$R=run$W->confirm($L)unless$R;break$F=&rand(0,1)if run&compare($L$F){$L=$F$C=1}else{$C=&add(1$C)unless run&compare($C$T){out'W'break}}} ``` Unfortunately, my language doesn't have infinite loops, yet... However, this loops 10000 times, which should be enough to get the user to stop or give you a win. It is possible to emulate this with `setTimeout`, but the program flow will be extremely weird, and cost a ton of bytes. Additionally, the result of the last coin flip is shown in the message requesting to continue or stop, to save bytes. ### Ungolfed and readable ``` $func = call $argv["map"]["constructor"]("return self"); %window = call $func(); %times = &int(call %window->prompt("How many equals")); %last_flip = &rand(0, 1); %count = 1; for $i in 0..9999 { $result = call %window->confirm(&str_concat("Rolled ", %last_flip, ' ', %count, " time(s). Continue?")); unless $result { break; } $flip = &rand(0, 1); if call &compare(%last_flip, $flip) { %last_flip = $flip; %count = 1; } else { %count = &add(1, %count); unless call &compare(%count, %times) { echo "You're Winner!"; break; } } } ``` ### Ungolfed to Plain English ``` Set $func to the result of calling $argv["map"]["constructor"]("return self"). Set %window to the result of calling $func(). Set %times to the result of calling &int( Call the function %window->prompt("How many equals") ). Set %last_flip to the result of calling &rand(0, 1). Set %count to 1. Loop from 0 to 9999 as $i Begin Set $result to the result of calling %window->confirm( Call the function &str_concat("Rolled ", %last_flip, ' ', %count, " time(s). Continue?") ). Unless $result then Break. Set $flip to the result of calling &rand(0, 1). If Call &compare(%last_flip, $flip) Begin Set %last_flip to $flip. Set %count to 1. End Else Begin Set %count to the result of calling &add(1, %count); Unless Call &compare(%count, %times) Begin Show the value "You're Winner!". Break. End End End ``` All versions work exactly the same, but the output is kinda different, just to be more user friendly. ## Explanation The variable `$argv` is an array with arguments passed to the `.execute()` method of the compiler. This can be used to run `[]["filter"]["constructor"]("return this")()`, which returns the `window` object (Source in <http://www.jsfuck.com/>). But since the compiler changes the `this` value, I had to use `self`, which is the same as `window.self` which is just the window object. Since `[]["filter"]...` is invalid syntax, I get around it by using `$argv->filer ...` (`$argv["filter"]...` is valid as well). The keyword `run` (or `call`) is required to say "I am absolutely sure this variable is a function, now run it". Due to bugs, the `if` and `unless` requires that the functions are executed with `run`, otherwise it assumes it is checking if the function exist. The syntax `$T=&int(run$W->prompt)` is valid, because you don't need to have parenthesis when there's no arguments. You will find a few cases where the syntax makes no sense, like `$C=1for$i in0..9999` or `$C=&add(1$C)unless`. As long as the tokens are distinguishable from each other, there's no problem. `$C=1for$i in0..9999` will be parsed as the following tokens: `$c`, `=`, `1`, `for`, `$i`, `in`, `0`, `..`, `9999`. Since, currently, there's no boolean operators, I use the `unless` block. It is basically an `if(!(condition))`. Since I need to check if values are false-y, for example: `unless$R;break`, I use this block. The function `&compare` checks if the first argument is lower, higher or equal to the second argument. If it is lower, returns -1. If it is higher, returns 1. Otherwise, returns 0 (a false-y value). `$W->prompt` (`window.prompt`) shows a message requesting a value. `$W->confirm` (`window.confirm`) shows a message and requests the user to click "OK" or "Cancel". ``` console.log(window.prompt("Write any value", "any value")); console.log(window.confirm("Want to show 'true'?")); ``` [Answer] # JavaScript (browser), 105 bytes ``` p=prompt,r=()=>Math.random()<.5,t=p();c=b=1;for(u=r();b;b=c==t?p(3):+p`1.0`){n=r();p(n);n==u?c++:c=1,u=n} ``` * Coin flip outcome 1: `true` * Coin flip outcome 2: `false` * Continue/Quit prompt: `1.0` * Continue playing input: `1` * Quit game input: `0` * Congratulatory message: `3` ]
[Question] [ We have already defined a folding number [here](https://codegolf.stackexchange.com/questions/95458/folding-numbers). But now we are going to define a Super Folding Number. A Super Folding number is a number that if folded enough times it will eventually reach one less than a power of two. The method of folding is slightly different than in the folding number question. The folding algorithm goes as follows: * Take the binary representation e.g. 5882 ``` 1011011111010 ``` * Spilt it into three partitions. First half, last half and middle digit (iff it has a odd number of digits) ``` 101101 1 111010 ``` * If the middle digit is zero this number cannot be folded * Reverse the second half and superimposed on the first half ``` 010111 101101 ``` * Add the digits in place ``` 111212 ``` * Iff there are any 2s in the result the number cannot be folded otherwise the new number is the result of the folding algorithm. A number is a Super Folding number if it can be folded to a continuous string of ones. (All Folding numbers are also Super Folding Numbers) Your task is to write code that takes in a number and outputs a truthy value if the number is a Super Folding number and falsy otherwise. You will be scored on the size of your program. ## Examples ### 5200 Convert to binary: ``` 1010001010000 ``` Split in half: ``` 101000 1 010000 ``` The middle is one so we continue Superimpose the halves: ``` 000010 101000 ``` Added them: ``` 101010 ``` No twos so we continue Split in half: ``` 101 010 ``` Fold: ``` 010 101 111 ``` The result is `111` (7 in decimal) so this is a Super Folding Number. ## Test Cases The first 100 Super Folding Numbers are: ``` [1, 2, 3, 6, 7, 8, 10, 12, 15, 20, 22, 28, 31, 34, 38, 42, 48, 52, 56, 63, 74, 78, 90, 104, 108, 120, 127, 128, 130, 132, 142, 150, 160, 170, 178, 192, 204, 212, 232, 240, 255, 272, 274, 276, 286, 310, 336, 346, 370, 400, 412, 436, 472, 496, 511, 516, 518, 524, 542, 558, 580, 598, 614, 640, 642, 648, 666, 682, 704, 722, 738, 772, 796, 812, 852, 868, 896, 920, 936, 976, 992, 1023, 1060, 1062, 1068, 1086, 1134, 1188, 1206, 1254, 1312, 1314, 1320, 1338, 1386, 1440, 1458, 1506, 1572, 1596] ``` [Answer] Here's my first ever shot at code golf: # Python 3, 167 bytes 167 bytes if tabs or single spaces are used for indentation ``` def f(n): B=bin(n)[2:];L=len(B);M=L//2 if'1'*L==B:return 1 S=str(int(B[:M])+int(B[:-M-1:-1])) return 0if(~L%2==0and'0'==B[M])or'2'in S else{S}=={'1'}or f(int(S,2)) ``` Edit: Thanks to everyone's help below, the code above has been reduced from an original size of 232 bytes! [Answer] ## Java 7, 202 bytes ``` boolean g(Integer a){byte[]b=a.toString(a,2).getBytes();int i=0,l=b.length,o=0,c,z=(a+1&a)==0?-1:1;for(;i<l/2&z>0;o+=o+c*2,z*=c>1|(l%2>0&b[l/2]<49)?0:1)c=b[i]+b[l-++i]-96;return z<0?1>0:z<1?0>1:g(o/2);} ``` It took a bit of effort to make the old folding function recursable, but here it is. It's ugly as sin, to be honest. I'll have to take a look in the morning to see if I can golf it further, since I can barely stand to look at it right now. With line breaks: ``` boolean g(Integer a){ byte[]b=a.toString(a,2).getBytes(); int i=0,l=b.length,o=0,c,z=(a+1&a)==0?-1:1; for(;i<l/2&z>0;o+=o+c*2,z*=c>1|(l%2>0&b[l/2]<49)?0:1) c=b[i]+b[l-++i]-96; return z<0?1>0:z<1?0>1:g(o/2); } ``` [Answer] # [CJam](http://sourceforge.net/projects/cjam/), ~~47~~ 44 bytes ``` ri2b{_W%.+__0e=)\_,1>\0-X+:*3<*&}{_,2/<}w2-! ``` [Try it online!](http://cjam.tryitonline.net/#code=cmkyYntfVyUuK19fMGU9KVxfLDE-XDAtWCs6KjM8KiZ9e18sMi88fXcyLSE&input=MTU5Ng) or [generate a list](http://cjam.tryitonline.net/#code=J1tyaSl7SSAKMmJ7X1clLitfXzBlPSlcXywxPlwwLVgrOiozPComfXtfLDIvPH13Mi0hCntJJyxTfSYKfWZJOzsnXQ&input=MTU5Ng) of super folding numbers up to a given number. Golfing attempts can be seen [here](http://cjam.tryitonline.net/#code=ZSNyaTJie19XJS4rX3syPX0lXywsX1clLj0uXjp8MSQsMT18IX17XywyLzx9dzItIQplI3JpMmJ7X1clLitfezI9fSVfLDpBLF9XJS49Ll5BMT0rOnwhfXtBMi88fXcyLSEKZSNyaTJie19XJS4rX3syPX0lXywsX1clLj0uXl8sMT0rOnwhfXtfLDIvPH13Mi0hCmUjcmkyYntfVyUuK19fMGU9MiVcXywxPVwwLVgrOioyPnx8IX17XywyLzx9dzItIQogIHJpMmJ7X1clLitfXzBlPSlcXywxPlwwLVgrOiozPComfXtfLDIvPH13Mi0h&input=MTU5Ng). --- The code breaks down to the following phases: ``` ri2b e# get input in binary { e# While fold is legal _W%.+_ e# "fold" the whole number onto itself _0e=)\ e# count zeros and add 1 (I) _,1>\ e# size check, leave 0 if singleton (II)* 0-X+:*3< e# product of 2s, leave 0 if too many (III) *& e# (II AND III) AND parity of I }{ e# Do _,2/< e# slice opposite to the actual fold** }w e# End while 2-! e# return 1 if "fold" ended in all 2s ``` **EDIT:** This version more or less takes a [De Morgan's Law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws#Formal_notation) approach to the previous version. *\*The problem with running on singletons is that we get stuck with an empty string after the slice.* *\*\* If a binary number is super folding, its mirror image (with leading 0s if needed) is. This saves a byte over taking the right half.* [Answer] # JavaScript, 149 bytes ``` f=(i,n=i.toString(2),l=n.length,m=l/2|0)=>/^1*$/.test(n)?1:/[^01]/.test(n)|!+n[m]&l?0:f(0,+n.slice(0,m)+ +n.slice(m+l%2).split``.reverse().join``+"") ``` Defines a recursive function. ## Explanation: ``` f=(i //Defines the function: i is input ,n=i.toString(2) //n is the current number ,l=n.length //l is the length of the number, ,m=l/2|0)=> //m is the index of the center character /^1*$/.test(n)?1: //returns 1 if the number is all ones /[^01]/.test(n) //returns 0 if the number has any chars other than 0 or 1 |!+n[m]&l?0: //or if the middle char is 0 f(0,+n.slice(0,m)+ +n.slice(m+l%2).split``.reverse().join``+"") //otherwise recurses using the first half of the number plus the second half ``` [Answer] ## JavaScript (ES6), ~~113~~ ~~109~~ 108 bytes ``` f=(n,[h,...r]=n.toString(2),b='')=>++n&-n-n?h?f(2,r,r[0]?b+(h- -r.pop()):+h?b:2):!isNaN(n=+('0b'+b))&&f(n):1 ``` ### Formatted and commented ``` f = ( // given: n, // - n = integer to process [h, ...r] = n.toString(2), // - h = highest bit, r = remaining low bits b = '' // - b = folded binary string ) => // ++n & -n - n ? // if n is not of the form 2^N - 1: h ? // if there's still at least one bit to process: f( // do a recursive call with: 2, // - n = 2 to make the 2^N - 1 test fail r, // - r = remaining bits r[0] ? // - if there's at least one remaining low bit: b + (h - -r.pop()) // append sum of highest bit + lowest bit to b : +h ? b : 2 // else, h is the middle bit: let b unchanged ) // if it is set or force error if it's not : !isNaN(n = +('0b' + b)) && // else, if b is a valid binary string: f(n) // relaunch the entire process on it : 1 // else: n is a super folding number -> success ``` ### Demo ``` f=(n,[h,...r]=n.toString(2),b='')=>++n&-n-n?h?f(2,r,r[0]?b+(h- -r.pop()):+h?b:2):!isNaN(n=+('0b'+b))&&f(n):1 // testing integers in [1 .. 99] for(var i = 1; i < 100; i++) { f(i) && console.log(i); } // testing integers in [1500 .. 1599] for(var i = 1500; i < 1600; i++) { f(i) && console.log(i); } ``` [Answer] # Perl, ~~71~~ 70 bytes Includes +1 for `-p` Give number on STDIN `superfolding.pl`: ``` #!/usr/bin/perl -p $_=sprintf"%b",$_;s%.%/\G0$/?2:/.\B/g&&$&+chop%eg while/0/>/2/;$_=!$& ``` [Answer] # Python 2, 151 bytes ``` f=lambda n,r=0:f(bin(n)[2:],'')if r<''else(r==''and{'1'}==set(n)or(n in'1'and f(r,'')+2)or n!='0'and'11'!=n[0]+n[-1]and f(n[1:-1],r+max(n[0],n[-1])))%2 ``` **[ideone](http://ideone.com/QvjtZn)** A doubly-recursive function which takes an integer, `n`, and returns `0` or `1`. A variable `r` is maintained to allow both the result of folding and to know if we currently: have an integer (first only); have a new binary string to try to fold (outer); or are folding (inner). On the first pass `n` is and integer, which is `<''` in Python 2 so the recursion starts by casting to a binary string. The next execution has `r=''` and so the test `{'1'}==set(n)` is executed to check for a continuous string of `1`s (the RHS cannot be `{n}` as we may need to pass this point later with `r=''` and an empty `n` when that would be a dictionary which wont equal `{'1'}`, a set). If this is not satisfied the inner tail criteria is tested for (even if unnecessary): if `n in'1'` will evaluate to True when `n` is an empty string or a single `1`, whereupon a new outer recursion is begun by placing `r`, by the then folded, binary string into `n` and `''` into `r`. The literal `2` is added to the result of this function call to allow no fall through to the next part (to the right of a logical `or`) that is corrected later. If that is not a truthy value (all non-zero integers are truthy in Python) the outer tail recursion criteria is tested for: `n!=0` excludes the case with a middle `0` and the outer two characters are tested they do not sum to `2` by the string concatenation `'11'!=n[0]+n[-1]`; if these both hold true the outer bits are discarded from `n` with `n[1:-1]`, and then a `1` is appended to `r` if there is one on the outside otherwise a `0` is, using the fact that `'1'>'0'` in Python with `max(n[0],n[-1])`. Finally the addition of `2` at each inner recursion is corrected with `%2`. [Answer] # PHP, 113 bytes ``` for($n=$argv[1];$n!=$c;$n=($a=$n>>.5+$e)|($b=$n&$c=(1<<$e/=2)-1))if($a&$b||($e=1+log($n,2))&!(1&$n>>$e/2))die(1); ``` exits with error (code `1`) if argument is not super-folding, code `0` else. Run with `-r`. Input `0` will return true (code `0`). **breakdown** ``` for($n=$argv[1]; $n!=$c; // loop while $n is != mask // (first iteration: $c is null) $n= // add left half and right half to new number ($a=$n>>.5+$e) // 7. $a=left half | ($b=$n& // 6. $b=right half $c=(1<<$e/=2)-1 // 5. $c=mask for right half ) ) if($a&$b // 1. if any bit is set in both halves // (first iteration: $a and $b are null -> no bits set) || // or ($e=1+log($n,2)) // 2. get length of number & !(1&$n>>$e/2) // 3. if the middle bit is not set -> 1 // 4. tests bit 0 in length --> and if length is odd ) die(1); // -- exit with error ``` [Answer] # PHP, 197 Bytes ``` function f($b){if(!$b)return;if(!strpos($b,"0"))return 1;for($n="",$i=0;$i<($l=strlen($b))>>1;)$n.=$b[$i]+$b[$l-++$i];if($l%2&&!$b[$i]||strstr($n,"2"))return;return f($n);}echo f(decbin($argv[1])); ``` Expanded ``` function f($b){ if(!$b)return; # remove 0 if(!strpos($b,"0"))return 1; # say okay alternative preg_match("#^1+$#",$b) for($n="",$i=0;$i<($l=strlen($b))>>1;)$n.=$b[$i]+$b[$l-++$i]; #add first half and second reverse if($l%2&&!$b[$i]||strstr($n,"2"))return; #if middle == zero or in new string is a 2 then it's not a number that we search return f($n); #recursive beginning } echo f(decbin($argv[1])); ``` True values < 10000 > > 1, 2, 3, 6, 7, 8, 10, 12, 15, 20, 22, 28, 31, 34, 38, 42, 48, 52, 56, 63, 74, 78, 90, 104, 108, 120, 127, 128, 130, 132, 142, 150, 160, 170, 178, 192, 204, 212, 232, 240, 255, 272, 274, 276, 286, 310, 336, 346, 370, 400, 412, 436, 472, 496, 511, 516, 518, 524, 542, 558, 580, 598, 614, 640, 642, 648, 666, 682, 704, 722, 738, 772, 796, 812, 852, 868, 896, 920, 936, 976, 992, 1023, 1060, 1062, 1068, 1086, 1134, 1188, 1206, 1254, 1312, 1314, 1320, 1338, 1386, 1440, 1458, 1506, 1572, 1596, 1644, 1716, 1764, 1824, 1848, 1896, 1968, 2016, 2047, 2050, 2054, 2058, 2064, 2068, 2072, 2110, 2142, 2176, 2180, 2184, 2222, 2254, 2306, 2320, 2358, 2390, 2432, 2470, 2502, 2562, 2576, 2618, 2650, 2688, 2730, 2762, 2866, 2898, 2978, 3010, 3072, 3076, 3080, 3132, 3164, 3244, 3276, 3328, 3380, 3412, 3492, 3524, 3584, 3640, 3672, 3752, 3784, 3888, 3920, 4000, 4032, 4095, 4162, 4166, 4170, 4176, 4180, 4184, 4222, 4318, 4416, 4420, 4424, 4462, 4558, 4674, 4688, 4726, 4822, 4928, 4966, 5062, 5186, 5200, 5242, 5338, 5440, 5482, 5578, 5746, 5842, 5986, 6082, 6208, 6212, 6216, 6268, 6364, 6508, 6604, 6720, 6772, 6868, 7012, 7108, 7232, 7288, 7384, 7528, 7624, 7792, 7888, 8032, 8128, 8191, 8202, 8206, 8218, 8232, 8236, 8248, 8318, 8382, 8456, 8460, 8472, 8542, 8606, 8714, 8744, 8814, 8878, 8968, 9038, 9102, 9218, 9222, 9234, 9248, 9252, 9264, 9334, 9398, 9472, 9476, 9488, 9558, 9622, 9730, 9760, 9830, 9894, 9984 > > > ]
[Question] [ In this quine variant, your program must output its source code transposed across the diagonal from the top left to the bottom right. For example: ``` your program on four lines ``` outputs ``` yof ono u u r r      p l r i o n g e r s a m ``` The whitespace in the output is not arbitrary. Spaces appear in two situations: where there is a space in the original (e.g. between `r` and `l` in the fourth column) and where it's necessary to pad characters (e.g. all the spaces in the first column.) Both are required, and spaces cannot appear anywhere else in the output. A single trailing newline in the output can optionally be ignored. Trailing newlines in the source code have no effect on the output, and leading newlines in the source code must be handled as in the example above. Assume that every character that is not a newline is one column wide and one row tall, even though for characters like tab this may lead to an ugly output. Your solution must have at least two lines with at least two non-newline characters each, and must not be its own transpose (the output cannot be identical to the source.) [Cheating quines](https://en.wikipedia.org/wiki/Quine_(computing)#.22Cheating.22_quines) that read from the file that contains their source code, pull data from a URL, use quining built-ins, and so on are not permitted. This is code golf: shortest code in bytes wins. [Answer] ## [Fission](https://github.com/C0deH4cker/Fission), 17 bytes Still my favourite language for quines... ``` '" !0 0+ ;! DN "! ``` [Try it online!](http://fission2.tryitonline.net/#code=JyIKITAKMCsKOyEKRE4KIiE&input=) ### Explanation This quite similar to the basic [Fission quine](https://codegolf.stackexchange.com/a/50968/8478). In fact, if it wasn't for the "must have at least two lines with at least two non-newline characters each" rule, I simply could have transposed that and replace `R` with `D`. That rule makes things a bit more interesting though, because we need to print another line. Control flow starts at the `D` with a single atom going south. Since it hits the `"` it will wrap around and print ``` '!0;D ``` to STDOUT, similar to how it would in the normal quine. `'!` then sets the atom's mass to the character code of `!`. The `0` is a teleporter which transports the atom to the second column, where it's still moving south. With `+` we increment the atom's mass to the value of `"`. `!N!` the prints quote, linefeed, quote. STDOUT now looks like this: ``` '!0;D" " ``` After wrapping around, the atom hits another `"` and now prints the second line verbatim: ``` '!0;D" "0+!N! ``` We're done now. The atom uses the teleporter once again, and lands in the `;` which destroys it and thereby terminates the program. I suppose the neatest bit here is putting one `"` at the bottom and the other at the top so that I can print them in one go without having to set the value of `!` once more (because it would get overwritten by entering string mode again). [Answer] ## CJam, 14 bytes ``` {`"_~".+N*} _~ ``` [Test it here.](http://cjam.aditsu.net/#code=%7B%60%22_~%22.%2BN*%7D%0A_~) While shorter, probably a bit less interesting than the Fission solution. ### Explanation ``` { e# Quine framework. Runs the block while another copy of it is on the stack. ` e# Stringify the block. "_~" e# Push the remaining code as a string. .+ e# Element-wise append... essentially puts the two strings in a grid and e# transposes it. N* e# Join with linefeeds. }_~ ``` [Answer] # Javascript ES6, 90 bytes ``` $=_=>[...(_=`$=${$};$()`.split` `)[0]].map((x,y)=>_.map(v=>[... v][y]).join``).join` `;$() ``` Not bad, not bad. # Explanation Here's the standard quine framework: ``` $=_=>`$=${$};$()`;$() ``` To modify, I just split the quine string along newlines and chars to create a matrix of chars, transposed using 2 map functions, and joined to create the output. [Answer] # [Stax](https://github.com/tomtheisen/stax), 23 bytes ``` "34bL:f2MMm "34bL:f2MMm ``` [Try it online!](https://staxlang.xyz/#c=%2234bL%3Af2MMm%0A%2234bL%3Af2MMm&i=&a=1) Adaptation of the `"34bL"34bL` quine, which is based on an idea used in quines in many languages. [Answer] # [Befunge-93](http://www.quirkster.com/iano/js/befunge.html), 57 bytes ``` ^ _^ ,@ +, 5* 52 ,+ *9 28 +| 9 8# |! , ## !: ,^ # : ^ "" ``` This works by putting each character in the first column on the stack (except the quote itself), then printing each item off of the stack. After that, it prints the quote, prints a newline, and then moves over to the second column. It does the same thing sans print a newline. You can test it in the link in the title, but you'll need to copy-paste the code into the window yourself. If you hit the 'slow' button, it will show you the path the pointer takes and the stack at the time. [Answer] # Python 2, ~~91~~ ~~75~~ 69 bytes ``` s='#%r;print"s#\\n="+"\\n".join(s%%s)';print"s#\n="+"\n".join(s%s) ## ``` [**Try it online**](https://tio.run/nexus/python2#@19sq66sWmRdUJSZV6JUrBwTk2erpK0EpJT0svIz8zSKVVWLNdUR8hBphGyxJpey8v//AA) ### Explanation: This uses a modification of the standard quine: ``` s='s=%r;print s%%s';print s%s ``` After modification: ``` s='s=%r;print"\\n".join(s%%s)';print"\n".join(s%s) ``` This would be enough if a single line was allowed. Then, I added two characters to the 2nd line to fulfill that requirement. The `#` chars on the second line can be replaced with anything, so long as you change them in the first line, too, and it makes the program syntactically valid. To print it correctly now, I have to print `#` at the end of the first two lines. So I remove the first two characters from the string `s`, and print those with `#` before printing `s%s`. I put one of the `#` at the start of `s` to save some bytes by removing a newline literal. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 6 years ago. [Improve this question](/posts/53210/edit) This is a challenge about the the tricks and optimizations that can be used when golfing in Pyth. Pyth golfers may recognize many of the tricks involved. However, unfamiliar approaches and constructs may be involved, so take a look at the [Pyth Tips](https://codegolf.stackexchange.com/questions/40039/tips-for-golfing-in-pyth) as well as the [Pyth Character Reference](https://pyth.herokuapp.com/) if you get stuck. Solutions may be tested [here](https://pyth.herokuapp.com/). **Goal:** There are 8 problems, each with a Pyth snippet for you to optimize. Your goal is to create something equivalent but shorter. The reference solutions total 80 bytes. Your goal is to beat that by as much as possible. The winner will go to the submission that solves all 8 problems with the smallest total number of bytes. Tiebreaker is earlier post. **Answering:** Please spoiler your entire answer, except for your total score. It is intended that you do not look at other people's answers before submitting your own. Each submission should answer every problem and give the corresponding byte count, but feel free to use the reference implementation if you cannot improve it. **Details:** If the question calls for a certain value or output, `q` equality is desired, so `1` and `!0` are equivalent. If the question calls for testing whether a condition is true, the output must be truthy if the condition is true and falsy if the condition is false, but is unconstrained beyond that. You may not swap true for false and false for true. If the question calls for something to be printed, nothing else may be printed except a trailing newline. All answers must be valid for the most recent [Pyth commit](https://github.com/isaacg1/pyth) as of this question's posting. **Problem 1:** Given a set in Q, output a list containing the elements of Q in any order. ``` ; 3 bytes f1Q ``` **Problem 2:** Output the list `[1, 1, 0, 0, 1, 1, 0]`. ``` ; 9 bytes [J1JZZJJZ ``` **Problem 3:** Given a positive integer in Q, test whether all of Q's digits are positive (not zero). ``` ; 7 bytes !f!TjQT ``` **Problem 4:** Given a string in z, test whether z contains any quotation marks - `"` or `'`. ``` ; 9 bytes |}\'z}\"z ``` **Problem 5:** Map Q=1 to 'Win', Q=0 to 'Tie' and Q=-1 to 'Lose'. ``` ; 20 bytes @["Tie""Win""Lose")Q ``` **Problem 6:** Print `0123456789`. ``` ; 6 bytes sm`dUT ``` **Problem 7:** Given a string in z, count the number of inversions. (Indexes `i` and `j` form an inversion if `i < j` but `z[i] > z[j]`). ``` ; 17 bytes ssmm>@zd@zkrdlzUz ``` **Problem 8:** Given a list in z, count the number of repeated adjacent elements. ``` ; 9 bytes lfqFT.:z2 ``` [Answer] # 52 bytes > > **Problem 1: 2 bytes** > > ``` > SQ > ``` > > > **Problem 2: 5 bytes** > > ``` > jC\f2 > ``` > > > **Problem 3: 4 bytes** > > > ``` > -0`Q > ``` > > **Problem 4: 6 bytes** > > ``` > @z+N\' > ``` > > **Problem 5: 17 bytes** > > ``` > %3>"LTWoiisene"hQ > ``` > > or > > ``` > @c3"LoseTieWin"hQ > ``` > > **Problem 6: 3 bytes** > > ``` > pMT > ``` > > **Problem 7: 9 bytes** > > ``` > s>R_d.cz2 > ``` > > **Problem 8: 6 bytes** > > ``` > sqVztz > ``` > > > Combining @xnor's solution for problem 4 with mine (both 6 bytes) gives a nice [4 bytes](http://pyth.herokuapp.com/?code=%40z%60N&debug=0) solution. So 48 bytes are possible. > > > [Answer] # 54 bytes > > **Task 1, 2 bytes**: `SQ` > > **Task 2, 6 bytes**: `j102 2` > > **Task 3, 5 bytes**: `*FjQT` > > **Task 4, 6 bytes**: `@z"'\"` > > **Task 5, 17 bytes**: `@c3"LoseTieWin"hQ` > > **Task 6, 4 bytes**: `jkUT` > > **Task 7, 7 bytes**: `s>M.cz2` > > **Task 8, 7 bytes**: `sqM.:z2` > > > [Answer] # 58 bytes > > **Task 1, 2 bytes**: `SQ` > > **Task 2, 5 bytes**: `jC\f2` > > **Task 3, 6 bytes**: `!}`Z`Q` > > **Task 4, 8 bytes**: `|}\'z}Nz` > > **Task 5, 18 bytes**: `@c"Tie\nWin\nLose"bQ` > > **Task 6, 4 bytes**: `jkUT` > > **Task 7, 9 bytes**: `lf>FT.cz2` > > **Task 8, 6 bytes**: `sqVtzz` > > > [Answer] This post is for the accumulation of the best solutions across all answers. Please edit in the solution and the answerer who first found that solution if there any improvements. # 48 bytes > > 1. `SQ` - 2 bytes, first posted by @orlp > > 2. `jC\f2` - 5 bytes, first posted by @Maltysen > > 3. `-0`Q` - 4 bytes, first posted by @Jakube > > 4. `@z`N` - 4 bytes, mixture of @xnor and @Jakube, but not in any answers yet. > (I didn't see it when writing the question, either) > > 5. `@c3"LoseTieWin"hQ` - 17 bytes, first posted by @orlp > > 6. `pMT` - 3 bytes, first posted by @Jakube > > 7. `s>M.cz2` - 7 bytes, first posted by @orlp > > 8. `sqVtzz` - 6 bytes, first posted by @Maltysen > > > [Answer] ## 57 bytes > > 1. (2) `SQ` Sort. > > 2. (5) `jC\f2` Convert `f` to ASCII val then base 2. > > 3. (5) `/`Q`0` Count `'0'` in the number string. > > 4. (5) `@z`\'` Takes the set intersection of the string with `"'"`. > > 5. (18) `@c"Tie Win Lose"dQ` Makes the list with split. I didn't get slicing to work. > > 6. (4) `jkUT` Join `range(10)`. Apparently converts to a string automatically. > > 7. (9) `sm>d_d.:z`Counts substrings that are greater than their reverse. > > 8. (9) `l@C,zz.:z` Length of intersection of sublists of the list and pairs of elements in the list. Same length as reference solution. > > > ]
[Question] [ My daughter had the following assignment for her math homework. Imagine six friends living on a line, named E, F, G, H, J and K. Their positions on the line are as indicated (not to scale) below: ![](https://i.stack.imgur.com/ECRsA.png) Thus, F lives five units from E, and two units from G, and so forth. Your assignment: craft a program that identifies a path that visits each friend exactly once with a total length of *n* units, taking the locations of the friends and *n* as inputs. It should report the path if it finds it (for example, for length 17 it might report "E,F,G,H,J,K", and it should exit gracefully if no solution exists. For what it's worth, I completed an ungolfed solution in Mathematica in 271 bytes. I suspect it's possible much more concisely than that. [Answer] # Mathematica, 55 or 90 bytes Mathematica you said? ;) ``` FirstCase[Permutations@#,p_/;Tr@Abs@Differences@p==#2]& ``` This is an anonymous function that first takes the positions of the friends (in any order), and then the target length. It returns `Missing[NotFound]`, if no such path exists. ``` FirstCase[Permutations@#,p_/;Tr@Abs@Differences@p==#2]&[{0, 5, 7, 13, 16, 17}, 62] (* {7, 16, 0, 17, 5, 13} *) ``` I can save four bytes if returning all valid paths is allowed (`FirstCase` -> `Cases`). Returning an array of strings is a bit more cumbersome: ``` FromCharacterCode[68+#]&/@Ordering@FirstCase[Permutations@#,p_/;Tr@Abs@Differences@p==#2]& ``` [Answer] # Python 2, ~~154~~ 148 bytes ### (or 118 bytes for the general solution) This program accepts a line with a list and an integer like '[0, 5, 7, 13, 16, 17], n' on stdin and prints a path on the output of length n or nothing if impossible. ``` # echo "[0, 5, 7, 13, 16, 17], 62" | python soln.py ['G', 'J', 'E', 'K', 'F', 'H'] ``` It is challenging to write small programs in Python that require permutations. That import and use is very costly. ``` from itertools import* a,c=input() for b in permutations(a): if sum(abs(p-q)for p,q in zip(b[1:],b))==c:print['EFGHJK'[a.index(n)]for n in b];break ``` The source for the OP requirement before the minifier: ``` from itertools import* puzzle, goal = input() for option in permutations(puzzle): if sum(abs(p-q) for p,q in zip(option[1:], option)) == goal : print ['EFGHJK'[puzzle.index(n)] for n in option]; break ``` The general solution (not minified): ``` from itertools import* puzzle, goal = input() for option in permutations(puzzle): if sum(abs(p-q) for p,q in zip(option[1:], option)) == goal : print option; break ``` Due to the simple algorithm and vast number of combinations, execution for more than 20 initial positions will be very slow. [Answer] # J (48 or 65) I hypothesize that this can be golfed a hell of a lot more. Feel free to use this as a jumping off point to golf it further ``` ]A.~[:I.(=([:([:+/}:([:|-)}.)"1(A.~([:i.[:!#)))) ``` Or with letters: ``` ([:I.(=([:([:+/}:([:|-)}.)"1(A.~([:i.[:!#)))))A.[:(a.{~65+[:i.#)] ``` ## What it does: ``` 62 (]A.~[:I.(=([:([:+/}:([:|-)}.)"1(A.~([:i.[:!#))))) 0 5 7 13 16 17 7 16 0 17 5 13 7 16 5 17 0 13 7 17 0 16 5 13 7 17 5 16 0 13 13 0 16 5 17 7 13 0 17 5 16 7 13 5 16 0 17 7 13 5 17 0 16 7 ``` (I hope this I/O format is okay...) ## How it does it: ``` (A.~([:i.[:!#)) ``` Generates all permutations of the input ``` ([:+/}:([:|-)}.)"1 ``` Calculates the distance ``` (]A.~[: I. (= ([:distance perms))) ``` Sees which results are the same as the input, and re-generates those permutations (I suspect some characters can be shaved off here) With letters: ``` ((a.{~65+[:i.#)) ``` Create a list of the first n letters, where n is the length of the input list ``` indices A. [: letters ] ``` does the same as above [Answer] # Octave, 73 ``` function r=t(l,d,s)r=perms(l)(find(sum(abs(diff(perms(d)')))==s,1),:);end ``` There's really no un-golfing this, so let me try to explain... from inside to out, we permute all the distances, then for each permutation, we take the differences between houses, take the absolute value as a distance, add them up, find the index of the first permutation with the desired distance, and permute the letters and find that particular permutation of letters. ``` octave:15> t(["E" "F" "G" "H" "J" "K"],[0 5 7 13 16 17],62) ans = HEJFKG ``` which is 13-0-16-5-17-7 => 13+16+11+12+10=62. ``` octave:16> t(["E" "F" "G" "H" "J" "K"],[0 5 7 13 16 17],2) ans = ``` (blank for impossible inputs) [Answer] # Matlab (86) ``` x=input('');X=perms(1:6);disp(char(X(find(sum(abs(diff(x(X).')))==input(''),1),:)+64)) ``` Example in which a solution exists: ``` >> x=input('');X=perms(1:6);disp(char(X(find(sum(abs(diff(x(X).')))==input(''),1),:)+64)) [0, 5, 7, 13, 16, 17] 62 DBFAEC >> ``` Example in which a solution doesn't exist: ``` >> x=input('');X=perms(1:6);disp(char(X(find(sum(abs(diff(x(X).')))==input(''),1),:)+64)) [0, 5, 7, 13, 16, 17] 100 >> ``` --- # Matlab (62) If the **output format can be relaxed** by producing positions instead of letters, and producing an empty matrix if no solution exists: ``` X=perms(input(''));X(find(sum(abs(diff(X.')))==input(''),1),:) ``` Example in which a solution exists: ``` >> X=perms(input(''));X(find(sum(abs(diff(X.')))==input(''),1),:) [0, 5, 7, 13, 16, 17] 62 ans = 13 5 17 0 16 7 ``` Example in which a solution doesn't exist: ``` >> X=perms(input(''));X(find(sum(abs(diff(X.')))==input(''),1),:) [0, 5, 7, 13, 16, 17] 62 ans = Empty matrix: 0-by-6 ``` --- # Matlab (54) If it's acceptable for the program to provide **all valid paths**: ``` X=perms(input(''));X(sum(abs(diff(X.')))==input(''),:) ``` Example in which a solution exists: ``` >> X=perms(input(''));X(sum(abs(diff(X.')))==input(''),:) [0, 5, 7, 13, 16, 17] 62 ans = 13 5 17 0 16 7 13 5 16 0 17 7 13 0 17 5 16 7 13 0 16 5 17 7 7 16 5 17 0 13 7 16 0 17 5 13 7 17 5 16 0 13 7 17 0 16 5 13 ``` [Answer] # J, 54 bytes Outputs one correct route. If no route exists it outputs nothing. ``` f=.4 :'{.(x=+/|:2|@-/\"#.s A.y)#(s=.i.!6)A.''EFGHJK''' 62 f 0 5 7 13 16 17 GJEKFH ``` 52-byte code that outputs all routes (one per line): ``` f=.4 :'(x=+/|:2|@-/\"#.s A.y)#(s=.i.!6)A.''EFGHJK''' ``` 38-byte code that outputs positions instead letters: ``` f=.4 :'p#~x=+/|:2|@-/\"#.p=.(i.!6)A.y' ``` [Answer] # Haskell, 109 bytes ``` import Data.List a%b=abs$snd a-snd b n#l=[map(fst)p|p<-permutations(zip['E'..]l),n==sum(zipWith(%)p(tail p))] ``` Usage example: `17 # [0, 5, 7, 13, 16, 17]` which outputs all valid paths, i.e. `["EFGHIJ","JIHGFE"]`. If there's no valid path, the empty list `[]` is returned. The list of letters includes `I` (hope that's fine). How it works: make a list of `(name, position)` pairs, permute and take those where the path length equals `n` and remove the position part. [Answer] # [Python](https://python.org) + [`golfing-shortcuts`](https://github.com/nayakrujul/golfing-shortcuts), 123 bytes A port of [Logic Night's answer](https://codegolf.stackexchange.com/a/46865/114446). ``` from s import* def F(A,C): for B in Im(A): if s(abs(P-Q)for P,Q in z(B[1:],B))==C:p(['EFGHJK'[li(A,N)]for N in B]);break ``` ]
[Question] [ Inspired by the connection rules from [Calvin's Hobbies](https://codegolf.stackexchange.com/users/26997/calvins-hobbies)' question [Make me an alphabet tree](https://codegolf.stackexchange.com/questions/35862/make-me-an-alphabet-tree) take a number of lines of letters as input and output the number of distinct connected trees it represents. Letters connect to diagonally adjacent letters (never horizontally or vertically) and only where such a connection is available. Available connections correspond to the end of a line in the shape of the letter. For example, X can potentially connect at all four corners as they are all the ends of lines. W can only connect at the top left and top right corners, as the bottom left and bottom right corners are not ends of lines. ## Example 1 Input: ``` XXX XXX XXX ``` Output: ``` 2 ``` The two trees (which do not form part of the output): ``` X X X \ / / \ X X X / \ \ / X X X ``` ## Example 2 Input: ``` AMF QWK ``` Output: ``` 3 ``` The three trees (which do not form part of the output): ``` A F M \ / \ W Q K ``` ## Rules 1. The only valid characters are spaces, newlines, and the 23 upper case letters listed in Calvin's Hobbies' question: ACEFGHIJKLMNPQRSTUVWXYZ. 2. The letters B, D and O are not valid. 3. The output is undefined if the input contains invalid characters. 4. A tree can be of any size, including just 1 letter and including over 23 letters. 5. The same letter can appear an arbitrary number of times in a single tree. 6. The input will not be more than 79 lines long. 7. Each line (excluding newlines) will not be more than 79 characters long. 8. The lines will not necessarily be the same length as each other. 9. A tree is defined to be a set of connected letters. Since the connections are all diagonal this excludes letters which are horizontally or vertically adjacent from being part of the same tree. 10. Input containing zero trees (for example, all spaces and newlines) gives output 0. 11. To clarify, input and output are as defined on [meta](http://meta.codegolf.stackexchange.com/questions/1324/standard-definitions-of-terms-within-specifications/1326#1326) (so there is not already a variable containing the input). This is code golf. The shortest correct code wins. Code length is measured in bytes. If you have python 3.4, the [alphabet tree counter](https://github.com/phagocyte/Alphabet-tree-counter/blob/master/alphabet-tree-counter.py) outputs the number of connected trees in its input, and can be used to test your golfed code gives the same results. The [alphabet tree checker](https://github.com/phagocyte/Alphabet-tree-checker/blob/master/alphabet-tree-checker.py) confirms whether its input is a valid output for Calvin's Hobbies' original question, and outputs a list of the distinct trees in the input. This may be useful for visualising the trees if there is any dispute over the number of trees in a given input (although using it on large forests will give a lot of output - a visualisation of every single tree separately). If the either of these is incorrect please let me know so I can fix it. ## Table of connections. 1 is for upper left, 2 is for upper right, 3 lower left, 4 lower right. ``` A: 3 4 C: 2 4 E: 2 4 F: 2 3 G: 2 H: 1 2 3 4 I: 1 2 3 4 J: 1 3 K: 1 2 3 4 L: 1 4 M: 3 4 N: 2 3 P: 3 Q: 4 R: 3 4 S: 2 3 T: 1 2 U: 1 2 V: 1 2 W: 1 2 X: 1 2 3 4 Y: 1 2 Z: 1 4 ``` ## Sample forest Here is an example of a forest to test your code with. It has the maximum size of 79 x 79 and no spaces. The alphabet tree counter gives an output of 714. I don't recommend running the alphabet tree ***checker*** on it as it will try to output a separate visualisation of every single one of the 714 trees. ``` CKZNXXJEHCNHICKFHNAFZTMNXZKXSXAFHEKKFJYUZPCHRSNAUPEZKIHZJSKKPHQJYHKMXSHCXKEHCXQ YSRCHHQLXXKKXITAAHSKMXISHIGFXMVXTZZKLXIXVHJYKTAHSHYPCFLHSWIHHCXXRXXJNKXXVVRNSKM CZWJKKNIXXUHKXCKRTXXSVHQZERHXIXNHXPKELNKHXRHFKHIEPKUWKXKUPHEKKIKLLSFWUSLYEEXLSI KHGURVKSXXKAGXIWKCSHFNVWWHNHNIVYKKAKZKFSKHCVRHUENHFIIKNUNICHYRKYXXHTLKYHPQKWHKI KGAFRXJMKMJJSXCUTFAKLHHFXTIXKNHKKRHIZHXWRRXJNHXQEMKKXCNVHWFMPERJKKZLHIKIUZRKWLM YRXXXCXXHVISVIYTHNHKSXKRXYHXUFYYKXTHXRYIIKHEWHXVZAZHTQKJAKKHXKKVCKJHWHIIZXXZZYK FQLXHIHJFKSKWMTHXISAXTVIKKHTIXUAGUAJHHHHRVHXHRNWKXKUKWHVUJLKIJCWTLCHTXSYTKLTFWX AEKNFXUXHXHICSNCYWNEVVALHXUSACWKRNJAKLLXKVJCZHSAKYHXLHHTHFKSMCGXHFHPKTHXTRYYWXK HHHKHXGKFUHKSKHKKHHRHIKYNQSXMKQKIXHTXXHHIXCZIWGXKAHRXKRYXPXXXVSYIXWXVMUFYWHKINZ XXWWHXUTXGKXFKZUTHHZPJGMAEHZVGHLEXHKKPXHZIVKFETHKXTIVKSMHWYEKHIMIHWEHKHIIJXXJZS XHHXHRHKKXHHVXYZMNHIYHKKXXKAVWKUKEXYGGCHMLHFJCKXXXHEXGCZUKMHIXKVXKHZHFLCKXIPZHH TCHAXXKHHNKKMKPRFKKURCWLFXWIXUGTKKXHKRSYKZUXQXIEYWWWKKIXGXHALKAXXJHEXXLMNXJKHHL INKRHXMMXZSTAZZKGLAPKLHSPGKUINHUMXXXLTNZWENCXLKRIXHZXHHKHCSXSHHXXKCTXXXHSFHJIHI SHXKTXKXWPYZXKCNYSAVMICKJHKSMXKAWVNHZKGPFYPAEKEWXNKXXHKEYHAYWKIYHKXEHNJJRISLXXI IHZLMKYUTHWHIXEKRJIHFVHCFKLMSKIKHMUHQLYXILMHKXXXCJHZXJKKHSHXMVCHIGSICHITKIGMYYT USKJTKLQYXYKKRKELMXVMLKNNNXIHPHMXKNXXYFKRHXRNNJRCQKEFKXXSWHUECTMCWVCXHLALKMSIZM VCKPXRCSYRVEKTCUHKVIKAXHMNMJMTKMGXEPJXYZVLKQFIIJRZHXHHSSRKHHYRHZXFHXXLUKXCAHNXX CGHQIQXTHRLIKKQFHQCUKZXLMVLSWHJKGKYKJMKVFIHHKYHCKAFXHMEHKJKMKWIXAYEKYKCXIMKHRXJ XYIJIIAHHEXKIYGKHKIALIXKRHRXYXRAVHGXTUKKKXHIIGNHXFVVHTFUKHNIKHFKRXHXXNIIXTSQHIH XSNXRHIUXHTXWYRHXHSXZKKKXIKHEKSHHWINIGEIXNJYSXILYIKHVYAMFNKXYWEINHHXSVFVXQRHUHW FRIRFCKFKIVHCKYXKXMTXELJXNCKWYHKXVTXIIHFVFZVHYSXEXZNWKWIXESHXFHKCKVPXUXCIMRHNXR XELHXNMKVHRHHHVKTKKPCXEXZHKPHNAWVXJKWWHMSKFFRUJVSHGXFATZSSWYXKHIHKAHXIEJXSKXFLE KFKECCCPWKXJTVKXHJRYVXUIFHKUHHHLMKSVJICQHKXZKNIXHKEHKNYTKKFKHUCHZFILHRHKHQKIIEJ MGIKXXPZQXHRHHXKXJHAGJKHIXKILXNEVWHXWWLTFWHHUMKJPZTJXXTXVPTMHHMGEPHIXRHLGQTWJCV UKHXXYXHAFXXSIJXHHXKLJQJIIKXIKYHSRKUNNKHTMXTCTKXGWFHSJKQSCHINSKLGSKUTXKKAWAEXAM LFKXWWXXSKKXPUIKTFREKIXLXNXKHHVXJKVWEFKFMYFIHGHXSHTEUJRIEAMQSXQMRJIHRETXYMHKIUX XFAAMXHXUFITLAWNMJYHTCWQFNXAIXKSZXIXXKRKAHWHYEAMVHNKLHKVUTAIZLVXGCHHAZTTHCELIGK XPJRXIVVFTJKQFNSKMKFKIHMRCHWFYVIRVXFPTKIKUKQKKMVKWIYIKRXWEVXUIHFHXASHHXVFWEWHHK KYELCKHLXXHXHTVMJHNFQUFJXKUHIZXFEXRZMEYZHSJXVZKMYHNCVEXKXKATRFLGHXTHXRPHXLHKSTY IXUUFXHWMKRIWWIRSKSCQHXSIIKRHXZNFCXXHSLXHRNHZXNWHKMQRPTHTHXXSVKHXZXICYHSXXXKXHU TXESLHCCEHHHHKHICSILWLHFEKVKSUECLAZHZXIKRUKWKFHXILWNSTMXXAGKWVLQNXESKXYIIXKXZRI HHSSHXRXKHNUWLKPXLIXFUIHXNKIKJCHTGWXLJZSLHSMZMSZTKLFAVEKIMGXJVAIKXHWUUHKHURIYMG IXMYFVXIWMZVNVYWKYFVXJKKEHKMNLYXNXFSRHHSANKTKTNVKNTRHPXKLRCMHLHUWKIMGWVFAPZXWXH RHIKVZWLHJYUKCQSSCNZFRRMXTJXQMRXCZIVPRHJMHVVXHHHLHKNKRKNXLKKREIWSTINKKXFSMPILXK KSFKKXGIAKXKRWHNHZMVFVFUHIKJWIHUJHHNKKSXMMUVNHEJIYCCWEHHHGJXWJJVXWIPXCKWHSXFYXI RWVXEHJLHANHXIVHMMQHAHHRKTMHXXXLHPCQRSHTHVXXJSXQZRHKKLSFYXKTKLKXHKHRSXLKKXUJXKJ TNKIMHEXKVYMVMRKTXIXJHTXYIXKMHXKKWQGFLGIFIKXKTMXSYYMTVQITPWHXHHKXEYKXHHJETJHXVK KXEWWAHIHVHXAUTCHZLRXKMKHKNKREKKMKHIHPXXZNFHFYIXHJXXWKIKHQWWISXZHJZKHHZXTGIIXJN YKZHRXXFQKHKXZHVEWSHREHKIYTFSTHLREKHFJIAVWKMKJMXHXKWKWYRTKMHIIXNCVKXRHKKEMYERRL KREZXUHKRQKFYKWKHEZXKWWXEHXYKLAIKYNVXFRPUNFHVJHKWZXSXKIHKYHKXFHYXXXTXIXIXGIXKHK ZHIKXXXRCSKVKYVHXKRJHHXWCNEXRQIKAIHHTFHWCSCZCHKXMUMKLVKXPKLIZIYKRKHIKZSHHAKCNKK ZUHHHWKMNIXRGAVXHCXAQUKXHHEXLIRNNHLHCKRZSXHKMKWTKHKVJEUSKHXEFPHMPKHYKKUMHFLKSIJ KKKZXHRRNSSKXWIUCXPJUFLJSVXHMRKHXWHYURHXNKCWKIXKKWHXZMRAHHXCKIHKXXTJRHTEHUHTPZK HAKHLHCEGIXIIVAYWWKXCEXIHKWMKEHILYZEXKHKYVWJVKVYHFTSNIHGHCIJXKNSXXTXHSYEXNFKHSY KWGUHKCXWGCXKFSIPZXIZKPLHIXXYPKYHHFKYMNTXHIVMNTRYJPUKUKYUMZFTYSIIXVAXINHCMXKTEH GQYGHKHIKKKIKXYGCHKLAYSXPHHKFSICIKFFHSKHMAWVYKHJKNZZXYISGZMJWRRIJILHHKKHFFKARKH RIKUACKKMVIGHXKKMHFSXJEKXFMKSHXZXHKMHHXXSXHHLXHHEKKAKMXXECVLHEIKGWACSNKKVKARERJ CXMVNITXXMKCYUIHUHUXUIKYHNZYHXXLTHJATGKHKTIKKYTWXRJIXCJNHTYXIRLTKAMEHZMKRJXHAWV HKIMIQKMRSJNHZZYKHWWKSFIRHKHFWKKYFITXWATKKXSECSHKXHPQCNIIIWFMKUHUMXWCXYJHVSVELR NXUKLFAHVGGHYVTAWNIXHKXHXHXXAKKANKYIFXUTLKKTHHIKHKATJXKXETTWEKNIHQSKIXXJXXYLXXJ RXPCUSXZLZXVKIRLSVXHHXXKMAIXCXXQVIKIUKIXIXXJHXFRRSXXQREIWHXFKWISXYHVEKHYYXKZLMN XCHKWYHJRWXRLXLEAXXHKVRKLGUMWSCXINKHMNHHISNKLVKWXRWKEKPCRGZNIXSXTXHEKEEKHXTHJUH XGVNFTHKHNVGXGSRIPGKFXZTUKEKYKIINRKUHIKLHXRIYXRIKXSCENMZLXXHAXXWTIGJXHHWXHMIFIK HEVJQXTXKPFSTVKWGKXTKYRXJHVPKKNLQLPSXPIZVNIAKJJRHZHKFXIGRHKVCTVXINNHTGLIHMVYINA HIQHXXVZAHIHRHIHFTUWFKGKQKTAUXJSIXWHUXNXJIJIIAWUKHRLIHKVSIFSNKKHNTYCTPNWIKHHIKX MRLCMZXPALCTFXPHVHSVNXTJWFHKQZTZEYMALXXIXRJIKCFJYSPXKZXKUGKZLQHKUYINNUKKKLKMVLI VQHFXEKRVSHKKKHGWZWTLXRFWMVXHKKXWXKEHAJIXJKHXFNNGHKKLXKKKLJYKJEEHCKXTGHHICISHMF ZXPUAXPXKXXVYAHPIJHLRCIKXLCGZXLWFJPHXAHFKSLFEHGLKHFIIHHKHHCTVAKWPXWGIQKHNILHQJW XHPIQLZHKVUKXCMLHSFHEKHEKREWXKYIXSZHTAHIIEUYVUHSMKTHFKMGKSLMHXKYACCXXKATLYXKXFL WKHIKFVFKUVXXRVEYUTCRNCXPZCCLSKTHWQXXJMHFLKXHNXCVZXHGXYAVYEXVJCHKXIKMSVAXVHNEXV IXIKYSSJQKKPTXFXFREKXJAKKXEJXNVXHEUJHIMHHPNRVZHXUKZPWTXCCIHXAKZUSHXRMSLIUWHIHKK MXIHKCKKHSIHXCKCRKATFKFSJXLRXIJNFYQISMKHSAYKZXPXNIHWSKHXYZLAVXIEXVTYHGSRXXAGQRK IMCXXHXSCXVXCKCTHNSHWEIRAELTJMFKCXQIIXVFSZXHXXIPCCFIZXEXPWHEGJUHWXGZJCISRJSCIPV HIXHUIHJXXLXXXZLNZCTJKYHNHAVIHIITLHXGEXXKUIXGNKLHHUVFJAFKHHPCJSUKXHCSIHKCXZEIFI UKUHWRKSJFKZNYJMSZYRTXZKWHVIXLXHRFXTZHTHHHUMYTXKRXMFAKLUMAPNGHKKJUKYIHUXQHMIUVI XHCKNCKTSXTZMHETTLTMYXHJKUUVXHHSHIVSZKHHWXAWMFXVVHFUCXHMXWKXHXKVLLHXZSICSACKIHC FXFNPHXHTHCLHKJTSLVTHKHHXHXHHKTKSUTIXKYQUHAQXXNSLKUMTKHSKKYTXHTVPGVHHMXVNLHXIRF WJFVVXITNRCXKHTFARSIXASVCNXJQNXIJVUHYIVNIRZXMHHFKHKMMNCUXFTEXEKEHTIHSKAKXZVTSKY ZJGHRTHUWMHHZXHPAIHWHUSXXKLHKYKHJSHHNKXXKRSHMKHSIHIUIXKZXSUZHKXIMMIXMXTXZZLXXIM EQZKRLALIEVHXYKHXIFYKXMAINSNIASMGLLYHXHRIXVWUKZHFREJCAXKXWYHXNUKTQCUKIHLWKTEKMC MHLXXHHYQWHTXVHCMKKHGIUFSEHNEVYSXQHHXXKHMXUXQKHZHHHSHRKWHMMEHZMIKKYYWIUNEIJUIKT NCHKRNSJYLLIXKXAIERXKKXIQZVHXFVIIAXHIYUGZURXFHSXKLIWESKHEXQSCUHWKALZIVEZHAFKKWA IKCJWNVRKMITKNYXJYKYXVXXUKWHXXJAKLXXXVKXGXKKZXMHCKKCGRLZQINVHRLNVWXTKVLTEPTXUXH XVCICKXXXEVTIKIHHSHCKYIJXNCJKJSLSHVXJHTHSIKUXPHWRIKMFXXMMHKHCAQWITIEWEXPFHYXXKU XXSHHIXHWWRKITSHSXHJKEWHXIZHSHZCHFARIXNPHYSNIKJXLQENKFCXYRWMXAPIYTZKNMXFHNIMCCS PAACXJMNVZZHMXXSNVSXEIINNCHLSTIXHHKYXLEHQHKHPRWIXXHRKVCXFKLHSHKGXJGKLLLWSHIISKT WUYXTJHXXMKJCYIXQJRNFKYHHUUKTIAYXVUUXFCYLHXWWZAUHWZIUAIGKHKIMKXXXKJZXCKKRCJAKQJ EVAGXIHTINSXENKWVXWCLFUVHXFPFCIFVHWXRIFZRYZKUUEMXNGAJLIFHJJIGUXFKKRIMKGFKXJYXKV KKRHHWKIYXWXWKLWXWKFHXLXRXRKKENMHHIQRHTTMFYTGRLSHRXIXKKUEHXXJKRIKSYLTKYJMNIUWVE ``` [Answer] ## Ruby - 228 My very first Ruby golf. Still new to Ruby. Ruby is awesome language! Love learning it! =) But I'm afraid will probably lose. =( ``` g=$<.each.map{|k|k.ljust 99}*''<<?@*1e5 p (0..1e4).map(&f=->k,a=!0{l=(0..3).map{|i|k+~0**i+99*~0**(i/2)if"xhv8gstx930ognx8puyr".to_i(36)>>(i+4*g[k].ord-260)&1>0};(g[k]=?@;l.map{|v|v&&f[v,k]})if(l&[a]!=[])|!a&l.any?}).count{|x|x} ``` To run, create a file with the forest as `forest.txt` and run using `ruby test.rb forest.txt` **[GoRuby](http://ruby.janlelis.de/34-do-you-know-the-official-ruby-interpreter-goruby) Edition - 188** ``` g=A.e.m{|k|k.lj 99}.j.lj 1e5 p 9999.mp(&f=->k,a=N{l=4.mp{|i|k+~0**i+99*~0**(i/2)if"xhv8gstx930ognx8puyr".toi(36)>>(i+4*g.g(k)-260)&1>0}.cp;(g[k]=?@;l.m{|v|f[v,k]})if(l.i a)|!a&l.an}).cp.sz ``` Ok... So my fear came true. @Howard (I'd actually expected him) actually made a GS solution. [Answer] # JavaScript (E6) 235 ~~238 240 276 284 291 294 319~~ A function with a string parameter (the forest), returning the tree count. This seems ok with the rules in meta about input/ouput (point 2). This scans the forest numbering the branches (var u) and keeping a running count of joinined branches (var j now). Branches that have been joined are remembered in a set, so that two joined branches are recognizable even if they have different numbers. **Edit** Slightly changed the algorithm, now it manages the forest string as a char array avoiding the split into lines. Simplified the branch joining - slower but shorter. Bonus: at the end the r array can be used as a map to extract any of the n trees from the forest. I'll elaborate. ~~Probably a little more golfable, but not so much as the answer in Ruby. I'll try.~~ **Edit** Ruby *and* goRuby passed. In the meantime @bitpwner has probably become a Ruby guru and he'll cut away half of his ruby code with his next edit ... [Here](http://jsfiddle.net/mpzayr3s/4/) is a jsfiddle with less golfed code and the graphical output of tree connections. ``` C=t=>(r=['\n',...t]).map((e,i)=> e<' '?(a=b,p=i-h,b=[]): (k=(2&a[h=b.push(n='0x'+'30909a8ff6f53a0213accccfc5'[e.charCodeAt()-65]|0)]|1&a[h-2])&n/4, x=r[p-1],y=r[++p],k>2&&x-y?r=r.map(v=>v-x?v:y,++j):0, r[i]=k>1?y:k?x:n&&++u),j=u=h=b=0)|u-j ``` **Test** ``` C("AMF\nQWK") ``` Result: 3 *A new testcase* ``` CKZNXXJEHCNHICKFHNAFZTMNXZKXSXAFHEKKFJYU YSRCHHQLXXKKXITAAHSKMXISHIGFXMVXTZZKLXIX QZWJKKNIXXUHKXCKRTXXSVHQZERHXIXNHXPKELNW HGUR KZKF GAFR RZHX EXXXC THXRR LXHI UAJH KNFX NJAK TWWHXUTXGKXFKZUTHHZPJGMAEHZVGHLEXHKY XHRHKKXHHVXYZMNHIYHKKXXKAVWKUKEXYG AXXKHHNKKMKPRFKKURCWLFXWIXUGTKKXHK USHXK VNHZI LMKY MUHQ JTKL KNXX PVCKP XEPJA QIQX KYKJ IJIIHEXKIYGKHKIALIXKRHRXYXRAVH SXSNXRHIUXHTXWYRHXHSXZKKKXIKHF KIVHCKYXKXMTXELJXNCKWYHKXVHF HXNM WWHM GKFKE KSVJH KXXP WHXW UKHX RKUN JLFKX EFKFK XFAAMXHXUFITLAWNMJYHTCWQ XPJRXIVVFTJKQFNSKMKFKIHM KYELCKHLXXHXHTVMJHNFQUFJ C("CKZNXXJEHCNHICKFHNAFZTMNXZKXSXAFHEKKFJYU\nYSRCHHQLXXKKXITAAHSKMXISHIGFXMVXTZZKLXIX\nQZWJKKNIXXUHKXCKRTXXSVHQZERHXIXNHXPKELNW\n" +" HGUR KZKF\n GAFR RZHX\n EXXXC THXRR\n" +" LXHI UAJH\n KNFX NJAK\n TWWHXUTXGKXFKZUTHHZPJGMAEHZVGHLEXHKY\n" +" XHRHKKXHHVXYZMNHIYHKKXXKAVWKUKEXYG\n AXXKHHNKKMKPRFKKURCWLFXWIXUGTKKXHK\n USHXK VNHZI\n" +" LMKY MUHQ\n JTKL KNXX\n PVCKP XEPJA\n" +" QIQX KYKJ\n IJIIHEXKIYGKHKIALIXKRHRXYXRAVH\n SXSNXRHIUXHTXWYRHXHSXZKKKXIKHF\n" +" KIVHCKYXKXMTXELJXNCKWYHKXVHF\n HXNM WWHM\n GKFKE KSVJH\n" +" KXXP WHXW\n UKHX RKUN\n JLFKX EFKFK\n" +" XFAAMXHXUFITLAWNMJYHTCWQ\n XPJRXIVVFTJKQFNSKMKFKIHM\n KYELCKHLXXHXHTVMJHNFQUFJ") ``` Result: 149 *The huge forest* ``` C("CKZNXXJEHCNHICKFHNAFZTMNXZKXSXAFHEKKFJYUZPCHRSNAUPEZKIHZJSKKPHQJYHKMXSHCXKEHCXQ\nYSRCHHQLXXKKXITAAHSKMXISHIGFXMVXTZZKLXIXVHJYKTAHSHYPCFLHSWIHHCXXRXXJNKXXVVRNSKM\n"+ "CZWJKKNIXXUHKXCKRTXXSVHQZERHXIXNHXPKELNKHXRHFKHIEPKUWKXKUPHEKKIKLLSFWUSLYEEXLSI\nKHGURVKSXXKAGXIWKCSHFNVWWHNHNIVYKKAKZKFSKHCVRHUENHFIIKNUNICHYRKYXXHTLKYHPQKWHKI\n"+ "KGAFRXJMKMJJSXCUTFAKLHHFXTIXKNHKKRHIZHXWRRXJNHXQEMKKXCNVHWFMPERJKKZLHIKIUZRKWLM\nYRXXXCXXHVISVIYTHNHKSXKRXYHXUFYYKXTHXRYIIKHEWHXVZAZHTQKJAKKHXKKVCKJHWHIIZXXZZYK\n"+ "FQLXHIHJFKSKWMTHXISAXTVIKKHTIXUAGUAJHHHHRVHXHRNWKXKUKWHVUJLKIJCWTLCHTXSYTKLTFWX\nAEKNFXUXHXHICSNCYWNEVVALHXUSACWKRNJAKLLXKVJCZHSAKYHXLHHTHFKSMCGXHFHPKTHXTRYYWXK\n"+ "HHHKHXGKFUHKSKHKKHHRHIKYNQSXMKQKIXHTXXHHIXCZIWGXKAHRXKRYXPXXXVSYIXWXVMUFYWHKINZ\nXXWWHXUTXGKXFKZUTHHZPJGMAEHZVGHLEXHKKPXHZIVKFETHKXTIVKSMHWYEKHIMIHWEHKHIIJXXJZS\n"+ "XHHXHRHKKXHHVXYZMNHIYHKKXXKAVWKUKEXYGGCHMLHFJCKXXXHEXGCZUKMHIXKVXKHZHFLCKXIPZHH\nTCHAXXKHHNKKMKPRFKKURCWLFXWIXUGTKKXHKRSYKZUXQXIEYWWWKKIXGXHALKAXXJHEXXLMNXJKHHL\n"+ "INKRHXMMXZSTAZZKGLAPKLHSPGKUINHUMXXXLTNZWENCXLKRIXHZXHHKHCSXSHHXXKCTXXXHSFHJIHI\nSHXKTXKXWPYZXKCNYSAVMICKJHKSMXKAWVNHZKGPFYPAEKEWXNKXXHKEYHAYWKIYHKXEHNJJRISLXXI\n"+ "IHZLMKYUTHWHIXEKRJIHFVHCFKLMSKIKHMUHQLYXILMHKXXXCJHZXJKKHSHXMVCHIGSICHITKIGMYYT\nUSKJTKLQYXYKKRKELMXVMLKNNNXIHPHMXKNXXYFKRHXRNNJRCQKEFKXXSWHUECTMCWVCXHLALKMSIZM\n"+ "VCKPXRCSYRVEKTCUHKVIKAXHMNMJMTKMGXEPJXYZVLKQFIIJRZHXHHSSRKHHYRHZXFHXXLUKXCAHNXX\nCGHQIQXTHRLIKKQFHQCUKZXLMVLSWHJKGKYKJMKVFIHHKYHCKAFXHMEHKJKMKWIXAYEKYKCXIMKHRXJ\n"+ "XYIJIIAHHEXKIYGKHKIALIXKRHRXYXRAVHGXTUKKKXHIIGNHXFVVHTFUKHNIKHFKRXHXXNIIXTSQHIH\nXSNXRHIUXHTXWYRHXHSXZKKKXIKHEKSHHWINIGEIXNJYSXILYIKHVYAMFNKXYWEINHHXSVFVXQRHUHW\n"+ "FRIRFCKFKIVHCKYXKXMTXELJXNCKWYHKXVTXIIHFVFZVHYSXEXZNWKWIXESHXFHKCKVPXUXCIMRHNXR\nXELHXNMKVHRHHHVKTKKPCXEXZHKPHNAWVXJKWWHMSKFFRUJVSHGXFATZSSWYXKHIHKAHXIEJXSKXFLE\n"+ "KFKECCCPWKXJTVKXHJRYVXUIFHKUHHHLMKSVJICQHKXZKNIXHKEHKNYTKKFKHUCHZFILHRHKHQKIIEJ\nMGIKXXPZQXHRHHXKXJHAGJKHIXKILXNEVWHXWWLTFWHHUMKJPZTJXXTXVPTMHHMGEPHIXRHLGQTWJCV\n"+ "UKHXXYXHAFXXSIJXHHXKLJQJIIKXIKYHSRKUNNKHTMXTCTKXGWFHSJKQSCHINSKLGSKUTXKKAWAEXAM\nLFKXWWXXSKKXPUIKTFREKIXLXNXKHHVXJKVWEFKFMYFIHGHXSHTEUJRIEAMQSXQMRJIHRETXYMHKIUX\n"+ "XFAAMXHXUFITLAWNMJYHTCWQFNXAIXKSZXIXXKRKAHWHYEAMVHNKLHKVUTAIZLVXGCHHAZTTHCELIGK\nXPJRXIVVFTJKQFNSKMKFKIHMRCHWFYVIRVXFPTKIKUKQKKMVKWIYIKRXWEVXUIHFHXASHHXVFWEWHHK\n"+ "KYELCKHLXXHXHTVMJHNFQUFJXKUHIZXFEXRZMEYZHSJXVZKMYHNCVEXKXKATRFLGHXTHXRPHXLHKSTY\nIXUUFXHWMKRIWWIRSKSCQHXSIIKRHXZNFCXXHSLXHRNHZXNWHKMQRPTHTHXXSVKHXZXICYHSXXXKXHU\n"+ "TXESLHCCEHHHHKHICSILWLHFEKVKSUECLAZHZXIKRUKWKFHXILWNSTMXXAGKWVLQNXESKXYIIXKXZRI\nHHSSHXRXKHNUWLKPXLIXFUIHXNKIKJCHTGWXLJZSLHSMZMSZTKLFAVEKIMGXJVAIKXHWUUHKHURIYMG\n"+ "IXMYFVXIWMZVNVYWKYFVXJKKEHKMNLYXNXFSRHHSANKTKTNVKNTRHPXKLRCMHLHUWKIMGWVFAPZXWXH\nRHIKVZWLHJYUKCQSSCNZFRRMXTJXQMRXCZIVPRHJMHVVXHHHLHKNKRKNXLKKREIWSTINKKXFSMPILXK\n"+ "KSFKKXGIAKXKRWHNHZMVFVFUHIKJWIHUJHHNKKSXMMUVNHEJIYCCWEHHHGJXWJJVXWIPXCKWHSXFYXI\nRWVXEHJLHANHXIVHMMQHAHHRKTMHXXXLHPCQRSHTHVXXJSXQZRHKKLSFYXKTKLKXHKHRSXLKKXUJXKJ\n"+ "TNKIMHEXKVYMVMRKTXIXJHTXYIXKMHXKKWQGFLGIFIKXKTMXSYYMTVQITPWHXHHKXEYKXHHJETJHXVK\nKXEWWAHIHVHXAUTCHZLRXKMKHKNKREKKMKHIHPXXZNFHFYIXHJXXWKIKHQWWISXZHJZKHHZXTGIIXJN\n"+ "YKZHRXXFQKHKXZHVEWSHREHKIYTFSTHLREKHFJIAVWKMKJMXHXKWKWYRTKMHIIXNCVKXRHKKEMYERRL\nKREZXUHKRQKFYKWKHEZXKWWXEHXYKLAIKYNVXFRPUNFHVJHKWZXSXKIHKYHKXFHYXXXTXIXIXGIXKHK\n"+ "ZHIKXXXRCSKVKYVHXKRJHHXWCNEXRQIKAIHHTFHWCSCZCHKXMUMKLVKXPKLIZIYKRKHIKZSHHAKCNKK\nZUHHHWKMNIXRGAVXHCXAQUKXHHEXLIRNNHLHCKRZSXHKMKWTKHKVJEUSKHXEFPHMPKHYKKUMHFLKSIJ\n"+ "KKKZXHRRNSSKXWIUCXPJUFLJSVXHMRKHXWHYURHXNKCWKIXKKWHXZMRAHHXCKIHKXXTJRHTEHUHTPZK\nHAKHLHCEGIXIIVAYWWKXCEXIHKWMKEHILYZEXKHKYVWJVKVYHFTSNIHGHCIJXKNSXXTXHSYEXNFKHSY\n"+ "KWGUHKCXWGCXKFSIPZXIZKPLHIXXYPKYHHFKYMNTXHIVMNTRYJPUKUKYUMZFTYSIIXVAXINHCMXKTEH\nGQYGHKHIKKKIKXYGCHKLAYSXPHHKFSICIKFFHSKHMAWVYKHJKNZZXYISGZMJWRRIJILHHKKHFFKARKH\n"+ "RIKUACKKMVIGHXKKMHFSXJEKXFMKSHXZXHKMHHXXSXHHLXHHEKKAKMXXECVLHEIKGWACSNKKVKARERJ\nCXMVNITXXMKCYUIHUHUXUIKYHNZYHXXLTHJATGKHKTIKKYTWXRJIXCJNHTYXIRLTKAMEHZMKRJXHAWV\n"+ "HKIMIQKMRSJNHZZYKHWWKSFIRHKHFWKKYFITXWATKKXSECSHKXHPQCNIIIWFMKUHUMXWCXYJHVSVELR\nNXUKLFAHVGGHYVTAWNIXHKXHXHXXAKKANKYIFXUTLKKTHHIKHKATJXKXETTWEKNIHQSKIXXJXXYLXXJ\n"+ "RXPCUSXZLZXVKIRLSVXHHXXKMAIXCXXQVIKIUKIXIXXJHXFRRSXXQREIWHXFKWISXYHVEKHYYXKZLMN\nXCHKWYHJRWXRLXLEAXXHKVRKLGUMWSCXINKHMNHHISNKLVKWXRWKEKPCRGZNIXSXTXHEKEEKHXTHJUH\n"+ "XGVNFTHKHNVGXGSRIPGKFXZTUKEKYKIINRKUHIKLHXRIYXRIKXSCENMZLXXHAXXWTIGJXHHWXHMIFIK\nHEVJQXTXKPFSTVKWGKXTKYRXJHVPKKNLQLPSXPIZVNIAKJJRHZHKFXIGRHKVCTVXINNHTGLIHMVYINA\n"+ "HIQHXXVZAHIHRHIHFTUWFKGKQKTAUXJSIXWHUXNXJIJIIAWUKHRLIHKVSIFSNKKHNTYCTPNWIKHHIKX\nMRLCMZXPALCTFXPHVHSVNXTJWFHKQZTZEYMALXXIXRJIKCFJYSPXKZXKUGKZLQHKUYINNUKKKLKMVLI\n"+ "VQHFXEKRVSHKKKHGWZWTLXRFWMVXHKKXWXKEHAJIXJKHXFNNGHKKLXKKKLJYKJEEHCKXTGHHICISHMF\nZXPUAXPXKXXVYAHPIJHLRCIKXLCGZXLWFJPHXAHFKSLFEHGLKHFIIHHKHHCTVAKWPXWGIQKHNILHQJW\n"+ "XHPIQLZHKVUKXCMLHSFHEKHEKREWXKYIXSZHTAHIIEUYVUHSMKTHFKMGKSLMHXKYACCXXKATLYXKXFL\nWKHIKFVFKUVXXRVEYUTCRNCXPZCCLSKTHWQXXJMHFLKXHNXCVZXHGXYAVYEXVJCHKXIKMSVAXVHNEXV\n"+ "IXIKYSSJQKKPTXFXFREKXJAKKXEJXNVXHEUJHIMHHPNRVZHXUKZPWTXCCIHXAKZUSHXRMSLIUWHIHKK\nMXIHKCKKHSIHXCKCRKATFKFSJXLRXIJNFYQISMKHSAYKZXPXNIHWSKHXYZLAVXIEXVTYHGSRXXAGQRK\n"+ "IMCXXHXSCXVXCKCTHNSHWEIRAELTJMFKCXQIIXVFSZXHXXIPCCFIZXEXPWHEGJUHWXGZJCISRJSCIPV\nHIXHUIHJXXLXXXZLNZCTJKYHNHAVIHIITLHXGEXXKUIXGNKLHHUVFJAFKHHPCJSUKXHCSIHKCXZEIFI\n"+ "UKUHWRKSJFKZNYJMSZYRTXZKWHVIXLXHRFXTZHTHHHUMYTXKRXMFAKLUMAPNGHKKJUKYIHUXQHMIUVI\nXHCKNCKTSXTZMHETTLTMYXHJKUUVXHHSHIVSZKHHWXAWMFXVVHFUCXHMXWKXHXKVLLHXZSICSACKIHC\n"+ "FXFNPHXHTHCLHKJTSLVTHKHHXHXHHKTKSUTIXKYQUHAQXXNSLKUMTKHSKKYTXHTVPGVHHMXVNLHXIRF\nWJFVVXITNRCXKHTFARSIXASVCNXJQNXIJVUHYIVNIRZXMHHFKHKMMNCUXFTEXEKEHTIHSKAKXZVTSKY\n"+ "ZJGHRTHUWMHHZXHPAIHWHUSXXKLHKYKHJSHHNKXXKRSHMKHSIHIUIXKZXSUZHKXIMMIXMXTXZZLXXIM\nEQZKRLALIEVHXYKHXIFYKXMAINSNIASMGLLYHXHRIXVWUKZHFREJCAXKXWYHXNUKTQCUKIHLWKTEKMC\n"+ "MHLXXHHYQWHTXVHCMKKHGIUFSEHNEVYSXQHHXXKHMXUXQKHZHHHSHRKWHMMEHZMIKKYYWIUNEIJUIKT\nNCHKRNSJYLLIXKXAIERXKKXIQZVHXFVIIAXHIYUGZURXFHSXKLIWESKHEXQSCUHWKALZIVEZHAFKKWA\n"+ "IKCJWNVRKMITKNYXJYKYXVXXUKWHXXJAKLXXXVKXGXKKZXMHCKKCGRLZQINVHRLNVWXTKVLTEPTXUXH\nXVCICKXXXEVTIKIHHSHCKYIJXNCJKJSLSHVXJHTHSIKUXPHWRIKMFXXMMHKHCAQWITIEWEXPFHYXXKU\n"+ "XXSHHIXHWWRKITSHSXHJKEWHXIZHSHZCHFARIXNPHYSNIKJXLQENKFCXYRWMXAPIYTZKNMXFHNIMCCS\nPAACXJMNVZZHMXXSNVSXEIINNCHLSTIXHHKYXLEHQHKHPRWIXXHRKVCXFKLHSHKGXJGKLLLWSHIISKT\n"+ "WUYXTJHXXMKJCYIXQJRNFKYHHUUKTIAYXVUUXFCYLHXWWZAUHWZIUAIGKHKIMKXXXKJZXCKKRCJAKQJ\nEVAGXIHTINSXENKWVXWCLFUVHXFPFCIFVHWXRIFZRYZKUUEMXNGAJLIFHJJIGUXFKKRIMKGFKXJYXKV\n"+ "KKRHHWKIYXWXWKLWXWKFHXLXRXRKKENMHHIQRHTTMFYTGRLSHRXIXKKUEHXXJKRIKSYLTKYJMNIUWVE") ``` Result: 714 [Answer] ### GolfScript, 150 characters I thought a GolfScript implementation is missing in this competition. While it is not a particularly fitting challenge for GolfScript it can be done quite nicely. ``` n%{.,' '80*>+}%n*:^,,{.80+'AFJMNPRS'\'CEFGNSTUVWY'3$'ACELMQRZ'3$2+'JLTUVWYZ'}%4/{2/.{~'HIKX'+\^[=]&},=},{~@;;]}%.,{:A{A{1$&},{|}/$}%.&}*^' '-,\{,-)}/ ``` Note that [edc65](https://codegolf.stackexchange.com/users/21348/edc65)`s testcase takes only a few seconds but the huge forests may run for several minutes, depending on your computer. Although the algorithm itself is not extremely slow it is only slightly optimised for speed instead of size. It copies huge lists of trees several times which is a costly operation in GolfScript. I am still trying to find a shorter representation of the encodings for the letters' connections. Also you can save 16 characters if you can guarantee that all lines have the same length. [Answer] ## C - ~~691~~ 571 Bytes Any suggestions for further golfing are welcome. ``` #include <cstdio> #include <cstring> #define L(i) strlen(t[i]) #define R(a,b,c) if(z&a&&T(b,c)&8/a){f(b,c);} #define S !!strstr( #define U return #define V if(i<0||j<0||j>=L(i) char t[80][80];int n=0,I=0,J,C=0;int T(int i,int j){V)U 0;char c[]="i";c[0]=t[i][j];U 1*S"HIJKLTUVWXYZ",c)+2*S"CEFGHIKNSTUVWXY",c)+4*S"AFHIJKMNPRSX",c)+8*S"ACEHIKLMQRXZ",c);}int f(int i,int j){V||t[i][j]<0)U 0;int z=T(i,j);t[i][j]=-1;R(1,i-1,j-1)R(2,i-1,j+1)R(4,i+1,j-1)R(8,i+1,j+1)U 1;}main(){while(scanf("%s\n",t[n++])>0){};n--;for(;I<n;I++){for(J=0;J<L(I);J++){C+=f(I,J);}}printf("%d\n",C);} ``` ## Ungolfed ``` #include <cstdio> #include <cstring> #define L(i) strlen(t[i]) char t[80][80]; int n=0; int T(int i,int j){ if(i<0||j<0||j>=L(i)){return 0;} char c[]="i"; c[0]=t[i][j]; return 1*!!strstr("HIJKLTUVWXYZ",c) + 2*!!strstr("CEFGHIKNSTUVWXY",c) + 4*!!strstr("AFHIJKMNPRSX",c) + 8*!!strstr("ACEHIKLMQRXZ",c); } int f(int i,int j){ if(i<0||j<0||j>=L(i)||t[i][j]<0){return 0;} int z=T(i,j); t[i][j]=-1; if(z&1&&T(i-1,j-1)&8){f(i-1,j-1);} if(z&2&&T(i-1,j+1)&4){f(i-1,j+1);} if(z&4&&T(i+1,j-1)&2){f(i+1,j-1);} if(z&8&&T(i+1,j+1)&1){f(i+1,j+1);} return 1; } int main(){ while(scanf("%s\n",t[n++])>0){}; n--; int c=0; for(int i=0;i<n;i++){ for(int j=0;j<L(i);j++){ c+=f(i,j); } } printf("%d\n",c);return 0; } ``` ## Results The result I get from the sample input provided in the question is 714. [Answer] ## Python - ~~437~~ 429 Since forests contain newlines, I've set the input to come from a text file instead. To run, specify the forest in a file called `forest.txt`, save the code as `forest_of_alphabets.py` and run from terminal/command line with `python forest_of_alphabets.py forest.txt` **Code:** ``` import sys N="@" g=open(sys.argv[1]).read().replace(" ",N).split() u=max(map(len,g))+1 g=[list(k)+[N]*(u-len(k))for k in g]+[[N]*u] def f(y,x,a=0): c=g[y][x] if c>N: l=[zip([-1,-1,1,1],[1,-1]*2)[i]for i in 0,1,2,3if c in"CHAAEICFFJEHGKHIHLIJITKKKULMNVMNSWQPTXRRUYXSVZZXW___X___Y"[i::4]] if a<1 or a in l:g[y][x]=N;return[f(y+j,x+i,(-j,-i))for j,i in l] return 0 s=j=0 exec"i=0;exec's+=f(j,i)>0;i+=1;'*u;j+=1;"*len(g) print s ``` Any suggestions are welcomed. Did this in a rush during my office break. Tested with both test cases in this page and those in the [alphabet tree question](https://codegolf.stackexchange.com/questions/35862/make-me-an-alphabet-tree). **Update:** Tested with the sample, which yields 714 too. Changed the while loops to the exec which is all the rage these days. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/1431/edit). Closed 3 years ago. [Improve this question](/posts/1431/edit) Find a way to make circles of a given radius using characters in a console. Please specify the font name and size. Also, please provide at least one example of the output. For example: **Input:** ``` 3 ``` **Output:** ``` ****** ** ** ** ** * * ** ** ** ** ****** ``` ...Well, something better looking than that "hand drawn" "circle" with a radius of 3. --- **Bonus question:** Ellipses. :) [Answer] ### a Bresenham circle in Scala (35) The Bresenham - algorithm has 2 major points: * works without sin/ cosin. * you only calculate ¼\*½ circle, the other points are found by mirroring. How to do it: ``` 2 1 DCBABCD GFE | EFG IJ y|----JI GJ | /JG F | / |F DE | r/ |ED C | / | C B 4 |/ | B 3 A +-------A B 4' x B 3' C C DE ED F F GJ JG IJ JI GFE EFG DCBABCD 2'1' ``` * We only calculate the numbers from A in the zenit to I. + Point I is at 45°, defined by x == y. + Ground zero is where the + is. + The A in the zenit is the point (x=0, y=r), r = radius. + To draw a closed circle we move clockwise (++x), which is to the right (x+=1) or down to the next point, (y-=1). + every point(x,y) on the circle is r away from the center. Pythagoras says, r²=x²+y². + This smells like square-root and equitations with 2 solutions, but beware! + we start at A and want to know, whether we paint next the point below or the point beneath to the right. * we calculate for both points (x²+y²) and build for both the difference to r² (which stays of course constant). + since the difference can be negative, we take the abs from it. + then we look which point is closer to the result (r²), eo ipso smaller. + depending on that we draw the right or bottom neighbor. * the so found point + 1 x, y gets mirrored + 2 -x, y to the left + 3 y, x at the diagonal + 4 -y, x from there to the left * all those points get mirrored again to the south + 1' x, -y + 2' -x, -y + 3' y, -x + 4' -y, -x done. This isn't code golf, but all those numbers at the top of the existing solutions made me think it is, so I spent useless time in golfing my solution. Therefore I added a useless number at the top too. It's 11 times Pi rounded. ``` object BresenhamCircle extends App { var count = 0 val r = args(0).toInt // ratio > 1 means expansion in horizontal direction val ratio = args(1).toInt val field = ((0 to 2 * r).map (i=> (0 to 2 * r * ratio).map (j=> ' ').toArray)).toArray def square (x: Int, y: Int): Int = x * x + y * y def setPoint (x: Int, y: Int) { field (x)(y*ratio) = "Bresenham"(count) field (y)(x*ratio) = "Bresenham"(count) } def points (x: Int, y: Int) { setPoint (r + x, r + y) setPoint (r - x, r + y) setPoint (r + x, r - y) setPoint (r - x, r - y) } def bresenwalk () { var x = 0; var y = r; val rxr = r * r points (x, y); do { val (dx, dy) = { if (math.abs (rxr - square ((x+1), y)) < math.abs (rxr - square (x, (y-1)))) (1, 0) else (0, -1) } count = (count + 1) % "Bresenham".length x += dx y += dy points (x, y) }while ((x <= y)) } bresenwalk () println (field.map (_.mkString ("")).mkString ("\n")) } ``` The font-question is decided by sites webserver and your browser settings. Now, that I'm looking it is ``` 'Droid Sans Mono',Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif ``` Font-size is 12px. Pretty useless information, if you ask me, but who does? Bonus: ellipses and sample output: The invocation is ``` scala BresenhamCircle SIZE RATIO ``` for example ``` scala BresenhamCircle 10 2 s e r B r e s h n e e n h e m a a m e e r r e m m h a a h n n s e e s e e r r B B r r e e s e e s n n h a a h m m e r r e e m a a m e h n e e n h s e r B r e s A ratio of 2 will print a circular shape for most fonts which happen to be about twice as tall than wide. To compensate for that, we widen by 2. # As smaller value than 2 only 1 is available: scala BresenhamCircle 6 1 erBre aes sea ah ha e e es se r r B B r r es se e e ah ha aes sea erBre # widening it has more freedom: scala BresenhamCircle 12 5 s e r B r e s a h n e e n h a B m m B e r r e e s s e B r r B a m m a h h n n s e e s e e r r B B r r e e s e e s n n h h a m m a B r r B e s s e e r r e B m m B a h n e e n h a s e r B r e s ``` I restricted the ratio parameter for Int to keep it simple, but it can easily be widened to allow floats. [Answer] ## Javascript (360) ``` function c(r){var f=1.83;var e=2*Math.PI/(r*r*r*r*r);var s=r*2+1;var g=Array(s);for(var i=0;i<s;i++){g[i]=Array(Math.round(s*f))};for(var i=0;i<=2*Math.PI;i+=e) {var x=Math.round(f*r*Math.cos(i)+f*r);var y=Math.round(r*Math.sin(i))+r;g[y][x]=1;}for(var j=0;j<g.length;j++){for(var i=0;i<g[j].length;i++)document.write((g[j][i]==1)?'*':' ');document.writeln()}} ``` <http://jsfiddle.net/YssSb/3/> (`f` is a correction factor for the line-height / font-width ratio. If you use a square font setting, i.e., set line-height = font-size, you can set f=1 and get "square" circles. Or set `f` arbitrarily for ellipses.) Output for 3 (interestingly enough, accidentally exactly the same shape as OP), 5, 15: ``` ****** ** ** ** ** * * ** ** ** ** ****** ********* *** **** *** ** ** ** * * * * * * ** ** *** ** *** **** ********* *************** ****** ****** **** ***** *** *** *** *** *** *** ** ** ** ** ** ** ** ** ** ** * * ** ** * * * * * * * * * * ** ** * * ** ** ** ** ** ** ** ** ** ** *** *** *** *** *** *** **** ***** ****** ****** *************** ``` [Answer] ## Python (172) 172 chars including the two mandatory newlines. Uses the Bresenham algorithm for conic curves (no divisions or multiplications); it only outputs circles for square fonts, but should be exempt from staircase effects (*ie.* always has the same width). ``` y=input();t=[y*[' ']for x in range(y)];x=0;y-=1;p=3-2*y while x<=y:t[x][y]=t[y][x]='*';n,y=((x-y+1,y-1),(x,y))[p<0];p+=4*n+6;x+=1 for s in t[::-1]+t:print"".join(s[::-1]+s) ``` Not very pretty, but well, I thought I'd give it a shot. ``` **** * * * * * * * * * * * * **** ******** *** *** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *** *** ******** ``` **Edit**: typo, replaced *addition* with *division*. [Answer] ## Perl (92) I went for the “bonus question” and made it exploit the character aspect ratio to draw ellipses :) ``` ($w)=@ARGV;for$x(-$w..$w){$p.=abs($x*$x+$_*$_-$w*$w)<$w?'*':$"for(-$w..$w);$p.=$/;}print $p; ``` Example outputs: ``` >perl circle.pl 3 *** * * * * * * * * * * *** >perl circle.pl 5 ***** * * * * * * * * * * * * * * * * * * ***** >perl circle.pl 8 ***** ** ** * * * * * * * * * * * * * * * * * * * * * * * * * * ** ** ***** ``` [Answer] ## Haskell (~~112~~ 109) ``` g n=map(zipWith(?)f.repeat)f where x?y|abs(x^2+y^2-n^2)<n='*'|0<1=' ';f=[-n..n] main=interact$unlines.g.read ``` This works by checking, whether x² + y² - r² < n for all points. All points for which this is true are stars, all others are blanks. ### Examples: ``` $ echo 3 | runhaskell circ.hs *** * * * * * * * * * * *** $ echo 10 | runhaskell circ.hs ******* ** ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** ** ******* ``` See here for big example: <http://www.ideone.com/t042u> [Answer] ## Python, 180 characters This code makes circles if the font is square. It's pretty easy to modify to generate nominal ellipses if you know your font height/width ratio. ``` import math r=input() d=2*r+1 c=[' '*d]*d for a in xrange(9*d):f=math.pi*a/r/9; x=int(r+r*math.sin(f)+.5);y=int(r+r*math.cos(f)+.5);c[y]=c[y][:x]+'*'+c[y][x+1:] for s in c:print s ``` Examples: ``` 4: ***** ** ** ** ** * * * * * * ** ** ** ** ***** 7: ***** ** ** ** ** ** ** ** ** * * * * * * * * * * ** ** ** ** ** ** ** ** ***** ``` [Answer] # C, 127 Bytes, Font name: Arial Super Bold ``` #include<math.h> main(){int r=10,c=r*2+1,q=c*c,d;for(;q--;)d=hypot(r-q%c,r-q/c),printf("%c%s",d>r-4&&d<=r?42:32,q%c?"":"\n");} ``` Result: ``` ********* ************* *************** ***************** ****** ****** ***** ***** ***** ***** **** **** **** **** **** **** **** **** **** **** **** **** **** **** ***** ***** ***** ***** ****** ****** ***************** *************** ************* ********* ``` ]
[Question] [ This is a word puzzle. Your program should accept two words on the standard input. Word one is the start word. Word two is the end word. From the start word you have to reach the end word changing/add/remove one letter at a time. After each modification it must form a new valid word. Added letters are added to the beginning or end. You can remove letters from any location (but word must not fall bellow three letters in length). Note: You can not rearrange the letters to form a word. The output of the program is the sequence of words to get from the start word to the end word. Example: ``` Input: Post Shot Output: Post cost coat goat got hot shot ``` Winner: * The program must run in a reasonable time (less than a 10 seconds). * The program that can generate the shortest output sequence to the prize words. + **Zink -> Silicon** * If more than one program gets the shortest sequence then the shortest program in chars (ignoring white space). * If we still have more than one program submission date/time shall be used. Notes: * Capitalization is not relevant. * The code to build a dictionary does not count towards code cost. + Prize Words and sequence will be generated from: <http://dl.packetstormsecurity.net/Crackers/wordlists/dictionaries/websters-dictionary.gz> [Answer] ## traceroute - 10 chars ``` traceroute ``` detail ``` post#traceroute shot Type escape sequence to abort. Tracing the route to shot (1.1.4.2) 1 pot (1.1.1.2) 40 msec 68 msec 24 msec 2 hot (1.1.3.2) 16 msec 32 msec 24 msec 3 shot (1.1.4.2) 52 msec * 92 msec ``` Routers are preconfigured with OSPF enabled and arranged this way. ![enter image description here](https://i.stack.imgur.com/uEMNK.png) And yes, I need 233614 routers to fully support all the words. :-) [Answer] # PHP - ~~886~~ ~~689~~ ~~644~~ 612 Dictionary loading: ``` <?php foreach(file('websters-dictionary') as $line) { $word = strtolower(trim($line)); if (strlen($word) < 3) continue; $c[$word] = 1; } ``` Actual code (just concat both) : ``` list($d,$e)=explode(' ',strtolower(trim(`cat`)));$f=range(@a,@z);function w($a,&$g){global$c;if(isset($c[$a]))$g[]=$a;}$h[$d]=$b=@levenshtein;$i=new SplPriorityQueue;$i->insert($d,0);$j[$d]=0;$k[$d]=$b($d,$e);while($h){if(isset($c[$l=$i->extract()])){unset($h[$l],$c[$l]);if($l==$e){for(;$m=@$n[$o[]=$l];$l=$m);die(implode("\n",array_reverse($o)));}for($p=strlen($l),$g=array();$p--;){w(substr_replace($q=$l,"",$p,1),$g);foreach($f as$r){$q[$p]=$r;w($q,$g);w($r.$l,$g);w($l.$r,$g);}}foreach($g as$m){$s=$j[$l]+1;if(!isset($h[$m])||$s<$j[$m]){$n[$m]=$l;$i->insert($m,-(($k[$m]=$b($m,$e))+$j[$m]=$s));}$h[$m]=1;}}} ``` usage: ``` php puzzle.php <<< 'Zink Silicon' # or echo 'Zink Silicon'|php puzzle.php ``` Result: ``` zink pink pank pani panic pinic sinic sinico silico silicon (0.23s) ``` This should run in less than 0.5 second for 'Zink Silicon', and less than 1 second for most cases (sometimes longer when no solution exists, but it sill returns). This uses the [A\* algorithm](http://en.wikipedia.org/wiki/A-star_algorithm) with [levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) to estimate a lower bounds of the distances. Some intersting tests: * `vas arm` -> `vas bas bar barm arm` (with a word longer than both start and end) * `oxy pom` -> `oxy poxy poy pom` * `regatta gyrally` -> (none, but the script correctly terminates) * `aal presolution` -> +8 chars * `lenticulated aal` -> -9 chars * `acarology lowness` -> 46 hops * `caniniform lowness` -> 51 hops * `cauliform lowness` -> 52 hops * `overfoul lowness` -> 54 hops * `dance facia` -> some words in the path have 4 more chars than both start/end [Answer] # Python Since I couldn't golf dijkstra codes to compress to few hundreds bytes, here is ungolfed version of mine. ``` import sys, heapq, time # dijkstra algorithm from # http://code.activestate.com/recipes/119466-dijkstras-algorithm-for-shortest-paths/ def dijkstra(G, start, end): def flatten(L): while len(L) > 0: yield L[0] L = L[1] q = [(0, start, ())] visited = set() while True: (cost, v1, path) = heapq.heappop(q) if v1 not in visited: visited.add(v1) if v1 == end: return list(flatten(path))[::-1] + [v1] path = (v1, path) for (v2, cost2) in G[v1].iteritems(): if v2 not in visited: heapq.heappush(q, (cost + cost2, v2, path)) nodes = tuple(sys.argv[1:]) print "Generating connections,", current_time = time.time() words = set(x for x in open("websters-dictionary", "rb").read().lower().split() if 3 <= len(x) <= max(5, *[len(l)+1 for l in nodes])) print len(words), "nodes found" def error(): sys.exit("Unreachable Route between '%s' and '%s'" % nodes) if not all(node in words for node in nodes): error() # following codes are modified version of # http://norvig.com/spell-correct.html alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] prepends = [c+word for c in alphabet] appends = [word+c for c in alphabet] return words & set(deletes + replaces + prepends + appends) # Generate connections between nodes to pass to dijkstra algorithm G = dict((x, dict((y, 1) for y in edits(x))) for x in words) print "All connections generated, %0.2fs taken" % (time.time() - current_time) current_time = time.time() try: route = dijkstra(G, *nodes) print '\n'.join(route) print "%d hops, %0.2fs taken to search shortest path between '%s' & '%s'" % (len(route), time.time() - current_time, nodes[0], nodes[1]) except IndexError: error() ``` Tests ``` $ python codegolf-693.py post shot Generating connections, 15930 nodes found All connections generated, 2.09s taken post host hot shot 4 hops, 0.04s taken to search shortest path between 'post' & 'shot' $ python codegolf-693.py zink silicon Generating connections, 86565 nodes found All connections generated, 13.91s taken zink pink pank pani panic pinic sinic sinico silico silicon 10 hops, 0.75s taken to search shortest path between 'zink' & 'silicon' ``` Added user300's Tests ``` $ python codegolf-693.py vas arm Generating connections, 15930 nodes found All connections generated, 2.06s taken vas bas bam aam arm 5 hops, 0.07s taken to search shortest path between 'vas' & 'arm' $ python codegolf-693.py oxy pom Generating connections, 15930 nodes found All connections generated, 2.05s taken oxy poxy pox pom 4 hops, 0.01s taken to search shortest path between 'oxy' & 'pom' $ python codegolf-693.py regatta gyrally Generating connections, 86565 nodes found All connections generated, 13.95s taken Unreachable Route between 'regatta' and 'gyrally' ``` Some more ``` $ python codegolf-693.py gap shrend Generating connections, 56783 nodes found All connections generated, 8.16s taken gap rap crap craw crew screw shrew shrewd shrend 9 hops, 0.67s taken to search shortest path between 'gap' & 'shrend' $ python codegolf-693.py guester overturn Generating connections, 118828 nodes found All connections generated, 19.63s taken guester guesten gesten geste gest gast east ease erse verse verset overset oversee overseed oversend oversand overhand overhard overcard overcare overtare overture overturn 23 hops, 0.82s taken to search shortest path between 'guester' & 'overturn' ``` [Answer] ## Python, 288 characters (not counting the dictionary reading line) ``` X=set(open('websters-dictionary').read().upper().split()) (S,E)=raw_input().upper().split() G={S:0} def A(w,x): if x not in G and x in X:G[x]=w while E not in G: for w in G.copy(): for i in range(len(w)): for c in"ABCDEFGHIJKLMNOPQRSTUVWXYZ":A(w,w[:i]+c+w[i+1:]);A(w,w[:i]+w[i+1:]);A(w,c+w);A(w,w+c) s='' while E:s=E+'\n'+s;E=G[E] print s ``` for the challenge `zink` to `silicon`: ``` ZINK PINK PANK PANI PANIC PINIC SINIC SINICO SILICO SILICON ``` There are some strange words in that dictionary... ]
[Question] [ The [keitai input method](https://en.wikipedia.org/wiki/Japanese_input_method#Keitai_input) is a method for writing Japanese kana on a 12-key phone keypad. Similar to Western keypads, each kana is assigned to a key; when the key is pressed multiple times, it cycles between all kana assigned to that key. You will be using the following key-kana assignments, with this order of kana (based on [this layout](https://upload.wikimedia.org/wikipedia/en/1/1b/Keypad_on_Japanese_phone_708SC.jpg)): | Key | Kana | | --- | --- | | 1 | あいうえお | | 2 | かきくけこ | | 3 | さしすせそ | | 4 | たちつてと | | 5 | なにぬねの | | 6 | はひふへほ | | 7 | まみむめも | | 8 | やゆよ | | 9 | らりるれろ | | 0 | わをん | | \* | ゛゜小 | ### Dakuten, Handakuten, and Small Kana The `*` character (or some other non-digit character of your choice) will apply a dakuten (`゛`) or handakuten (`゜`), or make small (`小`) the kana before it. If a form can't be applied to the kana before it, it is skipped in the cycle. Kana with dakuten, handakuten, and small forms are in the table below. | Key | Kana | Dakuten | Handakuten | Small | | --- | --- | --- | --- | --- | | 1 | あいうえお | | | ぁぃぅぇぉ | | 2 | かきくけこ | がぎぐげご | | | | 3 | さしすせそ | ざじずぜぞ | | | | 4 | たちつてと | だぢづでど | | っ | | 6 | はひふへほ | ばびぶべぼ | ぱぴぷぺぽ | | | 8 | やゆよ | | | ゃゅょ | Note: `つ` is the only t-series kana to have a small form. Input `4**` gives `た` because `た` cannot be shrunk; but the input `444**` gives small `っ`. ## Input A list of strings, with each string containing a series of the same digit. ## Output The hiragana represented by the input. ## Test Cases ``` ['2','5'] => 'かな' ['222222','555555'] => 'かな' ['1','99','2','*','44444','111'] => 'ありがとう' ['4','*','2','*','22222','44444','0','999'] => 'だがことわる' ['11111','7','1111','00','33','000','4444', '***','999'] => 'おまえをしんでる' ['2','2','99','7','333'] => 'かかります' ['1','****'] => 'あ' ['4','**'] => 'た' ['444','**'] => 'っ' ['555','***********************'] => 'ぬ' ['22','*','88','*','111','55','88','*','111'] => 'ぎゅうにゅう' ['8','444','4'] => 'やつた' ['8','444','*','4'] => 'やづた' ['8','444','**','4'] => 'やった' ['6'] => 'は' ['6','*'] => 'ば' ['6','**'] => 'ぱ' ['6','***'] => 'は' ``` ## Other Rules * Input can be any reasonable method (list of strings, list of integers, a big string with delimiters, list of run-length-encoded strings, etc.) * Output can be any reasonable method (printing to STDOUT, returning a string, etc.) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! [Answer] # [JavaScript (Node.js)](https://nodejs.org), 180 bytes Expects a list of strings, where `*` sequences are concatenated with digit sequences. Returns a list of kana. ``` a=>a.map(s=>String.fromCharCode(Buffer("n *4>IN]bh")[n=+s[0]]+12321+(p=s.lastIndexOf(n),q=s.length+~p,p%=n%8?5:3)*(m=1855**n%79&3)+(n-4?p&&2*!n:q%(m+=p==2)>1?-2:p>1)+(q%m^n%7==1))) ``` [Try it online!](https://tio.run/##bVFdi9NAFH3vrxgX2sxM0tAkrU27TAouPuyLPvgYIsRu0nZpJ2mSFUEUElTELi6oIIKisIqigvrmkz9m5wf4E@pMPthEeh/uXM6cc@69M8fuXTeeRosw6dLgyNv6ZOsSy1VXbghjYt1KogWdqX4UrA7mbnTAKfDaie97EdyjAPetwxvOnfkesimRY7vnOLKmG7omw5DE6tKNk0N65N276UOKlLWAPDpL5vLDUAnbhLbNyWBsIAxXRDMHA4xpezjqGEiGtNufhJ2Ojq/Q8boNVzIJCdGRpU26@ji0NE5Zt1e3OZ8QDSG03bdbANjAlnRJkQaSowCJpRuWfpWAo1RXeYj7PHaTNH4/GvGkY576IvipaVpJz1j2jKWnLP3C0ic1XR9XmqpLpe3ljqNS/yEXvxT67Ixlm3prEZw8LBqKsifEhpFXvdITY9xw5OP8YelTlr1g6WuWcevPTV8xjF6tNcwNjcvlN/lC3OFNfRQsupQbN7as0Pd1tH@Jn9fwgfjTnVGSvzd@R6xlmrh8bvFNDaCQPGfZY/7yLP1WFDUHs3ggkQty9oilH5ujlhzcJH3aTfqPdd5kXS0n@lHHqs1@NsAK/dVEcc2h5bRUP4iuu9M5hDZwFRCcJMBBgFjgPlh6CYi8GBDgQxepx8GCQklC@2Aa0DhYeuoymEFOUAoWycUTIP39fXbx9hXPEhgD6eLdqdA8QNt/ "JavaScript (Node.js) – Try It Online") ## How? ### Interpreting the input string Given the input string \$s\$, we compute: * \$p\$: the 0-based position of the last digit in \$s\$ * \$q\$: the length of \$s\$, minus \$p\$ and minus \$1\$ ### Base code point We use a lookup Buffer and a fixed offset to get the base code point for the digit \$n\$: ``` Buffer("n *4>IN]bh")[n] + 12321 ``` [Try it online!](https://tio.run/##Fc2xDoIwFIXhnae4IQytBCLoJMKgk4sxcTQkILSIwXtNqV1In72W6Rv@k5x3a9q5U@NXJ0i9cE6SYpPQgFDCtvAcIVuNYw5LALA249vpJ6VQLETY7KvLtX6@Qv7AGmLI8l2eFX7aEc40iXSigTVYRgvaA0SLsZBU3rtWIw6pVPQ5@@sbjaiZ4bbhRWCd@wM "JavaScript (Node.js) – Try It Online") ### Length of the digit cycle The length of the digit cycle is \$5\$, except when \$n=0\$ or \$n=8\$, in which case it's \$3\$: ``` n % 8 ? 5 : 3 ``` We reduce \$p\$ by the above modulo, which gives the 0-based index in the digit cycle. ### Length of the `*` cycle For the length \$m\$ of the `*` cycle, we use the following formula: ``` 1855 ** n % 79 & 3 ``` which, with a couple of IEEE-754 approximation errors, gives: ``` [ 1, 2, 2, 2, 2, 1, 3, 1, 2, 1 ] ``` The 0-based index in the `*` cycle is \$q \bmod m\$. ### Final code point The generic formula for the final code point is: ``` base_code_point + p * m + (q % m) ``` But there are several special cases which are detailed below. ### Case \$n=4\$, \$p=2\$ For the special case where the digit \$4\$ is pressed \$3\$ times to generate the small kana っ, we need to increment \$m\$ and to add a correction offset to the final result: ``` + (n - 4 ? ... : q % (m += p == 2) > 1 ? -2 : p > 1) ``` ### Case \$n=0\$ The code points for \$n=0\$ have a specific offset (\$+2\$) when \$p>0\$: ``` + (n - 4 ? p && 2 * !n : ...) ``` ### Case \$n=1\$ or \$n=8\$ If \$n=1\$ or \$n=8\$, each pair of code points is reversed, leading to the sequence: $$x+1,x,x+3,x+2,\dots$$ In this case, we add \$(q \bmod m)\operatorname{XOR}1\$ instead of \$q \bmod m\$: ``` + (q % m ^ n % 7 == 1) ``` [Answer] # [Raku](https://raku.org/), ~~330~~ ~~295~~ ~~248~~ 240 bytes ``` *.map:{/(.)(\d)*(_)*/;uniparse 'hiragana letter '~({TR/ksth/gzdb/},{S/h/p/},'small '~*,~*)[flat ^4 Zxx($0 X~~2|3|4|6,6,1|8|{$_*9+$1%5==38},!0)][($2-1)%*]([<wa wo n>,|map((*X~ <a i u e o>),"",|'kstnhmr'.comb),<ya yu yo>][|^8,9,8][$0][$1%*])} ``` [Try it online!](https://tio.run/##bU/bUsIwEH3nK1ammKRGegVaBT5CfWCsJROkXMaWMgUGai@/jklpFUfPTHZPTs5udrdBEvbPUQq3Cxid1W7Etw@ZhrsEv82JihlRtcfDZr3lyS4AtFonfMk3HMJgvw8SQCXOXp60j91@pS0/5zOtoNmzttK2gqBdxMNQWFRaqsRbhHzfmtrwejphRYdJWZq5ldt5n/apkTt5pjDVvVOMTm80spyC3ujE97Bi3huko/rYGx45HGPYjGkuZsRYnZStIYc1HCCAeExou01zJCbZrKIEdd/jaEboMOWQHiCNx76XTx3qUsf3FF0cQzQlxXnHU2grDEZjyLzShwUorGjDIk7AQyaiqId8KmkFea9wEQ1xd10RTCaCLSGyYRiXZ5s1T01xY9GrQrfuIiGEwaVWUl0aLKtiel3HGLuuku3M5v9BZbfqfkxa6wkaYn9TMT37H82m8h/HYfUqcmUpsOvVnMtQMv4S2F/lSurXiTX5hwh2/gI "Perl 6 – Try It Online") An underscore is used as the single non-digit character. A sequence of underscores is taken to be appended to the preceding digits rather than being its own element in the input array. * `*.map: { ... }` converts each input element into a single Japanese character. * `/(.)(\d)*(_)*/` matches the given pattern against each input element. The match is assumed to always succeed. Afterwards, `$0` is the first digit, `$1` is a list of succeeding digits, and `$2` is a list of underscores. In Raku, lists are treated as numbers equal to their length when used in an arithmetic context, so `$1` can be interpreted as one less than the number of initial digits, and `$2` as the number of trailing underscores. * `[<wa wo n>,|map(...),<ya yo yu>]` constructs an array that maps digits to the list of romanized characters in the first "Kana" column given above. For example, 1 maps to the list `<a i u e o>`, 2 to the list `<ka ki ku ke ko>`, 8 to the list `<ya yu yo>`, etc. For brevity, the kana groups are generated out of order, so `[|^8,9,8]` slices the original list into the correct order. The given digit is used to look up the appropriate list of kana (`[$0]`), and the number of repetitions of the digit indexes into that list, wrapping around to the front of the list as needed (`[$1 % *]`). * A list of anonymous transformation functions is consulted. That's the list `({ TR/ksth/gzdb/ }, { S/h/p/ }, 'small ' ~ *, ~*)`. The first function transforms a kana into its dakuten form (by translating "k" to "g", "s" to "z", etc), the second one transforms it into its handakuten form (by replacing "h" with "p"), the third one makes the kana small (by prepending "small " to it), and the last one `~*` is a string-identity function that circles back to the first version of the kana. Each function except the last is only conditionally included in the list by the following array slice. For example, if the first digit is 1, only the third and fourth transformations are applicable; if it's 6, all but the third are. The appropriate function for the number of trailing underscores is called, again wrapping around back to the beginning as needed with `[($2 - 1) % *]`. * Finally the built-in `uniparse` function is called to convert the Unicode name of the character to the actual Unicode character, after prepending it with the common prefix "hiragana letter ". [Answer] # [JavaScript (Node.js)](https://nodejs.org), 229 bytes ``` x=>[...x].map(t=>String.fromCharCode(12440+~U(U(X[u=t.split`*`,t[0]],u[0]),u))) X=['854'];for(M=i=9;i;U=(x,y)=>x[~-y.length%x.length])for(Y=X[i--]=[j=i-7?5:3];j;)for(k of(Z=Y[--j]=[])+(i%7?i<4?M-49?21:213:i-5?1:321:12))Z[k-1]=++M ``` [Try it online!](https://tio.run/##fVNdi9NAFH3vrxiFJTNpkm3S1H7EaR4WX4TVh2Whu9PAhjZt0@02JU2XLOpCgoq4iwsqiKAorKKooL755I/Z@QH@hDqTJmwii/fhZnLnnDP33GHG9qE97/nuLJCnXt9ZDvAyxG2iKEpoKQf2DAa4vRX47nSoDHzvYGNk@xsMB1VN1yvl4224DTtkgQNlPpu4wZ64JwWkYlnSgmUkLRBCpQ4mQqOmC5Yx8Hy4iV3cNFxjG8NQOkK4HZJj@UiZONNhMFoL04WFOHYHd4gryxYmY@zKdbPWqlrG2Ej29oE3gLt4h8jymAEsVIbuWt10b@rmpqw3TU1taWq15co1U21V2Z@qIbRL9mXVwuXy5rLnTefexFEm3hDe3rp7R5knLt3BEewgxXdmE7vnwPVuvwzNa92@eB3d7/bXhxKbTlj@z0RCbtkgJQAIIIImSEJNsCQg0OiERl8EYEnZVhJ8P4mrQSrbbzZZ0kSWdB7sq6pqCo9p/JRGpzT6TKPHOZ4uZpzslIxbSRSbKf99Qn7B@fEZjU/yR/Ng4PrqQL6scHK1mqwqqaYoigVF1s5vGj2h8XMavaIxk/5U1OXNaJmteiJYvTR/khhiCq/zrYj8lNRxwWVWfZev6pf181ydDVm8OlLwt8LtcFuNhpiOm19TobCiPKPxIzZ5Gn1dLXIKjdWAeF6B44c0@lBsNcWIRdDHq0H/oM6LqBtpR9/ztczZj0Ixq/4sVsWcQskqKeyV3bJ7IwgJsCXgLQJgIYDb4B6YOAHwnTnAYABtpIw9dwoFARkg/6gYQFqhcEI2gfDn19nFm5csC6AFhIu3p5zzAC3/Ag "JavaScript (Node.js) – Try It Online") `0` is different from unicode-table so hardcoded [Answer] # [C (GCC)](https://gcc.gnu.org), ~~232~~ ~~228~~ 223 \* bytes * *-2 bytes thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* * *-(2+4) bytes thanks to [@c--](https://codegolf.stackexchange.com/users/112488/c)* * *-1 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` f(char**s){for(;**s;){int c=**s-48,n=~-strlen(*s)%(c&7?5:3),a=**++s-42?0:strlen(*s),k='\x06v\xa9'>>2*c&3;s+=a>0;a%=c-4|n-2?k:3;printf("\xe3%c%c",(c&8||c<1)+129,"\x91\x82\x8B\x95\x9F\xAA\xAF\xBE\x84\x89"[c]+k*n-(c-4|n-2|a-2?c%7-1?-a:a:1)-(c-4||n<2)-(c+n?-1:1));}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=tZbhitNAEMfxi2KfIizkmmwSyCbpNWkuDXegL9EUCctVj2ruaHuSo-1BgopYUdAPIn6wcBZFBfUFfBC_7os4m6QcXFNBVhcmmc5u_7-ZnV3adyt65y6ly-XqdDIw3F_Xrg8Uei8eYTxWp4PjkeKD56vTo2Qi0QB8w3H1JDg3xpPR_cNEgWWyQnfaYatjq3oMKzQN1lih2blcoQ-DZpSauw-jNPaa3a6F6Y7tj7Ug7pp-LAfUcGaJYYXDju2fjAA1UFCUHtoylSnSQd6dzegeUTVieTrMeCRKXQvsAPwW2O0o3d8Hg_fBLYg7YB7q0b42xImhVPqzGBhUbhskNOJO3CFqOTVL9izuakloEIiq_nxebceNHi_8QXyUKKo0bdyc8r2RcNrrS4E0RRbSUQsMzX2pmDnr9QPEsgXLPiNfGiip6ksnpxM-pzSlJv9U1SePowTp0hmE5pu6xeDixfgPBAKangcPTsFgDh_wJoTU4HKWP2PZc5Z9YtkTEa5T4dbYdaFrvFnk5dWksCz4r3kK-UuWL4SqJ2WZ7bJg7pqcbNuFZ1YJwfcRxnhrSrAlP1n2lOWvWPaG5ZDbR8HErGprCly7yMiu7_6i6Ajg34oeA1yWuNFy4TbXqb4XUnW26l6I6JZXDNePGthXsbtdHX3XrZzyABY5XIldBb9g-WO4gCz7UjoiebjlIefPTVL-iGUfBLt1CcDbIat_B_kD5UKQslvTi2-ignUn67uwaJ3qD3HVOtm_24F19HgIUdVvzBvlb-z6r8dv) \*: you have to encode each char in the hex string as a single byte instead of an escape code; I wasn't able to copy/paste it correctly on ATO. How to test it: run `gcc a.c && ./a.out | grep -Eva '(\b.+) \1\b'`. Outputs each testcase for which the function outputs an incorrect string. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 132 bytes ``` WS℅⁺¹²³¹⁵℅§§⪪§⪪”}∧﹪IC↗T″§×K_✳Y59G%⸿u-↷*f↨V±IFl⟲⦃⌊CψR^4ΦIhGIT↧P{$QTⅈZ?≕⌈⟧2EχPP⊖▷ζQ§⎇Z∨⁰\`⪪k>+²γ~δïwⅈV-⦃ïB.|←⁴G⭆!±W⁹✂φβQ²1”¶I⌈ι №ι⌈ι№ι* ``` [Try it online!](https://tio.run/##XU9JV8IwGLzzK@bloEktaotVFDfEDRVBcTcuoVSIhq@1pMK/r30ceE/nMutlwqFKw1iZPJ8MtYnAm5RktmtTTQMuBDqFsLxRrFRoo5R3TDbmnl/xAhfttK9JGV63TepH0zl3E6PtP8emsJhIWlnG4gIEx5KDsiupuolVD34FawHWNyQdNLBVw/YOdvewX5fUusThEY5P0Dw7xfmFpC7a6OAK15LeVQ83t3e4f3jE07OUeHl9kzRAiD4ifEgaGeghvj4lpSDESPDNXDBJTLhoqLHlLTXVo2zEtRBFxDAr4qy4rF38Lecxc5iYoZbnvu@UqlWn5HleKQjmMi//mF8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings of digits and `*`s. Explanation: ``` WS Loop over each line ”...” Compressed look-up table ⪪ ¶ Split on newlines § Indexed by ι Current string ⌈ Maximum i.e. first character I Cast to integer ⪪ Split on spaces § Indexed by № Count of ι Current string ⌈ Maximum i.e. first character ι In current string § Indexed by № Count of * Literal string `*` ι In current string ℅ Take the ASCII code ⁺ Plus ¹²³¹⁵ Literal integer `12315` ℅ Convert to Unicode Implicitly print ``` The look-up table is adjusted for the 1-indexing of the button value and number of button presses, although the number of `*`s remains 0-indexed. [Answer] # [Python 3](https://docs.python.org/3/) + [`romkan`](https://pypi.org/project/romkan/), 720 bytes ``` import romkan def f(x): s="'" for i in range(len(x)): j=x[i] if j[0].isdigit(): s+=["","","k","s","t","n","h","m","","r"][int(j[0])] if j[0]in"12345679":s+="oaiue"[len(j)%5] else:s+=[["n'","wa","wo"],["yo","ya","yu"]][int(j[0])%7][len(j)%3] else: if s[-2]in"aeiou'"and len(j)%2and s[-1]in"aeiou":s=s[:-1]+"ぁぃぅぇぉ"["aiueo".index(s[-1])] elif s[-2]in"ks"and len(j)%2:s=s[:-2]+"gz"["ks".index(s[-2])]+s[-1] elif s[-2:]=="tu"and len(j)%3:s=s[:-2]+"っ"if len(j)%3==2 else s[:-2]+"du" elif s[-2]=="h":s=s[:-2]+"hbp"[len(j)%3]+s[-1] elif s[-2]=="t"and len(j)%2:s=s[:-2]+"d"+s[-1] elif s[-2]=="y"and len(j)%2:s=s[:-2]+"ゃゅょ"["auo".index(s[-1])] return romkan.to_hiragana(s[1:]) ``` [Try it online!](https://tio.run/##fZLbbqMwEIavk6dAI1VAklbhkKPEk1hcsAISp10TcdCG3pGqqvY59tF4kOyMMSkkpFZsjecff3MgxzLfJ8K5XMIo1mLjZG7Ho8wDHcajOEk1rnGhpYHYRcZbJFAmfXTwToz7aPBYO7C5/8KzkO94bkh1lE09BjCj3yvuDHeOW@De4/7dSCn4jIvcIIBJsJbGBVi24y6Wqw1skQVJwIsIGBVwMJ8WMjZ6yyISGQOhI@1PQEcC/oxBmaBdkqMswO9keVr5LcUhioSozBl7til1EPGk0CEQoaZCbbJRtq4yluVlbIueKdRVVVcfdfVZV1919RcYULUJvHARRidDvjNVyZ00r1kvhQLaCNy9IwPlb4CNgKkE9TBb3/MgL7ocp8Opq3@Aka3iebZG/WqtHhbQrwppe@gA9r@O8D2ugQJk/kdthPDgRfnoRX3@qM@f9fmLZljcTzCN8iIVyLG2/uWY0leNDabbcukzTZ/Q4eC6XlzXlba8LBtz0tzca9C6sXzTHHeo@kxf3PpUJn0h141qobDZ4EERCKbklF63LOsm1FURbWTLbV/MJWpzm4AWKquGSeacIqlftOYKQExqcYBgq5yyzJV86gx0IUc0UPGd0x1002gayMC6G6kawXqtjKYxiej5@u/WTbN0PlQmP6tD8vLuPrv7ZyyHel6qqZP38h8 "Python 3 – Try It Online") (without `romkan` and `romkan.to_hiragana`) ]
[Question] [ [The city defines a dog as any living entity with four legs and a tail.](https://www.getyarn.io/yarn-clip/f5ee7276-d66d-480a-862f-2f0dcfa5311e) So raccoons, bears, mountain lions, mice, [these are all just different sizes of dog.](https://www.danharmonsucks.com/shows/community/quotes/season-five/basic-story/) Given an ASCII-art image of an animal, determine if that animal is a dog. ## Rules An animal is a dog if it has four legs and a tail. The foot of a leg starts with one of `\` (backslash), `|` (pipe), or `/` (slash), has one or more `_` in between, and another `\`, `|`, or `/`. Each foot will hit the last line of the string. The feet may not share a common border. ``` \ \ | / / | | / | | / / <-- These are all just |_| |___| |_____| |_____| |___| |_| different sizes of leg. ``` A tail is a line coming out of the left side of the figure and touching the leftmost part of the multiline string. The tail is made up of either `-` or `=` characters. The tail must be at least one character long, and can optionally end with a `o` or `*`. ``` o--- *-- *== -- == - = o=== *- <-- These are all just different sizes of tail. ``` You can take input as a multiline string, or array of lines. Output a truthy or falsy value to determine if the figure is a dog, or any two distinct values. Truthy test cases: ``` ______/\__/\ _/ ( U U ) *--/____. ,\_ w _/ \ /| |\ |\ \ /_/ \_/|_| \_\ ``` ``` _________/\ o==/ ''> |_||_||_||_| ``` ``` /\__/\ ( o O) / m/ | | don't ask o-----| \__ | ___ \_______ //\ \ \___ ___ \ /_/ \_\ /_| \_| ``` Falsy test cases: ``` __________ _ ______/ ________ \________/o)< (_______/ \__________/ ``` ``` ____/)(\ / \o >o ( \_./ o--\ \_. / \____/ || || \/ \/ ``` ``` /\/\/\/\/\ o-/ o.o /_/_/_/_/ ``` [Answer] # [Python](https://www.python.org), 102 bytes ``` lambda x:any(re.match("[\*o]?[\-=]+",r)for r in x)*len(re.split(r"[\\|/]_+[\\|/]",x[-1]))==5 import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LU5LCoMwEN17iiGrxKqhi0IphJ6iK0eCbQ0VNEqaUoXcpBuhtHfqbZqo83sw8x5vXt9-tLdOT28l8POwKt3_VFO252sJw6HUIzVV1pb2cqMkx7grjjmmotiQxDDVGTBQaxhY3FQ6MO99U1tqPBUdL-RmQZIMebotGBNiF9Vt3xkLplrdXG9qbanyKkJgDjkHx9DRvOBhUoCTT2BRLAQPlAwSlPD095mGANyBw1CLkHslSu6k84DgHdYXCWrCGFt-mKYF_w) Takes in a list of lines. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 59 bytes ``` ^((.*¶)*[*o][-=])?(.*¶)*(.*?[\\|/]_+[\\|/])*.*$ $#4$#1 ^41$ ``` [Try it online!](https://tio.run/##TVE7bsMwDN15CgJxEUutTQTIWCdH6FB0Mh21Q4cMrYCiQBedJ0fwAXwxl6QsO9SH4iP5SNo/n7/X7495GmG6wev7dBP1UIuGaZwvdd36aXS@93Hom25w5wUQde6ZEw3hMWvnW19BtTtWuwNcjodqntEkmBDrAQNI7xrxTRY68E1DGtLiEwf8E7@FMSIlTKw7J5JkcqAUkigG2NitAMSuIyyy3580QILXnTOMaesmtxLxxRVTOb4IFzPZBbFRMUNy73xSWhGTBSZi7V7R7M54bp/zM6n/rqN1jrBOgMK3zLa611KBonuGuhglhTceWsjt7erlE2pMxFOEPLeltKTjsb40Alai/CNS0pNR0mPExGVJcqkfWyOWSfP6Bw "Retina 0.8.2 – Try It Online") Link is to test suite that splits on blank lines for convenience. Explanation: ``` ^((.*¶)*[*o][-=])?(.*¶)*(.*?[\\|/]_+[\\|/])*.*$ ``` Optionally match a tail, then match any number of legs. ``` $#4$#1 ``` Replace with the count of legs and whether a tail was matched. ``` ^41$ ``` Check for exactly four legs and a tail. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~43~~ 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ε„*oõš„-=âJÅ?}àIθ„__¬:.œε…\|/Sã'_ý¢O}à4Q* ``` Input as a list of lines. [Try it online](https://tio.run/##yy9OTMpM/V/z/9zWRw3ztPIPbz26EMjQtT28yOtwq33t4QWe53YABeLjD62xOrzBW@/oZJDKZTE1@sGHF6vHH957aJE/UJVJoNb//wpgEA8G@jEgzAUW0AeRGgoKoUCooMmlpaurD1Kip6ATE69QDpQHK4tRUNCvUaiJASGIRn2gzph4/Zr4GiAVAwA) or [verify all test cases](https://tio.run/##vVTBahRBEL33VxR92d1he@riKbjZHLzoJYp4a2giWWQQt0N2VBY6EBC/wLuYCIIo3rKI4mWGXPMR@ZG1qnu6Z3Y3IeYQq7tnqqurql9VzZSd7T0vJksnq4WsTt7Ix4eTspyrg8NiWk72oZgevC63QA7n1e@hkA9nUJSwB/v2xRjkeF59XV6cXR5/zGx9dn5CjBrVp4/q9@Oj@lP14@InSYypvm9dHn/RzlS/6nf5@Qe2oC0@rT/3TP2nOt0l7XtPsmUh55OZrL/JqZVHw2oxXoIn4wk1L@EFyM8@wDMaMBCZUsgqOQy1gbd07tU0ADpwmmcwRLLUBp1x9NKiWojWv79C2NEIIVKvt80KpJ5mtPHeWkQBjoXdQdyyl1cIzdalB1Dypj1K4uylsIrJi8lVR5WwsMRTI0bUHBBLw3GQh4h0YB2fr0BMoZkUFJDHJtx0nC4zaAf3RT9uoolu/WBy73eDfpNZ1rKwbUVIhTfKkUPUzLGGSK5CfZzjFaTIq3GNOg4yjxhs7l1TvGFs6G5YrNt11@2tu@Ma6ys9XI@hg@O2hErTFKnA3WLfxBPGTPU7ZQ@fwc18JtY@B/wXniNUd/gHjWjc1R9kVojBrvaHWF54IFpwnSoFqfM9KPQimm1HAZUr2ExKujBiaC@k3qWvRoEMI4S0hoM6Ihk19wYwPprAe1kHUkhg5Hf@Ly5os7SOSxmjEq4d/As). (NOTE: I've added a remove spaces `ðK` before the partition builtin, to speed it up significantly. So should you test a 'dog' which has a space in one of its feet (e.g. `|_ |`, the `ðK` should be removed to test it properly.) **Explanation:** Step 1: Validate the tail: ``` ε # Map over each line of the (implicit) input-list: „*o # Push string "*o" õš # Convert it to a list of characters and append an empty string: # ["*","o",""] „-= # Push string "-=" â # Get all combinations of the two with the cartesian product: # [["","-"],["","="],["*","-"],["*","="],["o","-"],["o","="]] J # Join each inner pair together to a string: # ["-","=","*-","*=","o-","o="] Å? # Check for each whether the current line starts with it }à # After the map: pop and push the maximum to check if any was truthy ``` Step 2: Validate the feet: ``` I # Push the input-list again θ # Leave just its last line „__ # Push string "__" ¬ # Push its first character (without popping): "_" : # Keep replacing all "__" with "_" until there are no "__" left .œ # Get all partitions of this string ε # Map over each partition: …\|/S # Push triplet-list ["\","|","/"] ã # Get all pairs with the cartesian power of 2: # [["\","\"],["\","|"],["\","/"],["|","\"],["|","|"],["|","/"],["/","\"],["/","|"],["/","/"]] '_ý '# Join each inner pair with "_" delimiter: # ["\_\","\_|","\_/","|_\","|_|","|_/","/_\","/_|","/_/"] ¢ # Count how many times each foot occurs in the parts O # Sum the counts of each type of foot together }à # After the map: pop and leave the maximum sum of counts 4Q # Check if this is equal to 4 ``` Step 3: Combine the checks and output: ``` * # Multiply the two checks together # (after which the result is output implicitly) ``` [Answer] # [Factor](https://factorcode.org/), ~~62~~ 101 bytes ``` [ dup R/ ^[*o]?[-=]+/m re-contains? swap "\n" split last R/ [\\|\/]_+[\\|\/]/ count-matches 4 = and ] ``` +39 bytes to disallow dogs with more than four legs. Ouch. :\ [![enter image description here](https://i.stack.imgur.com/8lTAu.gif)](https://i.stack.imgur.com/8lTAu.gif) [Answer] # [Bash](https://www.gnu.org/software/bash/), 77 bytes Though it's using core tools, so should work on other shells. Edit: 7 bytes saved because I was being brain dead about how to test in TIO. Thanks for the nudge, @Neil. Edit: just added more test cases ``` grep -Eqo ^[o*]?[=-] $1&&[ `tail -1 $1|grep -Eo "[/\\|]_+[/\\|]"|wc -l` = 4 ] ``` [Try it online!](https://tio.run/##XVRb06JIEn3nVxAbEx27U9GRIrciJmY2UBQUFFRUpGd2Ry4FIqCCFJft/e29fNPzMLEPRFUmVVmZJ8/J4Fqn34JrHUsC@zliv7JJUw63J/s5HPfva8V2lLCf2ekvEMUUyibPWe6XT1Mm@vs/2P98S6p4PLp4Pdh/fXn8@Ns/v/z8@Tf2B@7Tpy/s7@/rLWc/c6P59c9jD/ZvX@DXX7/@9m/0ff3b1zZkP@e/sz@zAvvbt/8y5FGx5JbH7K1k33H9/pH9iY0ebHh9sz/84R/NP3efPrFxmD7@tDRbZ79@/atna7sfzp@@@z7ClPE3Q6hXqt29helmrqJp5J4h3M8GPZ88VrWnJerdzFNxIWzNQlKq3rGCxakX6PFwP76D4/JYF3u/v77WB8t6M/79LU1nzm3Ha1mrlp3mpp1YHyKdi9HMtj3lLEXb9Vuv63hdTkNlSpaCX3F7xUgRBrIQ8HnAsb6pc2nLPJ77l3kspaBy1/xrcpbFfW/ubm6bq7lu29fj/Hq6Z9w8bvkHihd1Eb3ovWnzbRXKincpYqDrNlhK@4FmDI7kJ0WuaU1O0nJyooTOzvLkRRXu3O9jQVlv0X5X5L48nQbNgneCRcWTgQ/2ghA73nPnbzdnR6ET9@WZjI5pr8hhgTi5V@wynhq1VJK2de6J/a79Z7rHQJ3A8riId3fo5ULsLmVi9MQXpHfEG6esIpNLBe94zuBUFFUCnnU31lB046vdffq6qZvieu/kcrcLZ8fpMtZ5ix@mcTYTZUKJ0@RKb/rDNYgP3iXKKiHOfLlmnO1dms/9NS5ulTVx@ol2lRDcJvtbHcvYXgf5HmQZYpj0lyvFdL1wgBfcns9kW1xET6kIl4Q@h0ScUUZevWulwJtZKV67w4Z/iEk4jbf@@5LsyEQujkGVax4fbB6VEo8xgm5Z854v2gSGiKqwnbz6zEFc4sCMAaRBSgtiwxJ6gi2Y1pbazGAGnbN2N/FT6MzFvmrJhAilEslZ6aGn@DwhHqcLolSZA1l6GLAr@BpD8EIVnWrsXXk8iwnddhl3pCZcRyAP/esy2A7MqWCA4ICOfBBCF9YEUzDREg5BAigQvdbXY2lhM82uP803GvDxDI4xFjn6gjFtDwK0uzmY66ji84bgI4w16LZ9wNtdIQgrhXK3gJPRSt/LYTlT9k9LY2Ro3N31VU8N@XDIj3K1SK1N6i1pivKolQ8T2rXeUyb2I@tlrVWy91I/Qks98iQ3w0KaeD6I0NEx8TODR8bNCABWKlzKgTCRro6Zn5ul7VHFe3r5tN9BUsSGIPFv0fGR7cia0EhExFOXZkrGI35yrwCI2zDDeZ0knqEhkpOGzsHbyGCSjqIIqdDxrdNOJ8rTVUJYqroijBjR9q1tT1YyaP70g0bpw3e8ZaRHEybSMpNbxtTRKadKLy8LpfmeThXgygJw@gIBRKflB8LfndVcygC7fVwuyUPrwkc51O5wAemM6yj1R6E3XolWGn/DDvRNKZChBI/Xrx1gDrY4hvvYup7iShwEgktIycgaQRY8Xo1iXU92HbdbdQbIbQDMi6@c2g@guZZTmFg3KJUB1pCixtc3lw10JFk3rvcUh3C@eVU8aO7ckI7iWdqSRynFZQhuvibS9WJGjNVlIIlB64inq0h6KnjQOnCDC5E9l/agU3DAxMs7@k7kZDITd@VW20abcMx8C28yAuK8wYAl86JTuNsZFGgNDvfClr2hK3p3LbQFpxfjjX3LxRKyCcU5TJu3qxnQjZQbadwSxcHBWH4pvkyQjzsmdkRnhazUpGDtZvRp7iszUcPVyOLleBl1ppwT3q5BjrSj40JGHKhPSzU69G3RaP4Bu7CLPyTiANMSSEAKRIfXbjDxMBnrbHYWbCXdE2DMpg1TTSpnqqkG8CESQRyFCAjk8TELpKQ40gVBhhVvgXEP5fekB7IBaeGCCAvoKiwLA@jxSZ@lA@Y7A2moVjqlEgGTBnoDyaIGbtdq1HiEiWWoXRwBs895aeTOqIaEgPoh27Eh8t0uVwR0kpH1OBnMy@4sOIqNNVQ1142iAa6woVQowNJCuKnQY2mEIWMgUk5Qk4F85OegAkXwRhWqYAUlyNkdFK0xNy7Y43Sq3gScSwkbgso3acnIfpIsqA6IuwAXVcwQ3Gcf42VsTTM28CNQDtiAiiZw3FTurX6qGzNQQeETgkkF7TP9YMDEyoDvXKCSjHfnA0@q/MG09mOuNrSPin13kedd/dyrtHJVRPstKc5rleA6PnXnoc5APmXAwZOYj0p0Rt5hCwdQxjIUoxMPwITjsHsQvjFeUapvb1aYZOhDGjYnjxdfypRiKyUpWXXVRuALsb2cItFDpQSowZXiYwstPioZIdKZEaP1Hxjp2IQmEuA1Ri/CVOkS7pDN8wUBOnew7FHkhZz3BsGbY8DXSWBw468lX1qS27ny8bxzGHcVaP2zTZqh6TplU2Axdvaa3mVhgp3hwJ/FHdc7W//sXR46f93t9q2zLMvevFrThbqf/fVj/t9RSQao1/Zp3S9qr6oq8@1/ "Bash – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 65 bytes ``` x=>x.match(/[\\|\/]_+[\\|\/](?=.*$)|$/g)[4]</^[*o]?[-=]/m.test(x) ``` [Try it online!](https://tio.run/##LUvBDoIwDL3zFT2YsKGsHjyY6OTmDxhPFBeCAzHIFKZisn9HQF/7Xpv2vWv6StusKe82rM1Z97nsO7nrxC212YVhTOQIEzX/LyySIphxN8OCx6tki6c4MEkUhzLBm7C6tazj/cbLTN2aSovKFCxnjX48y0YzP299LhqdnvdlpQ@fOmPLhf@0@drnnPcwQU1AGulNBxyVARyHAu4FUuJoEbAgBe/hP9kIAB04GvsXxCFJCp1ywyD4Ag "JavaScript (Node.js) – Try It Online") ``` '' < true '' ≮ false undefined ≮ true '|_|' ≮ true ``` [Answer] # awk, 57 bytes ``` /^[o*]?[=-]/{t=1}END{exit t&&gsub(/[/\\|]_+[/\\|]/,0)==4} ``` [Try it online!](https://tio.run/##XVRrD6JIFv3OrzCTSc@jtnNFXkV6ezcoigpKqajozOxGHgUiovIoHtP923tx@stkPxAqp1K3Tp17zvUuRfzNuxShLA4@BoMvg6jKuutz8NHv1@UlHzSMDj4O/gVByCCr0pQLfv5l8CdX@Pn1WX7@6Rv857fHr3/8@7fPH/@AP8vP/NfpWv8zbK7loPzwISoq72f4DX7//csf/0Xf//CP4S@fP4tfv/3EXerb4Icfv5f6gfvK0Uc@oNc0HFyzQRkW5a@fBsFj4F/KwY9v@NPg53/@tRgEvww@fBiEfvz4vjNY245uG4MvX/4OvpFP34F3oSz8NheLhWY3pThaTTQ0Cpwj@NtxZ6TDx6Jw9Ui7mWksTcW1eZfVvCWWNz20ItvvbvvS28/2xX17bi@v5c6ySu58K@XRmFw3gp7UWtboTtxIxS4w@BCNbdtVj3KwXpZGUYTLbOSrIzoTzzm/VecxwkCnIj52ODRWRSqvucdz@zL3mezlzlJ4DY@KtG3NzdWpUy01bPuyn1wOt4SfhLXwQOG0uAcvdqvqdJ37iuqe7iGwZe3N5G3HEg4HypMhx7SGB3k2PDDKxkdl@GIqf2y3oagu12i7uadnZTTyqqlAvGku0E7wtqIYEve5Oa9XR6KyofNyTc7ArFUV/454pVXtLBzNCzmjdU1ukV0W52e8xcCIZ7l8IDgb9HIgdGYKnbf0LMplIMwPSU6HpxzKcMLhWJI0Cq51my/h3vS3NrfR66qt7pdbo2SbjT/ej2ahIVhCNwqTsaRQRkmVqq157i5euHNPQZKLYXJWCo6sb/Jkcl7i@zW3hqQd6hcZwXW4vRahgu2ll25BUSCEYXu6MMyWUwKC6LRCotjSNHjKd39G2bOLpDHjlEVZqHe8GmfSpdmthIcU@aNwfS5P0YYOlfvey1PdFbzVI1fDvobXzArBPUs2hS5gGqyHrzYhiI8IjDlAOsTsTm2YQUuxBaPC0qoxjKEhS2cVPsXGnG7zmg6pmKmBkmQuekrPAxJwPKVqnhBI4l2HHfGscxRPNYnkfe@y/VGK2LpJ@D0z4dILuWtfp84mMGHiHEQCBjqD6DuwpJiBiWaw8yJAnuTWZyOUpzZXbdrDZKWDEI5hH2KJZy/oabvgoc2VYL5h6lmYi2eEsQ7NuvUEu7mL4kJl/NXjFbQwtoqfjdXt09I5BSpnc3kVo7my26V7JZ/G1ip2ZyxGaVAruyFravepUPuRtIpeq0k5M/ZQM5c@6XVuIV067iRoWE/8yOHecWMKgNUcZ4onDuULMdNjNbNdprpPNx21G4ju4VyUhVIiZ2QTRRcrmUp45LBETQQkDG85AHUqrjsuo8id64imtGITcFcKmLRhKEAaNEJN6tFQfTqqDzPNUMVeI1aX@vpgRZ1@Hr1tFD/OxJ0FRjDkAj0x@VnIiMF4TX65iS9PtmykAp/dAccvEEEitdBR4UYWEzkB7LRhNqMPvfEfWVc43QnkIy6C@NwHvXIztNCFKybQVplIuwxcwbg0gHlY4xBufetahnOpEynOIKa9a0RFdAUtCA0j2jT8ZtHMQak94F5CToqzB9UlG8HQukKmdrCEGFVnY3VaQUOjZeW4T6nzJ6tXLoDuTObyXjrKa/rI5DDzwUmXVL6czICzmgRkyauJdLhItGWiCzWBK5yo4jqsBYMBARPPbui7kaPhWNpka30drPye@RpK2gtCSpjDjHuxEdzsBO5oCYR/YctesQW7ORZaA2mlcGVfUymDZMhwCqOqdPQ5NL3lehvXVCXY65@fSS8TlP2GC4lEFsiKTQbWZsye5jY3I81f9C6e9YdRYyopFewClEDfEwcSSqA4zLRg19b3Sj/vsAOb8B0RAlxNIQLZk4igX2HoYtq/s9pYsJYNV4SeTe3HupyNNVPz4B0SUeqDCAiU/jIL5Oi@Z1OK5la4Bs7ZZd9Jd3QF8tQBCabQ5FgROzDCgzGOOyw0c6SjQm3UXAJMK2jnSJF0cJpaZ/OHH1lzrQkD4LapIPfe6dMQUdDese0botzsbEHBoAld9pPBPG2OIlFtrKO8uqxUHXCO52qOPCxPxasGLZZ7GRIOAvUABe3omx9BdxRAiXKUwwIyUJIbqHplrhyw@@mUlxTIKYMVRVlJa9q7n0ZTZgDiT8AHOdd5t/F7vPStqfoGvgulgOeQswj2q9y5Fk9tZXoaqEJEMc2hfsZvBwytBITGASYreHPcCTRPH1xtPyZaxdrgvm1OyqQpnluN5Y6GWLum9@NSo7gID82xKxJQDgnw8KTmI5dI7ztsYQ@yUIF7D@IOOL8fdg8qVPNXEBvrq@VHCXpHw@aV/uBLHTFsxTSmiyZficJdqk@HQHJRJgOqcK6esYWm75f0Ehlcr9HyL40MbEIViPDqq9/9WG0ifpdM0ikFNiFYcRlyfd4tQXQnGPBl6M35fmsmZJbsNI6yP24I5yw8vX3WUdVVTaOu7lgKyVY3msSPMOl2wlHa8C1Zn4/u6WEIl81mW5NZlrXmxRpNte347x/3/0Auz0G71E/rdtJaTdO4b/8D "Bash – Try It Online") ]
[Question] [ **This question already has answers here**: [More Codington Crescent](/questions/211322/more-codington-crescent) (4 answers) Closed 3 years ago. *Let's just see how this goes* If you've ever listened to the radio program "I'm sorry, I haven't a clue", then you've probably heard of the game called "Mornington Crescent". For those who haven't, it's a game where players name random stations on the London Underground network. The first person to name "Mornington Crescent" wins the game.1 In the same sort of spirit as the classic radio game, I present to you **Codington Crescent**. ## The Challenge The winner of this challenge is the first person to post a working program that prints the exact string `Codington Crescent`. ## The Rules 1. Each player has their own program that they will add/change characters. This is termed their **running program**. **In this way, the only [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") aspect is the rules. Everyone uses their own running program. No one shares a program at all** 2. Each answer (**a turn**) has to obey source restrictions defined by previous answers. These are called **rules**. Each varient lasts for 5 **turns**. Rules are in the style of either [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'"), or limiting of language names (but not both). 3. Running programs can change languages between turns. 4. Answerers (**players**) can either add or change (but not both) as many characters of their running program per turn as they like. Alternatively, they can choose to "pass", adding no new rules, and still counting as a turn. This may be the only choice if rules conflict with each other. The turn count is still incremented and is to be posted. Pro tip: You probably might want to mark it community wiki because it doesn't add much. 5. At the end of each turn, the player declares a new rule that will span the next 5 turns. Rules must be objective, and a TIO verification program is highly recommended. Also, rules have to be able to be applied to every language (e.g. `Programs must not error using Python 3.4.2` isn't a valid rule). 6. Play continues until a running program prints the target string. ## Starting Rules As to kick off the game, the first 5 turns must follow these rules: 1. Turns may not print `Codington Crescent`. 2. Running programs must be irreducible. (Clarification, not a rule change: irreducible in this case means that the program doesn't produce the output of the whole program if characters from the whole program are removed. Ie. There does not exist a program that has the default same output that can be constructed by removing characters from the original program.) 3. Maximum program length is 20 bytes. ## Example Rules These are purely examples of what you could add as rules to the challenge. They do not apply unless someone decides to use them. * **Languages must have at least 3 characters in their name** * **The first and last letter of the running program must be a space** * **Running programs must have an even amount of bytes** * **Languages must be in the practical category on TIO** * **Running programs must not be more than 30 bytes** ## Extra Answer Chaining Rules * You cannot answer twice in a row. Someone else needs to answer before you have another go. * Languages need to be on Try It Online in order to be valid answers. 1 The original game of Mornington Crescent doesn't really have rules... It's more of an activity that looks like it's a complicated game. **Pro-tip: sort by [oldest](https://codegolf.stackexchange.com/questions/209889/codington-crescent?answertab=oldest#tab-top) for a more cohesive flow of answers** ## Answer Template ``` # [Language], turn number [your turn] <code> [Try it online link] [prev answer link] ## Rules - Rule (n turns left) - Rule (n turns left) - Rule (n turns left) ``` ``` [Answer] # [R](https://www.r-project.org/), 43 bytes, codepoint total [59^2](https://tio.run/##y8z/n6ZgZasQ8z83tSQjP0WjQqdCobg0V6G4sKhE1dDW1kAhMS9FASxmZ2hiYqL5P01DKUE7wTY5scRa3Ts/JTMvvSQ/T11b3bkotTg5Na9EXdlB3TlGqaAIKAbkKWkWFGXmlfwHAA), turn number 6 [Previous submission (turn 4)](https://codegolf.stackexchange.com/questions/209889/codington-crescent/209913#209913) *This turn: added 23 characters = 'Codington'+'Crescent'#H* ``` `+`=cat;'Kodington'+'Crescent'#@'C"pr'+'nt' ``` [Try it online!](https://tio.run/##K/r/P0E7wTY5scRa3Ts/JTMvvSQ/T11b3bkotTg5Na9EXdlB3VmpoAgoBOT8/w8A "R – Try It Online") Rules * Programs may not print Codington Crescent.(expired) * Running programs must be irreducible. (expired) * Maximum program length is 20 bytes. (expired) * Programs must have the substring C"pr (last turn) * Programs may not contain brackets of any kind. (1 turn left) * Minimum program length is 19 bytes (2 turns left) * Programs may not contain any whitespace characters (3 turns left) * The codepoint sum needs to be a perfect square that's greater than 1444. (4 turns left) * Programs may only output 'Codington Crescent' if they are irreducible AND modifications (additions OR changes) of at most 8 characters from a previously-submitted answer (5 turns left) [Answer] # [R](https://www.r-project.org/), 158 bytes, codepoint total [105^2](https://tio.run/##RcrRCoIwGEDhV7G/iznMcGUSjEFkSRShUN7Ygk0Ti0hFJ9HTL6WLLs/Habr0o7VRG0Wu2mnbvbSWDIQlWCYVRYfq9igLVZXIQn6Tt1leKjReIR9oygDXTe@9AH0ySKLtPtzFUThKTsF5E4QxXAQnC48Td36XnHgzYUrMmLu8UjHgYK4wxX8Y4DfC2k5gAtJ@c9fhxJn3cQSMvw), turn number 9 [Previous submission (turn 6)](https://codegolf.stackexchange.com/questions/209889/codington-crescent/209918#209918) *This turn: added 115 characters: 'a=";b=")";k="ZPEJOHUPO!ZSFTDFOU"[`\156\143ha\162`(a)==48];`\143a\164`(`\143ha\162\164\162`("B-Z","a-w\40\103","M"))'* ``` a="`+`=cat;'Kodington'+'Crescent'#@'C";b=")pr'+'nt'";k="ZPEJOHUPO!ZSFTDFOU"[`\156\143ha\162`(a)==48];`\143a\164`(`\143ha\162\164\162`("B-Z","a-w\40\103","M")) ``` [Try it online!](https://tio.run/##RcrRCoIwFIDhZ@l0MYcJLpcEYxBZEkUolDe24CyTimCGDXr8Nemiy//j753TEjBE2WgryK67PszNdoaEJOvbd9MaS8YLkoG4SKCv3rsXEE8JdbneFpuqLEb1IT@u8qKCEyo2SxXjyV0rlk4x0FRKPj8LHHAwjgH@hwF@IyyjGiago4/isWJx4mMPlDr3BQ "R – Try It Online") Comments: *pppery*'s rule (turn 8) forbidding programs to output any of their own characters has rather scuppered any chance of me winning this turn, or even next turn, since my previous program (from turn 6) was packed-full of now-forbidden characters, and I'm not allowed to modify my code (to get rid of them) in the same turn as adding to it (to implement a new 'print X without X' approach). So, for this turn, I'm trying to (1) begin the first half of building-up my program under the current rules, which will need continuing on a subsequent turn before being ready to win, and (2) add a rule to stop the other current contestants. *Razetime*, *petStorm* and *Szewczyk* all already need more than >8 characters of changes to their current programs before they can win. *pppery* currently has a program that requires only 2 characters to be changed to print `Codington Crescent`, leaving 6 characters free to comply with the perfect-square-codepoint rule, which is probably enough. However, the approach of adding `+25` to all the printed characters means that the (space) character is encoded by a non-printable byte. Moreover, if the `+25` is changed, then >8 other characters would need to be changed to get `Codington Crescent` again. So I think (hope) that simply restricting code to printable ASCII is sufficient to block this program (at least for now). Rules: * Programs may not contain any whitespace characters (last turn) * The codepoint sum needs to be a perfect square that's greater than 1444. (1 turn left) * Programs may only output 'Codington Crescent' if they are irreducible AND modifications (additions OR changes) of at most 8 characters from a previously-submitted answer (2 turns left) * Programs may not output any characters contained in their source code (4 turns left) * Programs may not contain any bytes corresponding to non-printable ASCII characters (that is, <32 or >126) (5 turns left) [Answer] # [Io](http://iolanguage.org/), turn number 1 ``` "MoC"print ``` [Try it online!](https://tio.run/##y8z//1/JN99ZqaAoM6/k/38A) [prev answer link](https://codegolf.stackexchange.com/q/209889/96495) ## Rules * Turns may not print Codington Crescent. (1 turns left) * Running programs must be irreducible. (1 turns left) * Maximum program length is 20 bytes. (1 turns left) * Your answer has to include the substring `C"pr`. [Online Verifier](https://tio.run/##y8z/n6ZgZasQ8z83tSQjP0UjUydTITk/ryQxM684OLVQQ8k5RqmgSElT83@ahlKMkm8@mJ@ZV6KkqQCmc/L@AwA) (2 turns left) [Answer] # [///](https://esolangs.org/wiki////), Turn number 2 ``` C"prodington ``` **Edit:** Changed the porgram to fit the guidelines on irreducibility, [discussed here](https://chat.stackexchange.com/transcript/message/55310824#55310824). Rules have not changed. [Try it online!](https://tio.run/##K85JLM5ILf7/31mpoCg/JTMvvSQ/T@H/fwA "/// – Try It Online") ## Rules * Programs may not print Codington Crescent.(3 turns left) * Running programs must be irreducible. (3 turns left) * Programs must have the substring `C"pr` (4 turns left) * Maximum program length is 20 bytes. (3 turns left) * Programs may not contain brackets of any kind. (5 turns left) [Answer] # [str](https://github.com/ConorOBrien-Foxx/str), 25 bytes, turn number 8 ``` `*VKPUN\VU*YLZJLU\`25+p; ``` Note the invisible character with code point 7 between between `VU` and `*Y` Rules * Programs may not contain brackets of any kind. (expired) * Minimum program length is 19 bytes (last turn) * Programs may not contain any whitespace characters (1 turn left) * The codepoint sum needs to be a perfect square that's greater than 1444. (2 turns left) * Programs may only output 'Codington Crescent' if they are irreducible AND modifications (additions OR changes) of at most 8 characters from a previously-submitted answer (3 turns left) * Programs may not output any characters contained in their source code (5 turns left) [Try it online!](https://tio.run/##Ky4p@v8/QSvMOyDULyYslF0r0ifKyyc0JsHIVLvA@v9/AA) [Answer] # [R](https://www.r-project.org/), 19 bytes, turn number 4 ``` `+`=cat;'C"pr'+'nt' ``` [Try it online!](https://tio.run/##K/r/P0E7wTY5scRa3VmpoEhdWz2vRP3/fwA "R – Try It Online") Rules * Programs may not print Codington Crescent.(1 turns left) * Running programs must be irreducible. (1 turns left) * Maximum program length is 20 bytes. (1 turns left) * Programs must have the substring C"pr (2 turns left) * Programs may not contain brackets of any kind. (3 turns left) * Minimum program length is 19 bytes (4 turns left) * Programs may not contain any whitespace characters (5 turns left) [Answer] # [Io](http://iolanguage.org/), turn number 3 ``` "idoC"print ``` ## Original submission: [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 19 bytes, turn 3 **NOTE: invalidated per [(transcript)](https://chat.stackexchange.com/transcript/message/55310824#55310824)** ``` "nidoC"4k,@@@@@C"pr ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/XykvMyXfWckkW8cBBJyVCor@/wcA "Befunge-98 (FBBI) – Try It Online") # Rules * Programs may not print Codington Crescent.(2 turns left) * Running programs must be irreducible. (2 turns left) * Programs must have the substring `C"pr` (3 turns left) * Maximum program length is 20 bytes. (2 turns left) * Programs may not contain brackets of any kind. (4 turns left) * Minimum program length is 19 bytes (5 turns left) [Answer] # [Io](http://iolanguage.org/), 19 bytes, turn number 5 ``` "Codin34:::;C"print ``` [Try it online!](https://tio.run/##y8z//1/JOT8lM8/YxMrKytpZqaAoM6/k/38A "Io – Try It Online") [Prev answer](https://codegolf.stackexchange.com/a/209913/96495) ## Rules * Programs may not print Codington Crescent.(1 turns left) * Running programs must be irreducible. (1 turns left) * Maximum program length is 20 bytes. (1 turns left) * Programs must have the substring `C"pr` (2 turns left) * Programs may not contain brackets of any kind. (3 turns left) * Minimum program length is 19 bytes (4 turns left) * Programs may not contain any whitespace characters (5 turns left) * The codepoint sum needs to be a perfect square that's greater than 1444. (6 turns left) [Verifier](https://tio.run/##y8z/n6ZgZasQ8z83tSQjP0WjQqdCobg0V6G4sKhE1dDW1kAhMS9FASxmZ2hiYqL5P01DKUbJOT8lM8/YxMrKyto5RqmgKDOvREkTTP0HAA) [Answer] # [///](https://esolangs.org/wiki////), Turn number 7, [FARKLE](https://chat.stackexchange.com/transcript/message/55319944#55319944) ``` C"prodington ``` This is a passed move. No change. [Try it online!](https://tio.run/##K85JLM5ILf7/31mpoCg/JTMvvSQ/T@H/fwA "/// – Try It Online") ## Rules * Programs must have the substring C"pr (expired) * Programs may not contain brackets of any kind. (last turn) * Minimum program length is 19 bytes (1 turns left) * Programs may not contain any whitespace characters (2 turns left) * The codepoint sum needs to be a perfect square that's greater than 1444. (3 turns left) * Programs may only output 'Codington Crescent' if they are irreducible AND modifications (additions OR changes) of at most 8 characters from a previously-submitted answer (4 turns left) ]
[Question] [ This question is a sequel to [this one](https://codegolf.stackexchange.com/questions/205214/remove-loops-from-a-walk), working in the opposite direction. For a reminder of terminology, the letters `L`, `R`, `U`, and `D` represent one-unit movement of a robot on the coordinate plane in the directions left, right, up, and down respectively. Given a positive even integer `n`, generate and print *all* sequences of `L`, `R`, `U`, and `D` of length `n` that result in a closed loop that does not intersect itself. In other words, when the robot follows the instructions in the sequence of letters, it must visit a new cell with every movement until it completes the loop and returns to the original cell. Any of the generally accepted output formats for arrays and strings are allowed. The elements printed must be in alphabetical order. It can be assumed that the input is always a positive even integer. ``` Test cases 2 -> {"DU", "LR", "RL", "UD"} 4 -> {"DLUR", "DRUL", "LDRU", "LURD", "RDLU", "RULD", "ULDR", "URDL"} 6 -> {"DDLUUR", "DDRUUL", "DLLURR", "DLUURD", "DRRULL", "DRUULD", "LDDRUU", "LDRRUL", "LLDRRU", "LLURRD", "LURRDL", "LUURDD", "RDDLUU", "RDLLUR", "RRDLLU", "RRULLD", "RULLDR", "RUULDD", "ULDDRU", "ULLDRR", "URDDLU", "URRDLL", "UULDDR", "UURDDL"} ``` This is a standard code golf challenge, where the shortest answer wins. Standard rules apply. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 39 bytes ``` {∧'LURD'⊇⍨m⌿⍨(⍲∘⍧=⊢/)⍤1+\0J1*m←⍉4⊤⍳4*⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6sfdSxX9wkNclF/1NX@qHdF7qOe/UBK41HvpkcdMx71Lrd91LVIX/NR7xJD7RgDL0OtXKC2R72dJo@6ljzq3Wyi9ah3a@3/NLBg36Ou5kPrjR@1TQSaHxzkDCRDPDyD/6cpGHGlKZgAsRkA "APL (Dyalog Extended) – Try It Online") The output is a matrix of characters, one path on a line. ### How it works ``` {∧'LURD'⊇⍨m⌿⍨(⍲∘⍧=⊢/)⍤1+\0J1*m←⍉4⊤⍳4*⍵} ⍝ Input ⍵←n m←⍉4⊤⍳4*⍵ ⍝ A matrix of all length-n combinations of 0..3 ⍳4*⍵ ⍝ 0..4^n-1 4⊤ ⍝ Convert each to base 4 (each goes to a column) m←⍉ ⍝ Transpose and assign to m ∧'LURD'⊇⍨m⌿⍨(⍲∘⍧=⊢/)⍤1+\0J1*m 0J1*m ⍝ Power of i (directions on complex plane) +\ ⍝ Cumulative sum; the path of the robot ( )⍤1 ⍝ Test each row: ⊢/ ⍝ the last number (real+imag is always even) = ⍝ equals ⍲∘⍧ ⍝ NAND of the nub-sieve ⍝ (0 if all numbers are unique, 1 otherwise) ⍝ The condition is satisfied only if both are 0 m⌿⍨ ⍝ Extract the rows that satisfy the above 'LURD'⊇⍨ ⍝ Index each number into the string 'LURD' ∧ ⍝ Ascending sort ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~119 106~~ 104 bytes ``` def f(n,s="",p=0,*v): if p==n<1:print s for d in"DLRU":p in v or 0<n<f(n-1,s+d,p+1j**(ord(d)%15),p,*v) ``` [Try it online!](https://tio.run/##FcyxCsMgEIDhPU9xCAU1F4iFdhDdOnYK9A2uUjuch4ZAnt7a7ecfPjn3T@Fr7/ROkDRji0qhxBXtYfwEOYHEyMF5qZl3aBOkUoEgs3o8t5fyMhIOGHMNHAaxOGwzoczua60ulTSZi7sZlL/Zk76b/gM "Python 2 – Try It Online") --- Same idea in Python 3: # [Python 3](https://docs.python.org/3/), ~~102~~ 100 bytes *-2 bytes thanks to @ovs!* ``` def f(n,s="",p=0,*v):p==n<1==print(s);p in v or[f(n-1,s+d,p+1j**(ord(d)%15),p,*v)for d in"DLRU"if n] ``` [Try it online!](https://tio.run/##FcuxCsIwEADQXzkCQpJewSA6WG/r6CQ4idt5GIfLkZSCXx/r/p59l3fRQ@/8EhCv2Mg5NNpjXMPZiPSSiKxmXXwLk0FWWKHUx2bHhG1gtCF9YvSlsuewS8eA9s9SKvDG3Xy93V0W0GcXfwr9Bw "Python 3 – Try It Online") --- A recursive function that prints the results to `STDOUT`. Keep track of `s, p, v` which are the current sequence, the current position (as a complex number), and the list of visited positions respectively. The sequence is printed when `n == 0` and the position is back to `0`, aka `p==n<1`. Otherwise, if there is still moves and no self-intersection (`n > 0 and p not in v`), the function tries to move the current position in 4 directions, and recurs. Given the character `d` that is one of the 4 character `D, L, R, U`, the direction is determined as ``` 1j ** (ord(d) % 15) ``` since ``` d ord(d) ord(d)%15 1j**... D 68 8 1 L 76 1 1j R 82 7 -1j U 85 10 -1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 21 bytes ``` fS=oḟȯE½M#₁Q`π₁ "RULD ``` [Try it online!](https://tio.run/##yygtzv7/Py3YNv/hjvkn1rse2uur/KipMTDhfAOQ4lIKCvVx@f//vxkA "Husk – Try It Online") # Explanation A string over `RULD` encodes a self-avoiding loop if and only if the only contiguous substring with an equal number of R and L, and of U and D, is the entire string. I loop over all strings of the given length and check this condition by brute force. ``` fS=oḟȯE½M#₁Q`π₁ Implicit input n `π₁ Length-n words over string "RULD" (from second line). f Keep those that satisfy this: Q List of substrings oḟ Get the first one that satisfies this: M#₁ Counts of each letter in "RULD" ½ Split in half ȯE The halves (counts of R,U vs counts of L,D) are equal S= That equals the string, which is the last substring in the list ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~99~~ 96 bytes *-3 bytes thanks to [my pronoun is monicareinstate](https://codegolf.stackexchange.com/users/36445)!* ``` Sort["ULDR"~StringPart~#&/@Select[Range@4~Tuples~#,Tr[a=I^#]==0&&DuplicateFreeQ@Accumulate@a&]]& ``` [Try it online!](https://tio.run/##Dcy9CsIwFEDhVwktZJBCRYqLBK5QBMGhtnUKES7h9geaKvF2EvPqMeM5w@eQJ3LIs8U4CBW7l2edPW51m4WO/byODXoOuSyho4Us6xbXkaAK/fZe6BPyovca1fWZG6X2UtZpJ4zp4onucLZ2c9uSGlAaI2OTTIbdIEoQ30MhqkIcf6f4Bw) Pure function. Takes a number as input and returns a list of character lists as output. (I believe such a format is acceptable.) The logic is pretty simple: It takes all *n*-tuples of 1, 2, 3, 4, interprets them as powers of *i*, checks that the sequences end at 0 and contain no duplicates, and converts them to the `ULDR` format. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “ḅḍʂ»ðṗẆċⱮṚƑ¥ƇḢɗƑƇ⁸ ``` A monadic Link accepting a non negative integer which yields a list of lists of characters. **[Try it online!](https://tio.run/##AT0Awv9qZWxsef//4oCc4biF4biNyoLCu8Ow4bmX4bqGxIvisa7huZrGkcKlxofhuKLJl8aRxofigbj/w4dL//82 "Jelly – Try It Online")** ### How? Much the same as [Zgarb's Husk answer](https://codegolf.stackexchange.com/a/206026/53748)... ``` “ḅḍʂ»ðṗẆċⱮṚƑ¥ƇḢɗƑƇ⁸ - Link: integer, L “ḅḍʂ» - compressed string "URLD" ð - start a new dyadic chain, f("URLD", L) ṗ - ("URLD") Cartesian power (L) -> all length L strings using "URLD" Ƈ - keep those (s in those strings) for which: Ƒ - is invariant under?: ⁸ - use chain's left argument, "URLD", as the right argument of: ɗ - last three links as a dyad, f(s, "URLD"): Ẇ - all sublists (s) Ƈ - keep those (b in sublists(s)) for which: ¥ - last two links as a dyad, f(b, "URLD"): Ɱ - map across (for c in "URLD") with f(b, c): ċ - count Ƒ - is invariant under?: Ṛ - reverse - i.e. count('U')=count('D') and count('R')=count('L') Ḣ - head (iff the only sublist with equal counts is the string itself then this will be that same string) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~155~~ 139 bytes ``` r=input() for y in range(4**r): n=0;s=[];k='';exec'c=y%4;y/=4;s+=n,;n+=1j**(6>>c);k="DLRU"[c]+k;'*r if n==0<2>max(map(s.count,s)):print k ``` [Try it online!](https://tio.run/##Dcy7CoMwFADQ3a8IQslDaa2EDqbXqWOnQidxkKBtKl5DEsF8fep@ODaG74p1Sg4M2i0wnk2rI5EYJG7Az8ikEI43GUGolIeuVzNQqsZ91FRDPEkVLyCVLwBLhQVcf0KwW9tqfsD88Xy98073xayocBkx0/FAda/bZdjZMljmz3rdMJSe88Y6g4HMKck/ "Python 2 – Try It Online") [Answer] # perl -M5.010 -n, 189 bytes ``` $k=2*$_;@m=(D,L,R,U);y=D====y=U==&&y=R====y=L==&&!/.+(??{!($&=~y=D====$&=~y=U==&&$&=~y=R====$&=~y=L==&&y===c-length$&)})/&&say for map{sprintf("%0$k".b,$_)=~s/../'$m['."0b$&]"/geer}0..4**$_ ``` [Try it online!](https://tio.run/##RY5NC4JAGIT/isq2rqa7W2QXebGDR7sIniJEQ038RL2I6E9vswya0zPDMEybdKUlBCrgqKPQvlRAXMMzfCPQ7BFcWDVCAIDxCP7mvI@TGd0Tx5lkgjAsv@aG3/aG/j/1tg2Ah1kmdTY8EdZmjWHcR6OUNp1URe3Ut11eDylRdhwVCo0NFGqw9IxSpqLqplKFxwjfFZYlSTdzSk/6@lqI86tph7ype2FeLcoPXJj1Gw "Perl 5 – Try It Online") This iterates over the numbers from `0` to `4^$_`, where `$_` is the input number. Each number is turned into a binary format (padded out with zeros so they're all the same length (twice the size of the input)), and then `00` is replaced with `D`, `01` with `L`, `10` with `R`, and `11` with `U`. This enforces the correct order. Note that we include the number `4^$_` which will lead to a string that is "too long" (`RDDD..D0`), but will not pass the tests later on. We then print the string if 1) they are a loop (contains the same number of `U`s and `D`s, and the same number of `R`s and `L`s), and 2) no proper substring does contain a loop. Expanding the program gives us: ``` #!/opt/perl/bin/perl use 5.026; use strict; use warnings; no warnings 'syntax'; use experimental 'signatures'; my $k = 2 * $_; my @m = ("D", "L", "R", "U"); y/D// == y/U// && # Does $_ contain as many D's as U's ? y/R// == y/L// && # Does $_ contain as many R's as L's ? !/.+ # Grab a substring (??{ # Code block, result is seen as a pattern !( # Negate what follows, if true, the result is "" # and "" will always match # if false, the result is 1, # and since the string does not contain a 1, # the match will fail $& =~ y!D!! == $& =~ y!U!! && # Does the substring contain as many # D's as U's? $& =~ y!R!! == $& =~ y!L!! && # Does the substring contain as many # R's as L's? y!!!c - length ($&) # Is this a proper substring? # y!!!c is a funny way getting the # length of $_, saving 1 byte over # using length, and if the lengths # are unequal, subtracting them is # a true value )})/x && # if all conditions are met say # print the results for # do this for each map { sprintf ("%0$k" . "b", $_) # Get the binary representation =~ s/../'$m[' . "0b$&]"/geer # And replace pairs of digits # with directions; we're using a # double eval -- first to turn the # replacement part into '$m[0bXX]', # with XX the two binary digits from # match, then we eval that result to # get the right direction. } 0 .. 4 ** $_; # Range of numbers __END__ ``` [Answer] # [Python 3](https://docs.python.org/3/), 232 bytes ``` from itertools import* x,y,z={"D":1,"U":-1},{"L":-1,"R":1},() for j in product(*("DLRU",)*int(input())): n,m,s=0,0,() for c in j: if (n,m)in s:n=1e999 s+=(n,m),;n+=x.get(c,0);m+=y.get(c,0); z+=("".join(j),)*(n==m==0) print(z) ``` Brute-force approach (checks every possible string of the given length, with no optimization for performance). Can probably be golfed a lot more, but still includes several non-obvious tricks to it. The most notable is setting `n` to `1e999` (a short form for infinity) when a self-crossing path is detected, ensuring that it never goes back to zero and saving 3 bytes over the more obvious approach of `break` in the loop and moving the assignment to `z` into a `else`. [Try it online!](https://tio.run/##RY67bsMwDEV3fQXBSbTZwEa72AG3jJkC5Ascu5VRPSArQOwg3@5KXbLxnssDMqzpx7vPfZ@it2DSGJP3vwsYG3xMlXrwyps88YR9y3jF/qN98RPPZWC8ZPpiTWryEWYwDkL0t/uQdKXxdL5ckakyLmnjwj1pIuoVOLa8SMNNEaGYQzHnXIGZQOeecl56J@3YdV3GSy3/mI@ulsfhe0x64IaOtpb1nRRseQ/xMHvj9Ez5tnYiVqQhFWL5Y6N9//oD "Python 3 – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), 106 bytes Prints the paths to STDOUT. ``` f=(n,s='',p=0,o=[])=>s[n-1]?p||print(s):(o[n*n+p]^=1)&&[n,-1,1,-n].map((d,i)=>f(n,s+'DLRU'[i],p+d,[...o])) ``` [Try it online!](https://tio.run/##TcyxDoIwFIXhV@lgoJXbxhpjjKa46GYcTJyaGhoQxeBtQwmL@OwIm9NZ/vO9bGdD3lS@5d1mGEpFEYKKY/BqAU5pw1QaNHJp9r7vfVNhSwPbUqdxjok3NyVZFGkELkECRyPe1lNaQDUeywlL4sPpco11ZcAnBWghhDOMDTu9BLICsjaidM3R5k@KRKUkdxhcfRe1e9DsTBSZffCbMRKRkZvmPxidHw "JavaScript (V8) – Try It Online") ### Commented ``` f = ( // a recursive function taking: n, // n = input s = '', // s = output string p = 0, // p = position o = [] // o[] = array holding all visited positions ) => // s[n - 1] ? // if s has the requested length: p || print(s) // print it only if we're back to our starting point : // else: (o[n * n + p] ^= 1) // toggle the item in o[] at n² + p // NB: we need n² to make sure it's positive && // abort if it's now set to 0 (meaning that this // position was already visited) [n, -1, 1, -n] // list of directions (down, left, right, up) .map((d, i) => // for each direction d at position i: f( // do a recursive call: n, // pass n unchanged s + 'DLRU'[i], // append the direction character to s p + d, // add the direction to the position [...o] // pass a copy of o[] ) // end of recursive call ) // end of map() ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~60~~ 59 bytes ``` Nθ⊞υωFυ«≔Eι§⟦¹θ±¹±θ⟧⌕LURDκζ¿¬№EζΣ…ζλΣζ¿‹LιθFLURD⊞υ⁺ικ¿¬Σζ⟦ι ``` [Try it online!](https://tio.run/##PY7NCsIwEITP@hSLpw3Eg@DNk1SEgpaieBIPtcY2GBPbJP5UfPa4rdTLMsywM19eZnVuMhVCrG/eJf56FDVWbDZMvS3Rc3iQPpsa0DN4Dwdza2WhcZ3dUHKYu1ifxBP3Ew4Vh0QUmRM4YX9ZsQOHpdQnHK12m8WIw4UxihtqHcgzYGIcRsZr11U2HLb@itErVyIqTWeo7qG1G1IM2q@VsJaOLlyJktKK/A7yt8Kgp0@Vty0orc5AKCugH@0LIa0lre/lgZA@IUzD@K6@ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ⊞υω ``` Start the list of sequences off with an empty sequence. ``` Fυ« ``` Perform a breadth-first search of sequences. ``` ≔Eι§⟦¹θ±¹±θ⟧⌕LURDκζ ``` Convert the sequence into a list of directions `1`, `i`, `-1` and `-i`. As Charcoal doesn't have complex numbers, I'm simulating them using `n` instead of `i`. It's not possible for `n` of these numbers to overflow to zero (I need `n` `1`s and an `n+1`th `-n` to do that) so I'm safe. ``` ¿¬№EζΣ…ζλΣζ ``` Take the sums of the proper prefixes and check that the sum of the directions does not appear. Note that due to a Charcoal quirk the sum of `[]` is not zero, so we can allow a single zero to appear as a sum of the sequence. ``` ¿‹Lιθ ``` Is this sequence of the desired length? If not... ``` FLURD ``` Loop over each direction. ``` ⊞υ⁺ικ ``` Append the direction and push this candidate sequence to the list of sequences. ``` ¿¬Σζ ``` Did this sequence of the desired length finish back at the origin? ``` ⟦ι ``` If so then print it on its own line. [Answer] # [Swift 5/Xcode 10.3](https://developer.apple.com/swift/), ~~434~~ ~~433~~ ~~417~~ ~~399~~ ~~366~~ ~~360~~ 273 bytes ``` func g(_ a:[(Int,Int)],_ b:String)->[String]{let l=a.last!;if b.count==n{return l==(0,0) ?[b]:[]};return[(l.0,l.1-1,"D"),(l.0-1,l.1,"L"),(l.0+1,l.1,"R"),(l.0,l.1+1,"U")].flatMap{m in a[1...].contains{$0.0==m.0 && $0.1==m.1} ?[]:g(a+[(m.0,m.1)],b+m.2)}};return g([(0,0)],"") ``` [Try it online!](https://tio.run/##ZZAxa8MwFIT3/IpXEYKEZSGHkMFB6dKl0C4tnYQIcoiNQZaNLZPB@Le7z7XTod303R3o7nX3Mg@HKe/9FVxdNx31Kbz6wCA@g/4MbekLA8MSKOgFbKop@nzOGH6BLF1CLD4/4oO7BXDKCme78HQqc8jEte59UMoP7S30rUdbUcklg2edmVSb8bQYmjohuRNJnHDyQhifGd@ocPK2crTyx8ozoUa@CDMidza822aooPRgdSKEMPi9D7b03bCVQipVCQm7HSAkMyQj1jBpQW2kKXocJRyXRZXYs/FRDefrn86GE8KmcbNpcG6gv2fbM/ZXOvyXjoxN3w "Swift – Try It Online") ]
[Question] [ Unlike most languages, Python evaluates `a<b<c` as it would be done in mathematics, actually comparing the three numbers, as opposed to comparing the boolean `a<b` to `c`. The correct way to write this in C (and many others) would be `a<b && b<c`. In this challenge, your task is to expand such comparison chains of arbitrary lengths from the Python/intuitive representation, to how it would be written in other languages. # Specifications * Your program will have to handle the operators: `==, !=, <, >, <=, >=`. * The input will have comparison chains using only integers. * Don't worry about the trueness of any of the comparisons along the way, this is purely a parsing/syntactical challenge. * The input won't have any whitespace to prevent answers that trivialize parsing by splitting on spaces. * However, your output may have a single space surrounding either just the `&&`'s, or both the comparison operators and the `&&`'s, or neither, but be consistent. # Test Cases ``` Input Output --------------------------------------------------------------- 3<4<5 3<4 && 4<5 3<4<5<6<7<8<9 3<4 && 4<5 && 5<6 && 6<7 && 7<8 && 8<9 3<5==6<19 3<5 && 5==6 && 6<19 10>=5<7!=20 10>=5 && 5<7 && 7!=20 15==15==15==15==15 15==15 && 15==15 && 15==15 && 15==15 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! [Answer] # [Retina](https://github.com/m-ender/retina), ~~33~~ ~~22~~ 17 bytes *-5 bytes thanks to @MartinEnder* ``` -2`\D(\d+) $&&&$1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX9coIcZFIyZFW5NLRU1NTcXw/39jGxMbUy4waWNmY25jYWMJ5Jna2prZGFpyGRrY2ZramCvaGnEZAsVQMQA "Retina – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~16~~ 14 bytes Prints a space around each operator. ``` wJ"&&"m←C2X3ġ± ``` [Try it online!](https://tio.run/##yygtzv7/v9xLSU1NKfdR2wRnowjjIwsPbfz//7@xjYmNqY2ZjbmNhY0lAA "Husk – Try It Online") ### Explanation: ``` Implicit input, e.g "3<4<5<6" ġ± Group digits ["3","<","4","<","5","<","6"] X3 Sublists of length 3 [["3","<","4"],["<","4","<"],["4","<","5"],["<","5","<"],["5","<","6"]] C2 Cut into lists of length 2 [[["3","<","4"],["<","4","<"]],[["4","<","5"],["<","5","<"]],[["5","<","6"]]] m← Take the first element of each [["3","<","4"],["4","<","5"],["5","<","6"]] J"&&" Join with "&&" ["3","<","4","&&","4","<","5","&&","5","<","6"] w Print, separates by spaces ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~42~~ ~~47~~ 22 bytes Massively golfed thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` (\D(\d+))(?=\D) $1&&$2 ``` [Try it online!](https://tio.run/##K0otycxL/P9fI8ZFIyZFW1NTw942xkWTS8VQTU3F6P9/QwM7W1Mbc0VbIwA "Retina – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), 37 bytes ``` òͨ䫄0-9& ]«©¨ä«©¨„0-9& ]«©/±² ¦¦ ²³ ``` [Try it online!](https://tio.run/##K/v///Cmw72HVhxecmj1oRYDXUs1hVggayVUBEgji@of2nhok8KhZYeWKRzadGjz///GNiY2plxg0sbMxtzGwsYSyDO1tTWzMbTkMjSwszW1MVe0NTLgMgQKomIA "V – Try It Online") Hexdump: ``` 00000000: f2cd a8e4 ab84 302d 3926 205d aba9 a8e4 ......0-9& ].... 00000010: aba9 a884 302d 3926 205d aba9 2fb1 b220 ....0-9& ]../.. 00000020: a6a6 20b2 b3 .. .. ``` [Answer] ## Clojure, 88 bytes Update: `subs` instead of `clojure.string/join`. ``` #(subs(apply str(for[p(partition 3 2(re-seq #"(?:\d+|[^\d]+)" %))](apply str" && "p)))4) ``` [Answer] # [J](http://jsoftware.com/), ~~59~~ 46 bytes ``` 4(}.;)_2{.\3' && '&;\]</.~0+/\@,2~:/\e.&'!<=>' ``` [Try it online!](https://tio.run/##y/r/P81WT8FEo1bPWjPeqFovxlhdQU1NQV3NOibWRl@vzkBbP8ZBx6jOSj8mVU9NXdHG1k79f2pyRr5DmoOdQnJpiY@bQnFJSmaeuvp/YxsTG1MuMGljZmNuY2FjCeSZ2tqa2Rhachka2Nma2pgr2hoZcBkCBVExAA) ### How it used to work ``` (0 , }. ~:&(e.&'!<=>') }:) ``` We’re looking for operator boundaries. “Beheaded” and “curtailed” strings are turned into zeroes and ones where 0s are digits, then xored together. Prepend zero to match the length. ``` +/\ </. ] Split on boundaries. ┌──┬──┬─┬─┬─┬──┬──┐ │10│>=│5│<│7│!=│20│ └──┴──┴─┴─┴─┴──┴──┘ 3' && '&;\ Add && to infixes of 3. ┌────┬──┬──┬──┐ │ && │10│>=│5 │ ├────┼──┼──┼──┤ │ && │>=│5 │< │ ├────┼──┼──┼──┤ │ && │5 │< │7 │ ├────┼──┼──┼──┤ │ && │< │7 │!=│ ├────┼──┼──┼──┤ │ && │7 │!=│20│ └────┴──┴──┴──┘ _2{.\ Take even numbered rows. ;}., Concatenate after dropping the first box. ``` [Answer] # Charcoal, 29 bytes ``` ≔ ηFθ«¿›ι9«F›η!⁺&&η≔ωη»≔⁺ηιηι ≔ ηFθ«F∧›ι9›η!⁺&&η≔⎇›ι9ω⁺ηιηι ``` Two slightly different formulations of the same basic algorithm. The input string is iterated by character. As digits are found they are collected in a variable. When a boundary between a number and operator is found, an extra "&&" plus the variable is printed and the variable is cleared. The variable is initially initialised to a space so that the first boundary doesn't trigger the extra "&&". [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` e€ØDŒg⁸ṁṡ3m2j⁾&& ``` [Try it online!](https://tio.run/##ATMAzP9qZWxsef//ZeKCrMOYRMWSZ@KBuOG5geG5oTNtMmrigb4mJv///ycxMD49NTw3IT0yMCc "Jelly – Try It Online") Explanation: ``` e€ØDŒg⁸ṁṡ3m2j⁾&& Uses Jelly stringification, thus full program only e€ØD For each each char, 1 if it's in '0123456789', otherwise 0 Œg Split into longest runs of equal elements ⁸ṁ Reshape original input like the list we just made Reshaping will separate numbers from operators ṡ3 Get contiguous sublists of length 3 m2 Keep every second item, starting from the first This will keep every (number operator number) and remove every (operator number operator) substring j⁾&& Join with '&&' ``` [Answer] # Java 8, 46 bytes ``` s->s.replaceAll("(\\D(\\d+))(?=\\D)","$1&&$2") ``` **Explanation:** [Try it here.](https://tio.run/##jY5BawIxEIXv/oppEElQF9d2tWKiCF710mPtIc3GEo3ZZROFIvvb17HNxYsKeZCZ@ebN28mT7Beldrt83ygrvYeVNO7cAjAu6GorlYb1tQT4CJVxP6Bo/Hg2xX6NwueDDEbBGhwIaHx/5pNKlxbXF9ZSQjebJSrvMkbnAgtGeqSddjrtIWHN9N@jPH5b9IhWp8LkcMAw8d7nF0gWk/z6oA9JcQxJiaNgHXWJouSVvxH2l@ouw7PnKD7iY/7OJ0/QmRAjnj4m08FMZHz8IoaDxyya3iqu1K26uQA) ``` s-> // Method with String as both parameter and return-type s.replaceAll("(\\D(\\d+))(?=\\D)", "$1&&$2") // Replace the match of the regex // with the second String // End of method (implicit / single-line return-statement) ``` Regex explanation: ``` (\D(\d+))(?=\D) # 1) For all matches of this regex (\d+) # Capture group 2: a number (one or more digits) (\D \d+ ) # Capture group 1: anything but a number + the number # (`\D` will match the `=`, `!`, `<`, or `>`) (?=\D) # Look-ahead so everything after the match remains as is $1&&$2 # 2) Replace it with $1 # Result of capture group 1 (trailing part of the equation + the number) && # Literal "&&" $2 # Result of capture group 2 (the number) ``` Step by step example of the replacements: ``` Initial: 10>=5<7!=20 Match of first replacement: =5 Replace with: =5&&5 After first replacement: 10>=5&&5<7!=20 Match of second replacement: <7 Replace with: <7&&7 After second replacement (result): 10>=5&&5<7&&7!=20 ``` [Answer] # [Perl 5](https://www.perl.org/), 47 + 1 (-p) = 48 bytes ``` $\.=$1." && "x(!!$')while s/(\d+\D+(\d+))/$2/}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRs9WxVBPSUFNTUGpQkNRUUVdszwjMydVoVhfIyZFO8ZFG0RpauqrGOnXVv//b2hgZ2tqY65oa2TwL7@gJDM/r/i/rq@pnoGhwX/dAgA "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~60~~ ~~59~~ ~~58~~ 57 bytes ``` lambda s:re.sub(r'(\D(\d+))(?=\D)',r'\1&&\2',s) import re ``` [Try it online!](https://tio.run/##VcqxDoIwFIXhnaeoC7eNxNBqQc29uvAYXSBAJBFobuvg01fXDmf5zu@/8bVvJs3k0rtfh7EX4c7TKXwGySBdJ914VEo@yXUKKgany9IZqIIqltXvHAVPyfOyRTFLOOMFLagiB2ywxSve8sMSNagz1PWDLLYHMnXG/zQfqPQD "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 37 bytes ``` ->s{s.gsub(/\D(\d+)(?=\D)/,'\&&&\1')} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ulgvvbg0SUM/xkUjJkVbU8PeNsZFU19HPUZNTS3GUF2z9n9BaUmxQlq0urGNiY2peiwXCt/GzMbcxsLGEkXc1NbWzMYQWczQwM7W1MZc0dbIAFkUqBAVq8f@BwA "Ruby – Try It Online") [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 43 bytes ``` f=s=>s.replace(/(\W+(\d+))(?!$)/g,"$1&&$2") ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38/z/NttjWrlivKLUgJzE5VUNfIyZcWyMmRVtTU8NeUUVTP11HScVQTU3FSEnz/38A "JavaScript (SpiderMonkey) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` e€ØDnƝkṡ3m2j⁾&& ``` [Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzNc8o7NzX64c6FxrlHWo8Z9amrYxBvmKKipKTxqmMt1uB0oG/n/fzQXp5KxjYmNqZKOAjpQVgDKgDQApWHKbMxszG0sbCyRlCMrA1FANSAKqBBEAVWDKKAWsBGmtrZmNoaWaLaBjIDoBUpDNBuC1Bsa2Nma2pgr2hoZoOhQVgDLQGyDWANSA9IBNAEVQzQCdYB5ILW4WVyxAA "Jelly – Try It Online") Outputs with no spaces around the `&&`, but the Footer in the TIO link adds the spaces to make the output easier to read ## How it works ``` e€ØDnƝkṡ3m2j⁾&& - Main link. Takes a string S on the left e€ØD - Replace digits with 1, otherwise 0 Ɲ - To overlapping pairs [a,b]: n - a ≠ b k - Split S on truthy elements, grouping digits together ṡ3 - Split into overlapping lists of length 3 m2 - Take every other element j⁾&& - Join by "&&" ``` ]
[Question] [ Remember that a set is unordered without duplicates. **Definition** An *N*-uniquely additive set *S* whose length is *K* is a set such that all *N*-length subsets in *S* sum to different numbers. In other words, the sums of all the *N*-length subsets of *S* are all distinct. **Objective** Given an array/set as input and a number `N` to a function or to a full program in any reasonable format, find and return or output a truthy or falsey value (erroring for falsey is okay) denoting whether or not the input is *N*-uniquely additive. You may assume that each element only appears at most once and that each number is within your language's native datatype. If need be, you may also assume that the input is sorted. Last, you may assume that `0 < N <= K`. ## Examples Let's consider the set `S = {1, 2, 3, 5}` and `N = 2`. Here are all the sums of all unique pairs over `S` (for the unique ones are the only ones of interest for sums): ``` 1 + 2 = 3 1 + 3 = 4 1 + 5 = 6 2 + 3 = 5 2 + 5 = 7 3 + 5 = 8 ``` We can see that there are no duplicates in output, so *S* is 2-uniquely additive. --- Let's now consider the set `T = {12, 17, 44, 80, 82, 90}` and `N = 4`. Here are all the possible sums of length four: ``` 12 + 17 + 44 + 80 = 153 12 + 17 + 44 + 82 = 155 12 + 17 + 44 + 90 = 163 12 + 17 + 80 + 82 = 191 12 + 17 + 80 + 90 = 199 12 + 17 + 82 + 90 = 201 12 + 44 + 80 + 82 = 218 12 + 44 + 80 + 90 = 226 12 + 44 + 82 + 90 = 228 12 + 80 + 82 + 90 = 264 17 + 44 + 80 + 82 = 223 17 + 44 + 80 + 90 = 231 17 + 44 + 82 + 90 = 233 17 + 80 + 82 + 90 = 269 44 + 80 + 82 + 90 = 296 ``` They are all unique, and so *T* is 4-uniquely additive. ## Test Cases ``` [members], N => output [1, 4, 8], 1 => true [1, 10, 42], 1 => true ; all sets trivially satisfy N = 1 [1, 2, 3, 4], 3 => true [1, 2, 3, 4, 5], 5 => true [1, 2, 3, 5, 8], 3 => true [1, 2, 3, 4, 5], 2 => false ; 1 + 4 = 5 = 2 + 3 [-2, -1, 0, 1, 2], 3 => false ; -2 + -1 + 2 = -1 = -2 + 0 + 1 [1, 2, 3, 5, 8, 13], 3 => false ; 1 + 2 + 13 = 16 = 3 + 5 + 8 [1, 2, 4, 8, 16, 32], 3 => true [1, 2, 4, 8, 16, 32], 4 => true [1, 2, 4, 8, 16, 32], 5 => true [1, 2, 4, 8, 16, 32], 6 => true [3, 4, 7, 9, 12, 16, 18], 6 => true [3, 4, 7, 9, 12, 16, 18], 3 => false ; 3 + 4 + 12 = 19 = 3 + 7 + 9 ``` [Answer] ## Jelly, 7 bytes ``` œcS€ṢIP ``` [Try it online!](http://jelly.tryitonline.net/#code=xZNjU-KCrOG5oklQ&input=&args=WzMsIDQsIDcsIDksIDEyLCAxNiwgMThd+Mw) Returns a positive number for truthy and zero for falsey. ``` œc find combinations S€ sum each combination Ṣ sort the sums I find the difference between each pair of sums iff any sums are the same, this returns a list containing 0 P product of the elements of the resulting list ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` XN!sSdA ``` [**Try it online!**](http://matl.tryitonline.net/#code=WE4hc1NkQQ&input=WzMsIDQsIDcsIDksIDEyLCAxNiwgMThdCjY) Returns `true` (displayed as `1`) or `false` (displayed as `0`). ``` XN % Take array S and number N. Generate all combinations of elements from S % taken N at a time. Gives a 2D array where each combination is a row ! % Transpose. Each combination is now a column s % Sum of each column: gives a row array. If N=1 computes the sum of % the only row, and so gives a number S % Sort vector d % Array of consecutive differences. For a single number gives an empty array A % True if all elements of the input array are nonzero (for an empty array % it also gives true) ``` [Answer] # Matlab, 78 bytes ``` function n=f(s,n);p=perms(s);k=sum(unique(sort(p(:,1:n)),'rows')');unique(k)-k ``` This function returns a positive value (in fact `n`) for *truthy* and returns an error as a *falsey* answer (valid according to [this comment](https://codegolf.stackexchange.com/questions/81210/n-uniquely-additive-sets#comment199400_81210)) Explanation: ``` function n=f(s,n); p=perms(s); %create all permutations of the set k=sum(unique(sort(p(:,1:n)),'rows')'); %just take the first n entries of each permutation %sort those entries and %filter out all duplicates (we sorted as the order should NOT matter) %then sum each of those candidates unique(k)-k %if all those sums are distinct, unique(k) will have the same size % as k itself, and therefore we can subtract, otherwise it will throw % an error as we try to subtract vectors of different sizes ``` [Answer] ## Pyth, 8 bytes ``` {IsM.cFQ ``` [Test suite.](https://pyth.herokuapp.com/?code=%7BIsM.cFQ&test_suite=1&test_suite_input=%5B%5B1%2C+4%2C+8%5D%2C+1%5D%0A%5B%5B1%2C+10%2C+42%5D%2C+1%5D%0A%5B%5B1%2C+2%2C+3%2C+4%5D%2C+3%5D%0A%5B%5B1%2C+2%2C+3%2C+4%2C+5%5D%2C+5%5D%0A%5B%5B1%2C+2%2C+3%2C+5%2C+8%5D%2C+3%5D%0A%5B%5B1%2C+2%2C+3%2C+4%2C+5%5D%2C+2%5D%0A%5B%5B-2%2C+-1%2C+0%2C+1%2C+2%5D%2C+3%5D%0A%5B%5B1%2C+2%2C+3%2C+5%2C+8%2C+13%5D%2C+3%5D%0A%5B%5B1%2C+2%2C+4%2C+8%2C+16%2C+32%5D%2C+3%5D%0A%5B%5B1%2C+2%2C+4%2C+8%2C+16%2C+32%5D%2C+4%5D%0A%5B%5B1%2C+2%2C+4%2C+8%2C+16%2C+32%5D%2C+5%5D%0A%5B%5B1%2C+2%2C+4%2C+8%2C+16%2C+32%5D%2C+6%5D%0A%5B%5B3%2C+4%2C+7%2C+9%2C+12%2C+16%2C+18%5D%2C+6%5D%0A%5B%5B3%2C+4%2C+7%2C+9%2C+12%2C+16%2C+18%5D%2C+3%5D&debug=0) ``` Q eval input (provided as a 2-element array) .cF splat over combination sM sum each combination {I is the result invariant under { (dedup/uniq)? ``` [Answer] ## Haskell, 69 bytes ``` import Data.List n#s=(==)=<<nub$[sum x|x<-subsequences s,length x==n] ``` Usage example: `6 # [3,4,7,9,12,16,18]` -> `True`. Direct implementation of the definition: make a list of sums of all subsequences of length n and check if it equals itself with duplicates removed. [Answer] ## JavaScript (ES6), 132 bytes ``` (a,n)=>a.map(m=>{for(i=n;i--;)s[i].map(k=>s[i+1].push(m+k))},s=[...Array(n+1)].map(_=>[]),s[0]=[0])&&new Set(s[n]).size==s[n].length ``` Builds up the additive lists from 1 to n and then checks the last one for uniqueness. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes ``` :1f:+aLdL [L:I]hs.lI ``` Expects a list containing the list and then the integer as Input, and no Output, e.g. `run_from_atom(':{[L:I]hs.lI}f:+aLdL', [[1:2:3:5]:2]).`. ### Explanation * Main Predicate ``` Input = [A:I] :1f Find all ordered subsets of A of length I :+aL Apply summing to each element of that list of subsets. Call that L dL True if L minus all duplicate elements is still L ``` * Predicate 1: Find all ordered subsets of fixed length of a list ``` [L:I] Input = [L:I] hs. Unify Output with an ordered subset of L lI True if I is the length of Output ``` [Answer] # Julia, ~~46~~ 41 bytes ``` x\n=(t=map(sum,combinations(x,n)))==t∪t ``` [Try it online!](http://julia.tryitonline.net/#code=eFxuPSh0PW1hcChzdW0sY29tYmluYXRpb25zKHgsbikpKT09dOKIqnQKCmZvciAoeCwgbikgaW4gKAogICAgKFsxLCA0LCA4XSwgMSksCiAgICAoWzEsIDEwLCA0Ml0sIDEpLAogICAgKFsxLCAyLCAzLCA0XSwgMyksCiAgICAoWzEsIDIsIDMsIDQsIDVdLCA1KSwKICAgIChbMSwgMiwgMywgNSwgOF0sIDMpLAogICAgKFsxLCAyLCAzLCA0LCA1XSwgMiksCiAgICAoWy0yLCAtMSwgMCwgMSwgMl0sIDMpLAogICAgKFsxLCAyLCAzLCA1LCA4LCAxM10sIDMpLAogICAgKFsxLCAyLCA0LCA4LCAxNiwgMzJdLCAzKSwKICAgIChbMSwgMiwgNCwgOCwgMTYsIDMyXSwgNCksCiAgICAoWzEsIDIsIDQsIDgsIDE2LCAzMl0sIDUpLAogICAgKFsxLCAyLCA0LCA4LCAxNiwgMzJdLCA2KSwKICAgIChbMywgNCwgNywgOSwgMTIsIDE2LCAxOF0sIDYpLAogICAgKFszLCA0LCA3LCA5LCAxMiwgMTYsIDE4XSwgMykKKQogICAgcHJpbnRsbih4XG4pCmVuZA&input=) ### How it works This (re)defines the binary operator `\` for Array/Int arguments. `combinations(x,n)` returns all arrays of exactly **n** different elements of **x**. We map `sum` over these arrays and store the result in **t**. `t∪t` performs the set union of the array **t** with itself, which works like the longer `unique` in this case. Finally, we compare **t** with the deduplicated **t**, returning `true` if and only if all sums are different. [Answer] # Python, 89 bytes ``` from itertools import* lambda s,n,c=combinations:all(x^y for x,y in c(map(sum,c(s,n)),2)) ``` Test it on [Ideone](http://ideone.com/aqOv3P). ### How it works `c(s,n)` lists all **n**-combinations of **s**, i.e., all lists of **n** different elements of **s**. We map `sum` over the resulting lists, thus computing all possible sums of sublists of length **n**. After wards, we use `c(...,2)` to create all pairs of the resulting sums. If any two sums **x** and **y** are equal, `x^y` will return **0** and `all` will return **False**. Conversely, if all sums are unique, `x^y` will always be truthy, and `any` will return **True**. [Answer] # J, 34 bytes ``` load'stats' [:*/@~:[:+/"1(comb#){] ``` Straight-forward approach, only requires the `stats` add-on for the `comb` function. Returns `0` for false and `1` for true. As an alternative to using the `comb` builtin, there is a **38 byte** solution that generates the power set and chooses the subsets of size *n*. ``` [:*/@~:(>@{[:(</.~+/"1)2#:@i.@^#)+/@#] ``` ## Usage ``` f =: [:*/@~:[:+/"1(comb#){] 2 f 1 2 3 5 1 4 f 12 17 44 80 82 90 1 3 f _2 _1 0 1 2 0 6 f 3 4 7 9 12 16 18 1 3 f 3 4 7 9 12 16 18 0 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 50 bytes ``` ->s,n{!s.combination(n).map{|c|c.inject :+}.uniq!} ``` [Try it online!](https://tio.run/##jZJRT4MwEIDf@RXHnjQeZDCYmwn@EdKHDtpYwwqjJdGM/fZ60rlMg86n9u77rr1L2w@7dycLFz0b1MfQxFW73ynNrWr1nb6P97w7jtVYxUq/isrC08MpHrQ6hCdXlmWCkCFsGALtbD8IhgFM6WRJKJ0BKcKKEJuWOYKQE8xnYe4v@7OSAskbc6YRhREpy6mT1Bdf8W9Hk7P6xcg8XhNN5zv4YWQ3jfymsb42/ISPCFsyUm8lm39bl6ECFgtevUDdwmgQNIJ46@hpRT0GAL0wQ2OhAFnSh2CfGa6MgIXkqlmAkl9GWFzqSOoGa84kELp2zn0A "Ruby – Try It Online") If all elements are unique, `uniq!` returns `nil`. Negating that result, as in `!(...).uniq!` makes for a nice uniqueness test. This question was posted [a few weeks before](https://www.ruby-lang.org/en/downloads/releases/) Ruby 2.4.0-preview1, which introduced `Enumerable#sum`, which would save 9 bytes here. # 41 bytes (Ruby 2.4+) ``` ->s,n{!s.combination(n).map(&:sum).uniq!} ``` [Try it online!](https://tio.run/##jZLBboMwDEDvfIXpYWqlgEoKXTuJ/QjKIYVEiwSBkkTatO7bM490VTextafEfs@OLWV0hzcvS588G6LfY5PWfXdQmlvV66VepR0flg9PxnWr1Gl1jD98VVUZgZzAjhHAmx2dYCSCKZ2tEdEZQAlsELHpmCMECoTFLCzCY/9WYiB5a840wTBBZT1NQkPxFf/RGp3NH0Ye8BYpnZ/gl5HfNIqbxvbaCBs@EtijQYOV7e62LktFLBW8foGmh5MhoAmI10HUVjSnCGAUxrUWSpAV/gP2leHKCFhIrtoFKPltxOWlDqXBWXMmkdCN9/4T "Ruby – Try It Online") [Answer] # [R](https://www.r-project.org/), 41 bytes ``` function(s,n)max(table(combn(s,n,sum)))<2 ``` Sums all n-length subsets of s and checks if all values in a contingency table of these sums are 1 (all sums are unique). [Try it online!](https://tio.run/##PcpLCoAwDEXRuavIMIE4aOsX3IwWC4Kt4AfcfQxVHATCeXeXMJQSruTPZUt4cKI43niO0zqj3@KUjY8rEtFgJaBHw2AZHENN@lHxWcXQKZgfvkhZ1enk3snltmXo1TUyjV6Xd5EH "R – Try It Online") ]
[Question] [ This puzzle is the next in my series of Manufactoria challenges. # Background [Manufactoria](http://pleasingfungus.com/Manufactoria/) is a game / two-dimensional programming language. The player must create programs that will manipulate a queue to arrive at the desired output. It is easy to learn but hard to master, so it lends itself to creating a wide variety of challenges. If you don't know what I am talking about, I advise that you play the first few tutorial levels of the game. # Challenge Your challenge is to create a machine that will return the very last element of the input string. To make this even more challenging, the input string can be *any* combination of *all four colors*. The official custom level to be used is found here: <http://pleasingfungus.com/Manufactoria/?ctm=Last_in_Line!;IN:_a_series_of_colors_OUT:_the_very_last_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3;0>; This week's challenge is mostly focused on the idea of compression. I chose this challenge to require a huge mess of conveyor belts. The fact that all four colors appear in the input means that it is very hard to store information. Although I did not attempt compression, my first working prototype had 114 parts and fit into the 13x13 space with almost no room to spare. # Scoring The goal of this challenge is to use a few parts as possible. The score is the number of parts placed, and the lowest score wins. Although there are only 8 test cases, your creation should be able to theoretically function under any test case. The test cases provided are for debugging purposes. # Examples ``` in: byrgyrbyrrgry out: y in: ggryybrryr out: r in: #don't you love degenerate cases? out: in: gyrbrygbrygbyrb out: b ``` [Answer] ## 73 69 parts ![enter image description here](https://i.stack.imgur.com/csSbm.png) Organizing as a strip seems to save a lot of devices. Left-to-right, the columns are "last color was yellow", "last color was blue", two columns of devices, "last color was red", "last color was green", and "all done". <http://pleasingfungus.com/Manufactoria/?lvl=35&code=c10:8f2;q11:6f5;i11:7f0;p11:8f5;i12:6f4;q12:7f5;p12:8f5;c13:8f0;i10:7f6;i10:6f6;i13:6f7;i13:7f7;c9:6f3;c9:7f3;c9:8f3;q11:9f3;q12:9f3;c9:9f2;i10:9f3;i13:9f2;g12:12f3;c10:10f1;c13:11f1;c13:10f1;c10:11f1;p12:2f3;q12:3f3;c13:2f3;i13:3f5;c11:2f0;c10:2f3;i10:3f1;c11:3f0;c9:3f3;p11:11f3;p12:10f3;i11:10f1;i12:11f5;c14:3f3;c14:6f3;c14:7f3;c14:8f3;c14:9f0;i14:4f5;c14:5f3;i13:4f5;c13:5f3;y11:12f3;c11:13f2;c9:4f3;c9:5f3;c10:4f3;c10:5f3;b11:5f1;c11:4f2;c12:4f2;c15:4f3;c15:5f3;c15:6f3;c15:8f3;c15:7f3;c15:9f3;c15:10f3;c15:11f3;c15:12f3;c15:13f0;c14:13f0;c13:13f0;r12:5f1;&ctm=Last_in_Line!;IN:_a_series_of_colors_OUT:_the_very_last_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3>; [Answer] # 65 parts ![enter image description here](https://i.stack.imgur.com/j0Gjc.png) To be honest I couldn't even come up with the idea of putting pairs of readers directly against each other until I saw it in the already-posted solutions. But later I started to come up with a lot of optimization tricks. [Link](http://pleasingfungus.com/Manufactoria/?lvl=33&code=c7:6f2;c7:7f1;i7:8f3;c7:9f1;c7:10f1;c8:6f2;c8:7f3;p8:8f7;i8:9f1;q8:10f7;r8:11f2;c9:6f2;c9:7f0;p9:8f7;q9:9f7;i9:10f5;i9:11f7;b9:12f2;c10:5f3;i10:6f7;i10:7f6;i10:8f6;c10:9f2;c10:10f1;c11:5f0;c11:8f0;i11:9f3;c11:10f1;c11:11f1;c12:3f3;c12:4f3;q12:5f3;i12:6f7;i12:7f6;p12:8f3;i12:9f7;i12:10f6;i12:11f6;c12:12f3;c13:5f3;c13:6f2;c13:7f0;c13:8f1;q13:9f3;i13:10f1;p13:11f3;i13:12f1;y13:13f0;c14:6f3;c14:7f3;i14:8f1;q14:9f3;p14:10f3;i14:11f7;g14:12f0;c15:8f0;i15:9f2;c15:10f1;c15:11f1;c12:2f3;c10:11f3;c10:12f2;c11:12f2;c11:6f2;c11:7f0;&ctm=Last_in_Line!;IN:_a_series_of_colors_OUT:_the_very_last_color;byrgyrbyrrgry:y%7Cbbrrbryyyrrbr:r%7Cggryybrryr:r%7Cb:b%7C:%7Cgyrbrygbrygbyrb:b%7Cbrbrbryyrygbrg:g%7Crrrrrrrrrr:r;13;3;0;) [Answer] ## 91 88 parts ![enter image description here](https://i.stack.imgur.com/Etlq4.png) The upper left gadget handles green/blue, the lower right gadget handles red/yellow. <http://pleasingfungus.com/Manufactoria/?lvl=35&code=q8:6f5;c8:7f2;c9:5f2;p9:6f4;q9:7f2;i10:5f7;c10:6f0;p10:7f3;i12:6f6;i13:6f6;c13:11f0;i14:6f6;p14:10f3;r14:11f0;c15:6f0;p15:9f6;q15:10f0;c15:11f2;c16:6f0;q16:9f5;c16:10f0;i16:11f3;c17:6f0;c17:7f1;c17:8f1;c17:9f1;c17:11f1;b10:8f2;i11:8f7;c12:4f3;c12:7f3;c12:8f3;i12:9f5;i12:10f1;c12:11f3;i12:12f5;c14:3f3;c14:4f3;c9:4f2;i10:4f7;i11:4f7;c7:8f2;i8:8f3;c9:8f3;c9:9f2;c10:9f2;i11:9f7;i13:9f7;c14:9f2;c13:10f0;i11:10f6;c10:10f0;c9:10f0;c8:10f1;c8:9f1;c15:7f0;i14:7f6;i13:7f6;c15:8f0;i14:8f6;c13:8f3;c8:4f2;c16:7f0;g8:5f1;y16:8f1;q12:3f7;c13:2f3;i13:3f5;c13:4f3;i11:3f6;c10:3f3;p12:2f7;c11:2f3;c7:6f3;c7:7f3;c11:5f3;i11:6f6;c11:7f3;c12:5f3;c13:5f3;c14:5f3;c17:10f1;c11:11f3;c11:12f2;c13:12f2;c14:12f2;c15:12f2;c16:12f1;&ctm=Last_in_Line!;IN:_a_series_of_colors_OUT:_the_very_last_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3;0>; [Answer] ### 99 90 84 81 Parts ![last in line - further optimizations](https://i.stack.imgur.com/L0yqk.png) Yes - this is a mess of conveyer belts. But finally considerably less than 100 parts - also thanks to Volatility. <http://pleasingfungus.com/Manufactoria/?lvl=33&code=p12:9f3;i12:2f1;c11:9f0;c9:8f2;c10:8f2;i11:8f7;i12:8f5;i12:4f5;i12:5f5;c12:6f3;i12:7f1;i13:9f3;c14:8f3;i13:8f3;q12:3f3;q15:4f7;p15:5f7;c14:5f3;i14:6f1;i14:7f1;i13:7f0;i13:6f0;i13:5f4;c11:7f3;c10:7f2;c15:7f0;c16:5f3;c16:7f0;c11:2f3;c13:2f0;c14:2f0;c15:2f0;c16:3f1;c16:4f1;c16:2f0;c17:4f0;c17:5f1;c17:7f1;c17:8f1;c8:8f1;c8:7f1;c8:5f1;c8:4f2;c16:6f3;c17:6f1;g15:6f0;c8:6f1;c8:9f1;c8:10f1;c9:9f1;c9:10f0;p10:9f7;q10:10f3;b10:11f2;c11:10f2;c11:11f2;i12:10f5;c12:11f3;c13:10f1;c13:11f0;c16:10f2;c17:9f1;c17:10f1;c12:12f3;p14:9f7;q14:10f7;r14:11f0;c15:9f1;c15:8f1;c15:10f2;c11:3f3;q11:4f3;p11:5f3;y11:6f2;c10:5f3;c10:6f3;c9:4f2;c10:4f2;c13:3f3;c13:4f2;c14:4f2;&ctm=Last_in_Line!;IN:_a_series_of_colors_OUT:_the_very_last_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3;0>; [Answer] # 75 parts ![Screenshot of 75-part Manufactoria program to extract last input color](https://i.stack.imgur.com/Wu5Ll.png) <http://pleasingfungus.com/Manufactoria/?lvl=34&code=c11:9f1;q11:11f3;p11:12f7;g11:13f2;i12:9f1;i12:10f1;i12:11f1;i12:12f5;p13:9f7;i13:11f1;i13:12f5;i14:11f0;q13:10f3;c14:9f0;c15:11f0;c14:12f1;i14:10f4;c15:9f3;c15:10f3;c10:12f1;i10:11f0;i10:10f0;c10:9f1;c9:11f1;c9:10f1;c9:9f1;b13:13f0;c11:10f0;c9:6f2;c9:7f1;c9:8f1;c10:5f3;i10:6f5;i10:7f1;c10:8f2;r11:4f2;i11:5f0;i11:6f4;q11:7f5;p11:8f1;c12:4f3;i12:5f1;i12:6f5;i12:7f5;i12:8f5;y13:4f0;p13:5f1;q13:6f5;c13:7f2;c13:8f3;c14:5f3;i14:6f5;i14:7f5;c14:8f3;c15:6f3;c15:7f3;c15:8f3;p12:2f7;q12:3f3;c11:3f0;i14:3f5;c13:3f2;c15:3f3;c15:4f3;c15:5f3;c14:4f3;c10:4f3;c9:5f3;c9:4f3;c9:3f3;c10:2f3;c14:2f3;c13:2f2;c11:2f0;i10:3f1;&ctm=Last_in_Line!;IN:_a_series_of_colors_OUT:_the_very_last_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3;0>; Yeah, I know, it's six parts more than [Keith Randall's solution](https://codegolf.stackexchange.com/a/12066), but what can I say? I like the symmetry. ]
[Question] [ Create a function, expression, or program which does the following: 1. Take the prime factors of any number and sum them. For example, the prime factors of 28 are 2 2 7, summed to 11. 2. Multiply the result by the number of prime factors for the given number. E.g, 28 has 3 prime factors which sum to 11. 11 \* 3 is 33. 3. Repeat the process recursively, storing the resulting list (which starts with the original number), until you reach a number that is already included in the list. Halt without adding that final number, so that the list contains no duplicates. The progression for 28 is 28 33, because 33 results in 28 again. 4. Count the elements in the resulting list. In the case of 28, the answer is 2. Here are the results for `0<n<=10`, so you can check your algorithm. `2 1 1 10 1 11 1 9 5 10` (As balpha pointed out, the answer for `higley(1)` is 2, from the list 1 0. I originally had 1, due to a bug in my original algorithm written in J.) Since I'm a conceited SOB and haven't found this on [OEIS](http://oeis.org), let's call this the "Higley Sequence," at least for the duration of this round of code golf. As an added bonus, find the first two `n` having the lowest `higley(n)` where `n` is not prime and `n>1`. (I think there are only two, but I can't prove it.) This is standard code golf, so as usual the fewest keystrokes win, but I ask that you please upvote clever answers in other languages, even if they are verbose. [Answer] # J, 47 45 ``` #@((~.@,[:(+/@{:*+/@:*/)2 p:{:)^:_)`2:@.(=&1) ``` It's possible this would be much shorter without using `^:_`, but my brain is sufficiently fried already. **Edit:** (47->45) Double coupon day. Usage: ``` higley =: #@((~.@,(+/@{:*+/@:*/)@(2&p:)@{:)^:_)`2:@.(=&1) higley 1 2 higley"0 (1 + i. 10) 2 1 1 10 1 11 1 9 5 10 ``` [Answer] ### Golfscript, 68 67 62 61 chars ``` [.]({[.2@{1$1$%{)}{\1$/1$}if}*;;].,*0+{+}*.2$?@@.@+\@)!}do;,( ``` This is an expression: it takes `n` on the stack and leaves the result on the stack. To turn it into a program which takes `n` from stdin and prints the result to stdout, replace the leading `[` with `~` The heart of it is `[.2@{1$1$%{)}{\1$/1$}if}*;;]` (28 chars) which takes the top number on the stack and (by an incredibly inefficient algorithm) generates a list of its prime factors. C-style pseudocode equivalent: ``` ps = [], p = 2; for (int i = 0; i < n; i++) { if (n % p == 0) { ps += p; n /= p; } else p++; } ``` The `0+` just before `{+}*` is to handle the special case `n==1`, because Golfscript doesn't like folding a binary operation over the empty list. One of the non-prime fixpoints is 27; I found this without using the program by considering the mapping (pa `->` a2p), which is a fixpoint if a == p(a-1)/2, and trying small `a`. (`a==1` gives the fixpointedness of primes). Searching with the program turns up a second fixpoint: 30 = (2+3+5)\*3 --- ### Appendix: proof that there are only two non-prime fixpoints Notation: `sopfr(x)` is the sum of prime factors of `x`, with repetition (A001414). `Omega(x)` is the number of prime factors of `x` (A001222). So the Higley successor function is `h(x) = sopfr(x) Omega(x)` Suppose we have a fixpoint `N = h(N)` which is a product of `n=Omega(N)` primes. `N = p_0 ... p_{n-1} = h(N) = n (p_0 + ... + p_{n-1})` Basic number theory: `n` divides into `p_0 ... p_{n-1}`, so `w=Omega(n)` of those primes are the prime factors of `n`. Wlog we'll take them to be the last `w`. So we can divide both sides by `n` and get `p_0 ... p_{n-w-1} = p_0 + ... + p_{n-1}` or `p_0 ... p_{n-w-1} = p_0 + ... + p_{n-w-1} + sopfr(n)` Given that all of the primes `p_0` to `p_{n-w-1}` are greater than 1, increasing any of them increases the LHS more than the RHS. So for a given `n`, we can enumerate all candidate solutions. In particular, there can be no solutions if the LHS is greater than the RHS setting all the "free" primes to 2. I.e. there are no solutions if `2^{n-w} > 2 (n-w) + sopfr(n)` Since `sopfr(n) <= n` (with equality only for n=4 or n prime), we can make the weaker statement that there are no fixpoints if `2^{n-w} > 3 n - 2 w` Holding `w` fixed we can select different values of `n` satisfying `w=Omega(n)`. The smallest such `n` is `2^w`. Note that if `2^{n-w}` is at least 3 (i.e. if `n-w>1`, which is true if `n>2`) then increasing `n` while holding `w` constant will increase the LHS more than the RHS. Note also that for `w>2` and taking the smallest possible `n` the inequality is satisfied, and there are no fixpoints. That leaves us with three cases: `w = 0` and `n = 1`; `w = 1` and `n` is prime; or `w = 2` and `n` is semi-prime. Case `w = 0`. `n = 1`, so `N` is any prime. Case `w = 1`. If `n = 2` then `N = 2p` and we require `p = p + 2`, which has no solutions. If `n = 3` then we have `pq = p + q + 3` and two solutions, `(p=2, q=5)` and `(p=3, q=3)`. If `n = 5` then `2^4 > 3 * 5 - 2 * 1`, so there are no further solutions with `w = 1`. Case `w = 2`. If `n = 4` then `N = 4pq` and we require `pq = p + q + 4`. This has integer solution `p=2, q=6`, but no prime solutions. If `n = 6` then `2^4 > 3 * 6 - 2 * 2`, so there are no further solutions with `w = 2`. All cases are exhausted, so the only non-prime fixpoints are 27 and 30. [Answer] ## Ruby, 92 characters ``` f=->i{r=[i];(x=s=0;(2..i).map{|j|(s+=j;x+=1;i/=j)while i%j<1};r<<i=s*x)until r.uniq!;r.size} ``` This solution assumes higley(1) is actually 2, not 1 (see balpha's comment above): ``` (1..10).map &f => [2, 1, 1, 10, 1, 11, 1, 9, 5, 10] ``` [Answer] ## Octave - 109 chars ``` l=[input('')];while size_equal(unique(l),l);n=factor(l(1));l=[sum(n)*length(n) l];endwhile;disp(length(l)-1); ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` LU¡o§*LΣp ``` [Try it online!](https://tio.run/##yygtzv7/3yf00ML8Q8u1fM4tLvj//7@hAQA "Husk – Try It Online") or [Verify first 10 tests](https://tio.run/##yygtzv6f@6ip8eGOxYYG/31CDy3MP7Rcy@fc4oL//wE "Husk – Try It Online") ## Explanation ``` LU¡o§*LΣp input → n ¡o create an infinite list: p get the prime factors L length §* times Σ sum U longest unique prefix of the infinite list L length of the prefix ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ÆfS×LƊ$ƬL ``` [Try it online!](https://tio.run/##y0rNyan8//9wW1rw4ek@x7pUjq3x@X@4/VHTmv//jQ0A "Jelly – Try It Online") ## Explanation ``` ÆfS×LƊ$ƬL Main monadic link Ƭ Repeat and collect results until a duplicate occurs $ ( Æf Prime factorization Ɗ ( S Sum × Multiplied by L Length Ɗ ) $ ) L Length ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 19 bytes ``` i`vt0)Yftnws*yy-]xn ``` [Try it online!](https://tio.run/##y00syfmf8D8zoazEQDMyrSSvvFirslI3tiLvv0vIfyMLLkMuIy5jLhMuUy4zLnMuCy5LLkMDAA "MATL – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` l.u*sJPNlJ ``` [Try it online!](https://tio.run/##K6gsyfj/P0evVKvYK8Avx@v/fxMA "Pyth – Try It Online") --- Explanation: ``` .u Q | N = input, then N = s | sum of PN | list of prime factors of N J | (call this list J) * | times lJ | length of J .u | until a previous result is repeated. return the list of results l | print the length of the list ``` ]
[Question] [ Given a non-empty list/vector of positive integers, write a function to check the following conditions in as few bytes as possible. 1. Take the first integer (the key, or k1) and check that the next k1 values have no duplicate values, excluding instances of k1. 2. Take the last integer (the second key, or k2) and check that the k2 values before k2 have no duplicate values, excluding instances of k2. Note that both keys, k1 and k2, are elements of the list/vector as either key could contain the other. Also, k1 and/or k2 can be greater than the number of integers within the list, which means you should check every element of the list except for instances of the given key for duplicates. If both steps return True, return True, else, return False. **NOTE:** It should be rather intuitive that searching for duplicates within the first k1+1 elements excluding instances of k1 will exclude the first element, or k1. Some answers I've seen "pop" k1 off the list and do the test on the next k1 elements. Either method yields the same results. This is also true for k2 and it's test. ### Test Cases ``` [5,1,2,5,3,4,3] is TRUE because [k1=5][1,2,5,3,4] has no duplicates, nor does [5,3,4][k2=3] have any duplicates, excluding instances of k3. [6,9,12,15,18,19,8,8,3] is FALSE because [k1=6][9,12,15,18,19,8] has no duplicates while [19,8,8][k2=3] has a duplicate. [100,100,100,100,101,102,3] is TRUE because [k1=100][100,100,100,101,102,3] has no duplicates, and [100,101,102][k2=3] has no duplicates. [100,100,100,100,101,102,4] is FALSE. [k1=100][100,100,100,101,102,4] has no duplicates, but [100,100,101,102][k2=4] has duplicates. [6,6,6,6,6,6,6,3,3,3,3] is TRUE. [k1=6][6,6,6,6,6,6] has no duplicates, excluding instances of k1, and [3,3,3][k2=3] has no duplicates, excluding instances of k2. [1,2] is TRUE (clearly) [1] is TRUE (clearly) ``` [Answer] # JavaScript (ES6), ~~88 75 71~~ 69 bytes ``` a=>(g=_=>!a.reverse().some(o=(v,i,[k])=>v-k&&o[v]&(o[v]=i<=k)))()&g() ``` [Try it online!](https://tio.run/##fZBND4IwDIbv/gq9QJtUwkCIJo7Eg548@XEixBCcBFFnwOzv44gXCMy@aQ/N061976lK66wq3p/5S15Fc@NNyiPI@YVHs9SphBJVLQCdWj4FSA6KCorLBHmk5qVlyVglFrSVF2teIiKglQM2mXzV8iGch8zBPh3OWxsn3d4N4oAYeRSQTwvyk2kncMAy16V@Mp2enhuyIXXl/5QY3iWv9/PfHQzkGGtEW7YH27vN/jjiTkgrYh4x7dKS2IqWWsYrDO4stDvNFw "JavaScript (Node.js) – Try It Online") ### Commented The function \$g\$ reverses the input array and performs the test with the resulting leading key. ``` g= _ => // g takes no explicit input !a.reverse() // reverse the input array a[] .some(o = // we use the object o to store encountered values (v, i, // for each value v at position i in a[], [k]) => // with k = leading value: v - k && // abort if v is equal to the key o[v] & // otherwise, test whether o[v] is already set (o[v] = i <= k) // and i is less than or equal to the key, // in which case o[v] is set ) // end of some() ``` The main function simply invokes \$g\$ twice. ``` a => g() & g() ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ,Uḣ⁹ḟQƑʋḢ$€Ạ ``` [Try it online!](https://tio.run/##y0rNyan8/18n9OGOxY8adz7cMT/w2MRT3Q93LFJ51LTm4a4F/x/u3Gf9qGGOgq6dwqOGudaH27kOtwOlIv//j@aKNtUx1DHSMdUx1jHRMY7V4Yo207HUMTTSMQRKWOgYWupYACFYwtDAQAcVGwKxEX5JE4iRyNAYAsG6dIzAFIiI5YoFAA "Jelly – Try It Online") A monadic link taking a list of integers and returning a Jelly Boolean (1 for True, 0 for False). ## Explanation ``` ,U | Pair with reversed list ʋḢ$€ | For each pair, do the following as a dyad using the popped head as the right argument y: ḣ⁹ | - First y integers ḟ | - Filter out y QƑ | - Check if invariant when uniquified Ạ | All ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~95~~ ~~88~~ ~~75~~ 74 bytes ``` lambda x:all(A[:A[0]+1].count(a)<2for A in[x,x[::-1]]for a in A if a-A[0]) ``` [Try it online!](https://tio.run/##fY/RCoJAEEWf8yv2TaVbOGtKLRnsd0z7sBVLgmmIgX29rUpQD8VlGDgzdy5zf3bXppaDK45DZW@nixW9slUVaVaaE7Mksz43j7qLbLyXrmmFFmXNPXpWakXGjMh6NHIn7Go0xcN7UTBnIEhkSLFBaiCYkgTfRb7kPMzxqXTW5IKcmjEqWNzbsu6ERlgcQrhIx8FHYI4dSIJ88Ba0w9brb/Dmx82ZsLdOTLiI/Wsv "Python 2 – Try It Online") 7 bytes saved thx to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king); then 8 more thx to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink); and then 5 more from [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king); and 1 byte thx to [mypetition](https://codegolf.stackexchange.com/users/65255/mypetlion) pointing out an extra space. Function taking a list of ints; returns `False/True`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` ∨¬⮌θ⬤E⟦⮌θθ⟧✂⮌ι⁰⊟ι¹⬤ι∨⁼№ιλ¹⁼λ§ι⁰ ``` [Try it online!](https://tio.run/##RY09C8IwEIb/yo0XOKG1dnISceigFh1LhhADBo6mSdPiv4@xft10PPe87@m7CtopTqkNto94DnhyES9mNmE06IUg2DHjUQ3Y/SmBlwRXttr8XJtpQdC6YVnLb9QS5NaDnxSPuHdT/pIRLwrBh3N2Y9PfzON1LMR7til1XU0lrammijZUSZlWMz8B "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, which is `-` for true and nothing for false. Explanation: ``` ∨¬⮌θ ``` If the reversed list is empty then the result is true. (Don't ask me why I need to reverse the list first... I think the implicit input uses a subtly different data type or something.) ``` ⬤E⟦⮌θθ⟧ ``` Check the list both backwards and forwards. ``` ✂⮌ι⁰⊟ι¹ ``` Slice the last `n` elements of the reversed list where `n` is the last element. ``` ⬤ι∨⁼№ιλ¹⁼λ§ι⁰ ``` Check that each element is either unique or equal to the first element. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~138~~ \$\cdots\$ ~~102~~ 91 bytes ``` lambda x:all(len(set(t:=[e for e in l[1:l[0]+1]if e-l[0]]))==len(t)for l in[x,x[::-1]]if l) ``` [Try it online!](https://tio.run/##fY7PisJADMbvfYrcOrOm0HRU6kA9@gR7m51DxSkWYlvqiPXpu9Otgu4u8pE/JF/Ir7v5Y9uovOvHqvgauTztDyUMumQW7Bpxdl54XRgHVduDg7oBNqTZpHZBtq7AJVNvpSyKye/l5OPgMwMORuuE7GRjOXZ93XgRJ/EHqUW8hc/@4mDvuL3GMnpciQjMCgkzXKHCJSqLYUJpiq9BIbL7do3PUrPmO8zm@pNDkjqCmaMSLGX0m2lX8vl/qDVukDKkAJcjbTAPeg@3/Ptv/AY "Python 3.8 (pre-release) – Try It Online") Saved 11 bytes thanks to @JoKing!!! [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=uniq,head -pF,`, ~~71~~ 66 bytes ``` sub b{(@_=grep$_-@_[0],head$_[0]+1,@_)==uniq@_}$_=b(reverse@F)*b@F ``` [Try it online!](https://tio.run/##HY2xDsIgFEV/xYGh1YcBm8bahORNTDo6GUMkEiWpFIG6GH9dxA733DPd600Y2pzjpBf6XaESt2A8URTViZ3hbi5X8rcVB1S1EJOzT1QfooSugnmZEA3KeqlR5txAB9uSblfAgTPghRtovqNPdnQx00O7ZpyV3tuY@v6Y7DBPwsO6@SxTL@EH "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~64~~ 56 bytes Mimics the JavaScript answer in that it takes a helper function and checks the array and its reversed version, but the check for uniqueness is done by taking the subarray based on the key, removing all copies of the key, then checking if the (modified) subarray matches its deduplicated version. -8 bytes by improving the empty list check, and golfing the deduplication code. ``` ->a{g=->f=0,*a{a=a[0,f]-[f];a&a==a};g[*a]&g[*a.reverse]} ``` [Try it online!](https://tio.run/##fYzLCoMwEEX3fkXU4kLGkvgoisSlP5GGMqXRFqQUX6VIvj2NdtNuyuFcGGbm9tP5ZWp@NFGFS8ujquEUQlyQo6DQyEg0ssQAOUddtiJEGay579Ws@kFJbZ7XW6dIq8bBIQQJJ2rGjuxOdnpM40A8f3HdWqDUxF9Qe466X4zIgEEMGSSQQiIdwSiFX5k13nYH@Cb5sP5AvKZ1OyqAxcBscQ6sgNzyrziVbw "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ‚εć©£®KDÙQ}P ``` Port of [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/197674/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##yy9OTMpM/f//cNOjhlnnth5pP7Ty0OJD67xdDs8MrA34/z/a0MBABxUbArGRjnEsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w02PGmad23qk/dDKQ4sPrfN2OTwzsDbgv87/6GhTHUMdIx1THWMdEx3jWB2FaDMdSx1DIx1DoISFjqGljgUQgiUMDQx0ULEhEBvhlzSBGIkMjSEQrEvHCEyBiNhYAA). **Explanation:** ```  # Bifurcate the (implicit) input-string; short for Duplicate & Reverse copy ‚ # Pair this reversed input with the duplicated input ε # Map over the inner lists of this pair: ć # Extract the head; pop and push remainder-list and first item © # Store this head in variable `®` (without popping) £ # Leave the first `®` items from the remainder-list ®K # Remove all `®` (if present) DÙ # Duplicate this list, and uniquifiy it Q # And check if it's still the same }P # After the map, check if both were truthy # (which is output implicitly as result) ``` [Answer] # [J](http://jsoftware.com/), ~~36~~ 28 bytes ``` *&({.(-:~.)@-.~}.{.~{.<.#)|. ``` [Try it online!](https://tio.run/##dY1BC4JAFITv/oqhoM14PnbVIpeEKOgUHfoHlSsZZVEWhOVfNysCPcQwh2HmfW9XtljECDUECBK6ssOYLuezstfp5tx1dMH22OHiyTkXOY@4bT@4tC3LbLZHKISI0SdFLvXJI5@8byE/xYACUi6pajAkFdCwkle/VFJS06qy26T8G/l10oDq8r5qvCL3F@N3tKzFhGEOp@yOfXLJkFxwTSMTJ6mJsDbb1S05nusErRWEQPkC "J – Try It Online") * `*&( )|.` Take the original input (implicit in the hook) and its reverse `|.`, and multiply the boolean values `*` produced by transforming them with the verb in parens `&( )` Let's break down the verb in parens... * `}.{.~{.<.#` From the beheaded `}.` input take `{.~` this many elements: The smaller of `<.` the first element `{.` and the length of the list `#` * `{.( )@-.~` And from that remove all instances of `-.~` the first element of the list `{.` and `@` apply the inner verb in parens... * `(-:~.)` Is the list identical to `-:` its uniq `~.`? [Answer] # [R](https://www.r-project.org/), ~~72~~ ~~71~~ 70 bytes ``` `-`=function(l)!anyDuplicated(head(l,l[1]+1),l[1]) -(l=scan())&-rev(l) ``` [Try it online!](https://tio.run/##K/r/P0E3wTatNC@5JDM/TyNHUzExr9KltCAnMzmxJDVFIyM1MUUjRycn2jBW21ATTGty6Wrk2BYnJ@ZpaGqq6RallgG1/Tc0MFBAxYZAbKRg8h8A "R – Try It Online") Saved a byte thanks to [Sumner18](https://codegolf.stackexchange.com/users/82163/sumner18). [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` S¤&ΓȯS=uΣSx↑↔ ``` [Try it online!](https://tio.run/##yygtzv6fm18erPOoqfF/8KElaucmn1gfbFt6bnFwxaO2iY/apvz//z862lTHUMdIx1THWMdExzhWJ9pMx1LH0EjHEChuoWNoqWMBhCBxQwMDHVRsCMRGeOVMwOYhQ2MIBOnRMQKRsbEA "Husk – Try It Online") The function does the k1 test for the both the list and its reverse. ]
[Question] [ Given a date written in any (must handle all in the same program) of the following formats, parse it into a valid `yyyy/mm/dd date`. ``` 17th May 2012 March 14th, 2016 20 February 2014 September 14, 2017 Sunday, June 8, 2015 ``` **Rules** * Dates will sometimes be invalid, ie. incorrect day for the month or number of months in a year, you must handle both cases. Either by erroring out or returning a consistent falsey value, you choose. (They will however stick to the template formats above) * Padding for days and months less than 10 must be used to create a two digit output. * Month names will always be the full name, not shortened to their three character counterparts. * You can assume the year will always be within the 0000-9999 range. * Negative numbers need not be handled. * You can create a full program or function so output can be in any format, printed to console or returned from a function. * Input will always be a string, output must always be a string, if it makes it shorter to take it as a single argument in an array eg. `["17th May 2012"]` you may do so and output can be the same `["2012/05/17"]` * You can assume spelling in input will be correct. **BONUS:** cos who here doesnt like a challenge ;) If you can manage to also allow the input formats of `The Fourteenth of March, 2016` or `March the Fourteenth, 2016` you may take an extra **20 bytes** off your code with any final byte counts less than 1 resulting in 1. Here are the full written numbers for each of the days to avoid any confusion on spelling. ``` First, Second, Third, Fourth, Fifth, Sixth, Seventh, Eighth, Nineth, Tenth, Eleventh, Twelfth, Thirteenth, Fourteenth, Fifteenth, Sixteenth, Seventeenth, Eighteenth, Nineteenth, Twentieth, Twenty First, Twenty Second, Twenty Third, Twenty Fourth, Twenty Fifth, Twenty Sixth, Twenty Seventh, Twenty Eighth, Twenty Nineth, Thirtieth, Thirty First ``` **Test Cases** ``` INPUT | Output 17th May 2012 | 2012/05/17 March 14th, 2016 | 2016/03/14 20 February 2014 | 2014/02/20 September 14, 2017 | 2017/09/14 Sunday, June 8, 2015 | 2015/06/08 1st January 1918 | 1918/01/01 The Fourteenth of March, 2016 | 2016/03/14 March the Fourteenth, 2016 | 2016/03/14 November the Seventeenth, 2019 | 2019/11/17 The Thirtieth of April, 2016 | 2016/04/30 30 February 2014 | Invalid September 99, 2017 | Invalid Sunday, June8, 2015 | Invalid The Thirty First of April, 2016 | Invalid ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~91~~ ~~89~~ ~~91~~ 56 bytes ``` date("$args"-replace'th|rd|st|(\b.*)day|,')-f yyyy/MM/dd ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/PyWxJFVDSSWxKL1YSbcotSAnMTlVvSSjpiilprikRiMmSU9LMyWxskZHXVM3TaESCPR9ffVTUv7//68eXJoHlNJR8CrNS1Ww0FEwMjA0VQcA "PowerShell – Try It Online") Takes input as a string. Uses a `-replace` to get rid of junk, then uses the built-in `Get-Date` command with the `-f`ormat flag to specify the required `yyyy/MM/dd` format. That string is left on the pipeline and output is implicit. *Saved two bytes thanks to Mr Xcoder. Saved a huge chunk thanks to TessellatingHeckler's regex golfing.* [Answer] # Rails, ~~41~~, ~~37~~ 35 bytes ``` ->x{x.to_date.strftime('%Y/%m/%d')} ``` I don't know of an online interpreter for Rails, but here is a screenshot demonstrating this proc [![enter image description here](https://i.stack.imgur.com/UaaG8.png)](https://i.stack.imgur.com/UaaG8.png) [Answer] # PHP, ~~73~~ 164+1 bytes ``` for(preg_match("#(\d+)[^\d]+(\d+)#",$d=$argn,$r);$m++<12;)strpos(_.$d,date(F,strtotime($r[2].-$m)))&&printf(checkdate($m,$r[1],$r[2])?"$r[2]/%02d/%02d":E,$m,$r[1]); ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/dee4d03ee97cfdd9c116060a3287fe8c4860a39b). The date check was really expensive: I had to disassemble the date before using a builtin, then try and error on the month name. [Answer] # [Python 3](https://docs.python.org/3/) + parsedatetime library, ~~152~~ ~~139~~ ~~155~~ 153 bytes Saved 13 bytes thanks to Jonathan Allan Added 16 bytes to handle dates with invalid length days Saved 2 bytes by removing lambda assignment ``` lambda s:re.search(f'(^| ){str(h(s)[0].tm_mday)[:2]}[^\d]',s)and time.strftime('%Y/%m/%d',h(s)[0]) import parsedatetime as p,time,re h=p.Calendar().parse ``` [Try it online!](https://tio.run/##dZFfa4MwFMXf/RQXoZiAmMTaWgs@DfZQ6F76NJwd6UxRqH9IUqhs@@zOBLsJZRA4l9zfPfeQdL0u22Y53NK34cLrU8FBbaUIlODyo0RnDx2/AH8qLVGJFM5oHuj6vS54j7NtmH9nx7ci93yFeVOArupxUsuzKZC3eCWLmiwKz59GsVPVXSs1dFwqUXAtDAhcQeebypfCKdMueOIX0RRcIhxYctBCaQUpZA4AclmsS9jzHkLKQtcH1yihK8JiF/sW2Zv0wCJd@oZaT9Sa0CVh0Z0KKTyLk7xyab2iiYoIDUlI79RBdFrUJyFHP@sWT1xMaDJzO1zHzL0Pu2sjYGPJ1USuCB1Xb@4kUxp2vLF7WcI2hjJKKBvPnVo@pntpG/GQKkl@U837szR/YWYAi9h//rlzbiWYR4eqsaq240wnq0ajGzIX5jchTW0zYzkefgA "Python 3 – Try It Online") Does not support bonus dates [Answer] # [Python 2](https://docs.python.org/2/), 193 bytes ``` lambda s:time.strftime('%Y/%m/%d',time.strptime(re.sub(r'^(\w+) (\d+)',r'\2 \1',re.sub('^ ','',re.sub('(th|rd|st)|(Sun|Mon|Tues|Wednes|Thurs|Fri|Satur)day|,','',s))),'%d %B %Y')) import re,time ``` [Try it online!](https://tio.run/##dU9Na8MwDL37V4hCsE2zts669QN62aGHQk8tjLKs4CwOMTROkBVGwf@9Sz3GLttJT3pPT0/dlerWZbdqk98uuilKDX5NtjETT1jdgeDJaZo006Tk6Q/RRQIH3BcC@Vnkn2MJIi/HkqfI8wxyNYBvnp@Bp/y3FVQHLIMnGcShd2HfunDsjQ@vpnRDOdY9@rBFGw6aepSlvoY0OngpZcqTEpIXSE5cSmabrkUCNDHajYwnDxsYjUZMLaiGvb5CNlMZ22v8qEHNqU7vg2eWzWBrCuw1RsWcHUxHpikMDqqoWbAh3XA8hV3vDCzj8IkpT7DTLi6qlVqyx/@dVqs/nH6MhpBvav2g3hmrWgQL1kF8YOK7iyXBc8flGjq0jqASVt6@AA "Python 2 – Try It Online") ;-; pls halp [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 190 + 26 = 216 bytes ``` import java.time.format.*; s->DateTimeFormatter.ofPattern("uuuu/MM/dd").format(DateTimeFormatter.ofPattern("[EEEE, ][d ]MMMM [d, ]uuuu").withResolverStyle(ResolverStyle.STRICT).parse(s.replaceAll("(\\d)[a-z].","$1"))) ``` [Try it online!](https://tio.run/##lVJdb9owFH3nV1xFQ7Kr4BLajVLWStNWpFaKVDW8pTyY2JTQ4ET2DV028duZccKXqk3dfUhsH597zvW9C77inbyQaiFeN@myyDXCwp4xTJeSzXK95MjOhq2inGZpAknGjYGQpwp@twCaU4Mc7W@VpwKWFiMR6lS9xBPg@sVQdxXqtCWmGZuVKsE0V2zULL7WBL/@3Yqbjenc/uAox9bFyJlAqVk@e3QLRbzSxnkYngvh0cYm@SchvrPhwyQWMAltQCzsbpvGJnhLcf4kTZ6tpI6wyiQ52bFo/HT/fUxZwbWRxDAti4wn8luWEY88Pwsa886vCfN871PgUUo34GLo6t4/BkqDBm6a59iGF/Rxbp@zgl436Hn@AQi5TuYQXOLc32JfjrFeF0ZyqkuuHe/yGItkgXI5ldpyHbN/kjVXglc@PJRKwpXDP5@wy//A@@/xwCA8cOWcBYPg6sS1En/FLj5U0WDwvqJjRzvDDboettzKTkczkK4D13Uf6L4NaEUPLYkqY@VYXiIrLAdnxGt3LrrmGtqmrTzfsX0QjBdFVpHtjjLMawFC6XCnDglH20Jy9zOxFdghB0k/pHOvVjxLxV5snxJA1ncj5MnrWNsJJAe91u67bq03fwA "Java (OpenJDK 8) – Try It Online") **Important note:** it was *shorter* to also validate the day of week instead of ditching it, so that validation is included! I haven't tried with `SimpleDateFormat` beyond the obvious cases which all accepted dates like 30 February. So I had to ditch it and I used Java 8's `DateTimeFormatter`. ## Explanation ``` "[EEEE, ][d ]MMMM [d, ]uuuu" ``` This format means : * optional day-of-week followed by comma and space `[EEEE, ]` (happens in `Sunday, ...`), * followed by optional day with space `[d ]`, * followed by month in full letters `MMMM` and space, * followed by optional day with comma and space `[d, ]`, * followed by year of era `uuuu` to let the parser know we're in Gregorian era. Code: ``` import java.time.format.*; // Required for DateTimeFormatter, *and* ResolverStyle s->DateTimeFormatter.ofPattern("uuuu/MM/dd") // Output format .format( DateTimeFormatter.ofPattern("[EEEE, ][d ]MMMM [d, ]uuuu") // Input format .withResolverStyle(ResolverStyle.STRICT) // Invalidates xxxx-02-30 instead of transforming it into xxxx-02-28 .parse( s.replaceAll("(\\d)[a-z].","$1") // remove st, nd, rd, th ) ) ``` # Credits * 2 bytes in the regex thanks to Neil. [Answer] ## JavaScript (ES6), ~~124~~ 122 bytes ``` f= s=>(d=new Date(s.replace(/.[dht]\b/,'')+' +0')).getDate()==s.match(/\d\d?/)&&d.toISOString().replace(/-(..)(T.*)?/g,'/$1') ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` ]
[Question] [ In [Bloons Tower Defense 6](https://btd6.com/), the strength of different bloons can be measured by their Red Bloon Equivalent (RBE), or the number of single pops it takes to completely defeat the bloon. The RBE for the bloon types are as follows (sourced from [the wiki](https://bloons.fandom.com/wiki/Bloon)) | Bloon | RBE | | --- | --- | | red | 1 | | blue | 2 | | green | 3 | | yellow | 4 | | pink | 5 | | black | 11 | | white | 11 | | purple | 11 | | lead | 23 | | zebra | 23 | | rainbow | 47 | | ceramic | 104 | | moab | 616 | | bfb | 3164 | | zomg | 16656 | | ddt | 816 | | bad | 55760 | ## The Challenge Given a run-length encoded list of bloon types, **calculate the total RBE.** More specifically, find the RBE of each bloon type according to the table, multiply by the given count, and sum them all. ### Notes * Input can be taken in any reasonable format (comma-separated string, list of tuples, etc.) * You must output a single integer * Assume that input will never be invalid * Bloon types must be given *exactly* as shown in the table above, in lowercase * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score in bytes wins! ## Test Cases ``` Input: 1 red Output: 1 Input: 7 green Output: 21 Input: 5 bfb, 11 moab Output: 22596 Input: 1 red, 2 yellow, 3 white, 4 zebra, 5 moab, 6 ddt Output: 8110 Input: 1 moab, 1 bfb, 1 zomg, 1 ddt, 1 bad, 1 red, 1 blue, 1 green, 1 yellow, 1 pink, 1 black, 1 white, 1 purple, 1 lead, 1 zebra, 1 rainbow, 1 ceramic Output: 77257 ``` [Answer] # JavaScript (ES6), 111 bytes Expects a list of `[count, bloon]` pairs. ``` a=>a.reduce((t,[k,s])=>t+k*[23,3,104,616,3164,1,16656,4,47,23,816,55760,5,11,2][parseInt(s,36)*53%437%44%15],0) ``` [Try it online!](https://tio.run/##dZDLboMwEEX3@QoUKRKk04TBD9JFsu83IBYGTErjYGRIo/bnqWMlBvWxm@O5M3eu38WH6EvTdMNzqys51vtR7A9iY2R1KWUYDpCdoM@j/WF4Oq2zhAABjClw5ECQU0BAzhkHCjQF297ZBmMpj4EBIiR51gnTy9d2CHsgPFozsqIkXVG6QpZDHI2lbnut5EbpY1iHWYYQLK39Ms@jKNhuA1z8VKRWcTRStl6T/BYxKyrqYplDkOFt51mLYhpI2Atf/GttZxJbf0ql9NUhsXh9awbpiFr6koURjpjfboFbqKrBO@0Q4z@N/ATOL70t1uejB7fqIRKVrx9nund1kR7uH3OnWYIbdk17mo2JcqIpnBNeTKcmVHJmPQV3h4imLWYWpTTi3JQ@f5omLB2/AQ "JavaScript (Node.js) – Try It Online") ### How? The hash function was found by brute force: ``` parseInt(s, 36) * 53 % 437 % 44 % 15 ``` It's a bit long but almost perfect: * all slots from 0 to 14 are used * *black*, *white* and *purple* (all scoring 11) gracefully collide on the same slot * however, two distinct slots are used for *lead* and *zebra* (both scoring 23) Below is a summary table sorted by final lookup index: ``` string | parseInt() | * 53 | mod 437 | mod 44 | mod 15 | value -----------+-------------+---------------+---------+--------+--------+------- "lead" | 998293 | 52909529 | 191 | 15 | 0 | 23 "green" | 28152239 | 1492068667 | 339 | 31 | 1 | 3 "ceramic" | 27013759860 | 1431729272580 | 134 | 2 | 2 | 104 "moab" | 1057907 | 56069071 | 223 | 3 | 3 | 616 "bfb" | 14807 | 784771 | 356 | 4 | 4 | 3164 "red" | 35509 | 1881977 | 255 | 35 | 5 | 1 "zomg" | 1664872 | 88238216 | 50 | 6 | 6 | 16656 "yellow" | 2080372496 | 110259742288 | 37 | 37 | 7 | 4 "rainbow" | 59409106160 | 3148682626480 | 243 | 23 | 8 | 47 "zebra" | 59454982 | 3151114046 | 127 | 39 | 9 | 23 "ddt" | 17345 | 919285 | 274 | 10 | 10 | 816 "bad" | 14629 | 775337 | 99 | 11 | 11 | 55760 "pink" | 1190576 | 63100528 | 350 | 42 | 12 | 5 "black" | 19468964 | 1031855092 | 204 | 28 | 13 | 11 "white" | 54565250 | 2891958250 | 189 | 13 | 13 | 11 "purple" | 1563335762 | 82856795386 | 336 | 28 | 13 | 11 "blue" | 541526 | 28700878 | 29 | 29 | 14 | 2 ``` [Answer] # Python 3.9, 104 + 17 = 121 bytes ``` lambda l:sum([47,11,3164,616,16656,4,1,5,23,104,11,23,3,2,11,816,55760][hash(a*9828)%17]*b for a,b in l) ``` You also need to set an environment variable (I included it in the byte count). ``` PYTHONHASHSEED=65 ``` Input is a list of tuples of the form `(name, amount)` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 47 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḋɓ“µCḅṃ’,14ḥⱮị⁽%xBŻ€ṁ@“£t¢Bƈ/¦£¤Bh¥ç¤¿€ƥṣ½‘¤ḅØ⁵ ``` A dyadic Link that accepts the frequencies on the left and the respective bloons on the right and yields the total RBE. **[Try it online!](https://tio.run/##y0rNyan8///hju6Tkx81zDm01fnhjtaHO5sfNczUMTR5uGPpo43rHu7uftS4V7XC6ejuR01rHu5sdACpXFxyaJHTsQ79Q8sOLT60xCnj0NLDyw8tObQfqOTY0oc7Fx/a@6hhxqElQOMOz3jUuPX////RhjoKRjoKxjoKJjoKpjoKZrH/o9WLUlPUdRTUK4HuyC8HscozMktSQYyq1KSiRBAjNz8xCUSnpJSoxwIA "Jelly – Try It Online")** ### How? ``` ḋɓ“...’,14ḥⱮị⁽%xBŻ€ṁ@“...‘¤ḅØ⁵ - Link: frequencies, bloons Ɱ - map across the bloons applying: ḥ - hash... “...’ - ...with salt: 160553470 ,14 - ...and values: [1,2,...,14] ¤ - nilad followed by link(s) as a nilad ⁽%x - 10371 B - convert to binary -> [1,0,1,0,0,0,1,0,0,0,0,0,1,1] Ż€ - zero range each -> [[0,1],[0],[0,1],[0],[0],[0],[0,1],[0],[0],[0],[0],[0],[0,1],[0,1]] “...‘ - code-page indices = [2,116,1,66,156,47,5,2,3,66,104,4,23,3,11,12,164,223,10] ṁ@ - mould -> [[2,116],[1],[66,156],[47],[5],[2],[3,66],[104],[4],[23],[3],[11],[12,164],[223,10]] ị - (hashed bloons) index into (that) Ø⁵ - 250 ḅ - convert from base (250) -> bloon RBEs ɓ - dyadic chain: ḋ - (frequencies) dot-product (bloon RBEs) ``` [Answer] # Excel, 203 bytes ``` =LET( a,TEXTSPLIT(A1," ",","), SUM(LOOKUP(TAKE(a,,-1), {"b","bf","bla","blu","c","d","g","l","m","p","pu","r","re","w","y","z","zo"}, {55760,3164,11,2,104,816,3,23,616,5,11,47,1,11,4,23,16656})*TAKE(a,,1)) ) ``` Input is comma-separated string, e.g. `1 red, 2 yellow, 3 white, 4 zebra, 5 moab, 6 ddt`, in cell `A1`. [Answer] # [C (gcc)](https://gcc.gnu.org/), 200 bytes Takes an array of strings and its length as input. ``` f(s,n,c,t)char**s;{int L[]={47,23,55760,4,0,0,0,0,0,816,2,0,0,0,0,0,3,0,0,5,3164,0,0,0,616,16656,1,0,11,23,0,104};for(t=0;n--;t+=c*L[((**s*2[*s++]*7711)>>15)&31])for(c=atoi(*s);*(*s)++-32;);return t;} ``` [Try it online!](https://tio.run/##XVJRjpswEP3nFCOqVhicCkOASl5ygr0BRRUYk1glEBlHqybi7OkYAs3Wlmae/Z5nxh6L3VGIx6P1RtpTQQ0Rp0r7/sjvqjfwXpT5fZ/RKKZJkqUh3dNwmz9YSqOXdTzbhMYsXWUpSliaJmhxxZgNhD7cT7wdtGfykPe7HTdBLvz3wvMwsR8V/hgEpZ9ljJHDgSXkW8xKYvUir8ygPH8k3Lc2CHZxxAnX0lx1D4ZPjy@qF921kfA2mkYN308Hx17kXKneI87dARz2iuAbOZqiLFhWQg4LYcfdZaBl4070ZSuDo5ay/7yZQN3WLgWXMTgPVf2ZXaIgG8Ef2XXDh8UxfJyUkRbu4SZrXVmYLMcRpdA05v84K8m2fHAbzscFWf3CVc0Cnmlxp7vKBS3Fz/BfLQwuqv@9SivxhFuByF/1pXviTq7xt7IxFb5qvUYTUldnJdbqJ@7MflQ3@cvg@f5oTmMxPzbD7xBR/BTZqsLugmcbpZAPObo3SNAFAXnpzUWjpPXcr81Pe53Wm3uoSrqFVyUhfMk/29k8v0fInenxFw "C (gcc) – Try It Online") [Answer] # Swift 2.2, 128 bytes ``` {$0.reduce(0){$0+$1.1*[0,16656,3164,0,5,616,3,0,0,11,1,816,0,23,0,0,23,0,55760,11,104,2,4,0,0,47][($1.0.hashValue>>8&63^6)%26]}} ``` [Try it on SwiftFiddle!](https://swiftfiddle.com/duf6zjjbt5alvoqhwz4kpzrdhq) Takes a dictionary, e.g. `["red": 3, "blue": 7]`. It turns out that after some bit twiddling, each bloon type has a unique\* hashValue mod 26. So far I haven't found a way to get the modulus any lower. Since Swift 3, hash values differ between runs of the same program, so this strategy is no longer viable. \*"white" and "black" map to the same value, but they also have the same RBE, so it works out. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 146 bytes ``` .+ed * .+ue *2* .+en *3* .+y *4* .+nk *5* .+[khp] *11* .+e[ab] *23* .+n *47* .+c *104* .+ab *616* .+f *3164* .+g *16656* .+dt *816* .+ad *55760* _ ``` [Try it online!](https://tio.run/##NU7LbsMwDLv7K3QZMLhuUaWxs//YsRg2O3FTI84DRrKi/flMVrKTKJEimfwcBovr2/vnj4L1dPCNkOJ0WLyQRQZ@EPKSwVPIMs@hE1JncO3u05eQiCy7WkdLwVJ6KasMaqLP/GWdkAZNhjcyRMPXlnhjNJ@bWciPTWGpg9aVOUvxva4IiUpV0CZPZTS4m1OACP1IpkwqKODpYxwfCi7wuIfZKyjh5V2yCjQrFRhoKAP3DXcfeI19myeRfLVNHuxKW1x8npydwX8MwhSGbpPYmsGeS8ySpsgo@s1tb0K2Ngxu@699sn2o1@Nv/AM "Retina – Try It Online") Takes input on separate lines but link is to test suite splits on `,` for convenience. Explanation: Each stage matches a colour of balloon to multiply its quantity appropriately. The shortest possible unique remaining substring is used at each point, with preference being given to the rightmost such substrings as this will be deleted and therefore can be ignored when matching subsequent substrings. In this way for instance `.+nk` matches and deletes the whole of `pink` allowing `.+[khp]` to only match `black`, `white` and `purple`. The final `_` then calculates the total RBE which is converted back to decimal. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 81 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ø`.•4в#‡fÕçòÖ¹<÷E¤E%ÝÙ/J“Å;>Íslζ₂θ…•3ôs3δ£k•Ì¥δвιλùEmæâåÇÛZ•₄в•Cƒ2œÝù•3äÁ«.¥>sè*O ``` I suck at finding magic numbers, so this will have to do for now.. Replacing `.•4в#‡fÕçòÖ¹<÷E¤E%ÝÙ/J“Å;>Íslζ₂θ…•3ô3δ£k` with `C`, optional `Ø`, and some modulos will probably save some bytes. [Try it online](https://tio.run/##yy9OTMpM/f//8I4EvUcNi0wubFJ@1LAw7fDUw8sPbzo87dBOm8PbXQ8tcVU9PPfwTH2vRw1zDrda2x3uLc45t@1RU9O5HY8algH1GR/eUmx8bsuhxdlAzuGeQ0vPbbmw6dzOc7sP73TNPbzs8KLDSw@3H54dBZR91NRyYROQdj42yejoZKCxO8H6lxxuPLRa79BSu@LDK7T8//@PjjbVUUpKS1KK1Yk2NNRRys1PBLJjAQ) or [verify all test cases](https://tio.run/##RU9NT8JAEP0rZI0Xs8HwpQcNHAwXL97dNHFLF2xoKWlBgqdK/LjoBaOJUQ8ioIm3hiiNt0702PAb9o/ULW7Lad6beW/ejOVQVWfRSb@CMvxymEGVfgTzoyx3R8WFt8bdlzrcwRt4cB/4u/BVDcbVdXiGh8197j7BxU4Zbhwj/OSDQTjn7lT4CjBzCuEseG0KAtfBJJwtvNAPv8GvmjCFEUzgCh4PxZQPzheeqHu/w/zPrVjrL/1jOAs@ssGk7MD7xkGEI0JIDiObaUhRcIaQbYwaNmMtSUsYqXUVKZjkhMy0qCoHiQmTPEZ9ZhhWLyYFjHrHeofFuIjRKVNtGuNSYsZkCyNN66zWJP3cKkoYLbMh4VL8P6aaRDI67hldJqG8e4lXFwnS1lvNVE5rCU4PjSVdu20kxGBpUPpAHEr1lpourTGbmnpN/KH8AQ). **Explanation:** ``` ø # Zip/transpose the (implicit) input-list ` # Pop and push the list of Bloons and list of counts separated to the stack .•4в#‡fÕçòÖ¹<÷E¤E%ÝÙ/J“Å;>Íslζ₂θ…• # Push compressed string "redblugreyelpinblawhipurleazebraicermoaddtbfbzombad" 3ô # Split it into parts of size 3 s # Swap so the input-list of Bloons is at the top δ # Map over each Bloon: 3 £ # Leave just its first 3 characters k # Get the index of each in the list of strings •Ì¥δвιλùEmæâåÇÛZ• # Push compressed integer 1001001001006000000012000024057512200 ₄в # Convert it to base-1000 as list: # [1,1,1,1,6,0,0,12,0,24,57,512,200] •Cƒ2œÝù• # Push compressed integer 13492391042348 3ä # Split it into 3 equal-sized parts: [13492,39104,2348] Á # Rotate it once: [2348,13492,39104] « # Merge the two lists together .¥ # Undelta it with leading 0: [0,1,2,3,4,10,10,10,22,22,46,103,615,815,3163,16655,55759] > # Increase each by 1 sè # Index the earlier indices into this list * # Multiply each value by its count O # Sum this list together # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•4в#‡fÕçòÖ¹<÷E¤E%ÝÙ/J“Å;>Íslζ₂θ…•` is `"redblugreyelpinblawhipurleazebraicermoaddtbfbzombad"`; `•Ì¥δвιλùEmæâåÇÛZ•` is `1001001001006000000012000024057512200`; `•Ì¥δвιλùEmæâåÇÛZ•₄в` is `[1,1,1,1,6,0,0,12,0,24,57,512,200]`; and `•Cƒ2œÝù•` is `13492391042348`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 86 bytes ``` IΣE⪪S, ΠIE⪪ι ⎇μ§⪪”)¶⊟S|4ηJ?α8⊕rüQG§﹪⊗βⅉ№8℅jo”9⌕⪪”&⌈⊟²…x⦃P⦄h¿◨T-α~⁶?T÷`´Cgψ↥b·CQq”³…λ³λ ``` [Try it online!](https://tio.run/##RU/LasMwELz3K0xOCqQQxbZS0VMJFHIoBNIfWEuqLbqWhSo1TX7eXSkuFQuzr5kdqQGCmgDn@RSsi@wAX5Gd08jewLOzRxvZ0fkUz5HGPVtvqhUFwSlMOqmF8L9saVrm7yY4CFc2bqqXeHTa/CwbKy53spaNbCXnS@zqHM1e8m0jBRey5qKRXIhWyCcq23YvtvmwzNKv1uk/sWB0h6kP5mrQW9chXAbrU0ADN9MFsMqEcYLuo7tNo9aRRGqSOFwVmsMweYa5QR1cL@95nnmVKZuKV8TLQNw@IwmULugMdLtUmExGMmFcTsgKTpeckaPP@wqokpC5WJbJoseSkdMiU@wWWaB/3PlkHkarHubHb/wF "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S Input string ⪪ , Split on literal string `, ` E Map over substrings ι Current substring ⪪ Split on literal string ` ` E Map over words ⎇μ If second word then ”...” Compressed lookup table ⪪ ³ Split into substrings of length `3` ⌕ Find index of λ Second word … Truncated to length ³ Literal integer `3` § Index into ”...” Compressed lookup table ⪪ 9 Split on literal string `9` λ Otherwise first word I Cast to integer Π Take the product Σ Take the sum I Cast to string Implicitly print ``` 77 bytes using the newer version of Charcoal on ATO by taking the input as a dictionary: ``` IΣEA×ιI§⪪”)¶⊟S|4ηJ?α8⊕rüQG§﹪⊗βⅉ№8℅jo”9⌕⪪”&⌈⊟²…x⦃P⦄h¿◨T-α~⁶?T÷\`´Cgψ↥b·CQq”³…κ³ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PZAxTsMwFIavEmWJkVKpbhK3hglFQuqAhFS2qoPjuI1VJ7Ech9IiTsLSAQQ34QQMvU1fil3rDf__bH9-vz9-eMUMb5k6Hr96ux7NTn9PRjYW5ayzaNHX6JFpNG90b9FNHDzLWnRIxsFl-97Om1K8ooVW0qIQ0wlNaEozirGrSTJUOqV4nFKCCU0wSSkmJCN0BjbLpmQcxkFIQ6A_yKb0MCPKQvUbI_ZCadkUiu0qqXujBDuIwjDJhalbVqyLQ1uXpQVIAoh8z5XIq1aj7dDw6-6zK3jnIn4vw9GLClen3-VbNDCi2wDHQQQspwC5cRLQfpuVTsFsvqd64SSMKhqnYWbV7pyB6bfX44x7DXGsvwu5tPIGEnr8Jal_lMEvXKGQntWSD-599R_rDA "Charcoal – Attempt This Online") Link is to verbose version of code. [Answer] # [Scala](http://www.scala-lang.org/), 162 bytes [Try it online!](https://tio.run/##fZJRT8IwEMff@RQNCUmLF6Xb2inJSPTNBJ@IT8aHbuvmpGzYFQkSPjseE7Y9qH1Y@uv97/53l9WJMupYxe86ceRJFSXZDwhJdUZWCFTZvJ6Se2vV7mXhbFHmr2xKnsvCkYjsj5/KkGy60B8v9LF08KNgr9EMKUqVU9Hs9L3OKpPOdebohO0TVWvqgC6hZiyauavlGAtQzwcf@CQAySX4XAbAgUspJAQQhIDhWwwIEcoJCOAcPEbpQ5GjE63Bl2ws/FHgh6MgGHHBrl2FEXY4EjxrbMuZkmZ0XtSOUg5kaHU6ZHjIzQ3hg99UIapyq3XZ6rzfhQKFcRYPGRDKT7VXlYq7JE/cycG/bWCeh/edNqbaNugjbt8KpxsKkL50bFVDonVAkAhp6lq3W84nf5q1Wbzf8al4tcpbaMpdRCpt75dWm3ez0S2cl3Sm3hQnXBflspemko66ARvhxq5Nh0b3rLvhm0bwz4x7Fom2alUk7Q7C0BMhLuEwOBy/AQ) ``` val f:Seq[(Int,String)]=>Int=data=>data.foldLeft(0){case(t,(k,s))=>t+k*Seq(23,3,104,616,3164,1,16656,4,47,23,816,55760,5,11,2)((BigInt(s,36)*53%437%44%15).toInt)} ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 61 bytes ``` sm*@[616C\/5 816J2K11ZKy8328hZ23KZZ3y52Z3164yJ55760)%Ced8027h ``` [Try it online!](https://tio.run/##Tc3LCoMwEAXQXxGhixahJjYxy4I7/YNYF9FMNTQ@SBWJP28fi8TdPTB37mTnbt/f/eVeUkSzx5UEDNEcFwjxwrIEs47jpOA8sQTzBNGbzQlJaXw@ZSBZjNNvvSxRFIQGZFhFwT/XegGH1gAMTha0HlfHSQ2vQ000XmunZv9lWsykPTUIP7dBbYSTEWqoDxMNGNGrxrkfRe0nnz5vY986SDn7o99W9QE "Pyth – Try It Online") Takes input as a list of lists. The lookup portion could probably be compressed some more but who knows. ### Explanation ``` sm*@[...)%Ced8027hdQ # implicitly add dQ # implicitly assign Q = eval(input()) s # sum of m Q # map lambda d over Q * hd # multiply the first element of d by ed # the last element of d C # converted to int using base 256 and code points % 8027 # modulo 8027 @[...) # modularly indexed into the lookup table ``` [Answer] # [C#](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 123 bytes ``` x=>x.Sum(y=>new[]{616,1,4,0,5,47,3164,104,16656,816,3,23,0,11,55760,2}[y.Key.Aggregate(0,(a,n)=>3*a+n)*75%1847%16]*y.Value) ``` [Try it online!](https://tio.run/##nVRtb5swEP6eX3FFq2S3LgtJgK5pMqVv07RKm5Rq@9D2gwMmRaXAwDShKb89O0NISNtN6ohifOd77p57bOOkB07qLy@y0Dk@8x3pRyFP8uNUJn44ZX4ohwzUCN5gOR8M5/o4eyD5YBiK2fXtwjIsZrAeazOT9WzWNaweM9r4tyzTYoe42mWdLi4bBjNN22qzTnGd699Ero@m00RMuRSkzQhnIR0Mu3t8P6R7trlrHPbsXcO63cv1nzzIBF32W488ASlSCQPA4tAg@5o3bIgT2m8pmD5yXfIC2IwmFBb40xLhagwMKKDA1zvB2JIIEW5X8M578RNvgmhTYdF6iLgyjRWZTsf8ZP1vN2XCXARBNENHZ@WY3flSoN1d2U9iknC0e9sMakKuK9GyKjqHhtF@J5u6oVW6qtvaeooepg2zqrUO5c0@Nl21AB@1joekEVDvw6vGa0fsh/fN9AF3mnatS7NEnCVx0CwSiC1StXZrktwPJ1tFHZHwB9/ZHC/b7pg2atj6nknisfJ4M/B4kArlTSWXvgOPke8CRhyPGJwMSXlVyykgpKF45XMZTKIogCgM8vFdNLvgfpDS1qJsQ92hmKepcPEWtfulz4sSwZ07IGrx/jHGHQOXVl2XYw0U8xhRGFHdyf568QSmkdyY1c6XdTZOmeTr@SatehCLaT2iEuOHgfa3Vlds9wcqTj//naE4BJlQ@IwqHtVNNMPhrVjtx2g81hCgXYy@XmobVLGeOVwqGc7njoiVpiDoPym7wuNZIMkJfZOD0L8IeZXHglD9KhqXohDaLLye@h6Qna0Ng@dn2HnRxd/YnEZhGgVC/5Xgob30Q0E@aB5ZrPQsKBzAQnEqgGDGI7jRFvgubvAcYtrSxjfaVKMvdanGtyooPc/PqszCLT4uXP00ykJZqCTF8g8 "C# (Visual C# Interactive Compiler) – Try It Online") Pretty similar to the existing JavaScript answer. I brute-forced another hash function: ``` y.Key.Aggregate(0,(a,n)=>3*a+n)*75%1847%16 ``` C# has no built-in way to parse base 36 numbers (which the JavaScript answer uses), so I had to use `Aggregate` to get a unique int for each string which worked here (`GetHashCode` returns different values between program executions for strings so can't be used). ``` string | aggregate |*75%1847%16 -------------------------------- red | 1429 | 1 blue | 4070 | 15 green | 12743 | 10 yellow | 41924 | 2 pink | 4406 | 4 purple | 41204 | 13 black | 12131 | 13 white | 13841 | 13 zebra | 13930 | 11 lead | 4216 | 11 rainbow | 119486 | 5 ceramic | 109962 | 7 moab | 4331 | 0 bfb | 1286 | 6 zomg | 4723 | 8 ddt | 1316 | 9 bad | 1273 | 14 ``` ]
[Question] [ The Greatest Common Divisor, or **gcd**, of two positive integers \$x\$ and \$y\$ is the largest positive integer that divides both \$x\$ and \$y\$. The Least Common Multiple, or **lcm**, of two positive integers \$x\$ and \$y\$ is the smallest positive integer that is a multiple of \$x\$ and \$y\$. We define the Least Uncommon Multiple (**lum**) of \$x\$ and \$y\$ to be \$\frac{\text{lcm}(x,y)}{\text{gcd}(x,y)}\$. We define the Least Uncommon Multiple Count (**lucm**) of \$n\$ as the number of positive integer pairs \$x,y\$ such that \$x,y\leq n\$ and \$lum(x,y)=n\$. For example, \$lucm(2)=2\$, as \$lum(1,2)=lum(2,1)=2\$, while \$lum(1,1)=lum(2,2)=1\$. Another example: | \$lum(x,y)\$ | 1 | 2 | 3 | 4 | 5 | 6 | | --- | --- | --- | --- | --- | --- | --- | | 1 | 1 | 2 | 3 | 4 | 5 | **6** | | 2 | 2 | 1 | **6** | 2 | 10 | 3 | | 3 | 3 | **6** | 1 | 12 | 15 | 2 | | 4 | 4 | 2 | 12 | 1 | 20 | **6** | | 5 | 5 | 10 | 15 | 20 | 1 | 30 | | 6 | **6** | 3 | 2 | **6** | 30 | 1 | \$lucm\$(6) is the number of times 6 appears in the above table, which is 6. Thus \$lucm(6)=6\$. ## We define the sequence \$H\$ as follows: \$h\_i=lucm(i)\$ for all positive integers \$i\$. \$H\$ begins as follows: 1, 2, 2, 2, 2, 6, 2, 2, 2, 6... I was playing around with \$H\$, and what caught my interest was the set of numbers for which \$lucm(n)\$ was greater than that of any of the smaller integers. For example, \$lucm(6)=6\$, which is greater than any of the previous values in the sequence. We will call these numbers the Progressive Maxima of \$H\$. The first few progressive maxima of \$H\$ occur at \$n=1,\ 2,\ 6,\ 12,\ 20,\ 30\ldots\$ The challenge, should you choose to accept it, is to write code that calculates the most Progressive Maxima of \$H\$ within 1 minute without any hard-coding of the sequence. ### Scoring Using the following Python code as the reference code: ``` from math import gcd counter=1 prev_prog_max=1 prev_prog_max_val=1 counts={1:1} print(1,1,1) ctr=2 while True: for j in range(1,ctr): q=ctr*j/(gcd(ctr,j)**2) if q>=ctr and q in counts.keys(): counts[q]+=2 else: counts[q]=2 if counts[ctr]>prev_prog_max_val: counter+=1 print(counter,ctr,counts[ctr]) prev_prog_max=ctr prev_prog_max_val=counts[ctr] ctr+=1 ``` Take the number of progressive maxima your code returns in one minute, and divide it by the number of progressive maxima the reference code returns in one minute on your computer. The resulting value is your score. Highest score wins. For example, say my code returned 140 progressive maxima in 1 minute, and the reference code returned 45. My score would be \$\frac{140}{45}=\frac{28}{9}=3.\overline{09}\approx3.1\$. If there is a tie, the earliest answer wins. --- My current best, which I will post as a non-competing answer in a month after the last answer for this question, returned 389 progressive maxima in 1 minute, while the reference code returned 45. My score would thus be \$\sim\!\!8.64\$. I'm completely confident that I've gotten all of the elements of \$H\$ that are less than 1 billion, and pretty confident that I have all such elements under 1 quadrillion (though it took me about 3-4 days of runtime to get them). [Answer] # [Python](https://www.python.org) + [SymPy](https://www.sympy.org), \$119/47\approx 2.532\$ on my computer ``` from sympy.ntheory.factor_ import udivisors def lucm(n): return sum(2*d for d in udivisors(n) if d * d < n) counter = 1 prev_prog_max = 1 prev_prog_max_val = 1 print(1, 1, 1) ctr = 2 while True: count = lucm(ctr) if count > prev_prog_max_val: counter += 1 print(counter, ctr, count) prev_prog_max = ctr prev_prog_max_val = count ctr += 1 ``` The [`udivisors`](https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.factor_.udivisors) function returns a list of [unitary divisors](https://mathworld.wolfram.com/UnitaryDivisor.html) of a number. A unitary divisor of \$n\$ is a divisor \$d\$ of \$n\$ such that \$d\$ and \$n/d\$ are coprime. In fact, for two positive integers \$a,b\$, let \$g=\gcd(a,b)\$, then we can write \$a=gc,b=gd\$ for some coprime \$c,d\$, and we have \$\operatorname{lcm}(a,b)=gcd\$, \$\operatorname{lum}(a,b)=cd\$. Now assume that \$0<a,b\le n\$, \$\operatorname{lum}(a,b)=n\$. Then \$c,d\$ must be unitary divisors of \$n\$, and \$g\le n/\max(c,d)\$. So, for each unitary divisor \$d\$ of \$n\$ (and \$c=n/d\$), there are \$n/\max(c,d)=\min(c,d)\$ corresponding \$(a,b)\$'s such that \$\operatorname{lum}(a,b)=n\$. So the total number of such \$(a,b)\$'s is \$\sum\_{d\ \mid\ n\atop\gcd(d,n/d)=1}\min(d,n/d)\$. This equals to \$\sum\_{d\ \mid\ n,\ d^2<n\atop\gcd(d,n/d)=1}2d\$, except the special case \$n=1\$. [Answer] # [J](https://www.jsoftware.com), \$178/48 \approx 3.708 \$ Based on alephalpha's comment, powered by J's fast prime factorisation. ``` LUCM =: {{+/(<.|.)*/y^|:#:i.2^#y}} main =: {{ 'N C M' =. 1 echo 1 1 1 while. 1 do. N =. N+1 L =. LUCM ^/__ q: N if. L>M do. C =. C+1 M =. L echo C,x:N,M end. end. }} main '' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8GCpaUlaboWNw_6hDr7KthaKVRXa-tr2OjV6Glq6VfG1VgpW2XqGcUpV9bWcuUmZuZBlHCp-yk4K_iqK9jqKRhypSZn5CsYgiBXeUZmTipQTCElX49LQcEPpMBP2xDI9AExwZbE6cfHKxRaKfgBRTPTgIJ2vlDlCkBDgaqcwRoUFHzBWsBMsBXOOhVWfjq-QIHUvBQ9LjABc5a6OsQjUP_A_AUA) The function `LUCM` takes the prime factorisation of a number as the prime powers, e.g. 120 as `8 3 5` (`2^3 3^1 5^1`), and computes the LUCM from that. [Answer] # [Mathematica 13.2](https://www.wolfram.com/mathematica/) ~~112/48~~ 113/48 \$\approx 2.35\$ PyCharm 2020 + Python 3.8 was used for run Python code. Thanks to @alephalpha for the cool math idea, please vote for [his answer](https://codegolf.stackexchange.com/a/259513/114511)! ``` Clear[lucm]; lucm = Compile[{{n, _Integer}}, If[n == 1, 1, 2 Total@Select[Divisors[n], #^2 < n && GCD[#, Quotient[n, #]] == 1 &]]]; TimeConstrained[n = 1; count = 1; max = 0; While[True, res = lucm[n]; If[res > max, max = res; Print[count, " ", n, " ", res]; count += 1]; n += 1 ], 60]; count ``` Some tips for Mathematica speed optimization: * Switch on "Launch parallel kernels" → "At startup" * Use `Compile[]` with type declaration * Use real numbers for arithmetics to avoid long exact integer calculation, but integers for such built-ins as `GCD[]`, `Divisors[]` etc. * In old posts you can find a statement that old-school `Do[]`,`If[]` etc work faster than such built-ins as `Select[]`, `Reap[]/Sow[]` etc. That is not the case at all! * Run your program several times (maybe with small values) before the final trial. Mathematica uses cache ;) * Unfortunately there is no recurrent function for `Divisors[]`, but it is known that Mathematica effectively uses the results of previous calculations [Answer] ## Pythran 206/46 ~ 4.5 on my laptop Please note that this approach is on my laptop limited by available memory; the 206 were computed in well under 1 minute. @alephalpha's method with minor tweaks: * keep lists of primes and decompositions found so far aroundas we are spending the memory anyway a simple sieve is more efficient * use the rather crude bound lumc(n) <= 2^#distinct prime factors x sqrt n for some branch cutting * use Pythran acceleration (this is he most impactful) Code: accel.py (this must be Pythran compiled) ``` from numpy import prod # pythran export resdivsum(int32 [:],int,int,int,int) # pythran export decomp(int32 [:,:]) # pythran export master(int32 [:,:],int,int) def resdivsum(pp,mxdef,thmx,P,Q): if mxdef<0: return 0,mxdef ppp = prod(pp) if ppp*P < Q: ref = 2**len(pp) * thmx out = prod(pp+1)*P return out,mxdef - ref + out elif ppp*Q > P: out = 0 inc,mxdef = resdivsum(pp[:-1],mxdef,thmx,P*pp[-1],Q) if mxdef < 0: return out+inc,mxdef out += inc inc,mxdef = resdivsum(pp[:-1],mxdef,thmx,P,Q*pp[-1]) return out+inc,mxdef return 0,mxdef def decomp(dec): m,n = dec.shape for i in range(2,m): if dec[i,-1] <= 0: ib = -dec[i,-1] or i ii = -ib dec[i,-1] = 0 for j in range(i,m,i): ii += 1 if ii == 0: dec[j,-1] = -ib elif ii == ib: ii = 0 else: dec[j,dec[j,-1]] = i dec[j,-1] += 1 def master(dec,j,mxv): m,n = dec.shape lumc = 0 while lumc <= mxv and j<m: j+=1 d = dec[j] s = d[-1] d = d[:s] thmx = int(j**0.5) mxdef = (thmx<<s-1) - mxv lumc,defct = resdivsum(d,mxdef,thmx,1,1) return lumc,j ``` toplevel script (Python 3) ``` import time from numpy import zeros,int32 from accel import resdivsum,decomp,master # total time tt = 60 r = time.perf_counter() decompositions = zeros((100000000,10),int32) decomp(decompositions) print(time.perf_counter()-r) maxidx = [0,1] maxval = [0,0] n = 1 rm = 1 print(1,1,1) while time.perf_counter() < r+tt: lumc,n=master(decompositions,n,maxval[rm]) if n==len(decompositions): break rm += 1 maxidx.append(n) maxval.append(lumc) print(rm,maxidx[rm],2*maxval[rm]) ``` [Answer] # [SageMath](https://sagemath.org), \$113/35 \approx 3.23 \$ on SageMathCell Based on [@alephalpha's answer](https://codegolf.stackexchange.com/a/259513/110802), made a little change. **Thanks to @alephalpha for the cool math idea, please vote for [his answer](https://codegolf.stackexchange.com/a/259513/110802)!** --- Competition code, [run it online!](https://sagecell.sagemath.org/?z=eJx9kM1ugzAQhO9IvMMoJ0gpaXLooWryFL0jFxuwgg1aG9rH75q_JuqPBQfP7n7rmYo6AydqlQvSvsmNdiW06TvykHrUriMXR4vgtVHab1cjfBNHcSRVhXYoTWLTlzgCH1J-IAs3mOS0l6g6goS2G5E7oSvUpUwsDgfIDDLF-YwjhJXcu-f_FTYN-LIbrFcErsZRT2oseurqwojPX6RiFO0qa-uTY4bwMaj0AXEKROcF-SK4YWU2lbMJMbSzSsm0-KPRrcIbDWqxpVrROyX_n8QjvvnzHFu9G73g-WlBhvNOSlzDwnCZ3DJ8CpTfnG6IuXLBD783qDWrhymCVZ2jWGoZmJrNneltz32w3PRHcYl4Aixv9uvGNfadsnKXfgFKy7Th&lang=sage&interacts=eJyLjgUAARUAuQ==) ``` from sage.arith.misc import divisors import timeit import math def lucm(n): return sum(2*d for d in divisors(n) if gcd(n // d, d) == 1 and d * d < n) counter = 1 prev_prog_max = 1 prev_prog_max_val = 1 print(1, 1, 1) ctr = 2 start_time = timeit.default_timer() while True: elapsed_time = timeit.default_timer() - start_time if elapsed_time > 60: break count = lucm(ctr) if count > prev_prog_max_val: counter += 1 print(counter, ctr, count) prev_prog_max = ctr prev_prog_max_val = count ctr += 1 print("end") ``` Reference code, [run it online!](https://sagecell.sagemath.org/?z=eJx9UstugzAQvCPxD6ucMNC05JBDJPiK3qoIuWEhJjyNSVtV_ffuxkRxFaXLxczOzpgdSt230EpzBNUOvTZQHQrfW85GtaiM7_neoZ87gzpNfG_QeM4H3Vd5Kz_vgPwsGwYvA1P6neySH6aozgRJTI-gntHphlUnI7XJ2QXSxWxdYCnnxqI6EEz7OKoG4VXPuPM9oMJGDhMW_0_CE9z07Zwq_45msH1ZJLneNcqTfS17DTWoDrTsKqSb052FQx1TAsL6OaB1BXSMaxGGG3EjkNWYMQlkV8DIUnYl6xN-TYGrxWV7b-M-4s1cUWwmfES88showchsn92F4cwvIUaczxWzySwd_srYURMuz02dmg9al_wdCUujU2R_FXZbYVesxC_DDbz5&lang=sage&interacts=eJyLjgUAARUAuQ==) ``` from math import gcd import timeit counter=1 prev_prog_max=1 prev_prog_max_val=1 counts={1:1} print(1,1,1) ctr=2 start_time = timeit.default_timer() while True: elapsed_time = timeit.default_timer() - start_time if elapsed_time > 60: break for j in range(1,ctr): q=ctr*j/(gcd(ctr,j)**2) if q>=ctr and q in counts.keys(): counts[q]+=2 else: counts[q]=2 if counts[ctr]>prev_prog_max_val: counter+=1 print(counter,ctr,counts[ctr]) prev_prog_max=ctr prev_prog_max_val=counts[ctr] ctr+=1 print("end") ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/247241/edit). Closed 1 year ago. [Improve this question](/posts/247241/edit) The words "center a" probably give flashbacks to any decent HTML developer. Luckily, we are not working with divs, we are working with matrices. Given a matrix where w=h, and given a "length" to extend it by, make a new matrix and center the old one in it, populating blank squares with the length. For example: ``` m = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] l = 1 OUT = [ [1, 1, 1, 1, 1], [1, 1, 2, 3, 1], [1, 4, 5, 6, 1], [1, 7, 8, 9, 1], [1, 1, 1, 1, 1]] ``` ``` m = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] l = 2 OUT = [ [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 2, 3, 1, 1], [1, 1, 4, 5, 6, 1, 1], [1, 1, 7, 8, 9, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1] ``` I would do more examples but they are tough to type out :/ Notice that each dimension has length\*2 added to it. And that the "empty" space (the new matrix) is populated with the length. Here are the parameters and rules: **Params** * vars / method can be named whatever you want * 0 < m.length < 11 * -1 < m[x][y] < 11 * 0 < l < 11 **Rules** * Input will be `f(int[][] m, int l)` * Output will be `int[][]` * Use the closest thing to a matrix if not available in your language * Standard rules apply * This is `code-golf`, so shortest code per language wins! Good luck :) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 10 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Port of [my APL answer](https://codegolf.stackexchange.com/a/247244/43319). Anonymous tacit infix function taking taking `l` as left argument and `m` as right argument. ``` ∾˘⟜⌽⟜⍉⍟4⍟⊣ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oi+y5jin5zijL3in5zijYnijZ804o2f4oqjCgrin6gKMSBGIDPigL8z4qWKMSvihp) …`⍟⊣` repeat `l` times:  …`⍣4` repeat 4 times:   …`⟜⍉` transpose, then:    …`⟜⌽` flip upside-down, then:     …`∾˘` concatenate `l` to each row of that **Alternatively:** `∾˘` concatenate `l` to each row of… `⟜⌽` the flipped upside-down… `⟜⍉` transpose `⍟4` done four times `⍟⊣` done `l` times [Answer] # [Pyke](https://github.com/muddyfish/PYKE) (non-competing*†*), 5 bytes ``` VQA.X ``` Since the integers are guaranteed to be single digits, I/O are multi-line strings (*†*since the challenge asks for a strict integer-matrix I/O, I've marked it as non-competing). Takes the length as first input, and matrix-string as second. [Try it online.](https://tio.run/##K6jMTv3/PyzQUS/i/38jLiVDI@OYPBNTs5g8cwtLJQA) **Explanation:** ``` V # Loop the (implicit) first input amount of times: # (use the implicit second multi-line input-string) Q # Push the first input again A # Deep apply the following command: .X # Surround the string with this character around it # (after which the result is output implicitly) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes ``` ##~ArrayPad~#2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1m5zrGoKLEyIDGlTtlI7X9AUWZeib5DWrRrcka@voOyDoh2UDaKVXNwcKjmqq6uNtQx0jGu1ak20THVMQPS5joWOpa1tTqGtTr4pI1quWr/AwA "Wolfram Language (Mathematica) – Try It Online") Built-in. Input `[m, l]`. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 64 bytes ``` lambda n,l:(c:=[[l]*(l+l+len(n))]*l)+[l*[l]+e+l*[l]for e in n]+c ``` [Try it online!](https://tio.run/##rYxNDoIwEEb3nKI7ZujEBPAHSThJ6aIgREgdmsrG09eCxhOYWbyXyZfnXut94bJyPoxNG6x5dDcjmGwNfd0oZXUGVsYbGBhRZxalsln8y0HuHBcvBjGxYC374PzEK6Qtp4d5mRjSL5@rB4Pb1mzbbtdu0xGUyqmgUpM60onOkReq6Ko15YiYJJ/mT/4VL2I8vAE "Python 3.8 (pre-release) – Try It Online") It's been a while since I posted a working answer...so feel free to suggest golfs. There are probably plenty of them... ;) Sure enough... thanks @Jitse for -2 bytes. # Explanation Constructs a matrix. First `l` rows: `l` repeated `l+l+len(n)` times (length of n plus the extra, twice). Next `len(n)` rows: `l` repeated `l` times, plus the current row of the matrix, plus `l` repeated `l` times. Final `l` rows: same as first `l` rows. Then I use the walrus operator to save bytes. [Answer] # [R](https://www.r-project.org/), ~~55~~ 48 bytes ``` f=function(m,l)"if"(l,f(t(rbind(1,m,1)),l-.5),m) ``` [Try it online!](https://tio.run/##jYtBCoAgEADvPcPTLmyBRYcCf9EH0lgQdAUxqteb/aDTMDCTa2XDp7jik0CkgMqzgkAMBbL1coCmSBqRQj/MSBErQ9xL9jfodSHJ6TITiUuhwT6fbtiG7k82Yn0B "R – Try It Online") -7 bytes thanks to pajonk. +6 bytes if padding with `l` rather than `1`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ·FøXδ.ø ``` First input is the length, second the matrix. -1 byte thanks to *@emanresuA*. [Try it online](https://tio.run/##yy9OTMpM/f//0Ha3wzsizm3RO7zjf@yh3f@NuKKjDXWMdIxjdaJNdEx1zIC0uY6FjmVsLAA). (Footer `]»` added to pretty-print the output, feel free to remove it to see the actual matrix result.) **Explanation:** ``` · # Double the (implicit) input F # Loop that many times: ø # Zip/transepose the matrix; swapping rows/columns # (which will use the second implicit input in the first iteration) δ # Map over each row: .ø # Surround the row with a trailing/leading X # 1 (as integer, a literal `1` would add strings `"1"`, # so with this the output is cleaner) # (after which the result is output implicitly) ``` If the filler character should be the input-length (as the challenge spec says, but the second test case contradicts), it would still be 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) by replacing the `X` with `¹` (first input): [Try it online](https://tio.run/##yy9OTMpM/f//0Ha3wzsO7Ty3Re/wjv@xh3b/N@KKjjbUMdIxjtWJNtEx1TED0uY6FjqWsbEA). [Answer] # [APL (Dyalog)](https://dyalog.com), ~~16~~ 14 bytes Anonymous infix lambda taking `l` as left argument and `m` as right argument. ``` {⍺⌽⍤⍉⍤,⍣4⍣⍺⊢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR765HPXsf9S551NsJJHUe9S42AWKQcNeiR71ba/@nPWqboPGot@9RV/Oj3jWPerccWm/8qG3io76pwUHOQDLEwzNY81HHDJAYkOyb6hXs7/ffUCFNQT062lDHSMc4VifaRMdUxwxIm@tY6FjGxqpzGeGXBwA "APL (Dyalog Extended) – Try It Online") (Uses Extended because TIO's plain Dyalog is outdated) `{`…`}` "dfn"; `⍺` is left argument and `⍵` is right argument.  `⊢⍵` on the argument…  …`⍣⍺` repeat `l` times:   …`⍣4` repeat 4 times:    `⍺`…`⍤,` prepend `l`, then:     `⌽⍤⍉` mirror the transpose [Answer] # [Haskell](https://www.haskell.org/), 75 bytes ``` f m l=let r=replicate;b=r l$r(length m)1;a=r l 1in map(\x->a++x++a)$b++m++b ``` [Answer] # JavaScript (ES6), 71 bytes *(-6 bytes if we always fill with 1's instead)* Expects `(length)(matrix)`. ``` (n,N=n)=>g=m=>n--?g([q=(m=m.map(r=>[N,...r,N]))[0].map(_=>N),...m,q]):m ``` [Try it online!](https://tio.run/##lYxLCsIwFAD3OcVbvsBLsPUvvHiDXCAEKbUtSpP0I14/Wl25dDkDM/fqWc31dBseKqZrk1vOGMlylGw6DmyiUucO3cgYOOhQDTixcZa01hNZL6Vb@Y@@sLFy0YFGL08h1ynOqW90nzpssZDoBIArCEqCtacFNgRbgt0X9gQHgqMX76n4jcu/4vwC "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` d(∩ƛ¹p¹J ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJkKOKIqcabwrlwwrlKIiwiOynigYsiLCIyXG5bWzEsMiwzXSxbNCw1LDZdLFs3LDgsOV1dIl0=) Port of [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [05AB1E answer](https://codegolf.stackexchange.com/a/247245/80050). If it should be filled with `1`s instead (like in the test cases), then swap the tiny `¹` with a full-size `1` for the same byte count. **How it works:** ``` d(∩ƛ¹p¹J d( # Repeat 2*(length) times: ∩ # Transpose ƛ # For each row: ¹p # Prepend length ¹J # Append length ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes ``` Nest[Thread@*Reverse@*Append[#],#2,4#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773y@1uCQ6JKMoNTHFQSsotSy1qDjVQcuxoCA1LyVaOVZH2UjHRDlW7X9AUWZeib5DerSRTnW1oY6RjnGtTrWJjqmOGZA217HQsaytjf0PAA "Wolfram Language (Mathematica) – Try It Online") -15 bytes from ATT --- Explanation: `Nest[` Repeat the following process `Thread@*Reverse@*` Transpose and reverse (rotate clockwise) our matrix `Append[#],` with the padding variable appended. `#2,` Start with our original matrix `4#]&` and do this four times the padding amount times. Longer version that doesn't rotate the matrix: # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 98 bytes ``` f[m_,l_]:=Nest[{v}~Join~Append[#,v=Array[l&,a+l]]&,PadLeft[PadRight[#,a=Tr[1^m]+l,l],a+l,l]&/@m,l] ``` [Try it online!](https://tio.run/##FcpLCsIwEADQwwjddEBa/0LAbkWkiLthLINNbSCpJYaChPTqMa7e5hl2vTTs1JNj7NA0oBs6iqv8OPRTmM9vNczVOMqhxQVMorKWv6gz4FwTZVBze5Gdw@RNvXqXEou7xeJhKNeg6R8T2fJkErG2anDYofcFlLAK4NewgW1yB3s4hAAlUfwB "Wolfram Language (Mathematica) – Try It Online") Wouldn't be surprised if this gets golfed significantly further than its current state (I suspect it would involve either MovingMap or just Transposing the matrix to do the sides instead of PadLeft/Right), but it works. --- Explanation: `f[m_,l_]:=` Create a function (because of slot collisions) `Nest[` that will repeatedly apply `{v}~Join~` prepending v to our list `Append[#,v=` and appending it, where v is `Array[l&,a+l]]]&` a list of the padding amount, of a size equal to a plus the padding amount. `PadLeft[` Our starting input will be padding the left of `PadRight[#,a=` the right-padded version of the list, padded to length a, `Tr[1^m]+l,` where a is the length of the matrix plus the padding amount, `l],` using l as the element to pad with. `a+l,` The left padding will be padded to length a+l, `l]&` still using element l. `/@m,` Do this padding to each row of our input matrix. `l]` Finally, do the repeated application of the first step l times. [Answer] # [Factor](https://factorcode.org/) + `combinators.extras`, 51 bytes ``` [ dup <array> '[ [ _ 1surround ] map flip ] twice ] ``` Requires modern Factor for `1surround`, so have a picture: [![enter image description here](https://i.stack.imgur.com/x0xuH.gif)](https://i.stack.imgur.com/x0xuH.gif) Here is a version that works on TIO for 3 more bytes: [Try it online!](https://tio.run/##Hc07C8IwGIXhvb/ibE4WvF9xFRcXcSpF0vQrBNM0fknQUvrbY@j28HLgNEL6juPzcbtfj3gTG9IQzKJ3aLiHo08gI8lBdm2ljEhrl9PPs3CwTN73lpXxOGXZgAELLLHCmLTGBttJO@xxSBqxjAXqYHGeHi6YFSjwmpILzF0wNUq0wqLRyib6r5KEMkqhNZxqraa5F5WmPP4B "Factor – Try It Online") ## Explanation * `dup <array>` Create an array of \$l\$ \$l\$s. * `[ ... ] twice` Call a quotation two times. * `[ _ 1surround ] map` Append and prepend a copy of the array to each row of the matrix. * `flip` Transpose. [Answer] # [Julia 1.0](http://julialang.org/), 46 bytes ``` m>n=0<n ? [(a=ones(size(m,2));) m' a]>n-.5 : m ``` [Try it online!](https://tio.run/##fcqxDoIwFAXQna@4m@8larwIDgL1QwhDExlq2iexmqA/X1cnz3xurxg811KSs@HQGy4YxQ93m7Pk8JklbWvVTpE28JOz3b7FGalcQ16if8tIgjV47MAGbMHT5KjV8gj2jCZa/Z3Nzyxf "Julia 1.0 – Try It Online") * can take non-square matrices * recursive function. At each half-step, adds a column of ones to each side of the matrix * output is with floats, +1 byte to have ints [Try it online!](https://tio.run/##fcqxDoIwFAXQna@4m@8larwIDiL1QwhDExlq2hdCIVF/vq5Onvk8txg8X6UkZ/3pZrhjEN@vyzZlyeEzSdrXqp0i7eBHZ4djiytSeYQ8R/@WgQRr8NyBDdiCl9FRq3kJtkYTrf7O5meWLw "Julia 1.0 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` F⁴«FηFθ⊞κθ≔E§η⁰E⮌η§μλη»Iη ``` [Try it online!](https://tio.run/##NYs9C8IwGITn5lfcmBdewY/6Rafi5CAU15Ih1GqKtbVJLYL422NacLk7nrsrjLZFq2vvr62FjAkfEU3RECbvCNnLGXlndJSIKHWuujXypJ8y7Y/NpXxLw5gTY0TnciitK8Ob8a8fjJooABP@X5HZqunlQbs@rCjxPl8wcjHqkrFSLPKYsWZsxrhl7Bh7pZSfDfUP "Charcoal – Try It Online") Link is to verbose version of code. Does not require the matrix to be square. Takes `l` as the first argument for consistency (see below). Explanation: ``` F⁴« ``` Repeat four times. ``` FηFθ⊞κθ ``` Append `l` to each row `l` times. (`FθFη⊞λθ` also works of course.) ``` ≔E§η⁰E⮌η§μλη ``` Rotate the matrix. ``` »Iη ``` Output the matrix in Charcoal's default format (each element on its own line and rows double-spaced). String-based version inspired by @KevinCruijssen's Pyke answer for 19 bytes: ``` NηWS⊞υιUO⁺⊗ηLυθMηηυ ``` [Try it online!](https://tio.run/##HYxJDgIhEEX3nIJlkeCinU0vdWPiQOIJoCUNSQk2Q3t8LN39vLz/BqfTEDW2dg7vWm71ZWyCSfTs4zxaDn/8KMmHEYTgqmYHVXJPxt1gJKqwZjjFatA@6Sn5xYaxkCVoH3UuBMm@xtnCJPmvrShXSOhb61i3XLH1Zst2@wNrixm/ "Charcoal – Try It Online") Link is to verbose version of code. Takes `l` as the first argument. Explanation: ``` Nη ``` Input `l` as an integer (`θ` still contains `l` as a character). ``` WS⊞υι ``` Input the matrix. ``` UO⁺⊗ηLυθ ``` Draw an expanded matrix filled with the character `l`. ``` Mηηυ ``` Output the input matrix in the middle. [Answer] # [Perl 5](https://www.perl.org/), 66 bytes ``` sub f{my$f=[1,(1)x@_];($l=pop)?f($f,(map[1,@$_,1],@_),$f,$l-1):@_} ``` [Try it online!](https://tio.run/##pZLbaoNAEIav61MMi2V3YRIwTXpIsNn7QnPTOxVpGy1po24TAwnis9tZDwiptNAu4izfPwd@HR3ttrOq2h9eIC6Skx27noPCkUcVBgthb12dabmMhR2jSJ41icoO0QlQhRIJ2tuRI@cqLKs42wkL6Hj1GzzKhQnCVYANAG@KMEO47sENwi3CXdARpwnufZdALfqnr2uAaX6O2xHnuB000KTrXdNW/IeDyY8Ohn38JrY@B8Te7YDYe/7DzG9fxpJFfUlOwk7ot6PKDrl0aRsWLVdvWe7GQtWy7CjYlOeuEy3qgh6b7BrTpcV6t0nzGNiIDlzuwUQ/jY46es2j9dxPTS8/pQJzp@CnfsrQuqBaI0H0WfeFJfDsg8Mc@OPqCVYPfGGVltlxGlgwj43fs00qGJpq2uqCe7xBHLlZcDnmAS9pxccsYGX1BQ "Perl 5 – Try It Online") ]
[Question] [ The sci-fi shooter Destiny 2 contains guns which have the ability to regenerate ammunition directly into the magazine **if, and only if** `x` (precision) shots are landed (in a fixed amount of time), returning `y` bullets to the magazine. For example, the perk (ability) "Triple Tap" will return 1 bullet to the magazine if 3 precision hits are landed (`x = 3, y = 1` in this case). A gun may also have multiple perks. **Task** Your task is to take the initial magazine capacity of a gun, and take a list of perks in the form of `x` and `y`s in a suitable format, and return the highest number of shots that could be fired before having to reload the weapon. Input may be in any form suitable (list with magazine capacity as element 0, list of tuples, list/capacity being two different variables etc.) **Examples** ``` Input1 = [4, (3, 1)] # format here is [magazine, (x, y)...] Output1 = 5 Input2 = [6, (3, 1), (4, 2)] Output2 = 23 Input3 = [100, (1, 2)] Output3 = NaN # any version of NaN or Infinity would be fine here ``` A worked example of Input2/Output2 can be found [here](https://tio.run/##y0osSyxOLsosKNHNy09J/Q8EEVYKmXmZJZmJOQpJpTk5qSXFXPlWMKZCYkpKaopCeUZqnoKGsY6hpkJmsUJJUWZ6empRagqXP3aFJjpGaAq5FIAgAgzy/f1BCEoBERfQXAU9PWVsiAtoFFAOxMTAAA) (courtesy of [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) in comments). **Rules** * All values (including magazine size) maybe be zero, but never negative. * Input/Output may be in any suitable form. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins! [Answer] # [J](http://jsoftware.com/), 60 51 bytes ``` (0(i.~+_*1-e.)[+/\@,(*#)$])_1++/@(*0=]|/1+[:i.*./)/ ``` [Try it online!](https://tio.run/##fcuxCsIwFIXhvU9xUKG5SbzJtcUhUCgKTuLgWksHaTEuPoDSV4@ldXY4w/nhe6YV5wOqgBwWHmHalnG8nk9JeRV5NJ2Wbc/UGHerrdJr2rTUiTGuVtpX7ceJaUJkzY5couxyYMzSRH4jhK6h8Z@NXM806@@PF/YYoAQ7GwqUtLRyapYFxXLF@1@Q9AU "J – Try It Online") Feels like there might be a closed form solution, but I didn't find one. So instead I simulate the required number of times, which is bounded (see explanation). Consider `6 f (1 2,:3 4)` where we take the perks as the right argument, as a matrix like this: ``` 1 2 <- y values 3 4 <- x values ``` * `1+[:i.*./)/` 1...<the LCM of 3,4>: ``` 1 2 3 4 5 6 7 8 9 10 11 12 ``` * `]|/` Modded by 3 and 4: ``` 1 2 0 1 2 0 1 2 0 1 2 0 1 2 3 0 1 2 3 0 1 2 3 0 ``` * `0=` Where does that equal 0: ``` 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 ``` * `*` Multiply elementwise by `1 2`: ``` 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 2 0 0 0 2 0 0 0 2 ``` * `+/@` Sum the rows: ``` 0 0 1 2 0 1 0 2 1 0 0 3 ``` * `_1+` Minus 1: ``` _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 ``` * `((*#)$])` Repeat that 6 times: ``` _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 ``` * `[+/\@,` Append the 6 and scan sum: ``` 6 5 4 4 5 4 4 3 4 4 3 2 4 3 2 2 3 2 2 1 2 2 1 0 2 1 0 0 1 0 0 _1 0 0 _1 _2 0 _1 _2 _2 _1 _2 _2 _3 _2 _2 _3 _4 _2 _3 _4 _4 _3 _4 _4 _5 _4 _4 _5 _6 _4 _5 _6 _6 _5 _ 6 _6 _7 _6 _6 _7 _8 _6 ``` + The answer is now the index of the first 0. If there is no zero within 6 repetitions, there there will never be a 0, and we can continue forever. * `0(i.~+_*1-e.)` Find the index of the first 0, and add infinity if there is no zero: ``` 23 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ˜>P*U¹εÅ0`gª¦Xи}.«+<.¥+0k ``` First input as a list of `[x,y]` pairs, second input the starting ammunition. Outputs `-1` for `Infinity`/`NaN`, because 05AB1E doesn't have either. Port of [*@Jonah*'s J answer](https://codegolf.stackexchange.com/a/245630/52210). Thanks to *@DominicVanEssen* for noticing some bugs in my program (previously failed if \$y>x\$; if there were a mixture of both valid and invalid \$[x,y]\$ pairs in the input; and if either \$x=0\$ and/or \$y=0\$). [Try it online](https://tio.run/##yy9OTMpM/f//9By7AK3QQzvPbT3capCQfmjVoWURF3bU6h1arW2jd2iptkH2///R0cY6hrE60SY6RkDSCEiZxsZymQEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhNcUJh1b@Pz3HLkAr9NC6c1sPtxokpB9adWhZxIUdtXqHVmvb6B1aqm2Q/V/nf3S0iU50tLGOYWxsrI5CtBmUowMUNoIIGRoYAAUNYSpgXCNsGnSijYCUKULKCCpljEO1jgFQIhYA). **Explanation:** ``` ˜ # Flatten the (implicit) first input-list of [x,y]-pairs > # Increase each by 1 (edge case for the 0s) P # Take the product of this list * # Multiply it by the (implicit) second input-integer U # Pop and store this value in variable `X` ¹ε # Map over the [x,y]-pairs of the first input-list: Å0 # Convert both to a list of that many 0s ` # Pop and push both lists of 0s to the stack g # Pop the top and get its length to transform it back into an integer ª # Append it to the list ¦ # Remove the first 0 # (an [x,y] pair is now a list of x-1 amount of 0s appended with y) Xи # Cycle-repeat this list `X` amount of times } # After the map: .« # Reduce the list of infinite lists by: + # Adding the values at the same positions together < # Then decrease each by 1 .¥ # Undelta this list with leading 0 + # Add the second (implicit) input-integer to each value 0k # Get the 0-based index of the fist 0 (or -1 if there are none) # (after which the top of the stack is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` I⌕E×θΠEη§ι⁰⁻ιΣEη×÷ι§λ⁰§λ¹θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zL0XDN7FAIyQzN7VYo1BHIaAoP6U0uQQsmKGj4FjimZeSWqGRqaNgoAkEOgq@mXmlxSB@cGkuTBVEt2deiUtmWWZKKkgWpjEHrBGFb6ipCTGqEEha//8fbaajEK1hDJLQUdAw0VEw0oyN/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Takes the capacity and list of perks as separate inputs. Charcoal doesn't have `Infinity` or `NaN` so `-1` is output instead. Explanation: ``` ⌕ Find index of θ Capacity in Eη Map over perks §ι⁰ Perk `x` value Π Take the product × Multiplied by θ First input E Map over implicit range ι Current value ⁻ Subtract Eη Map over perks ι Current value ÷ Integer divided by §λ⁰ Perk `x` value × Multiplied by §λ¹ Perk `y` value Σ Take the sum I Cast to string Implicitly print ``` [Answer] # JavaScript (ES6), 67 bytes Expects `(magazine)(perks)`. Returns `NaN` for ∞. This processes a simulation, one shot at a time. ``` (n,q=0,m=n)=>g=a=>m?n>m--|!q++?g(a,a.map(([x,y])=>q%x?0:m+=y)):+g:q ``` [Try it online!](https://tio.run/##bctBCsIwEEDRvbdwIUzIpKRaXASmPUjoYqhtUJqksSItePeoiAvB9X//wneeu@t5uqkQT30eKEPARBo9BUG1I6baN6H2Sj22ScrGASMXnicAu@DavlDaLY02XtIqhJHOpNzFMMexL8boYIBKgLUHLNtWiM1vOn4T2gr3f0Cp9ZuUnzs/AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` ( n, // n = initial number of bullets q = 0, // q = number of shots m = n // m = number of bullets in the magazine ) => // g = a => // a[] = array of perks, in [x, y] format m ? // if there's still at least one bullet: n > m-- | // if m is less than n (decrement m afterwards) !q++ ? // or q is still 0 (increment q afterwards): g( // do a recursive call: a, // pass a[] unchanged a.map(([x, y]) => // for each perk [x, y] in a[]: q % x ? // if x does not divide q: 0 // do nothing : // else: m += y // add y bullets ) // end of map() ) // end of recursive call : // else: +g // return NaN : // else: q // return the total number of shots ``` [Answer] # [Clojure](https://clojure.org/), 160 bytes ``` #(loop[m %[x & y](apply map vector(for[[a b]%&](cycle(concat(repeat(dec a)0)[b]))))i 0](cond(= 0 m)i(>=(- m)%)(/ 1 0.)1(recur(apply - 1(Math/abs m)x)y(inc i)))) ``` [Try it online!](https://tio.run/##XU1LDsIgEN17ipeYmmGhghp3egNPQFjQKY0YWghWY09f8bMwzuZN3pdDvNyym6hxLdppTiHGpDtU@oEFRkM2pTCiswl3x0PM1MastUVtqoUhHjk44tizHSi75Ao0jmGFFLo2opyHNC9HQwdIdMLT8UDL8lSC1lCQK6FKlG/5u7WEopMdzmtbX4vtIUbyPcO/yiYxo5R9P4SeWuygt1Bl5Zfcf0joHTZ/kpISWr0T0xM "Clojure – Try It Online") Similarly to [Jonah's answer](https://codegolf.stackexchange.com/a/245630/78274), this simulates the shooting process. However, as Clojure's collections are lazy, we do not set any bounds, but cycle through infinite lists of extra added bullets (like `0 0 1 0 0 1 0 0 1...`) until the number of bullets in the magazine `m` reaches zero. When at any stage the magazine is refilled to its maximum capacity, this should go on indefinitely, and in such case Infinity is returned. Note: Clojure version on TIO is probably too old, as it doesn't accept `##Inf` literal. [Answer] # [R](https://www.r-project.org/), ~~78~~ 75 bytes ``` function(a,x,y){b=a;while(sum(x*a)&(a=a+sum(y[!T%%x])-1)<b)T=T+1;T/(a<b)-1} ``` [Try it online!](https://tio.run/##jY4xD4IwEIV3f0WNQVo5YgvIgjVxdHHqZhwKkUAiYGyJEONvx6IJYuJgbri87967u2tXyEZllVa8S@sy0XlVYgkNtOQecxndsvx8wqoucLOQZI4ll06v2sNUWFZzJC4j65gILhwWiSWWRrjsMWzFAfjACJqh1WRgISTYh4CYxsAj/dTzP2NGKfTc4F2Z5mWuW8Q3qKr1pdYK2Qba42Wm/vRS4309Q8d5@mY/8/vt1ykGtLeG3RM "R – Try It Online") Input is ammunition `a`, a vector of `x` hit values, and a vector of the corresponding `y` perk values. Uses either `Inf` or `NA` as "any version of NaN or Infinity" output options... ]
[Question] [ ## Introduction: In my recent [*~~Strikethrough~~ the Word Search List* challenge](https://codegolf.stackexchange.com/questions/243844/s%cc%b6t%cc%b6r%cc%b6i%cc%b6k%cc%b6e%cc%b6t%cc%b6h%cc%b6r%cc%b6o%cc%b6u%cc%b6g%cc%b6h%cc%b6-the-word-search-list) I mentioned the following: > > When I do the word-search puzzles, I ***(almost)*** always go over the words in order, and strike them through one by one. > > > In some cases I do them in reversed order as a change of pace, although that doesn't matter too much right now. When I do them in the correct alphabetical order however, I sometimes already see the word after the one I'm currently searching for. In those cases, I usually 'sneakily' strike through that next word already, before I continue searching for the actual current word. In almost™ all cases, this occurs when both words have the same starting letter, and the next word that I find accidentally is in a horizontal left-to-right direction. #### Brief explanation of what a word search is: In a [word search](https://en.wikipedia.org/wiki/Word_search) you'll be given a grid of letters and a list of words. The idea is to cross off the words from the list in the grid. The words can be in eight different directions: horizontally from left-to-right or right-to-left; vertically from top-to-bottom or bottom-to-top; diagonally from the topleft-to-bottomright or bottomright-to-topleft; or anti-diagonally from the topright-to-bottomleft or bottomleft-to-topright. ## Challenge: Today's challenge is simple. Given a grid of letters and a list of words, output the maximum amount of times what I describe above can occur. We do this with two steps: 1. Find all words from the given list which can be found in the grid in a horizontal left-to-right direction. 2. For each of those words, check if the word before it in the given list starts with the same letter. **Example:** ``` Grid: JLIBPNZQOAJD KBFAMZSBEARO OAKTMICECTQG YLLSHOEDAOGU SLHCOWZBTYAH MHANDSAOISLA TOPIFYPYAGJT EZTBELTEATAZ Words: BALL BAT BEAR BELT BOY CAT COW DOG GAL HAND HAT MICE SHOE TOP TOYS ZAP ``` Horizontal left-to-right words: [![enter image description here](https://i.stack.imgur.com/iqQgZ.png)](https://i.stack.imgur.com/iqQgZ.png) Word-pairs of these horizontal left-to-right words, with its preceding word in the list: ``` Words: BAT,BEAR ← B BEAR,BELT ← B CAT,COW ← C GAL,HAND HAT,MICE MICE,SHOE SHOE,TOP ``` From these pairs, three start with the same letters, so the output is `3`. ## Challenge rules: * As you may have noted above, we only look at the word directly preceding it. For the `BELT` in the example, `BALL`,`BAT`,`BEAR` are all three before it and start with a `B` as well, but we only look at the word directly preceding it (`BEAR` in this case), and the counter would only increase by 1 for the output. * If the very first word in the list is a horizontal left-to-right word, there is obviously no word before it. * The list of words is guaranteed to contain at least two words, and all words are guaranteed to be present in the given grid. * You can take the inputs in any reasonable format. Could be from STDIN input-lines; as a list of lines; a matrix of characters; etc. * You can optionally take the dimensions of the grid as additional input. * All words are guaranteed to have at least two letters. * You can assume each word is only once in the grid. * You can assume the list of words are always in alphabetical order. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the 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](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Inputs: JLIBPNZQOAJD KBFAMZSBEARO OAKTMICECTQG YLLSHOEDAOGU SLHCOWZBTYAH MHANDSAOISLA TOPIFYPYAGJT EZTBELTEATAZ BALL BAT BEAR BELT BOY CAT COW DOG GAL HAND HAT MICE SHOE TOP TOYS ZAP Output: 3 ``` --- ``` Inputs: ABC SRO KAX AB ASK ARB ARX AX Output: 1 ``` --- ``` Inputs: WVERTICALL ROOAFFLSAB ACRILIATOA NDODKONWDC DRKESOODDK OEEPZEGLIW MSIIHOAERA ALRKRRIRER KODIDEDRCD HELWSLEUTH BACKWARD DIAGONAL FIND HORIZONTAL RANDOM SEEK SLEUTH VERTICAL WIKIPEDIA WORDSEARCH Output: 1 ``` --- ``` AYCD EFGH DCBA ABC AYC CB CBA CD EF EFGH Output: 4 ``` [Answer] # [R](https://www.r-project.org/), ~~73~~ ~~69~~ 68 bytes *Edit: -1 byte thanks to pajonk* ``` function(g,w)sum((c(l<-substr(w,1,1),T)==c(T,l))[sapply(w,grepl,g)]) ``` [Try it online!](https://tio.run/##bVDBbpwwFLz3KyxOINFD7t3Ds/0Arw2P2E5ZqKKoWW1XVelmBVlF/fqt7SSHqL3M2Dw8b2aW6@Py9Otwelgu82HdXH9cTvvnn0@n/Fi@FOvld57v8/nL5/XyuD4v@Ut5U94UpS82m33uy7kovq3fz@f5T5gcl8N5Lo/FffFBMs@2RvG@m24JtpJpXkE7OY5giRFo3yqBwt/WbDTGNYQSqL5jzjSChon7ERrWNtBJB6ScAeapV9XYj1BvPcPJczQewcOUlfs842BMVgbyEcOSRCbdaAwo0iRoB5RUB6whvogrEsVx9BQo2gkUNiYcXaAJ@qwoPn1MCFwwF/Jo2CUXwMOf4HREm852F3H379PhK1qvRLDNLBFUlXHAGQirjAJPwDpJUlM3SMGk1eiIpNSMEPsJa6MG1jqlGgK0wMBYba2yaJkmqSRKKyRr0AzO4J1v3ioSegAb00oFNXUpf6Ve85NVE3U@fbOhE2pjEYgxy7tI9u45HAelVY9BKJ7JShc6F81/KhqDE6zqhknB4a0lEUsZIwqeIKqI6AOrBHVUuv4F "R – Try It Online") Function with arguments `g`=grid, as a single string with each line in the grid separated by spaces (newlines would also be fine), and `w`=words, as a vector of individual words. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12 11~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -3 thanks to @KevinCruijssen (take the wordsearch as a mulitline list of characters). ``` =Ḣ¥ƝŻḋẇ€ ``` A dyadic Link that accepts the list of words on the left and the wordsearch (a multiline list of characters) on the right and yields a non-negative integer. **[Try it online!](https://tio.run/##FU45DsIwEOz3TxTrxHGOTTbBi5Dd0yA@QEtDwRtokBANJUVEOhD8I3zE2MWMRiPNsd3sdvsQFvN4eV2/5880j6f5efwd7mGeHu9bCAqJQKGA0riMRFGxgyw6Ga8hZwMGCUrs8kgCbZVpsCVrEO4jnAWPfaipUn3nB8Y6h0YV2HqbGhkYG0mhTAYDjihlc2SzAktlnPBKHJbQpgWLXFnCVF0VrndoagHtJd3SKOj/ "Jelly – Try It Online")** ### How? ``` =Ḣ¥ƝŻḋẇ€ - Link: words W (list of lists of characters); wordsearch P (list of characters) Ɲ - for neighbouring words in W: ¥ - last two links as a dyad - f(left, right): = - left equals right (vectorises) Ḣ - head Ż - prepend a zero -> E = a list of 1s and 0s identifying whether the previous word stated with the same letter. € - for each Word in W: ẇ - is Word a sublist of P? -> F = a list of 1s and 0s identifying whether the current word is in the wordsearch ḋ - E dot-product F ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 58 bytes ``` lambda n,k:sum(a[0]==b[0]*(b in n)for a,b in zip(k,k[1:])) ``` [Try it online!](https://tio.run/##VVJRb9owEH6/X5G3kApNm/YyVeLhYjuJieGo7S5NKEIwYIugAZGgafvzzIbSdopy0d35@7774jv86X7tm6/fDsfzZvB83i1elqtF0PS39@3ppbeYfp4NBksX73rLoG6CJtrsj8Gif0n@1ofetr@dfrmfRdG5W7fdj0W7boNBEIbhUMl4Mq4eCIcc8jjBUWVigZqAMLcjyQSzDymUSpmMBEdKH8GojFFRxbbEDEYZjrlBkkYhWJrIpJyUmA4tiMrGQlmBFiuAGJVywYJnB9@AmEpgruLIgFMKKSrwbC5Y8NLgNT2pe0sDFU4AAGMGxs2X45NPAE0OqN1XP4EvQfFdaCuZ19NEmCTK@GNMSyXREsKYE89pXHAGXOfCEHGeAwkxqUSqZAEjI2VGKDQCKp1rLbXQkBOXXHDN3IBCFUaJR5t5YywvUHPgElMaOw@J9B5Iy4rG1uXaeaIRGCFyeEXdRoRC5nIiHBQK0ty4f8Myb7J0KiJJM@AsxqtpVwMWg88vzUvfXeGn9rCru1743PgnjADq5nDq/AVP23U3/9gPo8Bvhi/71Xhbhhns6rabvwOnP4/1qh/83h9Xc3f6nSOMZheK//ue7Aqewf7U3Vg2vbsbb3tVfks94oPmDOBwrJuu94qOzv8A "Python 3.8 (pre-release) – Try It Online") Takes the grid (`n`) as a string that includes newlines, and the list of words (`k`) as a... list of words. Simple. Find the number of consecutive pairs in `k` that have the same starting letter and where the second word in the pair is in the grid. The grid is a newline string, so if a word is present horizontally, then somewhere in the grid, there is a run of letters equal to that word that is not cut off by any newline. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` WS⊞υι≔⁰θWS«≧⁺∧№⪫υ¶ι⁼§ι⁰ψθ≔§ι⁰ψ»Iθ ``` [Try it online!](https://tio.run/##bY3LasMwEEXXma8wWUngQvZZjWzFj8iRE6kUm25MEmyDUR6W@6D0212JdNcu5sLMXM45ds39eGmGeX7v@uEckMxcJ6vsvTctoTQop7EjUxj0dA04jn1ryCoMbm77v/8Fi6K5PpqHvu0sKYdpDAM0JxJdJmNJfumNJy5fzZJ6cBjw29QMI0GbmdP5g/RhsHLXT0ofpsWv@M9/Dd9QOrMlUTNacqN0Pc@5yFi5q/cS8xi2bINFrRjHgwSJW11kEY/0PoFKCJVKHqNMnkGJNJIvNdMVplCkuIsVykwJBC3LbFOVFSa5Bl5rxoXmqLEGYCiECw2eDv4BTFYQuYuDQSwTSFCAp7nQ4NXgnR7qplJQYwnz09vwAw "Charcoal – Try It Online") Link is to verbose version of code. Takes both grid and list as a newline-terminated list of newline-separated strings. Explanation: ``` WS⊞υι ``` Read in the grid. ``` ≔⁰θ ``` Start with no matching words. ``` WS« ``` Loop through the list. ``` ≧⁺∧№⪫υ¶ι⁼§ι⁰ψθ ``` If the current word is a left-to-right word and its first letter is the same as that of the previous word then increment the count. ``` ≔§ι⁰ψ ``` Save the first letter of this word for the next iteration of the loop. ``` »Iθ ``` Output the final count. [Answer] # [J](http://jsoftware.com/), 36 31 bytes ``` 1#.(0,2=&{.&>/\[)*1#.,@E.&>/@,: ``` [Try it online!](https://tio.run/##ZVBNb9QwEL2/X2GBtNtF2bAtnEIX7fgjiTfeTGq7pEmROKBWiAsHekPw1xe720pFHMbj@Xhv5s3346tyeS@2lViKQmxElWxdCuVdfTx/XZ5tiovt4le5@Pj28@3qTcoUO5OjXVEdV@hlKf5tKarnnuKpDQ93Px@2pbj7@u3HbituK3F2dp/d5a4QxWIplh/KLxerP@Ly0SfQ6bf7XQHvREbnvTbYOyuHfr5i2mt0sqbDHKQhz2Dq4sEqo@JVg8m50LLRxM01gmsVj7OME7U4tNTrQGyDI0QebD0NEzX7CDNHaVw0FGnGWpJzkBSR2ZELkDxBpUwig@YGDTlktvRE5NHIMzNpsilgpgFrrACcv1BAUiGkfTu6wZokKHQgn7y/QU79Bxg/GR@tyvt4ZqprFzJMeessRSb0mnXH/agVtO9MYNa6AxszzKZxdsQhWNsyGU8g5zvvrTceHWurjfYqCTBuDM5cxzYLV91IXkNbarhPGmubNbK3M/cxxT5p5gOCMR2eUM8rYrSdHUyCYmSvQ7qdak@a3r@8wZSGmrppoZWkfAaVc1ASOX4snuoJevwL "J – Try It Online") *-5 stealing dominic's idea of taking the matrix lines as a single space-delimited string* [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes ``` 2lƛvh≈⁰ẋntc;∑ ``` [Try it Online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIybMabdmjiiYjigbDhuotudGM74oiRIiwiIiwiW1wiQkFMTFwiLCBcIkJBVFwiLCBcIkJFQVJcIiwgXCJCRUxUXCIsIFwiQk9ZXCIsIFwiQ0FUXCIsIFwiQ09XXCIsIFwiRE9HXCIsIFwiR0FMXCIsIFwiSEFORFwiLCBcIkhBVFwiLCBcIk1JQ0VcIiwgXCJTSE9FXCIsIFwiVE9QXCIsIFwiVE9ZU1wiLCBcIlpBUFwiXVxuSkxJQlBOWlFPQUpEICBLQkZBTVpTQkVBUk8gIE9BS1RNSUNFQ1RRRyAgWUxMU0hPRURBT0dVICBTTEhDT1daQlRZQUggIE1IQU5EU0FPSVNMQSAgVE9QSUZZUFlBR0pUICBFWlRCRUxURUFUQVoiXQ==) or [run all the test cases](https://vyxal.pythonanywhere.com/#WyIiLCJAZjphOmJ84oaQYSIsIjrhuKJa4bmqxpt2aOKJiOKGkGLhuotudGM74oiRIiwiO1xuxpvDtyRAZjs7IiwiW1tbXCJCQUxMXCIsIFwiQkFUXCIsIFwiQkVBUlwiLCBcIkJFTFRcIiwgXCJCT1lcIiwgXCJDQVRcIiwgXCJDT1dcIiwgXCJET0dcIiwgXCJHQUxcIiwgXCJIQU5EXCIsIFwiSEFUXCIsIFwiTUlDRVwiLCBcIlNIT0VcIiwgXCJUT1BcIiwgXCJUT1lTXCIsIFwiWkFQXCJdLFwiSkxJQlBOWlFPQUpEXFxuS0JGQU1aU0JFQVJPXFxuT0FLVE1JQ0VDVFFHXFxuWUxMU0hPRURBT0dVXFxuU0xIQ09XWkJUWUFIXFxuTUhBTkRTQU9JU0xBXFxuVE9QSUZZUFlBR0pUXFxuRVpUQkVMVEVBVEFaXCJdLFtbXCJBQlwiLFwiQVNLXCIsXCJBUkJcIixcIkFSWFwiLFwiQVhcIl0sXCJBQkNcXG5TUk9cXG5LQVhcIl0sW1tcIkJBQ0tXQVJEXCIsXCJESUFHT05BTFwiLFwiRklORFwiLFwiSE9SSVpPTlRBTFwiLFwiUkFORE9NXCIsXCJTRUVLXCIsXCJTTEVVVEhcIixcIlZFUlRJQ0FMXCIsXCJXSUtJUEVESUFcIixcIldPUkRTRUFSQ0hcIl0sXCJXVkVSVElDQUxMXFxuUk9PQUZGTFNBQlxcbkFDUklMSUFUT0FcXG5ORE9ES09OV0RDXFxuRFJLRVNPT0RES1xcbk9FRVBaRUdMSVdcXG5NU0lJSE9BRVJBXFxuQUxSS1JSSVJFUlxcbktPRElERURSQ0RcXG5IRUxXU0xFVVRIXCJdLFtbXCJBQkNcIixcIkFZQ1wiLFwiQ0JcIixcIkNCQVwiLFwiQ0RcIixcIkVGXCIsXCJFRkdIXCJdLFwiQVlDRFxcbkVGR0hcXG5EQ0JBXCJdXSJd). ## How? ``` 2lƛvh≈⁰ẋntc;∑ 2l # Get a list of overlapping pairs in the (implicit) first input ƛ # Map over them: vh # Get the first character of both ≈ # Are they equal? ⁰ # Push the second input ẋ # Repeat (so if the first characters are not equal, empty string, else second input) n # Push the pair again t # Get the second item in the pair c # Does the other string contain this string? ; # Close map lambda ∑ # Summate ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes ``` &`((.).+).*;.*\b\2.+,\1\b ``` [Try it online!](https://tio.run/##FY29jsIwEIT7eRDEnywdLdU6cZyEDRvwImQrBSBdcc0ViGfjAXixYBfzFTPSN8/f19//ff68P2/skbGdF7fl0qzMZmXWe7OeHtPObLbTz/SY5547Ox7TSaivcbANDSlYR2eB0EGHrnKVnjwic2jF1ST@gsBtJddkNVKLoaVjHUi6wASVsWviGMn3CpfUOlZHSgmwxJyhKHaUAVYiqtxkGWrx8MQotgxFuUb5LNKcGJBo/AI "Retina 0.8.2 – Try It Online") Takes input as two semicolon-separated comma-delimited lists but link includes header that converts from newline-separated for convenience. Explanation: ``` &` ``` Count the number of overlapping matches (except only match once at any given starting position). ``` ((.).+).*; ``` Match a word in the grid. ``` .*\b\2.+ ``` Check that its first letter appears in another word in the list. ``` ,\1\b ``` Check that the word appears in the list. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ü2ε€нË×yθå}O ``` Since there hasn't been a 05AB1E answer yet, I'm gonna post my prepared solution. First input is a list of words; second the grid as a multi-line string. [Try it online](https://tio.run/##Jc6tDsIwEAdw36cg1Sje4LZu3Ue362gJaQkCEgQKgUJgsDwAT4DDkiBAzS88Ay8ydqv65XIf/zscN9v9ru/b96x7/i6P76e9trdT92rvZ@z7FY9AKT6dDNqRBOZBFWp0RBy6MS4JgZKQMG5mUIvgOFPlcUKaDEct6oAzpAfN14xzXqg80rVvEArByiiFyhtKR4ZQWroS20YypxRdEoBywYzKhhd8ZB1krKJgA5gbBWxIyVOnHcjCssRb@j8BC35I@gM) or [verify all test cases](https://tio.run/##NVCxbtswEN3zFQFndelYoAhOJCXRpHUKSVeWLANJ0aIwULBF7RTI0KVrP6Bf0K1rgw7NEu9BvqE/4t7R7nLvdHp899592F6/3rw9fBYmfbzZPXu/2e5enIuL26ttcXaavfu0eUOz4uXi4e7iTODNjqaZ9HR/2P95/vjr79efT/f7b8v999vH3/sfX/BQPNwVh9VqJUpwThTnhDGDBn9Ed/zGgUEe/0rsGRTWDDXklw206oiZMzdSM4YGM0bsjjAExhE6sS7EzJmya8dLhJmaki0rmI@Bl@OUEGxkFRkv6ykNzrGUAqwXUwquIRNjGQdopjTn3QHQBAdTok2mGroB6lmckh4jh9AQYaSNFBVKUQgIlqvPvV9yXbIhKCWp83qbB/k00vbgKZxQBmpsOa@oDMcVDXozYhvzzJMNnFMTtGb54PQiNtS80j4amTm9sabTJMQ9ehUorGx4df@f5abkEaGqXIBySiC9cQYiUjbSVxbbXpFL5a0OiEpZupXW3ahrZ3q6RjCmQdCe@OC89d547SkQKqO08pIu3WjXn9ydbiL5BANXWebCBiVH1FUudTZJFHrOX2SASev1Pw). **Explanation:** ``` ü2 # Create overlapping pairs of the first (implicit) input-list of words ε # Map over each overlapping pair: € # Map over both words: н # Only leave their first character Ë # Check if both first characters are the same × # Repeat the second (implicit) input-grid by that check # (so the grid itself if truthy, or an empty string if falsey) y # Push the pair of words again θ # Pop and leave the last word å # Check if its in the grid (or empty string) }O # After the map: sum to get the amount of truthy values # (after which the result is output implicitly) ``` ]
[Question] [ I'm working on a golf for Java and I need an infinite loop. Obviously, I don't want to spend any more bytes than I have to, especially in such an expressive language. Assuming I have some code I want to run, obviously the baseline is set at `while(1>0)/*stmt*/` or 10 additional characters for a single line and `while(1>0){/*stmt1*//*stmt2*/}` or 12 additional characters for multiple lines. I say additional because the code I want to loop forever (well, forever-ish... I may or may not want to break out of or return from the loop) will have a certain length, and then I must tack on additional characters to make it actually loop. At first I thought this was the best I'd get, but I figured I'd throw it out to the experts to see if they can find a better one. [Answer] ``` for(;;){} ``` It works cause no condition evaluates to always true. Insert the code between the braces. If you only got a few statements you can place them inside the head (the (;;) part. That the loop still runs is caused by when the condition statement is not a boolean it counts as always true. Thanx to @Ypnypn for the reminder [Answer] # 50 bytes ``` interface M{static void main(String[]a){for(;;);}} ``` [Answer] # Java - 60 bytes (complete code) I'm probably not interpreting the question correctly, but this code when compiled and run results in an infinite-ish loop, in that technically it should run forever, but usually it will exhaust the stack memory. ``` public class X{public static void main(String[]a){main(a);}} ``` On Coding Ground it ends quite quickly, on my Windows 7 laptop with advanced virtual memory management, it runs a long time, just making the system slower and slower. [Answer] ``` for(/*init*/;;/*stmt*/){/*stmt*/} ``` To save characters, you can use the init and increment parts of the loop to save a few bytes by using the semicolons. ]
[Question] [ We want to go on a night hike with the youth group, but of course not everyone has their torch, even though we told them we planned to split up. What options are there for group formation if *n* teens have *m* torches with them, but each group needs at least one torch? **Example**: Three teens with torches (`X`) and two without (`x`) can be divided up as `XXXxx` (all together), `XX Xxx`, `XXx Xx`, `XXxx X`, `X X Xxx` or `X Xx Xx`. **Input**: A list in any form with *n* elements from two different symbols, e.g. a string as above `XXXxx` or a list `[True, True, True, False, False]`. It can be assumed that the input is sorted and only contains valid entries. **Output**: A list with all possibilities in a format corresponding to the input in an order of your choice, but without duplicates (`Xx` is the same as `xX`). **Test data**: ``` X --> X Xxxxxx --> Xxxxxx XXxx --> XXxx,Xx Xx,X Xxx XXXxx --> XXXxx,XX Xxx,XXx Xx,XXxx X,X X Xxx,X Xx Xx XXXXX --> XXXXX,XXXX X,XXX XX,XXX X X,XX XX X,XX X X X,X X X X X ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 6 bytes ``` Ooᵐᵗžũ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fmv88x9unfBw6_Sj-46uXFKclFwMlVhw0zjaMJYr2kAHBmE8Q2QWmG2oA4WxEL0A) Takes input as a sorted list of `1`s and `0`s, where `1` means with torch and `0` means without torch. ``` Ooᵐᵗžũ O Set partition; split the input into a list of subsets o Sort ᵐᵗž Check that each subset contains at least one nonzero element ũ Remove duplicate solutions ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œ€.œ€`€€{€{êʒ€àP ``` I/O as a list of `1`s/`0`s for `X`s/`x`s respectively. I have the feeling the first part of the code can be substantially shorter and I'm missing some obvious builtin combinations.. :/ [Try it online](https://tio.run/##yy9OTMpM/f//6ORHTWv0wGQCEANRNQgfXnVqEpA@vCDg//9oQx0QNNAxiAUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCgZF/pYu8V8qhhXkTFo4aFSgoah/drKulwKfmXloBVABX8Pzr5UdMaPTCZAMRAVA3Ch1edmgSkDy8I@F/rYg80QkHD/tzWc1sRxtXW2qtr6hzaZv8/OtowVifaUMcABsE8QyQWKhsMY2MB). **Explanation:**" ``` œ€.œ€`€€{€{ê # Get all unique sorted partitions: œ # Get all permutations of the (implicit) input-list €.œ # Get all partitions of each permutation €` # Flatten this list of lists of lists of 1s/0s one level down €€{ # Sort the values inside the parts of partitions €{ # Sort the parts of each partition ê # Sorted-uniquify the list of sorted partitions ʒ # Filter this list of partitions by: €à # Get the maximum of each part P # Take the product to check if all are truthy # (after which the filtered list is output implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes I'm very prepared for a smarter approach to trounce this! ``` Œ!ŒṖ€ẎṢ€ṢẸƇƊƑƇQ ``` A monadic Link that accepts a list of zeros (no torch) and ones (has torch) that yields a list of the possible partitions. **[Try it online!](https://tio.run/##y0rNyan8///oJMWjkx7unPaoac3DXX0Pdy4CMXYuerhrx7H2Y13HJh5rD/x/uB2kZAZQJvL//2gDHRA0BMFYAA "Jelly – Try It Online")** ### How? ``` Œ!ŒṖ€ẎṢ€ṢẸƇƊƑƇQ - Link: Hikers Œ! - all permutations of {Hikers} ŒṖ€ - list partitions of each Ẏ - tighten to a single list of hiker partitions Ƈ - keep those for which: Ƒ - is invariant under?: Ɗ - last three links as a monad - f(hiker partition): Ṣ€ - sort each group Ṣ - sort that Ƈ - keep those for which: Ẹ - any? (has torch?) Q - deduplicate ``` [Answer] # JavaScript (ES6), 106 bytes *-1 thanks to @l4m2* Expects a string with leading `1`'s for `X`'s and trailing `0`'s for `x`'s. Returns a single string with commas and line breaks as separators. ``` f=(s,o=O=[],p="1")=>s-(q=s.replace(p,""))?f(q,[...o,p].sort())+f(s,o,p+0)+f(s,o,p+1):O[o]||s?"":O[o]=o+` ` ``` [Try it online!](https://tio.run/##RZBBi8IwEIXv/RVDTgkd0/W6Ej3tudeBUrDE1lVKExtZCupv7ybTihPIvHzvzRxybf6aYMeLv28Gd2rnuTMyoDOlqWr0RmyFMvuwkTcT9Nj6vrGt9CiEUodO3rDSWjv0tQ5uvEul8i5No8@/PnKrvsvK1c9nOAjB0rj8mB3nXZUBCBIIXEUBxGBKFWkCrJkSsyUWNdIUXaQUWfw1wD4H2IttCUYNlPILBcbrJJF4b46F6QJuQGvjJ9C7LwDWk9WZ7tz409hfGcDs4RH3RgGfPyt0cUawyRQTCX0ZTu1UdtIqtYth64bg@lb37izjvyX4UvM/ "JavaScript (Node.js) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 96 bytes ``` f=(s,o=[],p="1")=>s-(q=s.replace(p,""))&&p<o[0]+f?f(q,[p,...o])+f(s,o,p+0)+f(s,o,p+1):s?"":o+` ` ``` [Try it online!](https://tio.run/##RZDBasMwDIbveQrhQ7GJ6rTXdm5PO@8qCIEGN@46QuzGYwTGnj2zlZTKYP369EsHfbU/bbTjPXxvB3/t5tkZGdGbusFgxF4oc4pb@TBRj13oW9vJgEIotdmEN1/vmtKdnXxgHVBr7RtVujyOody95F4d4lmIgy8vxWU@1gWAIIHAUVVADKYciWbAmimt9FnwWLYkjTQlK1L2L/3VwH02cC@lxZg0UPYvFBivk0TiuTkF5g84Aa2JS6BnXgCsr2gK7fz43tpPGcGc4DftTQJeh6t0dUOwuSkmEvo@XLvpw0mr1DGZrR@i7zvd@5tMl8vwT83/ "JavaScript (Node.js) – Try It Online") From Arnauld's # [JavaScript (Node.js)](https://nodejs.org), 82 bytes, slow ``` f=(s,o=[],p=s)=>p?(s-(q=s.replace(p,""))?f(q,[p,...o],p):'')+f(s,o,p-1):s?'':o+` ` ``` [Try it online!](https://tio.run/##RY5Bi8IwEIXv/RUhl2YwiXi0kva0570KRTDExK2WTuwUKS771zebKrhzeY/53vDmYu@W3NjFSQ148ikFI0iiaQ8yGgJTx0aQEjdDevSxt86LKDkHaIK4yTZKrTXmLFRlCauw3MqoNlBRU5YVro7FMe3agjG@5/Ipb53fZnGHQgccP6z7EsRMzb4zy4b99671@iyZWyCf91x3w8nPn0E4gF0OOxwIe697PIv8x7L8gfSLceoySYom666Kuoc329f8AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` ⊞υ⟦⟧FS«≔υθ≔⟦⟧υFθ«Fκ⊞υEκ⎇⁼ν⌕κλ⁺μιμ¿⁼ιX⊞υ⊞OκX»»Φυ⁼κ⌕υι ``` [Try it online!](https://tio.run/##RY7PCsIwDIfP7imCpwbqE3jy4MCDONBDQTyUObWs67b@EUX27LWZG56SkC/fL@VD2rKVOsYiuAcLHM4XXGe31gLbmS74o7fK3BkifLLFxjl1N0T1CZrH84VDoHm86kfy19cIs3YvO1ZzOFXWSPtm2z5I7ZjhkCtzpY1G5FDo4FjDQaW@QSTpQt1gxhWHpVji30r10FVW@taSZNymoyEbsiI97lmutK8ssZOjniIDpVBEjEKI1yuunvoL "Charcoal – Try It Online") Link is to verbose version of code. Assumes the input contains `X`s optionally followed by `x`s. Explanation: ``` ⊞υ⟦⟧ ``` Start with all possibilities of `0` elements. ``` FS« ``` Loop over the elements. ``` ≔υθ≔⟦⟧υFθ« ``` Loop over a saved copy of the possibilities and start collecting new possibilities. ``` Fκ⊞υEκ⎇⁼ν⌕κλ⁺μιμ ``` Add the current element to each of the unique lists in this possibility. (If there are duplicates then this doesn't prevent them, it just ensures that they are sorted so that they can be identified as duplicate.) ``` ¿⁼ιX⊞υ⊞OκX ``` If the current element is an `X` then also add it as a new list. ``` »»Φυ⁼κ⌕υι ``` Deduplicate and output the found possibilities. [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=uniq -F`, 114 bytes ``` $X=y/X//;$x=y/x//;say for uniq grep{s/^ +| +$//g;!/xX|\bx+\b| /&&$X==y/X//&&$x==y/x//}sort glob"{X,x,' '}"x(@F*3) ``` [Try it online!](https://tio.run/##Jc3BCoJAFIXhV7mJaKV2jXCjCK1c1TKYhQQJKgPi2MwEVxxfvWnC1flW/5laOWTW@qyckSEWPjmQg3rN0AkJn5G/oZfttCh8QmQg8hH7YofETN1QVDcGAIPAFbaEI5VbZFVCaugH0XgLiykOIVw92l@r4@VgLWNEXzFpLkZlk3t2Ss@p2xtXOs8fmg/l/9sm1Q8 "Perl 5 – Try It Online") It's extremely slow. TIO times out on any input longer than 4 characters. ]
[Question] [ Typically, when we want to represent a magnitude and direction in 2D space, we use a 2-axis vector. These axes are typically called X and Y: ![](https://i.stack.imgur.com/8ahzR.png) This isn't always convenient, however. The game BattleTech is played on a hexagonal grid, and it's convenient for the axes to line up with the sides of the hexagons. To represent velocity, thrust, and other such values, BattleTech uses a 6-axis Thrust Vector, with axes named A-F: ![](https://i.stack.imgur.com/bAPMf.png) Here are a few example Thrust Vectors, all of which represent the following magnitude and direction: ![](https://i.stack.imgur.com/KqxD9.png) * `{ A = 2, B = 1, C = 0, D = 0, E = 0, F = 0 }` * `{ A = 3, B = 0, C = 1, D = 0, E = 0, F = 0 }` * `{ A = 5, B = 0, C = 0, D = 3, E = -1, F = 0 }` This follows from two rules of equivalence for Thrust Vectors: * Adding or subtracting the same value to two opposite axes (A/D, B/E or C/F) leads to an equivalent Thrust Vector: `{ A = 1, D = 1 }` => `{A = 0, D = 0}` * Subtracting a value from two axes with a single axis between them (A/C, B/D, C/E, D/F, E/A, F/B) and adding that value to the axis between them leads to an equivalent Thrust Vector: `{ A = 1, B = 0, C = 1 }` => `{ A = 0, B = 1, C = 0}` It is possible to make a simple Thrust Vector look very complicated by placing value in axes in a different direction than the vector actually points in, which is undesirable. A *Consolidated Thrust Vector* is a Thrust Vector that fulfills the following conditions: * No axes hold a negative value. * There are up to 2 axes with nonzero values. * If there are 2 axes with nonzero values, they are adjacent axes. Of the above example vectors, only the first is Consolidated. **Your challenge is to accept a 6-axis vector (as a 6-element list or other convenient structure) of integer magnitudes, and return an equivalent vector which has been consolidated. There is only one possible solution for any given input.** Test cases: * `-1, 0, 0, 0, 0, 0` => `0, 0, 0, 1, 0, 0` * `1, 0, 0, 2, 0, 0` => `0, 0, 0, 1, 0, 0` * `1, 0, 2, 0, 0, 0` => `0, 1, 1, 0, 0, 0` * `1, 2, 3, 4, 5, 6` => `0, 0, 0, 0, 6, 0` * `1, 0, 2, 0, 3, 0` => `0, 0, 0, 1, 1, 0` * `1, 0, 1, 0, 1, 0` => `0, 0, 0, 0, 0, 0` * `0, 0, 0, 0, 0, 0` => `0, 0, 0, 0, 0, 0` * `0, 0, 0, 0, 0, 1` => `0, 0, 0, 0, 0, 1` * `1, 0, 0, 0, 1, 0` => `0, 0, 0, 0, 0, 1` * `-1, -1, -1, 1, 1, 1` => `0, 0, 0, 0, 4, 0` [Answer] # [Python](https://www.python.org), 78 bytes *-29 from ovs* *-3 from loopy walt* ``` lambda v:-clip(A@v,v@A,0) from numpy import* A=1-abs((r_[:6]-c_[:6])%6*2-5)//2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3_XISc5NSEhXKrHSTczILNBwdynTKHBx1DDS50orycxXySnMLKhUycwvyi0q0uBxtDXUTk4o1NIrio63MYnWTwZSmqpmWka6ppr6-EdTUzWn5RQplCpl5CtHRuoY6BjAYq8MVDeEaIXONkGWNdIx1THRMdcyQZY0RiqEYxDVANRnBNURYBFcMdAcEgWFsrBWXQkFRZl6JRplOmkaZpibE6QsWQGgA) We want a function that returns the indicated number if positive, else 0, for the element corresponding to the black axis. That function is \$\max(\min(x,y),0)\$, where \$(x,y)\$ are the coordinates of the vector's endpoint with respect to the neighbouring grey axes. ![](https://i.stack.imgur.com/Q36UC.png) Each coordinate in each of the six coordinate frames needed for the whole consolidated vector is in turn a linear function of the input coordinates. The linear functions can be combined into two circulant matrices – which is really one circulant matrix and its transpose. [`clip`](https://numpy.org/doc/stable/reference/generated/numpy.clip.html#numpy.clip) is abused here with negation to implement \$\max(\min(x,y),0)\$. \$-x\$ is clipped to bounds \$-y\$ and 0, and then * if \$y\ge0\$ normal clipping occurs and \$\max(\min(x,y),0)\$ is returned at the end by reversing the negation. * if \$y<0\$, `clip` is coded in NumPy to always return the upper bound of 0. But this is what we want, since \$\min(x,y)\$ will be negative regardless of \$x\$ and \$\max(\min(x,y),0)\$ will be 0. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes ``` UMθ⁻ι§θ⁺³κ≔✂θ¹χ²ηUMθ∧﹪κ²⁻ι⁻Ση⁺⌊η⌈ηIEθ⌈⟦⁰⁻ι§θ⁺³κ ``` [Try it online!](https://tio.run/##hU7LCoMwELz3K3LcQApq6akn8dRDQPAoOQSVGsyjNab49@mqodBTl4UdZoaZ7UY5d07qGLl8Vs4YaXt4McKVDR4UI@Vyt/2wblytkbowMlGc26n0Xj0sNFp1wybnuBkjBWVkRPk3r8TDXR@0g@nwfBsO0AQDI00lSCmTCC7XhOnRW8/KLlBJvwB27M8mS5v9f1zsITG2mznft2AExasQ8fzWHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` UMθ⁻ι§θ⁺³κ ``` Subtract each element from its opposite. ``` ≔✂θ¹χ²η ``` Get alternate elements so we can find the median (calculated below as `⁻Ση⁺⌊η⌈η`). ``` UMθ∧﹪κ²⁻ι⁻Ση⁺⌊η⌈η ``` Subtract the median from the alternate elements and zero out the other elements for now. ``` IEθ⌈⟦⁰⁻ι§θ⁺³κ ``` Reverse any negative elements and output the result. Example for given test case of `0, 1, 1, 2, 3, 5`: 1. Subtract each element from its opposite, resulting in `-2, -2, -4, 2, 2, 4`. 2. Take alternate elements, resulting in `-2, 2, 4`. The median is `2`. 3. Subtract `2` from the alternate elements, resulting in `0, -4, 0, 0, 0, 2`. 4. Reverse the `-4`, resulting in `0, 0, 0, 0, 4, 2` which is the final answer. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` y1Ǔ-:∆ṁ-:N1ǔY0v∴ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ5MceTLTriiIbhuYEtOk4xx5RZMHbiiLQiLCIiLCIxLDIsMyw0LDUsNiJd) Port of [*Neil's* Charcoal answer](https://codegolf.stackexchange.com/a/258428/116074). ``` y # uninterleave 1Ǔ # rotate left by one - # subtract : # duplicate ∆ṁ # median - # subtract : # duplicate N # negate 1ǔ # rotate right by one Y # interleave 0v∴ # elementwise maximum with 0 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ι`À-DÅm-D(Á.ιDd* ``` Port of [*@AndrovT*'s Vyxal](https://codegolf.stackexchange.com/a/258497/52210) and [*@Neil*'s Charcoal](https://codegolf.stackexchange.com/a/258428/52210) answers, so make sure to upvote them as well! [Try it online](https://tio.run/##yy9OTMpM/f//3M6Eww26Lodbc3VdNA436p3b6ZKi9f9/tKGOkY6xjomOqY5ZLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/czsTDjfouhxuzdV10TjcqHdup0uK1n@d/9HRuoY6BjAYqxMN4Rkh8YyQ5Ix0jHVMdEx1zJDkjOEqoRjIM0AxE8EzhNsAUwm0HoLAMDYWAA). **Explanation:** ``` # e.g. input=[1,2,3,4,5,6] ι # Uninterleave the (implicit) input-list into 2 parts # STACK: [[1,3,5],[2,4,6]] ` # Pop and push both inner lists to the stack # STACK: [1,3,5],[2,4,6] À # Rotate the top list once towards the left # STACK: [1,3,5],[4,6,2] - # Element-wise subtract the values in the lists from one another # STACK: [-3,-3,3] D # Duplicate this list # STACK: [-3,-3,3],[-3,-3,3] Åm # Pop and push its median # STACK: [-3,-3,3],-3 - # Subtract that from each value in the list # STACK: [0,0,6] D( # Create a negative copy # STACK: [0,0,6],[0,0,-6] Á # Rotate that list once towards the right # STACK: [0,0,6],[-6,0,0] .ι # Uninterleave the two lists to a single list # STACK: [0,-6,0,0,6,0] Dd* # Convert all negative values to 0s: D # Duplicate this list # STACK: [0,-6,0,0,6,0],[0,-6,0,0,6,0] d # Check for each value whether it's non-negative (>=0) # STACK: [0,-6,0,0,6,0],[0,0,0,0,1,0] * # Element-wise multiply the values in the lists # STACK: [0,0,0,0,6,0] # (after which the result is output implicitly) ``` [Answer] # [Wolfram Language (Mathematica)], ~~150~~143 bytes ``` (a=#;h=(a+a[[#1]]*RotateRight[{-1,1,-1,0,0,0},#1-#2])&;Do[a=h[i,1],{i,4}];Catch[Do[If[AllTrue[a,NonNegative],Throw[a]];a=h[i,3],{i,6,1,-1}]])& ``` [Try it online!](https://tio.run/##NY4xC8IwEIV3/0ZAqp7QWO0SCoouLiLF7bjh0LQJ2AZK1KHkt8e2Ise94R3vfdewN7phb@8cqyImXAhlioRXjCgk0bJ0nr0ubW089msJEgZJxwkg5FpsaDFXJ4dcGLQgCXoL20DqyP5ucDicKzw8n7fupZHh4tqLrgfcWxPcTOc@yETqF86mcD4hAo298drZ1u@rfS9hAxlsYQd5mP3dktuHa86t17Xuxu/SFIYNkFP8Ag "Wolfram Language (Mathematica) Try It Online") I' did something looks like Python Parcly Taxel' answer, but it' s uncompetitive. So I just start to play with equivalent transformations. If we apply four times function ``` tr1[arr_,i_]:=(a=arr;d=arr[[i]]; a[[i]]=0; a[[Mod[i+1,6,1]]]+=d; a[[Mod[i+2,6,1]]]-=d; a) ``` for `i = {1,2,3,4}` we get array `{0,0,0,0,x,y}`, but where `x, y` could be negative. And if we start going backwards from `i=6` with ``` tr2[arr_,i_]:=(a=arr;d=arr[[i]]; a[[i]]=0; a[[Mod[i-1,6,1]]]+=d; a[[Mod[i-2,6,1]]]-=d; a) ``` than sooner or later we will get the array of the required type. *No later than 6 steps* but I haven't found out exactly when, and had to apply the condition. Try to improve the answer later ]
[Question] [ You are given a string of unknown length that contains a varied amount of `(`, `{`, `[` and their respective closing parentheses (in this context all referred to as *brackets*). With one exception, all the brackets are all balanced, meaning an opening one has a corresponding closing one somewhere afterwards in the string. The brackets *may not be* "interpolated" with each other, i.e. opening bracket **b** which is inside opening bracket **a** must close *before* bracket **a** closes, so `([)]`, `{[(]})`, and `({[(])}())[()]` are invalid, but `([])`, `{[()]}`, and `({[()]})()[()]` are valid. ### Challenge The task is, inside the string there is a single unbalanced bracket, i.e. an opening bracket that does not have a closing one. You must insert the closing bracket where it is the **farthest distance apart** from the opening bracket, but not interpolated with other brackets, then return the modified (or new) string. ### Test cases `^` added to point out where a bracket was added. ``` "(" --> "(**)**" ^ "[(]" --> "[(**)**]" ^ "{[({}()([[[{}]]])]{[]}}" --> "{[({}()([[[{}]]])**)**]{[]}}" ^ "[[[]]" --> "[[[]]**]**" ^ "{[[]([(()){[[{}]()]})]}" --> "{[[]([(()){[[{}]()]}**]**)]}" ^ ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. ##### Difference from "possible dupes": 1. [This one](https://codegolf.stackexchange.com/questions/77138/are-the-brackets-fully-matched) only wants to see if the brackets are matched; nothing else 2. [Quite similar](https://codegolf.stackexchange.com/questions/50873/fix-the-braces-etc), but in that question is the possibility that one must add multiple braces, which I would approach quite differently in answering [Answer] # Python 3, 185 167 154 bytes This is probably more golfable, but I figured I'd try a more logical approach than the brute force attempts of the other answers: ``` def M(a): *u,b,f="",lambda s:s.translate(")] } "*25) for x in a: if x in"([{":u+=x, elif x!=f(y:=u.pop()):b+=f(y);*u,_=u b+=x return b+f(str(*u)) ``` Edit -18 bytes: saved some space with a for loop, and found a better solution to adding a potential missing closing bracket to the end of the string than the `if` I was using. (Bonus: this code can be made to work for an arbitrary number of unclosed brackets, at a cost of only +8 bytes, by changing `b+=f(str(*u))` to `while u:b+=f(u.pop()`) Edit -13 bytes: all thanks to some clever golfs by @ovs [Try it online!](https://tio.run/##ZVBLS8QwEL73V4yBhcluKagIEsnBg972InuLQbJtioXaljygS@lvr0n2QdFQEuab7zGd4eS@@@7xeTCL09ZZ4DBlEA5BwghSkp8rgTLUAqm8IpPAaUaKQohpllJSOQk5z4H1r3NtXb2EkMktvis/IVEgUjolXYiaw5f8/ndkbOXZvFS6hj0qyjLY@vyY15yQvFU/x0qBZbZwRnW2VU4joRJmINuHJ5pB3RsYoelABSE0dSoIiokwv@NjnEm3Eb7jNZ4Y98XQD2ECdtxFgL6EsC/uAy0AYwZGO2@6UNRoncGtp3Rp@H1mfVlqG9d6MF5nMTbuOSanfbP08yPfYyxpqgbTdA7JIfI2DYPb2djP7m0cdOl0FRKtbx1L4GvpvGrh4wJFJoENNnk0TZcV8Zb5SM8ZzS4M9zfsMmxB0kI4XwnDNqyGM61WTaurglyc0pJWVHb14e8qiLJVgr1po6zrb5ErewuDsjb5L78) ### Ungolfed code + Explanation Instead of brute force checking each combination, this program loops through the string, and wherever it finds a closing bracket that doesn't match the last unclosed opening bracket, it adds the missing closing bracket. ``` def M(a): u=[] ## List being used as a stack holding the unmatched brackets b="" ## Result string that gets built up f=lambda s:s.translate(")] } "*25) ## Lambda that swaps each opening bracket for its closing version for x in a: ## loop through the characters in the input if x in "([{": ## "pop" the first char to x, check if its an opening bracket u.append(x) ## if so, just push it onto the list of unmatched brackets elif x!=f(y:=u.pop()): ## if its a closing bracket, check if it matches the most recently opened bracket b+=f(y) ## if it doesn't, add the bracket that would close that one u.pop() ## and then pop the bracket x actually closes b+=x ## stick this loops x onto the output a=a[1:] ## because you cant .pop() a str in python, we dont actually remove the first char until here b+=f(str(*u)) ## if theres anything left unclosed, flip it and stick it on the end return b ``` [Answer] # x86-64 machine code, ~~26~~ 24 bytes ``` AA 04 01 0D 01 C3 31 C0 50 AC A8 0B 7B F2 59 88 0F AE 75 FA E3 EF EB F1 ``` [Try it online!](https://tio.run/##ZVJNb9swDD2Lv4LzEFRq3CAtth6cZYdt1112GqDo4Mhy4sKRDEvpnBj@6/MoZwn2AQgURT6@RxLSTfOw03occ39Ajt8SDotd7bZ5jSW4jPng/BZYXhSY1yk@AltsT8Hgslt@SaN9BJOx1gQoM9a5Fk3epdEAa45@jy15PmO1KyJNMD5MPFT4CdhL49CBzljjGmw11RzcK8q2qFSKugbmdR7LXqxBTRdBzmjIOTTo4ZwxEAmKFZgumNZi8jnB/tVVBZZc7/MW71vjj3UgLmdJ@BLzYoUTyPGrdyZvAHhbWV0fC4MffCgqt9h/BPizMnZPDRkvFa6xT3iSYiK5ilcveT9wwaWU/aCUEqqXahgmhJTqN0YqLjkXop9QXKiBTjKsoLIBD3lluYAeWEl75H8pY4Y3dQGMMGzKXAaUT@@f1YpiJb9OHER8Ny0RlzyZeZx5aoESF8AlewyRhN9t7F0MDHAr2Nivud5Xce@uMFkS07HHjgZfpniiZ@Gwv8Jxtnz6TvynNedH66udNcXU@r1wQnbzuaIF4499VRv8H4Fz4n2zxn8T56h6k@CzCuPX82JjSaqj5DCOP3VZ5zs/Phye35GhX7wmvKl/AQ "C++ (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string; and the address of the input, as a null-terminated byte string, in RSI. The starting point is after the first 6 bytes. -2 with some overlapping of instructions. Note the binary representations of the brackets' ASCII codes: ``` ( 00101000 ) 00101001 [ 01011011 ] 01011101 { 01111011 } 01111101 ``` In assembly: ``` o: stosb # (For left brackets) Add AL to the output string, advancing the pointer. add al, 1 # Add 1 to AL. .byte 0x0D, 0x01 # These two bytes combine with the next two instructions # to produce 'or eax, 0xC031C301'. # The effect on AL (which is the low byte of EAX) is # to set its low bit to 1. # This produces the corresponding right bracket. e: ret # Return. f: xor eax, eax # (Start here) Set RAX to 0. push rax # Push RAX onto the stack. s: lodsb # Load a byte from the input string into AL, advancing the pointer. test al, 0x0B # Set flags from its bitwise AND with binary 1011. jpo o # Jump if that has an odd number of 1 bits -- true for left brackets. c: pop rcx # (For right brackets and 0) Pop from the stack into RCX. # The low byte is the expected character for balanced brackets. mov [rdi], cl # Add that byte to the output string. scasb # Compare that byte with AL, advancing the pointer. jne c # Jump back if they are not equal, to continue popping. jrcxz e # Jump, to return, if RCX is 0. jmp s # Jump back to process the next byte. ``` [Answer] # [Python 3](https://docs.python.org/3/), 167 bytes ## Golfed Code ``` def f(s): S="";B="a" for c in s+B: if c in"({[":S+=c;B+=c elif abs(ord(c)-(b:=ord(B[-1])))>2:B=B[:-2];S+=chr(b+(1,2)[b>40])+c else:B=B[:-1];S+=c return S[:-1] ``` [Try it online!](https://tio.run/##XYvBqoMwEEX3fsWQ1QxWeNqulHSRX3A5zKKxhgpFJdrFI@Tbfal9FFoIgTvnnPl3vU3jcduuvQOHC9UZtFqpxmh1URm4yUMHwwhLbhICqyd/RcNFKZTm4HaqMLCq21x3jUlfAv09oYtd8Kl3VFg6V7XRhuuikuZp3jzaHMtDRWzPpx@h/NUt/b9XvrwMfL8@/AjtfttmP4wrOlSoiLL3YpSPHRhDREJmDlFESAJLjJ8Ns3xXLMiIRGHvkCSml5ztDw) Note that TIO has an old version of Python which doesn't allow assignment expressions, so the linked code is slightly longer than the real code. ## Explanation Similar to the [other python answer](https://codegolf.stackexchange.com/a/245353/110951) in its basic approach - instead of brute forcing, it loops through the string, adding in the missing bracket when it finds a closing bracket that does not match the last unclosed opening bracket. However, the code is quite different. * `def f(s)`: Defines a function that accepts a parameter `s`, which will be the input string. * `S="";B="a"`: Creates two variables `S` and `B`. `S` is the new string with the extra bracket inserted, which gets added to in the `for` loop. `B` is a string to store unclosed opening brackets. An extra character gets added to `B` (I chose `"a"` but it could be anything) because an extra run of the loop must be done to check if there is an unclosed bracket at the end of the string, and this would cause an error if `B` were empty. * `for c in s+B`: Loops through the characters in the input string. An extra character is added to the end of the string so that an extra run of the loop is done at the end. This is to check if there is still an unclosed bracket at the end of the string. Since `B` is currently equal to a string with one character, `s+B` can be used instead of e.g. `s+"a"`, saving two bytes. * `if c in"({[":S+=c;B+=c`: If the current character is an opening bracket, adds it to both `S` (the new string), and `B` (the string of unclosed opening brackets). * `elif abs(ord(c)-(b:=ord(B[-1])))>2:B=B[:-2];S+=chr(b+(1,2)[b>40])+c`: Only gets run if the current character is not an opening bracket (in which case it is of course a closing bracket). `abs(ord(c)-(b:=ord(B[-1]))>2)` is `True` if the closing bracket does not correspond to the last unclosed opening bracket. This is because the ASCII codes of closing brackets are always either 1 or 2 larger than those of their corresponding opening brackets (`ord("(")==40`, `ord(")")==41`, `ord("[")==91`, `ord("]")==93`, `ord("{")==123`, `ord("}")==125`). The `b:=` also assigns the ASCII code of the last unclosed opening bracket to a variable `b`, used later in the line to determine which closing bracket should be added. This is the bit TIO complains about, because it was only added in Python 3.8. `B=B[:-2]` removes the last two characters of `B` (the list of unclosed opening brackets). `S+=chr(b+(1,2)[b>40])+c` adds the missing closing bracket, and then the current character, to `S` (the new string). This once again uses the ASCII codes of the brackets. * `else:B=B[:-1];S+=c`: Only runs if the character is a closing bracket, and it matches the last unclosed opening bracket. `B=B[:-1]` removes the last character from the `B`; `S+=c` adds the character to the new string. * `return S[:-1]`: Returns the new string. Due to the extra run of the loop, it will have an extra character at the end. The `[:-1]` removes this character. [Answer] # [J](http://jsoftware.com/), 80 bytes ``` [:;@({~a:i:~<@(rplc&(,_2;&''\'()[]{}')^:_)@;"1)[:,/')}]';&.(1&|.)"0 1/<\,.<@}.\. ``` [Try it online!](https://tio.run/##jZFBS8QwEIXv/RXDHDoz0Ga3HtMqBcGTJ6/T7CLLLq4IingQYvav17S0rrCtNhBI3st8mbw8t2joANcWCDJYg40zN3D7cH/Xqi1r9qdHe7Snqub3t5ddytn2qkyJGmJR5wPJxm6lLrEQtdmKJDgqU8NF@mUE11CsqiYzVR1MY1pJ9runV4ilBLmFQ1zRICmLG0VlN8pe2QcWVlUfnHMizqsLYTx64Q/2SFWN4g@3253J6liZRXxfG@8PsfwX@dLv7CTZfx4/iBJkhJmR5zeALJjAf2OTYHwt/oHpglkA6kgzYeBAmstyCX2i7S5MnG@7T34huu99Mu5z79O/he03 "J – Try It Online") Simple approach: * Construct every possible solution: + Insert each of `)`, `]`, and `}` into every possible position. + This turns out to be verbose because J lacks an "insert at" verb. * For each candidate solution, repeatedly reduce it by replacing `()`, `[]`, and `{}` with the empty string. + Valid solutions will have reduced to the empty string. * Of the valid solutions, pick the one whose insertion point was farthest to the right. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;⁶ȧ®ṪOịʋ;ɼȧ$e?€“] } )” ``` A monadic Link that accepts a list of characters (from `(){}[]`) and yields a list of characters (with one of `)}}` inserted/appended), **[Try it online!](https://tio.run/##y0rNyan8/9/6UeO2E8sPrXu4c5X/w93dp7qtT@45sVwl1f5R05pHDXNiFWoVNB81zP3//79SdXR0rEa0hoamJpBVXRuroRlbC0RKAA "Jelly – Try It Online")** ### How? Forms a string by keeping open *brackets* and closing the last, as yet unclosed, open *bracket* when a close *bracket* (or the end of the string) is encountered. ``` ;⁶ȧ®ṪOịʋ;ɼȧ$e?€“] } )” - Link: list of (){}[] characters, A: ;⁶ - concatenate a space - will be identified as a closing bracket later “] } )” - set the right argument to "] } )" € - for each in the augmented A: ? - if... e - ...condition: exists in "] } )"? ʋ - ...then: last four links as a dyad: ȧ® - logical AND with the register Ṫ - tail (last, as yet unclosed opening bracket) O - ordinal ị - index into "] } )" (1-indexed & modular) - gives the matching closing bracket $ - ...else: last two links as a monad: ɼ - apply to register (initially 0) ; - concatenate ȧ - logical AND (to get back the single bracket) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 101 bytes ``` +T`()[]{}`d`\(\d*\)|\[\d*]|{\d*} \(\d*(?=]|}|$) $&) \[\d*(?=\)|}|$) $&] {\d*(?=\)|]|$) $&} T`d`()[]{} ``` [Try it online!](https://tio.run/##PYwxCsNADAR7vcOYVfyGkE@40y2cwSnSpAjpdHr7RTkbg5DQzLKf5/f13npf1go1etS9FpT9VrQVy8vmuUMGxOPOFm1SmWaV4RNl9GQUvxAPFLJm5dHdO8SQIYMHFGbmQVLpxgjJn39rhAGqPjyUkfMD "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` +T`()[]{}`d`\(\d*\)|\[\d*]|{\d*} ``` Repeatedly substitute matched brackets with digits, where matched brackets are either `()`, `[]`, `{}`, or any of the three pairs separated by an arbitrary number of digits, e.g. `[()]` would be substituted twice, first to `[01]`, then to `2013`. ``` \(\d*(?=]|}|$) $&) \[\d*(?=\)|}|$) $&] {\d*(?=\)|]|$) $&} ``` Find an unmatched bracket and insert its match. ``` T`d`()[]{} ``` Substitute matched brackets back from their digits. ]
[Question] [ # NDos' Numeral System NDos' numeral system is a numeral system invented by me. It represents every nonnegative integer by a binary tree. Given a nonnegative integer \$n\$: * If \$n=0\$, it is represented as the empty tree. * Otherwise, the tree has a root. With the binary expansion of \$n\$: + The left sub-tree of the root recursively represents the **length** of least significant consecutive `0`s of \$n\$ (trailing `0`s). + The right sub-tree of the root recursively represents the more significant side of \$n\$ split right before its least significant `1`. In other words, the right side is the number with its trailing `0`s and their leading `1` stripped off. For example, if \$n = 1100100\_2\$, there are two trailing `0`s, so the left sub-tree will be \$2\_{10} = 10\_2\$. Without the trailing `0`s and their leading `1`, \$ n \$ becomes \$1100\_2\$, so the right sub-tree has that value. For illustrative purposes, here are the full representation of the trees for \$n=1\_2\$ through \$n=1110\_2\$: [![NDos' numeral system](https://i.stack.imgur.com/KUtOK.png)](https://i.stack.imgur.com/KUtOK.png) Note that the numbers of nodes is not monotone. The smallest counterexample is \$10010\_2\$ and \$11000\_2\$. Here's a Haskell implementation of conversion between binary and NDos': ``` import Data.Bits data NDosNat = Zero | Push1 !NDosNat !NDosNat deriving (Eq, Show) intToNDos :: Int -> NDosNat intToNDos x | x < 0 = error "intToNDos: Negative input" | x == 0 = Zero | otherwise = let lSZN = countTrailingZeros x in Push1 (intToNDos lSZN) (intToNDos (shiftR x (lSZN + 1))) nDosToInt :: NDosNat -> Int nDosToInt Zero = 0 nDosToInt (Push1 lSZN mBS) = shiftL (shiftL (nDosToInt mBS) 1 .|. 1) (nDosToInt lSZN) ``` (I couldn't convert from nor to `Integer` because of Haskell's poor bit manipulation API.) # Objective Given a nonnegative integer, treat it as represented in NDos' numeral system, and output its horizontal mirror image. # Examples Here are some mappings. All numbers are in binary: ``` 0 ↔ 0 1 ↔ 1 10 ↔ 11 100 ↔ 111 101 ↔ 1000 110 ↔ 110 1001 ↔ 10000000 1010 ↔ 11000 1011 ↔ 100000000 1100 ↔ 1110 1101 ↔ 1000000 ``` # Rule **The input and the output must be integers natively supported by your language.** [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` f=lambda n,b=0:n and[f(n/2,b+1),f(b)*2+1<<f(n/2)][n%2] ``` [Try it online!](https://tio.run/##VY7BDoIwDIbve4pejJtO3HY0zBcxHiBIXAJlgR3g6bGdivHU9v//r21c0nNAt66t76q@bipAXXtzQaiwubUSz07XR6t0K2t1cEdblllU9xvu3H0NfRzGBNMyCdEOI3QBHxCQhWJKTcCLAECrAR14kAGTnMkYQ5RKg1PA0MwEk8UUu5Dkvjxd90oR2RPZM0lH6QkujvU40ibaC96zT7/mAzTY1QDhYITN1Qr7Fix335b7j28MRbeM4dDPMdk1P/s9/gcyv23O01/gBQ "Python 2 – Try It Online") Takes in a non-negative integer and outputs the "mirrored" integer. Use the recursive relation: If the left and right subtrees are `a` and `b` respectively, then the mirrored number will have `f(b)` and `f(a)` as left and right subtrees. To calculate `a` and `b`, I simply divide `n` by 2, then increment `b` by 1 until `n` is odd. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes -5 bytes borrowing some tricks from [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/241231/9288). ``` f(n,t=valuation(n,2))=if(n,(2*f(t)+1)*2^f(n>>t++)) ``` [Try it online!](https://tio.run/##FcpLCsMwDIThqwxZWbECsfuALuKLhBa8STEEVwSl0NO78m7@j5F8lOktrW2usi7fvJ9Zy6daRaKldHZx3JySDzTGl0FK6j1RyyL7z1VMCXKUqjaHHgPsRMRYZ0ZgRMaVcWPcGQ@TrsbBPFye1P4 "Pari/GP – Try It Online") [Answer] # x86 32-bit machine code, ~~29~~ 27 bytes ``` 51 0F BC C8 74 13 D3 E8 D1 E8 E8 F1 FF FF FF 91 E8 EB FF FF FF 41 F9 D3 D0 59 C3 ``` [Try it online!](https://tio.run/##XZFfT8MgFMWfy6e41iyBrVv2J/FhrL747LuJMwultMUwukCrncu@uvWy6Zy@APcc7o8DyHEpZd/faitNmytY@SbX9aS6J38ko7P/mtO2DBrZbESDVdY2arOh1KlyJ9yWzhhjoG0DBQ2jYJwIvwVK4rWdlKbOhIFibYsl7FpfgZIdh8wXYZGAEli9foCyOQdfuSAkIM1VMeMghUEGh05W5VXfj4xhz1jfSA5Oml8KcvHcenf2nWp4TDAgCUm3QttzZFdK3F4JB8MhFm@MHEgUnA5SmCaw5yR6r7RRQDtYpTC7YySKdvgyTUHjgYY4wdt3oxFDdkQuzto@Cllpq0DWuVrGwT0hcc5rOPzsg8F0/oSMfUppa70urcpPeYasYM/IfWH8CN8J9nCDhO5hEWgXAsUU2b5Rnq0tkrpg4nVbZ8NpR9L3n7IwovT9eLuY44B/lGKvMl8 "C (gcc) – Try It Online") Uses the `regparm(1)` calling convention – argument in EAX, result in EAX. -2 by making the function preserve ECX, removing the need to save it for the recursive calls. Assembly: ``` .global f f: push ecx # Save ECX onto the stack. bsf ecx, eax # ECX := position of lowest 1 bit in EAX (= left subtree number). jz e # Jump to the end if EAX was 0, which will return 0. shr eax, cl # Shift EAX right by the number from above, removing the trailing 0s. shr eax, 1 # Shift EAX right by 1 more, removing the first 1. # (Now EAX holds the right subtree number.) call f # Recursive call; apply the function to the right subtree number. xchg ecx, eax # Exchange the value in ECX (the left subtree number) # with the value in EAX (which is f(the right subtree number)). call f # Recursive call; apply the function to the left subtree number. inc ecx # Add 1 to f(the right subtree number). stc # Set the carry flag to 1. rcl eax, cl # Rotate EAX together with the carry flag left by CL, # which is 1+f(the right subtree number). # This appends to EAX a 1 and f(the right subtree number) 0s. e: pop ecx # Restore the value of ECX from the stack. ret # Return. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes -4 bytes thanks to @att. ``` f@0=0 f@n_:=(2f@#+1)2^f[(n/2^#-1)/2]&[n~IntegerExponent~2] ``` [Try it online!](https://tio.run/##Vcm9CsIwFEDh3ae4ECgtpiS5/oBCJYuDm@AYUgmS1A69SskgiH31mIKL4/nO4OLdDy72N5dS0LKRi6Dpum9KDJotVYVtMCUJbFmtKoG2MDSdKPrOj8fX80Ge4oQ2nceeovmNS8zVGcYBLdQH@OdgmJ2PhQKEhrfkoHJzWHPYcNhy2GWZNbPKrlaf9AU "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES6), 45 bytes A port of [Surculose Sputum's Python answer](https://codegolf.stackexchange.com/a/241230/58563). ``` f=(n,b=0)=>n&1?f(b)*2+1<<f(n/2):n&&f(n/2,b+1) ``` [Try it online!](https://tio.run/##fc5BDoIwEIXhvafoinQE6QxLA3oIT0CREgyZEmi8fk1c6tPdLL788x79s9@HbV7TSeN9zDl0VivfMXUXLeQarKdjU0rbBquuobMWxfuqfCmUh6h7XMZ6iZMNlj0bY6hO8Za2WSfbEBnnDB8@nUAn346hQ5AhRFKQZAYrBUcZvRccZRhmYRjG9k8ajoZtgfR3Or8A "JavaScript (Node.js) – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), 50 bytes It is unclear what the *arbitrary-length integers natively supported by* JS exactly are. Here is a version assuming that's BigInts. ``` f=(n,b=0n)=>x=n&1n?f(b)-~x<<f(n/2n):n&&f(n/2n,-~b) ``` [Try it online!](https://tio.run/##fc5LDoIwFIXhuavoiPQmPG4ZGoqLcAUUKcGQWwPEMGLrFeNMj8zO4Mufc2@ezdxOw2PJJNy6GL3VkjrLQrZerSRGLl47yra1qryWohQ6S5J8ZpptjmIbZA5jl4@h116zY1FKUb6E6zIN0uuSSBWF4tM3NBiaX/hOAojkTpFE1EDKDJ6aP1lGD4zgLMM0722YxvgoDo/juoH2IB5f "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` UME⊕N&ι±ι⊞Oυ∧ι×⊕⊗§υ⊖L↨ι²X²§υ÷κ⊗ιI⊟υ ``` [Try it online!](https://tio.run/##VY69DsIwDIR3nqKjIxUJWJkoXSrx04EXCI1FLZqkSpyWtw8JqlRxiy3f3Sd3vXSdlUOMVzmerdbSKEgrNKZzqNEwqrSPgW9BP9GBEGVREc/k8ZSiVBY3fElGIJGtNvj@PqKTbB2EslgyD9Lo/5i1Dc8hzRM3RuEnZ2tc7QuaF/dQSY@5fxA/Jb6d0xOHBF57jeGaJlII7wRZuCQWHTetI8Nwlp6htSOEfIxxv4vbafgC "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Calculates all of the mirror images from `0` to `n` inclusive and outputs the last one. ``` UME⊕N&ι±ι⊞Oυ∧ι ``` For each integer `0` to `n`, calculate the maximal power of 2 that is a factor of it, or `0` for `0`. For each of those powers of 2, if the value is `0` then just push that, otherwise push... ``` ×⊕⊗§υ⊖L↨ι²X²§υ÷κ⊗ιI⊟υ ``` ... the result of looking up the number of trailing zeros, doubled and incremented and multiplied by 2 to the power the result of looking up the original value integer divided by the doubled power of 2. ``` I⊟υ ``` Output the last of the calculated values. ]
[Question] [ Scala isn't a very commonly used language around here. Most of those who know it like it[citation needed], but some go `:\` when they encounter its user-defined operators, saying they're too complicated. However, they're governed by a very simple set of rules, outlined [here](https://docs.scala-lang.org/tour/operators.html). Their precedence depends on the first character. Here's the list for that (highest to lowest precedence): ``` * / % + - : = ! < > & ^ | (all letters) ``` So this ``` a + b ^? c less a ==> b | c ``` would be the same as this ``` ((a + b) ^? c) less ((a ==> b) | c) ``` Your task is to turn such an expression (only infix applications) into a tree-like structure or a string with all the sub-expressions in parentheses. ## Input A string or multiple characters given as an argument to a function, read from STDIN, given as command-line arguments, or using one of the other [default input methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes#tab-top). This string is the expression to be parsed. ## Output You could do one of the following, printed to STDOUT, returned from a function, or one of the other [default output methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes#tab-top): * The same string but with parentheses outside each sub-expression (the outermost expression may or may not be parenthesized). E.g., `expr op expr2 op2 expr3` -> `(expr op expr2) op2 expr3`. If you wish, you may also parenthesize the atoms (`(((expr) op (expr2)) op2 (expr3))`) * A multidimensional list, where each expression would broken up into the left argument, the operator/method, and the right argument. E.g., `expr op expr2 op2 expr3` -> `[['expr','op','expr2'],'op2','expr3']` * Some tree-like structure equivalent to the above 2 representations. You get the idea. ## Rules * All operators used are binary, infix, and left-associative. * Parsing goes from left to right. * There will always be one or more spaces between arguments and operators. * Operators may consist of any of the symbols mentioned above (`*/%+-:=!<>&^|`) and uppercase or lowercase letters(`[A-Za-z]`). They will be one or more characters. * Arguments to methods may be other expressions or alphabetical identifiers (`[A-Za-z]`). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! ## Test cases More coming soon ``` Input -> Output a -- blah /\ foo -> a -- (blah /\ foo) same ** fst *^ chr *& operators -> ((same ** fst) *^ chr) *& operators Lots Of SpAceS // here -> Lots Of (SpAceS // here) Not : confusing * At / ALL iS it -> (Not : ((confusing * At) / ALL)) iS it This *isnot* valid ** Scala -> (This *isnot* valid) ** Scala ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 59 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḳ¹ƇµḊm2ZḢeⱮ€ØẠṭ“*/%“+-“:“=!“<>“&“^“|”¤i€1ỤḢḤ+-,2œṖ⁸W€2¦ẎµÐL ``` A monadic Link accepting a list of characters which yields a list containing the bracketed expression as nested lists of `[expr, op, expr]` where `expr` and `op` are lists of characters. **[Try it online!](https://tio.run/##y0rNyan8///hjk2Hdh5rP7T14Y6uXKOohzsWpT7auO5R05rDMx7uWvBw59pHDXO09FWBpLYukLACYltFIGFjByTUgDgOiGseNcw9tCQTqMvw4e4lQDMe7liiratjdHTyw53THjXuCAfKGB1a9nBX36Gthyf4/D/cfnTSw50z/v9XUFBIVNBWSALScfYKyQr2cQopQHZOanExWMrW1g4oWaOQDAA "Jelly – Try It Online")** ### How? ``` Ḳ¹Ƈµ...µÐL - Link: list of characters, E Ḳ - split at spaces Ƈ - keep those which are truthy under: ¹ - identity (falsey for empty lists) µ...µÐL - repeat the monadic link (below) until no change occurs Ḋm2ZḢeⱮ€ØẠṭ“...”¤i€1ỤḢ - link, wrap three at highest precedence operator: list Ḋ - deueue m2 - mod-2 slice -> gets operators Z - transpose Ḣ - head -> first characters of operators ¤ - nilad followed by link(s) as a nilad: ØẠ - letters "A..Za..z" “...” - ["*/%","+-",":","=!","<>","&","^","|"] ṭ - tack -> ["*/%","+-",":","=!","<>","&","^","|","A..Za..z"] € - for each (1st character): Ɱ - map accross (the lists of characters) with: e - exists in? i€1 - first (1-based) index of 1 in each (0 if no 1 found) Ụ - grade-up (list of 1-based indices sorted by value) Ḣ - head - continued below... Ḥ+-,2œṖ⁸W€2¦Ẏ - ...continued Ḥ - double -> index, I, of operator in original list -,2 - [-1,2] + - add -> [I-1, I+2] ⁸ - chain's left argument, the list œṖ - partition (the list) at indices ([I-1, I+2]) €2¦ - apply to the secod element (the [expr, op, expr]) W - wrap in a list Ẏ - tighten ``` [Answer] # JavaScript (ES6), ~~180 ... 155~~ 152 bytes Returns a multidimensional list. The outermost expression is parenthesized, and so are the atoms. ``` f=(i,a=i.split(/ +/))=>"w | ^ & <> =! : +- */%".split` `.some(p=>a.map((s,j)=>i=!!s.match(`^[\\${p}]`)&j?j:i)|i)?[f(i=a.splice(i),a),i.shift(),f(a,i)]:a ``` [Try it online!](https://tio.run/##ZdFNj9owEAbgO7/iJWrRTAjJnTYgDr1UaPeQ3vgQXq@9MQo4it2tqtLfTh2H7RZ1bhk/eT22j@JVONmZ1s/O9lldr7okk4nS5K5tjKcC04K5XCQ/cMEeE3xeoBxjjukMafExGdgBh9zZk6K2XIj8JFoilx3Db6Ycj11oeFnTYb/Zbj/8an/vDjw5Lo9zwxfDy40mU4qYIxUZzgRnYffaaE@caRKZ4d1cXD9tRkAiMMUT9ktINMo5CJTlInQukEmGWEUBoug4Qh5k34uWe8x9mBMnhTSFdh7pHrLukE5gW9UJbzvXB8awfxzfIN/JYbLZDE@NqFFst9DWvs3zXiEsKrqxXsVB1ta7sP6oI6valVRVr2vVqVtM@IoqGLoHMeHB@vAo0p71d2fOL0ix8iiwWq9hKhgfUvqjDIzoHvIgmQfb532rjUNq3Nn6FK@iMc/9BVRSNCJ5Pw39z/ivG@1GubbdFxHe3iHcfNjU2UbljX2hr9XjQ@58F0Yw@idpchzq@gc "JavaScript (Node.js) – Try It Online") ### How? This is a recursive algorithm. At each iteration, we look for the **last operator** with the **lowest precedence**, split the expression at this position and process recursive calls on both resulting parts. We stop the recursion when we reach an atom. In order to split the expression and isolate the operator, we use a combination of `splice()` and `shift()` as shown in the following example, where integers are used instead of operators and operands. ``` a = [ 0, 1, 2, 3, 4, 5, 6 ]; i = 3; i = a.splice(i); // --> a[] = [ 0, 1, 2 ] (left expression) // i[] = [ 3, 4, 5, 6 ] (operator + right expression) i.shift(); // --> operator = 3 // i[] = [ 4, 5, 6 ] (right expression) ``` ### Commented ``` f = ( // f is a recursive function taking: i, // i = input string on the 1st iteration, // and then some non-empty array a = i.split(/ +/) // a[] = input string split on spaces ) => // NB: operators are expected at odd positions "w | ^ & <> =! : +- */%" // this string describes the groups of operators, // from lowest to highest precedence .split` ` // split it .some(p => // for each pattern p: a.map((s, j) => // for each string s at position j in a[]: i = // update i: !!s.match( // see if s matches p; the '\' is required for `^[\\${p}]` // 'w' and '^', and harmless for the other ones ) & j ? // if there's a match and j is odd: j // update i to j : // else: i // leave i unchanged ) // end of map() | i // make some() succeed if i is a number ) ? // end of some(); if successful: [ // build a new array consisting of: f( // the result of a recursive call ... i = a.splice(i), a // ... with the left expression ), // i.shift(), // followed by the operator f( // followed by the result of a recursive call ... a, i // ... with the right expression ) // ] // end of new array : // else: a // just return a[] ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 111 bytes ``` ,2,`\S+ {$&} ~(K`*/%¶-+¶:¶!=¶<>¶&¶\^¶|¶\w )L$`.+ +0`{([^{}]+)}( +[$&][^ {}]$* +){([^{}]+)}¶{($$1)$$2($$3)} {|} ``` [Try it online!](https://tio.run/##RY3PToMwAMbvfYrPpCPQbuLmbXEzO3mQ6AFvMEKHRZogXWjVA8PH6gP0xZCd/C6/fH@Sr5dWdWI9LcKnclpulmWecjLQYCS/4XPJ4oV3K@7d1rubnXcPe@8C7/LCu8uMHxIltLzlhN@VQ5gVw3jk0RiCZzQ4ZgVmTxl49N95N4SUriNKNzPvo5EMl5FMeTgvonmQR4SuJwGOE4pHVGilMRDY7fZzckFFBFYrnFrRIM5Ra02M@JRgDLWxYAWqpgcLoM@yF1b3hiTaGgCvNa5Kz4dKpohjNLKX5EVbbFHprv4yqvsAw8EixiFJoFIoS94aZcCU6bRl@Bater9@pZVoxR8 "Retina – Try It Online") Link includes test cases and a parenthesis-removing footer. Explanation: ``` ,2,`\S+ {$&} ``` Wrap only the variables in braces. ``` ~( ) ``` Evaluate the enclosed stages and execute the result as a script on the wrapped input. ``` K`*/%¶-+¶:¶!=¶<>¶&¶\^¶|¶\w ``` Temporarily replace the input with a list of character classes. Note that -+ in particular is in that order because of the way character classes work. The character classes are listed in descending order of priority. ``` L$`.+ ``` Loop over each character class in the list. ``` +0`{([^{}]+)}( +[$&][^ {}]$* +){([^{}]+)}¶{($$1)$$2($$3)} ``` Find the first operator beginning with that class, wrap its parameters in parentheses, and wrap the subexpression in braces. ``` {|} ``` Remove the now enclosing braces. The actual generated code looks like this: ``` +0`{([^{}]+)}( +[\w][^ {}]* +){([^{}]+)} ``` Match a braced term, then the operator, then another braced term. ``` {($1)$4($5)} ``` Wrap the terms on both sides of the operator in parentheses, and wrap the subexpression in braces. Previous 126-byte version accepted any character not one of space, parentheses or previously defined operator character as an operator of the highest precedence: ``` .+ ($&) ~(K`a-z¶|¶\^¶&¶<>¶!=¶:¶-+¶*/%¶^ () L$`.+ +0i`\(((([^ ()]+ +){2})$*[^ ()]+)( +[$&][^ ()]$* +)([^()]+)\)¶(($$1)$$4($$5)) ``` [Try it online!](https://tio.run/##LUxLToNAAN3PKZ7JlMwniBjdNNKGVRcSXeCuU8KUgkxCwBR0oeix5gBzMQTr27y877kcTKvDacV2@XQtCaMeJz/sMdf@p7Ojsypz1nP2YePsVeTs2llfOiuClbMZGCcJzeeZvDG5YjP2i3mQkPzr9ptT8a85g9xT73CRVMz5XP1LFHeWMUpDTundzPecT3yXk0yxUS2Hl9KoOCU0nDQkjsi2KLDNcEJT9j00omgz2yMKouH7ODa6RqBQdR1JuqEH8FxhQfoWF2WKIEBdnkvy1A1Yo@ja6r037SsE4gEB4iSBSWEG8lKbHsL0bTcIfOjGnCAE0kI3@hc "Retina – Try It Online") Link includes test cases and a parenthesis-removing footer. Explanation: ``` .+ ($&) ``` Wrap the entire expression in parentheses. ``` ~( ``` Evaluate the remaining stages and execute the result as a script on the wrapped input. ``` K`a-z¶|¶\^¶&¶<>¶!=¶:¶-+¶*/%¶^ () ``` Temporarily replace the input with a list of character classes. Note that `-+` in particular is in that order because of the way character classes work. The character classes are listed in ascending order of priority. ``` L$`.+ ``` Loop over each character class in the list. ``` +0i`\(((([^ ()]+ +){2})$*[^ ()]+)( +[$&][^ ()]$* +)([^()]+)\)¶(($$1)$$4($$5)) ``` Find the largest possible sub expression that contains an operator beginning with that class and wrap both of the arguments in parentheses. The actual generated code looks like this: ``` +0i`\(((([^ ()]+ +){2})*[^ ()]+)( +[a-z][^ ()]* +)([^()]+)\) ``` Match a `(`, then an even number of terms, then a term, then the operator, then any remaining terms, then a `)`. ``` (($1)$4($5)) ``` Wrap the terms on both sides of the operator in parentheses. [Answer] # [Perl 5](https://www.perl.org/), ~~292~~ ~~149~~ 137 bytes (last 12 bytes lost with tip from Nahuel Fouilleul in comments below) ``` sub{$_=pop;s/ +/ /g;for$o(qw(\*\/% +- : =! <> & \^ | \w)){1while s/\S+ +[$o]\S* +\S+/push@s,$&;"$#s,"/e}1while s/\d+,/($s[$&])/;/.(.*)./} ``` [Try it online!](https://tio.run/##ZZNPc9owEMXv/hRbIoxkyyikzcWOiXNP2wO5YWAckIM7xnItkT9D3K9O13KGJBMODPv2p93nJ1PLprw87l6A5PFR7@8PZBXXqo60AF@AeIhy1RBF/z7R1EvFEPwAQoi/wdUUXEiX8ArpE2OHydO2KCVokc588OdELdKZBz5Wot7rbaI5caMBOdN8IGT7Tm98LijRc@IumIjEmI49NhbtMXLOVLkJoXO0e6Gk4IniScOHikXDOt5l9YEUvh91PyhZcVKwVtdlYYRo0esrLNEeekSnYefZE0PWPQq10AAGHB@SHSr5bKDIfZ8UwwvXtVYbTlYRURhEiwusU5oodiD1QYzFNXHD83aKBVHzYLKI/51E1y0zbaK3ITg/Ua0tFE5sk1VMWd9Eu3b89YiOxn9UUdEBkBV66sytJfaDC37BxiM2ClFH2zivkY@y0TJREWaiTQO4gE94MGmdvZZwJ7UJw5@qkZGze0kMll1K8z6UVPvBFL/Egj80sv4mlmeCv7Uqwa@uRqPIySAI4L7MtiBSXKrgyyeYgoXoB4o5OttJ8DzItQFvCettA54LqpZNZlSj@3OUfsDYG8c@gc6tMh39O7fLZvXNWs5ACNjKRp4MWAgR@rnPnF/K4F2vVZXvdVE9gAc3BgTc3N5CMYPC9DZ6itLPHOtBxnrUudsWGrxCV8p48JiVxaZzPltnZfYeBf1KsROGafpwD8trWEMptcbg4niKyisK7yOoxZjlWA92mkVZxzLH6V5be6Hs4HTn7P@hqjmRzzWLE3xbT/KDMix2SW4B1uuFtrrF8c6bojL5ANt7E8Iw@H7ZRQ7Yk2sjN53049xKeAYrPeCnZdzOj5zW2ahKrjpLGGDkHP8D "Perl 5 – Try It Online") ``` sub { $_=pop; #put input string in $_ s/ +/ /g; #trim away unneeded spaces for $o ( #loop through operators qw(\*\/% +- : =! <> & \^ | \w) #...in order of precedence ) { 1 while s/\S+\s+[$o]\S*\s+\S+ #find first such operator and /push@s,$&; "$#s," #replace its sub-expression with /ex #a tag of id plus comma #and continue until no more #of current operator } 1 while s/\d+,/($s[$&])/; #replace all tags with their #subexpressions, now in parens /.(.*)./ #remove first+last char, return rest } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~82~~ ~~68~~ 67 bytes ``` ≔⮌Φ⪪S ιθF⪪⁺“ ∨μ[Ek✂◧‽_U⁹�A\”α.«W⊖Lθ¿№ι↥§§θ⊖κ⁰⊞θE³⊟θF²⊞υ⊟θWυ⊞θ⊟υ»⭆θι ``` [Try it online!](https://tio.run/##TZDNSsRAEITP5inagNKj2YnozagQFGFhxWDwKoRsJxkcJ5P5WQX12WMmLtE@dB@q@qOouqtM3VdyHHNrRavwiXZkLOG9kI4MlloKh2ulvSudEapFlkAM8bQFm9bAsqjpDeyNhfQW45P0iK9O@SU/vOZXN/yYv/AvHidQhV8eMwaf0cF7JyQB3lFt6I2Uoy1uSLWuw4FNDtEA3vZeORQJPGtNpq6mWLlbqy19LHdI4D/hNWQ6YwFQeNsF@aHSeJFA0esZnAFJSzBnPt@7/CJnSy7/RwiaD9p3VEwVOPxtIoCHuYZsHDe9swDw2ECYUuc1lZCm0JGhaFzt5A8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs the Python representation of a nested list. Explanation: ``` ≔⮌Φ⪪S ιθ ``` Split the input string on spaces and filter out empty strings (corresponding to runs of spaces). Reverse the result, so that the list can be processed by popping terms from it. ``` F⪪⁺“ ∨μ[Ek✂◧‽_U⁹�A\”α.« ``` Concatenate the compressed literal string `*/%.-+.:.!=.<>.&.^.|.` with the uppercase alphabet, split on `.`s, and loop over each character class. ``` W⊖Lθ ``` While there are operators left to process: ``` ¿№ι↥§§θ⊖κ⁰ ``` Does the uppercased current operator start with a character in the current class? ``` ⊞θE³⊟θ ``` If so then extract the operator and its parameters into their own sublist, and then push that list back as the left parameter of the next operator. ``` F²⊞υ⊟θ ``` Otherwise move the operator and its left parameter to a temporary list. ``` Wυ⊞θ⊟υ ``` Once all of the operators have been processed move all the saved operators and parameters back to the main list, also emptying the temporary list again. ``` »⭆θι ``` Stringify the resulting list. ~~85~~ 70 bytes for a human-readable format (with enclosing parentheses): ``` ≔⮌Φ⪪S ιθF⪪⁺“ ∨μ[Ek✂◧‽_U⁹�A\”α.«W⊖Lθ¿№ι↥§§θ⊖κ⁰⊞θ⪫()⪫E³⊟θ F²⊞υ⊟θWυ⊞θ⊟υ»θ ``` [Try it online!](https://tio.run/##TVBNS8RADD3bXxEHlIx2Z0VvVoWiCCsrFotXoXTTdnCcTudjFdTfXju6VHNIAu/l5SV1V9m6r9Q45s7JVuMjbck6wlupPFksjZIeV9oEX3ordYs8BQZsypJPaeBZ0vQWdsRCBYfsaHkgFsfiXOxfiosrcSiexadgKVRxVjDO4SPZe@ukIsAbqi29kva0wTXp1nc48IkhG8DrPmiPMoUnY8jW1WQr9yu9ofe5Din8V3iJnk54FCiC6yJ810uNDDnbtfeVwbMUit7ERb/HcJ4BKUfwc8rpbjjMrGy2G/6EIxYi9pUU02f8RMzGcd17BwAPDcQoTV5TCcsldGQpGRdb9Q0 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: As above, but after extracting the three elements into an array, the array is joined with spaces and then wrapped in parentheses before being pushed back to the list, meaning that the final result can be directly printed. [Answer] # [Scala](http://www.scala-lang.org/), 308 bytes I am sure it is not the shortest way to do that, but here is a solution in Scala :) ``` s=>{def g(q:Seq[String]):String=if(q.size<2)q(0)else{val o=Seq("*/%","+-",":","!=","<>","&","^","|").zipWithIndex val t=1.to(q.size-1,2).map(r=>o.map(a=>(r,if(a._1.contains(q(r)(0)))a._2 else 8))).map(_.minBy(_._2)).reverse.maxBy(_._2)._1 "("+g(q.take(t))+")"+q(t)+"("+g(q.drop(t+1))+")"} g(s.split("\\s+"))} ``` [Try it online!](https://tio.run/##ZZJNj5swEIbv/IopUldjCNDkVKEFid4qpe2BSj003cgLJrglGGx3ld00vz0dIFltEktjzMzj168/TMEbflSPv0Vh4QuXLYidFW1pIOu6vfPEG6hiyK2W7QaSFLL2GZKjSdJ9KSrYYB/nov851X@xeBokssI@NPJF3C9Yjx@YaIzYD1oqIRxdL3rvzlw/oC6meJdQd59Sd0fxQPHPZeGL7H5IW39uS7EbjdhkHlp1Ug7mswULt7xDnaRqHPAkRT2jtXm4noeFai3tx2CPmpEHxii9gMEKfKS/cco63Mr20zN91wtKafEktBFU2p2TJOW46Pq01dDyPwItY77LXL@nkX@ulFp1aP35VDs4GzSh6Rpp0V2tDOXY4QjUOjoe27RYocshCOCx4TVEqxVUShEEUQS3LUhhhPFEDzBzruQM3wrwPKiMBe8BilqDdweqE5pbpc2rOIkhvoHZiWYX@LX6UllDmW/VaCjvskLkg14ttIC3xkl@ZInES@zG8VdlIQa6puqvGV6XB5mFCLLlEmQO0p5lB8cTi3hJswknbpxwvcD3WhrwpGmV9YAekCyHPefDi78462GBW5a9wo5zOP4H "Scala – Try It Online") ]
[Question] [ *(Randomly inspired by <https://codegolf.meta.stackexchange.com/a/17272/42963>)* Given a rectangular matrix of digits (i.e., `0 - 9`), output the "pieces" of the matrix as if the digits are connected together forming a single piece, in ascending order by the digits. The pieces are guaranteed to connect only orthongonally -- no piece will connect diagonally. There will only ever be a maximum of 10 pieces (i.e., a `3` piece won't appear twice in the same matrix). For example, given the matrix ``` 0 1 1 1 0 0 1 2 3 3 2 2 ``` the following are the pieces, and an example output: ``` 0 0 0 1 1 1 1 2 2 2 3 3 ``` Spacing is important to keep the shape of the pieces, but the pieces do not necessarily need interior spacing. The pieces themselves should somehow be made distinct in a consistent manner (e.g., a newline between pieces, making sure each is a different character, etc.). Additionally, extraneous whitespace (for example, trailing newlines or leading columns) are not allowed. For example, the following would also be valid: ``` 0 00 111 1 2 22 33 ``` or ``` # ## ### # # ## ## ``` But the following would not be (note the trailing spaces behind the `0`s): ``` 0 0 0 ``` Rotations or reflections are also not allowed. For example, outputting ``` 1 111 ``` for the above matrix is also invalid. The matrix pieces may have holes, or be only a single element: ``` 0 0 0 1 0 2 0 1 0 0 0 3 ``` Or, the piece may be the whole matrix: ``` 0 0 0 0 0 0 ``` Here's a larger, more complicated test case: ``` 1 1 1 1 1 2 2 3 4 4 4 2 2 2 5 5 4 4 2 0 0 5 6 6 6 6 7 7 5 6 8 8 6 6 7 9 6 6 6 7 7 7 ``` And an example output: ``` 00 11111 22 222 2 3 444 44 55 5 5 6666 6 66 666 77 7 777 88 9 ``` ### Rules and I/O * Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can print it to STDOUT or return it as a function result. * Either a full program or a function are acceptable. * Leading whitespace to keep the shape (e.g., the "T" shape of the `1` in the example) is required, consistent whitespace to make the pieces distinct, and a single trailing newline at the end is allowed, but no other whitespace is permitted. * You can safely assume that the pieces are numbered `0` to `N` contiguously, meaning that (for example) `3` wouldn't be skipped in a six-piece matrix. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ZƒNQ2Fζʒà}}ε0Ü}0ð:, ``` -1 byte thanks to *@Mr.Xcoder*. Outputs 2D lists of pieces (with `1` and space characters `" "`) per newline. [Try it online](https://tio.run/##yy9OTMpM/f8/6tgkv0Ajt3PbTk06vKC29txWg8Nzag0Ob7DS@f8/OtpQBwaNdIxidaKNdUzA0AjKN9UxhfINdAzAfDMoNNcxh/ItgBAsAuSbgfnmUPlYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WGeLmUqvkmVdQWmKloGSvo@RfWgJh6/yPOjbJL9DI7dy2U5MOL6itPbfV4PCcWoPDG6x0/tce2mb/Pzo62kDHEARjdYAsENsIyDLWMdYxArJidRSiwcIGUAVGcBYIGiMpgAlChAx1YNAIaqAJGBpB@aY6plA@RKupjhkUmuuYQ/kWQAgWAfItEbJAPk2sMAPzzaHysbEA) or [pretty-print all test cases](https://tio.run/##yy9OTMpM/V9WGeLmUqvkmVdQWmKloGSvo@RfWgJh6/yPOjbJL9DI7dy2U5MOL6itPbfV4PCc2pDgoMMb/B41zLLyOrRb59A2@/@1ICI6OtpAxxAEY3WALBDbCMgy1jHWMQKyYnUUosHCBlAFRnAWCBojKYAJQoQMdWDQCGqgCRgaQfmmOqZQPkSrqY4ZFJrrmEP5FkAIFgHyLRGyQD5NrDAD882h8rGxAA). **Explanation:** ``` Z # Get the maximum digit of the (implicit) matrix-input (implicitly flattens) ƒ # Loop in the range [0, max]: NQ # Check for each digit in the (implicit) matrix if it's equal to the index 2F } # Inner loop two times: ζ # Zip/transpose; swapping rows/columns ʒ } # Filter the inner lists by: à # Get the max of the list # (so all rows/columns containing only 0s are removed) ε } # Map the remaining rows: 0Ü # Remove all trailing 0s 0ð: # Then replace any remaining 0 with a space " " , # And output the piece-matrix with a trailing newline ``` [Answer] ## Haskell, ~~133~~ ~~132~~ 129 bytes ``` f x=[until(any(>"!"))(tail<$>)m|m<-[[until((>'!').last)init r|r<-[[last$' ':[s|s==n]|s<-z]|z<-x],any(>'!')r]|n<-['0'..'9']],m>[]] ``` Takes the matrix as a list of strings and returns a list of list of strings. [Try it online!](https://tio.run/##TYzRasMgFIbv9xRWCkZIgppkaUuSN9gTyGF4sTKZSokO2uK7Z2o22EE4P993/D@V//owZtuu6D7Lbxe0qZR7VAs@YEqroLSZjgu10U6N/PXVQg6Etkb5QLXTAa1xzTaDI0HkIn308@wg@ql5QnxOzR3q0po/rhBdOieMtC05E4DaLhJgs0o7NCOrbm/vqLqt2gXUXimSLwhJzDjnuMaMcZFW1wmBod5NYtmIfTHW/TM7@QM8jygFfd@LkoYhpXI4vKYZx5JOpxRTOhc0YoBUkN72Aw "Haskell – Try It Online") ``` -- example matrix: ["0111","0012","3322"] -- [ |n<-[0..9]] -- for each digit 'n' from '0' .. '9' [ |z<-x] -- for each line 'z' of the input matrix 'x' [ |s<-z] -- for each digit 's' of line 'z' last$' ':[s|s==n] -- take 's' if 's'=='n', else a space -- now we have a list of 10 matrices where -- each matrix contains only the -- corresponding digit 'n' at it's original -- position and spaces for all other digits -- -> [["0 ","00 "," "],[" 111"," 1 "," "],[" "," 2"," 22"],[" "," ","33 "],[" "," "," "],[" "," "," "],[" "," "," "],[" "," "," "],[" "," "," "],[" "," "," "]] [ |r<-[ ],any(>'!')r] -- loop through rows 'r' and keep those with -- at least one non-space element until((>'!').last)init r -- and remove trailing spaces -- -> [["0","00"],[" 111"," 1"],[" 2"," 22"],["33"],[],[],[],[],[],[]] [ |m<-[ ],m>[]] -- loop through matrices 'm' and keep only -- non-empty until(any(>"!"))(tail<$>)m -- and remove common leading spaces -- -> [["0","00"],["111"," 1"],[" 2","22"],["33"]] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ẎQṢ=€ẸƇZ$⁺œr€ɗ€0o⁶ ``` [Try it online!](https://tio.run/##y0rNyan8///hrr7AhzsX2T5qWvNw145j7VEqjxp3HZ1cBOSfnA4kDPIfNW77/3D3loc7NgG5YYfbj056uHPG//@GCjBopGDEZaxgAoZGYJ6pgimUZ6BgAOSZQaG5gjmYZwGEYD6XJUJGwRwA "Jelly – Try It Online") Returns a list of pieces, where `1` represents a part of a piece, and `' '` is padding. Trailing `' '`s are removed. [Answer] # [Python 3](https://docs.python.org/3/), ~~271~~ ~~209~~ ~~206~~ ~~183~~ ~~176~~ ~~172~~ 191 bytes ``` lambda t:[[[*"".join(' #'[i==d]for i in r).rstrip()]for r in[w[min(r.index(d)for r in t if d in r):max(len(R)-R[::-1].index(d)for R in t if d in R)]for w in t if d in w]]for d in{*sum(t,[])}] ``` [Try it online!](https://tio.run/##nVVLj5swEL7zK0bsAVixUZPs9oHEoYeqRyROkRwrosF0XfGIwClUq/3tqR9AEmJns2vNAb75ZsbzeWTv/rHnqlwesnB9yJPiV5oACxBC97Y9@1PR0nXgzkE0DFOcVTVQoCXU3qxuWE13ridBDpeoRQVn1zNapqRzU29wAAOaQarigiLp3JyUbuw9xCgIHub4LCA@D4hV/vYcbbFExffLfbMvXOYj7L3iQ0oyKBK@sW6zq2nJXPXjBRbwJTdUyVwKV7BYim1D3zLvzaUeHPutWs@zLJE@pw3bVNlGZtiSpi@Un9RQyUVcfqyg29akfF8haRpSs01L2XNP/03/ktIH0u3IlpHUh2TL9slQUvFHL4Rh7/fBXpc/RWwgeC@v6/JHTwrk33dJC3qfPeOb5zszlrNOlFJpbYWd9Sajz7gxafY5G8gGAYcaVhQ64Fir0LlzBF1pwkjD9VH9ki4pdjlpIAQ0KuiOX2Ih9AljfwKhFT4FPd8c7MNc2SQJCJfyLi5cSx@4LYRLV3tCB7TyYYUvskhYeC74kZ4faclXkr9Dhb5bnQoLs0vZUqeCqTeOmvswtKIha2la7DYJ5uMgqDM3HPvjYAsD58mHpxOOEEjH@XxiX7gZOF@l9bQLzrdJEsHRn4R5@IyiR1cO0OC49Uyujf2VYdYUvG0PxzYN0/hmr@@QJ/rAfJvGHuPj6MovbI1Pz@TqFm/QcF0en6IbHpisv8b5fayu3sN/ "Python 3 – Try It Online") Edit: Some cleanup and -5 thanks to @[Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech). Edit: ~~-3~~ -26 once again thanks to @[Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech). Edit: -7 again thanks to @[Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech). Edit: +19: As noted by @[nimi](https://codegolf.stackexchange.com/users/34531/nimi) previously output had incorrect format. --- Input is matrix as list of lists: ``` Input = [[0, 1, 1, 1], [0, 0, 1, 2], [3, 3, 2, 2]] ``` Output is list of matricies: ``` Output = [[['#'], ['#', '#']], [['#', '#', '#'], [' ', '#']], [[' ', '#'], ['#', '#']], [['#', '#']]], ``` --- Ungolfed: ``` O = ' ' X = '#' def digits(t): return {d for r in t for d in r} def rows_with_digit(table, digit): return [row for row in table if digit in row] def table_with_digit(table, digit): subtable = rows_with_digit(table, digit) left_most_column = min([row.index(digit) for row in subtable]) right_most_column = max([len(row) - row[::-1].index(digit) for row in subtable]) return [row[left_most_column:right_most_column] for row in subtable] def format_table(table, digit): return [[X if i==digit else O for i in row] for row in table] def f(table): D = digits(table) R = [] for d in D: digit_table = table_with_digit(table, d) R.append(format_table(digit_table, d)) return R ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~173~~ ~~172~~ 165 bytes ``` s=input() for i in sorted(set(sum(s,[]))):R=[''.join([' ',i][c==i]for c in r)for r in s if i in r];print'\n'.join(t[min(r.find(i)for r in R):t.rfind(i)+1]for t in R) ``` [Try it online!](https://tio.run/##dVLLbtswEDybXzFQD5QQQbDlOH4EykfkyurAUHTFwqYEkkKar3f4UOPWcLDAaJc7s1ztcvxw/aDrixg62Zgsyy62UXqcXF6Q42CgoDTsYJzscitdbqdzbkvWFkVxeG0YpdXvQemcUdBStUw0jWqDTgSdKYJrYgmoYypm2ufRKO3oTz2LHTt7NNVR6S5XV81rcXCVmU8fVrGuS4mL75SQHxCDts5MwoFrSG6VNHjnHxiO8N06pX9hGuF6ifhTtsR7r0QP2w/TqcObBMdJWRcE4WuDI3puuHDS2IokGRqwlsxBxcdR@p4opUusgpElgleTNdaoUftMcYe9wl@rI/cxWh2jDTZz5Gv56Gm2LbYx2nmLMdlfM9imm8JgzjyOJl16IIvo@L5P/PzW8QMzlR1Pyq/1a7xeMZ@FVRQtWcS9YF5/mTUvGVnIP1IgvI45TS6M0RUtcRfqBG0JRtfBf/wf6lvSJvibO6Rlgivp6Q5sE9yQdl/wLzOS9t8XSaT2Ew "Python 2 – Try It Online") -15 bytes from an observation by [nimi](https://codegolf.stackexchange.com/users/34531/nimi). In program form, takes as input a list of lists of single characters; outputs by printing the pieces found using their character. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 38 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function. Takes a numeric matrix as argument and returns a list of lists strings. Each list of strings represents a piece with space-separated `1`s. Leading and internal (but not trailing) spaces are spaces. ``` ⊂{' +$'⎕R''↓⍕' '@~{⍉⍵⌿⍨∨/⍵}⍣2⊢⍺=⍵}¨∪∘, ``` [Try it online!](https://tio.run/##FYzPCgFRFMZf5SzUncnV5c4/FkrZGAvKeAElNoqtxIKamNyJpKzZyMaGjY3yKN@LjDP96px@5zt9g9mkNJwPJtNxliFZLwQVCwLpuScE4hPMWZBorBYwO5g39l@YO7Z3xbKEuWkkV5hPPdcfBw9sLzIbIT7ApNwSdpFsfk8H8ZEt6jV59lthlPFuR90OjcinAOZleapiS02aHHKlpZVrS8tR2pYeeeQymsqMJy1X@bYMKOC7T1XGzzuolv9z4qjgDw "APL (Dyalog Unicode) – Try It Online") `∪∘,` the unique elements of the ravel (flattened) matrix `⊂{`…`}¨` for each of those as `⍵`, call the following function with the entire matrix as `⍺`:  `⍺=⍵` indicate where that piece's number is in the matrix  `⊢` yield that (separates `2` from `⍺`)  `{`…`}⍣2` apply the following function twice (`⍵` is the Boolean matrix):   `∨/` mask for rows with at least one `1` (lit. row-wise OR-reduction)   `⍵⌿⍨` use that to filter the rows   `⍉` transpose (so we do this on the columns too, then transpose back)  `' '@~` replace with spaces at positions where not (i.e. where `0`)  `⍕` format as character matrix  `↓` split into list of strings  `' +$'⎕R''` PCRE replace trailing spaces (any number of spaces followed by a line-end) with nothing [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~258~~, 238 bytes Without LINQ. EDIT: Embodiment Of Ignorance pointing out better var declarations! Ty ty. ``` p=>{int j=0,o=0,l=0,x=p.GetLength(1),d=p.Length;while(j<d){int t=j/x,u=j++%x,z=p[t,u];o=z>o?z:o;l=z<l?z:l;}var s="";for(var m=l;m<=o;m++){j=0;while(j<d){int t=j/x,u=j++%x;s+=(p[t,u]==m?p[t,u]+"":" ")+(u==x-1?"\n":"");}s+="\n";}return s;}; ``` [Try it online!](https://tio.run/##jVJRa8IwEH5ef8VRGLQ0Ot0mDNPTh8H24mCwhz04H2rNNCVNSpJqZ@lvd6ndGIjI7uPIfd99OcKR1PRSpdmhNFyu4e3LWJZTLxWJMfCq1Vonee0BFOVS8BSMTaw7toqv4CXhMgjbJsBTKdOYSzsnC@JM2s2awBLwUOCkdjpkOCDKpXBZYdF/ZnbG5NpugmFIVk7oGN1tuGBBFq/C4zWL2U1FSsyi6LoieyzmlpQLqnA/UdP9WFGB@1i4StBmm2gw6Pv0U@mgJTkKmseoaB5FYe1ecHE6NREG3XzEfNpVke@PffDDKCgRq95w6n9Ip/ghbZy9JbTRzJZagqENPVCvWwJwQJBsBy0dEXhYHNf0F/UJd8qAtBiSe4cRGUFDznlu/@FpcXfOc1X/iL/Ni72T0Q31XHQ/pP@opFGC9d81t2zGJQuWAQ9D6jUOh28 "C# (.NET Core) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 291 bytes ``` import re t=input() a,b=t.split(),{c for c in t if' '<c} for c in sorted((b,a)[int(max(a))==len(a)],key=int):s=re.sub(r'[^%s\s]'%c,' ',t).split('\n');print"\n".join(''.join(l[i]for i in sorted({i for l in s for i,j in enumerate(l)if j in c})if i<len(l)).rstrip()for l in s if l.strip())+'\n' ``` [Try it online!](https://tio.run/##TVBhb4IwEP0sv@JCYtpujEgZc3PyS8QliHWrq4W0NdEYfzu7FnTmhfTee9d7R7uz@2k175t2K0pDCOnloWuNAyMiV0rdHR1lUZ1sSpfaTklkyaWBXWugAanBgdwRIMvmGt01i/fFltJNUrOV1I4e6hOtGStLJTQW6@RXnHG2YwtbGpHa44Yasvqa2squybRJcGDi2JhHKk3YZ2ewP650nO5bqSkhw6lWcu1z5UPuRYb1VJBCKZO9J0IfD8LUTlDF5A6C1lx9KZd@M8VYaqwzsqPsYQL6Kh1l9uzX6fGdovC/J99iav0taMEW0UScRAP@LaNJ2BhieImf@KyPZ4CodDjiaKCQeYHfCo88eJnHIGXAK51Djm0cvQxu4IPxGsAHWkAx0hBWwNuIOcwH@o4IQqU//j2Y@1gMxC/LMNmn@4HcZ@TxHw "Python 2 – Try It Online") Expects a quote-delimited sting as input. A semi-ludicrous percentage of the code is dedicated to handling non-space-separated/non-space-padded input. **Un-golfed Explanation:** ``` # built-in python regex handling. import re # get argument from STDIN t=input() # get elements which are whitespace separated, and all distinct non-whitespace characters a,b=set(t.split()),{c for c in t if' '<c} # choose whichever set has the appropriate number of values based on its max element # for non-space separated inputs, this prevents values like '333' for 4-piece sets (b,a)[int(max(a))==len(a)] # get elements in order by their integer value # this will force the items to print in order, since sets are unordered for c in sorted(..........................,key=int): # using regex substitute, replace any instance that DOESN'T match the current value or a whitespace with a space re.sub(r'[^%s\s]'%c,' ',t) # split replaced string into lines on line breaks s=...........................split('\n') # for each line in replaced input for l in s # get the index and value of each item in line for i,j in enumerate(l) # get distinct indexes which have a value that appears in the current piece {i ..................................if j in c} # get ordered list of distinct indexes a=sorted(...............................................) # for each line in the replaced input # only return values where line has non-whitespace values for l in s if l.strip() # get the value for each index that has a non-space value on other lines # as long as that index exists (for non-space-padded inputs) # this ensures that the spaces between values, if any, are removed # there may still be trailing spaces l[i]for i in a if i<len(l) # join characters back into one string, and remove trailing whitespace ''.join(..........................).rstrip() # join the lines back together with line breaks, and terminate with an extra line break # print output to screen print"\n".join(...................................................................)+'\n' ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 75 bytes ``` $ ¶9 .-10{T`9d`d`.$ *;(s`(\d)(?!.*\1$) +¶ ¶ G`\d /^\d|^$/m^+m`^. .$ $&¶ ``` [Try it online!](https://tio.run/##K0otycxLNPz/X4Xr0DZLLj1dQ4PqkATLlISUBD0VLi1rjeIEjZgUTQ17RT2tGEMVTS4FLgXtQ9uAirncE2JSuPTjYlJq4lT0c@O0cxPi9Li4gLpU1A5t@//fEASMjLiMTUxMjIC0qSmQNjDgMjUDAnNzIG1hAWRwWYK55gA "Retina – Try It Online") Explanation: ``` $ ¶9 ``` Append a digit to the input. This represents the loop counter. The newline simplifies the trailing whitespace removal. ``` .-10{ ``` Inhibit default output and repeat exactly 10 times. ``` T`9d`d`.$ ``` Advance the loop digit. ``` *;( ``` Output the result of the rest of the script but then restore the buffer. ``` s`(\d)(?!.*\1$) ``` Replace all digits that don't match the loop digit with spaces. (Because this uses a lookahead and there's nothing to look ahead at this point this also replaces the loop digit.) ``` +¶ ¶ ``` Remove all trailing whitespace. ``` G`\d ``` Remove all blank lines. ``` /^\d|^$/m^+ ``` Repeat as long as no line begins with a digit... ``` m`^. ``` ... delete the first character on each line. ``` .$ $&¶ ``` If there is anything left then append a newline to separate each shape from the next. (This is done to avoid stray newlines for missing digits.) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes ``` WS⊞υιFχ«≔Φυ№κIιθ¿θ«UTFθ«Fκ«¿⁼λIιλ→»M±Lκ¹»D⎚ ``` [Try it online!](https://tio.run/##TU7LTsMwEDzbX@HjWipSEhJS4IQKSEiAKugPWJVrW3Xtxo9yQPl2Yzs9sIfdmd2Z0e4lc3vLdEo/UmlO4M2cY/gOThkBlJJt9BLiiij6iA/WEWgbSn4xevJeCQOvSgfuimBjowlwzID5AIpSuiJTNiF1IDBVD9pZITTfOXWCckE18HpbyPFKqutlikx70P8yyTY/FkBXO0Jce04@7IXDw5cSMizrubS6/eSCBQ7v3Iggc3j@qa2aInmOp/Pyx0Zz5iqc8ZxSW6rr8G3f912ew5Bn0@DhLtc45rleZ4DvKx1xurnoPw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` WS⊞υι ``` Read the input into an array. (This could be removed if I used an ugly input format.) ``` Fχ« ``` Loop over the 10 digits. ``` ≔Φυ№κIιθ ``` Get the rows which contain those digits. ``` ¿θ« ``` Check that the digit was in fact found (to prevent outputting spurious newlines). ``` UT ``` Turn off automatic padding. ``` Fθ« ``` Loop over the found rows. ``` Fκ« ``` Loop over each column... ``` ¿⁼λIιλ→» ``` ... if the current input character equals the current loop digit then print it otherwise move the cursor right. ``` M±Lκ¹» ``` Move to the start of the next row. Using movement commands like this allows Charcoal to trim the output on both sides. ``` D⎚ ``` Dump and clear the canvas ready for the next digit. This allows the different digits to have different amounts of trimming. I tried a programmatic approach but that weighed in at 47 bytes, although it would also have been 43 bytes for a brief amount of time when `Equals` vectorised: ``` UTWS⊞υιFχ«≔ΦEυEκ⁼μIιΣκθEθ⭆✂κ⌊Eθ⌕μ¹⁻Lκ⌕⮌κ¹¦¹⎇μι ``` [Try it online!](https://tio.run/##LU7LasMwEDxHXyFykkAF27XrlJxKaaDQQKj9A8JR7SWyHOuRUkq/XV2JzGFnVzszq2GSdlikjrFfxlGr3sLM@J58T6AVZe/mGnznLZiRcU5PwU0sCAqo@FosZWXB6S/ZvDgHo2EH0F5ZdpTXJEp0EfRtDVI7Ngv6Kp1nwBGCdmFml9SsGLU54QGffSuu8rk0dBoGlTKOYGBGx11xAHNOgWWOwmVw7EOZ0U@YeV9/qpuyTuWHkuciaK@skfYneUHQLd2mz@zJX4xlQlWRx7quK@SmQS4K0jwh2hZ5t8OGPOexJfHhpv8B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` UT ``` Turn off automatic padding. ``` WS⊞υι ``` Read the input into an array. ``` Fχ« ``` Loop over the 10 digits. ``` ≔ΦEυEκ⁼μIιΣκθ ``` Compare each character with the input and build up a boolean array, but then filter out the rows with no matches. ``` Eθ⭆✂κ⌊Eθ⌕μ¹⁻Lκ⌕⮌κ¹¦¹⎇μι ``` Loop over the remaining rows and slice from the earliest match in any row to the latest match in the current row, then mapping the boolean array back to digits or spaces, which are then implicitly printed as an array of strings. [Answer] # Wolfram Language 101 bytes There has got to be a much more efficient way to accomplish this. ``` (g=#;Column[Table[Grid@Map[Replace[#,Thread[Complement[u=Union@Flatten@g,{n}]->""]]&/@#&,g],{n,u}]])& ``` [Answer] # Perl 5, 97 bytes ``` $x=$_;for$i(0..9){$_=$x;y/ //d;s/(?!$i)./ /g;s/ *$//gm;s/^ //gm;s/^ //gm until/^(?! )/m;$\.=$_}}{ ``` [TIO](https://tio.run/##RczdCoJAEIbhc69igjnQwJ3V2jYR6Qq6g9CTShb8Qw0M8dbbpkWJ9@R7mGW7R18pa3HKsEifbY/Gl0IkwYxFhlP6JiC6pwP5lx2aQDBLFuyRqKx55d424Dfg1YymopyfQ0B1ijfBHy/LbG0EWzHE3gGOrthJgVolQbJOaxq005lz9pL/hfVpu9G0zWDDTmqtbXhVQkZf) Explanation ``` -p0777 # options to read whole intput and print special var by default $x=$_; # save default var (input) into $x for$i(0..9){ # for $i in 0..9 $_=$x; # restore default var y/ //d; # remove all space char s/(?!$i)./ /g; # replace all char except $i by a space s/ *$//gm; # remove trailing space s/^\n//gm; # remove empty lines s/^ //gm until/^(?! )/m; # remove leading space until there is no more $\.=$_ # append default var to output record separator } }{ # trick with -p to output only reacord separator ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 29 bytes ``` AÆ®®¥X ÑÃÃÕfx Õfx ®¬r0S x1 fl ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=QcaurqVYINHDw9VmeCDVZnggrqxyMFMgeDEKZmw=&input=W1sxIDEgMSAxIDEgMiAyXQpbMyA0IDQgNCAyIDIgMl0KWzUgNSA0IDQgMiAwIDBdCls1IDYgNiA2IDYgNyA3XQpbNSA2IDggOCA2IDYgN10KWzkgNiA2IDYgNyA3IDddXQotUQ==) Updated to comply with stricter output formatting. Outputs as a list of pieces with each piece represented by a list of lines, using 2 as the filler character. Explanation: ``` AÆ #For the numbers 0-9: ®® Ãà # Map over each digit in the input: ¥X # True if it equals the current number, false otherwise Ñ # Multiply by 2 to turn the bool into a number Õfx # Remove columns that are all 0 Õfx # Remove rows that are all 0 ® # For each remaining row: ¬ # Turn it into a string r0S # Replace "0" with " " x1 # Trim spaces from the right fl #Remove unused pieces ``` [Answer] # [Python 3](https://docs.python.org/3/), 133 bytes ``` lambda s:[dedent(re.sub(" *$","",re.sub(f"[^{c}\\n]"," ",s),0,8)).strip("\n")for c in sorted(*s)[1:]] from textwrap import* import re ``` [Try it online!](https://tio.run/##LY3NCoMwEITveYpl6SGRIGq1WqFPoha0JlSoMSQpbSl9drv9mcs3s8sw9hHOi9mu@tCul34exh583YxqVCZwp2J/HThCtEGJKP9ZY3N8nl5tazo6A0ovZCIrIWIf3GQ5tgaFXhycYDLgFxfUyCMvmrTuOqbdMkNQ93BzvYVptvSP2I/g1GrdRNOaI2L6UZaxbZ7nGbEoiEnCih2pLIlVRYbtv7GkhhDrGw "Python 3 – Try It Online") Takes a newline-seperated string, returns a list of newline-seperated strings. Uses `textwrap.dedent` to get rid of leading spaces. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ŒĠµŒṬZSƇ$⁺ị⁾# œr€⁶) ``` [Try it online!](https://tio.run/##y0rNyan8///opCMLDm09OunhzjVRwcfaVR417nq4u/tR4z5lhaOTix41rXnUuE3z/@H2SOtHjduPdQEFIv//j4421FFARkZAFKujEG2so2ACQ0YIYVMdBVMkYQMgggqbISFzIEIIW4ARVAYkbImmFCQcCwA "Jelly – Try It Online") A monadic link taking the matrix as input and returning a list of one ragged list per piece. Footer displays this prettily, but I think output without that is consistent with rules of question. ]
[Question] [ ## Introduction: After I posted two rainbow-related challenges: *Codegolf Rainbow : Fun with Integer-Arrays* [1](https://codegolf.stackexchange.com/questions/170614/codegolf-rainbow-fun-with-integer-arrays) and *Codegolf Rainbow : Draw in Black-and-White* [2](https://codegolf.stackexchange.com/questions/170615/codegolf-rainbow-draw-in-black-and-white), the following comment was made by [*@ChrisM* in the ASCII (*Draw in Black-and-White*) challenge](https://codegolf.stackexchange.com/questions/170615/codegolf-rainbow-draw-in-black-and-white#comment411956_170615): > > Maybe you know this and it's by design (I know that rainbows are not rhombuses or ascii, too, and higher orders' positions get more complicated), but aren't the colours reversed in the 2nd rainbow? > > > And he's indeed right. When you see a double rainbow, the second one is actually a reflection of the first, so the colors are reversed. With three rainbows, it's an actual double rainbow, with the third one being a reflection of one of the other two. And with four, there are two rainbows, and two reflections of those. [![enter image description here](https://i.stack.imgur.com/6G5bg.png)](https://i.stack.imgur.com/6G5bg.png) So, let's make a third related challenge using that fact. ## Challenge: Inputs: A positive integer `n` which is `>=2`, and a list of integers of size `>= n+1`. Output: The same list ordered as follows: 1. First split the input lists in sub-lists of size `n` (where the trailing sub-list could be of any size in the range `[1,n]`). 2. Then we do the following based on the amount of sub-lists `m`: * Sort the first `m - m//2` amount of sub-lists from lowest to highest (where `//` is integer-divide). (I.e. with 6 sub-lists the first three will be sorted from lowest to highest; with 5 sub-lists the fist three will be sorted from lowest to highest.) * Sort the last `m//2` amount of sub-lists from highest to lowest (where `//` is integer-divide). (I.e. with 6 sub-lists the last three will be sorted from highest to lowest; with 5 sub-lists the last two will be sorted from highest to lowest.) 3. Merge all sub-lists together to form a single list again ### Examples: Inputs: `n=7` and `[3,2,1,-4,5,6,17,2,0,3,5,4,66,-7,7,6,-5,2,10]` Step 1: `[[3,2,1,-4,5,6,17],[2,0,3,5,4,66,-7],[7,6,-5,2,10]]` Step 2: `[[-4,1,2,3,5,6,17],[-7,0,2,3,4,5,66],[10,7,6,2,-5]]` Step 3 / Output: `[-4,1,2,3,5,6,17,-7,0,2,3,4,5,66,10,7,6,2,-5]` Inputs: `n=4` and `[7,4,-8,9,3,19,0,-23,-13,13]` Step 1: `[[7,4,-8,9],[3,19,0,-23],[-13,13]]` Step 2: `[[-8,4,7,9],[-23,0,3,19],[13,-13]]` Step 3 / Output: `[-8,4,7,9,-23,0,3,19,13,-13]` ## Challenge rules: * The integer input `n` is guaranteed to be larger than 1. * The size of the integer-list is guaranteed to be larger than `n`. * The trailing sub-list can be smaller than `n` (as can be seen in the examples and test cases). * I/O format is flexible in any reasonable format. Can be a list/array of integers or decimals, a comma/space/newline delimited string, stream of integers, etc. (Output may not be a 2D list of lists like step 2. Step 3 to flatten it back into a single list is required for this challenge.) ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), 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](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Inputs: n=7 and [3,2,1,-4,5,6,17,2,0,3,5,4,66,-7,7,6,-5,2,10] Output: [-4,1,2,3,5,6,17,-7,0,2,3,4,5,66,10,7,6,2,-5] Inputs: n=4 and [7,4,-8,9,3,19,0,-23,-13,13] Output: [-8,4,7,9,-23,0,3,19,13,-13] Inputs: n=2 and [7,-3,1] Output: [-3,7,1] Inputs: n=3 and [1,6,99,4,2] Output: [1,6,99,4,2] Inputs: n=2 and [5,2,9,3,-5,-5,11,-5,4,12,9,-2,0,4,1,10,11] Output: [2,5,3,9,-5,-5,-5,11,4,12,9,-2,4,0,10,1,11] Inputs: n=3 and [5,2,9,3,-5,-5,11,-5,4,12,9,-2,0,4,1,10,11] Output: [2,5,9,-5,-5,3,-5,4,11,12,9,-2,4,1,0,11,10] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ ~~17~~ 16 bytes ``` ġ₎↔ḍ↔{izo₎ᵐ↔}ᶠcc ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//8jCR019j9qmPNzRCySrM6vygfyHWycAObUPty1ITv7/PzraWMdIx1An3kTHVMdMx9AcyDPQMQZyTHTMzHTizXXMgcLxpiBFBrE65rH/gwA "Brachylog – Try It Online") -1 byte thanks to @sundar Expects input as `[<integer list>, n]`. Note that negative integers are represented with `_`, Brachylog's "low minus". Output variable is `R`. First time attempting Brachylog, so I imagine it's sub-optimal and ripe for reducing in bytes. ## Explanation Partition, bifurcate, sort based on index (0: asc, 1: desc), flatten. ``` ġ₎ | split head of input into groups of length n (last of list) ↔ | reverse so that... ḍ | dichotomize splits in two, attaching any additional element to the second list ↔ | reverse so first half of partitions corresponds to the 0 index { } | apply i | : append index z | : zip each sublist with the index of its parent o₎ᵐ | : map over sublists, ordering by the zipped index ↔ | : undo earlier reverse ᶠ | find all outputs cc | flatten two levels ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` sṢ€ŒHUÐeF ``` [Try it online!](https://tio.run/##y0rNyan8/7/44c5Fj5rWHJ3kEXp4Qqrb////o411jHQMdXRNdEx1zHQMzYE8Ax1jIMdEx8xMR9dcxxworGsKUmQQ@98cAA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes ``` lambda n,l:sum([sorted(l[i:i+n],reverse=i>len(l)/2)for i in range(0,len(l),n)],[]) ``` [Try it online!](https://tio.run/##nY/NboMwEITvfQpLvYC6VlmbnxCJvgj1gSrQWCImMrRSn56OSYHkWsmytLvfzOxef6bz4NTcVe9z31w@To1w1B/Hr0tUj4Of2lPU1/ZoX5wh3363fmwr@9a3LurjVxV3gxdWWCd84z7bKKHbhFxsqDbxfPXWTaKLChK1JkVMMqWMcuICVUIaRUp5TrKgAm2ZBSgx8bOoKlEDZjT0KgGVLPViglayqBR05mnNSpFVgJAHKoFyCY1UmiSj0Jv1AUgBIoySG8cLtDupxUlitqk0NLwTGgRjg7KEm1qpu86DVzgurIQr8ZjDjwvVsgWWCNfiJN7iFM7UYZrtml2QQhLwIHjY6F85a4r@o/kuh0NS0Jj5Fw "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 bytes ``` òV ®nÃÇwÃc ``` --- ``` Also 10 bytes òV mn ow c ``` [Try it online!](https://tio.run/##y0osKPn///CmMIVD6/IONx9uLz/cnPz/f7SxjpGOoY6uiY6pjpmOoTmQZ6BjDOSY6JiZ6eia65gDhXVNQYoMYrnMFXQDAQ "Japt – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 bytes ``` ô€{2ä`í«˜ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8JZHTWuqjQ4vSTi89tDq03P@/zfiijbVMdKx1DHW0TUFIUNDEGmiYwgS1DXSMQCxdQwNgBKxAA "05AB1E (legacy) – Try It Online") [Try it online!](https://tio.run/##yy9OTMpM/W@qYKRgqWCsYKoBQoaGINJEwRAkaKShYABiKxgaACU0HzWtObze6P/hLUBGtdHhJQmH1x5afXrO//8A "05AB1E – Try It Online") in [05AB1E (Elixir rewrite)](https://github.com/Adriandmen/05AB1E) – expects input to be on the stack, a default I/O method. Kevin came up with his own 11-byter which I used to get to 10. Then I came up with something else for 9 bytes. [Answer] # JavaScript (ES6), ~~82~~ 81 bytes *Saved 1 byte thanks to @redundancy* Takes input as `(list)(n)`. ``` a=>n=>(g=z=>a+a?[...a.splice(0,n).sort((x,y)=>1/z?x-y:y-x),...g(a[i+=n])]:a)(i=0) ``` [Try it online!](https://tio.run/##pZBRa8JAEITf@yvyeId78TYXjREu/pCQh8OqRCQRI0X98@lsWtGqhUJDCOxmvhl2tuEjdMtDvT@apn1f9WvfB180vlAbf/FFGIVFGcdxiLv9rl6ulKVGx117OCp1orP2BY8vi5M5z8/mpAnKjQplPfJNpat50Kr2VvfLtuna3SretRu1VqWjhJhMShOaEmeYLDkMKU2nZDLKsDYTEdlKq0zrKBqPoxIAY@muGJR2mAcjrOxAJmCrt4fIDCIzoxxqzoGZxJFhDA4JqSQ8PUPkDFwGTPT2C@aBfJFg8BtuyUu36LcEB39@cmMckucIT@Do/uQobnfYo6P0KeejWLzM8kWhyXAcbpNy0SDfnSCOCbp1opncyBuWAhRIsP8Eup@B1zj3zfBdIEukkFX/CQ "JavaScript (Node.js) – Try It Online") [Answer] # [Clojure](https://clojure.org/), 90 bytes ``` #(for[i[0 1]j((split-at(/(count %)2%2)(partition-all %2%))i)k(([seq reverse]i)(sort j))]k) ``` [Try it online!](https://tio.run/##lZBRa4MwFIXf/RWBISRww0xia6U/JeRBWoW0oi6mo/v17sSutLA@bEGEc3O@c2/uoR9Pl9Au/Nh2rFveeDcG623BlDtxPk@9j7KJ/J0fxssQWS50rgWfmhB99OMgm75nuc6F8OLMuZ3bDxbazzbMrfOCz2OI7CSEO4tFZPw4pnvLrjaz1pAmRbKkDW1JVVAFGYiStluSFVUoy00yFY4qx/YWXgVt7gRMxarXDJSKFdLAHBpUqMsd1TCoGk6pDUkFYRyVjv06aLADUoFI1uLGqRW65UlUHOkX7KuDPIM0lViFueoa6dqRcX9hnwjwaQ/pIVgIPqXSH9vQ66wYNW0Gz1f38fZWYycmXW8e0IMowSR/Iv4Xbx7x93DzY1dP8So1SJDLnMv4FPwQ@4HxZpr6L9axqxBi@QY "Clojure – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 23 bytes ``` ẇD:L½:£⌈Ẏvs⅛_¥⌈ȯvsvṘ⅛¾f ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E1%BA%87D%3AL%C2%BD%3A%C2%A3%E2%8C%88%E1%BA%8Evs%E2%85%9B_%C2%A5%E2%8C%88%C8%AFvsv%E1%B9%98%E2%85%9B%C2%BEf&inputs=2%0A%5B1%2C2%2C3%2C4%2C6%2C5%2C7%2C8%2C9%2C10%5D&header=&footer=) A big mess. ]
[Question] [ A checkerboard program is a program where each individual character's ordinal value alternates from even to odd, excluding the line terminator (which can be any standard line-endings). A triangular program is a program where each line has one additional character than the preceding line, with the first line having one character. You do not need to handle empty input. Your task is to build a program that validates that the given input adheres to those criteria and outputs/returns something truthy if the program meets the criteria, or something falsy otherwise. Your program must also meet these criteria. ## Examples of valid programs ``` G `e @u^ 5r{B ^ cB +$C VA01 ``` ## Rules * Your program may start with either an odd or an even byte as long as the parity of the characters alternates. * Your program must validate programs that start with either an odd or an even character. * For unicode characters, the underlying byte values must have alternating parity. * You can assume that input only contains printable characters. If your program contains unprintables, it should still be able to validate itself. * Your program may include one trailing newline, this does not need to be allowed by your validation as you can assume this is removed prior to validating. * [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/q/1061/9365) * The shortest code in bytes, in each language, wins. [Answer] ## C (gcc), 189 bytes ``` j ;l ;b; d;f␉ (char ␉*␉t) {b=*␉t% 2;for␉(␉ j=d=0;j=j + 1,␉l=j+ 1,␉*␉t; ) { for␉(;l=l- 1 ;t=t+ 1 )b= !b␉,␉d=d+ !(␉* ␉t␉*␉(␉*␉t- 10) *␉(␉*␉t%2-b) ) ; d␉|=*␉t- 10;t=t+ 1 ; }b= !d; } ␉ ␉ ``` [Try it online!](https://tio.run/##ldLNboMwDAfwc/wUriUk0oLU9mrlTbgQMloiRifEreuzM9OytXxuCwdM@CUK@J/FpyxrWw9cAlsGx7mCMDunNaitajTC1RopAjhyfqlVqMAbZ/bsjYcdHiJVGr9DkEIUo8Yr3B2XpozxAMiNaQSitgZhY1WknHE73IRqC6qRVWG3UuheQ/8QHGOrZSs5jvo0/dvHPnBAxptstXFyRyUXwHtaVKG@Asr4qIuqyUMKXFJRhFKlSWWzpHJveVKdzoWXea15Adv/4FT0X/F9thvkCceDBD0Bl/QLsEyroOsirYF7h2kFPJpPy6CPBS2C77zQEvjJES2AZ7xoHryEjmbBaxJpDgzSSTNgGFia@VHDCNMEjDNNk2aNM07jz5xEngagy9ytbb8A "C (gcc) – Try It Online") `␉` represents a tab character (I'm sorry). Note that there are several trailing spaces/tabs (I'm more sorry). The original with tabs intact is best viewed in vim with `:set tabstop=1` (words cannot express how sorry I am). It's a function (called `f`, which isn't immediately obvious from glancing at it) that takes a string as an argument and returns either `0` or `1`. I *could* reduce this by at least one and probably two or more lines, but note that it gets increasingly messy and low-effort towards the end, mostly because writing such awful code (even by PPCG standards) was making me feel like a bad person and I wanted to stop as soon as possible. The basic idea here is to avoid constructions that necessarily break the format (`++`, `+=`, `return`, etc.). Miraculously, important keywords like `for`, `char`, and `while` (which I didn't end up using) happen to fit the alternating parity rule. Then I used spaces (even parity) and tabs (odd parity) as padding to make the rest fit the rules. [Answer] # [Haskell](https://www.haskell.org/), ~~1080~~ 1033 bytes ``` ; f= g ij=f a =hi hi = g hij= ij g ' ' =0 g '"' =0; g '$' =0; g '&' =0-0 g '(' =0-0-0 g '*' =0-0-0; g ',' =0-0-0; g '.' =0-0-0-0 g '0' =0-0-0-0-0 g '2' =0-0-0-0-0; g '4' =0-0-0-0-0; g '6' =0; g '8' =0 g ':' =0; g '<' =0-0 g '>' =0; g '@' =0-0; g 'B' =0; g 'D' =0-0; g 'F' =0; g 'H' =0-0-0 g 'J' =0; g 'L' =0-0-0-0 g 'N' =0; g 'P' =0-0-0-0; g 'R' =0; g 'T' =0-0-0-0; g 'V' =0; g 'X' =0-0-0-0-0 g 'Z' =0; g '^' =0; g '`' =0 g 'b' =0; g 'd' =0; g 'f' =0; g 'h' =0; g 'j' =0; g 'l' =0; g 'n' =0; g 'p' =0; g 'r' =0-0 g 't' =0; g 'v' =0; g 'x' =0-0-0 g 'z' =0; g '\92' =0-0; g '|' =0; g '~' =0; g y = 1 ;z=0; i(-0)z=z; i m('\10':y ) ="y"; ; ; ; ; ; ; ; i m(mnmnmnmnm:y ) = i(m - 1 ) y ; ; i k m ="y"; ; k i [ ] =01<1010101010; k m('\10':y ) = k(m + 1 )(i m y ) ; ; k m y =01>10; m o = k 1$'\10':o ; ; ; o i('\10':y ) = o i y ; ; ; ; ; ; ; ; ; o i(k:y )|g k<i = o(1 - i ) y ; ; ; ; ; ; o i(k:y )|g k>i = o(1 - i ) y ; ; ; ; ; ; o i [ ] =01<10; o i y =01>10;v=01>10101010 s y|o 1 y = m y|o(-0) y = m y ; s y =v; ; ; ``` [Try it online!](https://tio.run/##lZRvi9NAEMbf76cYQrGtXiWRQ/TSLSIiIiJyiIiuYkXbpmk2x/VabCl@9d7sTDL506RG9kVmnnlmdrdpfovpOv69Wh2PoZppBXNQ0VLP1BT0IlKLCDTM8bHUEC3VHPq4tO8CzwWha@j3ivCBC0dkGHDIycM8YdtFNX2cp2z2i5SFJ2WBWy5Ppad0DBc9yw95JdK4ONhExBcscvtLkV@V5dcivylf6K3I76qHfy@FD0WBR11L6WO99ElKn@uX/yKl7xL9yC/4U6RfEs2K17EQcSnRqihbEW8kui1@qDsRtxL9Kf8Ie5HN8@wdUXYotvibW3b4Twog3LssGoz84V7v0RJBMuibwO9f7WAI2tt5IVSXcpbEZottOCGBEc4b4tzMFEMi/THO/QrfcOtgHPj5wu3i6nYQ45xHbs4AdwGnYTvZ3IH9YIJdGKfOCkGPW9P8ZCmeozwN8@w8tSs4Y@xMhznEY/dRpYMALxDJBbKloGKd/MtaumWYbZ@destPXmoNu0OK93RvIXGxewN5htPWLt7y5ONmo73Q2Jk2Fl@csQ4IxhIRjGUkuCcxwdgcChQZxgI1ZlzgOAMDmYQMlBVoYOdFLS/BgfwVOpBSxQN3XTZoNUBQ7wkhSD1FBE84ZQTrDZCgOY2UoEozJnhaMye41gIKmtlKCqq2o4Int7OC62dgQfPP0oIcJVw08YK3OQ8M9DAxiq/OeDtzAg3803aghnMRNmRGCzhw27i2bTM62NjCjgo8jGV6dMAHWzvxA/fvDBD2diSIsf@DEE@pZBpZfXMb2TvoYW2zOd4D "Haskell – Try It Online") ## Explanation This has been quite the interesting task for Haskell. ### Parity To start we need some way of determining if a character has an even or odd code-point. The normal way one might do this is to get the code-point and mod it by 2. However as one might be aware, getting the code-point of a character requires an import, which due to the source restriction means that it cannot be used. A more experienced Haskeller would think to use recursion. `Char`'s are part of the `Enum` typeclass so we can get their predecessors and successors. However `pred` and `succ` are also both unusable because they don't alternate byte parity. So this leaves us pretty stuck we pretty much can't do any manipulation with chars. The solution to this is to hardcode everything. We can represent (most) even chars as literals, odds we have trouble with because `'` is odd so it can't be next to the char itself making the literal impossible to express most of the odd chars. So we hard code all of the even bytes, and then add a catch all for the odd bytes at the end. ### The problem Bytes You may notice that there are some even bytes for which literals cannot be made by wrapping it in single-quotes. They are the unprintables, newlines and `\`. We don't need to worry about unprintables since as long as we don't use any of them we don't need to verify. In fact we can still use odd unprintables, like tab, I just don't end up needing to. Newline can sagely be ignored because it will be trimmed from the program anyway. (We could include newline, because it's code-point is rather convenient, but we don't need to). This leaves `\`, now `\` has the codepoint 92, which conveniently is an odd number followed by an even number, so `\92` alternates between evens and odds thus the literal `'\92'` is perfectly valid. Later on when we do need to represent newline we will notice that it luckily has this same property `'\10'`. ### Spacing problems Now in order to start writing actual code we need to be able to put a sizable number of characters on a single line. In order to do this I wrote the cap: ``` ; f= g ij=f a =hi hi = g hij= ij ``` The cap doesn't do anything except be valid Haskell. I had initially hoped to make definitions that would help us in the code later, but it didn't. There are also easier ways to make the cap, for example whitespace and semicolons, but they don't save bytes over this way so I haven't bothered to change it. ### Hardcoder So now that I have enough space on a line I start hardcoding values. This is mostly pretty boring, but there are a few things of interest. For one once the lines start getting even longer we can use `;` to put multiple declarations on a line, which saves us a ton of bytes. The second is that since we can't always start a line with a `g` every so often we have to indent the lines a bit. Now Haskell really cares about indentation, so it will complain about this. However if the last line before the indented line ends in a semicolon it will allow it. Why? I haven't the faintest, but it works. So we just have to remember to put the semicolons on the end of the lines. ### Function Building Blocks Once the hardcoder is done it is smooth sailing to the end of the program. We need to build a few simple functions. First I build a version of `drop`, called `i`. `i` is different from `drop` in that if we attempt to drop past the end of the string it just returns `"y"`. `i` is different from drop also in that if it attempts to drop a newline it will return `"y"`, These will be useful because later when we are verifying that the program is a triangle this will allow us to return `False` when the last line is not complete, or when a line ends early. Next we have `k` which in fact verifies that some string is triangular. `k` is pretty simple, it takes a number \$n\$ and a string \$s\$. If \$s\$ is empty it returns `True`. If the string begins with a newline it removes the newline and \$n\$ characters from the front. It then calls `k` again with \$n+1\$ and the new string. If the string does not start with a newline it returns `False`. We then make an alias for `k`, `m`. `m` is just `k` with `1` in the first argument, and a newline prepended to the second argument. Next we have `o`. `o` takes a number and a string. It determines if the string bytes (ignoring newlines) alternate in parity (using our `g`) starting with the input number. Lastly we have `s` which runs `o` with both `1` and `0`, if either succeeds it defers to `m`. If it fails both it just returns `False`. This is the function we want. It determines that the input is triangular and alternating. [Answer] # [Stax](https://github.com/tomtheisen/stax), 26 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` L Y$ i:- {2% *OFyF %vi =* ``` [Run test cases online](https://staxlang.xyz/#c=L%0AY%24%0Ai%3A-%0A+%7B2%25%0A*OFyF%0A%25vi+%3D*&i=a%0A%0Aa%0Aab%0A%0Aa%0Aba%0A%0Aab%0Aa%0A%0AG%0A%60e%0A%40u%5E%0A5r%7BB%0A%0A%5E%0AcB%0A%2B%24C%0AVA01%0A%0AL%0AY%24%0Ai%3A-%0A+%7B2%25%0A*OFyF%0A%25vi+%3D*&a=1&m=1) I had to introduce 3 junk characters. `i` is a no-op when outside all loop constructs. is always a no-op. `O` tucks a 1 under the top of the stack, but the value isn't used in the program. ``` LY move input lines into a list and store in Y register $ flatten i no-op :- get pairwise differences {2%*OF foreach delta, mod by 2, and multiply, then tuck a 1 under the top of stack yF foreach line in original input do... %v subtract 1 from length of line i= is equal to iteration index? * multiply ``` [Run this one](https://staxlang.xyz/#c=LY++++%09move+input+lines+into+a+list+and+store+in+Y+register%0A%24+++++%09flatten%0Ai+++++%09no-op%0A%3A-++++%09get+pairwise+differences%0A%7B2%25*OF%09foreach+delta,+mod+by+2,+and+multiply,+then+tuck+a+1+under+the+top+of+stack%0AyF++++%09foreach+line+in+original+input+do...%0A++%25v++%09subtract+1+from+length+of+line%0A++i%3D++%09is+equal+to+iteration+index%3F%0A++*+++%09multiply&i=a%0A%0Aa%0Aab%0A%0Aa%0Aba%0A%0Aab%0Aa%0A%0AG%0A%60e%0A%40u%5E%0A5r%7BB%0A%0A%5E%0AcB%0A%2B%24C%0AVA01%0A%0AL%0AY%24%0Ai%3A-%0A+%7B2%25%0A*OFyF%0A%25vi+%3D*&a=1&m=1) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~34~~ 26 bytes ``` ¶ ¡D ©€g ´ā´Q ´sJÇÈ ¥Ä{´нP ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0DauQwtduA6tfNS0Jp3r0JYjjYe2BALpYq/D7Yc7uA4tPdxSfWjLhb0B//8rKSkRrRqoFgA "05AB1E – Try It Online") Takes the input as a multiline string (input between *"""*). Explanations to come later. [Answer] # Python 3 (3.4?), 350 bytes A tricky challenge for a language as particular about whitespace as Python 3. The submission prints `0` or `1` to standard out and crashes for some inputs. The program expects the final line to be properly terminated, i.e. end with a newline character. The final line of the program is similarly terminated. UTF-8 is used to check byte parity. Tabs are replaced with spaces in this view. ``` 0 i\ = 1 t=(# '0'* 0) ;( g,) =(# open (1 , "w"),) k = eval ( 'p' + 'rin' + 't' ) #01 for a in (#0 open ( 0) ):#0 #01010101010101 a = a [:- 1 ] # if ( len (a )<i\ or len (a )>i ):[\ k('0' ),1 /0] #0101 i, t= -~i, t+ a #01 (k( 2-len ({(c^i )&1\ for i,c in eval (#0 "enu"+"m"+"erate")(#01 eval ( " byte"+"s")( t# ,' u8' ) ) } ) ) ) #01010 ``` Works for me with Python 3.4.2; doesn't work on any Python 3 on TIO. Seems to me to be a bug in TIO's interpreters. ## Hex Dump Revert with `xxd -p -r` on Unix. ``` 300a695c0a3d20310a743d28230a202730272a0a093029203b280a672c29 203d28230a206f70656e0928310a2c09227722292c29200a6b203d206576 616c09280a277027202b202772696e270a202b202774272029202330310a 666f7209206120696e092823300a6f70656e092809302920293a23300a23 30313031303130313031303130310a2061203d2061205b3a2d2031205d20 230a2069660928096c656e09286120293c695c0a6f72096c656e09286120 293e6920293a5b5c0a6b2827302720292c31202f305d2023303130310a20 692c09743d202d7e692c09742b2061202330310a286b2809322d6c656e09 287b28635e69202926315c0a09666f720920692c6320696e09206576616c 092823300a0922656e75222b226d222b2265726174652229282330310a20 6576616c092809220962797465222b22732229280974230a2c2720753827 20292029207d202920292029202330313031300a ``` [Answer] # Java 10, 209 bytes A void lambda taking an iterable or array of `byte`. Indicates true by returning normally, false by throwing a runtime exception. The program expects the final line to be properly terminated, i.e. end with a newline character. The final line of the program is similarly terminated. Everything is done under UTF-8, with the interpretation that "character" refers to Unicode code points. Tabs are replaced with spaces in this view. ``` d -> { long f= 1, h=0 , c = - 1 ,e ;for ( byte a: d) {var b =(e = a^10) <1&e>- 1 ;f= b?( h ^ f)> 0 ?0/0 : f+ 1: f ;h=b?0 :a>-65 ? h+ 1: h; c =b? c :c>=0 & ( (c^a )& 1 )<1 ?0/0 :a ; } /*1010101010101*/ } ``` [Try It Online](https://tio.run/##ZVLBcpswED2vvmInB49IbSwd2oMxeJpOb@2lOSZxRwhhcLHwIOHW4@HQf8t/uUIQO0mHYUFv33urXWkrDmK2zX6d921alRJlJYzB76LUeCIwgsYK6z55qUWFW6cIW1tWYd5qactah19qbdqdapbp0aqHpwRzjM8ZmSXkhECqWm9IHiOfEihiBlMiMcYZcjJVGOV1A4RCr0SxIJAFeDqIBlISU@V4Ys1ZQJZ8ohIncfyYpCsKBawhDxJgZMXmDBaQf0DuIomKOF05QCSzTx9xRQqPFxG6oukKJVnIxG1iAhSoXAsMJoRjsOQ4@AiMsEMyv@Xs1XM7x46cISLvR3Koywx3blr03jal3jw8oWg2JuiHBxdICqOM60Wr33gBewbcsEfN/csfNfPxZuoTfu0xn2WvE89/XyQj5lYDfVz/78o4429EXeTC9Sy/lcYu7@q6UkIn2CjTVvZly1fW56YRR09NaNAbuNPDsXXf5U9cDN0OE4B0cBwNnZ9tWtULwTbHgQJ5KKRUe0u9QbhR9s5dBkMDXwG6PkhhZYH0R6ttuVNf//R8d/NQjXXgUiAXlVFX4dhJKLKMDv/etc/dH41Vu7Bubbh3DdhKjwzTUzrSnf8B) ## Hex dump Revert with `xxd -p -r` on Unix. ``` 640a2d3e0a7b20090a6c6f6e670a663d20312c0a09683d30092c0a63203d 202d20310a2c65203b666f72090a28096279746520613a0a096429207b76 617209620a3d2865203d20615e3130290a3c3126653e2d2031203b663d0a 623f280968095e0966293e09300a3f302f30093a09662b20313a09660a3b 683d623f30093a613e2d3635203f0a682b20313a09683b2063203d623f20 630a3a633e3d30092609280928635e612029260a3120293c31203f302f30 093a61203b207d200a2f2a313031303130313031303130312a2f207d0a ``` ## Ungolfed ``` d -> { long f = 1, h = 0, c = ~h, e; for (byte a : d) { var b = (e = a^10) < 1 & e > -1; f = b ? (h^f) > 0 ? 0/0 : f + 1 : f ; h = b ? 0 : a > -65 ? h + 1 : h ; c = b ? c : c >= 0 & ((c^a) & 1) < 1 ? 0/0 : a ; } } ``` `f` is the expected number of characters on the current line, `h` is the number of characters seen so far on the current line, `c` is the last byte seen, and `b` is whether `a` is the newline. The condition `a > -65` tests whether `a` is the first byte in a character. This works because the single-byte (ASCII) characters are nonnegative in 8-bit two's complement, the first byte of longer characters has binary form `11xxxxxx` (at least -64 in two's complement), and the non-leading bytes in those characters are of the form `10xxxxxx`, at most -65 in two's complement. ([Source](https://en.wikipedia.org/wiki/Utf-8#Description)) When a character violates the triangular or checkerboard pattern (i.e. a newline appears early or late or a byte of the wrong parity appears), the left branch of the corresponding ternary (in assignment to `f` or `c`) activates and the method throws an arithmetic exception. ]
[Question] [ Today's date is quite an interesting one. Let's take a look at why. The date `07/12/2017` (in `DD/MM/YYYY` date format) can be split into the year (`2017`) and the rest (`07/12`). You may notice that the digits in the year can be rearranged to match the digits in the rest of the date, which is the basis of this challenge. ## The task Given an valid integer (e.g. no leading zeros) representing a year, consisting of exactly four digits, output all **unique** possible valid dates that can be made from those digits. You may take the number as a list of digits, or a string representing the input if you want. Each number in the input must be used **exactly once** in each of the final outputs. As leading `0`s aren't used in integers, the input will be in the range `1000 <= input <= 9999`. A valid date is one in which the date exists on the [Gregorian Calendar](https://en.m.wikipedia.org/wiki/Gregorian_calendar), such as `17/05/2000`. The only corner case is February 29th, which is only a valid date when the year is a leap year. You can (but don't have to) assume that leap years are years that are divisible by 4. You have to output a separator between the day and the month (e.g. `/`) and a **different** separator between different dates. You may optionally output the year with each date, but this must be consistent between dates. Finally, you may choose between the date format order, i.e. you can output as any of `DD/MM/YYYY`, `MM/DD/YYYY` etc. but leading `0`s are required when the input contains at least one `0`. Essentially, you may output in any obviously understandable format, such as an array of strings, one concatenated string etc. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins! ## Test cases ``` input outputs 2017 07/12, 12/07, 17/02, 21/07, 27/01, 27/10 2092 22/09, 29/02 2029 22/09 1000 Nothing 8502 25/08, 28/05 ``` [Reference Implementation](https://tio.run/##RVDLasQwDLz7K3QJttmQlC2FspDrfkEvpfRg1g51SWwjK6X5@lRK93ERGo00Gqms9JXT87bFuWQkiBSQcp5qCxTnoJQPI/y4KXrjHdmTAsKV4852lbBIIlwLuvF9M/fNu7bcgIEWTPCGS1AQfi@h0OlRPrupsvoaHMIAMZWFjFWV88o2gjd3I10JOC/kKOZUjQy0cLRWyVztLrmsPDgKCCKhxozg3cqaUHmhwDkngSj7JR9A6@47x2QYiVfpfxQZSTHeDtf9lfhgphWFFsTHp7Xgkr85ZvIgejDcj5Au@RnA2Dm/t8ABWI/jvloVjImM5uf9r7gOjtbabXt9eTr@AQ "Python 3 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~31~~ ~~30~~ ~~26~~ ~~24~~ ~~23~~ ~~22~~ 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Locale dependent. Outputs a 2D-array of the format `[["MM","DD"],...]`. ``` á â mò fÈÎ-ÐNcX)Î ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4SDiIG3yIGbIzi3QTmNYKc4&input=IjIwMTciCi1R) or [Try It Online!](https://tio.run/##ASkA1v9qYXB0///DoSDDoiBtw7IgZsOIw44tw5BOY1gpw47//yIyMDE3IgotUQ) (to avoid the locale dependency) ## Explanation If it wasn't for JavaScript's `Date` object wrapping invalid dates, I'd be able to get this down to [about ~~20 18~~ 16 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4SCj0E5jWPLDZs1tczcg4g&footer=8SCurzXDcVNpLA&input=IjIwMTci). Even when providing its argument as a single string, which the spec says *shouldn't* lead to wrapping, dates up to 31 still do for months that don't have 31 days. However, as the month's can only wrap over by one, we can take advantage of the fact that string arguments use 1-based months to simply filter by subtraction - if the month rolls over then the result of that subtraction will be `0`. ``` á â mò fÈÎ-ÐNcX)Î :Implicit input of N=[U="YYYY"] á :Permutations of U â :Deduplicate m :Map ò : Partitions of length 2 (=[["MM","DD"],...]) f :Filter È :By passing each X through the following function Î : First element of X - : Subtract Ð : Create new Date from NcX : N concatenated with X (=["YYYY","MM","DD"], which gets coerced to "YYYY-MM-DD", with MM being 1-based) ) : End date creation Î : 0-based month (=NaN for invalid dates, n-NaN=NaN) ``` --- ## Original, 22 bytes Preserving this, 'cause I really liked the setwise union trick. ``` á â¡ÐNcXòÃfÈÎ-2îUvÃms7 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4QriodBOY1jyw2bIzi0y7lV2w21zNw&footer=VvEgrq81w3FTaSw&input=IjIwMTci) (footer formats the output to match the examples in the challenge) Or [Try it online!](https://tio.run/##AUQAu/9qYXB0///DoQrDosKhw5BOY1jDssODZsOIw44tMsOuVXbDg21zN/9Wwq7CrsO5VDJ9Jy8gwq81w4NxU2ks/yIyMDE3Ig) to somewhat mitigate the locale dependency - TIO's locale doesn't include leading 0s for dates & months, so they're added back in in the footer. ### Explanation ``` á\nâ¡ÐNcXòÃfÈÎ-2îUvÃms7 :Implicit input of N=[U="YYYY"] á :Permutations of U \n :Reassign to U, leaving the value in N unchanged â :Setwise union with ¡ :Map each X in U Ð : New Date from Nc : N concatenated with Xò : Partitions of X of length 2 (=["YYYY","MM","DD"], which gets coerced to "YYYY-MM-DD", with MM being 1-based) à :End map f :Filter by È :Passing each through the following function Î : Get 0-based month (=NaN for invalid date) - : Subtract (NaN-n=NaN) 2î : First 2 characters of Uv : Remove and return first element of U à :End filter m :Map s7 : To locale date string (="DD/MM/YYYY") ``` The reason the setwise union doesn't include any elements from the first array is because `v` modifies that array so the filter ends up removing all elements from it. In the 16 byte version, which assumes a way to avoid dates wrapping over, we don't need to reassign the array of possible dates to U and instead filter by using `Í` to try to subtract the timestamp from 2, which will result in `NaN` if the date is invalid. We can't use the setwise union trick, though, so `â` get tacked on the end to deduplicate the final array. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œÙ2δôʒ`ÐU13‹rD•ü¯B•5°I4Ö*+ºS₂+Xè‹PĀ ``` 05AB1E doesn't have any date builtins, so manual calculations it is. Therefore all years divisible by 4 are counted as leap years (which is allowed in the challenge description), since that's shorter than [actual leap year calculations](https://codegolf.stackexchange.com/a/177019/52210). Output as a list of `[dd,MM]`-pairs. [Try it online](https://tio.run/##AUgAt/9vc2FiaWX//8WTw5kyzrTDtMqSYMOQVTEz4oC5ckTigKLDvMKvQuKAojXCsEk0w5YqK8K6U@KCgitYw6jigLlQxID//zIwOTI) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@PTj480@jclsNbTk1KODwh1ND4UcPOIpdHDYsO7zm03glImx7acGidyeFpWtqHdgU/amrSjji8Aqgm4EjD/1qd/9FGBobmOkYGlkZAwshSx9DAwEDHwtTAKBYA). **Explanation:** ``` œ # Get all permutations of the (implicit) input-integer Ù # Uniquify this list δ # For each permutation: 2 ô # Split it into parts of size 2 ʒ # Filter this list of [dd,MM]-pairs by: ` # Pop and push both values separated to the stack Ð # Triplicate the top value MM U # Pop and store one MM in variable `X` 13‹ # Check whether MM is smaller than 13 r # Reverse the values on the stack, so the order is MM<13,MM,dd D # Duplicate the top value dd •ü¯B• # Push compressed integer 16365656 5° # Push 10⁵: 100000 I # Push the input-year 4Ö # Check if it's divisible by 4 (1 if truthy; 0 if falsey) * # Multiply that by the 100000 (100000 if it's a 'leap year'; 0 if not) + # Add it to the 16365656 (16465656 if it's a 'leap year'; 16365656 if not) º # Mirror it: 1636565665656461 / 1646565665656461 S # Convert it to a list of digits: [1,6,3/4,6,5,6,5,6,6,5,6,5,6,3/4,6,1] ₂+ # Add 26 to each: [27,32,29/30,32,31,32,31,32,32,31,32,31,32,29/30,32,27] X # Push MM from variable `X` è # Index it into this list (0-based modulair, hence the leading dummy 27) ‹ # Check if dd is smaller than the indexed value P # Take the product of all values on the stack: (MM<13)*MM*dd*(dd<...) Ā # Check that this is NOT 0 # (after which the filtered list of [dd,MM]-pairs is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•ü¯B•` is `16365656`. [Answer] # [R](https://www.r-project.org/), ~~231~~ ~~216~~ ~~189~~ 186 bytes *Edit: -42 bytes by keeping numbers as numbers (no conversion to text) and using sprintf to fix the leading zeros* ``` function(y){e=unique(gtools::permutations(4,4,y%/%10^(0:3)%%10,F)) m=e[,1]*10+e[,2];n=e[,3]*10+e[,4] sprintf("%02d/%02d",m,n)[which(m&n&(m<(31-rep(-1:0,l=13)[-8])[n]-(n==2)*(2-!y%%4)))]} ``` [Try it online!](https://tio.run/##bc/BTsMwEATQe76iFLnaLY5qO0G0AV/5icig0rqNpXgdYkcoQnx7aA5cWi6j0ZvT9FMXYnQfrX0/7pONejoNdEguEIz4bfVA7nOwcE4htLGqOtv7Ie3nPULJSz6yDZPiDURVILs0/oqYeW1rLs1aiodLUeaZZij@oDRZ7HpH6QRLJtRxM8eSe05YfzXu0IBf0Qr8CxQy720HuawEb7UssM63BmsyOZDWCteg8ruRsRIRzc/VFVBCPmF2gzv1D6rdDUohBC7uFxRS4@h8PW8fhcLpFw "R – Try It Online") This challenge seemed quite innocuous when I read it, but turned-out to be much, much more complicated than I thought to implement! The actual checking for possible day/month combinations is less than one-third of the code! Finds all unique permutations of the digits of the year, combines them in pairs as numbers ~~text (to keep leading zeros),~~ then finds the indices that are possible ~~after converting back to numbers~~, and `sprintf`s the output to keep the leading zeros. Calculates days in months as `(31-rep(-1:0,l=13)[-8])` which gives all correct except Feb, then adjusts with `-(month==2)*(2-!y%%4))` to fix Feb for leap-years. Original commented code (before quite a lot of golfing): ``` possible_dates= function(y, # y = year (number) `+`=as.double, # `+` = alias to as.double() function, to easily # convert text to numbers a=apply, # a = alias to apply() function (runs helper function over all elements of matrix) p=paste0){ # p = alias to paste0 function (joins text together) d=a( # d (digits) = unique( # get the unique combinations of... gtools::permutations(4,4, # all permutations of... y%/%10^(0:3)%%10,F)) # the digits of the year... ,1,function(i) # and, for each combination... p(i[1:2],i[3:4])) # paste-together the first & second two digits as text a(d,2,p,collapse="/") # now, paste these together with '/' as separator, [which( # but only output those that satisfy... (m=+d[1,])& # first element (days) non-zero, and... (n=+d[2,])& # second element (months) non-zero, and... (m<(31-rep(-1:0,l=13)[-8])[n] # days less than days in the month... -(m==2)*(2-!y%%4)) # with correction for leap-years )] } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~94~~ ~~91~~ ~~90~~ 88 bytes *-3 bytes thanks to @Shaggy and another -2 bytes thanks to @vrintle* ``` ->y{[]|y.permutation.map{|d|("#{Time.gm y*'',(d*'')[/../],$'}"rescue$/)[/\S+-#$'/]}-[p]} ``` [Try it online!](https://tio.run/##FcjBDoIgAADQX2HqhhUCsrXyUD9RN@JgisaBYohtDPh2sss7PLs@fZ4uubn6wEX02EirV9c79Xlj3ZsQx1gXZbgrLfGsgd9DiOpxc8cJxkSgCqbCymVYZUW2e9wOTVlBIlLDjUiZM9qeEGC0Y39Zh0BLKUXgfKRMYNkPrwCii8CAiTs8qlm5BVv5lXaRAqT8Aw "Ruby – Try It Online") Takes input as an array of digits and returns an array of date strings in `yyyy-mm-dd` format. Leap years are handled correctly, i.e. it is *not* assumed that all years that are divisible by 4 are leap years. A gotcha with the `Time` library is that it sets an upper limit of 31 days for all months, silently wrapping to the next real calendar date, so a sanity check is required. Invalid months are automatically rejected. ``` ->y{ []| # combine with empty array y.permutation # form all permutations of the year digits .map{|d| # loop over permutations ("#{Time.gm y*'',(d*'')[/../],$'}" # (attempt to) create a time string using the first two digits of the permutation as the month and the last two digits as the day rescue$/) # if the time is invalid, rescue the exception and return a dummy string ($/) instead [/\S+-#$'/] # check that the day is the same as expected (to prevent date wrapping) and extract the full date if so } -[p] # remove nil elements } ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~149~~ 140 bytes Uses the simplified definition of leap years. ``` lambda y:{i+o+'/'+z+u for z,u,i,o in permutations(str(y))if((m:=int(z+u))==2)*~(y%4>0)+(m//8^m%2)+31>int(i+o)>0<m<13} from itertools import* ``` [Try it online!](https://tio.run/##FY5BCoMwFET3nuJvxMQEjLGlKupJSsFSQwPGH2JcxNJe3ZrNW83MGxv8G5eqtu5Q/f2YR/N8jRDaj2bIsiJjO9tAoYOdb1xzBL2AnZzZ/Og1LitZvSOBUq0IMW2vF0/OBqV9L2n@IyG9DIIyYoqifphUUlaVQwyd83QQnenK6psohwa0n5xHnFfQxqLz@RG1IQqlKG/8ZCMjZcOhFEJwqK9CtgmAdXFSxR9HzP4B "Python 3.8 (pre-release) – Try It Online") [Answer] ## Python 3, ~~186~~ 197 bytes ``` import itertools;import datetime;y=input();s=set() for p in itertools.permutations(list(y)): try:f=datetime.date(int(y),int(p[2]+p[3]),int(p[0]+p[1]));s.add(f) except:pass for d in s:print(d) ``` [Answer] # [k4](https://code.kx.com/q/ref/), 55 bytes ``` {?,/(@[.:;;()]x,"."/:0 0 2_)'(,"")(,/{(1_x),*x}\',')/x} ``` Not the most elegant, but it outputs a list of valid dates (accounting for e.g. leap years). Takes a string as input, e.g. `"2017"`. * `(,"")(,/{(1_x),*x}\',')/x` builds a list of the permutations of the input * `x,"."/:0 0 2_` takes each permutation, prepends the input year, and inserts `"."`s to format it as a date. E.g., for an input of `"0127"`, the output is `"2017.01.27"`. * `@[.:;;()]` is [error trap](https://code.kx.com/q/ref/apply/#trap); it attempts to eval the generated date string, returning an empty list if the value is an invalid date. * `?,/` returns the distinct valid dates ]
[Question] [ This is the Robber post. The [Cop post is here](https://codegolf.stackexchange.com/q/146926/31516). --- Your task is to take an integer input **N** and output the **Nth** digit in the sequence [OEIS A002942](http://oeis.org/A002942). The sequence consists of the square numbers written backwards: ``` 1, 4, 9, 61, 52, 63, 94, 46, 18, 1, 121, 441, ... ``` Note that leading zeros are trimmed away (**100** becomes **1**, not **001**). Concatenating this into a string (or one long number gives): ``` 1496152639446181121441 ``` You shall output the **Nth** digit in this string/number. You may choose to take **N** as 0-indexed or 1-indexed (please state which one you choose). ### Test cases (1-indexed): ``` N = 5, ==> 1 N = 17, ==> 1 <- Important test case! It's not zero. N = 20, ==> 4 N = 78, ==> 0 N = 100, ==> 4 N = 274164, ==> 1 ``` Your code should work for numbers up to **N = 2^15** (unless your language can't handles 32 bit integers by default, in which case **N** can be lower). --- ## Robbers: You should try to crack the Cops' posts. Your code must be in the same language as the Cop post, and have a Levenshtein distance exactly equal to the distance given by the cop. Your code cannot be longer than the original solution (but it can be the same size). You may [check the Levenshtein distance here!](https://planetcalc.com/1720/) The winner will be the robber that cracked the most posts. [Answer] # [Haskell](https://www.haskell.org/), [Laikoni](https://codegolf.stackexchange.com/a/146956/71256) ``` ((show.(*1).read.reverse.show.(^2)=<<[1..])!!) ``` [Try it online!](https://tio.run/##Xc2xDoIwEAbgnac4EwdqjoYiUkmoj@DiiJg0WMQI2lDUwfjqVlJMSLzhhi//f1dLc1FNYyuxt75v6tuT@gtGaKfkcVgP1RlFRz5ERGRZzigtyGxGbCvPVxCg7/2u72AOrdRQQR4jS5ClyDmmKUY8Zsmy8F6Btx3CKwQ3QmyAOWEc/yQKJ4md8PUk4dgKx9CUcY9i/N0J3vZTVo08GRuUWn8B "Haskell – Try It Online") The `(*1)` was necessary for type checking. [Answer] # [JavaScript, Arnauld](https://codegolf.stackexchange.com/a/146947/3852) ``` /*ZZ*/m=>[...Array(m+1).keys()].map(eval(atob("eD0+K1suLi4iIit4KnhdLnJldmVyc2VgYC5qb2luYGA="))).join``[m] ``` [Answer] # [cQuents 0](https://github.com/stestoltz/cQuents/tree/cquents-0), [Stephen](https://codegolf.stackexchange.com/a/146958/56433) ``` ":\r$$ ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/X8kqpkhF5f9/IwMA "cQuents 0 – Try It Online") I have no idea how this code works, but it still worked after removing the `*`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), [Jenny\_mathy](https://codegolf.stackexchange.com/a/146952/74672) ``` (Join@@Table[k@FromDigits@Reverse@(k=IntegerDigits)[i*i],{i,10^4}])[[#]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/Bfwys/M8/BISQxKSc1OtvBrSg/1yUzPbOk2CEotSy1qDjVQSPb1jOvJDU9tQgioRmdqZUZq1OdqWNoEGdSG6sZHa0cG6v2P6AoM69EwSEt2ijO0DT2PwA "Wolfram Language (Mathematica) – Try It Online") Alternative version also at distance 43: ``` (Join@@IntegerDigits@IntegerReverse[Range@#^2])[[1#]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/Bfwys/M8/BwTOvJDU9tcglMz2zpBjGC0otSy0qTo0OSsxLT3VQjjOK1YyONlSOjVX7H1CUmVei4JAWbRRnaBr7HwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [6502 Machine Code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), [Felix Palmen](https://codegolf.stackexchange.com/a/147042/75557) I tested this with all the questions test cases and quite a few extras (like 2^15... that took awhile), and it appears to work the same as the original with LD = 1. ``` 00 C0 20 FD AE A0 00 99 5B 00 C8 20 73 00 90 F7 99 5B 00 A2 0B CA 88 30 09 B9 5B 00 29 0F 95 5B 10 F3 A9 00 95 5B CA 10 F9 A9 01 A0 03 99 69 00 88 10 FA A0 20 A2 76 18 B5 E6 90 02 09 10 4A 95 E6 E8 10 F4 A2 03 76 69 CA 10 FB 88 F0 11 A2 09 B5 5C C9 08 30 04 E9 03 95 5C CA 10 F3 30 D6 A2 03 B5 69 95 57 CA 10 F9 A9 01 85 FB A2 03 A9 00 95 FB CA D0 FB A2 03 B5 FB 95 22 95 26 CA 10 F7 A9 00 A2 03 95 69 CA 10 FB A0 20 A2 02 46 25 76 22 CA 10 FB 90 0C A2 7C 18 B5 AA 75 ED 95 ED E8 10 F7 A2 7D 06 26 36 AA E8 10 FB 88 10 DD A0 0B A9 00 99 5A 00 88 D0 FA A0 20 A2 09 B5 5C C9 05 30 04 69 02 95 5C CA 10 F3 06 69 A2 FD 36 6D E8 D0 FB A2 09 B5 5C 2A C9 10 29 0F 95 5C CA 10 F4 88 D0 D7 E0 0A F0 05 E8 B5 5B F0 F7 09 30 99 5B 00 C8 E8 E0 0B F0 04 B5 5B 90 F1 88 B9 5B 00 C9 30 F0 F8 A2 7C 18 B5 DB E9 00 95 DB E8 10 F7 90 14 88 30 05 B9 5B 00 D0 EA A2 7C F6 7F D0 03 E8 10 F9 4C 73 C0 B9 5B 00 4C D2 FF ``` **[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22sqdig.prg%22:%22data:;base64,AMAg/a6gAJlbAMggcwCQ95lbAKILyogwCblbACkPlVsQ86kAlVvKEPmpAaADmWkAiBD6oCCidhi15pACCRBKleboEPSiA3ZpyhD7iPARogm1XMkIMATpA5VcyhDzMNaiA7VplVfKEPmpAYX7ogOpAJX7ytD7ogO1+5UilSbKEPepAKIDlWnKEPugIKICRiV2IsoQ+5AMonwYtap17ZXt6BD3on0GJjaq6BD7iBDdoAupAJlaAIjQ+qAgogm1XMkFMARpApVcyhDzBmmi/TZt6ND7ogm1XCrJECkPlVzKEPSI0NfgCvAF6LVb8PcJMJlbAMjo4AvwBLVbkPGIuVsAyTDw+KJ8GLXb6QCV2+gQ95AUiDAFuVsA0OqifPZ/0APoEPlMc8C5WwBM0v8=%22%7D,%22vice%22:%7B%22-autostart%22:%22sqdig.prg%22%7D%7D)**, usage: sys49152,n where n is the 0-indexed input. [Answer] # [Lua](https://www.lua.org), [Katenkyo](https://codegolf.stackexchange.com/a/146933/41024) ``` i=1s=""while(#s<...+0)do s=s..((i*i)..""):reverse():gsub("(0+)(%d+)$","%2")i=i+1 end print(s:sub(...,...)) ``` [Try it online!](https://tio.run/##FcxBCsJADEbhvaco0UJ@p4RWcDM4h1EmaKBUmVg9fqyLt/t483qNsDJ5Ifo@bFbe@0VE0oj67Ly4CLMdDSJEyE0/2lwZ@e7rjYnHBO5rwoEG6k8EK5amTpe6ezVb3uz577bhsAVExPkH "Lua – Try It Online") I don't know Lua, but this was a simple one, just replaced a space with a newline. [Answer] # [Python 3](https://docs.python.org/3/), [HyperNeutrino](https://codegolf.stackexchange.com/a/146930/59487) ``` lambda o:"".join(str(p*p+2*p+1)[::~0].lstrip("0")for p in range(o+1))[o] ``` [Try it online!](https://tio.run/##RcoxDoMwDEDRq0SZbCqhAFuknoQyBLUBI7CtkKVLrx7C1OEvT1@/eRUeSny@yh6O@R2MeGvbTYjhzAm00Udf63D0/uemdq9KCtZZjJKMGmKTAi8fkDrhKFO5nf7eOfSaiDNEIMRyAQ "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), [dylnan](https://codegolf.stackexchange.com/a/146990/62393) ``` d=lambda y:y if y%10>0 else d(y/10) lambda n:''.join([str(d(x*x))[::-1]for x in range(1,n+1)])[n-1]#fix ``` [Try it online!](https://tio.run/##Zcq9DsIgEADg3ae4xJjeWX@gI4l9EdIBAyimPRrKAE@PXZycv2@t@R15aM0@ZrM8rYGqKgQP9STFKMDNmwOL9S4FHfzvsOq62ycGRr3lhBbLuRBppa5y8jFBgcCQDL8cygv3kibSvNvRh9LWFDij9lgI/vIg9tu@ "Python 2 – Try It Online") Note: this cop submission was bugged and didn't work for inputs lower than 5. While I was at it I built this solution which has the correct Levenshtein distance AND fixes the bug. [Answer] # Perl 5, (-p) Xcali Updated after comment, Levenshtein Distance between ``` a$j.=int reverse$_**2for 1..$_;$_--;say$j=~s/.{$_}(.).*/$1/r ``` and ``` p$_=substr w.(join"",map{whyddwzz;0|reverse$_**2}1..$_),$_,1 ``` is 55 [Try it online](https://tio.run/##K0gtyjH9/18l3ra4NKm4pEihXE8jKz8zT0lJJzexoLo8ozIlJcXaoKYotSy1qDhVJV5Ly6jWUE9PJV6nvKpKUwdIG/7/b2j@L7@gJDM/r/i/bgEA) [Answer] # Java 8, [Kevin Cruijssen](https://codegolf.stackexchange.com/a/147029/58563) ``` /*!FooBarFooBarFoo!*/N->{String R="",T=R;for(int I=1,J;N+2>R.length();I++){for(T="",J=(I*I+"").length();0<J;T+=(I*I+"").charAt(--J));R+=new Long(T)+"";}return R.charAt(N);} ``` [Try it online!](https://tio.run/##hZHBa4MwFMbv@ytePSVa7exKpWQWtsNA2TxYb2OHzKbWziYSY8cQ/3Yba7eehpAE3vt@PN735UBP1BYl44ftV5cWtKrgjea8uQPIuWJyR1MGUV8CpHsqIUW6DxwT3Wr11adSVOUpRMDBh25mTl6EeKby752Ys8heNxslc55B7BvGNPFjshPyMivw3WlIImu@jp2C8UztESaBZeGmJ5IeD30UmIFlGPhG3D@GJLFuQr/dk0K2HWJMYsvn7BteBc9QgrVOWslULTnEv2CESduRwUFZfxbawdXISeRbOOoU0LDy@wdQPESw@akUOzqiVk6pJVVwxJ0ULfAlj391dzkGrEYAzxsBVmMT5t7CXT7g68e13Rk "Java (OpenJDK 8) – Try It Online") ### Change log * Replaced `.replaceAll()` with `new Long()`. * Removed the test for perfect squares. Now using perfect squares directly. * Updated all variable names to upper-case. * Rewritten the inequalities. * And finally added a 21-byte leading comment to reach the correct LD. [Answer] # [Octave](https://www.gnu.org/software/octave/), [Stewie Griffin](https://codegolf.stackexchange.com/a/147034/42295) ``` @(n)regexprep(fliplr(num2str((1:n)'.^2))'(:)',' +0*','')(n)%abcdefghijk ``` [Try it online!](https://tio.run/##HYtBCsIwEEX3nsJNmRktIQnVlILgSYRaZ2q1xhCrePuYuHmP/@A/h6X/cJKDUiod0VPkkb8hckCZpzBH9O@HfS0R0XSeQJ0sEWBHUMN6qzdZQPlW9efhwjJep9s9CRpaCe4KjCu0utC1/6LzqHJzjdk3lH4 "Octave – Try It Online") I was actually attempting my own Octave answer and spotted the existing one. Mine was already significantly shorter so adding a comment at the end was sufficient to get to the required distance of 63. [Answer] # PHP, [Jo.](https://codegolf.stackexchange.com/a/147087/75905) ``` <?for($j++;strlen($p)<$argv[1];$j++)$p.=(int)strrev($j**2);echo($p[$argv[1]+2-3]); ``` [Try it online!](https://tio.run/##NcpBCoAgEADAz3hwFSPraNFDokOEZRG6qPj8Njt0nkGHRMO0h8jZJaVJOd7Wc4YwsDUeZdaL@QAYNiM/fYY6oi11C9GBsZsLdc9/lp3qFzBEpNv2CZjP4BMp/wI "PHP – Try It Online") (I was planning to switch the inequality in order to get even larger LD...) [Answer] # [6502 Machine Code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), [Felix Palmen](https://codegolf.stackexchange.com/a/147652/75557) May also be a "simple" crack, but it *appears* to work as the original. Having the LD = 1 is just so tempting to try to crack it (sorry, Felix). :) ``` 00 C0 20 FD AE A0 00 99 5B 00 C8 20 73 00 90 F7 99 5B 00 A2 0B CA 98 88 30 09 B9 5B 00 29 0F 95 5B 10 F2 95 5B CA 10 FB A0 20 A2 76 18 B5 E6 90 02 09 10 4A 95 E6 E8 10 F4 A2 03 76 69 CA 10 FB 88 F0 11 A2 09 B5 5C C9 08 30 04 EB 03 95 5C CA 10 F3 30 D6 A2 03 B5 69 95 57 CA 10 F9 A9 01 85 FB A2 03 A9 00 95 FB CA D0 FB A2 03 B5 FB 95 22 95 26 CA 10 F7 A9 00 A2 03 95 69 CA 10 FB A0 20 A2 02 46 25 76 22 CA 10 FB 90 0C A2 7C 18 B5 AA 75 ED 95 ED E8 10 F7 A2 7D 06 26 36 AA E8 10 FB 88 10 DD A2 0B A9 00 95 5A CA D0 FB A0 20 A2 09 B5 5C C9 05 30 04 69 02 95 5C CA 10 F3 06 69 A2 FD 36 6D E8 D0 FB A2 09 B5 5C 2A C9 10 29 0F 95 5C CA 10 F4 88 D0 D7 E8 B5 5B F0 FB 09 30 99 5B 00 C8 E8 E0 0B F0 04 B5 5B 90 F1 88 B9 5B 00 C9 30 F0 F8 A2 7C 18 B5 DB E9 00 95 DB E8 10 F7 90 14 88 30 05 B9 5B 00 D0 EA A2 7C F6 7F D0 03 E8 10 F9 4C 68 C0 B9 5B 00 4C D2 FF ``` **[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22sqdig.prg%22:%22data:;base64,AMAg/a6gAJlbAMggcwCQ95lbAKILypiIMAm5WwApD5VbEPKVW8oQ+6AgonYYteaQAgkQSpXm6BD0ogN2acoQ+4jwEaIJtVzJCDAE6wOVXMoQ8zDWogO1aZVXyhD5qQGF+6IDqQCV+8rQ+6IDtfuVIpUmyhD3qQCiA5VpyhD7oCCiAkYldiLKEPuQDKJ8GLWqde2V7egQ96J9BiY2qugQ+4gQ3aILqQCVWsrQ+6Agogm1XMkFMARpApVcyhDzBmmi/TZt6ND7ogm1XCrJECkPlVzKEPSI0NfotVvw+wkwmVsAyOjgC/AEtVuQ8Yi5WwDJMPD4onwYtdvpAJXb6BD3kBSIMAW5WwDQ6qJ89n/QA+gQ+UxowLlbAEzS/w==%22%7D,%22vice%22:%7B%22-autostart%22:%22sqdig.prg%22%7D%7D)**, usage: sys49152,n where n is the 0-indexed input. ]
[Question] [ In [Keep Talking and Nobody Explodes](http://www.keeptalkinggame.com/), players are tasked with defusing bombs based on information from their "experts" (other people with a manual). Each bomb is made up of modules, one of which can be passwords, where the expert is given this list of possible passwords, all five letters long: ``` about after again below could every first found great house large learn never other place plant point right small sound spell still study their there these thing think three water where which world would write ``` And the player is given a list of 6 possible letters for each place in the password. **Given the possible letter combinations, output the correct password.** Input can be in any reasonable format (2D array, string separated by newline, etc.) **You may discount the code which you use to compress/generate the list/string/array/whatever of passwords.** (Thanks @DenkerAffe) NOTE: Passwords are case insensitive. You may assume that input will only solve for one password. ## Examples / Test Cases Input here will be represented as a array of strings. ``` ["FGARTW","LKSIRE","UHRKPA","TGYSTG","LUOTEU"] => first ["ULOIPE","GEYARF","SHRGWE","JEHSDG","EJHDSP"] => large ["SHWYEU","YEUTLS","IHEWRA","HWULER","EUELJD"] => still ``` [Answer] ## Pyth, 13 bytes ``` :#%*"[%s]"5Q0c"ABOUTAFTERAGAINBELOWCOULDEVERYFIRSTFOUNDGREATHOUSELARGELEARNNEVEROTHERPLACEPLANTPOINTRIGHTSMALLSOUNDSPELLSTILLSTUDYTHEIRTHERETHESETHINGTHINKTHREEWATERWHEREWHICHWORLDWOULDWRITE"5 ``` [Test suite.](https://pyth.herokuapp.com/?code=%3A%23%25%2a%22%5B%25s%5D%225Q0c%22ABOUTAFTERAGAINBELOWCOULDEVERYFIRSTFOUNDGREATHOUSELARGELEARNNEVEROTHERPLACEPLANTPOINTRIGHTSMALLSOUNDSPELLSTILLSTUDYTHEIRTHERETHESETHINGTHINKTHREEWATERWHEREWHICHWORLDWOULDWRITE%225&input=%5B%22FGARTW%22%2C%22LKSIRE%22%2C%22UHRKPA%22%2C%22TGYSTG%22%2C%22LUOTEU%22%5D&test_suite=1&test_suite_input=%5B%22FGARTW%22%2C%22LKSIRE%22%2C%22UHRKPA%22%2C%22TGYSTG%22%2C%22LUOTEU%22%5D%0A%5B%22ULOIPE%22%2C%22GEYARF%22%2C%22SHRGWE%22%2C%22JEHSDG%22%2C%22EJHDSP%22%5D%0A%5B%22SHWYEU%22%2C%22YEUTLS%22%2C%22IHEWRA%22%2C%22HWULER%22%2C%22EUELJD%22%5D&debug=0) ``` # filter possible words on : 0 regex match, with pattern % Q format input as "[%s]" surround each group of letters with brackets (regex char class) * 5 repeat format string 5 times for 5 groups of letters ``` [Answer] ## Bash, 22 bytes ``` grep `printf [%s] $@`< <(echo ABOUTAFTERAGAINBELOWCOULDEVERYFIRSTFOUNDGREATHOUSELARGELEARNNEVEROTHERPLACEPLANTPOINTRIGHTSMALLSOUNDSPELLSTILLSTUDYTHEIRTHERETHESETHINGTHINKTHREEWATERWHEREWHICHWORLDWOULDWRITE | sed 's/...../&\n/g') ``` Run like so: ``` llama@llama:~$ bash passwords.sh FGARTW LKSIRE UHRKPA TGYSTG LUOTEU FIRST ``` ``` printf [%s] $@ surround all command line args with brackets grep ` ` output all input lines that match this as a regex < use the following file as input to grep ``` [Answer] ## JavaScript (ES6), 62 bytes ``` (l,p)=>p.find(w=>l.every((s,i)=>eval(`/[${s}]/i`).test(w[i]))) ``` 53 bytes on Firefox 48 or earlier: ``` (l,p)=>p.find(w=>l.every((s,i)=>~s.search(w[i],"i"))) ``` Would have been 49 bytes if not for that case insensitivity requirement: ``` (l,p)=>p.find(w=>l.every((s,i)=>~s.search(w[i]))) ``` ``` f= (l,p)=>p.find(w=>l.every((s,i)=>eval(`/[${s}]/i`).test(w[i]))) ; p=["about","after","again","below","could","every","first","found","great","house","large","learn","never","other","place","plant","point","right","small","sound","spell","still","study","their","there","these","thing","think","three","water","where","which","world","would","write"]; o1.value=f(["FGARTW","LKSIRE","UHRKPA","TGYSTG","LUOTEU"],p) o2.value=f(["ULOIPE","GEYARF","SHRGWE","JEHSDG","EJHDSP"],p) o3.value=f(["SHWYEU","YEUTLS","IHEWRA","HWULER","EUELJD"],p) ``` ``` <input id=o1><input id=o2><input id=o3> ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 25 bytes ``` :@laL,["about":"after":"again":"below":"could":"every":"first":"found":"great":"house":"large":"learn":"never":"other":"place":"plant":"point":"right":"small":"sound":"spell":"still":"study":"their":"there":"these":"thing":"think":"three":"water":"where":"which":"world":"would":"write"]:Jm.'(:ImC,L:Im'mC) ``` The uncounted bytes are the array of words, including the square brackets. ### Explanation ``` :@laL Unifies L with the input where each string is lowercased ,[...]:Jm. Unifies the Output with one of the words '( ) True if what's in the parentheses is false, else backtrack and try another word :ImC Unify C with the I'th character of the output ,L:Im'mC True if C is not part of the I'th string of L ``` [Answer] # Ruby, ~~48~~ ~~42~~ 39 bytes Now that it's done, it's very similar to the Pyth solution, ~~but without `%s` formatting~~ to the point where it's basically a direct port now. If you only output the result with `puts`, you don't need the `[0]` at the end since `puts` will deal with that for you. ``` ->w,l{w.grep(/#{'[%s]'*l.size%l}/i)[0]} ``` With test cases: ``` f=->w,l{w.grep(/#{'[%s]'*l.size%l}/i)[0]} w = %w{about after again below could every first found great house large learn never other place plant point right small sound spell still study their there these thing think three water where which world would write} puts f.call(w, ["FGARTW","LKSIRE","UHRKPA","TGYSTG","LUOTEU"]) # first puts f.call(w, ["ULOIPE","GEYARF","SHRGWE","JEHSDG","EJHDSP"]) # large puts f.call(w, ["SHWYEU","YEUTLS","IHEWRA","HWULER","EUELJD"]) # still ``` [Answer] # JavaScript (ES6), 71 bytes ``` w=>l=>w.filter(s=>eval("for(b=1,i=5;i--;)b&=!!~l[i].indexOf(s[i])")[0]) ``` Usage: ``` f=w=>l=>w.filter(s=>eval("for(b=1,i=5;i--;)b&=!!~l[i].indexOf(s[i])")[0]) f(array_of_words)(array_of_letters) ``` [Answer] ## Python, ~~64~~ ~~60~~ 57 bytes Code to create word list `w` as string, words are space-separated (bytes are discounted from solution code length): ``` w="about after again below could every first found great house large learn never other place plant point right small sound spell still study their there these thing think three water where which world would write" ``` **Current solution (57 bytes):** *saved 3 bytes thanks to [@RootTwo](https://codegolf.stackexchange.com/users/53587/roottwo)* ``` import re;f=lambda a:re.findall("(?i)\\b"+"[%s]"*5%a,w)[0] ``` This function takes a `tuple` (no `list`!) of exactly 5 strings which represent the possible letters for each password character as input. [See this code running on ideone.com](http://ideone.com/LMRj9B) --- **Second version (60 bytes):** ``` import re;f=lambda a:re.findall("\\b"+"[%s]"*5%a+"(?i)",w)[0] ``` This function takes a `tuple` (no `list`!) of exactly 5 strings which represent the possible letters for each password character as input. [See this code running on ideone.com](http://ideone.com/BMSux4) **First version (64 bytes):** ``` import re;f=lambda a:re.findall("\\b["+"][".join(a)+"](?i)",w)[0] ``` This function takes any iterable (e.g. `list` or `tuple`) of exactly 5 strings which represent the possible letters for each password character as input. [See this code running on ideone.com](http://ideone.com/FuqAip) [Answer] ## [Hoon](https://github.com/urbit/urbit), 125 bytes ``` |= r/(list tape) =+ ^= a |- ?~ r (easy ~) ;~ plug (mask i.r) (knee *tape |.(^$(r t.r))) == (skip pass |*(* =(~ (rust +< a)))) ``` Ungolfed: ``` |= r/(list tape) =+ ^= a |- ?~ r (easy ~) ;~ plug (mask i.r) (knee *tape |.(^$(r t.r))) == (skip pass |*(* =(~ (rust +< a)))) ``` Hoon doesn't have regex, only a parser combinator system. This makes it pretty complicated to get everything working: `(mask "abc")` roughly translates to regex's `[abc]`, and is the core of the parser that we are building. `;~(plug a b)` is a monadic bind of two parsers under `++plug`, which has to parse the first and then second or else it fails. `++knee` is used to build a recursive parser; we give it a type (`*tape`) of the result, and a callback to call to generate the actual parser. In this case, the callback is "call the entire closure again, but with the tail of the list instead". The `?~` rune tests is the list is empty, and gives `(easy ~)` (don't parse anything and return ~) or adds on another `mask` and recurse again. Having built the parser, we can get to using it. `++skip` removes all elements of the list for which the function returns yes for. `++rust` tries to parse the element with our rule, returning a `unit` which is either `[~ u=result]` or `~` (our version of Haskell's Maybe). If it's `~` (None, and the rule either failed to parse or didn't parse the entire contents), then the function returns true and the element is removed. What's left over is a list, containing only the word where each letter is one of the options in the list given. I'm assuming that the list of passwords is already in the context under the name `pass`. ``` > =pass %. :* "ABOUT" "AFTER" "AGAIN" "BELOW" "COULD" "EVERY" "FIRST" "FOUND" "GREAT" "HOUSE" "LARGE" "LEARN" "NEVER" "OTHER" "PLACE" "PLANT" "POINT" "RIGHT" "SMALL" "SOUND" "SPELL" "STILL" "STUDY" "THEIR" "THERE" "THESE" "THING" "THINK" "THREE" "WATER" "WHERE" "WHICH" "WORLD" "WOULD" "WRITE" ~ == limo > %. ~["SHWYEU" "YEUTLS" "IHEWRA" "HWULER" "EUELJD"] |= r/(list tape) =+ ^= a |- ?~ r (easy ~) ;~ plug (mask i.r) (knee *tape |.(^$(r t.r))) == (skip pass |*(* =(~ (rust +< a)))) [i="STILL" t=<<>>] ``` [Answer] # Python 3, 81 bytes ``` from itertools import* lambda x:[i for i in map(''.join,product(*x))if i in l][0] ``` An anonymous function that takes input of a list of strings `x` and returns the password. The list of possible passwords `l` is defined as: ``` l=['ABOUT', 'AFTER', 'AGAIN', 'BELOW', 'COULD', 'EVERY', 'FIRST', 'FOUND', 'GREAT', 'HOUSE', 'LARGE', 'LEARN', 'NEVER', 'OTHER', 'PLACE', 'PLANT', 'POINT', 'RIGHT', 'SMALL', 'SOUND', 'SPELL', 'STILL', 'STUDY', 'THEIR', 'THERE', 'THESE', 'THING', 'THINK', 'THREE', 'WATER', 'WHERE', 'WHICH', 'WORLD', 'WOULD', 'WRITE'] ``` This is a simple brute force; I was interested to see how short I could get this without regexes. **How it works** ``` from itertools import* Import everything from the Python module for iterable generation lambda x Anonymous function with input list of strings x product(*x) Yield an iterable containing all possible passwords character by character map(''.join,...) Yield an iterable containing all possible passwords as strings by concatenation ...for i in... For all possible passwords i... i...if i in l ...yield i if i is in the password list :[...][0] Yield the first element of the single-element list containing the correct password and return ``` [Try it on Ideone](https://ideone.com/bVhVwb) ]
[Question] [ [Mancala](https://en.wikipedia.org/wiki/Mancala) is the name of a family of board games that usually involve a series of cups filled with beads that the players manipulate. This challenge will use a specific rule set for a solitaire variant of the game. The board consists of a "basket" at one end, followed by an infinite number of cups, numbered starting from 1. Some of the cups will have some number of beads in them. If the `n`th cup has exactly `n` beads in it, you may "sow" the beads from it. Sowing means to take all `n` beads out of the cup, then deposit them one at a time in each cup towards the basket. The last bead will go into the basket. The player wins when all of the beads on the board are in the basket. Clearly, there are many boards which are not winnable, such as if there is exactly one bead in the second cup. There are no legal plays because all the cups with 0 beads cannot be sown, and the second cup does not have enough beads to be sown. This is obviously no fun, so your task will be to create winnable boards. ### Task Given a positive integer representing a number of beads output a list of non-negative integers representing the number of beads that should be put in each cup to make a winnable board as described above. This list should not contain any trailing zeroes. For any given number of beads, there is always exactly one winnable board configuration. ### Demonstration This is a demonstration of how to play the winnable board for and input of 4. The winnable board is `[0, 1, 3]`. We start with the only available move, sowing the beads from the third cup to get `[1, 2, 0]`. Now we actually have a choice, but the only correct one is sowing the first cup, getting: `[0, 2, 0]`. Then we sow the second cup yielding `[1, 0, 0]` and finally we sow the first cup again to get all empty cups. ### Test cases: ``` 1 => [1] 2 => [0, 2] 3 => [1, 2] 4 => [0, 1, 3] 5 => [1, 1, 3] 6 => [0, 0, 2, 4] 7 => [1, 0, 2, 4] 8 => [0, 2, 2, 4] 9 => [1, 2, 2, 4] 10 => [0, 1, 1, 3, 5] 11 => [1, 1, 1, 3, 5] 12 => [0, 0, 0, 2, 4, 6] 13 => [1, 0, 0, 2, 4, 6] 14 => [0, 2, 0, 2, 4, 6] 15 => [1, 2, 0, 2, 4, 6] 16 => [0, 1, 3, 2, 4, 6] 17 => [1, 1, 3, 2, 4, 6] 18 => [0, 0, 2, 1, 3, 5, 7] 19 => [1, 0, 2, 1, 3, 5, 7] 20 => [0, 2, 2, 1, 3, 5, 7] ``` Big thanks to [PeterTaylor](https://codegolf.stackexchange.com/users/194/peter-taylor) for coming up with a program to generate test cases! [Answer] # Python, 42 41 bytes ``` m=lambda n,i=2:n*[1]and[n%i]+m(n-n%i,i+1) ``` [Answer] ## CJam (21 bytes) ``` M{_0+0#_Wa*\)+.+}ri*` ``` [Online demo](http://cjam.aditsu.net/#code=M%7B_0%2B0%23_Wa*%5C)%2B.%2B%7Dri*%60&input=4) ### Explanation I independently derived the "unplaying" technique mentioned in [this paper](http://arxiv.org/pdf/1112.3593v1.pdf). We prove by induction that there is exactly one winning board for a given number of beads. Base case: with 0 beads, the only winning board is the empty one. Inductive step: if we sow from cup `k` then at the next move cup `k` will be empty and every cup nearer the basket will contain at least one bead. Therefore we can find the unique winning board with `n` beads from the winning board with `n-1` beads by looking for the lowest numbered empty cup, taking one bead from the basket and one from each cup below that empty cup, and placing them all in the empty cup. ### Dissection ``` M e# Start with an empty board { e# Loop _0+0# e# Find position of first 0 (appending to ensure that there is one) _Wa* e# Make array of that many [-1]s \)+ e# Append the index plus 1 (since board is 1-indexed) .+ e# Pointwise addition } ri* e# Read integer from stdin and execute loop that many times ` e# Format for display ``` [Answer] ## JavaScript (ES6), ~~63~~ 37 bytes ``` f=(n,d=2)=>n?[n%d,...f(n-n%d,d+1)]:[] ``` Port of @orlp's Python answer. Explanation: Consider the total number of beads in the `i`th and higher cups. Each play from one of these cups will remove `i` beads from that total. (For instance, if `i` is 3, and you play from the fifth cup, you reduce the number of beads in that cup by five, but you also add one to both the fourth and the third cups.) The total must therefore be a multiple of `i`. Now the `i-1`th cup cannot contain `i` or more beads, so in order for it to leave a multiple of `i` it must contain the remainder of the beads modulo `i`. Previous explanation (from @xnor's link): The naive approach is the "reverse playing" technique. This uses the observation that making a play empties a cup, so reverse playing collects a bead from each cup and puts them in the first empty cup, like so (63 bytes): ``` f=n=>n?[...a=f(n-1),0].some((m,i)=>(m?a[i]--:a[i]=i+1)>m)&&a:[] ``` Now, just consider the first `i` cups. In the case that one of them is empty, reverse playing will add `1` to the total number of beads in those cups, while in the case that none of them is empty, reverse playing will subtract `i` from the total, however this is equivalent to adding `1` modulo `i+1`. After `n` reverse plays the sum of the beads in the first `i` cups will therefore be equivalent to `n` modulo `i+1`, or put it another way, the number of beads in the `i`th cup will be equivalent to `n` minus the sum of the beads in the preceding cups, modulo `i+1`. Now for the `i`th cup to be playable the number of beads cannot exceed `i`, so in fact it will equal the number of remaining beads modulo `i+1`. (Note that I use `d=i+1` as it uses fewer bytes.) [Answer] # Ruby, 36 bytes A port of @orlp's answer because it's far too genius for me to think of anything better. ``` m=->n,i=2{n>0?[n%i]+m[n-n%i,i+1]:[]} ``` ]
[Question] [ (Hopefully it's still Thanksgiving for you) You got a turkey for your thanksgiving dinner but you don't know how to evenly distribute it. The problem is, some people eat more than others, so you need to find a solution ## Input There will be two inputs. The first will be an ascii art of various people. ``` o o \|/ \|/ | | | / \ / \ ``` ### ascii-art specifications Each person takes up a width of 3 columns. Each person is separated by a single column of spaces. The very top of each person is an `o`. Below the `o`, offset by `1` and `-1` in the x, are `\` and `/`, respectively. From the `o` to the second to last row in the input are `|`, the amount of these per person is their "height". The only data you will need to extract from each person is their "height". --- There will always be at least one person. Each person always has at *least* 2-height. The max height your program should handle is at *least* a height of 64. If you would like the input padded with spaces to form a rectangle, please specify this in your answer. --- The second input is the turkey. The turkey is not really a turkey, more of `NxM` dimensions of a turkey. If the second input is `3x2`, then the turkey has dimensions of 3\*2, with a total area of 6. ## Output The output may be a list or your language's closest alternative (e.g. Array). You may also output a string, with the values separated by spaces. The values for each person should be output in the order in which they were input. ## Challenge Your goal is to divide the area of the turkey among the people. An example scenario: Assume they are two people, with heights of `3` and `6`, respectively. If there is a turkey of `5x3`. The total area of the turkey that will need to be distributed is `15`. Now how would you distribute it among everyone? Here's how: ``` the_persons_height TurkeyForAPerson = -------------------- * turkey_area sum_of_all_heights ``` This means, for the first person with a height of `3`, they will get `3/9*15` turkey, or `5`, the second person with a height of `6` they will get `6/9*15` or `10` turkey. ## Output Output must solely consist of digits, and `.`, unless you choose to go for the bonus. In that case, it may only consist of digits, spaces (), and a slash (`/`). ## Full example Input: ``` 6x5 o | o \|/ \|/ | | | | | / \ / \ ``` Output: ``` 11.25 18.75 ``` ## Bonuses **-20% Bonus:** You output a fraction (must be simplified), it does **not** matter whether it is a mixed or improper fraction. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins! [Answer] # LabVIEW, 67 Bytes Im counting after what i proposed in the meta post so its not fixed but yeah here goes. [![enter image description here](https://i.stack.imgur.com/KrE1E.jpg)](https://i.stack.imgur.com/KrE1E.jpg) input padded with spaces is expected. Im counting heads and get the size of people from the line where the heads are at. [Answer] # Pyth, 23 bytes ``` mc*vXzG\*dsN=N-/R\|C.z0 ``` This doesn't work in the online version, because it uses `eval` to determine the size of the turkey. ### Explanation: ``` mc*vXzG\*dsN=N-/R\|C.z0 implicit: z = first input line .z read all other lines C transpose them /R\| count the "|"s in each column - 0 remove 0s in this list (columns with no "|"s) =N assign the resulting list to N m map each value d in N to: XzG\* replace every letter in z with a "*" v evaluate the result (does the multiplication) * d multiply with d c sN divide by sum(N) ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~49~~ 46 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545) ``` W=UqR y f@Y%4¥1 £Xq'| l -1)£Vq'x r@X*Y,1 *X/Wx ``` Outputs as an array. (Note that you will need to wrap each of the two inputs in quotation marks.) ### How it works ``` // Implicit: U = stick-figures, V = turkey size W=UqR y // Assign variable W to: split U at newlines, transpose rows with columns, f@Y%4==1 // take each stick-figure body, m@Xq'| l -1 // and count the number of "|"s. )m@Vq'x // Now map each item X in W to: V split at "x", r@X*Y,1 // reduced by multiplication, starting at 1, *X/Wx // multiplied by X and divided by the total of W. // Implicit: output last expression ``` [Answer] # MATLAB 109\*80% = 87.2 bytes ``` function o=f(t,p);p=char(strsplit(p,'\n'));a=sum(p(:,2:4:end)=='|');o=rats(prod(sscanf(t,'%dx%d'))*a/sum(a)); ``` So this is a MATLAB function which takes two inputs, the first is a string for the turkey size (e.g. `'8x4'`, and the second is the string containing the people. It returns a string containing improper fractions for each person. This could have been a lot smaller, but the new lines got tricky. MATLAB could easily convert a string with `;` as a separator for each line, but trying to use a newline proved difficult, costing 25 characters: ``` p=char(strsplit(p,'\n')); % Converts the input person string to a 2D array ``` Getting the size of the people is actually quite easy: ``` a=sum(p(:,2:4:end)=='|'); ``` This takes every fourth column starting from the second (which will be all the columns where bodies of people will be), then converts that to an array containing 1's where there are body bits and 0's where there aren't. Finally it sums column-wise which results in the array `a` which is a 1D array containing the size of each person. ``` prod(sscanf(t,'%dx%d'))*a/sum(a) ``` Next we extract the size of the turkey from the input string which is in the form `%dx%d`, i.e. one number then 'x' then another number. The resulting array of two numbers are multiplied together to get turkey area. This is multiplied by each of the peoples height, and also divided by the total height of all people to get the portion of turkey for each person as a decimal number. ``` rats(...) ``` The final step to qualify the bonus - this bit makes the code 6 characters longer, but the bonus knocks off ~22 so its worth it. `rats()` is a nice function which converts a decimal number to a simplified improper fraction (accurate to 13 d.p.). Feeding it an array of decimal numbers (i.e. the amount for each person) will return a single string containing fractions for each person in turn separated by spaces. Granted the output of `rats()` adds more than one space, but the question doesn't say it can't - just says the string must contain only digits, ' ' and '/'. This is the output from the example (quote marks added by me to prevent spaces being removed, not in actual output): ``` ' 45/4 75/4 ' ``` --- Example usage: ``` f('6x5',[' o ' 10 ' | ' 10 ' o \|/' 10 '\|/ | ' 10 ' | | ' 10 ' | | ' 10 '/ \ / \']) ``` output: ``` ' 45/4 75/4 ' ``` --- It also works (albeit with warnings) on the online **Octave** interpreter. You can try it [here](http://octave-online.net/?s=sXDNTxyrLGvZrFzQkaHpNcqcvqUsqIjjbeQqqWTpiWVwZsCS). The link is to a workspace with the `f` function defined in a file already. So you should be able to just enter the example usage above at the prompt. [Answer] # Pyth - 25 bytes Can definitely golf a couple bytes off of it. Pretty straightforward approach. ``` KfT/R\|C.z*R*FsMcz\xcRsKK ``` [Try it online here](http://pyth.herokuapp.com/?code=KfT%2FR%5C%7CC.z%2aR%2aFsMcz%5CxcRsKK&input=6x5%0A+++++o+%0A+++++%7C+%0A+o++%5C%7C%2F%0A%5C%7C%2F++%7C+%0A+%7C+++%7C+%0A+%7C+++%7C+%0A%2F+%5C+%2F+%5C&debug=0). [Answer] ## Haskell 119 bytes ``` import Data.List g x=sum[1|y<-x,y>'{'] s#p|(h,_:t)<-span(<'x')s=[g x*read h*read t/g p|x<-transpose$lines p,any(>'{')x] ``` Usage example: `"6x5" # " o \n | \n o \\|/\n\\|/ | \n | | \n | | \n/ \\ / \\\n"` -> `[11.25,18.75]`. [Answer] # JavaScript (ES6), 131 bytes ``` (t,p)=>eval(`h=[];for(s=0;m=r.exec(p);s++)h[i=m.index%l/4|0]=~~h[i]+1;h.map(v=>v/s*${t.replace("x","*")})`,l=p.search` `+1,r=/\|/g) ``` Returns an array of portions. ## Explanation ``` (t,p)=> // t = turkey equation, p = ASCII art of people eval(` // use eval to enable for loop without {} or return h=[]; // h = array of each person's height for(s=0;m=r.exec(p);s++) // for each match of "|", s = sum of all heights h[i=m.index%l/4|0]= // i = person index of this match ~~h[i]+1; // increment person's height (~~ casts undefined to 0) h.map(v=>v/s* // divide each height by the sum and multiply by turkey area ${t.replace("x","*")} // since this is inside an eval just convert t to an equation )`, // implicit: return array of each person's portion // These are executed BEFORE the eval (escaping characters would mean more bytes) l=p.search` `+1, // l = line length r=/\|/g // r = regex to match height markers ) ``` ## Test ``` var solution = (t,p)=>eval(`h=[];for(s=0;m=r.exec(p);s++)h[i=m.index%l/4|0]=~~h[i]+1;h.map(v=>v/s*${t.replace("x","*")})`,l=p.search` `+1,r=/\|/g) ``` ``` Turkey = <input type="text" id="turkey" value="6x5" /><br /> <textarea id="people" rows="8" cols="40"> o | o \|/ \|/ | | | | | / \ / \</textarea><br /> <button onclick="result.textContent=solution(turkey.value,people.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## Python 99 bytes ``` lambda a,b: [`(''.join(i)).count('|')*1.0/a.count('|')*eval(b)` for i in zip(*a.split('\n'))[1::4]] ``` Input:`' o \n | \n o \\|/\n\\|/ | \n | | \n | | \n/ \\ / \\','6*5'` Output: `['11.25', '18.75']` ]
[Question] [ Inspired by [Print the American Flag!](https://codegolf.stackexchange.com/questions/52615/print-the-american-flag) this is a direct copy but with the British flag as it has some symmetries but is still quite complex! Your challenge is to produce the following ASCII-Art in as few bytes as possible! Turn your head/screen (not both!) by 90 degrees to view it properly. ``` __________________________________________ |\ \XXXXXXXXXXXX 000000 XXXXXXXXXXXX//0/| |0\ \XXXXXXXXXXX 000000 XXXXXXXXXXX//0/ | |\0\ \XXXXXXXXXX 000000 XXXXXXXXXX//0/ | |\\0\ \XXXXXXXXX 000000 XXXXXXXXX//0/ /| |X\\0\ \XXXXXXXX 000000 XXXXXXXX//0/ /X| |XX\\0\ \XXXXXXX 000000 XXXXXXX//0/ /XX| |XXX\\0\ \XXXXXX 000000 XXXXXX//0/ /XXX| |XXXX\\0\ \XXXXX 000000 XXXXX//0/ /XXXX| |XXXXX\\0\ \XXXX 000000 XXXX//0/ /XXXXX| |XXXXXX\\0\ \XXX 000000 XXX//0/ /XXXXXX| |XXXXXXX\\0\ \XX 000000 XX//0/ /XXXXXXX| |XXXXXXXX\\0\ \X 000000 X//0/ /XXXXXXXX| |XXXXXXXXX\\0\ \ 000000 //0/ /XXXXXXXXX| |XXXXXXXXXX\\0\ 000000 /0/ /XXXXXXXXXX| |XXXXXXXXXXX\\0\ 000000 0/ /XXXXXXXXXXX| |XXXXXXXXXXXX\\0\ 000000 / /XXXXXXXXXXXX| |XXXXXXXXXXXXX\\0 000000 /XXXXXXXXXXXXX| |XXXXXXXXXXXXXX\\ 000000 /XXXXXXXXXXXXXX| | 000000 | |000000000000000000000000000000000000000000| |000000000000000000000000000000000000000000| |000000000000000000000000000000000000000000| | 000000 | |XXXXXXXXXXXXXX/ 000000 \\XXXXXXXXXXXXXX| |XXXXXXXXXXXXX/ 000000 0\\XXXXXXXXXXXXX| |XXXXXXXXXXXX/ / 000000 \0\\XXXXXXXXXXXX| |XXXXXXXXXXX/ /0 000000 \0\\XXXXXXXXXXX| |XXXXXXXXXX/ /0/ 000000 \0\\XXXXXXXXXX| |XXXXXXXXX/ /0// 000000 \ \0\\XXXXXXXXX| |XXXXXXXX/ /0//X 000000 X\ \0\\XXXXXXXX| |XXXXXXX/ /0//XX 000000 XX\ \0\\XXXXXXX| |XXXXXX/ /0//XXX 000000 XXX\ \0\\XXXXXX| |XXXXX/ /0//XXXX 000000 XXXX\ \0\\XXXXX| |XXXX/ /0//XXXXX 000000 XXXXX\ \0\\XXXX| |XXX/ /0//XXXXXX 000000 XXXXXX\ \0\\XXX| |XX/ /0//XXXXXXX 000000 XXXXXXX\ \0\\XX| |X/ /0//XXXXXXXX 000000 XXXXXXXX\ \0\\X| |/ /0//XXXXXXXXX 000000 XXXXXXXXX\ \0\\| | /0//XXXXXXXXXX 000000 XXXXXXXXXX\ \0\| | /0//XXXXXXXXXXX 000000 XXXXXXXXXXX\ \0| |/0//XXXXXXXXXXXX__000000__XXXXXXXXXXXX\__\| ``` The block is 44 x 42 characters. Note that the first line ends with a single space! No other trailing spaces are allowed but a trailing new line is allowed on the last line. I'm not aware of any date significance for the UK at the moment! [Answer] # SpecBAS - 1137 bytes Absolutely no hope of winning on characters, but the output is in colour... ``` 1 PAPER 15: CLS 2 PRINT AT 1,2;("_"*42): FOR y=2 TO 42: PRINT AT y,1;"|";AT y,44;"|": NEXT y 3 FOR y=4 TO 18: PRINT AT y,y-2;"\";AT y+1,y-2;"\": NEXT y: PRINT AT 19,17;"\" 4 FOR y=2 TO 14: PRINT AT y,y;"\ \";AT y+28,y+26;"\ \": NEXT y: FOR y=15 TO 17: PRINT AT y,y;"\";AT y+12,y+13;"\": NEXT y 5 FOR y=25 TO 39: PRINT AT y,y+3;"\\": NEXT y: PRINT AT 40,43;"\" 6 FOR y=2 TO 14: PRINT AT y,42-y;"/";AT y+1,42-y;"/": NEXT y: PRINT AT 2,41;"/" 7 FOR y=2 TO 17: PRINT AT y,45-y;"/";AT y+3,45-y;"/": NEXT y 8 FOR y=2 TO 16: PRINT AT y+23,18-y;"/";AT y+26,18-y;"/": NEXT y: PRINT AT 27,17;"/" 9 FOR y=1 TO 13: PRINT AT y+29,17-y;"//": NEXT y: PRINT AT 29,17;"/" 10 PRINT AT 42,18;"__";AT 42,26;"__";AT 42,41;"__" 11 INK 2 12 FOR y=2 TO 42: PRINT AT y,20;"0"*6: NEXT y 13 FOR y=21 TO 23: PRINT AT y,2;"0"*42: NEXT y 14 FOR y=3 TO 18: PRINT AT y,y-1;"0";AT y+23,y+25;"0": NEXT y 15 FOR y=2 TO 16: PRINT AT y,44-y;"0";AT y+26,19-y;"0": NEXT y 16 INK 1 17 FOR y=2 TO 13: LET l$="x"*(14-y): PRINT AT y,4+y;l$;AT y,28;l$;AT 44-y,4+y;l$;AT 44-y,28;l$: NEXT y 18 FOR y=6 TO 19: LET l$="x"*(y-5): PRINT AT y,2;l$;AT y,49-y;l$;AT 44-y,2;l$;AT 44-y,44-LEN l$;l$: NEXT y ``` ![enter image description here](https://i.stack.imgur.com/08Xsv.png) [Answer] # Python 2, 223 bytes ``` o="" x="X"*15 s=x+r"\ \0\\%s//0/ /"%x exec'o+="|%s 000000 %s|\\n"%(s[18:2:-1],s[25:41]);s=s[1:]+s[0];'*18 print" "+"_"*42+" \n"+o+"\n".join("|%s000000%s|"%(c*18,c*18)for c in" 000 ")+o[:43:-1]+o[43::-1].replace(" ","_") ``` Still much to golf. Despite its looks, the back half is the same as the front half reversed (barring the underscores), which is unusually nice for a pattern with slashes. [Answer] # Python 3 ~~361~~ 331 ``` p=print p("","_"*42,"") r='|' w="X"*16 s="\\ \\0\\\\" z="//0/ /" O=" 000000 " m=r+" "*18+"0"*3 o=w+s+w e=w+z+w T=e[::-1] f=o[::-1] R=range(18) for i in R:p(r+o[i+19:i+3:-1],O,e[i+4:i+20]+r) B="p(m+m[::-1]);" exec(B+"p(r+'0'*42+r);"*3+B) for i in R[1:]:p(r+T[i+1:i+17],O,f[i+16:i:-1]+r) p(r+T[19:35]+"__000000__"+o[4:17]+"__\\|") ``` This program makes use of python's awesome string slicing capabilities to create a string that represents the stripes: ``` o = "XXXXXXXXXXXXXXX\ \0\\XXXXXXXXXXXXXXX" ``` Then repeatedly print it backwards while shifting it to the right by increasing the start and end of the string slice to get this: ``` \ \XXXXXXXXXXX 0\ \XXXXXXXXXX \0\ \XXXXXXXXX \\0\ \XXXXXXXX X\\0\ \XXXXXXX XX\\0\ \XXXXXX XXX\\0\ \XXXXX XXXX\\0\ \XXXX XXXXX\\0\ \XXX XXXXXX\\0\ \XX XXXXXXX\\0\ \X XXXXXXXX\\0\ \ XXXXXXXXX\\0\ XXXXXXXXXX\\0\ XXXXXXXXXXX\\0\ XXXXXXXXXXXX\\0 XXXXXXXXXXXXX\\ ``` This is the top left corner. I repeat this four times with variants on the original string (like reversing the bit in the middle) to get the other four corners. [Answer] # CJam, ~~131~~ ~~126~~ ~~102~~ 99 bytes ``` S'_42*SK,'XE*"//0/ /"+2*f>Gf<_2> \W%2>.{"\/"_W%er" 000 ":_@}" 0 0" [I6I63].*+s_W%+42/{N"||"@*}/S'_er ``` The two linefeeds are included to prevent horizontal scrolling. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=S'_42*SK%2C'XE*%22%2F%2F0%2F%20%20%2F%22%2B2*f%3EGf%3C_2%3E%5CW%252%3E.%7B%22%5C%2F%22_W%25er%22%20000%20%22%3A_%40%7D%22%200%200%22%5BI6I63%5D.*%2Bs_W%25%2B42%2F%7BN%22%7C%7C%22%40*%7D%2FS'_er). ### Idea We start by modifying the string ``` XXXXXXXXXXXXXX//0/ /XXXXXXXXXXXXXX ``` by pushing 19 copies, discarding the first **n** characters for the **n**th copy and cutting off each results after the 16th character. ``` XXXXXXXXXXXXXX// XXXXXXXXXXXXX//0 XXXXXXXXXXXX//0/ XXXXXXXXXXX//0/ XXXXXXXXXX//0/ XXXXXXXXX//0/ / XXXXXXXX//0/ /X XXXXXXX//0/ /XX XXXXXX//0/ /XXX XXXXX//0/ /XXXX XXXX//0/ /XXXXX XXX//0/ /XXXXXX XX//0/ /XXXXXXX X//0/ /XXXXXXXX //0/ /XXXXXXXXX /0/ /XXXXXXXXXX 0/ /XXXXXXXXXXX / /XXXXXXXXXXXX /XXXXXXXXXXXXX /XXXXXXXXXXXXXX ``` By discarding the first two strings, we obtain the upper right quadrant of the flag. Now, if we reverse the order of the strings, once again discard the first two and swap the inclinations of the slashes, we obtain the upper left quadrant. By concatenating the corresponding strings, with `" 000000 "` in the middle and appending a few runs of spaces and zeroes, we obtain ``` \ \XXXXXXXXXXXX 000000 XXXXXXXXXXXX//0/ 0\ \XXXXXXXXXXX 000000 XXXXXXXXXXX//0/ \0\ \XXXXXXXXXX 000000 XXXXXXXXXX//0/ \\0\ \XXXXXXXXX 000000 XXXXXXXXX//0/ / X\\0\ \XXXXXXXX 000000 XXXXXXXX//0/ /X XX\\0\ \XXXXXXX 000000 XXXXXXX//0/ /XX XXX\\0\ \XXXXXX 000000 XXXXXX//0/ /XXX XXXX\\0\ \XXXXX 000000 XXXXX//0/ /XXXX XXXXX\\0\ \XXXX 000000 XXXX//0/ /XXXXX XXXXXX\\0\ \XXX 000000 XXX//0/ /XXXXXX XXXXXXX\\0\ \XX 000000 XX//0/ /XXXXXXX XXXXXXXX\\0\ \X 000000 X//0/ /XXXXXXXX XXXXXXXXX\\0\ \ 000000 //0/ /XXXXXXXXX XXXXXXXXXX\\0\ 000000 /0/ /XXXXXXXXXX XXXXXXXXXXX\\0\ 000000 0/ /XXXXXXXXXXX XXXXXXXXXXXX\\0\ 000000 / /XXXXXXXXXXXX XXXXXXXXXXXXX\\0 000000 /XXXXXXXXXXXXX XXXXXXXXXXXXXX\\ 000000 /XXXXXXXXXXXXXX 000000 000000000000000000000000000000000000000000 000000000000000000000 ``` The second half of the flag contains almost exactly the same character, in inverted reading order (right to left, bottom to top). All that's left to do to complete the entire flag is to push the first line, replace spaces with underscores in the last and introducing the vertical bars and actual linefeeds. ### Code ``` S'_42*S e# Push a space, a string of 42 underscores and another space. K, e# Push [0 ... 19]. 'XE* e# Push a string of 14 X's. "//0/ /" e# Push that string. +2* e# Concatenate and repeat the result twice. f> e# Push copies with 0, ..., 19 character removed from the left. Gf< e# Truncate each result after 16 characters. _2> e# Copy the array and discard its first two elements. \W%2> e# Reverse the original array and discard its first two elements. .{ e# For each pair of corresponding strings in the arrays: "\/" e# Push "\/". _W% e# Reverse a copy to push "/\\". er e# Perform transliteration on the string from the right array.. " 000 " e# Push that string. :_ e# Duplicate each charcter to push " 000000 ". @ e# Rotate the string from the left array on top. } e# " 0 0" e# Push that string. [I6I63] e# Push [18 6 18 63]. .* e# Vectorized repetition. +s e# Concatenate ad flatten. _W%+ e# Push a reversed copy and concatenate. 42/ e# Split into chunks of length 42. { e# For each chunk: N e# Push a linefeed. "||"@* e# Join the string "||", using the chunk as separator. }/ e# S'_er e# Replace spaces with underscores in the last string. ``` [Answer] # Javascript ES6, ~~726~~ ~~725~~ ~~655~~ ~~647~~ 643 bytes ``` a="__";l=" ";b=l+l;c=`| |`;d="X";e="0";f=b+e[r="repeat"](6)+b;g="\\ \\";h="//0/";i="/ /";Z="\\";A=Z+Z;j=A+0;k=d[r].bind(d);y=c+l[r](16)+f+l[r](16);z=c+e[r](42);B="/";C="\\0";D="0//";E=B+D;q=n=>k(n)+f+k(n);F=n=>g+q(n)+h;G=n=>c+k(n)+j+F(9-n)+k(3+n);H=n=>A+k(n+1)+c+k(n);I=n=>q(n)+g+e+H(8-n)+i+D;console.log(l+a[r](21)+` |`+F(12)+c+e+F(11)+d+c+C+F(10)+d+d+c+j+F(9)+k(3)+c+d+j+F(8)+k(4)+G(2)+G(3)+G(4)+G(5)+G(6)+G(7)+G(8)+y+z+z+z+y+c+k(14)+B+l+f+H(13)+B+b+f+e+H(12)+i+f+C+H(11)+i+e+f+l+C+H(10)+i+"0/"+f+b+C+H(9)+i+D+I(0)+I(1)+I(2)+I(3)+I(4)+I(5)+I(6)+I(7)+I(8)+q(9)+g+e+A+c+b+E+q(10)+g+e+Z+c+l+E+q(11)+g+e+c+E+k(12)+a+e[r](6)+a+k(12)+Z+a+Z+"|") ``` [Answer] # PHP, 240 bytes ``` <?=str_pad(_,42,_)." ";for($o=18;$o--;)$r.=" ".($s="|".substr("XXXXXXXXXXXXXX\\\\0\ \\XXXXXXXXXXXX//0/",$o,16)." 000").($v=strrev)(strtr($s,"\\","/"));echo$r;for(;$i<5;)echo" ",$s=str_pad("|",19,$i++%4?0:" ")."000",$v($s);echo" ",$v($r); ``` Note the space before the opening tag! [Try it online](http://sandbox.onlinephpfunctions.com/code/e2bf5de1f35c04c155b0a20449c7bb594132e517). [Answer] # SpecBAS again - 507 Bytes Here's a similar version to Brian's above (I don't have enough reputation to comment yet) but without the colour. It uses a very different method to generate the display. ``` 10 DEF FN rr$(r$)=r$(2 TO)+r$(1): DEF FN rl$(r$)=r$(LEN r$)+r$( TO LEN r$-1) 20 a$="\ \"+"x"*14+"\\0",b$="x"*12+"//0/ /xx",c$="x"*14+"/ /0//",d$="\\"+"x"*14+"\ \0",e$=" 000000 ": ?" ";"_"*42: DO 18: ?"|";a$( TO 16);e$;b$( TO 16);"|": a$=FN rl$(a$),b$=FN rr$(b$): LOOP: ?"|";TAB 17;e$;TAB 43;"|"'("|"+("0"*42)+"|"+#13)*3;"|";TAB 17;e$;TAB 43;"|": DO 18: ?"|";c$( TO 16);e$;d$( TO 16);"|": c$=FN rr$(c$),d$=FN rl$(d$): LOOP: ?#11;TAB 17;"__";TAB 25;"__";TAB 40;"__" ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 213 bytes ``` 00000000: b5d3 0106 4421 1080 6100 de29 e606 759c ....D!..a..)..u. 00000010: 105d a4c3 6fdb 461f 030f f607 f019 994c .]..o.F........L 00000020: 8cd7 c533 7b44 6f14 5177 118d 4aa9 653e ...3{Do.Qw..J.e> 00000030: b3a2 13d6 c6c2 1d9d b076 6375 c2d8 b270 .........vcu...p 00000040: 5327 8c6d 5fac 4e18 bbb1 3a61 ecc1 6ab1 S'.m_.N...:a..j. 00000050: f662 b518 0b46 83b1 6034 180b 5683 b162 .b...F..`4..V..b 00000060: f5c5 58b1 1a8c 05a3 c158 b1fa 62ac 587d ..X......X..b.X} 00000070: 3156 ac06 630f 8ed4 c1a9 85eb ebfe 8adf 1V..c........... 00000080: bf39 6da3 803b 67cc eab0 e08a 0663 0b93 .9m..;g......c.. 00000090: d160 2c3f 8806 6b99 8c06 6bc1 1d0d c67a .`,?..k...k....z 000000a0: 2968 3056 8c06 63c5 6830 568c 0663 c5e8 )h0V..c.h0V..c.. 000000b0: 8bb5 62f5 c1d8 8cd1 1b6b 3346 2fac cd58 ..b......k3F/..X 000000c0: bdb0 3663 f4c6 da8c d10b 6f4b 63fc f018 ..6c......oKc... 000000d0: 4d3d 469f 1f M=F.. ``` [Try it online!](https://tio.run/##fZNLb9UwEIX3/IrDClVCg52xJ04RsKm64CUhJNQNon7ERcBV2VyQQPz2y/G9Kd0xUuxEyXw@c2ZS9qV8W2/2u8PBbXGOEpvCeWcIYfLwLjmYdw5tnRasxhdzXCogjIuHIlnkTGQvD04ET4Z3sSGHqrDeCoL5Dqeuo5ub0Z1fsCxhMD6K3MqlbPF6Y0xkpNpm1KiKuYRAkA@Ifp7hfWoIOS@wqOtRh/6@uJV3P0Veyvp8Y@ioRfMEr81QrfKuLQ3FzQbTOaJOLaFMszvVcowfdc/1@8YIZESdZoqxhthzRVg9k0rx0Gwea60elvmI949k90neMv2clny58yOS0c0mGstMV4IhKb83pwE@uYJoSVE8P4EUptOO6yDyQaRsDBuMWCNiYqbPqcLFrKg@UozvGTZRW0xzG7VcnWrhVuTqz8aYyVAfDbm6YQC7kdYWyKCTKa4Fa@krUm4d8Dy8yn1sjDQ87UrnG09PTgtsrhVrLg6rSxnOjNNTFqWOZSfy9OYEqP8YCxnNm8NUlRLSEFMWSjjKKrTTN9fYsDmTcf34hchXOV3ya2NkMqbFEtSxoFOm0h4a6Yad9aSjxjUBZ5/dsZptu9NRxoyVwqSpcxY8Z4Ejx9OLFaiyTdPod220GHJszJChl0/o7Maow4/G2nUc10M1tNGc5tlW64GL9joG/siwzdLbV/Xe00ZGaMqRtqWDP8r/4s0zDsfh8Bc "Bubblegum – Try It Online") ]