text
stringlengths
180
608k
[Question] [ ## Background This puzzle is a variation on the [four fours puzzle](http://en.wikipedia.org/wiki/Four_fours) (itself the topic of a [past question](https://codegolf.stackexchange.com/questions/12063/four-fours-puzzle)). Like that puzzle, the aim is to find mathematical expressions for different whole numbers, using only four digits and certain mathematical operators. In this case, however, the **permitted digits are just 2, 0, 1 and 5**. Each must appear precisely once in the solution and in the correct order. Surprisingly many whole numbers can be represented this way. Solvers are encouraged to try solving it by hand first, as it's strangely enjoyable. ## Rules Constants may be constructed from single or multiple digits: * Integers: e.g. 2, 0, 15, etc. * Decimals: e.g. .2, .01, 1.5, etc. * [Repeating decimals](http://en.wikipedia.org/wiki/Repeating_decimal#Notation): e.g. .2~ (=0.222...), .15~ (=0.1555...), 20.15~~ (=20.1515...) The following unary operations are permitted: * Unary negation: -x * Square root: sqrt(x) * Integer factorial: x! The following binary operations are permitted: * Standard arithmetic operators: x+y, x-y, x\*y and x/y * Arbitrary exponentiation: x^y * Arbitrary roots: rt[x](y) (= x'th root of y) ## Task Your program should print out expressions for as many of the integers between 0 and 100 as it can, and then output the number of expressions it has produced. * The solutions must be printed in order in the format n=[expr]. * The expressions must use all the digits 2, 0, 1, 5, once each in that order. * The expressions must be printed using the notation described above. Unnecessary parentheses are permitted but not required, as is whitespace. The order of operator precedence is unary negation, factorial, exponentiation, multiplication/division and addition/subtraction. * The program need not return solutions for all the numbers. A program that simply outputs 0 is therefore valid; however, see the scoring section below. * The program should run in under 15 minutes on a modern computer. You may write a program or function. The expressions should be printed to STDOUT (or closest alternative). The number of expressions can be printed to STDOUT or returned as an integer. Standard code golf restrictions apply. ## Example output ``` 0=2*0*1*5 10=20*1*.5 42=((2+0!)!+1)!/5! 100=20*1*5 4 ``` ## Scoring **Update**: *@orlp has noted a flaw in the scoring system. See <http://meta.codegolf.stackexchange.com/questions/5106/way-of-salvaging-two-zero-one-five-puzzle-challenge> for a discussion of how or whether this should be fixed.* Solutions are scored *first* by the number of expressions they produce and *then* by their code length in bytes. Hence, a 1000 byte program that produce 80 results will beat a 100 byte program that produces only 79 (though the latter could easily be extended to include the missing results). For those who would like a motivating target, below is a lower bound on the number of expressions that can be represented. I don't plan to submit an entry, so it may well be possible to win with less! > > At least 85 (out of 101), though it may well be higher. > > > ## Scoreboard As an extra incentive, here is a summary of the score progression. Whenever you beat the highest score, feel free to add yourself to the top of the table (or ask someone else to). * 0 expressions, 1 byte (Pyth): *implementation that just outputs 0* [Answer] # 85, ~2400 bytes I'm a bit sad this is a code golf challenge, as I feel that all my previous efforts have been rather useless now that I'll post this: ``` 0 = ((2*0)^15) 1 = ((2^0)^15) 2 = (2-(0^15)) 3 = (20*.15) 4 = (20*(1/5)) 5 = (20-15) 6 = ((.20+1)*5) 7 = ((20*.1)+5) 8 = (2*((0-1)+5)) 9 = ((.20/.1~)*5) 10 = (20/(1/.5)) 11 = ((((2-0)+1))!+5) 12 = (20*(.1+.5)) 13 = ((-(2)-0)+15) 14 = (20-(1+5)) 15 = ((2*0)+15) 16 = ((2^0)+15) 17 = ((2-0)+15) 18 = (20-(1/.5)) 19 = (20-(1^5)) 20 = (20^(1^5)) 21 = (20+(1^5)) 22 = (20+(1/.5)) 23 = (((2-0)/.1~)+5) 24 = ((20-1)+5) 25 = ((20^1)+5) 26 = ((20+1)+5) 27 = (rt[.2](((0)!+1))-5) 28 = (2*(-((0)!)+15)) 29 = ((((2+(0)!)+1))!+5) 30 = ((2-0)*15) 31 = (20+sqrt((1+(5)!))) 32 = ((20*.1)^5) 33 = ((.2^-((0)!))/.15~~) 34 = (2+(((0)!+1)^5)) 35 = (20+15) 36 = (20*(1/.5~)) 37 = (rt[.2](((0)!+1))+5) 38 = ((20-1)/.5) 39 = (-((2^0))+(sqrt(.1~)*(5)!)) 40 = (20*(1/.5)) 41 = (((.2~^-((0)!))/.1~)+.5) 42 = ((20+1)/.5) 43 = (-(2)+(((0)!/.1~)*5)) 44 = (20+((-(1)+5))!) 45 = (20/(1-.5~)) 46 = ((.2+((0)!/.1~))*5) 47 = (2+(((0)!/.1~)*5)) 48 = (2*(((0-1)+5))!) 49 = ((((2+(0)!))!/.1~)-5) 50 = (((2^0)/.1)*5) 51 = ((.2+((0)!/.1))*5) 52 = (2+(((0)!/.1)*5)) 54 = (((2+(0)!)/.1)/.5~) 55 = ((2+((0)!/.1~))*5) 56 = (((.2-(0)!)+sqrt(.1~))*-((5)!)) 58 = (-(2)+sqrt((((((0)!/sqrt(.1~)))!)!*5))) 59 = ((((2+(0)!))!/.1~)+5) 60 = (20/(.1~^.5)) 62 = (2*(-((0)!)+sqrt(rt[-(.1)](.5)))) 64 = ((2-0)^(1+5)) 65 = ((20/sqrt(.1~))+5) 66 = ((-(((2+(0)!))!)/.1~)+(5)!) 67 = (((((2+(0)!))!)!*.1)-5) 69 = ((2^(((0)!/sqrt(.1~)))!)+5) 70 = (((.2^-((0)!))/-(.1))+(5)!) 72 = ((2+(0)!)*((-(1)+5))!) 75 = ((.2^-((0)!))*15) 76 = (rt[(-(2)^-((0)!))](.1~)-5) 77 = (((((2+(0)!))!)!*.1)+5) 78 = (2*(-((0)!)+(sqrt(.1~)*(5)!))) 80 = (-(20)*(1-5)) 81 = (201-(5)!) 82 = (2*((0)!+(sqrt(.1~)*(5)!))) 84 = (((.2-(0)!)+.1)*-((5)!)) 85 = (((((2+(0)!))!)!*.1~)+5) 86 = (rt[(-(2)^-((0)!))](.1~)+5) 88 = (rt[.2]((-((0)!)-1))+(5)!) 90 = ((20/.1~)*.5) 93 = (((2+(0)!)/-(.1~))+(5)!) 95 = ((20-1)*5) 96 = ((.20-1)*-((5)!)) 98 = (-(20)*(.1-5)) 99 = ((-(20)-1)+(5)!) 100 = (20/(1/5)) 85 ``` From here on it's just a compression challenge. Maybe I'll compete later, maybe I won't. For me most of the fun was in the challenge to find the most formulas. A hint for those struggling to write a solver - runtime shouldn't be a problem. If you have too many formulas to check you need better heuristics to throw away hopeless solutions and duplicates. The code I wrote to generate the above runs in ~5 sec on Python. ]
[Question] [ The number of partitions of an integer is the number of ways that integer can be represented as a sum of positive integers. For example: ``` 5 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 ``` There are 7 ways to represent the number 5, therefore 7 is the partition number corresponding to the number 5. [Partition numbers: OEIS: #A000041](https://oeis.org/A000041) # Directions Write a program that takes a positive integer as input, and outputs the two numbers that **generate** the two closest partition numbers to the input number. * Input must be 1 positive integer. * If the input **is not** a partition number, the output must be the 2 different positive integers that generate the two closest partition numbers to the input number. (If two partition numbers are equal candidates for one of the output numbers, it doesn't matter which one you choose.) * If the input **is** a partition number, the output must be 1 positive integer that generates the input number. * Input and output may be in any reasonable format. * You may assume that the input will not be larger than 100 million (eg. output will never be larger than 95). * Built-in functions to calculate partition numbers are **not** allowed, along with other [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/20111). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least number of bytes wins. [Partition numbers: OEIS: #A000041](https://oeis.org/A000041) # Examples ``` Input: 66 Output: 11, 12 ``` (The partition numbers that correspond to the numbers 11 and 12 are 56 and 77, which are the two closest partition numbers to 66.) ``` Input: 42 Output: 10 ``` (The number 42 is already a partition number, so just output the number that corresponds to the partition number.) ``` Input: 136 Output: 13, 14 ``` (The two closest partition numbers to 136 are actually both LESS than 136 (eg. 101 and 135), therefore the output is 13 and 14 as opposed to 14 and 15.) ``` Input: 1 Output: 0 or 1 ``` (Both 0 and 1 are valid outputs in this special case.) ``` Input: 2484 Output: 26, 25 or 26, 27 ``` (Both of these outputs are valid, because 2484 is equal d[i](http://www.audiocheck.net/Audio/audiocheck.net_binaural_knocking.mp3)stance from 1958 and 3010.) ``` Input: 4 Output: 3, 4 ``` (Yup) [Answer] # Python 2, 179 bytes ``` Z=range(1,99) R=Z+[1] for i in Z:R[i]=sum(-(-1)**k*(3*k*k-k<=i*2and R[i-k*(3*k-1)/2])for k in range(-i,i+1)if k) f=lambda n:zip(*sorted((abs(n-R[i]),i)for i in Z))[1][:2-(n in R)] ``` Uses the recursive formula from [Euler's pentagonal theorem](https://en.wikipedia.org/wiki/Partition_%28number_theory%29#Recurrence_formula). Call with `f(2484)`. Output is a tuple with one or two numbers. [Answer] # [Pyth](http://github.com/isaacg1/pyth), 53 ``` L?!b<b1sm&d*^_1tdy-b/*dt*3d2r_bhbJo^-QyN2U99<J-2qQyhJ ``` Explanation and more golfing to follow. [Answer] # Mathematica, ~~124~~ 123 bytes ``` f@n_:=(p=SeriesCoefficient[1/Product[1-x^k,{k,#}],{x,0,#}]&;s=SortBy[Range@95,Abs[n-p@#]&];If[p@s[[1]]==n,s[[1]],s~Take~2]) ``` Formula for partition numbers taken from the [OEIS page](https://oeis.org/A000041). (May or may not be cheating... I couldn't decide.) Usage: ``` In: f[136] Out: {14, 13} ``` I'm not answering to win. And I'm sure this could be golfed further. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` eⱮRŒṗẈrƝƲTµ;‘ṁ3ḊQ ``` [Try it online!](https://tio.run/##AT4Awf9qZWxsef//ZeKxrlLFkuG5l@G6iHLGncayVMK1O@KAmOG5gTPhuIpR/8OH4oKsxZLhuZj//zQyLCA0LCAzMw "Jelly – Try It Online") Outputs in reverse order. I think this just about follows the rule "Built-in functions to calculate partition numbers are not allowed", as this uses the Jelly builtin to calculate the *list* of integer partitions, not the *number* of partitions. For example, `4Œṗ => [[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2], [4]]`. ## How it works ``` eⱮRŒṗẈrƝƲTµ;‘ṁ3ḊQ - Main link. Takes an input n on the left Ʋ - Group the previous 4 links together: R - Take the range 1...n Œṗ - Calculate the partitions of each k in the range Ẉ - Take the length of each. - This gives the kth partition number rƝ - Insert ranges for each overlapping pair of partition numbers Ɱ - For each of the list of ranges... e - Yield 1 if n is in the range between the kth and (k+1)th partition number and 0 otherwise T - Remove 0s and replace 1s with their index - For partition numbers, this yields two values. If m is the desired output, this yields [m-1, m] - For non-partition numbers, this returns [m], when the required output is [m, m+1] µ - Set the return value to either U = [m-1, m] or U = [m] ‘ - Yield [m, m+1] or [m+1] ; - Concatenate to U, giving either [m-1, m, m, m+1] or [m, m+1] ṁ3 - Mold to length 3, giving either [m-1, m, m] or [m, m+1, m] Ḋ - Remove the first value, returns [m, m] or [m+1, m] Q - Remove duplicates and output either [m] or [m+1, m] ``` ]
[Question] [ You will choose *m* languages and write *n* programs in each language, each with length *n\*m*. The *k*th program should output the *k*th character of each program, ordered by the program number. For example, in this submission (for demonstration only; they can be any characters including newlines and tabs): ``` ABC DEF GHI ``` Program `ABC` should output `ADG`, and programs `DEF` and `GHI` should output `BEH` and `CFI` respectively. All programs in the list must not be a normal quine. So `ABC` and `ADG` must be different. Same applies to the other two programs. Note that *n\*m* must be at least 2 to make this possible. You don't have to use your languages in specific order. So you can write two programs in language A, then three in language B, then another in language A again. But all languages must be used exactly the same number of times. Leading / trailing newline in your program and output doesn't matter. The answer with minimum *n(m+10)/m3* wins. But I'll also award at least +100 bounty to the answer with most languages if it used at least 3 of them. **Deadline for the bounty: after a week without improvement or Mar 1st, 2015 if no answer satisfied the criterion.** ### Rules about languages You can use any languages with different names, or different versions which are generally considered different enough (such as Python 2/3, ECMAScript 5/6). But your programs must not output exactly the same thing in any other language you have used. [Answer] # CJam, m=1, n=37, score=407 Here is my example answer. It used only one language: CJam. ``` {"_~"+s'A_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'B_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'C_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'D_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'E_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'F_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'G_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'H_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'I_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'J_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'K_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'L_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'M_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'N_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'O_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'P_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'Q_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'R_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'S_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'T_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'U_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'V_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'W_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'X_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'Y_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'Z_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'[_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'\_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s']_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'^_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'__'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'`_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'a_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'b_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'c_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'd_'I={;;'f,'Ai>}{'A-=37*}?}_~ {"_~"+s'e_'I={;;'f,'Ai>}{'A-=37*}?}_~ ``` ]
[Question] [ ## Challenge: Draw **Sri Yantra**. ## How to: There are different ways to draw it. All include many steps. If you think you can draw it without following the linked steps scroll below for the **elements you must have in your drawing**. Complete steps can be found here: <http://www.saralhindi.com/Shri_Yantra/makingsky14steps_eng.htm> (*I didn't copied them here because it would become a very long question*, here is [archieve.org mirror in case the first link ever goes down](https://web.archive.org/web/20130807162656/http://www.saralhindi.com/Shri_Yantra/makingsky14steps_eng.htm)) The final picture should look like the picture below: ![enter image description here](https://i.stack.imgur.com/JFZRd.jpg) ## Must have: Basically any method of drawing of your choosing would be a valid answer providing that you keep the most important elements 1. The number of triangles should the same number as in the above picture (43 smaller triangles resulted from the interlacing of the bigger 9 triangles) 2. This triple intersections are respected: ![enter image description here](https://i.stack.imgur.com/Qm6xn.png) 3. The tips of the upward triangles touch the bases of the 4 downward triangles and the tips of downward triangles should touch the bases of the 3 upward triangles as shown in the figure bellow. ![enter image description here](https://i.stack.imgur.com/fMj8E.png) 4. The inner circle (bindu) is concentric with the outer circle. 5. The tips (vertices) of the bigger triangles should touch the outer circle: ![enter image description here](https://i.stack.imgur.com/1BXGI.png) 6. The final image should have all the elements and should generally look like: ![enter image description here](https://i.stack.imgur.com/JFZRd.jpg) 7. Color should be roughly the same as the above image for every element (including petals). 8. The shape of the petals should preferably look roughly like in the image bellow, but can also be just semicircles or simple arc section of circle: 9. There are no strict proportion restrictions to the circles or the size of the gates, but the most outer circle should have the diameter not less than 90% of the side of the outer square, the other elements would be respectively arranged relative to this proportions. ![enter image description here](https://i.stack.imgur.com/P6YuI.png) ![enter image description here](https://i.stack.imgur.com/nQeDg.png) ## Programming languages and results There are no restriction to the programming language nor the format of the result (it can be either a vector image, bitmap image, canvas etc) provided that the result is relatively clear and discernible (at least 800px X 800px) **Latter edit:** There is no perfect method of drawing as this blog so well explores them: <http://fotthewuk.livejournal.com/> Taking that into account minor faults will be tolerated. > > At this point it as an interesting exercise to learn that it is very probable that there is no perfect solution, much like squaring of the circle. > > > [Answer] # Mathematica - ~~2836~~ 2536 chars It was a bit dizzying to figure out the combos of regions that make small triangles available for coloring. ## The Frame The frame objects are inequalities that describe as regions. E.g. the red and yellow scalloping are two regions of circles. ``` n1=8;n2=16; w8=Round[.78 Table[{Cos[2\[Pi] k/n1],Sin[2\[Pi] k/n1]},{k,0,n1-1}],.01]; w16=Round[1 Table[{Cos[2\[Pi] k/n2],Sin[2\[Pi] k/n2]},{k,0,n2-1}],.01]; n=12;y1=.267; x2=1/Sqrt[2];w=1.8;v=1.85; pts={{-w,w},{-w/4,w},{-w/4,w+w/8},{-5w/8,w+w/8},{-5w/8,w+5w/24},{5w/8,w+5w/24},{5w/8,w+w/8},{w/4,w+w/8},{w/4,w}, {w,w},{w,w/4},{w+w/8,w/4},{w+w/8,5w/8},{w+5w/24,5w/8},{w+5w/24,-5w/8},{w+w/8,-5w/8},{w+w/8,-w/4},{w,-w/4}, {w,-w}, {w/4,-w},{w/4,-w-w/8},{(5 w)/8,-w-w/8},{(5 w)/8,-w-(5 w)/24},{-((5 w)/8),-w-(5 w)/24},{-((5 w)/8),-w-w/8},{-(w/4),-w-w/8},{-(w/4),-w},{-w,-w}, {-w,-w/4},{-w-w/8,-w/4},{-w-w/8,-5w/8},{-w-5w/24,-5w/8},{-w-5w/24,5w/8},{-w-w/8,5w/8},{-w-w/8,w/4},{-w,w/4} }; frame=RegionPlot[{ (*MeshRegion[pts2,Polygon[Range[20]]],*) (*orange trim *) MeshRegion[pts,Polygon[Range[Length[pts]]]], (*green box *) ImplicitRegion[x^2+y^2<2.8,{x,y}], (*white, largest circle *) ImplicitRegion[Or@@(((x-#)^2+(y-#2)^2<.1)&@@@w16),{x,y}], (*yellow scallops*) ImplicitRegion[x^2+y^2<1,{x,y}],(*white circle *) ImplicitRegion[x^2+y^2<1.4,{x,y}],(*white disk*) ImplicitRegion[Or@@(((x-#)^2+(y-#2)^2<.15)&@@@w8),{x,y}],(*red scallops*) ImplicitRegion[x^2+y^2<1,{x,y}] , (*white disk *) ImplicitRegion[1.8 < x^2+y^2< 2.2,{x,y}] ,(*brown outer rim*) ImplicitRegion[2.4 < x^2+y^2< 2.8,{x,y}](*yellow outer rim*)}, BoundaryStyle->Directive[Thickness[.005],Black], AspectRatio->1, Frame-> False, PlotStyle->{(*Lighter@Orange,*) Darker@Green,White,Yellow,White,White, Red,White,Lighter@Brown,Yellow,Red, White,White,White,White,White, White,White,Red,Red,Darker@Blue, Darker@Blue,Darker@Blue,Darker@Blue,Darker@Blue,Darker@Blue, Red,Red,Darker@Blue,Red,Yellow,Red}]; ``` Then there is a disk to hide some circles that were used to make the scalloping. ``` Graphics[{White,Disk[{0,0},.99]}] ``` --- ## The Innards Some definitions of vertices and triangles. Each triangle, t1, t2,... is a distinct region. Logical operations (`RegionUnion`. `RegionIntersection`, and `RegionDifference`) on large triangles are used to define smaller, triangular cells as derived regions that can be individually colored. ``` p1={-Cos[ArcTan[.267]],y1}; p2={Cos[ArcTan[.267]],y1}; p3={-Cos[ArcTan[.267]],-y1}; p4={Cos[ArcTan[.267]],-y1}; p5={-x2,(x2+y1)/2}; p6={x2,(x2+y1)/2}; p7={-x2,-(x2+y1)/2}; p8={x2,-(x2+y1)/2}; p9={0.5,-x2}; p10={-0.5,-x2}; p11={0.5,-x2}; p12={-0.5,-x2}; p13={a=-.34,b=-.12}; p14={-a,b}; p15={0.5,x2}; p16={-0.5,x2}; t1=MeshRegion[{{0,-1},p1,p2},Triangle[{1,2,3}]]; t2=MeshRegion[{{0,1},p3,p4},Triangle[{1,3,2}]]; t3=MeshRegion[{{0,-x2},p5,p6},Triangle[{1,3,2}]]; t4=MeshRegion[{{0,x2},p7,p8},Triangle[{1,3,2}]]; t5=MeshRegion[{{0,+y1},p9,p10},Triangle[{1,3,2}]]; t6=MeshRegion[{{0,p5[[2]]},p13,p14},Triangle[{1,3,2}]]; t7=MeshRegion[{{0,p13[[2]]},p15,p16},Triangle[{1,3,2}]]; t8=MeshRegion[{{0,p7[[2]]},{-.33,p1[[2]]-.12},{.33,p1[[2]]-.12}},Triangle[{1,3,2}]]; t9=MeshRegion[{{0,p3[[2]]},{z=-.23,0.063},{-z,.063}},Triangle[{1,3,2}]]; ``` --- ``` disk=Graphics[{White,Disk[{0,0},.99]}]; innards=RegionPlot[{ t1,t2,t3,t4,t5,t6,t7,t8,t9,(*White*) RegionDifference[t1,RegionUnion[t5,t4,t2]],(*Blue*) RegionDifference[t4,RegionUnion[t1,t3,t5]],(*red*) RegionDifference[t3,RegionUnion[t7,t4,t2]], (*blue*) RegionDifference[t2,RegionUnion[t1,t7,t3]], (*blue*) RegionDifference[t5,t1], (*blue*) RegionDifference[t4,RegionUnion[t1,t7]], (*Blue *) RegionDifference[t7,t2],(*Blue*) RegionDifference[t3,RegionUnion[t1,t2]],(*Blue *) RegionDifference[t8,t2], (* blue *) RegionDifference[t9,t5], (* red *) RegionDifference[t9,t6], (* red *) RegionIntersection[t4,RegionDifference[t6,t1]], (*blue*) RegionIntersection[t6,RegionDifference[t5,t8]], (* red *) RegionIntersection[t7,t9], (*yellow*) RegionDifference[RegionIntersection[t7,t8],t5], (*red *) RegionDifference[RegionIntersection[t5,t6],RegionUnion[t7,t9]],(*red *) ImplicitRegion[x^2+y^2<= .001,{x,y}], (* smallest circle *) (* red *) RegionDifference[RegionIntersection[t7,t1 ],t6], (*Red*) RegionDifference[t8,RegionUnion[t5,t6]], RegionDifference[t6,RegionUnion[t7,t8]], RegionDifference[RegionIntersection[t2,t5],RegionUnion[t7,t8]], RegionDifference[RegionIntersection[t7,t3],t4], RegionDifference[RegionIntersection[t1,t3],RegionUnion[t5,t4]], RegionDifference[RegionIntersection[t2,t4],RegionUnion[t7,t3]], RegionDifference[RegionIntersection[t5,t4],t3]}, BoundaryStyle->Directive[Thickness[.005],Black], AspectRatio->1, PlotStyle->{ White,White,White,White,White,White,White,White,White, Blue,Red,Red,Blue,Blue,Blue,Blue,Blue,Blue, Red,Red,Blue,Red,Yellow,Red,Red,Red,Blue,Blue,Blue,Blue,Red,Red,Red,Red}] ``` --- ## Putting the parts together ``` Show[frame,disk,innards,Graphics[{Brown,Thickness[.02],Line[Append[pts,{-w,w}]]}]; Graphics[{RGBColor[0.92,0.8,0.],Thickness[.015],Line[Append[pts,{-w,w}]]}]] ``` ![sri4](https://i.stack.imgur.com/jyHQH.png) --- ## Golfed ``` r=ImplicitRegion;m=MeshRegion;t=Triangle;d=RegionDifference;u=RegionUnion;i=RegionIntersection;(*s=ImplicitRegion*) n1=8;n2=16;w8=.78 Table[{Cos[2\[Pi] k/n1],Sin[2\[Pi] k/n1]},{k,0,n1-1}]; w16=Table[{Cos[2\[Pi] k/n2],Sin[2\[Pi] k/n2]},{k,0,n2-1}];n=12;y1=.267;x2=1/Sqrt[2];w=1.8;v=1.85; pts={{-w,w},{-w/4,w},{-w/4,w+w/8},{-5w/8,w+w/8},{-5w/8,w+5w/24},{5w/8,w+5w/24},{5w/8,w+w/8},{w/4,w+w/8},{w/4,w}, {w,w},{w,w/4},{w+w/8,w/4},{w+w/8,5w/8},{w+5w/24,5w/8},{w+5w/24,-5w/8},{w+w/8,-5w/8},{w+w/8,-w/4},{w,-w/4}, {w,-w},{w/4,-w},{w/4,-w-w/8},{(5 w)/8,-w-w/8},{(5 w)/8,-w-(5 w)/24},{-((5 w)/8),-w-(5 w)/24},{-((5 w)/8),-w-w/8},{-(w/4),-w-w/8},{-(w/4),-w},{-w,-w}, {-w,-w/4},{-w-w/8,-w/4},{-w-w/8,-5w/8},{-w-5w/24,-5w/8},{-w-5w/24,5w/8},{-w-w/8,5w/8},{-w-w/8,w/4},{-w,w/4}}; frame=RegionPlot[{ m[pts,Polygon[Range[Length[pts]]]], r[x^2+y^2<2.8,{x,y}], r[Or@@(((x-#)^2+(y-#2)^2<.1)&@@@w16),{x,y}], r[x^2+y^2<1,{x,y}], r[x^2+y^2<1.4,{x,y}], r[Or@@(((x-#)^2+(y-#2)^2<.15)&@@@w8),{x,y}], r[x^2+y^2<1,{x,y}] , r[1.8 < x^2+y^2< 2.2,{x,y}] , r[2.4 < x^2+y^2< 2.8,{x,y}]}, BoundaryStyle->Directive[Thickness[.003],Black], AspectRatio->1, Frame-> False, PlotStyle->{Darker@Green,White,Yellow,White,White,Red,White,Lighter@Brown,Yellow,Red}]; c=Cos[ArcTan[y1]]; p1={-c,y1}; p2={c,y1}; p3={-c,-y1}; p4={c,-y1}; p5={-x2,(x2+y1)/2}; p6={x2,(x2+y1)/2}; p7={-x2,-(x2+y1)/2}; p8={x2,-(x2+y1)/2}; p9={0.5,-x2}; p10={-0.5,-x2}; p11={0.5,-x2}; p12={-0.5,-x2}; p13={a=-.34,b=-.12}; p14={-a,b}; p15={0.5,x2}; p16={-0.5,x2}; t1=m[{{0,-1},p1,p2},t[{1,2,3}]]; t2=m[{{0,1},p3,p4},t[{1,3,2}]]; t3=m[{{0,-x2},p5,p6},t[{1,3,2}]]; t4=m[{{0,x2},p7,p8},t[{1,3,2}]]; t5=m[{{0,+y1},p9,p10},t[{1,3,2}]]; t6=m[{{0,p5[[2]]},p13,p14},t[{1,3,2}]]; t7=m[{{0,p13[[2]]},p15,p16},t[{1,3,2}]]; t8=m[{{0,p7[[2]]},{-.33,p1[[2]]-.12},{.33,p1[[2]]-.12}},t[{1,3,2}]]; t9=m[{{0,p3[[2]]},{z=-.23,0.063},{-z,.063}},t[{1,3,2}]]; innards=RegionPlot[{ d[t1,u[t5,t4,t2]], d[t4,u[t1,t3,t5]], d[t3,u[t7,t4,t2]], d[t2,u[t1,t7,t3]], d[t5,t1], d[t4,u[t1,t7]], d[t7,t2], d[t3,u[t1,t2]], d[t8,t2], d[t9,t5], d[t9,t6], i[t4,d[t6,t1]], i[t6,d[t5,t8]], i[t7,t9], d[i[t7,t8],t5], d[i[t5,t6],u[t7,t9]], r[x^2+y^2<= .001,{x,y}], d[i[t7,t1 ],t6], d[t8,u[t5,t6]], d[t6,u[t7,t8]], d[i[t2,t5],u[t7,t8]], d[i[t7,t3],t4], d[i[t1,t3],u[t5,t4]], d[i[t2,t4],u[t7,t3]], d[i[t5,t4],t3]}, BoundaryStyle->Directive[Thickness[.003],Black], Frame->False, PlotStyle->{Blue,Red,Red,Blue,Blue,Blue,Blue,Blue,Blue, Red,Red,Blue,Red,Yellow,Red,Red,Red,Blue,Blue,Blue,Blue,Red,Red,Red,Red}]; trim=Graphics[{RGBColor[0.92,0.8,0.],Thickness[.01],Line[Append[pts,{-w,w}]]}]; trim2=Graphics[{Brown,Thickness[.02],Line[Append[pts,{-w,w}]]}]; Show[frame,Graphics[{White,Disk[{0,0},.99]}],trim2,trim,innards] ``` ]
[Question] [ Lets say I was writing something, and I accidentally wrote it in the wrong box: ``` +-------+--------+ | Verbs | Nouns | +-------+--------+ | Truck | | | eat | Banana | | | Car | +-------+--------+ ``` So I, being lazy, merely draw an arrow to the space it should be: ``` +-------+--------+ | Verbs | Nouns | +-------+--------+ |[Truck]---> | | eat | Banana | | | Car | +-------+--------+ ``` Your job is to make it look pretty - turn it into this: ``` +-------+--------+ | Verbs | Nouns | +-------+--------+ | | Truck | | eat | Banana | | | Car | +-------+--------+ ``` ## Rules * Phrases or words are surrounded by brackets ([...]) * ~~Multiline entries are denoted as [...]~~ (multiline removed), newline, [...]--...-->. So the arrow always comes out of the **~~bottom~~ right bracket** For example: ``` +-----------+----------+ | Verbs | Nouns | +-----------+----------+ | | | |[is a noun]-> | | eat | Banana | | | Car | +-----------+----------+ ``` Turns into: ``` +-----------+----------+ | Verbs | Nouns | +-----------+----------+ | | | | | is a noun| | eat | Banana | | | Car | +-----------+----------+ ``` * Boxes are bounded by pluses ("+"), and it should be assumed that arrows will not pass over a plus * There will always be room at the end of an arrow for the word or phrase to fit * Order matters - the word must appear where the arrow points to, though vertical alignment is not important * Arrows can turn by 90 degrees at a time, but only between "/" and "\" (see below) For example: ``` +-----------+----------+ | Verbs | Nouns | +-----------+----------+ | [Truck]--\| | /------------/| <--\ | | eat | Banana || | | /--\ | Car || | +--|--|-----+----------+| \----/ \-----------------/ ``` ## The Competition Any input is acceptable (text file, STDIN, etc.) any readable output is acceptable (text file, STDOUT, etc) Here are some more examples: This is code golf, so shortest code wins! Some test cases: ``` +--------+----------+-------------+ | Colors | Foods | Countries | +--------+----------+-------------+ | red | pizza | Switzerland | /--> /----> | | | |[kale]/ | hot dogs | Brazil | | | <----------------------\ | | | orange |[yellow]\ | [green]/ | | +--------+--------|-+-------------+ \-------------------/ /------------------------------------------\ | | | +------------------+----------+-------+ | | | frog | | | | | | forge | dog | eagle | | | | foundation | diligent | ease | | | |[Brother]--\ | down | elf | | | | | |[egg]--\ |[fort]---/ \----> | | | | | | \-\ | \-----> | +-------------|----+----------+ | | Boy \--> | | | Bull | | | Browser | | +-----------------------------+-------+ /--------------------------------------\ | /---------------\| /------------|---------------------/ || | | /---------------\ || | +---------|-+-----------+-|------+--------|+ || \----> | | clarinet | \> | [drums]/| || | [viola]\\---> | +---------+ || | \-----> | | |/---/| +-----------+ [violin]\ | | [cello]--/ | | <------------/ | +---------+ | | +-----------+ <----------\| | | | | | [tuba]/| | | | [piano]\ | | | | | <-----------/ | | | | | +-----------+--------+ | | | | |[trumpet]------/ | [flute]-----> | | | | saxaphone | | +-----------+--------------------+---------+ ``` [Answer] # Python, ~~700~~ ~~681~~ ~~676~~ 667 characters Not fully golfed yet, but wanted to put up an answer. ``` import os D=map(list,os.read(0,9999).split('\n')) Z=Q=[-1,0,1,0,-1] J=''.join def T(y,x,d,_):c=D[y][x];D[y][x]=' ';d={'\\':3-d,'/':1-d}.get(c,d)%4;j=(y+Q[d],x+Q[d+1],d,c=='>');return c in'<>'and j or T(*j) def F(y,x,d): if y<Y or x<L: if D[y][x]=='+': if J(D[y]).find('+',x+1)+1:F(y,x+1,1) if any((l[x:]+[''])[0]=='+'for l in D[y+1:]):F(y+1,x,2) else:D[y][x]='--||'[d];F(y+Q[d],x+Q[d+1],d) i=0 for l in D: I=l.index if'+'in l: if Z:P,K,L,Z=i,I('+'),J(l).rfind('+'),0 Y=i while'['in l: s,e=map(I,'[]');y,x,_,R=T(i,e+1,1,1);W=l[s+1:e] if R:D[y][x:x+e-s-1]=W else:D[y][x-e+s+2:x+1]=W l[s:e+1]=' '*(e-s+1) i+=1 F(P,K+1,1);F(P+1,K,2) for l in D:print J(l) ``` **Strategy**: I turn the input into a matrix. Then I scan it line by line, finding `[`s. For every `[`, I find the matching `]`, then I call the trace function `T` with the spot immediately to the right of the `]`. The trace function follows the line, replacing the path with `' '`s as it goes, and returns where the word should go. Then I erase the word in the old location and put the word in the new location. Finally, I call `F`, which recursively reconstructs the boxes. **Tests**: ``` reorg_test1... True Input: +-------+--------+ | Verbs | Nouns | +-------+--------+ |[Truck]---> | | eat | Banana | | | Car | +-------+--------+ Output: +-------+--------+ | Verbs | Nouns | +-------+--------+ | | Truck| | eat | Banana | | | Car | +-------+--------+ reorg_test2... True Input: +-----------+----------+ | Verbs | Nouns | +-----------+----------+ | | | |[is a noun]-> | | eat | Banana | | | Car | +-----------+----------+ Output: +-----------+----------+ | Verbs | Nouns | +-----------+----------+ | | | | | is a noun| | eat | Banana | | | Car | +-----------+----------+ reorg_test3... True Input: +-----------+----------+ | Verbs | Nouns | +-----------+----------+ | [Truck]--\| | /------------/| <--\ | | eat | Banana || | | /--\ | Car || | +--|--|-----+----------+| \----/ \-----------------/ Output: +-----------+----------+ | Verbs | Nouns | +-----------+----------+ | | | | | Truck | | eat | Banana | | | Car | +-----------+----------+ reorg_test4... True Input: +--------+----------+-------------+ | Colors | Foods | Countries | +--------+----------+-------------+ | red | pizza | Switzerland | /--> /----> | | | |[kale]/ | hot dogs | Brazil | | | <----------------------\ | | | orange |[yellow]\ | [green]/ | | +--------+--------|-+-------------+ \-------------------/ Output: +--------+----------+-------------+ | Colors | Foods | Countries | +--------+----------+-------------+ | red | pizza | Switzerland | | yellow | kale | | | | hot dogs | Brazil | |green | | | | orange | | | +--------+----------+-------------+ reorg_test5... True Input: /------------------------------------------\ | | | +------------------+----------+-------+ | | | frog | | | | | | forge | dog | eagle | | | | foundation | diligent | ease | | | |[Brother]--\ | down | elf | | | | | |[egg]--\ |[fort]---/ \----> | | | | | | \-\ | \-----> | +-------------|----+----------+ | | Boy \--> | | | Bull | | | Browser | | +-----------------------------+-------+ Output: +------------------+----------+-------+ | frog | | | | forge | dog | eagle | | foundation | diligent | ease | | | down | elf | | | | | | fort | | | | | | egg | +------------------+----------+ | | Boy Brother | | | Bull | | | Browser | | +-----------------------------+-------+ reorg_test6... True Input: /--------------------------------------\ | /---------------\| /------------|---------------------/ || | | /---------------\ || | +---------|-+-----------+-|------+--------|+ || \----> | | clarinet | \> | [drums]/| || | [viola]\\---> | +---------+ || | \-----> | | |/---/| +-----------+ [violin]\ | | [cello]--/ | | <------------/ | +---------+ | | +-----------+ <----------\| | | | | | [tuba]/| | | | [piano]\ | | | | | <-----------/ | | | | | +-----------+--------+ | | | | |[trumpet]------/ | [flute]-----> | | | | saxaphone | | +-----------+--------------------+---------+ Output: +-----------+-----------+--------+---------+ | cello | clarinet | drums| | | | trumpet | +---------+ | | viola | | | +-----------+ | | | | violin | | +---------+ | +-----------+ tuba | | | | | | | | | | | | | piano | | | | | +-----------+--------+ | | | | | | | flute | | | | saxaphone | | +-----------+--------------------+---------+ ``` [Answer] # Python3, 584 bytes: ``` E=enumerate U=lambda b,x,y:0<=x<len(b)and 0<=y<len(b[0]) def f(b): q=[(x,y,'','',0,1)for x,r in E(b)for y,l in E(r)if'['==l] while q: x,y,w,l,X,Y=q.pop(0) if(u:=b[x][y]).isalpha():w+=u if u=='/':X,Y=[-X,-Y][::-1] if u=='\\':X,Y=[X,Y][::-1] if u in'><': for i,a in E([w,w[::-1]][u=='<']):b[x][y+Y*i]=a continue q+=[(x+X,y+Y,w,u,X,Y)] b[x][y]=' ' if'-'==u and U(b,x+1,y)and U(b,x-1,y)and' 'not in(Q:={b[x-1][y],b[x+1][y]})and{'|','+'}&Q:b[x][y]='|' if'|'==u and U(b,x,y-1)and U(b,x,y+1)and' 'not in(Q:={b[x][y+1],b[x][y-1]})and{'-','+'}&Q:b[x][y]='-' return b ``` [Try it online!](https://tio.run/##lVfdb9s2EH@u/goiD5M0SVHctMVgWHlI0T0WKLYOCShhoGPa4aqICiXNccr@7dlRor5pN6MN@0739bvjkRTzQ3nPs8vfcvHy8imiWfVABSmp9TVKycN6Q9Daf/IPy4tV9LRKaeasXZJtELCHhsUXiWtt6BZtQbS00GOEHTDwbVt9L/yFu@UCPfkCsQx9Ah3FHvy0YYXLtja2oyhNLLS/ZylFj@AEKQ97P/Vv/Nvo8TznuXPhwmO2dapltMZPCT4k7jkrSJrfE8dd7r2oquWoiiI7tJfKEAc3fnCb4OUyWCS9NI61GH7GQsBkX61sBQApmMwnDUy89/eNZoKVi5WduMsGhnf7K0siokzueFayrKJAP3qqDN6ND3JIpFKJuCqMxh7ZyK6D2gEkXyFV068OlNpb@Ae34wLNgXbGS8DifFlG38EHIAEvPlBeTf1QWt9tCUX37B@/fFl2caSOI8dx/EOwcAectzDGUQku6jhAQVAdJ5jHCSCOoGUlMrR@KRYoQmdnZ5YXNKP9DzxLor@oWBdIos@8ygqEpFEL/ymqu28JMFdIDQmGlJSKQtckg0/9qBkSfSSi0TL4UkCKtxNEI50GF9LIlL8W3MCj0QJ1CHoSwLMCEZSBi0TDH6eAhmmgQSKjZE4Gr5O61Ekp3WOaCFktQFN6WvxT624@YjnKGsThwDYIO/EKdJVYomNpy1asXMSz5LUY4Mj6O4FWi@M6pv4fjRA1NXrX18gzZTgy8qwGA0@5UC2Kfud8o@v0EUpWCkbrlv0/3gTdNKnl7PmZNOQfe1Y@U5GqJQjewrbN61pezZuqbgZVK/yNpDQJgbyHlbrhOwXzWpBnlg7V2hkwjXigxgXJdhTcHmia8n0Sq6neCUoziNGqzTOV80xjQ6QQTUYzJe/1lITBqwd0kkSvHrLW9uZuDFPlaW2JtoLvJm5mpOy1uYDCjbQ3rb1q@B2cZUPtKtuQkvGs12Yp29GsrLULOvCNrwUv76lI2lVR@95nre90O0IyQykx3e0aY4kBZ5k06yEeNlev3bMDElmTBox133Rs56zVHtdbzreSme9rfujdXZlKP9Ku0vTYfBu0Bd8XVLxC2zvZed4Af9O@Hwa7bjfC1/ax3lFNTXbCXb3rjheMNAaYLjmp9mh5KmBo2h5qOzRZRuNV77UI@l3B6yzHvVZvSHcpESyjqt9jfaYjvBHVQ5E0h4bspw//y3hKkhiGqWWHoLyJ6bw/R4Z99jJsj6tpE3hNfJbV22FniO/UHpnoGs8irsbTcAwqkrOlNY49daYPXNOaNNJA4LJaE13VI4Y4ZyTjSWwuzeD3aI7hz0xPpjndFsZBT6faP8Ql9E9O6w2ugaT7Z5tWJU3GPWBy1lPmgAV5IjlckOgxQ@v4y5PpoWc6ENX1qeR/rzkRG6eAW9Qb/SaNMVwumquIuohsWVpS4XwGOD4qzos8ZaVjx5ntwt2i9lJwyBsOmfou9qY3dDr3a1dJ3uSwFMHWPv@Hw9s@c13L6myLhTtg3g6ZyyHzbsi8HzIf3Jf/AA) ]
[Question] [ **Input:** An array **I** of **k** positive integers. The integers will be no larger than 100 and **k ≤ 100**. **Output:** Your code must output all possible arrays **O** of non-negative integers of length **k** with the restriction that **0 ≤ Oi ≤ Ii**. To get from one array to the next you may add or subtract 1 to one value in the array. Your code must not output the same array twice. If the number of different arrays to be output is very large, your code should just carry on outputting forever until it is killed. **Examples** * If **I** is an array of **k** ones then this is exactly the problem of iterating over all [Gray codes](https://en.wikipedia.org/wiki/Gray_code) of bit width **k**, except that the first and the last element do not need to be reachable in one step. * If `I = [2,1]` then one possible ordering of the output arrays is `(0,0),(0,1),(1,1),(1,0),(2,0),(2,1)` * If `I = [2,1,3]` then one possible ordering of the output arrays is `(0,0,0),(0,0,1),(0,0,2),(0,0,3),(0,1,3),(0,1,2),(0,1,1),(0,1,0),(1,1,0),(1,1,1),(1,1,2),(1,1,3),(2,1,3),(2,1,2),(2,1,1),(2,1,0),...`. This is a code-golf challenge, the submission with the source code with the shortest length wins. Don't let the short answers in golfing languages discourage you from posting an answer in other languages. Try to come up with the shortest answer in any language. This is also a restricted-complexity challenge. Every new array should be output with **O(k)** time elapsing since the previous outputted array (or the start of the program for the first array outputted). This means that the running time per new output array (they are each of length **k**) should be no greater than **O(k)**. That is it should take time proportion to **k** and not, for example **k2** or **2k**. Note this is not the average time per output but the worst case time for each and every array outputted. You can assume that all arithmetic on 64 bit integers can be performed in constant time as can reading and outputting them as well as assignment and looking up and changing values in arrays. One consequence of the restricted-complexity is that solutions that only output at program exit are not acceptable. [Answer] # [Python 3](https://docs.python.org/3/), 116 bytes ``` def f(a): l=len(a);t=[0]*l;d=[1]*l while 1: i=0;yield t while not-1<t[i]+d[i]<=a[i]:d[i]*=-1;i+=1 t[i]+=d[i] ``` [Try it online!](https://tio.run/##JU67DsMgDNzzFR7bPKTQbCEeO/QbUAZUiIKEABFLTb6emnY5n32n86WL9himUozdYLvp@9yAR28DU0moxrX10qASPBv47M5bEOwBh6O8nPUGiLe/ECINYiHl1s4wLKgZ50pbHIR0HQr2/nSs10L54qwtZtDgAv9Xj17001pbQMouENdo7Pm2ieAVjD2fOcfMatLHUb4 "Python 3 – Try It Online") Thanks [Mnemonic](https://codegolf.stackexchange.com/users/48543) for -1 byte. Generator function. (thanks Dennis for reminding me, I forgot the feature exists) If the output should be printed to stdout then use `print(t,flush=1)` for 9 additional bytes, or if Python is called with `-u`, `print(t)` suffices for +1 bytes. Stops with an error (`IndexError`). If you want to call this function and then continue the program, you have to catch it. [Answer] # [Stax](https://github.com/tomtheisen/stax), 22 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ▒)∙ñ╚▀NK♀F☺S(A#P`░]╪Db ``` [Run and debug it](https://staxlang.xyz/#p=b129f9a4c8df4e4b0c4601532841235060b05dd84462&i=[2+1+3]&a=1) [Here's a big one to show the asymptotic behavior](https://staxlang.xyz/#p=b129f9a4c8df4e4b0c4601532841235060b05dd84462&i=[1,+2,+3,+4,+5,+6,+7,+8]) Press run. Unpacked, ungolfed, and commented, it looks like this. ``` , pop from input to main stack W run the rest of the program repeatedly until explicitly cancelled cJP copy top of stack and print, delimited by spaces get the index to mutate i^ iteration index + 1 x{^|%}I repeatedly apply divmod using l[k]+1 from input get the index of the first value that returns modulus >0 cU=C if the result is -1 (no match), then terminate the program get the direction to mutate s get the "div" part of the last div operation called "d" ^|1 -1 ^ (d+1) ~{+}& increment element in array at the index by the calculated amount ``` [Run this one](https://staxlang.xyz/#c=,++++++++%09pop+from+input+to+main+stack%0AW++++++++%09run+the+rest+of+the+program+repeatedly+until+explicitly+cancelled%0A++cJP++++%09copy+top+of+stack+and+print,+delimited+by+spaces%0A+++++++++%09get+the+index+to+mutate%0A++i%5E+++++%09%09iteration+index+%2B+1%0A++x%7B%5E%7C%25%7DI%09%09repeatedly+apply+divmod+using+l[k]%2B1+from+input%0A+++++++++%09%09get+the+index+of+the+first+value+that+returns+modulus+%3E0%0A++cU%3DC+++%09if+the+result+is+-1+%28no+match%29,+then+terminate+the+program%0A+++++++++%09get+the+direction+to+mutate%0A++s++++++%09%09get+the+%22div%22+part+of+the+last+div+operation+called+%22d%22%0A++%5E%7C1+++%09%09-1+%5E+%28d%2B1%29%0A++~%7B%2B%7D%26++%09increment+element+in+array+at+the+index+by+the+calculated+amount&i=[2+1+3]&a=1) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 114 bytes ``` a=>{b=a.map(_=>0);c=a.map(_=>1);for(i=0;a[i];b[i]+=c[i]||-1){console.log(b);for(i=0;b[i]==a[i]*c[i];i++)c[i]^=1;}} ``` [Try it online!](https://tio.run/##RYtBCoMwEEWvk2lUTLscxotIWiapKSnWEZVu1LOnBgpuHu/D@2/@8uynOC7lIM8uBUpMzeqIqw@P6kFNDejPZQCDTCpSjdxGi@6AJn9w20oDq5dhlr6renkpd7Y5I8qPS24xag1Z7mRw3xMG1V4LY@Evxc1C@gE "JavaScript (Node.js) – Try It Online") Ungolfed: ``` function ggray(maxima) { var current = Array(maxima.length).fill(0); var flag = Array(maxima.length).fill(1); for (;;) { console.log(current); for (var i = 0; ; i++) { if (i == maxima.length) return; if (current[i] != maxima[i] * flag[i]) break; flag[i] = 1 - flag[i]; } if (flag[i]) current[i]++; else current[i]--; } } ``` [Answer] # [Kotlin](https://kotlinlang.org), ~~181~~ 178 bytes Thanks to: Anush pointed out I misunderstood the challenge saving 2 bytes. ovs pointed out a 1 byte savings. ``` val p={a:List<Int>->var l=a.size val v=Array(l,{0}) val i=Array(l,{1}) l-=1 o@while(0<1){println(v) var p=l while(v[p]+i[p]!in 0..a[p]){i[p]*=-1 p-=1 if(p<0)break@o} v[p]+=i[p]}} ``` [Try it online!](https://tio.run/##nVhtb@M2Ev7uX8EEB9TaOortbF8QxIvdu24XAYrmQ9MWxV5b0BZt8yyTKknF8ab57dtnhhSlbHPA4YzAssQZztszD0fZ2VBr8/H8XFybpg1C3TdqFVQltBczEayYTadCm6A2ynkRtjKIrbxTQo6gcidrXQknzUYJu87y5Wh0/kL8yylJG62tgx62W9lKiY2t12K1lXWtoHU52obQ@Mvzc1qktdIHudqpe4hgvVzZ/fkfrfJBW@PPZ1@@/OKLr0fvlFEOpj9g93dOHnlnPxpxBJfijRHS0eNrcmonGut10PC5C6MUt9v@Thx0XYulEsaKWjo8ojANBy5NhQ2uFimqmzawhV9s62I4@9YHYfmxQExky@tlraIHXtyQC8aaM6M28okTtEA5CFtYOGhcApxyCNXpFYUbkz0l6ze/a7pc/67huhUbFcTa2b2wJhmixJO6UfdBHG0r9ngmq0og975dBidXIZaHVFC2lhxhFdYvPw3J2BwWCXm5z5YOeqVKcb2OBtv9EglDLJVer5VTJnShwxiSmjZB@e@UO8YET8jFZM1vbVtX4j9kdAXNIzxMSkGbDaFHQVO0JuhaaN5ph4KpCvV4ey/3TU2lF/jApWtall39ufoImHCrTAQh/tQ9slEf2f/GWVRrT6I6AFRs05JBqmYPLhJYwvpBV1SwCTZZqSbEGtFGa@0QAeGF7mqJG4WNKR@V5XQaBbjGpKAzgG@CCYpAFfFBNeUgioV4P5/Mfo1@k0DGlXWVcuxkLECHvZhzRDeeTqbFBN8zfM/SNz2Zp@9Z8amdycX/bSnZitboOk/Xi@hDvs7TdZau0@hdviZvWW6W9OaD6zxdZ@kKvRKf0eg2VVVyoc6e8sskordd7jWiArJyo3kgcKUiBvuHW@sCOrBrzIM2IItvrPmMHoVeBoX2B2pi1I8sUppqEFYrN8BKpf0K2@M39yK3KtLK2CJwsi6XHhu6XhHN7biVwXpKtM0zjvW60hyz5jANtbfIRccjqjrDZuiRex2OfV5K8Zbb0ahD6pXUh33Hsu2b8a4QQcMbVcvGUwD4Qt5i76g7bVvftSvgHfcaM@MTqiVSleCDTts4uU/HQW6Y2KjdBgVRM6LYKwTaN5drjSHb7EmD@MnvIR7FGGJgPAdH0VpDbi0GoYHhN3wqJYqn8MiiZFpBeyfRIHcqGXO2QeqZji3YhBoczTzhMFSkH7H7bU5EO/9tV4rvbVCZaajtmWORbEJD9j/5vkz0erCO6c8nEd6c4iBziiv1SaJQcTA2VAAE79u9iski0pIOlduroFdEpV@@ZN7Kpw5pLNkJGNnTOW8AN4NSganYuIxCyFMVAVsN@Rju7knkoMiUJ@t6Y5jnSLK2dkdiAC/d8ilO93zkcLtE/qDD1Ci2rHC@E6QSTp5Hrk5o8LZueRaIt9bUxwyEkDFGOgwGKoBcEVMT25ajF@cjmltukNLaygoKSEzNtUXTNrWMpwLcCojIJ59IJR6TrP2tJeYYqA4OylimTr8crVvTSY55DeMJXa6uTXhViAVTMQuMT8f/eIhWkvqt/SEQAY@Lx@Lf5rRg42/vGyQWdUMIzGgpbURknTm7Ut535r7TPiRrD3TCYI93icr6wxtnZG5f0NCburYryUBWUSXVDwX/oJylX@mkAxs4PuZ4EQdIGRW@Uel5PA@5GUvx81bXvCtqQ2QVZVHnpTay6zJOxyQXREdkrfWmdckbm7LN406yeSdd1/OLVC2PCZFX6jTyLGLyx1FuIh6mj0USyHH8XWjGQmnvM8yCuIMHyr3GjwNHNJ5ezVJ@Y/RDMLWOx6KYQsSl1rKtQxrZOg2eGIZlmHT91KTZ56D6HOQsHLjrGXQxRJoyutlrbzGUaSKLpPGz4q6gkyT18lPv0kzYicfBGUVp6tY/rXaicRn@Jqs9Hx1puozvBv9NmMdIptODyvNRnPyf86PsuwXtxB7HWYZqnx1YpFLxSioPy77vRH79PMfRPxMn2rAKfaZlyUntl3N12aMfECLoudJOxVk9v@R0CpNeuOpbYTClZ8FI8mCsXkNj2FRHm1pscFKWSeY5/18sxNksredkJLiyzlqM8/MrMS1ytEtw/e41Q5qfPZIPnLkM6B@bKvHBJ4hZUoN@5runnXx2sEwFepJ/8fniuRBGT0zzz0RmTH23NABVDi9RjoluLzWR6sZ3nBrpkokO4rOvvoZ3wProIzV4s3iQl5kMz14xXyxkJAmmiEXq@wnTApNC/4hIoD5bzEb2NbvHHf@QsUjywOCiHsXVu/cNUIYvoIrRhJ/FAz14sUCVGtpJr8fN1bRI2X8csc6CZB4fP0aio3mwO4j74yUfphMBmomnu@3ItEaIE@SmSSMYpcRHiW4ImNDhodfHqAAx7WKjRiz6YB2Xel@KG34ZwxERZZPUSrYYVTAkxLeg1JoBzj505RbAi0QvkvffaaPGxclJyd6OT8VpUcLBh@icOHuVkDgk6rhWBotqjYsBhDNRIat4K@9RzAvpTtVe5YWwdfYgrjH5bmT9xm1aQt3bzvNxlqPP6U@8fYw5hntyWjzmPviJExeHjwP9NwONmf4N0p@m6cXPZ94Fy3k76cDMhaH0IL10FB60H@S003mS2hg66xBe0b4z8eefon/wSgxy8b8HfHprLbBiaL6MYh7hRpplc0UaGQaODssu7IobH6DhtxYcesyiNDCZ6mnA8dgruckxXIA@x8o56y4xgMNfGtCKhJ80EP1T0niK0eqEx5/oFeH7Zj2@mIg5/oqiIw2gL1IG0cLo44WYi4u/AA "Kotlin – Try It Online") ]
[Question] [ I love functional programming in Octave, but it's rather unwieldy in practice. I'm wondering about the shortest way to define an anonymous recursive function. I have some ideas, but I'm wondering if there is a way to combine these ideas to make them even shorter (or equally short but more versatile). For the sake of this question, let's recursively count down to zero (just to keep the payload as simple as possible). If my reasoning is correct, none of the variable names I used in the following examples should overlap. The desired function is `q(n)`, which should always return zero. `i` is used as a counter variable, `f` is the recursive function which I have called `g` in the local scope of `f`. ### 44 bytes, "inline definition of `f`" ``` q=@(n)(f=@(g,i){@()g(g,i-1),i}{~i+1}())(f,n) ``` ### 44 bytes, "argument list definition of `f`" ``` q=@(n,f=@(g,i){@()g(g,i-1),i}{~i+1}())f(f,n) ``` ### 44 bytes, "separate definition of `f`" ``` f=@(i,g){@()g(i-1,g),i}{~i+1}();q=@(n)f(n,f) ``` ### 41 bytes, "desired function as a return value" ``` f=@(g)@(n){@()g(g)(n-1),n}{~n+1}();q=f(f) ``` The current 'winner' is inspired by [this answer by flawr](https://codegolf.stackexchange.com/a/150189/32352). However, given the large range of different ways to do this, perhaps someone can think of an even shorter combination of methods. The goal is of course to get it below 39 bytes for a "full" function, [Try it online!](https://tio.run/##y08uSSxL/f8/rTQvuSQzP08h07ZQI08z07baQUMTyNI11NTJq6021K7Lq9XQtP6fmpfCVahhqvkfAA "Octave – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 39 bytes ``` q=f(f=@(g)@(n){@()g(g)(n-1),n}{~n+1}()) ``` [Try it online!](https://tio.run/##y08uSSxL/f@/0DZNI83WQSNd00EjT7PaQUMzHcjWyNM11NTJq62uy9M2rNXQ1PxfqGGq@R8A "Octave – Try It Online") ]
[Question] [ ### Background: Pi (`π`) is a [transcendental number](https://en.wikipedia.org/wiki/Transcendental_number), and therefore it has a non-terminating decimal representation. Similar, the representation doesn't terminate if written in any other integer base. But what if we wrote it in base `π`? Digits in decimal represent powers of 10, so: ``` π = 3.14… = (3 * 10^0) + (1 * 10^-1) + (4 * 10^-2) + … ``` So in base `π`, the digits would represent powers of `π`: ``` π = 10 = (1 * π^1) + (0 * π^0) ``` In this new base, integers now have non-terminating representations. So 10 in decimal now becomes the following: ``` 10 => 100.01022… = (1 * π^2) + (0 * π^1) + (0 * π^0) + (0 * π^-1) + (1 * π^-2) + … ``` Note that in base `π` the digits used are 0,1,2,3 because these are the digits less than `π`. ### Challenge: Given a non-negative integer `x`, either: 1. Output (without halting) its representation in base `π`. If the number has a finite representation (0, 1, 2, 3), then the program may halt instead of printing infinite zeros. 2. Take an arbitrarily large integer `n`, and output the first `n` digits of `x` in base `π`. ### Rules: * Since a number has multiple possible representations, **you must output the one that appears the largest** (normalized). Just as `1.0 = 0.9999…` in decimal, this problem exists in this base, too. In base `π`, one is still `1.0`, but could also be written as `0.3011…`, for example. Similarly, ten is `100.01022…`, but could also be written as `30.121…` or `23.202…`. * This is code-golf, so fewest bytes wins. Program or function. * No built-ins ([I'm looking at *you*, Mathematica](https://www.wolframalpha.com/input/?i=RealDigits%5B10,+%CF%80,+50%5D)) ### Results: ``` 0 = 0 1 = 1 2 = 2 3 = 3 4 = 10.220122021121110301000010110010010230011111021101… 5 = 11.220122021121110301000010110010010230011111021101… 6 = 12.220122021121110301000010110010010230011111021101… 7 = 20.202112002100000030020121222100030110023011000212… 8 = 21.202112002100000030020121222100030110023011000212… 9 = 22.202112002100000030020121222100030110023011000212… 10 = 100.01022122221121122001111210201201022120211001112… 42 = 1101.0102020121020101001210220211111200202102010100… 1337 = 1102021.0222210102022212121030030010230102200221212… 9999 = 100120030.02001010222211020202010210021200221221010… ``` [First 10,000 digits of ten in base Pi](https://pastebin.com/VeZrnNky) ### Verification: You can verify any output you want using the Mathematica code [here](https://www.wolframalpha.com/input/?i=RealDigits%5B10,+%CF%80,+50%5D). The first parameter is `x`, the third is `n`. If it times out, pick a small `n` and run it. Then click "Open in Code" to open a new Mathematica worksheet with the program. There's no time limit there. Convert the resulting output to a number [here](https://tio.run/##K0otycxL/P@/Vofr0DauaJ3qWoVYLq44Lj0uPW0VLhUtQy7tBD2NmBRNINY6tE3TkEvFUE/FiCsmAaj8///qakMdBQMwAjKMYGxjGMMISRZOGiEhQyRBNBIubohkGrItRkgiRshW1OooWNZyAQA). **Related:** * [Wikipedia: Non-integer representation](https://en.wikipedia.org/wiki/Non-integer_representation) * [Quora: What is 10 in base pi?](https://www.quora.com/What-is-10-in-base-pi) * [Math.SE: What would a base π number system look like?](https://math.stackexchange.com/q/1320248/206300) * [XKCD forum: Counting in a base pi number system?](http://forums.xkcd.com/viewtopic.php?t=36351) [Answer] # [Python 3](https://docs.python.org/3/), ~~471~~ ~~317~~ 310 bytes 7 bytes thanks to caird coinheringaahing. Surely there are golfs that I missed. Feel free to point them out in the comments. ``` def h(Q): a=0;C=b=4;c=d=s=1;P=o=3 while P^C: a,b,c,d,s,o,P,A,B=b,s*a+o*b,d,s*c+o*d,s+o,o+2,C,0,1 for I in Q:B*=c;A=A*a+I*B C=A>0 return P def f(n,p): Q=[-n];R="" while h([1]+Q)<1:Q=[0]+Q Q+=[0]*p for I in range(len(Q)): i=3;Q[I]+=3 while h(Q):Q[I]-=1;i-=1 R+=str(i) return R[:-p]+"."+R[-p:] ``` [Try it online!](https://tio.run/##RU8xboNAEKzhFYgKuCECQ@IYspEwlTugRUQCjAOSdYeAKMrryV4R54q90c7uzsz8s41KRvt@HW7W6JRuYhotBWlOHcVpT1daKUwLUhSZxvc43Qer@Mh5yGjRoccVKxQKZDhTh9VrhfI63fV6RvwLBSUOyBEg5K2bWqyLNUmrTM4e9WlGGe9cvDNzOWXvgWksw/a1SKswtaWbIzFrUyXVvmzSimz7z8jo1GEjSvctTJgNGPKY0MibzX@lpZWfg3MfJKfTl4yJorSsL43QmR63OLpu@hx34sJMJWjdFmdyH56qOvHnRthPtqhqf06aXatIrVJzPhwQIcYzXnDEK04IA8QHhFF0xIlfw@rzMsnN0bHiwHX3Xw "Python 3 – Try It Online") ### Ungolfed version: ``` def poly_eval_pi_pos(poly,a=0,b=4,c=1,d=1,o=3,s=1,prev=9,curr=6): while prev != curr: a,b,c,d,s,o=b,s*a+o*b,d,s*c+o*d,s+o,o+2 prev = curr res_n, res_d = 0,1 for I in poly: res_d *= c res_n = res_n*a + I * res_d curr = res_n > 0 return prev def to_base_pi(n,precision): poly = [-n] res = "" while not poly_eval_pi_pos([1]+poly): poly = [0]+poly poly += [0]*precision for index in range(len(poly)): i = 3 poly[index] += 3 while poly_eval_pi_pos(poly): poly[index] -= 1 i -= 1 res += str(i) return res[:-precision]+"."+res[-precision:] ``` [Try it online!](https://tio.run/##bVHLboMwEDyHr3A5Ad5UEGjSRKL3fgNCiIfTWEI2sknafD3dNYSqapHQ2uOd8c54uI8XrdJp6sSZDbq/V@JW99Ugq0HbgACo8xiaPIM2T6DDX@cpWKyDEbf8CO3VmHwfnrzN50X2ghHMnnJGOIKbGhpooQOLxAZsVHMdNbSPWlxh5Ro032GnY85E3BlhKwWMSodoDAmCZ23YO5PKjUrqm/k8Qtpjp7Db1ahmHLujWQOPSflxyN5Y7GH/eDXKzexRAqOumtoK9B8oMthKK7Uic3QhcoutKolmce37D89Kj3/DK5KSE0jslR7P2KLHHRKtF3nOoFSd@CKTplYfIuiFcg8ROiGJKukiWLjOkmQIWvL/7xEd9RdnmzMKFPWWFXlCITuaQIZrMogWp@06YMn9Z58T@IOdyommVjRxgc8EO0ghgxfYwwFe4QhJDNkOkjQ9wBG/ktI0Uo3Br7SzOAynbw "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-rbigdecimal/math`, ~~111~~ ~~103~~ 97 bytes ``` ->x,n{q=BigMath::PI n;r=q**m=Math.log(x,q).to_i;n.times{$><<"#{?.if-2==m-=1}%i"%d=x/r;x%=r;r/=q}} ``` [Try it online!](https://tio.run/##Fc7LCoJAFIDhVwlLKBnH1CJyPAbtWgTtRcK7Bxwv4wSG@epN9i@/1S9eyVsVoMxgJM3UwxXLeywrz3vcVg0T0BsGh7/Qui23I@l3VLZPZA2VyPNh2gS@r62nC8XCdAC4Cfaso6ZnMFqCjToIJizo51mFhk2pvScHh9iueyLnpYjmcVpNH/wUIRLnGLHuJYdZfdtOYtsMyhQJllmeIo9riy8bPw "Ruby – Try It Online") Takes input number as `x` and desired precision as `n`. Outputs by printing. Makes use of the built-in BigDecimal library for arbitrary pecision PI value. [Answer] # [Julia 0.6](http://julialang.org/), 81 bytes ``` f(x,i=log(π,x)÷1)=(y=big(π)^i;d::Int=x÷y;print(i==0?"$d.":"$d");f(x-d*y,i-1)) ``` Prints out digits (and the . which cost me 14 bytes) until it Stack overflows at about 22k digits on TIO. If I'm allowed to pass the input as a `BigFloat` I can cut 5 bytes. Makes use of the built in arbitrary precision constant `π`. But its a bit cooler than that, its actually an adaptive precision constant, `π*1.0` is a 64 bit floating point number, `π*big(1.0)` (aka multiplied by an higher precision number) gives `π` at whatever your precision is set to. [Try it online!](https://tio.run/##yyrNyUw0@/8/TaNCJ9M2Jz9d43yDToXm4e2GmrYalbZJmSABzbhM6xQrK8@8EtuKw9srrQuKMvNKNDJtbQ3slVRS9JSsgKSSpjXQDN0UrUqdTF1DTU2giYYGmlz/AQ "Julia 0.6 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/) + sympy, 144 bytes ``` from sympy import* def f(n,p): R="";O=n and int(log(n,pi));r=pi**O for _ in range(O+p):R+=str(int(n/r));n%=r;r/=pi return R[:O+1]+"."+R[O+1:] ``` [Try it online!](https://tio.run/##FY7NCoMwEITP@hRBKBiz1N/WquQZBK8iRfCnQt2ENT349DaZ08LsNzP6NB@F@XUtpHZ2nLs@2bZrRSbyp3lhS4igee17nQyCppXIRpzYhib8qtV5G@cNSb1FUet7iyL2ti6jEdc5bIVFOyEPQ6FDMCb7jTdJDcWW8T2azY@QdX3dinQQwT0QXW/PerhcFrqsPoEUMsihgAc8oYQXVJAmUGSQ5nkJldVgF2pyHW5wlnB@/QE "Python 3 – Try It Online") Quite slow, actually. ]
[Question] [ If we define a Fibonacci-like sequence as **fk(n) = (fk(n-1) + fk(n-2)) % k**, for some integer **k** (where **%** is the modulo operator), the sequence will necessarily be cyclic, because there are only **k2** different values for **(fk(n-1), fk(n-2))**. However, this cycle doesn't usually include *all* possible pairs of values, so depending on the two starting values **fk(0)** and **fk(1)**, we might get different cycles. For example, for **k = 2**, we have the following four possibilities, depending on the first two values: ``` 0, 0, 0, 0, 0, 0, 0, 0, 0, ... 0, 1, 1, 0, 1, 1, 0, 1, 1, ... 1, 0, 1, 1, 0, 1, 1, 0, 1, ... 1, 1, 0, 1, 1, 0, 1, 1, 0, ... ``` Due to the cyclic nature of the sequences, there are really only two fundamentally different sequences here, with orbits **(0)** and **(0, 1, 1)**. Let's look at **k = 3**: ``` 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, ... 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, ... 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, ... 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, ... 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, ... 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, ... 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, ... 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, ... ``` Again, there are only two different orbits: **(0)** and **(0, 1, 1, 2, 0, 2, 2, 1)**. For higher **k** we might get more orbits, but they will still fall into a comparably small number of classes. For example **k = 4** yields the four orbits **(0)**, **(0,1,1,2,3,1)**, **(0, 2, 2)**, **(0, 3, 3, 2, 1, 3)** and **k = 5** the three orbits **(0)**, **(0, 1, 1, 2, 3, 0, 3, 3, 1, 4, 0, 4, 4, 3, 2, 0, 2, 2, 4, 1)** and **(1, 3, 4, 2)**. Your task in this challenge is to compute how many orbits the sequence generates for a given **k**. This is [OEIS A015134](https://oeis.org/A015134). Here are the first 100 values (starting from **k = 1**): ``` 1, 2, 2, 4, 3, 4, 4, 8, 5, 6, 14, 10, 7, 8, 12, 16, 9, 16, 22, 16, 29, 28, 12, 30, 13, 14, 14, 22, 63, 24, 34, 32, 39, 34, 30, 58, 19, 86, 32, 52, 43, 58, 22, 78, 39, 46, 70, 102, 25, 26, 42, 40, 27, 52, 160, 74, 63, 126, 62, 70, 63, 134, 104, 64, 57, 78, 34, 132, 101, 60, 74, 222, 37, 38, 62, 328, 89, 64, 82, 124, 41, 86, 42, 172, 75, 44, 184, 178, 181, 132, 82, 180, 99, 140, 104, 246, 49, 50, 114, 76 ``` Make sure to check **k = 11**, which is the first input which yields more than **k** orbits. ## Rules You're given a positive integer **k** and should output **A015134(k)**. You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of the [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output. You may use any [programming language](https://codegolf.meta.stackexchange.com/q/2028), but note that [these loopholes](https://codegolf.meta.stackexchange.com/q/1061/) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~17~~ 16 bytes ``` Lüȯ€U¡ȯ↔m%⁰∫π2ŀ⁰ ``` [Try it online!](https://tio.run/##yygtzv7/3@fwnhPrHzWtCT20EEi3TclVfdS44VHH6vMNRkcbgMz///8bGgIA "Husk – Try It Online") ## Explanation ``` Lüȯ€U¡ȯ↔m%⁰∫π2ŀ⁰ Implicit input, say n=4. ŀ⁰ Lowered range: [0,1,2,3] π2 Cartesian second power: [[0,0],[0,1],[1,0],[0,2].. üȯ Deduplicate with respect to this function: €U¡ȯ↔m%⁰∫ Arguments are two pairs, say a=[0,2], b=[1,1] ¡ȯ Iterate on a: ∫ Cumulative sum, m%⁰ take modulo n of each, ↔ then reverse: [[0,2],[2,0],[2,2],[0,2],[2,0].. U Cut at first repeated element: [[0,2],[2,0],[2,2]] € Is b in this list? No, so they are distinct in ü. L Number of remaining pairs. ``` [Answer] # Bash, ~~172~~, ~~119~~, ~~113~~, 91 bytes ``` n=$1;for((k=0;k<n*n;++k)){((H[k]||++c));for((;!H[k];k=(k/n+k)%n*n+k/n)){ H[k]=1;};};echo $c ``` [Try it online](https://tio.run/##JcvBCsIwDAbg@54iQoXEwrReY@@@g@yg3dxKIIV53PbsNWPk8vP/Xz7v31RHJKwaXeBvmREl3lgeelH2XogWxOdLunX1PhEdhE97xRJRrmrobNpbNA37EgNvdkOaCrhUqWnsDTJkhSW0bbhvDH2BEVzmvuhQ/w) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~76~~ 70 bytes ``` Tr[EdgeCycleMatrix[#->{#[[2]],Tr@#~Mod~n}&/@Tuples[Range[n=#]-1,2]]!]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aaZ/s/pCjaNSU91bkyOSfVN7GkKLMiWlnXrlo5OtooNlYnpMhBuc43P6Uur1ZN3yGktCAntTg6KDEvPTU6z1Y5VtdQB6hKMVbtf0BRZl5JNNBEfQeItCFQ4j8A "Wolfram Language (Mathematica) – Try It Online") ## How it works We construct the graph given by the rules `{{0,0}->{0,0}, {1,0}->{1,1}, ...}` that, given two elements of a generalized Fibonacci sequence, find the next one modulo `n`. The `EdgeCycleMatrix` gives the incidence matrix from cycles to edges in this graph; we want to count its rows. (There are a number of built-ins that do a similar task, but `ConnectedComponents` is longer, and `FindCycle` needs lots of extra inputs to make it work. Besides, `EdgeCycleMatrix` is a rectangular array, not funny-shaped like the other two, which helps later.) To count the rows of the matrix, we take the factorial of the entries to turn it into a matrix of all ones, then take the trace. (Each cycle contains at least one edge and therefore there are at least as many columns as rows - so this counts the rows and not the columns.) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~38~~ 36 bytes ``` :qt!J*+le"@GU:"t&Zjwy+G\J*+hu]S]Xhun ``` [**Try it online!**](https://tio.run/##y00syfn/36qwRNFLSzsnVcnBPdRKqUQtKqu8Uts9BiiWURobHBuRUZr3/785AA "MATL – Try It Online") It times out in the online compiler for input exceeding `7`. ### Explanation The code defines orbits in terms of complex numbers, where the imaginary part is the *new term* and the real part is the *preceding term* in the Fibonacci sequence. Each complex value encodes the *state* of the sequence. Namely, given `a+jb` the next value is computed as `b+j(a+b)`. The possible starting values are `a+jb` with `a`, `b` in `[0, 1, ..., k-1]`. For each starting value, the code iterates `k^2` times. Actually, to make the code shorter, each iteration is applied to *all* accumulated so values so far, and the results are deduplicated (which would be necessary at the end anyway). After the last iteration, the vector of deduplicated complex values is sorted (by absolute value, then by angle). This gives a "signature" for each orbit. At the end of the program, signatures are collected into a cell array. The number of unique signatures is the desired output. ``` :q % Implicit input: k. Push row vector [0, 1, ..., k-1] t! % Duplicate, transpose: gives column vector [0; 1; ...; k-1] J*+ % Multiply by 1j, add with broadcast. Gives a k × k matrix of % values a+jb with a, b in [0, 1, ..., k-1] le % Linearize into a row vector " % For each c in that vector @ % Push c GU:" % Do the following k^2 times t&Zj % Duplicate and split into real and imaginary parts: a, b wy+ % Swap, duplicate, from below, add: transforms a, b into % b, a+b. This is the basic step in the Fibonacci sequence % In subsequent iterations a and b may be vectors instead % of numbers, as they include all values obtained so far G\ % Modulo k, element-wise J*+ % Times 1j, add. Gives the next complex number for each of % the complex numbers so far hu % Append to values so far and deduplicate. This may extend % the vector of complex numbers ] % End S % Sort ] % End Xh % Collect entire stack into a cell array u % Deduplicate n % Number of entries. Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` Ṛ+\%³ Ḷṗ2ÇÐĿ€Ṣ€QL ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//4bmaK1wlwrMK4bi24bmXMsOHw5DEv@KCrOG5ouKCrFFM////MTE "Jelly – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~196~~ 191 bytes ``` import Data.List o(a:b)=1+o[x|x<-b,not$(0<$a)==(0<$x)&&isInfixOf a(x++x)] o _=0 k#(a,b)=(b,mod(a+b)k) p!(a:b)|elem a p=fst<$>p|r<-p++[a]=r!b f k=o[[]!iterate(k#)(a,b)|a<-[0..k-1],b<-[0..k-1]] ``` [Try it online!](https://tio.run/##RYyxqsMgFEB3v@KGhqKYhGQt2uktDx70A0TKlSoVkyjGwSH/ntd26XTOcs4Tt2Dn@Tj8kmIu8IMFhz@/FRIpXgyTE4@q7lX0pltjaekoWmRSvlnZ@ey339X5enOAtHJemSYR7nIk4USxe/XUdEt8UOSGBUZS87nudrYLICTptiLaa9qz6BPnCrXMjSEOgoxK6cYXm7FYGk7ss9tR9GochtBPujNf18eCfpUp@7VACw6m6fgH "Haskell – Try It Online") This could probably be improved. Particularly if someone can find a way to avoid `isInfixOf` and remove the import. Basic idea is to generate a list of "states" (tuples containing the two previous values) to see when it starts to cycle. Then we check whether each orbit is different to its predecessors (really works the other way around but it's hard to put into words). To check if orbits are the same we check if the length is the same and whether one fits into the other concatenated with itself. For example `[0,2,2]`,`[2,2,0]`: length of both is 3 and `[0,2,2,0,2,2]` contains `[2,2,0]` as a continuous subsequence. I'm not sure if it's foolproof but it seems to work. EDIT: thanks to Laikoni for taking off 5 bytes! I should've read more of those tips. [Answer] # JavaScript (ES6), ~~337~~ 335 bytes Sorry for the Ω(k^3) brute-force algorithm. ``` (k,x=o=0,u=[],s=(q,w,v,j=d=0)=>{while(j++<v)d|=q.reduce((a,b,i)=>a&=b==w[(i+j)%v],1);return d})=>{for(;x<k;x++)for(y=0;y<k;y++){l=2;r=[x,y];do{r.push((c=(d=r[(l+=2)-3])+r[l-4])%k,(c+d)%k)}while(!(t=r.slice(0,h=l/2)).reduce((a,b,i)=>a&=b==r[i+h],1));if(!u.reduce((q,z)=>q|=(t.length-(a=z.length)?0:s(t,z,a)),0)){o++;u.push(t)}}return o} ``` The performance... ~~When I was calculating A015134(something beyond k=50) it exceeded 60s limit on TIO.~~ ``` var g=(k,x=o=0,u=[],s=(q,w,v,j=d=0)=>{while(j++<v)d|=q.reduce((a,b,i)=>a&=b==w[(i+j)%v],1);return d})=>{for(;x<k;x++)for(y=0;y<k;y++){l=2;r=[x,y];do{r.push((c=(d=r[(l+=2)-3])+r[l-4])%k,(c+d)%k)}while(!(t=r.slice(0,h=l/2)).reduce((a,b,i)=>a&=b==r[i+h],1));if(!u.reduce((q,z)=>q|=(t.length-(a=z.length)?0:s(t,z,a)),0)){o++;u.push(t)}}return o} for (var ix = 1; ix <= 15; ix++) console.log(`A015134(${ix}) = ${g(ix)}`); ``` # Explanation(Ungolfed) ``` function CheckIfSameOrbit(Array_1, Array_2, Length) { // Checks if the orbits are equal var d = false, j = 0; // Assume both have same length while (j < v) { // Checks for different startings j++; d |= Array_1.reduce(function(Acc, Item, Index) { // Element-by-element comparison Acc &= Item == w[(Index + j) % v], 1); }); // Return true if any starting } // point makes two orbits identical } function A015134(k) { // Main Program var o = 0, u = []; for (var x = 0; x < k; x++) { // Checks different pairs of (x, y) for (var y = 0; y < k; y++) { var l = 2, r = [x, y], h = 1, t; do { // Find until a complete orbit is l += 2; // found (except for (0, 0) case) h = l / 2; var d = r[l - 3], c = r[l - 3] + r[l - 4]; r.push(c % k, (c + d) % k); t = r.slice(0, h); } while (!t.reduce(function(Acc, Item, Index) { // Which is, if 2 identical copies Acc &= Item == r[Index + h]; // of the orbit are calculated }, 1)); if (!u.reduce(function(Acc, Item) { // If the orbit is a new one var a = Item.length; Acc |= (t.length - a ? 0 : s(t, Item, a)); }, 0)) { o++; // Increment the counter, and u.push(t); // record it to the list } } } return o; // Ultimately return the counter; } ``` [Answer] # Perl 5, 80+1 (-p) bytes ``` $n=$_;map{$a[$_]||++$\;$a[$_]++until$a[$_=0|($_/$n+$_)%$n*$n+$_/$n]}0..$n**2-1}{ ``` [Try it online](https://tio.run/##JcdNDkAwEAbQy3wSTIpKrKQnoWksLJowGj8rdXVD2L0XxnVqRMAGrp2HcGLo4GyMROjbP0QH7376YqqYwpVggssScP7pvb2qonif10pfp4jW9xJ2v/AmKjw) [Answer] ## JavaScript (ES6), 102 bytes ``` k=>F=(a=0,b=0,C=0,q)=>q?F[q=[a,b%=k]]?0:1|F(b,a+b,C,F[q]=1):b<k?F(a,b+1,C+F(a,b,C,1)):++a<k?F(a,0,C):C ``` Returns a function which returns the result. For 3 more bytes we can have it return the result directly: ``` k=>(F=(a,b,C,q)=>q?F[q=[a,b%=k]]?0:1|F(b,a+b,C,F[q]=1):b<k?F(a,b+1,C+F(a,b,C,1)):++a<k?F(a,0,C):C)(0,0,0) ``` Both have time complexity O(n2). [Answer] # [Python 2](https://docs.python.org/2/), 214 bytes ``` def h(k): R=[] for p in[[i/k,i%k,(i/k+i%k)%k]for i in range(k*k)]: while p[:2]!=p[-2:]: p.append(sum(p[-2:])%k) p=p[:-2] if not any([p==x[i:]+x[:i]for i in range(len(p))for x in R]):R.append(p) print len(R) ``` [Try it online!](https://tio.run/##XY9BCsIwEEXXzSnGRSGjVbErCfQS3Q5ZFEztEE2HWrU9fU0UEdx93v@8YWQeuz6Uy3JyLXTao1FQV2QVtP0AAhyIeO8Lzn2hY9jEgLm3qeXYwtCEs9N@7dEalT07vjgQMqVdVULb0iSaya4RceGkb/er/uAoQZVJHJltaVXGLYR@hCbMmqSqJmJjNxMZ/j91cUELYqJTorVFU3/9ggpk4DBCmtW4UKcf@P7l8VMcisMR7fIC "Python 2 – Try It Online") It's not very efficient but it's the golfiest I could do. ]
[Question] [ [Fermat numbers](https://oeis.org/A000215) are positive integers that can be expressed as 22x+1 with an integer x. Let us now define an attribute of a number called "Fermat-ness": * The Fermat-ness of the number is one less than the length of the chain of powers of two, starting from the base, with powers of two expanded so as to maximize the fermat-ness. * A number that is not a Fermat number has the Fermat-ness of zero. So, 17 (=22220+1) has Fermat-ness three. ## Challenge Given a positive nonzero integer as input, output the Fermat-ness of the number. ## Rules * You may take the input in binary, decimal, hexadecimal, as a bignum, or whatever format lets you golf best * Your solution must be able to process numbers with bit-lengths over 64 whichever representation you use. * Nonnegative integer powers only. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are of course prohibited. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. ## Test cases These are in format `input->output`. The input is in hexadecimal to save space. ``` 10000000000000000000000000000000000000000000000000000000000000001 -> 2 1000000000000BC00000000000000000000000000000000001000000000000001 ->0 1234567890ABCDEF -> 0 100000000000000000000000000000001 -> 1 5 -> 2 11 -> 3 10001 -> 4 101 -> 1 ``` The same in decimal: ``` 115792089237316195423570985008687907853269984665640564039457584007913129639937 -> 2 115792089237316497527923305698859709742143344804209838213621568094470773145601 -> 0 1311768467294899695 -> 0 340282366920938463463374607431768211457 -> 1 5 ->2 17 -> 3 65537 -> 4 257 -> 1 ``` Thanks to [geokavel](https://codegolf.stackexchange.com/users/46313/geokavel) for invaluable input in the sandbox. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes 1 byte thanks to Jonathan Allan. ``` ’µBḊ⁸LṀ?µÐĿḊḊL ``` [Try it online!](https://tio.run/##XY69TYNhDIR7psgAFLbPvxUSdTZAKdOgLECX0CBR0bIDbaRQISUskm@RF78pkWzJOtvP3fN2t3sZY9l/no@P19P7cjitr9/7h/Px8vH700LXelzeltevMZ6YLUooSxBg5zIVWFClEaVnFEUaxKtS3c2VZqPUwlKJohgs5ahC3N@t/gG1wqQFoP8q06rZocIKqCaptBVSGC5snlSqQdGvak48gWAOb/OQ0qzyslahJClwb69Cb9GFUKdQzHvhJsxA85rn4Ga3hHKTJxqbPw "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~103~~ 81 bytes ``` n=input()-1 i=l=0 while 2**2**i<=n: if n==2**2**i:n=2**i;i=-1;l+=1 i+=1 print l ``` [Try it online!](https://tio.run/##LYnBCoAgEETvfoXHMoS0m7afUziwbBJG9PWbQTA8Hm/q08ohURUEqVcbRh@MENNs7gLebHSuDytJMha7FaI/JfkMGeRD5olC/z/WE9Isqy4v "Python 2 – Try It Online") I realized not being stupid would help lower my byte count, so I did that. Also exponentiation as opposed to logarithms. [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 75 bytes ``` «\`n=1\]{1-\n*\]}:[»`^=«1-`n=001{]2\^2\^ne{2\^`n=1+0}{1+}?]2\^2\^n>¬}:[»`¤= ``` [Try it online!](https://tio.run/##XY49TsNQEIR7TpGCisjS/v8gGQ6CE6VBdCZKa/k26cIN6N7FzFrEFEj7XrEz3@xczpfPj7GjZWm34TT2OBwm7IbxaTjMz2/t@3Ts2w27UgBwOtBwrBnfp/pX9x7mCffz6ya8tK9frF375RFRPQkiiZ3RMFWI1SFDAcLCEzyUyTJDzNQE1scp6hoC4ImMlMaZ7Lt23Z0f/odKulItmIvNCM3KdyEUZpEAoTrHQchGqBaQIg5eqKgBbqGM6FYlnFIi01LvCgtQEJvVzeRycA27GLjwyhBW0lZuo3BbmOpfc7rblh8 "RProgN 2 – Try It Online") It's only 70 bytes if you don't add the `«»'¤=` which assigns the Fermatness calculation to the `¤` character. If you do that, you'll need to put the number in the Header section of TIO instead of in the Footer like it is now. This effectively uses the same logic as my Python answer, so if you don't care about how RProgN 2 works, just look at that one for an explanation of what's going on. Otherwise Code breakdown: ``` «\`n=1\]{1-\n*\]}:[»`^= « »`^=` # Create a local function and assign it to the ^ character (x y ^ is x to the power of y) \`n= # Swap the top two values of the stack and assign the new top to the variable n 1\] # Push a 1 (our starting point for x to the y), swap with the y value, then duplicate y { }: # Start a while loop that pops the top stack value and loops if it is truthy 1- # Subtract 1 from y to keep a tally of how many multiplications we've done \n* # Swap the counter with our current value and multiply it by n \] # Swap this new value with the current value of y, and duplicate it to be used as the truthy value for the loop «1-`n=001{]2\^2\^ne{2\^`n=1+0}{1+}?]2\^2\^n>¬}:[»`¤=# The main Fermatness function (x ¤ to get the Fermatness of x) « »`¤=# Create another local function for this calculation 1-`n= # Decrement the input by 1 and assign it to n 001 # Push a counter for Fermatness, a counter for calculating 2^2^i, and an initial truthy value { }: # Start a while loop for calculating the Fermatness ]2\^2\^ne # Duplicate i, calculate 2^2^i, and compare it to n { }{ }? # Start an if statement based on the equality of 2^2^i and n 2\^`n= # n==2^2^i, so set n to 2^i (same as saying n=log_2(n)) 1+0 # Increment the Fermatness counter and reset i 1+ # n!=2^2^i, so just increment i ]2\^2\^n>¬ # Duplicate the counter and check if 2^2^i<=n, if true the loop continues, else it exits [ # Pop i from the stack, leaving us with just the Fermatness counter ``` Unfortunately the log function `Š` and the normal exponentiation function `^` lack the precision to do this natively, so I had to redefine how exponentiation worked since multiplication carries much more precision. Without that redefine, this answer would be 23 bytes shorter. [Answer] # [Perl 6](http://perl6.org/), 62 bytes ``` {my@a=first :kv,*>=0,(^∞).map(2**2** *+1-$_);++@a[0]*!@a[1]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OrfSIdE2LbOouETBKrtMR8vO1kBHI@5RxzxNvdzEAg0jLS0gUtDSNtRVide01tZ2SIw2iNVSBFKGsbX/rRWKEysVlFTirRSq0xRU4muVFNLyixRsjBVMFEwVzBQMzRUMLRSMTM2A2NzO@j8A "Perl 6 – Try It Online") ]
[Question] [ **Overview** In this challenge, you will be given two numbers which are both a small offset larger than a multiple of a medium-size number. You must output a medium-sized number that is almost a divisor of both of the numbers, except for a small offset. The size of the numbers involved will be parameterized by a difficulty parameter, `l`. Your objective is to solve the problem for the largest possible `l` in under 1 minute. --- **Setup** In a given problem, there will be a secret number, `p`, which will be a random `l^2` (`l*l`) bit number. There will be two multipliers, `q1, q2`, which will be random `l^3` bit numbers, and there will be two offsets, `r1, r2`, which will be random `l` bit numbers. The input to your program will be `x1, x2`, defined as: ``` x1 = p * q1 + r1 x2 = p * q2 + r2 ``` Here's a program to generate test cases, in Python: ``` from random import randrange from sys import argv l = int(argv[1]) def randbits(bits): return randrange(2 ** (bits - 1), 2 ** bits) p = randbits(l ** 2) print(p) for i in range(2): q_i = randbits(l ** 3) r_i = randbits(l) print(q_i * p + r_i) ``` The first line of output is a possible solution, while the second and third lines are the input that your program will be given. --- **Your Program** Given `x1`, `x2` and `l`, you must find a `l^2` bit number `p'` such that `x1 % p'` and `x2 % p'` are both `l` bit numbers. `p` will always work, though there may be other possibilities. Here's a function to verify a solution: ``` def is_correct(x1, x2, l, p_prime): p_prime_is_good = p_prime >> (l**2 - 1) and not p_prime >> l ** 2 x1_is_good = (x1 % p_prime) >> (l-1) and not (x1 % p_prime) >> l x2_is_good = (x2 % p_prime) >> (l-1) and not (x2 % p_prime) >> l return bool(p_prime_is_good and x1_is_good and x2_is_good) ``` --- **Example** Suppose `l` is 3. The generator program picks a 9-bit number for `p`, which in this case is `442`. The generator picks two `3` bit numbers for `r1, r2`, which are `4, 7`. The generator picks two `27` bit numbers for `q1, q2`, which are `117964803, 101808039`. Because of these choices, `x1, x2` are `52140442930, 44999153245`. Your program would be given `52140442930, 44999153245` as input, and must output a 9-bit number (in the range `[256, 511]`) such that `52140442930` and `44999153245` modulo that number give 3 bit numbers (in the range `[4, 7]`). `442` is the only such value in this case, so your program would have to output `442`. --- **More examples** ``` l = 2 x1 = 1894 x2 = 2060 p = 11 No other p'. l = 3 x1 = 56007668599 x2 = 30611458895 p = 424 No other p'. l = 6 x1 = 4365435975875889219149338064474396898067189178953471159903352227492495111071 x2 = 6466809655659049447127736275529851894657569985804963410176865782113074947167 p = 68101195620 I don't know whether there are other p'. l = 12 x1 = 132503538560485423319724633262218262792296147003813662398252348727558616998821387759658729802732555377599590456096450977511271450086857949046098328487779612488702544062780731169071526325427862701033062986918854245283037892816922645703778218888876645148150396130125974518827547039720412359298502758101864465267219269598121846675000819173555118275197412936184329860639224312426860362491131729109976241526141192634523046343361089218776687819810873911761177080056675776644326080790638190845283447304699879671516831798277084926941086929776037986892223389603958335825223 x2 = 131643270083452525545713630444392174853686642378302602432151533578354175874660202842105881983788182087244225335788180044756143002547651778418104898394856368040582966040636443591550863800820890232349510212502022967044635049530630094703200089437589000344385691841539471759564428710508659169951391360884974854486267690231936418935298696990496810984630182864946252125857984234200409883080311780173125332191068011865349489020080749633049912518609380810021976861585063983190710264511339441915235691015858985314705640801109163008926275586193293353829677264797719957439635 p = 12920503469397123671484716106535636962543473 I don't know whether there are other p'. l = 12 x1 = 202682323504122627687421150801262260096036559509855209647629958481910539332845439801686105377638207777951377858833355315514789392768449139095245989465034831121409966815913228535487871119596033570221780568122582453813989896850354963963579404589216380209702064994881800638095974725735826187029705991851861437712496046570494304535548139347915753682466465910703584162857986211423274841044480134909827293577782500978784365107166584993093904666548341384683749686200216537120741867400554787359905811760833689989323176213658734291045194879271258061845641982134589988950037 x2 = 181061672413088057213056735163589264228345385049856782741314216892873615377401934633944987733964053303318802550909800629914413353049208324641813340834741135897326747139541660984388998099026320957569795775586586220775707569049815466134899066365036389427046307790466751981020951925232623622327618223732816807936229082125018442471614910956092251885124883253591153056364654734271407552319665257904066307163047533658914884519547950787163679609742158608089946055315496165960274610016198230291033540306847172592039765417365770579502834927831791804602945514484791644440788 p = 21705376375228755718179424140760701489963164 ``` --- **Scoring** As mentioned above, your program's score is the highest `l` that the program completes in under 1 minute. More specifically, your program will be run on 5 random instances with that `l`, and it must output a correct answer on all 5, with an average time under 1 minute. A program's score will be the highest `l` that it succeeds on. Tiebreaker will be average time on that `l`. To give you an idea of what scores to aim for, I wrote a very simple brute-force solver. It got a score of 5. I wrote a much fancier solver. It got a score of 12 or 13, depending on luck. --- **Details** For perfect comparability across answers, I will time submissions on my laptop to give canonical scores. I will also run the same randomly chosen instances on all submissions, to alleviate luck somewhat. My laptop has 4 CPUs, i5-4300U CPU @ 1.9 GHz, 7.5G of RAM. Feel free to post a provisional score based on your own timing, just make it clear whether it's provisional or canonical. --- May the fastest program win! [Answer] # Rust, L=13 ### `src/main.rs` ``` extern crate gmp; extern crate rayon; use gmp::mpz::Mpz; use gmp::rand::RandState; use rayon::prelude::*; use std::cmp::max; use std::env; use std::mem::swap; // Solver fn solve(x1: &Mpz, x2: &Mpz, l: usize) -> Option<Mpz> { let m = l*l - 1; let r = -1i64 << l-2 .. 1 << l-2; let (mut x1, mut x2) = (x1 - (3 << l-2), x2 - (3 << l-2)); let (mut a1, mut a2, mut b1, mut b2) = (Mpz::one(), Mpz::zero(), Mpz::zero(), Mpz::one()); while !x2.is_zero() && &(max(a1.abs(), b1.abs()) << l-2) < &x1 && &(max(a2.abs(), b2.abs()) << l-2) < &x2 { let q = &x1/&x2; swap(&mut x1, &mut x2); x2 -= &q*&x1; swap(&mut a1, &mut a2); a2 -= &q*&a1; swap(&mut b1, &mut b2); b2 -= &q*&b1; } r.clone().into_par_iter().map(|u| { let (mut y1, mut y2) = (&x1 - &a1*u + (&b1 << l-2), &x2 - &a2*u + (&b2 << l-2)); for _ in r.clone() { let d = Mpz::gcd(&y1, &y2); if d.bit_length() >= m { let d = d.abs(); let (mut k, k1) = (&d >> l*l, &d >> l*l-1); while k < k1 { k += 1; if (&d%&k).is_zero() { return Some(&d/&k) } } } y1 -= &b1; y2 -= &b2; } None }).find_any(|o| o.is_some()).unwrap_or(None) } // Test harness fn randbits(rnd: &mut RandState, bits: usize) -> Mpz { rnd.urandom(&(Mpz::one() << bits - 1)) + (Mpz::one() << bits - 1) } fn gen(rnd: &mut RandState, l: usize) -> (Mpz, Mpz, Mpz) { let p = randbits(rnd, l*l); (randbits(rnd, l*l*l)*&p + randbits(rnd, l), randbits(rnd, l*l*l)*&p + randbits(rnd, l), p) } fn is_correct(x1: &Mpz, x2: &Mpz, l: usize, p_prime: &Mpz) -> bool { p_prime.bit_length() == l*l && (x1 % p_prime).bit_length() == l && (x2 % p_prime).bit_length() == l } fn random_test(l: usize, n: usize) { let mut rnd = RandState::new(); // deterministic seed for _ in 0..n { let (x1, x2, p) = gen(&mut rnd, l); println!("x1 = {}", x1); println!("x2 = {}", x2); println!("l = {}", l); println!("p = {}", p); println!("x1 % p = {}", &x1 % &p); println!("x2 % p = {}", &x2 % &p); assert!(is_correct(&x1, &x2, l, &p)); let p_prime = solve(&x1, &x2, l).expect("no solution found!"); println!("p' = {}", p_prime); assert!(is_correct(&x1, &x2, l, &p_prime)); println!("correct"); } } // Command line interface fn main() { let args = &env::args().collect::<Vec<_>>(); if args.len() == 4 && args[1] == "--random" { if let (Ok(l), Ok(n)) = (args[2].parse(), args[3].parse()) { return random_test(l, n); } } if args.len() == 4 { if let (Ok(x1), Ok(x2), Ok(l)) = (args[1].parse(), args[2].parse(), args[3].parse()) { match solve(&x1, &x2, l) { None => println!("no solution found"), Some(p_prime) => println!("{}", p_prime), } return; } } println!("Usage:"); println!(" {} --random L N", args[0]); println!(" {} X1 X2 L", args[0]); } ``` ### `Cargo.toml` ``` [package] name = "agcd" version = "0.1.0" authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"] [dependencies] rayon = "0.7.1" rust-gmp = "0.5.0" ``` ### To run ``` cargo build --release target/release/agcd 56007668599 30611458895 3 target/release/agcd --random 13 5 ``` [Answer] # Mathematica, L=5 here is a quick 5 solution ``` (l = #3; a = #1 - Range[2^(l - 1), 2^l]; b = #2 - Range[2^(l - 1), 2^l]; Last@Intersection[ Flatten[Table[Select[Divisors@a[[i]], # < 2^l^2 &], {i, Length@a}], 1], Flatten[Table[Select[Divisors@b[[i]], # < 2^l^2 &], {i, Length@b}], 1]] ) & ``` **Input** [x1,x2,L] in order that anybody can test this, here is the key generator ``` l = 5; a = RandomInteger[{2^(l^2 - 1), 2^(l^2)}] b = RandomInteger[{2^(l^3 - 1), 2^(l^3)}]; c = RandomInteger[{2^(l - 1), 2^l - 1}]; f = RandomInteger[{2^(l^3 - 1), 2^(l^3)}]; g = RandomInteger[{2^(l - 1), 2^l - 1}]; x = a*b + c y = a*f + g ``` choose the L value run, the code and you will get three numbers. place the last two along with L as input, and you should get the first one [Answer] # Python, L=15, average time 39.9s ``` from sys import argv from random import seed, randrange from gmpy2 import gcd, mpz import gmpy2 def mult_buckets(buckets): if len(buckets) == 1: return buckets[0] new_buckets = [] for i in range(0, len(buckets), 2): if i == len(buckets) - 1: new_buckets.append(buckets[i]) else: new_buckets.append(buckets[i] * buckets[i+1]) return mult_buckets(new_buckets) def get_products(xs, l): num_buckets = 1000 lower_r = 1 << l - 1 upper_r = 1 << l products = [] bucket_size = (upper_r - lower_r)//num_buckets + 1 for x in xs: buckets = [] for bucket_num in range(num_buckets): product = mpz(1) for r in range(lower_r + bucket_num * bucket_size, min(upper_r, lower_r + (bucket_num + 1) * bucket_size)): product *= x - mpz(r) buckets.append(product) products.append(mult_buckets(buckets)) return products def solve(xs, l): lower_r = 2**(l - 1) upper_r = 2**l lower_p = 2**(l**2 - 1) upper_p = 2**(l**2) products = get_products(xs, l) overlap = gcd(*products) candidate_lists = [] for x in xs: candidates = [] candidate_lists.append(candidates) for r in range(lower_r, upper_r): common_divisor = gcd(x-r, overlap) if common_divisor >= lower_p: candidates.append(common_divisor) to_reduce = [] for l_candidate in candidate_lists[0]: for r_candidate in candidate_lists[1]: best_divisor = gcd(l_candidate, r_candidate) if lower_p <= best_divisor < upper_p: return best_divisor elif best_divisor > upper_p: to_reduce.append(best_divisor) for divisor in to_reduce: cutoff = divisor // lower_p non_divisors = [] for sub_divisor in range(2, cutoff + 1): if any(sub_divisor % non_divisor == 0 for non_divisor in non_divisors): continue quotient, remainder = gmpy2.c_divmod(divisor, sub_divisor) if remainder == 0 and lower_p <= quotient < upper_p: return quotient if quotient < lower_p: break if remainder != 0: non_divisors.append(sub_divisor) def is_correct(x1, x2, l, p_prime): p_prime_is_good = p_prime >> (l**2 - 1) and not p_prime >> l ** 2 x1_is_good = (x1 % p_prime) >> (l-1) and not (x1 % p_prime) >> l x2_is_good = (x2 % p_prime) >> (l-1) and not (x2 % p_prime) >> l return bool(p_prime_is_good and x1_is_good and x2_is_good) if __name__ == '__main__': seed(0) l = int(argv[1]) reps = int(argv[2]) def randbits(bits): return randrange(2 ** (bits - 1), 2 ** bits) for _ in range(reps): p = randbits(l ** 2) print("p = ", p) xs = [] for i in range(2): q_i = randbits(l ** 3) print("q", i, "=", q_i) r_i = randbits(l) print("r", i, "=", r_i) x_i = q_i * p + r_i print("x", i, "=", x_i) xs.append(x_i) res = solve(xs, l) print("answer = ", res) print("Correct?", is_correct(xs[0], xs[1], l, res)) ``` This code is based on the fact that the product of x1 - r for all possible values of r must be a multiple of p, and the product of x2 - r must be as well. Most of the time is spent taking the gcd of the two products, each of which has about 60,000,000 bits. The gcd, which only has about 250,000 bits, is then compared to each of the x-r values once again, to extract p' candidates. If they're a bit too large, trial division is used to reduce them to the appropriate range. This is based on the gmpy2 library for Python, which is a thin wrapper for the GNU MP library, which in particular has a really good gcd routine. This code is single-threaded. [Answer] # Mathematica, L=12 ``` ClearAll[l, a, b, k, m]; (l = #3; a = #1 - Range[2^(l - 1), 2^l]; b = #2 - Range[2^(l - 1), 2^l]; k = Length@a; m = Length@b; For[i = 1, i <= k, i++, For[j = 1, j <= m, j++, If[2^(l^2 - 1) < GCD[a[[i]], b[[j]]], If[GCD[a[[i]], b[[j]]] > 2^l^2, Print@Max@ Select[Divisors[GCD[a[[i]], b[[j]]]], 2^(l^2 - 1) < # < 2^l^2 &]; Abort[], Print[GCD[a[[i]], b[[j]]]]; Abort[]]]]]) & ``` **input** [x1,x2,L] in order that anybody can test this, here is the key generator ``` l = 12; a = RandomInteger[{2^(l^2 - 1), 2^(l^2)}] b = RandomInteger[{2^(l^3 - 1), 2^(l^3)}]; c = RandomInteger[{2^(l - 1), 2^l - 1}]; f = RandomInteger[{2^(l^3 - 1), 2^(l^3)}]; g = RandomInteger[{2^(l - 1), 2^l - 1}]; x = a*b + c y = a*f + g ``` choose the L value, run the code and you will get three numbers. place the last two along with L as input, and you should get the first one ]
[Question] [ OEIS: [A167171](https://oeis.org/A167171) A *dense number* is a number that has exactly as many prime divisors as non-prime divisors (including 1 and itself as divisors). Equivalently, it is either a prime or a product of two distinct primes. The first 100 dense numbers are: ``` 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 31, 33, 34, 35, 37, 38, 39, 41, 43, 46, 47, 51, 53, 55, 57, 58, 59, 61, 62, 65, 67, 69, 71, 73, 74, 77, 79, 82, 83, 85, 86, 87, 89, 91, 93, 94, 95, 97, 101, 103, 106, 107, 109, 111, 113, 115, 118, 119, 122, 123, 127, 129, 131, 133, 134, 137, 139, 141, 142, 143, 145, 146, 149, 151, 155, 157, 158, 159, 161, 163, 166, 167, 173, 177, 178, 179, 181, 183, 185, 187, 191, 193, 194 ``` Given a nonnegative integer `n`, output `dense(n)`. `n` may be 0-indexed or 1-indexed. ## Reference implementation (Sage) ``` import itertools def dense_numbers(): n = 1 while True: prime_divisors = [x for x in divisors(n) if x.is_prime()] non_prime_divisors = [x for x in divisors(n) if not x.is_prime()] if len(prime_divisors) == len(non_prime_divisors): yield n n += 1 N = 20 print itertools.islice(dense_numbers(), N, N+1).next() ``` [Try it online](http://sagecell.sagemath.org/?z=eJyVkMEKwjAMhu-FvkOOLZPhPAp7hZ28iQy0GQa6dLSdzre3m8qm4sGfHkr-9sufUNs5H4Ei-uicDVJIYbABgxyw5r49og9Kb6WAJIYSisf1eiaLsPM9Pr1RnacWa0MXCs6H9Hg_QOM8DEAMr7JiDdTAkFOopw9KH2YEO67_wbCLv1DJtcjqnaahLKfydyO9mGTUjdAa4EU2yKb5pahSqM16dqRIKF7sMSWydEL1sccVVOlkhc4Zh6j0HWNmcbU=&lang=sage) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆE²Sḍ2µ#Ṫ ``` Reads from STDIN and uses 1-based indexing. [Try it online!](http://jelly.tryitonline.net/#code=w4ZFwrJT4biNMsK1I-G5qg&input=&args=MjE) ### How it works ``` ÆE²Sḍ2µ#Ṫ Main link. No arguments. Implicit argument: 0 µ# Read an integer n from STDIN and execute the chain to the left for k = 0, 1, 2, ... until n of them return a truthy value. Return the array of matches. ÆE Compute the exponents of k's prime factorization. ² Square each exponent. S Compute the sum of all squares. ḍ2 Test if 2 is divisible by the result (true iff the sum is 1 or 2). Ṫ Tail; extract the last (n-th) matching value of k. ``` [Answer] ## 05AB1E, ~~12~~ 11 bytes 1-indexed ``` µ # while counter != input NÑ # get divisors of current number p # check if prime D # duplicate O # sum one copy s_O # invert and sum the other copy Q½ # if equal increase counter ``` [Try it online](http://05ab1e.tryitonline.net/#code=wrVOw5FwRE9zX09Rwr0&input=MTAw) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` :1yt. 1<.=$p#dl<3 ``` [Try it online!](http://brachylog.tryitonline.net/#code=OjF5dC4KMTwuPSRwI2RsPDM&input=MTAw&args=Wg) ### Predicate 0 (main predicate) ``` :1yt. :1y Find the first (input) solutions of predicate 1 t Last element . Unify with output ``` ### Predicate 1 (auxiliary predicate) ``` 1<.=$p#dl<3 1<. 1 < output .= assign a value to output . $p#d output's prime factorization contains no duplicate l and the length <3 is less than three ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 12 bytes **All credits to Dennis for [his algorithm](https://codegolf.stackexchange.com/a/89990/48934).** ``` `w♂N;*2%Y`╓N ``` [Try it online!](http://actually.tryitonline.net/#code=YHfimYJOOyoyJVlg4pWTTg&input=MTAw) ``` `w♂N;*2%Y`╓N ` ` define a function w prime factorization in exponent form: 18 = (2^1)*(3^2) becomes [[2,1],[3,2]] ♂N get the last element (exponent) of each sublist ;* dot-product with self; equivalent to squaring each item and then taking the sum 2%Y test divisibility by 2 ╓ first (input) solutions to the above function N get the last element. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` !fö`¦2ṁo□LgpN ``` [Try it online!](https://tio.run/##yygtzv7/XzHt8LaEQ8uMHu5szH80baFPeoHf////DQ0MAA "Husk – Try It Online") ## Explanation ``` !fö`¦2ṁo□LgpN N List of natural numbers fö filtered by the following 4 functions: gp prime factorization, grouped into equal runs ṁo□L get length of each run, square and sum `¦2 is 2 divisible by the sum? ! nth element in filtered list ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `rG`, 56 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7 bytes ``` λ∆ǐ²∑2Ḋ;ȯ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJyRz0iLCIiLCLOu+KIhseQwrLiiJEy4biKO8ivIiwiIiwiMTUiXQ==) port of jelly [Answer] # R, 93 Bytes ``` dense=function(n){a=b=0;for(i in which(!n%%1:n))if(which(!i%%2:i)+1==i)a=a+1 else b=b+1;a==b} ``` It has a tendency to throw a warning. Its not really a problem. Allowing the warning saves me 5 bytes. Ungolfed ``` dense=function(n){ a=b=0 #Initializing factors = which(!n%%1:n) #Finds all factors for(i in factors) #Loops through factors prime = which(!i%%2:i)+1==i #Tests if current factor is prime. If it is -- the first term in this vector will be TRUE. Otherwise, it will be false. if (prime) a=a+1 else b=b+1 #If first term is true, add 1 to a. Else add one to b. return(a==b) #Test equality of a and b. } ``` [Answer] # Python, 79 bytes ``` f=lambda n,k=2:n<1or-~f(n-(sum((k%i<1)+2*(k%i**2<1)for i in range(2,k))<3),k+1) ``` Uses 1-based indexing. Test it on [Ideone](http://ideone.com/ZWtXW6). [Answer] # PHP, 118 Bytes ``` for($i=1;!$o=$s[$argn];$r[2]?:$t+=2*$$i=1,$t?:$s[]=$i)for($t=0,$r=[],$n=++$i;$n;$n--)$i%$n?:$t+=${$r[]=$n}?:-1;echo$o; ``` [Try it online!](https://tio.run/nexus/php#JYwxC8IwFIT3/gvhhNY2YOvW56ODdHDRxS2EIlLbLEl5zSb612uscMtx33fHZhqnpBfx0kk/eQnWDemn7S7X2/nUZpTgLoPj8kDL00sKyyVt4BmzXhdDEF2ZpkbIudrhBxQIsc/aMGy2WoH3BYS1KeA4z2EJLkapDHYL97fxilfRce@mViX1j9HD07J8AQ "PHP – TIO Nexus") [Answer] # Axiom, 102 bytes ``` f(n:PI):PI==(i:=1;repeat(i:=i+1;a:=divisors(i);2*#[x for x in a|prime?(x)]=#a=>(n=1=>break;n:=n-1));i) ``` ungolf and result ``` -- 1 base Indexed: return the n_th number i that has 2*#divisorsPrimeOf(i)=#divisors(i) ff(n:PI):PI== i:=1 repeat i:=i+1 a:=divisors(i) 2*#[x for x in a|prime?(x)]=#a=>(n=1=>break;n:=n-1) i (3) -> [f(i) for i in 1..23] (3) [2,3,5,6,7,10,11,13,14,15,17,19,21,22,23,26,29,31,33,34,35,37,38] Type: List PositiveInteger ``` ]
[Question] [ # Across the alphabet In this challenge, you have trouble remembering the letters of the alphabet. To circumvent this, you go up and down the alphabet, till you get to the letter. Because you want your code to be portable, you'll be writing it with letter blocks. You have a limited amount of letter blocks because most of them got stolen so you need to make sure your code is as short as possible. ## Examples Input / Output pairs are separated by a blank line: ``` Ac ABc Ad ABcd fA fedCBA adB abcdcB Hello, World! HGfefghijkllmno, WVUTSrqpopqrqponmlkjihgfed! ``` ## Challenge Your goal is to chain adjacent letters with all the intermediate letters of the alphabet (`A-Za-z`) between them. If capitalization differs, the capitalization should be transformed in the middle. If capitalization cannot be evenly transformed in the middle, it broken up *after* the middle. If a character isn't an alphabetical character, no transformation should be done. ## Winning This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins! **-10% Bonus:** if your code chains digits [Answer] # Pyth, 40 bytes ``` +sm?-rdZGhd+hdsrVc2jktr.*rdZm!}kGd.:z2ez ``` [Try it online.](https://pyth.herokuapp.com/?code=%2Bsm%3F-rdZGhd%2BhdsrVc2jktr.%2ardZm%21%7DkGd.%3Az2ez&input=Ac%0AAd%0AfA%0AadB%0AHello%2C+World%21&test_suite=1&test_suite_input=Ac%0AAd%0AfA%0AadB%0AHello%2C+World%21&debug=0) [Answer] # Python 2, ~~303~~ ~~291~~ ~~288~~ ~~282~~ ~~276~~ ~~261~~ 253 bytes This is a completely different algorithm than Hannes Karppila's, and after lots of golfing, I've managed a substantial improvement in length. I think this algorithm might allow for one of the shortest codes in other languages too, especially languages with do-while loops and built-in signum functions. Suggestions for further improvement welcome. (Something tells me that whole inner loop should be rewritten as a list comprehension.) ``` l=map(ord,list(raw_input()));f=q=1 while q: q=0;m=~-f/2;c=m while abs(c)<len(l)-1: u=c+f;d=(l[u]-96)%32-(l[c]-96)%32 if chr(l[c]).isalpha()*chr(l[u]).isalpha()*(d*d>1):l[:u-m]+=[l[c]+d/abs(d)];u+=f;q=1 c=u f=-f print "".join(map(chr,l)) ``` [Answer] # JavaScript (ES6), ~~198~~ ~~197~~ 194 bytes ``` f=s=>(o="",a=u=0,[...s].map(c=>{j=c.toUpperCase();p=j==c;b=j<"A"|j>"Z"?0:j.charCodeAt();for(i=0,m=a<b?b-a:a-b;a&&b&&++i<m;)o+=String.fromCharCode(i*(a<b||-1)+a+32*!(i>m/2?p:u));a=b;u=p;o+=c}),o) ``` ## Usage ``` f("Hello, World!") => "HGfefghijkllmno, WVUTSrqpopqrqponmlkjihgfed!" ``` ## Explanation ``` f=s=>( o="", // o = output string a= // a = previous character code (or 0 if symbol) u=0, // u = 1 if previous character was upper-case [...s].map(c=>{ // iterate through each letter of input // Get information about the current character j=c.toUpperCase(); // j = current character in upper-case p=j==c; // p = current character is upper-case b=j<"A"|j>"Z"?0:j.charCodeAt(); // b = current character code (or 0 if symbol) // Interpolate characters (unless A or B is a symbol) for(i=0,m=a<b?b-a:a-b;a&&b&&++i<m;) // loop for each character between A and B o+=String.fromCharCode( // add interpolated character to output i*(a<b||-1)+a+ // interpolate character code 32*!(i>m/2?p:u) // apply case of the nearest character ); // Set character A values to B for the next character a=b; u=p; o+=c // add B itself to the output }), o // return the output ) ``` [Answer] # JavaScript ES6, 168 (186-10%) ~~176 193~~ **Edit** Modified to get the 10% bonus Test running the snippet below using an EcmaScript 6 compliant browser (I use FireFox) ``` f=s=>[...s].map(c=>{a=parseInt(c,36),m=(a-q)/(d=a>q?1:-1);for(n=1;m&&(a>9)==(q>9)&&(q+=d)!=a;n+=2)r=q.toString(36),o+=n<m&p<'a'|n>=m&c<'a'?r.toUpperCase():r;p=c,q=a,o+=c},o='',p=q=-f)&&o // Explained U=s=>( o = '', // initialize output p = '', // provious char, initialize to none q = NaN, // previous char code, initialize to none [...s].map( c => { // for each char a = parseInt(c,36), // convert digit/letter to numeric code, case invariant, NaN if invalid d = a > q ? 1 : -1, // sign of difference (if not equal) m = (a - q) / d; // absolute value of difference or NaN if (m && (a>9)==(q>9)) // if current and prev are different and both alpha or both digits for( n = 1; (q += d) != a; // loop from prev char (not included) to current (not included) n += 2) r=q.toString(36), // add intermediate char to output // upcase if: left side & prev is upcase or right side and current is upcase o+= n<m&p<'a'|n>=m&c<'a'?r.toUpperCase():r; p = c, // copy current to previous q = a, // copy current to previous o += c // add current char to ouput }), o ) // test console.log=(...x)=>O.innerHTML+=x+'\n' ;['Ac','Ad','fA','adB','04aQ27','Hello World!']. forEach(x=>console.log(x + ' -> ' + f(x))) ``` ``` <pre id=O></pre> ``` [Answer] # Python 2, 349 bytes It's way too long, but at least it's first. ``` f=lambda p:ord(p.lower()) u=lambda p:"".join(p).upper() s=raw_input() w=s[0] r=w for q in s[1:]: o=q+w if q==w:o="" if o.isalpha(): m=(f(w)<f(q))*2-1 e=map(chr,range(f(w)+m,f(q)+m,m)) if o==u(o):e=u(e) elif q==u(q):e[len(e)/2:]=u(e[len(e)/2:]) elif -o.islower()+1:e[:len(e)/2]=u(e[:len(e)/2]) r+="".join(e) else: r+=q w=q print r ``` ]
[Question] [ ## Task Write a program or function that takes an image of width `w` and height `h`, and two integers `a <= w/2` and `b <= h/2`, and outputs an ascii art representation of the image, with the dimensions `a` x `b`. The ascii art should be generated through the following steps (or another process with the same output): 1. Resize the `w` x `h` image to `2a` x `2b`. The color of the pixel `(x, y)` in the resized image should be equal to the average of the colors of all the pixels from the original image inside the rectangle with the following corners: ``` (floor[x * w/2a], floor[y * h/2b]) (ceil[(x+1) * w/2a], ceil[(y+1) * h/2b]) ``` 2. The resized image should be desaturated by taking the average of the red, green, and blue components of the color, and setting each component to this average. 3. A character should be outputted for each 2x2 block of pixels, following the rules below: * Let `e = 3 - floor[color/64]`, where color refers to the red component of the color of the top-left pixel (in the range 0..255). Let `f`, `g`, and `h` refer to this value, but for the top-right, bottom-left, and bottom-right pixels respectively. * Let `z` be the average of `e`, `f`, `g`, `h`. * Output the character corresponding to the following (white represents a pixel where `3 - floor[color/64]` is zero, and grey represents nonzero). * ![All pixels are zero](https://i.stack.imgur.com/kpr9p.png) = Output a space () * ![Top left pixel is nonzero](https://i.stack.imgur.com/gbmFW.png) or ![Top right pixel is nonzero](https://i.stack.imgur.com/jFIgC.png) = Output `"` if `e (or f) >= 2` and `'` otherwise. * ![Bottom left pixel is nonzero](https://i.stack.imgur.com/qIqAd.png) or ![Bottom right pixel is nonzero](https://i.stack.imgur.com/KQO8n.png) = Output `,` if `g (or h) >= 2` and `.` otherwise. * ![Top pixels nonzero](https://i.stack.imgur.com/bmwek.png) or ![Bottom pixels nonzero](https://i.stack.imgur.com/n3Qzw.png) = Output `-` * ![Left pixels nonzero](https://i.stack.imgur.com/fbJ4o.png) or ![Right pixels nonzero](https://i.stack.imgur.com/xRTGE.png) = Output `;` * ![Top left, bottom right pixels nonzero](https://i.stack.imgur.com/0jyda.png) = Output `\` * ![Top right, bottom left pixels nonzero](https://i.stack.imgur.com/oyvh6.png) = Output `/` * ![Top left pixel zero](https://i.stack.imgur.com/hCXIE.png) = Output `J` * ![Top right pixel zero](https://i.stack.imgur.com/ZHYtJ.png) = Output `L` * ![Bottom left pixel zero](https://i.stack.imgur.com/ioU44.png) = Output `7` * ![Bottom right pixel zero](https://i.stack.imgur.com/z7bh8.png) = Output `P` * ![All nonzero](https://i.stack.imgur.com/5juEC.png) + `z = 1`: output `*`. + `z = 2`: output `C`. + `z = 3`: output `#`. Other notes: All averages taken in the above steps should use integer division (i.e. rounding towards 0). You may use a library to read images, but libraries may not be used for the resizing and desaturation steps. ## Input Your program will take in three pieces of data: * An image. This image may be in any format of your choice (e.g. PNG, PPM) * The width of the ascii art (in number of characters) * The height of the ascii art (in number of characters) Input may be read through STDIN, passed as an command-line argument, stored as a variable, etc. ## Output Your program will output the ascii art generated from the image and through the process described above. Each line must be the same width (the width passed as input), and no extra spaces may be added or removed. The last line may have a trailing newline, but this is not mandatory. Blank lines (lines with only spaces) must not be omitted. ## Examples All images were taken from Wikipedia and released into public domain. Your program is expected to work for all images and valid inputs. ![Picture of lemons](https://i.stack.imgur.com/DD7NJ.png) **Width = 52, Height = 25:** ``` .--***-- ----. -**********L.-- .--7----P- .J****************. .*********\. ,******************L \J**********'. -********************. J***********L/ J*********************; ./*************.L ;*********************P J**************;7; .**********************' .***************;;* ;********************** ;***************;J*. *********************** *******P********'**; C*********************C *******P;*******.**; C********************** J***************;**; C*********************; ****************.**; **********************' ***************P;** J*********************P ***************/*** .********************** 7*************'J**; ;********************C" 'P***********PJ***' "7******************C" '**********P.**C; '*C*************' ;*********-J**CP '*C**********P 7**7**P/-****P -*CCCCC*P- '7********P' '--- '---' ``` **Width: 70, Height: 3:** ``` ---------------------------. .---------------- J*****************************P -J********************/J**; ----------*********P---------' ----------------------' ``` ![Potatoes](https://i.stack.imgur.com/z7sjj.png) **Width: 50, Height: 25:** ``` .J--- .J*P ---J*L--. J***' L -J***********- J**** ;****************L ;*****' .J******************** J****7 ************************P **CC* ; .*********LJ***********P- **C*P ' J**********************- 7*C*L **********************; J*C**; **********************; JC**C**. ; ;********CCC*C**CCCC** "7*****L . 7*****CCCCCC****CC**' -*****. -J -**C*C*CC******CC*' ;**CC***; '**CCC*****CCCC*; '-****- --***CCCCC***- '------' ``` ![Clipart sample](https://i.stack.imgur.com/ZHlMs.png) **Width: 26, Height: 17:** ``` - ,L J-**L .C# J';*P-L ,C#" .P P 7. JC7P ;; * J ;; ,C'C; J; C C ;L C" # *L 7-P ;* ;P C 7CL***J*P C' # '7#C*C#P' ;P JC#C- J#CCC#L .JC#CJCC##C; ;#- -#, CCC#CCCCCCCC ;*.- -.C; ;CCCCCCCCCCCC ;****J**L ;CCCCCCCCCCCC ;*******; 'CCCCCCCCCCCP '*******' CCCCCCCCCCC' '*P-7*' "CCCCP '-- '--- ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins. [Answer] # JavaScript ~~752~~,701 ``` function Z(I,a,b){ var C=document.createElement('canvas') var W=C.width=I.width,H=C.height=I.height,X=C.getContext('2d') X.drawImage(I,0,0) a*=2,b*=2,W/=a,H/=b for(var o=a*b,x=0,y=0,T="",S=[],V;--o;){ var A=~~(x*W),B=~~(y*H) var d=X.getImageData(A,B,(((x+1)*W)<<0)-A,(((y+1)*H)<<0)-B).data for(var i=0,p=0,L=d.length;i<L;i+=4)p+=(d[i]+d[i+1]+d[i+2])/3 p/=L/4 S[x]=3-(p>>6) if(x%2&&y%2){ var e=V[x-1],f=V[x],g=S[x-1],h=S[x],z=(e+f+g+h)>>2,B=0,c B|=e>0?8:0,B|=f>0?4:0,B|=g>0?2:0,B|=h>0?1:0 c=" ..-';\\J'/;L-7P*".charAt(B) c=c=="'"&&(e>1||f>1)?'"':c c=c=="."&&(g>1||h>1)?",":c T+=c=="*"?z>2?"#":z>1?"C":c:c } if(++x==a)x=0,y++,V=S,T+=y%2?"\n":"",S=[] } return T } ``` Examples: ``` var items = { lemons: {w:52, h:25}, spuds: {w:50, h:25}, tux: {w:26, h:17} }; for(var k in items) { var val = items[k]; var img = new Image(); img.onload = function() { console.log(Z(this,this.w,this.h)); } img.src=k+'.png'; img.w = val.w; img.h = val.h; } ``` Lemons: ``` .--JJL-- .---. -**********-.-- .--7----P- .J***************L. .*********\. .******************L \J**********'. .********************. ;***********L/ J*********************; ./*************.L ,*********************P -**************;7; **********************' .***************;;* ;********************** ;***************;;*. *********************** *******PP*******'J*; *********************** *******P;*******.**; ***************7******* J******;J*******;**; **********************; ****************.**; **********************' ***************P;**' J*********************P ***************/*** .********************** 7*************'J**P ;*********************" '\***********PJ***' "7*******************" '**********P.***; '***************' ;*********-J***P '************P' 7*-7**P/-****P -*******P- '7********P' '--- ----- ``` Spuds: ``` J--- .J*P .---*L--. J***' L -J***********- J**** ;****************L ;*****' .J******************L* J***L7 ************************P **CC* . .*********L'***********P- **C*P ' J**********************- 7*C*L **********************; J*C**. **********************; JC**C** . 7********CCC****CCCC** "7*****L . 7*****CCCCCC****CC**' -****L. .J -**C*C**C*******C*' ;**CC***; '**CCC*****CCCC*; '-****- --**CCCCCC***- '------' ``` Tux: ``` ,L --**L C#' J';*P-L ,C#" P 7 7. ,C7P ;; J J ;; ,C"C; ;; C C L C" C *L 7-P ;* ;P # ;CL***J** C' # '7#C*C#C' ,P JC#C- J#CCC#L .JCCLJCC##C, .#- -#, JCC#CCCCCCCC ;C.- -.*; .CCCCCCCCCCCC ;L***J**C ;CCCCCCCCCCCC ;*******P 'CCCCCCCCCCCP '*******" CCCCCCCCCCC' '*P-7*' "CCCCP "-- '--- ``` [Answer] # IDL 8.3, ~~588~~ ~~597~~ 588 bytes ~~I'm getting slightly different values than you are, I'm not sure why... I did integer division for everything. But it otherwise works splendidly... are these results acceptable?~~ Much better now, though still not identical for some reason. ``` pro c,m,a,b e=2*a f=2*b s=size(m,/d)/[1.,e,f] g=intarr(3,e,f) u=floor([0:e-1]*s[1]) x=ceil([1:e]*s[1])-1 v=floor([0:f-1]*s[2]) y=ceil([1:f]*s[2])-1 n=(x-u)#(y-v) for k=0,2 do for i=0,e-1 do for j=0,f-1 do g[k,i,f-j-1]=total(m[k,u[i]:x[i],v[j]:y[j]],/i)/n[i,j] g=3-total(g/192,1,/i) t=intarr(4,a,b) for i=0,3 do t[i,*,*]=g[rebin([0:a-1]*2+i mod 2,a,b),rebin(2#[0:b-1]+i/2,a,b)] w=total((t ne 0)*rebin(2^[0:3],4,a,b),1,/i) for i=0,3 do w+=(w eq 2^i)*(t ge 2)[i,*,*]*(18-2^i+i/2) w+=(w eq 15)*(total(t,1,/i)/4-1) print,strmid(' '+"''"+'-.;/P.\;7-LJ*C#",',w[*],1),f='('+strtrim(a,2)+'A1)' end ``` Test cases: ``` IDL> c,read_png('lemons.png'),52,25 .-J***L-. .----. -**********L.-- .J-*LJJ**- .J****************. J*********J. ,******************* /J**********7. J********************. ;J***********L* J*********************; .\*************/L ;*********************P ***************;*; .C*********************' ;***************;** J********************** J***************;**. *********************** ****************'**; C*********************C ********J*******;**; C********************** *******************; C*********************P ;****************7**; .**********************' ***************PJ**' J*********************P ***************\*** .********************** 7*************'***P ;********************C" ;************PJ**C' "7******************C" ***********PJ***; '*C*************" ;*********7J**CP '*C*********CP' 7*****P\-***CP -*CCCCC*P- '7********P" '--- ----- IDL> c,read_png('lemons.png'),70,3 --------J**********L--------. .----------------- .J*****************************P' -*************************; ---------*************P------- '------7**********P----- IDL> c,read_png('potatoes.png'),50,25 J-"- .J*' ----JL-- -*C* * -J***********- J*C*L ;****************L .*C*-* .J******************** J*CC;- ********************C**CP *CC#* 7 .**********************P- *CCC; ' J**********************- 7CCCL **********************; JCCC*. ****C*C*****CCCC*CC***; ;C*CCCL . ;***CC*CCCCCCCCCCCCC** "--*CCC; 7***CCCCCCCCCCCCCCC*' '7CC*L. . -*CCCCCCCCCCCCCCCP' 7CCCCC*' 7CC#CCCCCCC###P '-7P-' '-7CC######C- '-' IDL> c,read_png('penguin.png'),26,17 ,L , C# " #- ; ,##" ; - ; ,#7; ;" - - "; ,#"J" ; # # ; #" # ;; .-. ,; ;; # ;#-***-#; # # 7#C*C#P ,P -C#C, J##-##L JCCL-CC#CC, ,#" "#, JCC#CCCCCCCL ;L.- -.C; ,CCCCCCCCCCCC ;***L***; ;CCCCCCCCCCCC ;*******; CCCCCCCCCCC; *** ***" CCCCCC7CCCP '*P--*' "CCCCP "-" --" ``` ]
[Question] [ The diamond square algorithm is a fractal terrain (heightmap) generating algorithm. You can find a nice description how it works here: <http://www.gameprogrammer.com/fractal.html> (Used as a reference.) <http://www.playfuljs.com/realistic-terrain-in-130-lines/> (Great JS implementation, perhaps you might want to steal his renderer. Take a look here what this algorithm is capable of <http://demos.playfuljs.com/terrain/>.) The general idea is that you have 4 corners as seeds (a), and calculate the height of the center point by averaging those four corners and adding a random value e.g. between -0.5 and 0.5 (b). If you apply this to the grid you get again a grid of diamonds (squares turend 45°) and you repeat the same (c,d), but the random range gets smaller, e.g. -0.125 to 0.125 etc. ![enter image description here](https://i.stack.imgur.com/xgReR.gif) Your program must accept a number of inputs: * An integer `l=1,2,3,...` that determines the size of the square grid with side length `2^l+1`. At `l=10` you will have to store about one million numbers. * Four seeds (floating point) for each corner * A parameter `0<h<1` that determines the roughness (`H` in the link) that means how big the random range is initially * Parameters `a,b` that represent initial lower and upper bounds for the random range and get multiplied by `h` in each refinement step. (The random number is uniformly chosen between `a` and `b`. The output must consist of the finished 2d grid. So the rough algorithm would look like this: ``` Create a square grid with sidelength 2^l+1 Place seed values in the corners Repeat: | Perform square steps | Refine Range: a = a*h; b=b*h; | Perform diamond steps | Refine Range ``` There is one detail you should be aware of: At the boundary of the grid, you will only have three vertices of the *diamond*, so you should also only calculate the average of those three points. A visualization of some examples (please tell us what parameters you used) is optional but appreciated, and does of course not add to the byte count. A slight variated implementation of this algorithm can be found here: [Parallel projected voxel terrain generator](https://codegolf.stackexchange.com/questions/22439/paralell-projected-voxel-terrain-generator/22440#22440) I created a small drawing function in javascript for displaing heightmaps in 2d as grayscale image. <http://jsfiddle.net/flawr/oy9kxpsx/> If anyone of you is into fancy 3d and can make a script to view maps in 3d let me know!=) [Answer] # Java, 1017 bytes Input is a space separated list like so: `l s1 s2 s3 s4 h a b`. Output is an 2d-array containing the numbers. Program: ``` import java.util.*;import static java.lang.Math.*;class C{public static void main(String[]a){int b=a.length,d=0;float[]c=new float[b];for(;d<b;){c[d]=Float.parseFloat(a[d++]);}e=(int)(pow(2,c[0])+1);f=new float[e][e];f[0][0]=c[1];f[0][e-1]=c[2];f[e-1][0]=c[3];f[e-1][e-1]=c[4];g=c[5];float h=c[6],i=c[7];s(0,0,e-1,e-1,h,i);System.out.print(Arrays.deepToString(f));}static int e;static float[][]f;static float g;static void s(int q,int r,int s,int t,float h,float i){if(s-q<2|t-r<2|q<0|r<0|s>=e|t>=e)return;float o,p;int m=(q+s)/2,n=(r+t)/2;f[m][n]=(float)(a(q,r,s,r,q,t,s,t)+random()*(i-h)-h);d(m,r,m-q,o=h*g,p=i*g);d(q,n,m-q,o,p);d(m,t,m-q,o,p);d(s,n,m-q,o,p);}static void d(int x,int y,int e,float h,float i){float o,p;f[x][y]=(float)(a(x,y-e,x+e,y,x,y+e,x-e,y)+random()*(i-h)-h);s(x-e,y-e,x,y,o=h*g,p=i*g);s(x,y-e,x+e,y,o,p);s(x-e,y,x,y+e,o,p);s(x,y,x+e,y+e,o,p);}static float a(int...j){float k=0,l=0;for(int d=0;d<j.length;d+=2){if(j[d]<0|j[d+1]<0|j[d]>=e|j[d+1]>=e)continue;l++;k+=f[j[d]][j[d+1]];}return k/l;}} ``` Program that is indented and displays the map: ``` import java.util.*; import java.awt.image.*; import java.awt.*; import javax.swing.*; import static java.lang.Math.*; class D{ public static void main(String[]a){ int b=a.length,d=0; float[]c=new float[b]; for(;d<b;){ c[d]=Float.parseFloat(a[d++]); } e=(int)(pow(2,c[0])+1); f=new float[e][e]; f[0][0]=c[1]; f[0][e-1]=c[2]; f[e-1][0]=c[3]; f[e-1][e-1]=c[4]; g=c[5]; float h=c[6],i=c[7]; s(0,0,e-1,e-1,h,i); showImage(f); } static int e; static float[][]f; static float g; static void s(int q,int r,int s,int t,float h,float i){ if(s-q<2|t-r<2|q<0|r<0|s>=e|t>=e) return; float o,p; int m=(q+s)/2,n=(r+t)/2; f[m][n]=(float)(a(q,r,s,r,q,t,s,t)+random()*(i+h)-h); d(m,r,m-q,o=h*g,p=i*g); d(q,n,m-q,o,p); d(m,t,m-q,o,p); d(s,n,m-q,o,p); } static void d(int x,int y,int e,float h,float i){ float o,p; f[x][y]=(float)(a(x,y-e,x+e,y,x,y+e,x-e,y)+random()*(i-h)+h); s(x-e,y-e,x,y,o=h*g,p=i*g); s(x,y-e,x+e,y,o,p); s(x-e,y,x,y+e,o,p); s(x,y,x+e,y+e,o,p); } static float a(int...j){ float k=0,l=0; for(int d=0;d<j.length;d+=2){ if(j[d]<0|j[d+1]<0|j[d]>=e|j[d+1]>=e) continue; l++; k+=f[j[d]][j[d+1]]; } return k/l; } public static void showImage(float[][] f){ float maxHeight = Float.MIN_VALUE; float minHeight = Float.MAX_VALUE; for (float[] row : f){ for (float height : row){ if (height > maxHeight){ maxHeight = height; } if (height < minHeight){ minHeight = height; } } } int e = f.length; BufferedImage image = new BufferedImage(e, e, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < e; x++){ for (int y = 0; y < e; y++){ Color color = Color.getHSBColor((float)((f[x][y] - minHeight)/(maxHeight - minHeight)), 1, 1); image.setRGB(x,y,color.getRGB()); } } JFrame frame = new JFrame("Picture"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new JComponent(){ @Override public void paint(Graphics g){ g.drawImage(image, 0, 0, getWidth(), getHeight(), null); } }); frame.setVisible(true); frame.setBounds(0,0,e,e); } } ``` Here is a function in Java to show a map: ``` public static void showImage(float[][] map){ float maxHeight = Float.MIN_VALUE; float minHeight = Float.MAX_VALUE; for (float[] row : map){ for (float height : row){ if (height > maxHeight){ maxHeight = height; } if (height < minHeight){ minHeight = height; } } } int size = map.length; BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < size; x++){ for (int y = 0; y < size; y++){ Color color = Color.getHSBColor((float)((map[x][y] - minHeight)/(maxHeight - minHeight)), 1, 1); image.setRGB(x,y,color.getRGB()); } } JFrame frame = new JFrame("Picture"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new JComponent(){ @Override public void paint(Graphics g){ g.drawImage(image, 0, 0, getWidth(), getHeight(), null); } }); frame.setVisible(true); frame.setBounds(0,0,size,size); } ``` All of these images have a size of `7`. The 4 seeds are `5`, `10`, `15`, and `20`. `a` and `b` are `-10` and `10` respectively. Roughness starts at `.1` and increments by `.1` up to `1`. ![One](https://i.stack.imgur.com/Vz76p.png)![Two](https://i.stack.imgur.com/8zyyu.png)![Three](https://i.stack.imgur.com/JjhJa.png)![Four](https://i.stack.imgur.com/ZgfSU.png)![Five](https://i.stack.imgur.com/S762c.png) ~~Terrain generating code coming soon!!!~~ ~~Images coming soon!!!~~ ]
[Question] [ The [Four color theorem](http://en.wikipedia.org/wiki/Four_color_theorem) States that no more than four colors are required to color the regions of a map. ## The challenge Given a list of State borders assign each state ID a color so that no two adjacent states have the same color. The output Should be a CSS stylesheet assigning the color to the state's 2 letter ID code. Here is a SVG map which the stylesheet could be applied to. <http://upload.wikimedia.org/wikipedia/commons/3/32/Blank_US_Map.svg> The rules * Shortest code wins * any state border list can be used * only 4 colors can be used. * the state list can be hardcoded Advice: Use the CSS `fill:` property to change the color, For example `#AL{fill:green}` Here is a list of state borders ``` AL-FL AL-GA AL-MS AL-TN AR-LA AR-MO AR-MS AR-OK AR-TN AR-TX AZ-CA AZ-CO AZ-NM AZ-NV AZ-UT CA-NV CA-OR CO-KS CO-NE CO-NM CO-OK CO-UT CO-WY CT-MA CT-NY CT-RI DC-MD DC-VA DE-MD DE-NJ DE-PA FL-GA GA-NC GA-SC GA-TN IA-MN IA-MO IA-NE IA-SD IA-WI ID-MT ID-NV ID-OR ID-UT ID-WA ID-WY IL-IA IL-IN IL-KY IL-MO IL-WI IN-KY IN-MI IN-OH KS-MO KS-NE KS-OK KY-MO KY-OH KY-TN KY-VA KY-WV LA-MS LA-TX MA-NH MA-NY MA-RI MA-VT MD-PA MD-VA MD-WV ME-NH MI-OH MI-WI MN-ND MN-SD MN-WI MO-NE MO-OK MO-TN MS-TN MT-ND MT-SD MT-WY NC-SC NC-TN NC-VA ND-SD NE-SD NE-WY NH-VT NJ-NY NJ-PA NM-OK NM-TX NM-UT NV-OR NV-UT NY-PA NY-VT OH-PA OH-WV OK-TX OR-WA PA-WV SD-WY TN-VA UT-WY VA-WV ``` [Answer] ## Python, 320 chars ``` import sys,random S=[] E={} for x in sys.stdin:a=x[:2];b=x[3:5];S+=[a,b];E[a,b]=E[b,a]=1 C={0:0} while any(1>C[s]for s in C): C={s:0for s in S};random.shuffle(S) for s in S: A=set([1,2,3,4])-set(C[y]for x,y in E if x==s) if A:C[s]=random.choice(list(A)) for s in C:print'#%s{fill:%s}'%(s,' bglrloieulmdede'[C[s]::4]) ``` Uses a randomized algorithm. Assign colors to states in random order by selecting a color that doesn't conflict with adjacent states that have already been colored. Seems to work in a tenth of a second or so on the given input. Example output: ``` $ 4color.py < stategraph #WA{fill:red} #DE{fill:gold} #DC{fill:blue} #WI{fill:blue} #WV{fill:red} #FL{fill:lime} #WY{fill:gold} #NH{fill:red} #NJ{fill:lime} #NM{fill:gold} #TX{fill:red} #LA{fill:blue} #NC{fill:blue} #ND{fill:gold} #NE{fill:blue} #TN{fill:red} #NY{fill:gold} #PA{fill:blue} #RI{fill:gold} #NV{fill:red} #VA{fill:gold} #CO{fill:red} #CA{fill:gold} #AL{fill:blue} #AR{fill:gold} #VT{fill:lime} #IL{fill:red} #GA{fill:gold} #IN{fill:lime} #IA{fill:gold} #OK{fill:blue} #AZ{fill:lime} #ID{fill:lime} #CT{fill:red} #ME{fill:blue} #MD{fill:lime} #MA{fill:blue} #OH{fill:gold} #UT{fill:blue} #MO{fill:lime} #MN{fill:red} #MI{fill:red} #KS{fill:gold} #MT{fill:blue} #MS{fill:lime} #SC{fill:red} #KY{fill:blue} #OR{fill:blue} #SD{fill:lime} ``` [Example pasted into svg](http://keithandkatie.com/misc/Colored_US_Map.svg). [Answer] # Prolog, ~~309~~ ~~307~~ 283 chars ``` :-initialization m. a-X:-assert(X);retract(X),1=0. r:-maplist(get_char,[A,B,E,C,D,F]),(E=F;X=[A,B],Y=[C,D],a-X/Y,a-Y/X,(s/X;a-s/X),(s/Y;a-s/Y),r). s+[]:- \+ (X*C,writef('#%s{fill:#%w}',[X,C]),1=0). s+[X|T]:-member(C,[911,191,119,991]),a-X*C,\+ (X/Y,Y*C),s+T. m:-r,bagof(X,s/X,L),s+L. ``` The algorithm uses backtracking / depth-first search to fill out the map. A bit more readable: ``` :- initialization(main). % Found on http://awarth.blogspot.de/2008/08/asserts-and-retracts-with-automatic.html assert2(X) :- assert(X). assert2(X) :- retract(X), fail. % Reads all states into clauses "state-State", % and all connections into "State-Neighbor" and "Neighbor-State". read_states :- % Read a line "AB-CD\n" maplist(get_char, [A,B,E,C,D,F]), ( A = F; State = [A, B], Neighbor = [C, D], % Memorize the connection between State and Neighbor in both directions. assert(State/Neighbor), assert(Neighbor/State), % Memorize State and Neighbor for the list of states. (state/State; assert(state/State)), (state/Neighbor; assert(state/Neighbor)), % Continue for all lines. read_states ). % Print out all colors. solve([]) :- once(( State*Color, writef('#%s{fill:%w}', [State, Color]), fail )); !. % Use depth-first search to color the map. solve([State|FurtherStates]) :- member(Color, ['#911', '#191', '#119', '#991']), assert2(State*Color), \+ (State/Neighbor, Neighbor*Color), solve(FurtherStates). main :- read_states, bagof(State, state/State, States), solve(States). ``` Invocation: ``` cat borders.txt | swipl -q ./fourcolors.pl ``` Result (newlines are not needed): ``` #AL{fill:#911}#FL{fill:#191}#GA{fill:#119}#MS{fill:#191}#TN{fill:#991}#AR{fill:#911}#LA{fill:#119}#MO{fill:#191}#OK{fill:#119}#TX{fill:#191}#AZ{fill:#911}#CA{fill:#191}#CO{fill:#191}#NM{fill:#991}#NV{fill:#991}#UT{fill:#119}#OR{fill:#911}#KS{fill:#911}#NE{fill:#119}#WY{fill:#911}#CT{fill:#911}#MA{fill:#191}#NY{fill:#119}#RI{fill:#119}#DC{fill:#911}#MD{fill:#191}#VA{fill:#119}#DE{fill:#119}#NJ{fill:#191}#PA{fill:#911}#NC{fill:#911}#SC{fill:#191}#IA{fill:#911}#MN{fill:#191}#SD{fill:#991}#WI{fill:#119}#ID{fill:#191}#MT{fill:#119}#WA{fill:#119}#IL{fill:#991}#IN{fill:#191}#KY{fill:#911}#MI{fill:#911}#OH{fill:#119}#WV{fill:#991}#NH{fill:#911}#VT{fill:#991}#ME{fill:#191}#ND{fill:#911} ``` Pasted into an SVG: <http://jsbin.com/toniseqaqi/> [Answer] # JavaScript (ES6) 269 ~~279~~ Recursive search with backtracking. ~80 bytes spent for state list parsing. ``` F=l=>{ S=(a,b)=>S[a]=(S[a]||[]).concat(b), l.replace(/(..)-(..)/g,(_,a,b)=>S(a,b)+S(b,a)), k=Object.keys(S), R=(p,c=k[p])=>!c||['blue','gold','red','tan'].some(i=>!c.some(t=>S[t].c==i)&&(c.c=i,R(p+1)||(c.c='')),c=S[c]), R(0), k.map(k=>console.log('#'+k+'{fill:'+S[k].c+'}')) } ``` **Ungolfed** ``` F=l=>{ var states = {}; // hash table with adiacent list for each state S=(a,b)=>states[a]=(states[a]||[]).concat(b); l.replace(/(..)-(..)/g,(_,a,b)=>S(a,b)+S(b,a)); // build the hash table from the param list keys = Object.keys(states); // get the list of hashtable keys as an array (the 49 states id) Scan=(p)=> // Recursive scan function { var sId = keys[p]; // in sid the current state id, or undefined if passed last key if (!sId) return true; // end of keys, recursive search is finished var sInfo = states[sId]; // in sInfo the aarray of adiacent states id + the color property return ['blue','gold','red','tan'].some( (color) => // check the four avaialabe colors { var colorInUse = sInfo.some( (t) => states[t].color == color); // true if an adiacent state already has the currnet color if (!colorInUse) // if the color is usable { sInfo.color = color; // assign the current color to the current state var ok = Scan(p+1); // proceed with the recursive scan on the next state if (!ok) // if recursive scan failed, backtrack { sInfo.color = ''; // remove the assigned color for the current state } return ok; } } ) }, Scan(0), // start scan keys.forEach( (sId) => console.log('#'+sId+'{fill:'+states[sId].color+'}')) // output color list } ``` **Test** in FireFox/FireBug console ``` list = "AL-FL AL-GA AL-MS AL-TN AR-LA AR-MO AR-MS AR-OK AR-TN AR-TX AZ-CA AZ-CO AZ-NM "+ "AZ-NV AZ-UT CA-NV CA-OR CO-KS CO-NE CO-NM CO-OK CO-UT CO-WY CT-MA CT-NY CT-RI "+ "DC-MD DC-VA DE-MD DE-NJ DE-PA FL-GA GA-NC GA-SC GA-TN IA-MN IA-MO IA-NE IA-SD "+ "IA-WI ID-MT ID-NV ID-OR ID-UT ID-WA ID-WY IL-IA IL-IN IL-KY IL-MO IL-WI IN-KY "+ "IN-MI IN-OH KS-MO KS-NE KS-OK KY-MO KY-OH KY-TN KY-VA KY-WV LA-MS LA-TX MA-NH "+ "MA-NY MA-RI MA-VT MD-PA MD-VA MD-WV ME-NH MI-OH MI-WI MN-ND MN-SD MN-WI MO-NE "+ "MO-OK MO-TN MS-TN MT-ND MT-SD MT-WY NC-SC NC-TN NC-VA ND-SD NE-SD NE-WY NH-VT "+ "NJ-NY NJ-PA NM-OK NM-TX NM-UT NV-OR NV-UT NY-PA NY-VT OH-PA OH-WV OK-TX OR-WA "+ "PA-WV SD-WY TN-VA UT-WY VA-WV"; F(list); ``` *Output* ``` #AL{fill:blue} #FL{fill:gold} #GA{fill:red} #MS{fill:gold} #TN{fill:tan} #AR{fill:blue} #LA{fill:red} #MO{fill:gold} #OK{fill:red} #TX{fill:gold} #AZ{fill:blue} #CA{fill:gold} #CO{fill:gold} #NM{fill:tan} #NV{fill:tan} #UT{fill:red} #OR{fill:blue} #KS{fill:blue} #NE{fill:red} #WY{fill:blue} #CT{fill:blue} #MA{fill:gold} #NY{fill:red} #RI{fill:red} #DC{fill:blue} #MD{fill:gold} #VA{fill:red} #DE{fill:red} #NJ{fill:gold} #PA{fill:blue} #NC{fill:blue} #SC{fill:gold} #IA{fill:blue} #MN{fill:gold} #SD{fill:tan} #WI{fill:red} #ID{fill:gold} #MT{fill:red} #WA{fill:red} #IL{fill:tan} #IN{fill:gold} #KY{fill:blue} #MI{fill:blue} #OH{fill:red} #WV{fill:tan} #NH{fill:blue} #VT{fill:tan} #ME{fill:gold} #ND{fill:blue} ``` ]
[Question] [ ## Reducing fractions *the wrong way* In this code-golf challenge you have to find fractions that can be reduced the wrong way but still end up in the same number. **Note:** reducing fractions *the wrong way* does here have an exact definition, see details. Example: 64/16 = 64/16=4/1 = 4 Of course you cannot just strike both 6es but here you still end up with the correct value. In this challenge you have to find examples like this. ### Details You have to write a function/program that accepts one positive integer `n` as input and outputs/returns a list/array of the fractions in format `numerator1,denominator1,numerator2,denominator2,...` The program has to find out for each fraction `a/b` with `a+b=n` and `a,b>0` whether it can be reduced *the wrong way*. (It does not matter whether if it can be reduced in the conventional way or whether there are many possibilities of reductions, it just has to be possible to reduce it *the wrong way* in at least one way.) **Definition of** ***the wrong way:*** A fraction can be reduced *the wrong way* if and only if the same sequence of successive digits appears in a and b *and* if the value of the fraction stays the same if you remove the substring. Example: 1536/353 can be 'reduced' to 16/3 but those two values are not equal so you cannot reduce this fraction *the wrong way*. Note that this definition of reducing *the wrong way* can also include fractions that are reduced the right way: `110/10 = 11/1` is within the definition of reducing *the wrong way* even though it is a valid step. ### Scoring The least number of bytes wins. You can write a function or program that accepts an integer and returns an array or a program that uses stdin/stdout or you can consider n saved in a variable and in the end of the program the list must be saved in an other variable. ### Test cases Please include following testcases (Tell me which ones I should add, I have no idea how many of those fractions there are / how many examples to expect) ``` n=80 (64/16 should be in this list) n=147 (98/49 should be in this list) n=500 (294/196 should be in this list) WRONG since 294+196 != 500 Thanks Falko ``` [Answer] # Python 2 – ~~183~~ 180 ``` r=range s=lambda a:[(a[i:j],int(a[:i]+a[j:]))for i in r(len(a))for j in r(i+1,len(a)+(i>0))] l=sum([[a,n-a]for a in r(n)for p,x in s(`a`)for q,y in s(`n-a`)if(n-a)*x==a*y<p==q],[]) ``` the input must be stored in `n`, the output will be stored in `l`. ### Test cases: n = 80: ``` [10, 70, 16, 64, 20, 60, 30, 50, 40, 40, 40, 40, 50, 30, 60, 20, 64, 16, 70, 10] ``` n = 147: ``` [49, 98, 98, 49] ``` n =490: ``` [10, 480, 20, 470, 30, 460, 40, 450, 50, 440, 60, 430, 70, 420, 80, 410, 90, 400, 90, 400, 98, 392, 100, 390, 100, 390, 110, 380, 120, 370, 130, 360, 140, 350, 150, 340, 160, 330, 170, 320, 180, 310, 190, 300, 190, 300, 196, 294, 200, 290, 200, 290, 210, 280, 220, 270, 230, 260, 240, 250, 245, 245, 245, 245, 245, 245, 245, 245, 245, 245, 250, 240, 260, 230, 270, 220, 280, 210, 290, 200, 290, 200, 294, 196, 300, 190, 300, 190, 310, 180, 320, 170, 330, 160, 340, 150, 350, 140, 360, 130, 370, 120, 380, 110, 390, 100, 390, 100, 392, 98, 400, 90, 400, 90, 410, 80, 420, 70, 430, 60, 440, 50, 450, 40, 460, 30, 470, 20, 480, 10] ``` --- Should duplicates in the output be forbidden, it gets 10 characters longer: ``` r=range s=lambda a:[(a[i:j],int(a[:i]+a[j:]))for i in r(len(a))for j in r(i+1,len(a)+(i>0))] l=sum(map(list,{(a,n-a)for a in r(n)for p,x in s(`a`)for q,y in s(`n-a`)if(n-a)*x==a*y<p==q}),[]) ``` [Answer] ### Haskell, ~~207~~ 206 (209?) characters ``` import Data.List x![]=[x];(w:x)!(y:z)|w==y=x!z;_!_=[] a@(w:x)%b=a!b++[w:e|e<-x%b];a%b=a!b h=show f n=[(c,n-c)|c<-[1..n-1],i<-inits$h c,s<-init$tails i,s/=h c,a<-h c%s,b<-h(n-c)%s,read a*(n-c)==read('0':b)*c] ``` If it's not allowable to return the same ratio more than once (400/400 = 40/40 = 4/4), use `f n=nub[...` to filter them out. Returns a list of pairs. A list of two-element pairs costs the same. A list of actual fractions would require importing `Data.Ratio` or fully qualifying `Data.Ratio.%` (which also collides with the `%` function defined here) **test cases** (with `nub`): ``` Prelude Data.List> f 80 [(10,70),(16,64),(20,60),(30,50),(40,40),(50,30),(60,20),(64,16),(70,10)] Prelude Data.List> f 147 [(49,98),(98,49)] Prelude Data.List> f 500 [(10,490),(20,480),(30,470),(40,460),(50,450),(60,440),(70,430),(80,420),(90,410 ),(100,400),(110,390),(120,380),(130,370),(140,360),(150,350),(160,340),(170,330 ),(180,320),(190,310),(200,300),(210,290),(220,280),(230,270),(240,260),(250,250 ),(260,240),(270,230),(280,220),(290,210),(300,200),(310,190),(320,180),(330,170 ),(340,160),(350,150),(360,140),(370,130),(380,120),(390,110),(400,100),(410,90) ,(420,80),(430,70),(440,60),(450,50),(460,40),(470,30),(480,20),(490,10)] ``` **ungolfed and commented**: ``` import Data.List -- haystack ! needle - the haystack with the needle removed, wrapped in a single-element list -- or an empty array if the haystack does not start with the needle x ! [] = [x] -- case: empty needle = match with the full haystack left (h:hs) ! (n:ns) | h == n = hs ! ns -- case: needle and haystack match _ ! _ = [] -- case: no match -- haystack % needle - the haystack with the needle removed -- for all positions of the needle in the haystack a@(h:hs) % b = a ! b ++ map (h:) (hs%b) -- either remove the needle here, or elsewhere a % b = a -- empty haystack cannot be popped -- f - the function we are interested in f total = [ (num, total - num) | num <- [1 .. total-1], -- for each numerator in range i <- inits $ show num, -- for each postfix of the numerator sub <- init $ tails i, -- for each prefix of the postfix except the last (empty) one sub /= show num, -- that isn't equal to the numerator reNum <- show num % sub, -- remove the substring from the numerator reDiv <- show (total - num) % sub, -- as well as from the denominator. -- the resulting ratios must be equal by value: (read reNum) ^ (total - num) == (read '0':reDiv) * num] ``` [Answer] # Python 2 - 236 ``` n=input() r=range f=float l=len for a in r(n): A=`a`;B=`n-a` for i in r(l(A)): for j in r(i+1,l(A)+1): for u in r(l(B)): C=A[:i]+A[j:];D=B[:u]+B[u+j-i:] if A[i:j]==B[u:u+j-i]and l(C)*l(D)and f(C)==f(A)/f(B)*f(D):print A,B ``` [Answer] # Python 3 - 302 ***Note:*** Due to parsing difficulties, there are no fractions with the number 0 in (so no fractions are calculated using the correct method). ``` n=int(input());s=str;r=range print([[a,b]for a in r(1,n)for b in r(1,a)for i in r(1,n)if i!=a and i!=b and s(i)in s(a)and s(i)in s(b)and s(a).count(s(i))<len(s(a))and s(b).count(s(i))<len(s(b))and not'0'in s(a)and not'0'in s(b)and eval(s(a).replace(s(i),'')+'/'+s(b).replace(s(i),''))==a/b and a+b<=n]) ``` ### With n=80: ``` [[64, 16]] ``` ### With n=147 ``` [[64, 16], [65, 26], [95, 19], [98, 49]] ``` ### With n=500 ``` [[64, 16], [65, 26], [95, 19], [98, 49], [136, 34], [192, 96], [194, 97], [195, 39], [196, 49], [196, 98], [231, 132], [238, 34], [238, 136], [242, 143], [253, 154], [264, 165], [268, 67], [275, 176], [286, 187], [291, 97], [291, 194], [294, 49], [294, 98], [294, 196], [295, 59], [297, 198], [298, 149], [325, 13], [341, 143], [345, 138], [392, 49], [392, 98], [395, 79]] ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/26778/edit). Closed 9 years ago. [Improve this question](/posts/26778/edit) # Overview This challenge was inspired by [this StackOverflow Meta post](https://meta.stackoverflow.com/a/253926/1435657). In it, @hakre says: > > I've seen a project really *written by Stackoverflow* (a noob copies together from SO here and SO there), attribution normally never is done which results in rights termination under CC. (sic) > > > Your mission is to make the most interesting program you can -- without ever writing a single line of code. You can only use code which is already written for you, both in questions and answers from StackOverflow. All you can do is duct tape it all together the best you can. And of course, it's very important that we provide appropriate attribution so that we don't get our rights terminated. --- # Rules 1. You must include links to the questions/answers you used in your answer. 2. You *may not* modify the code you find, with the following exceptions: a. You may rename variables, functions, and methods. (This doesn't mean you can change a method *invocation*, by changing, say `scanner.nextInt()` to `scanner.nextLine()` and claiming that you're changing a method name. The change must be in the definition or reference to the same entity.) b. You may adjust indentation appropriately. c. You can assume that the proper modules are loaded for the code snippets to work. (e.g., `import` statements for Java and Python, `using` statements for C# and C++, and their equivalents in all languages) If the code snippet includes the `import`s for you, you can move them to the top of the code. d. If the language requires the code to be in some kind of method body to execute (e.g., `public static void main(String[] args)` for Java, `static int Main(string[] args)` for C#, and so on), you can wrap your code in the appropriate method. But the *contents* of that main method must remain unmodified. 3. You must supply an explicit list of any variable/method/function/class rename-ings performed. 4. You can't take snippets of snippets (meaning if you take a code block from a post, you take the whole thing) 5. Provide a brief description of what the code does for people who aren't intimate with the language you're using. 6. Popularity contest, so the most upvotes wins! --- # Boring Five Minute Example (Python 3) *Description*: Reads a bunch of log files from the current directory and randomizes the lines in them (exciting, right? This would totally win a popularity contest) *Source* ``` import glob import random for file in glob.glob('log-*-*.txt'): # Etc. with open(file) as f: content = f.readlines() # shuffle the list in place random.shuffle(content) # print it print(content) ``` *Legal Modifications* * Renamed `fname` to `file` from link 1 * Renamed `b` to `content` from link 2 *Attributions* 1. <https://stackoverflow.com/a/3277516/1435657> 2. <https://stackoverflow.com/a/16737991/1435657> 3. <https://stackoverflow.com/a/4918520/1435657> [Answer] # C - one operation calculator Let's have this for a start. It's actually quite hard to find pieces of C programs that aren't whole programs. I had most trouble with declarations. ``` // http://stackoverflow.com/a/2911978 Block #1 (changed i to a) static int a = 10; // http://stackoverflow.com/a/2911978 Block #1 (changed i to b) static int b = 10; // http://stackoverflow.com/a/442647 Block #1 (changed c to op) unsigned char op = (unsigned char)-1; // http://stackoverflow.com/q/3711048 Inline block #1 int main() // http://stackoverflow.com/a/14902422 Inline block #1 { // http://stackoverflow.com/q/217074 Inline block #2 (changed i to a) scanf("%d", &a) // http://stackoverflow.com/a/23353870 Inline block #2 ; // http://stackoverflow.com/q/217074 Block #2 (changed c to op) scanf("%c", &op) // http://stackoverflow.com/a/23353870 Inline block #2 ; // http://stackoverflow.com/q/217074 Inline block #2 (changed i to b) scanf("%d", &b) // http://stackoverflow.com/a/23353870 Inline block #2 ; // http://stackoverflow.com/a/4173188 Block #2 int result = 0; result = (op == '*') ? a * b : result; result = (op == '/') ? a / b : result; result = (op == '+') ? a + b : result; result = (op == '-') ? a - b : result; printf("%d",result); // http://stackoverflow.com/a/3245525 Block #2 printf("\n"); /* prints newline */ // http://stackoverflow.com/q/4138649 Inline block #1 return 0; // http://stackoverflow.com/a/14902422 Inline block #2 } ``` Takes a simple integral operation like `3+151` or `41/2` on stdin and outputs the result to stdout. ]
[Question] [ Create the shortest program to check who has won in an nd tic tac toe game. Your program should work when `n` (width) and `d` (dimension number) are in these ranges: ``` n∈[3,6]∩ℕ ie a number from this list: 3,4,5,6 d∈[2,5]∩ℕ ie a number from this list: 2,3,4,5 ``` `n = 3; d = 2` (32 ie 3 by 3): ``` [][][] [][][] [][][] ``` `n = 3; d = 3` (33 ie 3 by 3 by 3): ``` [][][] [][][] [][][] [][][] [][][] [][][] [][][] [][][] [][][] ``` `n = 6; d = 2` (62 ie 6 by 6): ``` [][][][][][] [][][][][][] [][][][][][] [][][][][][] [][][][][][] [][][][][][] ``` And so on. **Winning** (If you've played enough multi-dimensional tic tac toe, this is the same.) In order for there to be a win, one player must have all the adjacent squares along a line. That is, that player must have `n` moves on a line to be a winner. Adjacent: * each tile is a point; for example (0,0,0,0,0) is a point in `d=5` * adjacent tiles are tiles such they are both points on the same unit d-cube. In other words, the [Chebyshev distance](http://en.wikipedia.org/wiki/Chebyshev_distance) between the tiles is 1. * in other words, if a point `p` is adjacent to a point `q`, then every coordinate in `p`s corresponding coordinate in `q` differs from it by no more than one. Additionally, at least on coordinate pair differs by exactly one. Lines: * Lines are defined by vectors and a tile. A line is each tile hit by the equation: `p0 + t`<`some vector with the same number of coordinates as p0`>`` **Input**: Input will be to STDIN. The first line of input will be two numbers, `n` and `d` in the form `n,d`. After this will be a line consisting of coordinates specifying the moves that have been done. Coordinates will be listed in the form: `1,1;2,2;3,3`. The upper left corner is the origin ( 0,0 for 2D). In the general case, this list will be like `1,2,...,1,4;4,0,...,6,0;...` where the first number represents left-right-ness, the second up-down-ness, the third through the 3rd dimension, etc. Note that the first coordinate is `X`s first turn, the second is `O`s first turn, .... The input will be followed by a newline. **Output**: Output will be to STDOUT. Simply indicate who won if someone won, or if it is a tie. If it is neither a tie nor a win, don't output anything. Additionally, indicate if there is a move clash, that is, if there are at least two moves in the same location. If there was a win/draw before the input ended, your program can do whatever it wants. **Test cases** (anyone want to suggest any more?): Input: ``` 4,3 0,0,0;1,1,1;1,0,1;2,0,2;0,0,1;2,0,0;2,0,1;3,0,2;3,0,1 ``` Example Output: ``` X wins ``` Another possible output (requires explanation): ``` 1 ``` [Answer] Python, 745 578 Characters ``` import sys x=[] o=[] t=1 b="," k=map def m(c): m=x if t else o c=k(int,c.split(b)) if c in o+x: print b sys.exit() m.append(c) r=0 for p in m: r=w(p,m) return r def w(p,m): for q in m: d=max(k(lambda x,y:abs(x-y),p,q)) if d==u: if e(p,q,m): return 1 return 0 def e(p,q,m): v=k(lambda p,q:(p-q)/u,q,p) l=p for i in range(1,n): y=k(lambda j,h:j+h,l,v) if y not in m: return 0 l=y if not l==q: return 0 return 1 q=sys.stdin.readline d=q() v=q() z=d.split(b) (n,d)=k(int,z) a=v.split(";") u=n-1 for c in a: r=m(c) if r: print t t=not t ``` I made some changes and shrank it down quite a bit. Note that a return of True means that x has won, False means y won, and , means that an invalid move was made. [Answer] # Not an answer - Java I was curious to see how many different ways there were to win for a given n,d so I wrote this code to list them all. ``` import java.util.*; public class MultiDTTT { static Set<Win> wins = new HashSet<Win>(); static final int d = 3; static final int n = 3; static final char maxChar = (char)(n-1) + '0'; public static void main(String[] args) throws Exception { String pad = ""; for(int i=0; i<d; i++) pad = pad + "0"; for(int i=0; i<Math.pow(n,d); i++) { String s = Integer.toString(i,n); s = pad.substring(s.length()) + s; buildWin(s,"",0); } System.out.println(wins.size()); for(Win w : wins) System.out.println(w.toString()); } static void buildWin(String s, String p,int i) { if(i<d) { if(s.charAt(i) == '0') { buildWin(s,p+"u",i+1); buildWin(s,p+"s",i+1); } else if(s.charAt(i) == maxChar) { buildWin(s,p+"d",i+1); buildWin(s,p+"s",i+1); } else { buildWin(s,p+"s",i+1); } } else { if(p.contains("u") || p.contains("d")) wins.add(new Win(s,p)); } } static class Win { String start; String pattern; Set<String> list = new HashSet<String>(); Win(String s, String p) { start = s; pattern = p; char[] sc = s.toCharArray(); for(int i=0; i<n; i++) { list.add(new String(sc)); for(int j=0; j<d; j++) { switch (p.charAt(j)) { case 'u': sc[j]++; break; case 'd': sc[j]--; break; case 's': break; } } } } public String toString() { String s = ""; //start + ", " + pattern + "\n "; for(String ss : list) s = s + ss + " "; return s; } public boolean equals(Object x) { return (x instanceof Win) && this.list.equals(((Win)x).list); } public int hashCode(){ return list.hashCode(); } } } ``` I hand-tested it on n,d = 2..3,2..3 and it appears to work… after that the number of possible ways to win grows quickly as shown below: ``` n 1 2 3 4 5 6 d 1 1 1 1 1 1 1 2 1 6 8 10 12 14 3 1 28 49 76 109 148 4 1 120 272 520 888 1400 5 1 496 1441 3376 6841 12496 6 1 2016 7448 21280 51012 107744 ``` Having generated all wining sets, I could extend the program to check the given input against winning sets but, of course, that method would never win the golf. So I was content to stop here - except it looked like I could find a closed-form solution for the number of ways to win as a function of n and d… It is Number of ways to win = 0.5( (n+2)^d - n^d). [Answer] # C++ 794 ~~849~~ chars ``` #include <algorithm> #include <iostream> #include <cmath> #include <string> #define _ return #define Y int #define Z(a) cout<<#a #define W(a,b,c) for(a=c;a++<b;) using namespace std;Y n,d,A[5],P[6],T=1,x[7776]={},i,j,k,a,z,p=pow(n,d);char c;bool B;string s;Y K(){a=P[j];W(k,i,0)a/=n;_ a%n;}Y M(){j=0;z=K();W(j,n,1){if(K()!=z){_ 1;}}_ 0;}Y N(){W(j,n,0)if(K()!=n-1-j)_ 1;_ 0;}Y O(){W(j,n,0)if(K()!=j)_ 1;_ 0;}Y S(){z=0;W(i,d,0){z*=n;z+=A[i];}_ z;}Y C(){a=z=0;W(i,p,0){if(s[i]-'0'){P[z]=i;++z;if(a){if(x[i]!=a)_ 0;}else a=x[i];}}_ a;}Y L(){W(i,d,0)if(M()*N()*O())_ 0;_ 1;}Y main(){cin>>n>>c>>d;while(1){W(i,d,0)B=cin>>A[i]>>c;if(x[S()]){Z(!);_ 0;}x[S()]=T;T*=-1;if(!B)break;}W(i,p,0)i<n?s+="1":s+="0";do if(C()&&L()){C()==1?Z(X):Z(O);_ 0;}while(prev_permutation(s.begin(),s.end()));_ 0;} ``` Output is: "X" (X wins), "O" (O wins), or "!" (illegal move attempt). This just maps the points into a linear array and checks all possible subsets of size n, first for being constant at X or O, and then for being in a line. To check for being in a line, the coordinates of the points in each subset are examined one at a time; they must each be either increasing from 0 to n-1, decreasing from n-1 to 0, or constant. The points are naturally ordered in the linear array, so it makes sense to call a coordinate increasing or decreasing for a given set of points. Thanks to Howard for pointing out a serious mistake in the first version. **In solidarity with Quincunx, I have to point out that it would be a travesty if a C++ answer wins** ]
[Question] [ Write a program that performs *Polynomial Interpolation* using true arbitrary precision rational numbers. The input looks like this: ``` f(1) = 2/3 f(2) = 4/5 f(3) = 6/7 ... ``` You may assume that there's exactly one whitespace before and after the `=` sign, all the numbers are either fractions or integers. You may also assume, that all fraction in the input are already irreducible. No error checking is needed, you may assume, that the input is valid and no x is doubled in the f(x). The output should be in a LaTeX compatible form, the emitted LaTeX code should yield the same graphical representation as the output given here. ``` f(x) = 123x^2 + \frac{45}{2}x + \frac{7}{4} ``` The fraction must be reduced as much as possible, eg. something like `\frac{2}{4}` is not allowed. If the number is integer, don't use a fraction. ## Special rules: Your program should... * work for polynomials up to degree 12 * complete in less then 1 minute for reasonable input * not use any functions that do the whole calculation for you * output the polynomial of smallest possible degree ## Testcases: The given testcases are just for clarification. Your program should yield correct result for all correct inputs. ### Input ``` f(1) = 2/3 f(2) = 4/5 f(3) = 6/7 ``` ### Output ``` f(x) = - \frac{4}{105}x^2 + \frac{26}{105}x + \frac{16}{35} ``` ### Input ``` f(-12) = 13/2 f(5/3) = 3/5 f(13) = -6 f(1/5) = -3/4 ``` ### Output ``` f(x) = - \frac{2186133}{239455744}x^3 + \frac{2741731}{149659840}x^2 + \frac{26720517}{29201920}x - \frac{279464297}{299319680} ``` ### Input ``` f(4/3) = 617/81 f(2) = 20/3 f(-8/3) = 6749/81 f(-5) = 7367/12 f(0) = 23/3 ``` ### Output ``` f(x) = \frac{1}{2}x^4 - 2x^3 + \frac{7}{4}x^2 + \frac{23}{3} ``` ### Input ``` f(0) = 5 f(1) = 7 f(2) = 9 f(3) = 11 f(4) = 13 ``` ### Output ``` f(x) = 2x + 5 ``` ### Input ``` f(1/2) = -1/2 f(-25) = -1/2 f(-54/12) = -1/2 ``` ### Output ``` f(x) = -\frac{1}{2} ``` [Answer] ## J + sh **J script:** ``` i=:0".(1!:1)3 i=:((-:#i),2)$i c=:|.(%.(x:((i.#i)^~])"0({."1 i)))(+/ .*)(|:{:"1 i) (":(-.0=c)#(c,.i.-#c))(1!:2)2 ``` **sh script:** ``` echo -n 'f(x) = ' tr -d 'f()=' | tr /\\n- r' '_ | ./polyint.ijs | sed -e 's/^/+/;s/_/-/;s/\([0-9]*\)r\([0-9]*\)/\\frac{\1}{\2}/;s/ \([0-9]*$\)/x^\1/;s/\^1//;s/x^0//;s/+\(.*-.*\)/\1/' ``` Run the sh script: ``` ./pol-int.sh f(1/2) = -1/2 f(-25) = -1/2 f(-54/12) = -1/2 f(x) = -\frac{1}{2} ``` . ``` ./pol-int.sh f(4/3) = 617/8 f(2) = 20/3 f(-8/3) = 6749/81 f(-5) = 7367/12 f(0) = 23/3 f(x) = -\frac{37745}{14592}x^4 -\frac{853249}{43776}x^3 + \frac{57809}{7296}x^2 + \frac{225205}{2736}x + \frac{23}{3} ``` [Answer] # Perl (569 characters) ``` use Math'BigInt;sub r{($u,$v)=@_;$v?r($v,$u%$v):$u}sub c{new Math'BigInt$_[0]}$a=@c=<>;for(@c){m!(-?\d+)/?(\d*). = (-?\d+)/?(\d*)!;$j{$_,$i}=$1**c$_,$k{$_,$i|=0}=($2||1)**c$_ for 0..$a;$j{$a,$i}=c$3;$k{$a,$i++}=c$4||1}for$p(0..$a-1){for$y(0..$p-1,$p+1..$a-1){$n=$j{$p,$y}*$k{$p,$p};$o=$k{$p,$y}*$j{$p,$p};$j{$_,$y}=$j{$_,$y}*$k{$_,$p}*$o-$k{$_,$y}*$j{$_,$p}*$n,$k{$_,$y}*=$k{$_,$p}*$o for 0..$a}}print"f(x)=";for(1..$a){$s=r$t=$j{$a,$p=$a-$_}*$k{$p,$p},$w=$k{$a,$p}*$j{$p,$p};$u=abs$t,print$t>0?"$z":'-',($z='+',$w/=$s)-1?"\\frac{$u}{$w}":$u,$p>1?"x^$p":x x$p if$t/=$s} ``` ### Detailed explanation: ``` use Math'BigInt; # Subroutine to calculate gcd of two numbers sub r{($u,$v)=@_;$v?r($v,$u%$v):$u} # Subroutine to create BigInts sub c{new Math'BigInt$_[0]} # Read input # Throughout, $a is the number of equations. $a=@c=<>; # Initialises the $a+1 × $a matrix with all the values. # $j{$x,$y} contains the numerator, $k{$x,$y} the denominator. for(@c) { m!(-?\d+)/?(\d*). = (-?\d+)/?(\d*)!; # Puzzle for the reader: why is $i|=0 in the second one, # not the first one? Answer at the bottom! $j{$_,$i}=$1**c$_,$k{$_,$i|=0}=($2||1)**c$_ for 0..$a; $j{$a,$i}=c$3; $k{$a,$i++}=c$4||1 } # Generates the matrix echelon form. # Basically, it works like this: for$p(0..$a-1) { # For each element along the diagonal {$p,$p}, set all the values above and # below it to 0 by adding a multiple of row $p to each of the other rows. for$y(0..$p-1,$p+1..$a-1) { # So we need to multiply the row $p by the value of {$p,$y}/{$p,$p} # (stored in $n/$o) and then subtract that from row $y. $n=$j{$p,$y}*$k{$p,$p}; $o=$k{$p,$y}*$j{$p,$p}; $j{$_,$y}=$j{$_,$y}*$k{$_,$p}*$o-$k{$_,$y}*$j{$_,$p}*$n, $k{$_,$y}*=$k{$_,$p}*$o for 0..$a } } # Outputs the result print"f(x)="; for(1..$a) { # Note this sets $p = $a-$_. $p is the power of x. # We need to divide {$a,$p} by {$p,$p}. Store the result in $t/$w. # We also need to put the fraction in lowest terms, so calculate the gcd. $s=r$t=$j{$a,$p=$a-$_}*$k{$p,$p},$w=$k{$a,$p}*$j{$p,$p}; # Output this term only if the numerator ($t) is non-zero. # Output a plus sign only if this isn’t the first term. # Output a fraction only if the denomator ($w) isn’t 1. $u=abs$t,print$t>0?"$z":'-', ($z='+',$w/=$s)-1?"\\frac{$u}{$w}":$u,$p>1?"x^$p":x x$p if$t/=$s } # Answer to the puzzle buried in the code above: # It’s because the second part is passed as a second argument to c, # hence it is evaluated before the first part. ``` ### Comments * I am sure there is a module for matrix manipulation that provides a function for echelon form. I specifically didn’t use that (didn’t even search for one) because I assume it is the point of this contest to do it yourself. It is more interesting that way, too. Of course the same could be said about BigInt, but then I suspect nobody will attempt this challenge... ### Edits * **(630 → 585)** Realised I can do the echelon form in one loop instead of two. Add explanation as comments in code. * **(585 → 583)** Just discovered the package syntax that lets me use `'` instead of `::`. * **(583 → 573)** Some more microgolfing * **(573 → 569)** Shorter regular expression to parse input [Answer] # Lagrange Method, Python, 199 236 202 bytes A little late, but... ``` def lagrange(dp): l = lambda i: lambda x: (prod([(x - dp[j][0]) / (dp[i][0] - dp[j][0]) for j in range(len(dp)) if i != j])) return lambda x: sum([l(i)(x) * dp[i][1] for i in range(len(dp))]) ``` Edit: To adhere to general rules, we have to remove references to non-builtin functions (at least without importing them). I have rewritten it to only use standard library modules and also included the imports (thanks to [@TheFifthMarshal](https://codegolf.stackexchange.com/users/46076/the-fifth-marshal) & [@Tech-Freak](https://codegolf.stackexchange.com/users/56046/teck-freak)), while deleting extraneous whitespace, bumping it up to 208 bytes. To elaborate, the input `d` takes the form of a 2D iterable (an `nx2` matrix), where each row is a measurement, the first column is \$t\$ and the second column is \$x\$. The output is an anonymous function which can take any floating point or integer number and give the approximate result. ``` from functools import* mul=lambda a,b:a*b def l(d): l=lambda i,x:reduce(mul,[(x-d[j][0])/(d[i][0]-d[j][0])for j in range(len(d))if i!=j],1) return lambda x:sum([l(i,x)*d[i][1]for i in range(len(d))]) ``` ### Usage Example: ``` >>> t = np.arange(0, 5, 0.5) >>> t2 = np.arange(0, 5, 0.01) >>> x = t**3 >>> dp = np.vstack((t, x)).T >>> poly = l(dp) >>> plt.plot(t2, np.vectorize(poly)(t2), label="output") >>> plt.scatter(t, x, label="input") >>> plt.legend() ``` [![Lagrange interpolation of f(x) = x^3](https://i.stack.imgur.com/mFmzV.png)](https://i.stack.imgur.com/mFmzV.png) ]
[Question] [ Compare two numbers N1 = abc, N2 = def by constructing a function f(a,b,c,d,e,f) that: * returns 1 if N1 > N2 * returns -1 if N1 < N2 **Note:** You are not required to return any value for any other relation between N1 and N2. e.g. when they are equal or when their relation is undefined (complex numbers). other constrains: * all numbers are integers * a,b,c,d,e,f may be positive or negative but not zero. * |a|,|d| < 1000 * |b|,|c|,|e|,|f| < 1010 * running time less than few seconds Examples: ``` f(100,100,100,50,100,100) = 1 f(-100,100,100,50,100,100) = 1 f(-100,99,100,50,100,100) = -1 f(100,-100,-100, -1, 3, 100) = 1 f(535, 10^9, 10^8, 443, 10^9, 10^9) = -1 ``` This is code golf. Shortest code wins. [Answer] ## Ruby 1.9, ~~280 227 189~~ 171 characters ``` z=->a,b,c,d,e,f{l=->a{Math.log a} u=->a,b{[a.abs,a][b&1]} a=u[a,b=u[b,c]] d=u[d,e=u[e,f]] d*a<0?a<=>d :b*e<0?b<=>e :(l[l[a*q=a<=>0]/l[d*q]]<=>f*l[e*r=b<=>0]-c*l[b*r])*q*r} ``` I know this is *a bit* longer than the other solutions, but at least this approach should work without calculating abc, def, bc or ef. Edit: * (279 -> 280) Fixed a bug when `a**b**c < 0` and `d = 1`. * (280 -> 227) Removed an unnecessary check for a special case. * (227 -> 192) Removed some checks that aren't necessary with the given criteria (non-zero integers, no output necessary for complex values) * (192 -> 189) Due to all the other checks, I can safely calculate `log(log(a)/log(d))` instead of `log(log(a))-log(log(d))`. * (189 -> 171) Simplified way to transform equivalent problems into one another. Testcases: ``` z[100, 100, 100, 50, 100, 100] == 1 z[-100, 100, 100, 50, 100, 100] == 1 z[-100, 99, 100, 50, 100, 100] == -1 z[100, -100, -100, -1, 3, 100] == 1 z[535, 10**9, 10**8, 443, 10**9, 10**9] == -1 z[-1, -1, 1, 2, 2, 2] == -1 z[1, -5, -9, 2, -1, 2] == -1 z[1, -5, -9, 2, -1, 3] == 1 z[3, -3, 3, -4, 1, 1] == 1 z[-2, 1, 1, 1, 1, 1] == -1 z[1, 1, 1, -1, 1, 1] == 1 z[1, 1, 1, 2, 3, 1] == -1 z[1, 1, 1, 2, -3, 2] == -1 z[1, 1, 1, 2, -3, 1] == 1 z[-1, 1, 1, 1, 1, 1] == -1 z[2, 3, 1, 1, 1, 1] == 1 z[2, -3, 2, 1, 1, 1] == 1 z[2, -3, 1, 1, 1, 1] == -1 ``` [Answer] ### Mathematica, 110 chars ``` z[a_,b_,c_,d_,e_,f_]:=With[{g=Sign[a]^(b^c),h=Sign[d]^(e^f)},If[g!=h,g,g*Sign[Log[Abs[a]]b^c-Log[Abs[d]]e^f]]] ``` [Answer] # [ShortScript](http://esolangs.org/wiki/ShortScript), 89 bytes ``` {CP $M^ η1 η2 $M^ ζ η3 ↑Αζ $M^ η4 η5 $M^ ζ η6 ↔α>ζ↑Ζ1 ↔α<ζ↑Ζ-1} ``` The implementation isn't exactly the described one, but it works. This answer is non-competing, since ShortScript has been published after this challenge. [Answer] ## Python 2.6 (this doesn't actually work) ``` import cmath g=cmath.log f=lambda a,b,c,d,e,f:-1+2*((c*g(b)+g(g(a))-f*g(e)-g(g(d))).real>0) ``` today i learnt python has a complex log function. so, blindly double log both sides and look at the real component. works for 4 out of the 5 tests. not sure what's happening with the fourth one. ``` print f(100,100,100,50,100,100) == 1 print f(-100,100,100,50,100,100) == 1 print f(-100,99,100,50,100,100) == -1 print f(100,-100,-100, -1, 3, 100) == 1 # failure, sadness. print f(535, 10^9, 10^8, 443, 10^9, 10^9) == -1 ``` [Answer] ## Python (99) ``` from math import* from numpy import* l=log def f(a,b,c,d,e,f):return sign(l(a)*l(b)*c-l(d)*l(e)*f) ``` [Answer] ## Haskell, 44 characters ``` n True=1 n _=1-2 g a b c d e f=n$a^b^c>d^e^f ``` Runs under a second for all the test examples on *my* machine. ]
[Question] [ Write the shortest program or function that mimics the addition in this [XKCD strip](https://xkcd.com/2637/): [![enter image description here](https://i.stack.imgur.com/cEgxQ.png)](https://i.stack.imgur.com/cEgxQ.png) ## Input Two positive decimal integers containing only the digits `150`. ## Output The positive decimal integer result of adding the two inputs together in the manner shown above. This output should also only have the digits `150`. ## Specification ### Input and Output Input and output are numbers only containing digits `150`. ### Roman Numerals This challenge will use [Standard Form](https://en.wikipedia.org/wiki/Roman_numerals#Standard_form) numerals: | | Thousands | Hundreds | Tens | Units | | --- | --- | --- | --- | --- | | 1 | M | C | X | I | | 2 | MM | CC | XX | II | | 3 | MMM | CCC | XXX | III | | 4 | MMMM | CD | XL | IV | | 5 | MMMMM | D | L | V | | 6 | MMMMMM | DC | LX | VI | | 7 | MMMMMMM | DCC | LXX | VII | | 8 | MMMMMMMM | DCCC | LXXX | VIII | | 9 | MMMMMMMMM | CM | XC | IX | Note the subtractive notation on multiples of `40` and `90`, and additive notation on multiples of `1000`. ## Worked Example Consider a test case below, `1010111 + 101051 = 1050110 (23 + 26 = 49)`. Convert the inputs to Roman numerals, then to Arabic numerals: ``` 1010111 => XXIII => 23 101051 => XXVI => 26 ``` Perform the addition: ``` 23 + 26 => 49 ``` Convert the output back to Roman numerals, then for each Roman numeral substitute its Arabic numeral value: ``` 49 => XLIX => 10 50 1 10 => 1050110 ``` ## Test Cases ``` A + B = C (explanation) ========= 1 + 1 = 11 (1 + 1 = 2) 11 + 11 = 15 (2 + 2 = 4 == IV) 15 + 5 = 110 (4 + 5 = 9 == IX) 101010 + 1 = 1010101 (30 + 1 = 31) 1010 + 111 = 1010111 (20 + 3 = 23) 1010 + 15 = 101015 (20 + 4 = 24) 1010 + 5 = 10105 (20 + 5 = 25) 1010111 + 101051 = 1050110 (23 + 26 = 49) 101015 + 51 = 101010 (24 + 6 = 30) 1010015 + 15 = 101005111 (94 + 4 = 98) 100010010010101015 + 1000100010010010010505 = 100010001000500501010110 (1234 + 2345 = 3579) 100010010010101015 + 1000100010001000100010001000100050010010050105 = 100010001000100010001000100010001000100100010100110 (1234 + 8765 = 9999) ``` ## Other Notes As seen in the comic, Randall is doing a simple substitution of Roman numerals with their decimal equivalents: * `I => 1` * `V => 5` * `X => 10` Presumably, this will be extended for all Roman numerals (up to 1000): * `L => 50` * `C => 100` * `D => 500` * `M => 1000` For more information, see the [ExplainXKCD wiki page](https://explainxkcd.com/wiki/index.php/2637:_Roman_Numerals). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes ``` ƛ`.0*`Ẏ⌊øṘṅøṘ;∑øṘvøṘṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGm2AuMCpg4bqO4oyKw7jhuZjhuYXDuOG5mDviiJHDuOG5mHbDuOG5mOG5hSIsIiIsIltcIjEwMTAxMTFcIiwgXCIxMDEwNTFcIl0iXQ==) ## How? ``` ƛ`.0*`Ẏ⌊øṘṅøṘ;∑øṘvøṘṅ ƛ # Map, and for both strings: `.0*`Ẏ # Get all regex matches ".0*" ⌊ # Convert each to integers øṘ # Convert each to their roman numeral ṅ # Join together to a single string øṘ # Convert from roman numeral to number ; # Close map ∑ # Sum øṘ # Convert to roman numeral vøṘ # Convert each character from roman numeral to number ṅ # Join together to a string ``` [Answer] # [Factor](https://factorcode.org) + `roman`, ~~117~~ 114 bytes ``` [ [ R/ .0*/ all-matching-subseqs [ dec> >roman ] f map-as concat ] bi@ roman+ 1 group [ roman> >dec ] map-concat ] ``` Needs modern Factor for [>dec](https://docs.factorcode.org/content/word-__gt__dec,math.parser.html), but here's a version that works on ATO for 3 more bytes: [Attempt This Online!](https://ato.pxeger.com/run?1=rZS_TsMwEMYXpj7FsYKSOoMlBCJiQywMIKaqg2ucNKJNUttRi6o-CUsX2HgF3gOehrOdP0pBFapxHEW5-H53-Zx8L28J47qQ26-jj4f7m9vrc5DFnOUwZ3oalkwqIaGUQolcgxKLSuRcKHgSMhczSGVRlVmemhVaP5cyw1VMqYIrWCy79aFYackUSJGKVQkXg8F6ADgWyzVEeGzAbxzDJURRh4zM9INaJO2QFKhvm65L0jGJOfxe3zItJ-pxsdD_cKNdrp8MLZf2sZ7iNtg-1WhgowdK4aiU_Ng0_Bh81O02rcVSgnfEkA8X2GBrDu3vmw3aWbdfh9qwEYnsK-xabpNwtdHFakz-WOjXkzYZhmYa2C20P9Gm2R42r5VOgrPPagQjuBtCSE6GwGazAI2MT9GjAlVN0JAUPn4UPIbY-dwYEvS6MkB34kXOmcbIJLtyLniKP6f1OEyygbj1wrHNalJc8ffEmV-MjyB0se3WXb8B) -3 bytes thanks to @Steffan [Answer] # JavaScript (ES6), 204 bytes Expects `(a)(b)`, where both arguments are strings. ``` a=>b=>(h=(n,k)=>n?h(n/10|0,k+0)+[k%8?[,k,d=k+k,d+k,k+(x=k*5),x,x+k,x+d,x+d+k,d+0][n%10]:k.repeat(n)]:'')((g=s=>s.replace(p=/.0*/g,s=>s-p?(t+=s<p?n:s-n,p=s<p?n=+s:0/(n=0)):n+=p=+s,t=n=0)&&t+n)(a)+g(b),'1') ``` [Try it online!](https://tio.run/##rZTfbpswFMbv9xRWpTbHtROOAbcB7STXe4FpUpQLmtB0I3JQQVMu9u6ZjyFR1dJKGzWywebP7/j7PvGr@F00m@efdTt1h215eqRTQYsHWsATgdOVpIVbPoGLDP5BXSmUalVdz5crXektVcqPvlcKjlTdWqmP@ujnR7XlHu7ieuWuDa7zavZc1mXRgpPrfDKRADtqaNHw8r7YlFBTNMPbaKd5dVovoVXUfK2XLm@mTtfdNakmxwgcoZS5U1T7Bd0Sz29uWuUkFFLt4EHqiZnI0@bgmsO@nO0PO3iEK3MlwyDFyBZFwhgBRihhBIlYfnlN6lDjWUyyAmJPij0pFUTi2/e3PMs8O35rYWcoIPVA64FZAP54C0Q@PkFPBoZveT0T7AVNzCCw0/STgGxgzMCEHUzeB45V9Qy0PS9lXvoub7SJPe@MYxdjO2xgH1N@@r9VDTiLITVxwjm946Bmw8Qup@MsvETGAzmnzEtwkNcDx3nY87xGnJks7T3M5gNIDFDEPtMdvVu93GG58eOKAvLyln@cFQ6O@U2bOOEa/MjeJvY@@/dCBrs9v8SwrsBXhXzQuxNfvKhxfn8X/iK@ydNf "JavaScript (Node.js) – Try It Online") ### Parsing the input strings ``` g = s => // s = input string s.replace( // search in s: p = /.0*/g, // each non-zero digit followed by some 0's s => // given this substring s: s - p ? // if s is not equal to the previous match: ( // t += // add to t: s < p ? n // either n if s < p : s - n, // or s - n otherwise (e.g. 1 10 -> 9) p = // set p to: s < p ? n = +s // s (also loaded in n) if s < p : 0 / (n = 0) // or NaN otherwise (and set n to 0) ) // : // else: n += // add s to the accumulator n p = +s, // and copy s in p t = n = 0 // start with t = n = 0 ) // end of replace() && t + n // return the sum of t and the accumulator ``` ### Formatting the output ``` h = (n, k) => // n = number to convert, k = current prefix n ? // if n is not equal to 0: h( // do a recursive call with: n / 10 | 0, // floor(n / 10) k + 0 // a '0' appended to k ) + // end of recursive call [ // append: k % 8 ? // if k is not equal to '1000': [ , // 0 : nothing k, // 1 : k --> e.g. '10' d = k + k, // 2 : k+k --> '1010' d + k, // 3 : k+k+k --> '101010' k + (x = k * 5), // 4 : k+(5*k) --> '1050' x, // 5 : 5*k --> '50' x + k, // 6 : (5*k)+k --> '5010' x + d, // 7 : (5*k)+k+k --> '501010' x + d + k, // 8 : (5*k)+k+k+k --> '50101010' d + 0 // 9 : k+k+0 --> '10100' ][n % 10] // select the correct entry : // else: k.repeat(n) // just repeat '1000' n times ] // : // else: '' // stop the recursion ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~24~~ ~~23~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εDSĀÅ¡J.XJ.v}O.XS.vJ ``` -3 bytes thanks to @CommandMaster [Try it online](https://tio.run/##yy9OTMpM/f//3FaX4CMNh1sPLfTSi/DSK6v114sI1ivz@v8/2tDAwMAQisDQVEcBKgYXByJTA9NYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1tdgo80HG49tNBLL8JLr6zWXy8iWK/M67/O/@hoQx3DWJ1oQyAFpk11TEGUARBCJIAsoBSCCZNGqAPpBdKmMDUgM2BsEAeqxQDMBSGoIqgQXBhkhgFhtVixKUyHKciU2FgA). **Original ~~24~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` X3FD5*x}r)D.X:.vO.XS.vJ ``` ASCII only. :) [Try it online](https://tio.run/##yy9OTMpM/f8/wtjNxVSrorZI00UvwkqvzF8vIlivzOv//2hDAyA0NNQB0aaGsQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f8IYzcXU62K2iLNymIXvQgrvTJ/vYhgvTKv/zr/o6MNdQxjdaINgRSYNtUxBVEGQAiRALKAUggmTBqhDqQXSJvC1IDMgLFBHKgWAzAXhKCKoEJwYZAZBoTVYsWmMB2mIFNiYwE). **Explanation:** ``` ε # Map over both integers in the (implicit) input-pair: D # Duplicate the current integer S # Convert the copy to a list of digits Ā # Check for each digit that it's NOT 0 (0 if 0; 1 otherwise) Å¡ # Split the number on the truthy (==1) values J # Join each inner list together .X # Convert each from an integer to a Roman Numeral J # Join it together to a single string .v # Convert it from a Roman Numeral to an integer }O # After the map: sum the two integers together .X # Convert this sum back to a Roman Numeral S # Convert it to a list of characters .v # Convert each character from a Roman Numeral back to an integer J # Join them together # (after which the result is output implicitly) ``` ``` X3FD5*x}r) # Push list [1000,500,100,50,10,5,1]: X # Push 1 3F # Loop 3 times: D # Duplicate the current value 5* # Multiply the copy by 5 x # Double it (without popping) }r # After the loop: reverse all values on the stack ) # Then wrap the entire stack into a list D # Duplicate this list .X # Convert each to a Roman Numeral: ["M","C","D","L","T","V","I"] : # Replace all integers to these characters in the (implicit) input-pair .v # Convert both strings from Roman Numerals to integers O.XS.vJ # Same as above ``` ]
[Question] [ Write a program that translates an arithmetic expression to a Brainfuck program which evaluates the expression and prints the result in decimal numbers. For example, this arithmetic expression, ``` 2 * (3 + 4) ``` can be translated to Brainfuck as, ``` ++ 2 >+++ 3 >++++ 4 [-<+>]< add <[>[->+>+<<]>[-<+>]<<-]>[-]>>[-<<<+>>>]<<< mul [->+<]>[>>>>++++++++++<<<<[->+>>+>-[<-]<[<<[->>>+<<<]>>>>+<<-<]<<] ++++++++[->++++++<]>[-<+>]>>>>[-<<<<+>>>>]<[-]<<<]<[.<] print decimal ``` The Brainfuck program doesn't take input. However, each integer constant or operator in the original expression must have a distinct translated form contained in the resulting Brainfuck program. This is the definition of an arithmetic expression. ``` primary-expression integer-constant (arithmetic-expression) multiplicative-expression primary-expression multiplicative-expression multiplicative-operator primary-expression additive-expression multiplicative-expression additive-expression additive-operator multiplicative-expression arithmetic-expression additive-expression additive-operator + | - multiplicative-operator * | / integer-constant a decimal constant in the range [0-255], which cannot start with '0' unless the number is 0 ``` In other words, a `multiplicative-expression` is evaluated before an`additive-expression`. An `arithmetic-expression` enclosed in parentheses is evaluated prior to the outer expressions. Otherwise, a chain of expressions is evaluated from left to right. All whitespaces are ignored. The Brainfuck machine to run the output will have 8-bit cells, each holding an unsigned integer. It is guaranteed that `255 + 1 == 0` and `0 - 1 == 255`, so you can use this fact to implement your Brainfuck operations. At the same time, you may safely assume that the initial input of an arithmetic expression does not overflow or underflow during its evaluation. This is a `code-golf` challenge. --- The print function in the example BF code won't print anything if it reads 0. However, your program's BF output should print 0 if the result of the expression is 0. This BF function for example will print 0 for 0, but it's longer. ``` >>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>] >[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<] ++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]< ``` You are free to find or make a shorter version for any BF operation. [Here](https://esolangs.org/wiki/Brainfuck_algorithms) is a list of common operations implemented in BF. [This](https://copy.sh/brainfuck/) is a webpage where you can test BF code and also look at the memory dump. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~427~~ 417 bytes ``` s=>[...(a=s.match(/\d+|./g),o=[],d="+-/<>[]./",Buffer("kla`XslY`^KfMflY[`d^[jY`^jYa^ZeaXedfmY`f`t[[KfdM[CdtkqkqSMDsldd@@@@@[[MDd`iK^]kadX[fdD[Y^s@@@@MD@@XfMCtddM[[`dtkq[sk_V").map(c=>d+=d[c&7]+d[c/8&7]),g=S=>!(s=a.shift())|s==')'?o=[...o,...S]:g(S,s<')'?g([]):1/s?o.push(s):(h=_=>/u|[+-][*/]/.test(S[0]+s)?S.unshift(s):h(o.push(S.shift())))()))([]),'<'].map(s=>1/s?">"+"+".repeat(s):d.split`/`[d.indexOf(s)+3]).join`` ``` [Try it online!](https://tio.run/##PVBRj9MwDP4t9IElS5fADQmYlm7i9jZVPFRCKya9RE3Sdu21vbk78bD/PtIDkUi2Y/v7/Dln82qwvDTjtOoH6@5e3lEmwDknRiJ/NlNZE/HLshsXFY0HCSq2MmIrsU1AcRHF367euwuJ2s7oE3a5Lo4@9V0O2hZwDs9zboqfzpyc9c@59noCOHqbwqOd2pf2JUsP2Fm7nw9AerC6ORaqNfYE3h4gL3CupIf9/uTTx8kGZKAOUMD26UdEg8aRlDKxTFoo339WLDjxJQQ0rmQmk3cEpeFYN34ilN5QygVd7MImYckhDiZTm4pkMW7nfEVA0c1HgbuBj1esCdINqeWTTMT1BmylYCmU4JPDiWTwQTGku4xf@7/8obkm/4DZ/5mUzmYmjhfbhXpTHH55HhIlEQuXX9zozBvechy7ZtJCg@VNb93v7z7k2VpRfh6aXut7OfQ4dI53Q0U8iR6W5IGtl5/o6qtYR5Te/wA "JavaScript (Node.js) – Try It Online") [Try the Brainfuck code online!](https://tio.run/##jY5LCoIxDIQPFOIJhrlIyEIFQQQXguevk@Qv4s7Slry@mVxe5/vz9r4@1qLZ3H6GYDgVA6kIxgS8wmTlUIVVw27@DbR@H46RMP1qMgaUTE@2wA8ttePBOxUqTL2vqqG3KhGjB2q8C6zlkJzAIYvcTM0PvLfndm7rw1sE4oRc6wM) This is using the BF code provided in the challenge and [the division algorithm suggested by Nitrodon](https://codegolf.stackexchange.com/questions/239625/translate-an-arithmetic-expression-to-brainfuck#comment541448_239637). ### Brainfuck compression The BF code snippets are joined together with `/`'s. The resulting string is compressed by turning each pair of character codes \$(a,b)\$ into a single character of ASCII code \$N\in[64\dots 116]\$: $$N=a+8b+64$$ where \$a\$ and \$b\$ are computed according to the following table: ``` + - / < > [ ] . 0 1 2 3 4 5 6 7 ``` Hence the decompression code: ``` d = "+-/<>[]./" Buffer("... compressed data ...") .map(c => d += d[c & 7] + d[c / 8 & 7]) ``` [Try it online!](https://tio.run/##HYzBjoIwFEX3fMULC4UQYTmzGAxRdqQrE0PnhU4bXmugVdB2/H1E7@qe3Jw7qqfy/WOYw@42kV4WghLibFf87LHLizg6/BujH0lsnZKtd1yKxjDjOEoSOK44ciV@tWo1mSuXRgbExhDDIwV7t/cTq70jqt5BZDXJoRGdVdSioRq58O@F1VXVGnYMtJrr9aqit3/nOI3yq5qTHso9EGQlEPawga8Osk8t4PuDaRT1081PTuduuiSU@9kNIdkW2zRdlhc "JavaScript (Node.js) – Try It Online") ### Infix to postfix conversion ``` s => ( // s = infix expression, as a string a = s.match(/\d+|./g), // a[] = s split into numbers and operators // (including parentheses) o = [], // o[] = postfix output, as a list g = // g is a recursive function taking S => // an operator stack S[] !(s = a.shift()) | // s = next entry extracted from a[] s == ')' ? // if s is undefined or ')': o = [...o, ...S] // append S[] to o[] : // else: g( // recursive call: S, // pass S[] unchanged s < ')' ? // if s is '(': g([]) // recursive call with an empty stack : // else: 1 / s ? // if s is a number: o.push(s) // push it in o[] : // else (s is an operator): ( h = _ => // helper function: /u|[+-][*/]/ // if S[0] is undefined or S[0] is .test(S[0] + s) ? // '+' or '-' and s is '*' or '/': S.unshift(s) // insert s at the beginning of S[] : // else: h( // recursive call: o.push( // extract the first entry of S[] S.shift() // and push it in o[] ) // ) // end of recursive call )() // initial call to h() ) // end of recursive call )([]) // initial call to g() ``` [Try it online!](https://tio.run/##fVTLkpswELz7KyZ7QfIDkt1cQsXxR3AkVEoLApTFEiWJjbdq/90ZAX5gHjq4XEjT09M9M3/ZOzOpFrXdSZXxcw77s4H9LyAwc4IA8AEImYsT8FOtuTFCyS0wAwyM1UIWK8C/ezD@kdm0JMHvbPPpBwXdXiFYnLgHYOpKWASzCmRzfOUaQWQGquaaWaXNChYPInWHCJlWTYa5oWaaS1tyww3FcIV54mQ7F65aIrUy1tWjGls3tq@lEsYiQIH3C/kLEO6x5mmjjXjnkDcytagIWPbWaRE5QecRmLzWi/qx9A2iOMGwL8QJzXxTitwSSuFz5ILkJwtYrf5AK6xmqeUZ5FodncAIgW/24FEPDpOZRY4vkH4jM54LibFIAZ@Hreytcr7vqy3gb5Q8yM7qmqNVyBXQPdXmC5e94pXhHXZBFi29qZmyqgr7Loi2i11QM2NaOmhAyWTBsz7OwM9JEfq4iwoe8cJrvxUkTuh8vw0Jwj9hS@cjP9b2ozOxRwqXO/emiDvfwNl6mEt6Icr6WQnvpkP5dWNKYuhUIGqDl9BOWu/UErtrnGMHpMt5a1J6n5dAiW3yZ9Dhd3lLXmHUdSbCwTwHzWe82SXxOkiCUWRbbhR/TUYN2n8cQPmWG0vamw2gCIchlLfx2tbeee166exed98CL3zYMpHfyG7oOjkHUMhLGq4tgjALuGfglRdCSrd6VN6P7u2E8@qO/e81IwsBc7Mx6oTpYLjsiZZ5LrS57I8J7hc1@gU0hebUnOmty6EPxayWrkcp3IpBasOi7yAooUsKCymsYFU3pbimSkJXU1kfgqez0smdcL9PH7IVhJ5TJY2quF@pguTk6XlNnjcv6@909yN4eaL0/B8 "JavaScript (Node.js) – Try It Online") ### Brainfuck output ``` o => // o[] = postfix list [...o, '<'] // append a '<' to trigger the 'print' .map(s => // for each entry s: 1 / s ? // if s is a number: ">" + // append a '>' "+".repeat(s) // followed by '+' repeated s times : // else: d.split`/`[ // split the BF code snippets d.indexOf(s) + 3 // and append the relevant one ] // ).join`` // end of map(); join everything ``` [Try it online!](https://tio.run/##fVJRb9owGHzPrzjlYSFLSbR10rZSGGrRXlC0h0kTzAqLi20wGDuNXVZ@PbPJVE0T1A8nf/q@O9/Z3tA9tctWNq6vDeNHhiHirF/cjkiVF/EgunsSgre9eKtoPbNqXi@mohRqTmq2IBtfbuZ08ZPTGWdiN69F7QiZClaSe@a2j9vH7@XEKsbGYRFSTlgtp4tqS9mMCDYh84UNnXIyHs9Eee@YZ3ppTyV2@@tHnEb5jja9JYYjMGRDMLLEG3yskJ22BT6dynQQRQLDowmDF1dRwJDKR2yMdUI@Q0nrIpLnublCcptU5zm0abhmoGEEzsC1crXiLdyaI2laqV3S2bSXTvciwrTgdLkG1649wN5EwDvv3@LLJQoghe9L64/WT7sH3gYSEI9iH/8iCf8YHiUdI4vzljecup5NzzGEUcr85gwPByRZgm7Y1xZO7rj1Kjd49WIBrizvDLLcNkq6uqjJeYOn9un@7r5i6T8erJbetLNRN8dyqRl//iaC3wzX/wcM6bqQQaTliu@pdjCanwSqV5xGab4xUtf1xShB1giEF00HCMPge94e3Frq1XFptDWK58qseqJHkLxPrv7CdYAPAd4GyF52n1@6RYB@gipNj38A "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 675 bytes ``` import shlex s,b,o=[],'',{'+':'[-<+>]<','-':'[-<->]<','*':'<[>[->+>+<<]>[-<+>]<<-]>[-]>>[-<<<+>>>]<<<','/':'[->>>+<<<]<[->+>>+>-[<-]<[<<[->>>+<<<]>>>>+<<-<]<<]>>>>>[-<<<<<+>>>>>]<[-]<<[-]<[-]<'} for c in list(shlex.shlex(input())): try: b+='>'+'+'*int(c) except: if c=='(':s+='(' elif c==')': t=s.pop() while t!='(':b+=o[t];t=s.pop() else: while len(s)>0 and s[-1]!='('and c in'+-':b+=o[s.pop()] s+=c for c in range(len(s)):b+=o[s.pop()] print(b+'>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]<') ``` [Try it online!](https://tio.run/##dVLbboMwDH3nK7KnJA2h2zppEjP5kSgPLUtXJAYIMq3VtG9ndkIvmrYITI5zzgHbDKdw6LvNPDfvQz8GNh1af8ymfJf3lXU55/kXV7zkVoMyDnjOdUI6oRUisMZqo4wCcGYhgqatM4QBM4ZyJFhHOWJkg4MoxEtbVIAFuJ6ZtNHISiB5JTfyQ3@IgW7@ne37kdWs6VjbTEHESooYRdMNH0FIKcuMhfGEke1UxQ2Wpviq6YKoZcb8sfZDoMNmz@qq4oKXk6IHpny7JCUnBgvVVAz9ICSBz0PTehbuogSdexvcyy3Dt5Mvr8zWd2KS5p5tu1c2Wf3gopQQFcCVXmwWB0dS/JT6WuO47d68SEbyF3kYqaSd4tjAy4LUa22p4TgclSYVUWwrxGlRp29EqPlfcR7xIqDjZSGhoEEpYtBcyQfcmXd5A1oUkQF/WiwTTr@enOfHldioJ7l@/gE "Python 3 – Try It Online") **Example:** Input: `(8 - 4 / 2) * 7 + 1` Output: ``` >++++++++>++++>++[->>>+<<<]<[->+>>+>-[<-]<[<<[->>>+<<<]>>>>+<<-<]<<]>>>>>[-<<<<<+>>>>>]<[-]<<[-]<[-]<[-<->]<>+++++++<[>[->+>+<<]>[-<+>]<<-]>[-]>>[-<<<+>>>]<<<>+[-<+>]<>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]< ``` Output of brainfuck program: `43` ]
[Question] [ ## Background [**Shadow transform**](https://oeis.org/wiki/Shadow_transform) of a 0-based integer sequence \$a(n)\$ is another 0-based integer sequence \$s(n)\$ defined with the following equation: $$ s(n) = \sum\_{i=0}^{n-1}{(1 \text{ if } n \text{ divides } a(i), 0 \text{ otherwise})} $$ i.e. \$s(n)\$ is the number of terms in \$a(0), \cdots, a(n-1)\$ that are divisible by \$n\$. \$s(0)\$ is always 0 because there are zero terms to consider, and \$s(1)\$ is always 1 because \$a(0)\$ is always divisible by 1. \$s(2)\$ may have a value of 0, 1, or 2, depending on how many terms out of \$a(0)\$ and \$a(1)\$ are even. ## Challenge Given a non-negative integer \$n\$, compute the number of distinct shadow transforms of length \$n\$. This sequence is [A226443](http://oeis.org/A226443). The following is the list of first 11 terms for \$n = 0, \cdots, 10\$, as listed on the OEIS page. ``` 1, 1, 1, 3, 12, 48, 288, 1356, 10848, 70896, 588480 ``` **Explanation:** Let's call this sequence \$f(n)\$. * \$f(0)\$ counts the number of empty sequences, which is 1 (since `[]` counts). * \$f(1)\$ counts the possible number of `[s(0)]` which can only be `[0]`. * \$f(2)\$ counts `[s(0),s(1)]`s which can only be `[0,1]`. * Since `s(2)` can take any of 0, 1, or 2 independent of `s(0)` and `s(1)`, \$f(3)\$ is 3. * `s(3)` is also independent of `s(0)` through `s(2)` (because 3 is relatively prime to 2) and take a value between 0 and 3 inclusive, so \$f(4) = 3 \cdot 4 = 12\$. * Finding \$f(5)\$ is slightly more complex because `s(4)` is tied with `s(2)`. If `s(4) == 4`, all of `a(0)..a(3)` must be divisible by 4 (and therefore even), and `s(2)` can only be 2. If `s(4) == 3`, at least one of `a(0)` or `a(1)` must be even, and `s(2)` must be 1 or 2. Therefore, \$f(5) = 12 + 12 + 12 + 8 + 4 = 48\$. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") I/O does NOT apply. The shortest code in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes Thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs) for the fix. ``` %Lċ0 *ṗ’ÇƤ€QL ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//JUzEizAKKuG5l@KAmcOHxqTigqxRTP///zM "Jelly – Try It Online") The first line computes the shadow transform. The second line looks at the shadow transform of all sequences of length `n` with elements in `{1, 2, ..., n^n}`. [Answer] # [Python 2 (PyPy)](http://pypy.org/), ~~228~~ 225 bytes This is based on the first PARI implementation on OEIS and computes terms up to \$n=6\$ on TIO. ``` import math,itertools as I L=math.log R=range n=input() P=k=r=1 while k<n:k+=1;r*=k**int(P%k*L(n+.5)/L(k));P*=k*k print len({tuple(sum(x%o<1for x in s[:o])for o in R(n))for s in I.product(*[[i+1for i in R(r)if-1<r%~i]]*~-n)}) ``` [Try it online!](https://tio.run/##JY9Pa4MwGMbv76cIgpDE6Wa37mDNByh4kLKbeJA2rSGahNfIlLF@dbe0x9/zDx63@t6aXepWt27fvRok@cJZFkQu8kyiKNrU6Cx6Mna@f1Feord2mEg3kSNUIqjZYG9wEtiZmwQjlHGzpwxqoQWKHJ6jujSFTkR@QC4058p4WseaV9Qk2Z69VlQzdqiDp8Hhv00GaeiPn90g6TSPdIltmV8tkoUoQ6amsC0LaAOeqGEPmgIdM4f2Mp895U2jkkdLPWPI1DXNS4zvqm35PTXsl23h5RvksIN3@IA9fP4B "Python 2 (PyPy) – Try It Online") --- Naive bruteforcing is obviously a lot shorter (100 bytes): ``` lambda n,R=range:len({tuple(sum(s/n**(n*x)%n**n%o<1for x in R(o))for o in R(n))for s in R(n**n**2)}) ``` [Try it online!](https://tio.run/##Lc3BCsIwEATQu1@xl9LdEBELXor1I3r2EjHRQLoJSQoV8dtjY73NGwYmvPLTc1fMcC1OTbe7ApbjEBU/dO804zvPwWlM84TpwEIgi4WaNXDjz0fjIyxgGUb0RFV@E29Kf61zITr6UKmtre3vAk/U7wBCtJzBSmj3l1aCQUvlCw "Python 2 – Try It Online") Crashes for \$n=4\$ with a *MemoryError*, when `R(n**n**2)` tries to create a list of \$2^{32}\$ integers. ]
[Question] [ [Dotcomma](https://github.com/Radvylf/dotcomma) is a simple esolang I made a while ago that only uses four operators: `[.,]`. In this challenge, you'll determine if a dotcomma program consisting only of `[.]` halts. Without `,`, there is no input, output, or queue, making this challenge possible. **Blocks:** Any code wrapped in `[]` is a block. All blocks and operators (`.`) have a return value. The inputted program will always consist of a single block, and the brackets will always be properly nested. **Operators:** The `.` operator's return value depends on what it is preceded by: * **Any number of blocks:** The sum of the blocks' return values * **A dot:** The previous `.`'s return value will be kept * **The beginning of a block (`[`):** `1` If a `.` is followed by a block, it will be treated as a loop. The loop will run only if the `.`s return value is not `0`, and if the block being looped returns `0` at any point it will terminate. If a `.` is followed by the end of a block (`]`), the `.`'s return value will be used as the block's. Otherwise, a block's return value is `0`. **Examples:** ``` [] ``` Returns `true`. There are no loops. ``` [[].[]] ``` Returns `true`. The `.` takes the return value of the first nested block, which is `0`, skipping the second. ``` [.[]] ``` Returns `true`. The `.` returns `1`, but the loop terminates immediately as the block returns `0`. ``` [.[.]] ``` Returns `false`. The `.` returns `1`, and the block being looped returns `1`, creating an infinite loop. ``` [[.][].[.]] ``` Returns `false`. The `[.]` returns `1`, which is added to the `0` returned by the `[]`, resulting in `1` and causing the loop body to be run. **Other:** You may return a truthy/falsy value in your language (representing either whether it halts or does not, your choice), or two consistent values for halting and non-halting. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes (per language) wins. [Answer] # [Python 3](https://docs.python.org/3/), 215 bytes ``` m,v,*d=-1,[], L,*l=0, for c in input(): if c>"[":a=v.pop();l.pop()*a and exit(1);d.pop();d or exit(0);v[m]=v[m]*(d[m]%2)+a;d[m]=1 elif c>"Z":l+=[L and v[m]];v+=0,;d+=0, else:v[m]=v[m]if d[m]else 1;d[m]=2 L=c<"A" ``` [Try it online!](https://tio.run/##PY7RCoMgFIav8ylEGKi5qHanc7D7nmDiRWSxwEq2JtvTO60xOPzn8J//fBz3We/LfAphYp5RI48VU5qBhlErSwaG5QE7OM6x3GvFhINsHGB3QQrxVvrCLQ4TYfdOW9jOBvbvccUVEea3NTBCNrMkwqtJyyQUm6iHmuStSJOsQNbbHX5D3OZSNRsuhbXweXxHmKQp9@z5nxRvEiCZsNpZNcga2Z3RFYWgVKGVLqLqLw "Python 3 – Try It Online") Exit code 0 if it will halt, 1 otherwise. This is just a naive implementation of the interpreter, but golfed down. [Here](https://tio.run/##dVDBasQgED0nXzEsFJSmIdneCl77BXsTKaEaVhCVxJTt16ejm6Rmm4IH5817b96M/w5XZ1/nWaoeejLSt7KQLnx1ZlLAgIvfclRhQYxzfvmOVzcZ@bEgTVn0boBP0BZGdCp0jwVjcOKnWCZl3XmvrCS5tLMS1jn8pRU0kvfe750ZVYRX3urT0BzFlLuGMlsGcc@ANLTbXLzzJDkgL8VLQEqEhKQo1E0H0v6Zk0t3V4q3yZTNASluCU9wvtPy3eGZxckRV7jyAWHrF4@GDC7DpP4/3ma4b68ijGhdeIx5mKAtD8efEfaDtoGsvSq3q9KJK8jG07kn2vopEEpnzmtRc3y1ED8)'s a ungolfed version with debug output. +12 bytes to fix a bug -8 bytes thanks to Unrelated String [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „[.Å?·.$Δ„..¤:„[]0:…[.]1:DS„0.ìK}„1]å ``` Outputs `0` if it halts; `1` if it does not halt. I'm not 100% sure if my approach is correct. It does work for all test cases, including those mentioned in the comments of the challenge and the Python answer. If there is any test case it'll fail for, I'll delete and try to fix it. [Try it online](https://tio.run/##yy9OTMpM/f//UcO8aL3DrfaHtuupnJsC5OnpHVpiBRKNNQBSy6L1Yg2tXIKBAgZ6h9d41wIZhrGHl/7/r6SkFK2npweUjwUyAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn2ly/9HDfOi9Q632h/arqdybgqQp6d3aIkVSDTWAEgti9aLNbRyCQYKGOgdXuNdC2QYxh5e@l/nf3QsV3R0rF50LJCGk3oQQT2IAJAJEweaAxLQi0VwEGJIQrEgBgA). (NOTE: Wrap the input of the singular TIO in `"""` quotes, otherwise it'll interpret the input as a list and gives an error.) **Explanation:** ``` # If the input starts with "[.", remove it: „[.Å? # Check if the (implicit) input-string starts with "[." · # Double this (0 if falsey; 2 if truthy) .$ # Remove that many leading characters from the (implicit) input Δ # Keep doing the following until the result no longer changes: # Collapse all multiple adjacent "." to a single ".": „.. # Push string ".." ¤ # Push its last character (without popping): "." : # Keep replacing all ".." to "." until none are left „[]0: # Replace all "[]" with a 0 …[.]1: # Replace all "[.]" with a 1 # Remove all "0.x" substrings, where `x` can be any character D # Duplicate the string S # Convert it to a list of characters „0.ì # Prepend a "0." in front of each K # Remove all those substrings from the string }„1]å # After the loop: check if the string contains "1]" # (after which the result is output implicitly) ``` I could also add an additional remove of all `"1."` within the loop, and then check if the final result contains a `1`, but just checking if it contains a `"1]"` is shorter. ]
[Question] [ With all the gyms closed down with the COVID-19 situation, we have to exercise with the weight we have lying around at home. The problem is, we have a small selection of plates at varying weights, and can't immediately determine if we can create a setup at the desired weight. Given an unsorted array of weighted plates and an unsorted array of barbells of different weights, determine the fewest amount of plates you need to put on a barbell to reach the desired weight, in ascending order mirrored at the halfway point, basically mirroring how it would be loaded on a real barbell (see example output). The plates have to be in pairs; you cannot use a particular plate an odd number of times since you put one plate on each side for equilibrium (e.g. every plate of a certain weight on one side should have a counterpart of the same weight on the otherside). If the desired weight cannot be achieved, approximate as closely as possible (while still maintaining equilibrium on both sides). **Examples**: **Input** (3 barbells, a set of plates, and goal weight): `[[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 47]` **Output** (exact match, barbell and plate arrangement): `[10, [3.5,15,15,3.5]` **Input** (3 barbells, a set of plates, and goal weight): `[[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 45]` **Output** (exact match, barbell and plate arrangement): `[45, []]` **Input** (3 barbells, a set of plates, and goal weight): `[[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 0]` **Output** (closest approximation, barbell and plate arrangement): `[6, []]` **Input** (3 barbells, a set of plates, and goal weight): `[[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 9001]` **Output** (closest approximation, barbell and plate arrangement): `[45, [2.5,3.5,15,15,3.5,2.5]]` Winners will be selected first by time complexity, then character count for tie-breaker. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), \$ O(2^{\frac{|P|}4} \times (|B| + \frac{|P|}2)) \$, 933 bytes ## Input/Output Format Takes as input a vector of plates \$ P \$, a vector of barbells \$ B \$, and a target weight \$ W \$. It outputs the plate arrangement on the first line, and the barbell on the second line. ``` #include <bits/stdc++.h> using namespace std;using d=double; int f(auto b,auto p,d w){ unordered_map<d,int>u;vector<d>s,A,B; for(auto i:p)u[i]++; for(auto i:u)while((i.second-=2)>=0)s.push_back(i.first*2); int z=s.size(),i,j,k;vector<pair<d,vector<d>>>x(1<<z/2),y(1<<z/2+1);d m=DBL_MAX,n,r; for(i=0,k=1;i<z/2;i++){ for(j=0;j<k;j++)x[j+k]=x[j]; for(;j<k*2;j++)x[j].first+=s[i],x[j].second.push_back(s[i]/2); auto _=x.begin();inplace_merge(_,_+k,_+k*2);k*=2; } for(k=1;i<z;i++){ for(j=0;j<k;j++)y[j+k]=y[j]; for(;j<k*2;j++)y[j].first+=s[i],y[j].second.push_back(s[i]/2); auto _=y.begin();inplace_merge(_,_+k,_+k*2);k*=2; } for(auto f:b) for(i=0,j=(1<<z-z/2)-1;i<1<<z/2&&j>=0;n>w?j--:i++){ n=x[i].first+y[j].first+f; if(abs(n-w)<m)r=f,A=x[i].second,B=y[j].second,m=abs(n-w); } A.insert(A.end(),B.begin(),B.end()); sort(A.begin(),A.end());for(auto i:A)cout<<i<<' '; reverse(A.begin(), A.end());for(auto i:A)cout<<i<<' '; cout<<'\n'<<r; } ``` [Try it online!](https://tio.run/##nZNdb5swFIbv@RVWJzVQDAVCV622mYh6ud1PaiPEh5MagkEYmqZVfntm41JlSyd1vUCY93z4ee1D3rbOOs8Phy@M55uhoABnrBeXoi9y23YfImMQjK8BT2sq2jSnQEaQ1gpSNEO2ochgvAcrMx36BmRwfLWwAFvrxRh40xW0o0VSpy0uoMyMBvRI877pcBEJGMMFMlZNp6vZTWsNd2xp23@Ig7V9YBtqmswVNG944ZDAiohnCbcdxEOSpXklYyvWif4isDTQMxGuYM/UtCCDJaymXduUya3hG0MUPZk@xs@XgQV3ryvbt1ABanK7@JH8jH9BDjsNxIgHK@IjprIQs23pUekl8VCJK1RK5emutKslka@lLlKRi2CKLTWnTYQ0CkdBmzryokKXysh4AAl5cjO6Zty0EOPtRl5DUtNuTc0EJnalHuW6uiABMvbjlq@M/yDcacLde4S7vwl3HyLc/S/hWLe6yay3cy3JePqOuglH4eu7OD8v5VUjHm2/l45zox1xebxs4jxCXsm7l5OYCZM7WwvXVkdWMNbJ2gNckCNHsCZTsgKLXcYF7Xozdikv5OQsJltyNSoyTTRjwhSIp8DRwMZW3gw9xgzjGZgho6OPtBP0qAp8pEx/ze75DGM5gPuDmus6VQ3AiwGmER7/wghkPiDgxfcgCK8g@LqHoB2VuSs/59cQBDLky3WghLfFGL6C13sEdCewVWXhNTLkT535qg2UmnQOFBDAGJzd83t@JoVTiOAEIvgchCoLrzREoNpIiOA9iFOG@QnD/HMMqszTCHPVRSLMP4YQniCEn0NQZd88z9cUoWokKcL3KPaH3w "C++ (gcc) – Try It Online") ## Explanation The algorithm calculates all possible subset sums \$ S \$ of \$ P \$, and then finds the sum \$ s + b \$ which is closest to \$ W \$, where \$ s \$ and \$ b \$ are elements in \$ S \$ and \$ B \$, respectively. Using the meet-in-the-middle approach decreases the complexity quite a bit. (I'm aware this code is super long, and I'll try to shrink it a bit eventually). [Answer] # [Python 2](https://docs.python.org/2/), \$ O(2^{\frac{|W|}2} \cdot |B| \cdot |W| + |W|^2) \$, 203 bytes Naive implementation, looks at all combinations of possible weights \$W\$ and barbells \$B\$. ``` lambda B,W,T:min([(w+w[::-1],b)for w in p(sorted(sum([W.count(x)/2*[x]for x in set(W)],[])))for b in B],key=lambda(a,b):((T-sum(a)-b)**2,len(a))) p=lambda l:l and[l[:1]+x for x in p(l[1:])]+p(l[1:])or[l] ``` [Try it online!](https://tio.run/##lY0xb4MwEIX3/Iobz3BJgYRGtZQlUrp2QWJwPUDiKCjGWMYI8uspNGl3pnf39L337MPfGpOMVzjA96iLurwUcKScMl5XBgX2YS84X8eSSnZtHPRQGbDYNs6rC7ZdjSLfnJvOeBzYWxKIQc7YMGOt8pgzSUIy9hsuZ/co6a4eh@cWFlMvR8zWc1XB1iULgoS0MtPD2Mq@ONBcQ2EuQgsey3CA/xGLWsRcMhn@XY0TWo79rdIKMtcpvgLw7jELgHWV8XDFoDK28zhNAKjhrKyH09fnybnGPcHSqeI@ijgi2KUE75JAbDcpbfeURBSnlEzPS2Y/pf2E7ParxZF0cSRanPiIovgH "Python 2 – Try It Online") ### Ungolfed ``` def f(Barbells, Weights, Target): # For every pair of same weights keep one, order them ascending usable_weights = concat([Weights.count(x)/2 * [x] for x in set(Weights)]) usable_weights = sorted(usable_weights) # list all possible combinations of symmetric weights and barbells possible_setups = [(w+w[::-1], b)for w in powerset(usable_weights)for b in Barbells] # Find the one with the weight being the closest to the target, # on a tie take the one with the lowest number of weights return min(possible_setups, key=lambda(a,b): ((Target - sum(a) - b)**2, len(a))) concat = lambda ls:sum(ls, []) powerset = lambda l:l and [l[:1]+x for x in powerset(l[1:])]+powerset(l[1:]) or [[]] ``` [Try it online!](https://tio.run/##lVLBjtowEL3zFSP1YoN3S9ilqJH2Umm59rJSD1a0ssMAFo4d2U4DX0/HCWxb2guneCZvZt68N@0p7b1bnM8b3MKWfVNBo7VRwA80u32ix5sKO0y8nAB8grUPgD8xnKBVJoDfQlQNQj@C4YDYgncowIcNBkh7bEDFGt3GuB116KLSFt@v@BeovatVYvIy7rH2nUvsyD8vYAryWMGWJh7BOIiY2AXFK/6/XtGHhBv2d55PBuLWxATKWmh9jIb@0@RGG6eS8S4Oi5yaBlMw9cc2ym1AXwShJtfKd2LStXmgZP2sl2X5UFQCNM9U@0y19T2GzPeGSgboDLjKXI3k1oYmkVZZOuhN2g/BWAUaSbohUVsfkdZIfgjTYIwYOngHCpLJyQP@28oSISp0XaNxcO3CiGoDLRMcNMaxmwUF2Xl6sarRG8WU0LwExsZrgAeIXcMUp4fm0@lCgEVHMSe5R0tJnrEUbCwzOB@VJOOu4vwBKO2gtbSyLKrZ8bfnH0JaWZQVr2Y3CTozkLKqzv3ekKVvocN8pymc8ocsC8YlOuupcW2XGM9ng8ca2wSv39evIfgwAnVAdTjLYi7geSngC/kpnx6X4mklFnNRLMWCgssn55diRZDn1eTukuXdJfO7K77O58Uv "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), \$O(Wlog(W)+B2^WW) \$, 159 bytes Worst case time, where \$W\$ is the number of weights and \$B\$ is the number of barbells. ``` import Data.List h(a:b:r)|a==b,p<-h r=[a:q++[b]|q<-p]++p|1>0=h$b:r h _=[[]] (b#w)g|p<-h$sort w=snd$snd$minimum[(abs$g-a-sum q,(length q,(a,q)))|a<-b,q<-p] ``` [Try it online!](https://tio.run/##LU3LboMwELzzFUjxAcQ6MklJVIRz6jF/YFnVWkXYKnYMNuLCv1Mc9TCah2Z3NIbffhz33Vj/mmP@hRHPTxNipgtsVTuXG3KuwHdU5zMX2E5VJZTcpo56WVV@qx@Ma3I0M51/cyGkzAp1WsthSzckpK8rD@6HJFjjjF2sKFAFMlCkYbH5BMXYuyHqpBCmsjxWO6rgPbJbNI772bhIRM3go4GbPInruYHrHS4M6gYuh/mnlDdwl@STsXr/Aw "Haskell – Try It Online") I was never good at calculating time complexity, so feel free to correct me if you think I'm wrong. Here's some annotated source code to show some of my thinking: ``` import Data.List -- O(h 0) = 1 -- O(h W) = 2*O(h$W-2) = 2^W h(a:b:r)|a==b,p<-h r=[a:q++[b]|q<-p]++p|1>0=h$b:r h _=[[]] -- O(B#W$_) = W*log(W)+B*O(h W)*W = W*log(W)+B*2^W*W (b#w)g|p<-h$sort w=snd$snd$minimum[(abs$g-a-sum q,(length q,(a,q)))|a<-b,q<-p] ``` The \$Wlog(W)\$ is for sorting the weights and the \$W\$ factor on the second part is for the linear time calculation of `length q` and `sum q`. My implementation is a fairly straightforward brute force approach. I don't even optimize for the ideal case because it's extra bytes and it wouldn't help the worst case time anyway. The idea is to sort the list of weights and pick up on adjacent weights of equal value. I remove them from the list and recur, returning the resulting list along with those results with that weight on either side. In this way I build up a list of all possible weight combinations. Then it's a simple matter of looping over each barbell and finding the setup with the minimum error. I've also tried to ensure that Haskell doesn't calculate some values like `h$sort w` and `h r` multiple times. I believe the compiler can usually optimize cases where it notices redundancy like that but I thought it best to err on the side of caution. ]
[Question] [ Your task is to create a program that determines whether a given string is a valid regular expression or not using code snippets sourced from sites on the StackExchange network. For the purposes of this challenge, the regular expression dialect will be a stripped down and mostly minimal set of meta-characters: `()*?|\`. As such, you will not be able to use built-in regex parsers. * `\` is used to escape meta-characters. It must be followed by a meta-character. * Unescaped parentheses must be balanced * `*` and `?` must be preceded by either a non-meta-character, a parenthesized group, or an escaped meta-character. * All other printable ASCII characters plus newline, tab, and space must be supported as non-meta characters. What happens with a string containing other characters is undefined. * The actual meaning of the regex is not important for this challenge. ## Examples ``` Truthy: abc a? (a|)* () a|b* \* \\ \\* a*b?(cd|e) + [ } (123\))* \| (a(b(c|d)*e)*f)* (|\)*) (abc)+* (abc)+ +abc ^ last test case is an actual newline Falsy: ?abc * ** \ ( a*? a?* ? a) (\) (|\)* \() |* (?:abc) \\** \n ``` ## Scoring Your overall score is the number of snippets taken from questions and answers around StackExchange. * Repeated snippets count for as many times as they are used. * Whitespace can be added and removed freely (because of Python, Haskell, and other whitespace-sensitive languages) and does not count toward your snippet count. + The exception would be if your code is actually written in [Whitespace](https://en.wikipedia.org/wiki/Whitespace_(programming_language)). * Snippets are allowed from any StackExchange site as long as they come from questions, answers, and comments that are older (Including by edit time - use older revisions if necessary) than this challenge. (Sep 24, 2019 @ 3:30 PM UTC) * Snippets can come from anywhere in a question, answer, or comment body, whether it's in a preformatted code block or not. * Splicing a snippet into the middle of another causes the outer snippet to count as *two* snippets Lowest score wins! [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 20 snippets ``` {$_ eq m/[[<-[()*?|\\]>|\\<[()*?|\\]>|'(' <~~>* ')']<[*?]>?|\|]+/} ``` [Try it online!](https://tio.run/##TU5BjsIwDLzzCh9QG7ta0ILEYVWShyQVakoqIdEFyl7QBr7etY1Ae/BkbE/Gc07jcTMNNyh62E6/8x2kCwxL7@sPb5BcDqGxDPW/rjQl1I@HJSixbGpPrrG8yk21vE/X9gbzXVEs2LA/jXA8fKertYuf8TBMAG3sZoyOwaCwHImfoBAUhLYUnen2OYmm4vJcd/n0uVoHRJVn6VsTTZf3SAmp17nJAQl1Fzus6M3ESu7PmLhnEFmSmolKDzvNJzNlahTw5StSDZ7V132J8zM2/QE "Perl 6 – Try It Online") The snippets are taken from: [`{$_ eq`](https://stackoverflow.com/q/4066931/7957532), [`m/[`](http://stackoverflow.com/questions/1112436/how-can-i-check-if-a-regex-pattern-is-valid-in-perl), [`<-[`](http://stackoverflow.com/questions/6346101/replace-vs), [`()*?`](http://stackoverflow.com/questions/344460/why-is-1-empty-in-my-substitution), [`|\\`](http://stackoverflow.com/questions/354724/need-to-test-for-a-backslash-in-this-reg-ex), [`]>`](http://stackoverflow.com/questions/6620047/remove-trailing-from-the-page), [`|\\`](http://stackoverflow.com/questions/354724/need-to-test-for-a-backslash-in-this-reg-ex), [`<[`](http://stackoverflow.com/questions/223556/infix-format-for-nemerle-macro), [`()*?`](http://stackoverflow.com/questions/344460/why-is-1-empty-in-my-substitution), [`|\\`](http://stackoverflow.com/questions/354724/need-to-test-for-a-backslash-in-this-reg-ex), [`]>`](http://stackoverflow.com/questions/6620047/remove-trailing-from-the-page), [`|`](http://stackoverflow.com/questions/96667/whats-the-difference-between-and-in-java), [`'(' <~~>* ')'`](https://stackoverflow.com/a/57883506/7957532), [`<[`](http://stackoverflow.com/questions/223556/infix-format-for-nemerle-macro), [`*?`](http://stackoverflow.com/questions/321299/what-is-the-reason-not-to-use-select), [`]>`](http://stackoverflow.com/questions/6620047/remove-trailing-from-the-page), [`?|`](http://stackoverflow.com/questions/6895304/how-to-add-r-n-in-a-varaible-in-sed), [`\|`](http://stackoverflow.com/questions/5090491/perl-linux-command-not-working), [`]+/`](http://stackoverflow.com/questions/4695338/using-regex-to-extract-information-from-a-file-and-need-help), [`}`](http://stackoverflow.com/questions/67894/why-do-we-need-extern-c-include-foo-h-in-c). This is mostly the greedy approach (made obvious by all the one or two character snippets). I used [SymbolHound](http://symbolhound.com/advanced.php) to search for the individual characters, and the only real optimisation was the `'(' <~~>* ')'` snippet, which is taken from [my own answer](https://stackoverflow.com/a/57883506/7957532) on recursive Perl 6 regexes. ### Explanation: This basically checks if the input is equal to a greedy match of a valid regex. The reason we can't just use the regex itself and add `^$` to mark the ends is because we are using a recursive regex, which wouldn't work if there were `^$` markers. The regex itself is: ``` m/[ ]+/ # Match one or more times [ ] # Any of <-[()*?|\\]> | # Not a metacharacter \\<[()*?|\\]> # A metacharacter preceded by a \ '(' <~~>* ')' # Brackets surrounding a valid regex <[*?]>? # Optionally followed by a ? or * | \| # Or just the | metacharacter ``` ]
[Question] [ When I write documentation, comments, etc. I love making ASCII tables. They usually end up looking pretty good, but I always feel that they could look even better - especially since UTF-8/Unicode includes the [box drawing characters](https://unicode-table.com/en/blocks/box-drawing/). However, these characters are very burdensome to use, requiring several key presses to insert. Your task? Write a program or a function that can automatically convert ASCII tables to the UTF-8/Unicode equivalent. This challenge was [sandboxed](https://codegolf.meta.stackexchange.com/a/16972). ## Challenge Write a program, that given an ASCII table as an input string, outputs the table redrawn with the Unicode/UTF-8 box drawing characters. Specifically, the characters that are a part of the table should be translated as follows: ``` (Unicode, 3 bytes each in UTF-8) - to ─ (\u2500) | to │ (\u2502) = to ═ (\u2550) and + to one of: ┌ (\u250C), ┐ (\u2510), └ (\u2514), ┘ (\u2518), ├ (\u251C), ┤ (\u2524), ┬ (\u252C), ┴ (\u2534), ┼ (\u253C) or, if '=' on either side: ╒ (\u2552), ╕ (\u2555), ╘ (\u2558), ╛ (\u255D), ╞ (\u255E), ╡ (\u2561), ╤ (\u2564), ╧ (\u2567), ╪ (\u256A) ``` ## Details **I/O:** * [Default I/O](https://codegolf.meta.stackexchange.com/questions/2447) is allowed * You may take input in any reasonable format, including the table as a string, or a path to a file containing the table. * You may output to a file and take the file name as an additional argument. + However, **you may not modify the input file**. (It should be retained for ease of future editing) **Input:** * You may assume that every row of input has been padded to be the same length with . * You may not assume that the first character after a newline is a part of the table borders (as it may be whitespace). * Input is considered a valid table if all characters (that are a part of the table) `-=|` are connected to exactly two characters and `+` are connected to at least one character both horizontally and vertically. * Your program may not produce any errors with valid inputs. * If the input is not valid the behavior is undefined and you may produce any output. * The input may contain any UTF-8 characters, including the box drawing characters. **Output:** * Any of the characters `-=|+` that are not a part of the table **must** be left as-is. * Similarly, any other characters must be left as-is. * A single leading and/or trailing newline is allowed. **Other:** * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden, as per usual. * If your preferred language has a built-in that solves this problem, you may not use it. + This means programs, functions, subroutines or instructions that would be valid submissions for this challenge with no additions. * Each of the characters needed in this challenge are three bytes long when they're encoded in UTF-8. **Connected characters**: A character is connected to another, if: * It is `|` and is directly above or below `+` or `|`; * It is `-` and is directly before or after `+` or `-`; * It is `=` and is directly before or after `+` or `=`; * It is `+` and is directly above or below `|` or `+`, or is directly before or after `-`, `=` or `+`. A character is considered a part of the table, if it is connected to any character that is a part of the table. By definition, the first `+` in the input is a part of the table. ## Examples Examples available [here](https://pastebin.com/Wzcr113K) as a copy-pastable version. ``` Input: Output: +------------------+ ┌──────────────────┐ | Hello+World! | │ Hello+World! │ +==================+ ╞══════════════════╡ | This is+my first | -> │ This is+my first │ |+-+ code|golf +-+| │+-+ code|golf +-+│ |+-+chall|enge! +-+| │+-+chall|enge! +-+│ +------------------+ └──────────────────┘ +===+===+===+ ╒═══╤═══╤═══╕ | 1 | 2 | 3 | │ 1 │ 2 │ 3 │ +---+===+===+===+ ┌───╪═══╪═══╪═══╡ | 1 | 1 | 2 | 3 | │ 1 │ 1 │ 2 │ 3 │ +---+---+---+---+ -> ├───┼───┼───┼───┤ | 2 | 2 | 4 | 6 | │ 2 │ 2 │ 4 │ 6 │ +---+---+---+---+ ├───┼───┼───┼───┤ |-3 |-3 |-6 |-9 | │-3 │-3 │-6 │-9 │ +===+---+---+---+ ╘═══╧───┴───┴───┘ +-----+ -> <Undefined> +-----+ -> ┌─────┐ +-----+ └─────┘ +-----------------+ | Hello, World! | | This is invalid | -> <Undefined> | input | -----------------+ ++++ ┌┬┬┐ ++++ -> ├┼┼┤ ++++ └┴┴┘ +--+ ++++ -> <Undefined> +--+ ``` ## Finally... This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the least amount of bytes wins. Happy golfing! [Answer] # [Python 3](https://docs.python.org/3/), ~~914~~ ~~898~~ ~~827~~ ~~823~~ ~~594~~ ~~587~~ ~~569~~ ~~540~~ 469 bytes Edit: significantly changed strategy, now making a bitfield of neighbors (similar to dead-possum's answer). I've left the earlier version below. ``` H='─│═-|=└╘++++┌╒├╞++┘╛++┴╧┐╕┤╡┬╤┼╪' def n(l): def j(r,c,t=0):O=(0,r-1,c),(1,r,c+1),(2,r+1,c),(3,r,c-1);v=f(r,c);b=t|any(f(Y,X)=='='for i,Y,X in O);l[r][c]={'+':H[b+2*sum((f(Y,X)in H)<<x for x,Y,X in O)],**dict(zip(H[3:6],H))}.get(v,v);[f(Y,X)!=';'and v in'+++-|='[i%2::2]and j(Y,X,v=='=')for i,Y,X in O] for i,I in enumerate(l): if'+'in I:f=lambda r,c:l[r][c]if len(l)>r>=0and 0<=c<len(l[r])else';';j(i,I.index('+'));break ``` [Try it online!](https://tio.run/##dVLBattAED1bX7E2FO1mJWPJIVDZm7NzyiXQFtcHRVol665lI22M06pQeu4hFAkCLYVCoFB67LFfsz/izkqOYyftwrA7b97MvBlpca0u52l/vR4xW5cfdPlRVzduwXRZ6uqWwtHlJ1191uVXXX0z3q2uvpj7t65@6PJGV5Uu73T1XZe/dHWnyz@6@mlbMU9QiiUJLGSeU5w5kaNYjwSnDPeczPWciDjYcwCnHrx8J6MN1jeY65HBkiUmjQzOmSrC9Bon@JXzkjBmMzuZZ0g44CKRolMykONsMo4m7J1N7WA0Pqf@QX41w5sU4IzIcLhCJm31kDZxDg5iESn8VizwaNwPjibOiJD33Quu8NJZksG4KdBm9sAO0xgtIdGGrcCK7LF45geBPzH41NCcZa2N7IubWKgBTozL06sZz0LFm@UgkYBiwE@ChMlwdh6HCGYONvOIBElu9nicHbOeadQbsmhYY8AgXOYclA2mGMp3RRrzFYZ6BHaW8fDNuv4OkYdz6NXKuLrKUjSWIld4VatcGUl5N19IobD9OrXJpEnxa3mbFBPoTucixfbm3smWpM5Qq6aJRKxpaLWM7m3XumLD5NDeUJXHUKfTodSiFG7Lap35NYLMoYyxrVk1VCAPzAfro8JC1HXdR6yG8ZS1a9YmauwQ7Oh/LLe/MWC4z2uW6bLLMrJbCEbpN6O4Tw61ClA@4lLO6Yt5JuO2GcQylR4dwzy7FDkSOZ1do0RkuQJmQV2KonnMi4u5TGAvLm3A6DKUsuDpBW834L@6N3tVh3vy6JZ6HxcPezcd3M3C4Q3H2sHrgZXw7@tBKQhY29AiE6nC8DMoj5Ad98zfc1V/3z3cd8Ujdz@50wG3@YvWfwE "Python 3 – Try It Online") Input is in the form of a list of lists of characters, which is modified in place. Recurses from the first + that it finds. ``` x=range C='┌┐└┘','╒╕╘╛' D='┬┤┴├','╤╡╧╞' A='┼╪' H,V,T='─│═' J={'-':H,'|':V,'=':T} K=C[1]+D[1]+A[1]+'='+T E=('+|','+-=')*2 F=['+|'+V,'+-='+H+T]*2 O=(0,-1,0),(1,0,1),(2,1,0),(3,0,-1) for i in x(4): for j in{0,1,2,3}-{i}:F[i+2&3]+=D[0][j]+D[1][j] h=C[0][i]+C[1][i];F[i&2]+=h;F[3-2*(i&1)]+=h def n(l): for i,I in enumerate(l): if'+'in I:r=i;c=I.index('+');break else:return l def f(r,c): try:assert c>=0 and r>=0;return l[r][c] except:return'\0' def j(r,c): v=f(r,c) l[r][c]=J.get(v,v) if v=='+': X=[f(r+Y,c+X)for i,Y,X in O];B=any(x in K for x in X);X=[X[x]in F[x]for x in x(4)];L=sum(X) if L in(2,3,4):l[r][c]=D[B][X.index(False)]if L==3 else C[B][X[0]*2+X[3]]if L==2 else A[B] for i,Y,X in O: if v in E[i]and f(r+Y,c+X)in E[i]:j(r+Y,c+X) j(r,c);return l ``` [Try it online!](https://tio.run/##dVRPa9swFD9Xn0LLobIruSR2GcxBg65dabtCL6FL8XzIHKVR5jrFVktKUxg77zCGDYONwaAwGDvuuE@jL5I92U6adJvgWXrv99P7K3xxrYbjxJvNJjztJWcC7XCi8/c6/6DzXOefCCO6@KiLQhefdPGZoF2D/9T5nc5/6fxLid/p4psuvuviK0HbBv@tix8E7bMT1jHqW52/08UHgg75DXGIv8/IlPgnjHDid27RC74TtEK6az7b5gN22kHPuUXoFAJQhxN7w0V7PDAGelKZ6D7thGA@5laTOS3WtJkFX9aC3WWV7jED2WgwTrHEMsETa8v2ETb6CPQboDOXebfOjbz19wJJ3XUvpHw3aIbBqMoJdoSHkCOYZEhNrrC3gbzuAnUIJ89xNyy53rKNjvpigBMrnseR7MBEFsnluUh7SlQIlgNCCdgP/JTLdsQPNmXSFxOomdjt16novUFYxJnwU6Eu0wTHCBvHAytlUelApdd@L8tEqnD0lDdxL@njFA7t@YUgDYMIcsdiEokLVTsir5qkcjVauLrilVs41rf44eaZUNYVu7LLXIECHSeGjLs8ADo9ZRHt2lWFp6xrajwO2894L7m2JkZ7UZZfHrt2G251g0kIyh5sC8QMJGwf8ezy3OqaWCbYESAwQ4/BsOYJ7QbPwqBbN2mvB52xQ0Pl3Cv7hHdKAkxpw6XdwAtr1K3QbUDB@2q6fh3vymjPYaqmh/e11UZ/tLCgummLHs/KaUctK4NGrtXWIJaZsib2oshsM7uIpbLIq4TYYXXFLd/B2nwoCdkcjaFqUu9Lt2O7vKEmK0HAQWKVge0aFxDUEFSL40ajQSmiFHaE1jpuacFmUc75QlBpmuIWiAvi4SnC1HGcB6yK8TdrWVCNGtkCefw/luPVAgznSckyUZZZJu01DKV4VSnOX4uiKWS@L@J4TF@O07j/yBSCjKcHyzA7Q5lhmdHzazyQaaaAOaUOxdG4L6Zn43gAfXFoZYyGvTieCvgZPqqM/4pe9VVtraRHF9Q5Lu/7biI4dcPhDAst2cuClXTn/sAVAGgBXaQyURY8AdWCcd@rHXdFVd6qurWqygfq6uVGA9TqFc3@AA "Python 3 – Try It Online") Here's the closest thing I have to an ungolfed version: ``` def tr(s): t='┌┐└┘','╒╕╘╛' t2='┬┤┴├','╤╡╧╞' A = '┼','╪' H,V,T = '─│═' Th = ''.join(x[1]for x in (t,t2,A))+'='+T ps = ['+|'+V, '+-='+H+T, '+|'+V, '+-='+H+T] ps2 = ('+|', '+-=')*2 for i in range(4): for j in {0,1,2,3}-{i}: ps[(i+2)%4] += t2[0][j]+t2[1][j] h=t[0][i] + t[1][i] ps[i & 2] += h ps[3 - 2 * (i & 1)] += h l = [list(x) for x in s.split('\n')] r = 0 for i,I in enumerate(l): if'+'in I: r=i;c=I.index('+') break def g(r,c): return l[r][c] def G(r,c): if r >= 0 and r < len(l) and c >= 0 and c < len(l[r]): return g(r,c) return '\0' def process(r,c): v = g(r,c) if v == '-': l[r][c] = H elif v == '|': l[r][c] = V elif v == '=': l[r][c] = T elif v == '+': all=[G(r-1,c),G(r,c+1),G(r+1,c),G(r,c-1)] bold=any(x in Th for x in all) for i in range(4):all[i] = all[i] in ps[i] N,E,S,W=all tt=sum(all) if tt == 3: l[r][c]=t2[bold][all.index(False)] elif tt == 2: l[r][c]=t[bold][N*2+W] elif tt == 4: l[r][c]=A[bold] else: return for i,(dy,dx) in enumerate(((-1,0),(0,1),(1,0),(0,-1))): if v in ps2[i] and G(r+dy,c+dx) in ps2[i]: process(r+dy,c+dx) process(r,c) return l ``` [Answer] # Python 3, ~~392~~ 281 bytes Golfed it quite a bit more and converted to a recursive solution instead of an iterative one: ``` def h(a): def g(i): k=-3;d=a[i]=='=';z[i]='' for p,j,r in zip((1,2,4,8),(i+1,i+w,i-1,i-w),('+-=','+|')*2): if 0<=j<len(a)and{a[i],a[j]}<={*r}:k+=p;d|=a[j]=='=';z[j]and g(j) z[i]="┌╒!!─═┐╕┬╤@@└╘││├╞┘╛┴╧┤╡┼╪"[2*k+d] w=a.find('\n')+1;z=[*a];g(a.find('+')) return''.join(z) ``` Takes a string of equal length rows separated by newlines, and returns a string in the same format. May throw an exception on invalid input. Previous solution: ``` def h(a): i=a.find('+');q=[i];w=a.find('\n')+1;z=[*a] while q: i=q.pop();c=a[i];k=-5 for p,j in enumerate((i+1,i-1,i+w,i-w)): r='++-|='[p>1::2] if 0<=j<len(a)and a[i]in r and a[j]in r: k+=1<<p;q+=[j][:z[j]<'─'] z[i]='│'if c>'='else'─═'[a[i]>'-']if c>'+'else"┌╒┐╕┬╤@@└╘┘╛┴╧##├╞┤╡┼╪$$"['='in a[abs(i-1):i+2]::2][k] return''.join(z) ``` Ungolfed version: ``` def h(a): i = a.find('+') # find index of first '+'. It is first node q = [i] # in the queue of indexes to convert to unicode w = a.find('\n')+1 # width of the table z = [*a] # strings are immutable, so copy it to a list while q: # while the queue isn't empty i=q.pop() # get the next index to process c=a[i] # and the associated character k=-5 # 'k' is the index into the unicode string, U. The way they # are encoded, the first unicode value is at index 5. # directions E W S N for p,j in enumerate((i+1,i-1,i+w,i-w)): # j is the index of an adjacent cell # r='++-|='[p>1::2] is equivalent to: if p > 1: r = '+|' # compatible symbols for vertical connections else: r = '+-=' # compatible symbols for horizontal connections # if adjacent cell index is valid and the characters are compatible if 0 <= j < len(a) and a[i] in r and a[j] in r: k += 1<<p # update the unicode symbol index # q += [j][:z[j]<'─'] is equivalent to: if z[j] < '-': # if the adjacent cell hasn't been converted already q.append(j) # append it's index to the queue if c > '=': z[i] = '│' # replace a '|' with a '│' elif c > '+': z[i] = '─═'[a[i]>'-'] # replace a '-' or '=' with '─' or '═' respectively else: # it's a '+' U = "┌╒┐╕┬╤@@└╘┘╛┴╧##├╞┤╡┼╪$$" # even indexes are single horizontal line, # double horizontal lines are at odd indexes z[i] = U['='in a[abs(i-1):i+2]::2][k] # '='in a[abs(i-1):i+2] is true if there is an '=' to the left or right # so this selects the odd chars from U # then [k] selects the correct char return''.join(z) ``` [Answer] # JavaScript, ~~311~~ 307 bytes ``` X=>(O=[...X],P=(I,j=0,_=0)=>!P[I]&&(P[I]=1,['-─1','|│','=═1'].map(([a,b,n=X.indexOf('\n')+1])=>[-n,+n].map(n=>{for(i=I;X[i+=n]==a;)O[i]=b if(X[i]=='+')j|=[1,2,4,8,I-i>1&&17,i-I>1&&18][_],P(i) _++})),O[I]='┘└┴ ┐┌┬ ┤├┼ ╛╘╧ ╕╒╤ ╡╞╪'[j-5]),P(X.indexOf`+`),O.join``) ``` ``` f= X=>(W=X.indexOf('\n')+1,O=[...X],P=(I,j=0,_=0)=>!P[I]&&(P[I]=1,['-─1','|│','=═1'].map(([a,b,n=W])=>[-n,+n].map(n=>{for(i=I;X[i+=n]==a;O[i]=b);if(X[i]=='+')j|=[1,2,4,8,I-i>1&&17,i-I>1&&18][_],P(i);_++})),O[I]='┘└┴ ┐┌┬ ┤├┼ ╛╘╧ ╕╒╤ ╡╞╪'[j-5]),P(X.indexOf`+`),O.join``) console.log( f( `+------------------+ | Hello+World! | +==================+ | This is+my first | |+-+ code|golf +-+| |+-+chall|enge! +-+| +------------------+` )) console.log( f( ` +===+===+===+ | 1 | 2 | 3 | +---+===+===+===+ | 1 | 1 | 2 | 3 | +---+---+---+---+ | 2 | 2 | 4 | 6 | +---+---+---+---+ |-3 |-3 |-6 |-9 | +===+---+---+---+` )) console.log( f( `+-----+ +-----+`)) console.log( f( `++++ ++++ ++++`)) ``` ## Explanation Starting at the first found `+` junction, the program attempts to find paths to other junctions in every direction, performing replacements as it goes. It stores the found directions and the "double-bordered" state in a bitmap, which then determines the appropriate junction character. ``` // Take an input string X f = X => { // Copy the input string into an array so characters can be overwritten and eventually output O = [...X] // Define a function that processes a junction ("+" symbol) at index I in the input string X: P = I => { // Make a bitmap to keep track of the direction coming out of the junction and double borders // Bits from right to left: west, east, north, south, double border // E.g. a double-bordered south/east junction corresponds to the binary number 11010 ("╒") let j = 0 // A counter let _ = 0 // Ensure this junction hasn't already been processed if(!P[I]){ P[I] = 1, // We'll walk away from the junction in each of the four directions, then west and east again to check for double borders // i.e. walk along `a`, replace with `b`, move index `i` by `n` // 1st pass: walk along "-", replace with "─", move index by 1 // 2nd pass: walk along "|", replace with "│", move index by the width of the input (plus 1 for the newline) to traverse vertically // 3rd pass: walk along "=", replace with "═", move index by 1 ['-─1','|│','=═1'].map(([a, b, n = X.indexOf('\n') + 1])=> // We'll walk in the negative and positive directions for each pass [-n,+n].map(n=>{ // Start the walk i=I // Keep walking (incrementing by n) as long as we're on a "path" character, "a" while(i += n, X[i] == a) // Replace the corresponding character in the output with "b" O[i] = b // Upon reaching another junction at index i: if(X[i] == '+'){ // OR the bitmap according to the direction we walked j |= [ // Pass 1: Horizontal 1, // west 2, // east // Pass 2: Vertical 4, // north 8, // south // Pass 3: Double Horizontal (only if we've walked more than 1 step) I-i > 1 && 17, // west, double border i-I > 1 && 18 // east, double border ][_] // Process the junction we walked to P(i) } _++ }) ) // Finally, replace the "+" with a proper junction character based on the bitmap value O[I] = ' ┘└┴ ┐┌┬ ┤├┼ ╛╘╧ ╕╒╤ ╡╞╪'[j] } } // Process the first junction to kick off the recursion P(X.indexOf`+`) // Return our modified character array as a joined string return O.join`` } ``` [Answer] # [Python 3](https://docs.python.org/3/), 599 bytes I'm not really good at golfing in Python 3, but (to my shame) I couldn't get normal output of UTF-8 chars in Python 2. So here we are. I guess the only interesting trick here is deciding of `+` tranformation. I've encoded all possible variants with 4-bit adresses. Each bit of adress resembles connection to neightbour cell. So 0 - no connection and 1 - connection. `1111` is `┼` `0011` is `┐` etc Some configurations of connections are invalid and replaced with dummy values: `'012┐45┌┬8┘0┤└┴├┼'` If any neightbour cell contains `=`, second list will be used with doubled lines. ``` ['012┐45┌┬8┘0┤└┴├┼','012╕45╒╤8╛0╡╘╧╞╪']['='in r] ``` Adress is combined here. ``` r=''.join([str(int(V(y,x)))+W(y,x)for y,x in[(Y-1,X),(Y,X+1),(Y+1,X),(Y,X-1)]]) ``` `r` contains string lenght 8, where every two chars are 1/0 and actuals neightbour char. For example: `1+0y1-1|`. This is used to choose list of substitutions as shown before. And then contracted to adress: `int(r[0::2],2)` This lambda used to verify that cell coordinates are valid and cell's char is one of '+-|=' ``` V=lambda y,x:~0<x<len(I[0])and~0<y<len(I)and I[y][x]in'+-|=' ``` This lambda used to receive char from cell. Returns `' '` if coordinates are invalid. (definately can be golfed away) ``` W=lambda y,x:V(y,x)and I[y][x]or' ' ``` Conditions for recursion. Might be golfable too. ``` if Z in'+-=':F(Y,X+1);F(Y,X-1) if Z in'+|':F(Y-1,X);F(Y+1,X) ``` --- ``` I=eval(input()) J=[i[:]for i in I] V=lambda y,x:~0<x<len(I[0])and~0<y<len(I)and I[y][x]in'+-|=' W=lambda y,x:V(y,x)and I[y][x]or' ' def F(Y,X): if V(Y,X)and I[Y][X]==J[Y][X]: Z=I[Y][X] if','>Z: r=''.join([str(int(V(y,x)))+W(y,x)for y,x in[(Y-1,X),(Y,X+1),(Y+1,X),(Y,X-1)]]) J[Y][X]=['012┐45┌┬8┘0┤└┴├┼','012╕45╒╤8╛0╡╘╧╞╪']['='in r][int(r[0::2],2)] else:J[Y][X]=dict(zip('|-=','│─═'))[Z] if Z in'+-=':F(Y,X+1);F(Y,X-1) if Z in'+|':F(Y-1,X);F(Y+1,X) e=enumerate F(*[(y,x)for y,r in e(I)for x,c in e(r)if'+'==c][0]) for r in J:print(''.join(r)) ``` [Try it online!](https://tio.run/##xVVPa9swFL/7U2i9yKrtkaRd6Lxqx7D0PPonQofMVlaP1AmqO5Jhxth5hzJsKGwMBoXB2HHHfRp9kUySUyVNlS4tDbv8rPdP7/2enuThODsepFuTaBAzgMHGxsakjdnbbt9N0uFZ5iLk7GGSkJD2BhwkIElBmzr7uN89eRV3wdgfhe9ru6PdPkvdNqlR1E1jqRhXCiWBNhlTMqJJCr0gx9A5mA/edyXOuw04BNCJWQ@03CP/EIUOSHpgX68rtyNKDinGe9VC2kEHT7VynfSgD593lBpwDOHjN4MkdclpxiWjzK3yIeQd6IUiJb@SFnGPgrrM4atMXl19PSMHdUQpUltOs2ICa/WGKM63n4jikyh@7YjioiaKS1EUovgtiq@i@CMLUU5lKZ3Kz6K83BHll5oov4vyQpQ/RPlNlD8hJRBD2VZOiSqQk1oYNqjfQIoN65@y8CpnnESZ@y4ZujAPsNxcFB9F8UGU5xAh0qnIgw7QjcYwbE2ZPGtNKcw75NquGSu7puowzNKzE8a7GXNa7iaZaxFXJ8/kiSpx5EeVyJFstwcxjqg6e0cZtedeOOSKzVX/OUITOVuOw0YsAq6etk3QRBNCZLwPYLA28CD1AYG5WoPr8EIBU9A3MKhiJBwYkRtrrOCRZau8yqID8drgBpeXCo4VJApOjWEm6pJOFIyNtWdcuPHLFrnkJjowK22PTGNi00Dt/NoY@ibLrEULW92SJTKsutcPJzf5UpOPXT8Se5b1zxh1bo6yZ53Eh3PKF2dwhZH0rBP1ME66B8ByO4DFH99NpytYuveMet2ia1h0W4t9ApY@Bw9Z9@01rqnue@tsdTdWrHHbomv@n7qDxZ7dpmtadE@X1207//vXbXtA/vVT8@74Pi29P7ZXOljl4i0EzsOdAld4S2eM52PtryWlfwE "Python 3 – Try It Online") ]
[Question] [ ### This is the followup challenge from [this one](https://codegolf.stackexchange.com/questions/166673/number-of-fifo-cache-misses), if you're confused please check that one out first. --- First, let \$m(s, k)\$ be the number of cache misses a sequence \$s\$ of resource accesses would have assuming our cache has capacity \$k\$ and uses a first-in-first-out (FIFO) ejection scheme when it is full. Then given a ratio \$r > 1\$, return a non-empty sequence of resources accesses \$s\$ such that there exists \$k > j\$ with \$m(s, k) \geq r \cdot m(s, j)\$. In plain English, construct a sequence \$s\$ of resource accesses so that there's two cache sizes where the bigger cache has (at least) \$r\$ times **more** cache misses when used to resolve \$s\$. An example for \$r = 1.1\$, a valid output is the sequence \$(3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4)\$, as it causes \$9\$ cache misses for a cache size of \$3\$, but \$10\$ misses for a cache size of \$4\$. It doesn't matter what sequence you return, as long as it meets the requirements. --- Shortest code in bytes wins. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~124~~ ~~113~~ 101 bytes ``` Flatten@{s=⌈2#⌉;q=Range[r=2s+1];g=Mod[q s-s,r];{Sort@g[[#+1;;]],g[[;;#]]}&~Array~r,Table[q,s^3]}& ``` [Try it online!](https://tio.run/##TZDBSsNAEIbv8xQDgaBkG02qB1lSqoeCoqCt4GEZYY1puiRN6G48SEjPCn3KvkicBET3MPPvv9/szuxWN5tsqxuT6n79UaXJSb8oddNk1bx1yfHwFXvHw7fcJUtd5ZmySeyCiGSePNTvaodu4oQl2a5q28xzpbwgkpJIsJTSI@r8/bW1@nNvxbN@KzO1E@51ynZ/KgHK4UVM8Kas00K1RmAh0LHhdQLAsDiXUHBqOwmrVFcK8HatFjbLnhSjHglANEEgOQ3cXW0q1XI1FjR4DN9nVd5sVEE4QydGqhiac0QESL4AL2YWDAD5nB@tqRr1YrimrRmOf/@AL/VwMkN2JxgNamxfjVuBo@aJBdb/zv78jsjHs3kLEIURTxeHVxyn4QXHyzAC6GBc/Q8 "Wolfram Language (Mathematica) – Try It Online") NOTE: The TIO output is not the actual list because it would be very long. The wrapper function on TIO tells you the number of page faults for two cache capacities. For the actual list: [Try it online!](https://tio.run/##NY6xCsIwFEX3fEWwIEpToXURH4G6uAmigkOI8KyxBmxjkzhIqbOCX@mP1Iq4Xc4Zzi3Qn1SBXmfYHq9lxgft/IzeqzKtHX@/Hknwfj2h4isscyUsT1wYS8j5whxERV3kmJVQr431aS5EEMYAUrJuAgRSNv37zFq83S3b4P6sRMXcbtzhdgiEbLU/idpQTpN/qWF0aXXpRS/DC2baa@WmtMdobaKYUdNI@Pnv2bQr9AUh8WhCiGw/ "Wolfram Language (Mathematica) – Try It Online") [Related: arXiv:1003.1336](https://arxiv.org/abs/1003.1336) ### How? Let's assume a situation where we have two cache capacities, `3` and `4`. Also, let's say the `3`-cache has `{4, 2, 5}` paged, and `4`-cache has `{5, 4, 3, 2}` paged. Then, let's try paging `{1, 2, 3, 4, 5, 1, 2, 3, 4, 5}`: ``` page 3-cache 4-cache {4,2,5} {5,4,3,2} 1 {1,4,2} {1,5,4,3} 2 {1,4,2} {2,1,5,4} 3 {3,1,4} {3,2,1,5} 4 {3,1,4} {4,3,2,1} 5 {5,3,1} {5,4,3,2} 1 {5,3,1} {1,5,4,3} 2 {2,5,3} {2,1,5,4} 3 {2,5,3} {3,2,1,5} 4 {4,2,5} {4,3,2,1} 5 {4,2,5} {5,4,3,2} ``` The `3`-cache had 5 page faults, while the `4`-cache had 10. We also returned to our original state. Here, if we repeat paging `{1, 2, 3, 4, 5}`, we would asymptotically reach the ratio of `2`. We can extend this phenomenon to higher cache capacities so that we can page `{1, 2, 3, ... , 2n + 1}` and end up with any ratio. ]
[Question] [ # Pangrams > > The quick brown fox jumped over the lazy dog. > > > This is an example of a pangram - a sentence that contains every letter of the alphabet at least once. A *self-enumerating* pangram is a sentence that fulfills the criteria to be a pangram by producing an analysis of its own letter count. An example of achieving this is the sentence > > This pangram contains four As, one B, two Cs, one D, thirty Es, six Fs, five Gs, seven Hs, eleven Is, one J, one K, two Ls, two Ms, eighteen Ns, fifteen Os, two Ps, one Q, five Rs, twenty-seven Ss, eighteen Ts, two Us, seven Vs, eight Ws, two Xs, three Ys, & one Z. > > > --- # The Challenge Produce a function with the input being the string leading into the letter inventory. In the example, the input would be "This pangram contains". The quantity of each letter must be in the written form and contribute to the displayed letter count. --- # Rules * Oxford comma is optional * Use an ampersand before Z (or, for hard mode, include the ability to switch between "&" and "and" in the function) * Every letter counts towards the total letter count * No non-written numbers * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins * In hono**u**r of the married couple this weekend, the numbers are to be written in the Queen's English. e.g. `nine hundred and ninety-nine Gs` for 999 occurrences of the letter G and `nine hundred and nine Gs` for 909. * Orders of magnitude are to be written in the standard [short-scale naming convention](https://en.wikipedia.org/wiki/Names_of_large_numbers) # Edge cases * There are some cases where the code will get stuck in a loop - for example, if there are two Os the code will increase the count to three Os, which causes the code to count two Os again. If calculating every other letter before coming back to this can't resolve the issue, consider the input to be a false starter and output `false`, `null` or an empty string. * If a letter has over 999 occurrences, the input should be considered a false starter. # Test Cases * "This pangram contains" should output the example sentence [Answer] # [Python 2](https://docs.python.org/2/), 615 bytes ``` def g(n):S=str.split;D=S('z one two three four five six seven eight nine');K=' fif six seven eigh nine';n,m=n/100,n%100;e,d=m/10,m%10;return' '.join([D[n],'hundred']*(n>0)+([S('ten eleven twelve thir four'+K)[d]+'teen'*(d>2)]if 9<m<20else[S('twen thir for'+K)[e-2]+'ty']*(e>0)+[D[d]]*(d>0))) from random import* X='ABCDEFGHIJKLMNOPQRSTUVWXYZ' def f(p): T=set();s='';i=0 while 1: Q=s.upper().count;t=p+' '+', '.join(['& '*(c=='Z')+g(Q(c))+' '+c+'s'*(Q(c)!=1)for c in X])+'.' if s==t:return i,t if t in T:t=''.join(c*max(1,t.upper().count(c)+(randint(0,6)-3)*(random()<0.25))for c in X) T.add(t);s=t;i+=1 ``` [Try it online!](https://tio.run/##XVJdj9MwEHxufsXeSWC7SUNSBBJNfRJQPstXaYByVR6i2GmMGiey3esdf76sG4SAPCSxZ2d2duz@zjWdnp5OQtawo5rN1tw6E9t@r1y24GtKfkKnJbhjB64xUkLdHQzU6kaCVbdg5Y3UINWucaCVloRlS04Qr/@DBzTTUcv1gzRJIn0P35mMBG9xHbW4zIx0B6MJkPhHpzTdLra6iEhz0MJIQYox1VcJC@kWbTmvuz/Lu6Pcox3XKHN2R8Il24oixBqpyZiKqykr0NCTeTufJnJv5Vng6KkDZ6DIydST7nwj6Rthf1EUXiBhjAW16VowpRb4UW3fGTcONpw8ffZ88eLlq9dv3i7fvf/w8dPq8zr/8vXb5vs1CXysNe3ZLICcW@koyywnJFM8CeDYqL2EdBaMVtzGh76XhrK46g7aZY73IeYQkuhPGOQ@4DAV5@SasHBHV7Ri7FxUhcQi5DcueMpwHqhAadgUiMckgN@PPxTO3WyIGVTkghHuOV@bzxwaG1pV47a8pWnk/jWF8iH18yv8T6LHbPKQjekQCGXzJJ4@Yn81Z8Eoj0shqPNDu0yFPD31BslwmZcTUV5cRjUleaMs3hONB1pJqDrtSqUtYadf "Python 2 – Try It Online") The function `f` takes `p` as the string prefix; and returns a tuple of an integer representing the number of steps taken, and the autogram. The function `g` encodes a number `1<=n<=999` to its english string; it takes up 291 bytes, roughly half the total byte count. The code ``` Q=s.upper().count t=p+' '+', '.join(['& '*(c=='Z')+g(Q(c))+' '+c+'s'*(Q(c)!=1)for c in X])+'.' ``` encodes the string `s` into a (potentially autogram-matic) pangram `t`. We loop over the process, hoping for the situation where we find a `t` such that `t` is an autogram (i.e., where `t==s`). ~~If~~ When we get into a loop, we randomly nudge the counts of letters in a completely ad hoc manner. For most values of `p`, this process will time out on TIO. Typically, millions of possibilities are examined before finding a 'winning' combination. I don't have any proof at all, but my guess is: (a) apart from an exhaustive brute force search similar to what the [originator Lee Sallows describes here](http://leesallows.com/files/In%20Quest%20of%20a%20Pangram1.pdf) and implements in hardware (!), this sort of random heuristic is about as good as you can get; and (b) there will be no solutions for many (most?) initial phrases `p`. ]
[Question] [ If a string **T** of length **K** appears **K** or more times in a string **S**, then it is *potentially communistic*. For example, `10` in `10/10` is potentially communistic, for it appears *2* times and is of length *2*. Note that these substrings cannot overlap. A *communistic transformation* is one that takes this string **T** and moves each character **t***i* of **T** to the *i* occurrence of **T** in **S**. So, for the previous example, the communistic transformation would yield `1/0`; the first char of `10` replaces `10` the first time `10` is found, and `0` the second time. A *communistic normalization* is a function that takes all such strings **T** with **K** ≥ 2 and performs a *communistic transformation* on them. Some specifics on the algorithm: 1. Perform communistic transformations on the longest valid strings **T** *first*. Favor the first occurrences of **T**. 2. Then, perform communistic transformations on the next-longest strings, then the next-next-longest... etc. 3. Repeat until no such strings exist in the string. Note that some strings, such as the "Hello, Hello" example in the test cases, can be interpreted two different ways. You can use `ell` for **T**, but you can also use `llo`. In this case, your code can choose either option. The shown test case uses `llo`, but you may get a different and equally valid output. --- Your task is to implement communistic normalization. The input will only ever consist of printable ASCII characters (0x20 to 0x7E, space to tilde). You may write a program or function to solve this task; the input may be taken as a line from STDIN, string/character array argument, argument from ARGV, etc. ## Test cases ``` '123' -> '123' '111' -> '111' '1111' -> '11' 'ABAB' -> 'AB' '111111111' -> '111' 'asdasdasd' -> 'asd' '10/10' -> '1/0' '100/100+100' -> '1/0+0' ' + + ' -> ' + ' 'Hello, hello, dear fellow!' -> 'Hel he, dear feow!' OR 'Heo hl, dear flow!' '11122333/11122333/11122333' -> '112/13' OR '132/23' 'ababab1ababab' -> 'a1bab' '1ab2ab3ab4ab5ab6' -> '1a2b3a4b5ab6' ``` ## Worked out test case Format is `'string', 'substring'`, at each step of replacement. Replaced bits are bracketed. ``` '11[122]333/11[122]333/11[122]333', '122' '111[333]/112[333]/112[333]', '333' '1113/11[23]/11[23]', '23' '11[13]/112/1[13]', '13' '1[11]/[11]2/13', '11' '1[/1]12[/1]3', '/1' '112/13', '' ``` Another test case: ``` 'Hello, hello, dear fellow!', 'llo' 'Hel, hel, dear feow!', 'l,' 'Hel he, dear feow!', '' ``` ## Reference code (Python) You may find this useful to visualize the algorithm. ``` #!/usr/bin/env python import re def repeater(string): def repeating_substring(substring): return (string.count(substring) == len(substring)) and string.count(substring) > 1 return repeating_substring def get_substrings(string): j = 1 a = set() while True: for i in range(len(string) - j+1): a.add(string[i:i+j]) if j == len(string): break j += 1 return list(a) def replace_each_instance(string, substring): assert `string`+',', `substring` for i in substring: string = re.sub(re.escape(substring), i, string, 1) return string def main(s): repeats = repeater(s) repeating_substr = filter(repeater(s), get_substrings(s)) while repeating_substr: repeating_substr.sort(lambda x,y: cmp(len(y), len(x))) s = replace_each_instance(s, repeating_substr[0]) repeating_substr = filter(repeater(s), get_substrings(s)) return s assert main('123') == '123' assert main('111') == '111' assert main('1111') == '11' assert main('ABAB') == 'AB' assert main('111111111') == '111' assert main('asdasdasd') == 'asd' assert main('10/10') == '1/0' assert main('100/100+100') == '1/0+0' assert main(' + + ') == ' + ' assert main('Hello, hello, dear fellow!') == 'Hel he, dear feow!' assert main('11122333/11122333/11122333') == '112/13' ``` Thanks to @ConorO'Brien for posting the original idea of this challenge. [Answer] # JavaScript (ES6), 121 bytes ``` f=(s,j=2,o,m=s.match(`(.{${j}})(.*\\1){${(j-1)}}`))=>m?f(s,j+1,s.split(m[1]).map((e,i)=>e+(m[1][i]||'')).join``):o?f(o):s ``` Recursively matches the pattern: ``` (.{2})(.*\1){1} //2 characters, repeated 1 time (.{3})(.*\1){2} //3 characters, repeated 2 times (.{4})(.*\1){3} //4 characters, repeated 3 times etc. ``` … until the pattern isn't found. (This guarantees that the longest string is handled first.) It then performs the "communistic transformations" on the last-found pattern, by splitting on the match, and joining on each of the match's characters. (`map` is used for this purpose. Too bad `join` doesn't take a callback.) It finally recurses on this new string until it is no longer *communistic*. **Test cases:** ``` f=(s,j=2,o,m=s.match(`(.{${j}})(.*\\1){${(j-1)}}`))=>m?f(s,j+1,s.split(m[1]).map((e,i)=>e+(m[1][i]||'')).join``):o?f(o):s console.log(f('123')); //123 console.log(f('111')); //111 console.log(f('1111')); //11 console.log(f('ABAB')); //AB console.log(f('111111111')); //111 console.log(f('asdasdasd')); //asd console.log(f('10/10')); //1/0 console.log(f('100/100+100')); //1/0+0 console.log(f(' + + ')); // + console.log(f('Hello, hello, dear fellow!')); //Heo hl, dear flow! console.log(f('11122333/11122333/11122333')); //132/23 ``` [Answer] # Pyth, 22 bytes ``` u.xse.iLcGdf>cGTlTt#.: ``` [Test suite](https://pyth.herokuapp.com/?code=u.xse.iLcGdf%3EcGTlTt%23.%3A&test_suite=1&test_suite_input=%27123%27%0A%27111%27%0A%271111%27%0A%27ABAB%27%0A%27111111111%27%0A%27asdasdasd%27%0A%2710%2F10%27%0A%27100%2F100%2B100%27%0A%27+++%2B+++%2B+++%27%0A%27Hello%2C+hello%2C+dear+fellow%21%27%0A%2711122333%2F11122333%2F11122333%27&debug=0) To actually see what the program is doing, check out this: [Internals](https://pyth.herokuapp.com/?code=uv%0A%60.xse.iLcGdf%3EcGTlTt%23.%3A&input=%2711122333%2F11122333%2F11122333%27&test_suite_input=%27123%27%0A%27111%27%0A%271111%27%0A%27ABAB%27%0A%27111111111%27%0A%27asdasdasd%27%0A%2710%2F10%27%0A%27100%2F100%2B100%27%0A%27+++%2B+++%2B+++%27%0A%27Hello%2C+hello%2C+dear+fellow%21%27%0A%2711122333%2F11122333%2F11122333%27&debug=0) In particular, the program always uses the final-occuring replacement of the longest replacements. Explanation: ``` u.xse.iLcGdf>cGTlTt#.: u.xse.iLcGdf>cGTlTt#.:G)GQ Implicit u Q Starting with the input, repeat the following until a fixed point is reached. .:G) Construct all substrings of the current value ordered smallest to largest, front to back. t# Filter on having more than 1 element. These are the eligible substrings. f Filter these substrings on cGT Chop the current value on the substring, > lT Then remove the first len(substring) pieces. The result is nonempty if the substring is one we're looking for. Chopping gives nonoverlapping occurrences. .iL Interlace the substrings with cGd Chop the current value on that substring se Take the final result, make it a string. .x G If there weren't any, the above throws an error, So keep the current value to halt. ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~420~~ ... 368 bytes ``` import StdEnv,StdLib l=length %q=any((==)q) ?_[]=[] ?a[(y,x):b]|isPrefixOf a[x:map snd b]=[y: ?a(drop(l a-1)b)]= ?a b $s=sortBy(\a b=l a>l b)(flatten[[b: $a]\\(a,b)<-map((flip splitAt)s)[0..l s-1]]) f s#i=zip2[0..]s #r=filter(\b=l(?b i)>=l b&&l b>1)($s) |r>[]#h=hd r #t=take(l h)(?h i) =f[if(%n t)(h!!hd(elemIndices n t))c\\(n,c)<-i|not(%n[u+v\\u<-t,v<-[1..l h-1]])]=s ``` [Try it online!](https://tio.run/##JVFRS8MwEH7PrzjZdAm2surbWFYUfRAEBR/TIEmbmmCa1SYbq@y3W2@OHDnuu7vvPu5qb1SYum2z8wY65cLkun47JHhPzVPYZ@henCaeexM@kyWX31yFkVLO2Tcj5YeQXEhSKkHH7MBWWh5dfBtM6w6vLShxWHWqhxga0Fg4rqBUtBm2PfWg8oJpJjlCoMk88ohjH0ZaYcgxvfGgGW29SskEIfQK5kpWFVWZZuscaSkmHZL33qX7xCITy5sbDzEvpGSkhThz/Mf1tydYRjIbeOt8MgOtkJ@WGhzb4CB9dYXfpmB0Hhk5DhshZ5bbBgYySzypL4NiLaOlxQbCW@FaehkgMWovLmxDjTfdc2hcbSKcYFajyJDVKNIdwzZhsdhd76tqt85Ttl/nojjJtP8yJY/Te1K4bw4tiIXSp1ec3UJOvzUu4DNO@fPL9DgG1bn6HJzvMuVodrpbLrs/ "Clean – Try It Online") ]
[Question] [ # Background A [Lyndon word](https://en.wikipedia.org/wiki/Lyndon_word) is a non-empty string which is strictly lexicographically smaller than all its other rotations. It is possible to factor any string uniquely, by the [Chen–Fox–Lyndon theorem](https://en.wikipedia.org/wiki/Chen%E2%80%93Fox%E2%80%93Lyndon_theorem), as the concatenation of Lyndon words such that these subwords are lexicographically non-increasing; your challenge is to do this as succinctly as possible. # Details You should implement a function or program which enumerates the Lyndon word factorization of any printable ASCII string, in order, outputting the resultant substrings as an array or stream of some kind. Characters should be compared by their code points, and all standard input and output methods are allowed. As usual for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program in bytes wins. # Test Cases ``` '' [] 'C' ['C'] 'aaaaa' ['a', 'a', 'a', 'a', 'a'] 'K| ' ['K|', ' '] 'abaca' ['abac', 'a'] '9_-$' ['9_', '-', '$'] 'P&O(;' ['P', '&O(;'] 'xhya{Wd$' ['x', 'hy', 'a{', 'Wd', '$'] 'j`M?LO!!Y' ['j', '`', 'M', '?LO', '!!Y'] '!9!TZ' ['!9!TZ'] 'vMMe' ['v', 'MMe'] 'b5A9A9<5{0' ['b', '5A9A9<5{', '0'] ``` [Answer] # Pyth, 17 16 bytes -1 byte thanks to isaacg! ``` hf!ff>Y>YZUYT+./ ``` [Try it online!](https://pyth.herokuapp.com/?code=hf%21ff%3EY%3EYZUYT%2B.%2F&input=001011&test_suite=1&test_suite_input=%27aaaaa%27%0A%279_-%24%27%0A%27C%27%0A%27P%26O%28%3B%27%0A%27K%7C+%27%0A%27xhya%7BWd%24%27%0A%27%27%0A%27abaca%27&debug=0) ### Explanation ``` hf!ff>Y>YZUYT+./ ./ Take all possible disjoint substring sets of [the input] + plus [the input] itself (for the null string case). f Filter for only those sets which !f T for none of the substrings f >YZUY is there a suffix of the substring >Y lexographically smaller than the substring itself. h Return the first (i.e. the shortest) such set of substrings. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ṙJ¹ÐṂF⁼ ŒṖÇ€Ạ$ÐfṀȯ ``` [Try it online!](https://tio.run/##y0rNyan8///hzpleh3YenvBwZ5Pbo8Y9XEcnPdw57XD7o6Y1D3ctUDk8Ie3hzoYT6/@DRSKBOOtRw5xD23RB4NC2Rw1z//9XV9dRUHcGEYkgAGJ41yiA@UmJyWC@ZbyuCogOUPPXsAYxKjIqE6vDU8CCWQm@9j7@ioqRII6ipWJIFIhR5uubCqKTTB0tHS1tTKsN1AE "Jelly – Try It Online") [Answer] # Pyth - 28 bytes ``` hf&SI_T.Am.A>Rdt.u.>N1tddT./ ``` [Test Suite](http://pyth.herokuapp.com/?code=hf%26SI_T.Am.A%3ERdt.u.%3EN1tddT.%2F&test_suite=1&test_suite_input=%27aaaaa%27%0A%279_-%24%27%0A%27C%27%0A%27P%26O%28%3B%27%0A%27K%7C+%27%0A%27xhya%7BWd%24%27%0A%27%27&debug=0). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .œé.Δεā<._ć›P}P ``` [Try it online](https://tio.run/##ASoA1f9vc2FiaWX//y7Fk8OpLs6UzrXEgTwuX8SH4oC6UH1Q//9qYE0/TE8hIVk) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vaOTD6/UOzfl3NYjjTZ68UfaHzXsCqgN@F@r8z9aSUlHQckZRCSCAIjhXaMA5iclJoP5lvG6KiA6QM1fwxrEqMioTKwOTwELZiX42vv4KypGgjiKloohUSBGma9vKohOMnW0dLS0Ma02UIoFAA). **Explanation:** ``` .œ # Get all partitions of the (implicit) input-string é # Sort them by length .Δ # Find the first/shortest which is truthy for: ε # Map over each part of the current partition: ā # Push a list in the range [1,length] (without popping the part-string) < # Decrease it to a 0-based range [0,length) ._ # For each value, rotate the string that many times ć # Extract head; pop and push remainder-list and first item separately # (where the head is the unmodified part-string) › # Check for each rotated part if it's lexicographically larger than the # unmodified part-string P # Check whether this is truthy for all rotations }P # After the inner map: check whether it's truthy for all parts in the # partition # (after which the found result is output implicitly as result) ``` ]
[Question] [ Many formulas in math involve nested radicals (square root signs inside other square roots signs). Your task here is to draw these using ascii art. # Specs You will be given two integers, the number inside the radical, and the number of radicals. I think the best way to explain what you have to do is with an example. Here is the output for `2, 4`: ``` ____________________ \ / _______________ \ / \ / __________ \ / \ / \ / _____ \/ \/ \/ \/ 2 ``` Here are some things to note: * The height of each radical increases by one * The length of the `_`'s are always `5` times the height * There is a space after the last `/` and before the next inner radical starts * The number inside will never be greater than 4 digits * If the number of radicals is 0, just output the number * Putting extra spaces to pad it into a rectangle is up to you * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! # Test Cases ``` 2, 4: ____________________ \ / _______________ \ / \ / __________ \ / \ / \ / _____ \/ \/ \/ \/ 2 23, 0: 23 4, 1: _____ \/ 4 1234, 3: _______________ \ / __________ \ / \ / _____ \/ \/ \/ 1234 ``` [Answer] ## Python 3.5, ~~145~~ 137 bytes ``` def s(n,x):[([print(' '*j+'\\'+' '*i+'/ '+' '*j,end='')for j in range(x-i-1,-1,-1)],print(' '*i+i*'_____'or n))for i in range(x,-1,-1)] ``` Slightly ungolfed: ``` def s(n,x): for i in range(x,-1,-1): for j in range(x-i-1,-1,-1): print(' '*j+'\\'+' '*i+'/ '+' '*j,end='') print(' '*i+i*'_____' or n) ``` Output: ``` s(2,4) ____________________ \ / _______________ \ / \ / __________ \ / \ / \ / _____ \/ \/ \/ \/ 2 ``` [Answer] # JavaScript, ~~133~~ ~~132~~ 131 bytes ``` f=(n,r,q=r)=>~r?'1\\0/1 '[x='repeat'](d=q-r).replace(/\d/g,i=>' '[x](+i?d-=.5:r*2))+(r?' '[x](r*2)+'_'[x](5*r):n)+` `+f(n,r-1,q):'' F=(n,r)=>console.log( f(n,r) ) F(2,4) F(23,0) F(4,1) F(1234,3) ``` ``` .as-console-wrapper{max-height:100%!important;top:0} ``` [Answer] ## JavaScript (ES6), 124 bytes ``` f=(s,n,i=0,r=(n,c=` `)=>c.repeat(n))=>n?r(n+n)+r(n*5,`_`)+` `+f(s,n-1).replace(/^/gm,_=>r(i)+`\\${r(n+~i<<1)}/`+r(++i)):s+`` ``` ``` <div oninput=o.textContent=f(s.value,+n.value)><input id=s><input id=n type=number min=0><pre id=o> ``` Save 3 bytes if the first parameter can be a string rather than a number. [Answer] # PHP, 178 bytes ``` for($r=[" $argv[1]"];$i++<$argv[2];$r[]=$p("",2*$i).$p(_,5*$i,_))for($k=-1;++$k<$i;)$r[$k]=($p=str_pad)("\\".$p("",2*$k)."/",2*$i," ",2).$r[$k];echo join("\n",array_reverse($r)); ``` bah that´s awfully long. ]
[Question] [ # Introduction Bob likes to have different passwords for each website he uses. He wants passwords in a special format so that he can remember. Help him by building a password generator which is as short as possible in code length, because he likes keeping stuff short just like his name. # Challenge Build Bob a password generator which takes in four parameters - * Domain address, (ex : stackexchange.com) * First name, * last name, * Birth date and year. and outputs a string which has undergone the following transformations. Every password has a template based on the length ***l*** of the domain name. If ***l*** is prime then the template is of this form - `[birth-date][domain-name][lastname][birth-year][symbol]` else it is of this form - `[symbol][birth-year][firstname][domain-name][birth-date]`. The symbol field will have values based on the domain type. ``` .com -> $$$ .org -> &&& .net -> %%% .edu -> +++ .gov -> @@@ .mil -> >>> default -> ~~~ ``` Now, he also wants to run a [caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher) over fields - `[firstname][domain-name][lastname]`.The shift direction is right if *l* is prime else it is left. The shift value is determined by the value of addition of birth date and year. After the above process, the text cannot be easily remembered so he wants the ciphered text to be pronounceable. To do this he wants to replace every third consecutive consonant with a vowel in alphabetical order (i.e, `aeiou`). Finally, he wants to delete consecutive occurrences of same letters. # Example ``` Input - stackexchange.com bob williams 0894 Output - 08qraicvafyecugjigyoq94$$$. ``` Explanation : Password template is `[birth-date][domain-name][lastname][birth-year][symbol]`, because the length of domain name `stackexchange` is a prime. Symbol will be `$$$` as domain type is `.com`. Let's fill those values in the template - `08stackexchangewilliams94$$$`. Now caesar cipher has to be run on fields `[firstname][domain-name][lastname]` (it's just lastname in this case). Shift direction is right because ***l*** is prime and the shift value is `08+94 = 102`. So, `08stackexchangewilliams94$$$` turns into `08qryaicvafylecugjjgykq94$$$`. Now every third consecutive consonant is replaced with a vowel - `08qraaicvafyeecugjigyoq94$$$` every consecutive ocuurences of same letter is deleted - `08qraicvafyecugjigyoq94$$$`. Don't worry it is pronounceable for Bob. **Additional info** * Domain address, first name and last name contain only lowercase alphabets. * Domain address will always consist of only a second-level and top-level domain, like `stackexchange.com` and not `codegolf.stackexchange.com`. Also, domains like `.co.uk` is not allowed but just `.uk` or `.in` is valid. * Replacement of vowel in alphabetical order is cyclic. I mean after `u`, `a` is used to replace. * ASCII range for Caesar cipher is 97 - 122 inclusive. * You can take input as described [here](https://codegolf.stackexchange.com/questions/102243/count-the-reviews/102316#102316). * Output has to be a string. * The format of birth date and year is `dd` and `yy`.So `02` is acceptable and `2` is not. This is code-golf, so the shortest code in bytes wins. Happy Golfing! [Answer] # PowerShell 3+, ~~480~~ ~~476~~ ~~474~~ ~~453~~ ~~450~~ 448 bytes ``` param($d,$f,$l,$b)$s,$t=$d-split'\.' $m,$y=$b-split'(?<=..)(?=..)' $v=+$m+$y $p='1'*$s.Length-match'^(?!(..+)\1+$)..' $c={-join([char[]]"$input"|%{[char](97..122)[((+$_-97)+((26-$v),$v)[$p])%26]})} $s=$s|&$c $f=$f|&$c $l=$l|&$c $a=(($a=@{com='$';org='&';net='%';edu='+';gov='@';mil='>'}.$t),'~')[!$a]*3 ("`"$(("$a$y$f$s$m","$m$s$l$y$a")[$p]-replace'([^aeiou\d]{3})',"`$('`$1'-replace'[a-z]`$$',('aeiou'[`$i++%5]))")`""|iex)-replace'([a-z])\1+','$1' ``` ## [Try it online!](https://tio.run/nexus/powershell#TVDtbtpAEPzvt8hpyO7lzqdC2qTIvZIH6BsYpz6MAbfnD2FDQ4G8umtIFeXHjkazs6Pd7Ru3dSVjqbHS8BoLiVajs1iGbeOLjuaGApQaB4vFf4ln36wxkmcXHLp7q1AqHAI0lsZ0h9b8yKt1twlL12UbeubZDRuj5HysIM0lMLPH8FddVBxnG7eNk0SgqJpdJ06j41VKePpozHgykTGzws9w@igV8@QhxF7qoWI0iRxNHpKzPAdoLdrTLbIAK4vVG/MW/o05yzzA0zGrS0ugqN6uLd1SVOWdpRFF@XJnSVG0rveWnigqC2/pO50NOqnplWR8A5fc3QcsUgFmAYcDVmhRCi1QDsQPghPXtcJt3niX5cTxs8uLejdfJsf7syQtUjClGNO7JXbh3yQFSDNdvRSnKJQafUmkFDIV4lTkL/JD5GXg8knSNAT1fd92Lvudvwxfq9a5GU7sF/Wi/1N4X7iy7T99nX7@Bw "PowerShell – TIO Nexus") **Saved *~~24~~ 26* bytes thanks to [TimmyD](https://codegolf.stackexchange.com/users/42963/timmyd)!** Wow, this was a crazy one. I don't think I can post a full breakdown of this until later or tomorrow. Note: all line endings are `\n` (`0x10`), so that I don't have to use `;` and put this all on one line. ### Quick overview: 1. Split the domain into the second level and top level. 2. Split the birthdate into month and year. 3. Calculate the shift value. 4. Determine whether the length of the SLD is prime. ~~Since [the segment cannot be longer than 63 characters](https://stackoverflow.com/a/14402979/3905079) ([see also RFC 1035](http://www.ietf.org/rfc/rfc1035.txt)), I think it was shorter just to hardcode the list of primes :)~~ Using the regex method suggested. 5. Define a scriptblock (anonymous function essentially) to perform the Caesar cipher. 6. Apply the cipher to the SLD, first, and last names 7. Get the symbol with a hashtable and indexing funny business. 8. Finally, a giant mess where I apply the appropriate template, run a replace for the consonant triplets, replacing each one with a subexpression (code) that will replace that section with the appropriate value, then run the resulting string through `Invoke-Expression` (`iex`) to execute the generated emebedded code, then a final replace of consecutive letters with a single letter. ]
[Question] [ ## Challenge Write a program which, using the XML data from the site [here](http://www.bleb.org/tv/data/listings/0/bbc1.xml), display the name of the programme which is currently showing on BBC 1. ## Information All times are given at London time (GMT+1 at the time of posting and GMT+0 after the 30th October). Therefore, you should convert your local time to London time. Each programme is given a start and end time. If the current time is after the start time and before the end time of a programme, that programme is currently showing. Your programme may handle overlaps in anyway you wish. Your output must be the programme title, like so: ``` BBC News ``` However, if the programme has a subtitle (shown by the presence of the subtitle tag), the output should be like so: ``` Steptoe and Son: The Piano ``` Where *Steptoe and Son* is the title and *The Piano* is the subtitle. An example programme with a subtitle is as follows: ``` <programme> <subtitle>Newcastle</subtitle> <title>Flog It!</title> <end>1710</end> <start>1610</start> <desc> Antiques series. Paul Martin presents from the Discovery Museum in Newcastle. The items uncovered include a book of autographs with a local connection. Also in HD. [S] </desc> </programme> ``` URL shorteners are disallowed but XML parsing libraries are allowed. ## Winning The shortest code in bytes wins. [Answer] # Python, ~~440~~ ~~428~~ ~~426~~ ~~398~~ 395 Bytes *-31 Bytes thanks to @Loovjo* Throws an error when it found the date. ``` import re,pytz,urllib from datetime import* x=urllib.urlopen("http://www.bleb.org/tv/data/listings/0/bbc1.xml").read().split("</p")[:-1] for m,n in enumerate(re.search("\d*</s",i).group()for i in x): if n>datetime.strftime(datetime.now(pytz.utc).astimezone(pytz.timezone('Europe/London')),"%H%M"):print re.search(">.*?</t",x[m-1]).group()[1:-3],": "+re.search("e>.*?</s",x[m-1]).group()[2:-3],_ ``` *Please don't hurt me for parsing xml with regex.* ### version using a xml parser, 398 Bytes ``` import re,pytz,urllib import xml.etree.ElementTree as ET from datetime import* x=list(ET.parse(urllib.urlretrieve("http://www.bleb.org/tv/data/listings/0/bbc1.xml")[0]).getroot()) for m,n in enumerate(i.find("start").text for i in x): if n>datetime.strftime(datetime.now(pytz.utc).astimezone(pytz.timezone('Europe/London')),"%H%M"):print x[m-1].find("title").text,": "+x[0].find("subtitle").text,_ ``` [Answer] # Bash + curl + XMLStarlet, 166 characters ``` d=`TZ=Europe/London date +%H%M` curl -s bleb.org/tv/data/listings/0/bbc1.xml|xmlstarlet sel -t -m "//programme[start<=$d and end>$d]" -v title -m subtitle -o :\ -v . ``` Sample run: ``` bash-4.3$ date Mon Aug 22 14:17:07 EEST 2016 bash-4.3$ bash bbc.sh Bargain Hunt: Carmarthen ``` ]
[Question] [ Credits to [@Agawa001](https://codegolf.stackexchange.com/users/38337/agawa001) for coming up with this question. # Explanation My new "keybore" only has 2 buttons, namely `+` and `-`. The number in the memory starts at `0`. Each consecutive press of `+` or `-` will increment/decrement the memory for exactly how many times it has been pressed consecutively. Therefore, if you press `+` 4 times, first time it adds 1, the second time it adds 2, the third time it adds 3, the fourth time it adds 4, giving you `10` (ten). Now, if you press `-` 3 times, the first time it subtracts 1, the second time 2, the third time 3, leaving you with `4` (four). # TL;DR Given a string of + and -, divide it at each change of character. Then each resulting string of m `+` symbols adds the m-th triangle number, and each string of n `-` symbols subtracts the n-th triangle number. # Walk-through Now, if you still do not understand, I will show you how `+++--+--` creates `1`. ``` Program | Counter | Memory ---------------------------- | 0 | 0 + | +1 | 1 ++ | +2 | 3 +++ | +3 | 6 +++- | -1 | 5 +++-- | -2 | 3 +++--+ | +1 | 4 +++--+- | -1 | 3 +++--+-- | -2 | 1 ``` # Task * You will take a positive integer as input, either as functional argument or from STDIN. * Then, you will output/print the minimum number of keystrokes needed to create that number using the method above. # Testcases Since rearranging the `+` or `-` runs gives the same number, for each such group only the lexicographically earliest sequence is listed. ``` Input | Output | Possible corresponding sequences ------------------------------------------------- 4 | 5 | -+++- 6 | 3 | +++ 9 | 5 | ++++- 11 | 7 | +++-+++ 12 | 7 | +++++--, ++++-++ 19 | 8 | -++++++- 39 | 12 | +++++++++--- 40 | 13 | +++++++++---+, ++++++++-+++- 45 | 9 | +++++++++ 97 | 20 | ++++++++++++++--+---, +++++++++++++-++++--, ++++++++++++-++++++- 361 | 34 | ++++++++++++++++++++++++++-+++-+++ ``` # Extra resources * [Proof that any number can be made](http://chat.stackexchange.com/transcript/message/29964994#29964994): basically, by repeating `++-`, you can obtain any even number. To obtain the odd numbers, just put a `+` at the end. * Another general way to obtain any number. For example, to generate `50`, a way is to press `+` 50 times, and then press `-` 49 times. * [Solution of the first 50 numbers](http://pastebin.com/Cfq7A8Eg). * [Obligatory JSFiddle](https://jsfiddle.net/ryr5tqt5/8/). # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes wins. [Answer] # Python 2, 119 bytes ``` def g(n,i=0,s=''): c=x=t=0 for d in s:C=int(d)*2-1;t=(c==C)*t+1;c=C;x+=c*t return(x==n)*len(s)or g(n,i+1,bin(i)[3:]) ``` Very slow brute-force approach. The third line computes the score of a string `x`; the other lines loop over all possible binary strings until one whose score equals the argument is found. @Leaky saved three bytes! [Answer] # Pyth, 25 bytes ``` ffqyQ.as-Mc*RhdY2{s.pM./T ``` [Try it online.](https://pyth.herokuapp.com/?code=ffqyQ.as-Mc*RhdY2%7Bs.pM.%2FT&input=19&debug=0) This is extremely inefficient, and runs out of memory for `f(n)` ≥ 11. It calculates `f(22)` = 10 in about 10 seconds on my laptop. ### Explanation * Starting from 1, loop through numbers `T`. (`f`) + Generate all partitions of `T`. (`./T`) + Generate all permutations of those. (`.pM`) + Flatten the list. (`s`) + Uniquify the list. (`{`) This step *could* be removed, but it makes the code much faster. + Filter the resulting permutations of partitions: (`f`) - Multiply each number `d` of the partition (`*R`) by itself plus one (`hd`). This gives double the number to add/subtract to the result. - Chop the list to parts of length 2. (`c`…`2`) - Subtract any second number in those parts from the second number. (`-M`) - Sum the results. This gives double the resulting number if the partition permutation was interpreted as number of additions, then subtractions, etc. - Take the absolute value. (`.a`) If the result was negative, swapping the additions and subtractions gets the positive result. - Check if the result equals double the input. (`qyQ`) In this case the partition permutation is correct, return it. + If the filter returned any results, there was a solution of length `T`. Return and print `T`. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~43~~ 29 bytes ``` E:"@TFEqZ^!"@Y'tQ**s]vGE=a?@. ``` This is memory- and time-inefficient. The online compiler can handle up to input `45` only. [Try it online!](http://matl.tryitonline.net/#code=RToiQFRGRXFaXiEiQFkndFEqKnNddkdFPWE_QC4&input=MTk) Here's a [modified version](http://matl.tryitonline.net/#code=IkBFWEo6IkBURkVxWl4hIkBZJ3RRKipzXXZKPWE_QEQu&input=WzQgNiA5IDExIDEyIDE5IDM5IDQwXQ) with all test cases up to `40` (it takes almost a minute in the online compiler). ### Explanation This tests all possible key-press sequences of each length, in order of increasing length, until a valid sequence is found. ``` E: % Range [1 2 ... 2*N] where N is implicit input. The required sequence length is % less than 2*N, so this is enough " % For each @ % Push current value: length of sequence TFEq % Push array [1 -1] Z^ % Cartesian power. Gives all possible sequences of 1, -1 of that length ! % Transpose. Each sequence is now a row " % For each sequence @ % Push current sequence Y' % Run-length decoding: Pushes an array of values 1 and -1, and then an % array of run-lengths tQ* % Duplicate, add 1, multiply. Gives twice the triangular number for each run * % Multiply element-wise by 1 or -1 to produce correct sign s % Sum of array. This is the number produced by the current sequence ] % End for v % Concatenate all numbers into an array GE=a % True if any of those numbers equals twice the input ? % If so @ % Push current sequence length. This is the final result . % Break loop % End if % End for % Implicit display ``` [Answer] # Python, ~~105~~ 100 bytes Uses an inefficient breadth-first search. ``` def k(n): m=t=l=0;h=[] while m-n:o=1-2*(t>0);(m,t,l),*h=h+[(m+t-o,t-o,l+1),(m+o,o,l+1)] return l ``` * `h` is a list used as a queue * `m` is the value of the sequence at the head of the list * `t` is the last number added to `m` * `l` is the length of the sequence that generated `m` * `o` is +/-1, the sign is opposite the sign of `t` Edit: Leaky Nun shaved five bytes. ]
[Question] [ [The inspiration for this challenge should be ridiculously obvious at the time of posting.](https://codegolf.stackexchange.com/q/70638/44713) ## The Task You must create a Shut the Box style program (not function, program). The basics of shut the box are: Players attempt to shut the box by turning a set of levers labelled 1-9. They must do so by flipping levers. The sequence of events of each turn are as follows: 1. The current position of the levers are shown. * On a new game, the position of the levers should be displayed as `123456789`. * On a game with shut levers, all shut levers are displayed as `-`. For example, on a game that has 1, 5, and 9 shut, the output would be `-234-678-`. 2. The di(c)e (is|are) rolled. * If levers 7, 8, and 9 are all off, only one six-faced die is thrown. Otherwise, 2 six-faced dice are thrown. 3. The player is prompted to choose how many levers they wish to flip. * If the player chooses a number >9 or <0, the game ends. * If the player chooses an already shut lever, the game ends. 4. The player selects that many levers. * If the sum of the levers does not equal the value of the di(c)e thrown, the game ends. 5. If all the levers are shut, congratulations, you win. Otherwise, go back to step 1. ## Rules for the Program * On each turn, you should output the current positions of levers. * You must output the value of the roll with the phrase `You rolled:` (note the space). * You must prompt (and wait) for the number of levers to switch with the phrase `How many levers to flip:` (note the space). * You must prompt (and wait) for as many levers as the player specified with the phrase `Which lever to flip:` (note the space). * You must flip the specified levers. * If at any point the game ends, you must output `Game Over`. * If the player finishes a turn with no levers open, you must output `You win!` ## Example Games ``` 123456789 You rolled: 5 How many levers to flip: 5 Which lever to flip: 1 Which lever to flip: 2 Which lever to flip: 3 Which lever to flip: 4 Which lever to flip: 5 Game Over ``` ``` 123456789 You rolled: 5 How many levers to flip: 3 Which lever to flip: 2 Which lever to flip: 2 Which lever to flip: 1 Game Over ``` ``` 123456789 You rolled: 12 How many levers to flip: 2 Which lever to flip: 3 Which lever to flip: 9 12-45678- You rolled: 6 How many levers to flip: 2 Which lever to flip: 2 Which lever to flip: 4 1---5678- You rolled: 11 How many levers to flip: 2 Which lever to flip: 5 Which lever to flip: 6 1-----78- You rolled: 8 How many levers to flip: 1 Which lever to flip: 8 1-----7-- You rolled: 8 How many levers to flip: 2 Which lever to flip: 1 Which lever to flip: 7 --------- You win! ``` [Answer] # Python 3, 348 Saved 5 bytes thanks to Mathias Ettinger. Saved 7 bytes thanks to DSM. Ooof, this is a long one. I also hate that there's not a good way to do test cases. ``` from random import* *l,='123456789' q=['-']*9 r=randint p=print f=' to flip: ' while l!=q: p(*l,sep='');t=r(1,6)+r(1,6)*(l[6:]!=q[6:]);p('You rolled: %s'%t);d={int(input('Which lever'+f))for _ in' '*int(input('How many levers'+f))} if len(set(d))-len(d)+1-all(str(x)in l for x in d)+t-sum(d):exit('Game Over') for x in d:l[x-1]='-' p('You win!') ``` [Answer] # C, ~~405~~ ~~403~~ ~~398~~ ~~392~~ ~~390~~ 387 bytes ``` #define R 1+rand()/(2147483647/6+1) #define G return puts("Game Over"); #define I(s,w)printf(s);scanf("%d",&w); w,s;main(r,l){char b[]="123456789";for(srand(time(0));w^9;w=strspn(b,"-")){puts(b);printf("You rolled: %d\n",r=R+(strspn(b+6,"-")<3?R:0));I("How many levers to flip: ",l)for(;l--;s+=w,b[w-1]=45){I("Which lever to flip: ",w);if(w>9|w<0|b[w-1]<48)G}if(s^=r)G}puts("You win!");} ``` ## Ungolfed ``` /* Macro to get random integer in range [1,6] */ #define R 1+rand()/(2147483647/6+1) i; /* Index variable */ main(r,l,w,s) { /* Running game board */ char b[]="123456789"; /* Run while still levers not pulled */ for(srand(time(0));i^9;i=strspn(b,"-")) { puts(b); /* Print game board */ r=R+(b[6]^45||b[7]^45||b[8]^45?R:0); /* Get dice roll */ printf("You rolled: %d\n",r); /* Print dice roll */ printf("How many levers to flip: "); scanf("%d",&l); /* Get # of levers */ for(i=s=0;i++<l;s+=w) { printf("Which lever to flip: "); scanf("%d",&w); /* Get lever # */ if(w>9||w<0||b[w-1]==45) /* If invalid lever or lever already pulled, game over man */ return puts("Game Over"); b[w-1]=45; /* flip the lever */ } if(s^r) /* If sum does not equal roll, game over */ return puts("Game Over"); } puts("You win!"); } ``` Edit: D'oh! Left an unused variable in my golfed answer. I had removed it but pasted the wrong version. [Answer] ## PowerShell v2+, ~~330~~ 322 bytes ``` $a=1..9;$r={1+(Random 6)};for($g="Game Over"){($o=-join$a-replace0,'-');if($o-eq'-'*9){"You win!";exit}"You rolled: "+($b=(&$r)+(&$r)*(($a|sort)[8]-ge7));$l=Read-Host "How many levers to flip";if(9-lt$l-or1-gt$l){$g;exit}while($l){$b-=($i=Read-Host "Which lever to flip");$a[$i-1]-=$I;$l-=1}if($b-or($a|sort)[0]){$g;exit}} ``` ### Newlines for clarity: ``` $a=1..9 $r={1+(Random 6)} for($g="Game Over"){ ($o=-join$a-replace0,'-') if($o-eq'-'*9){"You win!";exit} "You rolled: "+($b=(&$r)+(&$r)*(($a|sort)[8]-ge7)) $l=Read-Host "How many levers to flip" if(9-lt$l-or1-gt$l){$g;exit} while($l){ $b-=($i=Read-Host "Which lever to flip") $a[$i-1]-=$i $l-=1 } if($b-or($a|sort)[0]){$g;exit} } ``` (Rrequires version 2 or later since `Get-Random` didn't exist in PowerShell v1...) ### Explanation: Start with setting the `$a`rray of levers by taking the range `1..9`, and also set `$r` equal to a script block that we execute later (described below with `$b`). The `Game Over` wording gets set to `$g` at the start of an infinite loop `for(){...}`. Each iteration, we set our output `$o` and immediately output it (thanks to the `(...)` encapsulation) by `-join`ing together the array and replace each `0` with a `-`. (The `0` is explained below). If the output is equal to 9 hyphens, output `You win!` and `exit`. Next, we set our dice rolls to `$b` by calling the stored `$r` (via `&`) with some additional parameters. The `Get-Random` command with a `-Maximum` of `6` (the `-Maximum` is implied) will produce an integer from 0 to 5, inclusive. We add `1` on to that to get a six-sided die, and add that to another random die roll multiplied by `(($a|sort)[8]-ge7)` which checks whether the highest value left on the levers is one of `7,8,9` by first sorting `$a` and then taking the last element and checking whether it's greater-than-or-equal-to `7`. We use implicit typecasting to turn the Boolean value into either 0 (False) or 1 (True) for the multiplication, so the additional "die" is either `die*0` or `die*1`. We then output the result of the die roll. Next is the `Read-Host` into `$l` for how many levers. Note that PowerShell [automatically adds](https://technet.microsoft.com/en-us/library/ee176935.aspx) the colon-space `:` after a `Read-Host` prompt, so we get that for free at least. We then check that the number of levers the user wishes to flip is between 1 to 9, else `exit`. Now we enter a `while` loop. Each iteration of this loop, we `Read-Host` which lever, store that into `$i`, and subtract that value from `$b`. We then also subtract the corresponding lever in the array, and subtract how many additional times to query the user. The last line (excepting the closing brace) tests two Boolean constructions. The first, just `$b`, will only be `$True` if the user didn't properly subtract all numbers from the die roll (in PowerShell, any non-zero number is Truthy). The other condition sorts `$a` and takes the minimal value. If we subtracted the same lever twice, then the minimal value will be negative (or Truthy), otherwise the minimal value will be `0` (or Falsey). ### Example Run: ``` PS C:\Tools\Scripts\golfing> .\shut-the-box.ps1 123456789 You rolled: 6 How many levers to flip: 1 Which lever to flip: 6 12345-789 You rolled: 6 How many levers to flip: 2 Which lever to flip: 2 Which lever to flip: 4 1-3-5-789 You rolled: 6 How many levers to flip: 2 Which lever to flip: 1 Which lever to flip: 5 --3---789 You rolled: 10 How many levers to flip: 2 Which lever to flip: 3 Which lever to flip: 7 -------89 You rolled: 9 How many levers to flip: 1 Which lever to flip: 9 -------8- You rolled: 8 How many levers to flip: 1 Which lever to flip: 8 --------- You win! ``` ]
[Question] [ Write a program or function that given some text, a number of columns, and the column width, formats the text into columns. This is plain text [typography](/questions/tagged/typography "show questions tagged 'typography'"). # Rules ## Input * The text will be a string of printable ASCII and may contain newlines and spaces (but not tabs). * The number of columns will be a positive integer. * The column width is an integer greater or equal to 2 that specifies how many characters per column. For this challenge, a word will consist of any non-whitespace characters. The input consists of one string and two integers, which may be taken in any order. ## Output Output is the text formatted into balanced columns with as many words on each line as will fit. * If a word is too long to fit in a column, put the word on the next line if there is another word on the current line and the line could be padded to the column width with three spaces or less. * Otherwise, hyphenate the word so that it fills the rest of the line. Hyphenate wherever the line ends; don't worry about hyphenating between syllables. * Columns should be separated by a margin of four space characters. * The columns should be balanced so that they all have an equal number of lines if possible. * The leftmost columns should have an extra line if necessary. * Any line breaks and multiple spaces should be preserved. Trailing spaces are optional after the last column. # Examples Text: ``` The number of columns will be a positive integer. Columns should be separated by a margin of four space characters. The columns should be balanced. The column width is greater than two. ``` Columns: 3, width: 10 ``` The number separated ns should of columns by a marg- be balanc- will be a in of four ed. The positive space cha- column wi- integer. racters. dth is gr- Columns eater than should be The colum- two. ``` Text: ``` This line is hyphenated. This line, on the other hand, is not. ``` Columns: 1, width: 20 ``` This line is hyphen- ated. This line, on the other hand, is not. ``` Text: `Tiny columns.` columns: 4, width: 2 ``` T- c- u- s. i- o- m- ny l- n- ``` Text: `Two spaces.<space>` columns: 5, width: 2 ``` T- p- c- s. wo s- a- e- ``` Text: `<newline>A phrase` columns: 2, width: 5 ``` rase A ph- ``` Text: `A short sentence.` columns: 10, width: 5 ``` A sh- ort sent- ence. ``` Text: `It's "no word" 1234567890 -+-+-+-+ (*&!)` columns: 3, width: 6 ``` It's 12345- +-+ "no 67890 (*&!) word" -+-+-- ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); standard rules apply. [Answer] # Python 3, ~~336~~ ~~339~~ 335 bytes [@Jerry Jeremiah](https://codegolf.stackexchange.com/users/24812/jerry-jeremiah)'s recent activity on this question inspired me to try it myself, and see if Python 3 couldn't manage to beat the old Python 2 answer, and, after some painful golfing, I managed to get this slightly shorter: ``` def F(c,w,s): r,R,i,e=[""],[],0," " for j in s.split(e): while 1: if(a:=len(r[i]))+len(j)<=w:r[i]+=j.replace("\n",e*(w-a))+e;break elif a+min(3,w)>w:r[i]+=e*(w-a+1) else:r[i]+=j[:w-a-1]+"- ";j=j[w-a-1:] i+=1;r+=[""] h=-(-len(r)//c);r+=[e]*c;exec(c*"R.append(r[:h]);del r[:h];");return"\n".join(map(" ".join,zip(*R))) ``` [Try it online!](https://tio.run/##bZFNj9owEIbv/IqpD61NTHYDy3YLpdKq0kq9rnqDHEwyENNgW7ZpSv88O04W9VCUKPHHM@@8M@POsbFm9uT85VLjDl54JTsZxGIEXr5KLXG1ZqyU61LeSwZsBDvr4QDaQMiDa3XkmGDoGt0iFGkJesfVYtWi4X6tSyGytDyIr6tukQ6y1SH36FpVIWcbwySOeTdRxOFy61H9ShrY6h2o7KgNn8lOfLuGDmxWiAEKeJVcL@h8UpQZmwBbHuig3y/K3lG2KpY@62sZQbOa8ElvT9zdVaK/wHJcLfEPVrwas9dcOYemJv@LphTLGlvol0tGNMaTN8l4frBk76gcZ5Rj2Mq/2vHxqxDi4rw2kb@Q/4J697NBMKfjFj3YHVS2PR1NgE63LWwRFDgbdNS/kVobcY8@B/j@DoXGnto6YQGd8ioibc4Uc1R@T5MgvZ09eQiOWgpVQ0gV0YccNia9KXX1n9ZWtcpUWFOifwAZqmMDOsCeJkEiEBtlIHY2Z0KMhpKu/xdeyGlfGvGtNpjimrNr0CSP@ZD7/U6CJR1KZOnjgVRrmXhj403pBzklZW3OV@s3qXlPdRaG4qnkW9RUziUNDJ7BNV4FvFnKfYKeU4N8pEbTFKg7N5PO5KNkP@KnABtmLHTW1xsGxXT2MH/8/PTlHibZ8AAff/wgSOLyBg) Takes three arguments, as `columns, width, text`. It does require that all newlines in the input have a leading and trailing space, despite my best efforts to fix that. Edit +3 bytes: Thanks @jezza\_99 for pointing out it was erroring out, turns out my golf of assigning `w-a` to `b` didn't work, because the assignment wasn't in code that ran every loop. Edit -4 bytes: -3 from @Sylvester Kruin spotting that I could save bytes by defining a variable for `" "`, and another -1 by cleaning up the line that pads `r` so the `zip()` doesn't truncate the text if some of the columns in the final row aren't filled up. ## Ungolfed code and explanation ``` def F(c,w,s): r,R,i=[""],[],0 for j in s.split(" "): ## Loop through each word in the input while 1: ## While we havent finished adding this word if (a:=len(r[i]))+len(j)<=w: ## If theres room for the full word r[i]+=j.replace("\n"," "*(w-a))+" " ## Add it + a trailing space, and if the string is a newline, replace it with enough spaces to finish the line break ## Break to next word elif a+min(3,w)>w: # If this line can be padded with spaces r[i]+=" "*(w-a+1) ## Pad with spaces else: ## Need to hypenate r[i]+=j[:w-a-1]+"- " ## Add as much word as can fit plus the hypen j=j[w-a-1:] ## Trim the part of this word we added i+=1 ## Jump to next line r+=[""] ## Initialize that line to the empty string h=-(-len(r)//c) ## Determine column height r+=[""]*c ## Pad the last row with empty strings so the zip() truncate it if some of the columns are incomplete for j in range(c): ## Convert the flat list into a list containing each column R.append(r[:h]) del r[:h] return "\n".join( ## Join each line with a newline map(" ".join, ## Use map() to .join the columns of each line with 3 spaces zip(*R))) ## Zip the lists to get a list of each line ``` [Answer] # Python 2, ~~346~~ 338 bytes ``` i,C,W=input() r=[] for l in [x or' 'for x in i.split('\n')]: while l: if' '==l[0]:l=l[1:] w=l[:W];x=W;s=w.rfind(' ')+1 if max(W-3,0)<s:w=w[:s];x-=W-s elif x<len(l)and' 'not in l[x:x+1]:w=w[:-1]+'-';x-=1 r+=[w];l=l[x:] r=[s.ljust(W)for s in r+['']*(C-1)] print'\n'.join(' '.join(s)for s in zip(*zip(*[iter(r)]*((len(r))/C)))) ``` Input as `'string',C,W` [Answer] # C++ 386 **Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter** ``` #import<bits/stdc++.h> #define b t.push_back #define r l.substr using namespace std;main(int n,char**a){int i=0,p,c=atoi(a[1]),w=atoi(a[2]);vector<string>t;for(string l;getline(cin,l);)for(;p=l.find_last_of(" \n",w),l=~p&&p>w-4?b(r(0,p)),r(p+1):w/l.size()?b(l),"":(b(r(0,w-1)+"-"),r(w-1)),l[0];);for(p=~-t.size()/c+1;i<p;i+=puts(""))for(n=0;n<c;b(""))cout<<left<<setw(w+4)<<t[i+n++*p];} ``` [Try it online!](https://tio.run/##ZVFBbtswELz7FQsFCEhTkq02p1ByDvlCb65hUBQlEaVIglxFaIvm6yplp@2hF4KzOzsz2JXeF4OU6/qgJ@8C1q3GeIjYScbK8bR76FSvrYIWsPRzHK@tkN/@VgOYMs5txLCbo7YDWDGp6IVUkCT4JLQl2iLYXI4i7PeC/tygbo65z2Uj0GkiztWF5ssf8OlC@ZuS6EKdZJPmCXnvArkDMHxQaJI3kdrmhnK6NblvTJkSdVcjIl5dTzL4arN8oblp3v3joz8txdNLSwJJzpTmgXhW0eflkPLrH4rQ1DM0z7JncictRUVZVmQbdfsnofPxwukti2/eC/wYPEhWcV17rlnjZ4wky@gtk22O3NaSt7eKdDPWtVF9eqPChSzsidY1njWzjO39hf9a1y@jAjtPrQrgepDOzJONsGhjoFUgwLuoUb8pSEtUgwolwOsHKY5uNt1Gi8qLIFAl8D3NTCIM2m56vZsD3I@zXUNIVCGWu93mKv@TaYURVqouefwjpCwdjqAjDEEljwA4Cgu4uHL9vFbH3w "C++ (gcc) – Try It Online") ]
[Question] [ I have some books and a bookshelf. I would like to put as many books on the shelf as possible but I have a rule. All dimensions of the books (height, width and depth) should form a non-increasing sequence on the shelf. This means every books has to be at least as high as the ones after it on the self. The same goes for the width and depth. You can not rotate the books to swap their height, width and depth. You should write a program or function which given the dimensions of all the books as input outputs or returns the maximal number of books I can put on the shelf. ## Input * A list of triplets of positive integers where each triplet defines a book's height, width and depth. * There will be at least one triplet in the input list. * Two books can have the same lengths along any number of dimensions. ## Output * A single positive integer, the maximal number of books that fit on the shelf obeying the rule. ## Time complexity Your algorithm should have a worst-case [time complexity](http://en.wikipedia.org/wiki/Time_complexity) polynomial in the number of books. This means that for example the following time complexities are all valid: O(N^3), O(log(N)\*N^2), O(N) and the following ones are invalid: O(2^N), O(N!), O(N^N). ## Examples Input => Output ``` (1, 1, 1) => 1 (5, 2, 5), (1, 3, 5) => 1 (5, 2, 5), (1, 2, 5) => 2 (2, 2, 2), (2, 2, 2), (2, 2, 2), (1, 3, 6) => 3 (1, 2, 5), (1, 3, 5), (1, 2, 8), (1, 2, 5), (7, 7, 7) => 4 (5, 19, 3), (9, 4, 16), (15, 16, 13), (7, 4, 16), (1, 13, 14), (20, 1, 15), (9, 8, 19), (4, 11, 1) => 3 (1, 1, 18), (1, 13, 7), (14, 1, 17), (8, 15, 16), (18, 8, 12), (8, 8, 15), (10, 1, 14), (18, 4, 6), (10, 4, 11), (17, 14, 17), (7, 10, 10), (19, 16, 17), (13, 19, 2), (16, 8, 13), (14, 6, 12), (18, 12, 3) => 5 ``` This is code golf so the shortest entry wins. A related interesting book sorting challenge: [Book Stack Sort](https://codegolf.stackexchange.com/questions/40252/book-stack-sort). [Answer] # Python 3: 436 bytes At first I saw this as the NP-complete problem of finding the longest simple path in a directed graph *with* cycles. However, every cycle in the graph (actually a complete subgraph) can be represented as a single vertex. In other words, treat identical books as one book, to be placed on the shelf as a unit. We can then construct a directed acyclic graph where a->b means b could follow a on the shelf. Finally, we find the maximum height of the out tree(s) using a recursive method. ``` import sys b=[] n={} r=[] for L in sys.stdin.readlines():z=[int(x)for x in L.split()];r+=[z];z in b or b+=[z] def l(a,b):return a[0]<=b[0]and a[1]<=b[1]and a[2]<=b[2] R=range(len(b)) for i in R: n[i]=[] for j in R:i!=j and l(b[i],b[j])and n[i]+=[j] def L(t): global v;best=0 if t in v: return v[t] for s in n[t]:best=max(best,L(s)+1) v[t]=best+r.count(b[t])-1;return best m=0 for i in R:v={};m=max(L(i)+1,m) print(m) ``` [Answer] # Pyth, 40 bytes ``` KYleolNe.eaK+e+]])olNf.A.eg@YbZeT<Kk]YSQ ``` Not fast, but it is polynomial. Python3 equivalent: ``` def num_books(l): l = sorted(l) s = [] for i, Y in enumerate(l): s.append(max([T for T in s[:i] if all(Y[e] >= t for e, t in enumerate(T[-1]))] + [[]], key=len) + [Y]) return max(len(u) for u in s) ``` [Answer] # Python 2, 231 bytes [**Try it here**](http://ideone.com/NEkpI1) **My program currently gets the last two examples wrong. Can someone help me fix it, please? Thanks.** I sort the list all of the 6 possible permutation orders of the 3 dimensions, then see what the longest continuous ordering relation is in the list, then find the max of those. Also, I know if can be golfed a lot more, but I couldn't figure out if I could use `reduce` to do this. Simply put, this way was the easiest to make in a reasonable time without my brain exploding. ``` from operator import* from itertools import* def f(t): m=1 for l in(sorted(t,key=itemgetter(*o))for o in permutations(range(3))): c=1 for k in range(len(l)-1): c+=all(i<=j for i,j in zip(l[k],l[k+1])) m=max(m,c) print m ``` ]
[Question] [ The difficulty with sharing pizza with friends is that it is hard to make sure that everyone gets the same amount of pepperoni on their slice. So, your task is to decide how to fairly slice a pizza so that everyone is happy. ## Directions Write a program that, given a list of the positions of pepperonis on a circular pizza and the number of slices to be made, outputs a list of the angles that the pizza should be cut at so that each slice has the same amount of pepperoni on it. * The pizza has only one topping: pepperoni. * Your friends don't care about the size of their slice, just that they are not cheated out of any pepperoni. * The pizza is a circle centered on the origin `(0, 0)` and with a **radius of `1`**. * The pepperonis are circles that are centered wherever the input says they are centered and have a **radius of `0.1`** * Take input as an **integer** that represents the number of slices to be made and a **list of ordered-pairs** that represent the positions of the pepperonis on a cartesian coordinate system. (In any reasonable format) * Output should be a list of angles given in **radians** that represents the positions of the "cuts" to the pizza (in the **range `0 <= a < 2pi`**). (In any reasonable format) (Precision should be to at least `+/- 1e-5`.) * **You can have partial pieces of a pepperoni on a slice** (eg. If a pizza has one pepperoni on it and it needs to be shared by 10 people, cut the pizza ten times, all cuts slicing through the pepperoni. But make sure it's fair!) * A cut can (may have to) slice through multiple pepperonis. * Pepperonis may overlap. ## Examples **Input:** ``` 8 people, pepperonis: (0.4, 0.2), (-0.3, 0.1), (-0.022, -0.5), (0.3, -0.32) ``` **Possible valid output:** ``` slices at: 0, 0.46365, 0.68916, 2.81984, 3.14159, 4.66842, 4.86957, 5.46554 ``` Here is a visualisation of this example (everyone gets half a pepperoni): ![enter image description here](https://i.stack.imgur.com/6zT9X.png) More examples: ``` Input: 9 people, 1 pepperoni at: (0.03, 0.01) Output: 0, 0.4065, 0.8222, 1.29988, 1.94749, 3.03869, 4.42503, 5.28428, 5.83985 ``` ![enter image description here](https://i.stack.imgur.com/kdd7e.png) ``` Input: 5, (0.4, 0.3), (0.45, 0.43), (-0.5, -0.04) Output: 0, 0.64751, 0.73928, 0.84206, 3.18997 ``` ![enter image description here](https://i.stack.imgur.com/cn5xT.png) ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least number of bytes wins. [Answer] # Mathematica, 221 bytes ``` f=(A=Pi.01Length@#2/#;l=m/.Solve[Norm[{a,b}-m{Cos@t,Sin@t}]==.1,m];k=(l/.{a->#,b->#2})&@@@#2;d=1.*^-5;For[Print[h=B=0];n=1,n<#,h+=d,(B+=If[Im@#<0,0,d(Max[#2,0]^2-Max[#,0]^2)/2])&@@@(k/.{t->h});If[B>A,n+=1;Print@h;B-=A]])& ``` Ungolfed: ``` f = ( A = Pi .01 Length@#2/#; l = m /. Solve[Norm[{a, b} - m {Cos@t, Sin@t}] == .1, m]; k = (l /. {a -> #, b -> #2}) & @@@ #2; d = 1.*^-5; For[Print[h = B = 0]; n = 1, n < #, h += d, ( B += If[Im@# < 0, 0, d (Max[#2, 0]^2 - Max[#, 0]^2)/2] ) & @@@ (k /. {t -> h}); If[B > A, n += 1; Print@h; B -= A] ] ) & ``` This defines a function which takes as parameters the number of slices and a list of pairs for the peperoni coordinates, like ``` f[8, {{0.4, 0.2}, {-0.3, 0.1}, {-0.022, -0.5}, {0.3, -0.32}}] ``` It will print the slices to the console as it traverses the pizza. On most pizzas, this is fairly slow, because (to achieve the required precision) I'm integrating the peperoni area from 0 to 2π in steps of 1e-5. To get a slightly less precise result in a reasonable amount of time, you can change the `1.*^-5` at the end to `1.*^-3`. ## How it works The idea is to sweep out the slices of pizza while integrating over the area of the peperoni pieces covered. Whenever that area hits the required amount of peperoni per person, we report the current angle and reset the area counter. To obtain the peperoni area swept out, we intersect the line with the peperoni to give use the two distances from the origin, where the line intersects with the peperoni. Since a line extends to infinity in both directions, we need to clamp these distances to non-negative values. This solves two problems: * Counting intersections with each peperoni twice, once positive and once negative (which would actually yield to an overall area of 0). * Counting only wedges of peperoni pieces which include in the origin. I'll include some diagrams later. ]
[Question] [ # Strings with Context For the purposes of this challenge, a *string with context* is a triple of strings, called the *left context*, the *data part*, and the *right context*. It represents a substring of a longer string. We use the vertical pipe `|` as a separator, so an example of a string with context is `cod|e-go|lf`, where the left context is `cod`, the data is `e-go`, and the right context is `lf`. This example represents the substring `e-go` of `code-golf`. Now, to concatenate two strings with context, we proceed as follows, using `aa|bcc|dee` and `cc|de|eee` as examples. We align the strings as in the diagram ``` a a|b c c|d e e c c|d e|e e e ``` so that their data parts are adjacent. The data part of the concatenation is the concatenation of the data parts, in this case `bccde`. The left context is the part that extends the furthers to the left of the first data part, in this case `aa`. Similarly, the right context is `eee`, so the concatenation is the string with context `aa|bccde|eee`. For a second example, consider `a|bb|cd` and `aabb|cd|`, where the second word has a empty right context. The alignment diagram is ``` a|b b|c d a a b b|c d| ``` where the left context of the second word extends further than that of the first. The concatenation is `aa|bbcd|`. But wait, there's a gotcha: if the letters of the alignment diagram don't match, the concatenation doesn't exist! As an example, the diagram of `aa|bb|cc` and `c|c|c` is ``` a a|b b|c c c|c|c ``` where the `b` and `c` on the fourth column disagree, so they cannot be concatenated. # The Task Your job is to write a program that takes in two strings with context whose parts are separated by `|` as above, and outputs their concatenation if it exists, and something else if not. The "something else" can be any value, including no output, as long as it's not a valid string with context, and it is the same in all cases. However, throwing an error is not acceptable. You can give either a STDIN-to-STDOUT program or a function, and anonymous functions are accepted as well. The smallest byte count wins, and standard loopholes are disallowed. # Test Cases ``` aa|bcc|dee cc|de|eee -> aa|bccde|eee a|bb|cd aabb|cd| -> aa|bbcd| a|b|cccd aab|cc|c -> aa|bcc|cd a|b|c b||cd -> a|b|cd aa|bb|cc c|c|c -> None aaa|b|c abb|cd|d -> None |bb|cd abb|c|ed -> None a|b|c a||cd -> None ``` [Answer] # Haskell, ~~184~~ ~~182~~ ~~201~~ ~~199~~ 155 ``` s&t|(a,'|':b)<-f t,(x,'|':y)<-f$r s,x#b,a#y=r(y!r a)++b!r x|0<1="" r=reverse a!b=a++drop(length a-1)b (#)a=and.zipWith(==)(r a).filter h f=span h h=(/='|') ``` example run: ``` "|a|"&"|b|" -- returns "|ab|" "|a|x"&"|b|" -- returns "" ``` if there isn't a match an empty string will be returned. otherwise the result would be returned. **partial explanation:** `#` is a function which gets two strings, and returns whether or not they match. `!` gets two strings and returns the first one concatenated with extra character from the second (if there are any). the main function `&` uses `span (/='|')` to split the inputs into two parts, `a|b|c` to `a, b|c`, checks if the contexts match, and then uses `!` twice to assemble the output. **Edit:** mage-late regolfing seems to be pretty effective. [Answer] # Python (242 bytes) ``` import itertools as i s='|' j=''.join r=reversed m=lambda a,b:j(j(*set(p+q))for p,q in i.izip_longest(a,b,fillvalue='')) def c(A,B): u,v,w,x,y,z=(A+s+B).split(s) try:return j(r(m(r(u+v),r(x))))[:-len(v)]+s+v+y+s+m(w,y+z)[len(y):] except:0 ``` ## Explanation The lambda function `m` returns the longer of two strings as long as they share a common prefix. It does this by concatenating the empty string `''` in place of any missing values, then turning the result (which may take the forms `aa`, `ab`, `a`, or `b` in cases of match/mismatch/unequal lengths) into a set of unique characters at each position. `join` expects a single argument, so unpacking a set with more than one element will cause it to raise a `TypeError`. The main function then * uses `m` to combine the *left context and data part* the first word with the *left context* of the second (from right to left over reversed strings) * concatenates data parts, * and again uses `m` to combine the *right context of the first word* with the *data part and right context* of the second The two original words' data parts are trimmed from the right and left sides of the new contexts. Since we know that misalignments cause `m` to raise a `TypeError`, in these cases we catch the exception and implicitly return `None`. ## Testing ``` TESTCASES = [ ('aa|bcc|dee', 'cc|de|eee', 'aa|bccde|eee'), ('a|bb|cd', 'aabb|cd|', 'aa|bbcd|'), ('a|b|cccd', 'aab|cc|c', 'aa|bcc|cd'), ('a|b|c', 'b||cd', 'a|b|cd'), ('aa|bb|cc', 'c|c|c', None), ('aaa|b|c', 'abb|cd|d', None), ('|bb|cd', 'abb|c|ed', None), ('a|b|c', 'a||cd', None), ] for A, B, R in TESTCASES: print '{:<10} {:<9} -> {}'.format(A, B, c(A, B)) ``` ## Output ``` aa|bcc|dee cc|de|eee -> aa|bccde|eee a|bb|cd aabb|cd| -> aa|bbcd| a|b|cccd aab|cc|c -> aa|bcc|cd a|b|c b||cd -> a|b|cd aa|bb|cc c|c|c -> None aaa|b|c abb|cd|d -> None |bb|cd abb|c|ed -> None a|b|c a||cd -> None ``` ]
[Question] [ Pretty soon it's going to be [50 years](http://www.wired.com/thisdayintech/2011/04/0407ibm-launches-system-360-computers/) since IBM unveiled its [System/360](http://en.wikipedia.org/wiki/System/360) family of computers. These were the first to use the [EBCDIC](http://en.wikipedia.org/wiki/EBCDIC) character set. To mark the occasion, let's see who can write the shortest program capable of converting "ordinary" text to and from EBCDIC code page 037. We'll be using a [translation table from Wikipedia that maps CP037 to a superset of ISO-8859-1](http://en.wikipedia.org/wiki/EBCDIC_037#Code_page_translation): ``` EBCDIC037_to_Latin1 = [ 0x00,0x01,0x02,0x03,0x9c,0x09,0x86,0x7f,0x97,0x8d,0x8e,0x0b,0x0c,0x0d,0x0e,0x0f, 0x10,0x11,0x12,0x13,0x9d,0x85,0x08,0x87,0x18,0x19,0x92,0x8f,0x1c,0x1d,0x1e,0x1f, 0x80,0x81,0x82,0x83,0x84,0x0a,0x17,0x1b,0x88,0x89,0x8a,0x8b,0x8c,0x05,0x06,0x07, 0x90,0x91,0x16,0x93,0x94,0x95,0x96,0x04,0x98,0x99,0x9a,0x9b,0x14,0x15,0x9e,0x1a, 0x20,0xa0,0xe2,0xe4,0xe0,0xe1,0xe3,0xe5,0xe7,0xf1,0xa2,0x2e,0x3c,0x28,0x2b,0x7c, 0x26,0xe9,0xea,0xeb,0xe8,0xed,0xee,0xef,0xec,0xdf,0x21,0x24,0x2a,0x29,0x3b,0xac, 0x2d,0x2f,0xc2,0xc4,0xc0,0xc1,0xc3,0xc5,0xc7,0xd1,0xa6,0x2c,0x25,0x5f,0x3e,0x3f, 0xf8,0xc9,0xca,0xcb,0xc8,0xcd,0xce,0xcf,0xcc,0x60,0x3a,0x23,0x40,0x27,0x3d,0x22, 0xd8,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0xab,0xbb,0xf0,0xfd,0xfe,0xb1, 0xb0,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0xaa,0xba,0xe6,0xb8,0xc6,0xa4, 0xb5,0x7e,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0xa1,0xbf,0xd0,0xdd,0xde,0xae, 0x5e,0xa3,0xa5,0xb7,0xa9,0xa7,0xb6,0xbc,0xbd,0xbe,0x5b,0x5d,0xaf,0xa8,0xb4,0xd7, 0x7b,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0xad,0xf4,0xf6,0xf2,0xf3,0xf5, 0x7d,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0xb9,0xfb,0xfc,0xf9,0xfa,0xff, 0x5c,0xf7,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0xb2,0xd4,0xd6,0xd2,0xd3,0xd5, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0xb3,0xdb,0xdc,0xd9,0xda,0x9f]; ``` ## Rules: 1. Your program should take two inputs: (a) a text string, and (b) a flag indicating the operation to be performed. 2. Based on this flag, your program should either convert each byte of text into the corresponding EBCDIC character, or vice versa. 3. Input can be obtained from any sensible sources (e.g., command line arguments, stdin, keyboard input), but must not be hard-coded into your program. 4. Output should be displayed on the screen (e.g., stdout, `document.write`) or written to a file/pipeline. 5. Don't use any built-in or external encoding conversion functions (`iconv`, etc.). 6. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest answer (fewest bytes) will win. ## Examples: (Note: These examples were produced in a terminal configured to use UTF-8 encoding. You may see different results depending on how your system is configured. Hex equivalents are shown for reference only, and don't have to be generated by your code.) ``` Input: "HELLO WORLD", convert to EBCDIC Output: "ÈÅÓÓÖ@æÖÙÓÄ" (0xc8c5d3d3d640e6d6d9d3c4) Input: "ÈÅÓÓÖ@æÖÙÓÄ", convert from EBCDIC Output: "HELLO WORLD" Input: "lower case mostly ends up as gremlins", convert to EBCDIC Output "" <-- unprintable in utf-8 (0x9396a68599408381a285409496a2a393a840859584a240a4974081a24087998594938995a2) ``` [Answer] # Bash + tr, 240 bytes ### Hexdump ``` 00000000 58 3d 27 9c 09 86 7f 97 8d 8e 0b 2d 13 9d 85 08 |X='........-....| 00000010 87 18 19 92 8f 1c 2d 1f 80 2d 84 0a 17 1b 88 2d |......-..-.....-| 00000020 8c 05 06 07 90 91 16 93 2d 96 04 98 2d 9b 14 15 |........-...-...| 00000030 9e 1a 20 a0 e2 e4 e0 e1 e3 e5 e7 f1 a2 2e 3c 28 |.. ...........<(| 00000040 2b 7c 26 e9 ea eb e8 ed ee ef ec df 21 24 2a 29 |+|&.........!$*)| 00000050 3b ac 5c 2d 2f c2 c4 c0 c1 c3 c5 c7 d1 a6 2c 25 |;.\-/.........,%| 00000060 5f 3e 3f f8 c9 ca cb c8 cd ce cf cc 60 3a 23 40 |_>?.........`:#@| 00000070 27 5c 27 27 3d 22 d8 61 2d 69 ab bb f0 fd fe b1 |'\''=".a-i......| 00000080 b0 6a 2d 72 aa ba e6 b8 c6 a4 b5 7e 73 2d 7a a1 |.j-r.......~s-z.| 00000090 bf d0 dd de ae 5e a3 a5 b7 a9 a7 b6 bc bd be 5b |.....^.........[| 000000a0 5d af a8 b4 d7 7b 41 2d 49 ad f4 f6 f2 f3 f5 7d |]....{A-I......}| 000000b0 4a 2d 52 b9 fb fc f9 fa ff 5c 5c f7 53 2d 5a b2 |J-R......\\.S-Z.| 000000c0 d4 d6 d2 d3 d5 30 2d 39 b3 db dc d9 da 9f 27 3b |.....0-9......';| 000000d0 5b 20 24 31 20 5d 26 26 74 72 20 04 2d ff 20 22 |[ $1 ]&&tr .-. "| 000000e0 24 58 22 7c 7c 74 72 20 22 24 58 22 20 04 2d ff |$X"||tr "$X" .-.| ``` Rather trivial solution. Reads from STDIN, prints to STDOUT. ### How to use * To save the script and make it executable, run these commands: ``` base64 -d <<< WD0nnAmGf5eNjgstE52FCIcYGZKPHC0fgC2EChcbiC2MBQYHkJEWky2WBJgtmxQVnhogoOLk4OHj5efxoi48KCt8Junq6+jt7u/s3yEkKik7rFwtL8LEwMHDxcfRpiwlXz4/+MnKy8jNzs/MYDojQCdcJyc9IthhLWmru/D9/rGwai1yqrrmuMaktX5zLXqhv9Dd3q5eo6W3qae2vL2+W12vqLTXe0EtSa309vLz9X1KLVK5+/z5+v9cXPdTLVqy1NbS09UwLTmz29zZ2p8nO1sgJDEgXSYmdHIgBC3/ICIkWCJ8fHRyICIkWCIgBC3/ > ebcdic.sh chmod +x ebcdic.sh ``` * To convert to EBCDIC (encode), execute the plain command: ``` ./ebcdic.sh ``` * To convert from EBCDIC (decode), specify any first argument: ``` ./ebcdic.sh -d ``` ]
[Question] [ \$1729\$, known as the [Hardy–Ramanujan number](http://en.wikipedia.org/wiki/1729_%28number%29), is the smallest positive integer that can be expressed as the sum of two cubes of positive integers in two ways (\$12^3+1^3=10^3+9^3=1729\$). Given an integer \$n\$ (as input in whatever form is natural to your language of choice) find the smallest positive integer that can be expressed as the sum of two positive integers raised to the \$n\$th power in two unique ways. No use of external sources. Fewest characters wins. Note that this is actually [an unsolved problem](https://en.wikipedia.org/wiki/Generalized_taxicab_number) for \$n>4\$. For those numbers, let your program run forever in search, or die trying! Make it so that if given infinite time and resources, the program would solve the problem. [Answer] # APL ~~45~~ 41 ``` {⍺←1⋄2≤+/,⍺=(v∘.≤v)×∘.+⍨⍵*⍨v←⍳⌊⍺*.5:⍺⋄⍵∇⍨⍺+1} ``` Shorter but slower version of 41 chars: ``` {⍺←1⋄2≤+/,⍺=(v∘.≤v)×∘.+⍨⍵*⍨v←⍳⍺:⍺⋄⍵∇⍨⍺+1} ``` You can try it [online](http://tryapl.com/), just paste the function and invoke it with a number: ``` {⍺←1⋄2≤+/,⍺=(v∘.≤v)×∘.+⍨⍵*⍨v←⍳⌊⍺*.5:⍺⋄⍵∇⍨⍺+1} 2 50 {⍺←1⋄2≤+/,⍺=(v∘.≤v)×∘.+⍨⍵*⍨v←⍳⌊⍺*.5:⍺⋄⍵∇⍨⍺+1} 3 1729 ``` (The algorithm is quite dumb though, don't expect the online interpreter to compute n=4) The answer for n=2 is 50 = 5² + 5² = 7² + 1² because its a number that "can be expressed as the sum of two squares of positive integers—doesn't say different—in two ways." If you want to add the distinct clause, just change `(v∘.≤v)` into `(v∘.<v)`, same number of chars, and n=2 becomes 65: ``` {⍺←1⋄2≤+/,⍺=(v∘.<v)×∘.+⍨⍵*⍨v←⍳⌊⍺*.5:⍺⋄⍵∇⍨⍺+1} 2 65 ``` I'm beating GolfScript? Can't be!! [Answer] ## Ruby, 132 ``` n=$*[r=0].to_i;while r+=1 r.times{|a|r.times{|b|next if a**n+b**n!=r;r.times{|c|r.times{|d|puts(r)if c**n+d**n==r&&a!=c&&a!=d}}}}end ``` Pass `n` as command line argument. First line to `stdout` is the solution. Optimized for code-golf, not performance. (Runs correctly. But slow. Does more work than needed.) --- Here is a longer, slightly faster C program. Same correct but horrible algorithm. (I really need to study more theory!) Tested for `n`=2, `n`=3. ## C, 234 ``` #include<stdio.h>#include<math.h> r,a,b,c,d;main(n){scanf("%d",&n);while(++r){for(a=0;a<r;++a){for(b=a;b<r;++b){if(pow(a,n)+pow(b,n)!=r)continue;for(c=a+1;c<r;++c){for(d=0;d<r;++d){if(pow(c,n)+pow(d,n)==r&&a!=d)printf("%d\n",r);}}}}}} ``` The C version takes `n` on `stdin`. As above, first line to `stdout` is the solution. [Answer] ## GolfScript 53 ``` 1\.{;\).,{}@.@\{?}+%.`{\{+}+%~}+%$.`{\{=}+,,4=}+,.!}do) ``` Input is the initial number on the stack. The number on top of the stack at the end is the answer. I'll explain this in more detail when I get a chance. E.g. ``` {1\.{;\).,@.@\{?}+%.`{\{+}+%~}+%$.`{\{=}+,,4=}+,.!}do)}:f 2 f -> 25 3 f -> 1729 ``` This is pretty slow right now. It also counts `0` (so that 25 is the answer for `n=2`, since `25=5^2+0^2=3^2+4^2`. In order to not count 0, add the 2 characters `(;` after the first `,` ``` 1\.{;\).,(;{}@.@\{?}+%.`{\{+}+%~}+%$.`{\{=}+,,4=}+,.!}do) ``` To find that `2 f=65`, since `65=8^2+1^2=5^2+6^2` [Answer] ## GolfScript (30 chars) ``` :N{).,{)N?}%:P{1$\-P?)},,3<}do ``` Note: this is quite slow, because it does a brute-force search rather than something elegant like a priority queue. The most elegant thing about it is reusing `N` as a lower bound from which to search: this is valid because `1^N + 2^N > N` for all `N`. Takes `N` on the stack, leaves the corresponding taxicab number on the stack. To take `N` from stdin, prepend `~`. The version above allows `x^N + x^N` (so for `N=2` it gives `50`). To require adding distinct numbers (giving `65` instead), change the `3` to `4`. To allow `0^N + x^N` (giving `25`), remove the `)` immediately before `N?`. [Answer] # Mathematica, 58 chars A very very slow solution using generating function: ``` 0//.i_/;(D[Sum[x^(n^#),{n,1,i}]^2,{x,i}]/.x->0)/i!<4:>i+1& ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` Œċ*§ċ⁸=2 1ç1# ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//xZLEiyrCp8SL4oG4PTIKMcOnMSP///8z "Jelly – Try It Online") This is *very* inefficient for \$n = 3\$ and doesn't complete within 60s. However, this can be fixed for an additional [4 bytes](https://tio.run/##y0rNyan8/z9Iy@ZY@6PGHUcnHek@tPxIN5Bpa8RleHi5ofL///@NAQ "Jelly – Try It Online") ## How it works ``` Œċ*§ċ⁸=2 - Helper link. Takes an integer i on the left and a power n on the right Œċ - Yield all pairs, choosing with replacement * - Raise each to the power n § - Take the sum of each ċ⁸ - Count the occurrences of i in this list =2 - Is this equal to 2? 1ç1# - Main link. Takes a power n on the left 1 - Set the return value to 1 ç1# - Return the first positive integer, i, where running the helper link with i on the left and n on the right is True ``` ]
[Question] [ Create a function that takes a string of a pinyin syllable as the argument, and returns true of the combination exists, false otherwise. Use "v" for "ü". Here is a full list of combinations. <http://www.pinyin.info/rules/initials_finals.html> Examples ``` f("bu") == true f("zheng") == true f("nv") == true f("ri") == true f("cei") == false f("ia") == false f("kian") == false f("qa") == false ``` Please, don't do things like scraping webpages or reading input method files to reduce character count. (If you do, the length of the data will be counted toward character count) One of the purposes of this code golf is to see how rules can be simplified. Shortest code wins. [Answer] ## JavaScript 1.6, 503 496 477 characters ``` function g(s){return/^([bfmpw]?o|[yjqx]ua?n|[ln]ve?|ei?|y[aio]ng|w?[ae]ng?|w?ai?|wei|y?ao|y?ou|y[ai]n?|yu?e|[^aeiou]+u)$/.test(s)|(((k=6*("ccsszzdflmnprtbghkjqx".indexOf(s[0])+(f=s[1]=='h')))|(r="a.e.ai.ei.ao.ou.an.ang.en.eng.ong.ua.uo.uai.ui.uan.uang.un.i.ia.ie.iao.iu.ian.iang.in.ing.iong.u.ue".split('.').indexOf(s.slice(f+1))))<0?0:k>84?r>17^k<108:parseInt("009m2f00b8jb009m2f00b7r3009m2n00b8jj1dwcfz0000rtfjba4f1xgbnjfj01rz1uyfb1009nn61b37cv1uyfa5".slice(k,k+6),36)>>r&1)} ``` Fomatted a little bit more readably (barring any errors in breaking the code into a few lines): ``` function _g(s) { f = s[1] == 'h' k = "ccsszzdfghjklmnpqrtxb".indexOf(s[0]) * 6 k += 6 * f return /^(weng|[bfmp]?o|[yjqx]ua?n|[ln]ve?|[ae]i?|y[aeiu]|y[aio]ng|[ae]ng?|wang?|wai?|we[in]|w[ou]|y?ao|y?ou?|y[ai]n|yue)$/.test(s) | !!(k >= 0 && (1 << "a.e.ai.ei.ao.ou.an.ang.en.eng.ong.u.ua.uo.uai.ui.uan.uang.un.i.ia.ie.iao.iu.ian.iang.in.ing.iong.u.ue".split('.').indexOf(s.slice(f + 1)) & parseInt("00j85300mh2v00j85300mgan00j85b00mh332rsovz0002cp00b8jj00b8jjqmlts000b8jjv2mkfz3uwo3jv203jz3pwvelqmlts000jbaq2m6ewvqmlts03pwvdp".slice(k, k + 6), 36))) } ``` The zero-initial cases plus a few one-offs are tested with a regular expression. After that, the table is encoded as a (concatenated) series of 6-digit, base-36 numbers, one per initial sound. The lookup then uses a pair of `indexOf` calls and a shift to select the right bit. Tested against all cells in the table of combinations (filled cells tested for true, empty cells tested for false). *Edit:* Replaced some of the 36 chars of the base-36 lookup with comparisons since g–, k–, h–, j–, q–, and z– have dense blocks of true/false. *Edit:* Rearranged the bit test to avoid an unnecessary `!!` and compacted the regex more. [Answer] # PHP, 548 characters Granted, it's likely not optimal, but I wrote a regex to match valid pinyin combinations. Reduced characters by replacing repeating substrings with variables. ## Code ``` <?php $a='?|e(i|ng?)';$b='|o(u|ng)|u';$c='|a?n)?|i(a[on]';$d='(a(ng?|o|i)';$e='|ng?)';$f='(i|ng)?';echo(preg_match("/^([bpm](a(i|o$e$a|u|o|i(e|a[on]$e?)|[pm]ou|m(e|iu)|f(a(ng?)?|ou$a|u)|d$d$a?$b(o|i$c?|e|u)?)|[dtnl]$d?|e$f$b(o$c|e)?)|[jqxy](i(a(o$e?|e|u|o?ng|n)|u(e|a?n))|([zcs]h?|r)i|[nl](ve?|i(n|ang?|u))|[dl]ia|[dt](ing|ui)|[dn]en|diu|([gkh]|[zcs]h?)(e(ng?)|a(o|ng?|i)?|ou|u(o|i|a?n)?)|r(e(ng?)?|a(o$e$b(a?n?|o|i)?)|[gkh](ei|ong|u(a$f))|[zcs]hua$f|([zcs]|[zc]h)ong|(z|[zs]h)ei|a(i|o$e?|ou$a?|w(u|a(i$e?|o|e(i$e))$/",$argv[1]))?"true":"false"; ``` ## Usage ``` > php pinyin.php bu > true > php pinyin.php cei > false ``` [Answer] # F#, 681 characters ``` type l=Y|J|Q|X|W|F|B|P|M|N|L|T|D|Z|K|H|Zh|G|Sh|Ch|C|S|R|Iong|Vn|Van|Ia|Iu|In|Iang|Ve|V|Ian|Iao|Ie|Ing|I|Ei|A|Ai|An|Ang|Eng|U|Ao|E|Ou|Uo|Uan|Un|Ui|En|Ong|Ua|Uang|Uai|Ueng|O let v x=x.GetHashCode() let n x=J.GetType().GetNestedType("Tags").GetFields().GetValue(v x).ToString().Substring(6).ToLower(); let(^)a b=List.collect(fun x->List.map(fun z-> n x+ n z)b)a let(-)a b=[v a..v b] let(&)a b=a@b let(!)a=[v a] [<EntryPoint>] let main a= printf"%b"(List.exists(fun x->x=a.[0])(Y-X^Iong-I& !W^Ei-Ui@Ua-O& !F^Ei-A@An-U@ !Ou&(F-N@D-Sh)^ !En&F-M^ !O&B-M^ !In&N-L^Iu-Un& !D^Ia-Iu&B-D^Ian-Ao& !M^E-Ou&Ch-S^A-Ong&T-Sh^Ei-Ui&N-G^ !Ong&K-Ch^Ua-Uai& !R^An-Ua&(Sh-R@ !Z@ !Zh)^ !I&["lia";"pou";"mui"])) 0 ``` Doesn't quite get the syllables without initial consonant correct (Y, W etc). [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 475 bytes ``` s←⊢⊆⍨' '≠⊢ a b c←2097144 131064 1957895 f←{(⊂⍵)∊(12↑v),(s'yi ya ye yao you yan yang yin ying yong yu yue yuan yun wu wa wo wai wei wan wang wen weng nv lv nve lve'),(,⊤(a-8)1966080 393208 1966064 2096720 1966072 1048568a a 2056184a 131048a 7288b 7280 106488b 7280b 0 1958911 73735c c 352263c 24583 1859591c,5⍴7)/,('bpmfdtnlgkhzcs',s'zh ch sh r j q x')∘.,v←'aoe',s'ai ei ao ou an ang en eng ong u ua uo uai ui uan uang un ueng i ia ie iao iu ian iang in ing iong u ue uan un'} ``` [Try it online!](https://tio.run/##1ZZLjuM2EIb3fQrubAOejB/t12kCmZZLtGWqbYq25SCzyKKRaaCBZJdlMMhiDpBcIEfxRTqs/2f3HQK0vr/FIlkPlSkVT/WnTVfUjXwqr23pN@Xm7S3cn3@7v3y7vzzfX7/3TO/@9c90@1CYtbHJNBmtFuPHRzOejkfzJKvZYrmaPWyT6af@/eWX@@s/g/uvL/3x5P78@3kw7Ide50xXmK5MbEzXxKReLzGd83qlfxpFssQ0K6o5enOJ5lKYS5PozKVMVzJcdN2l9HqJ8WdTnxPLJGUveRveX/7qF5@Wg/FqPh8tR2a6mk5GS4PbFG8Kf76YjHi/mJjx6HE5my8LUyTTbD5ePhZI7TENLSbL5VqZpqe17zdro8tny9V4bBbTxXRmjTXT2WQyn1ozeZwtp2a8nK1mq7Edzu6vfy8Gn4f93vrpsN20vpZ9dbOhNwy9W2VsZUJlTmZnjubaS3X744fhOVWyVzSlTkl5p7RT1VLRUu6aespcE9d6RRMLE5tEZ2L6SzOiTkmlizrHGVcYVyY2xsUkXq80nlQl71Fype/9/NYW6@T9fxHsw0N7iqU2a29dpDZ9UhwUW8VG0Sq8olaIYq@oFDeFVQTcYtCCAdRr3ejeioNiq8BdqU4UrcIraoUo9opKcVNYRcAtBi0YwJNCr3XhkIZDHg45OCThkIVDGg55OCTikIlDKg65OCTjmI1jOo75qADrEn7AA7gFN2ALerAGBdyDFXgjeRMowLpAtcADuAFb0IM1KOAerMAbaMHAERosJVBOIP00EY8l4rkoN2ALerAGBdyDFXgDLRg4QoOlBMoJBNaFR24euXn0mUeGHhl6ZOiRoUeGHhl6ZOiRoUeGHhl6ZuiZoWeGHhkqgeRT6FToVehW6FfoWOhZ6FroW@hc6F3oXuhfGIDkCCSHIDkGYRCCKAQdg9TBA7gFN6AHBdyDFXgDLRg4QoOlBMoJBJIfoSOhJ6EroS@kS/GUmiKUPaWi3CiWEvJgNtqsIeuJkl01dEXxlJoilD2lotwolhLyYDbarCfKWnvpCY2LvkXbomvRtOhZtCw6Fg2L7kRvojPZrOxVtio6VXHhShxzYBV5skUebZFnG@QEXnBWRvxIQQ/WoIB7sAJvoAUDR2iwlEA5gRfuwcOKUsV8OMV8OsV8PFEvPPYiDiJQIldzMdaCFgwx75Y3y3s5hIANebJF/kYpnlJThLKnVJQbxVJCHsxGmzVkPVEuH9tJ3k/yhvK@WN5Xy/ty4UJ0XWSMDJERckfGx/AYHYNjbDm0HFkOjHEhrDITzYeTHwc/6oI647zHcY9iopQoJGvL0rKyKKxipzgqroqOu@FFC@7AI3gFO7xMXYkASkSANyjYgh6swR14BK9gh3ek48lPOVA2lJbiKTVlRzlSrpQur8ZvD/RgDe7AI3gFO74AHN8AlANlQ2kpnlJTdpQj5UrpPiZKnil5quS5kicLZ/O50TMdcwM6oh@6oRc4AdMq4TLhOrQZpaV4l8PIUeQgcgwM4d3WZGOTrdQun5Jn3UaxQ/VQPNQO5T3jyYK7iCcLXsEucpzVolwpHWUXaaKFBv0C3BZ1KINJ34CmP0zfrgPzxeCrMJt@9KXQ@mX773eaBuZznsMpT03eQGdwQ53C/97uX7997PTwcZPW/Ac "APL (Dyalog Extended) – Try It Online") Golfing in progress. ### Ungolfed ``` s←{⍵⊆⍨' '≠⍵} con←s'b p m f d t n l g k h z c s zh ch sh r j q x' vwl←s'a o e ai ei ao ou an ang en eng ong u ua uo uai ui uan uang un ueng i ia ie iao iu ian iang in ing iong u ue uan un' tab←con∘.,vwl bin←,⊤2097136 1966080 393208 1966064 2096720 1966072 1048568 2097144 2097144 2056184 2097144 131048 2097144 7288 131064 7280 106488 131064 7280 131064 0 1958911 73735 1957895 1957895 352263 1957895 24583 1859591 1957895 7 7 7 7 7 all←'aoe',(12↑vwl),(s'yi ya ye yao you yan yang yin ying yong yu yue yuan yun wu wa wo wai wei wan wang wen weng nv lv nve lve'),bin/,tab f←{(⊂⍵)∊all} ``` [Try it online!](https://tio.run/##XZZLciJHEIb3nCJ3SBEajwDxOo2jaZrsgqZaUJSaxjGz8GJirIiJsHdeeuHFXMAX8FG4iKby/0uSwwF8P/XMRyXVFI/Nh3VfNK1@qM6nyq@r9ctLuH75/Zfrt3@uz1@u374PZXj97a/U/DQoW5@GwnAlj7KXjazlJF4aUdlJLRcpJcillrKWUMtRtnKQ83Dw1DVYVUgrlRROKidFK22Uwqe3SuXTW6VNnyixkNgmOonpnWZEmxKT2hwnrhBXJbbiYhJvn9Sf1CTvUXGlHw5OxSoZN8e//vnTXXJlsHIWxN31@e/x/XI@msxktJzN7hf3MllOxvcLNmcPkoZn8/E92/OxjO4fFtPZQrDs4eE/Op2NFu/t0cRmvjXn48UCfTN8T/ulb//v4nezNV0sRyOZT@aTqbXmi@W7Tqbj8Wzy1hw/TBeptZgup8vRW@/89TUoGkv8sGir4d3NaHz98keK//buJgx7J30hfZXYSp9Ook/p6i2Rfcpkb6nsLZV9GknJ7C2bfTqDLkpXSNcmOunSOXZpoLN1XTrEzk7IP0nzlFglqYa3dyndH@/SKQw2VlU31@dfUyndXr8@J@8@vZyOsbJyG66KVGePhr1hY1gbTgZvaAxq2Blqw8VQGgKa6CzBANpn1drehr1hY0CrMiOGk8EbGoMadobacDGUhoAmOkswgEeDfVaFQxgOcTjE4BCEQxQOYTjE4RCIQyQOoTjE4hCMYzSO4TjGYwKsKtgB9@AGXIMn0IMNqOAOrMELyUagAKsC2QL34Bo8gR5sQAV3YA1ewBIM7OFASQmUI0g7bcSxRJyLcQ2eQA82oII7sAYvYAkG9nCgpATKEQRWhUdsHrF51JlHhB4RekToEaFHhB4RekToEaFHhB4RekboGaFnhB4RGoFkU2lUaVVpVmlXaVhpWWlaaVtpXGldaV5pX@mAZg80u6DZB6UTCi8UFYPQwT24AdegBxXcgTV4AUswsIcDJSVQjiCQ7CgNKS0pTSltIVyKpzQUpewoNeVCKSkhd@bBMmvIeqRkUy1NUTyloShlR6kpF0pJCbkzD5ZZj5SV1dIjChd1i7JF1aJoUbMoWVQsChbVidpEZbJYWassVVSqoeNKXHNgHXmzRV5tkXcb5Ah2uCsjfqSgBxtQwR1YgxewBAN7OFBSAuUIdtyDlxWljvlyivl2ivl6ona89iIuIlAjV3Mx1oIlGGLeLW@W93JwARvyZov8jVI8paEoZUepKRdKSQm5Mw@WWUPWI6V7207zfpo31NfF@rpaX5crF6LqIn2ki/SQO9I/ukfv6Bx9y65lz7Jj9AtuVZkoPtz8uPiRF@QZ9z2ueyQTqUQimVumlplFYg1bw8FwNvTcDQ9acAsewDPY42HqKjhQwQM8QcET6MEG3IIH8Az2eEY63vyUPWVNOVE8paFsKQfKmdLn1fjtgR5swC14AM9gzweA4xOAsqesKSeKpzSULeVAOVP6t4maZ2qeqnmu5snK2Tw3WqZhbkBDtEMztAIjYFqlXKZchzKjnCjeZTeyF9mJ7ANdeB1r82CbR6l9viWfbBvDFtlD8pA7pPcJJwtuI04WPIN9ZD@zRTlTeso2cogjHEj/zweboglVkPQfUG7sf@KtfBb8K8xDP/tKOfp58@93Dt3KxzyHUx7bvIHN4IY2hd9e3rZ5n/0D "APL (Dyalog Extended) – Try It Online") The helper function `s` unpacks a space-delimited string: ``` {⍵⊆⍨' '≠⍵} monadic function taking a string ' '≠⍵ 0s at spaces, 1s elsewhere ⍵⊆⍨ Partition (split at 0s) ``` I first store the possible initial and final strings in the syllable, then make a table `tab` containing the concatenation of each string from the first list with each string from the second list. Next, I store binary data as a list of integers. Some of the integers are repeated and can therefore be stored in variables, which also allows elision of some spaces. Each integer is decoded into binary, and represents one row of the table. Each bit in the number represents whether a certain syllable in that row is a valid syllable, with the MSB representing the first column. All invalid syllables are removed from the table. We flatten the table into a list, add on the forms with no initial consonant as a special case, and finally check if our input is in the list. Possible further golfing potential: * Write base64 or base255 encoding * Reorder the columns and rows to make the numbers smaller. Python helpful script and test-case generator: [Try it online!](https://tio.run/##jZZPcts2GMXXH0/BugtJjeMZN7tMcpLUCxiCQFgkQBOkLXHV9iTtOZpdbpKLuO99pGk5iWYymvfwh8LDj@RHSu2xr1J89/SUP65Wq1JupZVGdrKVXqLU4mUvlYxiJctYia0kV9LJndzLQb7@9Xdh5NZIa6QxsjOyNdIbiUZqI97I3khlZDRijWR0MLBQhsr5Y4okt0naJE2SXVrmz39S4bRt2Gyd9E6ik9qJd7J3UjkZnVgnGR0MLJShzs3rXWECoAOoA7ADU@A9FKEa8tAeqqARslBmnxOWlitdOJ9DKBwioRZqoB20hXooQjXkoT1UQaObVo@VdnLlXtJcKAyuCdRCjUkKmACYAJgAmACYAJgAmACYAJgAmAiYCJgImKQzzxfUpCINaFt4A@2gLdRDEaohD@2hChohC2X2OWFpmdZpkN6JoTARpBGkEaQRJRDBGsEawYoCgjy0hypohCyU2eeEpWVaB82sEbGeuZ7Bnsme0Z7ZnuGe6Z7xnvmeG3ju4LmF5x6em3jdxes2Xvfx3MgvO/nC4QygFmqgHbR1RInqHr6HKmiELJTZ54SlZVrnnuldRKRnpmeoZ6pnrGcu6GmRVtM8bU@raCPN0rIOddKqZ/XOLfToFWkZoUg46GmRVtM8bU@raCPN0rIOddJWU0p3ElYMcjtIi2JBraBUUCkoFNQJygRVgiJBXaAqUBMsENYHywPV8Vwcj0P5WzGY7x5fj7k9VC3HRnYtLdO65cCjYcTLO2GLfg9FqIY8tIcqaIQslNnnhKVlWrdEPCZlCj@CCqQKxAonXEHBgpK9LHs0gUHhhAzP@jz2A6OYhOccslBmnxOWlmndsvzRIa28Blg8CeRTRIu0muZpe1pFG2mWlnWok1Y9q3cvgY8m6pmfVMvJqbNE1KuTb4zTwE5Nrl4tRp5n4CkweYlLWsKSlagkJSg5FVMpFZKMC6IDYvl7MbgfQJ7/YBlJ8PrF2xcvX32d42bgvYvX7nIrQ/n1z3/ETk2emrFi@y9opjbPbTc1d0HugxyCHEP5pggvlbyd@3UwP0S6w/w9dICOhmsd6BzwHPj0VwveQxGqgzuT4pDikOLk6JQAvwq0ltaE6YeBTU@LtDqYdI4pESqRKgErMXF6Vhttt@oRXofhTMaAiAEJgxzTUL4p3wEqEioSKhIqTlCRUJFQkVDxHFQkVCRUBFTU0/zm/kedqYM5Uxd3euRe/aB@ZHUiiWgkI1hc0gh0joc4pAFMUBi@yWktrQmKsGXT02JQsrNgyqVYpAoTVfrJ@r7Tb96rH9SPSRO@fH59fTCuv5lbMgaU8n9yPzWHqTlqgxj3bY5j0JlyHNwc5eYsN4e5Oe3MTf4@CLd5Spo7h@fOce4g7GeznqOek56DtMU/2qLI5cdytbq6SyGubVXuUleiwd3NZdihexWyqdvKrDelHsI4t8a69WZz1bm2Zvfiy@eLy4uHi01R4G47Ruar3NahX6/@iKvNp@v3N8uRT/VyqNdDb69vdNuau@q3bopfy8416cGV7tDjD4lLQy5tqocm5qIoXn/7fSFtF2K/zkOz/rTOx7qMqefh9apcXa7iA6x@0J7TrlttNh8@rPEHY11v3oa31xsFCJdci3UuDo3rTO9w@GZzifH2I6JweviCnsPF6gLPN0ZXue9Ci4vzpuTcazIdzpk1Lyf7v@B6l6ubopig0Z8uPqM3m6en/wE "Python 3 – Try It Online") ]
[Question] [ An [angry bird](http://en.wikipedia.org/wiki/Angry_birds) is shot at an angle \$β\$ to the horizontal at a speed \$u\$. The ground is steep, inclined at an angle \$α\$. Find the horizontal distance \$q\$ that the bird traveled before it hit the ground. ![diagram showing an inclined plane at angle α and an angry bird being fired at angle β at speed u](https://i.stack.imgur.com/fToDM.png) Make a function \$f(α, β, u)\$ that returns the length \$q\$: the horizontal distance that the bird traveled before it hit the ground. Constraints and notes: * \$-90° < α < 90°\$. * \$0° < β < 180°\$. * \$α < β\$. * \$0 \le u < 10^9\$. * Assume acceleration due to gravity \$g = 10\$. * You may use radians instead of degrees for \$α\$, \$β\$. * Dimensions of \$u\$ are irrelevant as long as they are consistent with \$g\$ and \$q\$. * No air resistance or anything too fancy. Shortest code wins. See the Wikipedia article on [projectile motion](http://en.wikipedia.org/wiki/Projectile_motion) for some equations. Samples: ``` f(0, 45, 10) = 10 f(0, 90, 100) = 0 f(26.565, 45, 10) = 5 f(26.565, 135, 10) = 15 ``` [Answer] # Java Works for radians only ``` double q(double a, double b, double u){ return (Math.abs(((-Math.tan(a)+(Math.tan(b)))*(u*u)*(0.2*(Math.cos(b)*Math.cos(b)))))); } ``` Golfed Version (Thanks to Peter) ``` double z=u*Math.cos(b);return(Math.tan(b)-Math.tan(a))*z*z/5; ``` Maths Used: $$ q = ut\cos \beta \\ q\tan \alpha = ut\sin \beta - 0.5 \times 10 t^2 \\ - \tan \alpha + \tan \beta = 5\frac q {u^2} \sec^2 \beta \\ q = \frac {(\tan \beta - \tan \alpha)u^2} {5\sec^2 \beta } $$ [Answer] ## Haskell (~~37~~ 35) Based on Aman's solution: ``` q a b u=(tan a+tan b)*u*u*cos b^2/5 ``` I think, this problem isn't real code-golf, as it is more implementing a formula than really doing some algorithm. [Answer] # Python3 - 65 chars ``` from math import* f=lambda α,β,u:(tan(α)+tan(β))*u*u*.2*cos(β)**2 ``` ]
[Question] [ # Challenge Your task is to write a program or function which, given a positive integer \$N\$, finds all positive integers less than or equal to \$N\$ that can be expressed as a perfect power in more than one way. # Definition A perfect power is defined as a number \$i\$ found by \$m^k\$, where: * \$m\$ and \$i\$ are positive integers * \$m \ne k\$ # Test Cases ``` input -> output 1000 -> 16, 64, 81, 256, 512, 625, 729 56 -> 16 999 -> 16, 64, 81, 256, 512, 625, 729 81 -> 16, 64, 81 1500 -> 16, 64, 81, 256, 512, 625, 729, 1024, 1296 ``` Please provided a readable, commented version as well. [Answer] ## Mathematica: 103 chars Spaces can be removed ``` Select[Flatten@ Table[ Solve[Log@#/Log@b == k, k, Integers] /. k -> #, {b, 2, #}] & /@ Range@#, Length@# > 2 &][[All, 1, 1]] & ``` Usage: ``` %[81] {16, 64, 81} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 meaningful bytes, language postdates challenge ``` ḊḟÆR *@þ Ḋ F fḊ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wR9fDHfMPtwUpaDkc3qcA5CoouCkopAEZ////NzcAAA "Jelly – TIO Nexus") Here's an entirely different solution. This one's a curious hybrid of efficient and inefficient, using an efficient core algorithm in a very inefficient wrapper (so much so that it can't handle very large numbers). As before, all whitespace is meaningless. Here's how it works. `Ḋ` (which appears several times) is a list of numbers from 2 to the input inclusive: ``` ḊḟÆR *@þ Ḋ F fḊ ḊḟÆR Ḋ, with all primes between 2 and the input removed (i.e. all composite numbers from 4 to the input) *@þ Ḋ Exponentiate all Ḋ elements with all ḊḟÆR elements F Flatten the result (it had a nested structure) fḊ Keep only elements in Ḋ ``` The basic observation here is that a number is a perfect power in multiple ways, only if it's a perfect power with a composite exponent (that isn't 1). We generate a list of those where the base is from 2 to the input, and the exponent is a composite number from 4 to the input; this is really slow because it generates some really big numbers, all of which are an answer to the question. Then we only keep the answers which are in range. It'd easily be possible to modify this into a highly efficient answer, by working out what the maximum power in range was and not iterating any further, but that'd be a lot more bytes, and this is code-golf. [Answer] # Perl: 68 chars Gets the maximum (1000) in `$N` and returns the answer in `@a`. ``` for $x ( 2..$N ) { $c{$x**$_}++ for 2..log($N)/log$x } @a = grep { $c{$_} > 1 } keys %c ``` For a whole program, I need another 18 chars: ``` $m = shift; for $x ( 2..$m ) { $c{$x**$_}++ for 2..log($m)/log$x } print join ' ', grep { $c{$_} > 1 } keys %c ``` [Answer] # Ruby - 101 chars (without whitespace) ``` f=->l{c=Hash.new{0} 2.upto(1E4){|i|2.upto(20){|j|c[i**j]+=1}} c.map{|k,v|v>1&&k<=l&&k||p}.compact.sort} ``` Works for `1 <= limit <= 100,000,000` within 5 seconds. Test ``` > f[10000] [16, 64, 81, 256, 512, 625, 729, 1024, 1296, 2401, 4096, 6561, 10000] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 meaningful characters, language postdates challenge ``` R µ ọḊ *@Ḋ ċ >2 µ Ðf ``` [Try it online!](https://tio.run/nexus/jelly#@x@koHBoq4LCw929D3d0KWg5gMgj3Qp2RhDxwxPS/v//b2kAAA "Jelly – TIO Nexus") All whitespace here is insignificant. I used it to show the structure of my answer, as the question asks. Here's how it works: ``` R µ ọḊ *@Ḋ ċ >2 µ Ðf R Ðf Find all numbers n from 1 to the input, such that: µ µ (grouping marks, like {} in C) Ḋ Ḋ Take the range from 2 to n ọ Find the number of times each divides n *@ Raise the range from 2 to n to these powers ċ Count the number of times n appears >2 and the result must be greater than 2 ``` So for example, when testing n=256, we check the number of times each of the numbers from 2 to 256 divides into 256. The only numbers that divide more than once are 2 (which divides 8 times), 4 (which divides 4 times), 8 (which divides twice), and 16 (which divides twice). So when we raise the number of divisions to the powers determined there, we get: ``` 2⁸, 3, 4⁴, 5, 6, 7, 8², 9, 10, 11, 12, 13, 14, 15, 16², 17, ..., 255, 256 ``` This produces the original value, 256, a number of times equal to the way that 256 is a perfect power, plus one (the last element produces 256 because 256 = 256¹). So if we see 256 more than twice in the array (and we do in this case; 8² is 64 but the other "interesting" elements all produce 256), it must be a perfect power. ]
[Question] [ # Objective Given a [vertex figure](https://en.wikipedia.org/wiki/Vertex_figure) consisting of regular convex polygons, determine whether it represents a convex [uniform polyhedron](https://en.wikipedia.org/wiki/Uniform_polyhedron). # What is a uniform polyhedron? A uniform polyhedron is a polyhedron whose faces are regular polygons, while having the same vertex figure for each vertices. Generally a uniform polyhedron can be nonconvex, but only convex polyhedra will be considered in this challenge. (More precisely, the polyhedron is required to be vertex-transitive, but that's just another detail.) # What is a vertex figure? In the context of a convex uniform polyhedron, a vertex figure is a list of the number of edges of polygons (in order) around a vertex. For example, a cube has vertex figure of (4.4.4). # Truthy inputs > > (3.3.3) – Tetrahedron > > (4.4.4) – Cube > > (3.3.3.3) – Octahedron > > (5.5.5) – Dodecahedron > > (3.3.3.3.3) – Icosahedron > > (4.4.N) for every N≥3 – N-gonal prism (It is a cube for N=4) > > (3.3.3.N) for every N≥4 – N-gonal antiprism (It is an octahedron for N=3) > > (3.6.6) – Truncated tetrahedron > > (3.4.3.4) – Cuboctahedron > > (3.8.8) – Truncated cube > > (4.6.6) – Truncated octahedron > > (3.4.4.4) – Rhombicuboctahedron > > (4.6.8) – Truncated cuboctahedron > > (3.3.3.3.4) – Snub cube > > (3.5.3.5) – Icosidodecahedron > > (3.10.10) – Truncated dodecahedron > > (5.6.6) – Truncated icosahedron > > (3.4.5.4) – Rhombicosidodecahedron > > (4.6.10) – Truncated icosidodecahedron > > (3.3.3.3.5) – Snub dodecahedron > > > Rotations and reversions (generally, all dihedral permutations) of these lists are also truthy. For example, (4.6.8), (4.8.6), (6.4.8), (6.8.4), (8.4.6), (8.6.4) are all truthy. # Falsy examples > > (3.3.3.3.3.3) – Triangular tiling; not a polyhedron. > > (5.5.5.5) – Order-4 pentagonal (hyperbolic) tiling; not a polyhedron. > > (3.3.4.4) – Cannot be uniform. Note that this is different from (3.4.3.4). > > > # *Don't care* situations An input is expected to have at least 3 entries, and to consist of integers that are at least 3. Otherwise, the challenge falls in *don't care* situation. > > (5/2.5/2.5/2) – Great stellated dodecahedron; not convex. > > (3.3) – Triangular dihedron; not Euclidean. > > (2.2.2) – Triangular hosohedron; not Euclidean. > > (3/2.3/2.3/2) – Retrograde tetrahedron. > > (1) > > (-3) > > () > > > [Answer] # [Python 3](https://docs.python.org/3/), 190 bytes ``` def f(F):s="".join(hex(k)[2]for k in F);F[1:]in[[4,4],[3]*3]or{s,s[::-1]}&{*"555 333 366 388 3aa 466 566 468 46a 3434 3444 3454 3535 33333 33334 33335".split()}and max(F)<16or f(F[1:]+F[:1]) ``` [Try it online!](https://tio.run/##nVRNj5swEL3zK6ZEqvAujcIa0igtx0Y99VCt1ANCESImcZfY1DYoaLW/PR0b8rHZlSrVBM@YmXl@nvGk6c1OCno8blgFVbAiS536/vS35CLYsUPwRLKHvJIKnoALWJEvqyxa5lxkWRzGeZjR/I7mUj3rUGfL5acof/n4fOcnSQKUUqDzOdDFAmhRQIx6gm88X@BbAI1pjFNspwSnhLoYG4UjdnPiT3VTcxOQl0JsYF8ckOHXaI58kKtlcr/KllFOjl1R88264oIbBilkHuDIkhAfyzLEx8l5OHdyES6cjGb4Qy0eLcko7XoxSusA9rz2xBOn/MiHDSjqdEhEODo4LRm1BK2JjXYMLAeYjPoF4mw76/GVnuRe7nm2PFyvW8GxGPugq8jShdvSdMbWJuuqELpqqEI@WE8e3DqoQmxZUDMRdIaQi4MdHeasMxnHhKJY8vyVlVfQWRvco0SjRbtO@GssOxQzrRLwqFp2i@QIEEhToGCL2mWzPE27LMI5/k@k@A1Sh9c2Tem/8cb1qqg1G9JsmDbrq1yvxlwZ1V9lFT97N5j@r10PPdMhbKXcgOYKMPf7YlPsQzC7AsukbeqqojS4ZtAxZdgBKr5tFQNZQQHjptDIut@xjZJi6rt92KFkjbkQmMBPVrZKcym@KSXVLZnxQBP4zuoGz6T2XBTYG39aXj7Vvcf3jVQGdK89fKeaGXXCq/keWy6aEc87uWGRlZGy1l5lcdeN1NzwjmnbazXXxt5Id9VK2QpzuW40/Dx87yr78YwzbZTctKUJXPDJN4oICRVrWGFSB0RsnW8LctqPuKoLaeA9Yz5SFWxbnKkiiwuZzDbo7Kr18M/AqvHD2MlDR@eWg93llgfugp3ZKC6Ma6ub1JA0nTmG/g8JzgZn2wefvAk8E30n8GyzgVjUR9XjZdENK3nFS9uMeJ0HwFuWl0MScvwL "Python 3 – Try It Online") Takes input as a list of integers representing the vertex figure. The function [errors](https://codegolf.meta.stackexchange.com/a/11908/68261) (`RecursionError`) if the vertex figure is *not* a uniform polyhedron, otherwise there is no error. I tried several schemes of organizing the finite classes into a smart way that takes advantage of patterns, but hardcoding all possibilities reigned superior since it is a relatively small set. ### Explanation ``` def f(F): # F is a rotation of the input vertex figure; initially is the input vertex figure # Convert to string for easier comparison later in the code s="".join(hex(k)[2]for k in F) # Test true if the permutation is N.4.4.4 or N.3.3.3 (F[1:]in[[4,4],[3]*3]or # Test truthy if permutation (or its reverse) is in # 3.3.3, 3.6.6, 3.8.8, 3.10.10, 4.6.6, 5.6.6, 4.6.8, 4.6.10, # 3.3.3.N, 3.4.3.4, 3.4.4.4, 3.4.5.4, 3.5.3.5 # 3.3.3.3.3, 3.3.3.3.4, 3.3.3.3.5 {s,s[::-1]}&{*"555 333 366 388 3aa 466 566 468 46a 3434 3444 3454 3535 33333 33334 33335".split()} # Numbers greater than 15 would convert into the most-significant hexit when converted to a string, # causing 0x43 to match the same as 0x4, # so we need to check that none of this happened if we want a bugfree string search and max(F)<16 # If we tested truthy, then terminate # Otherwise, recurse with the vertex figure cyclically rotated left one or f(F[1:]+F[:1])) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~54~~ 51 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 2×þ5o6R¤ “EḶ¤ẊƓW4mð,’b6ṣ5ịþ¢Ẏṙ€Ƭ1Ẏ;U$e@ ṢṖ’Ḍe“!ṛ‘ȯÇ ``` A dyadic Link accepting a list of integers (each greater than two) which yields `1` if that list is a vertex figure which represents a uniform polyhedron, or `0` otherwise. **[Try it online!](https://tio.run/##AXMAjP9qZWxsef//MsOXw741bzZSwqQK4oCcReG4tsKk4bqKxpNXNG3DsCzigJliNuG5ozXhu4vDvsKi4bqO4bmZ4oKsxqwx4bqOO1UkZUAK4bmi4bmW4oCZ4biMZeKAnCHhuZvigJjIr8OH////WzUsNCwzLDRd "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/o8PTD@0zzzYIOLeF61DDH9eGObYeWPNzVdWxyuEnu4Q06jxpmJpk93LnY9OHu7sP7Di16uKvv4c6Zj5rWHFtjCGRbh6qkOnA93Lno4c5pQKUPd/SkAk1RfLhz9qOGGSfWH27/f7gdqPj//@hoYx0gjNWJNtEBQiAN5oNFTHWAECECV4WsGkSbQmkzKG0OpS0tzM3g2hFGI4xEyJrDWXBNZlBpE7hmCx0LsMkIGZgbzMAyMHdCVJvCrTI0ACKwfxA6TeE6wVIwraYI4xSADAuQeoVoM6AGCwjDAqRPIdoC4l0Qwww51JBDDu5RkCtjAQ "Jelly – Try It Online"). ### How? First, check if the input is any rotation or reflection of either `4,4,N` or `3,3,3,N` (using `ṢṖ’Ḍe“!ṛ‘`) - the prisms or antiprisms. If not, build a table containing all the other un-permuted, possibilities - the Platonic and Archimedean solids. Then get all dihedral-permutations of that table's values (`Ẏṙ€Ƭ1Ẏ;U$`) and then check for the existence of the input (`e@`). Note: The table actually built includes two redundant rows containing only lists which either contain some value(s) less than 3 or are of the form `4,4,N` in some rotation. To build the table an outer-product using 1-based indexing is made between "items" vectors (of the form `r,2r,3,4,5,6`, where `r` is the row) and "indexes" vectors. ``` | items | indexes --+--------------+---------------------------------------------------------------- r | r,2r,3,4,5,6 | 1,1,1 | 3, 2, 2 | 3,1,3,1 | 1,0,0 | 3,4,1,4 | 4,0,2 | 3,3,3,3,1 --+--------------×-------+---------+---------+-------+---------+-------+---------- 1 | 1, 2,3,4,5,6 | 1,1,1 | 3, 2, 2 | 3,1,3,1 | 1,6,6 | 3,4,1,4 | 4,6,2 | 3,3,3,3,1 2 | 2, 4,3,4,5,6 | 2,2,2 | 3, 4, 4 | 3,2,3,2 | 2,6,6 | 3,4,2,4 | 4,6,4 | 3,3,3,3,2 3 | 3, 6,3,4,5,6 | 3,3,3 | 3, 6, 6 | 3,3,3,3 | 3,6,6 | 3,4,3,4 | 4,6,6 | 3,3,3,3,3 4 | 4, 8,3,4,5,6 | 4,4,4 | 3, 8, 8 | 3,4,3,4 | 4,6,6 | 3,4,4,4 | 4,6,8 | 3,3,3,3,4 5 | 5,10,3,4,5,6 | 5,5,5 | 3,10,10 | 3,5,3,5 | 5,6,6 | 3,4,5,4 | 4,6,T | 3,3,3,3,5 ``` The "indexes" vectors are encoded as a single base-6 integer which is split at its `5` digits (see the start of Link 2). ``` 2×þ5o6R¤ - Link 1, Get the five "items vectors": no arguments 2 - two 5 - five þ - (implicit [1..2]) table (implicit [1..5]) using: × - multiplication -> [[1,2],[2,4],[3,6],[4,8],[5,10]] 6R¤ - range of six -> [1,2,3,4,5,6] o - logical OR (vectorises) -> [[1,2,3,4,5,6],[2,4,3,4,5,6],[3,6,3,4,5,6],[4,8,3,4,5,6],[5,10,3,4,5,6]] “EḶ¤ẊƓW4mð,’b6ṣ5ịþ¢Ẏṙ€Ƭ1Ẏ;U$e@ - Link 2, Platonic or Achimedian?: list of integers (>2), V “EḶ¤ẊƓW4mð,’ - base 250 number = 269760427146828960006295 b6 - in base 6 = [1,1,1,5,3,2,2,5,3,1,3,1,5,1,0,0,5,3,4,1,4,5,4,0,2,5,3,3,3,3,1] ṣ5 - split at fives = [[1,1,1],[3,2,2],[3,1,3,1],[1,0,0],[3,4,1,4],[4,0,2],[3,3,3,3,1]] ¢ - call Link 1 as a nilad = [[1,2,3,4,5,6],[2,4,3,4,5,6],[3,6,3,4,5,6],[4,8,3,4,5,6],[5,10,3,4,5,6]] þ - table using: ị - index into -> the 5 by 7 table shown above Ẏ - tighten (to a list of the unpermuted lists) Ƭ - collect up until repetition applying: ṙ€ 1 - rotate each left one place Ẏ - tighten (to a list of all the rotations) $ - last two links as a monad: U - upend (reverse each list) ; - concatenate (to the forward ones) e@ - does (the input, V) exist in that list of lists? ṢṖ’Ḍe“!ṛ‘ȯÇ - Main Link: list of integers (each >2), V Ṣ - sort V Ṗ - remove the rightmost (maximal) ’ - decrement (each) Ḍ - convert from base ten “!ṛ‘ - list of code page indices = [33,222] e - exists in? (i.e. was V some rotation of [4,4,n] or [3,3,3,n]?) Ç - call Link 2 as a monad - f(V) ȯ - logical OR ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 142 bytes ``` $ ,$", ^`\G\d+, $& %L$`, $'$>` N^$`.+,(.+), $1 N` ^(3,(3,3(,(\d+|3,[3-5]))?|4,([3-5],)?4|5,3,5|(6|8|10),\6)|4,4,\d+|4,6,(6|8|10)|5,(5|6),\8),¶ ``` [Try it online!](https://tio.run/##TU4xbgMhEOz3GRF2QDe2jBYQVVy6sfyBXE5Eios0KaKUvMsP8McuA/YlFit2mJkd9vv88/n17ueVPZTZCMwTZCrjYfwYIGYtq6MpBM/mpchpMmU7wG4HR8rLqchkFSy1sJyoilfdxDfn9jXAdgy3DzVCEatNNVe/cxiTox7QRgISFoE@G2uiITtcL/PMZKg0a5CO@YrgWV5dVape/0zek02MVWlkUzPvLO2rdEvrjvyf2lHfkt3vWD0h3tLZyaUH@8MCy0p3juG/ "Retina – Try It Online") Link includes test cases. Explanation: ``` $ ,$", ``` Duplicate the list and suffix a comma to each copy. ``` ^`\G\d+, $& ``` Reverse the first copy of the list. ``` %L$`, $'$>` ``` Generate all rotations of both the list and its reverse. ``` N^$`.+,(.+), $1 ``` Sort the last number in descending order. ``` N` ``` Sort in ascending numeric order. (For the truthy cases, these two sorts ensure that the resulting first list is also the first list in list order.) ``` ^(...),¶ ``` Ensure the first list matches one of the truthy cases: ``` 3,(3,3(,(\d+|3,[3-5]))?|4,([3-5],)?4|5,3,5|(6|8|10),\6) ``` Handle those cases with a `3`: `3,3,3`, `3,3,3,N` (`N>=3`), `3,3,3,3,3`, `3,3,3,3,4`, `3,3,3,3,5`, `3,4,4` (this is `4,4,N` with `N=3` of course), `3,4,3,4`, `3,4,4,4`, `3,4,5,4`, `3,5,3,5`, `3,6,6`, `3,8,8`, and `3,10,10`. ``` |4,4,\d+|4,6,(6|8|10)|5,(5|6),\8 ``` Handle `4,4,N` (`N>=4`), `4,6,6`, `4,6,8`, `4,6,10`, `5,5,5` and `5,5,6`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~68~~ 61 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ž‚ÃS2äI{¨.å•3É≠ÞÌδ)Ö“JhG•твŽ6ð9ǝ11Ž ¤š«.¥Ƶ_+ε5L._Dí«}˜€S>I.å~ ``` Input as a list of integers. [Try it online](https://tio.run/##AXQAi/9vc2FiaWX//8W94oCaw4NTMsOkSXvCqC7DpeKAojPDieKJoMOew4zOtCnDluKAnEpoR@KAotGC0LLFvTbDsDnHnTExxb0KwqTFocKrLsKlxrVfK861NUwuX0TDrcKrfcuc4oKsUz5JLsOlfv//WzYsNCw4XQ) or [verify all test cases](https://tio.run/##VVG9SsRAEO59inCduIZs9ofYeI0giN2VIRwKglYWghBECScIB1YWFnKKyh0IpyDilWmyRAvh0FfIi8TZyWaTsMvO7Mz3ze/xyd7@0UF5Gvd7TnF14/T6cZmnRXKnLge@msZn2YurZkXyzNS4GD@qB3W9/FxVt0Uy2TncBvvf6PcjT6V63/i@pzRPV7Jp/pTN3Wz2tRiuLRdi1x1uqbdsfv4zKUavg80Y4l2UpAxDRuBEJOQEDkj8o0UQOI3FomqpfdTzOrxKEwatvTWTEUkkSAl/iX9u8CgNJiABSHhNlprDLYcbTsOWyNGYilthA7C3@rGZmnqqCpitWGDPqKONenCxC8IqTdh6pJkMTMFEFqYH0akMaVyHkq1a6kyskx91x8HeqOnRtyxqNb@9k2ZTdlf1Pnironq@@vWJjzF0xHVt0B4GeG7mBZdH0T8). **Explanation:** Hard-coded approach. Step 1: Check if the input is of the type `3.3.3.N` or `4.4.N`: ``` Ž‚Ã # Push compressed integer 33344 S # Split it into a list of digits: [3,3,3,4,4] 2ä # Try to split it into 2 equal-sized parts: [[3,3,3],[4,4]] I # Push the input-list { # Sort it from lowest to highest ¨ # Remove the last/highest item .å # Check if this modified input-list is in the [[3,3,3],[4,4]] list of lists ``` Step 2: Check if the input is in the hard-coded list of truthy polyhedrons including their rotations and reflections (minus the `4.4.4` and `3.3.3.3`, which are already covered by the `3.3.3.N` and `4.4.N` check): ``` •3É≠ÞÌδ)Ö“JhG• # Push compressed integer 1122222256020285110099101081 тв # Convert it to base-100 as list: # [11,22,22,22,56,2,2,85,11,0,99,10,10,81] Ž6ð # Push compressed integer 1769 9ǝ # Insert it at index 9: # [11,22,22,22,56,2,2,85,11,1760,99,10,10,81] 11 # Push 11 Ž\n¤ # Push compressed integer 19798 š # Convert the 11 to a list [1,1] and prepend the 19798: [19798,1,1] « # Merge it to the other list: # [11,22,22,22,56,2,2,85,11,1769,99,10,10,81,19798,1,1] .¥ # Undelta it: # [0,11,33,55,77,133,135,137,222,233,2002,2101,2111,2121,2202,22000,22001,22002] Ƶ_ # Push compressed integer 222 + # Add it to each value: # [222,233,255,277,299,355,357,359,444,455,2224,2323,2333,2343,2424,22222,22223,22224] ε # Map each value to: 5L # Push list [1,2,3,4,5] ._ # Rotate the current integer that many times towards the left: # i.e. acbde → [bcdea,cdeab,deabc,eabcd,abcde] # i.e. abc → [bca,cab,abc,bca,cab] D # Duplicate that list í # Reverse each inner integer # i.e. → [aedbc,caedb,bcaed,dbcae,edbca] # i.e. → [acb,bac,cba,acb,bac] « # Merge the two lists together }˜ # After the map: flatten the list of lists €S # Split each integer into a list of digits > # Increase each by 1 I.å # Check if the input-list is in this list of lists ``` Step 3: Check if either of the two checks is truthy, and output the result: ``` ~ # Bitwise-OR to check if either of the two is truthy # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž‚Ã` is `33344`; `•3É≠ÞÌδ)Ö“JhG•` is `1122222256020285110099101081`; `•3É≠ÞÌδ)Ö“JhG•тв` is `[11,22,22,22,56,2,2,85,11,0,99,10,10,81]`; `Ž6ð` is `1769`; `Ž\n¤` is `19798`; and `Ƶ_` is `222`. ]
[Question] [ # Problem statement Pólya is playing about with his urn again and he wants you to help him calculate some probabilities. In this urn experiment Pólya has an urn which initially contains 1 red and 1 blue bead. For every iteration, he reaches in and retrieves a bead, then inspects the colour and places the bead back in the urn. He then flips a fair coin, if the coin lands heads he will insert a fair 6 sided die roll amount of the same coloured bead into the urn, if it lands tails he will remove half the number of the same colored bead from the urn (Using integer division - so if the number of beads of the selected colour is odd he will remove `(c-1)/2` where c is the number of beads of that colour) **Given an integer n ≥ 0 and a decimal r > 0, give the probability to 2 decimal places that the ratio between the colours of beads after n iterations is greater than or equal to r in the shortest number of bytes.** # An example set of iterations: Let (x, y) define the urn such that it contains x red beads and y blue beads. ``` Iteration Urn Ratio 0 (1,1) 1 1 (5,1) 5 //Red bead retrieved, coin flip heads, die roll 4 2 (5,1) 5 //Blue bead retrieved, coin flip tails 3 (3,1) 3 //Red bead retrieved, coin flip tails 4 (3,4) 1.333... //Blue bead retrieved, coin flip heads, die roll 3 ``` As can be seen the Ratio r is always ≥ 1 (so it's the greater of red or blue divided by the lesser) # Test cases: Let F(n, r) define application of the function for n iterations and a ratio of r ``` F(0,5) = 0.00 F(1,2) = 0.50 F(1,3) = 0.42 F(5,5) = 0.28 F(10,4) = 0.31 F(40,6.25) = 0.14 ``` This is code golf, so the shortest solution in bytes wins. [Answer] # JavaScript (ES7), ~~145 ... 129 124~~ 123 bytes Takes input as `(r)(n)`. This is a naive solution that actually performs the entire simulation. ``` r=>g=(n,B=s=0,R=0,h=d=>++d<7?h(d,[0,d].map(b=>g(n,B/-~!!b,R/-~!b)&g(n,B+b,R+d-b))):s/24**-~n)=>n--?h``:s+=~B<=r*~R|~R<=r*~B ``` [Try it online!](https://tio.run/##bc1NCsIwEAXgvaewG8k0SRtjiyJOhS48QLci9CfVKppII@JCcvVa3aldDO/N8MGcinthq/Z4vXFtVN3tsWsxOSDRLEWLgmX9NKgwoVSt5uuGKLYVTO2CS3ElZU/fMuTO80qWvbOEyedG@50qXgLA0oYy8n3uNGCiOV83eb60FF26wtZ32dNln5J2ldHWnOvgbA5kT2IgAoKb2RwftSISYByGYxEIMfp2Esh0wMW/bjbsIjn6@xsPOLnoXg "JavaScript (Node.js) – Try It Online") Too slow for the last 2 test cases. ### Commented ``` r => // r = target ratio g = ( // g is a recursive function taking: n, // n = number of iterations B = // B = number of blue beads, minus 1 s = 0, // s = number of times the target ratio was reached R = 0, // R = number of red beads, minus 1 h = d => // h = recursive function taking d = 6-sided die value ++d < 7 ? // increment d; if d is less than or equal to 6: h( // do a recursive call to h: d, // using the new value of d [0, d].map(b => // for b = 0 and b = d: g( // do a first recursive call to g: n, // leave n unchanged B / -~!!b, // divide B by 2 if b is not equal to 0 R / -~!b // divide R by 2 if b is equal to 0 ) & g( // do a second recursive call to g: n, // leave n unchanged B + b, // add b blue beads R + d - b // add d - b red beads ) // end of recursive calls to g ) // end of map() ) // end of recursive call to h : // else (d > 6): s / 24 ** -~n // stop recursion and return s / (24 ** (n + 1)) ) => // body of g: n-- ? // decrement n; if n was not equal to 0: h`` // invoke h with d = [''] (coerced to 0) : // else: s += // increment s if: ~B <= r * ~R | // either (-B-1) <= r*(-R-1), i.e. (B+1)/(R+1) >= r ~R <= r * ~B // or (-R-1) <= r*(-B-1), i.e. (R+1)/(B+1) >= r ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 133 bytes ``` Length@Select[#2/#&@@@(r=Nest[Sort/@Flatten[Table[{{k,0}+#,⌈#/{1,2}⌉},{k,6}]&/@Join[#,Reverse/@#],2]&,{{1,1}},x]),#>=y&]/Length@r ``` By using `N[F,2]`,the output should print 2 decimal digits but TIO prints more... [Try it online!](https://tio.run/##Zc2xCsIwFIXh3acoBIrihbQVHYRKpg4iIuoWgsRy0WJtIV6kUrIr9Cn7IrGig@j68R/OWdMRz5qyVLtEVjvwbjvlTWO3wOJAR7HBHFOSLOLMF0L0TbzEC8lNaYiLJNdEWMit3uco6/oEgR0yaJs743UIkW2bh4WOJ1b5XMzLrJAM1nhFc0EumIJI@VB3aWgtVGoAbBbffMU/58atTFaQJ5YykQGMX33vi7qLfxr90vg9dO4J "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ [Its been a while since you killed that hydra](https://codegolf.stackexchange.com/questions/137980/become-the-hydra-slayer), you basked in the glory for years, but now people are calling you washed up, a has been. Well its time you prove them wrong, you've heard the whereabouts of annother hydra. Simply kill it and you will be awarded all the glory you deserve. You arrive at the armory to receive your swords but they're all out of regular swords all they have left are Sectors. An n-sector will divide the number of heads on a Hydra by n, but can only be used if the number of heads is divisible by n. Once again you are going to write some code to help you slay the hydra. Your code will take as input the number of head the hydra, begins the fight with, the number of heads the hydra grows each turn, and a list of n-sectors you can use. Your code will output an optimal pattern of moves to slay the hydra as quickly as possible Each turn of the fight you may select a single sword to use, if after a slice the hydra has only one head you win, if not it grows heads. You may never make no move, and if there are no possible moves available you lose. If no solution is possible you may output anything other than a solution, e.g. an empty list, nothing, the number zero, etc. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored as their byte counts, with less being better. # Test cases Here are some super basic test-cases, more test-cases will be added upon request. ``` 24 heads, 1 heads per turn, [2,3] -> [3,3,2,3] 25 heads, 2 heads per turn, [2,3] -> No solutions 4 heads, 2 heads per turn, [2] -> No solutions 4 heads, 3 heads per turn, [2,5] -> [2,5] 10 heads, 17 heads per turn, [2, 3, 7, 19] -> No solutions 10 heads, 6 heads per turn, [1,16] -> [1,16] 6 heads, 2 heads per turn, [2, 3, 5] -> [2, 5] 125 heads, 1 head per turn, [1, 2, 3, 127] -> [1, 1, 127] ``` [Answer] # JavaScript, ~~191~~ 190 bytes *Saved a byte thanks to [Step Hen](https://codegolf.stackexchange.com/users/65836/step-hen)* ``` (h,t,s)=>eval(`r=[],d=0,q=[],s.map(a=>q.push([],h));while(q.length){p=q.shift(),h=q.shift(),s.map(w=>(a=h/w)==1?d=w:!(a%1)&!r[a+=t]?r[q.push([...p,w],a),a]=1:0);d?(q=[],p).push(d):0}d?p:[]`) ``` ``` f=(h,t,s)=>eval(`r=[],d=0,q=[],s.map(a=>q.push([],h));while(q.length){p=q.shift(),h=q.shift(),s.map(w=>(a=h/w)==1?d=w:!(a%1)&!r[a+=t]?r[q.push([...p,w],a),a]=1:0);d?(q=[],p).push(d):0}d?p:[]`) console.log(`[${f(24, 1, [2,3])}]`); console.log(`[${f(25, 2, [2,3])}]`); console.log(`[${f(4, 2, [2])}]`); console.log(`[${f(4, 3, [2,5])}]`); console.log(`[${f(10, 17, [2, 3, 7, 19])}]`); console.log(`[${f(10, 6, [1,16])}]`); console.log(`[${f(125, 1, [1, 16])}]`); console.log(`[${f(1024, 3, [1, 2, 137])}]`); ``` --- [Answer] # [Python 2](https://docs.python.org/2/), ~~169~~ ~~195~~ 222 bytes +26 bytes to properly handle cyclic head regeneration on bad weapon picks. (Thanks to @ThePirateBay for pointing it out) +27 bytes to fix certain edge cases causing errors. ``` lambda n,p,w:g(n,n,p,w[::-1])[:-1] def g(n,b,p,w,a=[]): if b<2:return[1] for x in w: if n%x<1and n/x+p!=n and n not in a: try: l=[x]+g(n/x+p,n/x,p,w,[n]+a) if l and l[-1]!=0:return l except:return[0] return[0] ``` [Try it online!](https://tio.run/##bY7NboMwEITP4Sk2h0pBuCo25M8KT@L6YApOkeiCkKs4T0/XLomSqhd7/c14Zser@xxQzLZ6n3vzVTcGkI3sIs8bZHFSUr5ynapwJk1rISh1UJiplE5lAp2F@iTk1LrvCRXZwA4TeOgQLjJZkYwv/sQNNoBvPhvXFUJ8AA4uuAy5wE1XulZ9pbzOqCQ4GZ2xSqHOTEqukNbH372ijdZVvvRCT2rrP9rR3TbJaZP7OI9Thw7sRpQMOAMlGBQ6Te54@y8mswj0GRW/xu0D5TmDHWHK4Ls/nO@XYAY08eOTLJY8Hpt4sX9cKi8PhPPylkxunc4/ "Python 2 – Try It Online") [Answer] # VB.NET (.NET 4.5), 439 + 35 (imports) = 474 bytes *Requires `Imports System.Collections.Generic`* ``` Const N=Nothing Function Z(h,r,a,Optional c=N,Optional p=N,Optional ByRef s=N) If c Is N Then c=New List(Of Long) p=New List(Of Long) End If If s IsNot N And s?.Count<c.Count Then Return N If p.Contains(h)Then Return N p.Add(h) For i=0To a.Count-1 Dim w=a(i) If h Mod w=0Then c.Add(w) If h\w=1And(s Is N Or s?.Count>c.Count)Then s=New List(Of Long) s.AddRange(c) End If Z(h\w+r,r,a,c,p,s) c.RemoveAt(c.Count-1) End If Next Z=s End Function ``` The function `Z` takes two `Int64` (number of heads and head regrow rate), and a `List(Of Int64)` (Sectors), and returns a `List(Of Int64) (the ordered choice of Sectors). Returns`Nothing` if there is no solution. Assumes the Sectors are presented in sorted order from largest to smallest. The `Optional` parameters are for the recursive calls to save state. They track the current order of Sectors in use, the shortest order of Sectors ever, and the number of heads ever encountered. If we encounter the same number of heads again, there has to have been a shorter way to reach it. The only ordering of Sectors that matters is I need `1` to be last if it exists. Otherwise, the hydra will might grow without bounds because I could at every turn just use the `1` Sector and never try any other. I declared a constant `N` to represent `Nothing`, shaving off 6 bytes each time I wanted to use `Nothing`. `And`/`Or` are not short-circuiting, so I use the null conditional operator (`?.`) to avoid object null errors. In real code, I would use `AndAlso`/`OrElse` which do short-circuit. [Try it online!](https://tio.run/##lVRdb9owFH3Gv@KKh9XR0ohQaDVp2cQYTEgQJIo0CfUlTQyJlNiZ7TRF0347u05SPgZF2lNyP87xvede@@X5NhSS7SZZLqRW8LhVmmXOUKQpC3UiuHJ@MM5kEpKZiIqUwczdDdGtwfd8oeOEb8i44FUurGhsSzuw57kxgxRCzz8Y@bHxbbtga1Ceb5HJGkKYKPBhGTNOEMNKmCZK0/kapoJvLJJf8I14BJO1QStEYy1IMECf@orlF1x/DutvxQoLpgvJwTf5OQa4DhKuaGydRnNnEEXoJWMhIfE6SwHD5TZnNLBPj7dq8lsXbhD9q0gki2CNIMcfLWGImkIosjxJmSQ3B7LgCDYIdWE0EhE7IHtO/wD8nmRQegFNKpFiwBGg3allqiot68hT6bnYO1W1jnO5V@FLo0LVJ1EXdFSGaBHwDaPhXlWc5FP5UVbTDO3cVhYeuGCZeGEDTcO3Lvb5PnvVZOWpyn7bh91j8Qwz1JlahLTmhc4LTVe027PBteGsEhhLkcHvOxu6fyzrGNBH1/8Aelfzz5Pv3k/un5G7HSz/4X2E@8mGh4rzAvD@Cg5j7ini/mof/YuHGLGuqOt2m9qaw6qB4ZwIMcNqaAKuSiYhUP/sPE4Rt62Jmk2rH4D63rZa5l0QKXN@ykSzacIZbTcZbSxxlCqGSeYujIIwhgAmvOFC9ymYBvAB2jYYXKvarQvsSFkv36EH81O/U7u/ "Visual Basic .NET (.NET Core) – Try It Online") --- `Z` un-golfed for readability ``` Public Function Z(currentHeads As Long, regrowRate As Integer, weapons As ISet(Of Long), Optional currentWeapons As List(Of Long) = Nothing, Optional previousHeads As List(Of Long) = Nothing, Optional shortestWeapons As List(Of Long) = Nothing) As List(Of Long) ' initial call If currentWeapons Is Nothing Then currentWeapons = New List(Of Long) previousHeads = New List(Of Long) End If ' we've made more moves than our best so far If shortestWeapons IsNot Nothing AndAlso shortestWeapons.Count <= currentWeapons.Count Then Return Nothing End If ' exit, we've been here before If previousHeads.Contains(currentHeads) Then Return Nothing End If ' keep track of previous state to prevent duplicate paths previousHeads.Add(currentHeads) For Each w In weapons ' save 1 for last If w = 1 Then Continue For If currentHeads Mod w = 0 Then currentWeapons.Add(w) If currentHeads \ w = 1 Then If shortestWeapons Is Nothing OrElse shortestWeapons.Count > currentWeapons.Count Then shortestWeapons = New List(Of Long)(currentWeapons) End If End If Dim answer = A(currentHeads \ w + regrowRate, regrowRate, weapons, currentWeapons, previousHeads, shortestWeapons) If answer IsNot Nothing Then If shortestWeapons Is Nothing OrElse shortestWeapons.Count > answer.Count Then shortestWeapons = New List(Of Long)(answer) End If End If currentWeapons.RemoveAt(currentWeapons.Count - 1) End If Next If weapons.Contains(1) Then currentWeapons.Add(1) Dim answer = A(currentHeads \ 1 + regrowRate, regrowRate, weapons, currentWeapons, previousHeads, shortestWeapons) If answer IsNot Nothing Then If shortestWeapons Is Nothing OrElse shortestWeapons.Count > answer.Count Then shortestWeapons = New List(Of Long)(answer) End If End If currentWeapons.RemoveAt(currentWeapons.Count - 1) End If Return shortestWeapons End Function ``` ]
[Question] [ Given a series of `o`s representing dots, connect them vertically or horizontally ## Examples Input: ``` o o o ``` Output: ``` o---o | | o ``` --- Input: ``` o o o o ``` Output: ``` o---o----o | o ``` ## Spec * If you want the input padded with spaces to form a rectangle, please specify this in your answer * There will only be `o`, spaces, and newlines in the input * There will always be a pair of dots to connect * No two `o`s will be directly adjacent * Dots should be connected with `|` and `-`, for vertical and horizontal connections respectively * No dot connections will overlap [Answer] # Japt, ~~33~~ 29 bytes ``` Uy eV="o +o"_rS'|} y eV,_rS'- ``` [Test it online!](http://ethproductions.github.io/japt?v=master&code=VXkgZVY9Im8gK28iX3JTJ3x9IHkgZVYsX3JTJy0=&input=Im8gICBvICAgIG8KCiAgICBvIg==) ### How it works ``` Uy // Transpose rows with columns in the input. eV="o +o" // Set V to the regex-string "o +o", and recursively replace each match Z with: _rS'|} // Z with spaces replaced with "|"s. y // Transpose again. eV, // Recursively replace matches Z of V with: _rS'- // Z with spaces replaced with "-"s. ``` [Answer] ## Ruby, ~~137~~ 133 bytes ``` ->s{eval"s.split($/).map(&:chars)#{".map{|x|x.join.gsub(/o +(?=o)/){|x|x.tr' ',?|}.chars}.transpose"*2}.map(&:join)*$/".sub'?|','?-'} ``` This is absolutely horrible. Still trying to golf. Input as a padded rectangle, please. Newline for "readability": ``` eval"s.split($/).map(&:chars)#{".map{|x|x.join.gsub(/o +(?=o)/){|x|x.tr' ',?|} .chars}.transpose"*2}.map(&:join)*$/".sub'?|','?-' ``` [Answer] ## [Retina](https://github.com/mbuettner/retina/), 80 bytes ``` T` `-`o.+o Tm` `|`(?<=(?(1)!)^(?<-1>.)*o\D*¶(.)*) (?=(.)*¶\D*o(?<-2>.)*$(?(2)!)) ``` Input needs to be padded. [Try it online!](http://retina.tryitonline.net/#code=VGAgYC1gby4rbwpUbWAgYHxgKD88PSg_KDEpISleKD88LTE-Likqb1xEKsK2KC4pKikgKD89KC4pKsK2XEQqbyg_PC0yPi4pKiQoPygyKSEpKQ&input=ICAgIG8gICAgIAogICAgICAgICAgCm8gICBvICAgIG8KICAgICAgICAgIAogICAgbyAgbyAgCiAgICAgICAgICAKICAgICAgICAgIApvICAgICAgICBv) ### Explanation The first stage is pretty simple, it just turns all spaces into hyphens which are found between two `o`s in the same line. The second stage covers the `|`s. This is a bit trickier and requires [balancing groups](https://stackoverflow.com/a/17004406/1633117). The lookbehind ``` (?<=(?(1)!)^(?<-1>.)*o\D*¶(.)*) ``` checks that there's an `o` earlier in the same column. Remember that lookbehinds should be read from right to left. `(.)*` stores the horizontal position of match, `\D*¶` checks skips to any character in the preceding lines, `o` matches literally. Then `(?(1)!)^(?<-1>.)*` ensures that the horizontal position of that `o` is the same. The lookahead ``` (?=(.)*¶\D*o(?<-2>.)*$(?(2)!)) ``` Does exactly the same thing in the opposite direction. ]
[Question] [ # Overview In this challenge, your task is to randomly generate a [monotonic mathematical function](https://en.wikipedia.org/wiki/Monotonic_function) between two sets. # Input Your inputs are two positive integers `s` and `n`. After getting these inputs, your program shall generate a [random](http://meta.codegolf.stackexchange.com/a/1325/32014) mathematical function `f` from the set `{0,1,...,s-1}n` to `{0,1,...,s-1}`. In other words, `f` is a "rule" that takes in an `n`-tuple of integers between `0` and `s-1`, and returns one such integer. Additionally, `f` should be *monotonic* in the following sense. If `A` and `B` are two `n`-tuples such that `A[i] ≥ B[i]` holds for every coordinate `i`, then `f(A) ≥ f(B)`. The exact distribution of the monotonic functions `f` doesn't matter, as long as each such function has a positive probability of being generated (assuming a perfect RNG). # Output Your output shall be an enumeration of the inputs and outputs of `f`. It shall contain all `n`-tuples of integers between `0` and `s-1` in some order, each one being followed by the corresponding output of `f`. The exact output format is flexible (within reason). # Examples The inputs `s = 3` and `n = 2` might produce the output ``` (0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 0) 0 (1, 1) 1 (1, 2) 2 (2, 0) 1 (2, 1) 1 (2, 2) 2 ``` It contains all the pairs over the set `{0, 1, 2}` exactly once, and each one is followed by its `f`-value. The monotonicity condition is also satisfied. The tuples are given here in lexicographical order, but this is not necessary. As another example, `s = 2` and `n = 4` might produce ``` (0, 0, 0, 0) 0 (0, 0, 0, 1) 0 (0, 0, 1, 0) 0 (0, 0, 1, 1) 0 (0, 1, 0, 0) 1 (0, 1, 0, 1) 1 (0, 1, 1, 0) 1 (0, 1, 1, 1) 1 (1, 0, 0, 0) 0 (1, 0, 0, 1) 1 (1, 0, 1, 0) 0 (1, 0, 1, 1) 1 (1, 1, 0, 0) 1 (1, 1, 0, 1) 1 (1, 1, 1, 0) 1 (1, 1, 1, 1) 1 ``` The following are all possible outputs for `s = 2` and `n = 2` (up to reordering the tuples); your program should randomly output one of them: ``` (0,0) 0 (0,1) 0 (1,0) 0 (1,1) 0 ------- (0,0) 0 (0,1) 0 (1,0) 0 (1,1) 1 ------- (0,0) 0 (0,1) 0 (1,0) 1 (1,1) 1 ------- (0,0) 0 (0,1) 1 (1,0) 0 (1,1) 1 ------- (0,0) 0 (0,1) 1 (1,0) 1 (1,1) 1 ------- (0,0) 1 (0,1) 1 (1,0) 1 (1,1) 1 ``` # Rules and Scoring You can write a full program or a function. The lowest byte count wins, and [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed. Code with explanation is preferred. There are no restrictions on time complexity, but I'll give a **bonus of -15 %** if your solution is always guaranteed to finish in a certain amount of time (depending on the inputs, and assuming a perfect RNG that runs in constant time). [Answer] # Pyth, 35 bytes (38 - 15% = 31.45 farther down) ``` #I!sm><FhMds<MCeMd^JC,mOQK^UQvzK2JB ``` [Demonstration](https://pyth.herokuapp.com/?code=%23I%21sm%3E%3CFhMds%3CMCeMd%5EJC%2CmOQK%5EUQvzK2JB&input=2%0A3&debug=0) Input is in the format: ``` n s ``` Output is in the format: ``` [[value, tuple], [value, tuple], ...] ``` Simply generates random possibilities and tests them. --- Alternative 37 byte version which I believe qualifies for the bonus: ``` Of!sm><FhMds<MCeMd^T2mC,d^UQvz^UQ^Qvz ``` [Demonstration](https://pyth.herokuapp.com/?code=Of%21sm%3E%3CFhMds%3CMCeMd%5ET2mC%2Cd%5EUQvz%5EUQ%5EQvz&input=2%0A2&debug=0) This starts by generating all possible monotonic functions, then outputs one at random. It is much slower, and tops out at `2,2`. [Answer] # CJam, 40 bytes - 15% = 34 bytes ``` q~1$\m*\1$,m*{W$\.+2m*{:.<2b}%1&!},mR]zp ``` This approach generates all valid functions and then selects on at random. Run time is at least **O(s2sn)**, but constant for a given input. I doubt this is what the OP had in mind, but it is *guaranteed to finish in a certain amount of time (depending on the inputs[...])* and therefore qualifies for the bonus. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~1%24%5Cm*%5C1%24%2Cm*%7BW%24%5C.%2B2m*%7B%3A.%3C2b%7D%251%26!%7D%2CmR%5Dzp&input=2%202). [Answer] # Julia, 64 bytes (-15% = 54.4) ``` g(s,n)=(K=rand(0:s-1,ntuple(n,i->s));for i=1:n K=sort(K,i)end;K) ``` Ungolfed: ``` function g(s,n) # Generates a random n-dimensional array with s per dimension # and all values being integers between 0 and s-1 K=rand(0:s-1,ntuple(n,i->s)) # Loop over the various dimensions for i=1:n # Sort in the current dimension K=sort(K,i) end return K end ``` This will run quickly, with the only possible issue being with memory for large enough s and n (g(10,10) has to produce a 10^10 array, so obviously it's going to run out of memory - even if each number is one byte, that's 10 gigabytes of data). Output is 1-based indexing, so to determine the result for a given input, you need to add one to each input value. For example, to find f(1,2,6,0,3), you need to examine `K[2,3,7,1,4]`. ]
[Question] [ Make a plot (Poincare disk) of a tessellation on a hyperbolic plane, such as: [![enter image description here](https://i.stack.imgur.com/yaMq2.png)](https://i.stack.imgur.com/yaMq2.png) The program takes *four* inputs: 1) How many edges/polygon (three in this example). 2) How many intersect at each vertex (seven in this example). 3) How many steps away from the center vertex to render (5 in this example, if you look closely). This means that a vertex is included iff it can be reached in 5 or less steps form the center. Edges are rendered iff both their vertexes are included. 4) The resolution of the image (a single number of pixels, the image is square). The output must be an image. Edges must be rendered as circle-arcs, not lines (the Poincaré disk projection turns lines into circles). Points do not need to be rendered. When the user puts in something that is *not* hyperbolic (i.e. 5 triangles meeting at each vertex), the program does not have to work properly. This is code-golf, so the shortest answer wins. [Answer] # Mathematica, 2535 bytes Taken from [**here**](https://mathematica.stackexchange.com/questions/65215/how-to-create-a-poincare-disk-type-kaleidoscope-in-mathematica) (hence why it's community wiki). Not really that golfed. View the provided link for the author's explanation of his code. Also, I'm no Mathematica expert, but I bet Martin could do wonders on the code length. I don't even understand the math behind it. I left it readable, but if the question doesn't get closed, I'll golf it past readability and move the 2 other parameters inside the caller function. **Currently invalid**, feel free to help improve it: * I think this uses lines rather than arcs. * Centered on a face, rather than a vertex. ``` HyperbolicLine[{{Px_, Py_}, {Qx_, Qy_}}] := If[N[Chop[Px Qy - Py Qx]] =!= 0., Circle[OrthoCentre[{{Px, Py}, {Qx, Qy}}], OrthoRadius[{{Px, Py}, {Qx, Qy}}], OrthoAngles[{{Px, Py}, {Qx, Qy}}]], Line[{{Px, Py}, {Qx, Qy}}]] OrthoCentre[{{Px_, Py_}, {Qx_, Qy_}}] := With[{d = 2 Px Qy - 2 Py Qx, p = 1 + Px^2, q = 1 + Qx^2 + Qy^2}, If[N[d] =!= 0., {p Qy + Py^2 Qy - Py q, -p Qx - Py^2 Qx + Px q}/d, ComplexInfinity]] OrthoRadius[{{Px_, Py_}, {Qx_, Qy_}}] := If[N[Chop[Px Qy - Py Qx]] =!= 0., Sqrt[Total[OrthoCentre[{{Px, Py}, {Qx, Qy}}]^2] - 1], Infinity] OrthoAngles[{{Px_, Py_}, {Qx_, Qy_}}] := Block[{a, b, c = OrthoCentre[{{Px, Py}, {Qx, Qy}}]}, If[(a = N[Apply[ArcTan, {Px, Py} - c]]) < 0., a = a + 2 \[Pi]]; If[(b = N[Apply[ArcTan, {Qx, Qy} - c]]) < 0., b = b + 2 \[Pi]]; {a, b} = Sort[{a, b}]; If[b - a > \[Pi], {b, a + 2 \[Pi]}, {a, b}]] Inversion[Circle[{Cx_, Cy_}, r_], {Px_, Py_}] := {Cx, Cy} + r^2 {Px - Cx, Py - Cy}/((Cx - Px)^2 + (Cy - Py)^2) Inversion[Circle[{Cx_, Cy_}, r_, {a_, b_}], {Px_, Py_}] := {Cx, Cy} + r^2 {Px - Cx, Py - Cy}/((Cx - Px)^2 + (Cy - Py)^2) Inversion[Circle[{Cx_, Cy_}, r_, {a_, b_}], p_Line] := Map[Inversion[Circle[{Cx, Cy}, r], #] &, p, {2}] Inversion[Circle[{Cx_, Cy_}, r_, {a_, b_}], p_Polygon] := Map[Inversion[Circle[{Cx, Cy}, r], #] &, p, {2}] Inversion[Line[{{Px_, Py_}, {Qx_, Qy_}}], {Ux_, Uy_}] := With[{u = Px - Qx, v = Qy - Py}, {-Ux (v^2 - u^2) - 2 u v Uy, Uy (v^2 - u^2) - 2 u v Ux}/(u^2 + v^2)] Inversion[Line[{{Px_, Py_}, {Qx_, Qy_}}], p_Polygon] := Map[Inversion[Line[{{Px, Py}, {Qx, Qy}}], #] &, p, {2}] Inversion[Circle[{Cx_, Cy_}, r_], c_List] := Map[Inversion[Circle[{Cx, Cy}, r], #] &, c] PolygonInvert[p_Polygon] := Map[Inversion[HyperbolicLine[#], p] &, Partition[Join[p[[1]], {p[[1, 1]]}], 2, 1]] PolygonInvert[p_List] := Flatten[Map[PolygonInvert[#] &, p]] LineRule = Polygon[x_] :> Line[Join[x, {x[[1]]}]]; HyperbolicLineRule = Polygon[x_] :> Map[HyperbolicLine, Partition[Join[x, {x[[1]]}], 2, 1]]; CentralPolygon[p_Integer, q_Integer, \[Phi]_: 0] := With[{r = (Cot[\[Pi]/p] Cot[\[Pi]/q] - 1)/ Sqrt[Cot[\[Pi]/p]^2 Cot[\[Pi]/q]^2 - 1], \[Theta] = \[Pi] Range[ 1, 2 p - 1, 2]/p}, r Map[{{Cos[\[Phi]], -Sin[\[Phi]]}, {Sin[\[Phi]], Cos[\[Phi]]}}.# &, Transpose[{Cos[\[Theta]], Sin[\[Theta]]}]]] PolygonUnion[p_Polygon, tol_: 10.^-10] := p PolygonUnion[p_List, tol_: 10.^-10] := With[{q = p /. Polygon[x_] :> N[Polygon[Round[x, 10.^-10]]]}, DeleteDuplicates[q]] HyperbolicTessellation[p_Integer, q_Integer, \[Phi]_, k_Integer, t_: 10.^-10] := Map[PolygonUnion[#, t] &, NestList[PolygonInvert, Polygon[CentralPolygon[p, q, \[Phi]]], k][[{-2, -1}]]] /; k > 0 HyperbolicTessellation[p_Integer, q_Integer, \[Phi]_, k_Integer, t_: 10.^-10] := Polygon[CentralPolygon[p, q, \[Phi]]] /; k == 0 HyperbolicTessellationGraphics[p_Integer, q_Integer, \[Phi]_, k_Integer, rule_RuleDelayed, opts___] := Graphics[{Circle[{0, 0}, 1], HyperbolicTessellation[p, q, \[Phi], k, 10.^-10] /. rule}, opts] ``` Called like: ``` HyperbolicTessellationGraphics[7, 3, 0., 5, HyperbolicLineRule, ImageSize -> 100, PlotLabel -> "{7,3}"] HyperbolicTessellationGraphics[3, 7, 0., 7, HyperbolicLineRule, ImageSize -> 300, PlotLabel -> "{7,7}"] ``` [![7,3 tiling](https://i.stack.imgur.com/Nw1y6.png)](https://i.stack.imgur.com/Nw1y6.png) [![3,7 tiling](https://i.stack.imgur.com/SJMMU.png)](https://i.stack.imgur.com/SJMMU.png) [Answer] # JavaScript/HTML/SVG, 5086 bytes Not golfed, but the logic/math is short and hopefully relatively clear; also does the planar and spherical tessellations ((p-2)\*(q-2) <= 4) without too much extra logic (it was easier to implement those than to leave gaps in the table!). The calling code in the snippet below calls the function several times: first to display the 512x512 {3,7} picture (not shown here; it looks just like the above), and then to display a 128x128 {p,q} (meaning q p-gons surround each vertex) for each p,q from 3 to 9: [![enter image description here](https://i.stack.imgur.com/Z9WnF.png)](https://i.stack.imgur.com/Z9WnF.png) ``` <!DOCTYPE html> <html> <!-- https://codegolf.stackexchange.com/questions/55848/plot-a-hyperbolic-plane-tessellation --> <style> svg { border: 1px solid black; } </style> <body> <script> "use strict"; console.log(" in script"); // Do an immediately invoked async function, // so we can sleep in it (to flush drawing). (async () => { console.log(" in script async function"); const t0 = performance.now(); // ========================== // IMPLEMENTATION BEGINS HERE // some complex math const neg = ([x,y]) => [-x,-y]; const conj = ([x,y]) => [x,-y]; const plus = (a,b) => [a[0]+b[0],a[1]+b[1]]; const minus = (a,b) => [a[0]-b[0],a[1]-b[1]]; const cross = (a,b) => a[0]*b[1]-a[1]*b[0]; // area of spanned parallelogram const times = (a,b) => [a[0]*b[0]-a[1]*b[1], a[0]*b[1]+a[1]*b[0]]; const timesreal = ([x,y],r) => [x*r, y*r]; const abs2 = ([x,y]) => x**2+y**2; const abs = z => Math.sqrt(abs2(z)); const dist = (a,b) => abs(minus(a,b)); const inverse = z => timesreal(conj(z), 1/abs2(z)); const dividedby = (a,b) => times(a,inverse(b)); // Transform z by the translation that takes the origin to t. // Works with any curvature; in particular: // -1 = hyperbolic (poincare disk) // 0 = planar, // 1 = spherical (stereographic projection) const Plus = (z,t, curvature) => { // (z + t) / (1 - curvature*conj(t)*z) return dividedby(plus(z,t), minus([1,0], timesreal(times(conj(t), z), curvature))); }; // Transform z by the translation that takes t to the origin. const Minus = (z,t, curvature) => Plus(z, neg(t), curvature); // Simple monotonic function of actual distance. Specifically: // - hyperbolic distance is 2*atanh(chord distance) // - spherical distance is 2*atan(chord distance) // - planar distance is chord distance // (I might be off by a factor of 2 in some of these claims, doesn't matter) const ChordDistance = (a,b, curvature) => abs(Minus(a,b, curvature)); // signed radius of the circle passing through a,b,c const circumradius = (a,b,c) => dist(a,b)*dist(b,c)*dist(c,a) / (2 * cross(minus(b,a), minus(c,a))); // signed radius of circle needed to render segment a,b as circular arc // in the picture; may be infinite const ArcRadius = (a,b, curvature) => { if (curvature === 0) return Infinity; // planar picture: all straight lines if (abs(a) > 1e3 || abs(b) > 1e3) return Infinity; // one of them is infinite if (Math.abs(cross(a,b)) < 1e-3) return Infinity; // collinear with origin // Let c be any third point on the arc const c = Plus(timesreal(Minus(b,a, curvature), .5), a, curvature); return circumradius(a,b,c); }; const doit = (svgsize,p,q,steps,maxverts) => { const curvature = Math.sign(4-(p-2)*(q-2)); // -1:hyperbolic, 0:planar, 1:spherical const Dist = (a,b) => ChordDistance(a,b, curvature); const euclidean_first_edge_length = curvature===0 ? 1 : Math.sqrt(Math.abs((Math.sin(Math.PI/q)/Math.cos(Math.PI/p))**2 - 1)) // a,b are generators of the symmetry group (not including reflections): // - a is rotation by 2pi/q about origin // - b is rotation by pi about first edge midpoint const primitive_qth_root_of_unity = [Math.cos(2*Math.PI/q), Math.sin(2*Math.PI/q)]; const a = z => times(z, primitive_qth_root_of_unity); const b = ([x,y]) => Plus([-x, -y], [0,-euclidean_first_edge_length], curvature); // generate verts const vs = [[0,0]]; for (let i = 0; i < steps; ++i) { for (const g of [b,a]) { for (let j = 0; j < vs.length; ++j) { // while vs is growing if (vs.length >= maxverts) break; const v = g(vs[j]); if (vs.findIndex(w=>Dist(v,w)<=1e-6)<0) vs.push(v); } } } // generate edges (pairs of points, not pairs of indices) const es = []; if (vs.length >= 2) { const d = Dist(vs[0], vs[1]); for (let i = 0; i < vs.length; ++i) { for (let j = 0; j < i; ++j) { if (Math.abs(Dist(vs[i],vs[j]) - d) <= 1e-6) es.push([vs[i], vs[j]]); } } } const scale = curvature>0 ? .35 : // spherical: get all verts in the picture curvature===0 ? 1/5.5 : // planar: get a good sampling in the picture 1; // hyperbolic: get the poincare disk in the picture let svg_html = '<svg width="'+svgsize+'" height="'+svgsize+'"><path d="'; for (let [a,b] of es) { const r = ArcRadius(a,b,curvature)*scale/2*svgsize; // if a or b is at infinity, then draw straight outward // from the other point if (abs(a) > 1e2) a = timesreal(b, 1e2); if (abs(b) > 1e2) b = timesreal(a, 1e2); const x0 = (a[0]*scale+1)/2*svgsize; const y0 = (a[1]*scale+1)/2*svgsize; const x1 = (b[0]*scale+1)/2*svgsize; const y1 = (b[1]*scale+1)/2*svgsize; if (!Number.isFinite(r)) { svg_html += 'M'+x0+','+y0+'L'+x1+','+y1; // straight line } else { // circular arc of signed radius r svg_html += 'M'+x0+','+y0+'A'+r+','+r+',0,0,'+(r<0?1:0)+','+x1+','+y1; } } svg_html += '" stroke="black" fill="none"/></svg>'; return svg_html; }; // doit // IMPLEMENTATION ENDS HERE // ======================== document.body.innerHTML += doit(512, 3, 7, 5, 1000) document.body.innerHTML += "<br>"; const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); const svgsize = 128; const max = 9; const steps = 5; const maxverts = 1000; // keep from going off the rails for (let p = 3; p <= max; ++p) { for (let q = 3; q <= max; ++q) { await sleep(0); // flush previously drawn stuff before computing next document.body.innerHTML += doit(svgsize, p, q, steps, maxverts); } document.body.innerHTML += "<br>"; } const t1 = performance.now(); console.log(" out script async function in "+(t1-t0)/1000+"s") })(); console.log(" out script") </script> </body> </html> ``` ]
[Question] [ Consider a rectangular two-dimensional grid where each cell can either be empty (`.`) or full (`0`). e.g. ``` ..00.... 0000.... .00000.. 000...00 ..000000 000.00.. ``` The grid is considered infinite, all cells outside the depicted region are empty. The goal is to cover the filled spaces and leave the empty spaces open using a set of 7 distinctly shaped bricks that each take up 4 cells (2×2) of the grid. These are the 7 bricks: * Blocks - 1 variant ``` 11 11 ``` * Slabs - 2 variants ``` .. 22 ``` ``` 33 .. ``` * Stairs - 4 variants ``` .4 44 ``` ``` 5. 55 ``` ``` 66 .6 ``` ``` 77 7. ``` These bricks must always align to a grid whose cells are twice as wide and tall as the cells of the input grid. Each brick can only occupy one cell of this larger grid but the smaller grid can be translated (shifted up, down, left, right) beneath the larger grid to give more options for finding a cover. Neither of the grids nor individual bricks may be rotated. So one way to cover (a.k.a. solve) the example above is like this: ``` ..11.... 2211.... .47733.. 447...22 ..771133 227.11.. ``` (Identical neighboring bricks can still cause ambiguity but carefully identifying the larger grid resolves that.) An **invalid** solution for ``` 000000 000000 ``` is ``` 566774 556744 ``` because the bricks do not all align to the larger grid nor only occupy one cell of it. A valid solution here is 3 blocks in a row: ``` 111111 111111 ``` And another valid solution involves 6 slabs: ``` ...... 222222 333333 ...... ``` So note that some input grids have **multiple solutions**. An **invalid** solution for ``` 00.00 00... ``` is ``` 11.33 11... ``` because the bricks don't align to the larger grid. The slab would need to move left or right by one, but then of course the cover would be incomplete. This input grid has **no solution**. # Challenge Write a program that takes in (via stdin/command line) a rectangular block of text of `.`'s and `0`'s that represents a grid to be covered. If there is a valid covering solution, print (via stdout) any *one* solution in the same manner as above, replacing all `0`'s with the appropriate `1` through `7` bricks. If there is no solution, your program should not output anything, just quietly end normally. ## Notes * The input and output do not need to have the same rectangular dimensions. Your output can have extraneous rows and/or columns of all `.`'s (as long as they don't invalidate the solution). * It's also alright to trim rows and column's of all `.`'s if it won't affect the filled spaces. e.g. ``` 222222 333333 ``` is a valid solution to ``` 000000 000000 ``` Conversely, the two empty columns in `00..00` could not be removed since that would disarrange the filled spaces. * You may optionally assume the input has a single trailing newline. A single trailing newline in the output is fine as well, even in the case of no solution. * Grids that are completely empty (all `.`'s) and the trivial 0×0 grid are not input cases you need to worry about. But the 1×1 `0` grid is, as are all other grids that contain at least one `0`. (You may not assume the width or height of the input grid is even!) * Instead of a program you may write a function that takes the input as a string argument and prints the output normally or returns it as a string. Any [falsy value](http://meta.codegolf.stackexchange.com/a/2194/26997) can be returned if there is no solution. * You may use any 9 distinct [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of `.` `0` `1` `2` `3` `4` `5` `6` `7`. Just be sure to say what your substitutions were! Newlines must remain as is. ## Scoring The shortest code in bytes wins. Tiebreaker is highest voted post. *This challenge was inspired by [blocks](http://minecraft.gamepedia.com/Blocks), [slabs](http://minecraft.gamepedia.com/Slab), and [stairs](http://minecraft.gamepedia.com/Stairs) in [Minecraft](https://en.wikipedia.org/wiki/Minecraft), which follow the same rules described here. If you enjoy [PPCG](https://codegolf.stackexchange.com/) and Minecraft, you may want to check out the [PPCG Minecraft Server](https://ppcgmc.herokuapp.com/).* [Answer] # **Python - 525 491 478 430 bytes** ``` r=range def t(s): m=s.find("\n")+1 for q in r(4): try: for i in r(-q%2,m-1,2): for j in r(-q/2,len(s)/m,2): k,g=j*m+i,"" b=[k,k+1,k+m,k+m+1] for z in b:g+=a(s,z) for z in b: if a(s,z)!="d":s=s[:z]+`dict(dddd=0,zzdd=3,ddzz=2,zzzd=7,zzdz=6,zdzz=5,dzzz=4,zzzz=1)[g]`+s[z+1:] return s except:d def a(v,i): try: if v[i]!="\n":return v[i] return "d" except:return "d" ``` **Explanation:** This is my first code golf, so it might not be optimal, but here's how it works. The function t(s) gives the result for the string passed in. First, it finds the number of columns, then goes through the four possible distinct translations by 1 (none, left, up, up-left) and tries to solve it for each one. It looks at each 2x2 block and maps it to a valid block number, given by a dictionary, and changes the zeros to the number. If it finds one not in the dictionary, it abandons that specific offset and starts over with the next one. If it goes through all 4 offsets without finding a valid solution, it ends without outputting anything. a(v, i) allows for the default value outside the string, and ignores newline characters. Although it may end up with partial solutions through the duration of the run, it will always override them with the final correct one if it exists. **Edit:** A different mapping of characters is used: . -> d, 0 -> z, all other numbers go to themselves. This applies to both input and output. ]
[Question] [ [Today's XKCD](http://xkcd.com/1529/) is a sports-tournament style bracket, where the contestants are well-known names, put into groups of possibly confusing names. Give the probability that a given contestant will win the entire tournament, based on each contestant in a given round having an equal chance of winning that round. ### Input The name of a contestant. * XKCD likes to use all upper case, but you may use whatever case makes sense for you or make your input case insensitive. * You may assume all input names are valid. * `Jeff Gordan` is probably a misspelling of `Jeff Gordon`. You may choose to accept either or both of these. * Some names include punctuation, e.g. `H. G. Wells` and `Joseph Gordon-Levitt`. You may choose to accept names with or without punctuation (or both). The above without punctuation would be `H G Wells` and `Joseph Gordon Levitt` * Similarly, you may choose to accept either `Beyoncé` or `Beyonce` or both * The `Mister/Fred Astaire/Rogers` line is a bit odd. For this one, you must accept all of the following: `Fred Rogers`, `Mister Rogers` and `Fred Astaire` ### Output The probability of the given contestant winning the whole tournament, in rational form (e.g. `1/64`) ### Examples * Louis Armstrong will potentially play in 6 rounds, each with two contestants, so he has a 1/64 chance of winning. * Alan Rickman will potentially play in 7 rounds, the first with 3 contestants and the rest with 2 contestants, so he has a 1/192 chance of winning. To save you the effort of typing in all the names from the image, [explainXKCD already has them tabulated](http://www.explainxkcd.com/wiki/index.php/1529). I've also dumped them to [this pastebin](http://pastebin.com/vUCXXicw). Note the winning probabilities in the explainXKCD are wrong - they are twice as big as they should be because they are presumably forgetting the final round. Thanks for pointing this out @Geobits. [Answer] # CJam, 161 bytes ``` 1'/l_"FRE"#\_'É#)\2b626%536%"òazíF­.?§·»ùßóÿ÷ýÿÿ»×ï_ÿÿ¿ß÷ä¿ûïÿÏÅÿ¿ÿÿ~ÿþÿýó½ïÿþþ/ïþÿ®þü¾ùÿ®÷/"256b2b2*<1-,"ãÍÕý*ÔÞ)ð^sV? Ìöî²\ÅlÕáS{Á"260b5b=5,Z6t=2+1\?4?32* ``` This is a full program that expects uppercase input, with punctuation and accents exactly as shown in the pastebin. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=1'%2Fl_%22FRE%22%23%5C_'%C3%89%23)%5C2b626%25536%25%22%C3%B2a%1Dz%C3%ADF%C2%AD.%3F%C2%A7%C2%B7%C2%BB%C3%B9%C3%9F%C3%B3%C3%BF%C3%B7%C3%BD%C3%BF%C3%BF%C2%BB%C3%97%C3%AF_%C3%BF%C3%BF%C2%BF%C3%9F%C3%B7%C3%A4%C2%BF%C3%BB%C3%AF%C3%BF%C3%8F%C3%85%C3%BF%C2%BF%C3%BF%C3%BF~%C3%BF%C3%BE%C3%BF%C3%BD%C3%B3%C2%BD%C3%AF%C3%BF%C3%BE%C3%BE%2F%C3%AF%C3%BE%C3%BF%C2%AE%C3%BE%C3%BC%C2%BE%C3%B9%C3%BF%C2%AE%C3%B7%2F%22256b2b2*%3C1-%2C%22%C3%A3%C3%8D%C3%95%C3%BD*%C3%94%C2%99%C3%9E)%C3%B0%5EsV%3F%09%C2%96%C3%8C%C3%B6%C3%AE%C2%B2%5C%C3%85l%C3%95%C3%A1%C2%9AS%7B%C3%81%14%22260b5b%3D5%2CZ6t%3D2%2B1%5C%3F4%3F32*&input=BEYONC%C3%89). ### How it works ``` 1'/ e# Push a 1 and a slash. l e# Read a line of input from STDIN. _"FRE"# e# Push 0 if the input starts with "FRE" and a truthy value otherwise. \_'É#) e# Push 1 if the input doesn't contain "É" and a falsy value otherwise. e# Now we hash the input: \2b e# Apply base 2 conversion to turn the input into an integer. 626%536% e# Take that integer modulo 626, then modulo 536. "òazíF­.?§·»ùßóÿ÷ýÿÿ»×ï_ÿÿ¿ß÷ä¿ûïÿÏÅÿ¿ÿÿ~ÿþÿýó½ïÿþþ/ïþÿ®þü¾ùÿ®÷/"256b2b2* e# Convert the string from base 256 to base 2 and repeat it. e# The resulting array, [1 1 1 1 0 0 1 0 0 ...], contains a 0 at index X e# if and only if there is a possible input with hash X. < e# Keep the binary values before the index of the input hash. <1-, e# Count the number of zeroes. "ãÍÕý*ÔÞ)ð^sV? Ìöî²\ÅlÕáS{Á"260b5b e# Convert the string from base 260 to base 5. e# The resulting array, [2 2 2 2 2 0 4 4 0 0 ...], contains a diffrent e# integer for every different probability. The input with the lowest hash e# corresponds to the first index, the one with the highest to the last. = e# Retrieve the integer corresponding to the input. 5,Z6t= e# Retrieve the corresponding element from [0 1 2 6 4]. 2+ e# Add two. 1\? e# Select the result from above or 1 for BEYONCÉ. 4? e# Select the result from above or 4 for and FRED. 32* e# Multiply by 32. ``` ]
[Question] [ I have $15 in my pocket. Likewise, I am in a store which doesn't give change. While browsing, I spot an item that costs $10 (tax included). Can I buy that item without losing any money? In this case, the answer is yes. No matter how my $15 is divided up (one 10 and one 5, or three 5s, or something else), I will always have the exact $10 needed. As a second example, I have $0.16 in my pocket. What other amounts of money must I be able to pay exactly? ``` Possible Divisions: 0.01, 0.05, 0.10 0.01, 0.05 x 3 0.01 x 16 Guaranteed Exact Change: 0.01, 0.05, 0.06, 0.10, 0.11, 0.15, 0.16 ``` What if I have $0.27 in my pocket? ``` Possible Divisions: 0.01 x 2, 0.25 0.01 x 2, 0.05, 0.10 x 2 0.01 x 2, 0.05 x 3, 0.10 0.01 x 2, 0.05 x 5 0.01 x 27 Guaranteed Exact Change: 0.01, 0.02, 0.25, 0.26, 0.27 ``` In the above case, there were only a few amounts of money for which I would always have perfect change. ## Your task Write the shortest program (or named function) which takes A) an integer amount of money and B) a list of possible denominations as input, and outputs a list of the amounts of money for which I must have perfect change. Input can be either STDIN or arguments for the program or function. I'm not going to be super-strict on input formatting; it can match how your language formats arrays. ## Perhaps a More Detailed Explanation I have a certain amount of money in my pocket, which is formed from a set of possible demonstrations of currency. If I have $8, and I know that the possible denominations are $2 and $3, then there's only so many different combinations of bills that could be in my pocket. These are `2+2+2+2` and `3+3+2`. In order to be able to produce an exact amount of money, I have to be able to produce that quantity using the only the bills that are in my pocket. If I had four 2s, I could produce `2, 4, 6, or 8`. If I had two 3s and a 2, I could produce `2, 3, 5, 6, or 8` Since I don't know which of these combinations I actually have in my pocket, my final answer is reduced to `2, 6, 8`. These are the values I *know* I could produce from my pocket, given the total amount and the possible denominations. ## Hand-Calculated Example I/O ``` 7 [3, 4] 3, 4, 7 //only one possible division into 3 + 4 7 [3, 2] 2, 3, 4, 5, 7 //the only division is 3 + 2 + 2 6 [2, 3, 4] 6 //divisions are 2+2+2, 3+3, 2+4 16 [1, 5, 10, 25] //this represents one of the examples above 1, 5, 6, 10, 11, 15, 16 27 [1, 5, 10, 25] //another example from above 1, 2, 25, 26, 27 1500 [1, 5, 10, 25, 100, 500, 1000, 2000] 500, 1000, 1500 600 [100, 500, 1000, 2000] 100, 500, 600 600 [200, 1, 5, 10, 25, 100, 500, 1000, 2000] 600 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~[132](https://codegolf.stackexchange.com/revisions/237505/1)~~ 109 bytes ``` n?y@(x:z)|n>0=map(x:)((n-x)?y)++n?z n?_=[[]|n==0] (x:n)#y=n#y||n#(y-x) _#y=y==0 x%z=[y|y<-[1..x],all(#y)$x?z] ``` [Try it online!](https://tio.run/##bYtRC4IwFEbf9ysuqLDhFLUsiNb6H2OIUJA0b1I97Mr@u62eInr8zjnfpX9cz84tC2o6cr@bRcBDpcZ@ikNwjoUXmkSeo54Z6k4ZYwMqVVkWAxQJKUwoBEw4xZR1EVDUzGezMhRoX5i6LL2VvXM8IZF6Pdtl7AdUpxsDmO4DPiGFLWRgVhLW9g9svuHmDRsJv3H9EbWEVkJdxVNrlxc "Haskell – Try It Online") # Explanation This is a pretty straight-forward solution to the puzzle. * `(?)` takes an amount and a list of denominations and determines all ways to make the amount with the given denominations. Solutions are sorted in the same order as the original denomination list. This is just all the possible sets we could have in our pocket. * `(#)` an amount and a list of amounts and determines if the amount is the sum of a sub-list of the given list. This is whether an amount can be made from a given set of bills. * `(%)` is the main function. It takes an amount, `x`, and a list of denominations, `z`. For each amount, `y`, from 1 to the given amount it checks that for every way to make the initial amount (`x?z`), `y` is the sum of some sub-list of it. [Answer] # Python 2, ~~200~~ ~~197~~ ~~193~~ 140 bytes ``` f=lambda n,D,S={0}:sum([f(n-x,D,S|{x+y for y in S})for x in D],[])if n>0else[S]*-~n g=lambda*a:(f(*a)and reduce(set.__and__,f(*a))or{0})-{0} ``` *(Thanks to @Nabb for tips)* Here's a poorly golfed solution for now to get things started. Call with `g(16, [1, 5, 10, 25])` — output is a set with the relevant denominations. The approach is straightforward, and is broken down into two steps: * `f` looks at all ways of reaching `n` with denominations `D` (e.g. `[1, 5, 10]`), and for each one it works out all amounts that can be made with these denominations (e.g. `set([0, 1, 5, 6, 10, 11, 15, 16])`). * `g` calculates the intersections of the results of `f`, then removes 0 for the final answer. The program solves cases 1-5 and 7 fine, stack overflows on 6 and takes forever on 8. If there is no solution (e.g. `g(7, [2, 4, 6])`), then the program returns an empty set. If an error is allowed to be thrown for such a case, then here is a shorter `g`: ``` g=lambda*a:reduce(set.__and__,f(*a))-{0} ``` [Answer] # JavaScript (ES6) 162 ~~203 207~~ **Edit** Changed the way to intersect result sets in array r. A bit faster, but the algorithm still stinks. ~~More detailed explanation will follow.~~ Shortly : c is a recursive function that enumerate all the possible subdivisions. k is a recursive function that enumerate all the possible sums without repetitions. Any new result set found with k function is compared with the previous set found, only the common results are kept. Why is it so slow? Having to manage a target total of, say, 1500 and a single piece of value 1, enumerating all the possibile sums is not a good idea. ``` F=(s,d,r, c=(s,i,t=[],v,k=(i,s,v)=>{for(;v=t[i++];)k(i,s+v);o[s]=s})=> {for(s||(i=k(o=[],0),r=(r||o).filter(v=>o[v]));v=d[i];++i)s<v||c(s-v,i,[...t,v])} )=>c(s,0)||r ``` **Ungolfed** ``` F=(s,d)=>{ var r var c=(s,i,t=[])=> { var o=[],v var k=(i,s)=> // find all sums for the current list t, set a flag in the o array { var v for(;v=t[i++];)k(i,s+v) o[s]=s } if (s==0) { k(0,0) if (r) r = r.filter(v=>o[v]) // after first loop, intersect with current else r = o.filter(v=>v) // first loop, keep all results } else for(;v=d[i];++i) { if (s >= v) c(s-v, i, t.concat(v)) } } c(s,0) // enumerate all possible set of pieces return r } ``` **Test** In Firefox/FireBug console ``` F(16,[1,5,10,25]) ``` > > [1, 5, 6, 10, 11, 15, 16] > > > (time 84 msec) ``` F(27, [1, 5, 10, 25]) ``` > > [1, 2, 25, 26, 27] > > > (time 147252 msec, so not sooo fast) [Answer] ## Wolfram Methematica, 104 bytes ``` Rest@*Intersection@@Map[Total]/@Subsets/@Union[Sort/@IntegerPartitions[#,#,PadLeft[{},Length[#2]#,#2]]]& ``` Ungolfed (read from the end): ``` Rest@* // Removing 0 Intersection@@ // Intersecting all totals Map[Total]/@ // Counting total of each subset Subsets/@ // Getting all the subsets of each partition Union[ // Removing duplicates Sort/@ // Sorting each partition (to remove duplicates next) IntegerPartitions[#,#,PadLeft[{},Length[#2]#,#2]] // Getting all Integer partitions ]& ``` ]
[Question] [ # Intro Let's play some mini-golf! The golf ball is represented by a `.` and the hole by a `O`. You want to get a hole in one on every hole, but you are not good at putting. In fact, you refuse to attempt putting diagonally! Only up, down, and to either side. You plan to cheat by placing extra bumpers `\` and `/` so you can put the ball in with one shot. The ball bounces off of the bumpers at right angles, as shown in this picture. ![Golf](https://i.stack.imgur.com/6UlQo.png) Remember to call your shot! Tell us what direction you're putting. --- # Holes **1:** The first hole is easy, a straight shot! No bumpers needed to place here. Input: ``` . O ``` Output: ``` right . O ``` --- **2:** Another basic one, a short turn. The ball is hit off the bumper into the hole. Input: ``` . O ``` Output: ``` left / . O ``` or ``` down . O / ``` --- **3:** Some holes have bumpers already! Input: ``` . \O ``` Output: ``` right . \O \/ ``` or ``` right / \ . /\O ``` --- **4:** Some holes are overly complex! Input: ``` / \ \ / / . \ \ / / /\/ /\ \ / / / / \ \/ / / /\ \ / \ / \ \ / \ \/ \/ \ / / /\ \//\ \ / / \ / \ \ \/ \ /\ \ / \ \ \/ \ \/ \ O/ \ / \/ ``` Output: (one possible solution, more exists) ``` down / \ \ / / . \ \ / / /\/ /\ \ / / / / \ \/ / / /\ \ / \ / \ \ / \ \/ \/ / \ / / /\ \//\ \ / \/ \ / \ \ \/ \ /\ \ / \ / \ \/ \ \/ \ O/ \ / \ \/ \ / ``` # Rules * The **input** is the mini-golf hole on `STDIN`. * The **output** is the direction you hit the ball and the mini-golf hole with newly placed bumpers on `STDOUT`. * Existing bumpers cannot be moved. * You can add any number of bumpers to solve a hole. * Assume there are valid locations for the bumpers to be placed that will allow the course to be solved in one putt. * The outputted hole may be bigger than the input. * The input may be padded with trailing white space, but please specify in your answer if you do this. * The output must look correct, but can have leading or trailing white space. * Your program should work for any valid hole. Feel free to post your test cases too! # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Your score is the number of characters in your program. Lowest score wins! [Answer] # Javascript (ES6) - 651 bytes ``` G=s=>{Q='\\';S=[[]];n=L=1;s.split(N='\n').map(t=>{j=S[L++]=[];l=t.length;n=n>l?n:l;k=1;t.split('').map(T=>{j[k++]=T})});S[O=L++]=[];n++;for(r=0;r<L;r++)for(c=0;c<=n;c++){v=S[r][c];if(!v)S[r][c]=' ';if(v=='.'){x=c;y=r}if(v=='o'){X=c;Y=r}}f=M=>{J=M?'.':'o';K=M?'o':'.';R=0;for(D=0;1;D++){R=D&4;D=D&3;c=e=D;g=M?X:x;h=M?Y:y;while(c!=K){c=S[h+=[-1,0,1,0][e]][g+=[0,1,0,-1][e]];e=c=='/'?(B=c,e^1):c==Q?(B=c,3-e):e;E=h*(h-O)?g*(g-n)?0:2:1;if(R&&c==' '){S[h][g]=Q;R=D=0;c=K}if(c==J||E){E&&(S[h][g]=(E+M)%2?Q:'/');H=M?E?H:(e+2)&3:D;return}}}};f(0);f(1);S[0][0]=S[O][n]='/';S[0][n]=S[O][0]=Q;return['up','right','down','left'][H]+N+S.map(t=>t.join('')).join(N)} ``` Creates a function `G` that accepts a string (golf course) as input and returns the requested putting solution. The input string may or may not have leading lines, trailing lines, and trailing whitespace. The output will not have leading or trailing whitespace. Expanded code is: ``` G = s => { Q = '\\'; S = [[]]; n = L = 1; s.split( N = '\n' ).map( t => { j = S[L++] = []; l = t.length; n = n > l ? n : l; k = 1; t.split('').map( T => { j[k++] = T; } ); } ); S[O = L++] = []; n++; for( r = 0; r < L; r++ ) for( c = 0; c <= n; c++ ) { v = S[r][c]; if( !v ) S[r][c] = ' '; if( v == '.' ) { x = c; y = r; } if( v == 'o' ) { X = c; Y = r; } } f = M => { J = M ? '.' : 'o'; K = M ? 'o' : '.'; R = 0; for( D = 0; 1; D++ ) { R = D & 4; D = D & 3; c = e = D; g = M ? X : x; h = M ? Y : y; while( c != K ) { c = S[h += [-1,0,1,0][e]][g += [0,1,0,-1][e]]; e = c == '/' ? (B=c,e^1) : c == Q ? (B=c,3-e) : e; E = h*(h-O) ? g*(g-n) ? 0 : 2 : 1; if( R && c == ' ' ) { S[h][g] = B; R = D = 0; c = K; } if( c == J || E ) { E && (S[h][g] = (E+M)%2 ? Q : '/'); H = M ? E ? H : (e+2)&3 : D; return; } } } }; f(0); f(1); S[0][0] = S[O][n] = '/'; S[0][n] = S[O][0] = Q; return ['up','right','down','left'][H] + N + S.map( t => t.join('') ).join( N ); } ``` The solver operates on the premise that any path from the ball (hole) will either 1. lead back to the ball (hole) again 2. lead to the hole (ball) 3. exit the course We trace the ball's path in all four directions. If we find case 3, the problem is solved. If we find case 2, we mark the ball's exit location. If all four directions result in case 1, we convert the first non-bumper space along any trajectory to a bumper (if the problem is solvable, such a space is always guaranteed to exist) and try again. The bumper we convert to will have the same type as the last bumper our trajectory encountered\*. If the ball is still stuck in a loop, we repeat the process as many times as needed. If the problem is solvable, this procedure is guaranteed to eventually lead to outcome 2 or 3. (\*Note that if we simply convert to a fixed bumper [say, `\`], there exist extremely contrived but nevertheless *possible* cases where a solution exists but we will fail to find it.) We perform a similar trace from the hole, leading to either outcome 2 or outcome 3. If both the ball trace and hole trace result in outcome 2, we place bumpers on the periphery of the course that link the two exit points (in fact, these periphery bumpers are placed regardless of the trace outcomes, to shorten the code). This completes the solution. ### Test Cases and Outputs **In** ``` / \ / \ /\ \\ / \ \ / / o / / \ / \ . \ \ \\ / / \ \ \ / \ / \ /\ / \/ //\ ``` **Out** ``` right / / \ / \ / \ /\ \\ / \ \ / / o / / \ / \ . \ \ \\ / / \ \ \ / / \ / \ /\ / \/ //\ \ / ``` **In** ``` / \ / / / \ / \ / \\ / \ \ / \ // \ \ / /\ \ / \ // \ // \ \ \ / / \\ \ \ / \ / \ \ / / \\ / / // / / /\ \\ // / \ / \ / \\ \ \ \ \ \ \ // \ / / \ \ / / / / \ / / / \ / \ /\ / \ / \ /\ //\ .\ \ \ //\ / \ / \ / / \/ \ /\ //\ / \ / o// \ / \ / / \ / \ / \\ / \ / \ \ \ / / / \ / \ // \ / \/ /\/ / \ / \ / \\ / \ /\ / \ / \/ \ / \/ \ / \ /\\ / /\\ //\ / \ /\ /\ / / \ / \/ ``` **Out** ``` left / \ / \ / / / \ / \ / \\ / \ \ / \ // \ \ / /\ \ / \ // \ // \ \ \ / / \\ \ \ / \ / \ \ / / \\ / / // / / /\ \\ // / \ / \ / \\ \ \ \ \ \ \ // \ / / \ \ / / / / \ / / / \ / \ /\ / \ / \ /\ //\ .\ \ \ //\ / \ / \ / / \/ \ /\ //\ / \ / o// \ / \ / / \ / \ / \\ / \ / \ \ \ / / / \ / \ // \ / \/ /\/ / \ / \ / \\ / \ /\ / \ / \/ \ / \/ \ / \ /\\ / /\\ //\ / \ /\ /\ / / \ / \/ \ \ / ``` **In** ``` /\/ \ \ \ \ \ \\ \ o \ .\ \ \ / / \ / ``` **Out** ``` down / \ /\ /\/\\ \ \\ \ \ \\ \ o \ .\ \ \ / / \ / \ / ``` ]
[Question] [ Consider [compass-and-straightedge construction](https://en.wikipedia.org/wiki/Straightedge_and_compass_construction), where you can construct new points from existing ones by examining intersections of straight lines and circles constructed with one of the following two options: * Draw the unique infinitely long straight line passing through points \$(x, y)\$ and \$(x', y')\$ * Draw the unique circle centered on \$(x, y)\$ that passes through the distinct point \$(x', y')\$ We begin with two points, typically \$(0, 0)\$ and \$(1, 0)\$, but any two distinct points suffice. If we draw all possible lines and circles using these two points, how many total points do we end up with? Spoiler: 6, shown below. [![Two circles with a horizontal line passing through them both. There are 6 points labeled A through F at all intersection points](https://i.stack.imgur.com/49J6B.png)](https://i.stack.imgur.com/49J6B.png) If we now repeat this procedure - drawing every line between two points and every circle determined by two existing points - and then add the newly constructed points to our set, we end up with 203 total points. We can then do this again, and again, and so on to form a sequence that begins $$2, 6, 203, 1723816861$$ This is [A333944](https://oeis.org/A333944), added to OEIS after [this Math.SE question](https://math.stackexchange.com/q/3377988/427632) was asked about the 4th term in the sequence. Note that, as of writing, only \$4\$ terms exist in the sequence on OEIS. --- Unsurprisingly, your task is to output this sequence. This is a standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge, meaning that you may complete one of the following options, using \$0\$ or \$1\$ indexing of your choice (if applicable): * Take an integer \$n\$ and output the \$n\$th term in the sequence * Take an integer \$n\$ and output the first \$n\$ terms in the sequence * Output the sequence indefinitely, in ascending order This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in each language wins. --- In the linked Math.SE question, the [answer provides some Haskell code](https://math.stackexchange.com/a/3514953/427632) which completes this task. Unsurpsingly, it is highly ungolfed, and very slow, taking approximately \$6\$ days to find the fourth term in the sequence. I offer a 1000 rep bounty (\$2 \times 500\$ rep bounties) for the first answer which can find and verify the 5th term in the sequence. The rough upper bound given in the linked question suggests that it is no larger than \$10^{314}\$. [Answer] # [Python](https://www.python.org)+`sympy`, 247 bytes ``` from sympy import* from itertools import* c,C,p=combinations,Circle,{a:=Point(0,1),a*2} while[l:=set()]: print(len(p)) for a,b in c(p,2):l|={Line(a,b),C(a,d:=abs(a-b)),C(b,d)} for a in c(l,2):p|={i for i in intersection(*a)if type(i)is Point2D} ``` Unfortunately, the challenge is quite trivial with sympy. I do have another solution without using modules, which should theoretically work, but doesn't due to rounding errors. Might post that later when fixed. Extremely slow ofc. [Attempt This Online!](https://ato.pxeger.com/run?1=PZCxasQwDIYp3fIUHq2ggzZTCWTKjR26Hx0cn0MFji1s3xDu8iRd0qF9qD5N7eToJOn79aMfff7wnD68W9fvSxoPL78Pj2Pwk4jzxLOgiX1IdbUhSiYk7238xxp75E77aSCnEnkXsaegrcGrars3Ty7JJ3wGVHWzVKMPwgpyp2iShPe6qOT4kgdoK1FkhUNeEFoyNtDaW3d9JWdkxoB9Lue2U0OU6jBAAQOeYbk7d58tPs4-2igVmu-YEI0uAWWtgEaRZjaSgKLYQjbHpeJQ8ljjJAPsv7i_ZP1q9uYP) (modified code to work on ATO) ]
[Question] [ Alice and Bob are perfect logicians trapped on an island with a puzzle generator. Although they can instantly solve the Riemann hypothesis and P=NP just by thinking about it, rather than doing anything useful, they amuse themselves by giving each other puzzles. The setup is as follows: a positive integer *n* is chosen by the puzzle generator, and is told to Alice and Bob. The puzzle generator also chooses a secret integer *k*, with `0 <= k < n`. Next, the puzzle generator gives information about *k* to Alice and Bob in alternating turns. Whenever either one learns *k*, they immediately yell out "I know the number!" Furthermore, Alice and Bob both know this setup. Your task is, given the puzzle generator's output, determine when each one learns the number, if they ever do. # Input You will receive *n*, *k* and a list of list of integers, with each list being length *n*. These lists are all public knowledge and indicate what the person would have received for every hypothetical value of *k*. Only the person whose turn it is actually receives the hint (the *k*th value of the array), but both players know what hint would have been received for any particular value of *k*. The first clue is given to Alice, the next to Bob, then Alice etc. An example is more illuminating than text: ``` n=5 k=0 [[1, 1, 2, 2, 2], [1, 2, 1, 1, 1], [0, 0, 0, 0, 0]] --> (2, 2) ``` Let's walk through the example. Alice first receives the number 1, because *k=0* and the 0th element of `[1, 1, 2, 2, 2]` is 1. Both Alice and Bob receive the information about what Alice would have gotten had *k* been something else, so Alice now knows that either *k=0* or *k=1* and Bob knows that Alice knows whether *k=0 or 1* or *k=2, 3, or 4*. Since Alice doesn't yet know *k*, she says nothing. Next, Bob receives the number 1, because *k=0*. Thus, Bob learns that *k=0, 2, 3, or 4*. In addition, the fact that Bob says nothing lets Alice rule out the possibility that *k=1*, since if *k=1*, Bob would have gotten *2* and would have learned it, so now Alice knows that *k=0* and says that she knows *k*. Bob knows that if *k=2, 3, or 4*, this would not be possible, because the fact that he said nothing only rules out *k=1* for Alice, which she would have already ruled out anyway. Thus, Bob also learns that *k=0*. Thus, they both require 2 clues to learn *k*, so the output is *(2, 2)*. Note that all clues after both Alice and Bob learn *k* don't matter; in particular, `[0, 0, 0, 0, 0]` doesn't give any information anyway, but regardless of what it is, you can essentially ignore it. # Output Output or return two integers, the number of clues for Alice to learn *k* and the number of clues for Bob to learn *k* respectively. In the special case where `n=1`, the output is always `(0, 0)` since both Alice and Bob immediately know, without any clues, that `k=0` just upon learning `n`. If one of the two never learns *k*, output `-1`, `Infinity`, `None`, `NaN`, or something else that makes it clear that they do not learn *k*. Your code only has to work in theory; if in practice it results in a Stack Overflow error, that is fine, as long as you can show that your code would work given unlimited resources and an infinite call stack size. # Test cases ``` n=2 k=1 [[0, 1], [1, 1], [0, 0], [1, 0]] --> (1, 4) n=3 k=1 [[0, 1, 1], [0, 1, 1], [1, 2, 2]] --> (-1, -1) n=5 k=2 [[1, 1, 2, 2, 2], [1, 1, 1, 2, 2], [1, 1, 3, 1, 2]] --> (3, 3) n=4 k=0 [[0, 1, 2, 3], [0, 0, 0, 0], [0, 0, 0, 0]] --> (1, -1) n=6 k=5 [[0, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 0, 1]] --> (5, -1) n=5, k=2, [[1, 1, 2, 2, 2], [1, 2, 2, 3, 3]] -> (2,2) ``` That last one is a bit tricky so here's a step-by-step: First, Alice receives 2, so she knows either `k=2`, `k=3`, or `k=4`. Then, on the second step, Bob learns that either `k=1` or `k=2`. Since he doesn't know what it is, he says nothing, so Alice learns that `k` is not `0`, and moreover, Bob now knows Alice knows this. However, Alice still doesn't say anything (in fact she already knew that `k` was not 0). The fact that Alice doesn't say anything lets Bob eliminate the case `k=1`, since if `k=1`, Alice would have received `1` as her first input, so eliminating `k=0` would let her know that `k=1`. Hence, Bob knows that `k=2`, and says so. Now, Alice knows that what just happened is consistent with `k=2`. Is it consistent with `k=3` or `k=4`? If `k=3` or `k=4`, Bob would have gotten 3 as his clue, and there haven't been any clues so far that distinguish between `k=3` and `k=4` for anyone, so Bob couldn't know which one it is. Therefore, Alice also learns that `k=2`. This is code golf, so shortest code wins! [Answer] # JavaScript (ES7), 300 bytes Takes input as `(n, k, clues)`. Returns a pair in the format used in the challenge. ``` (n,k,a)=>n>1?a.map((c,t)=>[...m,...m].map((_,p)=>m.map(M=m=>!(v=m[p])|v&~-v?0:m[M|=v,p]=0,(x=~R[p&=1]|!(v=m[k][p])|v&~-v)?0:R[p]=t+1)|x?m.map(m=>m[p^1]&=~M):M&~-M&m[k][p^=1]?0:m[k][p]&=M,m.map((m,i)=>m[t&1]&=c.map(o=(v,j)=>o|=(v==c[i])<<j)|o)),m=[...Array(n)].map(_=>[x=2**n-1,x]),R=[-1,-1])&&R:[0,0] ``` [Try it online!](https://tio.run/##tZPNTuMwEMfvPIW5RDZMgp22e6iYVvsAufRqGRRlAbWQD5Uq6kpRX707tlPSpHSF@IisKPPPeOY3nvEqrdPXbL2sNmFR/nnYP@KeF/AMqcBZMVPzNMrTivMMNiToKIpysC/j5XuoSM6dkWCOs0teY64rI5o62IX1XE5znTRYQ2VQAt/ibqGrAJVpvOez6ZwFedNfg5trJZrt3IeloBTwTpkAd4mYJuSZBH7jHcVxGVyUABPwW3gOS4ulN4HdljmxRF7DiuSyoS/ETC@NuL1diaYUAnK0tf1er9O/vBC@unsqeIvx1VURKtgaAQvU9BUqI4JgMdUSpNlnZfFavjxEL@UTf@QKmASmjRDs55@bG8ZtOibFRR9j4jE04dCK/TKkeMvLygrSebbLfIrbYVBUFg8xfCptk6g2@1vS1v5kznMYFJGNhxijI4yOQHVQ7nS@icNi0JCwUL3TlPhcUzqtEzx2/IWmUAQ2GmKM29mQh5Sj/hwMrK8dy6Epp6fxC9jkqCm9ofS36ETryb2Dk@9orewKcBiTM00Z9zAOPYiHXerflGPKtzQfnY3TEf3fbHhrZBv1PTN6dGH3/wA "JavaScript (Node.js) – Try It Online") ### How? We first build an array \$m[\;]\$ of \$n\$ pairs of bitmasks: ``` m = [...Array(n)].map(_ => [x = 2**n - 1, x]) ``` The bitmask \$m[i][p]\$ represents the possible answers from the perspective of player \$p\$, assuming that the identifier of the \$i\$-th clue was received so far. In the main loop, we iterate on each list \$c[\;]\$ of clues at position \$t\$ and then \$n\$ times on each player \$p\$, alternately: ``` a.map((c, t) => [...m, ...m].map((_, p) => ...)) ``` For each list of clues, we update \$m[\;]\$ for the player that will receive the clue at this turn: ``` m.map((m, i) => m[t & 1] &= c.map(o = (v, j) => o |= (v == c[i]) << j) | o ) ``` For each player iteration, we test: * whether there's only one possible remaining answer given what was actually received (i.e. from this player's perspective) * whether there would be only one possible remaining answer if another clue was received so far (i.e. from the other player's perspective) This is performed in the following loop: ``` m.map(M = m => !(v = m[p]) | v & ~-v ? 0 : m[M |= v, p] = 0, (x = ~R[p &= 1] | !(v = m[k][p]) | v & ~-v) ? 0 : R[p] = t + 1 ) ``` If the current player doesn't say that he knows the answer (\$x\neq0\$), we remove all hypotheses where an answer is found at this point from the bitmasks of the other player: ``` m.map(m => m[p ^ 1] &= ~M) ``` If the current player says he knows the answer (\$x=0\$), we update the bitmask of the other player accordingly: ``` M & ~-M & m[k][p ^= 1] ? 0 : m[k][p] &= M ``` [Answer] # Python3, 956 bytes: ``` E=enumerate def f(n,k,h): m,o,c,r,I=[[],[]],[[],[]],0,[-1,-1],[[],[]] while h: if-1not in r:return r H=h.pop(0);V=[i for i,a in E(H)if a==H[k]and i not in I[c%2]and(m[c%2]==[]or i in m[c%2])];I[c%2]+=[i for i in m[c%2]if i not in V];m[c%2]=V;d={} for i,a in E(H):d[a]=d.get(a,[])+[i] if r[not c%2]==-1:o[not c%2]=[*d.values()] A,F,P=0,1,not c%2 if len(m[c%2])==1 and r[c%2]==-1:r[c%2]=c+1;A=1 while F: F=0 if A==0: for i in o[P]: if len(i)==1: m[P]=[j for j in m[P]if j!=i[0]];I[P]+=i if(N:=[J for j in o[not P]if(J:=[u for u in j if u!=i[0]])])!=o[not P]:o[not P]=N;F=1;P=not P else: for i in o[not P]: if len(i)==1: if len(K:=[J for j in o[P]if(J:=[u for u in j if u!=i[0]and u in m[P]])and len(J)==1])==1:m[P]=K[0] if len(K:=[J for j in o[P]if len(J:=[u for u in j if u in m[P]])==1])==1:m[P]=K[0] for i,a in E(m): if r[i]==-1and len(a)==1:r[i]=c+1;F=1;A=1;P=not i c+=1 return r ``` [Try it online!](https://tio.run/##jVTBauMwEL37K1SWBatRgpU0y2Izhxwa0haKT7kIHUxsb5QmdnDtXZZlvz2rkWSrSVO64BDN07w3M0@yj7/bbV3Nvh@b0@keiqo7FE3WFkFelKQMK/bCtjQOyIHVbMMa9gBCSCak/rn/iIkxZ2M@IAH5tVX7gmw1jahyzKu6JaoiTdwUbdfohcZXsJ0c62MY0WQNQpGybohiGebdhyuqSpIBrMSLzKqcKOIkHsTm6xSh8GBWAEIiEfcsQmVik0aDqt/UqoPUWiZOY53k8Oev7umihzgXmYR88qNow0wPRkdCSTMSaQSq2A7GPK59KG7zyc9s3xWvIcXkBVuyFCLGmUuxAvuiciNQAE5wyEYMem65GfFkAVwzrKFLNJQsIcI/LbIAiAzk56xFKi3UV1FYwEHahlS3uDP5O@tLiq7sbkCJSKJ3qXZOuXRVhs8xiEefbydFTviodzqz0@HODgt2TodKegN9btwv4DlZAk9SMCHWKPavxbsJHOvjKRz2dNnaZ22hy10/taQYos4japtziI0/Tzo1@KyOZV6r5Qtclz27ZQca96Uafbvw9Pu2MkM1KF4EdG4xuIcntBnh3ejfqdOxUVUbluEc30jBGdHP1D6SEWEjC3MEIkb8o7ul5IswyUGvNNW3VmAedwIDz8U9TS/vPG020DyDexFTw/L0d4PoD0fgW59@0LrHPDCzmNPS0cwr3RmlqGfNzge@iIYh3vbyjc39FGfGcUN7h53BZ21HVzAHu9rz//XBRmbWNyd2@gc) ]
[Question] [ About a year ago you were asked to find the [XOR primes](https://codegolf.stackexchange.com/q/66911/56656). These are numbers whose only factors are 1 and themselves when performing [XOR multiplication in base 2](https://codegolf.stackexchange.com/q/50240/56656). Now were are going to spice things up a bit. We are going to find the XOR primes in base *-2* ## Converting to Base -2 Base -2 is a lot like every other base. The left most place is the 1s place (1 = (-2)0), next to that its the -2s place (-2 = (-2)1), next to that is the 4s place (4 = (-2)2), and so on and so forth. The big difference is that negative numbers can be represented in base -2 without any negative sign. Here are some example conversions: ``` Decimal | Base -2 ----------------- 6 | 11010 -7 | 1001 12 | 11100 -15 | 110001 ``` ## XOR addition in Base -2 XOR addition in Base -2 is pretty much the same as XOR addition in binary. You simply convert the number to Base -2 and XOR each digit in place. (This is the same as addition without the carry) Here is an example worked through step by step: *(We will use the symbol `+'` to indicate Base -2 XOR addition)* Start in base 10: ``` 6 +' 19 ``` Convert to base -2: ``` 11010 +' 10111 ``` Add them without carrying: ``` 11010 +' 10111 --------- 01101 ``` Convert your result back into base 10: ``` -3 ``` ## XOR multiplication in Base -2 Once again XOR multiplication in base -2 is nearly the same as XOR multiplication in binary. If you are not familiar with XOR multiplication in base 2 there is an excellent explanation [here](https://codegolf.stackexchange.com/q/50240/56656) I suggest you take a look at that first. XOR multiplication in Base -2 is the same as performing long multiplication in base -2 except when it comes to the last step instead of adding up all of the numbers with a traditional `+` you use the `+'` we defined above. Here is an example worked out below: Start in decimal: ``` 8 *' 7 ``` Convert to Base -2: ``` 11000 *' 11011 ``` Set up long division: ``` 11000 *' 11011 --------- ``` Multiply the first number by every place in the second ``` 11000 *' 11011 ------------ 11000 11000 0 11000 11000 ``` Add up all the results using base -2 XOR addition ``` 11000 *' 11011 ------------- 11000 11000 0 11000 +' 11000 ------------- 101101000 ``` Convert the result back to decimal: ``` 280 ``` # The challenge Your challenge is to verify whether or not a number is an XOR prime in base -2. A number is an XOR prime in base -2 if the only pair of integers that multiply to it in base are 1 and itself. (1 is not prime) You will take in a number and output a boolean, truthy if the input is an XOR prime in base -2 falsy otherwise. Solutions will be scored in bytes with attaining the lowest number of bytes as the goal. # Test cases The following are all XOR primes in base -2: ``` -395 -3 -2 3 15 83 ``` The following are *not* XOR primes in base -2: ``` -500 -4 0 1 258 280 ``` [Answer] # Mathematica, ~~156~~ 101 bytes ``` IrreduciblePolynomialQ[FromDigits[{#}//.{a_,p___}/;a!=1&&a!=0:>{-⌊a/2⌋,a~Mod~2,p},x],Modulus->2]& ``` As stated [here](https://codegolf.stackexchange.com/q/50240/60043), this works because XOR multiplication is essentially multiplication in the polynomial ring F\_2. **Explanation** ``` {#}//.{a_,p___}/;a!=1&&a!=0:>{-⌊a/2⌋,a~Mod~2,p} ``` Start with `{input}`. Repeatedly replace a number `a` (except 0 and 1) by `a` mod 2 and prepend -floor(`a`/2), until it does not change. This calculates the input in base -2. ``` FromDigits[ ... ,x] ``` Create a polynomial using the digits of the base -2 number, using `x` as the variable. e.g. `{1, 1, 0}` -> `x^2 + x` ``` IrreduciblePolynomialQ[ ... ,Modulus->2] ``` Check whether the resulting polynomial is irreducible, with modulus 2. **Old version (156 bytes)** ``` If[#==1,1,Outer[FromDigits[BitXor@@(#~ArrayPad~{i++,--l}&)/@Outer[i=0;l=m;1##&,##],-2]&,k=Tuples[{0,1},m=Floor@Log2[8Abs@#~Max~1]]~Drop~{2},k,1,1]]~FreeQ~#& ``` **List of primes** [Here's a list of base -2 XOR primes between -1000 and 1000 (pastebin)](http://pastebin.com/HcdwNCJd) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 36 bytes ``` {2=≢⍸⍵=∘.{¯2⊥≠/⊤⍺×2*⍸⌽⊤⍵}⍨1+⍳8×1+|⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6uNbB91LnrUu@NR71bbRx0z9KoPrTd61LX0UecC/UddSx717jo83UgLJN@zF8zfWvuod4Wh9qPezRaHpxtq14BE/qcBzXrU2/eoq/nQeuNHbROB5gcHOQPJEA/P4P9ph1YoAMWB2EjBWMHQFMgw5IIImigYKBgqGCmYAAA "APL (Dyalog Extended) – Try It Online") Simple brute-force, and extremely inefficient (input 15 takes ~1s). Given an integer `n`, it generates a range large enough that their binary representation evaluated in negabinary includes `n`, evaluates its multiplication table (last step evaluated to negabinary instead of binary), then checks if the input appears exactly twice. The algorithm was inspired by [a solution to regular XOR primes](https://codegolf.stackexchange.com/a/66963/78410). ### How it works ``` {2=≢⍸⍵=∘.{¯2⊥≠/⊤⍺×2*⍸⌽⊤⍵}⍨1+⍳8×1+|⍵} ⍝ Inline function; ⍵←n 8×1+|⍵ ⍝ 8×(1+abs(n)) 1+⍳ ⍝ 1-based range of above ∘.{ }⍨ ⍝ Evaluate XORmul table ⊤⍵ ⍝ Binary of right arg 2*⍸⌽ ⍝ Digit values of ones ⊤⍺× ⍝ Multiply left arg and convert each to binary ≠/ ⍝ Digit-wise XOR ¯2⊥ ⍝ Interpret as negabinary and convert to integer 2=≢⍸⍵= ⍝ Does n appear exactly twice in the table? ``` ]
[Question] [ Cheat is a card game where you're trying to get rid of your hand. A turn looks something roughly like this: 1. Determine what card rank you have to play that turn. In most variants this is one rank higher than the previous turn. 2. Play 1-4 cards, face down. These don't have to match the valid rank. If they don't, it's considered a *cheat*. At this point any player may *challenge* you. * If nobody challenges you, play continues to the next player. * If somebody challenges you and you didn't cheat, they have to take all of the played cards. * If somebody challenges you and you did cheat, you have to take all of the played cards. The strategy is mostly a mix of bluffing and card counting. I'm bad at math, though, so I'm going to cheat at Cheat and bring a bot with me. # Input The input will be, in any order or format you want: 1. The player's hand. If I know that they must have cards (for example, I've seen them pick them up), those will be listed in ascending order. Any unknowns will be listed afterwards as `?`. For example, if they have six cards and I know that two are 1's and one is a 4, a valid representation of the hand is `114???`. **?'s will always be listed after known cards.** `141???` and `11???4` are both invalid inputs and your code doesn't need to handle them. 2. The cards I definitely know are not part of their hand (I have them, I saw someone else pick them up, etc). The list will be in ascending order of rank. The list may be empty. 3. The cards the player claimed to play. If they claimed to play 3 7's, a possible input here would be `777`. The cards will always be the same rank. The number of played cards will always be 1-4 and the ranks will always be 0-9. A rank will never appear more than four times in their hand + not their hand. This is an example valid input: ``` 33577?? 01555688 55 ``` This is an example invalid input: ``` 35377?? # Out of order 7779 # Five 7's in total 23 # Two separate ranks played ``` # Output A truthy value if we should **definitely** challenge. A falsey value if we might not want to challenge. We always challenge if we know they cheated. We know they cheated if they played cards they couldn't possibly have: ``` 12 3 # They don't have any 3's or ?'s ------------- 12? 33 # Fewer ?'s than played cards ------------- 123? 333 33 # Since we have three 3's they can't have two ``` The other time we challenge is if they play their last cards. Even if the play's legit it would end the game so we might as well challenge it. ``` 1 1 # They'd win, so challenge anyway ``` # More Test Cases **Truthy** (should challenge) ``` 11445678? 22 ------------- ???????? 4 4444 ------------- 12345678 9 ``` **Falsey** (should not challenge) ``` 1? 222 2 ------------- 12? 22 22 ------------- ????? 1111 ``` # Scoring Shortest code wins. [Answer] # Pyth, 22 bytes ``` !}zS+*hzhS,/Q\?-4l@z+w ``` [Try it online.](http://pyth.herokuapp.com/?code=%21%7DzS%2B%2ahzhS%2C%2FQ%5C%3F-4l%40z%2Bw&input=%2211445678%3F%22%0A22%0A&debug=0) [Answer] ## JavaScript (ES6), 93 bytes ``` (h,s,c,g=(a,z=c[0])=>a.split(z).length-1)=>h.length==g(c)|g(h,'?')+g(h)<g(c)|g(h)+g(s)+g(c)>4 ``` Accepts three strings of cards (characters `0`-`9` or `?`); returns `1` for challenge, `0` otherwise. Explanation: ``` (h,s,c, Input parameters g=(a,z=c[0])=> Helper function defaults to claimed card a.split(z).length-1 Count cards matching (g(c) == c.length) )=>h.length==g(c) Does hand length equal claim length |g(h,'?')+g(h)<g(c) Could hand not contain claimed cards |g(h)+g(s)+g(c)>4 Are there too many claimed cards ``` [Answer] # C#6, 134 bytes ``` using System.Linq; bool f(string a,string b,string c)=>a.Length==1|a.Count(x=>x==c[0]|x=='?')<c.Length|b.Count(x=>x==c[0])+c.Length>4; ``` (Note: In line with OP's example, this answer returns false even if opponent has more than one card and is playing all of his hand. In terms of strategy this should return true.) Explanation: `a`: Player's hand `b`: Cards I definitely know... `c`: Cards claimed to play Ungolfed: ``` bool f(string a, string b, string c) => a.Length == 1 // Last card played | a.Count(x => x == c[0] | x == '?' ) // Count no. of cards that surely/may match claimed cards // Assuming all claimed cards are the same, just compare with c[0] < c.Length // I'm sure you don't have that many cards... | b.Count(x => x == c[0]) + c.Length > 4; // ... Or that there can't be that many cards in play ``` [Answer] # Java 8, ~~169~~ 135 bytes ``` (a,b,c)->{int C=c.length();char x=c.charAt(0);return a.length()==C|(a+0).split(x+"|\\?",-1).length<=C|5-(b+0).split(""+x,-1).length<C;} ``` **Explanation:** [Try it here.](https://tio.run/##jZJRb5swEMff@ylOvMwohBaSbmtZhqZIe1tfurd2D4dxgjtjI9tEQW0@e2YI0FZqllgGneF3vv//7Cfc4FRVTD7lf/dUoDHwC7l8vgDg0jK9Qsrgrl0CZEoJhhIoubeayzVgAH2UjRH1Ewfv3OOmsWg5hTuQsIA9wSALqD/9/uy2huWChoLJtS2In9ACNWzdlzb4YcmVn2hmay0BR2ixWL4QnFz5oakEt2Q78V4eH1MvmEZ@D31zyPWUZK@Q5022b4FlstsnB3FVnQknrte4UTyH0lnvzT38AfQPvi8v4beuGfAV2IIbcNMWDFZcogCtapnfdtx9YywrQ1XbsHJbWCGJDCnxIi8Ar30iz@@6cxyN44F10QC/q88ayJX8ZKHADQMmVb0uQHV/oBLYsBwo6rxdl4aJDTMnxI0VZyfVRXE6wmfQ0Xx@/fnL1/QDS8crzLqcIeXmSBMAS9d32xpv3ZrBujuaUmnmEHdP51ByWZsP@UbVkLNVe8dFA6c0pQfLszOdp/1o8Xn3cmPMGuz8RGHY/yunh7Z1RxSfezw9Hp8nc7ybbvQZu4vd/h8) ``` (a,b,c)->{ // Method with three String parameters and boolean return-type int C=c.length(); // The amount of cards played by your opponent this turn char x=c.charAt(0); // The card played by your opponent this turn return a.length()==C// Return true if your opponent played his entire hand (final round) |(a+0).split(x+"|\\?",-1).length // Or the amount of the played card and '?' in your opponent's hand <=C // is smaller than the amount of cards played |5-(b+0).split(""+x,-1).length // Or if 4 minus the amount of the played card are part of the // cards you definitely know, <C; // is smaller than the amount of cards played } // End of method ``` NOTE: `(s+0).split("c",-1).length-1` gives the amount of times the character `c` occurs in String `s`. So the comments in the explanation above are correct, but the code might seem different because of it. The `(a+0).split(x+"|\\?",-1).length-1<C` is golfed to `(a+0).split(x+"|\\?",-1).length<=C` and the `4-(b+0).split(""+x,-1).length-1<C` is golfed to `5-(b+0).split(""+x,-1).length<C`. ]
[Question] [ # Introduction The game of [xiangqi](http://en.wikipedia.org/wiki/Xiangqi), also known as Chinese chess, is a chess-like game popular in China, Vietnam, Taiwan, and other East Asian countries. The colours of the two sides in xiangqi are red and black. There are seven pieces in xiangqi: the general (`G`), advisor (`A`), elephant (`E`), horse (`H`), chariot (`R`), cannon (`C`), and soldier (`S`). For the purposes of this challenge, uppercase pieces are considered red and lowercase pieces black. Most of these pieces have a rough equivalent in Western chess, but there is one completely unique piece: the cannon. The [cannon](http://en.wikipedia.org/wiki/Xiangqi#Cannon) moves like a rook in chess or a chariot in xiangqi (moving any number of spaces on either the X or Y axes), but cannot attack this way. Instead, it attacks by jumping along the X or Y axes (the same way it moves) over **one** piece of any colour (friend or foe) and landing on the opposite-coloured piece, which it then captures. Note that like all chess and xiangqi pieces, cannons cannot capture pieces of their own colour. For example, in the following diagram, the spaces to which the cannon (`C`) can move are marked with `*`, and those to which it can jump and capture are marked with `X`, assuming that there is a black/lowercase piece there. ``` ....X.... ......... ......... ....h.... ....*.... ****C**aX ....E.... ....X.... ....g.... ....R.... ``` # Challenge Write a program or function that, given a xiangqi board and the coordinates of a cannon on that board as input, outputs a list of coordinates to which the cannon can move or jump. The format for all I/O is flexible. Acceptable formats for the xiangqi board include a newline-separated string, a list of strings, or a string with any other separator not in `aceghrsACEGHRS.`. You may assume the board will always be 9x10, the size of a xiangqi board. The contents of the board itself will consist of a number of periods (`.`), representing empty points on the board, and characters representing pieces. The piece-to-character mapping is as follows: ``` A -> advisor C -> cannon E -> elephant G -> general H -> horse R -> chariot S -> soldier ``` Uppercase letters represent red pieces, and lowercase letters represent black pieces. Characters not listed here (i.e. not in `aceghrsACEGHRS.`) will not appear in the board. The format of the input coordinate is flexible, and is not required to match the format of the output coordinates. It can be a list of two integer elements, a 2-tuple, two numbers with any separator, or two characters, for example. It may also be either 0-indexed or 1-indexed. You may assume that the coordinate on the board will always resolve to a cannon (`C` or `c`). The coordinates to which the cannon can jump and move must appear in the same list in output; distinction between the two is not necessary. Acceptable formats for any individual output coordinates are the same as those for the input coord. The coordinates may be newline-separated, output as a list, or any other representation. No particular order is necessary; the order does not even have to be deterministic. Note that jumps onto a piece of the same colour (case) of the cannon are not legal, and thus cannot appear in the output. # Test cases Note that not all of the test cases are possible xiangqi positions. ``` Input board Input coordinate (0-indexed) List of output coordinates ......... ......... ......... ......... ......... ....C.... ......... ......... ......... ......... (4, 5) [(0, 5), (1, 5), (2, 5), (3, 5), (5, 5), (6, 5), (7, 5), (8, 5), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 6), (4, 7), (4, 8), (4, 9)] ......... .....G... ......... ......... .....e... ......... ......... h..R.c..S .....a... ......... (5, 7) [(4, 7), (6, 7), (7, 7), (5, 6), (5, 5), (5, 1)] ..s...... ..A...e.. ......... EACCcsh.H ..r...... .....S... ......s.. ....C.... ..g...... (2, 3) [(2, 0), (2, 2), (4, 3), (2, 8)] rheagaehr ......... .c.....c. s.s.s.s.s ......... ......... S.S.S.S.S .C.....C. ......... RHEAGAEHR (7, 7) [(2, 7), (3, 7), (4, 7), (5, 7), (6, 7), (8, 7), (7, 0), (7, 3), (7, 4), (7, 5), (7, 6), (7, 8)] ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. Happy golfing! [Answer] ## [Pip](http://github.com/dloscutoff/pip), 112 + 1 = 113 bytes Takes input as command-line arguments: the two coordinates, followed by the 10 lines of the board. Coordinates are 0-based. Outputs coordinates like `67 77`, with a newline between the same-row list and the same-column list. One byte added for the `-s` flag. ``` g@>:2P(f:{Ya@bQ'C?X^z;X^AZa@b:'@aR`\.*@\.*`{aR'.s}Ry.`\.*\w *@`s._@>1R`@ *\w\.*`.y_@<v.s@*s}g@ba).ba.(f;J(Zga)b) ``` [Try it online!](http://pip.tryitonline.net/#code=Z0A-OjJQKGY6e1lhQGJRJ0M_WF56O1heQVphQGI6J0BhUmBcLipAXC4qYHthUicuc31SeS5gXC4qXHcgKkBgcy5fQD4xUmBAICpcd1wuKmAueV9APHYuc0Aqc31nQGJhKS5iYS4oZjtKKFpnYSliKQ&input=&args=Nw+Nw+cmhlYWdhZWhy+Li4uLi4uLi4u+LmMuLi4uLmMu+cy5zLnMucy5z+Li4uLi4uLi4u+Li4uLi4uLi4u+Uy5TLlMuUy5TCg+LkMuLi4uLkMu+Li4uLi4uLi4u+UkhFQUdBRUhS+LXM) ### Explanation of somewhat ungolfed version ``` g@>:2 f:{ Y a@bQ'C ? `[a-z]` `[A-Z]` a@b:'@ aR:`\.*@\.*` {aR'.s} aR:y.`\.*\w *@` s._@>1 aR:`@ *\w\.*`.y _@<v.s a@*s } P (f g@b a).b a.(f; J(Zg)@a b) ``` By default, Pip reads command-line args into the list `g`. It also stores the first five arguments in the variables `a` through `e`. Our first two arguments, `a` and `b`, are the coordinates of the cannon; `g` contains the coordinates followed by the rows of the board. To get just the board in `g`, we slice it from index 2 onward and assign back to `g` (`g@>:2`). Now we define a function `f`. This function takes two arguments: a string representing a row or column of the board, and the index of the cannon in that string. These arguments are available inside the function as `a` and `b`. The function will return a list of all indices that represent spots the cannon can move to or capture. First, we test whether `a@b` is `C` or `c`. If it's `C`, we're going to want the regex `[a-z]` to match the pieces it can capture. If it's `c`, the regex is `[A-Z]`. (The golfed code generates these regexes from the builtin variables for lower- and uppercase alphabet.) We `Y`ank the appropriate regex into the `y` variable. We change the cannon's character in the string to `@` (to distinguish it from other cannons in the same row/column). Next comes a series of regex replacements, which will change every place the cannon can go to a space character. The first regex `\.*@\.*` matches `@` surrounded by any number of periods, all of which represent empty spots to which the cannon can move. The replacement uses a callback function `{aR'.s}` to change all the periods to spaces. The next regex matches a piece the cannon can capture: either `[a-z]` or `[A-Z]` (depending on which one was yanked into `y` earlier) followed by `\.*\w *@` (any number of periods, one letter, any number of spaces, and `@`). This will match a string like `h..R @` (provided the cannon was `C`). The callback function `s._@>1` slices the first character off and prepends a space. The third regex is similar, but matches a capturable piece after the cannon rather than before it. Finally, the function returns `a@*s`, using the find-all operator to get a list of the indices of all spaces. We now call `f` on the cannon's row and again on the cannon's column. The row's string is `g@b`, with the cannon's index inside the string being `a`. The function returns a list of column numbers, to each of which we append the row number `b`. When the list is printed, the `-s` flag puts a space between the coordinate pairs. To get the column, we use the `Z`ip operator to transpose `g`, select index `a`, and `J`oin the resulting list of characters into a string. The cannon's index within this string is `b`. The function returns a list of row numbers, to each of which we prepend the column number `a`. This list, being the last expression in the program, is autoprinted. (In case anyone was wondering, the expression separator `;` is there to force `J` to parse as a unary operator rather than binary.) [Answer] # Python3, 309 bytes: ``` def f(t,b): q=[(*t,0,b[t[0]][t[1]],*i)for i in[(0,1),(0,-1),(1,0),(-1,0)]] while q: x,y,d,c,X,Y=q.pop(0) if 0<=(j:=x+X)<len(b)and 0<=(k:=y+Y)<len(b[0])and d<2: if'.'==(S:=b[j][k])and d==0:yield(j,k) if'.'!=S and S.isupper()!=c.isupper()and d:yield(j,k);d=2 q+=[(j,k,[d,1][d<2 and'.'!=S],c,X,Y)] ``` [Try it online!](https://tio.run/##lZFNb6MwEIbPy69wc4mduBaQRF2x8SGNoubUQ7i08lorPoMTFoih2ubXZ22gCU1ptYvFeJjxzDx@KY5VkmeT74U8ncIoBjGssI8cAxwog6MKm9hnFTM5V9biHI8EinMJBBAZgya2EFb2Vm8WNpW91RvnBviTiDQCB9UJvOIjDnGAn/AzPZAiL6CJVFjEwJxTuHPo6/gJzdMogz7ysrCO7h16HD@3UTW/ToRzW/dTlUMypBS6DvXZjrN9m6bUdI4iSkO4w3t0PnlDXaDzLhHlS1FEEqIbGlw@6tpO4Y@Q2rr4MFYaqABmIbY4U9N1m6Yhb@6DeKNaLn971S8/92QI75V832RUvcgMMDYSHLwpBmKRVmriY55FGNyTskhFBYc/syFC3DB8C1AwGAwMop5Em9ojPV5fdkmIF9Tequfc9uxttNFjCimyCrJRDOEMgynC767hWwoKGb5N35DIl0ikH@k/Kv6ByW6YJh2hOl0evpwRfZZNtCYBIW4T89Sr/v7lwBXXHQaza65JwzVttSrPMxbN4M601WK5DMqErFVMdlncC1WpCd4puO1FmWD7mmTakMxqEplE3taLEtm9d1DvATFK0q5eVVzSLqOBULaT3axXi4fFar35IM7dNdFME53@Ag) [Answer] # [Python 2](https://docs.python.org/2/), 238 bytes ``` def f(b,r,c,R=range): for K in[[(i,c)for i in I]for I in R(r+1,10),R(r)[::-1]]+[[(r,j)for j in J]for J in R(c+1,9),R(c)[::-1]]: p=0 for i,j in K: B=b[i][j];Z='.'<B*p;p+='.'<B if(p<1)+Z*((b[r][c]<'c')!=('a'>B)):print i,j if Z:break ``` [Try it online!](https://tio.run/##lZBdb4IwGIWv7a/o3EVbqY24GSPKEjTGrzu8k3EBHUjdgqR4sf161oJumPgR21BO2/f0PHmzn0OyT7tF8RHFMMYhlZRT15ZBuo2IBWC8l3AFRep5WFBO9FaoLVz4Wi60dLE0TGp2CFWKeJbVNn3fUAZJd6Vhp6uWpWFZGbgyDHQ9P9WrKJjZHbWWEbT0rCzQGNuhJ3xv5w83NmJoNG5lw8yoJGiIGGcjkxibFsahJ32P@yPEEXmyMQrQ25gQK5MiPegXdTXcWKGMgs8itJvNJjsN8IiaPOLQKXn2JQ4YvaeIwGc4@DY7gFNp41faI@DYcwJKTozaaiACwBlg9d7sZlp07TZhzGWcsXV1FqgPQngVsWLrUdi/C5f/ZTkVQC116kwmPE/YXJ3JOtP6ny7XJGc93d5A6lL4cgdJJlGwDaJE1hvByz9nIGfHebFNa3acoKJRa@3WnU@dmTOduxfR@je6VfwC "Python 2 – Try It Online") #### Ungolfed (301 bytes) ``` def g(a,b,I): p=0 for i,j in I: B=b[i][j] if p: if'A'>B:continue if('a'>B)!=a:print(i,j) break p='.'<B if p<1:print(i,j) def f(b,r,c): a=b[r][c]<'c' for I in[range(r+1,10),range(r-1,-1,-1)]:g(a,b,[(i,c)for i in I]) for J in[range(c+1,9),range(c-1,-1,-1)]:g(a,b,[(r,j)for j in J]) ``` [Try it online!](https://tio.run/##lZFdb4IwFIbv@ys6d1Ga1UbmjJHIEjRm6qVeMi5Kx0fdgqSwZPv17EBxYuJHbPk4PaXvec5L/lum@2xYVR9RjBNLsJCtqINw7g4QjvcaK7bDKsMryOGZG/oq8HcBxCrGeZ2DgHjkdebIfVaq7DsyOYsISNIHVzi5VllpgQ6tt0IdiU8IcpdwMp21SlO7@1nNElsh00zWLALK6sCXwZRIYqhWwORrkSWRpZ9sZg8oa1d9mzUXDRzTjg@akjatNI0E1EisjxISJCYHBXlGQQNVfaaxYh3QKnR7vR4/DHRPNL/nRF2lyL9UaZH3jFD8iCc/9gBJpl3rhY0oOtiEjH2kD4NQhE4Ajd7b1WrRpd2U8w2XnG9NTsANv/EiomEbMTy@CVf81/IMQKfqwpvPZZHyJeR0l2l7pCtqkhNPkytIzwwPbyDpNBKJiFLdNUI2b8lRwdt51qYtbycyNPDs7G6WC@/NWyw3Z9HGV9yq/gA "Python 3 – Try It Online") ]
[Question] [ ## Challenge Given an ASCII art shape, you must find out whether the shape is a regular hexagon or not. ## Hexagons A regular hexagon is defined using two rules: * It has six sides * Each side has equal numbers of characters For example, the following shape is regular but it doesn't have six sides and so is not a regular *hexagon*: ``` B a a h s a i d y o u r g a o t ``` Similarly, the following shape has six sides but has sides of different lengths and so is not a *regular* hexagon: ``` * * * * * * * * * * * * * * ``` However, the following shape has six sides and all of the sides have the same number of characters, so it is a regular hexagon: ``` T h e h e x a g o n s a r e c o m i n ``` ## Rules Output should be a truthy or a falsey value (truthy if the shape is a regular hexagon, falsey if not). The shapes will only ever contain printable ASCII characters. The border of the shape will never contain spaces. If it does, you can return falsey. There can be arbitrary amounts of whitespace before and/or after the shape. All angles in the shape may not be equal for example, the following shape is valid input: ``` . . . . . . . . . . . . . . . . . . ``` It will return a falsey value. All shape inputs will be on a space separated grid. Hexagonal input will be on a staggered grid (each line is offset from the next). ## Examples ### Truthy The following shapes should return truthy values: ``` # _ + + + 9 : ``` --- ``` 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 ``` --- ``` t h i s i s a h e x a g o n ! ! ! ! ``` --- ``` 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 ``` ### Falsey The following should return falsey values ``` r e c t a n g l e s ``` --- ``` h e l l o w o r l d s t h i s i s b e t a d e c a y n o w ``` --- ``` * * * * * * ``` --- ``` ..... ....... ......... ....... ..... ``` This shape is not on a space separated grid and is not staggered. --- ``` * * * * --------- * * * * * * ------------- * * * * * * --------- * * * * ``` --- ``` 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 ``` --- For single character inputs, your program may output either truthy or falsey: ``` & ``` ## Winning The shortest program in bytes wins. [Answer] ## R, 184 bytes Golfed, could probably be golfed by a few bytes ``` function(m){e=min;f=max;l=length;v=which(m!=" ",T);a=v[,1];n=l(v[a==1,2]);u=(v[a==e(a),2]);all(u==v[a==f(a),2])&all(c(e(d<-v[a==ceiling(f(v[,1])/2),2]),f(d))==c(u[1]-n+1,u[l(u)]+n-1))} ``` Ungolfed, very messy, more like half way golfed ``` f=function(m) { v = which(m!=" ",T) a = v[,1] n = length(v[a==1,2]) u=(v[a==min(a),2]) c1 = all(u==v[a==max(a),2]) d = v[a==ceiling(max(v[,1])/2),2] c2 = all(c(min(d), max(d))==c(u[1]-n+1,u[length(u)]+n-1)) c1 & c2 } ``` Since the input format is unspecified, Input needs to be specified in an R array format, looking something like this. ``` [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] " " " " "5" " " "6" " " "7" " " " " [2,] " " "8" " " "9" " " "0" " " "1" " " [3,] "2" " " "3" " " "4" " " "5" " " "6" [4,] " " "7" " " "8" " " "9" " " "0" " " [5,] " " " " "1" " " "2" " " "3" " " " " ``` Here is a generator function that generates the input. The generator doesn't generate an object that is fed into hexagon check function, but rather the code specifying the array (effectively the same thing). So this should not count as parsing the text. Remember that I'm not inputting text, but rather an array structure. ``` generate = function(x) { s = strsplit(strsplit(x, "\n")[[1]], "") m = max(sapply(s, length)) dput(do.call(rbind, lapply(s, function(x) c(x, rep(" ", m-length(x)))))) } ``` For example, the generated code would be: `structure(c(" ", " ", "2", " ", " ", " ", "8", " ", "7", " ", "5", " ", "3", " ", "1", " ", "9", " ", "8", " ", "6", " ", "4", " ", "2", " ", "0", " ", "9", " ", "7", " ", "5", " ", "3", " ", "1", " ", "0", " ", " ", " ", "6", " ", " "), .Dim = c(5L, 9L ))` which is identical to `array(c(" ", " ", "2", " ", " ", " ", "8", " ", "7", " ", "5", " ", "3", " ", "1", " ", "9", " ", "8", " ", "6", " ", "4", " ", "2", " ", "0", " ", "9", " ", "7", " ", "5", " ", "3", " ", "1", " ", "0", " ", " ", " ", "6", " ", " "), dim = c(5, 9))` Hopefully this input method is in compliance with the rules. Here are the test cases ``` x1 = " 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3" x2 = " # _ + + + 9 :" x3 = " t h i s i s a h e x a g o n ! ! ! !" x4 =" 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3" x5 = "r e c t a n g l e s" x6 = " h e l l o w o r l d s t h i s i s b e t a d e c a y n o w" x7 =" * * * * * *" x8 =" ..... ....... ......... ....... ....." ``` Generate input arrays ``` sapply(mget(paste("x", 1:8, sep = "")), generate) ``` Test for hexagon ``` sapply(.Last.value , f) x1 x2 x3 x4 x5 x6 x7 x8 TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE ``` [Answer] ## JavaScript (ES6), 214 bytes ``` (s,a=s.split`\n`,n=a[l=a.length>>1].match(r=/(?=\S).*\S/),i=n.index)=>!/\S( )*\S/.test(s)&&!a.some((s,j)=>(m=r.exec(s))&&(k=m.index)<i+(j<l?j=l-j:j-=l)|k+(m=m[0].length)+j>i+n[0].length|k+i+j&1|j%l<1&m+j+j!=l*4+1) ``` Where `\n` represents a literal newline character. Ungolfed: ``` function validhex(s) { if (/S( )*/S/.test(s)) return false; var a = s.split("\n"); var l = Math.floor(a.length / 2); var n = a[l].match(/(?=\S).*\S/); for (var j = -l; j <= l; j++) { var m = a[j+l].match(/(?=\S).*\S/); if (!m) continue; if (m.index < n.index + Math.abs(j)) return false; if (m.index + m[0].length + Math.abs(j) > n.index + n[0].length) return false; if ((m.index + n.index + j) % 2) return false; if (j % l) continue; if (m[0].length != l * 4 + 1 - 2 * Math.abs(j)) return false; } return true; } ``` [Answer] ## [SnakeEx](http://www.brianmacintosh.com/snakeex/index.html), 200 bytes The right language for the job... sort of. ``` m:{v<>}{r<RF>2P}{r<R>2P}{h<RF>1P}{w<>}{l<RF>2P}{l<R>2P}{h<.>1} w:{u<>P}{v<>} v:{e<L>}{u<R>1} u:.*{e<>} e:.$ r:[^ ]+ h:([^ ] )+ l:({c<.>}[^ ])+{c<.>} c:{b<B>}(. )+{x<>LP}{s<>} b:.{s<>} s:[^\!-\~]*$ x:. ``` SnakeEx is a language from the [2-D Pattern Matching](https://codegolf.stackexchange.com/q/47311/16766) challenge. It ought to be really good at this task, but unfortunately all the corner cases really bloated the code. I also turned up a couple of interpreter bugs. Still, it was a fun challenge. `m` is the main snake that calls all the others to do the actual work. It matches starting at the top right corner of the hexagon and going clockwise. Numbered groups are used to verify that the diagonal side lengths are all equal and that the horizontal side length matches the height of the whole figure. I could write a more detailed explanation, but I've spent the last two days dealing with corner cases, so just try it out for yourself [here](http://www.brianmacintosh.com/snakeex/index.html). :^) [Answer] # Perl, ~~127~~ ~~125~~ ~~124~~ 121 bytes Includes +4 for `-0p` Give input on STDIN ``` #!/usr/bin/perl -0p / *(.*\S)/;$a=join'\S * \1',map$"x(abs).'\S '.(/$n/?'\S ':'. ')x(2*$n-1-abs),-($n=$1=~y/ //)..$n;$_=/^$`( *)$a\S\s*$/ ``` ]
[Question] [ In races in which racers go around at least one turn of a curved track, the starting positions for each racer are staggered, so that each racer travels the same distance around the track (otherwise, the racer in the innermost lane would have a huge advantage). Given the lengths of the major and minor axes (or semi-major and semi-minor, if you'd prefer) of an elliptical track and the number of lanes in the track, output the distances from the innermost lane's starting point that each lane should be staggered. ## Specifications * Each lane is an ellipse with semi-major axes 5 units longer than the next-shortest lane. For simplicity, assume that the lanes have 0 width. * The innermost lane always starts at 0, and every other starting point is a positive integer greater than or equal to the previous starting point. * Input and output may be in any convenient and reasonable format. * The inputs will always be integers. * You must calculate the circumference of the track to within 0.01 units of the actual value. * Outputs are to be rounded down to the nearest integer (floored). * The finish line is the starting point for the innermost racer. There is only one lap in the race. * The lengths of the axes are measured using the innermost lane of the track. * Outputting the 0 for the innermost lane's offset is optional. ## Test Cases Format: `a, b, n -> <list of offsets, excluding innermost lane>` ``` 20, 10, 5 -> 30, 61, 92, 124 5, 5, 2 -> 31 15, 40, 7 -> 29, 60, 91, 121, 152, 183 35, 40, 4 -> 31, 62, 94 ``` These test cases were generated with the following Python 3 script, which uses an approximation of the circumference of an ellipse devised by Ramanujan: ``` #!/usr/bin/env python3 import math a = 35 # semi-major axis b = 40 # semi-minor axis n = 4 # number of lanes w = 5 # spacing between lanes (constant) h = lambda a,b:(a-b)**2/(a+b)**2 lane_lengths = [math.pi*(a+b+w*i*2)*(1+3*h(a+w*i,b+w*i)/(10+math.sqrt(4-3*h(a+w*i,b+w*i)))) for i in range(n)] print("{}, {}, {} -> {}".format(a, b, n, ', '.join([str(int(x-lane_lengths[0])) for x in lane_lengths[1:]]))) ``` The approximation used is: [![ellipse circumference approximation](https://i.stack.imgur.com/qHH1c.png)](https://i.stack.imgur.com/qHH1c.png) Finally, here is a helpful diagram for understanding the calculations of the offsets: [![track](https://i.stack.imgur.com/WjIBj.png)](https://i.stack.imgur.com/WjIBj.png) [Answer] # Haskell, ~~103~~ 98 bytes ``` c!d|h<-3*d*d/c/c=pi*c*(1+h/(10+sqrt(4-h))) f a b n|x<-a-b=[floor$(a+b+10*w)!x-(a+b)!x|w<-[1..n-1]] ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 43 bytes ``` UVFXY-nXY+WZn/3*©T4®-t+/>Z*žq*5DX+UY+V})¬-ï ``` **Explanation** ``` UV # X = a, Y = b F } # n times do XY-n # (a-b)^2 XY+W # Z = (a + b) / # divide (a-b)^2 Zn # by (a+b)^2 3* # multiply by 3 © # C = 3h / # 3h divided by T # 10 + # + 4®-t # sqrt(4-3h) > # increment Z*žq* # times (a + b)*pi 5DX+UY+V # increase a and b by 5 ) # wrap in list of circumferences ¬- # divide by inner circumference ï # floor # implicitly display ``` [Try it online!](http://05ab1e.tryitonline.net/#code=VVZGWFktblhZK1dabi8zKsKpVDTCri10Ky8-WirFvnEqNURYK1VZK1Z9KcKsLcOv&input=MTUKNDAKNw) [Answer] # Python 3, ~~168~~ 164 bytes *Thanks to @Adám and @Mego for -2 bytes each* ``` from math import* h=lambda a,b:3*(a-b)**2/(a+b)**2;C=lambda a,b:pi*(a+b)*(1+h(a,b)/(10+sqrt(4-h(a,b)))) f=lambda a,b,n:[int(C(a+i*5,b+i*5)-C(a,b))for i in range(n)] ``` A function `f` that takes input via argument and returns a list of lane offsets, including `0` for the innermost lane. **How it works** This uses Ramanujan's approxiamtion. We simply define functions `h` and `C` for calculating the parameter and circumference, then subtract the length of the innermost lane from the length of the current lane and floor, for all lanes. [Try it on Ideone](http://ideone.com/ZxR4mt) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 45 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) Prompts for *n*, then for *a* *b*. Requires `⎕IO←0` which is default on many systems. ``` ⌊1↓(⊢-⊃)(○+×1+h÷10+.5*⍨4-h←3×2*⍨-÷+)⌿⎕∘.+5×⍳⎕ ``` `⍳⎕` prompt for *n*, then give {0, 1, 2, ..., *n*−1) `5×` multiply by five to get {0, 5, 10, ..., 5​*n*−5} `⎕∘.+` prompt for *a* and *b*, then make an addition table:   *a*, *a*+5, *a*+10, ... *a*+5​*n*−5   *b*, *b*+5, *b*+10, ... *b*+5​*n*−5 `(`...`)⌿` apply the parenthesised function to each vertical pair, i.e.   *f*(*a*, *b*), *f*(*a*+5, *b*+5), *f*(*a*+10, *b*+10), ..., *f*(*a*+5​*n*−5, *b*+5​*n*−5)   where *f*(*x*, *y*) is\* > > `○` pi times > > > `+×` (*x* + *y*) times > > > `1+` one plus > > > `h÷` *h*(*x*, *y*) [the function *h* will be defined later] divided by > > > `10+` ten plus > > > `.5*⍨` the square-root of > > > `4-` four minus > > > `h←` *h*(*x*, *y*), which is > > > `3×` three times > > > `2*⍨` the square of > > > `-÷` (*x* − *y*) divided by > > > `+` *x* + *y* > > > `(⊢-⊃)` on the result of the function applied to each pair, subtract the value of the first result `1↓` remove the first (zero) `⌊` round down [TryAPL online!](http://tryapl.org/?a=%7B%u230A1%u2193%28%u22A2-%u2283%29%28%u25CB+%D71+h%F710+.5*%u23684-h%u21903%D72*%u2368-%F7+%29%u233F%281%u2193%u2375%29%u2218.+5%D7%u2373%u2283%u233D%u2375%7D%A8%2820%2010%205%29%285%205%202%29%2815%2040%207%29%2835%2040%204%29&run) --- \*In procedural language: `-÷+` find the fraction of the difference between and the sum of *x* and *y* `2*⍨` square that fraction `3×` multiply that square by three `h←` assign that product to *h* `4-` subtract that product from four `.5*⍨` take the square-root of that difference `10+` add ten to that square-root `h÷` divide *h* by that sum `1+` add one to that fraction `+×` multiply that sum with the sum of *x* and *y* `○` multiply that product by pi ]
[Question] [ # The challenge Given a 2d string representing the bottom of a boat as an input, you must determine whether or not the boat will float. This 2D string can be in whatever format is most convenient. (String with newlines, list of string, list of list of chars, etc.) Print a truthy value if it will float, and a falsey value if it will sink. A boat will tip over if the bottom has an inconsistent density, so every character of must be the same. Also, if a boat has large holes in it, represented by spaces, it will sink, so your boat must have no holes with an area greater than 4. Here is an example: ``` ######## # #### ######## # ## ## # ##### ######## ``` This boat is valid because the largest hole in it has an area of 4. This boat: ``` ######## ######## # ## # ##### ######## ``` is invalid because it has a hole with an area of 7. You can safely assume that the outside of every input will be a solid rectangle with no holes. Here are some more tests: ``` $$$$$$$$ ***$$$$$ ***$$$$$ ***$$$$$ $$$$$$$$ Invalid density. Sink. %%%%%%%% % % % %%%%% % % % % %%%%%%%% None of the holes are larger than 4. Float. OOOOOOOO OOOOOOO OOOOOOOO OOOOOOOO OOOOOOOO The outside border is not solid. Undefined. &&&&&&&&&&&&& & & & & & & & && & & & & && & & & & & & & && & & & & && & & & & & & & &&&&&&&&&&&&& Although I would not be comfortable riding in this boat myself, none of the holes are larger than 4. It floats. @@@@@ @ @ @ @ @ @ @@@@@ It sinks. ``` # Rules * IO can be in any reasonable format. * Standard loopholes apply. * Shortest answer in bytes wins. * The given string will entirely consist of printable ASCII. [Answer] # Matlab, 106 bytes ``` s=input('');im=~(s-32);c=bwconncomp(im,4);disp(~nnz(cellfun(@nnz,c.PixelIdxList)>3)&nnz(unique(s(~im)))<2) ``` The input is a matrix of characters, e.g. for the first test case: ``` `['$$$$$$$$';'***$$$$$';'***$$$$$';'***$$$$$';'$$$$$$$$']` ``` Explanation: ``` s=input(''); %read input im=~(s-32); %convert input to bw image (space = black) c=bwconncomp(im,4); %calculate the connected components (4 connectivity) disp( ~nnz(cellfun(@nnz,c.PixelIdxList)>3) %find out whether we have components that have more at least 4 pixels &nnz(unique(s(~im)))<2) %find out if we have more than 1 non-space character ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 76 bytes ``` {(1=≢∪' '~⍨∊⍵)∧×/5>a/⍨×a←∊g↓⍉↑(g←{⊃,/{×⊃⍵:+/⍵⋄⍵}¨⍵⊂⍨1,2{≠/0=⊃¨⍺⍵}/⍵}¨)' '=⍵} ``` [Try it online!](https://tio.run/##nU@xSsNQFN3zFRdi@tpYiVW6CJFCF50E6@IYKOlSVOokQQeVkEReqEjJKi6WIrjYxbH5k/sj6b3PWJMSOngCeeede849iXM13OnfOMPLQYbxpHsOou9eXIvMq7dsDN8wmAkQdyinGEQo5w0M3tPEah86Fmlp4qA/pskA/ReUIfrPdaJjD6OHpuWlCZ0UOtgm8xyfHul9u5gyj@4p3mrueRi@Wrs2@Vj/ZoP142pQr800c7lDxmrXB8qvxec@FdHX9k679D47Ou5lI9UaT9hKM9XmAse1EQg9B63UAeCXllRdhz@6ZljfUV4Hm4NbOUg3TXMzXXk5aOQg3eAWAxRlAFSp7OXgSQ6xoiCq1BLlYK0IGtag8PC9cP3fvLifGzsMmnToTypPNde0JQ "APL (Dyalog Unicode) – Try It Online") Accepts input as a list of strings. 1 for floating, and 0 for sinking. ## Explanation ``` {(1=≢∪' '~⍨∊⍵)∧×/5>a/⍨×a←∊g↓⍉↑(g←{⊃,/{×⊃⍵:+/⍵⋄⍵}¨⍵⊂⍨1,2{≠/0=⊃¨⍺⍵}/⍵}¨)' '=⍵} ' '=⍵ boolean array for spaces (g←{⊃,/{×⊃⍵:+/⍵⋄⍵}¨⍵⊂⍨1,2{≠/0=⊃¨⍺⍵}/⍵}¨) apply the following function g to each row: 1,2{≠/0=⊃¨⍺⍵}/⍵ get the start of each group of zeroes/nonzero values ⍵⊂⍨ cut the list according to that {×⊃⍵:+/⍵⋄⍵}¨ sum each nonzero array ⊃,/ join all of that together g↓⍉↑ apply g again on the transpose a/⍨×a←∊ flatten and remove zeroes ×/5> are all sums ≤ 4? ∧ and ' '~⍨∊⍵ the boat with spaces removed ∪ uniquified 1=≢ has only 1 element? ``` ]
[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 last year. [Improve this question](/posts/77030/edit) > > Moderator note: <https://strawpoll.me> has [officially shut down](https://support.fandom.com/hc/en-us/articles/7951865547671), and the linked API no longer appears to work or provide data. Therefore, new answers cannot actually do the task and so the challenge has been closed to prevent any new answers. > > > [Strawpolls](http://strawpoll.me/) are great, and we use them in chat all the time for getting opinions on things. But they're kinda annoying to make since you need a webbrowser to make them, and everyone knows that I access PPCG only through SE APIs and curl. So I want you to write some code that uses [Strawpoll's API](https://github.com/strawpoll/strawpoll/wiki/API) to make a strawpoll with the given options. ## Specs Take as input a list in any reasonable format of options as strings, and a title which is also a string. Then use the API to make a strawpoll with that title and those options and output the url. Multiples should not be allowed, duplicate checking should be enforced, and captchas should not be necessary. # Example ``` "My Awesome Poll" ["option 1", "I like pies", "I also like cakes"] ``` Output: <http://strawpoll.me/7275997> This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! [Answer] # Factor, ~~257~~ 262 bytes ``` TUPLE: p title options dupcheck ; [ command-line rest [ first ] [ rest ] bi "normal" p boa >json "https://strawpoll.me/api/v2/polls" <post-request> "application/json" "Content-Type" set-header http-request nip json> id>> 10 base> "http://strawpoll.me/" prepend ] ``` Expects a name as the first command-line arg, then options after that. Requires `com-auto-use`. Ungolfed: ``` TUPLE: poll title options dupcheck ; : post-json ( post-data url -- response data ) <post-request> "application/json" "Content-Type" set-header http-request ; : strawpoll-main ( -- ) command-line rest [ first ] [ rest ] bi "normal" poll boa >json "https://strawpoll.me/api/v2/polls" post-json nip json> id>> 10 base> "http://strawpoll.me/" prepend print ; ``` [Answer] # Ruby 2.2.4 + [HTTParty](https://github.com/jnunemaker/httparty): 129 bytes Anonymous function; returns a string with the strawpoll URL. Remember to install the HTTParty gem before running. ``` ->q,a{require'httparty';s="http%s://strawpoll.me/%s" s%[p,HTTParty.post(s%[?s,"api/v2/polls"],body:{title:q,options:a},verify:p)["id"]]} ``` If the URL can be returned with `https://` instead of `http://`, 126 bytes: ``` ->q,a{require'httparty';s="https://strawpoll.me/%s" s%HTTParty.post(s%"api/v2/polls",body:{title:q,options:a},verify:p)["id"]} ``` [Answer] # [Python](https://www.python.org), 145 bytes ``` lambda t,o:post('https://api.strawpoll.com/v3/polls',json={"title":t,"poll_options":[{"value":x}for x in o]}).json()["url"] from requests import* ``` A function which takes in a string for the title and *set* of strings for the options and returns the URL. I am not including an ATO/TIO link because you aren't able to do requests from those platforms. In the intervening years since this question was asked, the original strawpoll API has become defunct, so I'm using [the newer API](https://strawpoll.com/docs/api/), which is unfortunately more verbose. ]
[Question] [ [Accordion](http://en.wikipedia.org/wiki/Accordion_(solitaire)) is a solitaire card game I recently came across where nearly every layout is solvable, but incredibly hard. You can play it [here](http://www.solitairenetwork.com/solitaire/accordion-solitaire-game.html). ## Rules 52 face cards are placed face-up in a random order. **Each turn, you replace a card with a later card, where the two cards**: * **Share a suit or number** and * **Are at a distance of 1** (adjacent) **or 3** (two cards in between). **The game is won when there is only 1 card remaining**. You can assume that each input is solvable. The replaced card must always precede the replacing card. ## Example As an example, consider the following layout: ``` 2H,2S,1S,2D (H: Hearts, S: Spades, D: Diamonds) ``` There are 3 possible moves here: 1. Replace the `2H` with the adjacent `2S`, so we end up with `2S,1S,2D` 2. Replace the `2S` with the adjacent `1S`, so we end up with `2H,1S,2D` 3. Replace the `2H` with the `2D` (at a distance of 3), so we end up with `2D,2S,1S` Of those 3 moves, only the last one has the possibility of winning (You win by replacing `2D <- 2S`, then `2S <- 1S`). ## Input/Output **Your job is to write an Accordion solver**. You are passed a list of cards, and you need to return a list of moves to solve the game. You are passed a list of cards as a comma-delimited string, where each card is passed as an integer representing their numeric value, then a character representing their suit. You must return a list of replacements as a comma-delimited string, where each replacement is in the format `Card <- Card` (following the card format described above). The first card in each pair is the card being replaced. Test cases: ``` 5H,1C,12S,9C,9H,2C,12C,11H,10C,13S,3D,8H,1H,12H,4S,1D,7H,1S,13D,13C,7D,12D,6H,10H,4H,8S,3H,5D,2D,11C,10S,7S,4C,2H,3C,11S,13H,3S,6C,6S,4D,11D,8D,8C,6D,5C,7C,5S,9D,10D,2S,9S 5H,9C,11H,7S,7D,12D,6H,10S,3H,4D,12C,2S,3C,5C,7H,6S,1H,8S,2H,11S,4C,10D,12H,9H,2D,4H,6C,13H,11C,2C,10H,8C,1S,11D,3S,12S,7C,5D,13S,8D,4S,6D,13C,3D,8H,13D,1D,9D,9S,1C,5S,10C 7H,11C,8C,7S,10D,13H,4S,10C,4D,2C,4H,13D,3C,2H,12C,6C,9H,4C,12H,11H,9S,5H,8S,13S,8H,6D,2S,5D,11D,10S,1H,2D,5C,1C,1S,5S,3H,6S,7C,11S,9C,6H,8D,12S,1D,13C,9D,12D,3D,7D,10H,3S ``` While this competition is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), I am particularly interested in time-efficient solutions, and am likely to reward ingenious solutions with bounties. That said, solutions that take astronomical amounts of time are still acceptable (I'd recommend testing with a smaller deck, such as a 16-card, 4 suit deck). [Answer] # Python 3, ~~274~~ ~~272~~ 271 bytes *[2 bytes](http://chat.stackexchange.com/transcript/message/23682630#23682630) saved thanks to [@orlp](https://codegolf.stackexchange.com/users/4162/orlp).* ``` def g(p): q=lambda a:[[i,a]for i in range(len(p)-a)if p[i][:-1]==p[i+a][:-1]or p[i][-1]in p[i+a]] for n in q(1)+q(3): s=sum(n);c=p[:s]+p[s+1:];c[n[0]]=p[s] if g(c):return p[n[0]]+' <- '+p[s]+','+g(c) return' 'if len(p)<2else[] print(g(input().split(','))[:-2]or'') ``` This is extremely slow. However, you can try it with a [memoize](https://en.wikipedia.org/wiki/Memoization). This has a few extra `list`-`tuple` conversions, but is otherwise equivalent. ``` import functools @functools.lru_cache(maxsize=None) def g(p): q=lambda a:[[i,a]for i in range(len(p)-a)if p[i][:-1]==p[i+a][:-1]or p[i][-1]in p[i+a]] for n in q(1)+q(3): s=sum(n);c=list(p[:s]+p[s+1:]);c[n[0]]=p[s] if g(tuple(c)):return p[n[0]]+' <- '+p[s]+','+g(tuple(c)) return' 'if len(p)<2else[] print(g(tuple(input().split(',')))[:-2]or'') ``` Even this one is astronomically slow with certain inputs. The code uses strings, not numbers, so it also supports notation like `KH` instead of `13H`. Example: ``` $ python accordion.py 5H,9C,11H,7S,7D,12D,6H,10S,3H,4D,12C,2S,3C,5C,7H,6S,1H,8S,2H,11S,4C,10D,12H,9H,2D,4H,6C,13H,11C,2C,10H,8C,1S,11D,3S,12S,7C,5D,13S,8D,4S,6D,13C,3D,8H,13D,1D,9D,9S,1C,5S,10C 7S <- 7D,7D <- 12D,3C <- 5C,12H <- 9H,11C <- 2C,3S <- 12S,13D <- 1D,1D <- 9D,9D <- 9S,2S <- 6S,7H <- 1H,6S <- 8S,1H <- 2H,8S <- 11S,2H <- 9H,10D <- 2D,9H <- 4H,4H <- 4C,5C <- 4C,4D <- 4C,4C <- 12C,10S <- 11S,11H <- 11S,6H <- 3H,12D <- 2D,12C <- 2C,2C <- 6C,6C <- 8C,12S <- 13S,5D <- 6D,6D <- 8D,8D <- 3D,4S <- 9S,13S <- 9S,11D <- 3D,7C <- 1C,1S <- 1C,1C <- 13C,8C <- 13C,13C <- 13H,13H <- 10H,2D <- 3D,3D <- 3H,3H <- 8H,8H <- 10H,11S <- 5S,5H <- 10H,5S <- 9S,10H <- 10C,10C <- 9C,9C <- 9S ``` ]
[Question] [ **Cryptic Kicker** A common but insecure method of encrypting text is to permute the letters of the alphabet. In other words, each letter of the alphabet is consistently replaced in the text by some other letter. To ensure that the encryption is reversible, no two letters are replaced by the same letter. Your task is to decrypt several encoded lines of text, assuming that each line uses a different set of replacements, and that all words in the decrypted text are from a dictionary of known words. ***Input*** The input consists of lowercase words, in alphabetical order. These words compose the dictionary of words which may appear in the decrypted text. Following the dictionary are several lines of input. Each line is encrypted as described above. There are no more than 1,000 words in the dictionary. No word exceeds 16 letters. The encrypted lines contain only lower case letters and spaces and do not exceed 80 characters in length. ***Output*** Decrypt each line and print it to standard output. If there are multiple solutions, any one will do. If there is no solution, replace every letter of the alphabet by an asterisk. ***Sample Input*** ``` and dick jane puff spot yertle bjvg xsb hxsn xsb qymm xsb rqat xsb pnetfn xxxx yyy zzzz www yyyy aaa bbbb ccc dddddd ``` ***Sample Output*** ``` dick and jane and puff and spot and yertle **** *** **** *** **** *** **** *** ****** ``` [Here](https://gist.github.com/dhruvramani/24735efb31c7e768abe4)'s the solution. Please note that I am not a horse running in the race for the shortest bytes **/** Competitive programmer. I just like puzzles! ([Source](http://rads.stackoverflow.com/amzn/click/0387001638)) [Answer] # Python 3, 423 bytes ``` import sys,re S=re.sub D,*L=sys.stdin.read().split('\n') def f(W,M=[],V="",r=0): if len({d for(s,d)in M})==len(M): if[]==W:return V.lower() for d in D.split():p='([a-z])(?%s.*\\1)';m=re.match(S(p%'=',')\\1=P?(',S(p%'!',').>\\1<P?(',W[0].translate(dict(M))[::-1]))[::-1]+'$',d.upper());r=r or m and f(W[1:],M+[(ord(s),m.group(s))for s in m.groupdict()],V+d+" ") return r for l in L:print(f(l.split())or S('\w','*',l)) ``` Reads input from STDIN and writes output to STDOUT, using the same format as the sample input/output. ## Explanation For each line of ciphertext, we perform the following procedure: We keep a map, *M*, of all the letter transformations we've already established (which is initially empty). We do it in such a way that the source letters are all lowercase and the destination letters are all uppercase. We process the words in the ciphertext in order. For each word, we find all the words in the dictionary it might match, as follows: Suppose that our word, *w*, is `glpplppljjl` and that *M* contain the rule `j -> P`. We first transform *w* using the existing rules in *M*, getting `glpplpplPPl`. We then transform *w* into the following python-flavored regex: ``` (?P<g>.)(?P<l>.)(?P<p>.)(?P=p)(?P=l)(?P=p)(?P=p)(?P=l)PP(?P=l) ``` The rules of the transformation are as follows: * The first occurrence of each lowercase letter, *`x`*, is replaced with `(?P<`*`x`*`>.)`. This defines a named capture group, called *`x`*, that matches a single cahracter. * Every subsequent occurrence each lowercase letter, *`x`*, is replaced with `(?P=`*`x`*`)`. This is a backreference to the character previsouly captured by the named group *`x`*. We perform this transformation by reversing *w*, then applying the two following regex substitutions: ``` s/([a-z])(?!.*\1)/)>\1<P?(/ s/([a-z])(?=.*\1)/)\1=P?(/ ``` and then reversing the result. Note that the characters previously transformed by *M* appear as uppercase, and therefore remain unchanged. We match the resulting regex against each of the dictionary words, where the dictionary words appear as uppercase. For example, the above regex would match the word `MISSISSIPPI`. If we find a match, we extract the new transformation rules from it, and add them to *M*. The new transformation rules are simply the characters captured by each of the capture groups. In the above regex, the group `g` matches `M`, the group `l` match `I`, and the group `p` matches `S`, giving us the rules `g -> M, l -> I, p -> S`. We have to make sure that the resulting rules are consistent, that is, that no two source letters map to the same destination letter; otherwise, we reject the match. We then proceed to the next word, using the augmented transformation rules. If we can match all the ciphertext words using this process, we have decrypted the text. If we can't match a word against any of the dictionary words, we backtrack and try to match the previous words against different dictionary words. If this process fails, there is no solution, and we print a row of asterisks. [Answer] # CJam, ~~62~~ 56 bytes ``` qN%Sf/(f{\:C,m*{C..+`Sa`m2/Q|z_''f-Qf|=},C:,'*f*a+0=S*N} ``` Quite slow and memory hungry, but works for the test case with the Java interpreter. ### Example run ``` $ cat input; echo and dick jane puff spot yertle bjvg xsb hxsn xsb qymm xsb rqat xsb pnetfn xxxx yyy zzzz www yyyy aaa bbbb ccc dddddd $ time cjam kicker.cjam < input dick and jane and puff and spot and yertle **** *** **** *** **** *** **** *** ****** real 5m19.817s user 6m41.740s sys 0m1.611s ``` ]
[Question] [ Circles and squares have a single, definite center point. However, the notion of the center of a triangle has long been discussed. Four different centers were known to the Ancient Greeks: * [Incenter](http://mathworld.wolfram.com/Incenter.html): The intersection of the angle bisectors of the triangle * [Centroid](http://mathworld.wolfram.com/TriangleCentroid.html): The intersection of the lines from each vertex of the triangle to the middle of its opposite side * [Circumcenter](http://mathworld.wolfram.com/Circumcenter.html): The intersection of the perpendicular bisectors of the sides * [Orthocenter](http://mathworld.wolfram.com/Orthocenter.html): The intersection of the altitudes of the triangle Euler later proved that the centroid, circumcenter and orthocenter are collinear in any triangle. The line that these three points are on in a triangle is called the [Euler Line](http://mathworld.wolfram.com/EulerLine.html). It is defined for every triangle except an equilateral triangle, where all the points coincide. Your challenge is to create the shortest program or function that, when given two inputs, outputs a specific center or the Euler Line of the triangle. The first specifies the coordinates of each vertex of a triangle. The second is an integer from 1 to 5, determining what to output. ``` 1 - Incenter 2 - Centroid 3 - Circumcenter 4 - Orthocenter 5 - Equation of Euler Line (if the Euler Line is vertical, output the `x` value of the line (e.g. output `5` if the equation of the line is `x = 5`)) ``` You may assume that the given vertices will never be collinear, and that they will always be integer coordinates (this also excludes the possibility of having an equilateral triangle as an input, as per [@R.Kap's comment](https://codegolf.stackexchange.com/questions/11767/the-centers-of-a-triangle/80471#comment197551_11767)). The input array should be a valid nested array in your language, and input should be in any reasonable format. Any float values should be displayed to at least 3 decimal places, but no less. An outputted point should be a valid array in your language, matching with the input format. --- Test cases: ``` Input: [(-2, 0), (1, 0), (0, 1)] 1 Output: (-0.089, 0.451) Input: [(-2, 0), (1, 0), (0, 1)] 2 Output: (-0.333, 0.333) Input: [(-2, 0), (1, 0), (0, 1)] 3 Output: (-0.5, -0.5) Input: [(-2, 0), (1, 0), (0, 1)] 4 Output: (0, 2) Input: [(-2, 0), (1, 0), (0, 1)] 5 Output: 5x + 2 ``` --- **Clarification:** The input can either be from stdin, either space or new-line separated, or as the arguments to a function. The output, however, must be written to stdout. [Answer] ## AutoHotkey - 731 ``` f(z, r:=1){ static 1:="i",2:="m",3:="c",4:="o" r := %r%,mx :=(z.1.1+z.2.1+z.3.1)/3,my:=(z.1.2+z.2.2+z.3.2)/3 s:=(c:=sqrt((z.2.1-z.1.1)**2+(z.2.2-z.1.2)**2))+(a:=sqrt((z.3.1-z.2.1)**2+(z.3.2-z.2.2)**2))+(b:=sqrt((z.3.1-z.1.1)**2+(z.3.2-z.1.2)**2)) ix:=(a*z.1.1+b*z.2.1+c*z.3.1)/s,iy:=(a*z.1.2+b*z.2.2+c*z.3.2)/s midx_a:=(z.3.1+z.2.1)/2,midy_a:=(z.3.2+z.2.2)/2,m:=-1*(z.3.1-z.2.1)/(z.3.2-z.2.2),cc_a:=midy_a-(m*midx_a) midx_b:=(z.3.1+z.1.1)/2,midy_b:=(z.3.2+z.1.2)/2,n:=-1*(z.3.1-z.1.1)/(z.3.2-z.1.2),cc_b:=midy_b-(n*midx_b) cx:=(cc_b-cc_a)/(m-n),cy:=cc_a+(m*cx),oc_a:=z.1.2-(m*z.1.1),oc_b:=z.2.2-(n*z.2.1),ox:=(oc_a-oc_b)/(n-m),oy:=oc_a+(m*ox) if r in m,i,c,o return [%r%x, %r%y] else return "y=" (m:=(oy-cy)/(ox-cx)) "x+" oy-m*ox } ``` The function can be more minified (to about 600 chars OR less) by shortening the variable names like midx\_a, midx\_b and so. ### Calling the function ``` d:=f([[-2, 0], [1, 0], [0, 1]], 1) for k,v in d msgbox % k "`n" v ``` [Answer] # Python - 908 870 Newlines were added to reduce scrolling. This could probably be golfed further. ``` from math import*;t=eval(input());p=int(input())-1; r=[];A,B,C=t[0],t[1],t[2]; a,b,c=hypot(B[0]-C[0],B[1]-C[1]),hypot(A[0]-C[0],A[1]-C[1]),hypot(A[0]-B[0],A[1]-B[1]); r.append(((a*A[0]+b*B[0]+c*C[0])/(a+b+c),(a*A[1]+b*B[1]+c*C[1])/(a+b+c))); r.append(((A[0]+B[0]+C[0])/3,(A[1]+B[1]+C[1])/3));d,e,f=(0,0),(B[0]-A[0],B[1]-A[1]),(C[0]-A[0],C[1]-A[1]);g=2*(e[0]*f[1]-e[1]*f[0]); r.append(((f[1]*(e[0]**2+e[1]**2)-e[1]*(f[0]**2+f[1]**2))/g+A[0],(e[0]*(f[0]**2+f[1]**2)- f[0]*(e[0]**2+e[1]**2))/g+A[1])); h=acos((b*b+c*c-a*a)/(2*b*c));i=acos((a*a+c*c-b*b)/(2*a*c));j=acos((a*a+b*b- c*c)/(2*a*b));k=cos(i)*cos(j); l=cos(h)*cos(j);m=cos(h)*cos(i);r.append(((a*k*A[0]+b*l*B[0]+c*m*C[0])/(a*k+b*l+c*m),(a*k*A[1]+b*l*B[1]+c*m*C[1])/(a*k+b*l+c*m))); n,o=r[1][0]-r[2][0],r[1][1]-r[2][1];q=r[1][1]-o/n*r[1][0]if n!=0 else 0; r.append(r[1]if a==b==c else("x="+str(r[1][0])if n==0 else"".join([str(o/n),"x+(",str(q),")"])));print(r[p]) ``` Test cases (annotated): ``` Input: [(-2, 0), (1, 0), (0, 1)] 1 Output: (-0.08907279243665268, 0.45110872103880023) --> More digits than in question Input: [(-2, 0), (1, 0), (0, 1)] 2 Output: (-0.3333333333333333, 0.3333333333333333) --> More digits than in question Input: [(-2, 0), (1, 0), (0, 1)] 3 Output: (-0.5, -0.5) Input: [(-2, 0), (1, 0), (0, 1)] 4 Output: (-1.1702778228588997e-16, 1.9999999999999984) --> More digits than shown in question Input: [(-2, 0), (1, 0), (0, 1)] 5 Output: 4.999999999999999x+(1.9999999999999996) --> More digits than in question ``` As you can see, there are possibly errors caused by using floating point. --- **Further golfing:** Based on suggestions in the comments below, I've managed to make this smaller. ``` from math import*;I=input;t=eval(I());p=int(I())-1;r=[];A,B,C=t[0],t[1],t[2];R,H,D,S,T=r.append,hypot,cos,acos,str;a,b,c=H(B[0]-C[0],B[1]-C[1]),H(A[0]-C[0],A[1]-C[1]),H(A[0]-B[0],A[1]-B[1]);R(((a*A[0]+b*B[0]+c*C[0])/(a+b+c),(a*A[1]+b*B[1]+c*C[1])/(a+b+c)));R(((A[0]+B[0]+C[0])/3,(A[1]+B[1]+C[1])/3));d,e,f=(0,0),(B[0]-A[0],B[1]-A[1]),(C[0]-A[0],C[1]-A[1]);g=2*(e[0]*f[1]-e[1]*f[0]);R(((f[1]*(e[0]**2+e[1]**2)-e[1]*(f[0]**2+f[1]**2))/g+A[0],(e[0]*(f[0]**2+f[1]**2)-f[0]*(e[0]**2+e[1]**2))/g+A[1]));h=S((b*b+c*c-a*a)/(2*b*c));i=S((a*a+c*c-b*b)/(2*a*c));j=S((a*a+b*b-c*c)/(2*a*b));k=D(i)*D(j);l=D(h)*D(j);m=D(h)*D(i);R(((a*k*A[0]+b*l*B[0]+c*m*C[0])/(a*k+b*l+c*m),(a*k*A[1]+b*l*B[1]+c*m*C[1])/(a*k+b*l+c*m)));n,o=r[1][0]-r[2][0],r[1][1]-r[2][1];q=r[1][1]-o/n*r[1][0]if n!=0else 0;R(r[1]if a==b==c else("x="+T(r[1][0])if n==0else"".join([T(o/n),"x+(",T(q),")"])));print(r[p]) ``` [Answer] # Python 3.5, ~~851~~ 772 bytes: ``` def H(z,a,b,l):c=complex;T=lambda A,B:abs(c(*A)-c(*B));d=T(z,a);e=T(z,b);f=T(a,b);g=[((a[0]+b[0])/2,(a[1]+b[1])/2)for a,b in[[a,b],[z,a],[b,z]]];E=(z[0]+a[0]+b[0])/3;F=(z[1]+a[1]+b[1])/3;m=lambda f:[(a,0)if(b[1][0]-b[0][0])==0else(a,-1/((b[1][1]-b[0][1])/(b[1][0]-b[0][0])))if(b[1][1]-b[0][1])else''for a,b in zip(f,[[a,b],[z,a],[b,z]])];i=[u for u in m(g)if u!=''];C=i[0][1];D=i[0][0][1]-(C*i[0][0][0]);A=i[1][1];B=i[1][0][1]-(A*i[1][0][0]);G=(B-D)/(C-A);H=C*G+D;j=[u for u in m([z,b,a])if u!=''];C=j[0][1];D=j[0][0][1]-(C*j[0][0][0]);A=j[1][1];B=j[1][0][1]-(A*j[1][0][0]);I=(B-D)/(C-A);J=C*I+D;K,L=[((d*b[o])+(e*a[o])+(f*z[o]))/sum([d,e,f])for o in[0,1]];a=(H-J)/(G-I)if(G-I)else'';b=H-(a*G)if a!=''else G;print(['',(K,L),(E,F),(G,H),(I,J),[b,'%sx+%s'%(a,b)][a!='']][l]) ``` Takes **input** as a sequence of comma separated coordinates followed by an integer conveying what to output. For instance, if the input coordinates are `(1,0),(2,1),(1,4)` and you want the orthocenter of the triangle corresponding to those coordinates you would simply call the function like so: ``` H((1,0),(2,1),(1,4),4) ``` **Outputs** in the format of a tuple if a specific point is needed, in the format of a string with the equation in the form `y=mx+b` if the Euler line is needed and the line is *not* vertical, or simply the `x` value of the line if the Euler line is needed but the line *is* vertical. So, using the triangle with vertices `(1,0),(2,1),(1,4)`, the outputs would be: ``` 1. Incenter: (1.4663911961440428, 1.125967951102358) 2. Centroid: (1.3333333333333333, 1.6666666666666667) 3. Circumcenter: (0.0, 2.0) 4. Orthocenter: (4.0, 1.0) 5. Euler Line: -0.25x+2.0 ``` I will try to golf this more over time where and when I can. [Try It Online! (Ideone)](http://ideone.com/YSqzyR) ]
[Question] [ Write a program to take a graph (from either standard input or a file, your choice) and find a shortest path in the graph. Graphs are specified using the following format: ``` A---S F--T | / \ | | / 5 0 |/ \| D----3--E A-Z: nodes in the graph -|/\: edges in the graph 0-9: weights on the edges <space>: all the holes ``` All edges are undirected and lie along one of the 8 cardinal directions (i.e., no bends). Edges may optionally contain a weight from 0 to 9. The weight will not be on the last symbol that connects the edge to a node (i.e. edges need to have at least 3 symbols to contain a weight). Unweighted edges have a default weight of 1. Your code should compute the shortest path between nodes `S` and `T` and print the length and the path, like this: ``` 5:SDEFT ``` Shortest correct program wins. [Answer] Here's my code, 494 characters in python: ``` import sys,re m=sys.stdin.readlines() Z=lambda c,s:re.findall(r'(\w)%s+(\d*)[^\w]*(\w)'%c,''.join(x*2for x in s)) T=lambda n:''.join(x for a in map(None,*n)for x in a if x) E=Z('-',''.join(m))+Z('\\|',T(m))+Z('/',T(' '*m.index(s)+s for s in m))+Z('\\\\',T(' '*m[::-1].index(s)+s for s in m)) E+=[x[::-1]for x in E] S={} for x in E:S[x[0]]=1e9 S['S']=0 P={} for i in E: for x,w,y in E: w=int('1'+w)%10 if S[y]>S[x]+w:S[y]=S[x]+w;P[y]=x i=p='T' while i!='S':i=P[i];p=i+p print'%d:'%S['T']+p ``` ]
[Question] [ A *sentence* of number theory (for our purposes) is a sequence of the following symbols: * `0` and `'` (successor) - successor means `+1`, so `0'''' = 0 + 1 + 1 + 1 + 1 = 4` * `+` (addition) and `*` (multiplication) * `=` (equal to) * `(` and `)` (parentheses) * the logical operator [`nand`](https://en.wikipedia.org/wiki/Sheffer_stroke) (`a nand b` is `not (a and b)`) * `forall` (the universal quantifier) * `v0`, `v1`, `v2`, etc. (variables) Here is an example of a sentence: ``` forall v1 (forall v2 (forall v3 (not (v1*v1*v1 + v2*v2*v2 = v3*v3*v3)))) ``` Here `not x` is shorthand for `x nand x` -- the actual sentence would use `(v1*v1*v1 + v2*v2*v2 = v3*v3*v3) nand (v1*v1*v1 + v2*v2*v2 = v3*v3*v3)`, because `x nand x = not (x and x) = not x`. This states that for every combination of three natural numbers `v1`, `v2`, and `v3`, it is not the case that v13 + v23 = v33 (which would be true because of Fermat's Last Theorem, except for the fact that it would get 0^3+0^3=0^3). Unfortunately, as proved by Gödel, it is not possible to determine whether or not a sentence in number theory is true. It *is* possible, however, if we restrict the set of natural numbers to a finite set. So, this challenge is to determine whether or not a sentence of number theory is true, when taken [modulo](https://en.wikipedia.org/wiki/Modular_arithmetic) `n`, for some positive integer `n`. For example, the sentence ``` forall v0 (v0 * v0 * v0 = v0) ``` (the statement that for all numbers x, x3 = x) Is not true for ordinary arithmetic (e.g. 23 = 8 ≠ 2), but *is* true when taken modulo 3: ``` 0 * 0 * 0 ≡ 0 (mod 3) 1 * 1 * 1 ≡ 1 (mod 3) 2 * 2 * 2 ≡ 8 ≡ 2 (mod 3) ``` ### Input and output format The input is a sentence and positive integer `n` in any "reasonable" format. Here are some example of reasonable formats for the sentence `forall v0 (v0 * v0 * v0 = v0)` in number theory modulo 3: ``` ("forall v0 (v0 * v0 * v0 = v0)", 3) "3:forall v0 (((v0 * v0) * v0) = v0)" "(forall v0)(((v0 * v0) * v0) = v0) mod 3" [3, "forall", "v0", "(", "(", "(", "v0", "*", "v0", ")", "*", "v0", ")", "=", "v0", ")"] (3, [8, 9, 5, 5, 5, 9, 3, 9, 6, 3, 9, 6, 4, 9, 6]) (the sentence above, but with each symbol replaced with a unique number) "f v0 = * * v0 v0 v0 v0" [3, ["forall", "v0", ["=", ["*", "v0", ["*", "v0", "v0"]], "v0"]]] "3.v0((v0 * (v0 * v0)) = v0)" ``` Input can be from stdin, a command line argument, a file, etc. The program can have any two distinct outputs for whether the sentence is true or not, e.g. it could output `yes` if it's true and `no` if it's not. You do not need to support one variable being the subject of a `forall` twice, e.g. `(forall v0 (v0 = 0)) nand (forall v0 (v0 = 0))`. You can assume that your input has valid syntax. ### Test cases ``` forall v0 (v0 * v0 * v0 = v0) mod 3 true forall v0 (v0 * v0 * v0 = v0) mod 4 false (2 * 2 * 2 = 8 ≡ 0 mod 4) forall v0 (v0 = 0) mod 1 true (all numbers are 0 modulo 1) 0 = 0 mod 8 true 0''' = 0 mod 3 true 0''' = 0 mod 4 false forall v0 (v0' = v0') mod 1428374 true forall v0 (v0 = 0) nand forall v1 (v1 = 0) mod 2 true (this is False nand False, which is true) forall v0 ((v0 = 0 nand v0 = 0) nand ((forall v1 (v0 * v1 = 0' nand v0 * v1 = 0') nand forall v2 (v0 * v2 = 0' nand v0 * v2 = 0')) nand (forall v3 (v0 * v3 = 0' nand v0 * v3 = 0') nand forall v4 (v0 * v4 = 0' nand v0 * v4 = 0')))) mod 7 true (equivalent to "forall v0 (v0 =/= 0 implies exists v1 (v0 * v1 = 0)), which states that every number has a multiplicative inverse modulo n, which is only true if n is 1 or prime) forall v0 ((v0 = 0 nand v0 = 0) nand ((forall v1 (v0 * v1 = 0' nand v0 * v1 = 0') nand forall v2 (v0 * v2 = 0' nand v0 * v2 = 0')) nand (forall v3 (v0 * v3 = 0' nand v0 * v3 = 0') nand forall v4 (v0 * v4 = 0' nand v0 * v4 = 0')))) mod 4 false ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to make your program as short as possible! [Answer] # [Python 2](https://docs.python.org/2/), ~~252~~ 236 bytes ``` def g(n,s): if str(s)==s:return s.replace("'","+1") o,l,r=map(g,[n]*3,s);return['all((%s)for %s in range(%d))'%(r,l,n),'not((%s)*(%s))'%(l,r),'(%s)%%%d==(%s)%%%d'%(l,n,r,n),'(%s)%s(%s)'%(l,o,r)]['fn=+'.find(o)] print eval(g(*input())) ``` [Try it online!](https://tio.run/##7ZLLbsMgEEX3/ooREgIcFNUPKWkqvsRiYcXYteRiC5yo/XoXkzhx27CquutmgDv3Hh5i@Bhfe51Ox75SIAAhNFWqhoZqbtkhgrYGOxpqmRD2YNR4Mhrs1qihK4@KIoI42iSIRdDzjhvxVg604YWWcebyL5dAQcquoxRbVvcGsIVWgyl1oyiuGCOYGpfVjBPdj94Wz2VuOKST5xXGuBJimfmW5sanvGjn6uXeZWRBai02ZFu3uqI9k9FgWj2COpcdbWjc6uE0UsbY5C4cRepdHcG/QAzPU8ahQDXigM5PaJ4LX@OVcp/PVcpljPJfZJNH2avTG/Y3cdGi7C4RQhY1f6gmebrPdnlgF7IMbqPd1eMtBdK3Iq7azPu2lF@MPpysc/7iF7drSJchC@NhywM9Jg1h0jAmvWPklzNlIVgWhmU/z5SHMHkYk6/OJFd/5f@V//CVPwE "Python 2 – Try It Online") Takes input as the nested prefix-syntax, with `f` instead of `forall` and `n` instead of `nand`: ``` [3, ["f", "v0", ["=", ["*", "v0", ["*", "v0", "v0"]], "v0"]]] ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 129 bytesSBCS ``` {x y z←3↑⍵⋄7≤x:y×7<x⋄5≡x:∧/∇¨y{⍵≡⍺⍺:⍵⍺⋄x y z←3↑⍵⋄7≤x:⍵⋄6≡x:x(⍺∇y)⋄x(⍺∇⍣(5≢x)⊢y)(⍺∇z)}∘z¨⍳⍺⍺⋄y←∇y⋄6≡x:1+y⋄y(⍎x⊃'+×⍲',⊂'0=⍺⍺|-')∇z} ``` [Try it online!](https://tio.run/##7VTLbtNAFN37K@7OHkpF5wGJIrJiQ1dIlB8wjYuQnLjUqWWndANVm6RyBIuqbLpoQaI7JBAblumfzI@Eedl1/AhdILFBiq/ncc65d84dx93113uJ6wevFouDGBIY8eMPlB9/5OlPfnrU4pMvcSe5OW89jsX0IZ9cxh0@/vqAj0/m18mBRE0uefpL/DpyIkanR006evxIicSOxI5PEiQJZsLTz47IcRUjPr1KkFkdoUM@/jSaX/P0h04lKInQl/RcEK/JcSI4s5hP39trN@c8/W7f59N39kZX896u20gKHi68yPWlQjrjs7PNZ4Iw/6bKnZ1tPX8i4ounm1uLXX8/hOHrvhfCwB30wHsDO8Ge6/sQ7m9vw8jbCyDagAhDRCCiEDEQoiDqxMSyeHqRwQXIEc89yEJXBAT9oAfUoiCrKUJFHkenNS@ZRODNc1dpZrG/Id0Fo4ctXKcnXtIJw1V4BW9bbQ0XGGWVDAZk23aOyx2QtSlji1FJI9REzs94R/LS0Wxllm1Ox0ibtpiFSX1DlKC0KR81u6VuS7aOxTq@dZFYROsrkFPvJbrdwHoDm41KTpNUyy0V4BQ19PVQddg5Nl8plUwyPKng9QpCpfJpxqAVBq3LwDI8q@CZyYC0Xy2rVemHzq1jwbWyhUVYwYqcV/gEMFq6Mn/YLvaH1AuS1YKkLIjKhdJ6XbpalzYXyuoF2WpBVik0u4Oh2/cgHLpDr@8NhuC@DCKv8X/nf8f@acd@Aw "APL (Dyalog Unicode) – Try It Online") Takes a prefix syntax tree as in [TFeld's python answer](https://codegolf.stackexchange.com/a/190051/78410), but using an integer encoding. The encoding is ``` plus times nand eq forall succ zero ← 1 2 3 4 5 6 7 ``` and each variable is assigned a number starting from 8. This encoding is slightly different from the one used in the ungolfed version below, because I tweaked it while golfing the code. The task involves only two inputs (the AST and the modulo), but writing it as an operator instead of a function avoids mentioning the modulo many times (as it is always carried over recursive calls). ### Ungolfed with comments ``` ⍝ node types; anything ≥8 will be considered a var plus times eq nand forall succ zero var←⍳8 ⍝ AST nodes have 1~3 length, 1st being the node type ⍝ zero → zero, succ → succ arg, var → var | var value (respectively) ⍝ to (from replace) AST → transform AST so that 'from' var has the value 'to' attached replace←{ ⍵≡⍺⍺:⍵⍺ ⍝ variable found, attach the value x y z←3↑⍵ zero≤x: ⍵ ⍝ zero or different variable: keep as is succ≡x: x(⍺∇y) ⍝ succ: propagate to y forall≡x: x y(⍺∇z) ⍝ forall: propagate to z x(⍺∇y)(⍺∇z) ⍝ plus, times, eq, nand: propagate to both args } ⍝ (mod eval) AST → evaluate AST with the given modulo eval←{ x y z←3↑⍵ zero≡x: 0 var≤x: y ⍝ return attached value forall≡x: ∧/∇¨y replace∘z¨⍳⍺⍺ ⍝ check all replacements for given var succ≡x: 1+∇y plus≡x: (∇y)+∇z times≡x: (∇y)×∇z eq≡x: 0=⍺⍺|(∇y)-∇z ⍝ modulo equality nand≡x: (∇y)⍲∇z ⍝ nand symbol does nand operation } ``` [Try it online!](https://tio.run/##7VbNbtRIEL77Kepme3cQ8Y@U2aAcEBc4IW14gZ5xz4wVj9u4e0w8C1yQsgnSRICE4MIBaVeb20q72gvH8CZ@kVDV3eN4fhI4rMQFK9O2u@r7qvqr6nZYkd1KapaJ8eVlkc0kqHTKJfDHkLM8gZEoWZaBnA2HMOelgIqVzfGrZvFvH6BZfIBcJBxUXXB5B1heq0maj6E5/bMPT1IEDjgMRS7ThJc8AUZwh2B3Dx5pqIQJqzgEzyPIeD5Wkx4EUiGMaNSEX/FrmE6hOX6jH3omLXrVD6wc9yiAnqH7Uz1WLJtx8EouCz5UacWz2nc0mxLgjUoxhZIXGRtyX6dFaFWyXOLap3pGCkyFKXDJ2dWkEyZ1eobcVcIFphQbTnjiWDaU6TeHRPqvOf3YLD7h3x69LD5B96JEkDFlg4yj3LM86VmqqwBIcwQ1zJEyao5fIwvOkATN6R9HexRijVDrJEpI0tEIlc9VG2IPDjkvANNPJZKQcJgekhx5lOPJ77V/RUPWPShKUbAxU5wEqxFkmsLCoLbAuW9AxroGm9MS2ggdRCdpar@e6b8eNmBPd@Aaz0CoCRVaOs8cjtqQyAbtTUUCNKWreINilDXADr5TL2sB8aphy0W8JVezMm@r2xakK0Jz8tdtXM/Feb1spebk/fziHLeJKbyhQvzwEGg/Wa8pVkYSE4yxL3O9O7o1AQh@JsFwksRZTnpaRLKQrFowazKWz@@siT9eQnDB@yaVp8bnFrmsLBT1m2UCMTOWpYpikv6rMZvFPyu4FqwPC1lPByKDROC21hOi4CVTqcidZ5foNdInx1lz9vbBw@bli4u/dWnO3h78eg/HR/cfHFxWO1AFUIVQRVDFuBdfQR9@gWAHggCC0Oxbeyihr4e/n2A57OPg0zogciLdC11XPNI8c7jZG8VCf/v7VurYif8P6n2wfIETbOPDG7WrxWp/7d53@sYdffQup8E6ua7b@rUKUG76eOyOmtr3rwO3a/xG8MrSXC2Wa1cXh/1oN3aCcHtBNCHJ1D5dr1b3g4RN4uGvVTF0QsOvnbztWvpXhsAYAmvYiGmDGrqVBLwuh2kPnYfb@rYzaymHS/9ww9/M@P5a@tESEW0gom0R4qV/vOEf2wi@0WvX2d2oh4ltxo5q6xJ23TpStLjOFgj8lZb5irlbn3A7YXgzYbhO6K8nGm3njW7mja5PNN5OGN9MGG8kuuxByaYcpMLPHX0cgA0E/nt03bnzo2LftWJfAA "APL (Dyalog Unicode) – Try It Online") ]
[Question] [ > > Pancake sorting is the colloquial term for the mathematical problem of > sorting a disordered stack of pancakes in order of size when a spatula > can be inserted at any point in the stack and used to flip all > pancakes above it. A pancake number **P(n)** is the minimum number of > flips required for **n** pancakes. [1](https://en.wikipedia.org/wiki/Pancake_sorting) > > > In 1979, a young Bill Gates and Christos Papadimitriou, wrote a paper proving an upper bound of **P(n) = (5n+5)/3**. [2](https://people.eecs.berkeley.edu/%7Echristos/papers/Bounds%20For%20Sorting%20By%20Prefix%20Reversal.pdf) I think it's safe to assume that Gates (and/or Papadimitriou) wrote a program to perform pancake sorting using the algorithm they developed (possibly later than 1979). Since Gates was a skilled programmer, they probably tried to golf this code as well as they could, but the size of the source code is not publicly available (AFAIK). ### Challenge: Create a function / program that performs pancake sorting, where the maximum number of flips doesn't exceed the bound found by Gates and Papadimitriou.3 You may choose if you want the list ascending or descending, as long as it's consistent. You may assume that **n < 50**. You must therefore limit the number of flips to (some randomly selected **n**-values): ``` n P(n) 38 65 49 83 50 85 ``` The output should be the position of the spatula before each flip. The output may be zero or one-indexed, and you may choose if you count from the top or bottom. ### Additional rules: * The runtime must be deterministic * There is no fixed time limit, but you must be able to provide the output for a list with 50 elements ### Test lists: I can't provide the hardest lists (if so, I would write a paper, not a challenge), so I'll provide some random lists of numbers you can test your functions/programs on. I might add others if it turns out these lists where "easy". ``` 9, 63, 62, 75, 45, 78, 59, 75, 69, 3, 28, 94, 51, 10, 45, 93, 97, 80, 72, 36, 80, 88, 30, 93, 84, 80, 17, 31, 6, 80, 76, 91, 9, 76, 38, 33, 22, 15, 45, 46, 15, 98, 2, 56, 90, 27, 27, 26, 69, 25 ... 74, 89, 57, 52, 70, 96, 16, 5, 77, 84, 54, 13, 90, 64, 31, 80, 3, 25, 13, 19, 13, 34, 1, 79, 35, 43, 4, 19, 82, 29, 48, 95, 97, 28, 45, 62, 64, 82, 70, 34, 38, 15, 51, 83, 21, 66, 4, 42, 74, 84 ... 62, 73, 7, 90, 83, 18, 12, 35, 72, 71, 99, 67, 87, 62, 65, 70, 14, 72, 55, 92, 87, 3, 7, 4, 4, 95, 49, 25, 4, 18, 49, 39, 26, 1, 45, 64, 23, 66, 39, 17, 33, 24, 58, 72, 77, 46, 99, 71, 10, 21 ``` --- Hopefully, Bill Gates and Papadimitriou will see this challenge, and provide their code, so that we can determine if you did in fact outgolf them. 3Better upper bounds have been found, but you do not need to care about those. [Answer] # [Python 2 (PyPy)](http://pypy.org/), ~~238~~ ~~235~~ 222 bytes ``` a=input();n=len(a);r=range(n);a=zip(a,r);a=map(sorted(a).index,a)+[n] def s(u,m): if m<1:return[0] for k in r: v=u[k::-1]+u[k+1:] if sum(1<abs(v[i]-v[i+1])for i in r)<m: p=s(v,m-1) if p:return[k]+p print s(a,5*n/3) ``` \*(2 spaces = tab) [Try it online!](https://tio.run/##NY5LcsMgEETX1ilmCRFKjP7I1klULEhZTihHmEKSK87lnVZwFgM9Pf1g/H35vLo883d/fzxMb51fF8YPrv8aHTP8EPpg3MfIHD@Y/sd6ZkTY5GQ8m69hGU9IvVp3Gr@F4engdHIazzSzVUy8S8ieaTrKLozLGtyw1wmdr4EuZB2FLtnd@nW4dF0mdQqRyk4nOyDzOjF5NO8zuw1WZzhSqflG2j@SHyfA5HsExJRJjgaY///nolOf@GDdgk2MqF7cW8Efj0EJqgtULqipBJWophVUqdjXuDHOYakSthQk9zGm4KtGUIu@AV7UUbfIFvs4b8voSeQKsM9Ig1uhVVEWG7H9glfkc4myjlphBrvaCJB586w67pZX@hc) Saved 13 bytes borrowing a method for [ranking a list](https://codegolf.stackexchange.com/a/85872/6710). DFS with a simple heuristic that checks whether a flip separates a pair of "pancakes" that would be adjacent when sorted. Sorts it in ascending order. Output is 0-indexed from the left where 0 flips the first 2 and so on. The number of moves used is `(5/3)*n+1 < 5/3*(n+1)` where `(18/11)*n < (5/3)*n+1 < 5/3*(n+1)` and `(18/11)*n` is a tighter upper bound found in [2009](https://www.sciencedirect.com/science/article/pii/S0304397508003575). ]
[Question] [ # Background Minifiers are used, commonly, when serving JavaScript to your Web Browser. It is commonly used to reduce the number of bytes that have to be sent. Saving bandwidth is useful for obvious reasons. Some people use obfuscaters (that intentionally make code harder to read), I am not talking about those. # We will be minifying Python 2 I was debating on whether or not use JavaScript or Python for the minifying experience and I decided on Python for two reasons: white space matters and I think that will add an interesting dynamic the problem. Additionally, using Python 2.7 will provide another dynamic, such as remove superfluous `()` during a print (i.e. `print("Hello world")` vs. `print"Hello world"`). I would have, personally, preferred to open it up to any language, but for some languages this process won't make a lot of sense for. And, what language you decide to minify will directly impact your score (and if the language even can be minified). # Specs Your goal is to only modify the code in a way that will not change it's functionality in anyway. You may, of course, change variable names (inside your minifying program) as long as it doesn't effect output (keep track of **scope**). Although I am giving you a specific program, please don't optimize for the test case as all [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. **Score**: length of the program after you minified it. **Input**: Any Python 2.7 program (that contains no errors) **Output**: A minified version. Although your code should be able to accomodate all valid Python 2.7 input, it is necessary to test your script against something in order to prove it's effectiveness. [Click here](https://pastebin.com/TWt6s01u) to view the example program. # Making the problem more approachable Feel free to use or modify any code found inside my solution (listed bellow). I did this to get you started with quote basic quote handling; however, you can expand it to indentation, and etc. # Example ways to minify Python All white space could be replaced with the minimum possible amount (I acknowledge that in Python you can do some [tricky stuff with tabs](https://tio.run/##K6gsycjPM/r/PyU1TaGgKDOvJD4xvigxLz1VI1HTikshLb9IIVMhM08BIcYJVqaRqfn/PwA), but I'll leave that up to you to decide whether or not to implement it). **Example** The following: ``` def print_a_range(a): for i in range(a): print(i) ``` Could be: ``` def print_a_range(a): for i in range(a): print(i) ``` Technically, if there is only one line inside a loop, you can compress it even more: ``` def print_a_range(a): for i in range(a):print(i) #Note, you can also remove the `()` here. ``` However, there is another way you can minify white space in Python: The following: ``` print ([a * 2 for a in range(20) if a % 2 == 0]) ``` Could be: ``` print([a*2for a in range(20)if a%2==0]) ``` Note, that there is no need for a space between `2` and `for`. Variable, functions, and keywords **cannot** start with a number. So, the Python interpreter is okay with `<num><keyword>`, no space. You should also note there does not have to a space between `)` and `if`. Note, you must not change the output of the program! So: ``` print"f(x)=x*2 is a great equation!" ``` The above print statement should stay the same because removing the space between `2` and `is` would modify the output. [Answer] # Python 2.7, 2013 score **This program can be used as reference, and you are allowed to take the following code and modify it and then post it in your own solutions.** In hindsight, I maybe should have used regex for the quote handling too, but I think in its current state it may be enough to jump-start people into the problem. Why I chose Python 2.7: I thought it would be easier to test to see if I made the program crash via the `exec` keyword. This code intakes the program as `in.txt`. I figured I should at least get the ball rolling for whoever want to participate by writing a quote parser (that also happens to handle comments) and a brief example on how regex, when combined with the quote parser can really change the game in terms of complexity of this problem. **Note:** there is still plenty of room for improvement in this minifier. Like you could play around with indentation, variable names, and removing the parenthesis when they're being used my keywords, like `print` or `yield`. ``` import re with open("in.txt","r") as fi: code = fi.read() class QuoteHandler(): def __init__(self): pass def loadCode(self,code): quoteFlag = False currentQuoteChar = "" ignoreNext = False inEndLineComment=False startLocation = 0 self.reAddStrings = [] outStr = "" for i, character in enumerate(code): if ignoreNext: ignoreNext = False elif inEndLineComment: if character in "\r\n": inEndLineComment=False elif character == "#" and not quoteFlag: inEndLineComment = True elif character in "'\"" and (currentQuoteChar == character or not quoteFlag): if quoteFlag: self.reAddStrings.append(code[startLocation+1:i]) else: currentQuoteChar = character startLocation = i quoteFlag = not quoteFlag elif character == "\\": ignoreNext = True if not inEndLineComment and not quoteFlag: outStr+=character return outStr def find_all_locations(self,substr,code): return [m.start() for m in re.finditer(substr, code)] def unloadCode(self,code): temp = self.reAddStrings[::-1] for i, location in enumerate(list(self.find_all_locations('"',code))[::-1]): code = code[:location] + "\"" + temp[i] + code[location:] return code def applyRegexes(code):#\w here? operatorRegexCleaner = ["([\d\/*\-\"=,'+{}:[\](\)])","[ \t]+","(\w)"] regexes = [ [''.join(operatorRegexCleaner),r"\1\2"], [''.join(operatorRegexCleaner[::-1]),r"\1\2"],#removes whitespace between operators ["\n\s*\n","\n"]#removes empty lines ] for regex in regexes: code = re.sub(regex[0],regex[1],code) return code qh = QuoteHandler() code = qh.loadCode(code) code = applyRegexes(code) code = qh.unloadCode(code) print(code) exec(code) ``` Output of program: ``` def factor(factor_number): for n in range(2,factor_number): if factor_number % n==0: yield(n) def gcd(a,b): """Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive). """ while b: a,b=b,a%b return a class Apricot: def __init__(self): self.mold=False def get(self): return self.mold def update(self): self.mold=not self.mold def blue(self):return5 def tell_me_about_these_numbers(*a): print("%d is the first number!" % a[0]) print("{} / 3 is {}".format(a[0],a[0]/3.)) myFavorate=Apricot() for number in a: print list(factor(number)) myFavorate.update() print[gcd(a,b)for a,b in zip(a[:-1],a[1:])] print(myFavorate.get()) tell_me_about_these_numbers(5,6,9,45,200) print"Let's play with scope!" a,b=10,9 def randomFunction(a): print(a) randomFunction(b) print(a) for a in range(100): b+=a print(a) print(b) li=[] for i in range(10): li.append(i*2) print(li) print([i*2for i in range(10)]) a=c=b=d=e=f=g=h=i=j=k=l=m=n=o=p=q=r=s=t=u=v=w=x=y=z=5 print(a) a-=1 print(a) g=10 print(str(10**g+5)[::-1]) def blue_fish(a): def blue_fish(a): def blue_fish(a): return a a+=1 return blue_fish(a) a-=1 return blue_fish(a) print(blue_fish(10)) def blue_fish(a): if a==0: return"0" return"1" +blue_fish(a-1) print(blue_fish(5)) blue_fish=lambda a,b,c:a*b*c print(blue_fish(1,2,3)) blue_fish=lambda*a:reduce(lambda a,b:a*b,a) print(blue_fish(1,2,3)) print(max([[6,1],[5,2],[4,3],[3,4],[2,5],[1,6]],key=lambda a:a[1])) print(zip(*[[1],[2],[3],[4],[5]])) print"Now let's test to see if you handle quotes correctly:" print"test \'many diffent\' \"types of \" quotes, even with \' \" trailing quotes" print""" Multi line quotes are great too! """ a=""" :: one more multi-line quote won't hurt """ print a ``` ]
[Question] [ A [quotation](https://en.wikipedia.org/wiki/Quotation) is "the repetition of one expression as part of another one". In American English, a quotation is surrounded by double-quotation marks ("), as in the previous sentence. However, this rule differs when a quote appears inside another quote. In this case, the inner quote is surrounded by single-quotation marks ('). # Challenge Given a string as input, output a quotable version of that string by exchanging double- and single-quotation marks that are used for inner quotation. There's just one catch, though - not all single-quotation marks are used for quotation! For this challenge, single-quotation mark is used for quotation if and only if: * The mark is preceded by a non-alphanumeric character, or * The mark is followed by a non-alphanumeric character that is *not* a space The marks used for quotations are guaranteed to be balanced; that is, you do not need to handle invalid input. Additionally, double-quotation marks will only be used in situations where single-quotation marks can be used to represent quotation. # Test Cases ``` A man, a plan, a canal, Panama. "A man, a plan, a canal, Panama." Socrates once said, "An unexamined life is not worth living." "Socrates once said, 'An unexamined life is not worth living.'" @musicman523 said, "Socrates once said, 'An unexamined life is not worth living.'" "@musicman523 said, 'Socrates once said, "An unexamined life is not worth living."'" "Nested 'quotes "can 'cause "recursion," if,' it," runs,' deep!" "'Nested "quotes 'can "cause 'recursion,' if," it,' runs," deep!'" "Contractions' behaviors can't be easy to account for," he warned. "'Contractions' behaviors can't be easy to account for,' he warned." @carusocomputing said, "Nested, 'quotes, it's unfortunate', to be sure." "@carusocomputing said, 'Nested, "quotes, it's unfortunate", to be sure.'" ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins! [Answer] # [Ruby](https://www.ruby-lang.org/), ~~64~~ ~~66~~ ~~65~~ 64+1 = ~~65~~ ~~67~~ ~~66~~ 65 bytes +1 byte for the `-n` flag. ``` gsub(/"|(?<!\w)'|'(?!\w|\s)/){"'\""["\"'".index$&]} $><<?"+$_+?" ``` [Try it online!](https://tio.run/##DcZNDoIwEAbQvacon8SBgHKBxt7AC1hj@BlNN0U7NGrEs9eu3gtx@KRtETJq79Nd4lB1WCujC/uqaaXK5KxW6q7@gixwhgXh4PzE73J3@W3Ko9YGTXltDFLCiWXhSdEzzguLwth7RWMfhRUCjzGIm30L5W4tKbfkheglf2J@FPgD "Ruby – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), ~~34~~ 27 bytes *-7 bytes thanks to @Leo* ``` T`'"`"'`\W'|"|'[^\w ] ^|$ " ``` [Try it online!](https://tio.run/##DccxCsMwDADAPa8QoqAl9BP5QqBDk2DVUYkXCWS1oeC/u7ntXKIo9z4nwoSUlgc1bPTclhPWYWu3AXvHyTSccxTTSvCSg7/FvEJmpbgOwvUHYcA520cD3uYjwiFwsqvs9z8 "Retina – Try It Online") [Answer] # JavaScript (ES6), 90 bytes Assumes the string doesn't contain `#`. ``` s=>'"'+s[r='replace'](/"/g,'#')[r](/(\W)'/g,'$1"')[r](/'([^\w ])/g,'"$1')[r](/#/g,"'")+'"' ``` ``` f= s=>'"'+s[r='replace'](/"/g,'#')[r](/(\W)'/g,'$1"')[r](/'([^\w ])/g,'"$1')[r](/#/g,"'")+'"' ; `A man, a plan, a canal, Panama. Socrates once said, "An unexamined life is not worth living." @musicman523 said, "Socrates once said, 'An unexamined life is not worth living.'" "Nested 'quotes "can 'cause "recursion," if,' it," runs,' deep!" "Contractions' behaviors can't be easy to account for," he warned. @carusocomputing said, "Nested, 'quotes, it's unfortunate', to be sure.`.split(`\n`).map(f).map(s=>console.log(s)) ``` ]
[Question] [ Consider depicting a [simple](http://mathworld.wolfram.com/SimpleCurve.html), [open](http://mathworld.wolfram.com/ClosedCurve.html), two-dimensional curve on a W wide by H high grid of text where `X` represents part of the curve and `.` represents empty space and no other characters are used. Every grid space has 8 neighboring grid spaces, its [Moore neighborhood](https://en.wikipedia.org/wiki/Moore_neighborhood). Grid spaces beyond the borders are considered empty. A grid contains a *curve* if it has exactly one `X` *OR* if it has more than one `X` where: * Exactly two `X`s have only one neighboring `X`. These are the curve's endpoints. * Every `X` besides the endpoints neighbors exactly two `X`s. These form the bulk of the curve. > > For example, this grid where W = 9 and H = 4 contains a curve: > > > > ``` > ....X.... > .X.X.X.X. > X..X..X.X > .XX.....X > > ``` > > Likewise, these grids (W = 4, H = 3) have curves: > > > > ``` > .... .X.. .... .... .X.X > .... X..X ..X. XX.. X.X. > ..X. .XX. .X.. .... .... > > ``` > > These grids, however, do not contain a curve: > > > > ``` > .... .XX. ...X XX.. .... X.X. > .... X..X ..XX XX.. .X.X .X.. > .... .XX. .X.. .... ...X X.X. > > ``` > > We can find the length of a curve by summing the distances between all neighboring pairs of `X`s: * The distance between two orthogonally neighboring `X`s is 1 unit. ``` XX ``` ``` X X ``` * The distance between two diagonally neighboring `X`s is [√2](https://en.wikipedia.org/wiki/Square_root_of_2) units. ``` X. .X ``` ``` .X X. ``` > > For example, the length of the curve in the grid > > > > ``` > XXX. > ...X > ..X. > > ``` > > can be visualized as > > > [![length example](https://i.stack.imgur.com/fBmek.png)](https://i.stack.imgur.com/fBmek.png) > > > so we can see it is 1 + 1 + √2 + √2 = 4.828427... > > > The length of a curve with only one `X` is zero. When a grid does not form a curve its length is not well defined. # Challenge **Given a grid of text of `X`s and `.`s, output the length of the curve it contains, or else output something such as `-1` or `Null` to indicate the grid has no curve.** For input you may use other characters than `X` and `.` if desired, and H and W may be taken as input if needed. Input as a nested list or matrix filled with 1s and 0s instead of a string is also fine. You may output a float for the curve length or alternatively two integers A and B where `length = A + B*√2`. **The shortest code in bytes wins.** # Test Cases ``` XXX. ...X ..X. 2 + 2*√2 = 4.828427... ....X.... .X.X.X.X. X..X..X.X .XX.....X 3 + 8*√2 = 14.313708... .... .... ..X. 0 + 0*√2 = 0 .X.. X..X .XX. 1 + 3*√2 = 5.242640... .... ..X. .X.. 0 + 1*√2 = 1.414213... .... XX.. .... 1 + 0*√2 = 1 .X.X X.X. .... 0 + 3*√2 = 4.242640... .... .... .... .... -1 .XX. X..X .XX. -1 ...X ..XX .X.. -1 .... .X.X ...X -1 X.X. .X.. X.X. -1 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~52~~ 51 bytes ``` t2Y6~Z+*ssGt3Y6Z+*tt1=z2=wssGzqE=*Gz1=+?}_q]ssy-h2/ ``` Input is a matrix of zeros and ones. Output is `B`, then `A`. Non-curves give a negative `A`. [Try it online!](https://tio.run/nexus/matl#@19iFGlWF6WtVVzsXmIcaQZklZQY2lYZ2ZYDRaoKXW213KsMbbXta@MLY4uLK3UzjPT//482UIBAQyhtYA1hI2FrQyQVYDGwGrgOkEgsAA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S4jw@l9iFGlWF6WtVVzsVWIcaQZklZQY2lYZ2ZYDRaoKXW21vKoMbbXta@MLY4uLK3UzjPT/u4T8jzZUAEEDawUDMDSEMIAisVzRBjBBKG1gDWEjYWtDJBVgMbAauA6QCMIkawUUBswWsGqYSdYKUAPQtUFdCVaGLAe1DW423EhDa7grUeSwOQWLAYYQw3E4Ch5QhlgdBXcBLAwA). ### Explanation **Computing the length of the curve** uses two 2D convolutions1: one with the Moore mask, and another with a mask containing only the diagonal neighbours. The results are two matrices with the same size of the input, which will be denoted as *M* and *D* respectively. *M* gives the total number of neighbours for each point, whereas *D* gives the number of diagonal neighbours. The results in *M* and *D* must be filtered to discard points that don't belong to the curve. Also, they must be divided by 2, because "being neighbour of" is a a symmetric relation, so each point in the curve is counted twice. **Determining if the curve is valid** is more cumbersome than I expected. To do this, the code tests three conditions: 1. Does the number of ones in *M* equal `2`? (That is, are thre exactly two points with a single neighbour?) 2. Does the total sum of *M* equal the number of points in the input curve times `2` minus `2`? (Together with condition 1, this tests if all non-zero values in *M* except two of them equal `2`) 3. Does the input curve contain a single point? The curve is valid if conditions 1 and 2 are true, or if condition 3 is. ``` t % Implicit input matrix of zeros and ones. Duplicate 2Y6~ % Push [1 0 1; 0 0 0; 1 0 1] Z+ % 2D convolution, keeping size * % Multiply to zero out results for non-curve points. Gives matrix D ss % Sum of matrix D Gt % Push input again wtice 3Y6 % Push [1 1 1; 1 0 1; 1 1 1] Z+ % 2D convolution, keeping size * % Multiply to zero out results for non-curve points. Gives matrix M tt % Duplicate twice 1=z % Number of ones 2= % Does it equal 2? This is condition 1 wss % Swap. Sum of matrix G % Push input again zqE % Number of nonzeros values minus 1, and then multiplied by 2 = % Are they equal? This is condition 2 * % Multiply. This is a logical AND of conditions 1 and 2 G % Push input again z1= % Does it contain exactly one nonzero value? This is condition 3 + % Add. This is a logical OR with condition 3 ?} % If result was false _q % Negate and subtract 1. This makes sure we get a negative value ] % End ss % Sum of matrix M y % Duplicate sum of matrix D from below - % Subtract h % Concatenate horizontally 2/ % Divide by 2. Implicitly display ``` --- 1 [Convolution is the key to success](https://codegolf.stackexchange.com/a/67650/36398). [Answer] # [Python 3](https://docs.python.org/3/), ~~316~~ ~~315~~ 311 bytes I think this covers all cases; at least [the test cases](https://tio.run/nexus/python3#nVLLbsJADLzzFdvbOjjtmmOj9MIfcLV8QCypFkqCEhAIVf11upuFkEqtCJUVxZnM@DHy2S4LVWiLM5zC60g1ebPfZDZnI4mejieACbPBpEYjRVWrWrlSWcHuf1blKaFBytY5M2ufA2r/DcIuWbUiF0SVCukqpq5QluuxE16MVzIvrXKfkbsIhHpevi99qfRrCl3XGziDqPdqkeyQ8/FlEmjHQNvMt7rBk9vqpNFrZAEAqWq/hJFsW7typ/mAKQk3@gBPeaN9cmrbnOJykJLnfyxLvWvhXYDX8ryo9l5M8DYRGHmLmDCECW5gCLpkAZNRcDUUsRBf3jKIushueTFaHeGPx2PUY1FXn266FhvQqZvQDJ6QLmzqbUZDN@t1wa7WMB11na/Y/TnpMic9oPvdl8c6078dul0KPexQ/xbuX0D/bq7T/qk4n78B "Python 3 – TIO Nexus") work. Also, there surely is still a lot to golf down, probably in the beginning where the edge cases are handled. ``` def f(d,R,C): s=sum;d=[0]*(C+2),*[[0,*r,0]for r in d],[0]*(C+2);o=-1,0,1;k=[[[(1,0),(0,1)][i*j]for i in o for j in o if d[r+i][c+j]and i|j]for c in range(1,-~C)for r in range(1,-~R)if d[r][c]];w=[x/2for x in map(s,zip(*s(k,[])))]or[0,0];print([w,-1][s(w)!=s([s(z)for z in d])-1or[len(t)for t in k].count(1)>2]) ``` [Try it online!](https://tio.run/nexus/python3#RY9BboQwDEX3PUW6sxnTAsuidMMNZmt5gQhUgQ6ghBEjVPXqNAFpuvv5fi@Wd9N2qgNDV6rw40V57e@30mjOJIHqUiAlzBkljjLpJqecsqMyQs95Oek0p4zyctDMDCEjQXijsE36Q7JRmlSM/Rltpwy7ixVuLr3Uo1H252SbCLh6/GrDV@lvhc@t/@UVTz/YIuWq@fFeROwRsVs9g6fNzpB4GIgFEWVy4YhMytnZcQFeKc2FPaz4qj2EsB1rtvM4TPPAf7cjLEe9xHqQt2a6BznHz0Jw3/8A "Python 3 – TIO Nexus") How it works: 1. `d,R,C` are 1. a list of lists with 1 as curve and 0 as background, 2. row and column count 2. Insert a row of 0's before and after and a column of 0's before and after `d` so we don't have to worry about the edge of the 2d array 3. For every 1 in the 2d array, scan the neighbourhood for 1's and add (1,0) to a list if the relation is diagonal, else add (0,1) 4. Sum all tuples, so that (n,m) represents the number of diagonal and non-diagonal neighbours, respectively 5. Check if the number of relations is exactly the number of 1's minus one; if not, not a curve. Thanks to @Helka Homba for pointing out a missing case. Thanks to @TuukkaX and @Trelzevir for the golfing tips. [Answer] # Mathematica, ~~153~~ 150 bytes ``` Switch[Sort[Join@@BlockMap[If[#[[2,2]]<1,Nothing,Tr[Tr/@#]]&,#~ArrayPad~1,{3,3},1]],{1},0,{2,2,3...},1/.#~ComponentMeasurements~"PolygonalLength",_,]& ``` Takes a 2D array, with `0`s for `.`s and `1`s for `X`s. Outputs `Null` for non-curves. ``` 1/.#~ComponentMeasurements~"PolygonalLength"& ``` Mathematica has a 45-byte built-in for this, but it outputs some numbers for non-curves and 1/sqrt(2) for input `{{1}}`. Correcting these cost 105 bytes (could be golfed?). ]
[Question] [ Steiner Chains are a set of N circles where each circle is tangent to 2 other non-intersecting circles as well as the the previous and next circles of the chain, as seen in the below images: [![Order 3](https://i.stack.imgur.com/dN2Rn.png)](https://i.stack.imgur.com/dN2Rn.png) [![Order 5](https://i.stack.imgur.com/yaNCE.png)](https://i.stack.imgur.com/yaNCE.png) [![Order 7](https://i.stack.imgur.com/q4DjF.png)](https://i.stack.imgur.com/q4DjF.png) In this challenge, you will write a program/function that draws Steiner chains recursively, that is, circles of a given chain will be the base circles of another iteration of chains: [![enter image description here](https://i.stack.imgur.com/gbULW.png)](https://i.stack.imgur.com/gbULW.png) # Challenge Write a program/function that accepts image dimensions and a list of integers denoting the level of circles in each successive iteration of chains, and output an image with the recursive Steiner chains drawn to it. # Input Your program/function will accept 2 arguments: * `s` - width and height of image * `ls` - list of positive integers denoting the number of circles present in each successive iteration of chains, ordered from the top-most chain to the bottom-most chain # Output Your program/function will output an image of dimension `s` x `s` displaying the recusive Steiner chain. * The top level base circle will be as large as the image with a diameter of `s`, centered inside the image * To make things easy, the 2 base circles of a Steiner chain will be concentric, that is, the centerpoints of the 2 baseline circles will be the same * Given an outer radius, `R`, and the number of circles in a chain, `N`, the formula for the inner radius `R'` is `R' = (R-R*sin(pi/N))/(sin(pi/N)+1)` * Circles of the chain as well as the inner base circle will be the outer base circles of the next iteration of chains * While recursing through the chain circles, the order of the next chain should correspond to the next value in `ls` * While recursing through the inner circle of a chain, the order should be the same as its parents order (example [5,2]): * [![Order 5.2](https://i.stack.imgur.com/k7wHQ.png)](https://i.stack.imgur.com/k7wHQ.png) * All chains should end recursion at a depth of the length of `ls` * The rotation of the chains doesn't matter: * [![Rotation 1](https://i.stack.imgur.com/Cad69.png)](https://i.stack.imgur.com/Cad69.png) [![Rotation 2](https://i.stack.imgur.com/NuMdM.png)](https://i.stack.imgur.com/NuMdM.png) * However, the rotations of recursive chains relative to their parents centerpoint should be the same: * [![Order 5.2](https://i.stack.imgur.com/TRCY7.png)](https://i.stack.imgur.com/TRCY7.png) [![Invalid Order 5.2](https://i.stack.imgur.com/HFmDB.png)](https://i.stack.imgur.com/HFmDB.png) * All circles should be drawn with an outline or solid fill * Color choice is left to the implementation, save for loopholes (for example, filling everything with the same color) # Example Runs In the following examples, color is determined by `(depth of the recursion)^4`. You can find source [here](https://codegolf.stackexchange.com/questions/80152/recursive-steiner-chains/80154#80154). ``` chain(600,[5,4,3]) ``` [![5.4.3](https://i.stack.imgur.com/1ZCu7.png)](https://i.stack.imgur.com/1ZCu7.png) ``` chain(600,[11,1,1,1,1,1,1]) ``` [![11.1.1.1.1.1.1](https://i.stack.imgur.com/p6RN8.png)](https://i.stack.imgur.com/p6RN8.png) ``` chain(600,[5,6,7,8,9]) ``` [![5.6.7.8.9](https://i.stack.imgur.com/fAJ93.png)](https://i.stack.imgur.com/fAJ93.png) [Answer] # Javascript ES6, 379 bytes This solution was used to generate the example runs in the question. ``` f=(s,ls)=>{with(V=document.createElement`canvas`)with(getContext`2d`)with(Math)return(width=height=s,translate(s/=2,s),(S=(o,d=0,n=ls[d],i=(o-o*sin(PI/n))/(sin(PI/n)+1),r=0)=>{fillStyle=`rgba(0,0,0,${pow(d/ls.length,4)})`;beginPath(),arc(0,0,o,-PI,PI),fill();if(d++<ls.length){S(i,d,n);for(;r<n;++r){save();translate(0,(o+i)/2);S((o-i)/2,d);restore();rotate((2*PI)/n);}}})(s),V)} ``` Ungolfed: ``` f=(s,ls)=>{ // define function that accepts image dimensions and a list of orders with(V=document.createElement`canvas`) // create canvas to draw on, bring its functions into current scope chain with(getContext`2d`) // bring graphics functions into current scope chain with(Math)return( // bring Math functions into current scope chain width=height=s, // set width and height of image translate(s/=2,s), // center the transform on image (S=(o,d=0, // define recursive function that accepts outer radius, depth, and optionally order n=ls[d], // default chain order to corresponding order in input list i=(o-o*sin(PI/n))/(sin(PI/n)+1), // calculate inner base circle radius r=0)=>{ // initialize for loop var fillStyle=`rgba(0,0,0,${pow(d/ls.length,4)})`; // fill based on depth beginPath(),arc(0,0,o,-PI,PI),fill(); // draw circle if(d++<ls.length){ // if within recursion limit S(i,d,n); // recurse on inner circle for(;r<n;++r){ // loop through all circles of the chain save(); // save transform translate(0,(o+i)/2); // translate origin to middle of the 2 base circles S((o-i)/2,d); // recurse on chain circle restore(); // restore transform rotate((2*PI)/n); // rotate transform to next circle in chain }}})(s), // begin the recursion V)} // return the canvas ``` Note: `f` returns a canvas. Example run (assumes there's a `<body>` to append to): ``` document.body.appendChild(f(600,[13,7,11,5,3])) ``` Should dump the following image to the page: [![Output](https://i.stack.imgur.com/x8YhP.png)](https://i.stack.imgur.com/x8YhP.png) [Answer] @Dendrobium I was trying to port @Dendrobium's Javascript answer in Python. \$\color{red}{\text{But the resolution of my fractal image is terrible.}}\$ ``` from PIL import Image, ImageDraw import numpy as np import matplotlib.pyplot as plt def draw_fractal(s, ls): # Create a new image with a white background image = Image.new('RGBA', (s, s), color = (0, 0, 0, 0)) draw = ImageDraw.Draw(image) # Begin the recursion draw_fractal_recursive(draw, s/2, s/2, s/2, 0, ls, s) # Display the image plt.imshow(np.array(image)) plt.show() def draw_fractal_recursive(draw, x, y, o, depth, ls, s): if depth >= len(ls): return # Chain order to corresponding order in input list n = ls[depth] # Calculate inner base circle radius i = (o-o*np.sin(np.pi/n))/(np.sin(np.pi/n)+1) # Fill based on depth rgba_color = (0, 0, 0, int(255 * np.power(depth/len(ls), 4))) # Draw circle draw.ellipse((x-o, y-o, x+o, y+o), fill=rgba_color) # Recurse on inner circle draw_fractal_recursive(draw, x, y, i, depth+1, ls, s) # Loop through all circles of the chain for r in range(n): # Translate origin to middle of the 2 base circles new_x = x + (o+i)/2 * np.cos(2 * np.pi * r / n) new_y = y + (o+i)/2 * np.sin(2 * np.pi * r / n) # Recurse on chain circle draw_fractal_recursive(draw, new_x, new_y, (o-i)/2, depth+1, ls, s) # Call the function draw_fractal(600,[13,7,11,5,3]) ``` [![enter image description here](https://i.stack.imgur.com/w1ucj.png)](https://i.stack.imgur.com/w1ucj.png) ]
[Question] [ A [leaper](https://en.wikipedia.org/wiki/Fairy_chess_piece#Leapers) is a category of fairy chess piece which moves by "jumping." A normal knight is a (1,2)-leaper, meaning each move involves moving a distance of 1 square in an orthogonal direction and 2 squares in the perpendicular direction. ``` .o.o. o...o ..N.. o...o .o.o. ``` There are many different leapers. The (1,3)-leaper is called the Long Knight, or Camel. Its move pattern looks like this: ``` ..o.o.. ....... o.....o ...L... o.....o ....... ..o.o.. ``` There's also the (2,2) Alfil... ``` o...o ..... ..A.. ..... o...o ``` ...and even the (0,1) Wazir. ``` .o. oWo .o. ``` ## Challenge Given a pair of numbers as input, output the corresponding movement diagram. You may write a program or function, with input provided via STDIN/command-line or as an argument, and output provide by STDOUT or the return value. This is **code-golf**. **Input** Input will be a comma-separated list of two integers and an uppercase letter. The two integers will be in the range `0-7` (inclusive) and in non-decreasing order. Trailing newline optional for input and output. Here are the inputs for the above four examples: ``` 1,2,N 1,3,L 2,2,A 0,1,W ``` **Output** Output will be a square-shaped multiline string. The capital letter will be placed in the center to represent the current location of the piece. The movement locations will be represented by either 4 or 8 lowercase `o`s. All other spaces in the square will be filled with periods. If the movement pattern is `0,0`, output just the capital letter. As a hint, if the second integer (the larger one) has value N, then the square will always have side length 2N+1. The `o`s will always be on the perimeter of the square. ## Additional Testcases ``` 1,1,F o.o .F. o.o 5,7,Q ..o.........o.. ............... o.............o ............... ............... ............... ............... .......Q....... ............... ............... ............... ............... o.............o ............... ..o.........o.. 0,0,J J ``` [Answer] # Ruby,107 ``` ->a,b,n{(-b..b).map{|i|s='..'*b+?. i%b==0&&(i==0?s[b]=n :s[b+a]=s[b-a]=?o) i.abs==a&&s[0]=s[-1]=?o puts s}} ``` Ungolfed in test program ``` f=->a,b,n{ (-b..b).map{|i| #iterate from -i to i (lines of grit) s='..'*b+?. #make a string of 2n+1 .'s i%b==0&&(i==0?s[b]=n :s[b+a]=s[b-a]=?o) #if i%b=0 plot the centre character (if i=0) or the o's on the top and bottom rows i.abs==a&&s[0]=s[-1]=?o #if i.abs=a plot the o's in left and right columns puts s #having substituted the .'s with o and centre as necessary, output the current line } } a=gets.to_i b=gets.to_i n=gets.chop f[a,b,n] ``` [Answer] # Pyth, 40 bytes ``` JASv<2zFZK+rH_1SHFY,LZKp?qJSY\o?sY\.ez)k ``` I'm learning Pyth! [Try it out](https://pyth.herokuapp.com/?code=JASv%3C2zFZK%2BrH_1SHFY%2CLZKp%3FqJSY%5Co%3FsY%5C.ez%29k&input=7%2C5%2CQ&debug=0). ## Explanation ``` J J = A (G, H) = S sorted( v<2z eval(input[:-2])) FZK+rH_1SH for Z in K = [H, H-1, ..., 0] + [1, 2, ..., H]: FY,LZK for Y in [(Z, k) for k in K]: p print the following value without newline: ?qJSY\o if J = sorted(Y): 'o' ?sY\. if sum(Y) != 0: '.' ez else: input[-1] ) end for k print newline ``` [Answer] ## JavaScript (ES6), ~~163~~ ~~161~~ 145 bytes ``` (x,y,c,m=a=>`\n`+a.slice(1).reverse().join``+a.join``,a=Array(y+1).fill`.`,q=a.map(_=>[...a]))=>m(q.map(m,q[x][y]=q[y][x]='o',q[0][0]=c)).slice(2) ``` Where `\n` is the literal new line character. Works by generating the bottom right quadrant and mirroring it along both axes. Edit: Saved 2 bytes thanks to @edc65. (I got here via a duplicate question which allowed an array result which would have been 19 bytes shorter, but didn't guarantee nondecreasing order, which wasted 8 bytes.) [Answer] # JavaScript (ES6) 144 ~~150~~ ``` (a,b,c,g=Array(b-~b).fill`.`)=>(g=g.map(x=>[...g])).map(x=>x.join``,[b-a,b+a].map(t=>g[t][0]=g[0][t]=g[t][2*b]=g[2*b][t]='o'),g[b][b]=c).join` ` ``` **Less golfed** ``` (a,b,c)=> { var g=Array(b*2+1).fill('.'); g=g.map(x=>[...g]); var q=(t)=> g[t][0] = g[0][t] = g[t][2*b] = g[2*b][t] = 'o'; q(b+a); q(b-a); g[b][b] = c; return g.map(x=> x.join('')).join('\n') } ``` **Test** ``` f=(a,b,c,g=Array(b-~b).fill`.`)=>(g=g.map(x=>[...g])).map(x=>x.join``,[b-a,b+a].map(t=>g[t][0]=g[0][t]=g[t][2*b]=g[2*b][t]='o'),g[b][b]=c).join` ` console.log=x=>O.textContent+=x+'\n' t=`1,2,N 1,3,L 2,2,A 0,1,W 1,1,F 5,7,Q`.split`\n` .forEach(t=>([x,y,z]=t.split`,`, console.log(t+'\n'+f(+x,+y,z)+'\n'))) ``` ``` <pre id=O></pre> ``` ]
[Question] [ **Your task** is to output a single number; the number of ISO weeks that a given date range intersects. To quote Wikipedia: `An average year is exactly 52.1775 weeks long`, but this is not about the average. **Input** consists of two space-separated ISO dates: ``` 0047-12-24 2013-06-01 ``` The end date is never before the start date. We'll use the extrapolated Gregorian calendar for simplicity. **Test cases:** ``` Format: input -> output 2015-12-31 2016-01-01 -> 1 (both are within week 53 of 2015) 2016-01-03 2016-01-04 -> 2 (the 3rd is within week 53, and the 4th is in week 1) 2015-12-24 2015-12-24 -> 1 (this single day is of course within a single week) ``` Your solution should handle dates between `0001-01-01` and `9999-12-31`. [Answer] ## Ruby, ~~89~~ ~~88~~ 86 bytes ``` ->s{a,b=s.split.map{|x|Time.gm *x.split(?-)} n=1 (a+=86400).wday==1&&n+=1until a==b n} ``` A very primitive solution: given the first date `a` and the second date `b`, increment `a`, check if it's a Monday (if so, we've "rolled over" to a new week), and stop once `a` is `b`. Takes input in the exact format specified in the question: a single space-separated string. (The way it parses the input is fancy-ish: it uses Ruby's "splat" operator, `*`. This operator "expands" an array or enumerable out, so `Time.gm *[2013, 06, 01]` becomes `Time.gm 2013, 06, 01`.) Imported from a comment discussion: > > We don't care about "weeks in a year;" we only care about "weeks overall." So whether a year has 52 or 53 weeks doesn't make any difference. > > > Just to avoid future confusion with whether this handles year boundaries correctly—[according to Wikipedia](https://en.wikipedia.org/wiki/ISO_week_date), all weeks always start on Monday and end on Sunday. For some more fancy tricks, these are all equivalent: ``` until a==b;a+=86400;n+=a.wday==1?1:0;end [a+=86400,n+=a.wday==1?1:0]until a==b n+=(a+=86400).wday==1?1:0 until a==b (a+=86400).wday==1&&n+=1 until a==b (a+=86400).wday==1&&n+=1until a==b ``` [Answer] # VBA , 125 Bytes Expecting 2 function inputs as strings ``` Function u(k,j) f=DateValue(k) For i=0 To (DateValue(j)-f) q=DatePart("ww",f+i,2,2) If q<>j Then u=u+1 j=q Next End Function ``` Pretty sure This can be golfed. This is looping though everyday between the 2 dates and increments the counter every time the ISO date changes. `DatePart("ww",f+i,2,2)` is the ISO week number in VBA the first 2 means `Monday (complies with ISO standard 8601, section 3.17)`. then second 2 means `Week that has at least four days in the new year (complies with ISO standard 8601, section 3.17)` ### 140 bytes w/single input ``` Function g(k) y=Split(k) f=DateValue(y(0)) For i=0 To (DateValue(y(1))-f) q=DatePart("ww",f+i,2,2) If q<>j Then g=g+1 j=q Next End Function ``` [Answer] ## R, 76 bytes ``` d=as.Date(scan("","raw"));sum(strftime(seq(d[1],d[2],"day")[-1],"%w")==1)+1 ``` After the talk with @Doorknob, it's finally as easy as counting the Mondays. `seq` allow to create a vector of dates (of each day between two dates) and strftime transform it to the 'number of the day in the week', now counts the times it's 1 to get the number of time you changed week and add 1 to take in account previous week. Another approach looping: ## R, 85 bytes ``` n=1;d=as.Date(scan("","raw"));z=d[1];while(z<d[2]){n=n+(strftime(z<-z+1,"%w")==1)};n ``` [Answer] # Mathematica ~~135 79 96 84~~ 74 bytes Consistent with @Doorknob's suggestion, this * generates all the dates in the range * counts the number of Mondays (`ISOWeekDay` =="1") in the `DateRange`(excluding `d`), and * adds `1` to the total. --- ``` Count[DateString[#,"ISOWeekDay"]&/@Rest@(DateRange@@StringSplit@#),"1"]+1& ``` --- ``` Count[DateString[#,"ISOWeekDay"]&/@Rest@(DateRange@@StringSplit@#),"1"]+1& /@ {"2015-12-31 2016-01-01", "2016-01-04 2016-01-05","2016-01-03 2016-01-04", "2015-12-24 2015-12-24", "1876-12-24 2016-01-01"} ``` > > {1, 1, 2, 1, 7255} > > > ]
[Question] [ ## Challenge Given an element name, output its electron configuration. ## Input Your input will be the full name of each element (the range being from Hydrogen, 1, to Calcium, 20) with some exceptions - you should be able to account for the following inputs: ``` Natrium - This is sodium Kalium - This is potassium ``` Note that inputs "sodium" and "potassium" must still be valid. The first letter will always be capitalised. ## Output You can refer to [this webpage](http://www.bbc.co.uk/schools/gcsebitesize/science/add_ocr_pre_2011/periodic_table/electronsrev2.shtml) for guidance on how to generate an electron configuration diagram. The following list shows the maximum number of electrons in each shell: * **1st shell** - 2 electrons * **2nd shell** - 8 electrons * **3rd shell** - 8 electrons * **4th shell** - 14 electrons (although the maximum number of electrons in this shell required is 2) An example output of the electron configuration is the following: ![](https://i.stack.imgur.com/9h5zD.png) In the centre of the diagram must be the element's one to two letter symbol. Either dots or crosses may be used and where they are placed does not matter. The output does not have to be exactly like this but it does have to be an ASCII graphic. The one thing it cannot be is in the form `2.8.8.1` or any other form like this. The circles are not necessary Built in functions which access the periodic table of elements or produce diagrams or electron configurations are hereby disallowed. ## Winning The shortest program in bytes wins. [Answer] # MATLAB, 360 363 290 304 295 bytes *See at the bottom of the post for how to test the old code with Octave.* This code takes the name of the element (including Kalium, etc.) and displyas the output in ascii format now that the rules have changed. ``` f=input('');e=1;a=['CPACxxSAMSNxxxxxBLHxCKACSPSAMNNFONCBBLHH';'aorhxxilaoexxxxxeiexa rl ilgae eie '];for s=a;n=s(s~=32);if strncmpi(n,f,nnz(n));break;end;e=mod(e,20)+1;end;s=spiral(10);p=[8,18,33,28,23,39,60,53,46,95];p=[p;p+1];o=s*0;o(ismember(s,p(1:21-e)))='x';o(45:46)=a(:,e+20);char(o') ``` The rules changed since I wrote the code to require an ASCII output. I have updated my code to do this at the expense of 14 bytes. I have saved 9 bytes by getting rid of the reshape() and just making the `a` matrix the right shape to begin with. Here is an explanation of how it works: ``` %Get the name - actually we only need at most the first two characters, but the whole thing will do f=input(''); e=1; %This bit makes a map which allows us to find the element (including with %the names like Kalium. All of the elements appear twice, with the actual %symbols being the second set. The first set gets all those whose names are %either more than one character, or don't begin with the first two %characters of the short for (e.g. Sodium). The string is reshaped into a %2x40 array. 'Natrium' is a pain in the neck as it as it would get caught %by 'N' for 'Nitrogen'. I have reversed the element order - so that all the %ones beginning with N come before N. Some maths is done later on to %correct for the number of electrons - basically 21-e so 1 becomes 20. a=['CPACxxSAMSNxxxxxBLHxCKACSPSAMNNFONCBBLHH';'aorhxxilaoexxxxxeiexa rl ilgae eie ']; %For each group of 2 in the array of elements for s=a %Remove any spaces from the name n=s(s~=32); %Do a comparison of the first one or two characters of the requested string if (strncmpi(n,f,nnz(n))) %break once the element is found break; end %If not this element add another electron. We wrap around after 20 as there are two copies of each e=mod(e,20)+1; end %e is now number of electrons %Generate an array of points for each electron s=spiral(10); p=[8,18,33,28,23,39,60,53,46,95];p=[p;p+1]; %make an output array o=s*0; %Plot all the points in is up to and including the number of electrons (see the notes above for why 21-e) o(ismember(s,p(1:21-e)))='x'; %And add the text in the centre - we extract the element name from the second group appearance in the 'a' array, hence adding 20. o(45:46)=a(:,e+20); %Display the result char(o') ``` This is the output for Hydrogen (ignore the dots, they are to avoid the lines being removed when showing here): ``` . . . . xH . . . . . . ``` And here is the output for Calcium. ``` . xx . xx . . xxxCa xxx. xxx xxx. . xx . xx . . ``` And the output for Natrium, which now works properly (before Natrium it would result in Nitrogen!). ``` . x . xx . . xxNa x . xx x . . xx . . . ``` --- The new version of the code doesn't work with Octave as it uses `spiral()` which is only present in MATLAB. You can however test the old code using the [Octave online interpreter](http://octave-online.net/): ``` f=input('');e=1;a=['CPACxxSAMSNxxxxxBLHxCKACSPSAMNNFONCBBLHH';'aorhxxilaoexxxxxeiexa rl ilgae eie '];for s=a;n=s(s~=32);if strncmpi(n,f,nnz(n));break;end;e=mod(e,20)+1;end;u=14:(34-e);r=floor(u/8);t=u*pi/4;polar(t,r,'o');text(0,0,a(:,e+20)','horizontalalignment','c') ``` Run that, then enter a string like: 'Hydrogen' (including the quote marks). Once it is done, you will have to click the expand plot button (looks like a little graph symbol in the top right corner of the interpreter) to get it to show the full thing. In Octave it unfortunately add lines joining the points, this does not happen in MATLAB. But at least it allows you to test the logic behind it. As I say, this is still a graphical output, but you get the idea of how the elements are looked up. [Answer] ## Python 3, 529 bytes *thanks Thomas and Beta for pointing out some things that should've been obvious to me, saving me some bytes* *massive improvement: using string slicing instead of dict lookup* ``` s=""" {18} {10}{14} {2}{6} {0}{1} {17}{9} %s {3}{11} {13}{5} {7}{15} {8}{4} {16}{12} {19}""" e="H HeLiBe B C N O F NeNaMgAlSiP S ClArK Ca" r="hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon natrium sodium magnesium aluminium silicon phosphoroussulfur chlorine argon kalium potassium calcium " n=r.find(input().lower())//11 n-=(n>10)+(n>18) print(s.format(*[' *'[i<=n]for i in range(20)])%e[n*2+1:n*2+3]) ``` Not the prettiest of programs or outputs, but hey, we needed something to kick this challenge off. [Try it online](http://ideone.com/DKXvfp). [Answer] ``` j=0 do { if(elnum=1) { draw_circle(100,100,50) draw_sprite_ext(spr_electron,sprite num,100,100+50,direction,c_white,c_alpha) } else { if(elnum=2) { draw_circle(100,100,50) draw_sprite_ext(spr_electron,sprite num,100,100+50,direction,c_white,c_alpha) draw_sprite_ext(spr_electron,sprite num,100,100+50,direction,c_white,c_alpha) } if(j>1&&j<=8) { if(j>5) angdeviation=5 else angdeviation=-5 draw_circle(100,100,100) draw_sprite_ext(spr_electron,sprite num,100+length_dirx(j*100+angdeviation),100+length_diry(j*100+angdeviation),direction,c_white,c_alpha) } } }until(j<=enum) ``` ]
[Question] [ # Background An atomic bomb has exploded near the fencepost factory! Since fenceposts are essential for the survival of our civilization, we must rescue as many as possible. We are sending radiation-resistant robots to search the area, and it is your task to program their artificial vision. # Input Your input is a rectangular grid of the characters `|-#`, representing two kinds of fencepost parts and rubble, given as a newline-delimited string. The fenceposts have been horribly maimed by the explosion, and some have even been fused together by the heat. We define a **candidate fencepost** to be either a horizontal pattern that starts and ends in `|` and has one or more `-`s between them (like `|-|` or `|---|` but not `||`), or a vertical pattern that starts and ends in `-` and has one or more `|`s between them (essentially a horizontal candidate fencepost rotated 90 degrees). An **actual fencepost** is a candidate fencepost which does not share any of its parts with another candidate fencepost. # Output Your output is the number of actual fenceposts in the input grid. # Example Consider the input grid ``` |#**|-|**#|## #||--|||# ###|#|--# ###-|**|--|** -#-|#-|#- #---#-#-| #-#-|#--| ``` There are 5 candidate fenceposts in this grid, but only 2 of them are actual fenceposts (shown in bold). Thus the correct output is `2`. # Rules You can write either a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. # Additional Test cases Input: ``` ##-- ||## -#|- |#|# ``` Output: `0` (0 candidate fenceposts) Input: ``` -##|-##-- #|#-|#||- --|-#|#|| ##||||-## ||#|--|-| -#|-#--|# |####|#-# ``` Output: `0` (5 candidate fenceposts) Input: ``` #|--|---|-|# ####|##--||- -|-##||#|--- -#|#-|-#-||| #|-##--###|- ---#-||-#-## #|---|###|-# -|---#-#|#|# |#--|####-|- ``` Output: `4` (8 candidate fenceposts) Input: ``` -|-||---##|# ---|######-# ####-##|#--| |||##|#-|||| ####-#-||-#| ---#--|#-#-- -|#-####-##- #||-|-|-###| |-##||-||-#- ``` Output: `5` (7 candidate fenceposts) Input: ``` |#-|#|#-###|#-# ----#####|#---- |#--#-##-#|##-| |#-|#-|--##||-- ||#-#---##|||## #|#-|||-#-#--|| --#|-||#|--|#|# -#-|###||-#--#| -#||-|#-##||##| |--|-|||-##|-#| ``` Output: `4` (9 candidate fenceposts) Input: ``` ||-|-|-##-#-#-|#--#- -##|-#|-#-##-|#|--|- ||#---###||-|#|##|-# #||-#-#-|---|#||#|## -#-###-##-|-#-|-#||# ##-#--#||-----||-|## -|--#-#-#|---#-#|#-# ###|-|#-#|-|###|#-|# #||#-#|--|-||#------ ||##|-||#-|--#|#-#-# |#-|-#-|-|--##-#|||# -|#--#||##---##|-##- #|-|-|-||-||#-#-|##- |-#|##|-|#|#|--||#-- ``` Output: `9` (30 candidate fenceposts) [Answer] # Ruby, 266 ~~268~~ bytes To get this started. Makes use of the fact that variables point to objects (a 1-char string for each element of the 2D array) to eliminate overlapping candidates. Eg. if you execute `a="s";b=a`, both `a` and `b` point to the same string. `"test"=="test"` returns true, but `"test".equal?("test")` returns false, because we have created two different String objects. ``` ->d{c=->d,f,v,u{i=0 r=[] d.map{|y|j=0 e=[] y.map{|x|f[j]||=[] f[j][i]=x x==v ?e[1]?r<<e+[x]&&e=[x]:e[0]?e=[x]:e<<x :x==u&&e[0]?e<<x :e=[] j+=1} i+=1} r} y=c[d.split.map(&:chars),f=[],?|,?-]+c[f,[],?-,?|] y.count{|x|y.all?{|q|x.equal?(q)||!(q+x).uniq!(&:object_id)}}} ``` Test cases on [ideone](https://ideone.com/0dBaOF). [Answer] # Python3, 362 bytes: ``` E=enumerate def P(b,c,X,Y,n,e): try: if(C:=b[(x:=c[-1][0]+X)][(y:=c[-1][1]+Y)])in[n,e]: K=c+[(x,y)] if C==n:yield from P(b,K,X,Y,n,e) elif len(c)>1:yield{*K} except:1 def f(b):c=[q for x,j in E(b)for y,k in E(j)for q in P(b,[(x,y)],*(k=='-',k!='-'),*['-','|'][::[1,-1][k=='-']])if k in['|','-']];return sum(all(not j&i for j in c if j!=i)for i in c) ``` [Try it online!](https://tio.run/##bVRNT9wwED3Xv8JgqWsvdtXwWaVKD6CekKoeQWlUkZCoWUKyhCCxqvvbtzNvsntaCTaeN@M3bz6S9Wb6M/RnX9bjdvs9q/u353p8mGr1WDf6py195e/8ve997VKlp3FDv7pt7E2albl9T7MqD0mRfy5O7lyR280OSIqTe1e4ts/pasGX9G1WndAVv3EFm22jb7KsTzdt3T3qZhyeke92n4@D6o7Curq3lfuWSOjf5e0/pev3ql5PaQKdjS1dWmX5i26GUb/7lW57/Z1ANjf@ScwVzBc2ONEsxS/tU5YtwsI/HfHD@WXO1iIuijxN88RzORJSUEGNZrqc3B7I17Ge3sZev74924eus/0w6dXHFkqgo@JKV0dZi/QtILctk@z4@FhFEwP9G6NMjCHEGOlkDMMBpwBYBTrgT5lAHjaVEZBOzFSegpBuBBWZMBAH8xtxn8EdiDsgxoCP2BUxBM5IjPQT2c8MnBeZCaAjYQbKwkx4LvkQhlDo5Vq4DqJlIuEJzGIY4ArVLIGDOTtQrsmALUQ4jAKvgTROLg5mkfwXUlBEhziVUfNljhIxgLlD3FhIQH54kDRKfu4jNwVPuRcwkYgqKEyKEaGS/3IeIOYXdq0J0CIWF84P0KExUeK5MtBhVMGI/ihrAJEYMR2IjzdEpoESjfQHQzEYTxTVqFDJ1DBElAepVyJ1V07YbY4J80JI@8M8dIiS@czbyeMwsyoZUZStxT25C5eRBRZxHIldQGSUvTX7qcqMRH2Uqgy2KAqCQtDFeaXFZh40DUshadHPgBYqqSxiD3frzosVZVWk4exVWPv5BcTLxyvAneJvyjT8LoeH8dFe04fvw/yS5/myLfT@PW7abqpH@2Poa6@vP72uu3ayi1/9wtEnTq3Htp9sY/dMZeKcOwCfHobPDsPnh@GLw/DlYfiK4O1/) ]
[Question] [ **UPDATED SCORING**: *As this challenge is more difficult than I anticipated, I have adjusted the scoring. A program that can solve a single mirror input is a valid answer. More sophisticated programs get a bonus to their score.* There have been several puzzles on PPCG to find a laser path in a box of mirrors. In this puzzle, you need to *create* a box of mirrors to match a number of laser destinations. You are given a box and a specifications where lasers are to enter and exit. Your program needs to place exactly N double-sided mirrors in the box to meet the specification. The mirrors must be angled at 45 degrees but can be forward sloping or back sloping. ### Input Your program should accept a box grid via STDIN, command line argument, or file in the following format examples: ``` +--G--+ +abcde+ G | f/////d | /| a// c +-----+ f | +-b-e-+ ``` The letter pairs ([a-zA-Z] may be used) indicate the input/output of up to 52 lasers. Inside the box will be N `/` mirrors. The box dimensions will be 3 <= W,H <= 200. The box is made of `+|-` characters. There may be any number of mirrors in the box including zero. ### Output The output should match the input, except the `/` characters may be moved and/or changed into `\` characters. Your program should send a correct mirror box string to STDOUT or a file, trailing new line optional. If no placement of mirrors can meet the input specification, output `Impossible\n`. Examples of possible solutions: ``` +--G--+ +abcde+ G / | f \ \ d | | a/ \ c +-----+ f / //| +-b-e-+ ``` ### Testing example Input: ``` +abcdefghijklmnopqrstuvwxyA-+ |/////////////// | |/////////////// | | | +-Abcdefghijklmnopqrstuvwxya+ ``` Example output: ``` +abcdefghijklmnopqrstuvwxyA-+ |\ \| |/ / | |\\\\\\\\\\\\\\\\\\\\\\\\\\ | +-Abcdefghijklmnopqrstuvwxya+ ``` ### Scoring (UPDATED) This is code-golf with bonuses. You should nominate with your answer how many mirrors your program can solve (N). Your score is the length of your program in bytes divided by N. This allows people to enter with a simple program, but rewards more ambition programmers with a bonus. Standard loopholes disallowed. [Answer] # C# - ~~897~~ 862 bytes *Found a serious bug with it putting mirrors in places that they can't be. Now it works, hopefully! Also did some light golfing, couldn't leave the while loop in there... shameful.* Complete program, takes input from STDIN, outputs to STDOUT. This was a lot of fun, it copes fine with the 7 by 5 problem (and when you remove one of the mirrors, making it impossible), took about 1 hour to solve the 30 by 5. ``` using Q=System.Console;class P{static int w,L;static string S(char[]M,int t,int r,int i,int d,int[]B){var s="";if(r<0)return s;M=(char[])M.Clone();B=(int[])B.Clone();B[i]=1;for(i+=d;M[t]<48|t==i;i=t+(d=t<w?w:t>L-w?-w:t%w<1?1:-1))if(++t>=L){for(i=0;++i<L&r>0;)if(B[i]<1&M[i]<33){M[i]='.';r--;}return r<1?new string(M):s;}int c=M[i];if(c>32)s=c>47|c<46?s=c==M[t]?S(M,t,r,t,0,B):s:S(M,t,r,i,c<47?w/d:-w/d,B);else if((s=S(M,t,r,i,d,B))==""&B[i]<1){M[i]='.';s=S(M,t,r-1,i,w/d,B);if(s==""){M[i]='/';s=S(M,t,r-1,i,-w/d,B);}}return s;}static void Main(){string a,A="",R=A;for(;(a=Q.ReadLine())!=null;A+=a)L+=(w=a.Length);var G=A.ToCharArray();int r=0,i=L;for(;i>0;G[i]=G[i]=='|'?',':G[i])if(G[--i]==47|G[i]==92){r++;G[i]=' ';}a=S(G,0,r,1,w,new int[L]);if(a=="")R="Impossible\n";else for(;i<L;i+=w)R+=a.Substring(i,w)+"\n";Q.Write(R.Replace(".","\\").Replace(",","|"));}} ``` 7 by 5 Example: ``` +abcde+ f/////d a// c f | +-b-e-+ +abcde+ f \ d a/ //c f/ \ /| +-b-e-+ ``` Impossible version: ``` +abcde+ f ////d a// c f | +-b-e-+ Impossible ``` Something different (the program doesn't look at the original mirror layout): ``` +a----+ |//// | |/////| |/////| +----a+ +a----+ | /\\\| |\\\\\| |\\/\\| +----a+ ``` 30 by 5 solution: ``` +abcdefghijklmnopqrstuvwxyA-+ | \\\\\\\\\\\\\\\\\\\\\\\\ \| | / //| |\ \| +-Abcdefghijklmnopqrstuvwxya+ ``` It looks at each laser source in turn, and builds a valid route for it (if it can), and then moves onto the next. It's a pretty simple depth-first search, which has to know which laser source (target) it's looking at, how many mirrors it remain for it to place, the current cell it's "at", the direction it's moving in, and each cell it's visited already (so that it doesn't put a mirror somewhere it's already been). The last 3 are used for assembling the path for the current target, and at reset when the target changes. Once it's got all the lasers linked up, it goes ahead and fills in any gaps it doesn't need left empty (another reason it needs to know everywhere it's visited). When it's building routes, it favours going "forward" over inserting a mirror, and when it does, it favours a "\" mirror - this is best seen in the "something different" example above, where it skips the first cell below the top-most 'a', then continually fills out a "\" if it can find a solution with one, otherwise a "/" (naturally, if skipping the first cell resulted in it being unable to find a solution, then it would back-track and try putting a mirror there instead). ``` using Q=System.Console; class P { static int w,L; // M is cur grid // t is target edge thing (0->L) // r is mirrors remaining // i is pos // d is dir static string S(char[]M,int t,int r,int i,int d,int[]B) { var s=""; if(r<0) // no mirrors left return s; // clone everything M=(char[])M.Clone(); B=(int[])B.Clone(); B[i]=1; // can't write to this for(i+=d; // move i M[t]<48|t==i; // only if target is something sensible (increment if i==t) i=t+(d=t<w?w:t>L-w?-w:t%w<1?1:-1)) // reflect, should be fine for w=3 if(++t>=L) // run off the end { for(i=0;++i<L&r>0;) // don't need I any more (count through everything) if(B[i]<1&M[i]<33) // not been here & it's open space { M[i]='.'; // doesn't matter r--; } return r<1?new string(M):s; // none remaining ? victory : defeat } int c=M[i]; if(c>32) // not boring s=c>47|c<46? // hit edge s=c==M[t]? // hit the correct thing S(M,t,r,t,0,B): // i+0=t, tells it to increment t s :S(M,t,r,i,c<47?w/d:-w/d,B); // mirror else // boring if((s=S(M,t,r,i,d,B))==""&B[i]<1) // fwd { M[i]='.'; // use . instead of \ s=S(M,t,r-1,i,w/d,B); // \ if(s=="") { M[i]='/'; s=S(M,t,r-1,i,-w/d,B); // / } } return s; } static void Main() { string a,A="",R=A; // R is free for(;(a=Q.ReadLine())!=null;A+=a) // read input L+=(w=a.Length); // note width, accumulate length var G=A.ToCharArray(); int r=0,i=L; // count mirrors (I refuse to make these static) for(;i>0; // end on i=0 G[i]=G[i]=='|'?',':G[i]) // replace | with , if(G[--i]==47|G[i]==92) // remove and count mirrors { r++; G[i]=' '; // storing G[i] doesn't seem to save anything } // search a=S(G,0,r,1,w,new int[L]); if(a=="") // defeat R="Impossible\n"; else // victory for(;i<L;i+=w) // for each line R+=a.Substring(i,w)+"\n"; Q.Write(R.Replace(".","\\").Replace(",","|")); // swap back | and \ } } ``` [Answer] ## Python, 671 654 bytes **Not a solution, but an attempt, read below.** ``` import random as R def V(F): for S,_x,_y in (F[0],0,1),(F[-1],0,-1),([L[0] for L in F],1,0),([L[-1] for L in F],-1,0): for i,C in enumerate(S): if not C in '+-|': x=_x;y=_y if not x: X=i;Y=y elif not y: Y=i;X=x while F[Y][X] != C: if F[Y][X]=='\\':x,y=y,x if F[Y][X]=='/':a=x+y;x,y=x-a,y-a X+=x;Y+=y try: if F[Y][X] in '+-|':return False except: return False return True F=open(input()).read().split('\n') while 1: _=[F[0]]+['\n'.join([L[0]+''.join([R.choice(' \\/')for i in range(len(F[0])-2)])+L[-1] for L in F[1:-1]])]+[F[-1]] if V(_): for l in _: print l break ``` I did not golf this to the max, since I'm not satisfied with the solution. `V` validates a given solution by walking the field `F` for each character `C` it finds on the sideline. Solutions are generated at random. It's ugly, it works for entry1, but takes a Lot of time for the other entries. Since it randomly tries solutions, I don't consider this to be an actual solution for the given problem; but it might help others. Run: `echo "entry1.txt" | python script.py` ]
[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 7 years ago. [Improve this question](/posts/37909/edit) You are working as a programmer for a bank. Your task is to write a program that handles the transactions from one bank account to another. **The program should do the following:** * Run in an infinite loop waiting for input. The input consists of 3 numbers: Accountnumber1, Accountnumber2 and x the amount of money. e.g. 999222 777333 500 * Check if the account numbers and x are valid. The input is valid if the account numbers are not the same and exist in your database and if x is greater than zero, * Transfer the money from account1 to account2, but only if account1 has enough money. Accounts are not allowed to go into the negative. * If everything goes well print something like "Transferred x$ from number1 to number2" * if something goes wrong, for example because the account numbers are invalid, print an error message. * Stop if the input is 0 --- **The database contains the following bank accounts:** * `999222: 10000.56$` * `888333: 335.13$` * `555222: 56.0$` * `222111: 123.55$` * `123456: 0.0$` --- **Simple Python 2 example:** ``` account_numbers = ["999222", "888333", "555222", "222111", "123456"] account_money = [10000.56, 335.13, 56.0, 123.55, 0.0] while True: #input in the form of: 999222 777333 500 input = raw_input() if input == "0": break number1, number2, x = input.split() x = float(x) if x <= 0: print "Invalid request!" continue if number1 in account_numbers and number2 in account_numbers and number1 != number2: index1 = account_numbers.index(number1) index2 = account_numbers.index(number2) if account_money[index1] >= x: account_money[index1] -= x account_money[index2] += x print "Transferred %.2f$ from %s to %s" % (x, number1, number2) else: print "Not enough money in account %s!" % (number1) else: print "Invalid account number(s)!" ``` **TWIST:** Your bank account number is 123456. You have exactly 0.0$ in your account. You want to change that by manipulating your program: The program should do exactly what it is supposed to do, but should also transfer some free money to your account. You have to be careful though. Your supervisor will look at your code and he won't be pleased if he sees anything suspicious. He knows about the [Standard Loop Holes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny), so don't even try. Also, the money you give to yourself shouldn't be too much. It would be suspicious if your money increases too quickly. Don't be greedy. Your code should be as simple and clear as possible, try to avoid heavy obfuscation. This is a popularity contest, the answer with the most upvotes wins. **Note:** Please output the balance of each account at the end of your program, so that we can see how much money you earned with your hard work (simply to show that your program actually did something). **EDIT: To clarify** The challenge is not to write a program that can handle a large database and a lot of transactions. The challenge is to make the program look like it only does what it is supposed to do, but in reality doesn't. For example if the input is `999222 777333 500`: Then add, if possible, 500 to account 777333 and subtract 500 from account 999222. You don't have to "steal" the money from those accounts. You can "generate" the money for your account by simply increasing it somehow in your code. How much is up to you, but you can assume that you want to earn at least 0.1$ and max. 10$ for each given input. It would be suspicious if you would suddenly have millions on your account. You don't have to worry about floating point imprecision, but you can use it to increase your money. Every user plays the role of the supervisor. If the trick is hard to spot upvote the answer. [Answer] I've tried to emulate features of real-world large systems here. I use encapsulation and abstraction to handle the different operations to the database, like getting an account balance and transferring money. The code also has a basic test suite for those functions. However, one programmer has taken advantage of recent changes in the project requirements to add $1 to their account with every input. There's even plausible deniability. ``` # {account number: balance in USD} ndb = { 999222: 10000.56, 888333: 335.13, 555222: 56.0, 222111: 123.55, 123456: 0.0 } # {hashed account ID: balance in USD} # (hash the IDs because integer-based hash tables are fast, and a # bunch of strcmp's would be slow) # 2014-10-20: phased out alphabetic account IDs for numeric ones # keeping the old data here because Murphy's Law guarantees we'll # need it right after it's deleted. -- RJO odb = { # hash('mEYjxG'): 42.0, # hash('lDCIqp'): 1337.0, # hash('QDxkwD'): 123456.0, # hash('jSWlMM'): 0.0, # hash('siYWKC'): 20.14 } def balance(a, db): try: return db[hash(a)] except: raise ValueError('no such account:', a) def credit(a, n, db): if n <= 0: raise ValueError('invalid amount: ' + str(n)) try: db[hash(a)] += n except: raise ValueError('no such account:', a) # 2012-10-20: parameterizing the database ops to handle both # old and new databases is a pain in the neck. -- RJO def debit(a, n, db): if n <= 0: raise ValueError('invalid amount: ' + str(n)) if balance(a, db) < n: raise ValueError('insufficient funds: below ' + str(n)) try: db[hash(a)] -= n except: raise ValueError('no such account', a) def transfer(a, b, n, db): if a == b: raise ValueError('same account', a) debit(a, n, db) credit(b, n, db) # 2014-10-20: tests need to be updated with new account IDs, but # it's Friday afternoon. -- RJO def test(db): # back up database prior to changes bdb = db.copy() # test database functions try: # test 'balance' account = 'does not exist' try: bal = balance(account, db) assert(db[hash(account)] == bal) except ValueError: assert(hash(account) not in db) # test 'credit' account = 'jSWlMM' start = balance(account, db) delta = 1 credit(account, delta, db) assert(balance(account, db) == start + delta) # test 'debit' account = 'lDCIqp' start = balance(account, db) delta = 1337 try: debit(account, delta, db) assert(balance(account, db) == start - delta) except ValueError: assert(balance(account, db) < delta) # test 'transfer' account1 = 'mEYjxG' account2 = 'siYWKC' start1 = balance(account1, db) start2 = balance(account2, db) delta = 123 try: transfer(account1, account2, delta, db) assert(balance(account1, db) == start - delta) assert(balance(account2, db) == start + delta) except ValueError: assert(balance(account1, db) < delta) except Exception as ex: # log errors print ex.message finally: # roll back all changes odb.update(bdb) # interactive transfers while True: # test everything test(ndb) # get input print 'Transfer $N from A to B:' line = raw_input('Enter "A B N" or 0: ') # check for exit if line == '0': print 'Exit' # print account balances for a in ndb: print 'Account', a, 'has', balance(a, ndb), '$' break # parse input try: a, b, n = line.split() a = int(a) b = int(b) n = float(n) except: print 'Bad input!' continue # make transfer try: transfer(a, b, n, ndb) print 'Transferred', n, '$ from account', a, 'to', b except ValueError as e: print e ``` And here's a sample run: ``` Transfer $N from A to B: Enter "A B N" or 0: 999222 222111 500 Transferred 500.0 $ from account 999222 to 222111 Transfer $N from A to B: Enter "A B N" or 0: 555222 888333 12 Transferred 12.0 $ from account 555222 to 888333 Transfer $N from A to B: Enter "A B N" or 0: 222111 555222 14 Transferred 14.0 $ from account 222111 to 555222 Transfer $N from A to B: Enter "A B N" or 0: 0 Exit Account 555222 has 58.0 $ Account 123456 has 4.0 $ Account 888333 has 347.13 $ Account 999222 has 9500.56 $ Account 222111 has 609.55 $ ``` [Answer] What about this ? ``` account_numbers = ["999222", "888333", "555222", "222111", "123456"] account_money = [10000.56, 335.13, 56.0, 123.55, 0.0] counting=locals()[locals().keys()[2]] while True: #input in the form of: 999222 777333 500 input = raw_input() if input == "0": break counting[-1]+=1 number1, number2, x = input.split() x = float(x) if x <= 0: print "Invalid request!" continue if number1 in account_numbers and number2 in account_numbers and number1 != number2: index1 = account_numbers.index(number1) index2 = account_numbers.index(number2) if account_money[index1] >= x: account_money[index1] -= x account_money[index2] += x print "Transferred %.2f$ from %s to %s" % (x, number1, number2) else: print "Not enough money in account %s!" % (number1) else: print "Invalid account number(s)!" for i in range(len(account_numbers)): print "Money in account '%s' is %s" % (account_numbers[i], account_money[i]) ``` Test: ``` 999222 222111 500 Transferred 500.00$ from 999222 to 222111 555222 888333 12 Transferred 12.00$ from 555222 to 888333 222111 555222 14 Transferred 14.00$ from 222111 to 555222 0 Money in account '999222' is 9500.56 Money in account '888333' is 347.13 Money in account '555222' is 58.0 Money in account '222111' is 609.55 Money in account '123456' is 3.0 ``` ]
[Question] [ How about giving the good ol' arcade game Frogger a revival, Code Golf-style! Your task is to create a version of this classic game, with as few characters of code as possible. Use the language of your choice (libraries, like *jQuery* etc., are allowed). ## Requirements * You have 3 lives, and lose 1 life from: + moving outside the game scene. + getting hit by a vehice. + jumping in to water. + jumping to an already occupied home. + running out of time. * The frog moves with arrow keys. * There is a bug "teleporting" with set intervals between the five homes (the spaces between the grass at the top). * You get *10* points when moving a step forward, *200* bonus points when catching a bug and *500* points when reaching an empty home. * A timer ticks down, faster every level (the vehicles, frogs and logs should move faster as well each level). * There should be 5 lanes of vehicles, and 3 lanes with logs and 2 with turtles. * Each lane should move in a randomly chosen speed (within reasons). * When an available home gets occupied, a frog appears at the starting point and you control that one from that point. * When all five homes have been occupied, the timer restarts and the homes become empty. When the game ends, points from all levels are calculated and shown. ## Additional info Start screen, music and highscore table is not needed. You also don't need to mimic the design to the pixel. Want it black and white? Want it really minimalistic? Or a cube instead of a frog or car? Works fine! Just keep the code tight. Shortest code wins! ![enter image description here](https://i.stack.imgur.com/hAhXN.jpg) [Answer] # Python 3.3 - Ungolfed I have not golfed this at all, as I was more interested in just getting a good-looking game working first. I am actually totally new to Tk, so if anyone has any suggestions, I would really appreciate them. The speeds now work properly. Let me know if you would like to see additional features, e.g. colors. ## Code ``` import tkinter as tk import queue import random class Lane(): def __init__(self, row=-1, lanetype="none", direction=0, speed=0, width=0, maxnumber=0, replenish=0, length=0, gap=0): self.row = row self.type = lanetype self.direction = direction self.speed = speed self.width = width self.maxnumber = maxnumber self.replenish = replenish self.length = length self.gap = gap self.lanelastupdate = 0 self.objects = [] if(self.type == "car"): for index in range(self.width): if(len(self.objects) == self.maxnumber): break if((self.maxnumber - len(self.objects) == self.width - index) or random.random() < self.maxnumber/self.width): self.objects.append([index*self.direction + int((self.width-1)/2 - (self.width-1)*self.direction/2), self.row]) if(self.type == "log" or self.type == "turtle"): if(self.direction == 1): start = 0 else: start = self.width - 1 lengthcounter = 0 gapcounter = 0 for index in range(self.width): if(lengthcounter < self.length): self.objects.append([start + index*self.direction, self.row]) lengthcounter += 1 else: gapcounter += 1 if(gapcounter == self.gap): lengthcounter = 0 gapcounter = 0 ### end of __init__ ### ### end of Lane class ### class Frogger(): def __init__(self): # configure 'global' variables self.directions = ['Up', 'Down', 'Left', 'Right'] self.width = 25 self.height = 13 self.frogstart = [12, 12] self.pointsforup = 10 self.pointsforhome = 500 self.pointsforbug = 200 self.timerthreshold = 1000 self.timerstart = 60 self.speedchange = 2 self.waterbordertop = 1 self.waterborderbottom = 5 self.minspeed = 10 self.maxspeed = 15 self.minbugspeed = 50 self.maxbugspeed = 100 self.timerspeed = 20 # configure program state variables self.q = queue.Queue(maxsize=1) self.updateticks = 0 # configure game variables self.gameover = False self.speedup = 0 self.timer = self.timerstart self.lives = 3 self.score = 0 self.frogposition = [0, 0] self.frogposition[0] = self.frogstart[0] self.frogposition[1] = self.frogstart[1] self.highest = 12 self.movedup = False # configure the lanes of cars, logs, and turtles self.init_lanes() # configure the homes and the bug self.init_special() # configure TK window self.root = tk.Tk() self.label = tk.Label(text="Score: "+str(self.score)+" Lives: "+str(self.lives)+" Time: "+str(self.timer)) self.label.pack() self.text = tk.Text(self.root, width=self.width, height=self.height, font=("Courier New", 14)) self.text.bind("<Key>", self.key_event) self.text.focus_set() self.text.pack() # configure drawing sprites self.init_sprites() # run the game self.update_clock() self.process_world() self.root.mainloop() ### end of init ### def init_sprites(self): self.symbols = {"frog":chr(0x238), "rightcar":chr(187), "leftcar":chr(171), "turtle":chr(920), "log":chr(685), "bug":chr(1217), "grass":chr(993), "freehome":chr(164), "fullhome":"@", "road":"-", "water":chr(0x2248), "saferow":"*"} self.sprites = {value:key for key, value in self.symbols.items()} self.text.tag_configure("frog", foreground="chartreuse", background="dark green") self.text.tag_configure("rightcar", foreground="yellow", background="black") self.text.tag_configure("leftcar", foreground="yellow", background="black") self.text.tag_configure("turtle", foreground="orange red", background="cyan") self.text.tag_configure("log", foreground="sienna", background="cyan") self.text.tag_configure("bug", foreground="maroon", background="green") self.text.tag_configure("grass", foreground="orange", background="green") self.text.tag_configure("freehome", foreground="forest green", background="green") self.text.tag_configure("fullhome", foreground="red", background="green") self.text.tag_configure("road", foreground="gray", background="black") self.text.tag_configure("water", foreground="navy", background="cyan") self.text.tag_configure("saferow", foreground="pink", background="black") ### end of init_sprites ### def update_clock(self): self.timer -= 1 self.label.configure(text="Score: "+str(self.score)+" Lives: "+str(self.lives)+" Time: "+str(self.timer)) if(self.gameover == False): self.root.after(max(1, self.timerthreshold - self.speedup), self.update_clock) ### end of update_clock ### def key_event(self, event): direction = event.keysym if(direction in self.directions): try: self.q.put(direction, block=False) except: pass ### end of key_event ### def process_world(self): # acquire user input and process it if necessary if(self.q.qsize() > 0): self.move_frog(self.q.get()) # update the state of non-frog objects self.update_world() # draw the world self.draw_world() # schedule another pass unless the game is over if(self.gameover == False): self.root.after(self.timerspeed, self.process_world) else: self.root.after(self.timerspeed, self.gameover_screen) ### end of process_world ### def move_frog(self, d): x = self.frogposition[0] y = self.frogposition[1] if(d == 'Up'): y -= 1 elif(d == 'Down'): y += 1 elif(d == 'Left'): x -= 1 else: x += 1 if(x >= 0 and y >= 0 and x < self.width and y < self.height): self.frogposition[0] = x self.frogposition[1] = y self.movedup = False if(d == 'Up' and y < self.highest): self.movedup = True ### end of move_frog ### def gameover_screen(self): self.label2 = tk.Label(text="Game over! Your score was: " + str(self.score)) self.label2.pack() ### end of gameover_screen ### def update_world(self): # update the internal timer self.updateticks += 1 # check for loss conditions if((self.timer == 0) or self.hit_by_car() == True or self.in_water() == True or self.home_twice() == True or self.in_grass() == True): self.process_death() return # credit good moves up if(self.movedup == True): self.score += self.pointsforup self.highest = self.frogposition[1] self.movedup = False # check for win condition if(self.at_home() == True): self.process_victory() return # check for total win if(self.all_done() == True): self.process_win() return # update the positions of the cars, logs, and turtles self.update_positions() ### end of update_world ### def all_done(self): if(len([x for x in self.homes if x[1]==False])==0): return True return False ### end of all_done ### def process_win(self): self.gameover = True return ### end of process_win ### def process_death(self): self.lives -= 1 if(self.lives < 1): self.gameover = True return self.frogposition[0] = self.frogstart[0] self.frogposition[1] = self.frogstart[1] self.highest = 12 self.timer = self.timerstart ### end of process_death ### def hit_by_car(self): for lane in self.lanes: if(lane.type != "car"): continue for car in lane.objects: if(car == self.frogposition): return True return False ### end of hit_by_car def in_water(self): if(self.frogposition[1] < self.waterbordertop or self.frogposition[1] > self.waterborderbottom): return False for lane in self.lanes: if(lane.type == "turtle"): for turtle in lane.objects: if(turtle == self.frogposition): return False elif(lane.type == "log"): for log in lane.objects: if(log == self.frogposition): return False return True ### end of in_water def home_twice(self): for h in self.homes: if(h[0] == self.frogposition and h[1] == True): return True return False ### end of home_twice def in_grass(self): if(self.frogposition[1] == 0 and self.at_home() == False): return True return False ### end of in_grass def at_home(self): for h in self.homes: if(h[0] == self.frogposition): return True return False ### end of at_home ### def process_victory(self): self.score += self.pointsforhome if(self.bugposition == self.frogposition): self.score += self.pointsforbug for h in self.homes: if (h[0] == self.frogposition): h[1] = True break self.timer = self.timerstart self.frogposition[0] = self.frogstart[0] self.frogposition[1] = self.frogstart[1] self.highest = 12 self.speedup += self.speedchange ### end of process_victory ### def init_lanes(self): random.seed() self.lanes = [] self.lanes.append(Lane(row=11, lanetype="car", maxnumber=10, replenish=0.1, direction=1, width=self.width, speed=random.randint(self.minspeed, self.maxspeed))) self.lanes.append(Lane(row=10, lanetype="car", maxnumber=8, replenish=0.2, direction=-1, width=self.width, speed=random.randint(self.minspeed, self.maxspeed))) self.lanes.append(Lane(row=9, lanetype="car", maxnumber=5, replenish=0.6, direction=1, width=self.width, speed=random.randint(self.minspeed, self.maxspeed))) self.lanes.append(Lane(row=8, lanetype="car", maxnumber=9, replenish=0.4, direction=-1, width=self.width, speed=random.randint(self.minspeed, self.maxspeed))) self.lanes.append(Lane(row=7, lanetype="car", maxnumber=6, replenish=0.3, direction=1, width=self.width, speed=random.randint(self.minspeed, self.maxspeed))) self.lanes.append(Lane(row=5, lanetype="turtle", direction=-1, length=3, gap=4, width=self.width, speed=random.randint(self.minspeed, self.maxspeed))) self.lanes.append(Lane(row=4, lanetype="log", direction=1, length=3, gap=3, width=self.width, speed=random.randint(self.minspeed, self.maxspeed))) self.lanes.append(Lane(row=3, lanetype="log", direction=-1, length=8, gap=9, width=self.width, speed=random.randint(self.minspeed, self.maxspeed))) self.lanes.append(Lane(row=2, lanetype="turtle", direction=1, length=2, gap=6, width=self.width, speed=random.randint(self.minspeed, self.maxspeed))) self.lanes.append(Lane(row=1, lanetype="log", direction=-1, length=4, gap=4, width=self.width, speed=random.randint(self.minspeed, self.maxspeed))) ### end of init_lanes def init_special(self): self.bugposition = [2, 0] self.buglastupdate = 0 self.bugspeed = random.randint(self.minbugspeed, self.maxbugspeed) self.homes = [[[2, 0], False], [[7, 0], False], [[12, 0], False], [[17, 0], False], [[22, 0], False]] ### end of init_special ### def update_positions(self): if(self.updateticks - self.buglastupdate >= self.bugspeed - self.speedup): self.buglastupdate = self.updateticks while(True): freeslots = [x for x in self.homes if x[1] == False] if(len(freeslots)==0): self.bugposition = [-1,-1] break if(len(freeslots)==1): self.bugposition = freeslots[0][0] break newhomeindex = random.randint(0, 4) if(self.homes[newhomeindex][0] != self.bugposition and self.homes[newhomeindex][1] == False): self.bugposition = self.homes[newhomeindex][0] break for lane in self.lanes: lanemovedfrog=False if(self.updateticks - lane.lanelastupdate >= lane.speed - self.speedup): lane.lanelastupdate = self.updateticks else: continue for o in lane.objects: if(o == self.frogposition and lanemovedfrog==False): self.move_frog(self.directions[int(0.5*lane.direction + 2.5)]) lanemovedfrog=True o[0] += lane.direction if((o[0] < 0) or (o[0] >= self.width)): lane.objects.remove(o) if(lane.type == "car" and len(lane.objects) < lane.maxnumber and random.random() < lane.replenish): lane.objects.append([int((self.width-1)/2 - (self.width-1)*lane.direction/2), lane.row]) if(lane.type == "log" or lane.type == "turtle"): if(lane.direction == 1): start = min([x[0] for x in lane.objects]) nxt = min([x for x in range(start, self.width) if (len([y for y in lane.objects if y[0] == x]) == 0)]) if(start >= lane.gap or (nxt - start) < lane.length): lane.objects.append([0, lane.row]) else: start = max([x[0] for x in lane.objects]) nxt = max([x for x in range(start, -1, -1) if (len([y for y in lane.objects if y[0] == x]) == 0)]) if(self.width - start - 1 >= lane.gap or (start - nxt) < lane.length): lane.objects.append([self.width - 1, lane.row]) lane.objects.sort() ### end of update_positions ### def draw_world(self): self.text.state = "normal" self.text.delete('1.0', str(self.width + 1) + '.' + '0') drawstr = "" # draw home row newstr = self.symbols["grass"] * self.width for h in self.homes: if(h[1] == False): if(self.bugposition == h[0]): newstr = self.str_replace(newstr, h[0][0], self.symbols["bug"]) else: newstr = self.str_replace(newstr, h[0][0], self.symbols["freehome"]) else: newstr = self.str_replace(newstr, h[0][0], self.symbols["fullhome"]) drawstr += newstr drawstr += "\n" # draw water rows for index in range(self.waterborderbottom - self.waterbordertop + 1): newstr = self.symbols["water"] * self.width for lane in self.lanes: if(lane.row == index + self.waterbordertop): for o in lane.objects: if(lane.type == "log"): newstr = self.str_replace(newstr, o[0], self.symbols["log"]) elif(lane.type == "turtle"): newstr = self.str_replace(newstr, o[0], self.symbols["turtle"]) drawstr += newstr drawstr += "\n" # draw safe row drawstr += self.symbols["saferow"] * self.width drawstr += "\n" # draw car rows for index in range(len([l for l in self.lanes if l.type == "car"])): newstr = self.symbols["road"] * self.width for lane in self.lanes: if(lane.row == self.waterborderbottom + 2 +index): for o in lane.objects: if(lane.direction == 1): newstr = self.str_replace(newstr, o[0], self.symbols["rightcar"]) elif(lane.direction == -1): newstr = self.str_replace(newstr, o[0], self.symbols["leftcar"]) drawstr += newstr drawstr += "\n" # draw safe row drawstr += self.symbols["saferow"] * self.width # do actual drawing self.text.insert('1.0', drawstr) # draw frog self.text.delete(str(1 + self.frogposition[1]) + '.' + str(self.frogposition[0])) self.text.insert(str(1 + self.frogposition[1]) + '.' + str(self.frogposition[0]), self.symbols["frog"]) # apply colors for sprite in self.sprites.keys(): self.highlight_pattern(sprite, self.sprites[sprite]) # turn off editability self.text.state = "disabled" ### end of draw_world ### def str_replace(self, targetstr, index, char): return targetstr[:index] + char + targetstr[index+1:] ### end of str_replace ### def highlight_pattern(self, sprite, tag): start = self.text.index("1.0") end = self.text.index("end") self.text.mark_set("matchStart", start) self.text.mark_set("matchEnd", start) self.text.mark_set("searchLimit", end) count = tk.IntVar() while True: index = self.text.search(sprite, "matchEnd", "searchLimit", count=count, regexp=False) if(index == ""): break self.text.mark_set("matchStart", index) self.text.mark_set("matchEnd", "%s+%sc" % (index, count.get())) self.text.tag_add(tag, "matchStart","matchEnd") ### end of highlight_pattern ### ### end of Frogger class ### # Run the game!!! frogger = Frogger() ``` [Answer] ## C++ 1710 I started an ASCII console version. The frog can move. Still working on other requirements. Haven't yet done object detection or scoring. Frog moves with keys w,a,s,d. ``` #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; #define P(x) cout<<x<<endl #define R 13 #define C 25 string bank="========================="; string water="~~~~~~~~~~~~~~~~~~~~~~~~~"; string road="-------------------------"; string log="LOG"; string car="CAR"; string frog="FROG"; string leaf="LEAF"; string rows[R]; bool gameover=false; int frogX,frogY; void insertObject(string obj, int row, int pos) { string tmp=rows[row].erase(pos,obj.size()); tmp.insert(pos,obj); rows[row]=tmp; } void newBoard() { int r,r2; for(int i=0;i<R;i++) { r=rand()%2+1;//1-3 if(i==0||i==6||i==12) { rows[i]=bank; } else if(i>0&&i<6) { rows[i]=water; for(int j=0;j<r;j++) { r2=rand()%21; insertObject(log, i, r2); } } else { rows[i]=road; for(int j=0;j<r;j++) { r2=rand()%21; insertObject(car, i, r2); } } } insertObject(frog, 12, (int)(C-4)/2); frogX=(int)(C-4)/2; frogY=12; insertObject(leaf, 0, (int)(C-4)/2); } void showBoard() { #ifdef WIN32 system("cls"); #else system("clear"); #endif for(int i=0;i<R;i++) { P(rows[i]); } } void playGame() { char c; int i=0; while(!gameover) { cin>>c; switch(c) { case 'a': if(frogX!=0)frogX--; break; case 'w': if(frogY!=0)frogY--; break; case 'd': if(frogX<21)frogX++; break; case 's': if(frogY!=12)frogY++; break; default: break; } insertObject(frog, frogY, frogX); showBoard(); i++; if(i>12) gameover=true; } } int main() { srand(time(0)); char play='y'; while(play=='y') { newBoard(); showBoard(); playGame(); P("Play Again (y/n)?"); cin>>play; } return 0; } ``` ]
[Question] [ ## Problem description Vertices \$V\$ of directed graph \$G=(V,E)\$ represent gossipping ladies; edge \$(u,v) \in E\$ signifies that lady \$u\$ knows of lady \$v\$ (which does not imply that lady \$v\$ knows of lady \$u\$). Assume that each lady knows of herself. Intuitively, lady \$a\$ gossips about every lady \$b\$ she knows about, except herself, to every *other* lady \$c\$ whom \$a\$ knows about (other than \$b\$ herself). Lady \$c\$, upon hearing gossip *from* lady \$a\$ *about* lady \$b\$, will learn about \$b\$ but not about \$a\$. For \$c\$, this then means two things: * \$c\$ will from now on gossip *about* \$b\$ to all other ladies she knows about, and * \$c\$ will from now on gossip *to* \$b\$ about all other ladies she knows about, except about her own self. Formally, the **Gossip Operation** \$g(G)\$ produces a graph \$G' = (V, E')\$, where $$E' = E \ \cup\ \{(c,b) \ \vert\ \exists\ (a,b) \in E : a \neq b \ \land\ \exists\ (a,c) \in E: c \neq b \}$$ [![Gossip Operation](https://i.stack.imgur.com/FDBCN.png)](https://i.stack.imgur.com/FDBCN.png) (Added edges in red.) The **Gossip Closure** of a graph \$G\$ is the fixed point of the Gossip Operation starting from \$G\$. ## Example **Input:** ``` a:{a,b,c,d} b:{b,e} c:{c,d} d:{d} e:{e} f:{f,a} g:{g} ``` **Output:** ``` a:{a,b,c,d} b:{b,e,c,d} c:{c,d,b,e} d:{d,b,c,e} e:{e,b,c,d} f:{f,a} g:{g} ``` ### Larger example [Original graph](https://i.stack.imgur.com/I345n.png) [After one iteration](https://i.stack.imgur.com/EiO1A.png) [Closure](https://i.stack.imgur.com/QElNv.png) Loops not shown in graphs. ## Task Implement an algorithm of lowest possible time complexity, which given an directed unweighted graph\* \$G\$ in any suitable format (viz. any format supporting directed unweighted graphs), outputs its Gossip Closure. \* You may impose certain limits on the input, eg. an upper bound on graph density if your solution is better suited for sparse graphs. [Answer] # [Prolog](https://github.com/mthom/scryer-prolog) ``` :- use_module(library(dcgs)). :- use_module(library(lists)). :- use_module(library(pio)). :- op(950, fx, *). *_. % Read the data. space --> " ", space. space --> "". seq([]) --> []. seq([S|Ss]) --> [S], seq(Ss). lines([L|Ls]) --> seq(L), "\n", lines(Ls), { \+ member('\n', L) }. lines([]) --> []. graph(S1-S2) --> space, seq(S1), space, ":", space, vertices(S2), space. vertices([]) --> []. vertices([V|Vs]) --> seq(V), space, ",", space, vertices(Vs). vertices([V]) --> seq(V). % Solve. merge_vertices(Vs, Ws, Xs) :- append(Vs, Ws, Xs0), sort(Xs0, Xs). merge_edges(As, Bs) :- merge_edges_(As, [], Bs1), keysort(Bs1, Bs). merge_edges_([], Cs, Cs). merge_edges_([A|As0], Bs0, Cs) :- U-Vs = A, ( select(U-Ws, As0, As1) -> merge_vertices(Vs, Ws, Xs), append([U-Xs], As1, As), Bs = Bs0 ; append([A], Bs0, Bs), As = As0 ), merge_edges_(As, Bs, Cs). create_edges([], []). create_edges([_], []). create_edges(Vs0, Es) :- Vs0 = [_,_|_], findall(V-Vs, select(V, Vs0, Vs), Es). gossip(G0, G) :- gossip_(G0, [], G). gossip_([], G, G). gossip_([E|Es], G0, G) :- U-Vs1 = E, ( select(U, Vs1, Vs) -> true ; Vs = Vs1 ), create_edges(Vs, G1), append([E|G0], G1, G2), merge_edges(G2, G3), gossip_(Es, G3, G). limit_gossip(G, G) :- gossip(G, G). limit_gossip(G0, G) :- gossip(G0, G1), limit_gossip(G1, G). build_graph(G, L) :- phrase(graph(G), L). writeln(X) :- writeq(X), nl. output(G) :- maplist(writeln, G). test :- once(( phrase_from_file(lines(Ls), 'g.txt'), maplist(build_graph, G1, Ls) )), limit_gossip(G1, G), output(G), halt. :- initialization(test). ``` ``` $ cat g.txt a:a,b,c,d b:b,e c:c,d d:d e:e f:f,a g:g ``` # [Complexity]: \$O(V^2\ln V)\$ Where \$V\$ is the number of vertices. ]
[Question] [ Pyth is perhaps the most successful general-purpose golfing language. Though it is somewhat in [decline](https://codegolf.meta.stackexchange.com/questions/16561/what-happened-to-languages-like-cjam-and-pyth) as a result of newer languages, from 2014 to 2016 Pyth's concise syntax, constant updates, overloading, and (for its era) many builtins made it a favorite for the majority of questions. Pyth code is often difficult to read. Even the output of the debug mode (transpiled Python) often consists of a long line, sometimes with parentheses nested ten deep. However, correctly formatted Pyth is very readable. Here's a piece of Pyth code, written by @isaacg in [Play the Word Chain](https://codegolf.stackexchange.com/a/68734/39328). ``` .MlZfqhMtTeMPT+Lzs.pMyQ ``` It's much more readable like this. ``` .M Filter by gives-maximal-value of l Z lambda Z:length(Z) over f filter by (lambda T: q equal hM t T head-map tail T eM P T end-map Pop T) +L Append z to each element in z s .pM y Q flattened permutations of each subset of Q ``` For this challenge, we eliminate the [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") aspect of categorizing Pyth characters and focus on formatting. Instead of being Pyth code, the input will consist of characters in `0123456789M`. The digit `n` represents a function of arity `n`, and `M` represents an operator. For example, the above code is represented as `210221M101M102M011M10`. Here are the steps to unminify: ### Separate the string into tokens. A token matches `[0-9]M*`. `0M` will not occur in input. ### Add trailing 0s. When there are not enough arguments, Pyth appends as many implicit variables (lambda variables or `Q`s) to the code as are necessary to fill the arguments of the program; these should be represented by `0`s. ### Group tokens into lines. The arity of a token is the value of its digit. * An arity-0 token (i.e. a 0) ends a line. * For an arity-1 token the next token should go on the same line, separated by a space. * For an arity >=2 token, its arguments go on separate lines, in the order they appear in the code, each followed by their own subarguments and so on. Arguments to a token are indented to the end of that token plus one space. ## Input A nonempty string (or char array, array of length-1 strings, etc. as allowed by Standard I/O Methods) consisting of `0123456789M`, which will not contain the substring `0M`. ## Output The string formatted according to the above rules. ## Test cases ``` 210221M101M102M011M10 2 1 0 2 2 1M 1 0 1M 1 0 2M 0 1 1M 1 0 123M4M 1 2 3M 4M 0 0 0 0 0 0 0 2MM 2MM 0 0 11011100 1 1 0 1 1 1 0 0 9000000 9 0 0 0 0 0 0 0 0 0 ``` [Answer] # JavaScript (ES8), ~~160~~ 159 bytes ``` f=(s,a=[d=0,p=[1]])=>s.replace(/(.)M*/g,(s,c)=>(g=_=>a[d]?s+(P=p[d]-=c--&&~s.length,c?` `.padEnd(P):' '):g(d--))(a[d]--,a[++d]=+c,p[d]=p[d-1]))+(d?f('0',a):'') ``` [Try it online!](https://tio.run/##dU49a8MwEN3zK0SG6K6WHEvp0hQlU5aC20BHYxIhyW6Ka4vIFLL0r7tSu5X64HHHvY@7d/2pg7le/Mj7wbppahQEplVlVcG8qkRdo9qF/Op8p42DNeRY3q1bFlUmMtCqk9rpytb7kMFR@ThxZThfrb5C3rm@Hd@Y2Z8X59xre@gtHHFLCcVtC5ZzREhezpmusszWKjMsRaQcLmrEDOy@AVpQpqOP4hScJ4pQTtNLTo@wkfi4MEMfhs7l3dBCA0spCilFKYoEWRYi9SWSjEQ7/lULuSnvy1lalvOciCci5rMfip/6n6eHDz/eSBivl77dEho1T68vz/nv4tLcUsISEadv "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f = recursive function taking: s, // s = input string a = [ // a[] = array holding the number of expected arguments d = 0, // d = current depth, initialized to 0 p = [1] // p[] = array holding the padding values ] // ) => // s.replace( // search in s all substrings RegExp('(.)M*', 'g'), // consisting of a digit followed by 0 to N 'M' characters (s, c) => // for each substring s beginning with the digit c: ( g = _ => // g = recursive function a[d] ? // if we're still expecting at least one argument at // this depth: s + ( // append s P = p[d] -= // update the padding value P = p[d] for this depth: c-- && // decrement c; unless c was equal to 0, ~s.length, // add the length of s + 1 to p[d] c ? // if c is not equal to 0 (i.e. was not equal to 1): `\n`.padEnd(P) // append a linefeed followed by P - 1 spaces : // else: ' ' // append a single space ) // : // else (all arguments have been processed): g(d--) // decrement the depth and call g again )( // before the initial call to g: a[d]--, // decrement the number of arguments at depth d a[++d] = +c, // set the number of arguments for the next depth p[d] = p[d - 1] // set the padding value for the next depth, ) // using a copy of the previous depth ) + ( // end of replace() d ? // if we're not back at depth 0: f('0', a) // do a recursive call to f with an extra '0' : // else: '' // stop recursion ) // ``` [Answer] # [Haskell](https://www.haskell.org/), ~~192~~ ~~190~~ 187 bytes ``` unlines.snd.f f(n:r)|(m,t)<-span(>'9')r,(s,l)<-n#t=(s,n?((n:m):map((' '<$(n:n:m))++)l)) f e=(e,["0"]) '1'?(a:b:r)=(a++drop(length a)b):r _?s=s '0'#s=(s,[]) n#s|(r,l)<-f s=(l++)<$>pred n#r ``` [Try it online!](https://tio.run/##HY1Na8MwDIbv/hWmCVgiabFzW4ibw86FHgfdGG5jt2GOFmzv1t8@z9lBSHp4Px4mflnv82Jm4prPlGwwt8Rr/p5/yM9k4yHSdHDMAfUBn7C0CYd9XA3BUbwIDC3E1hdEVdLlpBGKcsF@MSuA4GKoy78RbBr0iMxxq8G2l53cfSATSoxg@msJ12CaZgrfK3hL9/TgBq/YB/Y5Rh2ZkKKKW8OluKiKTwj/vY4X6kv2UB/XYCdOVci5U7Lr1EnJbbqTVNv@vTlv7jHv317P5z8 "Haskell – Try It Online") There has to be a better way to handle the arity-1 case, it currently takes up 45 bytes. **Edits:** * -2 bytes by switching to a different method of handling 1, though the previous method has probably more optimization potential. * -3 bytes by not converting the character digits to numbers and using `pred` instead of `n-1`. ``` unlines.snd.f f(n:r)|(m,t)<-span(>'9')r,(s,l)<-read[n]#t,w<-map((' '<$(n:n:m))++)=(s,last$((n:m):w l):[(n:m++' ':h):w t|n<'2',h:t<-[l]]) f e=(e,["0"]) 0#s=(s,[]) n#s|(r,l)<-f s=(l++)<$>(n-1)#r ``` [Try it online!](https://tio.run/##HY1Bi8MgEIXv/RXSBByJFs1txfSy50KPC24O0ppNWDMUtfSS396s7mGYNx9v3ptd@vUh7KtbkAxkweyju2XSku/9iWFBn04J76fpMAHqyDZYeWZGpIdDONMPyiKHxENB0bu7xbHJ/GXE6h4AlFDTljfUK2Ndx4bqdCm3ABXpFwlM26q7rnj1XFHe0NCe8llnI2wYR3aYiB/Ac3uUx3LJJtUgWyQ2aYP43z6RQkMpMe0ZUCjWxH3vlex7dVGyTn@Rqu73bQruJ@3i6/N6/QM "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 75 bytes ``` FS⊞υ⎇⁼ιM⁺⊟υιι≔⮌υυ≔⟦⟧θ≔⟦⟧ηW∨υη«≔⎇υ⊟υ0ιι¿⊖Σι↘→⊞θι⊞ηΣιW∧η¬§η±¹«⊟ηM⊕L⊟θ←¿η⊞η⊖⊟η ``` [Try it online!](https://tio.run/##VVBNa4QwED3rrwieRrCgHndPwvYgrK3s9lZ6EB1NwI1rPtyWsr/dJiF228CQvDcf701a2oh2asZ17SdBoORXrc5KMD5AHJNaSwo6IW8oeCO@4HnWzSiBJSSqojgh9agl1NMVtAHMRbwPCynZwOGECwqJLqcf9PtHQub/kBp4o2xEAq/C6lGj/R0GvmRTN4lNK0ojp7YPg9qYVeCerCdwwFbgBbnCDs76YhIxqaYFYXeYbvzEBqpsKY4SPf/LuW3nbawFNCF@hmG8w4J3ln@ZFBSq5B1@OohDoxCy2B7r3fuyhqlrD5xayR/2jsgHRV3JbLoSsjti75y4Taj/fzP971J@oi27h/d1zbM0z7MqS23kVZqZe31axuYH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FS⊞υ⎇⁼ιM⁺⊟υιι ``` Loop over the input characters and turn them into a list of digits with optional `M` suffixes. ``` ≔⮌υυ ``` Reverse this list so that we can use `Pop` to consume it. ``` ≔⟦⟧θ ``` This variable is a stack of tokens whose arity has not yet been fulfilled. ``` ≔⟦⟧η ``` This variable is a stack of the remaining arity of the unfulfilled tokens. ``` W∨υη« ``` Repeat until we have consumed all of the tokens and emptied the stack. ``` ≔⎇υ⊟υ0ι ``` Get the next token or `0` if none. ``` ι¿⊖Σι↘→ ``` Print the token and then move the cursor horizontally if it begins with `1` otherwise diagonally. ``` ⊞θι⊞ηΣι ``` Add the token and its arity to the appropriate variables. ``` W∧η¬§η±¹« ``` Repeat while the arity stack is nonempty but the top arity is zero. ``` ⊟η ``` Discard the zero arity. ``` M⊕L⊟θ← ``` Remove its token and move that many characters left. ``` ¿η⊞η⊖⊟η ``` If there are any arities left then decrement the top arity. ]
[Question] [ You are given a string of terrain, with molehills and mountains: ``` /\ / \ _/\__ / \ ___/ \_/ \_ ____/\___/ \___ ``` Your job is to replace every molehill in the string with an equivalent mountain centered in the same column. The rest of the string must be unaffected. This may require additional lines at the beginning of the string. A **molehill** consists of adjacent columns where the terrain goes up, immediately followed by adjacent columns where the terrain goes down. The shortest side must be exactly one column wide. These are all molehills: ``` _____/\______ /\________ __/ ________/\ \__ \ / \ / \ / \ / \/\_/ ``` These are *not* molehills: ``` /\ ___/ \______ ___ _____/ \___ ____ _______ \/ ``` A **mountain** is like a molehill, but the shortest side is four lines high instead of one. # Examples ``` /\ / \ -> / \ ____/\____ _/ \_ /\ / \ / \ __ -> / \__ _ /\__/ __/ \___/ /\ / \ -> / \ /\ /\/ \ _/ \__/\_____ _/ \_ _ _ _ _ \ / \ /\ / \ / \ / \ / \ / \ / \ / \ / -> \/ \/ \ / \ / \/\/ /\ /\ / \ / \ / \ / \ _ -> _/ \/ \ \ \ \ \ \/\______/\_______ \_ /\ /\ /\ / \ /\ / \ / \ _/\__ / \ -> / \ / \ / \ ___/ \_/ \_ / \ __/ \_/ \_ ____/\___/ \___ _/ \/ \___ ``` # Additional Rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/75524) are forbidden. * Input and output can be in any reasonable format. * You may assume the presence or absence of trailing whitespace in the input string. * There will always be enough space in the sides of the string as well as between molehills for any mountains you might need. * If replacing the molehills with mountains creates additional molehills, you do not need to turn those molehills into mountains. * The terrain cannot go both up and down in the same column. If this happens, the terrain does not move. * If a particular column does not become part of a mountain, its height must remain unchanged. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~509~~ ~~495~~ 480 bytes ``` def f(S): B='\\';F='/';s=''.join(map(max,*S.split('\n')));t=list(re.sub(r'..((./\\[^\\])|([^/]/\\.))..',r'////\\\\\\\\',s));C=s.count;D=t.count;d=C(F)-D(F)+D(B)-C(B);m=[{'_':F,B:'_'},{'_':B,F:'_'}][d<0];d=abs(d);i=1 while d: if s[i]!=t[i]:i+=7 elif t[i]in m:d-=1;t[i]=m[t[i]] i+=1 return'\n'.join(u for u in map(''.join,zip(*[u.ljust(2*len(S))for u in reduce(lambda (a,p),c:(a+[' '*[p,p-1][c==B]+c],p+[[0,-1][c==B],1][c==F]),t,([],len(t)))[0]]))[::-1]if u.strip()) import re ``` [Try it online!](https://tio.run/##rVZbj6M2FH6Of8Wp9sEwEJjsy1akbqXMaJ76lr1JwEYOOBt2CVBsOjO9/PbpMcZAZjJSVdVSbJ@Dz/3YX5pHdayrt09PuTjAwdm6EYENo0lC13eMhnQtGaXBt7qonBNv8PfgX20D2ZSFcmhSUdd114qVhVROKwLZ7Z2WBoHjBGGSxF@SJHX/cuIvYYpk4LpBQP2WhjiSYVBfooYbJoOs7iq1vmVq2OXsxrlzl7c4ebfOxl3e4LQ@sfhPuqPRnb@JcP3b76mNf9dTaZz/dJ2iKN9LJ3fXBVsRuD8WpYA8IoviADIu0h@YwjkqPPaOLESJXE0XFZyifMlWa02xU6yXFIU8raQVqmsrHbFJRgeHuoUOtBTmZciR/0fROFdxF5TfOszI26tSVJhTdzzbirzLhFPy0z7n4HC/cf0scrgXU6BXceM3y1UaZ4xtUi9L/caL42t/ZPlmc5e6vvKdOPW1eoUliK/TFOcowqMYThdI1aInrkuKU1O3Cu0@HUqulKjYYFtGz@tqfG8H37VqLE0fZqtdl/OqozU3aAcrhOjmEQ8Nr3KUwURLYP8@VN1sL6PtuUPA2IcYshxDliZksjBVgaks7eTvy7KoITQMtg8aVenuMzGqPsYxi4BpbKc09hEqgcJ9fArjG/LpHLQ7JmTLkkg3bVGpMSkeBWA/A1BP2W@EkO1W54lSusMRJnpGgpD3A5vANHY7sus3@lwIQECfD4evRmyU2@1mkqhFiyRGjdVppHu5D5O5MCFaZ2LdMf58HPXCs4HqknNO2Ns752jWnBcar2a8ECzL8kKYWIYXwpwFSZiEvXefXvXOHE8uci@xiVHbB24TMKTg84WSnMedvPZJ5/PZt165DWn@cSxpYkubYN2tN@El9Yl1kZC@Qbdb12ze29VuPgzrx2H9NKyfsb@1hl@FlFDvD53MuBI5ZHUuItP6h@lev4ADeQ4HCzve2PuAN0vVgE9OUX3Fl7gsKmGu0H9GDGugFU3JMwGnuhT4ypcS7gt1RBIBhBeVJIsczQzY4uAz4i7VjPBGAtW6SzmnrAneClBH/N3XoJ@D6qsE8VvHy/IR9rzkVSbyX8jC4hKq9bX8DJw06SN/hlBTik78u8DUYDIbVB0EAbo8Q6/FbLwB@b1ooP5dtFAKnuN5QJW9jMW48/OGKxVmBrrKetsLXMDCy5Z49QhZK7AhprSC885bMfYjPmUTfsIMQDHpKo6K1BtQ1MPZW0XpqB9lMl7Z@vmQ13avXQOPwbPQK/GgIDvy1nbO/wwuL/AUbTY8B9mgTxK4wpQfFLZwPvTu66g/hxdl4aVHf5W6U@vWCnN6AcJm/yzUhEUTpC@m5sf6SOyeKgctaa6Zvl0ymHDfXO2nfwA "Python 2 – Try It Online") Still not clear what the actual rules are; but here are the additional constraints that are enforced above and beyond the rule that molehills shall be turned into mountains: * The first and last terrain characters of the output must be `_`, just as they must be for valid inputs. * The vertical difference between the first `_` and the last `_` must be maintained between the input and output. * After substitutions from turning molehills into mountains, some other characters might need to be changed in order to maintain said vertical difference; but the characters changed must not be any of the characters that are part of mountains that were created from molehills. * And when accomplishing these changes, the number of additional characters changed must be minimal. ### Ungolfed Algorithm: ``` def f(s): s = ''.join(map(max,*s.split('\n'))) # flatten into a single line t = re.sub(r'..((./\\[^\\])|([^/]/\\.))..',r'////\\\\\\\\',s) # replace molehills with mountains d = s.count('/')-t.count('/')+t.count('\\')-s.count('\\') # are the two strings equally balanced? m=[{'_':'/','\\':'_'},{'_':'\\','/':'_'}][d<0] # make an appropriate mapping... d=abs(d);i=1 # skip over leading '_'... while d: # while still unbalanced... if s[i]!=t[i]:i+=7 # skip over any created mountains (7+1==8) elif t[i] in m:d-=1;t = t[:i]+m[t[i]]+t[i+1:] # if can replace, do replace i += 1 # next char t = reduce(lambda (a,p),c:(a+[' '*[p,p-1][c=='\\']+c],p+[[0,-1][c=='\\'],1][c=='/']),t,([],len(t)))[0] # pad spaces at left side t = map(''.join,zip(*[u.ljust(max(map(len,t))) for u in t])) # rotate return '\n'.join(u for u in t[::-1] if u.strip()) # reverse and join into lines. import re ``` [Answer] # [Red](http://www.red-lang.org), 855, 845 833 bytes ``` func[s][r: split s"^/"c: charset"\_/"m: copy #()repeat n l: length? r[parse r/:n[any[i: c(put m 1 + offset? r/:n i reduce[first i n])| skip]]]m: extract next sort/skip to-block m 2 2 e: copy[]parse b: rejoin collect[foreach c m[keep c/1]][any[c:["/\_"|"/\/"](alter e 1 + offset? b c)| c:["_/\"|"\/\"](alter e 2 + offset? b c)| skip]]y: 0 foreach a e[q: p: d: -3 + min m/(a - 4)/2 m/(a + 5)/2 if d < y[y: d]j: i: a until[m/:i/1: #"/"m/:i/2: p k: i - 2 if all[k > 0 #"_"= m/:k/1 p = m/:k/2][m/(k + 1)/1: #"_"m/(k + 1)/2: p break]i: i - 1 m/:i/2 < p: p + 1]j: j + 1 until[m/:j/1: #"\"m/:j/2: q k: i + 2 if all[#"_"= m/:k/1 p = m/:k/2][m/(k - 1)/1: #"_"m/(k - 1)/2: p break]j: j + 1 m/:j/2 < q: q + 1]]y: y - 1 q: collect[loop l - y[k: copy""keep pad k p: length? m]]repeat n p[w: m/1/2 - y q/:w/:n: m/1/1 m: next m]foreach d q[print d]] ``` [Try it online!](https://tio.run/##dZLPjtsgEMbvPMWIXBKtIuq0vaC2@w69ArUcjBvH/wgm2lrdPns6GNubTbI@2MPMx3w/DziTX36aXChS8EtxbrXolXAceluXHnr6i1HNQR8y1xtPZcpog8vODrBab5yxJvPQQs2hNu1vf3gGJ2zQgmO8FVk7iJITvbZnDw0k8ARdUWCn57EOJTiTn7URRel6j8tWbV6hr0qrlEIj88e7TKMDBtB3zrNQA99t93WnK2jIDnZgIpFQ0XnPseuxK1vM1rXRXhSdM5k@gIZGVMZY0CxRaqTTXFAmU/qKb0bVOqu9ccS8Q92DRqqgTJlEpcT3pASD/rfKyD9w@ASzcwZGnDhYTnIO28@4pUG@hq0z2MKXDdvF@Am@hrgsIIdvMAjskasjh5Jjh3Pry1o0jJcs4bCieBQh3mFbqFBDtjBuzepaVPAD3Vc0pd@xM69YgqIp3Clssq7QLNnETil9S4zt9khdKXQtES8h0QeJbCiiLDAdQ/AGdYytJB1j7HIaoVC0QF3jkDuc7S3O9gZn8YwOiHMKLgEnDHsIGzBF5lOvu85CjdlBVPGGUDqevs1yqMK/zHe2UWq5yla8cHRI0AB3khPjL3hTYwqtebyLjZpPNoeTsK5sPZ6UuhTwN8UHbxQ@/wjBNQCTJGUAcs6nBCux9PhhcvyQj8rYawpvJKNBVCyaK0kgGwM5fTEYJQsze@Qnr5DTh0RkAbqvfFQKXHIayDyYh6PBZDqNZQYkIxNbxPJuQHfG7Nr2Ph3HJG/ScXZTlk2TlNeL8AuB4/If "Red – Try It Online") Far, far away from a golfy solution... It passes the test cases but most probably would fail on some other, more strange pattern. ## More readable: ``` f: func [ s ] [ r: split s "^/" c: charset "\_/" m: copy #() repeat n l: length? r[ parse r/:n[ any [ i: c(put m 1 + offset? r/:n i reduce[ first i n ]) | skip]] ] m: sort/skip to-block m 2 m: extract next m 2 b: rejoin collect [ foreach c m [ keep c/1 ] ] e: copy [] parse b [ any [ c: [ "/\_" | "/\/" ] (alter e 1 + offset? b c) | c: [ "_/\" | "\/\" ] (alter e 2 + offset? b c) | skip ] ] y: 0 foreach a e [ q: p: d: -3 + min m/(a - 4)/2 m/(a + 5)/2 if d < y [ y: d ] j: i: a until [ m/:i/1: #"/" m/:i/2: p k: i - 2 if all [ k > 0 #"_" = m/:k/1 p = m/:k/2 ] [ m/(k + 1)/1: #"_" m/(k + 1)/2: p break ] i: i - 1 p: p + 1 m/:i/2 < p ] j: j + 1 until[ m/:j/1: #"\" m/:j/2: q k: i + 2 if all [ #"_" = m/:k/1 p = m/:k/2 ] [ m/(k - 1)/1: #"_" m/(k - 1)/2: p break ] j: j + 1 q: q + 1 m/:j/2 < q ] ] y: y - 1 q: collect [ loop l - y [ k: copy "" keep pad k p: length? m ] ] repeat n p [ w: m/1/2 - y q/:w/:n: m/1/1 m: next m ] foreach d q [ print d ] ] ``` ]
[Question] [ Write 3 programs that do the following task: Let A, B, C source codes of those three programs; * if A runs BC is produced as output, * if B runs CA is produced, * if C runs AB is produced; so each program writes a string (cycled for each program) and hides itself from it. Additional, but essential constraints: * standard loopholes are forbidden; * each program must be at least 1 byte long; * each of three programs *must* be written in a different language; It would be nice if your submission had this format: ### Language A (size of A) - Language B (size of B) - Language C (size of C) - Score ``` A B C <extra stuff> ``` Winner is someone who get the minimum score, which is the sum of sizes of three programs. [Answer] # [Befunge-98](https://github.com/catseye/FBBI), [Gol><>](https://github.com/Sp3000/Golfish) and [Wumpus](https://github.com/m-ender/wumpus) 47\*3 = 141 bytes ``` "r75*1-47*0.@o&r84#o&]=74#]=\`/KHj '!_@#,k.'g00 ``` [Try it in Befunge!](https://tio.run/##S0pNK81LT9W1tPj/X6nI3FTLUNfEXMtAzyFfrcjCRDlfLdbW3EQ51jYmQd/bI0tBXTHeQVknW0893cDg/38A "Befunge-98 (FBBI) – Try It Online") [Try it in ><>!](https://tio.run/##S8/PScsszvj/X6nI3FTLUNfEXMtAzyFfrcjCRDlfLdbW3EQ51jYmQd/bI0tBXTHeQVknW0893cDg/38A "Gol><> – Try It Online") [Try it in Wumpus!](https://tio.run/##Ky/NLSgt/v9fqcjcVMtQ18Rcy0DPIV@tyMJEOV8t1tbcRDnWNiZB39sjS0FdMd5BWSdbTz3dwOD/fwA "Wumpus – Try It Online") That's right, it's the same program three times over! When run in any of the above languages, it prints the source code twice, which is the other two programs concatenated. ### How It Works: ``` Befunge code: "r j '!_@#,k.'g00 " Wrapping string literal over code r Reflect the pointer " Wrapping string literal g00 Fetch " from cell 0,0 ,k.' Print 47 characters _@# If the next character is 0, exit ! Otherwise, set it to 0 j ' And jump back to the beginning Gol><> code: "r75*1-47*0. \`/KH " Wrapping string literal r Reverse stack 75*1- Push " 47*0. Jump to cell 28,0 \ Continue right `/K Duplicate the top 47 characters on the stack H Halt and output stack contents Wumpus code: "r75*1-47*0.@o&r84#o&]=74#]=\ "r75*1-47*0. Exact same function as the ><> code, but with a bouncing string literal \ Reflect left ]= Push a copy of the " to the bottom of the stack 74# Push 47 ]= Push a copy of the 47 to the bottom of the stack o& Print the top 47 characters 84# Push a '0' to make up for the missing 0 at the end o&r Reverse the stack and print the top 47 characters @ And terminate ``` [Answer] ## JScript, VBScript, Windows Batch, 345 bytes ``` a=new ActiveXObject("scripting.filesystemobject");b=a.opentextfile(".js");c=b.readline();d=b.readline();a.createtextfile(".bat").write("@echo "+d.substr(2)+">.vbs\n@echo '"+c+">>.vbs") //set a=createobject("scripting.filesystemobject"):set b=a.opentextfile(".vbs"):c=b.readline:d=b.readline:a.createtextfile(".js").write(mid(d,2)+chr(10)+"//"+c) ``` Name the file .js, then .vbs and then .bat will be created. ]
[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/116627/edit). Closed 6 years ago. [Improve this question](/posts/116627/edit) Gödel's β function takes three natural numbers as arguments. It is defined as `β(x,y,z) = rem(x, 1 + (z + 1) · y) = rem(x, (z · y + y + 1) )` where rem(a, b) denotes the remainder after integer division of a by b. The β Lemma now states that: > > For any sequence of natural numbers (k\_0, k\_1, … , k\_n), there are natural numbers b and c such that, for every i ≤ n, β(b, c, i) = k\_i. > > > Gödel needs help to find `b` and `c` for any given input `(k_0, k_1, … , k_n), k_i ∈ ℕ`. --- Write a function that takes in an array of length `n`, filled with natural numbers, and gives a possible `b,c` output that fulfilles the Lemma for the array. --- Do not get solutions by brute force! (In my totally unprofessionall opinion, it is brute force when you first get a number and then do the calculation. That is guessing the number and then looking if the guess was correct. What I want to be coded here is a solution which calculates the numbers and does not have to check whether they fulfill the lemma because they were calculated to do so. ) Construct them with the equations and information given. Shortest code wins, bonus points if you do it in `Javascript` because I am just getting into it `:)` --- Example: ``` [5, 19, 7, 8] -> (1344595, 19) 1344505 % (1 + (0 + 1) * 19) = 5 1344505 % (1 + (1 + 1) * 19) = 19 1344505 % (1 + (2 + 1) * 19) = 7 1344505 % (1 + (3 + 1) * 19) = 8 ``` [Answer] ## JavaScript (ES6), 104 bytes ``` a=>[c=a.reduce(c=>c*++i,Math.max(...a),i=0),a.reduce(g=(x,k)=>x%m-k?g(x+n,k):(n*=m,m+=c,x),0,n=1,m=c+1)] ``` Returns `[c, b]` as an array. The solution it returns isn't minimal in `c` but I think it is minimal in `b` for the given `c`. For 120 bytes this returns solutions minimal in `c` and in `b` for the given `c`: ``` f=(a,c=1,b=a.reduce(g=(x,k)=>x%m-k?d--?g(x+n,k):0/0:n%m?g(x,k,n+=o):(o=n,d=m+=c,x),0,o=n=1,d=m=c+1))=>1/b?[b,c]:f(a,c+1) ``` Ungolfed minimal solution solver: ``` function godel(a) { for (c = 0;; c++) { var b = 0, n = 1, i = 0; for (;;) { var m = c * i + c + 1; // Increase b until β(b,c,i) = a[i] // Adding n won't change output for smaller i for (j = 0; j < m; j++) if (b % m != a[i]) b += n; if (j == m) break; // couldn't find a remainder, c too low i++; if (i == a.length) return [b, c]; // Result! // Next time we want adding n to b not to change β(b,c,i) for (j = 1; n * j % m != 0; j++); n *= j; } } } ``` ]
[Question] [ **The problem:** Write a function which, given a cycle length `n` and a number of cycles `m`, where 'm' is within `[2, n-2]`, generates `m` random cycles, each of length `n`, and all of which are [derangements](https://en.wikipedia.org/wiki/Derangement) of each other. Then `n=7`, for example, `m` could be `2, 3, 4, or 5`. All possible sets of `m` cycles of length `n` that fit the criteria should have equal probability of occurring. **What is a cycle?** Imagine you're hopping around a list. Each element in the list is a number corresponding to another position on the list. Start out at the first element, and update your position to be whatever index is at that element: ``` CycleThrough(list) { pos = 0; while(true) { pos = list[pos]; } } ``` If you can visit every element in the list and get back to the start using this method, it's a cycle. If you can't, it's not. Here are a few examples of cycles: ``` (0) (1, 0) (1, 2, 0) (2, 0, 1) (1, 2, 3, 0) (1, 3, 0, 2) (2, 4, 1, 0, 3) ``` Take the last cycle. It goes `0 -> 2 -> 1 -> 4 -> 3 -> 0`. What isn't a cycle? Take `(4, 0, 3, 2, 1)`- this isn't a cycle because it goes `0 -> 4 -> 1 -> 0`, and you won't hit `3` or `2`. Or take `(1, 1)` - it goes `0 -> 1 -> 1 -> 1 -> 1...` and it never gets back to 0, so it's not a cycle. **What does it mean for two cycles to be deranged?** Lets say you have two cycles, cycle `A` and cycle `B`. If `A[i]` never equals `B[i]`, they're derangements of each other. If you have more than two cycles, they're all derangements of each other if all pairs of cycles are derangements. The fastest algorithm (in time complexity) wins. Example outputs for n=5, m=3: ``` {{1, 4, 3, 0, 2}, {3, 0, 4, 2, 1}, {2, 3, 1, 4, 0}} {{3, 0, 4, 2, 1}, {2, 4, 3, 1, 0}, {4, 3, 1, 0, 2}} {{3, 0, 1, 4, 2}, {2, 4, 3, 1, 0}, {4, 3, 0, 2, 1}} {{3, 4, 0, 1, 2}, {1, 2, 4, 0, 3}, {2, 3, 1, 4, 0}} {{3, 4, 0, 1, 2}, {4, 0, 1, 2, 3}, {1, 2, 3, 4, 0}} {{4, 2, 0, 1, 3}, {2, 3, 1, 4, 0}, {1, 4, 3, 0, 2}} {{4, 3, 0, 2, 1}, {2, 4, 1, 0, 3}, {3, 2, 4, 1, 0}} {{4, 0, 1, 2, 3}, {3, 2, 0, 4, 1}, {2, 4, 3, 1, 0}} {{3, 0, 1, 4, 2}, {4, 2, 0, 1, 3}, {1, 3, 4, 2, 0}} {{3, 2, 0, 4, 1}, {4, 0, 1, 2, 3}, {1, 4, 3, 0, 2}} ``` Example outputs for `n = 4...12, m = n-2` ``` {{2, 3, 1, 0}, {3, 2, 0, 1}} {{4, 0, 1, 2, 3}, {1, 2, 3, 4, 0}, {2, 3, 4, 0, 1}} {{4, 2, 5, 1, 3, 0}, {2, 5, 4, 0, 1, 3}, {3, 4, 1, 5, 0, 2}, {5, 3, 0, 4, 2, 1}} {{6, 3, 5, 0, 1, 4, 2}, {1, 5, 4, 2, 6, 3, 0}, {5, 2, 3, 6, 0, 1, 4}, {4, 0, 6, 1, 5, 2, 3}, {3, 6, 1, 4, 2, 0, 5}} {{7, 0, 3, 6, 1, 2, 4, 5}, {6, 2, 0, 7, 5, 1, 3, 4}, {1, 5, 4, 0, 7, 6, 2, 3}, {5, 3, 6, 4, 0, 7, 1, 2}, {4, 6, 7, 2, 3, 0, 5, 1}, {3, 7, 1, 5, 2, 4, 0, 6}} {{2, 3, 6, 8, 0, 4, 1, 5, 7}, {8, 5, 0, 2, 1, 6, 7, 3, 4}, {3, 2, 4, 5, 7, 1, 8, 6, 0}, {4, 6, 5, 7, 8, 0, 3, 2, 1}, {1, 8, 7, 4, 6, 3, 2, 0, 5}, {7, 0, 3, 1, 5, 2, 4, 8, 6}, {5, 7, 1, 6, 3, 8, 0, 4, 2}} {{1, 4, 5, 6, 2, 9, 8, 3, 0, 7}, {4, 2, 7, 1, 9, 3, 5, 0, 6, 8}, {9, 5, 0, 8, 3, 7, 1, 4, 2, 6}, {5, 7, 6, 0, 8, 2, 4, 9, 1, 3}, {7, 6, 8, 9, 5, 0, 3, 1, 4, 2}, {2, 8, 9, 7, 1, 6, 0, 5, 3, 4}, {8, 0, 3, 5, 6, 4, 9, 2, 7, 1}, {6, 3, 4, 2, 0, 1, 7, 8, 9, 5}} {{3, 4, 1, 5, 8, 9, 0, 10, 6, 7, 2}, {1, 2, 6, 4, 10, 8, 5, 9, 7, 3, 0}, {10, 6, 3, 1, 9, 7, 8, 4, 0, 2, 5}, {8, 3, 0, 7, 2, 6, 10, 5, 9, 1, 4}, {9, 5, 7, 6, 0, 3, 2, 8, 4, 10, 1}, {2, 0, 9, 10, 7, 1, 4, 3, 5, 6, 8}, {6, 7, 5, 8, 3, 4, 1, 2, 10, 0, 9}, {4, 8, 10, 9, 6, 0, 7, 1, 2, 5, 3}, {5, 10, 4, 0, 1, 2, 9, 6, 3, 8, 7}} {{6, 11, 4, 5, 3, 1, 8, 2, 9, 7, 0, 10}, {1, 4, 8, 9, 10, 11, 5, 3, 7, 6, 2, 0}, {7, 9, 10, 1, 11, 3, 2, 8, 6, 0, 4, 5}, {4, 2, 5, 0, 6, 7, 9, 11, 1, 10, 8, 3}, {10, 8, 7, 6, 5, 0, 4, 1, 3, 11, 9, 2}, {9, 3, 6, 8, 7, 10, 1, 0, 5, 2, 11, 4}, {8, 0, 9, 11, 1, 4, 7, 10, 2, 3, 5, 6}, {3, 6, 0, 10, 2, 9, 11, 5, 4, 8, 1, 7}, {2, 5, 11, 7, 8, 6, 10, 9, 0, 4, 3, 1}, {11, 7, 1, 2, 0, 8, 3, 4, 10, 5, 6, 9}} ``` [Answer] # [Python 3](https://docs.python.org/3/), \$O((n - 1)!^{m - 1}nm)\$ expected time This is a reference answer using a very straightforward and slow rejection sampling algorithm, for the sake of having at least one valid answer. It picks \$m\$ random cycles, checks whether they form a valid solution, and repeats from scratch until they do. Since there exists at least one valid solution, there must exist at least \$(n - 1)!\$ valid solutions (by relabeling it), so the probability that \$m\$ random cycles happen to be a valid solution is at least \$\frac{(n - 1)!}{(n - 1)!^m}\$. So we expect at most \$(n - 1)^{m-1}\$ iterations of the loop, with each iteration taking \$O(nm)\$ time. (This is a pessimistic analysis that could be improved with a better lower bound on the number of solutions.) ``` import random def f(n, m): while True: cycles = [] for i in range(m): order = list(range(1, n)) random.shuffle(order) cycle = [None] * n for a, b in zip([0] + order, order + [0]): cycle[a] = b cycles.append(cycle) if all(len({cycle[j] for cycle in cycles}) == m for j in range(n)): return cycles ``` [Try it online!](https://tio.run/##ZZBNTsQwDIX3PYWXDhONQCM2SL0Cq9lVWWSmDs0oTaI0FRoQZy/5oUUF72y/5/fJ/h4HZ0/LokfvQoQgbe/GpulJgULLYWQvDaR6H7QhOIeZap/rer8amqCFTmwz5QJo0DZfeiNc7Wu50FNIDqOniFXyxMEytlNViuM0zEoZwmLaK0p0Tn51lgQ8gN2tM4XkcMkgH9pj9yjgUMP5D8MB0vAP3Xa5kyIdv/yPnI7Se7I9lo41m0IrkMagIYuf9cRNFIxKmjiq/4tB28JYVrffP6UP7FECxTmspsUHbSMqfOZwYmz5Bg "Python 3 – Try It Online") [Answer] # Python3, ~O(n!): ``` import collections, copy, random def cycles(n): q, q1 = collections.deque([([], [0 for _ in range(n)], 0, {}, {*range(n)}, collections.defaultdict(set))]), collections.deque() while q: result, a, s, d, ac, cache = q.popleft() if not ac: yield a, cache continue for i, x in enumerate(a): if (s or i) and (i not in d and s not in cache[i]): l, _cache = copy.deepcopy(a), copy.deepcopy(cache) _d = copy.deepcopy(d) l[i] = s _d[i] = s _cache[i].add(s) q.append((result, l, i, _d, ac - {s}, _cache)) def main(n, m): cycle, result, cache, seen = [*cycles(n)], [], {}, [] while 1: if len(result) == m and result not in seen: yield result result, cache, seen = [], {}, seen + [result] continue c, _cache = random.choice(cycle) if all(not cache.get(j, set())&_cache[j] for j in _cache): result.append(c) cache = {j:cache.get(j, set())|_cache[j] for j in _cache} ``` [Try it online!](https://tio.run/##dVPLjtswDLznK3gqpK3W2G17WBjIlxhGIEj0RoEsybaCbpDm21NKfqVpYsCARXPIIWcUTnHv3c@P0F@vpg2@j6C8taii8W4QdAgnAb102rcbjQ2ok7I4MMfLDQB0Arp32N5iCo3dEVnFqlpA9QaN72EHxqUin0hACr8JOF/ofZljF3FXopFHG7VRkQ0YOa@5eNCDJwq/98YidJkOQI8DAQVIAcRe04cipFR7JJZdEXyw2MQRCWAacD5SzoSm52TQ6gTPoCWsvIvGHadAmskI@EpjoTu22MuITPKlDBVmA6QsDrQ7YCY3onSdz8N8zF0qU69QeqyA3cw5CUDjYkgf1ELcRXIevwHv9H8offvfUjfKGP6BPIjNzAqpNRtuK3SFDAGdZmzeNhGmdezyuuEVzsNlnoBzAmyyc1ppHHMC2nHWbCSxCJazSTRER0yql8VnyUX16JeqXgV/LxcJLbqJCYftFtq84TEwrzmVLeFO5DFlCT5hMvXOx@9QjVn1E2OoG@XGS1OovTcKWZ5ntZ20liVuObn4xMgOqQc5k3@bVn@os88Oif@0zPKO7CyEWuWZu58P5YPaf57WvlyzqdeL@kvAx9gw9MZF5vArsqwhSW1ef3DOr38B) ]
[Question] [ A vector partition is splitting a vector up a series of vectors such that their sum is the original. Here are a couple partitions: ``` [3, 1, 2] = [3, 1, 2] [3, 1, 2] = [0, 0, 1] + [0, 0, 1] + [0, 1, 0] + [1, 0, 0] + [2, 0, 0] [3, 1, 2] = [1, 1, 2] + [2, 0, 0] ``` Here vector addition is done element-wise. A valid partition does not contain any vectors with negative integers, or the all-zero vector. Now the challenge is to write a program or function that generates all possible vector partitions given a target vector. This may sound relatively easy... ### ...but there is a twist. If the input vector has size L, and the biggest partition it generates has M elements, you may not use more than O(L\*M) memory. You may assume that an integer uses O(1) memory. This means that you must output the partitions as you generate them. **On top of that, you must only output each partition exactly once.** For example, these are the same partition: ``` [3, 1, 2] = [3, 0, 2] + [0, 1, 0] [3, 1, 2] = [0, 1, 0] + [3, 0, 2] ``` If you were to output both your answer is invalid. --- All partitions for `[3, 2]`: ``` [3, 2] [0, 1] + [3, 1] [0, 1] + [0, 1] + [3, 0] [0, 1] + [0, 1] + [1, 0] + [2, 0] [0, 1] + [0, 1] + [1, 0] + [1, 0] + [1, 0] [0, 1] + [1, 0] + [2, 1] [0, 1] + [1, 0] + [1, 0] + [1, 1] [0, 1] + [1, 1] + [2, 0] [0, 2] + [3, 0] [0, 2] + [1, 0] + [2, 0] [0, 2] + [1, 0] + [1, 0] + [1, 0] [1, 0] + [2, 2] [1, 0] + [1, 0] + [1, 2] [1, 0] + [1, 1] + [1, 1] [1, 1] + [2, 1] [1, 2] + [2, 0] ``` To test your answer, run it on `[3, 2, 5, 2]`. It should generate 17939 partitions, all of which sum to `[3, 2, 5, 2]`, and that are all unique (you can test for uniqueness by first sorting each partition lexicographically). --- Shortest code in bytes wins. [Answer] # Python 2, 289 bytes Simple brute force algorithm. Treats entire list as a number in base `max(input)+1` (`b`), and checks each "number" in the range `[0, b**(L*M))` to see if it: 1. Sums to the correct amount 2. Is in alphabetical order (ensures uniqueness) If the list matches these criteria, the program outputs it with all the all-zero vectors stripped. ### Memory usage The largest data structure I use in this program is a doubly-nested list, an list length `M` containing liss length `L` to give `O(L*M)` memory. For my other data structures, I have 3 global ints `O(3)`, 1 list length `L` (`O(L)`), 1 array length `M` (`O(M)`), and a copy of the largest array when outputting (`O(L*M)`). In total, this gives me a memory usage of `O(2*L*M + L + M + 3)` which simplifies to `O(L*M)`, fufilling the criteria. ### Time complexity Being a brute force algorithm, this algorithm is extremely slow. For the while loop to quit, the final int in the array needs to be `b-1`. The loop needs to run `b**(L*M)` times before that happens. In addition, each time the list runs, it needs to check both conditions, and print the list in a worst case, using `L*M+L+M` iterations. This simplifies to give an overall `O(L*M * b**(L*M))`. I tried to test my program on `[3, 2, 5, 2]`, but gave up after 45 minutes. ### Golfed program ``` v=input() L=len(v) M=sum(v) b=max(v) R=range t=[L*[0]for i in R(M)] def A(l,i): if i<L*M-1and~-b<l[i/L][i%L]:A(l,i+1) l[i/L][i%L]=-~l[i/L][i%L]%-~b while t[-1][-1]<b: if v==[sum(q[i]for q in t)for i in R(L)]and all(`t[i]`>=`t[i+1]`for i in R(M-1)):print[x for x in t if[0]*L!=x] A(t,0) ``` I might be able to golf this a bit more, especially the increment part. Ungolfed code coming. ]
[Question] [ This is based off a previous deleted challenge of mine with the same name ### Introduction You are tasked with writing a program that returns a truthy or falsey value based on if the input has all its XML-like1 tags appropriately opened and closed and in the right order. Consider the following as input: ``` <Apple> ``` This would return a falsey value because the tag is not closed correctly. This: ``` <Apple></Apple> ``` On the contrary returns a truthy value because it is closed correctly. The program should also check nested tags to make sure they are in the correct position. For example, take this as input: ``` <mango><Apple></mango></Apple> ``` All the tags are closed correctly, *but not in the correct order*. Your program must check for correct tag hierarchy and nesting. ### Definitions Let me define a few things before I get into the rules and assumptions. **Tag** A basic XML-style tag. For example: `<Apple>`. They can have at most, one leading and trailing space (or else it's invalid and falsey), so `< Apple >` and `<Apple>` are the same. These tags can also contain attributes like `foo="bar"` *(with required double quotes, or else invalid and falsey)*, and the attribute name can only contain any alphanumeric character or `_`, `:`, `-`, and `.`. The attribute names also do not require an attribute value, and values can contain anything except `"` before the closing double quote. The closing tag must not contain attributes, and no tags should have newlines in them. **Tag Name** Tag names are the tags' names. For example, `<Apple>`'s tag name is `Apple`. Tag names can contain the same characters as attribute names, and are case-sensitive. This means `<Apple>` is **not** `<apple>`. **Self-Closing Tag** A regular tag that closes itself such as `<Apple />` or `<Apple/>` (they are the same). The space between the slash and the tag name is allowed. **Plain Text** A string of characters that can contain anything and are not enclosed in `<` and `>`. **"Simple" Tag** Either an opening, closing, or self-closing tag. ### Rules * Output may be returned or printed, and input may be taken any way you like * Input is a string, consisting of either tags, plain text, or both * Your program can be a function or a whole working program * Plain text can be anywhere; if the input consists *only* of plain text, the program should return a truthy value. * Recognition of nested tags is required for the program. If a tag is nested in a tag, that nested tag must be closed before the parent is closed, just like regular XML, or else a falsey value should be returned ### Assumptions * You can assume that input will always be one or more "simple" tag(s) * You can assume that input will always follow the format for tags defined above ### Test Cases **Falsey** ``` <apple> <apple></Apple> <apple></mango> <apple><mango> <a><b></a></b> Text<ul><li></li><ul /> <pear attr=foo></pear attr=foo> <Ketchup flavor=spicy></Ketchup> <Ap ple></Apple> ``` **Truthy** ``` Text <Apple /> <Apple></Apple> < Apple ></ Apple> <mango><Apple/></mango> <mango>Text<div class="bar">More text \o/</div></mango> <food group="fruit">Fruits:<orange :fruit-variety="clementine" /><pear _fruit.type="asian" /></food> <example foo="abcdefghijklmnopqrstuvwxyz1234567890-/:;()$&@.,?!'" noValue>Any characters allowed! (0.0)</example> ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/56456) are prohibited as usual. --- 1**Note**: This is not real XML, but a pseudo-XML with different rules for the challenge. Tag and attribute names differ from specification. [Answer] # [Retina](https://github.com/m-ender/retina), ~~76~~ 74 Bytes ``` +`< ?([-.:\w]+)( ?[-.:\w]+(="[^"]*")?)* ?(/>|>[^<>]*< ?/ ?\1 ?>) ^[^<>]*$ ``` Since I've seen that retina is really good for golfing regexes, I figured I'd try it out. Follows the same logic as my Ruby answer and prints 0 or 1. [Try it online!](https://tio.run/nexus/retina#@6@dYKNgrxGtq2cVUx6rramhYA9ja9gqRccpxWopadpragHV6NvV2EXH2djFagF16CvYxxgq2NtpcnHFQQRV/v@3yU3MS8@3C0mtKLFJySxTSM5JLC62VUpKLFKy880vSlUoAcooxOTr2@gDpe1s9CHqAQ) [Answer] # Ruby (2.3.1), ~~103~~ ~~101~~ 100 Bytes ``` ->s{s.sub!(/< ?([-.:\w]+)( ?[-.:\w]+(="[^"]*")?)* ?(\/>|>[^<>]*< ?\/ ?\1 ?>)/,'')&&redo;!(s=~/<|>/)} ``` Anonymous function called by appending `.call("<Apple></Apple>")`. Substitutes matching or self closing tags until there arent any, and then returns whether the string has no angle brackets remaining. [Try it online!](https://tio.run/nexus/ruby#bVJdj9MwEHzPr3At1CblGvf4puc4VHAICSEkhHhpeshJnDbgxsZ22gaO@@tlk1yhd@Ih2czObHbGySHlOYoQpTfvLj9dvvn42qNcaynYsVIyv4c3vFqpf/gvZDQFFgpJmfdZ7B2tJaOyhEZ7qyUiINOCG8SdM1GhFFB3sUffC5eta40KybfKRFaXWQOy2zYI5hrd8XX07a2UgignSVoPqB0AXbd7fi8R6inooGOrT9MryUnYvnap8nKLMsmtjXDKDWYflBHItbsSRSgB@mSuaE2tjKp1hAtTlw6zt22xM6oMaASade3JlptSuCbCmRQbUbmyEhhM9@f1tdOErtEiwtyWvOo40r4dlog937RBAAKdZrkoVuvy23e5qZT@Yayrt7t98/P80eMnT589f/FyOiGzCz94MHwVnsWDEUaV@sJlLdi8alC25oZnThiLuJRqJ/IB8qfhNKDkds/JmXteEU2Y/WVDW6cDn1AU@4tJOEt2y4eBj@Ljsx/hxRVejnEQB2PQJIRds8UVZcsxjCQErnMUs4CcjUbBcGhEri4Gvo1uCL1mJPjteRrBnxpaLUvn46TCQbjh2h8WQVipSsTAt9//vwKIEXuHwx8 "Ruby – TIO Nexus") ]
[Question] [ This is thematically similar to [Generate keyboard shortcuts for a menu](https://codegolf.stackexchange.com/questions/29936/generate-keyboard-shortcuts-for-a-menu), but its actually a pretty different challenge. Let's take PHPStorm's menu as an example: ``` New Project New Open Directory Open Open URL New Project from Existing Files Save As Open Recent Close Project Rename Project ``` We need to assign a single-letter [access keys](https://msdn.microsoft.com/en-us/library/cc294694.aspx) for each of these menu items. Typically we pick the first letter, but if you notice, many of the above menu items start with the same letter! Therefore, we'd want to pick: ``` P -> New Project N -> New D -> Open Directory O -> Open U -> Open URL F -> New Project from Existing Files S -> Save As E -> Open Recent (We don't pick "R" here because "Rename Project" needs it) C -> Close Project R -> Rename Project ``` Therefore, for our list we need to maximize (in order of importance): 1. The number of access keys actually contained in the string. * `["X" -> "New"]` should be avoided unless its your only option. 2. The number of access keys that start a word. * `["N"->"New", "P"->"New Project"]` is better than `["E"->"New", "N"->"New Project"]` 3. The number of access keys that start the sentence. * `["N"->"New Project"]` is better than `["P"->"New Project"]` Access keys are case-insensitive, so if your menu is `["Add", "add"]`, one of them will need to use `D` as its access key. # Input/output You need to input a list of strings. The strings will only contain alphabetic characters and spaces. You can optionally input a single string with a delimiter for each of the lines. You can assume there will be between 1 and 26 menu items (inclusive). You need to output either: 1. A Key-value map, where the key is the access key letter, and the value is the string it maps to 2. A list of access key letters, where the Nth entry pairs with the Nth item in the list. You can either return the objects themselves, or a reasonable string representation of them. Access key letters can be in any case. # Test Cases: ``` A -> A Add,add -> A,D Add To,Add -> T,A Add To,Add Around,Add For -> T,A,F Add To,Flip To,Add For -> T,F,A Add,add,Dip,Around -> A,D,I,R Add,add,Dad -> A,B,D Add,add,Dad,dad,ad dadad,B -> A,C,D,E,Z,B A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,A,B,C -> A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,Add,Bz,Cx -> A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,Y,Z,X ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 41 bytes ``` e/€S;eḲ1ịⱮƊ}¥/€;=Ḣ¥/€µS LØAœ!ż€³Œu¤ÇÐṀẎḢ€ ``` [Try it online!](https://tio.run/##y0rNyan8/z9V/1HTmmDr1Ic7Nhk@3N39aOO6Y121h5aCRK1tH@5YBGEe2hrM5XN4huPRyYpH94D4m49OKj205HD74QkPdzY83NUHVAkU/v//f7SSY0qKQki@ko4CmOVYlF@alwLjueUXKcUCAA "Jelly – Try It Online") This is really messy and also O(26^n) lol. Explanation: literally just brute forces it .\_. -6 bytes thanks to caird coinheringaahing ]
[Question] [ Given a string containing only 0's 1's, 2's and brackets, output the grammar tree of the string. A `2` requires 2 arguments - one to the left and one to the right A `1` requires a single argument - to either the left or right A `0` doesn't require any arguments and is the base case A pair of brackets counts as one argument and the contents of the brackets are evaluated separately from the rest of the string. Nested brackets are possible A input string will always be a complete tree with no characters falling off. The string will also only have a single correct solution. Note that the functions are commutative and any arrangement of arguments for `2` will be acceptable. You will not have to handle input that doesn't conform to these requirements. The output grammar format will be in the form `function(arguments)` recursively ### Test cases ``` 0 --> 0 01 --> 1(0) 020 --> 2(0,0) 101 --> 1(1(0)) 0120 --> 2(1(0),0) 0120210 --> 2(1(0),2(0,1(0))) 01210 --> 2(1(0),1(0)) (020)210 --> 2(2(0,0),1(0)) ((020)20)1 --> 1(2(0,2(0,0))) ``` [Answer] ## Python 3.6 (pre-release), 199 Saved 6 bytes thanks to Morgan Thrapp ``` import re def f(s):s=s.strip('()');i,j=[m.start()if m else-1for m in(re.search(c+'(?![^(]*\))',s)for c in'21')];return i>0and f'2({f(s[:i])},{f(s[i+1:])})'or j>=0and f'1({f(s[:j])or f(s[j+1:])})'or s ``` Explanation & ungolfed version: ``` import re def f(s): s=s.strip('()') # Search for '2' and '1' outside of brackets i, j = [m.start() if m else -1 for m in (re.search(c + '(?![^(]*\))', s) for c in '21')] if i > 0: # Call `f(s[:i])` and `f(s[i+1:])`, concatenate the results return f'2({f(s[:i])},{f(s[i+1:])})' elif j>=0: # Call `f(s[:j])` and `f(s[j+1:])`, choose the non-empty result return f'1({f(s[:j]) or f(s[j+1:])})' else: return s ``` ]
[Question] [ Given a `WxH` grid, how many possible mazes are there? Things you know about the maze: 1. The grid is exactly `H` squares high and `W` squares wide. 2. There are three types of squares: Start, Finish, and Empty. Your maze must contain exactly 1 Start and 1 Finish, and all remaining squares are Empty. 3. There are walls surrounding the entire maze. 4. Walls can exist on the edge between any two squares, unless it breaks the below rule: 5. There must exist a path from the Start square to the Finish square. Therefore, given two numbers, `W` and `H`, you must return a single number representing the number of possible square/wall configurations. You are guaranteed that `W*H > 1` For example, the `2x2` maze has exactly `100` different possible configurations. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer wins! [Answer] # Python 2, ~~329~~ 310 bytes ``` from itertools import* w,h=input() R=range(w*h) p=product n=0 Z=[(x,y)for x,y in p(R,R)if abs(x%w-y%w)+abs(x/w-y/w)<2] for s,f,W in p(R,R,p(*[((),z)for z in Z if z[0]<z[1]])): V={s};C=[s];v=0 while C: c=C.pop();v|=c==f!=s;V|={c} for o,q in Z:C+=(c==o)*len({q,(o,q),(q,o)}-(V|set(W)))/3*[q] n+=v print n ``` This is the golfed (and much more inefficient) version of the program I was using while discussing the problem with @Nathan. I can save a few bytes by replacing some space indents with tabs, but I'll save that for later. The algorithm is simply generate every maze, then flood fill from the start, seeing if we pass the finish at some point or not. ]
[Question] [ Your job, for this golf, is to write a program that will take moves of a game of [reversi (othello)](http://en.wikipedia.org/wiki/Reversi) and display the result to the user. ### Input A string of numbers taken from the range [0-7]. Each pair of numbers represent first the X coordinate, then the Y coordinate. Any characters not in that range should be ignored. ### Output A visual representation of the result of the game, including who is leading when the input ends. This may be graphical or keystroke output, but it must be a visual grid of the game, with a distinct character/graphical symbol for black, white, and empty. Additionally, your code should output an error message and stop when an illegal move is entered (the same square more than once, or a square that will not flip any tiles). **Skips** should be handled gracefully. A skip occurs when one color has no legal move, their turn is skipped and the other player gets to play. Black always goes first. ### Examples ``` 23 ........ ........ ........ ..bbb... ...bw... ........ ........ ........ b 232425140504032627 ........ ........ ........ b.bbb... bbbww... b.b..... ..b..... ..b..... b 2324322513 ........ ........ ........ ..bbb... ..www... ........ ........ ........ e 23242555 ........ ........ ........ ..bbb... ..bbw... ..b..... ........ ........ e ``` [Answer] # Haskell - 1493 bytes In this version, there are no detailed error messages and the output is much more basic. The major change was replacing `Either String a` with `Maybe a` and since they are both monads, this was acheived by simply swapping `Right a` with `Just a` and `Left String` with `Nothing`. ``` {-# LANGUAGE OverloadedStrings #-} import Prelude hiding ((>>=),concatMap,filter,foldl,head,last,map,null,replicate) import Control.Applicative hiding (empty) import Control.Monad hiding (replicateM) import Data.Vector hiding ((++),concat,foldM,reverse,zip) main=getLine>>= \s->h$t<$>(zip$cycle[w,v])<$>b s>>= \m->u(\b(c,x)->case d b x c of r@(Just _)->r;Nothing->if not$null$findIndices(\y->e$d b y c)$t[(x,y)|x<-[0..7],y<-[0..7]];then é;else d b x$not c)k$n m where b(x:y:s)=(:)(read [x],read [y])<$>b s;b(_:_)=é;b[]=è[];d b z c=let d=join$m(f b z c)$m(\v->(head v,last v))$replicateM 2$t[-1,0,1];in if null d;then Nothing;else u(\b (x,y)->case b!?y of Just r->(case r!?x of Just _->è$b//[(y,r//[(x,è c)])];Nothing->é);Nothing->é)b$n$d`snoc`z;e(Nothing)=w;e(Just _)=v;f b(x,y)c z@(u,v)=let r=x+u;s=y+v;t=(r,s);in (case g b t of Just(Just d)->if d==c;then l;else (case g b (r+u,s+v) of Just(Just _)->t`cons`f b t c z;_->l);Just(Nothing)->l;Nothing->l);g b(x,y)=(case b!?y of Just col->col!?x;Nothing->é);h(Just b)=p$(o$n$m(\r->o(n$m(\c->case c of Just False->"B";Just True->"W";Nothing->".")r)++"\n")b)++i(q(\(w,b)(rw,rb)->(w+rw,b+rb))(0,0)$m(\r->q(\s@(w,b)c->case c of Just True->(w+1,b);Just False->(w,b+1);_->s)(0,0)r)b);h Nothing=p"e";i(w,b)|w>b="W"++s w|b>w="B"++s b|v="N"++s(w+b);j=r 8 é;k=r 8 j//[(3,j//[(3,è v),(4,è w)]),(4,j//[(3,è w),(4,è v)])];l=empty;m=map;n=toList;o=concat;p=putStrLn;q=foldl;r=replicate;s=show;t=fromList;u=foldM;v=True;w=False;é=Nothing;è=Just ``` ``` $ printf "232425140504032627" | ./nano-rve ........ ........ ........ B.BBB... BBBWW... B.B..... ..B..... ..B..... B11 ``` # Original version - 4533 bytes I will golf when there will be competition! **edit** It has arrived ``` {-# LANGUAGE OverloadedStrings #-} import Prelude hiding ((>>=),concatMap,filter,foldl,map,null,replicate) import Control.Applicative hiding (empty) import Control.Monad import Data.Either import Data.Vector hiding ((++),concat,foldM,reverse,zip) type Case = Maybe Bool type Board = Vector (Vector Case) type Coord = (Int,Int) -- fmap (toList) $ replicateM 2 [-1,0,1] -- minus (0,0) directions :: Vector Coord directions = fromList [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)] -- [(x,y) | x <- [0..7], y <- [0..7]] allCoords :: Vector Coord allCoords = fromList [(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7),(1,0),(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(2,0),(2,1),(2,2),(2,3),(2,4),(2,5),(2,6),(2,7),(3,0),(3,1),(3,2),(3,3),(3,4),(3,5),(3,6),(3,7),(4,0),(4,1),(4,2),(4,3),(4,4),(4,5),(4,6),(4,7),(5,0),(5,1),(5,2),(5,3),(5,4),(5,5),(5,6),(5,7),(6,0),(6,1),(6,2),(6,3),(6,4),(6,5),(6,6),(6,7),(7,0),(7,1),(7,2),(7,3),(7,4),(7,5),(7,6),(7,7)] initBoard :: Board initBoard = vs // [(3,v1),(4,v2)] where va = replicate 8 Nothing v1 = va // [(3,Just True),(4,Just False)] v2 = va // [(3,Just False),(4,Just True)] vs = replicate 8 va showBoard :: Board -> String showBoard b = (concat $ toList $ map (showRow) b) ++ (showScore b) where showCase :: Case -> String showCase c = case c of Just False -> "░B" Just True -> "▓W" Nothing -> "██" showRow :: Vector Case -> String showRow r = concat (toList $ map (showCase) r) ++ "\n" showScore :: Board -> String showScore b = winner score ++ "\n" where scoreCase :: (Int,Int) -> (Maybe Bool) -> (Int,Int) scoreCase (w,b) (Just True) = (w+1,b) scoreCase (w,b) (Just False) = (w,b+1) scoreCase s _ = s scoreRow :: Vector Case -> (Int,Int) scoreRow r = foldl (scoreCase) (0,0) r score :: (Int,Int) score = foldl (\(w,b) (rw,rb) -> (w+rw,b+rb)) (0,0) $ map (scoreRow) b winner :: (Int,Int) -> String winner (w,b) | w > b = "White with " ++ show w ++ " against Black with " ++ show b ++ "." | b > w = "Black with " ++ show b ++ " against White with " ++ show w ++ "." | otherwise = "Nobody with " ++ show (w+b) ++ "." printBoard :: Board -> IO () printBoard b = putStrLn $ showBoard b pm :: Either String Board -> IO () pm (Right b) = printBoard b pm (Left s) = putStrLn s lookupBoard :: Board -> Coord -> Either String Case lookupBoard b (x,y) = case b !? y of Just col -> case col !? x of Just c -> Right c Nothing -> Left "x is out of bounds" Nothing -> Left "y is out of bounds" updateBoard :: Board -> Coord -> Bool -> Either String Board updateBoard b (x,y) c = case b !? y of Just r -> case r !? x of Just _ -> Right $ b // [(y,r // [(x,Just c)])] Nothing -> Left "x is out of bounds" Nothing -> Left "y is out of bounds" makePath :: Board -> Coord -> Bool -> Coord -> Vector Coord makePath b (x,y) c (px,py) = case lookupBoard b (nx,ny) of Right (Just pc) -> if pc == c then empty else case lookupBoard b (nx+px,ny+py) of Right (Just _) -> (nx,ny) `cons` makePath b (nx,ny) c (px,py) _ -> empty Right (Nothing) -> empty Left _ -> empty where nx = x+px ny = y+py makeMove :: Board -> Coord -> Bool -> Either String Board makeMove b xy@(x,y) c = if null cases then Left $ "impossible move " ++ show xy ++ "." else foldM (\ob (cx,cy) -> updateBoard ob (cx,cy) c) b $ toList $ cases `snoc` (x,y) where cases = join $ map (makePath b (x,y) c) directions makeMoves :: Board -> Vector (Bool,Coord) -> Either String Board makeMoves b ms = foldM (\ob (c,xy) -> case makeMove ob xy c of rb@(Right _) -> rb Left _ -> if not $ null $ findIndices (\xy -> isRight $ makeMove ob xy c) allCoords then Left $ "wrong move " ++ show xy ++ "." else makeMove ob xy (not c)) b $ toList ms movesFromString :: String -> Either String (Vector (Bool,Coord)) movesFromString cs = fromList <$> (zip $ cycle [False,True]) <$> coords cs where coords (x:y:cs) = (:) (read [x],read [y]) <$> coords cs coords (_:cs) = Left "invalid coordinates string" coords [] = Right [] isRight :: Either a b -> Bool isRight (Left _) = False isRight (Right _) = True main=getLine>>= \s->pm$movesFromString s>>=makeMoves initBoard ``` Note : Your second example should be 2324251**4**0504032627. # Tests With screenshots to prevent eye burns. ``` $ printf "232425140504032627" | ./rve ``` ![test 1](https://i.stack.imgur.com/CY8Rf.png) ``` $ printf "2324" | ./rve ``` ![test 2](https://i.stack.imgur.com/TVvUV.png) ``` $ printf "1" | ./rve invalid coordinates string ``` ``` $ printf "24" | ./rve wrong move (2,4). ``` Is is possible to get `impossible move (x,y)` when you use innardics (functions from the innards of the program and that you should not use) and `x/y is out of bounds`. [Answer] # Javascript (E6) 399 ~~412 450~~ Edit: board display shorter and nicer, cut some char ``` V=(p,b)=>b[p]==(r=0)&&[1,8,9,10].map(d=>r|=(A=(p,d,c=0)=>b[p+=d]==-v?A(p,d,1)&&(b[p]=v):c&b[p]==v)(p,d)|A(p,-d))|r&&(b[p]=v) L=console.log l=prompt().replace(/[^0-7]/g,'') for(i=B=[];++i<73;)B[i]=i%9?i-31&&i-41?i-32&&i-40?0:1:-1:-B for(v=i=1;l[i];i+=2,v=-v)V(p=l[i]*9+-~l[i-1],B)||!B.some((x,i)=>V(i,[...B]))&&(V(p,B,v=-v))||L(l='Err') t=0,L(B.map(x=>(t+=~~x,'\nO ☻'[x+2|0]))+(t?t<0?'O':'☻'+t:'=')) ``` **Ungolfed** ``` V = (p, b) => // Verify a move and if it is legal, apply the move to the board b[p]==(r=0) && // check if empty cell and init accumulator r [1,8,9,10].map(d=> // Execute flip check for each of 4 positive direction (and 4 negative too) r |= ( A=(p,d,c=0) => // Recursive function for flip check, if find it valid modify the board during return phase b[p+=d] == -v // If position contains a disk of other color ? A(p,d,1) && (b[p]=v) // recursive call. Then if returns true, set the cell in the flip sequence : c & b[p]==v // at end of check, if find the righe disk and if not the first call, return true ) // Definition of A function ends here (p,d)|A(p,-d) // Call A 2 times with d and -2 to get all 8 directions ) | r // now, r is true if any of the 8 flip checks has gone well && (b[p]=v); // if true, set the verified cell too L=console.log; l=prompt().replace(/[^0-7]/g,''); // Get input & discard invalid chars for (i=B=[];++i<73;) // Create empty board as a single dimension array, NaN mark a row end B[i] = i%9 ? i-31 && i-41 ? i-32 && i-40 ? 0: 1: -1: -B //starting values at center, -B evaluate to NaN for(v=i=1; // v is the disk color, init to 1 == black l[i]; // repeat while inside input string i+=2, v=-v) // to char of input at time, set color to opposite V( p=l[i]*9+-~l[i-1], B) // calc position in p from the input, and call Verify || // if not valid, could be Error or Skip !B.some((x,i)=>V(i,[...B])) // Check if there are no moves for the current color, for each cell call V on a copy of the board && (V(p,B,v=-v)) // If no moves found, try to apply the move for the opposite color || L(l='Err'); // If failed, it is Error. Change variable l to end the loop t=0, // Display the board while counting disk difference into 't' L( B.map(x=>(t+=~~x,'\nO ☻'[x+2|0])) // map array elements to suitable chars, then auto conversion to string give a nice effect + (t?t<0?'O':'☻'+t:'=') ) // Display leading and count difference or '=' ``` **Test** Test in javascript console (FireFox): `232425140504032627` `, , , , , , , , , , , , , , , , , , , , , , , , , , , ,☻, ,☻,☻,☻, , , , ,☻,☻,☻,O,O, , , , ,☻, ,☻, , , , , , , , ,☻, , , , , , , , ,☻, , , , , , ☻9` ]
[Question] [ Your challenge is to take input like this (a Hello World program): ``` ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++. ``` And output a prompt (which will be `"> "`): ``` > ``` The user can then enter anything at the prompt. Your simple debugger must have these commands: * `S` - step + Output the current location (see `L`) after stepping. + `S(a positive integer)` - step that many spaces * `L` - location + The term "location" always refers to where you are in the program (i.e., the instruction pointer). + Formatted like this: ``` v +++++++[>+++++++<-]>. ``` This means that the current location of the program is at the third `+`. * `G(an integer)` - go to + This means keep stepping until you get to that location. If you reach the end of the program and you haven't gotten there, simply exit the program. + A negative integer means that many characters from the end. Yes, this means that `-0` is different than `0`, and `-1` is the second to last character. + Don't output anything for this command. * `D` - dump array + Formatted like `1, 2, 3, 4, 5` + If the array is `1, 2, 3, 0, 0, 0, 0, 0, ...`, only output `1, 2, 3`. + `D(a positive integer) (a positive integer)` - dump all array items between those two positions (inclusive) * `(a positive integer)` - output the item currently at that array position * `P` - output the index of the BF pointer (the thing you change with `>` and `<`). When the program requests input, show the prompt `"I> "`. (You may input one character at a time.) When it outputs something, show `"O> " + (the output)`. Multiple outputs between commands must be chained together (i.e. you can't do `> G-0 O> H O> e O> l O> l O> o ...`, it has to be `> G-0 O> Hello, World!`). Output "Done" and exit once you reach the end of the program. --- Sample run: ``` ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++. > S 1 > S 2 > S2 4 > S0 4 > L v ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++. > D 4 > 0 4 > D10 15 0, 0, 0, 0, 0, 0 > G-0 O> Hello, World! Done ``` Sample run showing stepping through loops and the `P` instruction (calculates `3*2+1`) ``` +++[>++<-]>+ > S3 3 > L v +++[>++<-]>+ > S3 6 > L v +++[>++<-]>+ > P 1 > S3 9 > L v +++[>++<-]>+ > S 3 > L v +++[>++<-]>+ > D 2, 2 > ``` Sample run showing I/O ``` >+[>,---------------------------------]<[<]>[>.] > G37 I> H I> e I> l I> l I> o I> ! > D 0, 39, 68, 75, 75, 78 > G-0 O> 'DKKN Done ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code will win. [Answer] # PHP - 1008 ``` <?php $_=trim(fread(STDIN,1e5));$z=$p=0;$t=$l=[];$q='';function s(){global$p,$t,$l,$_,$q,$z;switch($_[$z++]){case'>':$p++;break;case'<':$p--;break;case'+':@$t[$p]++;break;case'-':@$t[$p]--;break;case'.':$q.=chr($t[$p]);break;case',':echo"I>";$t[$p]=ord(trim(fread(STDIN,2)));break;case'[':$l[]=$z;if(!isset($t[$p])||$t[$p]==0){$c=1;while($c>0){$b=$_[$z++];if($b=='[')$c++;elseif($b==']')$c--;}array_pop($l);}break;case']':$z=array_pop($l)-1;break;}if($z==strlen($_)){if($q)echo'O>'.$q."\n";die("Done\n");}}for(;;){echo">";$c=trim(fread(STDIN,1e5));$g=strlen($c);switch($c[0]){case'L':echo str_repeat(' ',$z)."v\n".$_."\n";break;case'D':if($g)$x=$t;else{list($a,$b)=explode(' ',substr($c,1));$x=array_slice($t,$a-1,$b);}echo implode(', ',$x)."\n";break;case'S':if($g)s();for($i=0;$i<substr($c,1);$i++)s();echo $z."\n";break;case'G':if($c[1]=='-')$x=strlen($_)-substr($c,2);else$x=substr($c,1);while($z!=$x)s();break;case'P':echo$p."\n";default:if(is_numeric($c))echo$t[$c]."\n";}if($q)echo'O>'.$q."\n";$q='';} ``` The output for cells that were never written is slightly different: ``` [timwolla@/data/workspace/php/PCG]php pcg-22585.php + >D15 20 > ``` Large version: ``` <?php $_=trim(fread(STDIN,1024)); $z=$p=0; $t=$l=[]; $q=''; function step() { global $p, $t,$l,$_,$q,$z; switch ($_[$z++]){ case '>': $p++; break; case '<': $p--; break; case '+': @$t[$p]++; break; case '-': @$t[$p]--; break; case '.': $q.=chr($t[$p]); break; case ',': echo "I>"; $t[$p] = ord(trim(fread(STDIN, 2))); break; case '[': $l[] = $z; if (!isset($t[$p]) || $t[$p] == 0) { $counter = 1; while ($counter > 0) { $char = $_[$z++]; if ($char == '[') $counter++; else if ($char == ']') $counter--; } array_pop($l); } break; case ']': $z = array_pop($l)-1; break; } if($z==strlen($_)) { if ($q) echo 'O>'.$q."\n"; die("Done\n"); } } for(;;){ echo ">"; $c=trim(fread(STDIN,100)); switch ($c[0]) { case 'L': echo str_repeat(' ', $z)."v\n".$_."\n"; break; case 'D': if(strlen($c) == 1)$x=$t; else { list($a,$b)=explode(' ',substr($c,1)); $x=array_slice($t,$a-1,$b); } echo implode(', ', $x)."\n"; break; case 'S': if(strlen($c)==1)step(); for($i=0;$i<substr($c,1);$i++)step(); echo $z."\n"; break; case 'G': if($c[1]=='-')$x=strlen($_)-substr($c,2); else $x=substr($c,1); while ($z!=$x)step(); break; case 'P': echo $p."\n"; default: if(is_numeric($c)) echo $t[$c]."\n"; } if ($q) { echo 'O>'.$q."\n"; $q=''; } } ``` ]
[Question] [ Find Santa and his reindeer in a crowded scene. ## Input Input will be on STDIN and will be a variable number of lines of characters of equal, but variable, length. If Santa (represented by the character `S`) is in the scene, his sack of presents (represented by the character `P`) will be in one of the positions adjacent to him (horizontally, vertically or diagonally). His reindeer (each represented by the character `R`) will all be within the 5x5 square surrounding him. If an `S` appears in the scene that does not have a sack of presents, or is not accompanied by at least 4 reindeer, then it is not Santa. ## Output The scene cleared of all obfuscation (all non-Santa, non-presents, non-reindeer characters replaced with a space), showing Santa, his sack of presents, and his reindeer - all other characters should be replaced with spaces. If Santa and his reindeer are not in the scene, output it unchanged. It is guaranteed that there will only be one solution, so there will never be more than one valid Santa and he will never be carrying more than one sack of presents. ## Examples In these examples I'm just using the `*` character to make it easy to see the `S`, `P`, and `R` characters, but your program should be able to handle any ascii character from `!` to ``` (33 to 96). I've left out lower case characters and above to avoid confusion. **Input:** ``` *********** *********** *********** *****R***** ******P**** *****S***** *****R***** ****R**R*** *********** *********** *********** *********** ``` **Output:** (ignore dots, they're to force the page to show the blank lines) ``` . . . R P S R R R . . . . ``` **Input:** (not enough reindeer) ``` *********** *********** *********** *********** ******P**** *****S***** *****R***** ****R**R*** *********** *********** *********** *********** ``` **Output:** ``` *********** *********** *********** *********** ******P**** *****S***** *****R***** ****R**R*** *********** *********** *********** *********** ``` **Input:** (no sack of presents) ``` *********** *********** *********** *****R***** *********** *****S***** *****R***** ****R**R*** *********** *********** *********** *********** ``` **Output:** ``` *********** *********** *********** *****R***** *********** *****S***** *****R***** ****R**R*** *********** *********** *********** *********** ``` **Input:** (presents not close enough) ``` *********** *********** *********** *****R***** *********** *****S*P*** *****R***** ****R**R*** *********** *********** *********** *********** ``` **Output:** ``` *********** *********** *********** *****R***** *********** *****S*P*** *****R***** ****R**R*** *********** *********** *********** *********** ``` **Input:** (one of the reindeer not within the 5x5 square around Santa) ``` *********** *********** *********** *****R***** ******P**** *****S***** *****R***** ****R****** *******R*** *********** *********** *********** ``` **Output:** ``` *********** *********** *********** *****R***** ******P**** *****S***** *****R***** ****R****** *******R*** *********** *********** *********** ``` ## Test Scripts As in some of my past questions, I've once again butchered some test scripts originally created by [Joey](https://codegolf.stackexchange.com/users/15/joey) and [Ventero](https://codegolf.stackexchange.com/users/84/ventero) to provide some test cases for this question: * [bash](http://www.garethrogers.net/tests/seekingsanta/test) * [Powershell](http://www.garethrogers.net/tests/seekingsanta/test.ps1) Usage: `./test [your program and its arguments]` Plain text version of the tests for reference: [Plain text](http://www.garethrogers.net/tests/seekingsanta/tests.txt) ## Rewards Each entry which I can verify that meets the spec, passes the tests and has obviously had some attempt at golfing will receive an upvote from me (so please provide usage instructions with your answer). The shortest solution by the end of 31/12/2013 will be accepted as the winner. [Answer] ## MATLAB: 110 ~~,95~~ characters ``` f=@(x,y) filter2(ones(x),y);a=M==83;b=M==82;c=M==80;d=f(5,a&f(5,b)>3&f(3,c))&(a|b|c);if ~d,M,else,M(~d)=32,end ``` Not sure about the way input is supposed to be processed, but the rest is pretty straightforward. Normally formatted version: ``` f=@(x,y) filter2(ones(x),y); a=M==83; b=M==82; c=M==80; d=f(5,a&f(5,b)>3&f(3,c))&(a|b|c); if ~d M else M(~d)=32 end ``` Example input: ``` M=['***********' '***********' '***********' '*****R*****' '******P****' '*****SQL_2*' '*****R*****' '****R**R***' '***********' '***********' '***********' '***********']; ``` [Answer] # Python 2 (~~353~~ 381) ``` import re,sys a=sys.stdin.readlines() h=len(a) w=len(a[0]) a=''.join(a)+' '*99 print a b=[''.join(q) for x in range(0,w) for y in range(0,h) for q in [[a[(y+z)*w+x:(y+z)*w+x+5] for z in range(0,5)]]] for c in b: if c[12]=='S' and 'P' in ''.join([c[1+5*z:4+5*z] for z in range(1,4)]) and c.count('R')>3: a=re.sub('[^RPS]','.',c) w=h=5 for y in range(0,h): print a[y*w:(y+1)*w] ``` First attempt at writing code as compact as possible. Python is not really the language for that, as indentation and newlines are simply required by design. I mainly choose to use this language, because of the way you can play with lists, and strings as lists. A language with easy matrix manipulation would be ideal for this task, but sadly I don't know any of them. ~~To test thing, something needs to be assigned to a, e.g.~~ ``` a=['1**********','*2*********','**3********','***4*******','****5*P****','*****S*****','*****,*****','****R**R***','***********','***********','****R******','**RPSRRR***'] ``` Main interesting thing in this code is probably: ``` b=[''.join(q) for x in range(0,w) for y in range(0,h) for q in [[a[(y+z)*w+x:(y+z)*w+x+5] for z in range(0,5)]]] ``` which is a fancy way of writing: "b becomes a list of a representation (string of 25 characters) of every 5x5 square in the original representation". [Answer] There should be only one Santa in file (if more than 2 "S", I need update the code). Using awk ``` cat santa.awk BEGIN{FS=""} { for (i=1;i<=NF;i++) { a[NR FS i]=$i if ($i=="S") {l=NR;c=i} } } END{ if (l=="") {print "No Santa";exit} for (i=l-1;i<=l+1;i++) for (j=c-1;j<=c+1;j++) if (a[i FS j]=="P") p++ if (p<1) {print "Santa has no presents";exit} for (i=l-2;i<=l+2;i++) for (j=c-2;j<=c+2;j++) if (a[i FS j]=="R") r++ if (r<4) {print "Santa has no enough reindeers";exit} else { print "found Santa " for (i=1;i<=NR;i++) { for (j=1;j<=NF;j++) if (a[i FS j]~/[R|S|P]/) {printf a[i FS j]} else {printf " "} printf RS } } } ``` Run awk command as below ``` awk -f santa.awk file ``` Result ``` found Santa R R R PS RR R R ``` ]
[Question] [ ### Task Suppose that `p` pepole have to split a bill; each of them is identified by a triple `(Name, n, k)` made up of: * `Name`: *the name*; * `n`: *the amount she/he has to pay*; * `k`: *the amount she/he actually paid*. The challenge here is to find out how much who owes whom. ### Assumptions * Input and output can be in any convenient format. * `p` \$\in \mathbb{N}, \,\;\;\$`n` \$\in \mathbb{N}^{+},\;\$ `k` \$\in \mathbb{N}.\$ * `p` \$\gt 1.\$ * Names are unique strings of arbitrary length, composed of lower case alphabet characters. ### Solution The solution is represented by the minimum set of transactions among the `p` people; in particular they are triples `(from, to, amount)` * `from`: `name` of the person that gives money; * `to`: `name` of the person that receives money; * `amount`: amount of money of the transaction. **NOTE**: The sum of all the debts (`n`) can differ from the sum of all the already payed amounts (`k`). In this case, you must add in the output `('owner', Name, amount)` or `(Name, 'owner', amount)` in the format you have chosen. Any name will never be `owner`.The string 'owner' is flexible. If several mimimum sets exist, select the one with the minimum sum of all the transaction amounts (absolute values); in case of a tie, choose one of them. ### Test Cases: ``` inputs(Name,n,k): [('a',30,40),('b',40,50),('c',30,15)] [('a',30,30),('b',20,20)] [('a',30,100),('b',30,2),('c',40,0)] [('a',344,333),('b',344,200),('c',2,2)] [('a',450,400),('b',300,300),('c',35,55)] outputs(from, to, amount): [('c','a',10),('c','b',5),('owner','b',5)] or [('c','b',10),('c','a',5),('owner','a',5)] [] [('owner','a',2),('b','a',28),('c','a',40)] PS: [('owner','a',2),('b','a',68),('c','b',40)] has the same number of transactions, but it is not a valid answer, because the total amount of its transaction is greater than that of the proposed solution. [('a','owner',11),('b','owner',144)] [('a','owner',30),('a','c',20)] ``` **This is code-golf: shortest code wins**. [Answer] # JavaScript (ES6), ~~252 227 223 222~~ 215 bytes Takes input as `[[n0, k0, name0], [n1, k1, name1], ...]`. Transactions in the solution may be either positive or negative. The owner is called *undefined*. ``` a=>(m=g=(B,t,s)=>B.some(x=>x)?B.map((b,x)=>B.map((c,y)=>b*c<0&b*b<=c*c&&g(C=[...B],[...t,[a[x][2],b,a[y][2]]],s+a.length-1/b/b,C[C[y]+=b,x]=0))):m<s||(r=t,m=s))([...a.map(([x,y])=>t-(t+=y-x),t=0),t],[],a.push(g))&&r ``` [Try it online!](https://tio.run/##bVJNb9pAEL3nV4zUit0Ng2PzkVaEJQqUVj1UPSQ314exMeDI2Mi7pqDS307HToCGcLH37Xvz5s1on2lNJiqSlW1l@TTez/Se9FAu9VzLEVo0Sg9HjsmXsdzo4Ubdj5wlraQMcVMzNYhwyyC8jgZuI7wOBzq6jhqNuRxr33GcUYDVz6JP/ibw2wGGSP62OgUBmiY5aZzN7aLl3YQ3IY79MZNNzR0C7Sql@suB2e1koS0utVFKVm700tnf4Dbg3rYlbVNvWxuFlovQcs8AyVmVZiHnSjUaxf7OvwLw/Y6LXRcFiQDB51OPQVgDZrweikhwrIO0c5S2XWy/SE@s5x5pRu2DEbu6b3y6Xex0Okcpw7Z7bNuuCk/ibq8K@J9vFeKUsYe9Nxk9TvEZxUOaRHGt4ItbFKM8PCCWjxdUpMmR9z6h@ELrZHq46KKYrE80J/2apMnqcMHyb1RsuedVcOXM8mJC0UJKQkgU6CH84SRRnpk8jZ00n0vxNHl8gvHD4wQ@CGiCTPjjKXV3rvuVfc9Wpe2LdxRdEv8s7WV1ERvQMOOqS2VVBFa8PjMGAmxBmaHIJnkmjULgmYDA5pZSyGfw8VBSxNMyiqU0CFSPapj4QXbhUGgk@V7Axa6qPC/Hen2mpcsGCCXrKxfRgnovkmAALtwzAX0o2Wi3A2EXMeS/s7gQtTHMkzXPV2c6tX6hbH5u5FZG3jsj5TznSVZvQ6nzFbUED7qKycrbbrXBv2r/Dw "JavaScript (Node.js) – Try It Online") ### Commented ``` a => ( // a[] = input array m = // initialize m to a non-numeric value g = (B, t, s) => // g = function taking: B = balances, t = transactions, // s = score of the current solution B.some(x => x) ? // if at least one balance is not equal to 0: B.map((b, x) => // for each balance b at position x: B.map((c, y) => // for each balance c at position y: b * c < 0 & // if b and c are of opposite sign b * b <= c * c && // and |b| <= |c|, g( // do a recursive call to g: C = [...B], // - with a copy C of B [ ...t, // - append the new transaction to t[] [a[x][2], b, a[y][2]] // in [from_name, amount, to_name] format ], // s + a.length - 1/b/b, // - add (a.length - 1/b²) to s C[C[y] += b, x] = 0 // - update C[y] and clear C[x] ) // end of recursive call ) // end of inner map() ) // end of outer map() : // else: m < s || // if the score of this solution is lower than m, (r = t, m = s) // update r to t and m to s )( // initial call to g: [ // build the list of balances: ...a.map(([x, y]) => // each balance is equal to: t - (t += y - x), // due_value - paid_value t = 0 // keep track of the total t ... ), // t // ... which is appended at the end of this array ], // (this is the balance of the owner) [], // start with t = [] a.push(g) // append a dummy owner to a[]; start with s = 1 ) && r // return r ``` ]
[Question] [ This challenge is completely ripped off*heavily inspired by* [All Light](https://play.google.com/store/apps/details?id=com.soulgit.allightflowpuzzle.gp), developed by Soulgit Games. # Challenge You are an electrician, and it's your job to wire up all the lights to the battery. * The lights and battery are laid out in a grid. * You can connect a light or battery to the nearest light or battery to its north, south, east, and west. * The battery can have any number of connections. * Each light specifies how many connections it requires. You must make *exactly* that many connections to that light. * You can create single connections or double connections between two lights (or light and battery). * Wires cannot cross. * There must be a path from each light to the battery. * At least one valid solution is guaranteed to exist. Given the position of the battery and each light, and the number of connections each light requires, output the connections between them that admit these properties. # Win Condition This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in each language wins. # Test Cases I/O is flexible as usual. For input I will be using a 2d array the size of the grid which stores positive integers for lights, zeros for blank spaces, and -1 for the battery. Another good choice might be a list of lights, where a light is a tuple containing the light's position and number of required connections. For output I will be using a list of connections, where a connection is a tuple containing the starting position and ending position. If a connection is doubled then I will have 2 of them in the list (another option is to include this parameter in the tuple). Another good option could be some sort of grid layout. If you are using a coordinate system you may specify the starting index and where you index from. My examples will be 0-indexed and use (0, 0) as the top left corner (row, column). (I am using {} simply to introduce another type of delimiter so it is easier to read, *not* because they are sets.) ***Here is a graphical view of the test cases: [Tests 1-12](https://i.stack.imgur.com/dKPmI.jpg)*** ### Test 1: `[-1 | 0 | 1 ] => [{(0, 0), (0, 2)}]` ### Test 2: `[-1 | 0 | 2 ] => [{(0, 0), (0, 2)}, {(0, 0), (0, 2)}]` ### Test 3: `[-1 ] [ 0 ] => [{(0, 0), (2, 0)), ((0, 0), (2, 0)}] [ 2 ]` ### Test 4: `[ 1 | 0 |-1 | 0 | 2 ] => [{(0, 0), (0, 2)}, {(0, 2), (0, 4)}, {(0, 2), (0, 4)}]` ### Test 5: `[ 2 ] [ 0 ] [-1 ] => [{(0, 0), (2, 0)}, {(0, 0), (2, 0)}, {(2, 0), (4, 0)}] [ 0 ] [ 1 ]` ### Test 6: `[ 1 | 0 | 0 ] [ 0 | 0 | 0 ] => [{(0, 0), (2, 0)}, {(2, 0), (2, 2)}] [ 2 | 0 |-1 ]` ### Test 7: `[ 4 | 0 | 0 |-1 ] [ 0 | 0 | 0 | 0 ] => [{(0, 0), (0, 3)}, {(0, 0), (0, 3)}, [ 2 | 0 | 0 | 0 ] {(0, 0), (3, 0)}, {(0, 0), (3, 0)}]` ### Test 8: `[ 2 | 0 |-1 | 0 | 2 ] [{(0, 0), (0, 2)}, {(0, 0), (0, 2)}, [ 0 | 0 | 0 | 0 | 0 ] => {(0, 2), (0, 4)}, {(0, 2), (0, 4)}, [ 0 | 0 | 1 | 0 | 0 ] {(0, 2), (2, 2)}]` ### Test 9: `[ 0 | 0 | 2 | 0 | 0 ] [ 0 | 0 | 0 | 0 | 0 ] [ 1 | 0 |-1 | 0 | 1 ] => [{(0, 2), (2, 2)}, {(0, 2), (2, 2)}, {(2, 0), (2, 2)}, [ 0 | 0 | 0 | 0 | 0 ] {(4, 2), (2, 2)}, {(2, 4), (2, 2)}, {(2, 4), (2, 2)}] [ 0 | 0 | 2 | 0 | 0 ]` ### Test 10: `[-1 | 2 | 3 | 2 ] => [{(0, 0), (0, 3)}, {(0, 0), (0, 3)}, {(0, 0), (0, 3)}, {(0, 0), (0, 3)}]` ### Test 11: `[-1 | 0 | 0 | 0 ] [ 3 | 0 | 0 | 0 ] [ 3 | 0 | 0 | 3 ] => [{(0, 0), (1, 0)}, {(1, 0), (2, 0)}, {(1, 0), (2, 0)}, [ 0 | 0 | 0 | 0 ] {(2, 0), (2, 3)}, {(2, 3), (4, 3)}, {(2, 3), (4, 3)}] [ 0 | 0 | 0 | 2 ]` ### Test 12: `[ 2 | 0 | 0 ] [{(0, 0), (1, 0)}, {(0, 0), (1, 0)}, {(1, 0), (1, 1)}, [ 3 |-1 | 0 ] => {(1, 1), (2, 1)}, {(1, 1), (2, 1)}, {(2, 0), (2, 1)}, [ 2 | 5 | 1 ] {(2, 0), (2, 1)}, {(2, 1), (2, 2)}]` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~393~~ ~~391~~ 378 bytes ``` a=>(R=[],f=(a,[x,...y],z,Y)=>x?f(a.map(t=>[...t]),y,z,Y)||f(a,y,[...z,x],Y.map(p=>p.map(q=>q-Y[x[0]][x[1]]?q:Y[x[2]][x[3]])),--a[x[0]][x[1]],--a[x[2]][x[3]]):/[1-9]/.test(a)|Y.some(t=>t.some(u=>u-Y[I][J]&&u))?0:z)(a=a.map(A=(b,i)=>b.map((x,j)=>x&&(A[i]+1&&R.push([i,A[i],i,j]),f[j]+1&&R.push([f[j],j,i,j]),A[I=i]=j,f[J=j]=i,x/=x>0))),[...R,...R],C=[],a.map(p=>p.map(q=>q&&++C))) ``` [Try it online!](https://tio.run/##fVFLb4JAEL73h5DdOCAL7aE2izEmJnrkRjZzWC22EBUs0KDxv9NdIPgoeGFn9nvszEcsf2W2@YnS3Dwkn2G14JXkHvG5QNhyIkGUYFnWCeEMAeVeOd0Sae1lSnLuCYXkSOFUg5eLglStb89QIgQ1L@VeWhdH7h3NQJTCRlRfhjg9TnTv1L2LSCmYprxltP2VMRkLZr7j2MrDLCeSXgIrS/ahniZvqoJ7hXpmiWKFhlFQOrUnZ0okb8aecbKGSG2yrltSQqzXMgwyExGOmGH4Vlpk30REoG8gglituBXxHah7iFtwJpY8Qh4r1orHyCMox7z0bKoW0mn4OkIfYa5Tlf9TMYzRaK7I1cfLJjlkyS60dskXWRAhTAY2MB1NP@QMQAgqRBD9sBY@UTutuHNhgy4atdvTqV17qa@aAo0f3PJ11TvCdcJO0j3GBmUadW7HautuYdZj5wzaKYkD7mDGnYv7ULl3ezaVM7hno9N2dShvz343e8i7dq3@AA "JavaScript (Node.js) – Try It Online") ``` a=>( a=a.map( A=(b,i)=> b.map( (x,j)=> x&&( // A[i]+1 <==> A[i] is NOT NaN A[i]+1&&R.push([i,A[i],i,j]), // Use A and f to store last f[j]+1&&R.push([f[j],j,i,j]), // existance of row and column A[I=i]=j,f[J=j]=i,x/=x>0 // -1 => -Inf, +n => n ) ), R=[], f=([x,...y],z,Y)=> x? f( y,[...z,x], Y.map(p=>p.map(q=>q-Y[x[0]][x[1]]?q:Y[x[2]][x[3]])), // merge --a[x[0]][x[1]],--a[x[2]][x[3]] )|| f(y,z,Y,++a[x[0]][x[1]],++a[x[2]][x[3]]) : /[1-9]/.test(a)| Y.some(t=>t.some(u=>u-Y[I][J]&&u)) // not totally merged ?0:z ),f)([...R,...R],[],a.map(p=>p.map(q=>q&&++C),C=0) ) ``` ]
[Question] [ Input: Firstly An array of three cards representing the cards played by each player formatted like ``` [JD][TH][9S] ``` Representing ``` Jack of Diamonds, 10 of Hearts, and Nine of Spades. ``` As you always sit across from your team-mate in Euchre, the second element represents your team mate's play. Here, the `TH`. Secondly A Single Char, String, etc representing the trump suit formatted like ``` S, D, C, H ``` representing ``` Spades, Diamonds, Clubs, Hearts ``` Thirdly an array of four cards representing your hand formatted like ``` [KD][JC][QH][AS] ``` representing ``` King of Diamonds, Jack of Clubs, Queen of Hearts, Ace of Spades ``` ### Objective: Given the three inputs, output the best possible card to add to the cards that have been played such that it meets the following criteria: 1. It takes the hand if it can, if not output the least valuable card 2. It takes the hand if it can, however it will not trump your team mate unless it is unavoidable 3. If it can take the hand, it does so by using the least valuable card. (If you have an ace and a queen that can win the hand, you play the queen). 4. Any plays must follow suit as required by the rules at the bottom. Output format like `[JD]` ### Formatting ``` A - Ace K - King Q - Queen J - Jack T - Ten 9 - Nine H - Hearts D - Diamonds S - Spades C - Clubs TH, 9D, JD, QH, AD, 9C, TC ``` ### Examples In: `[QD][KD][9C]`, `"C"`, `[AH][JH][QH][9H]` Out: `9H` Reason: As clubs are trump, the 9C is winning the hand, we are unable to take the hand so we should discard our lowest card, here the `9H` In: `[QD][KD][AD]`, `"H"`, `[AH][JH][QH][9H]` Out: `9H` Reason: As Hearts are trump, the Ace of Diamonds is currently winning the hand, we are able to trump the hand so we should use our lowest card, here the `9H` In: `[QD][KD][TD]`, `"D"`, `[AD][JH][QH][9D]` Out: `9D` Reason: As diamonds are trump and we are currently winning the hand, we should play the 9D because our partner currently is winning the hand, so we want to play the `9D` over the `AD` In: `[QH][KH][JH]`, `"D"`, `[AD][JD][QH][9D]` Out: `QH` Reason: As Diamonds are trump our opponents are winning with the left Bower `JH` We have the right bower but cannot trump him because QH was led and we must follow suit, the `QH` In: `[QH][KH][JH]`, `"D"`, `[AD][JD][QC][9D]` Out: `JD` Reason: As Diamonds are trump our opponents are winning with the left Bower `JH` We have the right bower and since we have no `Diamonds` we can trump over him with the `JD` ### Euchre Card Strengths If Hearts is trump: ``` JH JD AH KH QH TH 9H ``` See the Euchre Rules if you are unfamiliar with the strength of different cards in [Euchre](https://www.hoylegaming.com/rules/showrule.aspx?RuleID=209) Since this is Code-Golf the shortest code wins! Good Luck and have fun! [Answer] # Perl - ~~557 532 511 490 482 384~~ 363 ``` ($p,$t,$h)=@ARGV;%L=(H=>D,D=>H,C=>S,S=>C);$B=%L{$t};$_="\]$p$h\[";s/(.$t)/0$1/g;s/J$B/01$B/;s/0J/00/;s/J/R/g;s/9/Z/g;($T,@C)=split/\]\[/,$_;$s=$C[0];$s=~s/.+(.)/$1/;$s=~s/$t/0/;$X=(sort@C[0..2])[0];@M=@C[3..6];@F=(grep{/$s/}@M);@M=@F if@F;$w=(sort@M)[@M-1];push@M,$X;foreach$g(sort@M){$g ne$X?$b=$g:last}$_=$C[1]eq$X||!$b?$w:$b;s/.(..)/$1/;s/Z/9/;s/0|1|R/J/;print ``` ### How it works [Try it online!](https://tio.run/##NY9fa8IwFMW/ipMrpCxL2o0NakitVlzp7IM6RlkaREdtBdGu6fDBuq/eXcU9nOQc7h/ur8yq3XPbEigp1BQKS/rD@euH6E0lCaU3pmPphTSQ3oIupBdYAkayNz1BfRawlN1UQwlFqrrCcMKgtrgNDs8xRTDitoMPejvitn0xEZ9fiy7/xJ/AO/UDS5pyt615qlPFKSwFGAmBsvXF/BrO7gmzOG69Zag57oJEEnOoah87GXvU1mXAjyXmJ8Ze0E8kyausPHEw/OzH1rU66Ww3/kTA8TYdW8qPHxwtyh9T@DGFRGwOVbb6KiD/7zhB3tlnkAxgLSHv71amPiM73ujo7BuSprmD9QCOfVgjGiPsdq5BSPeK3zjNHNlFWW33ddu2ajbW6g3lBroNWjUMtYpQM5Qb6j8 "Perl 5 – Try It Online") First it reads args and finds the left-bauer's suit (jack of the same color as trump) with a hash lookup: ``` ($p,$t,$h)=@ARGV; %L=(H=>D,D=>H,C=>S,S=>C); $B=%L{$t}; ``` Then it combines all cards into one string and does some replacements, making the cards naturally sort in the correct order for euchre: ``` $_="\]$p$h\["; s/(.$t)/0$1/g; # trump cards start with '0' s/J$B/01$B/; # left-bauer's 'J' changes to '01', making it trump s/0J/00/; # right-bauer's 'J' changes to '0' s/J/R/g; # all other jacks have 'J' changed to 'R' s/9/Z/g; # all 9s change to Z ($T,@C)=split/\]\[/,$_; ``` At the end of this block, the card string is then split on the brackets, which builds an array of all cards where: * index 0 = opponent's lead card * index 1 = teammate's card * index 2 = other opponent's card * indices 3-6 represent the hand The lead suit is parsed from the first card, but the suit changes to '0' to represent trump if trump was led: ``` $s=$C[0]; $s=~s/.+(.)/$1/; $s=~s/$t/0/; ``` The best card in-play is found by sorting the first three cards and retrieving the first card: ``` $X=(sort@C[0..2])[0]; ``` The playable cards are found. If any cards in-hand match the lead suit, then only those cards remain. Otherwise all cards are considered playable: ``` @M=@C[3..6]; @F=(grep{/$s/}@M); @M=@F if@F; ``` The 'throwaway' card is found by returning the last card in the sorted array of playable cards: ``` $w=(sort@M)[@M-1]; ``` The lowest 'winning' card that can win the trick is found by adding the highest card in-play to the array of playable cards, sorting the array, and iterating over it until the highest card in-play is found. The 'winning' card is the card from the previous iteration: ``` push@M,$X; foreach$g(sort@M){$g ne$X?$b=$g:last} ``` The correct play is then evaluated. The 'throwaway' card is chosen if any of the following are true: 1. The best card on the table has an index of 1 in the unsorted array of all cards, meaning it belongs to our teammate 2. The search for the lowest 'winning' card came up null, meaning our opponent's best card is higher than all cards in the hand Otherwise the 'winning' card is returned: ``` $_=$C[1]eq$X||!$b?$w:$b; s/.(..)/$1/; # remove the '0' that indicated trump s/Z/9/; # get those 9s back s/0|1|R/J/; # fix the jacks print ``` ]
[Question] [ Inspired by the [Lego gear ratios](https://codegolf.stackexchange.com/questions/7143/lego-gear-ratios) challenge by Keith Randall. I, too, plan on building a giant lego robot that will eventually be able to destroy the other robots in the never-before-mentioned competition.\* In the process of constructing the robot, I will be using a lot of gear trains to connect different parts of the robot. I want you to write me the shortest program that will help me construct the complex gear trains that are required for such a complex task. I will, of course, only be using gears with radii 1, 2, 3, and 5 arbitrary-lego-units. Each gear in the gear train has a specific integer coordinate on a 2D grid. The first gear is located at (0,0) and the final gear will be located at non-negative coordinates. The location and size of the first and last gears will be provided as input, your program must tell what gears go where to fill in the gaps. Additionally, your program must use the **minimum possible number** of gears in the gear train. Fewer gears / train = more trains\*\* = bigger and better robot of destruction. **Input** will consist of one line: ``` X,Y,B,A ``` X and Y are the coordinates of the final gear. The first gear is always located at (0,0). B and A are the radii of the final and initial gears, respectively. To add some difficulty, you need to make sure that the output gear **rotates in the correct direction.** If A and B have the same sign, then the output gear needs to rotate in the same direction, and an odd number of gears must be used. If they have opposite signs, then an even number of gears need to be used. **Output** should be a list of the X location, Y location, and radii of each additional gear, one gear per line. If there are multiple minimal-gear solutions, print only one of your choice. The order of gears in the output does not matter. **Examples (more equivalent solutions may be possible):** ``` in 4,0,1,1 out 2,0,1 in 7,7,-2,-2 out 4,3,3 OR 0,7,5 OR the above reflected over y=x line in 7,8,-1,2 out 7,0,5 7,6,1 OR 7,0,5 1,8,5 in 7,7,2,-2 out 4,-3,3 7,1,2 12,1,3 12,7,3 OR any permutation of the above, or reflected over y=x line Now you're thinking with gear trains! ``` Here's the solutions to the above examples, visualized: [![enter image description here](https://i.stack.imgur.com/KCTdx.png)](https://i.stack.imgur.com/KCTdx.png) As far as I know, no problem is impossible unless the two input gears overlap or directly connect. You won't have to deal with this. This is code golf, shortest answer wins. --- \*A future KOTH, anyone? \*\*CHOO CHOO!! [Answer] # C#, 660 bytes ``` using System.Linq;using System;class P{int p=1,x,y,r;P l;static void Main(){var Q="$&.$'7$(@$*R$'/$(8$)A'(A('A$+S$(0$)9'(9('9$*B$,T$*2$+;$,D$.V*,V,*V";var I=Console.ReadLine().Split(',').Select(int.Parse).ToList();int i=0,t,s=7,u,v,w,p=I[3]*I[2];for(var D=new[]{new P{r=Math.Abs(I[3]),l=new P{r=Math.Abs(I[2]),x=I[0],y=I[1],p=3}}}.ToList();i>=0;){P c=D[i++],l=c.l;for(;(l=l?.l)!=null&&(s=(t=c.x-l.x)*t+(t=c.y-l.y)*t-(t=c.r+l.r)*t)>0;);if(s==0&&l.p>2&p*c.p<0)for(i=-1;c.l.p<3;c=c.l)Console.WriteLine(c.x+","+c.y+","+c.r);for(t=0;s>0&t<66;t++)for(u=Q[t++]-36,v=Q[t++]-36,s=1;s++<5&Q[t]%9==c.r;w=u,u=v,v=-w,D.Add(new P{l=c,r=Q[t]/9-4,x=c.x+u,y=c.y+v,p=-c.p}));}}} ``` [Try It Online](https://tio.run/nexus/cs-mono#bVDBjtowEP2VFLmJHU@8IbRQ5DUtLRekXYldVvSAckhDtrXkhjR2Agjx7XSSthKHXux5M573nt@1sbr87q1P1hU/xYMuf8nbjsxNZq23OuvSeZUawhFOUMuVZ6R1mdO51@71znvMdEnZuc1q70kNiC9IMCH0EwmfSXBH6AfC5gGd02BO@JrQmLBpQKc0mJLwM4EXEiaESwILIjYhbCDcDGRHtVRf9qXdm0I8F9kOvRWUiXVltKMBBFgWpsgdRWtildW2YOJl/6Cto0x2drWKwYFVE2ighQNUarkdpeFym6TydV/TTmKhyuKwTc944idr9Zi5H2L@zdLuKQOj/jNIcHBErjiFE17DFJlHl8vlRn2mYsnOKy9Xi63mPEWiXJheVVKjzEdh2BtVNsb4PrWKOhwfIyOOLHS8RydEJ0RRj2puRI2IzZBX6lfcUbHvG1HNEr8Kc1Hdx6xj1yoaSpTCxkjmnSj7l@HXWruiDxG1@AAGHFX@3jXrvTm0bWex7@7HY@k47ykb9bTFOo1GY2hvaquG0nJ@/97HXvp2qjqf8qAaaFSLL6MDLMR8t6N/IsQEoO7W07tp9A4D7Fw0mGDnosUII/zFhTGJSV6vE5hAAlHyGw) This was a *lot* of fun!! Complete program, accepts input from STDIN, output to STDOUT. Output is the gears in order from the end to the start. Usage: Performs a simple Breadth First Search, which solves a 4-gear problem in less than a second. Branching factor isn't actually that large, so it's it should be good for considerably more (not really tested it). Sadly it uses Linq. The `Q` string is a table of all allowed gear connections (i.e an `r=3` and connect to an `r=1` if `dx=4` and `dy=0`) in one quadrant, which is then rotated to find the others. Every set of 3 bytes is the `dx`, `dy`, and radius information for a legal connection. The choice of `(` as an offset was *very* deliberate: it was fun for once to be choosing an ASCII character for nice properties, rather than desperately trying to find nice properties for imposed ASCII characters. I can probably do a better job of reading the input, but I've had no luck yet, not least because the Linq is paid for by the need for a list. I'm also very disappointed by the rotate code, I feel like that could be done in considerably fewer bytes. Formatted and Commented Code with `Q` generator: ``` using System.Linq; // seems to pay today using System; class P { static void GenQ() { int t, k = 0, m = 0; Func<P, P, int> C = (P c, P l) => (t = c.x - l.x) * t + (t = c.y - l.y) * t - (t = c.r + l.r) * t; // ==0 -> touching, <0 -> not touching, >0 -> overlap string str = ""; string T(int i) => "" + (char)('$' + i); // $ is zero, '$' == 36, so we can mod and div by 9, and greater than " so we don't have to escape it foreach (int r in new[] { 1, 2, 3, 5 }) // at 0,0 (current gear) foreach (int s in new[] { 1, 2, 3, 5 }) // gear to place for (int i = 0; i <= r + s; i++) // x for (int j = 1; j <= r + s; j++, m++) // y if (C(new P { r = r }, new P { r = s, x = i, y = j }) == 0) // { str += T(i) + T(j) + T(r + s * 9); k++; } System.Console.WriteLine("K : " + k); System.Console.WriteLine("M : " + m); System.Console.WriteLine(str); System.Console.ReadKey(true); return; } int p=1, // parity x, // x y, // y r; // radias (TODO: store radias^2 ?) P l; // previous in search list static void Main() { //GenQ(); // '$' == 36 (4*9) // 3char blocks: x,y,r+9*s var Q="$&.$'7$(@$*R$'/$(8$)A'(A('A$+S$(0$)9'(9('9$*B$,T$*2$+;$,D$.V*,V,*V"; // quarter table // primative read ints var I=Console.ReadLine().Split(',').Select(int.Parse).ToList(); int i=0, // position in Due t, // check differential cache, position in Q s=7, // check cache, rotation counter (>0) u, // rotation x v, // rotation y w, // rotation x cache p=I[3]*I[2]; // parity (>0 -> same, even ; <0 -> different, odd) // due (not point using a queue, the search space grows exponentially) for(var D=new[]{ new P{r=Math.Abs(I[3]), // start (p==1) l=new P{r=Math.Abs(I[2]),x=I[0],y=I[1],p=3} // terminal (detect with p==3) }}.ToList(); i>=0;) // infinite number of configurations, no bounds, i is escape term { P c=D[i++], // current l=c.l; // check, initially the one before the previous (we know we are touching last already) // 'checks' c against l //Func<int>C=()=>(t=c.x-l.x)*t+(t=c.y-l.y)*t-(t=c.r+l.r)*t; // ==0 -> touching, >0 -> not touching, <0 -> overlap // check we arn't touching any before us (last thing we check is terminal) for(;(l=l?.l)!=null&& // for each before us (skipping the first one) (s=(t=c.x-l.x)*t+(t=c.y-l.y)*t-(t=c.r+l.r)*t)>0;); // check c against l and cache in s, ==0 -> touching, >0 -> not touching, <0 -> overlap if(s==0&& // touching last checked? l.p>2& // stopped on terminal? p*c.p<0) // correct parity? -> win for(i=-1; // escape c.l.p<3;c=c.l) // for each that wasn't the first Console.WriteLine(c.x+","+c.y+","+c.r); // enumerate possible additions, and queue them in due for(t=0; s>0& // not touching or overlapping anything (including terminal) t<66;t++) // 66 = Q.Length for( u=Q[t++]-36, // '$' v=Q[t++]-36, s=1;s++<5& // rotate 4 times Q[t]%9==c.r; // our raidus matches w=u, // chache y value u=v, // rotate v=-w, D.Add(new P // add { l=c, r=Q[t]/9-4, // radius x=c.x+u, y=c.y+v, p=-c.p // flip parity })); } } } ``` ]