text
stringlengths
180
608k
[Question] [ Suppose your alarm wakes you up one morning, but you hit snooze so you can sleep for 8 more minutes. When it rings again you grudgingly get up and take a shower, which you estimate takes 15 to 17 minutes. You then brush your teeth for exactly 2 minutes, and get dressed, which takes about 3 to 5 minutes. Finally, you eat a hurried breakfast in 6 to 8 minutes and run out the door. We can denote this timing sequence as `8 15-17 2 3-5 6-8`. *Given the uncertainty of your morning's routine, what is the probability you were doing each task at some particular number of minutes since you first woke up?* Assuming every task takes a whole number of minutes, we can chart every possible combination of uncertain time spans (e.g. 3, 4, and 5 minutes for brushing teeth). This chart shows all 27 possibilities, with time increasing to the right, and each task of N minutes represented by (N - 1) dashes and one vertical bar, just to mark its ending. The minute boundaries occur *between* characters, so the space between the `8` and `9` column is `8 min 59 sec` turning into `9 min`. ``` 1111111111222222222233333333334 1234567890123456789012345678901234567890 <-- Minute -------|--------------|-|--|-----| -------|--------------|-|--|------| -------|--------------|-|--|-------| -------|--------------|-|---|-----| -------|--------------|-|---|------| -------|--------------|-|---|-------| -------|--------------|-|----|-----| -------|--------------|-|----|------| -------|--------------|-|----|-------| -------|---------------|-|--|-----| -------|---------------|-|--|------| -------|---------------|-|--|-------| -------|---------------|-|---|-----| -------|---------------|-|---|------| -------|---------------|-|---|-------| -------|---------------|-|----|-----| -------|---------------|-|----|------| -------|---------------|-|----|-------| -------|----------------|-|--|-----| -------|----------------|-|--|------| -------|----------------|-|--|-------| -------|----------------|-|---|-----| -------|----------------|-|---|------| -------|----------------|-|---|-------| -------|----------------|-|----|-----| -------|----------------|-|----|------| -------|----------------|-|----|-------| 1234567891111111111222222222233333333334 <-- Minute 0123456789012345678901234567890 ``` It is clear that the routine could have taken 40 minutes at most and 34 minutes at least. The question is, at a particular minute, say minute 29, what is the chance you were doing each of the 5 tasks? Assume each uncertain time frame is uniformly distributed over the exact whole minutes. So a 4-7 task has 25% chance of taking 4, 5, 6, or 7 minutes. From the chart it can be seen that at minute 29 there was a... ``` 0/27 chance you were snoozing (task 1) 0/27 chance you were showering (task 2) 0/27 chance you were brushing (task 3) 24/27 chance you were dressing (task 4) 3/27 chance you were eating (task 5) ``` Similarly at minute 1 there was a `27/27` chance you were snoozing with `0/27` everywhere else. At minute 38 for example, 17 of the potential routines have already ended. So in 10 out of 10 cases you will be eating. This means the probabilities look like ``` 0/10 task 1, 0/10 task 2, 0/10 task 3, 0/10 task 4, 10/10 task 5 ``` # Challenge Write a *function* that takes an integer for the minute value, and a string consisting of a sequence of single integers, or pairs of integers `a-b` with `b` > `a`, all separated by spaces (just like `8 15-17 2 3-5 6-8`). All the integers are positive. The input minute will be less than or equal to the maximum time possible (40 in example). The function should return another string denoting the **unreduced** fractional chance of being in each task at the given minute. # Examples * `myfunc(29, "8 15-17 2 3-5 6-8")` returns the string `0/27 0/27 0/27 24/27 3/27` * `myfunc(1, "8 15-17 2 3-5 6-8")` returns the string `27/27 0/27 0/27 0/27 0/27` * `myfunc(38, "8 15-17 2 3-5 6-8")` returns the string `0/10 0/10 0/10 0/10 10/10` * `myfunc(40, "8 15-17 2 3-5 6-8")` returns the string `0/1 0/1 0/1 0/1 1/1` If your language does not have strings or functions you may use named variables, stdin/stdout, the command line, or whatever seems most appropriate. # Scoring This is code golf. The shortest solution [in bytes](https://mothereff.in/byte-counter) wins. [Answer] ## CJam, ~~124 115 100 92~~ 89 bytes This can be golfed a lot, but I have to sleep, so posting now itself :) ``` l~\:N;S/{'-/2*2<~i),\i>}%_{m*{(\+}%}*{[0\{1$+}*]}%:B;,,{0B{I>2<~N<!\N<*+}/}fI]_:+m*'/f*S* ``` [Try it online here](http://cjam.aditsu.net/) Input is like: ``` 29 "8 15-17 2 3-5 6-8" ``` Where first integer is the input minute and the second string is the time range sequence (as shown in examples in the question, just without the `,`) Output for the above mentioned input: ``` 0/27 0/27 0/27 24/27 3/27 ``` [Answer] ## Mathematica, ~~237~~ 216 bytes I'm sure I can shorten this a bit, but not now. At least I finally got to use the new associations from Mathematica 10! :) ``` f=(j=#;s=StringSplit;r=ToString;t=Lookup[Counts@Flatten[FirstPosition[#,n_/;n>=j]&/@Accumulate/@Tuples@i],#,0]&/@Range@Length[i=ToExpression[#~s~"-"&/@s@#2]/.{a_,b_}:>a~Range~b];Riffle[r@#<>"/"<>r@Tr@t&/@t," "]<>"")& ``` Ungolfed: ``` f = ( j = #; s = StringSplit; r = ToString; t = Lookup[ Counts@Flatten[ FirstPosition[#, n_ /; n >= j] & /@ Accumulate /@ Tuples@i], #, 0] & /@ Range@Length[ i = ToExpression[#~s~"-" & /@ s@#2] /. {a_, b_} :> a~Range~b]; Riffle[r@# <> "/" <> r@Tr@t & /@ t, " "] <> "") & ``` Usage as specified in the challenge: ``` f[29, "8 15-17 2 3-5 6-8"] ``` It returns `0/1` for all elements if the first input is larger than the maximum time span. [Answer] # Haskell, 232 ``` f=(\(a,b)->[a..fst$head$reads(tail$b++" ")++[(a,b)]]).head.reads n%l=(tail>>=zipWith(-))(0:map(\i->drop i&l*e[x|x<-map sum$mapM f$take i$w l,x>=n])[1..e$w l])>>=(++'/':show(id&l)++" ").show (&)i=product.map(e.f).i.w w=words e=length ``` run like this: ``` *Main> putStrLn $ 1 % "8 15-17 2 3-5 6-8" 27/27 0/27 0/27 0/27 0/27 ``` [Answer] ## APL, [162](https://mothereff.in/byte-counter#%7B%7B%E2%8D%B5%2C%27%2F%27%2Cy%7D%C2%A8%E2%8C%8A%7C-2-%2F0%2C%28y%E2%86%90%2B%2F%2C%E2%8D%BA%E2%89%A4%E2%8A%83%E2%8C%BDx%29%C3%971%2C%E2%8D%A8%C2%AF1%E2%86%93%E2%8D%BA%7B%2B%2F%C3%B7%E2%88%98%E2%8D%B4%E2%8D%A8%E2%8D%BA%E2%89%A4%2C%E2%8D%B5%7D%C2%A8x%E2%86%90%E2%88%98.%2B%5C%7B%E2%8A%83%7B%E2%8D%BA%2C%E2%8D%BA%E2%86%93%E2%8D%B3%E2%8D%B5%7D%2F%E2%8D%8E%28%27-%27%E2%8E%95R%27%20%27%29%E2%8D%B5%7D%C2%A8%28%27%5CS%2B%27%E2%8E%95S%27%5C0%27%29%E2%8D%B5%7D) ``` {{⍵,'/',y}¨⌊|-2-/0,(y←+/,⍺≤⊃⌽x)×1,⍨¯1↓⍺{+/÷∘⍴⍨⍺≤,⍵}¨x←∘.+\{⊃{⍺,⍺↓⍳⍵}/⍎('-'⎕R' ')⍵}¨('\S+'⎕S'\0')⍵} ``` **Example runs** ``` f←{{⍵,'/',y}¨⌊|-2-/0,(y←+/,⍺≤⊃⌽x)×1,⍨¯1↓⍺{+/÷∘⍴⍨⍺≤,⍵}¨x←∘.+\{⊃{⍺,⍺↓⍳⍵}/⍎('-'⎕R' ')⍵}¨('\S+'⎕S'\0')⍵} 29 f '8 15-17 2 3-5 6-8' 0 / 27 0 / 27 0 / 27 24 / 27 3 / 27 1 f '8 15-17 2 3-5 6-8' 27 / 27 0 / 27 0 / 27 0 / 27 0 / 27 38 f '8 15-17 2 3-5 6-8' 0 / 10 0 / 10 0 / 10 0 / 10 10 / 10 40 f '8 15-17 2 3-5 6-8' 0 / 1 0 / 1 0 / 1 0 / 1 1 / 1 ``` I hope you don't mind the weird spacing ]
[Question] [ This question is slightly harder than the ASCII art version. There is no art, and now you get to do some floating point arithmetic! # The Challenge The U.S.S. StackExchange was traveling through the gravity field of planet cg-00DLEF when an astronomical explosion occurred on board. As the head programming officer of the ship, it is your job to simulate the trajectory of your ship in order to predict whether you will be forced to crash land in cg-00DELF's solar system. During the explosion, your ship was heavily damaged. Due to the limited free DEEEPRAROM\* of the spaceship, you must write your program in as few characters as possible. \*Dynamically Executable Electronically Erasable Programmable Random Access Read Only Memory # The Simulation Somewhat like the ASCII art version, there will be the idea of time-steps. In the other version, a time-step was a relatively large amount of time: the ship could travel way beyond the gravity of a planet in a single time-step. Here, the time-step is a much smaller unit of time due to the larger distances involved. One major difference, however, is the non-existence of cells. The spaceship's current location and velocity will be floating point numbers, along with the gravitational forces involved. Another change is the fact that planets now have a much larger size. There will be up to three planets in the simulation. All three will have a specific location, radius, and gravity. The gravity for each planet is a vector that exerts a force directly towards the center of the planet. The formula to find the strength of this vector is `(Gravity)/(Distance**2)`, where the distance is the exact distance from the ship to the center of the planet. This means that there is no limit to where gravity can reach. At any specific time, the spaceship has a velocity, which is the distance and angle that it traveled from last time-step to now. The ship also has momentum. The distance that it will travel between the current time-step and the next is the sum of its current velocity added to all of the gravity vectors at its location. This becomes the spaceship's new velocity. Each simulation has a time limit of 10000 time steps. If the spaceship travels inside of a planet (it is closer to the center of the planet than the planet's radius), then it crashes into that planet. If the spaceship does not crash into any planet by the end of the simulation, then it is presumed to have escaped from gravity. It is unlikely that the ship could be aligned so perfectly that it manages to stay in orbit for 10000 time-steps while crashing on the 10001st time-step. # Input Input will be four lines to STDIN. Each line consists of four comma-delimited numbers. Here is the format of the numbers: ``` ShipLocX,ShipLocY,ShipVelX,ShipVelY Planet1LocX,Planet1LocY,Planet1Gravity,Planet1Radius Planet2LocX,Planet2LocY,Planet2Gravity,Planet2Radius Planet3LocX,Planet3LocY,Planet3Gravity,Planet3Radius ``` If there are fewer than three planets, then the leftover lines will be filled with zeros for all values. Here is an example input: ``` 60,0,0,10 0,0,4000,50 100,100,4000,50 0,0,0,0 ``` This means that the spaceship is located at (60,0) and is traveling straight "up/north" at a rate of 10 units/time-step. There are two planets, one located at (0,0) and one at (100,100). Both have a gravity of 4000 and a radius of 50. Even though all of these are integers, they will not always be integers. # Output Output will be a single word to STDOUT to tell whether the spaceship has crash landed or not. If the ship crash lands, print `crash`. Otherwise, print `escape`. Here is the expected output for the above input: ``` crash ``` You may be wondering what happened. [Here](http://pastebin.com/LgLTabpj) is a Pastebin post that has a detailed flight log for the spaceship. Numbers aren't very good at helping people visualize the event so here is what happened: The spaceship manages to escape the gravity of the first planet (to its west) with the help of the gravity of the second planet (to its northeast). It moves north and then passes slightly to the west of the second planet, barely missing it. It then curves around the northern side of the planet and crashes into the eastern side of the second planet. # Some more cases for examination ``` 60,0,10,-10 0,0,2000,50 100,100,1357.9,47.5 0,0,0,0 ``` escape (due to the inverse square law, 2000 isn't much gravity if you are 60 units away) ``` 0,0,0,0 100,100,20000,140 -50,-50,50,50 -100,-100,50,50 ``` crash (the first planet is extremely massive and extremely close) ``` 0,0,0,0 0,0,0,0 0,0,0,0 0,0,0,0 ``` escape (this is an edge case: there are no planets and a straightforward interpretation would suggest that the spaceship is directly on top of the planets) # Rules, Restrictions, and Notes This is code golf. Standard code golf rules apply. Your program should be written in printable ASCII characters only. You cannot access any sort of external database. You may write entries in any language (other than one that is specialized towards solving this challenge). End Transmission [Answer] ## Python, 178 170 chars ``` p=input a,b,c,d=p() x=a+b*1j v=c+d*1j P=(p(),p(),p()) R='escape' for i in' '*10000: for a,b,g,r in P: d=a+b*1j-x;v+=g*d/abs(d)**3 if abs(d)<r:R='crash' x+=v print R ``` [Answer] ## Golfrun/GolfScript?, ~~243~~ 232 chars ``` 10000:M;n%(','%2/{{~}%}/{{M*}%}:_~:v;_:x;'escape':R;{[','%2/{{~M*}%}/]}%:P; M,{;P{~\x{0\-}%{+~@+@@+[\]}:|~:d.[~0\-]{[+.2%~*\.-2%~*@\-\.3%~*\(;);~*+]}:&~);~sqrt:z ..**\~d@[`~0]\&@M.*/\{1$/}%v|:v;;z\<{'crash':R;}{}if}/x v|:x;}/R puts ``` Golfrun is a language I'm working on, born as GolfScript C interpreter, but soon drifted away someway; though I've written this code without using knowingly specific Golfrun features (except for `sqrt`), the test with the original GolfScript failed (I had to add the sqrt feature to the original code, I am not a Ruby guru but I believe the problem is not my tweaking). The first problem with this solution is that Golfrun, as GolfScript, has no floating point math. It is "simulated" magnifying the numbers, hopefully in the correct way (but I am not 100% confident I've done it coherently). Even so, the solution does not handle floating point numbers as input, so I had to magnify them by hand to have only integer numbers. Trying to implement the algorithm in the Python code, I have also implemented bits of complex math in a rather "general" way. Manipulating the algorithm in order to avoid this, and/or inlining whenever possible, delaying the definitions, could save other chars... How do I know this code works? Indeed, I am not sure it does! But giving the examples as input (after "removing" points where they appear), it wrote the expected results, except for the "corner case" (which raises an exception in Python too)... ]
[Question] [ This question is an extension of [Who's that Polygon?](https://codegolf.stackexchange.com/q/121815/110698) to arbitrary numbers of sides. A [fundamental polygon](https://en.wikipedia.org/wiki/Fundamental_polygon) for a surface is an polygon with a prescribed pairing for all its \$2n\$ sides, each marked with an arrow, such that identifying the sides according to this pairing and the arrow directions produces the surface (up to homeomorphism). This pairing can be described as a cyclic *fundamental word* with two each of \$n\$ distinct symbols, where any symbol may be inverted to represent an arrow pointing opposite to the direction of travel around the polygon. For example, the word \$abab^{-1}\$ describes the Klein bottle: [![](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/KleinBottleAsSquare.svg/240px-KleinBottleAsSquare.svg.png)](https://en.wikipedia.org/wiki/File:KleinBottleAsSquare.svg) In light of the [classification theorem](https://en.wikipedia.org/wiki/Surface_(topology)#Classification_of_closed_surfaces) for surfaces, which states that every closed 3D surface is homeomorphic to *either* the connect-sum of \$g\ge0\$ tori (including the sphere at \$g=0\$) *or* the connect-sum of \$k>0\$ cross-caps, it may not be immediately obvious what surface a fundamental polygon represents. Fortunately canonical forms and a canonicalisation process exist – the material below comes from Gerhard Ringel's *Map Color Theorem*. ## Canonical words for surfaces The canonical fundamental word for the connect-sum of \$g\ge0\$ tori, with genus \$g\$, is $$a\_1b\_1a\_1^{-1}b\_1^{-1}a\_2b\_2a\_2^{-1}b\_2^{-1}\dots a\_gb\_ga\_g^{-1}b\_g^{-1}$$ So the sphere's canonical word is the empty string, the normal torus's is \$aba^{-1}b^{-1}\$ and so on. The canonical fundamental word for the connect-sum of \$k>0\$ cross-caps, with genus \$-k\$ (although this is incorrect, this definition is used here because then the integers bijectively correspond to surface types) is $$a\_1a\_1a\_2a\_2\dots a\_ka\_k$$ The real projective plane and Klein bottle are the \$k=1\$ and \$k=2\$ cases of this sequence, so their canonical words are \$aa\$ and \$aabb\$ respectively. ## Canonicalisation The surface represented by a fundamental word is unchanged if * the word is cyclically rotated: \$aabb\to abba\$ * a symbol is inverted: \$aabb\to aab^{-1}b^{-1}\$ * a symbol and its **adjacent** inverse are cancelled: \$caba^{-1}b^{-1}c^{-1}\to aba^{-1}b^{-1}\$ The surface is orientable iff each symbol appears once inverted and once uninverted in the word. In that case a "handle" can be extracted by the following word transformation, where \$Q,R,S\$ are not all empty: $$PaQbRa^{-1}Sb^{-1}T\to PSRQTaba^{-1}b^{-1}$$ Repeating this process with intermediate cancellation leads to the canonical form for orientable surfaces described above. If the two occurrences of a symbol are both inverted or both uninverted, the surface is non-orientable. In this case a cross-cap may be extracted by the following word transformation, where \$Q^{-1}\$ is the group-theoretic inverse (so e.g. \$(abc)^{-1}=c^{-1}b^{-1}a^{-1}\$): $$PaQaR\to aaPQ^{-1}R$$ Do this as many times as possible to get a word of the form \$a\_1a\_1\dots a\_ia\_iO\$, where \$O\$ is the fundamental word of an *orientable* surface. Canonicalise \$O\$ as above and determine its genus \$g\$; the canonical form of the full non-invertible surface is then \$a\_1a\_1\dots a\_{i+2g}a\_{i+2g}\$, because a handle turns into two cross-caps in the presence of another cross-cap. ## Example This picture from one of my [MathsSE answers](https://math.stackexchange.com/a/4651117/357390) is an embedding of the [Johnson graph](https://en.wikipedia.org/wiki/Johnson_graph) \$J(5,2)\$: ![](https://i.stack.imgur.com/zDO90.png) The star-shaped border represents a fundamental polygon where * each black (dark blue) arc matches the grey (light blue) arc 5 steps away going counterclockwise * each golden yellow arc matches the light yellow arc 7 steps away going clockwise * in all cases the matching is parallel (as hinted by the faded exterior), so the surface is orientable Thus the corresponding fundamental word is $$ah^{-1}bf^{-1}ca^{-1}db^{-1}ei^{-1}fd^{-1}ge^{-1}hc^{-1}ig^{-1}$$ which reduces as follows: $$(a)h^{-1}(b)f^{-1}c(a^{-1})d(b^{-1})ei^{-1}fd^{-1}ge^{-1}hc^{-1}ig^{-1}$$ $$\to (d)f^{-1}(c)h^{-1}ei^{-1}f(d^{-1})ge^{-1}h(c^{-1})ig^{-1}aba^{-1}b^{-1}$$ $$\to ge^{-1}[hh^{-1}]ei^{-1}[ff^{-1}]ig^{-1}aba^{-1}b^{-1}dcd^{-1}c^{-1}$$ $$\to g[e^{-1}e][i^{-1}i]g^{-1}aba^{-1}b^{-1}dcd^{-1}c^{-1}$$ $$\to[gg^{-1}]aba^{-1}b^{-1}dcd^{-1}c^{-1}$$ $$\to aba^{-1}b^{-1}dcd^{-1}c^{-1}$$ Thus the surface has genus 2, which matched my expectation when I constructed the embedding based on a triangulation with 10 vertices and 36 edges – by Euler's formula such a triangular embedding, if orientable, must live on the genus-2 surface. Indeed (glue the three ends of the open surface below in a Y-shape so that the colours match): ![](https://i.stack.imgur.com/elLUj.png) ## Task Given a list of *nonzero integers* where the magnitudes from 1 to \$n\$ appear exactly twice each, representing a fundamental word with a negative number marking an inverted symbol, output the genus of the surface corresponding to that fundamental word, using the definition above where a negative genus \$-k\$ means "connect-sum of \$k\$ cross-caps". This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins. ## Test cases ``` [] -> 0 [1, -1] -> 0 [1, 1] -> -1 [1, 2, -2, -1] -> 0 [1, 2, -1, -2] -> 1 [1, 2, 1, -2] -> -2 [1, 2, 1, 2] -> -1 [-2, -2, -1, 1] -> -1 [1, 2, 3, -1, -2, -3] -> 1 [-3, 1, 3, -2, 1, 2] -> -2 [1, 2, 3, 4, -1, -2, -3, -4] -> 2 [1, 2, 4, 4, -2, -3, 1, -3] -> -2 [1, -8, 2, -6, 3, -1, 4, -2, 5, -9, 6, -4, 7, -5, 8, -3, 9, -7] -> 2 [1, -8, 2, -9, 3, -1, 4, -2, 5, -3, 6, -4, 7, -5, 8, -6, 9, -7] -> 3 [4, 3, 2, 1, 1, 2, 3, 4] -> -4 [3, 4, 1, 2, 6, 7, -4, 5, -2, -3, -7, -1, -5, -6] -> 3 [1, 2, 3, 3, -1, -2] -> -3 ``` [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/index.html), 159 bytes ``` f[]=0 f(p++a:b:q)|a+b==0=f$p++q f(p++a:q++a:r)=g$f$p++reverse[-x|x<-q]++r f(p++a:q++b:r++c:s++d:t)=(a+c)!(b+d)$f$p++s++r++q++t g x=min(-2*x)x-1 (0!0)x|x>=0=x+1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY9NCoMwEIX3niKCi6RjINpNCU0vIlLiT0SKYqKWFLxJF3XTVc_Qg_Q2TRWhMAzMe98Mb-6vfDTmdu7kJe_n-TkOih4-D5WkgnkKdwCSZ1yTSUImBBMqcJLeHP1rhogqWHRTXkvTlwm1kz1SnTrlj8y4Ach5D1DwgQgsISc-zqAg67YzHODAwauQFU3dYhrvLLE08jDzGXFXTy6ChWiN-W5k3SKBFEqiEMUh2i9F3UDjdGW2l74) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~56~~ ~~49~~ 46 bytes ``` (ṫ~c[€ɖ‡ṘNf&›|p;ȧ:(ṫ€:ḣt↔h:ḃ∇v€ÞfḣṘJf)W∑¥[d¥+N ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwi4pah4bmrYCAtPiBg4oKsaErijIp3wqhTIiwiKOG5q35jW+KCrMmW4oCh4bmYTmYm4oC6fHA7yKc6KOG5q+KCrDrhuKN04oaUaDrhuIPiiId24oKsw55m4bij4bmYSmYpV+KIkcKlW2TCpStOIiwiIiwiW10gLT4gMFxuWzEsIC0xXSAtPiAwXG5bMSwgMV0gLT4gLTFcblsxLCAyLCAtMiwgLTFdIC0+IDBcblsxLCAyLCAtMSwgLTJdIC0+IDFcblsxLCAyLCAxLCAtMl0gLT4gLTJcblsxLCAyLCAxLCAyXSAtPiAtMVxuWy0yLCAtMiwgLTEsIDFdIC0+IC0xXG5bMSwgMiwgMywgLTEsIC0yLCAtM10gLT4gMVxuWy0zLCAxLCAzLCAtMiwgMSwgMl0gLT4gLTJcblsxLCAyLCAzLCA0LCAtMSwgLTIsIC0zLCAtNF0gLT4gMlxuWzEsIDIsIDQsIDQsIC0yLCAtMywgMSwgLTNdIC0+IC0yXG5bMSwgLTgsIDIsIC02LCAzLCAtMSwgNCwgLTIsIDUsIC05LCA2LCAtNCwgNywgLTUsIDgsIC0zLCA5LCAtN10gLT4gMlxuWzEsIC04LCAyLCAtOSwgMywgLTEsIDQsIC0yLCA1LCAtMywgNiwgLTQsIDcsIC01LCA4LCAtNiwgOSwgLTddIC0+IDNcbls0LCAzLCAyLCAxLCAxLCAyLCAzLCA0XSAtPiAtNFxuWzMsIDQsIDEsIDIsIDYsIDcsIC00LCA1LCAtMiwgLTMsIC03LCAtMSwgLTUsIC02XSAtPiAzXG5bMSwgMiwgMywgMywgLTEsIC0yXSAtPiAtMyJd) First we extract all cross-caps. This is done by looking at the last symbol. If it occurs in the same orientation twice, the cross-cap is extracted by taking a word \$PaQa\$ and transforming it into \$PQ^{-1}\$, incrementing the register each time it happens. Otherwise the word is rotated to the left. This is repeated as many times as the number of symbols in the input. ``` (ṫ~c[€ɖ‡ṘNf&›|p; ( ; # run the following once for each symbol in the input: [1, 2, 3, 1, -2, 3] ṫ # tail extract [1, 2, 3, 1, -2], 3 ~c # contains? without popping [1, 2, 3, 1, -2], 3, 1 [ # if: € # split on [[1, 2], [1, -2]] ɖ‡-- # apply the following to the second item: ṘN # reverse and negate [[1, 2], [2, -1]] f # flatten [1, 2, 2, -1] &› # increment register | # else: p # prepend ``` Now we are left with a word of an orientable surface so we can forget which symbols are inverted. Now we extract handles and remove adjacent inverses. This is done by looking at the last symbol. We write the word as \$PaQa\$. If there is a common symbol in \$P\$ and \$Q\$ there exists a handle \$RbSaTbUa\$ so we transform the word into \$RUTS\$, leaving a 1 on the stack each time it happens. If there are no common symbols in \$P\$ and \$Q\$ then \$a\$ will eventually become adjacent with itself so we can delete it, leaving a 0 on the stack each time it happens. This is repeated as many times as the number symbols left in the word after extracting cross-caps. ``` ȧ:(ṫ€:ḣt↔h:ḃ∇v€ÞfḣṘJf) ȧ # absolute value :( ) # run the following once for each symbol in the word: ṫ # tail extract € # split on : # duplicate ḣ # head extract t # tail ↔ # intersection h # head : # duplicate ḃ # boolify ∇ # shift (leave it on the stack for later) v€ # vectorise split on Þf # flatten by one level ḣ # head extract Ṙ # reverse Jf # join and flatten ``` All that's left is to combine the number of cross-caps extracted and number of handles extracted. ``` W∑¥[d¥+N W # wrap stack in a list ∑ # sum ¥[ # if register is non-zero d # double ¥+ # add register N # negate ``` ]
[Question] [ ### Background Math SE's HNQ [How to straighten a parabola?](https://math.stackexchange.com/q/4209381/284619) has 4,000+ views, ~60 up votes, 16 bookmarks and six answers so far and has a related companion HNQ in Mathematica SE [How to straighten a curve?](https://mathematica.stackexchange.com/q/251570/47301) which includes a second part asking to move a point cloud along with the curve that we can ignore here. From the Math SE question: > > Consider the function \$f(x)=a\_0x^2\$ for some \$a\_0\in \mathbb{R}^+\$. Take \$x\_0\in\mathbb{R}^+\$ so that the arc length \$L\$ between \$(0,0)\$ and \$(x\_0,f(x\_0))\$ is fixed. Given a different arbitrary \$a\_1\$, how does one find the point \$(x\_1,y\_1)\$ so that the arc length is the same? > > > Schematically, > > > [![flattening a parabola](https://i.stack.imgur.com/djrlsm.png)](https://i.stack.imgur.com/djrlsm.png) > > > In other words, I'm looking for a function \$g:\mathbb{R}^3\to\mathbb{R}\$, \$g(a\_0,a\_1,x\_0)\$, that takes an initial fixed quadratic coefficient \$a\_0\$ and point and returns the corresponding point after "straightening" via the new coefficient \$a\_1\$, keeping the arc length with respect to \$(0,0)\$. Note that the \$y\$ coordinates are simply given by \$y\_0=f(x\_0)\$ and \$y\_1=a\_1x\_1^2\$. > > > [![flattening a parabola](https://i.stack.imgur.com/x7o8V.gif)](https://i.stack.imgur.com/x7o8V.gif) > > > ### Problem Given a positive integer n and values a0 and a1 defining the original and new parabolas: 1. Generate \$n\$ equally spaced values for \$x\_0\$ from 0 to 1 and corresponding \$y\_0\$ values. 2. Calculate the new \$x\_1\$ and \$y\_1\$ such that their path distances along the new parabola are equal to their old distances. 3. Output the \$x\_0\$, \$x\_1\$ and \$y\_1\$ lists so that a user could plot the two parabolas. **note:** The basis of the calculation can come from any of the answers to either linked question or something totally different. If you choose to use a numerical rather than analytical solution an error of \$1 \times 10^{-3}\$ would be sufficient for the user to make their plot. Regular Code Golf; goal is shortest answer. ### Example This is quite a bit late but here is an example calculation and results. I chose the same numbers as in Eta's [answer](https://codegolf.stackexchange.com/a/233178/85527) in order to check my math. [![flattening the parabola code golf](https://i.stack.imgur.com/IVGDF.png)](https://i.stack.imgur.com/IVGDF.png) ``` s0: [0.00000, 0.13589, 0.32491, 0.59085, 0.94211, 1.38218, 1.91278, 2.53486, 3.24903] x0: [0.00000, 0.12500, 0.25000, 0.37500, 0.50000, 0.62500, 0.75000, 0.87500, 1.00000] x1: [0.00000, 0.13248, 0.29124, 0.46652, 0.64682, 0.82802, 1.00900, 1.18950, 1.36954] ``` script: ``` import numpy as np import matplotlib.pyplot as plt from scipy.optimize import root def get_lengths(x, a): # https://www.wolframalpha.com/input?i=integrate+sqrt%281%2B4+a%5E2x%5E2%29+x%3D0+to+1 return 0.5 * x * np.sqrt(4 * a**2 * x**2 + 1) + (np.arcsinh(2 * a * x)) / (4 * a) def mini_me(x, a, targets): return get_lengths(x, a) - targets a0, a1 = 3, 1.5 x0 = np.arange(9)/8 lengths_0 = get_lengths(x0, a0) wow = root(mini_me, x0.copy(), args=(a1, lengths_0)) x1 = wow.x fig, ax = plt.subplots(1, 1) y0, y1 = a0 * x0**2, a1 * x1**2 ax.plot(x0, y0, '-') ax.plot(x0, y0, 'ok') ax.plot(x1, y1, '-') ax.plot(x1, y1, 'ok') np.set_printoptions(precision=5, floatmode='fixed') things = [str(q).replace(' ', ', ') for q in (lengths_0, x0, x1)] names = [q + ': ' for q in ('s0', 'x0', 'x1')] for name, thing in zip(names, things): print(' ' + name + thing) _, ymax = ax.get_ylim() xmin, _ = ax.get_xlim() ax.text(x0[-1:]+0.03, y0[-1:]-0.1, str(a0) + 'x²') ax.text(x1[-1:]-0.04, y1[-1:]-0.1, str(a1) + 'x²', horizontalalignment='right') title = '\n'.join([name + thing for (name, thing) in zip(names, things)]) ax.set_title(title, fontsize=9) plt.show() ``` [Answer] # Mathematica, ~~108~~ 107 bytes ``` {n,a,b}=Input[];L=ArcLength;Subdivide@--n x/.FindRoot[{t,t^2a}~L~{t,0,#}-{t,t^2b}~L~{t,0,x},{x,0}]&/@% %^2b ``` (Assuming an interactive environment). Input is entered in the form `{n, a0, a1}`. Below is the output of a sample run with input `{9, 3, 1.5}`: ``` {0, 1/8, 1/4, 3/8, 1/2, 5/8, 3/4, 7/8, 1} {0., 0.13247799662957596, 0.2912428843578418, 0.4665152489073556, 0.6468180849532895, 0.8280191118364263, 1.0089961907516996, 1.189503180997409, 1.369535545562379} {0., 0.026325629386478908, 0.1272336265336128, 0.3264547161946379, 0.6275604525339613, 1.0284234743495764, 1.5271099694271602, 2.122376726404432, 2.8134414158382643} ``` ## Explanation This uses `FindRoot` to find `x`s where the `ArcLength` of the original equation to each point in x0 matches the `ArcLength` of the flattened equation up to each `x`. Here is a visualization of the points in the example: [![enter image description here](https://i.stack.imgur.com/mioc0.png)](https://i.stack.imgur.com/mioc0.png) With the (identical) corresponding arc lengths at each point: ``` {0., 0.1358872650466621, 0.32491055615709175, 0.5908450391982809, 0.9421066199781004, 1.3821781999397988, 1.9127768947936938, 2.534864156640448, 3.249029586202852} ``` ]
[Question] [ [Sandbox](https://codegolf.meta.stackexchange.com/a/22322/80214) Inspired by a [Codingame](https://codingame.com/) challenge I tried (and failed at) about a month ago. Given a binary tree of words, say: ``` HELLO / \ WORLD EATING / / \ ARCH IDAHO GUARD / DOOZY / ZEPPELIN / \ POWER LIGHT ``` 1. Take the root of the tree. 2. Print it in the South direction. ``` H E L L O ``` 3. For each of the tree's children, given iteration index i: 1. Find the first character in the child that it has in common with the root. If there are multiple occurrences of that character in the root, choose the first occurrence as the join point. 2. The drawn root word will have to intersect the child at this point. 3. Draw the left node down to the left, and the right node down to the right. ``` H E LA LWT O I R N L G D ``` 4. Now, for each of the diagonal words' children, do the same, except always print downward. ``` H E LA LWT AO I R DN LC A G D H H U O A R D ``` 5. Go back to step3 and perform the steps again until the tree is complete. ``` H E LA LWT AO I R DN LC A G D H H U O A R D O O Z YE P OP W E E L R II N G H T ``` ## Clarifications * No two child words will have the same first common letter. * Words from different subtrees will never intersect. * Input will always be a valid binary tree. * Each parent will always have a common character with both of its children. * Trees can be taken in any suitable and reasonable format for your language. * Leading and trailing whitespace is allowed, so long as the structure of the lightning is as shown. * All words will be given in the same case. # Testcases ``` PROGRAMMING | CHALLENGES | \ PUZZLES CODING ``` ``` P R PO UG C ZRHO ZA D LM I LEM N E SI G N N G G E S ``` --- ``` DIGERIDOO | \ GIRDLE ORNATE | | \ EXQUISITE ROLL TALONS | \ QUEEN TAPESTRY | \ PASTE YELLOW | ERROR ``` ``` D I G IE R R D I L D E O X OR Q ON UU L A E I L T E S AE N I L T O EA N P P S EA S TT E R R Y R E O L R L O W ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 88 bytes ``` ↓§θ⁰⊞υ⁺E³¦⁰θFυ«≔¬§ι⁰ηFΦι›λ³«≔§κ⁰ζ≔§Φζ№§ι³λ⁰εJ§ι¹§ι²M⌕§ι³ε✳⁻⁶§ι⁰M⌕ζε✳⁻²η⊞υ⁺⟦ηⅈⅉ⟧κ✳⁻⁶ηζ≦±η ``` [Try it online!](https://tio.run/##bZFfa8IwFMWf56cIfUogg01hD9tTWTPpqE1NK1OKD0UzW@wS7R83HH72LknbbYoPgXtzz/ldcrJKk2Ilk7xpgiITFXx05KfAwK5cseZfcI/BHUJPg6AuU1hjEOR1CSfJDo70AIO9Hr7LAsAage/BjV2W2UZAX1awR2QGgUGqlDdG@pLlFS/0YFzwRJc5BiOEDKFH9PZtu@io3ZezDnTE4FnW4mzlSHlyvVabuTG/1h@7SP4X3aO/l6p2iIxuIg9cocX6ksfVcbKCr6pMCjjJhMri4YygHnrJOF73DXUgrfYs2zjFYA6VYQHREoNtJzF/c2V3in6zUb/Sp883KtUu8dPg1DRxbDnumDDXodTCILbGLnM8Ykoyn87c0I3abjojxLeWuozsgIQRW5j7wA47BWGMMmtpJAviefRNNW1LmW93KkY9r8d41A@Nprk95D8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ↓§θ⁰ ``` Print the first word vertically. ``` ⊞υ⁺E³¦⁰θFυ« ``` Start a breadth-first traversal of the tree, but prefixing three status variables to each entry for the coordinates and the direction. ``` ≔¬§ι⁰η ``` Get the direction of the previously printed word and flip it to 0 (which will become downwards) if it was non-zero or 1 (which will become down left) if it was zero. ``` FΦι›λ³« ``` Loop over any child nodes. ``` ≔§κ⁰ζ ``` Get the current node's word. ``` ≔§Φζ№§ι³λ⁰ε ``` Find the first letter in its word that's shared with its parent's word. ``` J§ι¹§ι²M⌕§ι³ε✳⁻⁶§ι⁰M⌕ζε✳⁻²η ``` Jump to the parent's start, then move to the parent's shared letter, then work back to where this branch's word needs to start. ``` ⊞υ⁺⟦ηⅈⅉ⟧κ ``` Concatenate this word's position and direction with the node and push that to the list of nodes to traverse. ``` ✳⁻⁶ηζ ``` Print the node's word in the appropriate direction. ``` ≦±η ``` Flip the direction in case this word was printed down left and there's a sibling node still to print. ]
[Question] [ In this challenge, your task is to detect (vertical) *Skewer Symmetry*. This means that one half of the pattern can be produced by mirroring the other half along a vertical axis, and then moving it vertically. For example, the following pattern has skewer symmetry: ``` asdf jkl;fdsa ;lkj ``` Because if you start from the left half... ``` asdf jkl; ``` ...then mirror it along a vertical axis... ``` fdsa ;lkj ``` ...then move it down by a character (filling the empty rows with spaces)... ``` fdsa ;lkj ``` ...you get the second half. ## Rules: * You may assume the input is rectangle and has an even number of columns. * If the pattern itself exhibits reflection symmetry, it is considered skewer symmetry. * This is strict character by character symmetry, so `[[` is considered symmetrical, but not `[]`. * You should output truthy if the input has skewer symmetry, falsy otherwise. * Default I/O rules apply, standard loopholes are banned. ## Test Cases Truthy cases: ``` asdf jkl;fdsa ;lkj ``` ``` asdffdsa ``` ``` [ [ ``` ``` ba abdc cd ``` Falsy cases: ``` [ ] ``` ``` ab ba ``` ``` aa a a ``` ``` a a b b ``` ``` ab b a ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~44~~ 34 bytes[SBCS](https://en.wikipedia.org/wiki/SBCS) [crossed out ~~44~~ is still regular 44 ;(](https://codegolf.stackexchange.com/q/170188/75323) Hats off to @Bubbler, @ngn and @TesselatingHeckler as they managed to shave some bytes off of my solution, more or less independently but coming up with the same simplifications. ``` {1∊(l↓⍵)⍷⍨a/⍨∨⌿' '≠a←⊖⍵↑⍨l←2÷⍨≢⍵}⍉ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rwUUeXRs6jtsmPerdqPurd/qh3RTWQqQ@kH3WseNSzX11B/VHnAqBQ7aOuaUDqUdtEoBxQxwSjwyDVjzoXgSV7O/@nKQBFFaqB@vR1qGQmF9ejvqlAcaDRYFrBWMHiUe8W9cTilDQFIMjKzrFOSylOBLGtc7Kz1NHVGyLUg9SpY5pnApJXUEhMSkpMSU5OUVCAqVFQx1BtpGAENg2oFpdJiUkgt4CJRPX/AA "APL (Dyalog Unicode) – Try It Online") Now I'll explain **how it works**: ``` { }⍉ ⍝ We define a monadic function that we apply right after transposing (⍉) the input [this means we will be operating on columns instead of rows] 2÷⍨≢⍵ ⍝ Start by finding how many columns the input has (≢),split that in half (2÷⍨) l← ⍝ and assign that to l (l←) ... ⍵↑⍨ ⍝ Using it right away to take (↑⍨) l columns from the original input ⍵ ⊖ ⍝ which we then reverse (⊖) [effectively flipping the columns upside down] a← ⍝ and assign to a (a←) ' '≠ ⍝ We then compare each character in a to ' ' ∨⌿ ⍝ and we "interleave" the logical OR (∨) over the columns (⌿) [to find columns where at least one character is different from ' '] a/⍨ ⍝ finally selecting those columns from a (a/⍨) ⍷⍨ ⍝ Now we superimpose that piece of the original character matrix over all possible locations (l↓⍵) ⍝ of the columns of ⍵ that remain after we drop (↓) the first l columns [i.e. we take the second half of the columns] 1∊ ⍝ and we look for matches by checking if there is a 1 (Truthy) in any position (∊) ``` [Answer] # [J](http://jsoftware.com/), ~~34~~ ~~23~~ 38 bytes ``` 1 e.[:(e.&:((-:@#{.])"1)|."1\.)"2],:|. ``` [Try it online!](https://tio.run/##bZBRa4MwFIXf/RUHO3oVNKu2DyPB0TE2GOxprzaMxESKla2ghcH6311ifZilF0LCyXfuudxmCBnVKDgICVbg7qQMzx/vr0MGy0oeWbbkUZTy7eKXyTjM4jMLsx2Lw1wm/MyGOLDV/hs11tjgzvWBVkqbqjIABUFvu75gkKIU9VYGgSkY0XgZl5hBON@D96nO1HDVHFpRm075t2gPDf1nE34BPTD72CD3TUqMVdI84NZgE7ByQD6Z01TSDV1prWb6etKVG1JdOcYor2toH3PZTkRvX8dTT4Jefo626q0hAXqq@pNqKXbmzxx@U8vH@x3M8Ac "J – Try It Online") *thanks to nimi for catching a bug* Will attempt to regolf the fixed version later. [Answer] ## Haskell, ~~137~~ ~~135~~ 133 bytes ``` f s=uncurry(#)$unzip$splitAt(div(length$s!!0)2)<$>s a#b@(x:y)|e$last a++x=init a#y|e$last b++a!!0=b#a|r<-reverse<$>b=a==r e=all(<'!') ``` [Try it online!](https://tio.run/##TYxLTsMwEIb3OcXkIdVWCkIsaYzgAJwgitBM7FA3rhXZTtWg3j04EQ14MZ75/scRfa@MmecOvBhtOzo3sZwXo/3WQ@EHo8N7YFJfmFH2KxwLn6ZP/JlXxatPMKc3dn2Z@E0VBn0ALMur0FbHLZ/ukMoSY0hQjjdXPTh1Uc6rWEAChXCJEmgMq3bpjs9n1BYEnHH4@AQ2OG0DPHYc6gSgztDLDuLL9tmpN4dOeozrQg6mP2XNfnOt0u9dw2paRn1nALREkWQbv1ZGOSr/7M3WRvGkrQzX2Gr5YwALJaDY0iTzDw "Haskell – Try It Online") ]
[Question] [ ## Background **[Tatamibari](https://en.wikipedia.org/wiki/Tatamibari)** is a logic puzzle designed by Nikoli. A Tatamibari puzzle is played on a rectangular grid with three different kinds of symbols in it: `+`, `-`. and `|`. The solver must partition the grid into rectangular or square regions according to the following rules: * Every partition must contain exactly one symbol in it. * A `+` symbol must be contained in a square. * A `|` symbol must be contained in a rectangle with a greater height than width. * A `-` symbol must be contained in a rectangle with a greater width than height. * Four pieces may never share the same corner. (This is how Japanese tatami tiles are usually placed.) The following is an example puzzle, with a solution: [![Example Tatamibari puzzle](https://i.stack.imgur.com/UGBks.png)](https://i.stack.imgur.com/UGBks.png) [![Example Tatamibari puzzle solution](https://i.stack.imgur.com/STEe0.png)](https://i.stack.imgur.com/STEe0.png) ## Task Solve the given Tatamibari puzzle. ## Input & output The input is a 2D grid that represents the given Tatamibari puzzle. Each cell contains one of the four characters: `+`, `-`, `|`, and a character of your choice to represent a non-clue cell. In the test cases, an asterisk `*` is used. You can choose any suitable output format which can unambiguously represent any valid solution to a Tatamibari puzzle. This includes, but is not limited to: (if in doubt, ask in comments.) * A list of 4-tuples, where each tuple includes the top index, left index, width and height of a rectangle (or any equivalent representation) * A numeric grid of the same shape as the input, where each number represents a rectangle * A list of coordinate sets, where each set includes all the coordinates of the cells in a rectangle If a puzzle has multiple solutions, you can output any number (one or more) of its valid solutions. The input is guaranteed to have at least one solution. ## Test cases ``` Puzzle: |-* *+| *-* Solution: 122 134 554 ===== Puzzle: +*** **|* *+** ***- Solution: 1122 1122 3322 3344 ====== Puzzle: |*+*+ ***** ****- ***+| +**** Solution: 12233 12233 44444 55667 55667 ======= Puzzle: ****-** **-**|* *|***** ****-** ******* **+*|** *****+* One possible solution: 1122222 1133344 1155544 1155544 6667744 6667788 6667788 =========== Puzzle: *-****|+** +*-******| ****+***** *-******|| **++|***** +****-|*** -****-**+* ********-* |*+*+|**** *-*--**+*+ Solution: 1111122334 5666622334 7777822994 7777A2299B CCDEA2299B CCFFFFGGHH IIIIJJGGHH KLLMMNGGOO KLLMMNGGPP QQRRSSSTPP ``` ## Rules Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~417~~ ~~374~~ 366 bytes Input is list of lines, `~` for non-clue. Outputs a single solution to stderr in the format `(x_start, width, y_start, height)`. ``` R=range k=input() X,Y=len(k[0]),len(k) W,H=R(X),R(Y) Q=[[]] for q in Q:C=[(x,y)for(a,b,c,d)in q for x in(a,a+b)for y in(c,c+d)];max(map(C.count,C+W))<4>0<all(sum(w>x-s>-1<y-t<h<[c for r in k[t:t+h]for c in r[s:s+w]if'~'>c]==['+|-'[cmp(h,w)]]for(s,w,t,h)in q)==1for x in W for y in H)>exit(q);Q+=[q+[(s,w+1,t,h+1)]for s in W for w in R(X-s)for t in H for h in R(Y-t)] ``` [Try it online!](https://tio.run/##RVDBbuIwEL37KywueGRnRdI9hTgXLr2CVqLI8sEYt44IToiNkkiIX6dxKraSNZp5b96b8bRjsI3Lns8d75T7MujMK9feAgH0wQ68No6cxUoCmzNAe/bOd@QD2I4cAG25EFKiz6bDV1w5vM03XJCBjTBBRLEj0@wEE3HFsWeYeiZU0WPk8RhLzTQ9gVxf1EAuqiWbP7q5ucA2dA9Q/C1Xhapr4m8X0pdD4sskLcYkFLYQevbs4tyzCHmgVkZAR6ATPve0l9Xn8rEsteRcLOk9WQp9aYllPcjYSzzrWWB23hA4T19L4j1@LYjfoTRDFcgV1lvKxZWKKKNpFNIU5pn@V9PHdLpQ4uc/htliZuwPc0gCyOdzQR8LtqD3BUL/bBUNpqvjzrSd8cYFnyP6QPSOUG8rbbFWDh8NblUXqsaZU/QK1kzGdd30lfvCvRpzlGboLUMozTFZMZwyHCOgbKrTV50BevvPxwff "Python 2 – Try It Online") This is too inefficient for the suggested test cases. --- ## Ungolfed ``` grid = input() total_width = len(grid[0]) total_height = len(grid) partitions = [[]] for partition in partitions: # list the corners of all rectangles in the current partition corners = [(x, y) for (start_x, width, start_y, height) in partition for x in (start_x, start_x + width) for y in (start_y, start_y + height)] # if no corners appears more than three times ... if corners != [] and max(map(corners.count, corners)) < 4: # .. and all fields are covered by a single rectangle ... if all( sum(width > x - start_x > -1 < y - start_y < height for (start_x, width, start_y, height) in partition) == 1 for x in range(total_width) for y in range(total_height)): # ... and all rectangles contain a single non-~ # symbol that matches their shape: if all( [char for row in grid[start_y: start_y + height] for char in row[start_x:start_x + width] if '~' > char] == ['+|-'[cmp(height, width)]] for (start_x, width, start_y, height) in partition): # output the current partition and stop the program exit(partition) # append each possible rectangle in the grid to the current partition, # and add each new partition to the list of partitions. partitions += [partition + [(start_x, width + 1, start_y, height + 1)] for start_x in range(total_width) for width in range(total_width - start_x) for start_y in range(total_height) for height in range(total_height - start_y)] ``` [Try it online!](https://tio.run/##rVXbjtowEH33V0zhgVgJaGH7FJX9ir6haGWCIZYSO7JNQ6QVv07HiXMBQlVVRQhie85czvFMytpmSm5ut5MWB9iCkOXZBpRYZVn@WYmDzXA35zJwBru3pDvKuDhldnRGCSmZtsIKJQ3u73ZJQshRaei30fuwMDEB/MwhF8aCzTikSkuuDagjsDwHzVPL5CnnxuEag7PWXNrBR@Ohg2HI4BJBTZvd0cflEBiLoE88b2qKoF3XEbSF0LvcpjxcnMXgxj9A2DqcDFqPIHUfEiE@ZuIZEEeQqq@DlSVn@F8ozbFs5mrXHB9FgVSsVqsGhZgO8A0rT4DJAxTsEhSsDPzJKlVnaaPOkFL4Ad/jPtM5Omtgju2j4PkBg2unwy@u@QH2NTAwwkkwiNEn4JNAbPBYO5hzEbR35wN5W/ZkfcByjTnU/VaNq5aMJx//phyF7RbWBF4JqLEIHoxuN520rR9tfSwa35k7BgcKRxc2VdIydNHzJ5VcXh@wpi72KncSW1TOphkC8ZoLDSZjJb8P9YrqXZox3eSsVeWybvrUcxQ/3bnkJc@NH1e1qjz8Ej9c8sRlsbguUEdn/ewLud8twq/lYpcWZdBG9LrRJPlfEsdPjuagzhYH1/SUaAQyVpXNcanVSbPiyQe/CBsMQYjvTdeNCOcszaBUxoj9XTf4ydRMT6um40edK3dPDt6X5NUoQw9tRiGOv2FItr02GqwhUjzgQpx59@Th1vqJQLdJJ/l39Hcq/117eFAbbAoy9Dv9c8RXTfYK5WuZBA0TBeu83WbhdRbNwq8ZIT8zYdrXGspWam5QG3z3hFcSfhFSZQLFSHHI7nlLs5I4@rysR5XnqsIOhorVMVlvyPuGkHUMwVvkaHa/lGxwve7WG0re@3P3pb8B "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), 193 bytes Returns all possible solutions as grids with -1, -2 … indicating rooms. There is room for improvements, but the `((((((` started to confuse me. :-) ``` [:(#~0=0(e.,)"2])'*+-|'([:,/(([(<./@,@:<:@[`]`[}{.<@:+"1,/@(#:i.)@{:)"2((((({(0,=/,</,>/)@$)~0({.*(1=#)*0<{.)@-.~,);.0~*[:*/0<1{])"2#]){.([,:-~)"1/>:))[(#~0<:,)~,/@(#:i.)@$)"2)^:(1#.*@,)@,:@i.] ``` [Try it online!](https://tio.run/##1ZHLTsMwEEX3/gqrqZQZv9PlNKksIbFixdYKVEKtKBs@wCa/HmynhSIeeyIl9ozPvTMTv8wr0x75QLzlijtO@dWG39zf3c6BoJnc4OBgFK42I7ZC6tRCIGUBAvTGeuWpJx/24z68RdN7kqtOWQ8NnQz6SFkH5Yng1GBVb9XOol/j5CAaAd3QoHB9zKw2k8KtcZMIJKzruzhmcTNiNBAU6QlXnd0RYihd9aRw@iy0zig@EHSNEV6hV@RPZpyRsWMd7vdRcr4TvjHJq2zxb0ZjjB2enl85bLU/Ig9b87jhUO8PWdKCCZmYyCv@BUohMilSwetO6L8FKXOycAud8fzJlWTNfJF@01a@6vRSMl35nNclluVoieW1a@d4NPxHb13gVIaQyz5HbDFYTC/JkpXyXLoe6hIwfW5DfjRS/l6dN10cdD2XDOd3 "J – Try It Online") For the larger test cases I provided `ff` that has a filter `[:(#~1*@#.|@,"2)` for intermediate steps, where empty grids got added because of padding. ### How it works * `'*+-|' … i.]` Map `*+-|` to `0 1 2 3`. * `,/@(#:i.)@$` From all the tiles * `[(#~0<:,)~` that aren't part of a room, * `{.([,:-~)"1/>:` starting from the most top-left tile, that isn't part of a room yet, try every possible rectangle spanning down-right. * `…"2#]` For that rectangle to be valid for the next step, * `[:*/0<1{]` 0.) it must have a positive size in each dimension * `0({.*(1=#)*0<{.)@-.~,` 1.) no tile must be part of a room, 2.) exactly one symbol must be within the rectangle, * `(({(0,=/,</,>/)@$)~` 3.) the dimension of the rectangle fulfill the constraint of the symbol. * `(<./@,@:<:@[`]`[}{.<@:+"1,/@(#:i.)@{:)"2` For every valid rectangle, copy the current grid and place the next room. * `^:(1#.*@,)@,:` We need to do this `n` times, where `n` is the number of symbols. * `[:(#~0=0(e.,)"2])` After this there might be grids that have `n` rooms, but still empty tiles; those must be filtered out. ]
[Question] [ Write an indefinitely-running program that reports how many instances of itself are currently running. Each instance of the program should also report the order in which it was opened out of all other currently-running instances. ## Example The user launches the program for the first time - we'll call this Instance 1. Instance 1 displays `1/1`, because it is the **first** instance to be launched out of a total of **1** currently-running instances. While Instance 1 is running, the user launches the program a second time to become Instance 2. Instance 1 now displays `1/2`, being the **first** instance out of a total of **2** currently-running instances. Instance 2 displays `2/2`, because it is the **second** instance out of a total of **2** currently-running instances. Let's say the user continues to spawn more instances until there are **5** of them. In order of launch, their outputs are: `1/5` `2/5` `3/5` `4/5` `5/5`. Now, let's say the user decides to terminate Instance 3. Instance 4 then becomes the new Instance 3 and Instance 5 the new Instance 4, because they are respectively the **third** and **fourth** instances to have been launched out of what is now a total of **4** instances. So each instance's change in output would be as follows: * `1/5` → `1/4` * `2/5` → `2/4` * `3/5` → (Terminated) * `4/5` → `3/4` * `5/5` → `4/4` ## Rules * You may output the two numbers (instance number, total instances) in any reasonable format. * Whenever an instance is launched or terminated, all other instances must update their respective outputs within 100 milliseconds. * If you choose to update output by printing to a new line (or other "appending" output format; as opposed to replacement), you must print only when the number of instances changes, and not at any other time. * This is code golf. Shortest program in bytes wins. * In your answer, you are encouraged to specify what the user must do to open more than one instance, and/or record a screencast to demonstrate. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 39 bytesSBCS Anonymous prefix function. Call by spawning on the dummy argument `⍬` (empty numeric vector), i.e. `f&⍬`. Query currently running threads with `⎕TNUMS` and kill one or more threads with `⎕TKILL n`. Threads output changes in [own number, total number] as soon as they get processor time, i.e. pretty much instantly. ``` {⍵≡n←n[⍋n←⎕TNUMS~0]:∇n⋄∇n⊣⎕←n⍳⎕TID,⊢/n} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71bH3UuzAMy86If9XaDGI/6pob4hfoG1xnEWj3qaM971N0CproWA2VACh/1bgap8XTRedS1SD@v9v9/9eCCxPK8zLx0hbTMslSF8sySDAUDPUOF4tTk/LwUhcy8ktSissScYit1rjS1R71ruID6XXxASijmq3tn5uSAbC7JyCxKAVoAcpq3p4@PgjEA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous lambda where `⍵` is the argument (initially `⍬`, the empty numeric vector)  `n[`…`]` index `n` (to be defined) with:   `⎕TNUMS~0` all **T**hread **Num**bers except number `0` (the REPL)    `n←` store as `n`    `⍋` permutation which would sort ascending   now we have the active threads in order   `⍵≡` if the argument is identical to that…   `:` then:    `∇⍵` tail recurse on the argument   `⋄` else:    `⊢/n` the rightmost thread number    `⎕TID,` this **T**hread's **ID** (thread number) prepended to that    `n⍳` find the **ɩ**ndices of those two    `⎕←` print that to STDOUT    `n⊣` discard that in favour of `n`    `∇` recurse on that [Answer] # Python 3, ~~694~~ 691 bytes # main.py ``` from requests import post as u from _thread import* import os os.system("start cmd /C python s") def l(): def p(q): while 1:print(u(*q).text,end="\r") q=['http://localhost'] q+=[u(q[0],'*').text] start_new_thread(p,(q,)) input() u(q[0],'-'+q[1]) while 1: try:l();break except:0 ``` # s (short for server.py) ``` from bottle import* from requests import post as q try: q("http://localhost") except: ids=["0"] @post('/') def _(): content = request.body.read().decode('utf-8') if len(content)==0:return"" if content[0]=="*":ids.append(str(int(ids[-1])+1));return str(ids[-1]) elif content[0]=="-":del ids[ids.index(content[1:])] else:return str(ids.index(content)) + "/" + str(len(ids)-1) run(port="80") ``` # Why is it so long? Unfortunately, this functionality doesn't seem to be built into Python. I was tempted to use multiprocessing, but that didn't quite seem to be the right fit for what we're doing (letting a user open a program from anywhere). So, I took the advice of a StackOverflow post I saw (I misplaced the link) and I implemented it using `bottle`. (I am open to new suggestions). I used the Bottle library to run my own mini http server so all the different instances can communicate with each other. I suppose I could have used a socket, although I'm not convinced that would have reduced the byte count. I have two seperate files, `s` and `main.py`. `s` is short of server and because it appears in the code, I figured I should make the name as short as possible. # Communication Web Server's API The web server only accepts POST requests and only responds to input inside the POST's body. All requests go through `/` (or `localhost/`). Valid input: * `*` in the post body will request for the server to return a new id to assign the client. * `-<id>` in the post body will remove the id from the active list of id's, decreasing all relevant id's and the total count. * An empty request in the post body will simply return an empty string. This is what is used for testing to see if the server is online. # Closing the program I implemented multi-threading so closing the program is as simple as pressing enter. # Opening the program If you do not have Python setup correctly inside your environmental variables simply create a `.bat` file and put it in the same folder as `main.py` and `s` with the following code (if you installed Python for all users, it may be at a different location): ``` set PATH=%userprofile%\AppData\Local\Programs\Python\Python36 python main.py ``` # Credits From 694 to 691 bytes [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m). [Answer] # sh + linux/unix tools, 128 bytes if sleep supports floating point numbers ``` trap '(flock 9;grep -vw $$ p>t;mv t p)9>l' exit;(flock 9;echo $$>>p)9>l;f(){ echo $(sed -n /^$$\$/= p)/$(wc -l<p);sleep .1;f;};f ``` otherwise, 159 bytes ``` trap '(flock 9;grep -vw $$ p>t;mv t p)9>l' exit;(flock 9;echo $$>>p)9>l;perl -MTime::HiRes=usleep -nE/^$$'$/&&say("$./",$.+(@a=<>)),usleep 1e5,$.=-(@ARGV=p)' p ``` or sleep can be replaced with `:` (no-op), but it will make active waiting. [Answer] # Java 8, (199+301=) 500 bytes **M.jar: (the main program)** ``` import javafx.collections.*;class M{static ObservableList o=FXCollections.observableArrayList();static int j,F;int i,f;{F=0;ListChangeListener e=(ListChangeListener.Change c)->{if(f<1)System.out.println((F>0&i>F?--i:i)+"/"+j);};o.addListener(e);o.add(i=++j);}public void f(){F=f=i;j--;o.remove(--i);}} ``` **S.jar: (the server to control the program-flow)** ``` import java.util.*;interface S{static void main(String[]a){List<M>l=new Stack();for(Scanner s=new Scanner(System.in);;){Float n=s.nextFloat();if(n%1==0)l.add(new M());else{int t=(int)(n*10-1);l.get(t).f();l.remove(t);}}}} ``` **Explanation of the code:** ``` import javafx.collections.*; // Required import for ObservableList, FXCollections, and ListChangeListener class M{ // Program-class static ObservableList o=FXCollections.observableArrayList(); // Static list to keep record of all instances static int j, // Static integer (total number of instances) F; // Static flag (remove occurred?) int i, // Non-static integer (id of this instance) f; // Non-static flag (has been removed) { // Non-static initializer-block (shorter than constructor) F=0; // Reset the static flag remove_occurred, because we add a new instance o.addListener((ListChangeListener.Change c)->{ // Add a change listener for the ObservableList // This will monitor any additions or removes on the List if(f<1) // If this instance is not removed yet: System.out.println( // Print: (F>0&i>F? // If a removed occurred and this id is larger than the removed instance --i // Decrease its id by 1 before printing it : // Else: i) // Just print its id +"/"+j); // Plus the total number of instances left }); o.add( // Add anything to the Observable list to trigger the listener i=++j); // Increase the total amount of instances, and set the id of this instance to the last one } // End of non-static initializer-block public void f(){// Finalize-method F=f=i; // Set both flags to the current id j--; // Decrease the total amount of instances o.remove(--i);// Remove the current instance from the list to trigger the listener } // End of Finalize-method } // End of Program-class import java.util.*; // Required import for List, Stack and Scanner interface S{ // Server-class static void main(String[]a){ // Mandatory main-method List<M>l=new Stack(); // List of programs for(Scanner s=new Scanner(System.in); // Create a STDIN-listener for user input ;){ // Loop indefinitely int t=s.nextInt(); // Get the next integer inputted if(t<1) // If it's 0: l.add(new M()); // Startup a new program, and add its instance to the list else{ // Else: l.get(t).f(); // Close the program with this integer as id l.remove(t);} // And remove it from the list of programs } // End of loop } // End of main-method } // End of Server-class ``` **General explanation:** All programs will keep a record of their own id; the total number of instances left; whether a remove occurred; and which programs have closed. The server is just a wrapper-class to start and stop programs. When a user inputs `0`, it will startup a new program. When the used inputs a positive integer (i.e. `2`), it will close the program with that id. (Note: S.jar has M.jar as library to access it.) **Gif to see it in action:** [![enter image description here](https://i.stack.imgur.com/LBD4h.gif)](https://i.stack.imgur.com/LBD4h.gif) ***Thoughts to golf it further:*** I just noticed while writing the explanation that I only use the `ObservableList` for it's add/remove-`ListChangeListener`, and don't use its content at all. Removing this and using another type of static Listener might be shorter. ]
[Question] [ > > **TL;DR:** Given an array of chars and a robot in a starting position of the array, write an algorithm than can read a string with movements (`F` for "go forward", `R` for "rotate 90 degrees right" and `L` for "rotate 90 degrees left") and calculate the ending position of the robot. More details in the complete text. > > > We have at home a very simple programmable device for kids: a small vehicle with buttons to make the vehicle go forward, turn 90 degrees left or turn 90 degrees right. Something similar to this: [![Mouse vehicle](https://i.stack.imgur.com/n00Wom.jpg)](https://i.stack.imgur.com/n00Wom.jpg) We also have a foam mat with letters like this: [![Playing mat](https://i.stack.imgur.com/Y4pp0m.jpg)](https://i.stack.imgur.com/Y4pp0m.jpg) The purpose of all this is to teach the kids both the alphabet and the rudiments of programming, all at once. ### The challenge Suppose we have randomly arranged our foam mat like this: ``` +---+---+---+---+---+---+---+ | E | R | L | B | I | X | N | +---+---+---+---+---+---+---+ | O | A | Q | Y | C | T | G | +---+---+---+---+---+---+---+ | F | W | H | P | D | Z | S | +---+---+---+---+---+---+---+ | K | V | U | M | J | +---+---+---+---+---+ | | +---+ ``` Suppose also we have modified the vehicle so that when we program a "go forward" command, the vehicle goes forward exactly size of one square in the mat. So, if the vehicle is in the `U` square and goes north, it stops exactly in the `P` square. The instructions are all given to the vehicle before it starts to move, and those are: * `F`: The vehicle goes forward into the next square. * `R`: The vehicle turns 90 degrees right in its place (no further movement). * `L`: The vehicle turns 90 degrees left in its place (no further movement). Once the instructions are given, you can press the "GO" button and send the vehicle to a given position as it will follow every instruction in the given order. So, you can tell the kid to insert the needed instructions for the vehicle to go to a given letter. You must write the shortest program/function that processes a `string` (input parameter) with a set of instructions and calculates the letter the vehicle stops over (output `string`). Details: * The vehicle always starts at the blank square at the bottom, and facing north (towards the `U` square). * The input string will contain only the letters `F`, `R`, `L` and `G` (for the "go" button). You can use lowercase letters for the mat and the instructions, if you prefer so. * The algorithm must obey every instruction in the string before the first `G` (every instruction after that is ignored as the vehicle has started moving). * If the vehicle goes out of the mat at any given moment (even if the input string has not been completely processed), the algorithm must return the string `Out of mat`. * If not, the algorithm must return the letter the vehicle has stopped over. The starting point counts as a char (or an empty string). ### Examples: ``` Input: FFG Output: P Input: FRFRFG Output: Out of mat Input: RRFFG Output: Out of mat Input: FFFRFFLFG Output: X Input: FFFRFFLF Output: <-- Nothing or a whitespace (the robot has not started moving) Input: FFFRRFFFG Output: <-- Nothing or a whitespace (the robot has returned to the starting point) Input: RRRRRLFFFLFFRFRFGFFRRGRFF Output: L (Everything after the first G is ignored) ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program for each language win! [Answer] # JavaScript (ES6), ~~194~~ ~~176~~ ~~169~~ 163 bytes Saved some bytes thanks to @Luke and @Arnauld. ``` s=>(p=35,d=3,t='ERLBIXN1OAQYCTG1FWHPDZS11KVUMJ11111 11',[...s].every(i=>i=='L'?d--:i>'Q'?d++:i<'G'?+t[p+=[1,8,-1,-8][d%4]]||!t[p]?p=1/0:p:0)?'':t[p]||'Out of mat') ``` Ungolfed: ``` s=>( p=35, d=3, t='ERLBIXN1OAQYCTG1FWHPDZS11KVUMJ11111 11', [...s].every(i=>i=='L'?d--: i<'Q'?d++: i<'G'?+t[p+=[1,8,-1,-8][d%4]]||!t[p]?p=1/0:p: 0 )?'': t[p]||'Out of mat' ) ``` ``` f= s=>(p=35,d=3,t='ERLBIXN1OAQYCTG1FWHPDZS11KVUMJ11111 11',[...s].every(i=>i=='L'?d--:i>'Q'?d++:i<'G'?+t[p+=[1,8,-1,-8][d%4]]||!t[p]?p=1/0:p:0)?'':t[p]||'Out of mat') console.log(f('FFG')); //P console.log(f('FRFRFG')); //Out of mat console.log(f('RRFFG')); //Out of mat console.log(f('FFFRFFLFG')); //X console.log(f('FFFRFFLF')); //(space) console.log(f('FFFRRFFFG')); //(space) console.log(f('RRRRRLFFFLFFRFRFGFFRRGRFF')); //L console.log(f('FFFFFRRFG')); //Out of mat ``` [Answer] # [Python 2](https://docs.python.org/2/), 235 bytes ``` x=0;y=1;a=4;b=3 p='ERLBIXN','OAQYCTG','FWHPDZS','aKVUMJ','aaa ' r='' for i in input(): if'G'==i:r=p[a][b];break elif'G'>i: b+=x;a-=y; if(-1<a<5)-1or(''<p[a][b:]<'a')-1:r='Out of mat';break else:x,y=[[y,-x],[-y,x]][i<'R'] print r ``` [Try it online!](https://tio.run/##VZBJb4MwEIXv/hVWLkNUkEqXCzCVupkutGlpuiIfTGoUqykgh6jw6@kQIlW1ffj83psZ2XXXLKvyoF9Unxonk0nf4n7YoR8qPApzPGQ1wmWanF2/3YMLs9PH9/N5TCRerx4uPp6I1O3L893NAEpxYBYBWFFZbrgp6dSbxpkGjJsCYkA0gcU6UzLLZZhbrb4Y16utd2IoxfM9bEPlYRfSxRSO50cqOp56fmUdgGgsDWQECkikZjDbNLwq@Ldq4K/jWget22GWda7XSjfzOreVMjMRpCBZbU3ZcNvTe9nP0qw0n9uNHsbrVi/48Bc9CBEDA5HSHiBNd4IgQST/eIfEuyitRAzOWD54MbljbpuM4Rc "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~226~~ ~~231~~ 241 bytes Second edit; should work now. Again, plenty of optimization to be done. ``` n=input();s="0ERLBIXN00OAQYCTG00FWHPDZS000KVUMJ000000 00000";d=1;c=40;i=0;w=[-1,-9,1,9] while n[i]!="G"and c>=0: if n[i]=="F":c+=w[d] else:d=[d+[-1,3][d<0],-~d%4][n[i]=="R"] i+=1 print(["Out of mat",s[c]][c in range(len(s))and s[c]!="0"]) ``` [Try it online!](https://tio.run/##LU5La8MwGLvnV3iGQUIc@EJ7abxvsJezR7d22XvGh2CnqyFzQ@MSetlfz5pQHXSQhKRm79cbN@l7h9Y1Ox9GvEUKN8X88u7zCWBx8fx19ZoDiI/b5fX3CwA8vL893sMIMjLlBlOucQrcIvAOZZKyZMZSNlNBt7Z1RZy06gRpTktniD5HyAJiV6OMSAXNdIydNCogVd1WmUFp4qFloqQ5A8WSP3M6VfKYL@ghaGNMg2ZrnQ8lXew82azIb@kpa6VWSmpiHdmW7qcK68qFbRQN04N3@AFURX0vhCiEmIv8Hw "Python 3 – Try It Online") [Answer] # [Wolfram Language](http://reference.wolfram.com/language)/Mathematica, 300 Bytes ``` p=Re[(1-7I)#[[1]]]&;d=Drop;t=Throw;s=Switch;s[#,0,"Out of mat",_,StringPart["000 0000KVUMJ0FWHPDZSOAQYCTGERLBIXN",p@#]]&@Catch@Fold[If[MemberQ[d[d[Range[4,35],{2,5}],{7}],p@#],#,t@0]&@(s[#2,"F",#+{#[[2]],0},"R",#{1,-I},"L",#{1,I},_,t[#]]&)[#1,#2]&,{4,I},If[StringFreeQ["G"]@#,{"G"},Characters@#]&@#]& ``` Ungolfed: ``` p = Re[(1 - 7 I) #[[1]]] &; d = Drop; t = Throw; s = Switch; s[#, 0, "Out of mat", _, StringPart["000 0000KVUMJ0FWHPDZSOAQYCTGERLBIXN", p@#]] &@ Catch@ Fold[ If[MemberQ[d[d[Range[4, 35], {2, 5}], {7}], p@#], #, t@0] &@(s[#2, "F", # + {#[[2]], 0}, "R", # {1, -I}, "L", # {1, I}, _, t[#]] &)[#1, #2] &, {4, I}, If[StringFreeQ["G"]@#, {"G"}, Characters@#] &@#] & ``` ]
[Question] [ You're sick of other players smugly announcing "BINGO" and walking triumphantly past you to claim their prize. This time it will be different. You bribed the caller to give you the [BINGO](https://en.wikipedia.org/wiki/Bingo_(U.S.)) calls ahead of time, in the order they will be called. Now you just need to create a BINGO board that will win as early as possible for those calls, guaranteeing you a win (or an unlikely tie). Given a delimited string or list of the calls in order, in typical BINGO format (letters included, e.g. `B9` or `G68`, see the rules for more info), output a matrix or 2D list representing an optimal BINGO board for those calls. Assume input will always be valid. ### BINGO Rules: * 5x5 board * A "BINGO" is when your card has 5 numbers in a row from the numbers that have been called so far. * The center square is free (automatically counted towards a BINGO), and may be represented by whitespace, an empty list, `-1`, or `0`. * The 5 columns are represented by the letters `B`,`I`,`N`,`G`,`O`, respectively. * The first column may contain the numbers 1-15, the second 16-30, ..., and the fifth 61-75. * The letters and numbers taken for input may optionally be delimited (by something that makes sense, like a `,` or space) or taken as a tuple of a character and a number. * Output requires only numbers in each place in the matrix. * Squares that will not contribute to your early BINGO must be valid, but do not have to be optimal. * **This is code-golf, shortest code wins** ### Examples: I'm using this input format for the examples, because it's shorter. See the section above for acceptable input/output formats. ``` O61 B2 N36 G47 I16 N35 I21 O64 G48 O73 I30 N33 I17 N43 G46 O72 I19 O71 B14 B7 G50 B1 I22 B8 N40 B13 B6 N37 O70 G55 G58 G52 B3 B4 N34 I28 I29 O65 B11 G51 I23 G56 G59 I27 I25 G54 O66 N45 O67 O75 N42 O62 N31 N38 N41 G57 N39 B9 G60 I20 N32 B15 O63 N44 B10 I26 O68 G53 I18 B12 O69 G49 B5 O74 I24 Possible Output (this has a horizontal BINGO in 3rd row. A diagonal is also possible.): [[11,25,42,53,68], [ 6,22,32,57,62], [ 2,16, 0,47,61], [ 3,17,37,59,75], [ 9,19,41,46,70]] N42 N34 O66 N40 B6 O65 O63 N41 B3 G54 N45 I16 O67 N31 I28 B2 B14 G51 N36 N33 I23 B11 I17 I27 N44 I24 O75 N38 G50 G58 B12 O62 I18 B5 O74 G60 I26 B8 I22 N35 B1 B4 G53 O73 G52 O68 B10 O70 I30 G59 N43 N39 B9 G46 G55 O64 O61 I29 G56 G48 G49 I19 G57 N37 O72 I25 N32 B13 B7 B15 O71 I21 I20 O69 G47 Must be a vertical BINGO in 3rd (N) column (because 4 N's came before one of each B,I,G,O): [[11,25,42,53,63], [ 2,22,34,57,65], [ 6,16, 0,47,66], [ 3,17,41,54,75], [ 9,19,40,46,70]] ``` [Answer] # Mathematica, 302 bytes ``` (b=Prepend;i=1;n=15#&@@#-15+Range@5&;g=#~b~{N,0};o={#2,#3,#,##4}&@@#&;While[(l=Length@Union[t=(k=Take)[#&@@@g,i]])<5&&Max[#2&@@@Tally@t]<5,i++];If[l<5,m=#&@@Commonest@t;If[m===#,o[g~k~i/.{m,x_}->x/.{_,_}->Nothing],n@#2]&,o@DeleteDuplicates@b[n@#2,<|#->#2&@@@Reverse@g|>@#]~k~5&]~MapIndexed~{B,I,N,G,O})& ``` Unnamed function taking as its argument a list of ordered pairs, such as `{{N,42},{N,34},{O,66},{N,40},...}` (note that the first element in each ordered pair is not a string but rather a naked symbol), and returning a 2D list of integers, where the sublists represent columns (not rows) of the bingo board. Output for the first test case: ``` {{1,3,2,4,5},{17,18,16,19,20},{31,32,0,33,34},{46,48,47,49,50},{62,63,61,64,65}} ``` In general, when the earliest possible bingo occurs because of a number called in each of the B/I/G/O rows, then those numbers will be in the center row; each column will otherwise contain the four smallest possible numbers (taking the already used number into account). For example, if the first test case is changed so that the second number called is `B12` rather than `B2`, then the first column of the output board will be `{1,2,12,3,4}`. Output for the second test case: ``` {{1,2,3,4,5},{16,17,18,19,20},{42,34,0,40,41},{46,47,48,49,50},{61,62,63,64,65}} ``` In general, when the earliest possible bingo occurs because of five numbers called in a single column (or four called in the N column), then the remaining four columns contain their five smallest possible numbers in order. If the second test case is changed from `{{N,42},{N,34},{O,66},{N,40},...}` to `{{O,72},{O,74},{O,66},{N,40},...}` (only the first two entries changed), then the output is: ``` {{1,2,3,4,5},{16,17,18,19,20},{31,32,33,34,35},{46,47,48,49,50},{74,66,72,65,63}} ``` Somewhat ungolfed version: ``` (b=Prepend;i=1;n=15First[#]-15+Range[5]&;g=b[#,{N,0}];o={#2,#3,#,##4}&@@#&; While[ (l=Length[Union[t=(k=Take)[Apply[#&,g,{1}],i]]])<5 && Max[Apply[#2&,Tally[t],{1}]]<5, i++]; MapIndexed[ If[l<5, m=First[Commonest[t]];If[m===#,o[k[g,i]/.{m,x_}->x/.{_,_}->Nothing],n[#2]]&, k[ o[DeleteDuplicates[b[n[#2],Association[Apply[#->#2&,Reverse[g],{1}]][#]]]] ,5]& ],{B,I,N,G,O} ])& ``` The first line is mostly definitions to shorten the code, although `g` prepends the center square `{N,0}` to the input to simplify the bingo-finding. (The `n` function gives the smallest five legal bingo numbers in the `#`th column, 1-indexed. The `o` function takes a 5-tuple and moves the first element so that it's third.) The `While` loop in lines 2-6 finds the smallest initial segment of the input that contains a bingo. (The third line tests for one-in-each-column bingos, while the fifth line tests for single-column bingos). For any function `F`, the operator `MapIndexed[F,{B,I,N,G,O}]` (starting in line 7) produces the 5-tuple `{F{B,1},F{I,2},F{N,3},F{G,4},F{O,5}}` (well, technically it's `{F{B,{1}},...}`); we apply a function `F` that creates a bingo-board column out of its two arguments. That function, however, depends on which type of bingo was found: line 8 is true when we have a single-column bingo, in which case the function (line 9) uses the relevant input numbers in the bingo column and default numbers in the other columns. In the other case, the function (lines 10-12) uses the relevant input numbers in the center of each column and default numbers elsewhere. [Answer] # JavaScript (ES6) 372 Bytes Can probably still be golfed a bit, but I don't see how. Suggestions are much appreciated ;) ``` A=a=>[1,2,3,4,5].map(x=>x+15*a),F=a=>{b=[[],[],[i=0],[],[]],a.replace(/[^0-9 ]/g,"").split` `.some(x=>{b[--x/15|(c=0)].push(++x);return b.some((x,i)=>(d=x.length)>4||d==1&i-2&&++c>3)});for(e=[A(0),A(1),A(2),A(3),A(4)];i<5;a=b[i][0],b[i][0]=b[i][2],b[i++][2]=a)for(j=0;j<5&b[i].length<5;j++)b[i][j]<i*15+5?e[i].splice(e[i].indexOf(b[i][j]),1):b[i][j]=e[i].shift();return b} ``` ]
[Question] [ ## The challenge Your task is to animate Adve the Adventurer moving through a creepy (i.e. Halloween) maze. Adve is a `•`; he's character fluid, though, so he does not mind being represented by a different character. To animate Adve, you print out each frame; a frame is the map with his current location in it. Adve moves one space forward every turn and never backtracks. He starts in the first row and ends in the last. ## Input Any reasonable format like a string with a delimiter or string array. You can assume the input will be a map greater than 3\*3, containing only one possible path. The only characters present will be `#` and . ## Output The frames. ## Example maze ([ok... labyrinth](https://codegolf.stackexchange.com/q/98061/42854?noredirect=1#comment238339_98061)) Here is a map without Adve in it; the first and last frames are this empty map (this map is 9x15): ``` ### ##### ## ##### ## ###### ## # ####### # # ### # # # # # # # ### # ####### # #### #### #### #### ### ##### ### ##### ### ##### ### ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! The *exact* output for this can be found [here](http://www.pastebin.com/Y2fHazBr) (37 frames). ## This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] ## Perl, 84 bytes *Thanks [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) for guiding me to the right direction to golf out around 30 bytes!* Bytecount includes 82 bytes of code and `-0p` flags. ``` /.*/;say y/A/ /r;s/&(.{@{+}})? /A$1&/s||s/ (.{@{+}})?&/&$1A/s||s/ /&/?redo:y;A&; ``` Note that there are two final spaces, and no final newline (it won't work otherwise). Takes the maze as input as outputs all the needed frames for Adve to get out of it. Note that Adve is a `&` rather than a `•`, since the latter isn't utf8 (and perl doesn't use utf8 by default). Run it with `-0pE` flags : ``` perl -0pE '/.*/;say y/A/ /r;s/&(.{@{+}})? /A$1&/s||s/ (.{@{+}})?&/&$1A/s||s/ /&/?redo:y;A&; ' <<< "### ##### ## ##### ## ###### ## # ####### # # ### # # # # # # # ### # ####### # #### #### #### #### ### ##### ### ##### ###" ``` --- *Just for the eyes*, I also made this animated version, that is a little bit longer, but will clear the terminal between each print and sleep 0.15 sec, so it will look like Adve is actually moving : ``` perl -0nE 'system(clear);/.*/;say y/A/ /r;select($,,$,,$,,0.15);s/&(.{@{+}})? /A$1&/s||s/ (.{@{+}})?&/&$1A/s||s/ /&/?redo:say"\e[H",y/A&/ /r' <<< "### ##### ## ##### ## ###### ## # ####### # # ### # # # # # # # ### # ####### # #### #### #### #### ### ##### ### ##### ###" ``` [Answer] # JavaScript (ES6), 137 (1 byte saved thx @ETHproductions) ``` m=>(o=>{for(p=m.search` `-o,r=[m];[d,o/d,-o/d].some(q=>1/m[d=q,q+=p]?p=q:0);r.push(q.join``))(q=[...m])[p]=0})(d=1+m.search` `)||[...r,m] ``` *Less golfed* ``` m=>{ d = o = 1+m.search`\n`; // offset to next row and starting direction p = m.search` `-o; // starting position, 1 row above the first for( r=[m]; // r is the output array, start with empty maze // try moving in 3 directions (no back) // if no empty cell found, we have exit the maze [d,o/d,-o/d].some(q => 1/m[d=q,q+=p]? p=q : 0); r.push(q.join``) // add current frame ) q=[...m], q[p] = 0; // build frame, '0' used to mark Adve position return [...r,m] // add last frame with maze empty again } ``` **Test** ``` F= m=>(o=>{for(p=m.search` `-o,r=[m];[d,o/d,-o/d].some(q=>1/m[d=q,q+=p]?p=q:0);r.push(q.join``))(q=[...m])[p]=0})(d=1+m.search`\n`)||[...r,m] function go() { var i=I.value,r=F(i), frame=x=>(x=r.shift())&&(O.textContent=x,setTimeout(frame,100)) frame() } go() ``` ``` #I { width:10em; height: 19em; font-size:10px} #O { white-space:pre; font-family: monospace; font-size:10px; vertical-align: top; padding: 4px} ``` ``` <table><tr><td> <textarea id=I>### ##### ## ##### ## ###### ## # ####### # # ### # # # # # # # ### # ####### # #### #### #### #### ### ##### ### ##### ### ##### ### </textarea><button onclick='go()'>go</button></td><td id=O></td></tr></table> ``` ]
[Question] [ [![enter image description here](https://i.stack.imgur.com/6Ee3A.jpg)](https://i.stack.imgur.com/6Ee3A.jpg) In music theory, an [interval](https://en.wikipedia.org/wiki/Interval_(music)) is the difference between two pitches. Each pitch is defined by the number of half-steps (The difference between C and C#) or whole steps (The difference between C and D). One whole step is the same as two half-steps. Here is a list of all the default intervals and the number of half-steps they represent: ``` 0 Perfect Unison 2 Major Second 4 Major Third 5 Perfect Fourth 7 Perfect Fifth 9 Major Sixth 11 Major Seventh 12 Perfect Octave ``` There are 3 variations on the default intervals, **minor**, **diminished**, and **augmented**. * A **minor** interval is one half-step lower than a major interval, but not a perfect interval. So you have a minor second (1), a minor third (3), a minor sixth (8), and a minor seventh (10). There is no such thing as a minor fourth, minor fifth, minor unison or minor octave since these are all perfect intervals. * A **diminished** interval is one half-step lower than a minor *or* perfect interval. There is diminished Second (0), diminished third (2), diminished fourth (4), diminished fifth (6), diminished sixth (7), diminished seventh (9) and diminished octave (11). * An **augmented** interval is one half-step *higher* than a major or perfect interval. We have Augmented Unison (1), Augmented Second (3), Augmented third (5), Augmented Fourth (6), Augmented fifth, (8), Augmented sixth (10), and Augmented seventh (12). # The challenge: You must write a program or function that takes a number of half steps or whole steps and then prints *one of* the valid English descriptions of this interval. It doesn't matter which description you pick, as long as it exactly matches the IO table. You can take this as one string ``` "5w" == 5 whole steps "3h" == 3 half steps ``` or as a number and a string/char. ``` 5, "w" == 5 whole steps 3, "h" == 3 half steps. ``` You can assume that every input will be between 0 and 12 half steps. # IO table Here is a full list mapping the number of half-steps to all acceptable outputs. ``` 0 Perfect unison, Diminished second 1 Minor second, Augmented unison 2 Major second, Diminished third 3 Minor third, Augmented second 4 Major third, Diminished fourth 5 Perfect fourth, Augmented third 6 Diminished fifth, Augmented fourth 7 Perfect fifth, Diminished sixth 8 Minor sixth, Augmented fifth 9 Major sixth, Diminished seventh 10 Minor seventh, Augmented sixth 11 Major seventh, Diminished octave 12 Perfect octave, Augmented seventh ``` Here is some sample I/O: ``` 5w Minor Seventh 5h Augmented Third 12h Perfect Octave 12w UNDEFINED 1w Diminished third 2h Major Second ``` [Answer] # Ruby, Rev B 138 bytes ``` ->n,s{i=12-n-n*(s<=>?h) [a='Augmented','Major','Minor',d='Diminished',a,'Perfect',d][i%7]+' '+%w{seventh fifth third unison}[i%7/4+i/7*2]} ``` 5 bytes saved by not repeating `Augmented/Diminished`. 1 byte saved by use of `?h`. # Ruby, Rev A 144 bytes ``` ->n,s{i=12-n-n*(s<=>'h') %w{Augmented Major Minor Diminished Augmented Perfect Diminished}[i%7]+' '+%w{seventh fifth third unison}[i%7/4+i/7*2]} ``` The idea is to minimise the number of basic intervals (seventh fifth third and unison only) and take advantage of the fact that sevenths and fifths have an analogous relationship to that between thirds and unisons. There are four types of seventh/third and 3 types of fifth/unison so the index variable `i` is set to 12 minus the number of half steps, so that the first term of the expression `i%7/4 + i/7*2` will correctly select the type of basic interval. **ungolfed in test program** ``` f=->n,s{ #n = number of steps. s= step size, w or h i=12-n-n*(s<=>'h') # i=12-n. If s is later in the alphabet than 'h' subtract again for whole steps %w{Augmented Major Minor Diminished Augmented Perfect Diminished}[i%7]+ ' '+%w{seventh fifth third unison}[i%7/4+i/7*2] } -1.upto(12){|j| puts f[j,'h'] } 0.upto(6){|j| puts f[j,'w'] } ``` **output** ``` Diminished unison Perfect unison Augmented unison Diminished third Minor third Major third Augmented third Diminished fifth Perfect fifth Augmented fifth Diminished seventh Minor seventh Major seventh Augmented seventh Perfect unison Diminished third Major third Diminished fifth Augmented fifth Minor seventh Augmented seventh ``` Undefined behaviour inputs: The function gives the correct answer of `diminished union` for -1 halfsteps, but fails for inputs over 12. For example, it outputs `perfect unison` for 14 half steps, as the algorithm is based on a cycle of 14 rather than 12. [Answer] ## Python 2, 149 bytes ``` def f(n,c):n*=1+(c>'h');print(n-6)%13%2*"Diminished"or"Augmented",'octave seventh sixth fifth fourth third second unison'.split()[71056674174>>3*n&7] ``` First, whole steps are converted to half steps. Then, `Diminished` vs `Augmented` is printed. These alternate for adjacent `n` except that `n=5` and `n=6` give the same, which is achieved by first putting them across a boundary modulo an odd number. Finally, the distance is printed, computed via a three-bit lookup table. This is shorter than doing `int('6746543230210'[n])`. [Answer] # Python 2.7, 155 bytes ``` s='second unison third fourth sixth fifth seventh octave Diminished Augmented'.split() def f(n,c):x=0xDE9CB87561430>>[4,8][c>'h']*n;print s[x%2+8],s[x/2%8] ``` [Answer] # Retina, 153 bytes ``` \d+ $* (.*)w|h $1$1 ^1*$ $.0 ^[02479]|11 Diminished $0 ^\d Augmented $0 10|7 sixth 11 octave 12|9 seventh 8 fifth 4|6 fourth 5|2 third 1 unison \d second ``` Input number is first converted to unary, then doubled if followed by `w`, and any letters are removed, leaving only the unary number. This number is then converted back to decimal. Finally, some search and replace is applied to construct the final output. Example runs: ``` 6w => 111111w => 111111111111 => 12 => Augmented 12 => Augmented seventh 7h => 1111111h => 1111111 => 7 => Diminished 7 => Diminished sixth 3w => 111w => 111111 => 6 => Augmented 6 => Augmented fourth 0h => h => => 0 => Diminished 0 => Diminished second ``` [Try it online!](http://retina.tryitonline.net/#code=XGQrCiQqCiguKil3fGgKJDEkMQpeMSokCiQuMApeWzAyNDc5XXwxMQpEaW1pbmlzaGVkICQwCl5cZApBdWdtZW50ZWQgJDAKMTB8NwpzaXh0aAoxMQpvY3RhdmUKMTJ8OQpzZXZlbnRoCjgKZmlmdGgKNHw2CmZvdXJ0aAo1fDIKdGhpcmQKMQp1bmlzb24KXGQKc2Vjb25k&input=OWg) [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 166 bytes Well, this can definitely be further golfed. ``` WW2M1+*a+mZ 'dehsinimiD' 'roniM' 'rojaM' 'tcefreP' 'detnemguA' 'dnoces ' 'htruof ' 'htxis ' 'evatco ' 6m1m 6m2m 6m3m 6m5m 7m1m 7m4m 7m5m 8m1m 8m2m 8m3m 8m5m 9m1m 9m4m ``` This works by defining the minimal amount of items possible, then calling those items through the method syntax. [Try it Online!](http://vitsy.tryitonline.net/#code=V1cyTTErKmErbVoKJ2RlaHNpbmltaUQnCidyb25pTScKJ3JvamFNJwondGNlZnJlUCcKJ2RldG5lbWd1QScKJ2Rub2NlcyAnCidodHJ1b2YgJwonaHR4aXMgJwonZXZhdGNvICcKNm0xbQo2bTJtCjZtM20KNm01bQo3bTFtCjdtNG0KN201bQo4bTFtCjhtMm0KOG0zbQo4bTVtCjltMW0KOW00bQ&input=NQp3&debug=on) [Answer] # Javascript 189 bytes ``` a=>(n='sutsftfxFvxov'[N=parseInt(a)*(a.slice(-1)>'v'?2:1)])&&((N>5?N+1:N)%2?'Augmented ':'Dimished ')+'unison,second,third,fourth,fifth,sixth,seventh,octave'.split`,`['ustfFxvo'.indexOf(n)] F= a=> (n='sutsftfxFvxov' //using the right side of the possible answers //set n = the letter representing //unison, first, second ... //set N to 12 for 12h, but 24 for 12w [N=parseInt(a)*(a.slice(-1)>'v'?2:1)]) && //if we were out of range (12w) we'll return undefined ( (N>5?N+1:N)%2? //get Aug or Dim (right side goes) //DADADAADADADA // ^^ makes this a pain 'Augmented ':'Dimished ' ) + //turn n (which is u for unison, x for sixth, etc //into it's full name 'unison,second,third,fourth,fifth,sixth,seventh,octave' .split`,` ['ustfFxvo'.indexOf(a)] ``` [Answer] ## Java, ~~225~~ 224 bytes There has got to be a better way to pack these strings but I don't have any ideas. ``` (i,s)->{String A="Augmented",M="Major",m="Minor",P="Perfect",D="Diminished",d=" Second",f=" Fourth",a=" Sixth",C=" Octave";String[]o=new String[]{D+d,m+d,M+d,A+d,P+f,A+f,D+a,m+a,M+a,A+a,D+C,P+C};i*=s=='w'?2:1;return o[i-1];} ``` Indented: ``` static BiFunction<Integer, Character, String> interval = (i,s) -> { String A="Augmented",M="Major",m="Minor",P="Perfect",D="Diminished", d=" Second",f=" Fourth",a=" Sixth",C=" Octave"; String[] o = new String[] {D+d,m+d,M+d,A+d,P+f,A+f,D+a,m+a,M+a,A+a,D+C,P+C}; i *= s=='w' ? 2 : 1; return o[i-1]; }; ``` ]
[Question] [ URLs are getting too long. So, you must implement an algorithm to shorten a URL. ## i. The Structure of a URL A URL has 2 main parts: a **domain** and a **path**. A domain is the part of the URL before the first slash. You may assume that the URL does not include a protocol. The path is everything else. ## ii. The Domain The domain of a URL will be something like: `xkcd.com` `meta.codegolf.stackexcchhannnge.cooom`. Each part is period-seperated, e.g. in `blag.xkcd.com`, the parts are "blag", "xkcd", and "com". This is what you will do with it: * If it contains more than two parts, put the last two aside and concatenate the first letter of the rest of the parts. * Then, concatenate that to the first letter to the second-to-last part. * Add a period and the second and third letter of the second-to-last part. * Discard the last part. ## iii. The Path The path will be like: `/questions/2140/` `/1407/`. As before, "parts" are seperated by slashes. For each part in the path, do: * Add a slash * If it is completely made of base-ten digits, interpret it as a number and convert to a base-36 integer. * Otherwise, add the first letter of the part. At the end, add a slash. ## iv. Misc. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. * The path can be empty, but the URL will always end with a slash. * There will not be a protocol (e.g. `http://`, `file:///`) * There will never be less than two parts in the domain. * Standard loopholes apply. ## Examples In: `xkcd.com/72/` Out: `x.kc/20/` In: `math.stackexchange.com/a/2231/` Out: `ms.ta/a/1pz/` In: `hello.org/somecoolcodeintrepreteriijjkk?code=3g3fzsdg32,g2/` Out: `h.el/s/` [Answer] # JavaScript (ES6), 149 bytes ``` u=>u.split`/`.map((p,i)=>i?/^\d+$/.test(p)?(+p).toString(36):p[0]:(d=p.split`.`).slice(0,-1).map((s,j)=>s[l=j,0]).join``+"."+d[l].slice(1,3)).join`/` ``` ## Explanation I made this independent of [@Neil's solution](https://codegolf.stackexchange.com/a/69849/46855) but it ended up looking *very* similar. ``` u=> u.split`/`.map((p,i)=> // for each part p at index i i? // if this is not the first part /^\d+$/.test(p)? // if p is only digits (+p).toString(36) // return p as a base-36 number :p[0] // else return the first letter : (d=p.split`.`) // d = domain parts .slice(0,-1).map((s,j)=> // for each domain part before the last s[l=j,0] // return the first letter, l = index of last domain part ).join`` +"."+d[l].slice(1,3) // add the 2 letters as the final domain ) .join`/` // output each new part separated by a slash ``` ## Test ``` var solution = u=>u.split`/`.map((p,i)=>i?/^\d+$/.test(p)?(+p).toString(36):p[0]:(d=p.split`.`).slice(0,-1).map((s,j)=>s[l=j,0]).join``+"."+d[l].slice(1,3)).join`/` ``` ``` <input type="text" id="input" value="math.stackexchange.com/a/2231/" /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## Pyth, 93 85 bytes ``` Lsm@+jkUTGdjb36J<zxz\/KP>zhxz\/=cJ\.pss[mhd<J_2hePJ\.<tePJ2\/;=cK\/sm+?-djkUThdysd\/K ``` Hand-compiled to pythonic pseudocode: ``` z = input() # raw, unevaluated G = "abcdefghijklmnopqrstuvwxyz" k = "" T = 10 L def y(b): # define y as base10to36 sm join(map(lambda d: @+jkUTGd (join(range(T),interleave=k)+G)[d], # the join(..)+G makes "0...9a...z" jb36 convert(b,36) # returns a list of digit values in base10 J<zxz\/ J = z[:z.index("\/")] # domain portion KP>zhxz\/ K = z[1+z.index("\/"):][:-1] # path portion =cJ\. J = J.split(".") # splits domain into parts pss[ no_newline_print(join(join[ # 1 join yields a list, the other a string mhd<J_2 map(lambda d:d[0],J[:-2]), hePJ J[:-1][-1][1], \. ".", <tePJ2 J[:-1][-1][1:][:2], \/ "\/" ; ]) =cK\/ K = K.split("\/") sm print(join(map(lambda d: +?-djkUThdysd\/ "\/"+(d[0] if filterOut(d,join(range(T),interleave=k)) else y(int(d))), # the filter will turn pure number into empty string, which is False K K))) ``` Finally, the excruciation ends... [Answer] ## JavaScript ES6, 157 bytes ``` u=>u.split`/`.map((p,i)=>i?/^\d+$/.test(p)?(+p).toString(36):p[0]:p.split`.`.reverse().map((h,i)=>i--?i?h[0]:h[0]+'.'+h[1]+h[2]:'').reverse().join``).join`/` ``` Edit: Saved 4 bytes thanks to Doᴡɴɢᴏᴀᴛ. [Answer] # Python 2, ~~378~~ 365 Bytes **Update** Golfed it down by a bit. The ~150 Bytes for the base36-function are annoying, but I can't get rid of it until python has a builtin for that... ``` def b(n): a=abs(n);r=[]; while a : r.append('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'[a%36]);a//=36 if n<0:r.append('-') return''.join(reversed(r or'0')) u=raw_input();P=u.split("/")[0].split(".") print"".join([p[0] for p in P[0:-2]]+[P[-2][0]]+["."]+list(P[-2])[1:3]+["/"]+[b(int(p))+"/"if p.isdigit()else p[0]+"/" for p in u.split(".")[-1].split("/")[1:-1]]) ``` **Old version** ``` def b(n): a=abs(n) r=[] while a: r.append('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'[a%36]) a//=36 if n<0:r.append('-') return''.join(reversed(r or'0')) u=raw_input() P=u.split("/")[0].split(".") s="" if len(P)>2: for p in P[:-2]:s+=p[0] s+=P[-2][0]+"."+P[0][1:3] P=u.split(".")[-1].split("/")[1:-1] for p in P: s+="/"+(b(int(p)) if p.isdigit() else p[0]) print s+"/" ``` Since Python does not have a builtin way to convert ints to a base36-String, I took the implementation from numpy and golfed it down. Rest is pretty straightforward, I will golf it down more after work. Suggestions always appreciated in the meantime! [Answer] **Pyhton 2, ~~336~~ 329 bytes** **update** fixed and shorter thanks to webwarrior ``` def b(a): r='' while a: r+=chr((range(48,58)+range(65,91))[a%36]) a//=36 return ''.join(reversed(r or '0')) u=raw_input() P=u.split('/')[0].split('.') s='' if len(P)>2: for p in P[:-2]: s+=p[0] s+=P[-2][0]+'.'+P[0][1:3] P=u.split('.')[-1].split('/')[1:] for p in P: s+='/'+(b(int(p)) if p.isdigit() else p[0]) print s+'/' ``` **original** DenkerAffe's version with some mods : correctly handle "foo/bar?baz" scheme, plus, no need for negative case in the base36 conversion function. ``` def b(a): r='' while a: r+=('0123456789ABCDEFGHUKLMNOPQRSTUVWXYZ'[a%36]) a//=36 return ''.join(reversed(r or '0')) u=raw_input() P=u.split('/')[0].split('.') s='' if len(P)>2: for p in P[:-2]: s+=p[0] s+=P[-2][0]+'.'+P[0][1:3] P=u.split('.')[-1].split('/')[1:] for p in P: s+='/'+(b(int(p)) if p.isdigit() else p[0]) print s+'/' ``` ]
[Question] [ One aspect of password strength testing is runs of adjacent letters on the keyboard. In this challenge, a program must be created that returns `true` if a string contains any runs of adjacent letters. ## What counts as a run of adjacent letters? For this simplified version of a password strength tester, a run of adjacent characters is 3 or more letters which are next to each other in a single direction (left, right, above or below) on a QWERTY keyboard. For the purpose of this challenge the layout of the keyboard looks like this: ``` 1234567890 QWERTYUIOP ASDFGHJKL ZXCVBNM ``` In the diagram above `Q` is below `1` but not below `2`, so a string that contains `1qa` or `aq1` anywhere inside it would make the program return `true`, but `2qa` would not. ## Input The password string to check. It will only contain the characters `[0-9a-z]` or `[0-9A-Z]` (your choice). ## Output The program must return a truthy value if the password contains one or more runs of adjacent keys, or falsey if it contains none. ## Examples The following inputs should output true: * `asd` * `ytrewq` * `ju7` * `abc6yhdef` And these inputs should output false: * `abc` * `aaa` * `qewretry` * `zse` * `qwdfbn` * `pas` ## Rules * Answers may be complete programs or functions. * Standard loopholes are disallowed. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score (in bytes) wins! [Answer] # Pyth - ~~66~~ ~~62~~ 60 bytes Pretty straightforward approach. Checks if any of substrings len 3 are in any of the rotations of the keyboard. Will be using base encoding for keyboard. ``` .E}Rjb+J+Kc+jkS9"0 qwertyuiop asdfghjkl zxcvbnm"b.tKN_MJ.:z3 ``` [Test Suite](http://pyth.herokuapp.com/?code=.E%7DRjb%2BJ%2BKc%2BjkS9%220%0Aqwertyuiop%0Aasdfghjkl%0Azxcvbnm%22b.tKN_MJ.%3Az3&input=asd&test_suite=1&test_suite_input=asd%0Aytrewq%0Aju7%0Aabc6yhdef%0Aabc%0Aaaa%0Aqewretry%0Azse%0Aqwdfbn%0Apas&debug=0). [Answer] # [Japt](https://github.com/ETHproductions/Japt), 78 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545) ``` V=1oA ¬+`0\nqØÆyuiop\n?dfghjkl \nzxcvbnm`;1+¡Y©(((VbX -VbUgY-1)-5 a -5 %A a)bB ``` Outputs `0` for falsey cases; otherwise, a positive integer. The `?` should be replaced with the unprintable Unicode char U+0086, or if you don't want to go to all that trouble, just `as`. ### How it works ``` V=1oA q +"0\nqwertyuiop\nasdfghjkl \nzxcvbnm";1+Um@Y&&(((VbX -VbUgY-1)-5 a -5 %A a)bB // Implicit: U = input string V=1oA q // Set variable V to the digits 1-9, plus +"..."; // this string. Um@ // Take U and map each character X and its index Y with this function: Y&& // If Y is 0, return Y; otherwise, VbX - // take the index of X in V, subtract VbUgY-1 // the index of (char at position Y - 1 in U) in V, -5 a -5 // subtract 5, take the absolute value, subtract 5 again, %A a // take modulo by 10, then take the absolute value. // This returns 1 for any pair of characters that is adjacent // within V, horizontally or vertically. bB +1 // Take the index of 11 in the result and add one. // Implicit: output last expression ``` [Answer] ## C#, 227 ``` int h(string k){var q="1234567890,QWERTYUIOP,ASDFGHJKL,ZXCVBNM,1QAZ,2WSX,3EDC,4RFV,5TGB,6YHN,7UJM,8IK,9OL,";int i=0,j=0;for(;i<k.Length-2;i++)if((q+String.Concat(Enumerable.Reverse(q))).Contains(k.Substring(i,3)))j=1;return j;} ``` 0 is falsey, 1 is truthy. Concatenated all keys horizontal and vertical, and reversed, and checks if any of 3 chars of input is contained within. C# is really verbose, gotta dive into other languages :( [Answer] # PHP, 173+1 bytes ``` while(~$argn[$i+2])($p=preg_match)($r=_.join(".{10}",str_split(($t=substr($argn,$i++,3))))."|$t"._,$d=_1234567890_qwertyuiop_asdfghjkl__zxcvbnm)||$p($r,strrev($d))?die(1):0; ``` Run as pipe with `-nR` with lowercase input or [try it online](http://sandbox.onlinephpfunctions.com/code/27fe1d84d61b3c3d0e1690da075118d8be89ab2f). [Answer] ## Clojure, 156 bytes ``` #(some(set(for[R[["1234567890""QWERTYUIOP""ASDFGHJKL.""ZXCVBNM..."]]R[R(apply map list R)]r R p(partition 3 1 r)p((juxt seq reverse)p)]p))(partition 3 1 %)) ``` This was a quite interesting task to implement. ]
[Question] [ First, some definitions. A [Hadamard matrix](https://en.wikipedia.org/wiki/Hadamard_matrix) is a square matrix whose entries are either +1 or −1 and whose rows are mutually orthogonal. The [Hadamard conjecture](https://en.wikipedia.org/wiki/Hadamard_matrix#Hadamard_conjecture) proposes that a Hadamard matrix of order 4k exists for every positive integer k. A [circulant matrix](https://en.wikipedia.org/wiki/Circulant_matrix) is a special kind of matrix where each row vector is rotated one element to the right relative to the preceding row vector. That is the matrix is defined by its first row. It is [known](http://arxiv.org/pdf/1109.0748.pdf) that, except for 4 by 4 matrices, there are **no circulant Hadamard matrices**. A matrix with m rows and n >= m columns is **partial circulant**, if it is the first m rows of some circulant matrix. **The task** For each even integer n starting at 2, output the size of the largest partial circulant matrix with +-1 entries and n columns that has the property that all its rows are mutually orthogonal. **Score** Your score is the highest `n` such that for all `k <= n`, no one else has posted a higher correct answer than you. Clearly if you have all optimum answers then you will get the score for the highest `n` you post. However, even if your answer is not the optimum, you can still get the score if no one else can beat it. **Languages and libraries** You can use any available language and libraries you like. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in Linux if at all possible. **Leading entries** * **64** by Mitch Schwartz in **Python** [Answer] # Python 2 Table up to `n = 64`, verified optimal with brute force up to `n = 32`: ``` 4 4 0001 8 4 00010001 12 6 000001010011 16 8 0000010011101011 20 10 00010001011110011010 24 12 000101001000111110110111 28 14 0001011000010011101011111011 32 14 00001101000111011101101011110010 36 18 001000101001000111110011010110111000 40 20 0010101110001101101111110100011100100100 44 18 00010000011100100011110110110101011101101111 48 24 001011011001010111111001110000100110101000000110 52 26 0011010111000100111011011111001010001110100001001000 56 28 00100111111101010110001100001101100000001010100111001011 60 30 000001101101100011100101011101111110010010111100011010100010 64 32 0001100011110101111111010010011011100111000010101000001011011001 ``` where `0` represents `-1`. If `n` is not divisible by 4 then `m = 1` is optimal. Generated using this code (or small variations of it) but with more trials for higher `n`: ``` from random import * seed(10) trials=10000 def calcm(x,n): m=1 y=x while 1: y=((y&1)<<(n-1))|(y>>1) if bin(x^y).count('1')!=n/2: return m m+=1 def hillclimb(x,n,ns): bestm=calcm(x,n) while 1: cands=[] for pos in ns: xx=x^(1<<pos) m=calcm(xx,n) if m>bestm: bestm=m cands=[xx] elif cands and m==bestm: cands+=[xx] if not cands: break x=choice(cands) return x,bestm def approx(n): if n<10: return brute(n) bestm=1 bestx=0 for trial in xrange(1,trials+1): if not trial&16383: print bestm,bin((1<<n)|bestx)[3:] if not trial&1: x=randint(0,(1<<(n/2-2))-1) x=(x<<(n/2)) | (((1<<(n/2))-1)^x) ns=range(n/2-2) if not trial&7: adj=randint(1,5) x^=((1<<adj)-1)<<randint(0,n/2-adj) else: x=randint(0,(1<<(n-2))-1) ns=range(n-2) x,m=hillclimb(x,n,ns) if m>bestm: bestm=m bestx=x return bestm,bestx def brute(n): bestm=1 bestx=0 for x in xrange(1<<(n-2)): m=calcm(x,n) if m>bestm: bestm=m bestx=x return bestm,bestx for n in xrange(4,101,4): m,x=approx(n) print n,m,bin((1<<n)|x)[3:] ``` The approach is simple randomised search with hill climbing, taking advantage of a pattern noticed for small `n`. The pattern is that for optimal `m`, the second half of the first row often has small edit distance from the (bitwise) negation of the first half. The results for the above code are good for small `n` but start deteriorating not long after brute force becomes unfeasible; I would be happy to see a better approach. Some observations: * When `n` is odd, `m = 1` is optimal because an odd number of ones and negative ones can't add up to zero. (Orthogonal means dot product is zero.) * When `n = 4k + 2`, `m = 1` is optimal because in order for `m >= 2` we need to have exactly `n/2` sign reversals among `{(a1,a2), (a2,a3), ... (a{n-1},an), (an,a1)}`, and an odd number of sign reversals would imply `a1 = -a1`. * The dot product of two rows `i` and `j` in a circulant matrix is determined by `abs(i-j)`. For example, if `row1 . row2 = 0` then `row4 . row5 = 0`. This is because the pairs of elements for the dot product are the same, just rotated. * Consequently, for checking mutual orthogonality, we only need to check successive rows against the first row. * If we represent a row as a binary string with `0` in place of `-1`, we can check orthogonality of two rows by taking bitwise xor and comparing the popcount with `n/2`. * We can fix the first two elements of the first row arbitrarily, because (1) Negating a matrix does not affect whether the dot products equal zero, and (2) We know that there must be at least two adjacent elements with same sign and two adjacent elements with differing sign, so we can rotate to place the desired pair at the beginning. * A solution `(n0, m0)` will automatically give solutions `(k * n0, m0)` for arbitrary `k > 1`, by (repeatedly) concatenating the first row to itself. A consequence is that we can easily obtain `m = 4` for any `n` divisible by 4. It is natural to conjecture that `n/2` is a tight upper bound for `m` when `n > 4`, but I don't know how that would be proven. ]
[Question] [ Capacitors are notorious for being manufactured with high tolerances. This is acceptable in many cases, but some times a capacity with tight tolerances is required. A common strategy to get a capacity with the exact value you need is to use two carefully measured capacitors in parallel such that their capacities add up to something in the range you need. The goal in this challenge is, given a (multi) set of capacities, to pair the capacitors such that the total capacity of each pair is in a given range. You also need to find the best set of pairings, that is, the set of pairings such that as many pairs as possible are found. ## Constraints 1. Input comprises in a format of choice * an unordered list of capacities representing the (multi) set of *capacitors you have* * a pair of capacities representing the lower and upper bound of the *target range* (inclusive) 2. all capacities in the input are positive integers smaller than 230, the unit is pF (not that that matters). 3. In addition to the list of capacities in the input, the set of *capacitors you have* also contains an infinite amount of capacitors with a value of 0 pF. 4. Output comprises in a format of choice a list of pairs of capacities such that the sum of each pair is in the *target range* specified. Neither the order of pairs nor the order of capacities within a pair is specified. 5. No capacity in the output may appear more often than it appears in the set of *capacitors you have*. In other words: The pairs you output must not overlap. 6. There shall be no possible output satisfying conditions 4 and 5 that contains more pairs of capacities than the output your program produces. 7. Your program shall terminate in O(*n*!) time where *n* is the length of the list representing the set of *capacitors you have* 8. Loopholes shall not be abused 9. The *target range* shall not be empty ## Scoring Your score is the length of your solution in octets. If your solution manages to solve this problem in polynomial time O(*n**k*) for some *k*, divide your score by 10. I do not know if this is actually possible. ## Sample input * range 100 to 100, input array `100 100 100`, valid output: ``` 0 100 0 100 0 100 ``` * range 100 to 120, input array `20 80 100`, valid output: ``` 0 100 20 80 ``` the output `20 100` is not valid * range 90 to 100, input array `50 20 40 90 80 30 60 70 40`, valid output: ``` 0 90 20 80 30 70 40 60 40 50 ``` * range 90 to 90, input array `20 30 40 40 50 60 70 80 90`, valid output: ``` 0 90 20 70 30 60 40 50 ``` * range 90 to 110, input array `40 60 50`, valid output: ``` 40 60 ``` [Answer] # Python 2, 11.5 A Python golf for once: ``` (a,b),l=input() l=[0]*len(l)+sorted(l) while l: e=l[0]+l[-1] if a<=e<=b:print l[0],l[-1] l=l[e<=b:len(l)-(a<=e)] ``` I add one 0 pF capacitor for every regular one, there are never any more needed. Then we sort the capacitors and keep pairing the lowest and highest capacitor. If the sum is within the allowable range we print it, if it is above the range we discard the highest, if it's below discard the lowest. Example input / output: ``` [[90,100], [20,30,40,40,50,60,70,80,90]] 0 90 20 80 30 70 40 60 40 50 ``` [Answer] # CJam, 5.6 This is a direct re-implementation of the algorithm in [orlp](https://codegolf.stackexchange.com/users/4162/orlp)'s answer. If you upvote my answer, please make sure that you also upvote [this answer](https://codegolf.stackexchange.com/a/54113/32852). I also suggest that the answer with the original algorithm is accepted, because I very much doubt that I would have figured out how to solve this elegantly in O(n\*log(n)). ``` l~_,0a*+${(\)@_2$+4$~2$\>{;;\;\+}{<{;+}{oSop}?}?_,1>}g;; ``` [Try it online](http://cjam.aditsu.net/#code=l~_%2C0a*%2B%24%7B(%5C)%40_2%24%2B4%24~2%24%5C%3E%7B%3B%3B%5C%3B%5C%2B%7D%7B%3C%7B%3B%2B%7D%7BoSop%7D%3F%7D%3F_%2C1%3E%7Dg%3B%3B&input=%5B90%20100%5D%20%5B50%2020%2040%2090%2080%2030%2060%2070%2040%5D) Sample input: ``` [90 100] [50 20 40 90 80 30 60 70 40] ``` Explanation: ``` l~ Get and interpret input. _, Get length of resistor list. 0a*+ Append the same number of 0 values. $ Sort the list. { Loop until less than 2 entries in list. ( Pop off first value. \) Pop off last value. @_ Pull first value to top, and copy it. 2$ Copy last value to top. + Add first and last value. 4$~ Copy specified range to top, and unwrap the two values. 2$ Copy sum to top. \> Swap and compare for sum to be higher than top of range. { It's higher. ;;\; Some stack cleanup. \+ Put first value back to start of resistor list. } { Not higher, so two cases left: value is in range, or lower. < Compare if sum is lower than bottom of range. { It's lower. ;+ Clean up stack and put last value back to end of resistor list. } { Inside range, time to produce some output. o Output first value. So Output space. p Output second value and newline. }? Ternary operator for comparison with lower limit. }? Ternary operator for comparison with upper limit. _, Get length of remaining resistor list. 1> Check if greater 1. }g End of while loop for processing resistor list. ;; Clean up stack, output was generated on the fly. ``` ]
[Question] [ Inspired by this question [earlier today](https://codereview.stackexchange.com/questions/97309/generate-probabilities-around-a-numpad), I'd like to see interesting ways various programming languages can turn a numpad into probabilities. Commonly, tile-based games will allow you to use a numpad to move in any direction based on where your character currently is. When making an AI for these games, `Math.random() * 8` is not sufficient, so I had to get a little creative to make the movement look and feel somewhat natural. A numpad is defined as such: ``` 7 | 8 | 9 - - - - - 4 | x | 6 - - - - - 1 | 2 | 3 ``` Please note, 5 is an invalid number, as you cannot move onto yourself. All examples will use these probabilities: `[50, 40, 30, 20, 10]` If I wanted to generate probabilities around `8`, it would look like this: ``` 40 | 50 | 40 -- | -- | -- 30 | xx | 30 -- | -- | -- 20 | 10 | 20 ``` The output would be `[20, 10, 20, 30, 30, 40, 50, 40]` (with 5 omitted) or `[20, 10, 20, 30, null, 30, 40, 50, 40]` (with 5 present) If I wanted to generate them around `1`, it would look like this: ``` 30 | 20 | 10 -- | -- | -- 40 | xx | 20 -- | -- | -- 50 | 40 | 30 ``` The output would be `[50, 40, 30, 40, 20, 30, 20, 10]` (with 5 omitted) or `[50, 40, 30, 40, null, 20, 30, 20, 10]` (with 5 present) You may write a full program that takes the input in any usual way (command line, stdin) and prints the output, or you may write a function with a number argument, that prints or returns the output. Your program or function should accept one number - the position to generate around. You should use these probabilities: `[50, 40, 30, 20, 10]` (they do not have to be hardcoded). Shortest code in bytes wins. Standard loopholes are disallowed. Answers posted in the linked thread are disallowed. Trailing or leading spaces are allowed. You may treat position `4` as absent or empty, depending on your preference. I'm not too picky on output format - print it out as comma-separated strings or as an array. (This is my first question, go easy on me!) [Answer] # CJam, 27 bytes ``` 12369874s_$\_r#m<f{#4-z)0S} ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=12369874s_%24%5C_r%23m%3Cf%7B%234-z)0S%7D&input=8). ### Idea If we go through the digits around **5** in counterclockwise fashion, we obtain the string `12369874` or any of its rotations (depending on the starting point). After rotating this string so that the input digit **n** is at the leftmost position, the digits in the rotated string have the following probabilities: ``` 50 40 30 20 10 20 30 40 ``` If we consider the indexes of these digits, which are ``` 0 1 2 3 4 5 6 7 ``` subtract **4** from each to yield ``` -4 -3 -2 -1 0 1 2 3 ``` and take absolute values to get ``` 4 3 2 1 0 1 2 3 ``` we only have to add **1** and append a **0** to get the desired probabilities. ### Code ``` 12369874s e# Push "12369874". _$ e# Push a sorted copy, i.e., "12346789". \ e# Swap it with the unsorted original. _r# e# Find the index of the input in an unsorted copy. m< e# Rotate the unsorted original that many units left. f{ } e# For each character C in "12346789": e# Push the rotated string. # e# Find the index of C. 4- e# Subtract 4. z e# Compute the absolute value. ) e# Add 1. 0S e# Push a 0 and a space. ``` [Answer] # Prolog, 166 bytes ``` a(A,R):-I:J:K:L:M=50:40:30:20:10,B is abs(5-A),member(B:S,[4:[I,J,K,J,L,K,L,M],3:[J,I,J,K,K,L,M,L],2:[K,J,I,L,J,M,L,K],1:[J,K,L,I,M,J,K,L]]),(A/5>1,reverse(S,R);S=R). ``` This uses the fact that the result for 9 is the reverse of the result for 1, same for 2 and 8, 3 and 7 and 4 and 6. There are recognizable patterns to go from the result of 1 to the results of 2,3 and 4 but I'm pretty sure it would be longer to code this than hardcoding the sequences for 1 to 4, which is what I did. Example: `a(7,R).` outputs `R = [30, 20, 10, 40, 20, 50, 40, 30]`. [Answer] # Python - 115 ``` a=[50,40,30,20,10,20,30,40] b=[0,1,2,7,8,3,6,5,4] def v(n): c=8-b[n-1] return[(a[c:]+a[:c])[e]for e in b if e-8] ``` `a` is an array with the values in order around the numpad (counter-clockwise from 1), and `b` maps numbers on the numpad to positions around it. Based on the number of spaces around the numpad for the input number (determined using `b`), it makes an array with that many elements moved from the front of `a` to the end, then uses `b` again to rearrange the elements to correspond with numpad numbers. [Answer] # Pyth - 38 bytes Uses kinda the same technique as the Python answer except with base compression for the two arrays. ``` J_jC"3ê"T*RTm@.<jC"<àR"[[email protected]](/cdn-cgi/l/email-protection) ``` [Try it here online](http://pyth.herokuapp.com/?code=J_jC%22%1B3%C3%AA%C2%8A%22T*RTm%40.%3CjC%22%03%3C%C3%A0R%22T-8%40JtQd.DJ4&input=8&debug=0). [Answer] # Java, 190 ``` void g(int n){int i[]={8,0,1,2,7,8,3,6,5,4};String v="54321234",s="";n=i[n];if(n>0)v=v.substring(8-n)+v.substring(0,8-n);for(n=0;n++<9;s=", ")if(n!=5)System.out.print(s+v.charAt(i[n])+"0");} ``` `String v` holds the probabilities (divided by 10) in countrclockwise order with input = 1 being the default 50. `int[]i` translates the input into an index into v. For example, `v.charAt(i[1])` is `5`. Inputs 0 and 5 are invalid so both i[0] and i[5] have a placeholder value of 8 which is the index for '\0' at the end of v. I rotate the numbers in v to the right by the value i[n], and then print the probabilities as comma separated strings. ]
[Question] [ See [Hole #1](https://codegolf.stackexchange.com/questions/39748/9-holes-of-code-golf-kickoff) if you are confused. What does every kid do after he/she collects buckets of candy over Halloween? Sort it by type and size, of course1! ## The Challenge Given a dumped-out bag of candy of varying shapes and sizes, sort the candy from left to right based on: * First: The amount of candy (so 5 of one will be more left than 4 of another) * Second (if there are any ties after the first): If the amount is the same, the candy with more **internal area** (based on number of characters) will rank higher. If after the second sort there is still a tie, then you may choose either to be first. ## Input You will be given the candy through stdin; strewn about. See examples below. ## Output Output the candy ordered in the correct order. Note, candy should *always* be placed in *very* neat columns to appease your OCD fish2. The candy of the same type should be placed directly under one another. See examples below. ## What do you mean by "interior area"? * The interior area of a piece of candy is measured by the total characters making up the candy as a whole. * Any whitespace within a "border" is considered part of the area of the candy. * A border is any connected loop of characters, each character diagonal or next to it's neighbor. For example, ``` +--------+ | | | | | | | | +--------+ ``` has more area than ``` XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX ``` even though is has less characters overall. ## Examples input: ``` _ \| |/ _ _ lllllll -*------------*- -\ /- lllllll lllllll lllllllll | /\ /\ / | +|\ooooo/|+ lllllllll lllllllll llll+llll | / \/ \/ | ||o o|| llll+llll llll+llll lllllllll -*------------*- ||o o|| lllllllll lllllllll lllllll /| |\ +|/ooooo\|+ lllllll lllllll | -/ \- | | | _ | | -\ /- | lllllll | | +|\ooooo/|+ | lllllllll | | ||o o|| | llll+llll | | ||o o|| + lllllllll rrr--rrr + + +|/ooooo\|+ lllllll rr||rr -/ \- | | || | | | || | | | || | | | || | | \| |/ | || | + -*------------*- | || | | /\ /\ / | | || | -\ /- | / \/ \/ | | || | +|\ooooo/|+ -*------------*- rr||rr ||o o|| /| |\ rrr--rrr ||o o|| +|/ooooo\|+ -/ \- ``` Would become ``` _ \| |/ -\ /- rrr--rrr lllllll -*------------*- +|\ooooo/|+ rr||rr lllllllll | /\ /\ / | ||o o|| | || | llll+llll | / \/ \/ | ||o o|| | || | lllllllll -*------------*- +|/ooooo\|+ | || | lllllll /| |\ -/ \- | || | | | || | | \| |/ -\ /- | || | | -*------------*- +|\ooooo/|+ | || | | | /\ /\ / | ||o o|| | || | | | / \/ \/ | ||o o|| rr||rr + -*------------*- +|/ooooo\|+ rrr--rrr /| |\ -/ \- _ lllllll \| |/ -\ /- lllllllll -*------------*- +|\ooooo/|+ llll+llll | /\ /\ / | ||o o|| lllllllll | / \/ \/ | ||o o|| lllllll -*------------*- +|/ooooo\|+ | /| |\ -/ \- | | | | + _ lllllll lllllllll llll+llll lllllllll lllllll | | | | | + _ lllllll lllllllll llll+llll lllllllll lllllll | | | | | + ``` A second example: ``` qq \/ qq qq qq +-----+ qq qq qq + | jjjjjjjj qq qq | | jjjjjj \/ qq qq | | jjjj +-----+ <---notice that the left side is not connected qq +-------+ jj jj + | <--> <--> j j | | jj <> jj | | <--> qq jjjjjjjj jj jj +-------+ qq jjjjjj jjjj qq qq jjjj qq qq jj jj j j +---------------------------------------------------------+ jj <> jj ooooo +---------------------------------------------------------+ jj jj o yyyyyy jjjj o ww - notice diagonal border, allowed o ww jjjjjjjj o yyyyyy ooooo ooooo jjjjjj ooooo o yyyyyy o yyyyyy jjjj o ww o ww jj jj o ww o ww j j o yyyyyy o yyyyyy jj <> jj ooooo ooooo jj jj jjjj ``` Solution: ``` qq ooooo jjjjjjjj <--> \/ +---------------------------------------------------------+ qq o yyyyyy jjjjjj +-----+ +---------------------------------------------------------+ o ww jjjj <--> + | qq o ww jj jj | | qq o yyyyyy j j <--> | | ooooo jj <> jj +-------+ qq jj jj qq ooooo jjjj \/ o yyyyyy +-----+ qq o ww jjjjjjjj + | qq o ww jjjjjj | | o yyyyyy jjjj | | qq ooooo jj jj +-------+ qq j j ooooo jj <> jj qq o yyyyyy jj jj qq o ww jjjj o ww qq o yyyyyy jjjjjjjj qq ooooo jjjjjj jjjj qq jj jj qq j j jj <> jj qq jj jj qq jjjj ``` Note that columns have 1 character of spacing between them, and are aligned horizontally at the top. Also note that each candy is in an exact columns, each candy with 1 character of spacing in between. ## Scoring This is code-golf, so shortest program (in bytes) wins. 1 What else would you do? Obviously you want to display your awesome might and power in the amount of candy you collected, right? 2 I know what you're thinking! A fish has to look through a *curved* bowl at your candy, so therefore it would be distorted anyway! Well, my fish lived (before it died) in a *rectangular* aquarium. [Answer] # Ruby, 928 characters Whew, this one was fun! ``` w=[];b=' ';u=$<.read.split' ';k=->l,z,t,p{loop{y=!!1;z.each{|c|t.each{|o|v=[c[0]+o[0],c[1]+o[1]] y=!(z+=[v])if v[0]>=0&&v[1]>=0&&v[0]<l.size&&v[1]<l[0].size&&p[l[v[0]][v[1]]]&&!z.index(v)}} break if y};z};(y=y;z=k[u,[[u.index{|p|y=p.index /\S/},y]],([-1,0,1].product([-1,0,1])-[0,0]),->x{x!=b}] n=z.min_by{|c|c[0]}[0];m=z.min_by{|c|c[1]}[1];q=Array.new(z.max_by{|c|c[0]}[0]-n+1){b*(z.max_by{|c|c[1]}[1]-m+1)} z.each{|c|q[c[0]-n][c[1]-m]=u[c[0]][c[1]];u[c[0]][c[1]]=b};w+=[q])while u*''=~/\S/;o=Hash.new 0;w.each{|c|o[c]+=1} p=->q{e=k[q,((0...q.size).flat_map{|x|[[x,0],[x,q[0].size-1]]}+(1...q[0].size-1).flat_map{|y|[[0,y],[q.size-1,y]]}).select{|c|q[c[0]][c[1]]==b},[[0,1],[0,-1],[1,0],[-1,0]],->x{x==b}] (q.size*q[0].size)-e.size};r=o.sort_by{|k,v|v+(p[k]/1e3)}.reverse.map{|k,v|(k+[b*k[0].size])*v} r.map!{|k|k+([b*k[0].size]*(r.max_by(&:size).size-k.size))};puts ([b]*r.max_by(&:size).size).zip(*r).map{|r|r.join(b)[2..-1]} ``` You can give the input on STDIN, or you can pass an input file as an argument (like `ruby organize.rb candy.txt`) and it will treat the file as STDIN automatically. All semicolons can be replaced with newlines; I just glued some lines together to reduce vertical space. Ungolfed (2367 chars): ``` #!/usr/bin/ruby input = $<.read.split("\n") candies = [] # utility method flood = -> arr, coords, offsets, cond { loop { changed = false coords.each{|c| offsets.each{|o| nc = [c[0]+o[0], c[1]+o[1]] if nc[0] >= 0 && nc[1] >= 0 && nc[0] < arr.length && nc[1] < arr[0].length && cond[arr[nc[0]][nc[1]]] && !coords.index(nc) coords.push nc changed = true end } } break if !changed } coords } # while there are non-whitespace characters in the pile while input.join =~ /\S/ # get coordinates of the first character to flood-fill on y = nil x = input.index{|row| y = row.index /\S/ } # flood-fill on that character coords = flood[input, [[x, y]], ([-1,0,1].product([-1,0,1]) - [0, 0]), ->x{x != ' '}] # x = max, n = min xx = coords.max_by{|c| c[0] }[0] nx = coords.min_by{|c| c[0] }[0] xy = coords.max_by{|c| c[1] }[1] ny = coords.min_by{|c| c[1] }[1] # create a properly sized thingy for this one candy candy = Array.new(xx - nx + 1) { ' ' * (xy - ny + 1) } # fill the thingy, while also removing it from the pile coords.each{|c| candy[c[0] - nx][c[1] - ny] = input[c[0]][c[1]] input[c[0]][c[1]] = ' ' } candies.push candy end # group by same candies candytypes = Hash.new 0 candies.each{|c| candytypes[c] += 1 } area = -> candy { # we want to eliminate surrounding spaces # so flood-fill all spaces that touch the edges surround = (0...candy.length).flat_map{|x| [[x, 0], [x, candy[0].length-1]] } + (1...candy[0].length-1).flat_map{|y| [[0, y], [candy.length-1, y]] } surround.select! {|c| candy[c[0]][c[1]] == ' ' } surround = flood[candy, surround, [[0,1],[0,-1],[1,0],[-1,0]], ->x{x == ' '}] # now just subtract amount of surrounding spaces from total amount of chars (candy.length * candy[0].length) - surround.length } columns = candytypes.sort_by {|k, v| # this is a pretty ugly hack v + (area[k] / 1000.0) }.reverse.map{|k, v| (k + [' ' * k[0].length]) * v } columns.map!{|k| k + ([' ' * k[0].length] * (columns.max_by(&:length).length - k.length)) } puts ([' '] * columns.max_by(&:length).length).zip(*columns).map{|r| r.join(' ')[2..-1] } ``` ]
[Question] [ You know those wooden toys with little ball bearings where the object is to move around the maze? This is kinda like that. Given a maze and a series of moves, determine where the ball ends up. The board is held vertically, and the ball moves only by gravity when the board is rotated. Each "move" is a rotation (in radians). The maze is simply concentric circular walls, with each wall having exactly one opening into the outer corridor, similar to this (assume those walls are circles and not pointed): ![labyrinth](https://i.stack.imgur.com/x1RAU.png) As you can see, the ball starts in the middle and is trying to get out. The ball *will* instantly fall through as soon as the correct orientation is achieved, even if it's midway through a rotation. A single rotation may cause the ball to fall through multiple openings. For instance, a rotation `>= n * 2 * pi` is enough to escape any maze. For the purposes of the game, a ball located within `0.001` radians of the opening is considered a "fit", and will drop through to the next corridor. **Input:** Input is in two parts: * The maze is given by an integer `n` representing how many walls/openings are in the maze. This is followed by `n` lines, with one number on each, representing where the passage to the next corridor is. * The moves are given as an integer `m` representing how many moves were taken, followed (again on separate lines) by `m` clockwise rotations *of the board* in radians (negative is anticlockwise). All passage positions are given as `0 rad = up`, with positive radians going clockwise. For the sample image above, the input may look like this: ``` 7 // 7 openings 0 0.785398163 3.14159265 1.74532925 4.71238898 4.01425728 0 3 // 3 moves -3.92699082 3.14159265 0.81245687 ``` **Output:** Output the corridor number that the ball ends in. Corridors are zero-indexed, starting from the center, so you start in `0`. If you pass through one opening, you're in corridor `1`. If you escape the entire maze, output any integer `>= n` For the sample input, there are three moves. The first will cause the ball to fall through **two** openings. The second doesn't find an opening, and the third finds **one**. The ball is now in corridor `3`, so expected output is: ``` 3 ``` Behavior is undefined for invalid input. Valid input is well-formed, with `n >= 1` and `m >= 0`. Scoring is standard code golf, lowest number of bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/14215) are forbidden. Input must not be hard-coded, but can be taken from standard input, arguments, console, etc. Output can be to console, file, whatever, just make it output somewhere visible. [Answer] ## JavaScript 200 ``` function f(i){with(Math)for(m=i.split('\n'),o=m.slice(1,t=+m[0]+1),m=m.slice(t+1),c=PI,p=2*c,r=0,s=1e-3;m.length;c%=p)abs(c-o[r])<s?r++:abs(t=m[0])<s?m.shift(c+=t):(b=t<0?-s:s,c+=p-b,m[0]-=b);return r} ``` **EDIT** : Here is an **animated** example proving that this solver works : <http://jsfiddle.net/F74AP/4/> [![animated](https://i.stack.imgur.com/T8rX0.gif)](http://jsfiddle.net/F74AP/4/) The function must be called passing the input string. Here is the call of the example given by the OP : ``` f("7\n0\n0.785398163\n3.14159265\n1.74532925\n4.71238898\n4.01425728\n0\n3\n-3.92699082\n3.14159265\n0.81245687"); ``` It returns `3` as intended. [Answer] ## Perl, ~~211~~ 191 With newlines and indentation for readability: ``` $p=atan2 0,-1; @n=map~~<>,1..<>; <>; while(<>){ $_=atan2(sin,cos)for@n; $y=abs($n[$-]+$_)<$p-.001 ?$_ :($_<=>0)*$p-$n[$-]; $_+=$y for@n; $p-.001<abs$n[$-]&&++$-==@n&&last; $_-=$y; .001<abs&&redo } print$- ``` Number of moves in the input is discarded, stdin's eof indicates end of moves. ]
[Question] [ [Marshall Lochbaum's online BQN REPL](https://mlochbaum.github.io/BQN/try.html) has an interesting(and aesthetically pleasing) method of displaying arrays. Your task is to implement a version with simpler rules. ``` [2,[3],4,[[[6,[5],7]]]] ``` becomes: ``` ┌─ · 2 ┌· 4 ┌· · 3 · ┌· ┘ · ┌─ · 6 ┌· 7 · 5 ┘ ┘ ┘ ┘ ┘ ``` ## Rules for drawing * A singleton array has ``` ┌· · ``` as its top left corner. * A non-singleton array has ``` ┌─ · ``` as its top left corner. (In the actual BQN, this is used for rank-0, or "unit" arrays) * All arrays have ``` ┘ ``` as their bottom right corner. * Each element at a certain depth will be displayed at the same depth vertically. For example, 2 and 4 are displayed 1 unit from the top since they are at depth 1. * Each further level of nesting depth moves 1 unit down in depth. * Numbers next to each other will be separated by a single space. ## Other details * You may take a ragged numeric array in any way your language supports. * The input will only consist of integers and nested arrays containing integers. * If your language does not support arrays with depth, you may take a string/other equivalent that your language supports. * If your language's codepage does not contain the characters `┌ · ─ ┘`, you can count them as 1 byte. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in each language wins. * Since bacon strips are thin, your code must be thin and small as well. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 72 bytes ``` FS≡ι(«⊞υⅉP⌈┌´·↘→⊞υⅉ»)«≔⊕⊟υιM¹⁻ιⅉ┘M⁻ⅉ⊟υ↑¿υ⊞υ⌈⟦ι⊟υ⟧»,«↑≔KD⊕ⅈ←ι§≔ι⊖⌕ι┌¦─↘»ι ``` [Try it online!](https://tio.run/##dZG9asMwEMfn@CkOTydQh36DOwVMIdCAaSm0lA7GluOjjmwsKQmUQMcOGTv0Tbr3UfIijmTloxm66e7@97/fnbIybbM6rbquqFvAkWyMftAtyQkyBmpOOisBicF7kKVKQIhhZN@DxKgSDYdnK7sJBmNTaWpsm8ZovfrkEK6/Vr8/YV@rZwKjuJ7Le5qU@pDah8dmy@0k5icNlaKJtGRZK6ZCapFjUjdoGONAe7NTDmOSRiF5m96257Ek3wcOL7IKDnuX6LFxdSrAxrCDGacLmpopvtBO@vqXjns6v4k32JImQrzF1IpMU33M/YT9uDtR6B287xnqkczFwsHH4qC/JZm7nDtm6Frt4@Ofmy6DXBSp/YYI/N7Oftl1eMbxnPELjohXHC8Zv7bXYd3JrNoA "Charcoal – Try It Online") Link is to verbose version of code. Uses lists rather than arrays because they're easier to input. Explanation: ``` FS≡ι ``` Switch over each character of the input as a string. ``` (« ``` For a `(`, ... ``` ⊞υⅉ ``` ... save the vertical position as the top margin, ... ``` P⌈┌´·↘→ ``` ... assume a single-element list, ... ``` ⊞υⅉ ``` ... and save the vertical position again, this time as the bottom margin. ``` »)« ``` For a `)`, ... ``` ≔⊕⊟υι ``` ... get the bottom margin of this list, plus 1, ... ``` M¹⁻ιⅉ ``` ... move to that row, ... ``` ┘ ``` ... close the list, ... ``` M⁻ⅉ⊟υ↑ ``` ... move to and forget the top margin of this list, ... ``` ¿υ⊞υ⌈⟦ι⊟υ⟧ ``` ... and update the bottom margin of the containing list if necessary. ``` »,« ``` For a `,`, ... ``` ↑≔KD⊕ⅈ←ι ``` ... grab the text on the previous row, ... ``` §≔ι⊖⌕ι┌¦─ ``` ... find the `┌` and change the character after it to a `─`, ... ``` ↘ ``` ... and move to the next column on the original row. ``` »ι ``` Otherwise, just output the current character. Note that the `·` is in Charcoal's code page (so because it needs to be quoted it ends up costing me two bytes!) but the box-drawing characters are not. They would normally cost three bytes in Charcoal so as I use them four times I have subtracted 8 bytes from Charcoal's calculation. ]
[Question] [ An [arithmetico-geometric sequence](https://en.wikipedia.org/wiki/Arithmetico-geometric_sequence) is the elementwise product of an arithmetic sequence and a geometric sequence. For example, `1 -4 12 -32` is the product of the arithmetic sequence `1 2 3 4` and the geometric sequence `1 -2 4 -8`. The nth term of an integer arithmetico-geometric sequence can be expressed as $$a\_n = r^n \cdot (a\_0 + nd)$$ for some real number \$d\$, nonzero real \$r\$, and integer \$a\_0\$. Note that \$r\$ and \$d\$ are not necessarily integers. For example, the sequence `2 11 36 100 256 624 1472 3392` has \$a\_0 = 2\$, \$r = 2\$, and \$d = 3.5\$. ### Input An ordered list of \$n \ge 2\$ integers as input in any reasonable format. Since some definitions of geometric sequence allow \$r=0\$ and define \$0^0 = 1\$, whether an input is an arithmetico-geometric sequence will not depend on whether \$r\$ is allowed to be 0. For example, `123 0 0 0 0` will not occur as input. ### Output Whether it is an arithmetico-geometric sequence. Output a truthy/falsy value, or two different consistent values. ### Test cases True: ``` 1 -4 12 -32 0 0 0 -192 0 432 -1296 2916 -5832 10935 -19683 2 11 36 100 256 624 1472 3392 -4374 729 972 567 270 117 48 19 24601 1337 42 0 -2718 -1 -1 0 4 16 2 4 8 16 32 64 2 3 4 5 6 7 0 2 8 24 ``` False: ``` 4 8 15 16 23 42 3 1 4 1 24601 42 1337 0 0 0 1 0 0 1 0 0 1 -1 0 4 16 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~184~~ ~~128~~ 135 bytes ``` {3>$_||->\x,\y,\z{?grep ->\r{min (x,{r&&r*$_+(y/r -x)*($×=r)}...*)Z==$_},x??map (y+*×sqrt(y²-x*z).narrow)/x,1,-1!!y&&z/y/2}(|.[^3])} ``` [Try it online!](https://tio.run/##VVBJbsIwFN1zCleNIjvYSTzEiReBe7S0UapChVSGGlBjAufgHj1COVj6HZAKG@v7TX9YT@2n7hYOhTNUdq0cBdXhwEaThk4cnezb8YedrhEAtl3Mlwg3tLVhaKOgGmKXWMQaEuHgfCotOcZxHJGnsgyqI23G40W9RtgNo/Np82W32P3@sCbak3hZW7v6JklDOWX84cGF4T5xiTjiQ/z8Kl/IsdvUDs1wUBE0W9kB5hQxRREXFKWEokc0bba2vsOZFIQOcAqKXjTAjBvR/5T0PBdGUyQMh5dlhcd4amTmKaML6S0eg0ypPQdOkUGlhW@hciClNH0XpmQOYC4MRcYTmc5BnafeD5UqoDB9otIpJCqfLGXeD/@@e5uvdpt@WCZyXlwHBw34hLrdkPkV@WUNiNC3nOr1PPM4@KRv46Og4Bf5/0X4rfF6pDu0@wM "Perl 6 – Try It Online") Computes \$r\$ and \$d\$ from the first three elements and checks whether the resulting sequence matches the input. Unfortunately, Rakudo throws an exception when dividing by zero, even when using floating-point numbers, costing ~9 bytes. Enumerates the sequence using \$a\_n=r \cdot a\_{n-1}+r^n \cdot d\$. Some improvements are inspired by Arnauld's JavaScript answer. ### Explanation ``` 3>$_|| # Return true if there are less than three elements ->\x,\y,\z{ ... }(|.[^3])} # Bind x,y,z to first three elements # Candidates for r x # If x != 0 ??map (y+*×sqrt(y²-x*z).narrow)/x,1,-1 # then solutions of quadratic equation !!y&&z/y/2 # else solution of linear equation or 0 if y==0 ?grep ->\r{ ... }, # Is there an r for which the following is true? ( , ...*) # Create infinite sequence x # Start with x { } # Compute next term r&& # 0 if r==0 (y/r -x) # d r*$_ # r*a(n-1) ($×=r) # r^n + * # r*a(n-1)+d*r^n Z==$_ # Compare with each element of input min # All elements are equal? ``` [Answer] # JavaScript (ES7), ~~135~~ 127 bytes ``` a=>!([x,y,z]=a,1/z)|!a.some(n=>n)|[y/x+(d=(y*y-x*z)**.5/x),y/x-d,z/y/2].some(r=>a.every((v,n)=>(v-(x+n*y/r-n*x)*r**n)**2<1e-9)) ``` [Try it online!](https://tio.run/##dVFBboMwELz3FznFdtaA18bGUuHYF/QW5YAaUrVKTQUtApS/0w29NKoj32ZnPDO77/VQ9y/d2@eXDO2xWU7lUpfVhu1HmGA@lDWodOaXTZ307UfDQlkFftlP6bhjx5JNYpKjmLkQSZ6OHAiXR5jTKcXDr6ArqzpphqabGBsg8LJig2TjLogp7WQQIxedEIF@wEfVSM/58tKGvj03ybl9Zdvn7rvZ8oe/2IntFUgDCkFqPPB/0wzoRXCpPNLIaBIq9BbQKwsyLwhQmdc5wd4WOiIlggJtiZYB5hYskr9xCFr7WARptDPg0IMnUm4doMvoDwemAOVjDsZmCpTWRImXkuhUEa1Fua@9QNlodAPkaYFaWhMlaKLkYMFFfZHkuApvZtun@txHbrO65VdD1PEqGtQ17N0lGFz3cO@yUeWK37n77X6WHw "JavaScript (Node.js) – Try It Online") ## How? We use two preliminary tests to get rid of some special cases. For the main case, we try three different possible values of \$r\$ (and the corresponding values of \$d\$, which can be easily deduced) and test whether all terms of the input sequence are matching the guessed ones. Because of potential rounding errors, we actually test whether all squared differences are \$<10^{-9}\$. ### Special case #1: less than 3 terms If there are less than 3 terms, it's always possible to find a matching sequence. So we force a truthy value. ### Special case #2: only zeros If all terms are equal to \$0\$, we can use \$a\_0=0\$, \$d=0\$ and any \$r\neq 0\$. So we force a truthy value. ### Main case with \$a\_0=0\$ If \$a\_0=0\$, the sequence can be simplified to: $$a\_n=r^n\times n\times d$$ Which gives: $$a\_1=r\times d\\ a\_2=2r^2\times d$$ We know that \$d\$ is not equal to \$0\$ (otherwise, we'd be in the special case #2). So we have \$a\_1\neq 0\$ and: $$r=\frac{a\_2}{2a\_1}$$ ### Main case with \$a\_0\neq 0\$ We have the following relation between \$a\_{n+1}\$ and \$a\_n\$: $$a\_{n+1}=r.a\_n+r^{n+1}d$$ For \$a\_{n+2}\$, we have: $$\begin{align}a\_{n+2}&=r.a\_{n+1}+r^{n+2}d\\ &=r(r.a\_n+r^{n+1}d)+r^{n+2}d\\ &=r^2a\_n+2r.r^{n+1}d\\ &=r^2a\_n+2r(a\_{n+1}-r.a\_n)\\ &=-r^2a\_n+2r.a\_{n+1} \end{align}$$ We notably have: $$a\_2=-r^2a\_0+2r.a\_1$$ Leading to the following quadratic: $$r^2a\_0-2r.a\_1+a\_2=0$$ Whose roots are: $$r\_0=\frac{a\_1+\sqrt{{a\_1}^2-a\_0a\_2}}{a\_0}\\ r\_1=\frac{a\_1-\sqrt{{a\_1}^2-a\_0a\_2}}{a\_0}$$ [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` {}!=Solve[i=Range@Tr[1^#];(a+i*d)r^i==#,{r,a,d},Reals]& ``` [Try it online!](https://tio.run/##TY9da4MwFIbv8yvOLJR9RPCcxMR0CN7semP2zloIrXZCa4tKGZT@dnd0uxiBkPPk/eCc/PBVnfzQ7PxYp5vxdn9I8/PxWhVN@unbQ5WtuwK3i/L10b80z/unbtuk6ULeOunl/i4/K3/sy@X4XtfZ7Fut@qvvepHvfFsIgI@uaYcCoM7W57fvS1f1fXNus3xgfsgvx2YoFjKAoAQol5IN/38CIRBCDUgQKhIR8BEhOuKHVgyRnAFyaCCMEwYYORUzdiZRgkcEZRhGQLEBQ5ykLYFSjkSoldVgyYFjFBsLZCN2WNAJoBOkTYSASjGYqkOymHA5p0/tgIYLNLDWADcbzaNiEIMBy3riL9JiVsSTiNQUpAAn81@8prnhdzOm8z1vKQIZbNqgLMcf "Wolfram Language (Mathematica) – Try It Online") `Solve` return all solution forms. The result is compared with `{}` to check if there is any solution. ]
[Question] [ Given an integral polynomial of degree strictly greater than one, completely decompose it into a composition of integral polynomials of degree strictly greater than one. ### Details * An *integral polynomial* is a polynomial with only integers as coefficients. * Given two polynomials `p` and `q` the *composition* is defined by `(p∘q)(x):=p(q(x))`. * The [*decomposition*](https://en.wikipedia.org/wiki/Polynomial_decomposition) of an integral polynomial `p` is a finite ordered sequence of integral polynomials `q1,q2,...,qn` where `deg qi > 1` for all `1 ≤ i ≤ n` and `p(x) = q1(q2(...qn(x)...))`, and all `qi` are not further decomposable. The decomposition is not necessarily unique. * You can use e.g. lists of coefficients or built in polynomial types as input and output. * Note that many builtins for this task actually decompose the polynomials over a given *field* and not necessarily integers, while this challenge requires a decomposition integer polynomials. (Some integer polynomials might admit decomposition into integer polynomials as well as decomposition that contain rational polynomials.) ### Examples ``` x^2 + 1 [x^2 + 1] (all polynomials of degree 2 or less are not decomposable) x^6 - 6x^5 + 15x^4 - 20x^3 + 15x^2 - 6 x - 1 [x^3 - 2, x^2 - 2x + 1] x^4 - 8x^3 + 18x^2 - 8x + 2 [x^2 + 1, x^2 - 4x + 1] x^6 + x^2 + 1 [x^3 + x + 1, x^2] x^6 [x^2, x^3] x^8 + 4x^6 + 6x^4 + 4x^2 + 4 = (x^2 + 1)^4 + 3 [x^2 + 3, x^2, x^2 + 1] x^6 + 6x^4 + x^3 + 9x^2 + 3x - 5 [x^2 + x - 5, x^3 + 3*x], [x^2 + 5*x + 1, x^3 + 3*x - 2] ``` Use Maxima for generating examples: [Try it online!](https://tio.run/##y02syMxN/P@/QKNCU8HKVqEizljbSKtC29iaqxAuZKRboW1ozVUEFzBV0AaSJgq6IEltM2uugqLMvBKNgvycypTU5PzcAg0TrUKNIg2QqZqaOkDC@v9/AA "Maxima – Try It Online") Some decomposition algorithms can be found [here](https://www.sciencedirect.com/science/article/pii/S0747717185800122) and [here](https://www.sciencedirect.com/science/article/pii/S0747717189800276). [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 84 bytes ``` f(p)=[if(q'',[f(q),r],p)|r<-x*divisors(p\x),r''&&p==subst(q=substpol(p,r,x),x,r)][1] ``` Based on the algorithm described [here](https://www.sciencedirect.com/science/article/pii/S0747717185800122 "Polynomial decomposition algorithms"). [Try it online!](https://tio.run/##TY3dCoMwDIVfJXihrbYwf3Ew9yJOwTE2CjJjdaODvbtLrcJucnLyJTnYaSUfuCx3hryq1Z2NQSBqEi50I5B/9Uma8Kbeahr0xPBiCASB72NVTa/rNLPRKQ49Q6EFcSM0b@q4WTrE/sMQ5BlQq@dMrWeNBzaOC6hNm0AEsQDTFiChCE2b20FOTUaD5EBNuk8St0J1vbAL5c7LjZOSTdzHCP4DbCnJZaFjxRrivN3K9qMduNfHDadrct7w5Qc "Pari/GP – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes ``` Decompose[#/.x->x+a,x]/.a->0& ``` [Try it online!](https://tio.run/##XY47C4MwFIX3/ooLgkuj9jE4FKWDFboV6RYyRHu1gjGShJJS@tvTOJQ@psv5OOfcI7i5ouCmb7hrM1dgI8UkNdIgiW2U2yUnliUxj/JV6BQfLzXXOMnhriGDM68HpKWSoui73mhaeYMUx9Fgh4o@opRA@iSwZQQsm@9uMXfMeR8/2MmLfSmHCw02kMRgIcohWEPo/QQqvKHyU37eMt9xUv1o/vAXnMFbtx/C3As "Wolfram Language (Mathematica) – Try It Online") I have the example set up here to compose a random polynomial from random quadratics (or less), expand it out, and then try to decompose it. It's necessary to complicate the polynomial with dummy variable (a) since the built-in will not attempt to decompose a monomial. I notice that the answer often has much larger coefficients than in the original composition, but they are indeed always integers. ]
[Question] [ > > This question is based on [what I came up with](https://codegolf.stackexchange.com/a/127426/70347) to answer [another question](https://codegolf.stackexchange.com/q/127397/70347). > > > Sometimes the questions here ask to draw some ASCII art. One simple way to store the data for the art is [RLE (run-length encoding)](https://en.wikipedia.org/wiki/Run-length_encoding). So: ``` qqqwwwwweeerrrrrtttyyyy ``` becomes: ``` 3q5w3e5r3t4y ``` Now to draw a big ASCII art you maybe be getting data like this (ignoring the new line characters): ``` 19,20 3(4)11@1$20 11@19,15"4:20 4)19,4:20 11@ ^^^ Note that this is "20 whitespaces" (Character count: 45) ``` The characters used for the ASCII art are never going to be lowercase or uppercase letters or numbers, only signs, marks and symbols but always in the printable ASCII character set. You want to save some space in that string, so you replace the numbers with the uppercase character set (being 'A' equals to 1, 'B' equals to 2 until 'Z' equals to 26), because you are never going to get more than 26 repetitions of a character. So you get: ``` S,T C(D)K@A$T K@S,O"D:T D)S,D:T K@ (Character count: 34) ``` And finally you notice that some groups of (letter+symbol) are repeating, so you substitute the groups that appear 3 times or more in the string by the lowercase character set, in order or appearance in the string, but storing in a buffer the substitutions made (in the format "group+substitution char" for each substitution), and leaving the rest of the string as is. So the following groups: ``` S, (3 times) T (4 times) K@ (3 times) ``` gets substituted by 'a', 'b' and 'c', respectively, because there are never going to be more than 26 groups repeating. So finally you get: ``` S,aT bK@c abC(D)cA$bcaO"D:bD)aD:bc (Character count: 9+24=33) ``` [The last step only saves 1 byte because the groups that actually save characters after being substituted are the ones appearing 4 times or more.] ### The challenge Given a string containing the RLE data to draw an ASCII art (with the restrictions proposed), write the shortest program/function/method you can in order to compress it as described. The algorithm must print/return two strings: the first one containing the dictionary used for the compression, and the second one being the resulting compressed string. You may return the strings as a Tuple, an array, List or whatever, in the given order. Note that if the string cannot be compressed in the step 2, the algorithm must return an empty string as first return value and the result of the step 1 as second return value. You do not need to include the result of step 1 in the output values, I just include them in the examples for clarification purposes. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest answer for each language win! ### Another test case ``` Input: 15,15/10$15,15/10"10$10"10$10"10$10"15,15/ Output of step 1: O,O/J$O,O/J"J$J"J$J"J$J"O,O/ Final algorithm output: O,aO/bJ$cJ"d abcabdcdcdcdab --- Input: 15,15/10$15,15/10" Output of step 1: O,O/J$O,O/J" Final algorithm output: <empty string> O,O/J$O,O/J" ``` [Answer] ## JavaScript (ES6), ~~168~~ 167 bytes Returns an array of two strings: `[dictionary, compressed_string]`. ``` s=>[(a=(s=s.replace(/\d+/g,n=>C(n|64),C=String.fromCharCode)).match(/../g)).map(v=>s.split(v)[a[v]||3]>=''?D+=v+(a[v]=C(i++)):0,i=97,D='')&&D,a.map(v=>a[v]||v).join``] ``` ### Test cases ``` let f = s=>[(a=(s=s.replace(/\d+/g,n=>C(n|64),C=String.fromCharCode)).match(/../g)).map(v=>s.split(v)[a[v]||3]>=''?D+=v+(a[v]=C(i++)):0,i=97,D='')&&D,a.map(v=>a[v]||v).join``] console.log(f('19,20 3(4)11@1$20 11@19,15"4:20 4)19,4:20 11@')) console.log(f('15,15/10$15,15/10"10$10"10$10"10$10"15,15/')) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~269~~ ~~280~~ ~~268~~ 266 bytes Nothing fancy going on here. Good opportunity to use some simple regular expressions. The first version failed for strings containing special characters that were interpreted within the regex. Second version (using re.escape) works with all the test cases. That correction cost 11 bytes. Second version did not assign substitution characters in order, as required in the problem specification, and as pointed out by @CarlosAlejo. So, back to the drawing board. ## Corrected version, further golfed * -6 bytes saved by not printing output on two lines * +3 bytes: Switching to code substitutions via a string to allow meeting the challenge as specified. * -4 bytes: Since I'm no longer calling re.findall twice, I don't need to rename it * -5 bytes: switching from for loops to while loops. * -2 bytes thanks to @Comrade Sparkle Pony ``` import re S=re.sub b=a=input() for i in re.findall('\d{1,2}',a): b=S(i, chr(64+int(i)),b) n,s,p=96,'',0 while p<len(b): c=b[p:p+2];f=b.count(c) if f>2and not c in s:n+=1;s+=c+chr(n) p+=2 p=0 while p<len(s):k=s[p:p+2];v=s[p+2];b=S(re.escape(k),v,b);p+=3 print s,b ``` [Try it online!](https://tio.run/##VU/RSsQwEHzPVywiJCFLufTOg7ZG/Id7VB@aNKXhahqS9kTEb6@J4INPOzvMzsyGz3VafL3v7j0scYVoyUVFW6VNE6165XzYVsbJuERw4HwWVKPzQz/PjL4OXxLrb4o9bwlodWEOwUyRnU/C@ZU5zlFz4jFhUM0ZKcUD@ZjcbCE8ztYzXe6M0i@hDaJ@60alK7Ns@dRwAm6E8anu/QB@WcGU9NR6oWSXhDKiBPksC0LVJKj/zom3V5X@fG8FFlA65g9sMn2w7Mrxlgt22eFIQsyVIaHedyobrA9wZCcu5bO8z7jMBuXD3anNW@Yb/EWZpz8 "Python 2 – Try It Online") [Answer] # Lua, 215 bytes Just a good bit of pattern matching. I think Lua's underrated when it comes to golfing... look at all those statements squished together! ``` g,c=string.gsub,string.char u=g(arg[1],"%d%d?",function(n)return c(n+64)end)l,d=97,""g(u,"..",function(m)n,e=0,g(m,".", "%%%0")g(u,e,function()n=n+1 end)if n>2 then l,s=l+1,c(l)d,u=d..m..s,g(u,e,s)end end)print(u,d) ``` [Answer] # [Python 2](https://docs.python.org/2/), 186 bytes ``` from re import* S=sub('\d+',lambda m:chr(int(m.group(0))+64),input()) Q=[] for p in findall('[A-Z].',S): if S.count(p)>2:a=chr(len(Q)+97);Q+=[p+a];S=sub(escape(p),a,S) print''.join(Q),S ``` I was hoping to finally find use for `re.subn` :C ``` # first step - convert all numbers to uppercase letters S=sub('\d+',lambda m:chr(int(m.group(0))+64),input()) # empty list to hold encoding of second step Q=[] # find every encoded pair (uppercase letter and some char) for p in findall('[A-Z].',S): # if it occures 3 or move times if S.count(p)>2: # get lowercase letter to substitute with a=chr(len(Q)+97) # store encoding into list Q+=[p+a] # update string - substitute pair with lowercase letter S=sub(escape(p),a,S) # output # encodings of second step, space, result # if nothing was compressed at step 2, space would prepend result (of step 1) print''.join(Q),S ``` [Compressed at step 2](https://tio.run/##JY7LboMwEEX3/opRFcme2EExoa0gImo/AbErYeHwSFzhhxxY9OupaVf3oZmj63/mh7Ppuo7BGQgDaONdmPekLp/LjdFrz6mYlLn1CkzRPQLTdmYmuQe3eHZE5G8ZCm39MjNEUpVNS0YXwIO2MGrbq2litPk8fLUJFTUWBPQIddK5JXI8XtJClRt2GiyrkOfveK542Xiu2vP/huHZKT/EW6EigPgQF1CafDu9fYh6XanMRXqEE8tQyg@5i37TXMjXl6yIKfa5@HOxp78) [Not compressed at step 2](https://tio.run/##NY7LDoIwFAX3/YrGmLTXVhTiI0Iw8RMIO5FF5SE1tL2psPDrEWPcncWcyeB76JyNpqn1zlDfUG3Q@WFF8vQ13jm71YLJXpl7raiJq85zbQdugod3I/ItgDjsQGqL48ABSJYWJWmdp0i1pa22tep7zorL@loGTOYQE6pbmgeVG2cPwjmKVfrV9o3lGYjTEZJMpAUKVSa/huZVKWxmVqpZQNDPBYwFT6e/D5lPEwv3Mtxvwu3yPxbsAw) --- # [Python 2](https://docs.python.org/2/), 246 bytes Whole second step done in repl lambda of re.sub. Just for fun. ``` from re import* Q=[] S=sub('\d+',lambda m:chr(int(m.group(0))+64),input()) S=sub('[A-Z].',lambda m:(lambda m:S.count(m)>2and(m in Q or not Q.append(m))and chr(Q.index(m)+97)or m)(m.group(0)),S) print''.join(Q[i]+chr(i+97)for i in range(len(Q))),S ``` [Try it online!](https://tio.run/##JY7LboMwEEX3/opRFcme2EExoa0gImo/AbErYeHwSFzhhxxY9OupaVf3oZmj63/mh7Ppuo7BGQgDaONdmPekLp/LjdFrz6mYlLn1CkzRPQLTdmYmuQe3eHZE5G8ZCm39MjNEUpVNS0YXwIO2MGrbq2litPk8fLUJFTUWBPQIddK5JXI8XtJClRt2GiyrkOfveK542Xiu2vP/huHZKT/EW6EigPgQF1CafDu9fYh6XanMRXqEE8tQyg@5i37TXMjXl6yIKfa5@HOxp78) [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 81 bytes ``` s/\d+/chr$&+64/ge;$b=a;for$a(/([A-Z].)(?=.*\1.*\1)/g){s/\Q$a/$b/g&&($\.=$a.$b++)} ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPyZFWz85o0hFTdvMRD891VolyTbROi2/SCVRQ18j2lE3KlZPU8PeVk8rxhCENfXTNauBugJVEvVVkvTT1dQ0VGL0bFUS9VSStLU1a///NzTVMTTVNzRQgTGUQGw0Eiz1L7@gJDM/r/i/rq@pnoGhwX/dghwA "Perl 5 – Try It Online") Prints the encoded string on the first line, the triples on the second line [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 133 bytes ``` gsub(/(\d+)(.)/){(64+$1.to_i).chr+$2} c=?`;s='' $_.scan(/(..)(?=.*\1.*\1)/){s+=$&+c.succ!if !s[$&]} puts s.scan(/(..)(.)/){gsub$1,$2} ``` [Try it online!](https://tio.run/##bU3RDoIwDHznK5AssDkcFMEEDcH/EIMyo/IChMKDMfy6cyMxMcaHtte7Xq8fq4dSNxwrGtDiwhkVLGBPuok5ATG0Zc2EvPecRJMls/y0w8zzLFIKlOdGW4RgNM/EsgBTxoo8Iy6XAkcpF/XVXuCBuMfJ6sYBbfz2zUkmmoCv/ysFqR@F9prGDGAPRGMzUx8SJ97qTfOpPyPNW5BoIYCQfIBj8E@fpT@nr7Yb6rZBtere "Ruby – Try It Online") ]
[Question] [ # Introduction For my 5th KOTH, I present to you a challenge based on the well-known game [Battleship](https://github.com/Thrax37/hit-master) with a few twists. You'll only command one ship, whose type you'll be able to select between the 5 "traditionnal" classes, but you'll be able to undertake multiple actions each turn, including moving! This is played as a FFA (Free For All) and your goal will be to be the last ship standing. # Principle The game is turn-based. At the start of the game, you'll have to choose the class of your ship. Then each turn, players will be able to execute several actions depending on their ship. The game takes place on a 2D grid (X, Y) whose side is defined this way : `X = 30 + numberOfPlayer` `Y = 30 + numberOfPlayer` The starting position of each ship is random. Play order is randomized each turn, and you won't know your position in the "queue" nor the number of players. The game lasts for **100 turns** or until there's only one ship left alive. Each time you hit an enemy ship or get hit, you'll earn or lose points. The player with the highest score wins. A bounty will be awarded to the winner (value depending on the number of participants). The controller provides you with input via command arguments, and your program has to output via stdout. # Syntax ***First Turn*** Your program will be called **once** without any argument. You'll have to ouput an integer between 1 and 5 (inclusive) to select your ship : `1` : Destroyer [length: 2, moves/turn: 3, shots/turn: 1, range: 9, mines: 4] *Skill* : Free ship rotations (no cooldown) `2` : Submarine [length: 3, moves/turn: 2, shots/turn: 1, range: 5, mines: 4] *Skill* : Can Plunge/Surface (see outputs). While underwater, you can only use "Movement" actions and can be seen only with a scan. You can't be hit by a shot, but can take damage from mines. `3` : Cruiser [length: 3, moves/turn: 1, shots/turn: 2, range: 9, mines: 2] *Skill* : Can Repair (see outputs) `4` : Battleship [length: 4, moves/turn: 1, shots/turn: 3, range: 7, mines: 1] *Skill* : Can Shield (see outputs) `5` : Carrier [length: 5, moves/turn: 1, shots/turn: 1, range: 7, mines: 3] *Skill* : Shots deal AOE (Area Of Effect) damage to target (1 range splash damage). If the target is hit with the shot, up to 2 cells of **this** ship will also be damaged. ***Turns*** **Input** Each time your program is called, it will receive arguments in this format: `Round;YourPlayerId;X,Y,Direction;Hull;Moves,Shots,Mines,Cooldown;Hits,Sunken,Damage;Underwater,Shield,Scan;Map` Rounds are 1-indexed. **Example input** ``` 1;8;1,12,0;111;1,2,2,0;0,0,0;0,0,0;UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.O.....UUUUUUUUXXXX.O.....UUUUUUUUXXXX.O.....UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU ``` Here, it's the 1st round, you're player 8. Your ship is positioned on (X = 1, Y = 12) and your direction is toward the top (0 = Top, 1 = Right, 2 = Bottom, 3 = Left). Your hull is not damaged (your ship has a length of 3, and each bit is true [1 = OK, 0 = Damaged]). You can move 1 time, shoot 2 times, have 2 mines left and your "skill" is available (cooldown = 0). You didn't hit anything, nor have sunken any ship and you didn't get hit either. You're not underwater, your shields (if any) are not activated and your scan isn't either. More on the map later... **Output** You have to output a String describing what actions you'll execute this turn. The order of the characters in your output String will define the orders of the actions. You can output the same actions multiple times if it doesn't exceed the limits of your ship. If one or multiple actions is invalid, each one will separately be considered as `W`. Here's the list of available actions : `M` : Move 1 cell in the direction you're facing (consume 1 move) `B` : Back 1 cell from the direction you're facing (consume 1 move) `C` : Rotate your ship clockwise (consume 1 move / free for Destroyers) `K` : Rotate your ship counterclockwise (consume 1 move / free for Destroyers) `A` : Ram your ship in the direction you're facing (works only if another ship is occupying the cell in the direction you're facing / doesn't move your ship / consume all moves) `F` : Fire 1 shot to a cell in range (consume 1 shot). Must be followed by the targetted cell in this format ([+-]X[+-])Y / example : `F+2-3`) `N` : Place 1 mine to a cell adjacent to your ship (consume all shots and 1 mine). Must be followed by the targetted cell in this format ([+-]X[+-])Y / example : `N+0+1`) `S` : Activate your scan for the next turn (consume all shots) `R` : Repair the damaged hull the closest to the "head" of your ship (consume all shots, cooldown = 3 turns / Cruiser only) `P` : Plunge/Surface (consume all shots, cooldown = 3 turns, max duration = 5 turns / Submarine only) `D` : Activate your shield preventing the next damage during your next turn (consume all shots, cooldown = 3 / Battleship only) `W` : Wait (does nothing) *Clarification*: "Consume all moves/shots" means you can only use this action if you have not used any of your moves/shots before during this turn. **Example output** `MF+9-8CM` : Moves 1 cell, then fires on the cell whose relative position to the "head" of your ship is (targetX = X + 9, targetY = Y - 8), turns clockwise and finally moves 1 cell again. # Gameplay **The Grid** Here's an example grid (33 x 13) where 3 players are placed : ``` ███████████████████████████████████ █ █ █ 00 █ █ 2 █ █ 2 █ █ 2 █ █ █ █ 11111 █ █ M █ █ █ █ █ █ █ █ █ █ █ ███████████████████████████████████ ``` As we can see, there's also a Mine `M` right next to the player 1. Let's take player 2 to understand positioning and direction : Player 2's position is X = 3, Y = 4, Direction = 3. Since its direction is "Bottom", the rest of his "ship cells" are positioned "over" its "head" (X = 3, Y = 3) & (X = 3, Y = 2) **Player's map** The last argument each players receive is their "own" map. By default a ship detects everything in a **range of 5 cells**, but it can activate a **Scan** to increase this range to **9**. The argument is always 361 (19 x 19) characters long. It represents the square centered around the "head" of your ship, where each character corresponds to an element defined this way : `.` : Empty cell `O` : Your ship `M` : Mines `X` : Wall (cells out of the map) `U` : Unknown (will be revealed by a scan) `A` : Enemy ship undamaged cell `B` : Enemy ship damaged cell `C` : Enemy ship underwater undamaged cell (only seen with a scan) `D` : Enemy ship underwater damaged cell (only seen with a scan) `W` : Wreckage (dead ship) The string is composed of 19 characters of the first line, followed by 19 charcters of the second lines ... until the 19th line. Lets take a look at what player 2 receives with and without a scan (line breaks for better understanding, but not send to players) : ``` XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXX............. XXXXXX.......AA.... XXXXXX...O......... XXXXXX...O......... XXXXXX...O......... XXXXXX............. XXXXXX.......AAAAA. XXXXXX........M.... XXXXXX............. XXXXXX............. XXXXXX............. XXXXXX............. XXXXXX............. XXXXXXXXXXXXXXXXXXX UUUUUUUUUUUUUUUUUUU UUUUUUUUUUUUUUUUUUU UUUUUUUUUUUUUUUUUUU UUUUUUUUUUUUUUUUUUU UUUUXXXXXXXXXXXUUUU UUUUXX.........UUUU UUUUXX.......AAUUUU UUUUXX...O.....UUUU UUUUXX...O.....UUUU UUUUXX...O.....UUUU UUUUXX.........UUUU UUUUXX.......AAUUUU UUUUXX........MUUUU UUUUXX.........UUUU UUUUXX.........UUUU UUUUUUUUUUUUUUUUUUU UUUUUUUUUUUUUUUUUUU UUUUUUUUUUUUUUUUUUU ``` **Mines** The mines are triggered when a ship moves to a cell occupied by a mine or when a shot is fired on the mine. Mines can't be triggered with the action "Ram". Mines deal AOE damage (1 range splash damage) to everyone, even to the person who placed the mine. Mines can trigger "chain" explosions if another mine is in the radius of the explosion. **Rotations** The rotations are central symmetries centered on the ship's "head". Rotations will only trigger a mine if it is placed on the "destination position" (you won't trigger mines in an arc. **Area of effect** 1 range splash damage (for mines and Carrier's shots) is defined by a 3x3 (9 cells) square centered on the initial shot/explosion (x, y). It hits those coordinates : `[x - 1; y - 1],[x - 1; y],[x - 1; y + 1],[x; y - 1],[x; y],[x; y + 1],[x + 1; y - 1],[x + 1; y],[x + 1; y + 1]` # Scoring The scoring is defined by this formula : `Score = Hits + (Sunken x 5) - Damage taken - (Alive ? 0 : 10)` where : `hits` : number of hits on enemy ship, either by Ram, Shot or Mine explosion (1 hit by enemy ship cell damaged, including chain explosions) `sunken` : number of "last hit" on an enemy ship which caused it to sink `damage` : number of hits received (not decreased by Repair, but prevented by Shield) `alive` : checks wether your ship is alive at the end (at least 1 hull cell undamaged) # Controller You can find the controller on [GitHub](https://github.com/Thrax37/hit-master). It also contains two samplebots, written in Java. To make it run, check out the project and open it in your Java IDE. The entry point in the main method of the class Game. Java 8 required. To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the players package (you can take example on the already existing bots). This class must implement Player to override the method String getCmd(). The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : return "C:\Ruby\bin\ruby.exe MyBot.rb";. Finally, add the bot in the players array at the top of the Game class. # Rules * Bots should not be written to beat or support specific other bots. * Writing to files is allowed. Please write to"yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed. * Your submission has 1 second to respond. * Provide commands to compile and run your submissions. * You can write multiple submissions # Supported Languages I'll try and support every language, but it needs to be available online for free. Please provide instructions for installation if you're not using a "mainstream" language. As of right now, I can run : Java 6-7-8, PHP, Ruby, Perl, Python 2-3, Lua, R, node.js, Haskell, Kotlin, C++ 11. [Answer] # RandomBot This is an example bot. It chooses a ship, an action and a target cell (if needed) randomly. ``` import java.util.Random; public class RandomBot { int round; int playerID; public static void main(String[] args) { if (args.length == 0) { Random random = new Random(); int ship = random.nextInt(5); String[] ships = { "1", "2", "3", "4", "5" }; System.out.println(ships[ship]); } else { new RandomBot().play(args[0].split(";")); } } private void play(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); String[] actions = { "M", "B", "C", "K", "F", "S", "N", "A" }; Random random = new Random(); int action = random.nextInt(8); int rangeX = random.nextInt(5); int rangeY = random.nextInt(5); int mineX = random.nextInt(1); int mineY = random.nextInt(1); String signX = random.nextInt(1) == 1 ? "+" : "-"; String signY = random.nextInt(1) == 1 ? "+" : "-"; System.out.println(actions[action] + (action == 4 ? signX + rangeX + signY + rangeY : "") + (action == 6 ? signX + mineX + signY + mineY : "")); } } ``` # PassiveBot This is an example bot. It does nothing. ``` public class PassiveBot { int round; int playerID; public static void main(String[] args) { if (args.length == 0) { System.out.println("5"); } else { new PassiveBot().play(args[0].split(";")); } } private void play(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); System.out.println("W"); } } ``` [Answer] # PeaceMaker, Python 2 (Battleship) PeaceMaker shoots 3 times on the nearest enemies (spiral distance) and moves back and forth in a line while staying at least 2 cells away from mines. ``` from os import sys def reversedSpiralOrder(length): #Initialize our four indexes top = 0 down = length - 1 left = 0 right = length - 1 result = "" while 1: # Print top row for j in range(left, right + 1): result += str(top * length + j) + ";" top += 1 if top > down or left > right: break # Print the rightmost column for i in range(top, down + 1): result += str(i * length + right) + ";" right -= 1 if top > down or left > right: break # Print the bottom row for j in range(right, left + 1, -1): result += str(down * length + j) + ";" down -= 1 if top > down or left > right: break # Print the leftmost column for i in range(down, top + 1, -1): result += str(i * length + left) + ";" left += 1 if top > down or left > right: break result = result.split(";") del result[-1] return result[::-1] def canMove(x, y, direction, hull, map): # M = 1, B = 2 moves = 0 if direction == 0: y1 = -1 y2 = -2 hx1 = hx2 = x1 = x2 = 0 hy1 = -y1 + hull hy2 = -y2 + hull elif direction == 1: x1 = 1 x2 = 2 hy1 = hy2 = y1 = y2 = 0 hx1 = -x1 - hull hx2 = -x2 - hull elif direction == 2: y1 = 1 y2 = 2 hx1 = hx2 = x1 = x2 = 0 hy1 = -y1 - hull hy2 = -y2 - hull elif direction == 3: x1 = -1 x2 = -2 hy1 = hy2 = y1 = y2 = 0 hx1 = -x1 + hull hx2 = -x2 + hull if map[y + y1][x + x1] == "." and map[y + y2][x + x2] != "M": moves += 1 if map[y + hy1][x + hx1] == "." and map[y + hy2][x + hx2] != "M": moves += 2 return moves if len(sys.argv) <= 1: f = open("PeaceMaker.txt","w") f.write("") print "4" else: arguments = sys.argv[1].split(";") sight = 19 round = int(arguments[0]) playerID = int(arguments[1]) x = int(arguments[2].split(",")[0]) y = int(arguments[2].split(",")[1]) direction = int(arguments[2].split(",")[2]) hull = arguments[3] moves = int(arguments[4].split(",")[0]) shots = int(arguments[4].split(",")[1]) mines = int(arguments[4].split(",")[2]) cooldown = int(arguments[4].split(",")[3]) hits = int(arguments[5].split(",")[0]) kills = int(arguments[5].split(",")[0]) taken = int(arguments[5].split(",")[0]) underwater = int(arguments[6].split(",")[0]) shield = int(arguments[6].split(",")[1]) scan = int(arguments[6].split(",")[2]) map = [[list(arguments[7])[j * sight + i] for i in xrange(sight)] for j in xrange(sight)] initialShots = shots priorities = reversedSpiralOrder(sight) actions = "" sighted = 0 for priority in priorities: pX = int(priority) % sight pY = int(priority) / sight if map[pY][pX] == "A": sighted += 1 if shots > 0: shots -= 1 actions += "F" + ("+" if pX - 9 >= 0 else "") + str(pX - 9) + ("+" if pY - 9 >= 0 else "") + str(pY - 9) if shots == initialShots and sighted > 0: actions += "D" elif shots == initialShots and sighted <= 0: actions += "S" else: actions += "" f = open("PeaceMaker.txt","r") fC = f.read(1) lastDirection = int("1" if fC == "" else fC) y = 9 x = 9 if lastDirection == 1: if canMove(x, y, direction, len(hull), map) == 1 or canMove(x, y, direction, len(hull), map) == 3: actions += "M" elif canMove(x, y, direction, len(hull), map) == 2: actions += "B" lastDirection = 0 elif lastDirection == 0: if canMove(x, y, direction, len(hull), map) == 2 or canMove(x, y, direction, len(hull), map) == 3: actions += "B" elif canMove(x, y, direction, len(hull), map) == 1: actions += "M" lastDirection = 1 f = open("PeaceMaker.txt","w") f.write(str(lastDirection)) print actions ``` ]
[Question] [ ## Introduction > > In mathematics, a polygonal number is a number represented as dots or pebbles arranged in the shape of a regular polygon. The dots are thought of as alphas (units). These are one type of 2-dimensional figurate numbers. > > > The number 10, for example, can be arranged as a triangle: > > > > ``` > * > ** > *** > **** > > ``` > > But 10 cannot be arranged as a square. The number 9, on the other hand, can be: > > > > ``` > *** > *** > *** > > ``` > > Some numbers, like 36, can be arranged both as a square and as a triangle: > > > > ``` > ****** * > ****** ** > ****** *** > ****** **** > ****** ***** > ****** ****** > > ``` > > By convention, 1 is the first polygonal number for any number of sides. The rule for enlarging the polygon to the next size is to extend two adjacent arms by one point and to then add the required extra sides between those points. In the following diagrams, each extra layer is shown as in red. > > > Triangular Numbers: > > > [![Triangular Numbers](https://i.stack.imgur.com/ppI5p.gif)](https://i.stack.imgur.com/ppI5p.gif) > > > Square Numbers: > > > [![Square Numbers](https://i.stack.imgur.com/qhd5R.gif)](https://i.stack.imgur.com/qhd5R.gif) > > > Polygons with higher numbers of sides, such as pentagons and hexagons, can also be constructed according to this rule, although the dots will no longer form a perfectly regular lattice like above. > > > Pentagonal Numbers: > > > [![Pentagonal Numbers](https://i.stack.imgur.com/tSqsz.gif)](https://i.stack.imgur.com/tSqsz.gif) > > > Hexagonal Numbers: > > > [![Hexagonal Numbers](https://i.stack.imgur.com/8071C.gif)](https://i.stack.imgur.com/8071C.gif) > > > Source: [Wikipedia](https://en.wikipedia.org/wiki/Polygonal_number) ## Your task Given a positive integer *N* (1 <= *N* <= 1000), print every type of Polygonal Number *N* is starting from Triangular Numbers up to and including Icosagonal (20-gon) Numbers. For example, the number 10 is a triangular number and a decagonal number, so the output should be something like (you can choose your own output format, but it should look somewhat like this): ``` 3 10 ``` ## Test cases ``` 1 -> 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2 -> (None) 3 -> 3 6 -> 3 6 36 -> 3 4 13 ``` For reference, the `n`-th `k`-gonal number is: [![(k-2)(n)(n-1)/2 + n](https://i.stack.imgur.com/YQY5C.png)](https://i.stack.imgur.com/YQY5C.png) Credit: xnor Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins. [Answer] ## Python 3, 68 bytes ``` lambda R:[s+2for s in range(1,19)if(s-2+(4+s*(s-4+8*R))**.5)/2%s==0] ``` For each potential number of sides `s+2`, solves the quadratic formula `R=s*n*(n-1)/2 + n` for `n` to see if the result is a whole number. Compare (73 bytes): ``` lambda R:[s+2for s in range(1,19)if R in[n+s*n*~-n/2for n in range(R+1)]] ``` An alternative approach of solving for `s` gives 62 bytes in Python 3, but fails on `R=1`. ``` lambda R:{(R-n)*2/n/~-n+2for n in range(2,R+1)}&{*range(3,21)} ``` [Answer] ## JavaScript (ES6), 90 bytes ``` n=>[...Array(21).keys(n--)].slice(3).filter(i=>(Math.sqrt(i*i+8*i*n-16*n)+i-4)%(i+i-4)==0) ``` Solves the quadratic equation. 73 bytes on new enough versions of Firefox: ``` n=>[for(i of Array(18).keys())if(((~-i**2+8*n*-~i)**.5+~-i)/2%-~i==0)i+3] ``` [Answer] # ><>, 62 + 3 = 65 bytes ``` &1v v0<;?)+8a:+1~~< 1.292:{<>+n}ao^ >:&:&=?^:&:&)?^:@:@$-{:}++ ``` Expects the input at the top of the stack, so +3 bytes for the `-v` flag. This is my first time programming in ><>, so I may be missing some obvious tricks to shorten the code. ## Explanation: ### Initialization ``` &1v v0< 1 ``` Moves *N* to the register, pushes the counter to the stack (starting at `1`, which corresponds to triangular numbers), and starts the sequence with the values `0` and `1`. ### Main Loop ``` :&:&=?^:&:&)?^:@:@$-{:}++ ``` Compares the top of the stack with the register. If it is equal, go to the print routine. If it is greater, go to the reset routine. Otherwise take the difference between the top two stack items, add the counter, and add to the previous top stack item. This calculates the next polygonal number. ### Print ``` .292:{<>+n}ao^ ^ ``` Prints the counter + 2, followed by a newline, then moves to the reset routine. ### Reset ``` v0<;?)+8a:+1~~< 1 ^ ``` Removes the top two stack items and increments the counter. Ends the program if the counter is greater than 18, otherwise pushes the starting numbers `0` and `1` to the stack and returns to the main loop. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` 18pȷµḢ×’×H+µ€_³¬FT:ȷ+3 ``` [Try it online!](https://tio.run/nexus/jelly#ASoA1f//MThwyLfCteG4osOX4oCZw5dIK8K14oKsX8KzwqxGVDrItysz////MzY "Jelly – TIO Nexus") **Explanation** ``` 18pȷµḢ×’×H+µ€_³¬FT:ȷ+3 18pȷ - All possible (k-2,n) pairs µ µ€ - to each pair compute the corresponding polygonal number: Ḣ - retrieve k-2 ×’ - multiply by n-1 ×H - multiply by half of n + - add n _³ - subtract the input. There will now be 0's at (k-2,n) pairs which produce the input ¬FT - retrieve all indices of 0's. The indices are now (k-2)*1000+n :ȷ - floor division by 1000, returning k-3 +3 - add 3 to get all possible k. ``` [Answer] # Axiom 203 bytes ``` l(x)==(local q,m,a;v:List INT:=[];for i in 3..20 repeat(q:=solve((i-2)*n*(n-1)+2*n-2*x=0,n);if #q>1 then(m:=rhs q.1;a:=rhs q.2;if(m>0 and denom(m)=1)or(a>0 and denom(a)=1)then v:=cons(i,v)));v:=sort v;v) ``` here is less golfed and routine that show numbers ``` l(x)== local q,m,a v:List INT:=[] for i in 3..20 repeat q:=solve((i-2)*n*(n-1)+2*n-2*x=0,n) -- this would find only rational solutions as r/s with r,s INT if #q>1 then -- if exist rational solution and denominator =1=> add to list of result m:=rhs q.1;a:=rhs q.2; if(m>0 and denom(m)=1)or(a>0 and denom(a)=1)then v:=cons(i,v) v:=sort v v (2) -> [[i,l(i)] for i in 1..45] Compiling function l with type PositiveInteger -> List Integer (2) [[1,[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]], [2,[]], [3,[3]], [4,[4]], [5,[5]], [6,[3,6]], [7,[7]], [8,[8]], [9,[4,9]], [10,[3,10]], [11,[11]], [12,[5,12]], [13,[13]], [14,[14]], [15,[3,6,15]], [16,[4,16]], [17,[17]], [18,[7,18]], [19,[19]], [20,[20]], [21,[3,8]], [22,[5]], [23,[]], [24,[9]], [25,[4]], [26,[]], [27,[10]], [28,[3,6]], [29,[]], [30,[11]], [31,[]], [32,[]], [33,[12]], [34,[7]], [35,[5]], [36,[3,4,13]], [37,[]], [38,[]], [39,[14]], [40,[8]], [41,[]], [42,[15]], [43,[]], [44,[]], [45,[3,6,16]]] Type: List List Any ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 67 bytes ``` {for(k=2;++k<21;)for(n=0;++n<=$1;)if((k/2-1)*(n*n-n)+n==$1)print k} ``` [Try it online!](https://tio.run/nexus/awk#@1@dll@kkW1rZK2tnW1jZGitCeLn2RoA@Xk2tipAgcw0DY1sfSNdQ00tjTytPN08Te08W6CMZkFRZl6JQnbt///GZlwA "AWK – TIO Nexus") I tried actually solving the quadratic, but checking each value to see if it works is shorter *(and less error-prone for me)* [Answer] # R, ~~68~~ 66 bytes ``` N=scan();m=expand.grid(k=1:18,1:N);n=m$V;m$k[m$k*n*(n-1)/2+n==N]+2 ``` Reads `N` from stdin. Computes the first `N` k-gonal numbers and gets the `k` where they equal `N`, using xnor's formula; however, saves bytes on parentheses by using `1:18` instead of `3:20` and adding `2` at the end. `expand.grid` by default names the columns `Var1`, `Var2`, ..., if a name is not given. `$` indexes by partial matching, so `m$V` corresponds to `m$Var2,` the second column. old version: ``` N=scan();m=expand.grid(k=3:20,1:N);n=m$V;m$k[(m$k-2)*n*(n-1)/2+n==N] ``` [Try it online!](https://tio.run/nexus/r#@@9nW5ycmKehaZ1rm1pRkJiXopdelJmikW1raGVooWNo5adpnWebqxJmnauSHQ3EWnlaGnm6hpr6Rtp5trZ@sdpG/43N/gMA) [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes Pari/GP has a built-in to test whether a number is a polygonal number. ``` x->[s|s<-[3..20],ispolygonal(x,s)] ``` [Try it online!](https://tio.run/nexus/pari-gp#DcqxCoAgEADQXzmcPDhFay1/RBxaDEFO8RoK@nfrzS/DDvM2Icorm4mrtYtLVKS3@pyNj6pvEkwzt6H5v57AO@cI@ih8aSZQYAIogqwZEecH "Pari/GP – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) I just started writing an effective dupe of this challenge (albeit covering all k>1 not just [1,20]) ...so instead I'll answer it! ``` Ṫð’××H+⁸ 18pÇċ¥Ðf⁸+2 ``` A full program printing a Jelly list representation of the results\* **[Try it online!](https://tio.run/##y0rNyan8///hzlWHNzxqmHl4@uHpHtqPGndwGVoUHG4/0n1o6eEJaUC@ttH///@NzQA "Jelly – Try It Online")** \* No results prints nothing;   a single result prints just that number;   multiple results prints a `[]` enclosed, `,` separated list of the numbers ### How? ``` Ṫð’××H+⁸ - Link 1, ith (x+2)-gonal number: list [x,i] e.g. [3,4] (for 4th Pentagonal) Ṫ - tail & modify (i.e. yield i & make input [x]) 4 ð - new dyadic chain, i.e. left = i, right = [x] ’ - decrement i 3 × - multiply by [x] [9] H - halve [x] [2] × - multiply [18] ⁸ - chain's left argument, i 4 + - add [22] 18pÇċ¥Ðf⁸+2 - Main link: number, n e.g. 36 18p - Cartesian product of range [1,18] with n [[1,1],[1,2],...,[1,36],[2,1],...,[18,1],[18,2],[18,36]] - (all pairs of [(k-2),i] which could result in the ith k-gonal number being n) Ðf - filter keep if this is truthy: ⁸ - chain's left argument, n 36 ¥ - last two links as a dyad: Ç - call the last link as a monad (note this removes the tail of each) ċ - count (this is 1 if the result is [n] and 0 otherwise) - filter keep result: [[1],[2],[11]] +2 - add two [[3],[4],[13]] - implicit print ...due to Jelly representation: [3, 4, 13] ``` ]
[Question] [ Your task is to regulate traffic on a crossroads. There are 4 roads coming from north, east, south and west. The input is a string representing the upcoming traffic on each road. For example, `NNNWS` indicates there is a total of 5 cars: three at the north, one at the west and one at the south. The order of characters has no importance here, `NNNWS` is equivalent to `WNNSN`. You must output the order in which the cars should go, using the priority to the right rule: cars coming from the south must let cars coming from east go first, east gives way to north, north gives way to west and west gives way to south. For example, with the input `NNNWS`, the south car should go first, then the west car, then the 3 north cars. The output should thus be `SWNNN`. There are some indecidable cases, for example `NS` or `NNWSE` : you should then output the string `stuck`. **Test cases** ``` N => N NW => WN NWS => SWN SNW => SWN SSSSS => SSSSS ENNNNES => NNNNEES NS => stuck NNWSE => stuck ``` [Answer] # Perl, 65 bytes Includes +2 for `-lp` Give input on STDIN. Assumes the empty string is not a valid input ``` #!/usr/bin/perl -lp s%.%'+(y/NESW/ESWN/*s/N(.*)W/W$1N/,/N/^/S/)'x4%gere+0or$_=stuck ``` If you don't mind the absence of a newline after `stuck` you can drop the `l` option [Answer] # PHP, 267 Bytes use the new [spaceship operator](http://php.net/manual/en/language.operators.comparison.php) and [usort](http://php.net/manual/en/function.usort.php) -5 Bytes by @IsmaelMiguel ``` <?foreach($f=[E,S,W,N]as$l)$s.=+!($r=strstr)($i=$argv[1],$l);if(in_array($s,[0101,1010,0000]))die(stuck);$x=($p=strpos)($s,"1");$t=$r($j=join($f),$f[$x]).$r($j,$f[$x],1);$a=str_split($i);usort($a,function($x,$y)use($t,$p){return$p($t,$x)<=>$p($t,$y);});echo join($a); ``` ## Breakdown ``` # Extended Version without notices $s=""; foreach($f=["E","S","W","N"] as $l){$s.=+!strstr($i=$argv[1],$l);} #bool concat swap the false true values in string if(in_array($s,["0101","1010","0000"])){die("stuck");} # NS WE NESW -> stuck = end program $x=strpos($s,"1"); # find the first false value for an begin for the sort algorithm $t=strstr($j=join($f),$f[$x]).strstr($j,$f[$x],1); # create the sort pattern #sort algorithm example sort string = NESW-> N is not in the string function c($x,$y){ global $t; return strpos($t,$x)<=>strpos($t,$y); # e.g. comparison E<=>W =-1 , W<=>S=1, W<=>W =0 } $a=str_split($i); # Input in an array usort($a,"c"); #sort array echo join($a);# output array as string ``` [Answer] ## Batch, 216 bytes ``` @echo off set/pt= set/an=2,e=4,s=8,w=16,r=0 :l set/ar^|=%t:~0,1% set t=%t:~1% if not "%t%"=="" goto l set/a"o=449778192>>r&3,l=1053417876>>r&3" if %l%==0 (echo stuck)else set t=NESWNE&call echo %%t:~%o%,%l%%% ``` Simple port of my JavaScript answer. Takes input on STDIN in upper or lower case. [Answer] ## JavaScript (ES6), ~~108~~ ~~107~~ ~~106~~ 104 bytes ``` s=>(r=t=`NESWNE`,s.replace(/./g,c=>r|=2<<t.search(c)),t.substr(449778192>>r&3,1053417876>>r&3)||`stuck`) ``` Accumulates a bitmask of which directions have approaching cars and extracts the appropriate portion of the priority string. ]
[Question] [ # Characters Let’s call these Unicode characters **English IPA consonants**: ``` bdfhjklmnprstvwzðŋɡʃʒθ ``` And let’s call these Unicode characters **English IPA vowels**: ``` aeiouæɑɔəɛɜɪʊʌː ``` (Yes, `ː` is just the long vowel mark, but treat it as a vowel for the purpose of this challenge.) Finally, these are **primary and secondary stress marks**: ``` ˈˌ ``` > > Note that `ɡ` ([U+0261](http://graphemica.com/%C9%A1)) is not a lowercase g, and the primary stress marker `ˈ` ([U+02C8](http://graphemica.com/%CB%88)) is not an apostrophe, and `ː` ([U+02D0](http://graphemica.com/%CB%90)) is not a colon. > > > # Your task Given a word, stack the vowels on top of the consonants they follow, and place the stress markers beneath the consonants they precede. (As the question title hints, such a writing system, where consonant-vowel sequences are packed together as a unit, is called an [abugida](https://en.wikipedia.org/wiki/Abugida).) Given the input `ˈbætəlʃɪp`, produce the output: ``` æə ɪ btlʃp ˈ ``` > > A **word** is guaranteed to be a string of consonants, vowels, and stress marks, as defined above. There will never be consecutive stress marks, and they will always be placed at the start of the word *and/or* before a consonant. > > > # Test cases There may be consecutive vowels. For example, `kənˌɡrætjʊˈleɪʃən` becomes ``` ɪ ə æ ʊeə knɡrtjlʃn ˌ ˈ ``` If a word starts with a vowel, print it on the “baseline” with the consonants: `əˈpiːl` becomes ``` ː i əpl ˈ ``` A test case with an initial, stressed vowel: `ˈælbəˌtrɔs` becomes ``` ə ɔ ælbtrs ˈ ˌ ``` A long word: `ˌsuːpərˌkaləˌfrædʒəˌlɪstɪˌkɛkspiːæləˈdoʊʃəs` becomes ``` æ ː ː ʊ uə aə æ əɪ ɪɛ iəoə sprklfrdʒlstkkspldʃs ˌ ˌ ˌ ˌ ˌ ˈ ``` A nonsense example with an initial diphthong, lots of vowel stacking, and no stress markers: `eɪbaeioubaabaaa` becomes ``` u o i a eaa ɪaaa ebbb ``` # Reference implementation Your program should produce the same output as this Python script: ``` consonants = 'bdfhjklmnprstvwzðŋɡʃʒθ' vowels = 'aeiouæɑɔəɛɜɪʊʌː' stress_marks = 'ˈˌ' def abugidafy(word): tiles = dict() x = y = 0 is_first = True for c in word: if c in stress_marks: tiles[x + 1, 1] = c elif c in consonants or is_first: y = 0 x += 1 tiles[x, y] = c is_first = False elif c in vowels: y -= 1 tiles[x, y] = c is_first = False else: raise ValueError('Not an IPA character: ' + c) xs = [x for (x, y) in tiles.keys()] ys = [y for (x, y) in tiles.keys()] xmin, xmax = min(xs), max(xs) ymin, ymax = min(ys), max(ys) lines = [] for y in range(ymin, ymax + 1): line = [tiles.get((x, y), ' ') for x in range(xmin, xmax + 1)] lines.append(''.join(line)) return '\n'.join(lines) print(abugidafy(input())) ``` [Try it on Ideone.](https://ideone.com/pi1GdB) # Rules * You may write a function or a full program. * If your program has a Unicode character/string type, you can assume inputs and outputs use those. If not, or you read/write from STDIN, use the UTF-8 encoding. * You may produce a string containing newlines, or a list of strings representing rows, or an array of Unicode characters. * Each row of output may contain any amount of trailing spaces. If you produce a string, it may have a single trailing newline. * Your program should produce the correct output for arbitrarily long words with arbitrarily long vowel chains, but may assume that the input word is always valid. * If there are no stress markers, your output may optionally include a final empty row (containing nothing, or spaces). * The shortest answer (in bytes) wins. [Answer] # NARS2000 APL, 138 bytes ``` ⍉⌽⊃E,⍨¨↓∘' '¨∨/¨∊∘M¨E←(1+(W∊M←'ˌˈ')++\W∊'bdfhjklmnprstvwzðŋɡʃʒθ')⊂W←⍞ ``` [Answer] # Python, 222 bytes (202 characters) ``` import re def f(s):y=[w[0]in'ˈˌ'and w or' '+w for w in re.split('([ˈˌ]?[bdfhjklmnprstvwzðŋɡʃʒθ]?[aeiouæɑɔəɛɜɪʊʌː]*)',s)[1::2]];return[[x[i-1:i]or' 'for x in y]for i in range(max(len(w)for w in y),0,-1)] ``` Returns an array of unicode characters with an array for each row (containing single spaces for each space required) Not sure where one can get decent output online yet (and I haven't even got the tools to test it properly here either). I have loaded a version to [**ideone**](http://ideone.com/O2rr7v) that just uses English consonants and vowels with `,` and `.` as stress marks, where I have fudged the test cases to conform. [Answer] ## JavaScript (ES6), 181 bytes ``` f= s=>(a=s.match(/[ˈˌ]?.[aeiouæɑɔəɛɜɪʊʌː]*/g).map(s=>/[ˈˌ]/.test(s)?s:` `+s)).map(s=>(l=s.length)>m&&(t=s,m=l),m=0)&&[...t].map(_=>a.map(s=>s[m]||` `,--m).join``).join` ` ; ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` [Answer] # [Go](https://go.dev), 609 bytes ``` import."strings" type P struct{x,y int} func M(s[]int)(m,n int){for _,e:=range s{if e<=m{m=e};if e>=n{n=e}};return} func f(s string)(L string){T,x,y,F,R:=make(map[P]rune),0,0,1>0,ContainsRune for _,r:=range s{if R("ˈˌ",r){T[P{x+1,1}]=r}else if R("bdfhjklmnprstvwzðŋɡʃʒθ",r)||F{y=0;x++;T[P{x,y}],F=r,1<0}else if R("aeiouæɑɔəɛɜɪʊʌː",r){y--;T[P{x,y}],F=r,1<0}} var u,v[]int for k:=range T{u,v=append(u,k.x),append(v,k.y)} for y,Y:=M(v);y<Y+1;y++{o:=[]string{} for x,X:=M(u);x<X+1;x++{if r,ok:=T[P{x,y}];ok{o=append(o,string(r))}else{o=append(o," ")}} L+=TrimPrefix(Join(o,"")," ")+"\n"} return} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVQ9b-M2GAa6mb-C0CTBjBFvhR3dUiBDcQcYQYY7uEZD2VSqSKIEknKt6jRlCVIN7iGLkQ65As3gqUOHdjY6UAL6A_pr-lJS2sshtAXp_Xqe90u6_-UyefgzpcuQXjIc04CjIE4TobDlx8r6NVP-0Zf_fEE75ciSSgT8UlpI5SnDMwxytlTFhuQ44KpEfsaX-I0t5wsQHTsm3Oidwk8E_pawiSsoByJZBD5mJ25cxC4rp0Z45fKCg1BOBVOZ4D2Wb0vckTr266en4pwAIzklZxM3piGzY5rOZwuRceaQY_iNXx2TrxKuoB55BlrU8Ytn_Ge21dw0lUUEAM5nxWY4JuNy4YqSRZLhzsNb-d9dhVHMUyHV-vsfDr_99aP-WF_XH_7-w0S-f39a5O7xdDMcTlsQkpcLcuoKMj45_hSIsiDJDo_6J32nd_pe_6z39W1dNduWPz86eiG8RGsqcEbWbTvbIsKnEs4L0Ls0TRlf2RkJRxuH9NIapNwpW_-cvJu4b-y1M81P3g3H03w4LJKJO190rSw6rw15a7wyZ7o5eQteUI3pkCAJ8P2X1zQJi-SJMiEdgi0cp63zU5OFLQeyfz10z0UQzwTzg439dRJwY7Oc1j60vuFWifppP23a7-1iKSZVv1u4QIOA4KSfPSpRtxhmV23HWJdUMoknLp4vTFxRwFi9w6PSu6i-1vvUIvgCGr_Deo88BboUNTcXJUGDQWGFesebSn8UEHBV3zY3EYPBXIPWMg6DC9weCAUAfHjE9S3TOxRyCFFXAMYRxk0FLv9j6l1zkwbNNjLMuNkiHEB0GqHOB5sED4-RB36VEvpOtn7YZHiHkbEoISHHDriPqGTWbFO9E00V0siE-pDzqv5gHiO9l0rvwaTvQ2m4AcWksUpgyaCanuLZgWLgoGb7XA1yfQv6DPKhcIEbLOweWqDvMQ70LgElkqkII18AfyRVCJzRqr6GpKs26a4hVd8ZbErpyoDmeu2b4FEKf9qmlSGcQI8wRZhRivQeDIh5ntc2tESD7u3FSzPkbvu7mcPwB2yTMtgSsCxHCch0qTIaGdm3l6PAARV8yUYzWB4V8ZdUHcLn2s_lDvcFrxL1y_vw0N3_BQ) A direct port of the reference implementation. ## Ungolfed Explanation ``` // map of x-y coords to a character type tile map[P]rune func (t tile) Xs() (o []int) { for k := range t { o = append(o, k.x) } return } func (t tile) Ys() (o []int) { for k := range t { o = append(o, k.y) } return } // coordinate pair type P struct{ x, y int } func min[T int](s []T) T { var m T for _, e := range s { if e <= m { m = e } } return m } func max[T int](s []T) T { var m T for _, e := range s { if e >= m { m = e } } return m } func f(s string) string { C, V, S := "bdfhjklmnprstvwzðŋɡʃʒθ", "aeiouæɑɔəɛɜɪʊʌː", "ˈˌ" // constant strs tiles := make(tile) // the actual map x, y := 0, 0 // (x0,y0) is the leftmost center isFirst := true // is this character the first of a line? for _, r := range s { // for each char... if strings.ContainsRune(S, r) { // if it's stress... tiles[P{x + 1, 1}] = r // put it underneath the next syllable } else if strings.ContainsRune(C, r) || isFirst { // if it's a consonant or the first letter... y = 0 x++ tiles[P{x, y}] = r // place on the baseline isFirst = false } else if strings.ContainsRune(V, r) { // if's a vowel... y-- tiles[P{x, y}] = r // place 1 above the baseline at the current x isFirst = false } } // get the ranges for outputting into a string xs, ys := tiles.Xs(), tiles.Ys() xmin, xmax := min(xs), max(xs) ymin, ymax := min(ys), max(ys) lines := []string{} for y := ymin; y < ymax+1; y++ { // for each vowel at height y... line := func() (o []string) { for x := xmin; x < xmax+1; x++ { // for each syllable on that vowel height... if r, ok := tiles[P{x, y}]; ok { // get the char o = append(o, string(r)) } else { o = append(o, " ") // use a space if there is no vowel there } } return }() lines = append(lines, strings.TrimPrefix(strings.Join(line, ""), " ")) // add to the output } return strings.Join(lines, "\n") // return the string } ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pVa9b9tGFAc6VfdXPHApCdOyvRVN3A4BOrSL0RhBC9doTtRRZkTxiLujQ0XR5MVwNbhBFsEdkgL1oKlDh-5GB4pA9_bP6F_Q9-5IWXaT5qOCLd3He-_3e193d_HTQL7488ucR0M-EDDiScZYMsqlMuCzjhePjIc_2qgkG2iP4XggU54NulINtsotUeZbkcxwHzUNCgQ_Fybe_PivD__e2kJzOcgYys0xRFKqvgYjgUN0xBWPjFDMjHMBJkkJOT_YO1RFJhiLiywC39iNAL7WfgC-hINDRAhgwjqxVDCET3ZBIRHUp7WOhF3geS6yvi9DGHbLgHWmrKOEKVTGpreMfvN-Rse3jDJ00nqWZNwIyHnS-LQHGJIiMhMoQxgDgsC0cWyUZAf7tHLoa8TfD2CfsI65ghHsOyLfhSCuuWjLJYlx7e4uCtGsM0JqAgfTNUYwah0d8fL9QT59M4hDidG4K42g-SW1eyE8COE-mfZ6_fjo0TAdZbnS5vjxk6tffv--erk8WT774zcvBI-LRBZXl9UP1fNqXl1UP1aL5dlyVp_TZn1azzywIcYK4xhDBNGsQynUZH7Eh8J3CX3rD5ozRwKw_gqeUtmxjk0RmtsOYfvtDV3b88vtcLwdQKKt6VTEZiS1gUhkVOSdRH-eoPsEgUUh3tm-tYtfq76xMLG1ie3FIU0y8dkqqepGUt8Bh_QFj44sULfbdfXQ9H73nswMNrn-CnvUv48wwX8ZJ9oxJOYjWyFCa2fP5e5gb1LCBuyEsDM9xBJTb-aWFwatQZH1hcoEN0c2BpkosSjGacp7qa1TEKkW8DrW9yzrp0-hzchkDaGly225yYzqTa6HOhUGY9_4MUba2zQoNzZu-IW19FY-tX6lPBIgM4vT41pQLslgS3EXYo4-vdm5B69NiXXOenYsH4u09WBz8_8T3wHek8fiBnvgxs6jQinsAChf4w6dKayDpgbCKdia1bYMZWEw44ZOFDzE6NJwPmOzaiRqu98y79L1EDZjOtVRAk_YEEo8Au0ZkWR-qVEE5zRgnbHdH6_tj9t9HCAlcsIiHBw61MnUNZc9JUj9Dg7vWhMbOzje2LgV9_VmsjGnmByJZHBkYOzibyOF5uggbe-i9iy1Zy8ZsAxLC1giYNkAlivAdaC2D1w1IaBDdrBN0qmhVQhyuArgKvV3aHUCa_mgY8Aq3boHHU1fBYHdbepy8ipRD7zgZlwKFMVs5lQ9SAZxlKATLpMNX7viDLP2q7lwcUYJbhK0wrHTcNUV-yoZ7SkRJ6XfLn0hMcskhoy8wNEKiA3v9-lNQt66klu_6P6ljSDet5lnNRsZ0mxKc9o8fT741T1rhDbNK4Bik2DUV5LtUwCb17fpjrB3mpIjvckEL7_e1aWp5unypFrkeB0-xGtyDtWC9Qyu5aw-fTgNMRgTb1jNs3pWvVSo8Gh5Vp-mAq_RE1z1SKDz0AUfVdEAXF3C8kxUczbMUMU8QmMZA6hnKHJts5rXp3lSn6eEDPU5gwS185Q5GSCCV5dpD-VmRlXPtZUDYvgcGO3QVV2fOsONxkwX9XlezVU9G_KUVGPk3F8-o2FaLbSpFrhVXQw1YaMVotGX-CRAbxqIGx90Bj-sPr-5jPPlGa4XyIfjP4rh82KBIaguAJJqLnGR6VwN01ghfqrNEDHT_vIESc8saReQWRMZIFecGxjcnn239DjHP25pFQwkxgg4w2bkrFrgBhO9Xs8GdLq6nKPry9nlnNoGX9Eisu-DqCtx3jxO6HTwo25CJY8P8e4eFo9Js1ctOQu3V2_Pnd1XSE3b4n3xwv3-Aw) ]
[Question] [ Tonight, my fiancée took me out to dinner to celebrate my birthday. While we were out, I heard *Happy Birthday* sung to 5 different guests (including myself), in a restaurant full of 50 people. This got me wondering - the original birthday problem (finding the probability that 2 people in a room of `N` people share the same birthday) is very simple and straightforward. But what about calculating the probability that at least `k` people out of `N` people share the same birthday? In case you're wondering, the probability of at least 5 people out of 50 total people sharing the same birthday is about 1/10000. ## The Challenge Given two integers `N` and `k`, where `N >= k > 0`, output the probability that at least `k` people in a group of `N` people share the same birthday. To keep things simple, assume that there are always 365 possible birthdays, and that all days are equally likely. For `k = 2`, this boils down to the original birthday problem, and the probability is `1 - P(365, N)/(365)**N` (where `P(n,k)` is [the number of k-length permutations formed from n elements](https://en.wikipedia.org/wiki/Permutation#k-permutations_of_n)). For larger values of `k`, [this Wolfram MathWorld article](http://mathworld.wolfram.com/BirthdayProblem.html) may prove useful. ## Rules * Output must be deterministic, and as accurate as possible for your chosen language. This means no Monte Carlo estimation or Poisson approximation. * `N` and `k` will be no larger than the largest representable integer in your chosen language. If your chosen language has no hard maximum on integers (aside from memory constraints), then `N` and `k` may be arbitrarily large. * Accuracy errors stemming from floating-point inaccuracies may be ignored - your solution should assume perfectly-accurate, infinite-precision floats. ## Test Cases Format: `k, N -> exact fraction (float approximation)` ``` 2, 4 -> 795341/48627125 (0.016355912466550306) 2, 10 -> 2689423743942044098153/22996713557917153515625 (0.11694817771107766) 2, 23 -> 38093904702297390785243708291056390518886454060947061/75091883268515350125426207425223147563269805908203125 (0.5072972343239854) 3, 3 -> 1/133225 (7.5060987051979735e-06) 3, 15 -> 99202120236895898424238531990273/29796146005797507000413918212890625 (0.0033293607910766013) 3, 23 -> 4770369978858741874704938828021312421544898229270601/375459416342576750627131037126115737816349029541015625 (0.01270542106874784) 3, 88 -> 121972658600365952270507870814168157581992420315979376776734831989281511796047744560525362056937843069780281314799508374037334481686749665057776557164805212647907376598926392555810192414444095707428833039241/238663638085694198987526661236008945231785263891283516149752738222327030518604865144748956653519802030443538582564040039437134064787503711547079611163210009542953054552383296282869196147657930850982666015625 (0.5110651106247305) 4, 5 -> 1821/17748900625 (1.0259790386313012e-07) 4, 25 -> 2485259613640935164402771922618780423376797142403469821/10004116148447957520459906484225353834116619892120361328125 (0.0002484237064787077) 5, 50 -> 786993779912104445948839077141385547220875807924661029087862889286553262259306606691973696493529913926889614561937/7306010813549515310358093277059651246342214174497508156711617142094873581852472030624097938198246993124485015869140625 (0.00010771867165219201) 10, 11 -> 801/8393800448639761033203125 (9.542757239717371e-23) 10, 20 -> 7563066516919731020375145315161/4825745614492126958810682272575693836212158203125 (1.5672327389589693e-18) 10, 100 -> 122483733913713880468912433840827432571103991156207938550769934255186675421169322116627610793923974214844245486313555179552213623490113886544747626665059355613885669915058701717890707367972476863138223808168550175885417452745887418265215709/1018100624231385241853189999481940942382873878399046008966742039665259133127558338726075853312698838815389196105495212915667272376736512436519973194623721779480597820765897548554160854805712082157001360774761962446621765820964355953037738800048828125 (1.2030611807765361e-10) 10, 200 -> 46037609834855282194444796809612644889409465037669687935667461523743071657580101605348193810323944369492022110911489191609021322290505098856358912879677731966113966723477854912238177976801306968267513131490721538703324306724303400725590188016199359187262098021797557231190080930654308244474302621083905460764730976861073112110503993354926967673128790398832479866320227003479651999296010679699346931041199162583292649095888379961533947862695990956213767291953359129132526574405705744727693754517/378333041587022747413582050553902956219347236460887942751654696440740074897712544982385679244606727641966213694207954095750881417642309033313110718881314425431789802709136766451022222829015561216923212248085160525409958950556460005591372098706995468877542448525403291516015085653857006548005361106043070914396018461580475651719152455730181412523297836008507156692430467118523245584181582255037664477857149762078637248959905010608686740872875726844702607085395469621591502118462813086807727813720703125 (1.21685406174776e-07) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` 365:Z^!tXM=s>~Ym ``` First input is `N`, second is `k`. [**Try it online!**](http://matl.tryitonline.net/#code=MzY1OlpeIXRYTT1zPn5ZbQ&input=Mgoy) This is an enumeration-based approach, like [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/82538/36398), so input numbers should be kept small due to memory limitations. ``` 365: % Vector [1 2 ... 365] Z^ % Take N implicitly. Cartesian power. Gives a 2D array with each % "combination" on a row ! % Transpose t % Duplicate XM % Mode (most frequent element) of each column = % Test for equality, element-wise with broadcast. For each column, gives % true for elements equal to that column's mode, false for the rest s % Sum of each column. Gives a row vector >~ % Take k implicitly. True for elements equal or greater than k Ym % Mean of each column. Implicitly display ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ĠZL 365ṗÇ€<¬µS÷L ``` Extremely inefficient. [Try it online!](http://jelly.tryitonline.net/#code=xKBaTAozNjXhuZfDh-KCrDzCrMK1U8O3TA&input=&args=Mg+Mg) (but keep **N** below **3**) ### How it works ``` 365ṗÇ€<¬µS÷L Main link. Left argument: N. Right argument: K 365ṗ Cartesian product; generate all lists of length N that consist of elements of [1, ..., 365]. Ç€ Map the helper link over all generated lists. It returns the highest amount of people that share a single birthday. < Compare each result with K. ¬ Negate. µS÷L Take the mean by dividing the sum by the length. ĠZL Helper link. Argument: A (list of integers) Ġ Group the indices have identical values in A. Z Zip; transpose rows with columns. L Take the length of the result, thus counting columns. ``` [Answer] # J, ~~41~~ 36 bytes ``` (+/%#)@(<:365&(#~>./@(#/.~)@#:i.@^)) ``` Straight-forward approach similar to the others. Runs into memory issues at **n > 3**. ## Usage Takes the value of `k` on the LHS and `n` on the RHS. ``` f =: (+/%#)@(<:365&(#~>./@(#/.~)@#:i.@^)) 0 f 0 0 0 f 1 1 1 f 1 1 0 f 2 1 1 f 2 1 2 f 2 0.00273973 0 f 3 1 1 f 3 1 2 f 3 0.00820417 3 f 3 7.5061e_6 ``` On my pc, using an i7-4770k and the timer foreign `6!:2`, computing for **n = 3** requires about 25 seconds. ``` timer =: 6!:2 timer '2 f 3' 24.7893 timer '3 f 3' 24.896 ``` ## Explanation ``` (+/%#)@(<:365&(#~>./@(#/.~)@#:i.@^)) Input: k on LHS, n on RHS 365& The number 365 #~ Create n copies of 365 ^ Calculate 365^n i.@ The range [0, 1, ..., 365^n-1] #: Convert each value in the range to base-n and pad with zeroes to the right so that each has n digits (#/.~)@ Find the size of each set of identical values >./@ Find the max size of each <: Test each if greater than or equal to k (+/%#)@ Apply to the previous result +/ Find the sum of the values # Count the number of values % Divide the sum by the count and return ``` ]
[Question] [ We don't have a single challenge about drawing a real 3 dimensional cube, so here it goes: # Challenge Your task is to draw a rotated, cube with perspective. It can be in a separate window or as an image. # Input Your input is 3 separate numbers between 0 and 359.99... These represent the rotation around the x, y and z axis in degrees. ``` 0 0 0 30 0 40 95 320 12 ``` # Output You can either display it in a separate window or save an image. You can use any type of display (vector based, rasterized, etc.). Edit: ASCII is allowed too, to allow golfing languages with only textual output. The output for rasterized or ASCII graphics must be at least 50\*50 (pixels for rasterization, characters for ASCII) # Additional information The positive z axis points out from the window, the x axis is horizontal, and the y axis is vertical. Basically the OpenGL standard. Rotations are counter-clockwise if you look at the cube in the negative direction of a specific axis, e.g looking down for the y axis. The camera should be on the z axis at a reasonable distance from the cube in the negative z direction, the cube should be at (0;0;0). The. cube also needs to be fully visible, and take up at least 50% of the drawing frame. The camera should look in the positive z direction at the cube. The rotations of the cube get applied in the x->y->z order. The cube is rotated around it's center, it doesn't move. To project a cube in 2d space, you need to divide the x and y coordinates of the cube with the distance parallel to the z-axis between the point and the camera. # Rules Rendering libraries are allowed, but the vertices need to be defined in the code. No 3d cube model class. # Test cases [![enter image description here](https://i.stack.imgur.com/bEOH3.png)](https://i.stack.imgur.com/bEOH3.png) [Answer] ## HTML/CSS/JS, 739 bytes, probably non-competing But I just wanted to show off CSS 3D transforms. ``` w=_=>o.style.transform=`rotateZ(${z.value}deg) rotateY(${y.value}deg) rotateX(${-x.value}deg)` ``` ``` input { width: 5em; } #c{width:90px;height:90px;margin:90px;position:relative;perspective:180px}#o{position:absolute;width:90px;height:90px;transform-style:preserve-3d;transform-origin:45px 45px 0px;}#o *{position:absolute;width:90px;height:90px;border:2px solid black}#f{transform:translateZ(45px)}#b{transform:rotateX(180deg)translateZ(45px)}#r{transform:rotateY(90deg)translateZ(45px)}#l{transform:rotateY(-90deg)translateZ(45px)}#u{transform:rotateX(90deg)translateZ(45px)}#d{transform:rotateX(-90deg)translateZ(45px)} ``` ``` <div oninput=w()> X:<input id="x" type="number" value="0" min="0" max="360"> Y:<input id="y" type="number" value="0" min="0" max="360"> Z:<input id="z" type="number" value="0" min="0" max="360"> </div> <!-- Above code for ease of use of snippet. Golfed version: <div oninput=w()><input id=x><input id=y><input id=z></div> --> <div id=c><div id=o><div id=f></div><div id=b></div><div id=r></div><div id=l></div><div id=u></div><div id=d> ``` [Answer] # [Shoes](http://shoesrb.com/) (Ruby) ~~235~~ 231 Everything computed from scratch. ``` Shoes.app{p,a,b,c=ARGV.map{|j|j.to_f/90} k=1+i="i".to_c p=(0..3).map{|j|y,z=(k*i**(j+a)).rect x,z=(((-1)**j+z*i)*i**b).rect q=(x+y*i)*i**c [90*(k+q/(z-4)),90*(k+q/(4+z))]} 4.upto(15){|j|line *(p[j%4][0].rect+p[(j+j/4)%4][1].rect)}} ``` Call from commandline eg `shoes cube3d.rb 0 30 0` The idea is to simultaneously generate / rotate the four vertices of a tetrahedron in 3d. Then, as these are reduced to 2d, we generate the four vertices of the inverse tetrahedron (the total 8 vertices being those of the cube.) This gives 4 pairs of vertices corresponding to the 4 body diagonals. Finally the 2d vertices are connected by lines: each vertex of the original tetrahedron must be connected to each vertex of the inverse tetrahedron forming the 12 edges and 4 body diagonals of the cube. The ordering ensures the body diagonals are not plotted. **Test cases output** Note that, to be consistent with the last two test cases, rotation about the z axis is clockwise from the POV of the viewer. This seems to be in contradiction with the spec however. Rotation direction can be reversed by modifying `*i**c` -> `/i**c` [![enter image description here](https://i.stack.imgur.com/TK4ZJ.png)](https://i.stack.imgur.com/TK4ZJ.png) **ungolfed** ``` Shoes.app{ p,a,b,c=ARGV.map{|j|j.to_f/90} #Throw away first argument (script name) and translate next three to fractions of a right angle. k=1+i="i".to_c #set up constants i=sqrt(-1) and k=1+i p=(0..3).map{|j| #build an array p of 4 elements (each element wil be a 2-element array containing the ends of a body diagonal in complex number format) y,z=(k*i**(j+a)).rect #generate 4 sides of square: 1+i,i-1,-1-i,-i+1, rotate about x axis by a, and store in y and z as reals x,z=(((-1)**j+z*i)*i**b).rect #generate x axis displacements 1,-1,1,-1, rotate x and z about y axis by b, store in x and z as reals q=(x+y*i)*i**c #rotate x and y about z axis, store result in q as complex number [90*(k+q/(z-4)),90*(k+q/(4+z))]} #generate "far" vertex q/(4+z) and "near" vertex q/-(4-z) opposite ends of body diagonal in 2d format. 4.upto(15){|j| #iterate through 12 edges, use rect and + to convert the two complex numbers into a 4 element array for line method line *(p[j%4][0].rect+ #cycle through 4 vertices of the "normal" tetrahedron p[(j+j/4)%4][1].rect) #draw to three vertices of the "inverted" tetrahedron. j/4=1,2,3, never 0 } #so the three edges are drawn but the body diagonal is not. } ``` Note that for historical reasons a scale factor of 90 is applied in line 9 (chosen to be the same as 90 degrees in line 2 for golfing) but in the end there was no golfing advantage in using this particular value, so it has become an arbitrary choice. [Answer] # Maple, ~~130+14~~ (in progress) ``` with(plots):f:=(X,Y,Z)->plot3d(0,x=0..1,y=0..1,style=contour,tickmarks=[0,0,0],labels=["","",""],axes=boxed,orientation=[Z,-X,Y]); ``` [![enter image description here](https://i.stack.imgur.com/TL0Tt.png)](https://i.stack.imgur.com/TL0Tt.png) This plots a constant function inside a box, then uses plot options to hide ticks, labels and the function itself. Adding `projection=.5` to the options brings the camera closer, enabling perspective view. I wrote this before the specs were finalized and the rotation order is `x, y', z''` instead of `x, y, z`. Until I fix the angles, here is another solution # POV-Ray, 182 ``` #include"a.txt" #include"shapes.inc" camera{location 9*z look_at 0} light_source{9*z color 1} object{Wire_Box(<-2,-2,-2>,<2,2,2>,.01,0)texture{pigment{color rgb 1}}rotate<R.x,-R.y,-R.z>} ``` reads input through the `a.txt` file which should contain `#declare R=<xx,yy,zz>;` with `xx,yy,zz` being the rotation angles [![enter image description here](https://i.stack.imgur.com/sGx3V.jpg)](https://i.stack.imgur.com/sGx3V.jpg) ]
[Question] [ ## Description Write a function `f(m, G)` that accepts as its arguments a mapping `m`, and a set/list of distinct, non-negative integers `G`. `m` should map pairs of integers in `G` to new integers in `G`. (`G`, `m`) is guaranteed to form a finite [abelian group](https://en.wikipedia.org/wiki/Abelian_group), but any element of `G` may be the identity. There is an important theorem that says: > > [[Each finite abelian group] is isomorphic to a direct product of cyclic groups of prime power order.](http://groupprops.subwiki.org/wiki/Finite_abelian_group#Definition) > > > `f` must return a list of prime powers `[p1, ... pn]` in ascending order such that ![G is isomorphic to Z_p1 times ... times Z_pn](https://i.stack.imgur.com/VTlHs.png) ## Examples * `f((a, b) → (a+b) mod 4, [0, 1, 2, 3])` should return `[4]`, as the parameters describe the group **Z4**. * `f((a, b) → a xor b, [0, 1, 2, 3])` should return `[2, 2]`, as the parameters describe a group isomorphic to **Z2 × Z2**. * `f((a, b) → a, [9])` should return `[]`, as the parameters describe the trivial group; i.e., the product of zero cyclic groups. * Define `m` as follows: ``` (a, b) → (a mod 3 + b mod 3) mod 3 + ((floor(a / 3) + floor(b / 3)) mod 3) * 3 + ((floor(a / 9) + floor(b / 9)) mod 9) * 9 ``` Then `f(m, [0, 1, ..., 80])` should return `[3, 3, 9]`, as this group is isomorphic to **Z3 × Z3 × Z9** ## Rules * `m` may either be a function (or function pointer to some function) `Int × Int → Int`, or a dictionary mapping pairs in `G × G` to new elements of `G`. * `f` may take its parameters in the opposite order, i.e. you may also implement `f(G, m)`. * Your implementation should *theoretically* work for arbitrarily large inputs, but need not actually be efficient. * There is no limitation on using built-ins of any kind. * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins. ## Leaderboard For your score to appear on the board, it should be in this format: ``` # Language, Bytes ``` ``` var QUESTION_ID=67252,OVERRIDE_USER=3852;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Matlab, 326 bytes With some group theory the idea is quite simple: Here the TL;DR Calculate all possible orders of elements of the group. Then find the biggest subgroup of a certain prime power order and "factorize" it out of the group, rinse, repeat. ``` function r=c(h,l) %factorize group order N=numel(L); f=factor(N); P=unique(f); %prime factors for k=1:numel(P); E(k)=sum(f==P(k)); %exponents of unique factors end; %calculate the order O of each element O=L*0-1; l=L; for k=2:N+1; l=h(l,L); O(l==L & O<0)=k-1 end; %% O=unique(O); % (optional, just for speedupt) R=[]; % for each prime,find the highest power that % divides any of the orders of the element, and % each time substract that from the remaining % exponent in the prime factorization of the % group order for p=1:nnz(P); % loop over primes while E(p)>1; % loop over remaining exponent for e=E(p):-1:1; % find the highest exponent B=mod(O,P(p)^e)==0; if any(B) R=[R,P(p)^e]; % if found, add to list O(B)=O(B)/(P(p)^e); E(p)=E(p)-e; break; end; end; end; if E(p)==1; R=[R,P(p)]; end; end; r=sort(R) ``` Example inputs: ``` L = 0:3; h=@(a,b)mod(a+b,4); h=@(a,b)bitxor(a,b); L = 0:80; h=@(a,b)mod(mod(a,3)+mod(b,3),3)+mod(floor(a/3)+floor(b/3),3)*3+ mod(floor(a/9)+floor(b/9),9)*9; ``` Golfed version: ``` function r=c(h,l);N=numel(L);f=factor(N);P=unique(f);for k=1:numel(P);E(k)=sum(f==P(k));end;O=L*0-1;l=L;for k=2:N+1;l=h(l,L);O(l==L&O<0)=k-1;end;R=[];for p=1:nnz(P);while E(p)>1;for e=E(p):-1:1;B=mod(O,P(p)^e)==0; if any(B);R=[R,P(p)^e]; O(B)=O(B)/(P(p)^e);E(p)=E(p)-e;break;end;end;end;if E(p)==1;R=[R,P(p)];end;end;r=sort(R) ``` [Answer] ## [GAP](http://gap-system.org), ~~159~~ 111 bytes GAP allows us to simply construct a group by a multiplication table and compute its abelian invariants: ``` ai:= # the golfed version states the function w/o assigning it function(m,G) local t; t:=List(G,a->List(G,b->Position(G,m(a,b)))); # t is inlined in the golfed version return AbelianInvariants(GroupByMultiplicationTable(t)); end; ``` # The old version The finitely presented group with generators G and relations a\*b=m(a,b) (for all a, b from G) is the group (G,m) we started with. We can create it and compute its abelian invariants with GAP: ``` ai:= # the golfed version states the function w/o assigning it function(m,G) local F,n,rels; n:=Size(G); F:=FreeGroup(n); rels:=Union(Set([1..n],i-> Set([1..n],j-> F.(i)*F.(j)/F.(Position(G,m(G[i],G[j]))) ) )); # rels is inlined in the golfed version return AbelianInvariants(F/rels); end; ``` # Examples ``` m1:=function(a,b) return (a+b) mod 4; end; # I don't feel like implementing xor m3:=function(a,b) return 9; end; m4:=function(a,b) return (a+b) mod 3 # no need for inner mod + ((QuoInt(a,3)+QuoInt(b,3)) mod 3) * 3 + ((QuoInt(a,9)+QuoInt(b,9)) mod 9) * 9; end; ``` Now we can do: ``` gap> ai(m1,[0..3]); [ 4 ] ``` Actually, we are not restricted to using lists of integers. Using the correct domain, we can just use the general plus: ``` ai(\+,List(Integers mod 4)); [ 4 ] ``` So I can essentially do the second example using that its group is isomorphic to the additive group of the 2 dimensional vector space over the field with 2 elements: ``` gap> ai(\+,List(GF(2)^2)); [ 2, 2 ] ``` And the remaining examples: ``` gap> ai(m3,[9]); [ ] gap> ai(m4,[0..80]); [ 3, 3, 9 ] ``` # Additional remarks In the old version, m did not need to define a group composition for G. If m(a,b)=m(a,c), that just says that b=c. So we could do `ai(m1,[0..5])` and `ai(m3,[5..15])`. The new version will fail horrible in these cases, as will both versions if m returns values that are not in G. If (G,m) is not abelian, we get a description of the abelianized version of it, that is its biggest abelian factor group: ``` gap> ai(\*,List(SymmetricGroup(4))); [ 2 ] ``` This is what `AbelianInvariants` is usually used for, we would normally just call `AbelianInvariants(SymmetricGroup(4))`. # The golfed version ``` function(m,G)return AbelianInvariants(GroupByMultiplicationTable(List(G,a->List(G,b->Position(G,m(a,b))))));end ``` ]
[Question] [ The popular webcomic [Homestuck](http://www.mspaintadventures.com) makes use of a programming language called `~ATH` to destroy universes. While this code golf challenge is **not** to write a program to annihilate our existence, we will be destroying some more tame (albeit less interesting) entities: *variables*.  `~ATH` (pronounced "til death," notice how `~ath` is "tilde ath") works by creating a variable called `THIS`, executing a command with `EXECUTE`, and finishing the program with `THIS.DIE()`. A wiki page for the language's use in Homestuck can be found [here](http://mspaintadventures.wikia.com/wiki/~ATH). The goal of this challenge will be to create a `~ATH` interpreter. For the sake of the challenge, I'm going to create some details of `~ATH` that don't really exist but make it (somewhat) useful. * The language will only work with integers, which are declared with `import <variable name>;`. The variable will automatically be set to a value of 0. Only one variable at a time can be imported. * A variable `x` can be copied by writing `bifurcate x[y,z];`, which will delete the variable `x` and replace it with identical variables `y` and `z`. Note that it cannot create a variable with the same name as the one deleted. Essentially, a variable is renamed, then a copy of the variable with a different name is created. This seems like a stupid feature, but stupidity is [very](http://www.mspaintadventures.com/?s=6&p=003552) deeply [ingrained](http://www.mspaintadventures.com/?s=6&p=005289) in Homestuck. * The syntax for writing a program that executes code on `x` is `~ATH(x){EXECUTE(<code>)}`. If you want to execute code on two variables simultaneously, the code becomes nested, like this: `~ATH(x){~ATH(y){EXECUTE(<code>)}}`. All commands in `<code>` will be executed on both `x` and `y`. * Now let's move onto commands. `+` increments relevant variable(s) by 1 and `-` decrements them by 1. And... that's it. * The final feature of `~ATH` is that it kills whatever it works with. Variables are printed in the format `<name>=<value>` (followed by a newline) at the command `[<name>].DIE();`. Afterwards, the program prints the word `DIE <name>` and a newline a number of times equal to the absolute value of the value of the variable. When variables are killed simultaneously with `[<name1>,<name2>].DIE();` (you can have as many variables killed as you want, so long as they exist), the `DIE()` command is executed on the variables sequentially. **Example programs** Program 1: ``` import sollux; //calls variable "sollux" import eridan; //calls variable "eridan" ~ATH(sollux){EXECUTE(--)} //sets the value of "sollux" to -2 ~ATH(eridan){EXECUTE(+++++)} //sets the value of "eridan" to 5 [sollux].DIE(); //kills "sollux", prints "DIE sollux" twice ~ATH(eridan){EXECUTE(+)} //sets the value of "eridan" to 6 [eridan].DIE(); //kills "eridan", prints "DIE eridan" 6 times ``` Output: ``` sollux=-2 DIE sollux DIE sollux eridan=6 DIE eridan DIE eridan DIE eridan DIE eridan DIE eridan DIE eridan ``` Program 2: ``` import THIS; //calls variable "THIS" ~ATH(THIS){EXECUTE(++++)} //sets the value of "THIS" to 4 bifurcate THIS[THIS1,THIS2]; //deletes "THIS", creates variables "THIS1" and "THIS2" both equal to 4 ~ATH(THIS1){EXECUTE(++)} //sets the value of "THIS1" to 6 [THIS1,THIS2].DIE(); //kills "THIS1" and "THIS2", prints "DIE THIS1" 6 times then "DIE THIS2" 4 times import THAT; //calls variable "THAT" bifurcate THAT[THESE,THOSE]; //deletes "THAT", creates variables "THESE" and "THOSE" ~ATH(THESE){~ATH(THOSE){EXECUTE(+++)}EXECUTE(++)} //sets the value of "THESE" and "THOSE" to 3, then sets the value of "THESE" to 5 [THESE,THOSE].DIE(); //kills "THESE" and "THOSE", prints "DIE THESE" 5 times then "DIE THOSE" 3 times ``` Output: ``` THIS1=6 DIE THIS1 DIE THIS1 DIE THIS1 DIE THIS1 DIE THIS1 DIE THIS1 THIS2=4 DIE THIS2 DIE THIS2 DIE THIS2 DIE THIS2 THESE=5 DIE THESE DIE THESE DIE THESE DIE THESE DIE THESE THOSE=3 DIE THOSE DIE THOSE DIE THOSE ``` --- This is code golf, so standard rules apply. Shortest code in bytes wins. [Answer] # Python 2.7.6, ~~1244~~ ~~1308~~ ~~1265~~ ~~1253~~ ~~1073~~ ~~1072~~ ~~1071~~ ~~1065~~ ~~1064~~ 1063 bytes Alright, I'm not breaking any records here but this is about the smallest Python will go insofar as reading input all at once from a file rather than sequentially over time. I'll try to one-up this later in a different language (and an interpreter, not just a parser). Until then, enjoy the disgustingly horrid monstrosity. *Note*: opens a file called `t` in the working directory. To make it open a command line argument, add `import sys` to the top of the file and change `'t'` to `sys.argv[1]` ``` n=s='\n';m=',';X='[';Y=']';c=';';A='~ATH';D='import';b,g,k=[],[],[];r=range;l=len;f=open('t','r').read().split(n) def d(j,u): p=[] for e in j: if e!=u:p.append(e) return''.join(p) for h in r(l(f)):f[h]=f[h].split('//')[0].split() while[]in f:f.remove([]) for h in r(l(f)): i=f[h] if i[0]==D and l(i)==2and i[1][l(i[1])-1]==c and d(i[1],c)not in b:g.append(0);b.append(d(i[1],c)) elif i[0].startswith(A): i=i[0].split('){') for e in r(l(i)): if i[e].startswith(A): i[e]=i[e].split('(') if i[0][1]in b:g[b.index(i[0][1])]+=(i[1].count('+')-i[1].count('-')) elif i[0].startswith('bifurcate')and l(i)==2and i[1][l(i[1])-1]==c: i=i[1].split(X) if i[0] in b: z=d(d(i[1],c),Y).split(m) for e in r(l(z)):g.append(g[b.index(i[0])]);b.append(z[e]) g.remove(g[b.index(i[0])]);b.remove(i[0]) elif i[0].startswith(X)and i[0].endswith('.DIE();')and l(i)==1: z=d(i[0],X).split(Y)[0].split(m) for e in r(l(z)): k.append((z[e],g[b.index(z[e])])) for e in r(l(k)):k0=k[e][0];k1=k[e][1];s+=k0+'='+str(k1)+n+('DIE '+k0+n)*abs(k1) print s ``` [Answer] ## Python 2, ~~447~~ ~~475~~ ~~463~~ 443 bytes ``` exec("eNp1UUtrAjEQvu+vCEshiYnrxl7KbqOUVmjvCoUkxUdiG7BRkpW2iP3tTVwrReppMsx8r4l936x9A8JXoN5kmu/2WeCxK0KjrSu8mWmEs0Ad96YI27lDPu/1is7wKqcQ0kBLenM+ty0nilu4zqnPtYCSQcXL2P2LmNvl1i9mjWlBUhwKbRt14uhHjlSvjzVy1tqswO/7AjsSpKtwIpGvt2zALqyNnkf3k/FIolb2ACjlpe2jR6lk8fAUQbKNulx7YIF1IDkqwmZlGwQpxNXGW9cASyCHZKqFVVOCoJQOEhjxABKLO7N5QGmET5qOs/Qfoqq6TGUfb3ZlgKvOnOxTwJKpDq6HSLzsVfK1k7g1iB7Hd9/JWh3T9wclkYwTlY4odP0nnvk0C3RUwj95/ZUq".decode('base64').decode('zip')) ``` It turns out zipping and encoding the program base64 still saves bytes over the normal version. For comparison, here's the normal one: ``` import sys,re d={} s=sys.stdin.read() s,n=re.subn(r"//.*?$",'',s,0,8) s,n=re.subn(r"import (.*?);",r"d['\1']=0;",s,0,8) s,n=re.subn(r"bifurcate (.*?)\[(.*?),(.*?)\];",r"d['\2']=d['\3']=d['\1'];del d['\1'];",s,0,8) s,n=re.subn(r"([+-])",r"\g<1>1",s,0,8) s,n=re.subn(r"EXECUTE\((.*?)\)",r"0\1",s,0,8) s,n=re.subn(r"\[(.*?)\]\.DIE\(\);",r"for i in '\1'.split(','):print i+'='+`d[i]`+('\\n'+'DIE '+i)*abs(d[i])",s,0,8) n=1 s=s[::-1] while n:s,n=re.subn(r"\}([+-01]*);?([^}]*?)\{\)(.*?)\(HTA~",r";\g<2>0+\1=+]'\3'[d;\1",s,0,8) exec(s[::-1]) ``` Basically the "regexy wands of magic" solution that was desired. Reads in the entire program from stdin as a single string, replaces ~ATH expressions with Python expressions that do the described semantics, and exec()s the resulting string. To see what it's doing, look at the python program the second provided test program gets translated to: ``` d['THIS']=0; 0+1+1+1+1;d['THIS']+=0+1+1+1+1+0; d['THIS1']=d['THIS2']=d['THIS'];del d['THIS']; 0+1+1;d['THIS1']+=0+1+1+0; for i in 'THIS1,THIS2'.split(','):print i+'='+`d[i]`+('\n'+'DIE '+i)*abs(d[i]) d['THAT']=0; d['THESE']=d['THOSE']=d['THAT'];del d['THAT']; 0+1+1;d['THESE']+=0+1+1+00+1+1+1;d['THOSE']+=0+1+1+1+0; for i in 'THESE,THOSE'.split(','):print i+'='+`d[i]`+('\n'+'DIE '+i)*abs(d[i]) ``` It's a good thing that `00 == 0` :P Obviously, a few bytes could be saved by exploiting ambiguity in the rules. For instance, it isn't said what should happen in the event someone tries to `DIE()` a variable that hasn't been `import`ed, or that has already been `bifurcate`d. My guess based on the description was that there should be an error. If no error is required, I could remove the `del` statement. EDIT: Fixed a bug that the provided test cases didn't test for. Namely, the way it was, every `~ATH` block reset the variable to zero before incrementing it. It cost me 28 bytes to fix that. If anyone sees a better way to replace `~ATH` blocks, I'd love to know it. EDIT 2: Saved 12 bytes by unrolling the regex loop, making them all subns and letting the compression take care of the repetition. EDIT 3: Saved 20 more bytes by replacing the inner `for` loop with a string multiplication. ]
[Question] [ You saved the day with your [prime sequence code](https://codegolf.stackexchange.com/q/59736/42963), and the math teacher loved it. So much so that a new challenge was posed to the librarian (a/k/a, your boss). Congratulations, you get to code the solution so the librarian can once again impress the math teacher. Start with the sequence of natural numbers in base-10, \$\mathbb N\$ > > 0, 1, 2, 3, 4, 5, 6 ... > > > Excluding `0` and `1`, every number in this sequence either is prime, \$\mathbb P\$ > > 2, 3, 5, 7, 11, 13 ... > > > or composite, \$\mathbf C\$ > > 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20 ... > > > Reflecting on how the librarian thought to insert an integer digit into the decimal expansion of a number from \$\mathbb P\$, the math teacher instead created a function \$G(x,y)\$ that takes a number \$x\$ from \$\mathbb N\$ with \$1 \le x \le 9\$ and a number \$y\$ from \$\mathbf C\$ and inserts \$x\$ into the decimal expansion of \$y\$ in every position, in order left-to-right, selecting only unique numbers. For example, \$G(3,14)\$ is \$314, 134, 143\$. However, \$G(1,14)\$ is only \$114, 141\$, as whether you prepend or insert the \$1\$ into \$14\$, the same number \$114\$ is generated. The math teacher wondered how many times you'd have to do these permutations before you get a number that's in \$\mathbb P\$, if you took \$x\$ in increasing order. The math teacher called this the **Composite-Prime Index** of a number, and wrote it as \$\text{CPI}(y)\$. For example, \$4\$ only needs to be done twice: \$14, 41\$, since \$41\$ is prime, so \$\text{CPI}(4)\$ is \$2\$. However, \$8\$ needs to be done 6 times, \$18, 81, 28, 82, 38, 83\$ before reaching \$83\$ as a prime number, so \$\text{CPI}(8)\$ is \$6\$. Your task is to write code that will output this **Composite-Prime Index**, given an input number. ## Input * A single integer \$y\$, such that \$y\$ is in \$\mathbf C\$, input via function argument, STDIN, or equivalent. * For the purposes of calculation, you can assume \$y\$ will fit in usual integer ranges (e.g., assume \$2^{31}-1\$ as an upper bound). * Behavior for \$y\$ not in *C* is undefined. ## Output The resultant **Composite-Prime Index**, calculated as described above, output to STDOUT or equivalent, with two exceptions: * If the *very last* permutation (i.e., appending \$9\$ to \$y\$) is the one that results in a prime, output `-1`. An example, expanded below, is \$y=14\$. * If there is no permutation (i.e., \$G(x,y)\$ is a subset of \$\mathbf C\$ for all \$1 \le x \le 9\$), output `0`. An example, expanded below, is \$y=20\$. ## Examples ``` y -> operations : output 4 -> 14, 41 : 2 6 -> 16, 61 : 2 8 -> 18, 81, 28, 82, 38, 83 : 6 9 -> 19 : 1 10 -> 110, 101 : 2 12 -> 112, 121, 212, 122, 312, 132, 123, 412, 142, 124, 512, 152, 125, 612, 162, 126, 712, 172, 127 : 19 14 -> 114, 141, 214, 124, 142, 314, 134, 143, 414, 144, 514, 154, 145, 614, 164, 146, 714, 174, 147, 814, 184, 148, 914, 194, 149 : -1 15 -> 115, 151 : 2 16 -> 116, 161, 216, 126, 162, 316, 136, 163 : 8 18 -> 118, 181 : 2 20 -> 120, 210, 201, 220, 202, 320, 230, 203, 420, 240, 204, 520, 250, 205, 620, 260, 206, 720, 270, 207, 820, 280, 208, 920, 290, 209 : 0 ``` ## Restrictions * This is code-golf, since you'll need to transcribe this to an index card so the librarian can show the math teacher, and your hand cramps easily. * Standard loophole restrictions apply. The librarian doesn't tolerate cheaters. ## Leaderboard ``` var QUESTION_ID=63191,OVERRIDE_USER=42963;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+(?:[.]\d+)?)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Haskell, ~~166~~ 161 bytes ``` p n=mod(product[1..n-1]^2)n>0 q=p.read n#c=[h++c:t|i<-[0..length n],(h,t)<-[splitAt i n]] [y]%i|q y= -1|1<2=0 (y:z)%i|q y=i|1<2=z%(i+1) f n=((n#)=<<['1'..'9'])%1 ``` Usage examples: `f "8"` -> `6`, `f "14"`-> `-1`, `f "20"`-> `0`. How it works: `p` is the primality test (stolen from @Mauris' [answer](https://codegolf.stackexchange.com/a/57704/34531) in a different challenge). `q` a wrapper for `p` to convert types from strings to integer. `n # c` inserts `c` at every position in `n`. `%` takes a list of numbers and an index `i`. When the first element of the list is prime, return `i`, else recure with the tail of the list and `i+1`. Stop when there's a single element left and return `-1` if it's prime and `0` otherwise. [Answer] # Pyth, 35 bytes ``` &sKm}dPdsm{msj`dcz]khlzS9|%hxK1lK_1 ``` [Test suite](https://pyth.herokuapp.com/?code=%26sKm%7DdPdsm%7Bmsj%60dcz%5DkhlzS9%7C%25hxK1lK_1&input=16&test_suite=1&test_suite_input=4%0A6%0A8%0A9%0A10%0A12%0A14%0A15%0A16%0A18%0A20&debug=0) [Answer] ## [Minkolang 0.11](https://github.com/elendiastarman/Minkolang), 85 bytes ``` n1(l*$d`)d9[i3G(0c2c$%$r2c*l*2c3c1+*++2gl:d2G)2gx1c2G3gx]r3XS(2M4&I)N.ikI1-4&1~N.1+N. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=n1%28l*%24d%60%29d9%5Bi3G(0c2c%24%25%24r2c*l*2c3c1%2B*%2B%2B2gl%3Ad2G)2gx1c2G3gx%5Dr3XS(2M4%26I)N%2EikI1-4%261%7EN.1%2BN.&input=12) ### Explanation (coming soon) ``` n Take integer from input (say, n) 1( Calculate smallest power of 10 greater than n (say, a) l* Multiply by 10 $d` Duplicate stack and push n>a ) Close while loop (ends when n<=a) d Duplicates a (let's call it b) 9[ For loop that runs 9 times i1+ Loop counter + 1 (say, i) 3G Puts the loop counter in position 3 ( Opens while loop 0c2c$% Copies n and b and pushes n//b, n%b $r Swaps top two elements of stack 2c*l* Copies b and multiplies by 10 2c3c* Copies b and i and multiplies them ++ Adds it all together (inserts i) 2gl: Gets b and divides by 10 d2G Duplicates and puts one copy back ) Closes while loop (breaks when b=0) 2gx Gets and dumps b 1c2G Copies a and puts it in b's place 3gx Get and dumps i ] Close for loop r Reverses stack 3X Dumps the top three elements (namely, n, a, and b) S Removes duplicates ( Opens while loop 2M Pushes 1 if top of stack is prime, 0 otherwise 4& Jump four spaces if prime I)N. If the loop actually finishes, then all were composite, so output 0 and stop. ik Pushes loop counter and breaks I1- Pushes length of stack minus 1 (0 if last one was prime) 4&1~N. If this is 0, pushes -1, outputs as integer, and stops. 1+N. Adds 1, outputs as integer, and stops. ``` [Answer] # Javascript, 324 bytes ``` y=>(p=(n,c)=>n%c!=0?c>=n-1?1:p(n,++c):0,u=a=>a.filter((c,i)=>a.indexOf(c)==i),g=(x,y)=>u(((x,y,z)=>z.map((c,i)=>z.slice(0,i).join("")+x+z.slice(i).join("")).concat(y+x))(x,y,y.split(''))),h=(x,y)=>g(x,y).concat(x==9?[]:h(++x,y)),i=h(1,y).reduce((r,c,i)=>r?r:p(c,2)?i+1:0,0),console.log(p(y,2)||y<2?'':i==h(1,y).length?-1:i)) ``` If y not in C, then STDOUT output is empty. ## Explanation ``` y=>( //Prime Test function p=(n,c)=>n%c!=0?c>=n-1?1:p(n,++c):0, //Unique function u=a=>a.filter((c,i)=>a.indexOf(c)==i), //Generates numbers from a couple x and y g=(x,y)=>u(((x,y,z)=>z.map((c,i)=>z.slice(0,i).join("")+x+z.slice(i).join("")).concat(y+x))(x,y,y.split(''))), //Generates all possible numbers from y using recusion h=(x,y)=>g(x,y).concat(x==9?[]:h(++x,y)), //Check if any prime in the generated numbers i=h(1,y).reduce((r,c,i)=>r?r:p(c,2)?i+1:0,0), console.log( //Is Y in C ? p(y,2)||y<2? '' : // Check if the answer is not the last one i==h(1,y).length?-1:i) ) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` D-ṭJœṖ€$jþ9ẎṖ€ḌQẒµL,-yi1$ ``` [Try it online!](https://tio.run/##y0rNyan8/99F9@HOtV5HJz/cOe1R0xqVrMP7LB/u6oPwHu7oCXy4a9KhrT46upWZhir/jQwe7uh6uGP@4bYg68PtKkAl7v8B "Jelly – Try It Online") +6 bytes to allow for: > > If the very last permutation (i.e., appending 9 to y) is the one that results in a prime, output -1 > > > ## How it works ``` D-ṭJœṖ€$jþ9ẎṖ€ḌQẒµL,-yi1$ - Main link. Takes n on the left D - Digits of n -ṭ - Append -1; Call this D $ - To D: J - Indices; Yield [1, 2, ..., len(D)] € - For each index i: œṖ - Partition D at index i 9 - Generate the range [1,2,3,4,5,6,7,8,9] þ - Pair up all pairs from the range and the partitions: j - Join each partition with the corresponding integer Ẏ - Tighten into a list of lists Ṗ€ - Remove the -1 from each Ḍ - Convert back to integers Q - Deduplicate Ẓ - Replace primes with 1 and composites with 0 µ - Call this list of bits B L - Length of B ,- - Pair with -1 $ - To B: i1 - Yield the first index of 1, or 0 if not found y - If the index is equal to the length, replace with -1 ``` ]
[Question] [ ### The Game Recently, much of my time has been taken up by an addicting game on my phone, called Logic Dots, which inspired me to write this challenge. It's easier to explain the rules if I show you the game display, so here is a screenshot of an unsolved, and solved puzzle: ![](https://i.stack.imgur.com/EQoZ8.png) ![](https://i.stack.imgur.com/7K8VD.png) Now here, there are three main things to notice. 1. The game board (the 4x4 grid of squares in the center) 2. The required shapes (the linked dots in the second bar from the top, under the score and menu, etc.), which are all lines, or `a` by 1 rectangles 3. The numbers over the rows and columns, which denotes how many dots need to be in the column, for a solution The objective of the game is to fit the required shapes into the grid. You can rotate the shapes, but they cannot go in diagonally. In the solution, notice that all shapes are created exactly once (because they are only in the required shapes once), and in this case they are all horizontal but they can also be vertical. The pink filled in squares denote squares not used. Here is a bigger, and slightly more complicated grid: ![](https://i.stack.imgur.com/SlrXK.png) ![](https://i.stack.imgur.com/ALzQJ.png) Notice that in the unsolved puzzle, there are already a few squares filled i.n The greyed out squares signify blocked squares that you **CANNOT** place a dot on. The dots with tails tell you that a dot is in that spot, and it links to **at least** one more dot in the direction of the tail, but not in any other direction (including the opposite direction). ### Notation For the rest of this post, I will refer to the board using the following symbols: * **<, >, ^, v -** Signifies a pre-placed dot with a tail extending in the direction of the point * **\* -** Signifies a dot. If given on an unsolved grid (input), it is an individual shape. If in output, then it is connected to the dots around it. * **# -** Signifies a blocked grid square (where you cannot place a dot) * **-, | (hyphen and bar) -** Signify a dot with a right and left tail, and a dot with an up and down tail respectively * \*\* (space character) -\*\* Signifies an empty space Using these symbols, the latter example case (unsolved) can be represented as follows: ``` < # ^ # ``` And the solution can be represented as: ``` *< * * * * * * * *#* ^ # * ``` Note that no two shapes can touch horizontally, vertically **or diagonally**, so the following case is not valid: ``` *** ** ** ``` ## Challenge Your challenge is to solve any logic dots puzzle, from 4x4 to 9x9 inclusive. You will receive four lines of input, then the game board. The lines will be as follows: * 1st line, Shapes - The shapes to find, each given in the form `sizexquantity` (eg. `3x2` for two shapes of length three) and separated by a space. Example line: `3x1 2x1 1x1` * 2nd line, Columns - A space separated list of the required dot count for each column. Example line: `1 1 2 2` * 3rd line, Rows- A space separated list of the required dot count for each row. Example line: `3 0 3 0` * 4th line, Board size - A single integer, the board size, `B` The board is then given, and is `B` lines of input representing the board using the notation mentioned above. For example, the complete input for the latter example case is as follows: ``` 4x1 3x1 2x2 1x2 1 4 0 3 0 5 4 1 1 2 3 2 6 < # ^ # ``` Your program will then output the solved board, in the same notation. The matching output for the above input is as follows: ``` ** * * * * * * * *#* * # * ``` Note that a game board can have multiple solutions. In this case, just output one valid solution. Also, your program must output a correct solution within 10 seconds on a reasonable desktop computer for a complicated 10x10 grid. This is code golf, so least bytes wins. --- # Test Cases **Input 1** ``` 3x2 1x4 2 2 3 1 2 4 0 3 0 3 5 # # * ``` **Output 1** ``` *** * ***# # * * * ``` **Input 2** ``` 3x1 1x6 2 0 4 0 3 3 1 2 1 2 5 * # ``` **Output 2** ``` * * * * * * * # * * ``` **Input 3** ``` 5x1 4x1 2x1 1x2 1 2 3 3 2 2 0 5 0 4 0 4 6 # - # < ``` **Output 3** ``` # ***** **** # * ** * ``` [Answer] # Python 2: ~~766~~ ~~739~~ ~~696~~ ~~663~~ 633 bytes ``` def f(B,S,o=0): if[]==S:print'\n'.join(B);exit() s=S[0] for i in r: for j in R(Z-s+1): if(B[i][j]in' '+'>v'[o])*(B[i][j+s-1]in' '+'<^'[o])*({' ','-|'[o]}>=set(B[i][j+1:j+s-1]))*all(B[x][y]in'# 'for x,y in [(x,y)for y in R(j-1,j+s+1)for x in i-1,i+1]+[(i,j-1),(i,j+s)]if 0<=x<Z>y>=0):q=B[:];q[i]=q[i][:j]+'*'*s+q[i][j+s:];q=(q,t(q))[o];any((t(q)+q)[k].count('*')>m[k]for k in R(Z+Z))or f(q,S[1:]) o or f(t(B),S,1) y=raw_input;S=[];s=str.split for i in s(y()):u,v=map(int,s(i,'x'));S+=[u]*v m=map(int,s(y())+s(y()));Z=input();R=range;r=R(Z);B=[y()for _ in r];J=''.join;t=lambda x:map(J,zip(*x)) f(B,S[:len(S)-J(B).count('*')]) ``` See it working online: [Ideone.com](http://ideone.com/wSZzkI) (The online version may be too slow for large and difficult grids, offline it should be fine) Input is via stdin, just copy and past the lines from the OP (but be careful, stackexchange sometimes deletes spaces or lines). Some basic ideas of this code: It uses a recursive function `f`. `f` tries to place one shape at the board. For each possible location it calls itself with the modified board. There are 3 loops in it. `o` determines the orientation (2 - horizontal, 3 - vertical). It will always place the shape horizontal, therefore at the end of `o=2`, it will transpose the board with the function `t`. `i` is the row and `j` are all possible starting columns. Then a lot of checks happen, if the ends of the shape have valid chars, if the middle of the shape has valid chars and if the surrounding is empty. [Answer] # JavaScript (ES6) 661 ~~667 695 702 745 755 786 790 784 798~~ ~~Work in progress, can be shortened.~~ Probably too slow on a complex grid. Maybe not. **Edit** A bit longer, a lot faster. **Edit 2** Bug fix, columns/rows check. Incidentally, now it's faster The M function is the main. The w parameter is a multiline string with all the input. The function parses the input and prepare a starting board. Characters `<>^v|-*` in the starting board are replaced with `,`, each `,` has to be replaced with `*` in the correct solution. The R function tries recursively to place all shapes in the board. When a shape is placed, it calls itself passing a shorter list of shapes and the modified board. When all shapes are placed, a solution can still be invalid if there are `,` not replaced by `*`. The P function test if a shape can be placed a a given position and orientation. It checks all the costrains (inside the board, no overlap, no touch, valid row and column count) ``` M=w=>( [x,c,r,z]=w=w[S='split'](n='\n'), (b=[...w.slice(4).join(n)]) .map((c,p)=>~(k='*<>-*^v|'.indexOf(c))&&[(q=k>3?z:1,0),k&1&&-q,k&2&&q].map(o=>b[p+o]=0), c=c[S](e=' '),r=r[S](e),w=z++,f='*',s='',x[S](e).map(v=>s+=v[0].repeat(v[2]))), R=(s,b,x=0,y=0,n=s[0],V=i=>b[i]>'#', P=(p,o,q,t,g,l,d=[...b])=>{ if(l<z-n&!V(p+o*l-o)&!V(p+o*l+o*n)) { for(i=-1;v=d[p],++i<w;p+=o,t-=v==f) if(i>=l&i-n<l) for(v!=e&v!=0|[q,w,~z].some(w=>V(p+w)|V(p-w))?t=0:d[p]=f,j=o*i,u=k=0; ++k<z;(u+=d[j]==f)>g[i]?t=0:j+=q); return t>=n&&d.join('') } })=>{ if(b){ if(!n)return~b.search(0)?0:b; for(s=s.slice(1);y<w||(y=0,++x<w);++y) if(h=R(s,P(y*z,1,z,r[y],c,x))||n>1&&R(s,P(x,z,1,c[x],r,y)))return h } })(s,b) ``` **Test** In FireFox/FireBug console ``` ;['3x2 1x4\n2 2 3 1 2\n4 0 3 0 3\n5\n \n \n #\n # \n *\n' ,'3x1 1x6\n2 0 4 0 3\n3 1 2 1 2\n5\n* \n \n \n # \n \n' ,'5x1 4x1 2x1 1x2\n1 2 3 3 2 2\n0 5 0 4 0 4\n6\n# \n - \n \n \n # \n < \n' ,'4x1 3x1 2x2 1x2\n1 4 0 3 0 5\n4 1 1 2 3 2\n6\n < \n \n \n \n # \n ^ # \n'] .forEach(x=>console.log(x,M(x).replace(/ /g,'`'))) // space replaced with ` for clarity ``` *Output* (total execution time < 1sec) ``` 3x2 1x4 2 2 3 1 2 4 0 3 0 3 5 # # * ***`* ````` `***# ``#`` *`*`* 3x1 1x6 2 0 4 0 3 3 1 2 1 2 5 * # *`*`* ``*`` ``*`* *``#` ``*`* 5x1 4x1 2x1 1x2 1 2 3 3 2 2 0 5 0 4 0 4 6 # - # < #````` `***** `````` `****` `#```` *`**`* 4x1 3x1 2x2 1x2 1 4 0 3 0 5 4 1 1 2 3 2 6 < # ^ # **`*`* ```*`` `````* `*```* `*`*#* `*`#`* ``` ]
[Question] [ The most recognizable [sliding puzzle](http://en.wikipedia.org/wiki/Sliding_puzzle) is the [fifteen puzzle](http://en.wikipedia.org/wiki/15_puzzle). It has a 4 by 4 grid, 15 tiles, and one empty grid space. The tiles can only move into the empty space and must always be in line with the grid. Let's define a generalized sliding puzzle as a two-dimensional *W* wide by *H* high grid (*W*, *H* both positive integers) that contains some number of **identical unmarked** tiles (between 0 and *W*×*H* of them) snapped to the grid, arranged in any way (without overlapping), with empty grid spaces filling the rest of the area. For example if *W* and *H* are 3 and a tile is `T` and an empty space is `E` one of many possible siding puzzle arrangements is ``` TTT TET EET ``` For these puzzles there are 4 possible moves: shove everything **up**, shove everything **down**, shove everything **left**, or shove everything **right**. 'Shoving' in some direction makes all the tiles travel in that direction as far as possible until they hit another tile or the grid boundary. Sometimes shoving will not change the layout of the grid, If the example grid is shoved right the result is ``` TTT ETT EET ``` Shoved left the result is ``` TTT TTE TEE ``` Shoved down the result is ``` EET TET TTT ``` (notice that both the leftmost `T`'s moved) Shoving up does not change the grid layout in this case. Note that since the tiles are indistinguishable these puzzles do not have 'solved' states. Also note that a puzzle may start in a layout that is impossible to get back to once a shove has been made (e.g. one tile in the middle of a 3 by 3 grid). # Challenge Using only [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) write two rectangular blocks of code, both *M* characters wide and *N* characters tall (for any positive integers *M*, *N*). One code block will represent a tile of a sliding puzzle, the other code block will represent an empty grid space. Arranging these two code blocks into a *W* by *H* grid will create a code-represented sliding puzzle which can be saved as a text file and run as a normal program. When run, these kind of programs should prompt the user via stdin for a number from 1 to 4; **1 is for up, 2 down, 3 left, 4 right**. When the user types in their number and hits enter, the program calculates how to shove its source code tiles in that direction and saves the new puzzle layout in a file (either a new file or in the same file), then terminates. This process can be repeated indefinitely with the new sliding puzzle code file generated after each shove. # Example Suppose my tile code block looks like this ``` // my // tile ``` and my empty grid space code block looks like this ``` //empty //space ``` (*M* = 7, *N* = 2, this is of course not actual code) Any valid sliding puzzle arrangement of these two blocks should create a program in the language I'm using that can be run to let the user shove in some direction. The code representation of the example grid is: ``` // my// my// my // tile// tile// tile // my//empty// my // tile//space// tile //empty//empty// my //space//space// tile ``` So running this and pressing 2 (for down) then Enter would write this to another file (or the same file): ``` //empty//empty// my //space//space// tile // my//empty// my // tile//space// tile // my// my// my // tile// tile// tile ``` That file could then be run and shoved in the same exact way. # Notes * Any code-representation of a *W* by *H* sliding puzzle should be runnable and be able to shove itself properly. This includes all grid sizes from 1 by 1 to some reasonable maximum (216 by 216 or more). * **A program *may* read its own source code.** There are no quine-based restrictions. Comments of any sort are also fine. * The program must prompt for a direction to shove in even if there are no tiles to shove or no tiles can be shoved. The prompt is simply a place to type in a number, no message is required. * You may assume the input is always valid (1, 2, 3, or 4). * Padding your code blocks with spaces is fine. Remember that they can only be printable ASCII, this mean no tabs and no newlines (besides the newlines that help form the code blocks). * If your language does not support stdin use whatever input method seems closest. * You can require that a newline be at the end of your code-puzzle files. (Or require that it not be there.) * How you name new files is not important. `f.txt` or just `f` is fine. * The two code blocks may not be identical. # Scoring The goal is to do this with the smallest code size (which is why this is tagged code-golf). The submission with the smallest code block area (*M*×*N*) is the winner. Tie-breaker goes to the highest voted answer. *Related: [Code that runs the Game of Life on itself](https://codegolf.stackexchange.com/q/35974/26997)* [Answer] # [TECO](http://almy.us/teco.html), 153 Empty block: ``` 0T@^Ux#EBx#27@:^Ux##MxA1^QUq^T%d/51%w"G153UsZ/QqUlQq/153Un|Qq%s/153UlZ/QqUn'Qd&1UhQl<.UpQn<Qh-\"F%c'TRQs:C>QpJQn<D-%c"L%c1-Qh\|Qh\'RQs:C>Qw"GC|153%pJ'>EX ``` Tile block: ``` 1T@^Ux#EBx#27@:^Ux##MxA1^QUq^T%d/51%w"G153UsZ/QqUlQq/153Un|Qq%s/153UlZ/QqUn'Qd&1UhQl<.UpQn<Qh-\"F%c'TRQs:C>QpJQn<D-%c"L%c1-Qh\|Qh\'RQs:C>Qw"GC|153%pJ'>EX ``` The program, which modifies itself in place, must be saved in a file named `x`. It can be run via the command `tecoc mung x.`. The dot is important; without it, TECO attempted to find a file named `x.tec`. The trailing newline must be present. The printable ASCII restriction was a bit of a pain for this one, as the language utilizes many unprintable characters. Most of them can be replaced by a two-byte sequence beginning with a caret, but "Escape" (ASCII 27) is the one character that is 'inescapable', so to get it I had to put its ASCII value into a string and exec it. Thus, the 4-byte `EBx<Esc>` exploded into `@^Ux#EBx#27@:^UX##Mx`. This could be reduced greatly, especially by splitting the program into two parts, storing them as strings and running only if both are present. ]
[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/4651/edit). Closed 9 years ago. [Improve this question](/posts/4651/edit) Your challenge is to write a [Chef](http://www.dangermouse.net/esoteric/chef.html) program that works well as a recipe and also as a program. Its utility as a recipe is strictly required (I don't want a recipe for grapeleaves in chocolate-mustard sauce); its utility as a program is a looser requirement, so that it is enough to print something interesting (the first few integers, for example, or "just another chef", or "just another Chef hacker", or "hello world") or do some helpful calculation (printing the sum of two numbers, for example). Votes should take this into account, and the winner is the program with the most net upvotes after some time. (Code length is not important here.) [Answer] I wrote [this program](https://codegolf.stackexchange.com/a/4850) for [another challenge](https://codegolf.stackexchange.com/questions/4834/lowest-unique-bid-auction), but I decided to try and make it a valid answer for this one too: ``` Shirred Eggs. This recipe prints the number 2 and, in doing so, yields two delicious shirred eggs. Ingredients. 2 eggs Cooking time: 12 minutes. Pre-heat oven to 175 degrees Celsius. Method. Put eggs into mixing bowl. Pour contents of the mixing bowl into the baking dish. Shirr the eggs. Bake the eggs until shirred. Serves 1. ``` As I mentioned in the other answer, it seems pretty hard to write anything in Chef that involves something more complicated than mixing stuff in a bowl and baking it, and still have it work both as a program and as a recipe. **Edit:** Changed the recipe from fried to [shirred](http://en.wiktionary.org/wiki/shirr) eggs — thanks to Blazer for [the suggestion](https://codegolf.stackexchange.com/questions/4834/lowest-unique-bid-auction/4850#comment10233_4850)! The cooking time and temperature should be considered advisory only; I haven't actually tried the recipe yet myself, so I can't vouch for their accuracy. ]
[Question] [ [Code 39](http://en.wikipedia.org/wiki/Code_39), developed in 1974, is one of the most commonly used symbologies, or types, of barcodes, although it is the UPC/EAN system that is most often seen in retail sales. Code 39 barcodes can encode uppercase letters, numbers, and some symbols and are trivial to print from computer software using a special font. This led to their widespread commercial and industrial use (e.g. company ID badges, asset tracking, factory automation). Create the shortest program or function to read a Code 39 barcode in any orientation from a 512x512 pixel grayscale image; the barcode might not be aligned horizontally or vertically. * Your program must accept a standard image file format and produce the data encoded in the barcode as its standard output or return value (not including any start/stop character). * No image contains more than one valid Code 39 barcode, and no barcode encodes a space character (ASCII 32). * If no valid Code 39 barcode is shown in the image, the program must output a single question mark (`?`). I have prepared a [JavaScript reference implementation and test suite](https://github.com/plstand/dumb3of9) of images in PNG format, both with valid barcodes and without. The reference implementation, which fails only 3 of 46 test cases in most recent Web browsers, is intended to show one possible decoding algorithm, not to strictly conform to the above specification. A valid submission passes at least 80% of these tests (37/46) and takes no more than one minute to do so for each image on a reasonably fast CPU (e.g. 2.6 GHz quad-core). My reference implementation passes 93% of tests and processes each image within 10 seconds (on my desktop PC running Google Chrome). *(This question was [proposed on Meta](https://codegolf.meta.stackexchange.com/questions/336/proposed-questions-sandbox-mk-ii/345#345) on May 28, 2011.)* [Answer] ## Python, 899 chars ``` import sys,random raw_input() X,Y=map(int,raw_input().split()) input() I=[' x'[v<'~']for v in sys.stdin.read()] M={196:' ',168:'$',148:'*',388:'.',52:'0',97:'2',49:'4',112:'6',292:'8',73:'B',25:'D',88:'F',268:'H',28:'J',67:'L',19:'N',82:'P',262:'R',22:'T',193:'V',145:'X',208:\ 'Z',42:'%',138:'+',133:'-',162:'/',289:'1',352:'3',304:'5',37:'7',100:'9',265:'A',328:'C',280:'E',13:'G',76:'I',259:'K',322:'M',274:'O',7:'Q',70:'S',385:'U',448:'W'\ ,400:'Y'} N=500 for w in' '*30000: a,b,c,d=eval('random.random(),'*4);A=''.join(I[int((a+(c-a)*i/N)*X)+X*int((b+(d-b)*i/N)*Y)]for i in range(N)).lstrip();T=A.count(' x')+1;K=A.count('x')/T;L=A.count\ (' ')/T;s='';z=c=0 while A: z*=2;y=A.find(' ') if y<0:y=len(A) z+=y>K;A=A[y:] z*=2;y=A.find('x') if y<0:y=len(A) z+=y>L;A=A[y:];c+=2 if c>9: if z/2in M:s+=M[z/2];z=c=0 else:break if s and'*'==s[0]and'*'==s[-1]and'*'!=s:print s[1:-1];break ``` This code takes a [pnm format](http://en.wikipedia.org/wiki/Netpbm_format) image as input, so I normally run it like: ``` pngtopnm s01.png | ./barcode.py ``` The code itself just picks lots of random scanlines and tries to match the black and white runs on that scanline to the code39 patterns. It is randomized so it can fail to find barcodes on occasion. (I get about a 20% false negative failure rate on the test images.) When it fails it takes about a minute to run, when it succeeds it often does so much quicker than that. I've never seen a false positive. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 3 years ago. [Improve this question](/posts/1213/edit) I have designed a simple random generator that cycles two numbers in a chaotic way using a multiply and modulus method. It works great for that. If I were to use it as a cipher generator it would however be vulnerable to a known plaintext attack, given that an attacker can reverse engineer the seed from a series of random numbers in a computationally efficient manner. To prove the cipher broken **find a legal pair of seed values that generate 7 zeros in a row in the range [0;255], using as little power, CPU-time etc. as possible.** Here is the random generator written in JavaScript: ``` function seed(state1,state2){ //Constants var mod1=4294967087 var mul1=65539 var mod2=4294965887 var mul2=65537 function random(limit){ //Cycle each state variable 1 step state1=(state1*mul1)%mod1 state2=(state2*mul2)%mod2 //Return a random variable return (state1+state2)%limit } //Return the random function return random } //Initiate the random generator using 2 integer values, //they must be in the ranges [1;4294967086] and [1;4294965886] random=seed(31337,42) //Write 7 random values in the range [0;255] to screen for(a=0;a<7;a++){ document.write(random(256)+"<br>") } ``` I have made a tool for testing candidate number pairs, it can be found [here](http://ebusiness.hopto.org/testpuzzle.htm). **For the next 3 days, no spoilers allowed**, an answer must contain only a set of numbers, and it should of course be a different set from those posted by previous solvers. Thereafter you are encouraged to post code and explain your approach. Edit, quarantine is over: Answers should contain both a unique set of numbers and explanation and code to document the solving method. Most elegant solution wins. For the record: Writing a program that can find a solution quickly is elegant. Making a program that utilize the features of a GPU efficiently to do it even faster is elegant. Doing the job on a piece of "museumware" is elegant. Finding a solution method that can feasibly be utilized using only pen and paper is very elegant. Explaining your solution in an instructive and easily understandable manner is elegant. Using multiple or very expensive computers is inelegant. [Answer] # C++, 44014022 / 164607120 It is in C++, uses 1 GB of memory, and took about 45 seconds to find this first pair. I'll update the time once it finds them all. Code below. It first finds all pairs that generate 4 zeros, then whittles those down by simple trial (see the `check` method). It finds pairs that generate 4 zeros by generating two large arrays, one which contains the first 4 low-order bytes of the state1 generator, and the second which contains the negative of the first 4 low-order bytes of the state2 generator. These arrays are then sorted and searched for a match, which corresponds to the overall generator outputting 4 zeros to start. The arrays are too big to store in memory, so it does the work in batches sized to just fit in memory. Looks like the complete run will take ~12 hours. **Edit**: Improved the code so it only takes ~1 hour to get all possible seeds. Now it generates the tables into 256 different files, one for each first byte of output. We can then process each file independently so we don't have to regenerate data. **Edit**: Turns out you can generate the 256 subtables individually instead of all at once, so no disk needed. Running time down to ~15 minutes using 256MB. ``` #include <stdio.h> #include <stdint.h> #include <algorithm> using namespace std; #define M1 65539 #define N1 4294967087 #define M2 65537 #define N2 4294965887 #define MATCHES 7 // M^-1 mod N #define M1_INV 3027952124 #define M2_INV 1949206866 int npairs = 0; void check(uint32_t seed1, uint32_t seed2) { uint32_t s1 = seed1; uint32_t s2 = seed2; for (int i = 0; i < MATCHES; i++) { s1 = (uint64_t)s1 * M1 % N1; s2 = (uint64_t)s2 * M2 % N2; if (((s1 + s2) & 0xff) != 0) return; } printf("%d %u %u\n", npairs++, seed1, seed2); } struct Record { uint32_t signature; // 2nd through 5th generated bytes uint32_t seed; // seed that generated them }; // for sorting Records bool operator<(const Record &a, const Record &b) { return a.signature < b.signature; } int main(int argc, char *argv[]) { Record *table1 = (Record*)malloc((N1/256+1)*sizeof(*table1)); Record *table2 = (Record*)malloc((N2/256+1)*sizeof(*table2)); for (int i = 0; i < 256; i++) { // iterate over first byte printf("first byte %x\n", i); // generate signatures (bytes 2 through 5) for all states of generator 1 // that generate i as the first byte. Record *r = table1; for (uint64_t k = i; k < N1; k += 256) { uint32_t sig = 0; uint32_t v = k; for (int j = 0; j < 4; j++) { v = (uint64_t)v * M1 % N1; sig = (sig << 8) + (v & 0xff); } r->signature = sig; r->seed = k; r++; } Record *endtable1 = r; // generate signatures (bytes 2 through 5) for all states of generator 2 // that generate -i as the first byte. r = table2; for (uint64_t k = (-i & 0xff); k < N2; k += 256) { uint32_t sig = 0; uint32_t v = k; for (int j = 0; j < 4; j++) { v = (uint64_t)v * M2 % N2; sig = (sig << 8) + (-v & 0xff); } r->signature = sig; r->seed = k; r++; } Record *endtable2 = r; sort(table1, endtable1); sort(table2, endtable2); // iterate through looking for matches const Record *p1 = table1; const Record *p2 = table2; while (p1 < endtable1 && p2 < endtable2) { if (p1->signature < p2->signature) p1++; else if (p1->signature > p2->signature) p2++; else { check((uint64_t)p1->seed * M1_INV % N1, (uint64_t)p2->seed * M2_INV % N2); // NOTE: may skip some potential matches, if p1->signature==(p1+1)->signature or p2->signature==(p2+1)->signature p1++; } } } } ``` ]
[Question] [ My third word search related challenge in a row. :) ## Challenge: #### Brief explanation of what a word search is: In a [word search](https://en.wikipedia.org/wiki/Word_search) you'll be given a grid of letters and a list of words. The idea is to cross off the words from the list in the grid. The words can be in eight different directions: horizontally from left-to-right or right-to-left; vertically from top-to-bottom or bottom-to-top; diagonally from the topleft-to-bottomright or bottomright-to-topleft; or anti-diagonally from the topright-to-bottomleft or bottomleft-to-topright. #### Actual challenge: Given a list of coordinates indicating the crossed out words within a grid (in any reasonable format*†*), output how many line-islands there are. We've had challenges involving finding the amount of islands in a matrix. But in this case it's different: just looking at the grid, words could be right next to each other, but would still be two separated line-islands. E.g. In the following partially solved word search, we have four separated line-islands, even though the letters of the words are right next to each other. [![enter image description here](https://i.stack.imgur.com/Ixc5v.png)](https://i.stack.imgur.com/Ixc5v.png) This partially solved word search above would result in an output of `4`. If 'word' `FG` was `FGH` like this: [![enter image description here](https://i.stack.imgur.com/EzHDe.png)](https://i.stack.imgur.com/EzHDe.png) The output would have been `3` instead, because the `FGH`+`NKH` now form a single connected line-island. In this challenge we'll only be taking the coordinates of the words in a grid as input, and output the amount of line-islands. ## Challenge rules: * *†* You're allowed to take the input in any reasonable format. It could be pair of coordinates per word to indicate their start/end positions (e.g. `[[[0,0],[0,2]],[[1,1],[1,3]],[[3,1],[1,3]],[[3,2],[2,3]]]` for the second example above); it could be a full list of coordinates per word (e.g. `[[[0,0],[0,1],[0,2]],[[1,1],[1,2],[1,3]],[[3,1],[2,2],[1,3]],[[3,2],[2,3]]]`); a list of bit-mask matrices per word (e.g. `[[[1,1,1,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,1,1,1],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,1],[0,0,1,0],[0,1,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,1],[0,0,1,0]]]`); etc. If you're unsure if a possible input-format is valid, leave a comment down below. * All 'words' are guaranteed to have at least two letters. * You can assume the input won't be empty. * You can optionally take the dimensions of the grid as additional input. * Note that coordinates of 'words' are not guaranteed to be in the same positions to still form a single line-island! E.g. this grid would result in `1` because the lines cross, but neither 'word' share the same letter-positions: [![enter image description here](https://i.stack.imgur.com/MM1au.png)](https://i.stack.imgur.com/MM1au.png) ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: [![enter image description here](https://i.stack.imgur.com/Ixc5v.png)](https://i.stack.imgur.com/Ixc5v.png) * Input as start/ending coordinates of the 'words': `[[[0,0],[0,2]],[[1,1],[1,2]],[[3,1],[1,3]],[[3,2],[2,3]]]` * Input as coordinates of the complete 'words': `[[[0,0],[0,1],[0,2]],[[1,1],[1,2]],[[3,1],[2,2],[1,3]],[[3,2],[2,3]]]` * Input as bit-mask matrices of the 'words': `[[[1,1,1,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,1,1,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,1],[0,0,1,0],[0,1,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,1],[0,0,1,0]]]` **Output: `4`** --- [![enter image description here](https://i.stack.imgur.com/EzHDe.png)](https://i.stack.imgur.com/EzHDe.png) * Input as start/ending coordinates of the 'words': `[[[0,0],[0,2]],[[1,1],[1,3]],[[3,1],[1,3]],[[3,2],[2,3]]]` * Input as coordinates of the complete 'words': `[[[0,0],[0,1],[0,2]],[[1,1],[1,2],[1,3]],[[3,1],[2,2],[1,3]],[[3,2],[2,3]]]` * Input as bit-mask matrices of the 'words': `[[[1,1,1,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,1,1,1],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,1],[0,0,1,0],[0,1,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,1],[0,0,1,0]]]` **Output: `3`** --- [![enter image description here](https://i.stack.imgur.com/MM1au.png)](https://i.stack.imgur.com/MM1au.png) * Input as start/ending coordinates of the 'words': `[[[0,0],[1,1]],[[0,1],[1,0]]]` * Input as coordinates of the complete 'words': `[[[0,0],[1,1]],[[0,1],[1,0]]]` * Input as bit-mask matrices of the 'words': `[[[1,0],[0,1]],[[0,1],[1,0]]]` **Output: `1`** --- [![enter image description here](https://i.stack.imgur.com/mrZ3j.png)](https://i.stack.imgur.com/mrZ3j.png) * Input as start/ending coordinates of the 'words': `[[[1,9],[8,9]],[[8,6],[1,6]],[[1,4],[4,7]],[[9,0],[0,9]],[[1,0],[6,0]],[[6,1],[3,4]],[[9,4],[9,9]],[[0,1],[0,8]],[[9,3],[1,3]],[[0,0],[9,9]]]` * Input as coordinates of the complete 'words': `[[[1,9],[2,9],[3,9],[4,9],[5,9],[6,9],[7,9],[8,9]],[[8,6],[7,6],[6,6],[5,6],[4,6],[3,6],[2,6],[1,6]],[[1,4],[2,5],[3,6],[4,7]],[[9,0],[8,1],[7,2],[6,3],[5,4],[4,5],[3,6],[2,7],[1,8],[0,9]],[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0]],[[6,1],[5,2],[4,3],[3,4]],[[9,4],[9,5],[9,6],[9,7],[9,8],[9,9]],[[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8]],[[9,3],[8,3],[7,3],[6,3],[5,3],[4,3],[3,3],[2,3],[1,3]],[[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9]]]` * Input as bit-mask matrices of the 'words': [pastebin](https://pastebin.com/MA6rJqsT) **Output: `4`** --- [![enter image description here](https://i.stack.imgur.com/qg3N9.png)](https://i.stack.imgur.com/qg3N9.png) * Input as start/ending coordinates of the 'words': `[[[8,6],[1,6]],[[1,4],[4,7]],[[9,0],[0,9]],[[6,1],[3,4]],[[9,4],[9,9]],[[9,3],[1,3]],[[0,0],[9,9]]]` * Input as coordinates of the complete 'words': `[[[8,6],[7,6],[6,6],[5,6],[4,6],[3,6],[2,6],[1,6]],[[1,4],[2,5],[3,6],[4,7]],[[9,0],[8,1],[7,2],[6,3],[5,4],[4,5],[3,6],[2,7],[1,8],[0,9]],[[6,1],[5,2],[4,3],[3,4]],[[9,4],[9,5],[9,6],[9,7],[9,8],[9,9]],[[9,3],[8,3],[7,3],[6,3],[5,3],[4,3],[3,3],[2,3],[1,3]],[[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9]]]` * Input as bit-mask matrices of the 'words': [pastebin](https://pastebin.com/JCAP7Jmj) **Output: `1`** [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` żSH$ƝẎ)ṭfƇ@ẎQʋ€ÐL`QL ``` A monadic Link that accepts a list of lists of pairs of integers - the full list of coordinates for each word - and yields the island count. **[Try it online!](https://tio.run/##y0rNyan8///onmAPlWNzH@7q03y4c23asXYHIDPwVPejpjWHJ/gkBPr8//8/OjraQMcgVifaUMcwFkhFG@kYASljHWMwzwAoCpIzgMoZg@WMYmNjAQ "Jelly – Try It Online")** (Two islands each being two words crossing at cell corners, where equal-island words are non-adjacent in the input list.) Or see the [test-suite](https://tio.run/##zZE9TgMxEIV7zkGD5MK7Y4/tjpIiTUQZrUQDBcoFaGlSICEuwA3gACC6iBTcIlzE2F@c7HYgUcAWbz1/783P9eVyeZPz@9v52fHmcft6f7J9eb7arE7Lc/5x93n7tH6YXcxneb0q75wX5bPGDqZgB/ZD@S06rK5ZgtUXq/qk@Xp8xRqOzLc008Ifk9XyGraNxu7DnUnkVxTQgR5UMICxYKWIRvEpcSVXqVM4FD5FRlvvDp8/xJ0JRBLNRZoKdK6l88royPITxgBjZCep8VoilixLhaXawmTJUtg97A52Kew79aqSUEmoJFQSKqmpjHeoKKADPahgAGPjFaYSppLJVDLpQdqdxtuNp9pfVVqFo9ofNh7Qi2Ofu2P@n9P8dul/ssLhCw "Jelly – Try It Online"). ### How? *Needs updating*: ``` ṭfƇ@ẎṢQ - Link 1, add crossing words: Coordinates, (all) Word Coordinates @ - with swapped arguments: Ƈ - filter keep (those Word Coordinate lists) for which: f - filter keep (i.e. contain some of the same entries) ṭ - tack to Coordinates Ẏ - tighten Ṣ - sort Q - deduplicate żSH$ƝẎ)ç€ÐL`QL - Main Link: Word Coordinates ) - for each list in Word Coordinates: $Ɲ - for neighbours: S - sum (vectorises) H - halve ż - Word Coordinates zip-with those "intermediate coordinates" Ẏ - tighten ` - use as both arguments of: ÐL - loop until no change with: ç€ - call Link 1 for each Q - deduplicate L - length ``` [Answer] # Python3, 560 bytes: ``` lambda w:len({str(i[0])for i in g(w)}) S=lambda a:[(t:=(a[1][0]-a[0][0])/([1,(k:=a[1][1]-a[0][1])][k!=0])*(k>0)),[a[0][1],t*-1*a[0][1]+a[0][0]][k!=0]] M=lambda j,k:[(x:=(k[1]-j[1])/(j[0]-k[0])),j[0]*x+j[1]][::-1] N=lambda s,p:min(t:=[s[0][0],s[1][0]])<=p[0]<=max(t)and min(t:=[s[0][1],s[1][1]])<=p[1]<=max(t) V=lambda a,b:(j:=S(a))[0]!=(k:=S(b))[0]and N(a,m:=M(j,k))and N(b,m) def g(w): Q,S=[[i]for i in w],[] while Q: if(v:=Q.pop(0))[-1]not in S: if[]==(j:=[i for i in w if i not in S and V(v[-1],i)]):yield v else:Q=[v+[i]for i in j]+Q S+=v[-1:] ``` [Try it online!](https://tio.run/##nZFNbtswEIX3OgWzG1p0I1qBYxNhb5AAgoBsWC5kWGqoPwuWYDsoenZ3RqKdtAXSIhtSo/fNe6NR9zq87Np41e3Phf52rrNms83YUdV5Cz/6YQ/ORJYXuz1zzLXsOxz5Tx6k2oOZMjAoDZmRFsF5hgc13IKRAiqlR0F6QVpuTXWjEZhB9TXiXBgviGE2lzNfhN7GwzZ4vOSVosLEEyZW5FqS5S2UFF1RLhf0PDuFpFij1Fza4OnS3YtONa6liU0/RYh@mtzyB93h/aCb7AQDz9ot@w2VHpUelVc0eL5uQ2wUlEqnkHGOTTeaVpDCZqzI8gky0Sj9CPghnE9vNqLhwTYvxuWqgCUi1cY4e1360QpjA3Z8cXXOEiSYK@CgdPKl23WAWzT4le1uIDYlGXVjtaZRjGNvPvgeny4ko/hnOFC3cNxy9eryessO5JDXfa4SbQ7h@0lKGyakpqGmNmXP3d61AxRgjIkErhPPhcULfz@64jlVsa9iXy3wWlCFvyz4p0f8CQ/qJS7yXdFfnBRrVFZ4ErcSy5Fb@uQ7vO7E/Vit/VRrr1G1JEeslqN/jPxEUt/ak1N2JFZei9/NP005kn/M9f@TfJT9Udr5Fw) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 90 bytes ``` Length@ConnectedComponents@Graph[#->If[#⋂#2=={},##]&@@@Tuples[Total/@#~Tuples~2&/@#,2]]& ``` [Try it online!](https://tio.run/##zVM9a8MwFNz9NwyZVCxbsmwNLoIMpdChQ7aQwaRKHUjsEKuTcYau/Zf9I650UW2PgQ4phAvv4@6e3sPH0lT6WJr9thx2xfCi63dTqWVT13pr9NuyOZ6aWtemVU/n8lStw4fH5906/P76DJOi6HoShpuFUmr1cTrodr1qTHmIVHi5xpdkYQOSbDaLwejWbMtWt0UXBF3XUUJ7YjEGJr3962JEsY8YosRGLsd8LkHORj25QWfOvF3N8V2deh061mMiwXDIgByYAgUwA@YWnUZOBHICdYFeAZ6AhoCegI/w03Pk0rHOSYaKxHQ5psowu7CzO0WOrnSmmEExx1ak16WoUHRRMCjYFEoUXQLqKdQ51JlVv7o7FwkXCRcJFwkX6V2mSzhkQA5MgQKYAXOvy/Aqhlex2avYbAbmLzVdb7rV712ZZ3Cw03HjGfzyaU5/zf9zm79u/R47DAL720Vq/LKj6PW8r83wAw "Wolfram Language (Mathematica) – Try It Online") A simple set intersection between the lists of coordinates would detect almost all the cases except the 'phantom intersection' of two diagonal 'words'. In this special case, these phantom intersecting diagonals, have both 2 coordinates that add up to a same one. ``` +---------+---------+ |A |B | | x y | x+1 y | | | | +---------X---------+ A coords. B coords. |B |A | (x,y) + (x+1,y+1) = (x,y+1) + (x+1,y) | x y+1 | x+1 y+1 | | | | +---------+---------+ ``` Unfortunately a test for this would not detect the standard intersection of two words that actually have one common coordinate. As such my first implementation combined two test: * the intersection between the plain lists of coordinates `#` * the intersection between the lists of the **sums of consecutive coordinates** `Partition[#,2,1]` (this also assumed the lists would always be in order). But then I thought why not **sum every pair of coordinates** (multisets) of a 'word'? Also pushed by the fact that `Tuples[#,2]` is shorter than `Partition[#,2,1]` ## Technicalities The only doubt: can there be false positives? That is, can two 'words' that do not share any coordinate be mapped into 'words' that do share some coordinates? To sum all the coordinates in a 'word' with themselves is essentially a x2 scaling done in a redundant fashion. So, for each mapped coordinate of a 'word' \$(x\_i+x\_j,y\_i+y\_j)\$ we can infer its preimage: a pair of coordinates of 'word' that yield the mapped one. Hence if two 'words' share a mapped coordinate they also have to share the relative pair of 'core coordinates'. This pair of 'core coordinates' (`P`,`b`) are the two coordinates around the possibly 'phantom point' (`@`) \$(\frac{x\_i+x\_j}{2},\frac{y\_i+y\_j}{2})\$ ``` +---------+---------+ +---------+---------+ +---------+---------+ +---------+---------+ +---------+---------+ |BBBBBBBBB| | |PPPPPPPPP| | | | | |PPPPPPPPP| | | |PPPPPPPPP| |BBBB@BBBB| | |PPPPPPPPP| | | | | |PPPPPPPPP| | | |PPPPPPPPP| |BBBBBBBBB| | |PPPPPPPPP| | | | | |PPPPPPPPP| | | |PPPPPPPPP| +---------+---------+ , +----@----+---------+ , +---------+---------+ , +---------@---------+ OR +---------@---------+ | | | |bbbbbbbbb| | |PPPPPPPPP|bbbbbbbbb| | |bbbbbbbbb| |bbbbbbbbb| | | | | |bbbbbbbbb| | |PPPPPPPPP@bbbbbbbbb| | |bbbbbbbbb| |bbbbbbbbb| | | | | |bbbbbbbbb| | |PPPPPPPPP|bbbbbbbbb| | |bbbbbbbbb| |bbbbbbbbb| | +---------+---------+ +---------+---------+ +---------+---------+ +---------+---------+ +---------+---------+ ``` ]
[Question] [ If you have read in your childhood a Geronimo Stilton's book, I am sure that you remember the style of the text, sometimes the words were decorated for making the act of reading more funny for kids: [example](https://www.google.com/search?q=geronimo%20stilton%20texto&tbm=isch&ved=2ahUKEwiSzoTxwdXwAhWJ5RoKHa0jAc0Q2-cCegQIABAA&oq=geronimo%20stilton%20texto&gs_lcp=CgNpbWcQAzoCCAA6BAgAEB46BggAEAgQHjoECAAQE1CkNFifPWCPP2gAcAB4AIABWYgB7QOSAQE2mAEAoAEBqgELZ3dzLXdpei1pbWfAAQE&sclient=img&ei=c-WkYNLIDInLa63HhOgM&bih=774&biw=1190&rlz=1C1CHBF_esES920ES920#imgrc=c_67TO5E7NrLLM). But when you are an adult you don't have that little entertainment in your readings... why? In a nostalgic attack I have decided to make an algorithm to create that output with every text in the world. It's not very similar, but it's curious. ## Idea: Make a program that with an input like this: ``` It was in the morning of June 21, and I had just set paw in the office. Right away I could tell it wasn't going to be a good day. My staff was running around like a pack of rats in a maze. And everyone was complaining about something. "Geronimo, the air-conditioner's broken!" yelled my secretary, Mousella MacMouser. "Geronimo, we are run out of coffee!" shrieked Blasco Tabasco, one of my designers. "Geronimo, the computers are all down!" cried my proofreader. Mickey Misprint. ``` Create an output like this: [![output](https://i.stack.imgur.com/ziGNU.png)](https://i.stack.imgur.com/ziGNU.png) or this: [![enter image description here](https://i.stack.imgur.com/Wivc4.png)](https://i.stack.imgur.com/Wivc4.png) (These outputs are images because there are two ways to create the output, show it in your program some way or create an output HTML like mine.) This is my raw output: ``` <font face="Verdana">It was in the morning of June 21, and I had just set </br> paw in the <b><font face="Comic Sans MS" size="5" style="color:rgb(111,229,136);">office</font></b>. Right away I could tell it wasn't </br> going to be a good day. My staff was <b><font face="Comic Sans MS" size="5" style="color:rgb(77,170,241);">running</font></b> </br> around like a pack of rats in a maze. And everyone </br> was complaining about something. </br> "Geronimo, the air-conditioner's broken!" </br> <b><font face="Comic Sans MS" size="5" style="color:rgb(174,152,239);">yelled</font></b> my secretary, Mousella MacMouser. </br> "Geronimo, we are run out of coffee!" shrieked </br> Blasco Tabasco, one of my <b><font face="Comic Sans MS" size="5" style="color:rgb(101,139,153);">designers</font></b>. </br> "Geronimo, the computers are all down!" </br> cried my <u><font face="Comic Sans MS" size="5" style="color:rgb(70,164,71);">proofreader</font></u>. Mickey Misprint. </br> </font> ``` ## Algorithm: I have made an example of the algorithm (not golfed) in Java: [Here is it](https://tio.run/##xVZRk9o2EH6/X7HVQ2LXHDnIkM7dYTJNHzLpDC8l0z4AD7Isgw4jMZJ8Lrnw268rgY1d4JJpO1PPzdksu/t9@@1qzQN9pNcP6er5meXUGPjItZJireDpCvDaFEkuGBhLLd4elUhhTYUMJlYLuZjOgeqFCfe@7trbQUhhBc0/8z9tTD5ZKKlBG9glh7XS0rmoDH4tJId@rwNUpvAJljSFh8JYMNzOJIGozlpdZEPLKo/KMsF4F34Ti6UFWtItpmCqyFOwPM9BeFT5@lKqhXIsrIKEA4WFUimkdNuF8dZVm2Wesy6kI3shBdWqQOa5WLkUG8pWripNrS@WolJfkODP6MIfud4qyS8kclBMrTc5SutY0UQVKINac7vEz90LYTNSdavjJaFCXzMlU9QesfRrA4lWKy5/mJELGbaoFMeWYs2caW6p3nZgrAqDdgpjyvyz/h4CJeJr7hQDRx6FYNgizhEczFILvuLphTQfcPKYgs80cfcOIHkXj6xSbsQCSzHfK4FTsbAY4MlQnINUlS8IwJCYr3@jlco0pylWC2PBVnyLN7PBcbZdcv/3Ac@ErMZ7mClpIaOMxzPyO9cplXRGRicxeFgMl5ZLxk3cOCBds8mFDRzD8BiDsGA2nKHTH0qncYCGMBhTu@xqPC5qHYQ/3oZR76YdggcAIXTcMGdKBz4bGsEMaw7dnMuFXaItihonuEW4RGgT1yFTM6/YQpNsE6Z0MOXQR9YQ5QmEJ5wFB77DRqlnHN118Iyi@7Nf1w2JYg89LecRkjx13vHccAdduR1IBuHo7cvQTVGb17fa1HsXRoPzobXQLOdUxv6/y1OTQ5HPBjql9wATXM38LO7bqBe@BIurOBW4RKlbFxC38sW99yQhd0HL1n9PCnJHBAm/2QNfyfQGezAkURMnIqPWgflFrfHFMqHSwHjiVoX44swD92i3uXtmKlf6Ti@SgETn6uwPBmFEOv/4y/DeHddoT7nnKL9xDEfDNyfUK6/@S8P19C8H9Oryp0YSZJnoES6NY4ajb9vPV0MakzTZGsvXXdzTXb/gchnUEYfe7q7OvP/b4@oH9TBKZfvg1o6Sl84Np@uJYBfc3@50NQm3M4TfGfVpRMPJ0viwtbjiMZn3XHDrDCYIp2Le1tFtluG7AXz9CgEb3d7Aq1fAhrc/hc7CRr1@/8xRP3B1UxsHbEl16GeGtVNfaHGC747V/YXW7c5U3Cr2uofljpwI19f/S839eavk6Gj/L6uvsvbm@/JNkRg/KcFR@1qTTluhI6Pa1lhD@Nul0LICqEZ4d/X8/Bc) This is the list of steps that you have to follow starting whit the base input: 1. Start catching a random word in position 5-20(words) 2. If the word is less or equals to 3 char long (e.g. `her`, `a`) catch the next word until you find someone whit more than 3 char 3. "Clean the word", the transformed word cant contain characters like `"` or `.`. The modified word has to starts and end whit [A-Z][a-z] and only whit that characters so... clean it if you need is the 3th step ``` Examples of this step: if you word is | word cleaned ------------------|---------------- "Geronimo, | Geronimo final. | final air-conditioner | air-conditioner (Don't remove special characters inside the word) ``` 4. Put it randomly (1/3 cases) in **bold**, *cursive* or underlined (Only one at the same time for word) 5. Give the word a bigger size than the rest of the text (how much big is your election) 6. Give the word a random color (Try to make this in the widest range of colors that you can, in my code creates an RGB with Java random function in every color that goes from 0 to 255) 7. Give the word any font... (What you want, doesn't matter what you use but must be different to the text font) 8. From this word repeat the 1st step for grab a new one random word next to this Example of algorithm: ``` In step one by a random decision between 5 and 20 you have to start in word 7 for example: It was in the morning of *June* 21, and I had just set paw in the office. On time that you have modified that word you start again the random function and you add the result to your actual position for get the next word... the result of the random function this time has been 8: It was in the morning of *June* 21, and I had just set paw *in* the office. But that word is 2 char long and the next one too so we take the word "office" It was in the morning of *June* 21, and I had just set paw in the *office.* Office has a point at the end, lets clean it: It was in the morning of *June* 21, and I had just set paw in the *office*. And the last step is modify this last word ``` Rules * As I have said, **the output can be show in your program** (or directly in HTML if you use JavaScript or something like that) **or outputs an HTML text whit all the properties in it**. * The **structure of the HTML can be as you want, as long as when you execute it the result should follow the rules**. Basically, you don't have to make it like my example output. * The **base font and size can be what you want**, I have used Verdana in my example because I think that the output is more... "beautiful"? and my code is not golfed. * If you can, put a picture to the executed HTML in your solution please. * In reference to the randomness, the only thing that is relevant is that **the output text has different colors, styles and words every time you run the program**, if there some options are more probable (for example red is more probable than green as a color) that doesn't matter. * And in reference to the randomness of the colors, **it's not necessary that all colors are contemplated in the output, try to put the most colors you can**... I know that this is not very mathematically precise because is a problem to talk about colors when there are so much ways to create them (RGB, hexadecimal, HSV...) so I'm going to try to put a "minimal" rule: * **Lets say that the "extreme" colors must have non 0 probability**, for example in RGB I mean that this colors are mandatory: `0,0,0` `255,255,255` `255,0,0` `0,255,0` `0,0,255` `255,0,255` `0,255,255` `255,255,0` but if you want you can use too the colors in between (That is the principal idea) And **if for some reason you cant use that rule of extreme colors have in mind that at least the output must be 8 different colors**. * This is code golf, so the shortest code wins. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~246 244~~ 232 bytes ``` f=(i,j=p=0,r=_=>Math.random()*3|0,q=_=>p+=4+r()*5,x=q())=>i.replace(/[-'\w]+/g,m=>j++==p?(m[3]?[q(),`<${s="bis"[r()]} style="font:2em monospace;color:rgb(${[r()*85,r()*85,r()*85]})">${m}</${s}>`]:[++p,m])[1]:m).replace(/\n/g,"<br>") ``` [Try it online!](https://tio.run/##ZZJPb5tAEMXvfIoJihQIhPxrpMrJOmovVSr5UvXmoHqBAa/N7pDdJQ51/dndgaqqop4GZt@@95vRbuSrdKVVnb8wVOHxWItIpRvRiavUih9ivpB@nVlpKtJRfH776yp9GdtdIj4kljt36Zt4ieJYzFVmsWtlidHl8uLseZcnl02qxXyTJEJ0j5Fe3uaPS9amq4fTvRNhoVy4ZI/8AM4PLYqwJuNnN6hBkyHXsdd9SS3ZmW2K6HQ/is8/3qXvSn6Iw/npXh8eLtn1MF/ls2WSdKnO4@V1PtPxP6xnw0ThQ2HnYXx8lRZKELB68rCTDpQBv0ZOtkaZBqiGr71BuLlOgaeHJ1jLCja98@DQB53c/b1Bda1KzOCbatYe5E4OLC6pbyvw2LagJn9z5oOGRmdPUCBIaIgqqOSQwWLgBci6njhsb0aAQFrqObdV21HMu9iOTFb6CVWClj859BNL8BXtQAaD8XpJmqdV0wyyoJ5xSaNf838WhF/QklGa0olcKntRkqmUV3zdnjkoLG3RnITBwORYgWYyLC16aYcUFtQ77ktYyHL6tu8sd@xocRwAxlymLXk3iCchuLVVuMUq@NzycyP4LouxpsC5o5BzKnSqYQr3H@Y4Uu/5ZLKXvNKKdiMkv9s/jJ0lqi3KiolgocotDlxcZ5Xx2eo@CHhKRy1mLTVRHZVxfH/8DQ "JavaScript (Node.js) – Try It Online") *Saved ~~2~~ 8 bytes thanks to @ophact!* *Saved 6 bytes thanks to @EliteDaMyth!* --- Returns the resulting text with HTML-formatting applied. (Ab)uses a RegExp-replacer to modify the picked words. If anyone is interested, I'd be happy to add an explanation, if requested. --- ``` f=(i,j=p=0,r=_=>Math.random()*3|0,q=_=>p+=4+r()*5,x=q())=>i.replace(/[-'\w]+/g,m=>j++==p?(m[3]?[q(),`<${s="bis"[r()]} style="font:2em monospace;color:rgb(${[r()*85,r()*85,r()*85]})">${m}</${s}>`]:[++p,m])[1]:m).replace(/\n/g,"<br>") var c = `It was in the morning of June 21, and I had just set paw in the office. Right away I could tell it wasn't going to be a good day. My staff was running around like a pack of rats in a maze. And everyone was complaining about something. "Geronimo, the air-conditioner's broken!" yelled my secretary, Mousella MacMouser. "Geronimo, we are run out of coffee!" shrieked Blasco Tabasco, one of my designers. "Geronimo, the computers are all down!" cried my proofreader. Mickey Misprint.`; document.write(f(c)); ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~459...~~ 375 bytes ``` m=>`<p>${(g=(t,M=Math.random,c=_=>M()*255|0,o=c(),p=c(),q=c(),y='biu'[M()*3|0],x=(N,F)=>N.replace(/[a-zA-Z]|(?<=[a-zA-Z]).(?=[a-zA-Z])/g,F),T=t.length<20,z=_=>T?0:x(t[B=4+M()*15|0],G=>G)[3]?B:z())=>T?t:(t[C=z()]=x(t[C],Y=>`<${y} style=font-size:20;font-family:sans-serif;color:rgb(${[o,p,q]})>${Y}</${y}>`))&&t.slice(0,20).concat(g(t.slice(20))))(m.split(/\s/)).join` `}</p>` ``` [Try it online!](https://tio.run/##ZVNRT9swEH7vrzgQos7mpqWMl1K3AqRVTCoPEy@sq1Y3cVLTxBdsh5ICv707Z0LTtDzYuct33/fdOX6Uz9IlVle@ZzBVh0wcSjFZjavJySvLBfN8LubSb2IrTYolT8QvMZmz6NPw4uJtwFEkLOJVuz61ayO6a113FwFz/jZY8hfB7vjXSEzuYquqQiaK9Reyt7/q/Vi@selYfARRzKZ/g35ORfxe@LhQJveb8XDA90H8fjoYvTC/uBZfPgeRs4ugMhOTWbQ4X06vR3sWRQHmR4S6ERQuRSi4WfKH0NrJa/MOzjeFEhka33N6r0bDwWUbZLLURTNy0rieU1ZnlwkWaEc2X7OT1wXyij8t3yOazsP7uB@oJqsoOj31sSs0tTbgw0EUJ2gS6VnOPtKUpIeVsasK7Vn/p@tHUfyI2qxgRUTVZHWgIoeFigvMWcZWtx520oE24DcKSrRGmxwwg2@1UTA840AnArewkSk81s6DU75Tyd1HBWYZKcfwXecbD3InGwInWBcpeFUUoFt@0/WdHAOzR1grkJAjppDKJoZ5Q2OSWdb6sLUJBjrSYk26hd4GcCWTbfBkpW@tSijlnkSvCKKelW3QqE4oT7Cks9dtD3KNNdnFUvkNxXHneKYsGl0ib51LbXs0jFR7TeW262BtcavM0XGnIecqhZKcqcQqL23DYY61o7yEuUzad/sP5Y4YrQoNQNAltwnNRqmjY3Abq9VWpZ3rgm4Bwr1ch50D6QYg6aTK6ZxcuP9shpZqT19aekkjTXEXTNJ1@uOxsoiZVTIlRzDXyVY1tLnKauNj@m0OvwE "JavaScript (Node.js) – Try It Online") Wow. Just wow. I'm probably missing a really obvious golf here. This is probably the longest program I have ever written, after "Help me count the omer". ## How does this work? Wraps an immediate invocation of `g`, a recursive function, inside a `p` tag. In `g`, we initialize multiple arguments: `t`, which is an array of words, `M`, the built-in random function, and then `c` which returns a random integer from 0 to 255. This is followed by three invocations used as the color of the word (each call to `g` only replaces one word). We also set the "effect" used on the modified word. Next, the function `x` is where the magic happens: takes a word and a callback and replaces all alphabetical letters and special characters sandwiched between alphabetical letters with a call to the callback. I'm not a regular expressions expert, but luckily I knew enough about lookbehinds and lookaheads to implement the `replace`. This saved 47 bytes because before I was using a lengthy `test` condition. We also create `z` which finds a random number whose corresponding word has at least 4 characters. Function body: if the length of `t` is less than 20, return `t` unchanged, otherwise set `t[C=z()]` (the random word) to a call to `x` with that word and a special HTML generator as a callback. We also use an `&&` so that rather than returning an assignment, we return a concatenation of the new `t` and a recursive call with `t.slice(20)`. Note that using spread operators saves no bytes. `g` is then invoked with `m.split(/\s/)` and joined with a space. ]
[Question] [ The program should start out with 2 separate files, here named "a" and "b". "a" and "b" should be what I am calling inverse quines: "a", when run, should output "b"'s source code, and "b", when run, should output "a"'s source code, for example: ``` ./a #source code of b, optionally followed by newlines ./b #source code of a, optionally followed by newlines ``` If the outputs of "a" and "b" are then appended to the same file, here called "c", such as this: ``` touch c ./a >> c ./b >> c ``` The resulting file, "c", when run, should output the code of "a", followed by a newline, followed by the source code of "b" and a newline. The full running of these files should go as follows: ``` touch c ./a >> c ./b >> c ./c #source code of a \n #source code of b \n ``` Any coding languages can be used, and as this is code golf, the source code should be as small as possible. There are no limits on what the source code of "a" and "b" can be, and newlines can be placed freely at the end of code outputs, such that the output ends in a single or a string of newlines. [Answer] # Bash, 63 37 bytes ## a ``` t=;x(){ cat $2 $1;};x b \ ``` ## b ``` ${t-cat} a ``` -26 bytes thanks to Nahuel Fouilleul [Try it online!](https://tio.run/##dc@9CoMwEAfw/Z7ihkB0cGhXrdCChUIfwSV3plgIhmJEW/HZbVSkDnX93/3ug1RdjiMrh0kir7d7dpaYogJ3irsg7HGqiCOKQzzEHRLmMDcBbMhlIgSid5FPB6/ndOlRHqXIAJpLizLrNDdO@zhgWzldOaxL25gC9atRBimUQP4mP2QRQubVimgHqRXRH8R7CB/WGNvqAun928ubEfXzoyW0jBFPf4zjFw "Bash – Try It Online") ## quick explanation There are two key tricks: * We define our own version of `cat` called `x` which swaps its arguments, when there are 2 arguments given. It will have only 1 argument when `a` is run, but 2 arguments when `c` is run. * `b` uses bash default arguments to accomplish what it needs. When `t` is undefined, as it will be when `b` is run alone, it becomes `cat a`. When t is defined, it just returns `a`, becoming the second argument to `a` command `x b a`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 39 (20+19) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ## Program a: ``` "34çìD«r»¨"34çìD«r»¨ ``` [Try it online.](https://tio.run/##yy9OTMpM/f9fydjk8PLDa1wOrS46tPvQCjTu//8A) ## Program b: ``` "34çìD«r»¨"34çìD«r» ``` [Try it online.](https://tio.run/##yy9OTMpM/f9fydjk8PLDa1wOrS46tPvQChTu//8A) ## Program c (concatenation of a+b): ``` "34çìD«r»¨"34çìD«r»¨"34çìD«r»¨"34çìD«r» ``` [Try it online](https://tio.run/##yy9OTMpM/f9fydjk8PLDa1wOrS46tPvQChK4//8DAA) or [try it online as pure quine](https://tio.run/##yy9OTMpM/f9fydjk8PLDa1wOrS46tPvQCjQuFz5prv//AQ). **Explanation:** *Program a:* ``` "34çìD«r»¨" # Push string '34çìD«r»¨' 34 # Push 34 ç # Convert it to a character: '"' ì # Prepend it in front of the string: '"34çìD«r»¨' D # Duplicate it « # Merge the copy to itself: '"34çìD«r»¨"34çìD«r»¨' r # Reverse the items on the stack # (no-op, since there is just a single item) » # Join all items on the stack by newlines # (no-op, since there is just a single item) ¨ # Remove the last character: '"34çìD«r»¨"34çìD«r»' # (after which the result is output implicitly) ``` *Program b:* The same as program a, but without the trailing `¨`, so it'll output `"34çìD«r»¨"34çìD«r»¨` (being program a) instead. *Program c:* ``` "34çìD«r»¨"34çìD«r»¨ # It starts the same as program a "34çìD«r»¨" # Push string '34çìD«r»¨' # STACK: ['"34çìD«r»¨"34çìD«r»', '34çìD«r»¨'] 34çìD« # Do the same as above # STACK: ['"34çìD«r»¨"34çìD«r»', '"34çìD«r»¨"34çìD«r»¨'] r # Reverse the items on the stack # STACK: ['"34çìD«r»¨"34çìD«r»¨', '"34çìD«r»¨"34çìD«r»'] » # Join all items on the stack by newlines # STACK: ['"34çìD«r»¨"34çìD«r»¨\n"34çìD«r»¨"34çìD«r»'] # (after which the result is output implicitly) ``` [Answer] ## [Ruby](https://www.ruby-lang.org/en/), 60 \* 2 bytes This is essentially a quine relay but within one language. Here is `a.rb`: ``` eval s=%q[1;puts "eval s=%q[#{s[0][?1]&&?2||?1}#{s[1..]}]"] ``` The `b.rb` is only different in one symbol: ``` eval s=%q[2;puts "eval s=%q[#{s[0][?1]&&?2||?1}#{s[1..]}]"] ``` Testing: ``` $ ruby b.rb > c.rb $ diff c.rb a.rb $ ruby a.rb > c.rb $ diff c.rb b.rb $ ruby b.rb >> c.rb $ ruby c.rb eval s=%q[1;puts "eval s=%q[#{s[0][?1]&&?2||?1}#{s[1..]}]"] eval s=%q[2;puts "eval s=%q[#{s[0][?1]&&?2||?1}#{s[1..]}]"] ``` ]
[Question] [ # Leon's story Leon is a professional sling shooter and he comes to a shooting range everyday to practice. A casual target is not a challenge for him anymore so before shooting he first covers the target of radius `1.0` with `k` rectangle stickers. He then fires `n` shots that cannot hit the stickers. [![enter image description here](https://i.stack.imgur.com/4EyRy.png)](https://i.stack.imgur.com/4EyRy.png) What's special about Leon is that he always shoots randomly but with a [uniform distribution](https://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly). Leon everyday takes on a bigger challenge and puts more stickers. However he started noticing that **shooting takes too much time** now so he decided to ask you for the best strategy. --- # Task Implement a program which will randomly pick `n` points with the **lowest time complexity** possible. Each point should be inside a circle target, and none of them lands in any of `k` rectangle stickers. **Input:** List of `k` rectangles in whatever form fits you. Eg. where each rectangle is a list of: ``` [x_min, x_max, y_min, y_max] ``` The list could be: ``` [[0.1, 0.3, -0.2, 0.1], [-0.73, -0.12, 0.8, 1.4]] ``` **Output:** List of coordinates of `n` points in whatever form fits you. **Rules:** * Points have to be picked randomly with [uniform distribution](https://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly) * Every point lays inside a circle * None of the points lays inside a rectangle sticker * Stickers can overlap each other * Circle's radius is equal to `1.0` and its center is at coordinates `(0.0, 0.0)` * Every coordinate is in form of floating point number * For edge cases - choose whatever fits you --- **EDIT:** Thanks to @Luis Mendo and @xnor it turned out that one more rule might be useful. * With each new sticker `1/4` of the remaining board will be covered. This means that having `k` stickers the uncovered part of the target will be `(3/4)^k` of the whole. --- ## Rating **The best time complexity wins!** **EDIT:** For the sake of rating we will assume that `k` and `n` are linearly proportional, meaning that `O(k^2 + n)` will be rated equally to `O(k + n^2)` [Answer] # Area-based algorithm, \$O(k^2+n\log(k))\$ Our general strategy is to instead select points (outside the sticker rectangles) from the square (-1,-1) to (1,1), then repeat if we don't get a point within the circle. On average, we will have to select \$\frac{4}{\pi}\$ points from the square for each point in the circle. The runtime is not depend on rectangle coverage, but it does depend on measures of rectangle intersection (denoted `L` in the complexity analysis in the code). For the listed complexity, I use \$L=O(k)\$, which is probably not tight. If \$L=O(\log(k))\$ can be proven, then the complexity is \$O((k+n)\log(k))\$ (see `get_heights` for an algorithmic alternative). Define "open area" to be the area that points could be generated in. Recall that we are using a square instead of a circle, so the total area is piece-wise linear in x. 1. Precompute the total open height function \$h(x)\$ (this is piece-wise constant, so store the change at each transition: either the start or end of a new rectangle). Similarly, pre-compute the cumulative areas \$\int\_{-1}^{x} h(x)\$, which is piece-wise linear, so once again store the value at each transition. This can be done in \$O(k \log(k))\$ time 2. Precompute the intervals on which y coordinates can be distributed for a given x (again, only storing this interval on each transition). This might be able to be done in \$O(k \log(k))\$, but this algorithm only succeeds at \$O(k^2)\$ time 3. Generate points. For each point: (average \$\frac{4}{\pi} n\$ times for a total runtime of \$O(n\log(k))\$ a. Choose a random value \$r\$ for the area (\$O(1)\$) b. Find \$x\$ such that \$\int\_{-1}^{x} h(t) dt = r\$. This is accomplished through binary search on the pre-computed heights \$h\$ and cumulative areas \$\int h\$, so this is done in \$O(\log(k))\$ time c. Choose a random value \$y\$ for the given x such that (x,y) is in an open area. Through similar binary search as 3b, this is done in \$O(\log(k))\$ time d. Reject the point if it is outside the circle (constant factor 4/pi) The total runtime is \$O(k\log(k)) + O(k^2) + O(n\log(k)) = O(k^2+n\log(k))\$ In the following example images, I used the same n=10000, so more rectangle coverage meant a higher density of points. [![Given example](https://i.stack.imgur.com/dVdh9m.png)](https://i.stack.imgur.com/dVdh9m.png) [![Many overlaps](https://i.stack.imgur.com/97TSFm.png)](https://i.stack.imgur.com/97TSFm.png) [![Random rects](https://i.stack.imgur.com/v1jZ0m.png)](https://i.stack.imgur.com/v1jZ0m.png) Full python code below, including matplotlib display: ``` import math import random # for binary search import bisect # matplotlib for plotting the output points import matplotlib.pyplot as plt import matplotlib def find_le(ls, x): # find_le is O(log(|ls|)) # Find rightmost value less than or equal to x in ls i = bisect.bisect_right(ls, x) return i-1, ls[i-1] class Interval: def __init__(self, lo, hi): # each range is tuple (lo, hi) # ranges shall be sorted in ascending order # each range does not overlap with other ranges self.ranges = [(lo, hi)] def remove(self, lo, hi): new_ranges = [] for self_range in self.ranges: if lo <= self_range[0] <= hi < self_range[1]: new_ranges.append((hi, self_range[1])) elif self_range[0] < lo <= self_range[1] <= hi: new_ranges.append((self_range[0], lo)) elif self_range[0] < lo < hi < self_range[1]: new_ranges.append((self_range[0], lo)) new_ranges.append((hi, self_range[1])) elif lo <= self_range[0] < self_range[1] <= hi: pass elif hi <= self_range[0] or self_range[1] <= lo: # no overlap new_ranges.append(self_range) self.ranges = new_ranges def cache_lengths(self): # If L is the number of subintervals of this Interval # then cache_lengths is O(L) ⊂ O(k) # in cum_lengths, (0.6, 0.7) means that the total length to the # left of x=0.7 in this interval is 0.6 self.cum_lengths = [(0, -1)] last_length = 0 for self_range in self.ranges: length = self_range[1] - self_range[0] self.cum_lengths.append((last_length, self_range[0])) last_length += length self.total_length = last_length def random_point(self): # If L is the number of subintervals of this Interval # then random_point is O(log(L)) ⊂ O(log(k)) r = random.random()*self.total_length # This find_le is O(log(L)) i, (length_left, x_left) = find_le(self.cum_lengths, (r,)) return (r - length_left) + x_left def __repr__(self): return "I" + str(self.ranges) def interval_complement(rects): # O(L) where L is the length of rects list interval = Interval(-1, 1) for rect in rects: interval.remove(rect.bottom, rect.top) return interval class Rect: def __init__(self, left, right, bottom, top): self.left = min(left, right) self.right = max(left, right) self.bottom = min(bottom, top) self.top = max(bottom, top) self.width = self.right - self.left self.height = self.top - self.bottom def __repr__(self): return f"Rect({self.left}, {self.right}, {self.bottom}, {self.top})" def overlap(self, others): # returns vertical (y) overlap between self and other rects total_overlap = 0 # https://pyinterval.readthedocs.io/en/latest/guide.html#operations is # looking so tempting right now, but unions/merges would # require Principle Inclusion-Exclusion which can be k^2 worst case starts = sorted(others, key=lambda rect: rect.bottom, reverse=True) ends = sorted(others, key=lambda rect: rect.top, reverse=True) active_rects = set() overlap_start = self.bottom while ends: if starts and starts[-1].bottom < ends[-1].top: active_rect = starts.pop() if not active_rects and active_rect.bottom > self.bottom: # This is the start of an overlap interval overlap_start = active_rect.bottom active_rects.add(active_rect) else: active_rect = ends.pop() active_rects.remove(active_rect) if not active_rects: # This is the end of an overlap interval # Rare cases of negative = started and ended below start of self total_overlap += max(0, min(active_rect.top, self.top) - overlap_start) return total_overlap def as_matplotlib_rect(self): return matplotlib.patches.Rectangle((self.left, self.bottom), self.width, self.height) def get_heights(rects): # get_heights is O(k log(k)) total # Sorting: O(k log(k)) # Use these lists as a queue starts = sorted(rects, key=lambda rect: rect.left, reverse=True) ends = sorted(rects, key=lambda rect: rect.right, reverse=True) # list of tuples (open height starting at x, x, open intervals starting at x) heights = [(2, -1, Interval(-1,1))] active_rects = set() while ends: # inner loop performed once for k left edges and k right edges, # so this is O(k) if starts and starts[-1].left < ends[-1].right: # next x-pos is the start of a new rect rect = starts.pop() height_diff = rect.height - rect.overlap(active_rects) height = heights[-1][0] - height_diff active_rects.add(rect) # interval_complement is O(L) so this is O(k^2), not sure if it is O(k log(k)) heights.append((height, rect.left, interval_complement(active_rects))) else: # next x-pos is the end of an old rect rect = ends.pop() active_rects.remove(rect) # rect.overlap is O(L) as well height_diff = rect.height - rect.overlap(active_rects) # Two choices to get O(k log(k)): # 1. prove that |active_rects| is O(log(k)) under the given approaches # 2. avoid using interval_complement on each transition using some increments approach, and avoid doing rect.overlap on each transition height = heights[-1][0] + height_diff heights.append((height, rect.right, interval_complement(active_rects))) heights.append((2, 1, Interval(-1,1))) # cum_areas is the cumulative areas from -1 to x (of not rects) # Not subtracting curve because we will be sampling from square cum_areas = [(0, -1, Interval(-1, 1))] last_height = 2 for height, x, interval in heights[1:]: last_area, last_x, _ = cum_areas[-1] new_area = (x-last_x)*last_height cum_areas.append((last_area + new_area, x, interval)) last_height = height return (heights, cum_areas) def random_pick_points(rects, num_points): # random_pick_points is O((n+k) log(k)) # Step 1. Precompute heights: O(k log (k)) heights, cum_areas = get_heights(rects) total_area = cum_areas[-1][0] points = [] # Step 2. Precompute vertical intervals: O(k) for _, _, y_interval in cum_areas: y_interval.cache_lengths() # Step 3. Sample points outside rects and within circle # Total time complexity of this loop is O(n log(k)) while len(points) < num_points: # This loop is reached average (4/pi)*n = O(n) times # Each occurence has complexity O(log(k)) # Step 3a. Choose a random area value area = random.random()*total_area # Step 3b. Choose the x value such that area is the total area # outside rects and within 2x2 square to the left of x # There are 2k+1 total cum_areas so this find_le is O(log(k)) i, (area_left, x_left, y_interval) = find_le(cum_areas, (area,)) height, _, _ = heights[i] x = x_left + (area - area_left) / height # Step 3c. Choose a y value uniformly in the open spaces of that x value # Interval.random_point() is O(log(k)) y = y_interval.random_point() # Step 3d. Rejection sample until points are inside the circle # On average, takes constant 4/pi random points to land within the circle if x*x + y*y < 1: points.append((x, y)) # Done! return points def display_points(rects, points): fig, ax = plt.subplots(1) ax.plot(*zip(*points), 'ko', markersize=1, alpha=0.5) ax.axis([-1, 1, -1, 1]) ax.add_collection( matplotlib.collections.PatchCollection( [rect.as_matplotlib_rect() for rect in rects], facecolor = 'r', edgecolor='None', alpha=0.5 ) ) plt.show() def display_random_points(rects, num_points): points = random_pick_points(rects, num_points) display_points(rects, points) def random_rects(k): return [Rect(*[random.random()*2-1 for _ in range(4)]) for i in range(k)] k = 20 # rects = random_rects(k) # print("Rects:", rects) n = 10000 # print("Points:", random_pick_points(rects, n)) display_random_points(random_rects(k), n) ``` [Try it online](https://tio.run/##tVlbb9vGEn7Xr9hGL6RNyZZbnAMI9Xk5TYEAQVMkKXAAwyUociXtEbXLcJexhKYvfezP7B9JZ/bGXVJyhBYNjFgi57Zz@WZ23BzVVvCvP39m@0a0iuwLtZ3Yz23BK7GfTMlatGTFeNEeiaRFW3qKFZO0VJNJRddkzXiV1zSpZUYO6XJC4N/UPSVMkjdJLTbJp1p@SlP79nt4S1q22aq9kIp8LOqOkppKSdS24ATU0g9dURMlyIEwTmqpGRm5t6rn5leuZVjVmqSlqms5YbNFBlwP8PtxMinrAkS/4oq2oMqYiKbnOeNM5Xkiab0GepGRLbNHMIbSotyiPzb6JKpr4EiJpQvINIUkclvUNVlRIsFJtELLC1lSXjG@gUNVtD0tuhLAzIUi4iNt66IhT0xtiVBb2lrRng8tnVt19@TB2QKHdIdq6R7EnD/Sm@R1StiavNYn2lLCu/0KFIk1kR1E2zhJ4ne1Zb3bvAhOn/Legkf/HLMFtebWXzw0trdAB3INlpFvA/KH20f4vmXxw8VjzBernxdNA85Nki3LYq40jdhoDQqHuoYGLIwBFymMZKGXL1b4F0/4JYV/xzEnI3GJYxqoqoE4SS85Ti88PZPYPU@f2CUUDAVM4Ru1lVpGlNev/kZKT5GLxxoMdEGt/PH7b/Bhl04Cckjusts70owkt/N/ZeR2/u@U7GnBNY4pbYoSCoDMECKewbNATk3XCs063AMvStX2OYvRBBAc@yjQqxHgNiOzRdqXIWCdsgTw/vavlKfnjrNgFmdJxDI0zadgYE4W8w9yMbT7@t7aEB9d@7I/W8ARwJ9uXnkjwIn/SJKECvr29jp1iYLfdsHZWrDU8MzNryS9Gp0mUPIelY/a5@tAIhR1YthyzB/offp3CopcMx6GAzjaLDTKtMmkhaAGolJybYWZ3u68kpdiD61vT8GnLfRd6fu8rpAnaFS0d6wNkMBeBLSkZlKZ/u3y@t57N8FGvTCGYYYiB@am5uwj5zjntru1egYQSol9pmnBm008Abjw2e7/FojOd37tRj1MZMSJRYnLOAF1ud6TPeNJwDIEMXyGVMXhGSqjxQoLVQ5TvrGiztM8scpXq9U@6@2NabfUWuelz0J7JoGHWtq01kOBH6x71y/QockvXs2vGfmlN8B/M2L9V1D4a/qi12IHHhsGPfHIqGCNOkmATrESUic5pn5MWlH1RKkBMgK15UYmzB0vw5SZYwkRcUq2SjVyeXPTHIMEK8CbtBKlnDNxQ/lNXSgq1c2mYxWdw8RaT0VD20IxwbFJhGguxA5HPQkwT/eNws8mHlw8QWJ1inQc2W72tMVG9yS6uopO@6FjUEo/toyXDIfNV7ysOwk8s5cH@wnKjcHoWMKgDKPm7uc7ENPCFF0Wsm8tUhWtwgZhRtHEuDYjO3q8r4v9qiq0m5ZkUEngJknv37dd0JoBxy@WBAE@J6YoFftIc4MJmIAq6V/a@OTabpeeNicdDZwbPILWjKZJe1zMAfPxAQZ/V2Pfah79BMwbDyiBYahZ888b0STjGQtU4ZweHQWVBg@c1v@EZxgrDcDewqY5usBM9hnOhk0o/Df02diI544KLbqqkuBBesEsF7sK3XrGUZEiC9qRrktce4nXKJb95T6bkrcFFBjWim71nG4KVOgCD7c2jCdIhU8rWounPi4Yz5NCY4i5NngNcxlCexgUXRwOB1NA3iiCo@4ciTUNeUNVbiBcDhpx8MZMDTtiJxEjx5K9gyIGWFqGBPbVT5KiR@F/bNiQ1/BDPnS0M6gyRBSt/hwM2L43woEYSp4VYbvxWMZU26fnNLyPS5IAHnNiO5s2E4EX5u9Dhj/6bT/fRQRGovMbjtN3OE5n0XyySO14fRbBTiETXhI4dCNoCg2BhgHTzR5ySvCS6klnZ4Z/WmEjwJzb2V6hn2SBHGwnNuP1PeSLuKcFB6in5cbFNIXMP4ADZo04AUB4/9JRiHi@BJDGjXnF1muceTGINigz8811@9CPp0QAtw0Jmo8X0lkofPIsoo2hbNoPnv0c6693sXd/vkszjUOyA5gADzM1KKeB6PdvvnuzJN@/@t/g@UumZ5GmhUOb2@Cn0NRPBGFofFswzJAelQDL9maVhDHBg8OUjdkD5vLNCbcF937qisfX4qlRPopDYMQY@0@lS4C8dXU2W870iFP9YRy5fzCjrs9m1LPOtKh0qTeHsgBdxuDiYA3va5AVhfcwPOhq057M83ULg8VsYfaiiTAdMzj0lPygU3elWrQGQK7sWuBe0bLoANif4IfZFWUBhiOFlik/dKBBy@it8NuFbHhds3ioL@DewXf@Euc8dsiCVQb3EVgsg6WXloH6MvMReHIQ5q3AeEWrR3wKBMlhZujTq8AMT@n540WEZr72ciITgwKIDxaIdvdme5Ss15OaBu22A6zcmRWBdF2Od3Zp0PfsMbHBmoRf79JBd36naEMWc7gaUMy5TlHnT9/LiScfmwfHGM8Ok354sV6N3O52PNY0v@y1xtxFxvgLmu@0y75bYVLkGf4c8zAjvLo@H3qCebzwixzx9Zy8wwSmzjjRKQn3M9KP5LhDRxWsLWtqed/rZZxigKumcA9MHf3GR3dqHQAeOd90d7AjsfGD3tpHcznc3TgxLW74cZ4E1xQbSpJvbhqWXnFwJGhItRnh7fEl/kFAlFCxGuW3ELTAyHGrcK4o5uS/WyGgvAubURotzF9V@tuXCfBwE9VHfyR35eUiFh3sX2lkB1bqfqYlWqQyW86BmLMxuTvcWcSxG9F@Dxo5E7dKSHS3u15YFX1Cu749WpXtBqsyJI8WZWEWhkszL9syhQszB2m5gScHZazHpgM8NvIBYDQ/NCmvOyU3ZABRzs9lEL@j9XLHGc6L9dHshKkZYmVTlNRuKHF6HYR46mF6Hm1B09O@OYLBQbXFLCMrqzl5S/8PkcQNhDS113HFaleBGCjGdcB17@rrzm4KuauEjKhiRzG7OcySMIphYbjUtdIgL@ogY05IhNnscHUAXx@vjlCQi3hgMWI8@APMHz2Ufic4/SqEc0M8iRBcJy34axkSPuil19XDsIruoCdrjNOrS9xvJ9@kj6l@xvpnO/w73Q5b5e3EXSIG6iZNi/7X2zW5fJG57o6osbi9da9/NNCD7883nDT9/PlP) I guess, if you can read a list of points. ]
[Question] [ In the plane (\$\mathbb R^2\$) we can have at most five distinct points such that the distances from each point to every other point (except itself) can assume at most two distinct values. An example of such an arrangement is a regular pentagon - the two different distances are marked with red and blue: ![](https://i.stack.imgur.com/obcV3.jpg) ### Challenge Given a number \$n = 1,2,3,\ldots\$ find the size \$s\_n\$ of the largest 2-distance set in \$\mathbb R^n\$. ### Definitions * We measure the *Euclidean distance* \$d(a, b) = \sqrt{\sum\_{i=1}^n (a\_i - b\_i)^2}\$. * A set \$S \subseteq R^n\$ is a 2-distance set if the number of distinct distances \$| \{ d(a,b) \mid a,b \in S, a \neq b\}| = 2\$. ### Details Any output format defined in [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") is allowed. ### Examples ``` n = 1, 2, 3, 4, 5, 6, 7, 8 s_n = 3, 5, 6, 10, 16, 27, 29, 45 ``` This is [OEIS A027627](https://oeis.org/A027627), and these are all the terms that we know so far. Answers to this challenge are expected to be able to find *any* term of this sequence - given enough ressources - not just the first eight. [Answer] # [Mathematica](https://www.wolfram.com/mathematica/), ~~220~~ 218 bytes ``` For[n=1,1>0,n++,For[m=1,1>0,m++,x=Array[a,{m,n}];d=Table[(Norm[x[[i]]-x[[j]]]^2-1)*(Norm[x[[i]]-x[[j]]]^2-y)==0,{i,1,m-1},{j,i+1,m}];If[Not[CylindricalDecomposition[Flatten@{d,y>0},Flatten@{y,x}]],Break[]]];Print[m-1]] ``` [Try it online!](https://tio.run/##dY7LCsIwEEV/x9opNG5LxBcFN8VFd8MIsY2Y2iQSIzSUfnuNC925mplz4czVwt@kFl41Yp5L69BwBrV7STBpCh@gv0BHMPCtcyKggFGDmahoeS0uvcRFZZ3GAVERZXF0RHReZSxZ/klCwnkOowIGOmMTjB2oNO7RebxiZT3uQ69M62Kz/iAbqx/2qbyyBsteeC/NZmwhrPMJfneAYSKCnZPijvFNcXLKeIx@onl@Aw) Un-golfed version: ``` For[ n = 1, 1>0, n++, For[ m = 1, 1>0, m++, x = Array[a, {m, n}]; d = Table[(Norm[x[[i]] - x[[j]]]^2 - 1)*(Norm[x[[i]] - x[[j]]]^2 - y) == 0, {i, 1, m - 1}, {j, i + 1, m}]; If[Not[ CylindricalDecomposition[Flatten@{d, y > 0}, Flatten@{y, x}]], Break[]] ]; Print[m - 1] ] ``` In this code, we apply a key tool from real algebraic geometry. A [semialgebraic set](https://en.wikipedia.org/wiki/Semialgebraic_set) is a subset of \$\mathbb{R}^d\$ defined by polynomial equalities and inequalities. We may identify the set of 2-distance subsets of \$\mathbb{R}^n\$ of cardinality \$m\$ with a semialgebraic subset of \$\mathbb{R}^{mn+2}\$. We force one of the distances to equal 1 without loss of generality, which means our semialgebraic set is a subset of \$\mathbb{R}^{mn+1}\$. We denote the other distance (squared) by \$y\$. For which values \$Y\subseteq\mathbb{R}\$ of \$y\$ does there exists a size-\$m\$ subset of \$\mathbb{R}^n\$ with squared distances \$\{1,y\}\$? This can be answered with the help of [Tarski--Seidenberg](https://en.wikipedia.org/wiki/Tarski%E2%80%93Seidenberg_theorem), which says that the projection of any semialgebraic set is semialgebraic. In our case, this means there is some univariate polynomial \$p\$ and relation \$\*\in\{=,<,\leq\}\$ such that \$Y=\{y\in\mathbb{R}:p(y)\*0\}\$. This projection may be accomplished using [cylindrical algebraic decomposition](https://en.wikipedia.org/wiki/Cylindrical_algebraic_decomposition) (CAD), which enjoys an [implementation in Mathematica](https://reference.wolfram.com/language/ref/CylindricalDecomposition.html). Given a set of polynomial equalities and inequalities, as well as an ordered list of variables, Mathematica's implementation returns either an explicit description of every point in the corresponding semialgebraic set, or `False` if the set is empty. In the above code, we run CAD for increasingly larger values of \$m\$ until we get `False`, at which point we know that \$s\_n=m-1\$. Sadly, the runtime of CAD is doubly exponential in the number of variables, and so we shouldn't expect this approach to determine \$s\_9\$ any time soon. In fact, a minute of runtime only gives \$s\_1=3\$. ]
[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/186408/edit). Closed 4 years ago. [Improve this question](/posts/186408/edit) **Background** There are self-extracting `.ZIP` files. Typically they have the extension `.EXE` (and by executing the file they will be extracted) but when renaming them to `.ZIP`, you can open the file with some ZIP extracting software. (This is possible because `.EXE` files require a certain header but `.ZIP` files require a certain trailer so it is possible to build a file that both has an `.EXE` header and a `.ZIP` trailer.) **Your task:** Create a program that creates "self-displaying" image files: * The program shall take some 64x64 image (at least 4 colors shall be supported) as input and some "combined" file as output * The output file of the program shall be recognized as image file by common image viewers * When opening the output file with the image viewer, the input image shall be displayed * The output file shall also be recognized as executable file for any operating system or computer type (If a file for an uncommon operating system or computer is produced, it would be nice if an open-source PC emulator exists. However, this is not required.) * When executing the output file, the input image shall also be displayed * It is probable that renaming the file (for example from `.PNG` to `.COM`) is necessary * It is not required that the program and it's output file run on the same OS; the program may for example be a Windows program and output files that can be executed on a Commodore C64. **Winning criterion** * The program that produces the **smallest output file** wins * If the size of the output file differs depending on the input image (for example because the program compresses the image), the the **largest possible** output file created by the program representing a 64x64 image with up to 4 colors counts **By the way** I had the idea for the following programming puzzle when reading [this question on StackOverflow.](https://stackoverflow.com/questions/56454930/is-it-possible-to-execute-a-script-stored-within-a-jpeg-file) [Answer] # 8086 MS-DOS .COM file / BMP, output file size = 2192 bytes ## Encoder The encoder is written in C. It takes two arguments: Input file and output file. The input file is a 64x64 RAW RGB image (meaning it is simply 4096 RGB triplets). Number of colours is limited to 4, so that the palette can be as short as possible. It is very straight-forward in its doings; it merely builds a palette, packs pixels pairs into bytes and glues it together with pre-made headers and the decoder program. ``` #include <stdio.h> #include <stdlib.h> #define MAXPAL 4 #define IMAGESIZE 64 * 64 int main(int argc, char **argv) { FILE *fin, *fout; unsigned char *imgdata = malloc(IMAGESIZE * 3), *outdata = calloc(IMAGESIZE / 2, 1); unsigned palette[MAXPAL] = {0}; int pal_size = 0; if (!(fin = fopen(argv[1], "rb"))) { fprintf(stderr, "Could not open \"%s\".\n", argv[1]); exit(1); } if (!(fout = fopen(argv[2], "wb"))) { fprintf(stderr, "Could not open \"%s\".\n", argv[2]); exit(2); } fread(imgdata, 1, IMAGESIZE * 3, fin); for (int i = 0; i < IMAGESIZE; i++) { // BMP saves the palette in BGR order unsigned col = (imgdata[i * 3] << 16) | (imgdata[i * 3 + 1] << 8) | (imgdata[i * 3 + 2]), palindex; int is_in_pal = 0; for (int j = 0; j < pal_size; j++) { if (palette[j] == col) { palindex = j; is_in_pal = 1; } } if (!is_in_pal) { if (pal_size == MAXPAL) { fprintf(stderr, "Too many unique colours in input image.\n"); exit(3); } palindex = pal_size; palette[pal_size++] = col; } // High nibble is left-most pixel of the pair outdata[i / 2] |= (palindex << !(i & 1) * 4); } char BITMAPFILEHEADER[14] = { 0x42, 0x4D, // "BM" magic marker 0x90, 0x08, 0x00, 0x00, // FileSize 0x00, 0x00, // Reserved1 0x00, 0x00, // Reserved2 0x90, 0x00, 0x00, 0x00 // ImageOffset }; char BITMAPINFOHEADER[40] = { 0x28, 0x00, 0x00, 0x00, // StructSize 0x40, 0x00, 0x00, 0x00, // ImageWidth 0x40, 0x00, 0x00, 0x00, // ImageHeight 0x01, 0x00, // Planes 0x04, 0x00, // BitsPerPixel 0x00, 0x00, 0x00, 0x00, // CompressionType (0 = none) 0x00, 0x00, 0x00, 0x00, // RawImagDataSize (0 is fine for non-compressed,) 0x00, 0x00, 0x00, 0x90, // HorizontalRes // db 0, 0, 0 // nop 0xEB, 0x1A, 0x90, 0x90, // VerticalRes // jmp Decoder // nop // nop 0x04, 0x00, 0x00, 0x00, // NumPaletteColours 0x00, 0x00, 0x00, 0x00, // NumImportantColours (0 = all) }; char DECODER[74] = { 0xB8, 0x13, 0x00, 0xCD, 0x10, 0xBA, 0x00, 0xA0, 0x8E, 0xC2, 0xBA, 0xC8, 0x03, 0x31, 0xC0, 0xEE, 0x42, 0xBE, 0x38, 0x01, 0xB1, 0x04, 0xFD, 0x51, 0xB1, 0x03, 0xAC, 0xD0, 0xE8, 0xD0, 0xE8, 0xEE, 0xE2, 0xF8, 0x83, 0xC6, 0x07, 0x59, 0xE2, 0xEF, 0xFC, 0xB9, 0x00, 0x08, 0xBE, 0x90, 0x01, 0xBF, 0xC0, 0x4E, 0xAC, 0xD4, 0x10, 0x86, 0xC4, 0xAB, 0xF7, 0xC7, 0x3F, 0x00, 0x75, 0x04, 0x81, 0xEF, 0x80, 0x01, 0xE2, 0xEE, 0x31, 0xC0, 0xCD, 0x16, 0xCD, 0x20, }; fwrite(BITMAPFILEHEADER, 1, 14, fout); fwrite(BITMAPINFOHEADER, 1, 40, fout); fwrite(palette, 4, 4, fout); fwrite(DECODER, 1, 74, fout); // BMPs are stored upside-down, because why not for (int i = 64; i--; ) fwrite(outdata + i * 32, 1, 32, fout); fclose(fin); fclose(fout); return 0; } ``` ## Output file The output file is a BMP file which can be renamed .COM and run in a DOS environment. Upon execution, it will change to video mode 13h and display the image. A BMP file has a first header BITMAPFILEHEADER, which contains among other things the field ImageOffset, which denotes where in the file the image data begins. After this comes BITMAPINFOHEADER with various de-/encoding information, followed by a palette, if one is used. ImageOffset can have a value that points beyond the end of any headers, allowing us to make a gap for the decoder to reside in. Roughly: ``` BITMAPFILEHEADER BITMAPINFOHEADER PALETTE <gap> IMAGE DATA ``` Another problem is to enter the decoder. BITMAPFILEHEADER and BITMAPINFOHEADER can be tinkered with to make sure they are legal machine code (which does not produce a non-recoverable state), but the palette is trickier. We could of course have made the palette artificially longer, and put the machine code there, but I opted to instead use the fields biXPelsPerMeter and biYPelsPerMeter, the former to make the code aligned properly, and the latter to jump into the decoder. These fields will of course then have garbage in them, but any image viewer I have tested with displays the image fine. Printing it might produce peculiar results, though. It is, as far as I know, standard-compliant. One could make a shorter file if the `JMP` instruction was put in one of the reserved fields in BITMAPFILEHEADER. This would allow us to store the image height as -64 instead of 64, which in the magical wonderland of BMP files means that the image data is stored the right way up, which in turn would allow for a simplified decoder. ## Decoder No particular tricks in the decoder. The palette is populated by the encoder, and shown here with dummy-values. It could be slightly shorter if it did not return to DOS upon a keypress, but it was not fun testing without that. If you feel you must, you can replace the last three instructions with `jmp $` to save a few bytes. (Don't forget to update the file headers if you do!) BMP stores palettes as BGR (*not* RGB) triplets, padded with zeroes. This makes setting up the VGA palette more annoying than usual. The fact that BMPs are stored upside-down only adds to the flavour (and size). Listed here in NASM style: ``` Palette: db 0, 0, 0, 0 db 0, 0, 0, 0 db 0, 0, 0, 0 db 0, 0, 0, 0 Decoder: ; Set screen mode mov ax, 0x13 int 0x10 mov dx, 0xa000 mov es, dx ; Prepare to set palette mov dx, 0x3c8 xor ax, ax out dx, al inc dx mov si, Palette + 2 mov cl, 4 std pal_loop: push cx mov cl, 3 pal_inner: lodsb shr al, 1 shr al, 1 out dx, al loop pal_inner add si, 7 pop cx loop pal_loop cld ; Copy image data to video memory mov cx, 64 * 64 / 2 mov si, ImageData mov di, 20160 img_loop: lodsb aam 16 xchg al, ah stosw test di, 63 jnz skip sub di, 384 skip: loop img_loop ; Eat a keypress xor ax, ax int 0x16 ; Return to DOS int 0x20 ImageData: ``` ]
[Question] [ You have a little robot with four distance sensors. It knows the layout of a room, but it has no sense of orientation other than being able to lock onto the grid orientation. You want to be able to find out where the robot is based on the readings, but it can be ambiguous because of the limited sensors. ## Challenge Explanation You will be given a room layout and four clockwise distance readings giving the number of cells between you and a wall. There can be walls in the middle of the room and the edges of the grid are also walls. The robot cannot be placed on top of a wall. Your objective is to list all of the locations within the room that the robot could be in that would give the given readings. Keep in mind that the robot has no sense of orientation (other than being locked to 90 degree angles on the grid- i.e. the robot will never be oriented diagonally or some other skew angle), so a reading of [1, 2, 3, 4], for example, is the same as reading [3, 4, 1, 2]. ## Examples For these examples, cell coordinates will be given as 0-indexed (x, y) pairs from the top-left cell. Readings will be given in clockwise order in a square bracketed list. Layouts will use pound signs for walls and other characters (usually dots) to represent empty cells. ### Case 1 ``` . . . . . . . . . . # . . . . . ``` * [1, 0, 2, 3] ==> (1, 0), (3, 1) * [0, 0, 3, 3] ==> (0, 0), (3, 0), (0, 3), (3, 3) * [2, 1, 1, 0] ==> (0, 2), (2, 1) * [1, 1, 2, 2] ==> (1, 1) ### Case 2 ``` # a . # a . a # . . # a . . # . . # # . . # . . a # . . # a . a # . a # ``` * [0, 0, 1, 1] ==> every position on the grid that is a dot * [1, 0, 0, 0] ==> all of the a's on the grid ### Case 3 ``` . ``` * [0, 0, 0, 0] ==> (0, 0) ### Case 4 ``` . # # . . . ``` * [1, 2, 0, 0] ==> (0, 1) * [0, 1, 2, 0] ==> (0, 1) * [0, 0, 1, 0] ==> (0, 0) * [1, 0, 1, 0] ==> (1, 1) * [0, 1, 0, 1] ==> (1, 1) ### Case 5 ``` . # . . . . . . . . # . . . . . ``` * [2, 1, 1, 0] ==> (0, 2), (2, 1) * [0, 2, 2, 1] ==> (1, 1) * [1, 0, 2, 2] ==> (1, 1) * [0, 3, 0, 0] ==> (0, 0) * [1, 0, 1, 1] ==> (1, 2) ## Other Rules * Input may be in any convenient format. Input is a grid of walls and spaces and a list of four distances in clockwise order. * Output may either be a list of all cells that satisfy the reading or a modified version of the grid showing which cells satisfy the reading. The exact format of the output doesn't matter as long as it is reasonable and consistent. Valid output formats *include, but are not limited to*: + Printing a line for each cell coordinate as an ordered pair + Printing the grid with `.`, `#`, and `!` for space, walls, and possible locations, respectively. + Returning a list of ordered pairs + Returning a list of indexes + Returning a list of lists using different values for spaces, walls, and possible locations + Return/print a matrix of 0s and 1s, using 1s to represent cells where the reading would occur. (It is not necessary to include walls) + Once again, this list is not exhaustive, so other representations are valid as long as they are consistent and show every possible valid location in a grid or list. If you are unsure, leave a comment and I will be happy to clarify. * You may assume that a reading corresponds to at least one location on the grid. * You may assume that the input grid is at least 1x1 in size and has at least one empty space. * You may assume that the input grid is no larger than 256 cells in each dimension. * You may assume that the input grid is always a perfect rectangle and not jagged. * There is no penalty or bonus if your program happens to give sane outputs for invalid inputs. * This is code golf, so shortest code wins. [Answer] # JavaScript (ES6), ~~130 128 126~~ 125 bytes Takes input as \$(m)(l)\$ where \$m\$ is a binary matrix describing the room layout (\$0\$ = wall, \$1\$ = empty) and \$l\$ is the list of distances. Returns another binary matrix where each valid position is marked with \$1\$. ``` m=>l=>m.map((r,y)=>r.map((v,x)=>v&!!([...'3210321'].map(d=>(g=X=>(m[Y+=~-d%2]||0)[X+=(d-2)%2]?1+g(X):0)(x,Y=y))+g).match(l))) ``` [Try it online!](https://tio.run/##rVLLboMwELzzFe6htVc4yJj20sj00J9IRDmgQGgiHhGgiEhRf50aXFJDTS@tAOOdsdeznj1G56jeVYdTsyrKOOn2osuFnwk/d/LoREhFLyD8SgVn2srg/HB3RwLHcbDHXSY/HA50LHySio0c82Bri49VfM/D65VBsLEFiVccZPzi2inZwDMD0tKtuADYKcjtze6dZADQNUndIIFyJHyU9cOuLOoyS5ysTMme5CCXDcdVPamEtf0UOy0O2hCcY3koCMYwzt4KDMhGw9@y9HT4NaoT5GJYW/I8FMjHpeOLQroYMyOPwrXVy@9FBmoVp8gLQYPZAHtzmI9p2ARWmCR5Dxu0c107o5o8XeGEmNehJgr9W4ZJ/ezGzStSDFuoyJu4YUz6y@7HmZfsVtqiS/w7oX7OF2Mwz@SSCWa3C1oQ@/RT7D803kIrqWbkZj/GDtNXe4Z7cXVTu08 "JavaScript (Node.js) – Try It Online") (with post-processed output for readability) ### Commented ``` m => l => // m[] = layout matrix; l[] = list of distances m.map((r, y) => // for each row r[] at position y in m[]: r.map((v, x) => // for each cell v at position x in r[]; v && // yield 0 if v = 0 !!( // otherwise, test whether we can find l[] within a [...'3210321'] // list containing twice the results of the sensors .map(d => // for each direction d: (g = X => ( // g = recursive function taking X m[Y += ~-d % 2] // add dy[d] to Y || 0 // use a dummy object if we're out of the board )[X += (d - 2) % 2] ? // add dx[d] to X; if (m[Y] || 0)[X] is equal to 1: 1 + // add 1 to the final result g(X) // and do a recursive call : // else: 0 // yield 0 and stop recursion )(x, Y = y) // initial call to g with X = x and Y = y ) // end of map() over directions + g // coerce the result to a comma-separated string, // followed by harmless garbage ).match(l) // test whether l[] can be found in this string // (l[] is implicitly coerced to a string as well) ) // end of map() over r[] ) // end of map() over m[] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~234~~ ~~202~~ ~~200~~ 191 bytes ``` lambda m,a:[(i,j)for j,l in e(m)for i,c in e(l)if('#'<c)*[(''.join(L)[::-1]+'#').find('#')for L in l[:i],zip(*m)[i][:j],l[:i:-1],zip(*m)[i][:j:-1]]in[a[q:]+a[:q]for q in 0,1,2,3]] e=enumerate ``` [Try it online!](https://tio.run/##lVNNb9wgEL3zK9ByABJigd1erDpSlGsq9U440F3csLKx13YrpX9@C9jKsp9qLGRgeG@GNzP079Nb5/J9Xb3uG93@3GjYMl1KYtmW1t0At6yB1kFD2ri1bD1vG2prghH@tqZ3kmCcbTvryAuVZfkg1L0/oVlt3SZgIvMl8BpZWsX@2p7ctVRaJcutYsEYSMf2YFHWSS13pbrXstyp4GYX3HAmWM4KpYCpjPvdmkFPZt8P1k0QP@vRQIEB@P70o1qtVpn/wPJD8ypYx76xE8GvDlMAZmpNPIVJwXwAmDNYKIqq6hGSYKEMkoJBQY/BPIKLBMwP4DiH42VfnJB9DBEHT8h5AOfnkWakP8iTa4mPy8@684NupDM/gEZeto7aMwRQnD@MftYoZGMwfaPXhmCNGc587a6nZ1YcYi/3MH/M8A77brST7Rz0Y3oz8NdgN36hJ2hHvemmSznmB@W6aWBXR6bGY@rkWGCRFPZ2GflpiLkyx@6@JO4QAv/TG/mZ0ws9seBug/hZ7Tm9lKYUJK6F44eCXGqMr6nQTz6IT7Upv9Kmpx4X3A2QiO8qabQlQ/t/ "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` PθFθ¿⁼¶ι⸿¿№E⁴E⁴⊖⌕⁺⪫KD⊕⌈η✳§⟦→↓←↑⟧⁺κμω#¦#η!ι ``` [Try it online!](https://tio.run/##RY9Na8MwDIbv/RWae5HBG/s6taeybNCxQBjslOYQEmURdezUcdb@e89NQyvQ18sjIVVt6Spb6hDSUXvuHRuPB7leNNZBLIAbwPfDWOoBxc4IBSwlZBMmdk5EkvRAE/Zmx6imZY@vCuaUUOWoI@Opxg82NWZ6HPDTssGMaJ@wo8qzNbg1NzAtT9yNHbZSxg1XZOO3pqYT5qtv/m29glVijyamL2rO3U9fKJj27xV0Up6nj9HFUsxxktrbA3fX@y8Cy3UIuRDiIdpiDstLFVUF@ZOCRwXPCl6KItz/6X8 "Charcoal – Try It Online") Link is to verbose version of code. Charcoal seems to add some padding to the output for some reason; I'm assuming it's a bug in Charcoal. Explanation: ``` Pθ ``` Print the map without moving the cursor. ``` Fθ ``` Loop over each character in the map. ``` ¿⁼¶ι⸿ ``` If it's a newline then move the cursor to the start of the next line. ``` ⊖⌕⁺⪫KD⊕⌈η✳§⟦→↓←↑⟧⁺κμω#¦# ``` Find the distance to the wall in direction `k+m`. ``` ¿№E⁴E⁴...η!ι ``` Loop over all four starting directions `k`, peek in all four clockwise directions `m`, and if the result includes the second input then print a `!` otherwise print the current character. [Answer] # [J](http://jsoftware.com/), 61 bytes Takes in the grid with infinity `_` for empty tiles, `1` for walls. Returns the grid with either 0 or 1, with the latter indicating a possible position. ``` e."1 2]]0 1|:i.@4|."{_2+((,-)|.=i.2)([:<./(1+|.!.1)^:(<_))"$] ``` [Try it online!](https://tio.run/##jVHBboMwDL3zFV6K1ESlbhJ2CiAhTdppp10Ry6EqpbvsA8a/MyeEDNg6TVYU@enZfn5@HxnuO6gM7CEDCYbeEeHp9eV5vCBToNtWghrMDevHAdmn1QfOs6MYsLqhFrwxJZ64Ogz4gEq8GV5aIVjajiJJ@srwpugKnu0ak534gPWOGok6FbXpiHA59x9QXmk6wwKtBu4ViMSCj9WvFvlcq0iuhhx6uE6ApMiXgCaOY0XApZrCAfcFKAgj/dCYJREF9S/OLNTpcpMXMqSPjQzipNQi1vyk0Lqp9b0mK0I3HamhdoJWxmx82AAyQH8b873wvcv8brv0pm8MmO8QGPl6B7XwbPwC "J – Try It Online") Can probably further be golfed by trying other arrangements of the different axes. * `((,-)|.=i.2)` 4 directions in clockwise order: `0 1, 1 0, 0 _1, _1 0` * `(…)^:(<_)"$` for each direction and the grid * `^:(<_)` until the output does not change, return all intermediate steps: * `1+|.!.1` shift the grid, pushing new 1 in at the borders, incrementing each cell. * `[:<./` take the minimum of each cell over all steps. * `_2+` Minus 2. We now have the 4 grids, representing each direction, with the cell representing the distance. * `i.@4|."{` get all possible rotations of the 4 grids. * `0 1|:` transpose so that each cell has 4 lists: the possible arrangements of the sensors. * `e."1 2]]` set cells to 1 if the given sensor input is in the 4 lists, otherwise to 0. ]
[Question] [ tl;dr: Output the values where the reduced prime factorization leader changes. Every positive integer has a unique prime factorization. Let's call the reduced prime factorization just the list of multiplicity of the prime factors, ordered by the size of the factors. For instance, the reduced prime factorization of `1980` is `[2, 2, 1, 1]`, because `1980 = 2 * 2 * 3 * 3 * 5 * 11`. Next, let's record how often each reduced prime factorization happens, over integers in `[1, 2, ..., n]`. For instance, in `[1, 2, ..., 10]`, the following reduced prime factorizations occur: ``` [1]: 4 (2, 3, 5, 7) [2]: 2 (4, 9) [1, 1]: 2 (6, 10) []: 1 (1) [3]: 1 (8) ``` We'll call the leader up to `n` the reduced prime factorization that occurs the most often over `[1, 2, ..., n]`. Therefore, the reduced prime factorization leader for `n = 10` is `[1]`. Ties will be broken by the size of the largest integer less than or equal to `n` with that reduced prime factorization, with smaller largest integer being better. For instance, up to `n = 60`, the reduced prime factorizations `[1]` and `[1, 1]` occur 17 times each. The maximum integer in that range giving `[1, 1]` is `58`, while the maximum integer giving `[1]` is `59`. Therefore, with `n = 60`, the reduced prime factorization leader is `[1, 1]`. I'm interested in the values of `n` where the reduced prime factorization leader changes. Those are the values of `n` where the reduced prime factorization leader is different from the reduced prime factorization leader up to `n-1`. As an edge case, we will say that the leadership changes at `n = 1`, because a leader does not exist for `n = 0`. Your challenge is to output. An initial sequence of the desired output is: ``` 1, 3, 58, 61, 65, 73, 77, 1279789, 1280057, 1280066, 1280073, 1280437, 1280441, 1281155, 1281161, 1281165, 1281179, 1281190, 1281243, 1281247, 1281262, 1281271, 1281313, 1281365 ``` Allowed output styles are: * Infinite output. * The first `k` leader changes, where `k` is the input. * The `k`th leader change, where `k` is the input. `k` may be zero or one indexed. This is code-golf. If you're not sure about anything, ask in the comments. Good luck! [Answer] # [Husk](https://github.com/barbuz/Husk), 18 bytes ``` m←ġ(←►Lk=mȯmLgpṫ)N ``` [Try it online!](https://tio.run/##yygtzv6v8Khtovmjpsb/uY/aJhxZqAEkH03b5ZNtm3tifa5PesHDnas1/f7/BwA "Husk – Try It Online") This prints the infinite list. The link truncates the result to the first 7 values, since the program is quite inefficient and times out after that on TIO. The parentheses are ugly, but I don't know how to get rid of them. ## Explanation ``` m←ġ(←►Lk=mȯmLgpṫ)N No input. N The list of natural numbers [1,2,3,4,.. ġ( ) Group into slices according to this function. Each slice corresponds to a run of numbers with equal return values. ←►Lk=mȯmLgpṫ Function: from n, compute the reduced factorization leader in [1..n]. As an example, take n = 12. ṫ Reversed range: [12,11,10,9,8,7,6,5,4,3,2,1] m Map over this range: p Prime factorization: [[2,2,3],[11],[2,5],[3,3],[2,2,2],[7],[2,3],[5],[2,2],[3],[2],[]] g Group equal elements: [[[2,2],[3]],[[11]],[[2],[5]],[[3,3]],[[2,2,2]],[[7]],[[2],[3]],[[5]],[[2,2]],[[3]],[[2]],[]] ȯmL Take length of each run: [[2,1],[1],[1,1],[2],[3],[1],[1,1],[1],[2],[1],[1],[]] k= Classify by equality: [[[2,1]],[[1],[1],[1],[1],[1]],[[1,1],[1,1]],[[2],[2]],[[3]],[[]]] The classes are ordered by first occurrence. ►L Take the class of maximal length: [[1],[1],[1],[1],[1]] In case of a tie, ► prefers elements that occur later. ← Take first element, which is the reduced factorization leader: [1] The result of this grouping is [[1,2],[3,4,..,57],[58,59,60],[61,62,63,64],.. m← Get the first element of each group: [1,3,58,61,65,73,77,.. ``` [Answer] # JavaScript (ES6), 120 bytes Returns the N-th leader change, 1-indexed. ``` N=>(F=m=>N?F((F[k=(D=(n,d=2,j)=>d>n?j:n%d?D(n,d+1)+(j?[,j]:[]):D(n/d,d,-~j))(++n)]=-~F[k])>m?F[N-=p!=k,p=k]:m):n)(n=p=0) ``` ### Demo ``` let f = N=>(F=m=>N?F((F[k=(D=(n,d=2,j)=>d>n?j:n%d?D(n,d+1)+(j?[,j]:[]):D(n/d,d,-~j))(++n)]=-~F[k])>m?F[N-=p!=k,p=k]:m):n)(n=p=0) for(let n = 1; n <= 7; n++) { console.log('a(' + n + ') = ' + f(n)) } ``` ### Commented Helper function **D()**, returning the reduced prime factorization of **n** in reverse order: ``` D = (n, d = 2, j) => // n = input, d = divisor, j = counter d > n ? // if d is greater than n: j // append j and stop recursion : // else: n % d ? // if d is not a divisor of n: D(n, d + 1) + ( // recursive call with n unchanged and d = d + 1 j ? // if j is not undefined: [,j] // append a comma followed by j : // else: [] // append nothing ) // : // else: D(n / d, d, -~j) // recursive call with n divided by d and j = j + 1 ``` Main function: ``` N => // N = target index in the sequence (F = m => // m = # of times the leader has been encountered N ? // if N is not equal to 0: F( // do a recursive call to F(): (F[k = D(++n)] = // increment n; k = reduced prime factorization of n -~F[k]) // increment F[k] = # of times k has been encountered > m ? // if the result is greater than m: F[N -= p != k, // decrement N if p is not equal to k p = k] // update p and set m to F[p] : // else: m // let m unchanged ) // end of recursive call : // else: n // stop recursion and return n )(n = p = 0) // initial call to F() with m = n = p = 0 ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç▓Δk/‼&²Θºk∙♥╜fv╛Pg8╝j♀§ ``` This program takes no input and theoretically produces infinite output. I say "theoretically" because the 8th element will take more than a year. [Run and debug it](https://staxlang.xyz/#c=%C3%87%E2%96%93%CE%94k%2F%E2%80%BC%26%C2%B2%CE%98%C2%BAk%E2%88%99%E2%99%A5%E2%95%9Cfv%E2%95%9BPg8%E2%95%9Dj%E2%99%80%C2%A7&i=&a=1&m=1) The corresponding ascii representation of the same program is this. ``` 0WYi^{|n0-m|=c:uny=!*{i^Q}Md ``` It keeps the last leader on the stack. Iterating over integers, if there's a distinct mode in the factor representation, and it's different than the last one, output it. ``` 0 push zero for a placeholder factorization W repeat the rest of the program forever Y store the last factorization in the y register i^ i+1 where i is the iteration index { m using this block, map values [1 .. i+1] |n0- get the prime exponents, and remove zeroes |= get all modes c:u copy mode array and test if there's only one ny=! test if mode array is not equal to last leader * multiply; this is a logical and { }M if true, execute this block i^Q push i+1 and print without popping d discard the top of stack if it was a leader change, this pops i+1 otherwise it pops the mode array at this point, the last leader is on top of the stack ``` [Answer] # [Python 2](https://docs.python.org/2/), 145 bytes ``` m=i=0;f=[] while 1: i+=1;a=i;d=[0]*-~i;k=2 while~-a:x=a%k>0;k+=x;a/=x or k;d[k]+=1-x k=filter(abs,d);f+=k,;c=f.count if c(k)>c(m):print i;m=k ``` [Try it online!](https://tio.run/##Hc0xDoMwDEDRPafwUgkKtMCIZS6CGNJAhGUgCFI1Xbh6irr/p799/eTWOsaFmEq01PXqM/E8QtUo4Iwq1MQ4UFf29@JkFKoV/Iuz0E0gfZO2RMkooH5SALeD4NBJf9EiKBCyPPtxT/TryIcUbUaSoyH7MO69@uthwSSStiZZ0mbbefXAuJDE@AM "Python 2 – Try It Online") ## Ungolfed ``` m=0 # reduced prime factorizations leader i=0 # current number f=[] # list of reduced prime factorizations while 1: # Infinite loop: i+=1 # next number a=i # a is used for the prime factorization d=[0]*-~i # this lists stores the multiplicity k=2 # current factor while~-a: # As long as a-1 != 0: x=a%k>0 # x := not (k divides a) k+=x # If k does not divide a, go to the next factor a/=x or k # If k does not divide a, # divide a by 1, # else divide it by k d[k]+=1-x # add 1 to the multiplicity of k if k divides a k=filter(abs,d) # Only keep non-zero multiplicities # k is now the reduced prime factorization of i f+=k, # append k to the list of reduced prime factorizations c=f.count # c(x) := number of occurences of x in f if c(k)>c(m): # has the current reduced prime factorization # appeared more often than the leader? print i;m=k # print the current number, set new leader ``` [Try it online!](https://tio.run/##jVTBjtowEL3zFVOtKpECLdkjlbfqcU/9AMTBxONl5MSOYqeEPeyv07GzoZRNI3xK5PfevDeZSX0KB2cfz@dKrGHkPECDqi1QQd1QhaBlEVxDrzKQsx5KlAqbGf2PXLRNgzaAbas947TY7kZxJfkATk8Wmx0PVCLkmw/sZ6vJUkAonas3MwBaiHykCoDF7mIGQAqCUZgE8tB6NqJdA@GAY4ZYQIntevdl9Ua3AuHAAjGUB88M9EmkastAdUkFhROzjXgcLz90rS/HyJT8bSU3t8ifXMXZF5Ae5CqHTwLWMT9AJ@Rn87S@xccb2AiwLsDcgKLfpNiczBLJLEQ3YofPswZGO4ZGZk8DuYQXB8GlbKmzF8Pcwm@sxc0z92rNYPw8XJ4GKOxPkN@Bx9LjQKIQWSaR1NbseEBW3QeSVAryIdH114qzaYCS86Fn6QtqKgM2c7n3S5X91fplS66GWHNGu3rFxl3LEfpp9ybOn3XH5GNiJ6ItYim9EGY5Osh1jVax3numu/aMB1Dor4VreQRvJ3PeZWl@0gpFJVfwtKItuCP81gFZ0HEDNWNN9lTMq2xzrXCQ/S4MMz7hZLJHMZlkMlS8Xlw6oGVdafuY6bf0IwmwMJeh75Uw/za5v7j20qdagkd@xuO7zPn8Bw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) I feel like it's still golfable ``` ÆEḟ0µ€ĠL€M⁸’ߤ¹Ṗ? ®‘©Ç€F0;ITµL<³µ¿ ``` A full program taking `k` and outputting a Jelly list representation of the first `k` leader change points. **[Try it online!](https://tio.run/##AUoAtf9qZWxsef//w4ZF4bifMMK14oKsxKBM4oKsTeKBuOKAmcOfwqTCueG5lj8Kwq7igJjCqcOH4oKsRjA7SVTCtUw8wrPCtcK/////NQ "Jelly – Try It Online")** ]
[Question] [ When multiplying monomials in the Milnor basis for the Steenrod algebra, part of the algorithm involves enumerating certain "allowable matrices". Given two lists of nonnegative integers *r1*, ... ,*rm* and *s1*, ... ,*sn*, a matrix of nonnegative integers X [![a matrix](https://i.stack.imgur.com/CZZDt.png)](https://i.stack.imgur.com/CZZDt.png) is allowable if 1. The sum of the jth column is less than or equal to *sj*: [![column sums constraint](https://i.stack.imgur.com/VL2BB.png)](https://i.stack.imgur.com/VL2BB.png) 2. The sum of the ith row weighted by powers of 2 is less than or equal to *ri*: [![row sums constraint](https://i.stack.imgur.com/5gVIk.png)](https://i.stack.imgur.com/5gVIk.png) ## Task Write a program which takes a pair of lists *r1*, ... ,*rm* and *s1*, *s1*, ... ,*sn* and computes the number of allowable matrices for these lists. Your program may optionally take m and n as additional arguments if need be. * These numbers may be input in any format one likes, for instance grouped into lists or encoded in unary, or anything else. * Output should be a positive integer * Standard loopholes apply. ## Scoring This is code golf: Shortest solution in bytes wins. ## Examples: For `[2]` and `[1]`, there are two allowable matrices: [![example 1](https://i.stack.imgur.com/ZLnBA.png)](https://i.stack.imgur.com/ZLnBA.png) For `[4]` and `[1,1]` there are three allowable matrices: [![example 2](https://i.stack.imgur.com/7KMk6.png)](https://i.stack.imgur.com/7KMk6.png) For `[2,4]` and `[1,1]` there are five allowable matrices: [![example 3](https://i.stack.imgur.com/ixnk0.png)](https://i.stack.imgur.com/ixnk0.png) ## Test cases: ``` Input: [1], [2] Output: 1 Input: [2], [1] Output: 2 Input: [4], [1,1] Output: 3 Input: [2,4], [1,1] Output: 5 Input: [3,5,7], [1,2] Output: 14 Input: [7, 10], [1, 1, 1] Output: 15 Input: [3, 6, 16, 33], [0, 1, 1, 1, 1] Output: 38 Input: [7, 8], [3, 3, 1] Output: 44 Input: [2, 6, 15, 18], [1, 1, 1, 1, 1] Output: 90 Input: [2, 6, 7, 16], [1, 3, 2] Output: 128 Input: [2, 7, 16], [3, 3, 1, 1] Output: 175 ``` [Answer] # JavaScript (ES7), 163 bytes ``` f=([R,...x],s)=>1/R?[...Array(R**s.length)].reduce((k,_,n)=>(a=s.map((_,i)=>n/R**i%R|0)).some(c=>(p+=c<<++j)>R,p=j=0)?k:k+f(x,s.map((v,i)=>v-a[i])),0):!/-/.test(s) ``` ### Test cases **NB**: I've removed the two most time-consuming test cases from this snippet, but they should pass as well. ``` f=([R,...x],s)=>1/R?[...Array(R**s.length)].reduce((k,_,n)=>(a=s.map((_,i)=>n/R**i%R|0)).some(c=>(p+=c<<++j)>R,p=j=0)?k:k+f(x,s.map((v,i)=>v-a[i])),0):!/-/.test(s) console.log(f([1],[2])) // 1 console.log(f([2],[1])) // 2 console.log(f([4],[1,1])) // 3 console.log(f([2,4],[1,1] )) // 5 console.log(f([3,5,7],[1,2])) // 14 console.log(f([7,10],[1,1,1])) // 15 console.log(f([7,8],[3,3,1])) // 44 console.log(f([2,6,7,16],[1,3,2])) // 128 console.log(f([2,7,16],[3,3,1,1])) // 175 ``` ### Commented ``` f = ( // f = recursive function taking: [R, // - the input array r[] splitted into: ...x], // R = next element / x = remaining elements s // - the input array s[] ) => // 1 / R ? // if R is defined: [...Array(R**s.length)] // for each n in [0, ..., R**s.length - 1], .reduce((k, _, n) => // using k as an accumulator: (a = // build the next combination a[] of s.map((_, i) => // N elements in [0, ..., R - 1] n / R**i % R | 0 // where N is the length of s[] ) // ).some(c => // for each element c in a[]: (p += c << ++j) // increment j; add c * (2**j) to p > R, // exit with a truthy value if p > R p = j = 0 // start with p = j = 0 ) ? // end of some(); if truthy: k // just return k unchanged : // else: k + // add to k the result of f( // a recursive call to f() with: x, // the remaining elements of r[] s.map((v, i) => v - a[i]) // s[] updated by subtracting the values of a[] ), // end of recursive call 0 // initial value of the accumulator k ) // end of reduce() : // else: !/-/.test(s) // return true if there's no negative value in s[] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` UḄ€Ḥ>⁴ 0rŒpṗ⁴L¤µS>³;ÇẸµÐḟL ``` A full program taking **S**, **R** which prints the count **[Try it online!](https://tio.run/##AUsAtP9qZWxsef//VeG4hOKCrOG4pD7igbQKMHLFknDhuZfigbRMwqTCtVM@wrM7w4fhurjCtcOQ4bifTP///1szLCAzLCAxXf9bNywgOF0 "Jelly – Try It Online")** ### How? ``` UḄ€Ḥ>⁴ - Link 1, row-wise comparisons: list of lists, M U - upend (reverse each) Ḅ€ - convert €ach from binary (note bit-domain is unrestricted, e.g. [3,4,5] -> 12+8+5) Ḥ - double (vectorises) (equivalent to the required pre-bit-shift by one) ⁴ - program's 2nd input, R > - greater than? (vectorises) 0rŒpṗ⁴L¤µS>³;ÇẸµÐḟL - Main link: list S, list R 0r - inclusive range from 0 to s for s in S Œp - Cartesian product of those lists ¤ - nilad followed by link(s) as a nilad: ⁴ - program's 2nd input, R L - length ṗ - Cartesian power = all M with len(R) rows & column values in [0,s] µ µÐḟ - filter discard if: S - sum (vectorises) = column sums ³ - program's 1st input, S > - greater than? (vectorises) = column sum > s for s in S Ç - call the last link (1) as a monad = sum(2^j × row) > r for r in R ; - concatenate Ẹ - any truthy? L - length ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 101 bytes Let Mathematica solve it as a system of inequalities over the integers. I set up a symbolic array in `f` and thread over three sets of inequalities. `Join@@` just flattens the list for `Solve`. ``` Length@Solve[Join@@Thread/@{Tr/@(t=f~Array~{q=(l=Length)@#2,l@#})<=#2,2^[[email protected]](/cdn-cgi/l/email-protection)<=#,t>=0},Integers]& ``` [Try it online!](https://tio.run/##TYxBawIxEIX/SkAoCkPdJLrrwcj02NJDqd5EIbQxu7BGTEOhhPjXt6PRVUhm3jfvzex1qM1eh@ZLd1Z178bZUOPy0P6a9duhcYir2hv9Pca48mMcBrU7vXiv/07xqIatygsjHAhocZBGc0VKbD@1swaPz4EYwkIVCV5dMNb4n81T9@EbF9YWEWOMPEEUiQpVIDqryVlB1gIeScIUqgvnnQp4ke0@UAIvQUqCAjjcnQpm1CTI/jArgfEpfTIY3WD395CoCMtrQAITN6ufy8s8b6VN9w8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # Mathematica 139 bytes ``` Tr@Boole[k=Length[a=#]+1;AllTrue[a-Rest[##+0],#>=0&]&@@@Tuples[BinCounts[#,{2r~Prepend~0}]&/@IntegerPartitions[#,All,r=2^Range@k/2]&/@#2]]& ``` [Try it online](https://tio.run/##TU5Na4QwEL33VwwIe@kUNelqoVjs9lToQcSbtRDawZV14xJjL@L@dTt@dHdDMnlv3nuTHJXd01HZ6luNZfQ5ZibeNU1N@QEi@CBd2n2uGDoF3IP/DHcA8FrXmemI@w@QUmtzx2HRKxAceInAg00BG4jjeHZD1p1qavNdpd@aTts2dxB6AeacGDqR/jl7w@R3V/u03rWlkkyijK1s1eg5w88iGP6L@EqVLik@uGINOqJgNCam0jYv@eWUfsm05MZ93/sD9mLgwhWZTehxQrhggbdM4hbDmS@ZEH1vkS@GAP0ApWTioY9XJcQnviTKy2AIEPwtHxaAZ8B13zhCpsFqkAjiX7r05dxfUkMx/gE) Explanation: Partitions each of the *ri* into powers of 2 and then makes all tuples with one decomposition into powers of two for each integer, subtract the column totals from the list of the *si*. Count the number of tuples that make all remaining entries are positive. ]
[Question] [ [<< Prev](https://codegolf.stackexchange.com/questions/149820/advent-challenge-3-time-to-remanufacture-the-presents) [Next >>](https://codegolf.stackexchange.com/questions/149950/advent-challenge-5-move-the-presents-to-the-transport-docks) Santa was able to remanufacture all of the presents that the elves stole overnight! Now he has to send them to the assembly line for packaging. He usually has a camera to supervise the assembly line both to make sure the elves are doing a good job and because assembly line pictures look nice on advertising posters [citation-needed] Unfortunately, his camera broke, so he would like you to draw out a simulation of what the assembly line would look like! In order to keep to assembly line working at maximum efficiency and to reduce the risk of error or failure, all present boxes have the same width so that they fit perfectly on the conveyor belt. # Challenge Given a list of presents represented by their dimensions, output a conveyor belt with all of the presents. A present is drawn like such: ``` +----+ / /| +----+ | | | + | |/ +----+ ``` This present has width 1, height 2, and length 4. Note that the plus-signs don't count for the side-length, so a present with length 4 actually spans 6 positions. All presents are drawn next to each other with one space between the closest two characters; that is, the bottom-left corners of the presents are spaced such that if a present box has length `l` and width `w`, the next present box's bottom-left corner will be exactly `l + w + 4` positions right of the bottom-left corner of the previous box. After all present boxes are drawn, the conveyor belt is drawn by replacing the space between boxes on each of the last `width + 2` lines with underscores. The final output for present boxes with `(l, w, h)` of `[(4, 1, 2), (8, 1, 3), (1, 1, 1)]` would be: ``` +--------+ +----+ / /| / /| +--------+ | +-+ +----+ | | | | / /| | | +_| | +_+-+ + | |/__| |/__| |/ +----+___+--------+___+-+ ``` # Formatting Specifications You can choose either to take a list of 3-tuples where one of the elements is consistent across the whole list (that would be the width), or you can take the present width and then a list of 2-tuples representing the length and height of each present. You can take the inputs in any order and in any reasonable format, but the presents must be displayed in the same order that they are given as input. You may choose any reasonable output format for the ASCII-art (including returning from a function). # Test Cases These test cases are given as `[(l, w, h), ...]` format. ``` [(4, 1, 2), (8, 1, 3), (1, 1, 1)]: +--------+ +----+ / /| / /| +--------+ | +-+ +----+ | | | | / /| | | +_| | +_+-+ + | |/__| |/__| |/ +----+___+--------+___+-+ [(5, 3, 4), (8, 3, 1), (1, 3, 7)]: +-+ / /| / / | +-----+ / / | / /| +-+ | / / | | | | / / | +--------+ | | | +-----+ | / /| | | | | | +___/ / +_| | + | | /___/ / /__| | / | | /___+--------+ /___| | / | |/____| |/____| |/ +-----+_____+--------+_____+-+ [(0, 0, 0)] (this is the most interesting test case ever :P) ++ +++ ++ [(8, 3, 0), (0, 3, 8)] (more zero cases) ++ //| // | // | ++ | || | || | || | +--------+ || | / /+_|| + / //__|| / / //___|| / +--------+/____||/ +--------+_____++ ``` # Rules * Standard Loopholes Apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins * No answer will be accepted Note: I drew inspiration for this challenge series from [Advent Of Code](http://adventofcode.com/). I have no affiliation with this site You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge [here](https://codegolf.stackexchange.com/questions/149660/advent-challenge-1-help-santa-unlock-his-present-vault). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~96~~ 81 bytes ``` NθWS«→FυG↗→↙⁺²θ_≔I⪪ι υ≔⊟υπ≔§υ⁰ρ→↗G↑⊕π↗⊕θ→⊕ρ↓⊕π↙⊕θ ↑πP↗⊕θP←⊕ρ↓+↓πF²«↷⁴+ρ↷²+π↷¹+θ↶³ ``` [Try it online!](https://tio.run/##dVFdT8MgFH0ev@KmT5dYE/dhNPVp0ZclzjQuPpu6sY6EAaOwacx@e4W2s023PcE953A4B5abzCxVJspyJrWzb277xQzu6BM5bLhggBW8sIbLHCmFXzKYqz3D5J3nG@tlg7UygI5CqsRPriQmH7riYkhO64s6yFe29ttUuAJHMexoDNFnFM5Pi4LnEp@zwuJCC26Rew4i6iWuI0iV9tfEoDvY1M7kin2ji@HOUyZQvXj12GQKQCdnDDO5NGzLpGUr1N6hDd9lQtrkAm5oU@6CUdu57xS6hRz@SW2doqo0d8JyfQIvpujLzv0N7VjXyaKb6AzT/x83qr50kPK9stWdOAlcI2/ONpOp9610dFWq@9LhVemulYY@OA7zkRzLckzuYUIeYUiG8EDK2734Aw "Charcoal – Try It Online") Link is to verbose version of code. Input is the width on the first line, then the other dimensions on following lines, ending with a blank line. Explanation: ``` Nθ ``` Input the width. ``` WS« ``` Loop over the remaining lines until the blank line is reached. ``` →FυG↗→↙⁺²θ_ ``` Draw the belt between presents. The `u` variable is predefined to an empty list, which therefore does nothing on the first pass, while later on it ends up with a single element, causing this code to run once. (Using an `if` would be less golfy.) ``` ≔I⪪ι υ ``` Split the dimensions at the space, cast them to integer, and save them in `u`. ``` ≔⊟υπ ``` Remove the last dimension and save it in `p`. ``` ≔§υ⁰ρ ``` Copy the first dimension to `r`, but leave it in `u` so that the belt gets drawn on the next loop. ``` →↗G↑⊕π↗⊕θ→⊕ρ↓⊕π↙⊕θ ``` Erase the interior of the present, in case the belt overlaps it. ``` ↑πP↗⊕θP←⊕ρ↓+↓π ``` Draw the interior lines of the present. ``` F²«↷⁴+ρ↷²+π↷¹+θ↶³ ``` Draw halfway around the exterior of the present, then repeat for the other half. [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~160~~ 154 bytes 153 bytes of code, +1 for `-l` flag. ``` {YMX:_+B+3MUaRV$.({UwhlWg+^11{a<=h+w?J[sXa-haN[0hh+w]?'-XlWR'+sXlWR("/|"a<h)RV(("+|/"aCMw).sXw)@<MN[ah+w-awh]'_Xw-a+1|s]sXl+w+3}M,y}MUa)R`_ +`'_X#_<|:'_} ``` This is a function that takes a list of lists containing `[width height length]`. [Try it online!](https://tio.run/##JY1dS8MwGIXv@yteqtCG2K2hDqVWJuqVkF0UtmWE2L1o1xRrV0ghSNvfXqO7Os@B89HV3XxK5@HARVrQZ5rwLea760U4bK1u9hV9Z2zA7FFTu36TRmCkcSNj7bxaB5Fo9nlAzZ@E/nL0MdMk34WhT8eljy/ckoURljxlfCPRdSK0WgWFcEDZaJRrUkuTid/8TO6Z5McC6NEFropsTINimh/gtf4uW1OfWwPnE3T48YVVaQANSFt/9hp0WVe6h6Zsq14rr0ulBzKBW1ipf2Bwf4E7YBeIIVae8kI3R@Y5an4B "Pip – Try It Online") ### How? Top-level explanation: * Define a function that returns a list of lines representing one box * Map the function to each list of dimensions given * Concatenate the resulting lists of lines item-wise * Do a little post-processing with regex replacements to get the underscores to behave properly Leave a comment and I'll add a more detailed explanation. [Answer] # [Python 2](https://docs.python.org/2/), 508 bytes ``` def f(B): d=B[0][1]+2;H=max(B)[0]+d+1;W=sum(sum(b[1:])+3for b in B)+len(B);r=[[' ']*i+W*['_']for i in range(d)]+[W*[' ']for _ in' '*H];o=0 for h,w,l in B: for i in range(w+2,1,-1):r[i-1][o+i-2:o+l+i]=[' ']*(l+2)+['/'];r[h+i][o+i-1]=r[h+i][o+l+i]='/' r[0][o:o+l+2]=r[h+1][o:o+l+2]=r[w+h+2][o+w+1:o+w+l+3]=['+']+['-']*l+['+'] for i in range(1,h+1):m=min(i,w)-1;r[i][o:o+l+2+m]=['|']+[' ']*l+['|']+[' ']*m;r[i+w+1][o+l+w+2]='|' r[w+1][o+l+w+2]='+';o+=l+w+4 for l in r[H-1::-1]:print''.join(l).rstrip('_') ``` [Try it online!](https://tio.run/##ZVHLbsIwEDyTr/DNNutQHKiKHPnCiT/gYFkIBBRXeSBDlVbqv9Ndh0JLpSSa2RnP7jrHz/OhbYrLZbvbs72YS5OxrZ27sXfaQ1EubL3@wDIWYAu6XNrTey3o3ThtvITJvo1sw0LD5hKqXYPeMlrnOON@GGA5dHzFPZkCmeK6ed2JrfTgSGK9tEIJ8XDhy9aOM0a1g@pUlXJNNng430GhtMq1NNGFXHvXQsgL00IFwdu@t6igkOD4E/dldAcUkkt7e2PJjYZsEGnhNgUUvUH/4R0cEOCRDrShbwUTagQcF@E5tqsgsX@jaoVZ0tS2Do0IqpO5xnHCLR1qyvlKOeyac2c1ealpP25H06BMAz8UgZctWGLT/v7S3UW3yLUxuLU5xtCcOR@9tThIJUfxdI7hKPDvyMteOFEophWbSsXEJMEZQZ2gll5mGbmmiqH6fJUmV9dLgnfXWDF6fvMf6yxBki7f "Python 2 – Try It Online") Takes a list of lists of `[height, width, length]` ]
[Question] [ # Challenge Given a string input, output the demolished version of it. # The Process ``` P r Pr r o o o g g g r r r rogr r a -> a -> a -> a -> a -> -> -> -> -> m m m m m m m m m m mmar m i i i i i i i mi m n n n n gn gn gn gn gni mgni g g Pg Pg roPg roPg roPgmar roPgmar roPgmar roPgmar ``` 1. Place the string vertically. 2. Select a random integer between `1` and `(height of the column of characters) - 1` and a random direction (left or right). 3. Rotate that number of characters in that direction (if those spaces are unoccupied go to step 4; if not, go back to step 2). 4. Let those characters fall due to gravity. 5. Repeat until the height of the column of characters is at most `1` larger than the height of the columns next to it (i.e. it becomes impossible to further demolish ("steps 2-4") the column). 6. If there is another column of characters that is more than `1` character taller than one or more of its surrounding columns (i.e. demolish-able), repeatedly demolish that column until it is no longer demolish-able. If there are multiple demolish-able columns, completely demolish the tallest column (if there are multiple tallest columns, completely demolish the leftmost one). 7. Repeat until all columns are no longer demolish-able. If there are space characters in the input, demolish those first, all at once. ``` C o d e -> oC -> -> ... de G G G o o o l l l f f defoC ``` ## Rules * Standard loopholes are forbidden. * Trailing and leading newlines are allowed. * Your program may either print or return a string/equivalent. * The output must be non-deterministic (unless the input is not demolish-able). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submissions with the smallest byte counts in their languages win! [Answer] # [Python 2](https://docs.python.org/2/), ~~622~~ ~~595~~ ~~573~~ ~~552~~ ~~542~~ ~~534~~ ~~527~~ ~~520~~ 515 bytes ``` from random import* s=input() r=range R=choice Z=len L=h=Z(s) a=[[]for _ in' '*-~h] S=s[::-1].split() X=-1,1 for w in S[1:]: for i in r(Z(w)):a[h-~i*R(X)]+=w[i] a[h]+=S[0] while L: H=[map(Z,a[c-1:c+2])+[c]for c in r(1,h-~h)];D=L=[(min(n,m)-C,i)for n,C,m,i in H if~-C>min(n,m)] while D: _,c=min(L);n,C,m=map(Z,a[c-1:c+2]);D=X[n+2>C:1+(C-1>m)] if D: d=R(D);l=R(r(1,C-[0,m,n][d]));w,a[c]=a[c][-l:],a[c][:-l] for i in r(l):a[c-~i*d]+=w[i] for l in zip(*[l+[' ']*max(H)[1]for l in a if l])[::-1]:print`l`[2::5] ``` [Try it online!](https://tio.run/##ZVKxjuMgEK2Xr6Az2LBaIl1DRBqnSJFilTRRRmjXwnaMhLGFs/Jdivx6Dhzt6aRtGJj35r1hYPxz7Qa/ejzaMPQ4VL6OwfbjEK45mpT149eVUBRUhC4NOijTDdY06Kxc49FedepMJooqBaDbIeAPbH2GcZbze6fRUU0gJRf6dRqdTUInxQUTKFHnSMVHEFJLhFPCpkQgZzJTKivo@N3mB3KiulAzWI1iKm6P8KbR3FnX4H0s3Cnoq5GcWQWGC2mKlaYFmKUZ8xQULEp1VK@3aq@A9NYTz3rKS2ZponlWsp4t7jts2zsvN98cjfDTaivRywczKgF7ul5K1A/j6HACX6w2pRQFKbnYJIkX2y71uFYHsqVrF0PqquTwFo29hlpTup6TklZpAe6kXo4guYsK/8/HpeGYNJz6ezIJdQm92ZHk4ArIcKbzvvpNdhSE/odX8X7Yafp8FTkG66@f7hNWUv7Sj0f2HoZLqPp4ywsev24310w4/glshrrBl8G12V8 "Python 2 – Try It Online") ]
[Question] [ Given * a matrix `a` of characters from `u=" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"` * the coordinates of a submatrix as `x`,`y`,`w`,`h` (left, top, width>1, height>1) * a thickness `t` of 1 (as in `┌`) or 2 (as in `┏`) render an inner border for the submatrix with the specified thickness, taking into account existing lines. ``` x=4;y=1;w=2;h=3;t=2; a=[' ┌───┐', '┌┼┐ │', '│└┼──┘', '└─┘ '] // output r=[' ┌───┐', '┌┼┐ ┏┪', '│└┼─╂┨', '└─┘ ┗┛'] ``` When overwriting a line fragment, the new thickness should be the greater of the old thickness and `t`. This isn't about input parsing or finding the Kolmogorov complexity of Unicode, so you may assume `a`,`u`,`x`,`y`,`w`,`h`,`t` are available to you as variables. Also, you may put the result in a variable `r` instead of returning or outputting it, as long as `r` is of the same type as `a`. If your language forces you to put code in functions (C, Java, Haskell, etc) and your solution consists of a single function, you can omit the function header and footer. Larger test: ``` x=4;y=1;w=24;h=4;t=1; a=['┏┱─────┐ ┌┐ ┎──┲━┓', '┠╂─────┘ ││ ┃ ┗━┛', '┃┃ ││ ┃ ', '┠╂──┲━━┓ ┏━━━━┓ ││ ┌╂┰┐ ', '┃┃ ┗━━┩ ┃ ┃ └╆━┓ └╂┸┘ ', '┃┃ │ ┃ ┃ ┃ ┃ ┃ ', '┗┹─────┘ ┗━━━━┛ ┗━┛ ╹ '] // output r=['┏┱─────┐ ┌┐ ┎──┲━┓', '┠╂──┬──┴─────────┼┼─────╂──╄━┛', '┃┃ │ ││ ┃ │ ', '┠╂──╆━━┓ ┏━━━━┓ ││ ┌╂┰┐│ ', '┃┃ ┗━━╃──╂────╂─┴╆━┱──┴╂┸┴┘ ', '┃┃ │ ┃ ┃ ┃ ┃ ┃ ', '┗┹─────┘ ┗━━━━┛ ┗━┛ ╹ '] ``` [Answer] # JavaScript, 218 bytes ``` (a,x,y,w,h,t,u)=>a.map((l,j)=>l.map((c,i)=>u[(g=(a,b)=>a?g(a/3|0,b/3|0)*3+Math.max(a%3,b%3):b)(u.indexOf(c),t*((j==y||j==y+h-1)*((i>x&&i<x+w)*9+(i>=x&&i<x+w-1))+(i==x||i==x+w-1)*((j>y&&j<y+h)*3+(j>=y&&j<y+h-1)*27)))])) ``` `a` should be taken as array of array of char. ``` f = (a,x,y,w,h,t,u)=>a.map((l,j)=>l.map((c,i)=>u[(g=(a,b)=>a?g(a/3|0,b/3|0)*3+Math.max(a%3,b%3):b)(u.indexOf(c),t*((j==y||j==y+h-1)*((i>x&&i<x+w)*9+(i>=x&&i<x+w-1))+(i==x||i==x+w-1)*((j>y&&j<y+h)*3+(j>=y&&j<y+h-1)*27)))])) x=4;y=1;w=24;h=4;t=1; a=['┏┱─────┐ ┌┐ ┎──┲━┓', '┠╂─────┘ ││ ┃ ┗━┛', '┃┃ ││ ┃ ', '┠╂──┲━━┓ ┏━━━━┓ ││ ┌╂┰┐ ', '┃┃ ┗━━┩ ┃ ┃ └╆━┓ └╂┸┘ ', '┃┃ │ ┃ ┃ ┃ ┃ ┃ ', '┗┹─────┘ ┗━━━━┛ ┗━┛ ╹ '].map(x => [...x]) u=" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"; output = f(a,x,y,w,h,t,u).map(x => x.join('')).join('\n'); document.write(`<pre lang="en" style="font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,sans-serif;">${output}</pre>`) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~226~~ ~~201~~ 197 bytes ``` n,m=x+w-1,y+h-1 r=[*map(list,a)] R=range for i in R(x,x+w): for j in R(y,y+h):A,B=j in(y,m),i in(x,n);r[j][i]=u[sum(3**o*max((i<n*A,y<j*B,x<i*A,j<m*B)[o]*t,u.index(a[j][i])//3**o%3)for o in R(4))] ``` [Try it online!](https://tio.run/##bVLbUhpBEH3fr9iyKrU766pl4EnYB/kEXzc8UBUTloKFQijhTSH3i5J4JpiQ@91cjUkMxlz@5fwImdkFg@jU1E53T59zunun0qzly2FiUPemTMp9yp@U3wkQkvKAuEd0Kb8Ra5S/iG1C2fvEA6JPqOQ@5R9inbhPKOAPokco4CGlsm8Rt4kW8ZB4RPmXeEw8IzrEB@IT8ZJQtIrhNaWSuETcIT4Sn4lXxG9CQXYo25RXKQ@JDWKTUsWfEM@JNvGUeEHcJXaJPeIN5TrlFeItZYvyBrFFfCG@Eu8oL1NeI95TXqe8OWUYDS@ZanrzqVXvbDKVV05NOUbO8y2to3Frx3fHHK2ouc7Q3Bjd70Wz2LJcQ8UtXZ2qYpJke4xE3baGZlt/uhFB74igHcWPrUmQTjxNL65Fl6MTN0feKPafRreiYbtxQxPao5rU3jlS1Id@JnrSIwVEJP24v5MNRGJj8CFH@7Q2utEbOjm2sVri3RubmSaSBzFR1lB/sRis1OxSrmJrw80JMQjdkteYXp2Zd5vT@Zl5o@r5zlhC1ljyqrnw4rJxoVw1AzMIzSW74SqEWDBMHSvEsabGi4VFN@PpiPJLwtX5KjsUqapfyPpB1qv7K/WSnXCcslJp2HaQDp1Ft5kuOBm3kQ6UXUiXnIzwy1mn5tZng/D8csPOxWgxN6eRZxJCC5dj4aQQ2UGlGoQ12zoXWrOFstK0hmcxyizqzKoQxuAf "Python 3 – Try It Online") Ungolfed: ``` n,m=x+w-1,y+h-1 r=[*map(list,a)] for i in range(x,x+w): for j in range(y,y+h): p=u.index(a[j][i]) c=(p%3,p%9//3,p%27//9,p//27) A,B=j in(y,m),i in(x,n) P=(i<n*A,y<j*B,x<i*A,j<m*B) l=sum(max(P[o]*t,c[o])*3**o for o in range(4)) r[j][i]=u[l] ``` [Answer] ## JavaScript (ES6), 174 bytes ``` r=a.map((l,j)=>l.map((c,i)=>u[c=u.indexOf(c),g=n=>c/n%3<t&&g(n,c+=n),j==y|j==h&&(i>=x&i<w&&g(1),i>x&i<=w&&g(9)),i==x|i==w&&(j>=y&j<h&&g(27),j>y&j<=h&&g(3)),c]),w+=x-1,h+=y-1) ``` ``` a=` ┏┱─────┐ ┌┐ ┎──┲━┓ ┠╂─────┘ ││ ┃ ┗━┛ ┃┃ ││ ┃ ┠╂──┲━━┓ ┏━━━━┓ ││ ┌╂┰┐ ┃┃ ┗━━┩ ┃ ┃ └╆━┓ └╂┸┘ ┃┃ │ ┃ ┃ ┃ ┃ ┃ ┗┹─────┘ ┗━━━━┛ ┗━┛ ╹ `.match(/.+/g).map(s=>[...s]); x=4; y=1; w=24; h=4; t=1; u=" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"; r=a.map((l,j)=>l.map((c,i)=>u[c=u.indexOf(c),g=n=>c/n%3<t&&g(n,c+=n),j==y|j==h&&(i>=x&i<w&&g(1),i>x&i<=w&&g(9)),i==x|i==w&&(j>=y&j<h&&g(27),j>y&j<=h&&g(3)),c]),w+=x-1,h+=y-1) ;document.write(`<pre style="font-family:Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,sans-serif">${r.map(s=>s.join``).join`\n`}</pre>`); ``` ]
[Question] [ *This is a tips question for golfing in Python, which is on topic for main.* I'm looking for the shortest way to get all of the most common elements of a list in Python, in the shortest way possible. Here's what I've tried, assuming the list is in a variable called `l`: ``` from statistics import* mode(l) ``` This throws an error if there are multiple modes. ``` max(l,key=l.count) ``` This only returns 1 item, I need to get *all* the elements of greatest count. ``` from collections import* Counter(l).most_common() ``` This returns a list of tuples of `(element, count)`, sorted by count. From this I could pull all the elements whose corresponding count is equal to the first, but I don't see a way to golf this much better than: ``` from collections import* c=Counter(l).most_common() [s for s,i in c if i==c[0][1]] ``` I am sure there is a shorter way! Also, if it can be done without variable assignment or multiple uses of `l`, I can keep the rest of the code as a lambda expression to save more bytes. Edit: Per @Uriel's suggestion, we can do: ``` {s for s in l if l.count(s)==l.count(max(l,key=l.count))} ``` And I can alias `list.count` for a few bytes: ``` c=l.count;{s for s in l if c(s)==c(max(l,key=c))} ``` @Uriel pointed out that we can get a couple more bytes with `map`: ``` c=l.count;{s for s in l if c(s)==max(map(c,l))} ``` [Answer] How about this one? ``` c=l.count;{x for x in l if c(x)==max(map(c,l))} ``` Enclose in `[*...]` to get a list. ]
[Question] [ Yesterday, I left my sandwich on the table. When I got up today, there was a bite in it... Was it mine? I can't remember... # Problem: Take a representation of the sandwich and my bite pattern and tell me if it was my bite or not. # Examples: ### Example 1: My bite pattern: ``` .. . ``` Sandwich: ``` ##### .#### ..### ``` Output: ``` truthy ``` ### Example 2: My bite pattern: ``` .. .. ``` Sandwich: ``` ...## ..### .#### ``` Output: ``` falsy ``` ### Example 3: If there is at least 1 rotation that counts as truthy, the output is truthy. My bite pattern: ``` . . . ``` Sandwich: ``` ##. #.# .## ``` Output: Two possible rotations (biting in the northeast or southwest corner). ``` truthy ``` ### Some valid bites: ``` .. . ... . . . . . .. . . .. .. . . . ``` ### Some invalid bites: ``` .. ... . .. . . ``` # Rules: * My bite pattern orientation will always be for biting the northwest corner. And must be rotated to bite other corners; * There will always be 1 and only 1 bite in the sandwich; * The bite in the sandwich can be in any of the 4 cornes (rotated accordingly); * Bite patterns will always be symmetrical along the main diagonal; * Bite patterns will always be at least 1 wide and non empty; * The sandwich will always be a rectangle with width and height equal or greater than the width of my bite pattern; * In your input, you can choose any 2 distinct non-whitespace characters to represent the sandwich and the bite; * Spaces in the bite pattern means that my bite does not touch that part of the sandwich. [Answer] # [Ruby](https://www.ruby-lang.org/), 103 bytes 101 bytes ``` ->b,s{[a=s.map(&:reverse),s,s.reverse,a.reverse].any?{|t|b.zip(t).all?{|y,x|y==x.tr(?#,' ').rstrip}}} ``` [Try it online!](https://tio.run/nexus/ruby#fY/dCoMwDIXv9xSlhamQ5QEGnQ8iXlSoUHCjtGX4@@zOFB2bgrlo0sM5H0kt59ujAj8USnp8Kpte706/tfM6Aw8e1w@obSpRvbp8GMNYYW9sGjJUTbMIHbRjJ2WLwaW5gIQlGTofnLHTNM2VCZpJVnBEDhx5ebGm71WUBBWpW6eBHKwuKAfRWl52jH8IUuob3mBnkMXE4sP265AqcKWcMiLgcBCKuOHPWUfI/AE "Ruby – TIO Nexus") Saved 2 bytes by moving the assignment to the first use of a. Apparently Ruby is smart enough to not confuse the commas in the array definition and commas that would arise from simultaneous variable assignment (at least in this case :D) [Answer] # [Python 2](https://docs.python.org/2/), 134 bytes ``` b,s=input() a=[''.join(l[::-1])for l in s] print any(b==[l.replace('#',' ').rstrip()for l in x][:len(b)]for x in(a,a[::-1],s[::-1],s)) ``` Takes input as two lists of strings (one for each line). Assumes no trailing whitespace on the lines. [Try it online!](https://tio.run/nexus/python2#VY@xbsQgDIbn4ymsZDBIFOlWpIzXtQ@AGAilKhUiCKiae/oUkstVZbDNz8dv2y7vbhqGYZt5mXxM35UyYiaFKL4WH2lQUr5cNftYMgTwEYomKftYwcQ7nadJBZFdCsY6iiNyBGQil5p9on@fVq1kcJHOTHdtbRo13BzevJyZsa2NQmq@S3L5@fTBwbVVF7c6S22blBG3Wpcq3N5ebzkvWUIypWwKhWi9BWqucOyn387cC9TkhA5KdPn5etKd6kv8dxofzPhkYHfaIzwMG7TbHD0a9gs "Python 2 – TIO Nexus") **Examples:** ``` Input: ['..','.'],['#####','.####','..###'] (example 1) >True Input: ['..','..'],['...##','..###','.####'] (example 2) >False Input: ['',' .'],['#####','#.###','#####'] (no bite in top row) >True ``` [Answer] ## Python 2, 173 bytes [Try it online](https://tio.run/nexus/python2#VY0/C4MwEMX3fIqDDsnVKO0qzeLspONxQ4ItCDYVsRA/vTXGDg735/fu8W5ttTO9H7@zQlGb4elFZd52VIN9u85CKGl5yEJa38mL/EywwGvvvYfAGW0iX1WtWrox5rUKiNplRJzUKDlEFM05NFBZ5nfWFYpx6v0MrTEVbMFxpluC5gTrSvGj3quQrOnYovKnVLwhHR5Ibv4B) ``` S,b=input() L=len B=map(lambda x:[y<'.'and'#'or y for y in x]+['#']*(L(S[0])-L(x)),b+[[]]*(L(S)-L(b))) R=map(lambda x:x[::-1],B) print S==B or S==B[::-1]or S==R[::-1]or S==R ``` Takes input as two lists of lists of characters. First - sandwich Second - bite First it extends bite array to the size of sandwich array: ``` B=map(lambda x:[y<'.'and'#'or y for y in x]+['#']*(L(S[0])-L(x)),b+[[]]*(L(S)-L(b))) ``` `[y<'.'and'#'or y for y in x]` replaces all spaces to `#` `(L(S[0])-L(x)),b+[[]]*(L(S)-L(b))` calculates the number of missing element Then it compares all 4 rotation of this "extended" bite to the sandwich: ``` R=lambda:map(lambda x:x[::-1],B) print S==B or S==B[::-1]or S==R()or S==R()[::-1] print any(map(S.__eq__,[B,B[::-1],R(),R()[::-1]])) #longer but pretty ``` lambda R is used to mirror list of lists horizontally In the linked example sandwich is: ``` ##. #.# ### ``` And bite is: ``` . . ``` ]
[Question] [ The user will hide, and the computer will try to find them. First, the program will take an input, for the size of the grid. Like 5x5, 10x10, 15x15, etc. The grid won't always be a perfect square. The grid is sort of like a chessboard: ``` _______________________________ | | | | | | | A1 | | | | | A |_____|_____|_____|_____|_____| | | | | | | | | B2 | | | | B |_____|_____|_____|_____|_____| | | | | | | | | | C3 | | | C |_____|_____|_____|_____|_____| | | | | | | | | | | D4 | | D |_____|_____|_____|_____|_____| | | | | | | | | | | | E5 | E |_____|_____|_____|_____|_____| 1 2 3 4 5 ``` Now, the user will pick a square, such as `B2` (without telling the computer) The computer will start guessing squares. If it picks the correct square, the user will respond with `y`. If not, they will input the direction their tile is from the one picked (N, NE, E, SE, S, SW, W). So if the user picked `B2`, and the computer guessed `C3`, the user would input `NW`. Here is an example of the outputs and inputs: ``` Grid? 5x5 C3? NW C2? N B2? y ``` # Scoring: This will be scored a little differently than a normal challenge. The winner is the program that takes lowest number of guesses (on average) it takes to guess the correct square. The test cases to be averaged will be all of the possible squares in a 5x5 and then in a 10x10. However, it must also work with every pattern of grid up to 26 rows (i.e. 5x8, 6x2, 20x5, etc.). Please include a way for it to be tested, such as a JSFiddle. And lastly, in case of a tie, the shortest program wins. [Answer] # [Python 3.6](https://docs.python.org/3.6/), ~~466~~ ~~398~~ 392 bytes, minimax ``` x, y = 1, 1 w, h = [int(x) for x in input('Grid?\n').split('x')] def split_factor(a, b): N = b-y W = a-x S = h+~N E = w+~W return max(1, N, W, S, E, N*W, S*W, S*E, N*E) def move(a, b): *Z, = zip([a, x, a, a+1, x, x, a+1, a+1], [y, b, b+1, b, y, b+1, b+1, y], [1, a-x, 1, w+x+~a, a-x, a-x, w+x+~a, w+x+~a], [b-y, 1, h+y+~b, 1, b-y, h+y+~b, h+y+~b, b-y]) return Z[['N', 'W', 'S', 'E', 'NW', 'SW', 'SE', 'NE'].index(d)] d = '' while d != 'y': print() splits = {(a, b): split_factor(a, b) for a in range(x, x+w) for b in range(y, y+h)} a, b = min(splits, key=splits.get) d = input(f'{a}{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"[b]}?\n') x, y, w, h = move(a, b) ``` Input and output should be in the form shown in the example. This finds the square with the minimal "split factor"--which is the largest remaining area that can result from the player's answer (i.e. NW, E, y, etc.)--and guesses that. Yes, that's always the center of the remaining area in this game, but [this technique](https://en.wikipedia.org/wiki/Minimax) of minimizing the worst-case will work more generally in similar games with different rules. Unreadable version: ``` x=y=d=1 w,h=map(int,input('Grid?\n').split('x')) while d!='y':print();s={(a,b):max(b-y,h+y+~b)*max(w+x+~a,a-x)for a in range(x,x+w)for b in range(y,y+h)};a,b=min(s,key=s.get);d=input(f'{a}{chr(64+b)}?\n');*z,=zip([a+1,x,a+1,x,a,a,a+1,x],[b+1,b+1,y,y,b+1,y,b,b],[w+x+~a,a-x,w+x+~a,a-x,1,1,w+x+~a,a-x],[h+y+~b,h+y+~b,b-y,b-y,h+y+~b,b-y,1,1]);x,y,w,h=z[~'WENS'.find(d)or-'NWNESWSE'.find(d)//2-5] ``` [Answer] # Mathematica, optimal behavior on test cases, 260 bytes ``` For[a=f=1;{c,h}=Input@Grid;z=Characters;t=<|Thread[z@#->#2]|>&;r="";v=Floor[+##/2]&;b:=a~v~c;g:=f~v~h,r!="y",r=Input[g Alphabet[][[b]]];{{a,c},{f,h}}={t["NSu",{{a,b-1},{b+1,c},{b,b}}]@#,t["uWX",{{g,g},{f,g-1},{g+1,h}}]@#2}&@@Sort[z@r/.{c_}:>{c,"u"}/."E"->"X"]] ``` This program can be tested by cutting and pasting the above code into the [Wolfram Cloud](http://sandbox.open.wolframcloud.com). (Test quickly, though: I think there's a time limit for each program run.) The program's guesses look like `2 c` instead of `C2`, but otherwise it runs according to the spec above. The grid must be input as an ordered pair of integers, like `{26,100}`, and responses to the program's guesses must be input as strings, like `"NE"` or `"y"`. The program keeps track of the smallest and largest row number and column number that is consistent with the inputs so far, and always guesses the center point of the subgrid of possibilities (rounding NW). The program is deterministic, so it's easy to compute the number of guesses it requires on average over a fixed grid. On a 10x10 grid, the program requires 1 guess for a single square, 2 guesses for eight squares, 3 guesses for 64 squares, and 4 guesses for the remaining 27 squares, for an average of 3.17; and this is the theoretical minimum, given how many 1-guess, 2-guess, etc. sequences can lead to correct guesses. Indeed, the program should achieve the theoretical minimum on any size grid for similar reasons. (On a 5x5 grid, the average number of guesses is 2.6.) A little code explanation, although it's fairly straightforward other than the golfingness. (I exchanged the order of some initializing statements for expository purposes—no effect on byte count.) ``` 1 For[a = f = 1; z = Characters; t = <|Thread[z@# -> #2]|> &; 2 v = Floor[+##/2] &; b := a~v~c; g := f~v~h; 3 r = ""; {c, h} = Input@Grid, 4 r != "y", 5 r = Input[g Alphabet[][[b]]]; 6 {{a, c}, {f, h}} = {t["NSu", {{a, b - 1}, {b + 1, c}, {b, b}}]@#, 7 t["uWX", {{g, g}, {f, g - 1}, {g + 1, h}}]@#2} & @@ 8 Sort[z@r /. {c_} :> {c, "u"} /. "E" -> "X"] ] ``` Lines 1-3 initialize the `For` loop, which actually is just a `While` loop in disguise, so hey, two fewer bytes. The possible row-number and column-number ranges at any moment is stored in `{{a, c}, {f, h}}`, and the centered guess in that subgrid is computed by the functions `{b, g}` defined in line 2. Line 3 initializes the max-row `c` and max-column `h` from user input, and also initializes `r` which is the loop-tested variable and also the subsequent user inputs. While the test on line 4 is satisfied, line 5 gets input from the user, where the prompt comes from the current guess `{b, g}` (`Alphabet[][[b]]]` converts the row number to a letter). Then lines 6-8 update the subgrid-of-possibilities (and hence implicitly the next guess). For example, `t["NSu", {{a, b - 1}, {b + 1, c}, {b, b}}]` (given the definition of `t` on line 1) expands to ``` <| "N" -> {a, b - 1}, "S" -> {b + 1, c}, "u" -> {b, b}|> ``` where you can see the min-row and max-row numbers being updated according to the user's last input. Line 8 converts any possible input to an ordered pair of characters of the form `{ "N" | "S" | "u", "u" | "W" | "X"}`; here `"u"` stands for a correct row or column, and `"X"` stands for East (just to allow `Sort` to work nicely). When the user finally inputs `"y"`, these lines throw an error, but then the loop-test fails and the error is never propogated (the program simply halts anyway). [Answer] ## Batch, divide-and-conquer ``` @echo off set z = ABCDEFGHIJKLMNOPQRSTUVWXYZ set /p g = Grid? set /a w = 0, n = 0, e = %g :x= + 1, s = % + 1 :l set /a x = (w + e) / 2, y = (n + s) / 2 call set c = %%z :~%y%,1%% set /p g = %c %%x%? if %g :w=.% == %g % set /a w = x if %g :n=.% == %g % set /a n = y if %g :e=.% == %g % set /a e = x if %g :s=.% == %g % set /a s = y if %g :y=.% == %g % goto l ``` Works by creating the bounding box of the the area still to be searched. The next guess is always the centre of the box. For those compass points that are not included in the response, the box is reduced in that direction. For example for a response of `N`, the left, right and bottom of the box are set to the guessed square. At 369 bytes I'm not expecting to beat anybody so I've left the spaces in for readibility. ]
[Question] [ We are putting balls into a fixed number **a** bins. These bins begin empty. ``` Empty bin (a=4): 0 0 0 0 ``` And one by one we add balls to the bins. ``` 0 0 0 1 or 0 0 1 0 or 0 1 0 0 or 1 0 0 0 ``` We need a quick way to loop over all the possible states the bins take, without duplicates and without missing any and we don't want to enumerate all the possible bins. So instead we assign each bin-configuration an index. We assign the index by sorting the possible configurations in a specific way: 1. Sort ascending by sum: so first `0 0 0 0`, then the possible configurations with 1 ball added, then 2, etc. 2. Then sort within each sum in ascending order, from the first bin to the last: ``` 0 0 0 2 0 0 1 1 0 0 2 0 0 1 0 1 0 1 1 0 0 2 0 0 etc ``` 3. The index is then assigned ascending through this list: ``` 0 0 0 0 -> 1 0 0 0 1 -> 2 0 0 1 0 -> 3 0 1 0 0 -> 4 1 0 0 0 -> 5 0 0 0 2 -> 6 0 0 1 1 -> 7 0 0 2 0 -> 8 0 1 0 1 -> 9 0 1 1 0 -> 10 0 2 0 0 -> 11 ``` ## Rules Create a function or program that takes a list of any size with non-negative integers and print or output its index. You can assume **a** to be at least 2. Shortest code wins. You may use 0-indexed output or 1-indexed, but specify which you use. NB: all examples here are 1-indexed. ## Example code Not golfed, in R: ``` nodetoindex <- function(node){ a <- length(node) t <- sum(node) if(t == 0) return(1) index <- choose(t-1 + a, a) while(sum(node) != 0){ x <- node[1] sumrest <- sum(node) if(x == 0){ node <- node[-1] next } a <- length(node[-1]) index <- index + choose(sumrest + a, a) - choose(sumrest - x + a, a) node <- node[-1] } return(index + 1) } ``` ## Test cases ``` 10 10 10 10 -> 130571 3 1 4 1 5 9 -> 424407 2 9 -> 69 0 0 0 -> 1 0 0 1 -> 2 0 0 0 0 0 0 -> 1 1 0 0 0 0 1 -> 23 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` S0rṗLSÞi ``` [Try it online!](https://tio.run/nexus/jelly#@x9sUPRw53Sf4MPzMv9XPWrcFmWtdLj9UdMa9///o410FCxjdRSiDXQUQAjBNEQShSOQmCGqmGEsAA "Jelly – TIO Nexus") Brute-force solution. The first test case is too much for TIO, but I've verified it locally on my laptop. The second test case requires too much RAM, even for my desktop computer. ### How it works ``` S0rṗLSÞi Main link. Argument: A (array) S Compute the sum s of A. 0r Create the range [0, ..., s]. L Yield the length l of A. ṗ Cartesian power; yield the array of all l-tuples over [0, ..., s], in lexicographical order. SÞ Sort the l-tuples by their sums. The sorting mechanism is stable, so l-tuples with the same sum are still ordered lexicographically. i Find the index of A in the generated array of tuples. ``` [Answer] ## Clojure, 152 bytes ``` #(loop[v[(vec(repeat(count %)0))]i 1](if-let[r((zipmap v(range))%)](+ r i)(recur(sort(set(for[v v i(range(count v))](update v i inc))))(+ i(count v))))) ``` Not as easy as I thought. Less golfed version: ``` (def f (fn[t](loop[v[(vec(repeat(count t)0))]i 1] (if-let[r((zipmap v(range))t)](+ r i) (recur (sort-by (fn[v][(apply + v)v]) (set(for[v v i(range(count v))](update v i inc)))) (+ i(count v))))))) ``` Loops over current states `v`, creates a hash-map from elements of `v` to their rank, if the searched state is found then its rank is returned (+ the number of previously seen states). If not found then recurses with a new set of possible states. Oh actually we don't need that custom sorting function as all states within each loop has identical sum. This isn't as slow as I expected as `[3 1 4 1 5 9]` took only 2.6 seconds. [Answer] # Mathematica, 50 bytes A port of [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/102381/56178). ``` 0~Range~Tr@#~Tuples~Length@#~SortBy~Tr~Position~#& ``` Unnamed function taking a list of integers as input, and returning a depth-2 list with a single integer as output; for example, the input for the last test case is `{1,0,0,0,0,1}` and the output is `{{23}}`. A slightly ungolfed version is: ``` Position[SortBy[Tuples[Range[0,Tr[#]],Length[#]],Tr],#]& ``` Often we can save individual bytes in Mathematica by using prefix notation (`function@n` instead of `function[n]`) and infix notation (`a~function~b` instead of `function[a,b]`). This only works, however, when the resulting code happens to mesh well with Mathematica's intrinsic precedence order for applying functions. I was kind of amazed here that, with six sets of square brackets, it actually worked to remove *all* of them and save six bytes with the (pleasantly bracketless) submitted code. ]
[Question] [ Output a full formal poof of such statements such as `1+2=3`, `2+2=2*(1+1)` etc. # Introuction If you know Peano Arithmetic you can probably skip this section. Here's how we define the Natural Numbers: ``` (Axiom 1) 0 is a number (Axiom 2) If `x` is a number, the `S(x)`, the successor of `x`, is a number. ``` Hence, for example `S(S(S(0)))` is a number. You can use any equivalent representation in your code. For example, all of these are valid: ``` 0 "" 0 () ! 1 "#" S(0) (()) !' 2 "##" S(S(0)) ((())) !'' 3 "###" S(S(S(0))) (((()))) !''' ... etc ``` We can extend the rules to define addition as follows. ``` (Rule 1) X+0 = X (Rule 2) X+S(Y)=S(X)+Y ``` With this we can prove 2+2=4 as follows ``` S(S(0)) + S(S(0)) = 2 + 2 [Rule 2 with X=S(S(0)), Y=S(0)] S(S(S(0))) + S(0) = 3 + 1 [Rule 2 with X=S(S(S(0))), Y=0] S(S(S(S(0)))) + 0 = 4 + 0 [Rule 1 with X=S(S(S(S(0)))) S(S(S(S(0)))) = 4 ``` We can extend these rules to define multiplication as follows ``` (Rule 3) X*0 = 0 (Rule 4) X*S(Y) = (X*Y) + X ``` Although to allow this we need to define the structural role of parentheses. ``` (Axiom 3) If X is a number, (X) is the same number. ``` Addition and multiplication operators are strictly binary and parentheses must always be explicit. `A+B+C` is not well-defined, but `(A+B)+C` and `A+(B+C)` are. # Example Now we have enough to prove a theorem about multiplication: 2+2=2\*2 ``` 2 + 2 (2) + 2 (0 + 2) + 2 ((0*2) + 2) + 2 (1*2) + 2 2*2 ``` # Requirements A *proof that `A=B`* is a list expressions such that: * the first is `A`, * the last is `B`, and * each expression in the list apart from the first can obtained from the previous by transforming it under one of the rules. Your program will take **two valid expressions as input**, each expression contains numbers, addition, multiplication, and parentheses as defined above. Your program will output a proof, a list as defined above, that the two expressions are equal, if such a proof exists. If the two expressions are not equal, your program will output nothing. Proving or disproving is always possible in a finite number of steps, because each expression can be reduced to a single number and these numbers can be trivially tested for equality. If the input expressions are not valid (e.g. unbalanced parentheses, contains non-numbers, or non-binary operators) then your program should exit with error, throw an exception, print an error, or otherwise produce some observable behaviour *which is distinct from the case in which the inputs are valid but non-equal*. In summary, the normal output for admissible inputs is a list of equal numbers, including the inputs, which is produced by the following rules. ``` (Axiom 1) 0 is a number (Axiom 2) If `x` is a number, the `S(x)`, the successor of `x`, is a number. (Axiom 3) If X is a number, (X) is the same number (Rule 1) X+0 = X (Rule 2) X+S(Y)=S(X)+Y (Rule 3) X*0 = 0 (Rule 4) X*S(Y) = (X*Y) + X (Rule 5) X = (X) (Axiom 3 expressed as a transformation rule.) ``` Any suitable representation of the numbers in the input and output is allowed, e.g. `0=""=()`, `3="###"=(((())))`, etc. Whitespace is irrelevant. Rules can, of course, be applied in either direction. Your program does not have to output which rule is used, just the expression produced by its action on the previous expression. Shortest code wins. [Answer] # Perl, 166 + 1 bytes Run with `-p` (1 byte penalty). ``` $r='\((S*)';(@b,@a)=@a;push@a,$_ while+s/\+S/S+/||s/$r\+\)/$1/||s/$r\*\)//||s/$r\*S(S*)/(($1*$2)+$1/||s/$r\)/$1/;$\.=/[^S]./s;$_=$b[-1]eq$a[-1]?join'',@b,reverse@a:"" ``` More readable: ``` # implicit: read a line of input into $_ # we leave the newline on $r = '\((S*)'; # we use this regex fragment a lot, factor it out (@b, @a) = @a; # set @b to @a, @a to empty push @a, $_ while # each time round the loop, append $_ to @a +s/\+S/S+/|| # rule 2: change "+S" to "S+" s/$r\+\)/$1/|| # rule 1: change "(X+0)" to "X" s/$r\*\)//|| # rule 3: change "(X*0)" to "" s/$r\*S(S*)/(($1*$2)+$1/|| # rule 4: change "(X*Y" to "((X*Y)+X" s/$r\)/$1/; # rule 5: change "(X) to "X" $\.=/[^S]./s; # append a 1 to the newline character if we # see any non-S followed by anything $_=$b[-1]eq$a[-1]? # if @b and @a end the same way join'',@b,reverse@a # then $_ becomes @b followed by (@a backwards) :"" # otherwise empty $_ # implicit: output $_ ``` The input format expresses numbers in unary as strings of `S`, and requires the two inputs on separate lines (each followed by a newline, and an EOF after both are seen). I interpreted the question as requiring that parentheses should be literally `(` `)` and addition/multiplication should be literally `+` `*`; I can save a few bytes through less escaping if I'm allowed to make different choices. The algorithm actually compares the first line of input with an empty line, the second with the first, the third with the second, and so on. This fulfils the requirements of the question. Here's an example run: My input: ``` (SS+SS) (SS*SS) ``` Program output: ``` (SSS+S) (SSSS+) SSSS SSSS (SSSS+) ((SS+)SS+) (((SS*)SS+)SS+) (((SS*)S+S)SS+) (((SS*)+SS)SS+) ((SS*S)SS+) ((SS*S)S+S) ((SS*S)+SS) ``` The duplicated `SSSS` in the middle is annoying but I decided it didn't violate the specification, and it's fewer bytes to leave it in. On invalid input, I append `1` to the newline character, so you get stray `1`s sprinkled in at the end of the output. ]
[Question] [ Mr Short likes to play chess. Mr Short is also a very traditional man. Hence, Mr Short is disturbed by the recent trend of using [Algebraic notation](https://en.wikipedia.org/wiki/Algebraic_notation_(chess)) in modern chess, and he would rather use [Descriptive notation](https://en.wikipedia.org/wiki/Descriptive_notation), like his father and his father's father before him. # Note To simplify this challenge, I chose not to deal with disambiguaties (as in, when two pieces can move to the same square, or can capture the same piece.) Also there is no dealing with en passant, promotion, or Castling. # Algebraic notation for the uninitiated * The board squares are numbered from `a1` at the bottom left to `h8` as the top right. The letters represent the files (columns) while the numbers represent the ranks (rows). The white King is placed in the beginning of the game at the square `e1`. * A move consists of the piece that moved + the destination square. For example, a King moving to `e2` would be `Ke2`. * If the piece that had moved is a Pawn, the piece letter is omitted. For example, the starting move Pawn to `e4` is written as `e4`. * If the move is a capture, then the `x` letter is inserted between the piece and the destination square. For example, a Queen capturing at `f7` is annotated as `Qxf7`. * If the capturing piece is a Pawn, since it moves diagonally, the notation records the file the Pawn originated from. For example, when the Pawn at `c4` captures a piece at `d5`, the move is annotated as `cxd5`. * Piece symbols are `K` for King, `Q` for Queen, `B` for Bishop, `N` for Knight, and `R` for Rook. Pawns have no symbols. * Other annotations include `+` for check, and `#` for checkmate. A Pawn moving to f7 and giving check is `f7+`. Note lack of space. # Descriptive notation for the uninitiated * The files are described by the piece that starts on it. For example, what would be the `e` file in Algebraic, becomes the King file, or, for short, `K`. The other files are marked by their side, then the piece. So file `h` is the King's Rook's file, or `KR`. * The ranks are numbered from the point of view of the moving player. What would be the fourth rank in Algebraic, is the fourth rank for white, but the *fifth* rank for black. * It follows that the square `e4` is `K4` for the white player and `K5` for the black player. The square `f7` is `KB7` for the white player and `KB2` for the black player. * A move is annotated by the piece moving, then a dash, then the target square. So a Pawn moving to `K4` is `P-K4`. A Queen moving to `KR5` is `Q-KR5`. * A capture is annotated by the capturing piece, then `x`, then the captured piece. Therefore a Bishop capturing a Pawn is `BxP`. **Usually you need to mark *which* Pawn is being captured, but ignore this for sake of simplicity.** * Piece symbols are `K` for King, `Q` for Queen, `B` for Bishop, `Kt` for Knight (note the different symbol), `R` for Rook, and `P` for Pawn. * Other annotations include `ch` for check and `mate` for checkmate. A Pawn moving to `KB7` and giving check is `P-KB7 ch`. Note the space. # Input A string of algebraic notation moves, delineated by spaces. There are no move numbers. For example, the [Fool's mate](https://en.wikipedia.org/wiki/Fool%27s_mate) goes like this: ``` f3 e5 g4 Qh4# ``` Or the game Teed vs Delmar, from the same Wikipedia page: ``` d4 f5 Bg5 h6 Bf4 g5 Bg3 f4 e3 h5 Bd3 Rh6 Qxh5+ Rxh5 Bg6# ``` The [Immortal game](https://en.wikipedia.org/wiki/Immortal_Game). ``` e4 e5 f4 exf4 Bc4 Qh4+ Kf1 b5 Bxb5 Nf6 Nf3 Qh6 d3 Nh5 Nh4 Qg5 Nf5 c6 g4 Nf6 Rg1 cxb5 h4 Qg6 h5 Qg5 Qf3 Ng8 Bxf4 Qf6 Nc3 Bc5 Nd5 Qxb2 Bd6 Bxg1 e5 Qxa1+ Ke2 Na6 Nxg7+ Kd8 Qf6+ Nxf6 Be7# ``` You may assume that input is always a valid game. All moves are in the correct order, and no extraneous data is present. **No moves will include disambiguation**. For example, [The Evergreen game](https://en.wikipedia.org/wiki/Evergreen_Game) despite being, obviously, a valid game, is not going to be input due to the 19th move, `Rad1`. You may also assume that all input move lists start from the starting position. # Output A move list, with a similar format, in Descriptive notation. For example, the Fool's mate: ``` P-KB3 P-K4 P-KKt4 Q-KR5 mate ``` Teed vs Delmar: ``` P-Q4 P-KB4 B-KKt5 P-KR3 B-KB4 P-KKt4 B-KKt3 P-KB5 P-K3 P-KR4 B-Q3 R-KR3 QxP ch RxQ B-KKt6 mate ``` The Immortal Game: ``` P-K4 P-K4 P-KB4 PxP B-QB4 Q-KR5 ch K-KB1 P-QKt4 BxP Kt-KB3 Kt-KB3 Q-KR3 P-Q3 Kt-KR4 Kt-KR4 Q-KKt4 Kt-KB5 P-QB3 P-KKt4 Kt-KB4 R-KKt1 PxB P-KR4 Q-KKt3 P-KR5 Q-KKt4 Q-KB3 Kt-KKt1 BxP Q-KB3 Kt-QB3 B-QB4 Kt-Q5 QxP B-Q6 BxR P-K5 QxR ch K-K2 Kt-QR3 KtxP ch K-Q1 Q-KB6 ch KtxQ B-K7 mate ``` This is not the simplest Descriptive notation possible, since sometimes you don't need to specify which Knight file was moved to (as in, `Q-KKt4` could be written as `Q-Kt4` since the move `Q-QKt4` is impossible.) The move `BxP` is ambiguous (which pawn: should be `BxQKtP`), but Mr Short doesn't care about that too much. You may consider these your test cases. Note: I wrote these by hand. If you catch any glaring mistakes, please let me know. # Rules and Scoring * Standard rules apply : program with output to stdout, or function. Nothing to stderr. Standard loopholes are forbidden. * Please link to a site where we can test your code. * Code golf: shortest code wins. # In Conclusion This is my first challenge, so I *probably* made some noobish errors. Feedback on the question (in the comments, obviously) is appreciated. [Answer] ## Batch, 588 bytes ``` @echo off for %%r in (a.R b.Kt c.B d.Q e.K f.B g.Kt h.R)do set %%~nr1=%%~xr&set %%~nr8=%%~xr for %%r in (a b c d e f g h)do set %%r2=.P&set %%r7=.P set s= set a= :l set m=%1 set c= for %%r in (ch.+ mate.#) do if .%m:~-1%==%%~xr set c= %%~nr&set m=%m:~,-1% set/ab=(a^^%m:~-1%-1)+1,a=7-a set p=%m:~0,1% for %%r in (a b c d e f g h)do if %p%==%%r set p=P for %%r in (QR.a QKt.b QB.c Q.d K.e KB.f KKt.g KR.h)do if .%m:~-2,1%==%%~xr set d=-%%~nr%b% if %m:~-3,1%==x call set d=x%%%m:~-2%:~1%% set %m:~-2%=.%p:N=Kt% set s=%s% %p:N=Kt%%d%%c% shift if not "%1"=="" goto l echo%s% ``` `s` is the output string. `m` is the current move (moves are taken as command-line parameters). `a` is the current player (0 for White, 7 for Black). `b` is the row as seen from the point of view of the current player. `c` is the `ch` or `mate` flag. `p` is the current piece. If there is no piece (i.e. a lowercase letter `a-h`) then `P` is substituted. (The `N` to `Kt` substitution is done later to save bytes.) The destination column is then looked up in a dictionary. However if the move is actually a capture then the destination becomes an `x` followed by the piece previously on that square. Either way the destination square is then set to the piece that just moved there. The moves are accumulated until there are no more parameters and then they are printed. The variables `a1`...`h8` are used to store the last seen piece. The `.` prefix is there because of the way I initialise the back row; it's hard to loop over two variables at once in Batch unless I'm allowed to begin one with a `.`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 473 bytes ``` (n,c=(X=>[...'abcdefgh'].map(a=>[...'12345678'].map(b=>X[a+b]=a<'c'|a>'f'?a<'b'|a>'g'?['R','Kt',...'BQKB','Kt','R'][--b]:'P':''))&&X)({}),g=s=>s?s=='N'?'Kt':s:'P')=>n.split` `.map((e,i)=>(Q=c[S=e.slice(I=e.search(/[a-h](?!x)/),I+2)],((c[S]=g(e.split(/[a-hx]/)[0]))+(e[Z='includes']`x`?'x'+Q:'-'+((S=e[I])>'d'?'K'+['','B','Kt','R']['efgh'.indexOf(S)]:'Q'+['R','Kt','B','']['abcd'.indexOf(S)])+((Y=e[e.search(/\d/)])&&i%2?9-Y:Y))))+(e[Z]`#`?' mate':e[Z]`+`?' ch':'')).join` ` ``` [Try it online!](https://tio.run/##VVDbbtswDP0VrcVCCb5kSRwnMyYb8FsQIJ3bl2SeAMuyfClcJ6jTwcC2b08pJ8PQBxHi4Tk8JJ/lL9mr1@Z0drpjoS8lv9DOVpzueZi6rgsyV4UuqxqE@yJPVN7g2XzhLf3V@gbnPNyn0soFl99AwR8ZQgkR/vPxX0GUwiPYsD2DbeRxso1vKeIidZxcBPAdAgDGJpM9o7//MrviPQ/7qOccdhAZdtAbFuNh5/antjlnJBv9qbYbRGnCVfrEtdu3jdJ0Y35avqqaTlPp1IJGnwY2ZfbGmjNhU4pkwSuqr82upEFMWfpFMGZRnf7g0HSqfSt0DyIbsggGsJIAHLAoRaN0I1gIhRkOrBRwmw9rwXg5t@kKPTyU9Inhkokh/rvFSDdEc@YPRLSnBzT4v8HPYorwZNJ8nkdfnUNwYOw2pMjucTLyIs8agjG3TK7q6z3d52PT4aUu6tj1x1a77bGiJb3THtFLUmIcMMTKI0ntWWRbzki@JPGAYVf6@BZY8EmxILsaoRp5lSktifJJ5Y2kx2pGlFGMVZ8g0ZAS1O6qNTZDh8Q0Uwt0QnWBxSGfk7jwsYpqbQA5Q389JzuJ1KFaYVasjdDCFOWxXt3fMXZ5Bw "JavaScript (Node.js) – Try It Online") Output is different to the testcase, but it seems like there is an error the OP made. Only 1 mistake, though. ## How Quite simple for such a long program. Creates an object, `c`, which stores the position of every piece. Handling captures is simple, simply overwrite the square. Inside the `map` function, we assign `Q` to the target square's piece before overwriting, then refer to it when a capture is seen. If not a capture, then index into an array to find the correct file (correct me if "file" is not the right term as I'm no expert in chess) and determine the number (9-Y if black turn, Y if white term). Also a few simple invocations of `includes` and a few extra ternaries add the `ch`s and `mate`s at the end. ]
[Question] [ **A Latin square is a square that has no repeated symbols in either the X or Y columns**. For example: ``` ABCD DABC CDAB BCDA ``` is one such square. Notice how every column and row contains a permutation of the same 4 letters. However, our Latin square has a problem: **If I were to rotate the second row (`DABC`) 1 to the left, I'd end up with `ABCD`, which is identical to the permutation above it.** If it is *impossible* to rotate any 1 column/row and obtain another column/row, then we consider the square to be **rotation safe**. For example: ``` ABCD BDAC CADB DCBA ``` is rotation safe. The grid has the following properties: 1. **Point [0,N] uses the Nth symbol** 2. **Point [0,N] and [N,0] are always the same symbol**. (I'd like to also say that [x,y] and [y,x] are also always the same letter, but I can't prove it) **Your task is to print out 1 rotation-safe Latin square, when passed N.** I don't care if you output letters, numbers, a list, or a 2D array. **If you use numbers, the top column and row must be `0,1,2,3,...` (in that order). If you use letters, then it must be `A,B,C,D,....`** For example, if your input was 4, you should either print: ``` 0,1,2,3 0,1,2,3 1,3,0,2 or 1,0,3,2 2,0,3,1 2,3,1,0 3,2,1,0 3,2,0,1 ``` There are no rotation-safe Latin squares of size less than 4. I don't care what your program does if N is less than 4. For the curious, the number of rotation-safe squares is (starting at 4): `2,5,5906,(too long to calculate)` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to make answers as short as possible in your favorite language! [Answer] # Pyth - 29 bytes Brute force. ``` hf&!@JsCBTsm.>RdJStQ.A{IMJ^.p ``` Does not finish online even for `n=4`, but you can try it out locally, or [run this modified version online for one more byte](http://pyth.herokuapp.com/?code=hf%26.A%7BIMCT%21%40JsCBTsm.%3ERdJStQ%5E.p&input=4&debug=0). [Answer] # Sqlserver 2012 - 918 bytes On my box this runs for @k = 5, although it takes 16 seconds. This is code building code(watch out Skynet, you have competition) Is there a price for the longest script? ``` DECLARE @k int = 4; DECLARE @t VARCHAR(max)='WITH C as(SELECT top '+left(@k,1)+'row_number()over(order by 1/0)n FROM sys.messages),D(nÆ)as(SELECT concat(~),~ FROM Ø WHERE |)SELECT top 1~ FROM Å WHERE 1=1',@ varchar(999)=''SELECT @+=','+CHAR(x+65)FROM(values(0),(1),(2),(3),(4),(5))x(x)WHERE x<@k SELECT @t=REPLACE(REPLACE(REPLACE(REPLACE(@t,'Æ',@),'Ø',STUFF(REPLACE(@,',',',C '),1,1,'')),'Å',STUFF(REPLACE(@,',',',D '),1,1,'')),'~',STUFF(REPLACE(@,',','.n,'),1,3,'')+'.n'),@='';WITH C as(SELECT top(@k)x FROM(values(0),(1),(2),(3),(4),(5))x(x))SELECT @+=' AND '+char(65+C.x)+'.n<>'+char(65+D.x)+'.n'FROM c,c d WHERE C.x<D.x SELECT @t=REPLACE(@t,'|',STUFF(@,1,4,''));WITH A as(SELECT top(@k)x FROM(values(65),(66),(67),(68),(69),(70))x(x))SELECT @t+='AND '+char(A.x)+'.'+char(C.x)+'<>'+CHAR(B.x)+'.'+char(C.x)+' AND '+char(A.x)+'.n+'+char(A.x)+'.n'+' not like''%''+'+char(B.x)+'.n+''%'''FROM A,A B,A C WHERE A.x<>B.x and C.x<>B.x EXEC(@t) ``` [Try online!](https://data.stackexchange.com/stackoverflow/query/485215/rotation-safe-latin-squares) ]
[Question] [ [Subleq](https://esolangs.org/wiki/Subleq) is a programming language with **only one** instruction. Each instruction contains 3 parameters. Code and data space is the same. How it works: ``` A B C ``` A, B and C are signed ints. Instructions are executed in the next way: ``` *B = *B - *A if(*B <= 0) goto C; ``` One post is one tip. Write your tips for Subleq here! [Online interpreter, assembler and C to Subleq converter](http://mazonka.com/subleq/online/hsqjs.cgi) [Answer] # Third Argument in Output Command is Extra Memory Subleq specifies output with the three word command `x -1 y`, where x is the address of the value to be output. Unlike other Subleq commands, execution will proceed to the next command in all cases and `y` is ignored. This means it is available to be used for memory. For example `0:2 -1 65` will print the "A" (CHAR(65)) stored in 2: and then proceed to 3:. ]
[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/54877/edit). Closed 8 years ago. [Improve this question](/posts/54877/edit) ## Challenge: Your challenge (should you choose to accept it) is to compress and decompress the 5MB "*Complete Works of William Shakespeare*" as found here: <http://www.gutenberg.org/cache/epub/100/pg100.txt> (MD5: `a810f89e9f8e213aebd06b9f8c5157d8`) ## Rules: * You **must** take input via `STDIN` and output via `STDOUT`... * ...and you **must** provide an identical decompressed result to the input. + (This is to say you **must** be able to `cat inpt.txt | ./cmprss | ./dcmpress | md5` and get the *same* MD5 as above.) + (Anything via `STDERR` is to be discarded.) * You **must** use less than 2048 characters for your total source code. + *(This is **not** code-golf. You are **not** being scored based on length of source-code. This is was just a rule to keep things finite.)* + (Take the concatenated length of all source code if you have split it out.) * You **must** be able to (theoretically) process similar plain-text inputs too. + (e.g. hard coding a mechanism which is *only* capable of outputting the provided *Shakespeare* input is unacceptable.) + (The compressed size of other documents is irrelevant - provided the decompressed result is identical to the alternative input.) * You **may** use any choice of language(s). + (e.g. feel free to compress using `awk` and decompress using `java`) * You **may** write two separate programs or combine them with some form of "switch" as you please. + (There must be clear demonstrations of how to invoke both the compression and decompression modes) * You may **not** use any external commands (e.g. through `exec()`). + (If you are using a shell language - sorry. You'll have to make do with built-ins. You're welcome to post an "unacceptable" answer for the sake of sharing and enjoyment - but it won't be judged!) * You may **not** use any built-in or library provided functions who's stated purpose is to compress data (like `gz`, etc) + (Altering the encoding is not considered compression in this context. Some discretion may be applied here. Feel free to argue the acceptableness of your solution in the submission.) * Please try to have fun if choose to participate! All good competitions have an objective definition of winning; ergo: * Provided all rules are adhered to, the smallest **compressed** output (in `STDOUT` bytes) wins. + (Report your output please via `./cmprss | wc -c`) * In the event of a draw (identical output sizes), the most community up-voted wins. * In the event of a second draw (identical community up-votes), I'll pick a winner based on completely subjective examination of elegance and pure genius. `;-)` ## How to submit: Please format your entry using this template: ``` <language>, <compressed_size> ----------------------------- <description> (Detail is encouraged!) <CODE... ...> <run instructions> ``` I would encourage readers and submitters to converse through comments - I believe there's real opportunity for people to learn and become better programmers through codegolf.stack. ## Winning: I'm away on vacation soon: I may (or may not) be monitoring submissions over the next few weeks and will draw the challenge to a close on the 19th September. I hope this offers a good opportunity for people to think and submit - and for a positive sharing of techniques and ideas. If you've learned something new from participating (as a reader or submitter) please leave a comment of encouragement. [Answer] ## Perl 5, 3651284 Just a simple word-based dictionary scheme. Analyzes the word frequency of the corpus, and uses that to determine whether to use one or two bytes of overhead per word. Uses two special symbols for the bytes \0 and \1 since they do not appear in the corpus. There are plenty of other symbols that could be used. This was not done. Does not do any huffman encoding or any of that jazz. Compression script shakespeare.pl: ``` use strict; use warnings; use bytes; my $text = join "", <>; my @words = split/([^a-zA-Z0-9]+)/, $text; my %charfreq; for( my $i = 0; $i<length($text); ++$i ) { $charfreq{ substr($text, $i, 1) }++ } for my $i ( 0..255 ) { my $c = chr($i); my $cnt = $charfreq{$c} // 0; } my %word_freq; foreach my $word ( @words ) { $word_freq{ $word }++; } my $cnt = 0; my ( @dict, %rdict ); foreach my $word ( sort { $word_freq{$b} <=> $word_freq{$a} || $b cmp $a } keys %word_freq ) { last if $word_freq{ $word } == 1; my $repl_length = $cnt < 127 ? 2 : 3; if( length( $word ) > $repl_length ) { push @dict, $word; $rdict{ $word } = $cnt; $cnt++; } } foreach my $index ( 0..$ print "$dict[$index]\0"; } print "\1"; foreach my $word ( @words ) { my $index = $rdict{ $word }; if ( defined $index && $index <= 127 ) { print "\0" . chr( $index ); } elsif ( defined $index ) { my $byte1 = $index & 127; my $byte2 = $index >> 7; print "\1" . chr( $byte2 ) . chr( $byte1 ); } else { print $word; } } ``` Decompression script deshakespeare.pl: ``` use strict; use warnings; use bytes; local $/; my $compressed = <>; my $text = $compressed; $text =~ s/^.+?\x{1}//ms; my $dictionary = $compressed; $dictionary =~ s/\x{1}.*$//ms; my $cnt = 0; my @dict; foreach my $word ( split "\0", $dictionary ) { push @dict, $word; } my @words = split /(\x{0}.|\x{1}..)/ms, $text; foreach my $word ( @words ) { if( $word =~ /^\x{0}(.)/ms ) { print $dict[ ord( $1 ) ]; } elsif( $word =~ /^\x{1}(.)(.)/ms ) { my $byte1 = ord( $1 ); my $byte2 = ord( $2 ); my $index = ( $byte1 << 7 ) + $byte2; print $dict[ $index ]; } else { print $word; } } ``` Run using: ``` perl shakespeare.pl < pg100.txt >pg100.txt.compressed perl deshakespeare.pl <pg100.txt.compressed >pg100.txt.restored diff pg100.txt pg100.txt.restored ``` ]
[Question] [ Your program will control a mining robot searching underground for valuable minerals. Your robot will tell the controller where you want to move and dig, and the controller will provide feedback on your robot status. Initially your robot will be given an image map of the mine with some mining shafts already present, and a data file specifying the value and hardness of the minerals in the mine. Your robot will then move through the shafts looking for valuable minerals to mine. Your robot can dig through the earth, but is slowed down by hard rock. ![small mine image](https://i.stack.imgur.com/4LMnR.png) The robot that returns with the most valuable cargo after a 24 hour shift will be the winner. It may seem to be a complicated challenge but it is simple to make a basic mining robot (see the Sample Mining Robot answer below). ## Operation Your program will be started by the controller with the mine image, mineral data, and equipment filenames. Robots can use the mine image and minerals data to find valuable ore and avoid hard rock. The robot may also want to buy equipment from the equipment list. eg: `python driller.py mineimage.png minerals.txt equipmentlist.txt` After a 2 second initialisation period, the controller communicates with the robot program through stdin and stdout. Robots must respond with an action within 0.1 seconds after receiving a status message. Each turn, the controller sends the robot a status line: `timeleft cargo battery cutter x y direction` eg: `1087 4505 34.65 88.04 261 355 right` The integer `timeleft` is the game seconds left before the end of shift. The `cargo` is the integer value of the minerals you have mined so far less what you have paid for equipment. The `battery` level is an integer percentage of your remaining battery charge. The `cutter` integer level is the current sharpness of the cutter as a percentage of the standard value. The `x` and `y` values are positive integers with the robot position referenced from the top left corner at (0, 0). The direction is the current direction the robot is facing (left, right, up, down). When your robot receives the 'endshift' or 'failed' input, your program will soon be terminated. You might want your robot to write debugging/performance data to a file first. There are 4 possible commands the controller will accept. `direction left|right|up|down` will point your robot in that direction, and require 15 game-seconds. `move <integer>` will instruct your robot to move or dig that many units forward which takes time depending on the hardness of minerals cut and sharpness of your cutter (see below). `buy <equipment>` will install specified equipment and deduct the cost from your cargo value, but only if the robot is at the surface (y value <= starting y value). Equipment installation takes 300 game-seconds. The special command `snapshot` writes the current mine image to disk and takes no game time. You can use snapshots to debug your robot or create animations. Your robot will start with 100 battery and 100 cutter sharpness. Moving and turning use a small amount of battery power. Digging uses much more and is a function of the hardness of the minerals and current sharpness of the cutter. As your robot digs into minerals, the cutter will lose its sharpness, depending on the time taken and hardness of the minerals. If your robot has enough cargo value, it may return to the surface to buy a new battery or cutter. Note that high quality equipment has an initial effectiveness of over 100%. Batteries have the string "battery" in the name and (surprise) cutters have "cutter" in the name. The following relationships define moving and cutting: ``` timecutting = sum(hardness of pixels cut) * 100 / cutter cutterwear = 0.01 for each second cutting cutters will not wear below 0.1 sharpness timemoving = 1 + timecutting batterydrain = 0.0178 for each second moving changing direction takes 15 seconds and drains 0.2 from the battery installing new equipment takes 300 seconds ``` Note that moving 1 unit without cutting any minerals takes 1 game second and uses 0.0178 of the battery. So the robot can drive 5600 units in 93 game minutes on a standard 100 charge, if it is not cutting minerals or turning. NEW: The robot is 11 pixels wide so will cut up to 11 pixels with each pixel of movement. If there are less than 11 pixels to cut, the robot will take less time to move, and cause less wear on the cutter. If a pixel color is not specified in the mineral data file, it is free space of zero hardness and zero value. The run is terminated when time runs out, the robot battery is exhausted, a part of the robot exceeds the image boundary, an illegal command is sent, or robot communication times out. Your score is the final value of the robot cargo. The controller will output your score and the final map image. The stderr output of your program is logged in the robot.log file. If your robot dies, the fatal error may be in the log. ## The Mine Data ### equipment.txt: ``` Equipment_Name Cost Initial_Value std_cutter 200 100 carbide_cutter 600 160 diamond_cutter 2000 250 forcehammer_cutter 7200 460 std_battery 200 100 advanced_battery 500 180 megapower_battery 1600 320 nuclear_battery 5200 570 ``` ### mineraldata.txt: ``` Mineral_Name Color Value Hardness sandstone (157,91,46) 0 3 conglomerate (180,104,102) 0 12 igneous (108,1,17) 0 42 hard_rock (219,219,219) 0 15 tough_rock (146,146,146) 0 50 super_rock (73,73,73) 0 140 gem_ore1 (0,255,0) 10 8 gem_ore2 (0,0,255) 30 14 gem_ore3 (255,0,255) 100 6 gem_ore4 (255,0,0) 500 21 ``` ### mine image: ![test mine](https://i.stack.imgur.com/BqLdc.png) The mine image may have an alpha channel, but this is not used. ## The Controller The controller should work with Python 2.7 and requires the PIL library. I have been informed that the Python Pillow is a Windows friendly download to get the PIL image module. Start the controller with the robot program, cfg.py, image and data files in the current directory. The suggested command line is: `python controller.py [<interpreter>] {<switches>} <robotprogram>` E.g.: `python controller.py java underminer.class` The controller will write a robot.log file and a finalmine.png file at the end of the run. ``` #!/usr/bin/env python # controller.py # Control Program for the Robot Miner on PPCG. # Tested on Python 2.7 on Ubuntu Linux. May need edits for other platforms. # V1.0 First release. # V1.1 Better error catching import sys, subprocess, time # Suggest installing Pillow here if you don't have PIL already from PIL import Image, ImageDraw from cfg import * program = sys.argv[1:] calltext = program + [MINEIMAGE, MINERALFILE, EQUIPMENTFILE] errorlog = open(ERRORFILE, 'wb') process = subprocess.Popen(calltext, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=errorlog) image = Image.open(MINEIMAGE) draw = ImageDraw.Draw(image) BLACK, ORANGE, WHITE = (0,0,0), (255,160,160), (255,255,255) W,H = image.size dirmap = dict(right=(1,0), left=(-1,0), up=(0,-1), down=(0,1)) # read in mineral file (Name, Color, Value, Hardness): data = [v.split() for v in open(MINERALFILE)][1:] mineralvalue = dict((eval(color), int(value)) for name, color, value, hard in data) hardness = dict((eval(color), int(hard)) for name, color, value, hard in data) # read in the equipment list: data = [v.split() for v in open(EQUIPMENTFILE)][1:] equipment = dict((name, (int(cost), float(init))) for name, cost, init in data) # Set up simulation variables: status = 'OK' rx, ry, direction = START_X, START_Y, START_DIR # center of robot cargo, battery, cutter = 0, 100.0, 100.0 clock = ENDSHIFT size = ROBOTSIZE / 2 msgfmt = '%u %u %u %u %u %u %s' snapnum = 1 def mkcutlist(x, y, direc, size): dx, dy = dirmap[direc] cx, cy = x+dx*(size+1), y+dy*(size+1) output = [(cx, cy)] for s in range(1, size+1): output += [ (cx+dy*s, cy+dx*s), (cx-dy*s, cy-dx*s)] return output def send(msg): process.stdin.write((msg+'\n').encode('utf-8')) process.stdin.flush() def read(): return process.stdout.readline().decode('utf-8') time.sleep(INITTIME) while clock > 0: try: start = time.time() send(msgfmt % (clock, cargo, battery, cutter, rx, ry, direction)) inline = read() if time.time() - start > TIMELIMIT: status = 'Move timeout' break except: status = 'Robot comslink failed' break # Process command: movecount = 0 try: arg = inline.split() cmd = arg.pop(0) if cmd == 'buy': if ry <= START_Y and arg and arg[0] in equipment: cost, initperc = equipment[arg[0]] if cost <= cargo: cargo -= cost if 'battery' in arg[0]: battery = initperc elif 'cutter' in arg[0]: cutter = initperc clock -= 300 elif cmd == 'direction': if arg and arg[0] in dirmap: direction = arg[0] clock -= 15 battery -= 0.2 elif cmd == 'move': if arg and arg[0].isdigit(): movecount = abs(int(arg[0])) elif cmd == 'snapshot': image.save('snap%04u.png' % snapnum) snapnum += 1 except: status = 'Robot command malfunction' break for move in range(movecount): # check image boundaries dx, dy = dirmap[direction] rx2, ry2 = rx + dx, ry + dy print rx2, ry2 if rx2-size < 0 or rx2+size >= W or ry2-size < 0 or ry2+size >= H: status = 'Bounds exceeded' break # compute time to move/cut through 1 pixel try: cutlist = mkcutlist(rx2, ry2, direction, size) colors = [image.getpixel(pos)[:3] for pos in cutlist] except IndexError: status = 'Mining outside of bounds' break work = sum(hardness.get(c, 0) for c in colors) timetaken = work * 100 / cutter cutter = max(0.1, cutter - timetaken / 100) clock -= 1 + int(timetaken + 0.5) battery -= (1 + timetaken) / 56 if battery <= 0: status = 'Battery exhausted' break cargo += sum(mineralvalue.get(c, 0) for c in colors) draw.rectangle([rx-size, ry-size, rx+size+1, ry+size+1], BLACK, BLACK) rx, ry = rx2, ry2 draw.rectangle([rx-size, ry-size, rx+size+1, ry+size+1], ORANGE, WHITE) if clock <= 0: break if status != 'OK': break del draw image.save('finalmine.png') if status in ('Battery exhausted', 'OK'): print 'Score = %s' % cargo send('endshift') else: print 'Error: %s at clock %s' % (status, clock) send('failed') time.sleep(0.3) process.terminate() ``` The linked config file (not to be changed): ``` # This is cfg.py # Scenario files: MINEIMAGE = 'testmine.png' MINERALFILE = 'mineraldata.txt' EQUIPMENTFILE = 'equipment.txt' # Mining Robot parameters: START_X = 270 START_Y = 28 START_DIR = 'down' ROBOTSIZE = 11 # should be an odd number ENDSHIFT = 24 * 60 * 60 # seconds in an 24 hour shift INITTIME = 2.0 TIMELIMIT = 0.1 ERRORFILE = 'robot.log' ``` ## Answer Format The answers should have a title including programming language, robot name, and final score (such as *Python 3*, *Tunnel Terror*, *1352*). The answer body should have your code and the final mine map image. Other images or animations are welcome too. The winner will be the robot with the best score. ## Other Rules * The common loopholes are prohibited. * If you use a random number generator, you must hardcode a seed in your program, so that your program run is reproducable. Someone else must be able to run your program and get the same final mine image and score. * Your program must be programmed for *any* mine image. You must not code your program for these data files or *this* image size, mineral layout, tunnel layout, etc. If I suspect a robot is breaking this rule, I reserve the right to change the mine image and/or data files. ## Edits * Explained 0.1 second response rule. * Expanded on robot starting command line options and files. * Added new controller version with better error catching. * Added robot.log note. * Explained default mineral hardness and value. * Explained battery vs cutter equipment. * Made robot size 11 explicit. * Added calculations for time, cutter wear, and battery. [Answer] # Python 2, Sample Miner, 350 This is an example of the minimum code for a mining robot. It just digs straight down until its battery gives out (all robots start pointing down). It only earns a score of 350. Remember to flush stdout or else the controller will hang. ``` import sys # Robots are started with 3 arguments: mineimage, mineralfile, equipmentfile = sys.argv[1:4] raw_input() # ignore first status report print 'move 1000' # dig down until battery dies sys.stdout.flush() # remember to flush stdout raw_input() # wait for end message ``` ![sample miner path](https://i.stack.imgur.com/sZLt6.png) [Answer] # Python 2, Robot Miner Python Template, 410 This is a mining robot template to show how a robot operates and provide a framework for building your own robots. There is a section for analyzing the mineral data, and a section for responding with actions. The placeholder algorithms do not do well. The robot finds some valuable minerals, but not enough to buy enough replacement batteries and cutters. It halts with a dead battery on its way to the surface to a second time. A better plan is to use the existing tunnels to get close to valuable minerals and minimise the digging. Note that this robot writes a log file of each status message it receives so you can check it's decisions after a run. ``` import sys from PIL import Image MINEIMAGE, MINERALFILE, EQUIPMENTFILE = sys.argv[1:4] image = Image.open(MINEIMAGE) W,H = image.size robotwidth = 11 halfwidth = robotwidth / 2 # read in mineral file (Name, Color, Value, Hardness): data = [v.split() for v in open(MINERALFILE)][1:] mineralvalue = dict((eval(color), int(value)) for name, color, value, hard in data) hardness = dict((eval(color), int(hard)) for name, color, value, hard in data) # read in the equipment list: data = [v.split() for v in open(EQUIPMENTFILE)][1:] equipment = [(name, int(cost), float(init)) for name, cost, init in data] # Find the cheapest battery and cutter for later purchase: minbatcost, minbatname = min([(c,n) for n,c,v in equipment if n.endswith('battery')]) mincutcost, mincutname = min([(c,n) for n,c,v in equipment if n.endswith('cutter')]) # process the mine image to find good places to mine: goodspots = [0] * W for ix in range(W): for iy in range(H): color = image.getpixel((ix, iy))[:3] # keep RGB, lose Alpha value = mineralvalue.get(color, 0) hard = hardness.get(color, 0) # # ------------------------------------------------------------- # make a map or list of good areas to mine here if iy < H/4: goodspots[ix] += value - hard/10.0 # (you will need a better idea than this) goodshafts = [sum(goodspots[i-halfwidth : i+halfwidth+1]) for i in range(W)] goodshafts[:halfwidth] = [-1000]*halfwidth # stop robot going outside bounds goodshafts[-halfwidth:] = [-1000]*halfwidth bestspot = goodshafts.index(max(goodshafts)) # ----------------------------------------------------------------- # dirmap = dict(right=(1,0), left=(-1,0), up=(0,-1), down=(0,1)) logging = open('mylog.txt', 'wt') logfmt = '%7s %7s %7s %7s %7s %7s %7s\n' logging.write(logfmt % tuple('Seconds Cargo Battery Cutter x y Direc'.split())) surface = None plan = [] while True: status = raw_input().split() if status[0] in ('endshift', 'failed'): # robot will be terminated soon logging.close() continue logging.write(logfmt % tuple(status)) direction = status.pop(-1) clock, cargo, battery, cutter, rx, ry = map(int, status) if surface == None: surface = ry # return to this level to buy equipment # # ----------------------------------------------------------------- # Decide here to choose direction, move, buy, or snapshot if not plan and rx != bestspot: plan.append('direction right' if bestspot > rx else 'direction left') plan.append('move %u' % abs(bestspot - rx)) plan.append('direction down') if plan: action = plan.pop(0) elif battery < 20 and cargo > minbatcost + mincutcost: action = 'direction up' move = 'move %u' % (ry - surface) buybat = 'buy %s' % minbatname buycut = 'buy %s' % mincutname plan = [move, buybat, buycut, 'direction down', move] else: action = 'move 1' # ----------------------------------------------------------------- # print action sys.stdout.flush() ``` ![final mine map](https://i.stack.imgur.com/Pwxmw.png) ]
[Question] [ I struggle to easily encode big numbers in ><>. If only there was a program that could find the best way for me? ## What is `><>` [`><>`, pronounced "fish"](https://esolangs.org/wiki/Fish), is a esoteric 2dimentional programing language. We will consider a subset here, consisting of the following commands: * `0123456789` push one number to the stack, equal to the value of the digit * `abcdef` push one number to the stack. Interpreted as hex, so `a` will push `10`, `f` will push `15` etc. * `*` multiply the top 2 numbers on the stack * `+` add the top 2 numbers on the stack * `-` subtract the top 2 numbers on the stack * `,` divide the top 2 numbers on the stack * `%` modulo the top 2 stack items * `$` swap the top 2 stack values * `@` move the top value of the stack back by 2 * `"` start string parsing mode. Push the character values of each encountered character to the stack until encountering another `"`. Only printable ASCII characters are allowed for the purpose of this challenge. * `'` same as `"` but only ends with a `'` character. * `~` delete the top element of the stack. * `:` duplicate the top element of the stack Only these commands may be used, so `/\-|#xlp.gnoi!?&><^v;[]{}()` are not allowed to be used, except inside strings. Inside strings, only ASCII printable characters may be used. Line breaks are not allowed to appear anywhere. Your code must, when executed, push the specified number to the stack, and effect nothing else. Your snippet should be embed able in a bigger program in any place in any orientation. You only need to handle positive integers. Your program should take at most `O(n)` time to complete encoding a single number. ## Some examples `15` could be `f` `32` could be `48*` or `" "` `1111` could be `1e4f*+f*+`. This one likely can be made shorter. You can test your programs by appending a `n;` at the end. It should print the correct number. Online interpreters include [this one](https://tio.run/#fish), [this one](https://suppen.no/fishlanguage/), and [this one](https://mousetail.github.io/Fish/). Score excludes the "printing the output" part. ## Scoring Your score is your total length of the encoding your programs produces for the following test cases: * all numbers between 1 and 1500 inclusive * the first 1000 primes [(from wikipedia)](https://en.wikipedia.org/wiki/List_of_prime_numbers) whose value is greater than 1500 * All numbers of the form $$ 3^a+b $$ where `0<=a<30` and `-15<=b<=15`, whose value is greater than 1500 and not one of the first 1000 primes. * All numbers of the form $$ 7^a + 5 \pm Fib(b)$$ for all `10 <= a < 18`, `0<=b<29`, and `Fib(x)` is the Fibonacci function, if they would not fall into any of the other categories. `Fib(0)=0`. The [full list can be found here](https://gist.github.com/mousetail/fcd558c39f9d1a680db3de1c25e823de). (When there is overlap only count that test case once) Lowest score wins. First answer is tiebreaker. You don't need to golf your code. [Answer] # JavaScript (ES7), Score 29093 ``` let cache = {}; function testSuite(list) { let size = 0; list.forEach(n => { let res = solve(n).join(''); size += res.length; console.log(n + ': ' + res); }); console.log("Total size: " + size); } function solve(n, depth = 0) { if(!cache[n]) { cache[n] = solveNew(n, depth); } return cache[n]; } function solveNew(n, depth = 0) { if(n < 16) { return [ n.toString(16) ]; } if(n == 34) { return [ `'"'` ]; } if(n > 31 && n < 127) { return [ '"' + String.fromCharCode(n) + '"' ]; } if(depth > 1) { return null; } let sol = []; for(let d = Math.floor(n ** 0.5); d > 1; d--) { if(!(n % d)) { let r0 = solve(n / d, depth + 1), r1 = solve(d, depth + 1); if(r0 && r1) { if(isAscii(r1[r1.length - 1]) && isAscii(r0[0])) { [ r0, r1 ] = [ r1, r0 ]; } sol.push([ ...r0, ...r1, "*" ]); } } } for(let o = -15; o <= 15; o++) { if(o) { let r0 = solve(n - o, depth + 1), r1 = solve(Math.abs(o), depth + 1); if(r0 && r1) { if(o > 0 && isAscii(r1[r1.length - 1]) && isAscii(r0[0])) { [ r0, r1 ] = [ r1, r0 ]; } sol.push([ ...r0, ...r1, o < 0 ? "-" : "+" ]); } } } for(let j = 2; j <= 3; j++) { let q = Math.floor(n ** (1 / j)), op = ":".repeat(j - 1) + "*".repeat(j - 1); if(q > 2) { let r0, r1, d; d = n - q ** j; r0 = solve(q, depth + 1); r1 = solve(d, depth + 1); if(r0 && r1) { sol.push([ ...(d ? r1 : []), ...r0, op, ...(d ? [ "+" ] : []) ]); } d = (q + 1) ** j - n; r0 = solve(q + 1, depth + 1); r1 = solve(d, depth + 1); if(r0 && r1) { sol.push([ ...r0, op, ...(d ? [ ...r1, "-" ] : []) ]); } } } if(!sol.length) { return null; } sol = sol.map(mergeAscii); sol.sort((a, b) => a.join('').length - b.join('').length); return sol[0]; } function mergeAscii(a) { if(isAscii(a[0]) && isAscii(a[1])) { let b0 = a[0].slice(1, -1), b1 = a[1].slice(1, -1); if(!b0.match(a[1][0])) { return [ a[1][0] + b0 + b1 + a[1][0], ...a.slice(2) ]; } if(!b1.match(a[0][0])) { return [ a[0][0] + b0 + b1 + a[0][0], ...a.slice(2) ]; } } return a; } function isAscii(v) { return v[0] == '"' || v[0] == "'"; } ``` [Try it online!](https://tio.run/##xVbbjts2EH3fr5gIaCytbFWymwZZr7cogj62KLB9EwyEsui1DFn0SvQm6Mbfvj1DibrYTpqiKPpgkCbP3M7McLQVT6JaldleTwqVypeXXGpaidVG0oKej/Orq/WhWOlMFaRlpe8PmZZunlXao@crIkZX2Z8MDoHFAa6CtSp/gQq3oMWdgdXAUlbAVSp/km7hBVuVFe5o5M0NwGjxFwwKclk86E19vlIFJGSQqwfo82l0QyMsgBnBo2fM9lHOH0qL3Ci8IQdY3gF27MXSODGmVO71hr2v48nW7isTfVwsvcZ1@9/6/pv82ErWPuBXSn0oixZ7wVpfbGCwoFuKfrTWGkUxFYFW97rMigeXb5fWkpFYLGj2w5nIh5Ez@nCCvKNZRK9fk7EyfXsmAxFQVBsK1qXavd@I8j1KASliunHdV1i7f0fRiaLikOc1zFaFyhFlvDTpQUG4fJji6FehN8E6Vzgq6PqawuCNN8cNdGKZTKxiTgUQ31Hq2aOmjMKuiuh7Si2nPpwaNzjjWdTiBhjjUWMBusBNGXUWzHFW/Vytsswto7iMmnKkCUWoCcDb2zAOl15flEBoGY7ZNJcL/kRj9nc5byHHdgfXgv2h2rgxBUHAYrxAwLl2aOlZkVrgaLm1VCron0Rv5tjcLshsfL/HnfoKaRNS30CaSZRIKqj6h/QpJDMcMPW/8Ahm4MZP5EwcwkvgfwOrW1ibzrGA0xnWjlK@fbxQvm6EGtx6PRLVHjDnxglKuZdCu1uOmHsJeR2eNVSCsUcwNj3N2NiEnbaEc/dw8h7Z7tZG0svs4zBP/64NhrS6KYiEqhu0tDe2RKv9uL2Ma4ZrxIDpnvsIlG2bABBJcSkIRvx3gZy7bbtuctn7QZ3wo8T66lL@2htYv3@M3Ym9u5PlgzTVbjTzcaVK7bpiTInHY1K087Drk@T0rI61MQcl6JvhpOnsuKIdMLbPBLdZv/FEHHV9xzWXcBoYFlR5tpIuaJn034ckMvfR8L4r41dJiHA1Rj@Dhl3dTpzmCrmDOZ91@vbMpEU0yqee7fdjpz9q9Ydf1h9e0B/@jf7eEBdDTi1bT7WtBvTEJjCGeUB@/tz@dUYOpF96wr@X2c4M0@fe8J6elI4uD3Iwtm9pymrrCTj1TuBrkVdyMG534tOXZuvpAJ7xtMX7BhHe@T1vLs7cU5tnfNXOwxW2wB@A/E7Jj3QvtcvmrXFEzjO@YONv30XvsLXvax0zz7Ew5Lg72try5A9LkaY4qgM/doqF@fzEckszXq1We5/YWZnYWZkMH3b2bMaECS6Yrp7584ld6r3MQzcsF3Cm@zyOUWSMW571OPe0581f/gI "JavaScript (Node.js) – Try It Online") [Answer] # Python 3, score 28806 ``` import functools import itertools #import sympy import math STRINGABLE = sorted(b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~ ', reverse=True) MAX = max(STRINGABLE) ONECHAR = [*STRINGABLE, *range(15, 0, -1)] MULTIPLES_O = {a*b:(a,b) for a in ONECHAR for b in ONECHAR} SUMS_O = {a+b:(a,b) for a in ONECHAR for b in ONECHAR} MM = {*range(16), *STRINGABLE} def stringify(n): infix = '' prefix = '' postfix = '' options = [] while True: if n < 16: postfix = hex(n)[2:] + postfix break if n in STRINGABLE: prefix += chr(n) break if n in SUMS_O: a,b = SUMS_O[n] postfix = '+' + postfix if a < 16: postfix = hex(a)[2:] + postfix else: prefix += chr(a) if b < 16: postfix = hex(b)[2:] + postfix else: prefix += chr(b) break if n in MULTIPLES_O: a,b = MULTIPLES_O[n] postfix = '*' + postfix if a < 16: postfix = hex(a)[2:] + postfix else: prefix += chr(a) if b < 16: postfix = hex(b)[2:] + postfix else: prefix += chr(b) break for i in ONECHAR: if n+i in SUMS_O or n+i in MULTIPLES_O or n+i in ONECHAR: n += i postfix = '-' + postfix if i < 16: postfix = hex(i)[2:] + postfix else: prefix += chr(i) break if n-i in SUMS_O or n-i in MULTIPLES_O or n-i in ONECHAR: n -= i postfix = '+' + postfix if i < 16: postfix = hex(i)[2:] + postfix else: prefix += chr(i) break else: for i in ONECHAR: c = set(range(n%i, MAX+1, i)) & MM if c: if 0 in c: prefix += chr(i) postfix = '*' + postfix n //= i break j = max(c) if j in STRINGABLE: prefix += chr(j) postfix = '+' + postfix else: postfix = hex(j)[2:] + '+' + postfix if i in STRINGABLE: prefix += chr(i) postfix = '*' + postfix else: postfix = hex(i)[2:] + '*' + postfix n = (n-j) // i break # make n smaller ... options.append("'" + prefix + "'" + most(n,0) + postfix) options.append("'" + prefix + "'" + postfix) return min(options, key=len) def evaluate(s): import io s = io.StringIO(s) stack = [] while True: c=s.read(1) if c=='': break if c in '0123456789abcdef': stack.append(int(c, 16)) elif c in '*+-%': stack.append(eval(f'{stack.pop()}{c}{stack.pop()}')) elif c == ':': stack.append(stack[-1]) elif c == '~': stack.pop() elif c == '$': stack.append(stack.pop(-2)) elif c == '@': stack.insert(-2, stack.pop()) elif c == '"': while True: c = s.read(1) if c == '"': break stack.append(ord(c)) elif c == "'": while True: c = s.read(1) if c == "'": break stack.append(ord(c)) elif c == ',': raise NotImplementedError return stack def factor(n): from collections import Counter p = 2 l = [] while n > 1: if p*p > n: l.append(n) break if n%p: p += 1 + p%2 else: l.append(p) n //= p return Counter(l) #factor = sympy.factorint def two_squares(n): C = factor(n) for i in C: if i%4 == 3 and C[i]%2: return False return True def product(l): z = 1 for i in l: z *= i return z def divisors(n): F, C = zip(*factor(n).items()) for t in itertools.product(*(range(i+1) for i in C)): yield product(i**j for i,j in zip(F, t)) #from sympy import divisors @functools.lru_cache(None) def power(n): if n < 2: return '' options = [':'+power(n-1)+'*'] for i in divisors(n): if 1 < i*i <= n: options.append(power(i)+power(n//i)) return min(options, key=len) def nth_root(k, p): x = int(k**(1./p))+1 x1 = x-1 while x1 < x: x = x1 xp1 = x**(p-1) x1 = ((p-1)*x+k//xp1)//p return x #nth_root = lambda k,p:sympy.integer_nthroot(k, p)[0] def massage(x, p): options = [most(x) + power(p)] if p%2 and p > 2: options.append(most(x*x) + power(p//2) + most(x) + '*') return min(options, key=len) def powerful(n): possibilities = [] for p in range(2, n): x = nth_root(n, p) if x == 1: d2 = (x+1)**p-n if d2 < n and x+1 < n: possibilities.append((d2,x+1,p,'-')) break d1 = n-x**p if d1 == 0: if x < n: possibilities.append((d1,x,p,None)) continue d2 = (x+1)**p-n if d1 < n and x < n: possibilities.append((d1,x,p,'+')) if d2 < n and x+1 < n: possibilities.append((d2,x+1,p,'-')) options = [most(d,0) + massage(x, p) + s if d else massage(x, p) for d,x,p,s in sorted(possibilities)[:2]] return min(options, key=len) def power2(n): possibilities = [] for b in range(2, 20): bc = 1 for c in range(1, n): bc *= b a = n//bc if a*bc == n: possibilities.append((a,b,c,None,'')) continue d = (a+b)*bc - n possibilities.append((a+1,b,c,d,'-')) if a == 0: break d = n - a*bc possibilities.append((a,b,c,d,'+')) a,b,c,d,s = min(possibilities, key=lambda t:t[0]+t[1]+(t[3]or 0)) postfix = most(a) + '*' if a > 1 else '' if d is None: return most(b) + power(c) + postfix return most(d) + most(b) + power(c) + postfix + s def split(n): D = sorted(i for i in divisors(n) if 1 < i*i <= n) if len(D) == 0: return options = [] for d in D[-3:]: options.append(most(d,0) + most(n//d,0) + '*') options.append(most(d,0) + ':' + most(n//d - d) + '+*') options.append(most(n//d,0) + ':' + most(n//d - d) + '$-*') return min(options, key=len) def optimize(s): return s.replace("''", '') winners = [0,0,0] @functools.lru_cache(None) def most(n, depth=1): if n < 16: return hex(n)[2:] if n < 31: return hex(n-15)[2:] + 'f+' if depth: return stringify(n) options = [stringify(n), powerful(n), split(n)]#, power2(n)] options = [(optimize(s),i) if s else (s,i) for i,s in enumerate(options)]#list(map(optimize, filter(None, options))) s,i = min(options, key=lambda t:len(t[0]) if t[0] else 1000000000) winners[i] += 1 return s #most(7**2) def fib(n): a,b = 0,1 for _ in range(n): a,b = b,a+b return a if __name__ == '__main__': L = sorted(I for I in {*range(1, 1501), *[i for i in range(1501, 7920) if list(factor(i).values()) == [1]], *[3**a+b for a in range(30) for b in range(-15, 16)], *[7**a + 5 + m*fb for fb in [fib(b) for b in range(30)] for a in range(10, 18) for m in [1,-1]]} if I > 0) O = [most(i,0) for i in L] for i,j in zip(O, L): if evaluate(i)[0] != j: print(i, j, evaluate(i)) break print(f'{j}: {i}') else: print('Success!') s = ''.join(O) print(len(s)) print('\n' in s) print(winners) ``` [Try it online!](https://tio.run/##7Vlbd9vGEX7nr1hLVoAFAZKgIjthzdSOLCdqJCu17DYtzbIAuLSWAhYIAFqUFOWvu7MXXAleXOel55R6ERY7929mZxbRbXoVskMruo1uP32iQRTGKZotmJeGoZ@01AJNSSwX9tVKchtEt9nrwEmvWq3Lt29OX//w4vuzEzRECayTqe5qPbt/@PXRk6fffOu43pTMPlzR@bUfsDD6NU7Sxceb5e3di@@PX568@uHH07/8dHb@@uLnv765fPvub3//5R//fLS3//jgKx0bbdPqdAd/ejb87s/PR@/fj/81@ff9bw@/I81EMflI4oQM38YLglvnL34B8YGz1At9cOvi9cnxjy/ewJuRUaybyIgd9oHo9pGJeiaybDxunb87e3v689nJ5eQCtt87hjvQHdPFaBbGyEGUoYwZX3BLCw@ty3fnGVn7M8jOzzlJpssTDHoVSj60WuA2lKQxZR/o7FZneNBC8KNsRpdAqGniMYpJ9TlM0spCGKU0ZAn3wVgs3FxRnyDuNslQMJ0hhp4h@0mxVGV2RZagwag/GKN2tlzZ6sbEua7yA1sLe2qMpdbtIfKuYmC8Cyvh5Cob8DToJt@M2HiN7lpbW6M08HYazF413dlkOvET0sCgYqKD64LdnQS7XyrY3cW3JfA3Obj0eoOXjf97udnLPPNpKfMHdSVZmxYIR7BbLZRrUrHayIX/GNeGbjBVs9aFSClC13hr1WN0k8fWe23VcxSvbKp6L/ORVfeR1egja5uPrC0@av8P@miV0WbM8Z/Hj2uS6vL4YQfURHCItm0TUYzRV@j8vMl6r1lfeNPj0ta83smkzykp1ZB2u00xXQ@n7DdXLYOH1xk133SIrbduvpN17W3WrcfHKtjmGdi2sxUg/q/s@oOi9jl25Um0nS0DEp1ZcwyAWIOHKhb2IfrXBOiSwPF9EqNOp5O/VH1Tx4kiwqb6nrbHxSt3IPkYgDY6M3u40Ay3diWuEMQkXcQMBZTpitZE1@R26BNojkQnSD46/sJJiZ5kjaBq0kPxxBs8GnYuRb94egG75HLqeNebez9vmHTALVPdxuXGwBsONW2w2jB4HDor/b1WjacQm1lPWap7JhRNjEsVK2dltK2DTeTccH2m3cvFKIx0/HDvPVSetVXWQ0DiYBNf8TCy7HEj6e@NpEJa0/bHWyUJWqvfrOjzRnLKEhjAgMgsi29ksFdj0BToSuVfCXklxIrlmtpZMS6Mp1BAm5QCmP/RSnGWX6aUZtY8FTs0Ieh1mJ4GkU8CwmCAPYnjMC7npWAu83DmwJAc5@PYLA4D5IVQPjw5Z6m0PA4XwEkyicC2vvjPr6ciQ98huzKHRUYEa6yqpJ8ZtnVUOohqkxav3TYvNwf9Df1CLiCqCpCHa1T2hbJM96Ew7Utv8Njxm4GOfISEl75Kb8JJ8uvCiUmSO@wYNuc@bFV6leOKI@jB1zxgh8hhU3Q8ouOD/iDT4ZUDFpSV4qCSMqM4nC68FNST3O5Anl2V4xdy7pCR9Q6K051kM6UfaRLGhd6vTKH6HY10I9e/Q1MSJFlOcgEpF5BfnHQybQzVZ9G2jUsGY1yockuJP83Vp4YxlxtN0YRwuaBCioXXOeiExzO4Zeq2Ws/za5yOHy8mnuNdEf11yAiW7glvSIFeNfcXjl29NIAi2lZElo3bcAyPq95c8ZRibANjakC7PKyjuXY6Su4UZ2K6XYp3PRVZejWJwzDVr00UKfm8deBnzrVh6HanG2HclgBY2vBmadml/FtyLZeFepx2aRePkSABRpFVKkuCkS7WjGX7utuFfbjbraTJEuKUaQe7fSdwpw66NqOBTBXQkHwg8QT2FAaMemNpV@AkiQN4WRZmlWIi@o6l7Dq4yyI8zsIJaS4ShheR/mBdNyMZGGUW3W4fZy2NWIdI7xoFwWK28HMIQG@TUJf6NKWkdPXEMRNxzMhkgHOtjBnu@zyejBtehtOSFwO7CqRpn8dhCTllGJHF6jMjvH4G@ObugD38/0FVs8wd@rRvwg4zMmFExptK7JRHnlmAiKisHF8eot7KZL/cKNQ2lyBS5GZVpheylLIFaW0zVIrOjdxBGowHuOLXL3JSHZNT2QtX0AvPiRAkjp3aO46IqVAs4bhQ98cV@Xg06I/Hn4PE/i44dCs47PdKQHS9/MzIdnvFbruKWkUAx4hbvTrjQOl2XW/lLsxwRSfCGm@lGvzumK7pCZiYWh2djWgRiOGAcdou5tIsxFo7yIHgcknThiwQd3gC4g3tF5fFQAi3rLWrPdMSFLMVHiIe3AqdCrGsn@kghRrZTkf2uK2no8MxxKanuBSDo8Cio4qY1B3aLIk/dcIJQNIEcbfmp5@gc4ui6OHayFneN83L5RoKDnx1ix@BKTkoXxYfSmjjMVo/PXGmMeBcf4lVHKQuzXf8Iq0415cj63Aw3nwOZEkrhtluVz3m5X8LGfQHZWKAgXCM1t5GXxK1hsVja/cjiC8H9K4Yj7POHWaKyHc8AkO4tmdC@IHghjJGYuGvngl/461tk5r00ZRE6dXQrrZP5etAJbb4XlLeeGg3b7Tso/yaY9YuAMqFrVCUPwnVo19@Z5aPZTPH4HjfLKrkuM5AL/nRpAKJicwbPeHPsiMVtZqwRUBifiOh6IG1T8FNgRPlbEw0oz6fFkT5yiRhlbHAUmV8NapZrnO883wXevB/pCp2L/tJNiqcMCKIYacSfujCROyeGkZfQWVG3TwX5QeOnllMCJOi0pfLvNzomlBSy/ydVgtUm0yYE5DJRAyYk0ngUDaZqDnzrMj2UyHglAvIP/uZyD7q2fzb36hUDLLvkz14//RbOJxE9nPnqtGD4g6/DyJ89uBSoR6OOY9DwwANi6@PktFhD9fPPIt//LSfYEEFznEAe0c8C42ZJJ@JzSPuLHeFGhiO60LsHjD8Rm4NBK1tWqDWA9f9FAqwitZF3i1Qs1cahs5Kc0Ux81yY6Kw6V@QXYZS3y@jREM3rHxd5909NNDfLmze1dZJkpt3PHwbonj6oslOdk@Um7XLheSRJHqk9ifjU2pmHgOILdRCJjRy8CS6vaO@ZJrqc8qICL259@vQf "Python 3 (PyPy) – Try It Online") There are three methods this uses. The first is to try to express the number using a single string of characters, and several multiplications/additions (more or less, it can also use single digits (0-f) outside of the string). The next is to try to find a power that is close to the number, and express the number as `a^p + b`. The third is to express the number as a product of two numbers (of similar magnitude). It also removes any occurrences of `''` (this saves nearly 200 bytes!) [Answer] # Python, score=28800 ``` import requests import string import itertools real_printables = {ord(i) for i in ( set(string.printable) - set('\n\t\r\x0b\x0c'))} def get_factors(num, quote): quote_free_printables = real_printables - {ord(quote)} terms = [] factors = [] while num > 0: if num <= 15: terms.append(num) break if num in quote_free_printables: terms.append(num) break for factor in sorted(quote_free_printables, reverse=True): if num % factor == 0: break else: for factor in sorted(quote_free_printables, reverse=True): if num % factor in quote_free_printables: break else: for factor in range(15, 4, -1): if num % factor == 0: break else: factor = 15 assert factor != 1 terms.append(num % factor) factors.append(factor) num //= factor return terms, factors def encode_char_safe(char, quote): if char in real_printables - {ord(quote)}: return chr(char) elif 0 <= char <= 15: return f"{quote}{'0123456789abcdef'[char]}{quote}" else: raise ValueError(f"invalid char: {char}") def encode_naive(num, quote): string = '' multiplication_section = '' terms, multiples = get_factors(num, quote) # print(terms, multiples) for index, (term, multiple) in enumerate(zip(terms, multiples)): if term != 0: string += encode_char_safe(term, quote) + encode_char_safe(multiple, quote) if index == 0: multiplication_section = '+' + multiplication_section else: multiplication_section = '+*' + multiplication_section else: string += encode_char_safe(multiple, quote) if index != 0: multiplication_section = '*' + multiplication_section assert len(terms) == len(multiples) + 1 assert 1 not in multiples if terms[-1] != 1 or len(terms)==1: string += encode_char_safe(terms[-1], quote) if len(multiples) > 0: multiplication_section = '*' + multiplication_section return f"{quote}{string}{quote}{multiplication_section}".replace( quote*2, "") def encode_maybe_power(num, quote): return min( ( encode_naive(int(num ** (1/a)), quote)+b for a, b in zip( (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18), ('', ':*', '::**', ':*:*', '::::****', ':*::**', '::::::******', ':*:*:*', '::**::**', ':*::::****', '::::::::::**********', ':*:*::**', '::::::::::::************', ':*::::::******', '::**::::****', ':*:*:*:*', ':::::::::::::::****************', ':*::**::**' )) if int(num ** (1/a))**a == num ), key=len ) def encode_maybe_divide(num, quote): return min( ( ( encode_maybe_power(num, quote) if i == 1 else ( quote + encode_char_safe(i, quote) + quote + encode_maybe_power(num//i, quote) + '*' ).replace(quote*2, '') ) for i in itertools.chain( range(1, 16), real_printables - {ord(quote)} ) if num % i == 0 ), key=len ) def number_with_subtraction(num, sub, quote): if sub == 0: return encode_maybe_divide(num, quote).replace(quote*2, '') elif sub > 0: return ( quote + encode_char_safe(abs(sub), quote) + quote + encode_maybe_divide(num-sub, quote) ).replace(quote*2, '')+'+' elif sub > -16: return ( encode_maybe_divide(num-sub, quote) + quote + encode_char_safe(abs(sub), quote) + quote ).replace(quote*2, '')+f'-' else: return ( quote + encode_char_safe(abs(sub), quote) + quote + encode_maybe_divide(num-sub, quote) ).replace(quote*2, '')+f'$-' def encode(num): if num < 16: return '0123456789abcdef'[num] return min(( number_with_subtraction(num, b, quote).replace(quote*2, '') for quote in ('"', "'") for b in itertools.chain(range(-15, 16), *( (i, -i) for i in real_printables - {ord(quote)} )) if num-b > 0 ), key=len) # test_cases = range(500, 510) test_cases = requests.get( "https://gist.githubusercontent.com/mousetail/" "fcd558c39f9d1a680db3de1c25e823de/raw/" "c91113d663cf4d3f3cef7ad44d5ced22239f964e/test_cases.csv").text.split("\n") total_length = 0 for test_case in test_cases: res = encode(int(test_case)) total_length += len(res) print(f"{test_case:>8}\t{res:>8}") print(total_length) ``` Technically runs in `O(log N)`. Basically runs in 3 steps: * Try adding or subtracting every printable character to try to make it a perfect multiple * The dividing by every printable to make it a perfect power * If it is a perfect power try rooting it. This is the most important saving, and the main goal of the top 2 steps. * Now the main part of the loop. Basically we want to convert the remaining number to base `ord('~')`. However, if this would lead to digits that are not printable we take a smaller base instead. Base is adjusted for each individual digit. The score for just the last step would be `33749`. ]
[Question] [ This is a challenge to write bots to play the 1st and 2nd players in the following simple poker game. ## Rules of the poker game There are two players, A and B. Each antes $10 into the pot, and is dealt a card, which is a real number in the range [0, 1). Player A goes first, and may pass or bet. If A passes, then there is a showdown; the cards are revealed, and whichever player had the higher card wins the pot. If A bets, A chooses an amount \$b\$ to bet. \$b\$ must be an integer multiple of $1, in the range [$1, $50], and no greater than the amount of money A has at the time. **EDIT (19 Aug 2020)**: Moreover, \$b\$ must be no greater than the amount of money B has at the time, to enable B to go all-in to call, if B wants to. A adds \$b\$ to the pot. Then B may fold or call. If B folds, A wins the pot with no showdown. If B calls, B adds \$b\$ to the pot, and there is a showdown. **EDIT (19 Aug 2020)** Note that B will always have enough money to call, as A is not allowed to bet so much that B would not have enough. ## Rules of the tournament, matches and sessions The bots which are the entries to this contest will compete in an all-play-all tournament consisting of matches. Every pair of entries go head to head in a match. Each match has two contestants (call them X and Y). Each match consists of \$n\$ sessions, where \$n\$ is a number I will choose, depending on how many entries there are and how much time I feel like devoting to running the engine. At the start of each session, the tournament controller gives each contestant $100. There then follow a series of games. The games in each match alternate games where X's A-bot plays Y's B-bot, and games where Y's A-bot plays X's B-bot. Each session will continue until either 50 games in the session have been played, or one contestant no longer has enough money to start a further game (specifically, to put a $10 ante into the pot). Where a session contained \$g\$ games, and the winner gained an amount \$m\$ of money, that winner is awarded \$m/\sqrt{g}\$ points, and the loser loses the same amount of points. (The amount of points is higher, the lower \$g\$ is, so as to reward bots that consistently beat their opponents and thus win their opponent's entire stack quickly. However, I don't want very quick sessions to dominate the scoring too much, so I divide only by \$\sqrt{g}\$ and not by \$g\$.) The winning bot is the one who won most points over the course of all the matches it played in the tournament (as described in the previous paragraph). ## Interfaces of procedures in an entry An entry should contain C procedures which have the following prototypes: ``` int a(const Bot *bot); int b(const Bot *bot, const int aBet); ``` where types are defined as follows: ``` typedef float Card; typedef long Money; typedef Money (*AProcType)(const void* bot); typedef int (*BProcType)(const void* bot, const Money aBet); typedef struct Bot { AProcType a; BProcType b; Card card, opponentsPreviousCard; Money money, opponentsMoney; float f[50]; // scratch area for bots to use as they will } Bot; ``` Where `bot` points to an entrant's bot, just before `bot->a` or `bot->b` is called, the card dealt to that bot and the amount of money it has are assigned to `bot->card` and `bot->money`. If a game ended in a showdown, then, afterwards, each bot's card is assigned to the other bot's `bot->opponentsPreviousCard`. By contrast, if the game ended with one player folding, then the controller does not reveal the cards: instead, a negative value is assigned to `bot->opponentsPreviousCard`. In my sandbox proposal for this KotH, I asked whether or not the controller should *unconditionally* reveal both cards to both bots. It got a comment that in online poker "the winner has the choice whether they show or hide their cards". Seeing as a bot can't possibly do worse by hiding its card than by revealing it, I have opted instead to never reveal the cards dealt in a game where one player folded. The array `f` is provided to enable a bot to maintain state between games. In a game where the bot `bot` is the A-player, the controller will call the function `bot->a(bot)`. `0. <= bot->card < 1.0`. `a` must return the amount (in $) the bot is to bet. If `a` returns 0 or a negative value, that means the bot will pass. Otherwise, the bot will bet the value returned by `a`, $50, or all the player's money, whichever is the smallest. In a game where the bot `bot` is the B-player, the controller will call the function `bot->b(bot, aBet)` where the A-player has just bet an amount $`aBet`. `0. <= bot->card < 1.0`. The controller calls `bot->b` only if both the following conditions are true: * `aBet > 0` because if A had passed, B does not get to act. * `bot->money >= aBet` because, if A had bet but B could not afford to call, B must fold. `bot->b` must return 0 if the bot is to fold, and any other value if the bot is to call. X and Y will never be the same entry. So, even if you think each of your bots would be able to tell if its match-opponent is your other bot... it won't be. My sandbox proposal for this KotH expressed the game in terms of dealing cards from a pack. In such a game, if cards were not returned to the pack, the value of each card would change depending on how many cards above it and below it had not yet been seen, which would depend on the play. The proposal got a comment that cards are returned to the pack after each round. But in that case the above effect does not occur. So the cards might as well be independent variates from the uniform distribution on the interval [0, 1). Each entry's tournament score will be the sum of its match-scores. [Note that each entry is pitted against every other entry, so all entries play equal numbers of matches.] Loopholes are forbidden, as is trying to cheat. No bot may try to read or write or tamper with anything external to it, including the controller or other bots. However, calls to `rand` (in reasonable quantities) are allowed. **EDIT** Tue 11 Aug 20 to clarify that using `rand` is allowed, and to give direct read-access to the amount of the opponent's money. The following is a controller, provided just so that entrants can test their bots. My actual controller might contain additional code as required. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> // Return codes from playVonNeumannPokerGame #define G_FOLD 0 #define G_SHOWDOWN 1 #define G_MAYNOTBOTHPLAY 2 #define ANTE 10 #define BET_LIMIT 50 #define INIT_STACK 100 typedef float Point, Card; typedef long Index, Money, Stat; typedef Money (*AProcType)(const void* bot); typedef int (*BProcType)(const void* bot, const Money aBet); typedef struct Bot { AProcType a; BProcType b; Card card, opponentsPreviousCard; Money money; float f[50]; // scratch area for bots to use as they will } Bot; #define GAME_NAME_MAX 31 typedef struct Entrant { Bot *bot; char name[GAME_NAME_MAX+1]; Point vp; Money mny; } Entrant, *PEntrant; long nEntrants; Entrant *plr; #define NSESSIONSPERMATCH 500 #define MAXNGAMESPERSESSION 50 unsigned long nGamesInTotal, prngSeed; static void playVonNeumannPokerTournament(); static void playVonNeumannPokerMatch(PEntrant c1, PEntrant c2); static long playVonNeumannPokerGame(PEntrant a, PEntrant b); static void initBots(); static void tournament2Init(long nPlayers); static void tournament2MatchPlayers(long *pi1, long *pi2); static float fRand(); static int cmpByVP(const Entrant* e1, const Entrant* e2); // <nEntrants> <seed> int main(int argc, char** argv) { sscanf_s(argv[1], "%ul", &nEntrants); // for public engine sscanf_s(argv[2], "%ul", &prngSeed); srand(prngSeed); playVonNeumannPokerTournament(); } // main static void playVonNeumannPokerTournament() { long pi, pj; PEntrant e; nGamesInTotal = 0; //nEntrants = sizeof(aProc)/sizeof(aProc[0]); // works only if engine includes bot data plr = (PEntrant)calloc(nEntrants, sizeof(Entrant)); for(pi=0; pi<nEntrants; ++pi) // Initialise the entrants { e = &plr[pi]; e->vp = 0; } initBots(); // Connect each entrant to its bot for(pj=1; pj<nEntrants; ++pj) // all-play-all tournament for(pi=0; pi<pj; ++pi) playVonNeumannPokerMatch(&plr[pi], &plr[pj]); } // playVonNeumannPokerTournament static void playVonNeumannPokerMatch(PEntrant c1, PEntrant c2) { long si, mgi=0, sgi, r; Point win1, win2; c1->bot->opponentsPreviousCard = -1.0; c2->bot->opponentsPreviousCard = -1.0; for(si=0; si<NSESSIONSPERMATCH; ++si) { c1->mny = INIT_STACK; c2->mny = INIT_STACK; for(sgi=0; sgi<MAXNGAMESPERSESSION; ++sgi) { if(mgi&1) // c1 & c2 swap roles in the match's every game r = playVonNeumannPokerGame(c2, c1); // c2 is A; c1 is B else // even-numbered game r = playVonNeumannPokerGame(c1, c2); // c1 is A; c2 is B ++mgi; if(r==G_MAYNOTBOTHPLAY) break; // one player can't afford to continue the session if(r==G_SHOWDOWN) { c1->bot->opponentsPreviousCard = c2->bot->card; c2->bot->opponentsPreviousCard = c1->bot->card; } else { c1->bot->opponentsPreviousCard = -1.0; c2->bot->opponentsPreviousCard = -1.0; } } win1 = (c1->mny - INIT_STACK +0.0)/sqrt(sgi); // sgi must > 0. Take sqrt so as not to over-reward quick wins win2 = (c2->mny - INIT_STACK +0.0)/sqrt(sgi); c1->vp += win1; c2->vp += win2; } // for each session in the match } // playVonNeumannPokerMatch static long playVonNeumannPokerGame(PEntrant a, PEntrant b) { _Bool bCalls; Card ax, bx; Money aBet; long r=G_SHOWDOWN; // Unless each of the game's players can afford their ante, they cannot play a game. if(a->mny < ANTE || b->mny < ANTE) return G_MAYNOTBOTHPLAY; // players may not both play a->bot->card = ax = fRand(); b->bot->card = bx = fRand(); a->bot->money = b->bot->opponentsMoney = a->mny; b->bot->money = a->bot->opponentsMoney = b->mny; // Call A's bot to find out how much money A wants to bet. aBet = a->bot->a(a->bot); // But A may not bet more money than A has, nor yet more than the bet-limit aBet = aBet < 0 ? 0 : a->mny < aBet ? a->mny : aBet; aBet = aBet > BET_LIMIT ? BET_LIMIT : aBet; // EDIT 19 Aug 2020: A may not bet more money than B has. aBet = aBet > b->mny ? b->mny : aBet; // [If B cannot afford to call, B must fold; there is no need to call B's bot in such a case. Otherwise,] call B's bot to find B's reply (fold or call) // Treat A passing as A betting 0 and B calling bCalls = aBet < 1 ? 1 : b->mny < aBet ? 0 : b->bot->b(b->bot, aBet); if(!bCalls) // B folds { a->mny += ANTE; b->mny -= ANTE; r = G_FOLD; } else if(ax>bx) // B calls A's bet; A wins the showdown { a->mny += ANTE+aBet; b->mny -= ANTE+aBet; } else // B calls A's bet; B wins the showdown { a->mny -= ANTE+aBet; b->mny += ANTE+aBet; } return r; } // playVonNeumannPokerGame /*############################################################################# Bots This section is subject to change, and has my copies of user-submitted code for bots' a- and b-procedures ############################################################################### */ // This bot is so naive, it never bluffs. static Money naiveA(const Bot *bot) { Card x=bot->card; return 50.*x-25.; } static int naiveB(const Bot *bot, const Money aBet) { return bot->card>.5; } // This bot treats it like 3-card Kuhn poker static Money kuhn3A(const Bot *bot) { Card x=bot->card; Money m=bot->money; Money bet = 10; if(m<bet) bet = m; return 9.*x<1. || 3.*x>2. ? bet : 0; } static int kuhn3B(const Bot *bot, const Money aBet) { return bot->money>=aBet && 9.*bot->card>5.; } typedef char *String; static String botName[] = {"naive", "Kuhn3"}; static AProcType aProc[] = {naiveA, kuhn3A}; static BProcType bProc[] = {naiveB, kuhn3B}; static void initBots() { Bot *pBot; long i, j; for(i=0; i<nEntrants; ++i) { pBot = (Bot*)calloc(1, sizeof(Bot)); pBot->a = aProc[i]; pBot->b = bProc[i]; for(j=0; j<50; ++j) pBot->f[j] = 0.0; plr[i].bot = pBot; strncpy_s(plr[i].name, GAME_NAME_MAX+1, botName[i], GAME_NAME_MAX); } } // initBots static float fRand() { float r = rand(); return r / RAND_MAX; } static int cmpByVP(const Entrant* e1, const Entrant* e2) { return e2->vp > e1->vp ? 1 : -1; // map from floats to int +-1 } ``` [Answer] # LikeMe Bot Here's a simple bot. It mostly just assumes that the other bot bets roughly like it does. ``` int likemea(const Bot *bot){ // Always go big if we can't play again if we lose. if (bot->money < 10) return bot->money; // Force an all-in if there's a decent change we win. if (bot->card > 0.5 && bot->opponentsMoney <= 50) return bot->opponentsMoney; float max_pass = 0.5; float min_max_bet = 0.9; // Increase risk tolerance when in the lead. float lead = bot->money / (bot->opponentsMoney + 20); if (lead > 1){ // Don't go crazy. lead = lead / 2 + 1; if (lead > 1.5) lead = 1.5; max_pass /= lead; min_max_bet /= lead; } if (bot->card < max_pass) return 0; if (bot->card > min_max_bet) return 50; return (int)((bot->card - max_pass) / (min_max_bet - max_pass) * 50); } int likemeb(const Bot *bot, const int aBet){ // Get what I would have bet if I was a. int my_bet = likemea(bot); if (bot->money < 50){ // If I'm being pushed all-in, assume the other bot is playing riskier. my_bet = (int)(my_bet * 1.2); } if (my_bet >= aBet) return aBet; return 0; } ``` Please have mercy on my C. It's been a while, and I've never done much C anyway. [Answer] # Con-stats Bot Uses the power of probabilities and brute-force to choose better numbers than just '50%' or '50 money', the right constant stats to con you. ``` static Money constatsA(const Bot* bot) { Card x = bot->card; Money money = bot->money - ANTE; // ANTE is not taken out before call Money oppMoney = bot->opponentsMoney - ANTE; // same as above // Going all in is a bad strat normally? // Just put a minimum card, that'll fix it if (x > 0.72 && money < ANTE) return money; // If my card is over 0.71, I have an optimial chance of winning // make sure not to bet all _my_ money // BET_LIMIT + ANTE means that I can bet even harder, as they // don't need to go to 0, just low enough they can't ANTE anymore. if (x > 0.71 && oppMoney <= BET_LIMIT + ANTE && oppMoney < money) return oppMoney; // yep, 1. // Turns out, most bots self-destruct under their own weight? // Or they just get confused by the quite low bet. return 1; } static int constatsB(const Bot* bot, const Money aBet) { Card x = bot->card; Money money = bot->money - ANTE; if (x > 0.90) return true; // if it has enough for two more rounds // and a 55% of winning, go for it return x > 0.55 && money >= aBet + 2 * ANTE; } ``` Well, it was this, or making a neural network and exporting it to C. Never actually used C before, but C++ is close enough to know all this. Also, the controller's `Bot` struct is missing it's `opponentsMoney`. ]
[Question] [ I recently saw [this](https://esolangs.org/wiki/MarioLANG) language in a challenge and it's awesome. Does anyone have some tips for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")ing in it? Your tips should be at least somewhat specific to MarioLANG. Please post one tip per answer. [Answer] # Use the fall at the end for instructions This is a pretty simple tip but many MarioLANG programs end something like this, ending with Mario falling down: ``` ..... ===== ``` and this can be written instead as this: ``` .... ===. ``` saving two bytes. If your program has an elevator near an end like this you can often improve even further. This: ``` ]!...... =#====== < =" ``` goes to this: ``` ]!. =#. . . <. =". ``` You do have to be careful with the last one though, since the added spaces to get to the final instructions can in many situations be more costly than just writing it largely on one line. [Answer] # Duplicate input Sometimes, you will need multiple copies of a given input - here is a 27 byte snippet that will do this. ``` >[! "=# - ) ( + ( ) !+< #=" ``` Alternate 39 byte horizontal version: ``` > [! "=======# !-((+)+)< #=======" ``` Before: ``` Memory Pointer: ˅ Cell : n 0 0 ``` After: ``` Memory Pointer: ˅ Cell : 0 n n ``` ]
[Question] [ In this variant of the [Four fours puzzle](http://en.wikipedia.org/wiki/Four_fours) your should use up to `x` `x's` (and no other number) and a defined set of operations to reach every number from 0 to 100. If `x = 4` then you can use up to four `4s` and this question becomes the classic four fours puzzle (except you can use up to four 4s rather than having to use exactly four of them). We assume `1 < x <= 9`. In this version, only the following operators are allowed: * Addition (`+`), Subtraction (`-`), Multiplication (`*`), Division (`/`). Note this is real division, so that `5/2 = 2.5`. * Exponentiation (e.g. 4^4) as this would involve no extra symbols if written normally by hand. * You can make new integers by concatenating `xs`. E.g. you can make the integers `4, 44, 444, 4444`. You may also use parentheses to group numbers simply in order to control the order of evaluation of the operators. You can't for example combine parentheses with concatenation as in `(4/4)(4/4) = (1)(1) = 11`. No other symbols may be used and standard order of operations applies. Your program should generate, given an `x` in the defined range and an `n` between `0` and `100` inclusive, a correct solution for that input if it exists. Otherwise your code must output something to indicate no such solution exists. You must be able to run your submission to completion on your machine for any input values of `x` and `n` in the allowed range. This is code golf, so shortest solution wins. This old [related question](https://codegolf.stackexchange.com/questions/12063/four-fours-puzzle) uses more operators (and only 4s) and hence all numbers from 0 to 100 are solvable which won't be true for this challenge. **Input and output** Your code takes two integers `x` and `n` as input and should output a solution (or an indication there is no solution) in any human readable format you find convenient. Input `4 6` would mean "Using up to four 4s, make the number 6" for example. So if the input is `4 6` the output could be `(4+4)/4+4`. [Answer] # [Python 3](https://docs.python.org/3/), 265 bytes ``` def f(x,n): for e in g(x,x-(x>7)): try: if eval(e)==n:return e except:1 g=lambda x,d:{str(x)*-~i for i in range(d)}|{s%(a,b)for a in g(x,d-1)for b in g(x,d-a.count(str(x)))for s in'%s**%s (%s/%s) (%s+%s) (%s-%s) %s*%s %s/%s'.split()['**'in a+b:]}if d else{} ``` [Try it online!](https://tio.run/##rZHfaoMwFMbv8xQHhpjY2M3aP5vgnkMYu4hNdIJLJUmHxXav7pK4MmH0rleH3/nId87J153Mx0Gm48hFBRXuqSQZguqgQEAjobadPsb96464Phh1cgWaCsQXa7EgeS4zJcxRSRBWEf1edCZLUJ237LPkDHrKs0EbhXsSxd@N926ct2KyFpiTy3nQAWa0JE5i17E8Tnyj/Guw5f5wlAZPbsTL2sphoKMo0IAD/Rho4urit8auWtmqXgyXumsbg8lbGEWhdWaLMnu/2Hs4iFaL4TJ2qrEzKryiK0LQlVK6ndGaJskMNzTdzXBLN08z3NH1ZobPEz5c@cXz3QNAyDn6j3Mvi3z6NQQqH4obSSDny92Af1H4qTfyKKbdANQ5n2d5n2zsxtN56gc "Python 3 – Try It Online") Works for *all* numbers in the [reference](https://arxiv.org/pdf/1502.03501.pdf) linked by Engineer Toast. Runs up to `x=8` on tio, `x=9` takes a couple of minutes on my machine. --- The function `g` returns a set of all combinations with at most `x` number of `x`'s. `f` then loops through them and returns the first which evaluates to the number `n`. The number of possible values i found for each `x` are: ``` x possible numbers ------ 2 5 3 17 4 35 5 56 6 83 7 101 8 101 9 101 ``` All the numbers above can be generated from `(a+b)`, `(a-b)`, `(a+b)`, `a*b`, `a/b`, `(a/b)`, and `a^b`. `a+b` and `a-b` do not give more numbers. `a^b` is also only used once, as otherwise huge numbers are created (this is also verified in the reference document above) --- An alternate version which short-circuits as soon as it finds a solution (not as golfed): This is much faster as for `x=7..9` all numbers can be created. # [Python 3](https://docs.python.org/3/), ~~338~~ 289 bytes ``` def f(x,n,d=-1): d=[d,x][d<0];X=str(x);r=set() for E in{X*-~i for i in range(d)}|{s%(a,b)for a in[0]*d and f(x,n,d-1)for b in f(x,n,d-a.count(X))for s in'%s**%s (%s/%s) (%s+%s) (%s-%s) %s*%s %s/%s'.split()['**'in a+b:]}: try:e=eval(E) except:e=-1 if e==n:exit(E) r|={E} return r ``` [Try it online!](https://tio.run/##TY/BboMwDIbvPEWkCZHQ0EEp7UaXY98BCXEITdiQqoCSdKKi7NWZYaPiZH3@ZPt3e7dfjYrHUcgKVbijigoWRCR1kGC5oF2Ri4@wOGXMWI07ctLMSIuJg6pGozOqVZ/5wU89Yw2INFefEgsyPHrjYk5LMikOKg8LXyCuxHII7kyunMaWFt9empuyOCOzM@A81/i@axB2zatryFQ3/zWYKmiws/S2pr3WkC/3fN@DtXxTpsUA3yCr76lk8ptf8RniI9ldZGuhFURAdYUkYyqVHUzPXj9Yfx4cpKW9aXhrfGl1DcEqvKM7QpwnxvSwxj2NojUnND6u@UCTcM1Huk/W/PbHC77POP4C "Python 3 – Try It Online") ]
[Question] [ ## Introduction: You are a worker, who is in charge of managing a set of bridges, connecting a square grid of "nodes": ``` N - N - N | | | N - N - N | | | N - N - N ``` (the grid here is 3 by 3, but they can be larger). Each of the bridges has a set capacity from `1` to `10`, and each of the bridges has a number of cars over them, also from `1` to `10`. * If a bridge has a higher capacity than the number of cars on that bridge, then it is considered "safe", and you can cross over it. * If a bridge's capacity and number of cars going over it are equal, then it is considered "stable". It won't collapse, but you can't cross over it. * If a bridge has a lower capacity than the number of cars on that bridge, then it is considered "collapsing", and you only have a limited amount of time to fix it. When a bridge has `n` capacity and `m` cars, with `n` smaller than `m`, the time it takes to collapse is: ``` m + n ceil( ----- ) m - n ``` You must take materials (and therefore reduce the bridge's capacity) from other bridges and arrive to those bridges on time to fix them! To get materials from a bridge, you must cross over it. For example, take this small arrangement: ``` A - B ``` The bridge between `A` and `B` (which we'll call `AB`) has `3` capacity, and let's say you're on `A`, and want to take `1` material. To take the material, simply cross from `A` to `B`. *Note*: You don't have to cross the bridge multiple times to get multiple materials, you can take as much material as you want from a bridge in one go, as long as it doesn't cause the bridge to start to collapse. Now, `AB` has `2` capacity, and you have `1` material on you. You may only cross over bridges that are "safe", though (or if you're fixing a bridge, which is explained in the next paragraph). To fix a bridge, you must go over it, thereby depositing all materials needed to fix the bridge. For example, in the example above, if `AB` had `1` capacity and `2` cars currently on it, and you had `2` material on you, once you cross the bridge you will have `1` material, because that is all that's required to fix the bridge. You must fully cross a collapsing bridge before the bridge collapses, otherwise it will break. Each crossing of a bridge takes `1` hour, and the time it takes for the bridge to collapse is shown in the formula above. For example: ``` A | B | C - D ``` In this example, if your starting node was `A`, and `CD` only had a "lifespan" of 2 hours, the bridge would collapse before you can get to it (crossing `AB` takes 1 hour, crossing `BC` takes another hour). ## Task: Your task is to make a program that calculates, given a list of bridges, which are represented themselves as lists of two elements (first element is capacity, second element is cars on the bridge), whether or not it's possible to fix all of the bridges. The bridges work from top-to-bottom, left-to-right - so an input of ``` [[3 2] [3 2] [2 5] [5 1]] ``` means that the actual grid looks like this: ``` 3 A --- B | 2 | 3|2 2|5 | 5 | C --- D 1 ``` So `AB` has a capacity of `3` and `2` cars, `AC` has a capacity of `3` and `2` cars, `BD` has a capacity of `2` and `5` cars, and `CD` has a capacity of `5` and `1` car. ## Rules / Specs: * Your program must work for, at least, `10 * 10` grids. * Your program may accept the input as either a string with any delimiter, or a list of lists (see example I/O). * Your program must output the same value for true for all true values, and it must output the same value for false for all false values. * You can either submit a full program or a function. ## Example I/O: ``` [[5 5] [5 5] [1 1] [3 3]] => true [[2 5] [2 2] [3 3] [1 2]] => false [[3 2] [3 2] [2 5] [5 1]] => true NOTE, you can take the input like this as well: [[3, 2], [3, 2], [2, 5], [5, 1]] (Python arrays) 3,2,3,2,2,5,5,1 (Comma-separated string) 3 2 3 2 2 5 5 1 (Space-separated string) ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # Python3, 560 bytes: ``` R=range def V(b,x,y,X,Y): try:return[(b[x][y],b[x+X][y+Y])] except:return[] def f(r): K,w=0,int(len(r)**.5);b=[[K:=K+1for _ in R(w)]for _ in R(w)];e=dict(zip([l for x in R(w)for y in R(w)for l in V(b,x,y,0,1)+V(b,x,y,1,0)],r));q=[(e,0)] while q: e,c=q.pop(0);E=e.values() if all(a>=b for a,b in E):return 1 if c<min(-(-((b+a)/(b-a))//1)for a,b in E if a<b): for(j,k),(a,b)in e.items(): if a>b: for J,K in e: if(j,k)!=(J,K)and{j,k}&{J,K}: for s in R(a-b): Q=eval(str(e));Q[j,k][0]-=s;Q[J,K][0]+=s;q+=(Q,c+1), return 0 ``` [Try it online!](https://tio.run/##XVHBTuMwEL3nK8xlNUOmbdKq0qrF3LhsT@WwAlkWslNnyW5IUzdsGxDfXsZpAuzGh/Hze2@ex6nb5nFbzb7X/nS6ld5Uv1y0cbn4CZaO1NId3eMiEo1vF941z75SYNVRq1YT1/iOd/G9Rh0Jd8xc3Qwq3XXJwQf3ig4yoaJqoHQVH11ejue4tFKp1UKu4jTfevEgikrcwgH1v2jp5KbIGngpalClCORxIANov4IygOHqCaUYDyClBDV5xOVOKnABReLwWJRO7PiGwlEmd@N6W0OCyxvpxn9N@ez2gMwVuTBlCeZa2i7fkA05N9gPK9KzKLt6KioY8QIbG5yAHRnEySTFr66u3ZUN7yJCO/hNf5CAaWTajYvGPXFuR3faa3ved9k/aBW6uP6IBZ3/QgIzaKrNK8O3b6@M3gZNZ9yf38mM@uTuW0vHc8K@8eD4adaKzVoleiT3DLhHADGDXSxhTVmcIkWinzo51T780xyUmpOYaxIfNSWRhjojMdMaMfqUTnsJ1@mH5GyZ/iedfUqmvWVISYP09A4) ]
[Question] [ Wikipedia says about [Polar Coordinates](https://en.wikipedia.org/wiki/Polar_coordinate_system): > > In mathematics, the polar coordinate system is a two-dimensional coordinate system in which each point on a plane is determined by a distance from a reference point and an angle from a reference direction. > > > This seems perfect for describing hexagonal grids. Take the following hexagonal grid for example: ``` A B C D E F G H I J K L M N O P Q R S ``` Our reference point will be the center of the hexagon ('J'), and our reference angle will be to the top left corner of the hexagon ('A'). However, we'll describe the angle in terms of the number of *clockwise steps* around the outside of the hexagon from this point, not in angles. So we'll call it "Step number" instead of angle. For example, 'C' is at (2, 2) because it has a radius of 2 (since it is two rings away from the center, 'J'), and an step number of 2 (2 clockwise steps forward from 'A'). Similarly, 'O' is at (1, 3), because it is one ring away from the center, and three clockwise steps forward from 'E' (which is on the reference angle). For completeness, 'J' is at (0, 0), since you need 0 steps out and 0 steps clockwise to reach it. Now, you can also describe a hexagonal with [Cartesian Coordinates](https://en.wikipedia.org/wiki/Cartesian_coordinate_system), but because of the offset this is a little weird. Just like with our polar coordinates, we will put the center at (0, 0). Each space takes up a coordinate also, so 'K' is at (2, 0), not (1, 0). This would put 'A' at (-2, 2), and 'O' at (1, -1). # The challenge Given polar hexagonal coordinates, output the same coordinates in Cartesian coordinates. You may take these coords, and the output the answer in any reasonable format. This means that you may reverse the order of the inputs if you like. This also means you could output the coords as (Y, X), but if you do, please mention this in your answer to avoid confusion. You do not have to handle negative radii, but you may get negative angles, or angles that go more than a full revolution around the hexagon. For example, you may receive (1, 10), or (1, -2) as input. These would both correspond to 'N' in our previous hexagon. You do *not* have to handle non-integers for input. # Sample IO ``` #Polar #Cartesian (0, 0) (0, 0) (1, 2) (2, 0) (6, 0) (-6, 6) (2, -3) (-3, -1) (4, 23), (-5, 3) (5, -3), (-8, 2) (10, 50), (-20, 0) (6, 10), (10, 2) (8, 28), (0, -8) (8, -20), (0, -8) ``` [Answer] # JavaScript (ES6), 93 bytes ``` (r,d)=>[...Array(d+r*6)].map((_,i)=>x+="431013"[y+="122100"[i=i/r%6|0]-1,i]-2,x=y=-r)&&[x,-y] ``` Test snippet: ``` f=(r,d)=>[...Array(d+r*6)].map((_,i)=>x+="431013"[y+="122100"[i=i/r%6|0]-1,i]-2,x=y=-r)&&[x,-y] g=([r,d],e)=>console.log(`f(${r},${d}):`, `[${f(r,d)}]`, "expected:", `[${e}]`) g([0,0],[0,0]) g([1,2],[2,0]) g([6,0],[-6,6]) g([2,-3],[-3,-1]) g([4,23],[-5,3]) g([5,-3],[-8,2]) g([10,50],[-20,0]) g([6,10],[10,2]) g([8,28],[0,-8]) g([8,-20],[0,-8]) ``` [Answer] ## JavaScript (ES6), 95 bytes ``` f=(r,t,x=-r,y=r,d=2,e=0)=>t<0?f(r,t+r*6):t>r?g(r,t-r,x+r*d,y+r*e,d+e*3>>1,e-d>>1):[x+t*d,y+t*e] ``` Explanation: The solution for a zero angle is simply `-r,r`, so we start at that point. If the angle is negative, we add on a whole hexagon and call ourselves recursively, otherwise we start walking around the hexagon with a `d,e=2,0` step. Where possible, we leap `r` such steps, then rotating the step using the formula `d+e*3>>1,e-d>>1` to progress to the next side. Finally we take any remaining steps to reach our destination. ]
[Question] [ A couple months ago, we had a [discussion on meta](http://meta.codegolf.stackexchange.com/q/7683/42545) about increasing the reputation awarded for upvotes on questions. Here's the basics of our current reputation system for votes:1 * A question upvote `U` is worth 5 reputation. * An answer upvote `u` is worth 10 reputation. * A question or answer downvote `d` is worth -2 reputation. There have been many different suggestions for a new system, but the current most popular is identical to the above, but with question upvotes scaled to +10 rep. This challenge is about calculating how much more rep you would earn if this system were put into place. Let's look at an example. If the voting activity was `UUUUuuuuUUUUUduuudUU`, then you'd earn 121 under the current system: ``` U x 4 x 5 = 20 = 20 u x 4 x 10 = 40 = 60 U x 5 x 5 = 25 = 85 d x 1 x -2 = -2 = 83 u x 3 x 10 = 30 = 113 d x 1 x -2 = -2 = 111 U x 2 x 5 = 10 = 121 Total: 121 ``` But the same activity would earn 176 under the new system: ``` U x 4 x 10 = 40 = 40 u x 4 x 10 = 40 = 80 U x 5 x 10 = 50 = 130 d x 1 x -2 = -2 = 128 u x 3 x 10 = 30 = 158 d x 1 x -2 = -2 = 156 U x 2 x 10 = 20 = 176 Total: 176 ``` You would gain **55 rep** from this scenario. So far, calculating the changed rep isn't that hard; just count the number of `U`s and multiply by 5. Fortunately, the rep system isn't that simple: there is also a **rep cap**, which is the most reputation you can earn from votes in one UTC day. This is set to 200 on all sites. Also, the rep cap applies in real time: if you have already earned 196 rep and you receive an answer upvote, you will now have 200 rep. If you get a downvote right after that, the 2 rep will be subtracted from 200, so you will have 198 rep. With the voting activity `UUUuuuuUUUUuuuuUUUUUUUd`, you would earn 148 rep under the current system: ``` U x 3 x 5 = 15 = 15 u x 4 x 10 = 40 = 55 U x 4 x 5 = 20 = 75 u x 4 x 10 = 40 = 115 U x 7 x 5 = 35 = 150 d x 1 x -2 = -2 = 148 Total: 148 ``` But you would earn 198 under the new system: ``` U x 3 x 10 = 30 = 30 u x 4 x 10 = 40 = 70 U x 4 x 10 = 40 = 110 u x 4 x 10 = 40 = 150 U x 7 x 10 = 70 = 200 (rep capped) d x 1 x -2 = -2 = 198 Total: 198 ``` Thus, the increase is **50 rep**. ## Challenge Your challenge is to write a program or function that takes in a multi-line string and outputs the total rep that would be gained with the above algorithm. Each line counts as 1 UTC day, so the rep cap only applies once per line. ### Test cases (One or more lines of input, followed by the output integer.) ``` UUUuudd 15 UUUuUUUUuUuuUUUUudUUUUuU 57 UUUuUUUUuUuuUUUUudUUUUuU UUUuudd 72 uuuuuuu uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu uuuuuuuuuuuuuuuuuuuu UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU 0 UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU 5 (empty string) 0 UUUuuuuuUUUuuUUUUUUuuuUUUuuUUUUuuuuUUUdddddddUU 4 UUUuuuuuUUUuuUUUUUUuuuUUUuuUUUUuuuuUUUdddddddUU UuuUUUudUU UUUUUUUUUuuuuuuUUUUUUuuUUUUUUuuuuuUUUUUUUUuUUUuuuuUUUUuuuUUUuuuuuuUUUUUUUUuuUUUuuUU UUu U d UU UUUUUUUUUUUU 119 ``` **This is code golf, so shortest code in bytes wins.** Related challenges: [Calculate the bounded cumulative sum of a vector](https://codegolf.stackexchange.com/q/61684/42545), [Calculate your stack exchange reputation](https://codegolf.stackexchange.com/q/25047/42545) 1 This is a highly simplified version of the system. You also lose 1 rep for downvoting an answer, and there exist unupvotes, which [are weird and follow rules of their own](http://chat.stackexchange.com/transcript/message/27282054#27282054); and undownvotes, which [don't even have rules to follow](http://chat.stackexchange.com/transcript/message/25083191#25083191). [Answer] # Haskell, ~~98~~ 93 bytes Thanks to BlackCap to golf this further. Now, I think to try lambda in later challenges, now. ``` x#'U'=x _#'u'=10 _#'d'=(-2) a&b=foldl1(\d g->min 200$d+a#g) g=sum.map(\x->(10&x)-(5&x)).lines ``` The first 3 lines is the scoring, a&b is is the score, f is the difference and the g is the function sastifying the specification. Usage: ``` g"UUUuuuuuUUUuuUUUUUUuuuUUUuuUUUUuuuuUUUdddddddUU" -- 4 ``` [Answer] ## ES6, 104 bytes ``` s=>s.split` `.map(l=>(g=U=>[...l].map(c=>(r+=eval(c))>200?r=200:0,r=0)|r,t+=g(10)-g(5)),u=10,d=-2,t=0)|t ``` Calculates the before and after rep for each line. My first use of `eval`! [Answer] # Lua, 196 Bytes This program takes a single multi-line argument as input, and print the total difference in rep' ``` e,f,a=0,0,{u=10,U=10,d=-2}arg[1]:gsub(".-\n",function(s)x=0 y=0 s:gsub("[^\n]",function(c)t=x+a[c]x,t=t>199 and 200 or t,y+a[c]-(c<"V"and 5 or 0)y=t>199 and 200 or t end)e=e+x f=f+y end)print(e-f) ``` I assumed I am allowed to ask for a trailing new line in the input, if I'm not, here's a 204 Bytes solution that doesn't need it. ``` e,f,a=0,0,{u=10,U=10,d=-2}(arg[1].."\n"):gsub(".-\n",function(s)x=0 y=0 s:gsub("[^\n]",function(c)t=x+a[c]x,t=t>199 and 200 or t,y+a[c]-(c<"V"and 5 or 0)y=t>199 and 200 or t end)e=e+x f=f+y end)print(e-f) ``` ### Ungolfed and explanations ``` a={u=10,U=10,d=-2} -- define the table containing the vote values e,f=0,0 -- initialize the total sums of rep' arg[1]:gsub(".-\n",function(s)-- iterate over each line x=0 -- score by the new scoring method for this UTC day y=0 -- score by the old method s:gsub("[^\n]",function(c) -- iterate over each non new-line character t=x+a[c] -- new score for today x=t>199 and 200 or t -- reduce it to 200 if >=200 -- Do the same thing with the old scoring method t=y+a[c]-(c<"V"and 5 or 0)-- if c=="U", this question vote gives only 5 y=t>199 and 200 or t end) e=e+x f=f+y -- sum the scores over multiple days end) print(e-f) -- output the difference ``` [Answer] ## Perl, ~~104~~ 91 + 2 = 93 bytes ``` sub f{200*$.>$_[0]?$_[0]:200*$.}for(/./g){$a=/d/?-2:10;$s=f$s+$a;$o=f$o+$a-5*/U/}}{$_=$s-$o ``` Requires the `-p` flag: ``` $ echo UUUuUUUUuUuuUUUUudUUUUuU | perl -p recalc.pl 57 $ echo "UUUuUUUUuUuuUUUUudUUUUuU UUUuudd" | perl -p recalc.pl 72 ``` Breakdown: ``` sub f { # '$.' contains the line number (1, 2, ... n) 200*$. > $_[0] ? $_[0] : 200*$. } for(/./g){ $a= /d/ ? -2 : 10; $s=f( $s + $a ); # /U/ returns `1` if true $o=f( $o + $a - 5*/U/ ) } }{ # Eskimo exit while loop (do this after the outer (from -p) iteration) $_=$s-$o ``` ]
[Question] [ Someone's given us a string, but all bracket-like characters have been changed into normal ones, and we don't know which, or even how many there were. All we know is that if `L1,L2,L3,...,LN` were different kinds of left brackets and `R1,R2,R3,...,RN` were different corresponding kinds of right brackets, all being distinct (2N distinct bracket characters), a string would be valid iff it is one of (+ is normal string concatenation): * `L1+X+R1`,`L2+X+R2`,...,`LN+X+RN`, where `X` is a valid string, * `X+Y`, where `X` and `Y` are valid strings, * Any single character that is not a bracket character. * The empty string We know they started out with a valid string before they changed the brackets, and they didn't change them into any characters that already existed in the string. At least one pair existed for each bracket as well. Can you reconstruct which characters were originally left and right bracket pairs (find the `Li` and `Ri` following the given conditions)? Output the pairs of characters that were brackets. For example, if `(){}[]` were actually bracket characters, you might output `(){}[]` or `{}[]()` or `[](){}`, etc. There may be multiple ways to do this for a string, you only need to return one such that there is no bracket assignment with more pairs (see examples). Note that the output string should always have an even length. Examples: `abcc` - `c` cannot be a bracket, since there is no other character with two occurrences, but `ab` can be a bracket pair, so you would output exactly `ab`. `fffff` - any string with at most one character cannot have brackets, so you would return the empty string or output nothing. `aedbedebdcecdec` - this string cannot have any brackets because there is 1 a, 2 bs, 3 cs, 4 ds, and 5 es, so no two characters occur the same number of times, which is a requirement to have brackets. `abcd` - possible assignments are `ab`, `cd`, `abcd`, `cdab`, `adbc`, `bcad`, `ac`, `ad`, `bc` and `bd`, (as well as the empty assignment, which all of them have) but you must return one of the longest assignments, so you must return `abcd`, `cdab`, `adbc`, or `bcad`. `aabbcc`,`abc` - these both have `ab`, `ac`, and `bc` as valid pairs. You must return one of these pairs, doesn't matter which. `abbac` - a and b have the same character count, but they can't actually work, since one of them occurs to both the left and right of all occurrences of the other. Return nothing. `aabcdb` - `cd` and `ab` are the exact two bracket pairs, so output either `cdab` or `abcd`. `abcdacbd` - only one pair can be achieved at once, but `ab`,`ac`,`bd`,`cd`, and `ad` are all of the possible pairs you can return. No matter which pair you choose, it has an instance where a single other character is within it, which prohibits any other pairs, except in the case of `ad`, where the other pairs `bc` and `cb` are not possible alone either, and so can't be possible with `ad`. This is code golf, so shortest code in bytes wins. Input is from STDIN if possible for your language. If it isn't possible, indicate the input method in your answer. [Answer] ## Ruby, 373 bytes ``` i=gets.chomp b=[*(i.chars.group_by{|x|x}.group_by{|x,y|y.size}.map{|x|s=x[1].size x[1][0...s-s%2].map{|x|x[0]}*''}*'').chars.each_slice(2)] puts [*[*b.size.downto(1).map{|n|b.combination(n).map{|t|[t*'',(h=Hash[t] s=[] o=1 i.each_char{|c|s.push(c)if h.keys.include?c (o=false if s.empty?||!h[s.pop].eql?(c))if h.values.include?c} o ?s.empty?: o)]}}.find{|x|x[0][1]}][0]][0] ``` This uses a golfed version of the stack parser [here](https://stackoverflow.com/a/25979589/1995101). It can probably be simplified further, but I don't think my brain can handle any more. **All test cases:** <http://ideone.com/gcqDkK> **With whitespace:** <http://ideone.com/pLrsHg> **Ungolfed (mostly):** <http://ideone.com/oM5gKX> ]
[Question] [ # A simple register calculator This challenge involve a simple register calculator that works in the following way: * It has some registers named `A,B,C,...,Z`, each of them can contain an integer, they are all initialized to `0`. * It executes instructions of 3 characters: The first character of any instruction is one of `+,-,*,/,=` (add, subtract, multiple, divide, copy), the second character is the name of a register, and the third character is the name of a register or one of `0,1`. The meaning of the instruction should be quite clear, here some examples: + `+AB` means "set the value of the register `A` to the result of `A + B`", and similarly for `-AB,*AB,/AB`. The division `A / B` is done as in C. + `+A1` means "increment the register `A` of `1`", and similarly `-A1` decrements `A` of `1`. + `=AB` means "copy the value of `B` into the register `A`, similarly `=A0`, `=A1` sets `A` to `0`, `1`, respectively. * It takes as input a string of consecutive instructions and it returns the result of the last operation, some examples: + Given `=A1+A1*AA` it returns `4`. + Given `+A1+A1=BA+A1*AB` it returns `6`. + Given `+A1+A1+A1*AA=BA-B1*AB` it returns `72`. It is easy to write such a calculator in your preferred programming language, here an example in Python: ``` def compute(cmd): opr = {"=": lambda x, y: y, "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y} reg = {"0": 0, "1": 1, "A": 0, "B": 0, "C": 0, "D": 0, "E": 0} ans = 0 i = 0 while i < len(cmd): op = cmd[i] r1 = cmd[i + 1] r2 = cmd[i + 2] reg[r1] = ans = opr[op](reg[r1], reg[r2]) i += 3 return ans ``` # The challenge Write a program in any programming language that takes as input a positive integer `n` and returns a string of instructions that the calculator described above evaluates to `n`. For example, given `n = 13` a valid output for your program could be `+A1+A1+A1=BA+A1*AB+A1`. There are some restrictions: * Standard [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * The source code of your program should not exceed 1024 characters. # How to compute your score Run you program on each of the following 1000 random integers and sum the total number of operations in each output. For example, `+A1+A1+A1=BA+A1*AB+A1` consists of 6 operations, note that the copy instructions `=` are NOT operations and you should not count them. ``` 3188162812 3079442899 158430004 2089722113 3944389294 2802537149 3129608769 4053661027 2693369839 420032325 2729183065 4214788755 680331489 3855285400 4233942695 4206707987 2357544216 457437107 2974352205 3469310180 3552518730 4140980518 2392819110 2329818200 662019831 2841907484 1321812679 2853902004 2272319460 133347800 1692505604 2767466592 3203294911 1179098253 2394040393 2013833391 3329723817 977510821 2383911994 1590560980 2045601180 1324377359 1586351765 1604998703 3016672003 3653230539 1466084071 2746018834 1056296425 3225491666 2113040185 918062749 3506683080 1809626346 3615092363 3944952222 4281084843 137951018 577820737 2304235902 4143433212 3183457224 294693306 1680134139 689588309 3657258008 2664563483 628899295 886528255 2539006585 2767153496 2742374091 2927873610 3725967307 2252643563 2716697503 1098010781 895335331 305272851 2605870648 3473538459 2739664556 2127000353 1774191919 3239195523 3120846790 3239808174 2588745068 3363081711 3105613110 3443977876 3233369379 949558184 2159450658 2930876206 1714955144 712790171 2472327763 3524210951 24655707 754856403 3220292764 708275816 2369186737 2485130017 404438291 1444836457 3936354990 3488645083 3881548856 1385884481 3750970390 1355492018 4246667593 791749996 1768738344 4014670055 3594141439 3111942631 2763557857 250495911 1635747286 1397550167 35044748 826650975 1249876417 2756572453 2014910140 1934230545 3893965263 1921703452 3479225211 232639352 1205471850 3147410912 4161504178 3896565097 336993337 898565456 1377983619 627866260 2972370545 2867339047 1517056183 3113779980 3650970589 105184832 3785364530 1892053898 2844419064 3581584776 773357885 1635965442 579795505 1082737975 4177210361 33726403 500010881 3770114942 1949554222 1808394144 2552929558 1679344177 4127951276 3703470385 2167661112 2012330972 3330988942 1625024662 4028645080 2268576559 1122753547 2801157103 2297468355 1248325165 3040195088 1505917132 1975920989 1331044994 1060195583 4053434779 1711909914 4165818150 1144987338 2582851730 159607843 4224173218 1122473605 4137009351 1859108466 140046799 3608276151 3755161872 1715239079 2210528921 4149673364 1683676925 3555426962 1903470380 1647594563 3992028616 831939758 1940233614 616234640 1033981562 989110726 3308560842 1362495884 2271865210 2497232294 2166547324 3134965769 1407359056 184303653 876724554 2257276636 1339263453 1505646879 4103125312 602341088 3411146479 4076735898 988798982 2881621101 3835638677 350262003 2083944362 793689959 1796614310 1722728365 1419496784 311460422 988078714 1191131280 685548336 2073528073 1341976830 1380421367 854492684 2349152 2760841279 3512440862 3492462961 955419776 134666263 1515743147 2802649615 343970838 5900423 3640581071 3690344254 33097513 3453017483 2702390881 2881748921 488817210 3179354661 3029418544 70044411 1956963103 1138956191 4099413570 113469500 2905850103 2267006431 990605747 2016466413 1406729175 457735529 1987564886 2555785209 2550678495 1324710456 1215784300 717815828 1894258881 2929394992 2793836849 1428923741 633224565 3516183531 221895161 2798935778 517240774 1906654368 3577752510 1412213936 978042011 741638677 1565247138 2333064112 2549498124 212184199 1539484727 3421514248 1918972072 933315257 1744663538 3834248593 1024107659 112895438 3354823598 3126205726 375723484 2105901209 287450971 669099946 1397558632 2606373532 125689337 3717502670 3258204174 1650199158 600374361 368452551 3686684007 3030953879 492919617 1203996049 863919924 2155962926 2878874316 1081637213 4025621502 969421830 906800845 732593812 3705231669 100350106 2062905253 2394749290 1537677769 2230238191 447840016 1442872240 2024556139 3023217942 4009927781 643221137 1779666873 3953330513 2024171749 795922137 997876381 1924314655 1177794352 3951978155 2649627557 1497778499 1718873438 1921453568 1327068832 2832829727 2225364583 1476350090 2647770592 3820786287 916013620 3982837983 3614316518 308109070 1800544679 2981621084 1428321980 4050055605 1492289670 2386916424 3191268731 580405899 2267245329 1732073940 1096029767 1295821464 3364564864 2652920150 3364522304 488005592 2192878399 160846995 218793067 300953008 3159368600 3645636269 2691580186 827223351 3050975392 1465133880 1478016997 1719998613 652363401 2555898614 4066532621 1765212455 34216921 1638964775 1371429240 838490470 82423487 1714800592 3494875381 3873346547 4054782046 3696936256 4275305812 2168667803 4160190912 3795501892 1459579204 3788779072 265527890 854488955 2942834006 2379627823 518232762 518434777 3944651255 3797616526 3707541025 322349517 474725696 3644506417 298197509 2568152353 2590844880 3117635513 1074315194 4084685556 2962342284 2653600388 3288534723 3794138452 1647860359 4009971876 2133083710 3370033103 47844084 1104447774 1945114365 3574343235 3780282459 3381199373 1018537272 1382098367 1412005134 1344062628 2346644176 722899092 2614932463 2145401890 827890946 255045026 1886847183 2717637818 1153049445 1367369036 2426902133 1836600086 3249356599 3406700718 2782602517 805660530 2582980208 2668716587 1318623475 3718765477 3906582528 2049615170 2266673144 693017899 1850804437 3662076224 1439399599 3609671497 3521926429 661675539 3211764017 3849411286 3961495122 3240515755 3110520252 3247223395 2601642984 531083777 1428656097 2621375427 1425006097 3346815151 1736182994 2749088925 3828456894 522766581 1596198864 1089234568 516631143 1714958540 550383692 2205580129 1129010921 2855807192 843448099 2537619198 2817077189 1862738454 1292393032 1867270512 3245153467 1330535377 63085178 476740794 3784629223 1469948976 2840691011 1501561593 2222500334 1417999206 1501666518 1146520258 853475958 688318779 2212745726 3697365636 4188412866 1971070414 2765322323 3338736319 4106229372 3547088973 3610171853 417218792 2645989082 2625322695 3788226977 866881900 3042410163 3339075441 1434921464 2037891551 4265507318 1488099724 573885128 528293886 863928770 2214944781 3913280213 3752689511 3519398632 549671367 662190591 3578320334 1609736323 1920189717 2049295962 1680309555 3056307661 237881083 1746281815 3988208157 2505692550 533953235 3859868829 3792904168 3181176191 764556169 78617399 3222196435 2366977555 608590681 303423450 559903926 1444205960 2795852572 3461738581 2509323146 2734638697 118860267 1918139288 2567665860 2153622033 3097512138 4224583193 1308314884 1348993134 3573313872 80532767 373807250 3963872687 1414605355 1390608957 1438723366 3335250816 3812365414 1257060108 1155935111 2101397457 1834783042 1751275025 1697354321 2932378401 1665717453 1378885897 3863913849 169333097 1073827664 777437131 3466174585 4046814722 2525749031 2116514103 2240001267 3455152569 579339098 2014028365 3808320943 1577950380 2691778801 3752766002 3849855789 1537004930 384431257 2179992010 36153591 4192751001 1804838630 987326618 4149586235 2231006803 3583701679 820347619 316668661 709355791 3570998394 1949820944 2602827205 4168457060 4281494037 3371936535 2794977651 2859282911 3673967898 13357998 1321990240 1432920498 2348123485 205633677 1467790392 3366396640 382875586 3791338683 478208002 2728443830 2837394277 3723656578 289818980 3607540282 1775363546 2183739548 4177115501 775276465 1690545788 1075449013 572714464 2769169223 3277515030 3206017211 763710358 2535539628 538656028 1428522787 2412864965 2447537924 3399886379 1955069748 73813115 2985639257 3129134081 2902917098 3832348869 2446124823 1520308572 2779582451 3152572003 284626848 2622927684 2243844449 2707184379 3996077339 1143205932 4249437886 4013946423 1243498130 2239561716 2454002725 3202102404 3489290520 568827898 2077682453 1973647425 2311090024 3452693414 566624799 1905493748 3381640023 3228957600 2097911855 3346084948 2492783447 2933529940 2933060277 509789087 4110089257 2789615392 2293641703 3346767700 2861425094 1325878754 2100601638 3154735442 1589556635 543727545 2077077585 2301440962 3562819978 3678224450 88375847 2286883432 810549767 4111034512 672827645 3538058849 3243887391 4260719631 3878976366 1173949115 522599614 2237854030 3700071391 3701211843 2474968151 1856102230 1612779479 417924004 1408725257 3663088753 1092263738 373569884 1394203899 2687184291 2200173651 16483411 2144831293 1953173328 2680701575 1891347549 594615324 2941482356 1349499420 2341998425 3246298001 3915604073 2598997329 2742107968 1706515316 3230227853 1698480626 3171621896 3553701103 3699504403 3264436517 789435265 1540974002 76880268 2021546521 228600347 3120127535 855819397 913492933 1706352147 3824217844 4254086533 4210176230 247387836 3028729765 1294455673 832399118 1989368151 3843532893 4058042419 4176223654 1871853736 2245388136 3396787616 453433399 3628835268 13531968 1038657709 2005262423 409396841 3236752715 504051173 1284135365 1498489066 1951495621 785956452 979254655 1255744440 2124184282 1791931889 2785197261 941345859 2272057653 105734226 1038331147 3859502227 1364397134 1151431380 3572487724 3440271596 3567083908 3969594482 2717167268 2070800249 565656056 2585323347 3710407107 1655322191 2871691151 1578274901 925898023 98152205 2387892947 3688205134 1060122118 3601926463 3963544592 2836575178 3517776876 1116673438 4141604495 3702313624 3321374643 3027449932 446202974 2704262583 1454829930 310100992 4167677094 4283752410 3749990846 3082431927 3668805960 4197104147 2921050366 40497657 1198947069 4265036060 3094866761 732821358 3734577383 3582534668 1453076357 881135315 3444396361 3113501566 2961866531 3235889511 2927326630 151940017 498024918 427292182 4276572621 2573590608 901394328 2351057309 1560851771 836443396 702781140 4143407241 3833119244 1092986235 3835147739 2801574120 2220928350 2773965488 1092717858 2314157136 4281370255 1044194898 4056801311 2672327460 2464844936 2964067147 535238874 34767265 4052881906 277239886 3205998707 4168364957 3390679324 3154285793 3493261782 1364027732 633131904 2306043313 253100060 3085422190 1571296680 1116733249 517969149 2063982173 1580514293 2306636650 211667764 43257052 2187912911 1419556982 2885452390 475014467 4276725894 2112535198 1381468052 3535769995 3030340194 2554618335 701632787 3621637286 200999835 2299787216 148189901 476612087 3139125858 1721355976 2863292989 270189306 1574116759 4001329945 616943685 3636040393 1361384267 1959022335 122277322 2067861043 2294386020 1121565222 1844367203 3119120617 1420612680 1541302975 3197481918 648483752 451388069 856130175 2960393334 988907653 1730735603 1640257249 1832729474 306034410 853922102 2001624344 3253510094 3906676405 37452680 3779097581 1958179154 2395885855 800614078 2085912 3020166783 2260099399 3490922778 2459139074 3886269878 3341685647 1050712773 59317986 3041690572 3236133509 2401182200 1535265086 1663785422 3664887088 3252400434 377629836 1024996414 1518007563 1821746700 1231613438 1709191483 2422047361 1393454235 2346354546 3263498417 3321719966 3652825361 948364811 371026554 2175702095 1880788290 4214724129 503657540 ``` The same list of numbers [can also be found on Pastebin](http://pastebin.com/82iNkA7t). The lower your score is, the better it is. Good luck! **NOTES:** * I choose random integers between 0 and 2^32-1, so that computations could be performed in C (unsigned long) or other languages without native support for arbitrary sized integers. However, be careful of overflows! * When computing your score, check also that the output of your program is correct, it's easy to make errors. * I wrote a script of 512 characters that got a score of 27782. [Answer] ## Java, Total Score: 46009 operations *Saved **2000** operations thanks to steveverrill and **1000** thanks to Bob!* ``` z->{String s=Integer.toBinaryString(z),r="=A1";for(int j=s.length()-1;j>=0;j--){if(s.charAt(j)=='1')r+="+CA";r+=j>0?"+AA":"";}return r;}; ``` Test it with this full program: ``` public class Calculator { public static void main (String[] args) { A a = z->{String s=Integer.toBinaryString(z),r="=A1";for(int j=s.length()-1;j>=0;j--){if(s.charAt(j)=='1')r+="+CA";r+=j>0?"+AA":"";}return r;}; System.out.println(A.a(117)); } public interface A { void a(int c); } } ``` Caculates the strings based on the binary representations of the input numbers. Score calculated with this program: ``` public class Calculator { public static void main (String[] args) throws FileNotFoundException { FileInputStream is = new FileInputStream(new File("test.txt")); System.setIn(is); int c = 0; Scanner input = new Scanner (System.in); while (input.hasNext()) { c+=s(new Long(input.nextLine())).length()/3-3; } System.out.println(c); } public static String s(long z){String s=Long.toBinaryString(z),r="=A1";for(int j=s.length()-1;j>=0;j--){if(s.charAt(j)=='1')r+="+CA";r+=j>0?"+AA":"";}return r;} } ``` [Answer] Since the question got some votes, but only an answer was posted since so far, I post an answer (but not the 512 characters / 27782 score mentioned in the question). # Python, Score: 35238 ``` def f(n): cmd = "=B1=C1+C1+C1" while n > 0: r = n % 3 n /= 3 if r == 1: cmd += "+AB" if r == 2: cmd += "-AB" n += 1 if n > 0: cmd += "*BC" return cmd ``` The idea is the same of GamrCorps's answer, but instead of using binary representation I used [balanced ternary representation](https://en.wikipedia.org/wiki/Balanced_ternary). Why does it work better? Because a positive integer `n` has approximately `log(n)/log(2)` digits in base `2`, and on average half of them are `1`'s and the other half are `0`'s, hence about `(1/(2 log(2))) log(n) = 0.72... log(n)` instructions are required. In ternary balanced representation, `n` has about `log(n)/log(3)` digits, on average a third of them equal to `1`, and another third equal to `-1`, hence about `(2/(3 log(3))) log(n) = 0.60... log(n)` instructions are required. ]
[Question] [ # Write an interpreter for [2B](http://esolangs.org/wiki/2B) I like [David Catt](http://esolangs.org/wiki/User:David.werecat)'s esoteric language 2B, having memory stored in a tape where each cell is a seperate tape of bytes (the 'subtape'). Write an interpreter for it! ## Language Specification Official specification can be found [here](http://esolangs.org/wiki/2B#Instructions). In this specification, `"` means a number in the range `0-9` (`0` is interpreted as `10`), and `_` means a string of any length. Each cell stores a value in the range `0-255`, and overflow/underflow wraps around as it would a BF. (Thanks @MartinBüttner). To convert text to numbers `0-255`, use [ASCII codes](http://www.asciitable.com/). Because I can find no detail on this, I'm going to say that the tape length should be `255` minimum, but if you know otherwise please edit. ``` +-------------+----------------------------------------------------------------------------------------------------------------------------------------+ | Instruction | Description | +-------------+----------------------------------------------------------------------------------------------------------------------------------------+ | 0 | Zeroes the current cell and clears the overflow/underflow flag. | | { | If the current cell is zero, jump to the matching }. | | } | A placeholder for the { instruction. | | ( | Read a byte from the input stream and place it in the current cell. | | ) | Write the value of the current cell to the console. | | x | Store the value of the current cell in a temporary register. | | o | Write the value of the temporary register to the console. | | ! | If the last addition overflowed, add one to the current cell. If the last subtraction underflowed, subtract one from the current cell. | | ? | Performs a binary NOT on the current cell. | | +" | Adds an amount to the current cell. | | -" | Subtracts an amount from the current cell. | | ^" | Moves the subtape up a number of times. | | V" | Moves the subtape down a number of times. | | <" | Moves the tape left a number of times. | | >" | Moves the tape right a number of times. | | :_: | Defines a label of name _. | | *_* | Jumps to a label of name _. | | ~_~ | Defines a function of name _. | | @_@ | Calls a function of name _. | | % | Ends a function definition. | | #_# | Is a comment. | | [SPACE] | Is an NOP. | | [NEWLINE] | Is treated as whitespace and removed. | | [TAB] | Is treated as whitespace and removed. | +-------------+----------------------------------------------------------------------------------------------------------------------------------------+ ``` ## Tests ``` +0+0+0+0+0+0+0+2)+0+0+9)+7))+3)-0-0-0-0-0-0-0-9)+0+0+0+0+0+0+0+0+7)-8)+3)-6)-8)-7-0-0-0-0-0-0) ``` Should output `Hello world!` --- `+1:i:{()*i*}` Sort of a `cat` program, just without a newline. --- `+1:loop:{@ReadChar@*loop*}@PrintHello@@WriteAll@(~ReadChar~(x-0-3<2o^1>1+1>1%~PrintHello~+0+0+0+0+0+0+0+2)-1+0+0+0)+7))+3)+1-0-0-0-0-0-0-0-0)%~WriteAll~<1x:reverse:{<1v1>1-1*reverse*}o-1:print:{-1<1)^1>1*print*}%` Should first accept a name, then, on press of `Return`, should output `Hello name` (where *name* is what was inputted). Credit for that program goes to [David Catt](http://esolangs.org/wiki/User:David.werecat). --- I'm working on a full test program. ## Rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden * Your interpreter must meet all the specifications, except for comments, which are not required. ## Scoring * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins! * -10 bytes if your interpreter handles comments. ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` ``` var QUESTION_ID=67123;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table> ``` [Answer] # Python2, ~~748~~ ~~736~~ ~~731~~ ~~709~~ ~~704~~ 691 bytes This was a fun little challenge, I am sure I can make this code even shorter (maybe I'll do that at some point later). ``` from sys import* w=stdout.write p=open(argv[1],'r').read() c,r,s,x,y,t,o=0,0,256,0,0,0,0 g=[[0]*s]*s e=lambda d:p.find(d,c+1) def h(i,j=0,k=0):global c,x,y;c+=1;n=1+(int(p[c])-1)%10;l=g[x][y]+n*i;g[x][y]=l%s;o=l/s;x=(x+n*j)%s;y=(y+n*k)%s a="g[x][y]" b="[p[c+1:i]]" l={} f={} d={'0':a+"=0",'{':"if "+a+"<1:c=e('}')",'(':"i=stdin.read(1);"+a+"=ord(i)if i else 0",')':"w(chr("+a+"))",'x':"t="+a,'o':"w(chr(t))",'!':a+"+=o",'?':a+"=0if "+a+"else 1",'+':"h(1)",'-':"h(-1)",'^':"h(0,1)",'V':"h(0,-1)",'<':"h(0,0,-1)",'>':"h(0,0,1)",':':"i=e(':');l"+b+"=i;c=i",'*':"i=e('*');c=l"+b,'~':"i=e('~');f"+b+"=i;c=e('%')",'@':"i=e('@');r=i;c=f"+b,'%':"c=r"} while c<len(p): if p[c]in d:exec d[p[c]] c+=1 ``` This implementation requires for labels and functions to be declared (implemented) before being called. It works perfectly with the two tests given but it unfortunately doesn't work with the "SayHi.2b" program written by the author of the language (even after changing the order of declaration of the functions). I think this problem might have to do with the way I understood the tape and subtape system. When moving along the main tape, is the position on the corresponding subtape reset to 0? At the moment I am keeping the position on the subtape even when moving on the main tape. Here is the more readable version: ``` #!/usr/bin/python import sys w=sys.stdout.write p=open(sys.argv[1],'r').read() c,r,s,x,y,t,o=0,0,256,0,0,0,0 # c is the current index in the program string # r is the return index (for functions) # s is the size of the tape, subtapes and modulo for ints (max int will be 255) # x and y are the coordinates in the grid # t is the temporary register # o is overflow g=[[0]*s]*s # initialise a grid 256x256 with 0 e=lambda d:p.find(d,c+1) def n():global c;c+=1;i=int(p[c]);return i if i>0 else 10 # get the number specified def h(i):j=g[x][y]+i;g[x][y]=j%s;o=j/s # handle addition and substraction def m(i,j):global x,y;x=(x+i)%s;y=(y+j)%s # move current cell a="g[x][y]" # string of current cell b="[p[c+1:i]]" # key for label or function l={} # dictionary of labels f={} # dictionary of functions d={'0':a+"=0", '{':"if "+a+"<1:c=e('}')", '(':"i=sys.stdin.read(1);"+a+"=ord(i)if i else 0", ')':"w(chr("+a+"))", 'x':"t="+a, 'o':"w(chr(t))", '!':a+"+=o", '?':a+"=0if "+a+"else 1", '+':"h(n())", '-':"h(-n())", '^':"m(n(),0)", 'V':"m(-n(),0)", '<':"m(0,-n())", '>':"m(0,n())", ':':"i=e(':');l"+b+"=i;c=i", '*':"i=e('*');c=l"+b, '~':"i=e('~');f"+b+"=i;c=e('%')", '@':"i=e('@');r=i;c=f"+b, '%':"c=r", '#':"c=e('#')" } while c<len(p): # loop while c is not EOF # print c, p[c] if p[c]in d:exec d[p[c]] # execute code kept as a string c+=1 # increment index ``` Edit: Take into account the comments handling (-10 bytes), fixing an off by one error. This implementation doesn't support nested function calls (I could implement it if it is a required feature) Edit2: Changed the handler function to do addition, substraction and cell movement. More lambdas! :D (The "more readable version" may be out of sync now) Edit3: I just realized that handling comments costs me 5 bytes (taking into account the -10). So I just removed it, it's shame it now feels incomplete. Edit4: moved definition of n from lambda to var inside the handler h() ]
[Question] [ The barbells at my gym look like this: ``` =========[]-----------------------[]========= ``` They can hold plates of five different sizes, 2.5 pounds, five pounds, ten pounds, 25 pounds, and 45 pounds: ``` . . ! | . ! | | | | | | | | ' ! | | | ' ! | ' ``` For safety, we also add a clip `]` or `[` on the outside of all of our plates if there are any. The bar itself weighs 45 pounds. We always put the heaviest plates closest to the center, with no gaps between any plates, and put identical plates on both sides. We also always use the minimum number of plates possible, e.g. we never use two five-pound plates on one side instead of a single ten-pound plate. So if I want to lift 215 pounds, my bar looks like this: ``` . . .!| |!. !||| |||! ====]||||[]-----------------------[]||||[==== !||| |||! '!| |!' ' ' ``` Your code, a function or complete program, must take an integer from 45 to 575, always a multiple of 5, and output the bar that adds up to that weight. For example: Input: `45` Output (note there are no clips on an empty bar): ``` =========[]-----------------------[]========= ``` Input: `100` Output: ``` ! ! .| |. ======]||[]-----------------------[]||[====== '| |' ! ! ``` Input: `575` Output: ``` ..... ..... .!||||| |||||!. !||||||| |||||||! ]||||||||[]-----------------------[]||||||||[ !||||||| |||||||! '!||||| |||||!' ''''' ''''' ``` You can have trailing spaces on each line or not, but your output cannot have leading or trailing empty lines (the output for 45 should be one line, for 50 should be three lines, for 65 should be five lines, and so on.) This is code golf, shortest code wins! [Answer] # Python 2, 295 bytes ``` i=input()-45 w=90,50,20,10,5;p=".|||||'"," !|||! "," .|||' "," !|! "," .|' " a=[' '*46] b=zip(*a*3+['='*9+'[]'+'-'*24+'[]'+'='*9]+a*3) v=8 j=0 while i: if i>=w[j]:i-=w[j];b[v]=b[-v-1]=p[j];v-=1 else:j+=1 if v<8:b[v]=b[10];b[-v-1]=b[9] for l in zip(*b): L=''.join(l).rstrip() if L:print L ``` Builds the bar vertically, then rotates and prints non-empty lines. [Answer] # Pyth, 126 bytes ``` K[Z5TyT50 90)jfrT6.e::++J+?qk3\=dsm@bxKdhfqQ+45sTSSM^K8?qk3r"[]23-[]"9*27d_J"=\|""]|""\|=""|["c7s@L". !|='"jC"¾ª±À£¤¯aàI7"6 ``` The source code contains unprintable characters, so here it is as an XXD dump: ``` 0000000: 4b5b 5a35 5479 5435 3020 3930 296a 6672 K[Z5TyT50 90)jfr 0000010: 5436 2e65 3a3a 2b2b 4a2b 3f71 6b33 5c3d T6.e::++J+?qk3\= 0000020: 6473 6d40 6278 4b64 6866 7151 2b34 3573 dsm@bxKdhfqQ+45s 0000030: 5453 534d 5e4b 383f 716b 3372 225b 5d32 TSSM^K8?qk3r"[]2 0000040: 332d 5b5d 2239 2a32 3764 5f4a 223d 5c7c 3-[]"9*27d_J"=\| 0000050: 2222 5d7c 2222 5c7c 3d22 227c 5b22 6337 ""]|""\|=""|["c7 0000060: 7340 4c22 2e20 217c 3d27 226a 4322 04be s@L". !|='"jC".. 0000070: aa1f b1c0 a3a4 81af 61e0 4937 2236 ........a.I7"6 ``` This code is **extremely slow**, to the point of no actual use. You can speed it up by about 1000 times by adding a `.{` (`set`) call in between, while keeping the code functionally equivalent. Here's a copy-paste friendly version of the resulting code: ``` K[Z5TyT50 90)jfrT6.e::++J+?qk3\=dsm@bxKdhfqQ+45sTS.{SM^K8?qk3r"[]23-[]"9*27d_J"=\|""]|""\|=""|["c7s@L". !|='"j96235640060099376576144045263159 6 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes ``` ¹²[]P×=⁹≔⁻N⁴⁵θWΦ⟦⁵χ²⁰¦⁵⁰¦⁹⁰⟧¬›κθ«P|§⪪”{⊞⧴&β1←Z↶RΣ”,Lι→P[≧⁻⊟ιθ»‖B← ``` [Try it online!](https://tio.run/##TU9NT4NAED2XX7Hd02yymraRmNJ4qAdNk9I01XghPSAdYOJ2QViqRvztOMBBk53NfLx5816Sx1VSxKbr9hVZB/OFWnljKqOj5CJsjKNy6DzTGWuQd1KLpeLRuq4psxCSbWrY2LJxu@b8ihUoLW58/t4Z9JGTQQEPZBxPIl@L@UyLBYfPsZwdtdgVDh4rjHvAW7@llPj2Jv8uBy9YOUpio8XabewJP@GpNMQi27a91v2b6iFrp6xOasnXt2gzlwOpXuskLC4IwYGy3A3lH7mM5NCJy9HQgBldabEvSmYYrfx4B0wNJu6@caw1NV8QbDFlvq7zb/3u6mJ@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ¹²[]P×=⁹ ``` Print 12 `-`s, the `[]` and 9 `=`s. This comprises half of the bar. The cursor is left at the beginning of the `=`s. ``` ≔⁻N⁴⁵θ ``` Subtract 45 from the input to allow for the weight of the bar. ``` WΦ⟦⁵χ²⁰¦⁵⁰¦⁹⁰⟧¬›κθ« ``` Filter a list of the possible weights of pairs of weights for those that are not greater than the input, and repeat while the list is not empty. ``` P|§⪪”{⊞⧴&β1←Z↶RΣ”,Lι ``` Split the string `|||.,|.,|!,||.,||!` on commas and select the piece corresponding to the heaviest possible weight, and print it both upwards and downwards. (Alternatively, it's possible to just print it upwards and reflect in the `¬` direction at the end; a number of variations have the same length.) ``` →P[ ``` Print the clip (will get overwritten by the next weight if any). ``` ≧⁻⊟ιθ» ``` Subtract the weight from the input. ``` ‖B← ``` Reflect to complete the barbell. ]
[Question] [ I'm sure most of us have seen SQL results in a terminal, all neatly formatted into rows and columns. If you haven't, here's an example: ``` +----------+-----------+----------------+ | column 1 | column 2 | column 3 | +----------+-----------+----------------+ | data | more data | even more data | | etc | just goes | on and on | +----------+-----------+----------------+ ``` Your goal for this challenge is, given the columns and row data for a table, draw the table in this style. There should be a horizontal line at the top and bottom of the table, and one right below the header row. There should be vertical lines between every column, and one on both sides of the table. You should use pipes for vertical lines, hyphens for horizontal lines, and plusses for where they intersect. ## Specifics: * The data can be entered via stdin, or as the argument to a function, but it must be in some form of string * The data should be split by the string delimiter `;` * The data will consist of only ASCII characters, is not quoted, and will not contain the delimiter. * The first row of the data will be used for column headers * The data will always have the same number of columns * The input will always contain at least two rows (one header, one data). You do not have to handle empty sets. * A trailing or preceding newline is permitted * Each column should be as wide as the widest element, padding shorter elements on the right *(bonus -5% if you pad numbers on the left)* * There should be 1 space of padding before and after the headers and data, except when the column is wider * You are not allowed to use the actual `mysql` program to generate the table * Standard loopholes apply ## Sample Input: ``` column 1;column 2;column 3 hello;world;test longer data;foo;bar ``` ## Output ``` +-------------+----------+----------+ | column 1 | column 2 | column 3 | +-------------+----------+----------+ | hello | world | test | | longer data | foo | bar | +-------------+----------+----------+ ``` ## Scoring: Lowest number of bytes wins, of course. -5% bonus for padding numbers on the left (see specifics). [Answer] # CJam, ~~67~~ 58 bytes ``` ' qN/';f/ff+z_.{[z,):TS*'|+f.e|T'-*'++:T\(T@~T]}z{s_W=\N}/ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code='%20qN%2F'%3Bf%2Fff%2Bz_.%7B%5Bz%2C)%3ATS*'%7C%2Bf.e%7CT'-*'%2B%2B%3AT%5C(T%40~T%5D%7Dz%7Bs_W%3D%5CN%7D%2F&input=column%201%3Bcolumn%202%3Bcolumn%203%0Ahello%3Bworld%3Btest%0Alonger%20data%3Bfoo%3Bbar). [Answer] ## JavaScript (ES6), 262 bytes ``` f=x=>{w=[],o=z=>y(`| ${z[m]((c,i)=>(c+' '.repeat(w[i]-c.length))).join` | `} |`),(d=x.split` `[m='map'](r=>r.split`;`))[m](r=>r[m]((c,i)=>w[i]=Math.max(c.length,w[i]||0)));(y=console.log)(s=`+${w[m](c=>'-'.repeat(c+2)).join`+`}+`);o(d.shift());y(s);d[m](o);y(s)} ``` ### Demo Since it is ES6, this demo works in Firefox and Edge at this time. For some reason it does not work in Chrome/Opera even with experimental JavaScript features enabled. ``` // Snippet stuff console.log = x => document.getElementsByTagName('output')[0].innerHTML += x + '\n'; document.getElementsByTagName('button')[0].addEventListener('click', () => { f(document.getElementById('I').value); }); // Actual code f = x => { w = [], o = z => y(`| ${z[m]((c,i)=>(c+' '.repeat(w[i]-c.length))).join` | `} |`), (d = x.split ` ` [m = 'map'](r => r.split `;`))[m](r => r[m]((c, i) => w[i] = Math.max(c.length, w[i] || 0))); (y = console.log)(s = `+${w[m](c=>'-'.repeat(c+2)).join`+`}+`); o(d.shift()); y(s); d[m](o); y(s) } ``` ``` <p> <textarea id=I cols=80 rows=15>column 1;column 2;column 3 hello;world;test longer data;foo;bar</textarea> </p> <button type=button>Go</button> <pre><output></output></pre> ``` ]
[Question] [ ### Introduction After a long battle, you have managed to defeat a Sphinx in a contest of riddles. The Sphinx, impressed with your skill, wishes to give you a reward commensurate with your cleverness, and conjures into existence a strip of magical parchment divided into eight boxes, each containing a numeral. "Crease the parchment," says the Sphinx, "such that the boxes overlap, and those boxes will merge either through addition or multiplication. When one box remains, its value will be your reward in gold coins." ### Task You must write a program or function which takes as input a list/array/whatever of eight natural numbers, and returns/prints the maximum possible reward obtainable through a series of 'crease' operations. ### Mechanics The 'crease' operation is performed on some number of cells, and with either `+` or `*` as the operator. The first n cells of the list are folded across and merged with their destination cells using the operator. Any cells which are not consumed in the merge operation are left unmodified. Here is an example of creasing using n=3 cells: [![enter image description here](https://i.stack.imgur.com/6BRPG.png)](https://i.stack.imgur.com/6BRPG.png) using either addition, which would result in this: [![enter image description here](https://i.stack.imgur.com/x7jtN.png)](https://i.stack.imgur.com/x7jtN.png) or multiplication, which would result in this: [![enter image description here](https://i.stack.imgur.com/7WrEs.png)](https://i.stack.imgur.com/7WrEs.png) Note: For simplicity, creasing with fewer than 1 cell is disallowed, as is creasing with a number of cells greater than or equal to the length of the list. However, a list can by creased by more than half its cell count. A list of 8 cells can be creased by 5, resulting in a new list of length 5: `[0,1,2,3,4,5,6,7]` creased by 5 cells using the `+` operator would give `[9,9,9,1,0]`. ### Scoring Standard code golf rules - the code which produces correct output and has the fewest number of bytes wins. Bonus: If your code also returns/prints the sequence of crease operations which leads to the maximal reward, multiply your score by 0.8. Example output might look like: ``` crease 5 + crease 2 * crease 2 + crease 1 * ``` ### Examples Test your code using these inputs and results, in the form of `input - maximum reward`: ``` [0, 1, 2, 3, 4, 5, 6, 7] - 7560 [0, 9, 0, 3, 2, 6, 1, 5] - 1944 [0, 1, 0, 3, 0, 2, 0, 4] - 36 [6, 0, 9, 1, 9, 0, 7, 3] - 11907 [0, 5, 2, 0, 1, 3, 8, 8] - 2560 ``` [Answer] # Pyth, 31 bytes ``` Le+bSyMsm,sMJ.T,_<bd>bdm*FkJtUb ``` This defines a function, `y`, which computes the crease value. [Demonstration.](https://pyth.herokuapp.com/?code=Le%2BbSyMsm%2CsMJ.T%2C_%3Cbd%3Ebdm*FkJtUbyQ&input=%5B0%2C+5%2C+2%2C+0%2C+1%2C+3%2C+8%2C+8%5D&debug=0) This uses the recusive method, taking the maximum of the score of every possible successor. The base case of the recursion is implemented by concatenating the input to the sorted values of the possible successors, and then taking the end of the resultant list. If there is only 1 element in the input, there are no successors, and therefore the end of the list is the one element in the input. [Answer] ## C#, 275 272 bytes It's simply a recursive function that traverses every branch and returns the best score. Indented for clarity: ``` using M=System.Math; int F(int[]n){ int b=0,g,h,i=0,j,k,l=n.Length; if(l<2) return n[0]; for(;++i<l;){ int[]m=new int[k=M.Max(i,l-i)],o=new int[k]; for(j=0;j<k;j++){ m[j]=((g=i-j-1)<0?0:n[g])+((h=i+j)<l?n[h]:0); o[j]=h<l&g>=0?n[g]*n[h]:m[j]; } b=M.Max(b,M.Max(F(m),F(o))); } return b; } ``` ]
[Question] [ In [Chinese Checkers](https://en.wikipedia.org/wiki/Chinese_checkers), a piece can move by hopping over any other piece, or by making a sequence of such hops. Your task is to find the longest possible sequence of hops. # Input A sequence of 121 zeroes or ones, each representing a place on a board. A zero means the place is empty; a one means the place is occupied. Positions are listed from left to right; top to bottom. For example, the input of [this setup](https://upload.wikimedia.org/wikipedia/commons/1/18/Chinese_checkers_jump.svg) would be ``` 1011110011000001000000000000000000000000100000000001000000000000000000000000000001000000000000000000000001000001100111111 ``` Explanation: > > The top-most place is occupied by a green piece, so the first digit in the input is `1`. The second row has one empty position and then one occupied position, so `01` comes next. The third row is all occupied, so `111`. The fourth row has two empty and two occupied spaces (going left to right), so `0011`. Then comes five `0`'s, a `1`, and seven `0`'s for the next row, and so on. > > > Like in that setup, there is a corner pointing straight up. There may be any number of pieces on the board (from 1 to 121). Note that pieces of different colors are not represented differently. # Output The maximum length of a legal hop, using any piece on the board. You may not visit the same place more than once (including the starting and ending positions). However, you may hop over the same piece more than once. If there is no legal hop, output `0`. Do not consider whether there exists a legal non-hop move. For example, the output to the setup described above is `3`. Input and output may be done through stdin and stdout, through command-line arguments, through function calls, or any similar method. # Test Cases Input: ``` 0100000010000000000000000100000000000000000000000000000001010010000000000000000000000101000000000000000000100000000100001 ``` Output: `0` (no two pieces are next to each other) --- Input: ``` 0000000000111100000000011100000000011000000000100000000000000000000000000000000000000000000000000000000000000000000000000 ``` Output: `1` (initial setup for one player in top-left corner) [Answer] ## Perl, ~~345~~ 322 **Edit:** golfed, slightly. More test cases would be nice, but for now it looks like it works. I'll add comments later if necessary. With newlines and indentation for readability: ``` $_=<>; $s=2x185; substr$s,(4,22,unpack'C5(A3)*','(:H[n129148166184202220243262281300')[$i++],0,$_ for unpack A.join A,1..4,13,12,11,10,9..13,4,3,2,1; $_=$s; sub f{ my(@a,%h)=@_; $h{$_}++&&return for@a; $-+=$#a>$-; $s=~/^.{$a[0]}$_/&&f($+[1],@a) for map{("(?=.{$_}1.{$_}(0))","(?<=(0).{$_}1.{$_}.)")}0,17,18 } f$+[0]while/1/g; print$- ``` [Answer] # C,~~262~~ 260 **Golfed code** (debugging code and unnecessary whitespace removed. Changed from input via stdin to input via command line, and took advantage of the opportunity to declare variable i there. Latest edit: code moved into brackets of `for` loops to save two semicolons.) ``` t[420],j,l,x,y;f(p,d){int z,q,k;for(k=6;k--;t[q]&!t[p+z]?t[q]=0,f(q,d+1),t[q]=1:0)z="AST?-,"[k]-64,q=p+z*2;l=d>l?d:l;}main(int i,char**s){for(i=840;i--;x>3&y>5&x+y<23|x<13&y<15&x+y>13?i>420?t[i-420]=49-s[1][j++]:t[i]||f(i,0):0)x=i%20,y=i/20%21;printf("%d",l);} ``` **Explanation** This relies on a 20x21 board which looks like this, initially filled with zeroes when the program starts (this ASCII art was generated by a modified version of the program, and as the `i` loop counts downwards, zero is in the bottom right corner): ``` .................... .................... ...............#.... ..............##.... .............###.... ............####.... .......############# .......############. .......###########.. .......##########... .......#########.... ......##########.... .....###########.... ....############.... ...#############.... .......####......... .......###.......... .......##........... .......#............ .................... .................... ``` Loop `i` runs through this board twice, using x and y to calculate whether a square actually belongs to the checkerboard or not (this requires 6 separate inequalities in x and y.) If it does, the first time round it fills the squares, putting a `0` (falsy) for a `1` (occupied) and a `1` (truthy) for a `0` (unoccupied). This inversion is important, because all out-of-bounds squares already contain a 0, which means they resemble occupied squares and it is clear they can't be jumped into, without the need for a specific check. The second time round, if the square is occupied (contains 0) it calls the function `f` that searches for the moves. `f` searches recursively in the 6 possible directions encoded by +/-1 (horizontal), +/-20 (vertical) and +/-19 (diagonal) encoded in the expression `"AST?-,"[k]-64`. When it finds a hit, it sets that cell to a 0 (occupied) before calling itself recursively, then sets it back to 1 (empty) when the function is returned. The cell value must be changed before the recursive call to prevent hopping into that cell more than once. **Ungolfed code** ``` char s[999]; //input string. t[420],i,j,l,x,y; //t=board. i=board counter, j=input counter. l=length of longest hop found so far. f(p,d){ //p=position, d= recursion depth. //printf("%d,%d ",p,d); //debug code: uncomment to show the nodes visited. int k,z,q; //k=counter,z=displacement,q=destination for(k=6;k--;) //for each direction z="AST?-,"[k]-64, //z=direction q=p+z*2, //q=destination cell t[q]&!t[p+z]? //if destination cell is empty (and not out of bounds) and intervening cell is full t[q]=0,f(q,d+1),t[q]=1 //mark destination cell as full, recurse, then mark it as empty again. :0; l=d>l?d:l; //if d exceeds the max recorded recursion depth, update l } main(){ gets(s); //get input for(i=840;i--;) //cycle twice through t x=i%20, //get x y=i/20%21, //and y coordinates x>3&y>5&x+y<23|x<13&y<15&x+y>13? //if they are in the bounds of the board i>420? t[i-420]=49-s[j++] //first time through the array put 0 for a 1 and a 1 for a 0 ('1'=ASCII49) :t[i]||f(i,0) //second time, if t[i]=0,call f(). //,puts("") //puts() formats debug output to 1 line per in-bounds cell of the board :0; printf("%d",l); //print output } ``` ]
[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/16209/edit). Closed 1 year ago. [Improve this question](/posts/16209/edit) I'm a bit of a romantic, I love taking my wife out to see the sunrises and sunsets in the place we are located. For the sake of this exercise let's say I don't have code that can tell me the time of either sunset or sunrise for whatever date, latitude and longitude I would happen to be in. Your task, coders, is to generate the smallest code possible that takes a decimal latitude and longitude (taken in degrees N and W, so degrees S and E will be taken as negatives) and a date in the format YYYY-MM-DD (from Jan 1, 2000 onwards) and it will spit out two times in 24hr format for the sunrise and sunset. e.g. For today in Sydney, Australia ``` riseset -33.87 -151.2 2013-12-27 05:45 20:09 ``` Bonuses: -100 if you can factor in elevation -100 if you can factor daylight savings The code MUST spit out times in the relevant time zone specified in the input based off the latitude and longitude OR in the client machine's own time zone. [Answer] I've spent quite some time writing this: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- from math import * class RiseSet(object): __ZENITH = {'official': 90.833, 'civil': '96', 'nautical': '102', 'astronomical': '108'} def __init__(self, day, month, year, latitude, longitude, daylight=False, elevation=840, zenith='official'): ''' elevation is set to 840 (m) because that is the mean height of land above the sea level ''' if abs(latitude) > 63.572375290155: raise ValueError('Invalid latitude: {0}.'.format(latitude)) if zenith not in self.__ZENITH: raise ValueError('Invalid zenith value, must be one of {0}.'.format (self.__ZENITH.keys())) self.day = day self.month = month self.year = year self.latitude = latitude self.longitude = longitude self.daylight = daylight self.elevation = elevation self.zenith = zenith def getZenith(self): return cos(radians(self.__ZENITH[self.zenith])) def dayOfTheYear(self): n0 = floor(275*self.month/9) n1 = floor((self.month + 9) / 12) n2 = (1 + floor((self.year - 4*floor(self.year/4) + 2) / 3)) return n0 - (n1*n2) + self.day - 30 def approxTime(self): sunrise = self.dayOfTheYear() + ((6 - (self.longitude/15.0)) / 24) sunset = self.dayOfTheYear() + ((18 - (self.longitude/15.0)) / 24) return (sunrise, sunset) def sunMeanAnomaly(self): sunrise = (0.9856 * self.approxTime()[0]) - 3.289 sunset = (0.9856 * self.approxTime()[1]) - 3.289 return (sunrise, sunset) def sunTrueLongitude(self): sma = self.sunMeanAnomaly() sunrise = sma[0] + (1.916*sin(radians(sma[0]))) + \ (0.020*sin(radians(2*sma[0]))) + 282.634 if sunrise < 0: sunrise += 360 if sunrise > 360: sunrise -= 360 sunset = sma[1] + (1.916*sin(radians(sma[1]))) + \ (0.020*sin(radians(2*sma[1]))) + 282.634 if sunset <= 0: sunset += 360 if sunset > 360: sunset -= 360 return (sunrise, sunset) def sunRightAscension(self): stl = self.sunTrueLongitude() sunrise = atan(radians(0.91764*tan(radians(stl[0])))) if sunrise <= 0: sunrise += 360 if sunrise > 360: sunrise -= 360 sunset = atan(radians(0.91764*tan(radians(stl[1])))) if sunset <= 0: sunset += 360 if sunset > 360: sunset -= 360 sunrise_stl_q = (floor(stl[0]/90)) * 90 sunrise_ra_q = (floor(sunrise/90)) * 90 sunrise = sunrise + (sunrise_stl_q - sunrise_ra_q) sunrise = sunrise/15.0 sunset_stl_q = (floor(stl[1]/90)) * 90 sunset_ra_q = (floor(sunset/90)) * 90 sunset = sunrise + (sunset_stl_q - sunset_ra_q) sunset /= 15.0 return (sunrise, sunset) def sunDeclination(self): sunrise_sin_dec = 0.39782 * sin(radians(self.sunTrueLongitude()[0])) sunrise_cos_dec = cos(radians(asin(radians(sunrise_sin_dec)))) sunset_sin_dec = 0.39782 * sin(radians(self.sunTrueLongitude()[1])) sunset_cos_dec = cos(radians(asin(radians(sunrise_sin_dec)))) return (sunrise_sin_dec, sunrise_cos_dec, sunset_sin_dec, sunset_cos_dec) def sunHourAngle(self): sd = self.sunDeclination() sunrise_cos_h = (cos(radians(self.getZenith())) - (sd[0]* \ sin(radians(self.latitude))) / (sd[1]* \ cos(radians(self.latitude)))) if sunrise_cos_h > 1: raise Exception('The sun never rises on this location.') sunset_cos_h = (cos(radians(self.getZenith())) - (sd[2]* \ sin(radians(self.latitude))) / (sd[3]* \ cos(radians(self.latitude)))) if sunset_cos_h < -1: raise Exception('The sun never sets on this location.') sunrise = 360 - acos(radians(sunrise_cos_h)) sunrise /= 15.0 sunset = acos(radians(sunrise_cos_h)) sunset /= 15.0 return (sunrise, sunset) def localMeanTime(self): sunrise = self.sunHourAngle()[0] + self.sunRightAscension()[0] - \ (0.06571*self.approxTime()[0]) - 6.622 sunset = self.sunHourAngle()[1] + self.sunRightAscension()[1] - \ (0.06571*self.approxTime()[1]) - 6.622 return (sunrise, sunset) def convertToUTC(self): sunrise = self.localMeanTime()[0] - (self.longitude/15.0) if sunrise <= 0: sunrise += 24 if sunrise > 24: sunrise -= 24 sunset = self.localMeanTime()[1] - (self.longitude/15.0) if sunset <= 0: sunset += 24 if sunset > 24: sunset -= 24 return (sunrise, sunset) def __str__(self): return None ``` Now it's not yet functional (I screwed up some calculations) - I'll come back to it later (if I'll still have the courage) to [complete it / comment it](http://williams.best.vwh.net/sunrise_sunset_algorithm.htm). Also, some interesting resources that I found while researching the subject: * [How to compute planetary positions](http://stjarnhimlen.se/comp/ppcomp.html) * [How to adjust sunrise and sunset times according to altitude?](https://photo.stackexchange.com/questions/30259/how-to-adjust-sunrise-and-sunset-times-according-to-altitude) * [How To Convert a Decimal to Sexagesimal](http://geography.about.com/library/howto/htdegrees.htm) * [When is the right ascension of the mean sun 0?](https://physics.stackexchange.com/questions/46700/when-is-the-right-ascension-of-the-mean-sun-0) * [How do sunrise and sunset times change with altitude?](http://curious.astro.cornell.edu/question.php?number=388) * [What is the maximum length of latitude and longitude?](https://stackoverflow.com/questions/15965166/what-is-the-maximum-length-of-latitude-and-longitude) * [Computation of Daylengths, Sunrise/Sunset Times, Twilight and Local Noon](http://www.sci.fi/~benefon/sol.html) * [Position of the Sun](http://www.stargazing.net/kepler/sun.html) ]
[Question] [ Let's call a non-empty list of strings a ***mesa*** if the following conditions hold: > > 1. Each listed string is non-empty and uses only characters that occur in the first string. > 2. Each successive string is exactly one character longer than the preceding string. > 3. No string in the list is a [subsequence](http://en.wikipedia.org/wiki/Substring#Subsequence) of any other string in the list. > > > The term "mesa" is from visualizing like this (where the `x`s are to be various characters): ``` xx..x xx..xx xx..xxx . . . xx..xxx..x ``` NB: It's a mathematical fact that only finitely many mesas begin with a given string. Note the distinction between *subsequence* vs. *substring*; e.g., 'anna' is a subsequence (but not a substring) of 'banana'. ### Challenge: * Write the shortest program that takes an arbitrary non-empty alphanumeric input string and outputs the number of mesas that begin with that string. ### Input (stdin): * Any non-empty alphanumeric string. ### Output (stdout): * The number of mesas that begin with the input string. ### Scoring: * The winner is the program with the least number of bytes. ### Example mesas Only one mesa starts with `a`: ``` a ``` Only one mesa starts with `aa`: ``` aa ``` Many mesas start with `ab`: ``` ab ab ab ab (and so on) baa aaa bbb bbba bbaa baaaa aaaaaa ``` [Answer] ## GolfScript (106 103 chars) ``` n-..&1/:Z;]]0,\{.@+\{['']:E+.-2=,)E\{{`{+}+Z/}%}*{:x`{\1,+\{1$(@={\}*;}/0=!}+1$?!{.);[x]+\}*}/;}%.}do;, ``` Somewhere in the heart, of course, is some code from [Is string X a subsequence of string Y?](https://codegolf.stackexchange.com/questions/5529/is-string-x-a-subsequence-of-string-y) [Answer] ### Ruby, 142 characters ``` m=->l{[*l[0].chars].repeated_permutation(l[-1].size+1).reduce(1){|s,x|l.any?{|y|x*''=~/#{[*y.chars]*'.*'}/}?s:s+m[l+[x*'']]}} p m[[gets.chop]] ``` This algorithm is constructive, i.e. it builds all possible mesas for the input string and counts them. It makes the program really, really slow - but hey, it is codegolf. Example runs: ``` > a 1 > aa 1 > ab 43 ``` ]
[Question] [ ## Background *Flow Free* is a series of puzzle games whose objective is to connect all the same-colored pairs of dots on the grid. *Flow Free: Warps* introduces the "warping" mechanic: a line connecting two dots can go through the border of the grid, which makes it re-enter through the opposite side of the grid (torus topology). The following is an in-game screenshot of an initial grid and its complete solution, so that the readers can get some feel of the game. ![](https://i.stack.imgur.com/i4PBP.png) ![](https://i.stack.imgur.com/dqn56.png) Due to the warping nature, many of the lines should be drawn in multiple finger strokes. As in the screenshots, the game shows one-cell-wide extra border around the main grid whose cells act as "shadow" of the actual cells on the opposite side. The player can make any kind of moves on the shadow cells just like on the cells on the main grid. The following shows the relationships between the shadow cells and their corresponding main cells on a 5x5 grid. Note that the shadow corner cells are also functional. ``` E5 | E1 E2 **E3 E4 E5** | **E1** ---+----------------+--- A5 | A1 A2 **A3** A4 A5 | A1 B5 | **B1 B2 B3** B5 | B1 C5 | C1 C5 | C1 D5 | D1 D5 | D1 E5 | E1 E2 E3 E4 E5 | E1 ---+----------------+--- A5 | A1 A2 A3 A4 A5 | A1 ``` For example, the path `B1 B2 B3 A3 E3 E4 E5 E1` can be drawn in one finger stroke by starting at main B1 and going `>>^^>>>`, finishing at the top right corner shadow E1. Additionally, the game has a convenience feature: if you drop your finger at the cell (orthogonally) adjacent to the destination cell, the line is auto-connected with it. For example, if the destination of the above path is D1 instead, drawing the line through B1 to E1 is enough to complete the line, so the path still takes one finger stroke. But this feature only works between two cells adjacent *when only the main cells are considered*, e.g. dropping your finger at B5 (either main or shadow) won't auto-connect to B1. Under these mechanisms, every single line shown in the above screenshot takes just one finger stroke. Note that you can start at either side of the line, and you can start or extend the line at any equivalent cell (out of the main and shadow cells). To be precise, the player can do one of the following actions in one finger stroke: * First stroke: Start drawing a line from one of the two dots, and draw it as far as possible, and release. * Second and subsequent strokes: start drawing at the cell (or any of its shadows) where the last stroke stopped, and extend the line as far as possible, and release. ## Challenge Given the description of a line on a grid of *Flow Free: Warps*, determine how many finger strokes will be needed to complete the line. The line can be taken as input in a suitable, clear format. If the input is `B4 - B1 - B2 - A2 - D2` on a 4x4 grid, the following (and the respective equivalents according to Default I/O) are allowed: * An ordered list of coordinates: `[(2, 4), (2, 1), (2, 2), (1, 2), (4, 2)]` * A 2D grid where the path is marked with successive integers: `[[0, 4, 0, 0], [2, 3, 0, 1], [0, 0, 0, 0], [0, 5, 0, 0]]` If you want to use a different input format, please ask in comments. The line will always be valid in the following sense: * It has a well-defined start cell and an end cell. * Each adjacent pair of cells within the path are orthogonally adjacent on the grid, potentially through the border. You can further assume the grid is rectangular and has at least 4 rows and 4 columns. The grid may be non-square. You are *not* allowed to assume that the path does not touch itself. Many levels in the game contain some thin walls, which make some paths touch themselves by going through both sides of such walls. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases Since a line on a grid can be represented in multiple different ways, the test cases are presented in a visually clear style. ``` Input: [[ 1, 2, 3, 4 ], [ 8, 7, 6, 5 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ]] Output: 1 Input: [[ 1, 2, 0, 0 ], [ 0, 0, 0, 0 ], [ 7, 8, 5, 6 ], [ 0, 3, 4, 0 ]] Output: 1 (start at bottom shadow of 1 and release finger at shadow 7) Input: [[ 0, 0, 0, 0 ], [ 3, 4, 1, 2 ], [ 6, 5, 8, 7 ], [ 0, 0, 0, 0 ]] Output: 2 Input: [[ 0, 0, 0, 0 ], [ 3, 4, 1, 2 ], [ 6, 5, 0, 7 ], [ 0, 0, 0, 0 ]] Output: 1 (start at shadow 7 and release finger at shadow 2) Input: [[ 7, 8, 9, 0, 0, 0 ], [ 0, 0, 0, 1, 2, 3 ], [ 5, 0, 0, 0, 0, 4 ], [ 6, 0, 0, 0, 0, 0 ]] Output: 2 (first stroke can only go to 1..7 or 9..3) Input: [[ 0, 0, 4, 5, 0, 9 ], [ 0, 0, 0, 6, 7, 8 ], [ 0, 1, 0, 0, 0, 0 ], [ 0, 2, 3, 0, 11, 10 ]] Output: 1 (start at shadow 11 and release at shadow 2) Input: [[ 0, 0, 5, 0, 9, 0,15, 0,19 ], [24,25, 6, 7, 8, 0,16,17,18 ], [23, 1, 0, 0, 0, 0, 0, 0, 0 ], [22, 2, 3, 0,11,12,13, 0,21 ], [ 0, 0, 4, 0,10, 0,14, 0,20 ]] Output: 5 ``` [Answer] # JavaScript (ES7), 194 bytes Expects `(list, width, height)`, where `list` is an ordered list of 0-indexed coordinates. ``` (p,w,h)=>(m=g=([c,...p],N,X=-3,Y=X)=>1/X/Y?c?[0,1,2,3].map(k=>g(p,(X-([x,y]=c,P=k&1?x?~x+w?g:-1:w:x))**2<2&(Y-(Q=k&2?y?~y+h?g:-1:h:y))**2<2|!(p+p||k)?N:-~N,P,Q)):N>m?0:m=N:0)(p)|g(p.reverse())|m ``` [Try it online!](https://tio.run/##bY9Nk5pAEIbv/IrORWfWAZnxmw1ySo7Ubu1Fi@VAEJEoHwHXhYrxr5ueEXU3lWKq6H7ft5@e@Rkcgiosk2KvZ/kqOq/tMynYO9tQe05SO7aJFzLDMAqfuWxh6wO2tBfo8f6iv3RCxzMZZ4INfCMNCrK15zGOk4VOvJo1vh2yJ3vb4U7tnOreuxNbOrferZrShwfxVXTIUifPGBBO45ya3uYS2FhNGzh@IUWvOB631HEt/eSyJ/ZMqeXOU8e0Utu1TEoKesSdRhkdorKKCKXH9FxGv96SMiLdddWlaAWr78kuemmykJjU2Ocv@zLJYkKNqtgle9J9zV4zDK7z8lsQbkgF9hx@awBxmazAhuqew5R8qEpUBmLSG6UPvf7Fdd/SH1FJ6SMiimC/QYTnP7a82xZSMmioBJV37cCgVtoBOh0gcto7gA7cl5AaJ3x6AYd5VuW7yNjlMVmrIFN8z/SNXZTF175t5NAfeuYgYABDbQoTGMNIM0F9t78mAx@FCUxhBGPscUwGroZsMawhBSOTO@F/AfNjQCJnn/aqW2kjaCN4v/GtVkT8Iw1Bspi1Ap4x4DtgKgV@1eSRggC8soRz4AhprRahDFXzmSaGIEY3mBLHwCfAp5oY/EO@rxDi8w4BXNWCX3cNlaVqrmph/gU "JavaScript (Node.js) – Try It Online") ### How? As illustrated below, there are up to 4 distinct ways of selecting some cells in the grid: the original position **P** and 3 shadow positions **S**. ``` . | . . . | . ---+-------+--- . | P . . | S . | . . . | . . | . . . | . ---+-------+--- . | S . . | S ``` The loop `[0,1,2,3].map(k=>...)` attempts to do one recursive call per possibility. However, if a given shadow is invalid, at least one of the coordinates will be set to a non-numeric value, causing the search to be aborted early thanks to the test `1/X/Y`. We keep track of the current number of strokes in `N` and the minimum number of strokes in `m`. If the last position used is not a shadow, the corresponding stroke is never counted, even if it's not adjacent to the penultimate position. The test is `|!(p+p||k)`. Two searches are executed: from first to last point and from last to first point. ]
[Question] [ # Challenge ## Premise Consider a mosaic of \$m\times n\$ tiles, in \$k\$ unique colours designated by integers. Example (\$3\times6\$, four colours): ``` 4 1 3 2 4 2 1 2 4 2 1 3 4 3 2 1 4 4 ``` My poor man's mirror is a pane of glass of width \$\sqrt{2}\cdot\min(m,n)\$. I stand it diagonally on the mosaic, like so: ``` 4 1 3 M 4 2 1 2 M 2 1 3 4 M 2 1 4 4 ``` For this example I can pretend it reflects exactly two full tiles: ``` x 1 x M x x x 2 M x x x x M 2 1 x x ``` No matter what diagonal I choose, this is the **greatest number** of full tiles I can fake-reflect. Yay. ## Task Input: an integer matrix of \$m\$ rows and \$n\$ columns where \$2\leq m\leq1000,2\leq n\leq1000\$. The number of unique values is \$k\$ where \$3\leq k\ll mn\$. Output: three integers, in any format. The first and second respectively represent the row coordinate and column coordinate of the matrix element ('mosaic tile') at the **left** end of the 45-degree diagonal where the fake mirror should be placed for 'best effect', effectiveness being defined as shown above. The third integer is 0 or 1, respectively meaning a rising (bottom left to top right) or falling (top left to bottom right) diagonal. For clarity's sake, here are some simple test cases. ### Example 1 Input: ``` 4 1 3 2 4 2 1 2 4 2 1 3 4 3 2 1 4 4 ``` Output: `3 2 0` ### Example 2 Input: ``` 3 6 4 7 5 8 1 2 2 1 ``` Output: `4 1 1` or `5 1 0` (not both) As you can see, **a unique solution isn't guaranteed**. ### Example 3 Input: ``` 2 7 4 10 7 8 9 5 6 4 2 4 10 2 1 7 10 7 2 4 10 10 8 7 6 5 6 2 2 3 6 1 6 9 7 2 10 3 4 7 8 8 3 7 1 8 4 2 3 3 7 6 10 1 7 9 10 10 2 6 4 7 5 6 9 1 1 5 7 6 2 7 7 10 3 9 8 10 9 3 6 1 6 10 3 8 9 6 3 6 2 10 1 2 8 1 7 7 8 1 1 6 4 8 10 3 10 4 9 3 1 9 5 9 10 4 6 7 10 4 1 10 9 7 7 10 3 3 7 8 2 2 4 2 4 7 1 7 7 1 9 9 8 7 5 9 5 3 8 6 5 7 6 7 2 7 9 9 7 10 8 8 7 3 5 9 9 10 9 3 8 2 9 2 1 3 6 3 8 5 7 10 10 9 1 1 10 2 5 1 6 9 8 7 6 2 3 2 9 9 9 7 9 5 8 3 8 2 2 5 2 2 10 10 3 5 7 1 1 2 3 2 10 1 2 10 3 3 2 1 4 2 5 6 10 9 6 5 3 8 8 9 5 2 1 4 10 6 8 6 9 10 10 8 1 6 10 6 4 8 7 9 3 5 8 1 5 7 1 8 7 5 8 6 4 5 10 1 6 1 4 4 10 7 6 3 3 6 ``` Output: `1 10 1` ## Edit - indexing The example outputs are 1-indexed, but **0-indexing is allowed**. # Remarks * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins. * [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/), [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and [loophole rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * If possible, link an online demo of your code. * Please explain your code. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 91 bytes ``` ≔⟦⟧θWS⊞θI⪪ι ≔L§θ⁰η≔⊖⌊⟦Lθη⟧ζF⁻LθζF⁻ηζF²⊞υ⟦Σ⭆⊕ζ⭆⊕ζ⁼§§θ⁺ι⎇λμ⁻ζμ⁺κξ§§θ⁺ι⎇λξ⁻ζξ⁺κμ⎇λι⁺ιζκλ⟧I✂⌈υ¹ ``` [Try it online!](https://tio.run/##jVE9b4QwDN35FdZNjpRKhbJ1OvU6nFQkJLohhohLj6ghx0fSUv48dQAVOlTqlPj5@dnPLivRlTehp@nY9@pqMC84tOwx@KyUloBn0zib2U6ZKzIGqesrbDk8id5i1mhlUXE4wIExqlklXqS52gqP9mwucvD0e8Y4VBvjJMtO1tJYecFEGVW7GvO1rPXUwheMVPB268BTXI@7/Eij7DLVDonWIR2HPCPZZfZENGRlazqSyN@Z59YJ3f8Y2BlJNbUjx6@yM6L7Qs2h5rBMMdKf1sBW1juHwQf/Uxl2KsNvlVnUAzu62kRGnyKaLmhdKVmyuFxHq1JiIoZ5u45IoT/SNMUQwgNEEEMUhMvrkSCe0ZDiOJjuPvQ3 "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation: ``` ≔⟦⟧θWS⊞θI⪪ι ``` Input the mosaic. (These 12 bytes could be avoided by requiring the input to be in JSON format, but I was too lazy to punctuate the example.) ``` ≔L§θ⁰η ``` Get the width of the mosaic. ``` ≔⊖⌊⟦Lθη⟧ζ ``` Get the inner size of the mirror, i.e. the distance from the first to the last character of the mirror in terms of diagonal steps. ``` F⁻Lθζ ``` Loop over the possible row(s) of the top left corner of the mirror's enclosing square. ``` F⁻ηζ ``` Loop over the possible column(s) of the top left corner of the mirror's square. ``` F² ``` Loop over the possible rotations of the mirror. ``` ⊞υ⟦Σ⭆⊕ζ⭆⊕ζ⁼§§θ⁺ι⎇λμ⁻ζμ⁺κξ§§θ⁺ι⎇λξ⁻ζξ⁺κμ⎇λι⁺ιζκλ⟧ ``` Calculate the number of tiles it reflects exactly. Exact matches are counted twice and the diagonal is also counted but this doesn't affect the relative score. Push this number along with the potential solution to the predefined empty list. ``` I✂⌈υ¹ ``` Output the solution with the highest number of exactly reflected tiles. [Answer] # Python3, 557 bytes: ``` E=enumerate V=lambda x,y,n,m:0<=x<n and 0<=y<m U=lambda j,k,J,K,b,n,m:b[j][k]==b[J][K]if V(j,k,n,m)and V(J,K,n,m)else 0 def f(b): n,m=len(b),len(b[0]) q,r=[i for x,u in E(b)for y,_ in E(u)for i in[(x,y,0,0,x,y)]*(x+1>=min(n,m)and y+min(n,m)<=m)+[(x,y,1,0,x,y)]*(x+1>=min(n,m)and y+1>=min(n,m))],[] while q: x,y,d,c,X,Y=q.pop(0) if abs(X-x)+1==min(n,m):r+=[(*[[x,y],[X,Y]][d],d,c)];continue q+=[(x,y,d,c+U(*[[X+1,Y+1,X-1,Y-1],[X+1,Y-1,X-1,Y+1]][d],b,n,m)+U(*[[X,Y+1,X-1,Y],[X,Y-1,X+1,Y]][d],b,n,m),X-1,Y+[1,-1][d])] return max(r,key=lambda x:x[-1]) ``` [Try it online!](https://tio.run/##fVRNb6MwED2vf8Wol5riVhgIH9mwt1660t5apfKiijREpQ0kIUSb/Prs2GbcrFStQsCeee/N@NmwPQ1vmy7Ktv35fF/U3aGt@2qo2VOxrtrFsoKjOIlOtNNgVhxnHVTdEnB4mrXskSDv4kM8iJ9iYYAL9V6qj7IoFuqhVD/LZgVPXEMw6Wn6E9dgPavX@xoCtqxXsOILb8oAo8W67nAizEMFpcdgJ/pCNbDa9NjOAZoO7hGhpyfxYqcHM21worhuOcAfPr3yhh99@aNom45TAyefZrOi9XxLkP8lXAS8UqiSwZ@3Zl3DDns2Fi3Fq5iL52J3t91seYBNAy68Wuz5/Pbo@bJw/GnvF4rfKIU0lEJSWaplqRW88vvrphua7lAjf6dxo7b/qBlzX4pn/M9v8XkrNds3IxvxpVUy@@CNlE@CLabBmnQJHelKChTFsIfr6@vh0HfQVkfei4/65M7D9KgQ5Z33sri6umIxSIgghBhCJu1TRzAemVEMMdO4fWjgESSYStkEMg1nCLHpyKRDgBSQAzLQgwwgB5gAJCYYUgoH0iAtzMXxQkrKEiKF5orMWJp7DiMDsZHh2TqZgaUGltlq2OwYS6y6GedUKaS2UqqWG7Y005TqpyylYrmRxnH@b082axebUCqkmqFlaRnbqiReTHqRuccwCkuyLad4Qm7FTFIHKcXcMjMyzHmdktEpqdo16A0ca9jOk4tFW39Tgtsi1uLU4CeUkgHLSSE0EbuzEfmQkay13Bls7Z@4TWXZheMRibn6ttPsopRlh85m48KEpVTAybg9cEbZFmPSSMjPxNnB3Ll1WIQkZFR@cVbdAXDbmdIuTlh2cZgkJSckE1sDAtIwEffqWP@0keb90t/YYfOy2FT9ku/xU/ttfMGVummrLW@6QTR3@@26GTh@4uhjCqtmPdQ9/7XpagH7EXD9u7tGEGPbHnl8xT@Vped5X4TDr8MRhs9/AQ) ]
[Question] [ [UTF-8](https://en.wikipedia.org/wiki/UTF-8) is a relatively simple way to encode Unicode codepoints in a variable-width format such that it doesn't easily confuse code that isn't Unicode aware. ## UTF-8 overview * Bytes in the range of 1-0x7F, inclusive, are normally valid * Bytes with the bit pattern `10XX XXXX` are considered continuation bytes, with the six least significant bits being used to encode part of a codepoint. These must not appear unless they are expected by a preceding byte. * Bytes with the pattern `110X XXXX` expect one continuation byte afterward * Bytes with the pattern `1110 XXXX` expect two continuation bytes afterward * Bytes with the pattern `1111 0XXX` expect three continuation bytes afterward * All other bytes are invalid and should not appear anywhere in a UTF-8 stream. 5, 6, and 7 byte clusters are possible in theory, but will not be allowed for the purposes of this challenge. ## Overlong encodings UTF-8 also requires that a codepoint should be represented with the minimum number of bytes. Any byte sequence that could be represented with fewer bytes is not valid. Modified UTF-8 adds one exception to this for null characters (U+0000), which should be represented as `C0 80` (hex representation)), and instead disallows null bytes to appear anywhere in the stream. (This makes it compatible with null-terminated strings) # Challenge You are to make a program that, when given a string of bytes, will determine if that string represents valid Modified UTF-8 and will return a truthy value if valid and a falsy value otherwise. Note that you must check for overlong encodings and null bytes (since this is Modified UTF-8). You do not need to decode the UTF-8 values. # Examples ``` 41 42 43 ==> yes (all bytes are in the 0-0x7F range) 00 01 02 ==> no (there is a null byte in the stream) 80 7F 41 ==> no (there is a continuation byte without a starter byte) D9 84 10 ==> yes (the correct number of continuation bytes follow a starter byte) F0 81 82 41 ==> no (there are not enough continuation bytes after F0) EF 8A A7 91 ==> no (too many continuation bytes) E1 E1 01 ==> no (starter byte where a continuation byte is expected) E0 80 87 ==> no (overlong encoding) 41 C0 80 ==> yes (null byte encoded with the only legal overlong encoding) F8 42 43 ==> no (invalid byte 'F8') ``` # Rules * Standard rules and loopholes apply * Input and output can be in any convenient format as long as all values in the unsigned byte range (0-255) can be read in. + You may need to use an array or file rather than a null-terminated string. You need to be able to read null bytes. * Shortest code wins! * Note that using builtins to decode the UTF-8 is not guaranteed to conform to the requirements given here. You may need to work around it and create special cases. EDIT: added bonus for not using builtins that decode UTF-8 EDIT2: removed bonus since only the Rust answer qualified and it's awkward to define. [Answer] # [Elixir](https://elixir-lang.org/), 69 bytes ``` import String &valid? replace replace(&1,<<0>>,"\xFF"),"\xC0\x80","0" ``` [Try it online!](https://tio.run/##dY9RC4IwFIXf/RWyB1EYspngBFuINeiph159kdIYWMmy2L@3u0VENV@@y3bOPZfT9lJLNXXLcJLn4apGfz8qeTl5waPp5XHlq3bom0P7nmFAcVEQzjGqtRAoMrMitWYEYUTQFHnbXTzcx5vfxSE4dUoxIDFYcP4rY4qT/19IA38mzBJ1yOscFJYCKHHIwmwzc5clcxEbE85KQJkBcqfHRFg4VXvFInPItnf18sxVqD4R6dfT1pqe "Elixir – Try It Online") Makes use of built-in string validation function. Takes input as Elixir binary. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~41~~ 39 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function. Takes a Unicode string as argument where the characters' code points represent the input bytes. ``` {0::0⋄×⌊/'UTF-8'⎕UCS⍣2⎕UCS⍵}'À\x80'⎕R⎕A ``` [Try it online!](https://tio.run/##PY6xSgNBEIZ7n@LvNgGDs5fF26Q7LjlMJeSSziYgMUVAS0MIBCKHrl7QQrQURbBLIXmB5E3mRc451gsMw//Nv/PPjm6mjcvZaHp9VUw4e57z@rV3LoLAj3cQGsYp9Cm775pA51haVOf8l/PtYvejoPj@vcYPH@wydp/1Yk7tNsnq/o2f3IkaDpKGVT6G86@gUtuF2i8vbi2VXr8MLcZylfO1/4Bb7TZNzl6E0n4sfXDWS4sxJspomACmqY5KIgJpUODJEsIERnvqtGANNHlKCFbDBge7m8BGiEK0qoGGFFUk76VCT3I1LgeH5Njb5l/IlT8 "APL (Dyalog Unicode) – Try It Online") `'À\x80'⎕R⎕A` **R**eplace `C0 80`s with the uppercase **A**lphabet `{`…`}` apply the following anonymous function, where the argument is `⍵`:  `0::` if any error happens:   `0` return zero  `⋄` try:   `⎕UCS⍵` convert the string to code points   `'UTF-8'⎕UCS⍣2` interpret as UTF-8 bytes and convert resulting text back to bytes   `⌊/` lowest byte (zero if a null byte is present, positive if not, "infinity" if empty string)   `×` sign (zero if null byte is present, one if not) [Answer] # [Python 2](https://docs.python.org/2/), ~~104~~ 102 bytes ``` ''.join(chr(int(c,16))for c in input().replace('00','-').replace('C0 80','0').split()).decode('utf-8') ``` [Try it online!](https://tio.run/##dZJBbsIwEEX3nGJEF04qQDaNSmjVRdXCthfoxphJSGU8keMUcno6hqIGQSMvovH8N9/frruwITc9vH28L16Gw@Eg@O4JX@Tz50GIyRdVLjEbn1QuJGakHtO0IA8GKserbkOSTjzWVhtMhJRiJMaiV3mTkMei5GJT24rb08kaDa15sw3FOBfpAfcG68Az1aD2PAfUGAfRCe7RQPR1Pz@ITEE2hexBQPzuoMMGEm0trLrAv9pj9BQ2CHIs97MleO1KTAfsCqQCOT0LHUHCbbGfZeDaX8ZZ3gSPesvCXAJjMvWP0JALlWt1qMidALuKo2wD7zVB@4D@WGbS@xzyDJS88B5nGfIeTWAT2xW3U3FNbaAga2l3TV1yuAry6cli318Mw1EAdNSWm1tMXUTQUjJmsYT8FV5nMO9hiGCrXXdDGhUKeMmLYPreYHdycSMiTg73NR8Z1xEUnwfksz6IvtFbciWb52dSuZL7@O5PL6mf39/FHTtxfcz/eIXkbAcWS23hGvcD "Python 2 – Try It Online") Outputs via exit code [Answer] # Rust - ~~191 bytes~~ 313 bytes Per comment below original did not work properly. New and improved version. No libraries are used, because The Mighty Rust Has No Need For You And Your Libraries. This code uses pattern matching with a state machine. By [shamelessly ripping off the UTF8 spec](http://www.unicode.org/versions/corrigendum1.html), after finding it via [reference and discussion by Jon Skeet](https://stackoverflow.com/questions/7113117/what-is-exactly-an-overlong-form-encoding), we can copy the spec almost character for character into a rust Match pattern match block. At the end, we add in Beefster's special Mutf8 requirement for C0 80 to be considered valid. Ungolfed: ``` /* http://www.unicode.org/versions/corrigendum1.html Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte U+0000..U+007F 00..7F U+0080..U+07FF C2..DF 80..BF U+0800..U+0FFF E0 A0..BF 80..BF U+1000..U+FFFF E1..EF 80..BF 80..BF U+10000..U+3FFFF F0 90..BF 80..BF 80..BF U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF U+100000..U+10FFFF F4 80..8F 80..BF 80..BF */ let m=|v:&Vec<u8>|v.iter().fold(0, |s, b| match (s, b) { (0, 0x01..=0x7F) => 0, (0, 0xc2..=0xdf) => 1, (0, 0xe0) => 2, (0, 0xe1..=0xef) => 4, (0, 0xf0) => 5, (0, 0xf1..=0xf3) => 6, (0, 0xf4) => 7, (1, 0x80..=0xbf) => 0, (2, 0xa0..=0xbf) => 1, (4, 0x80..=0xbf) => 1, (5, 0x90..=0xbf) => 4, (6, 0x80..=0xbf) => 4, (7, 0x80..=0x8f) => 4, (0, 0xc0) => 8, // beefster mutf8 null (8, 0x80) => 0, // beefster mutf8 null _ => -1, })==0; ``` [try it on the rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=03a2127a05452312701fb98c44ebd8fd) ]
[Question] [ I work at a bakery that serves Wheat, Rye, Barley, Grain, and French bread, but the baker's a little weird - he stacks the loaves in random order, and sometimes just leaves some shelves at the end empty. Each day, the same customer comes in and asks for one of each loaf of bread, but the tricky thing is, he's a germophobe, so when I fill his bag, I can't take loaves from two adjacent shelves in consecutive selections. It takes one second to walk between adjacent shelves. It's a busy store; for any random configuration of loaves, I'd like to minimize the time it takes to get one of each unique loaf. I can start and end at any shelf. If today's ordering is `W B W G F R W`, a possible path is `0, 3, 5, 1, 4`, for a total of 12 seconds: `abs(3-0) + abs(5-3) + abs(1-5) + abs(4-1) = 12` (`1, 2, 3, 4, 5` doesn't work, because bread is picked consecutively from adjacent shelves.) If it's `B W B G B F B R B W B F`, a possible path is `1, 3, 5, 7, 10`, for a total of 9 seconds. The manager always makes sure there is a possible solution, so I don't need to worry about catching bad inputs. He usually sends me the order in a file, but if I want, I can type it to STDIN or read it a different way. I'd like the program to print out the indices of the best path, as well as its time, according to [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447). In short: 1. 5 types of bread. 2. Loaf orders appears as strings of random order and length. 3. Must select one of each unique loaf. 4. Cannot make adjacent consecutive selections. 5. Minimize the distance between selection indices. 6. Don't need to worry about invalid inputs. 7. [Default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447) apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest byte count wins. [Answer] # JavaScript (ES6), 114 bytes *Saved 1 byte thanks to @Oliver* Takes input as an array of characters. Outputs a comma-separated string where the first value is the total time and the next ones describe the path. ``` a=>(b=g=(r,s=o='',c,p)=>s[c>b|4]?o=(b=c)+r:a.map((v,i)=>s.match(v)||(d=p<i?i-p:p-i)<2||g([r,i],s+v,~~c+d,i))&&o)`` ``` [Try it online!](https://tio.run/##XYyxDoIwEIZ3n8LJXkNhME7Eg6QD7i4OhIRSFGuQNpQwNbw6Uk0wYflyd///3UuMwspemSHsdH2fHzgLTKDCBqFnFjUSwiQzFBOby6RypyLVuOSSBn0sorcwACNTPl@WQT5hpM5BjeasUhWa2ISKno/ONZD3TBXMBiObJhnUi0QPB03Lcpa6s7q9R61u4AE5uRG2J9zjO108Mo/r71ZQuts6/zpfHb6KfLU3vcw/mz8 "JavaScript (Node.js) – Try It Online") ### Commented ``` a => ( // a[] = input array b = // b = best score so far (initially a non-numeric value) g = ( // g = recursive function taking: r, // r = path s = // s = string of collected loaves of bread o = '', // o = final output c, // c = current cost p // p = index of the last visited shelf ) => // s[c > b // if the final cost is not greater than our best score | 4] ? // and we've successfully collected 5 loaves of bread: o = (b = c) + r // update the current output and the best score : // else: a.map((v, i) => // for each loaf of bread v at shelf i in a[]: s.match(v) || // if we've already collected this kind of bread (d = // or the distance d p < i ? i - p : p - i // defined as the absolute value of p - i ) < 2 || // is less than 2: stop recursion g( // otherwise, do a recursive call to g() with: [r, i], // r updated with the index of the current shelf s + v, // s updated with the current loaf of bread ~~c + d, // c updated with the last distance i // i as the index of the last shelf ) // end of recursive call ) // end of map() && o // return the current output )`` // initial call to g() with r = [""] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~212~~ 210 bytes ``` lambda s:min((sum(h(p)),p)for b in combinations(range(len(s)),5)for p in permutations(b)if(len(set(s[i]for i in p))==5)&all(d>1for d in h(p))) h=lambda p:[abs(y-x)for x,y in zip(p,p[1:])] from itertools import* ``` [Try it online!](https://tio.run/##RZCxboMwEIbn8BQ31eeKRkqlLEh0YKB7FwbKYIIdXGH7ZDtS6MtTm0Tqdvfdp7tfR2ucnX3fVP29LcKMk4BQGW0Rw83gjMR5SVw5DyNoCxdnRm1F1M4G9MJeJS7SYkjWebcoWyS9ucWnNXKtHpKMGHo9ZE3vGud1feYvYllw@jhlPmW@X@XFXD8DUdWLMeD6dt9P3Ms1W7@akErqT9XAh0J5Z0BH6aNzSwBtyPn4uk1SQZviVcUhQA3h6CUt4iKRASsZ48WBElbJSJXXNkIoKQ2OPy79IKeF/7j9aeBF0SLroIEOPqGFL@jSkoQyaBJqEmwSfvQt49sf "Python 2 – Try It Online") 2 bytes thx to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech). ]
[Question] [ Dice Cricket is a game I was introduced to as a child and have used as a way to pass time for years since. I couldn't find a Wikipedia page so I'll explain the rules below. # Dice Cricket Rules ## Premise Dice Cricket is a game similar to scoring a game of [cricket](https://en.wikipedia.org/wiki/Cricket) as you watch it but rather than *watching* and recording the result, you are *rolling a die* and recording the result. The results are recorded in a table as displayed at the bottom. ## Display Dice Cricket uses a specific display to show all the information happening. The table has 11 rows. Each row represents a batter. The layout of the row is explained below. ``` +------+------------------------------+---------+-----+ | Name | Runs | How Out |Score| +------+------------------------------+---------+-----+ ``` * Name: The name must be a string made up entirely of letters, upper or lower case * Runs: A batter can face 30 balls. Each ball can be one of `1 2 4 6 . /`. This will be explained in more detail below * How Out: The way the batter was out. Can be any of `Bowled, LBW (Leg Before Wicket), Caught, Retired or Not Out` * Score: The sum of all numbers in `Runs` ## How the Game Works In a game, there are always 2 batters out on the pitch. The first player is by default the current batter and the second in the "off" batter. A game is made up of "balls": each ball in a cricket match is represented by a dice roll. Each roll does a different command: * 1,2,4 and 6 make the batter score that much. If 1 is rolled, the current batter becomes the "off" batter and the "off" batter becomes the current * 3 is a "dot ball", meaning that nothing happens. It is represented in the `Runs` section as a `.` and scores 0. A `0` may not be used to represent it. * 5 is a wicket. If 5 is rolled, the current batter is "out", This means that a `/` is added to the runs and from then on, the batter cannot score anymore runs. The batter is then swapped with the next batter who has not batted. The `How Out` section is a random choice of the possible ways to get out: `Bowled, LBW, Caught` Example for a wicket (this is just for clarity, this isn't how its outputted) ``` player a is on 4,6,2,6,4 player b is on 6,4,2,6,6 player c hasn't batted player a is current batter WICKET!!! player a is on 4,6,2,6,4,/ player b in on 6,4,2,6,6 player c is on NOTHING player c is current batter ``` Every 6 balls, the two batters switch; the current batter becomes the "off" batter and the "off" batter becomes the current batter If the `Runs` section is filled (30 balls), the batter is out and the `How Out` section is set to `Retired`. A `/` **isn't** placed at the end of the `Runs` box. # Actual Challenge (yes all that was rules of the game) Your challenge is to output a completed table (like the example at the end), given a list of names. The contents of the output should contain only the table and/or leading or trailing whitespace. ## Rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed * All 11 players should have something in the `Runs` section. * Only 1 player can be `Not Out`. Every other non-retired player should be out of a choice of `[Bowled, LBW, Caught]` * The names can be any length between 1 and 6 that matches the regex `A-Za-z` * The final line in the table should be the total line (see example) * You don't have to align the text in the table in any way, but the row and column separators must be aligned. ## Example ``` Input: ['Fred', 'Sonya', 'David', 'Ben', 'Cody', 'Hazel', 'Nina', 'Kim', 'Cath', 'Lena', 'Will'] Output: +------+------------------------------+---------+-----+ | Name | Runs | How Out |Total| +------+------------------------------+---------+-----+ |Fred |.662/ | Caught | 14 | +------+------------------------------+---------+-----+ |Sonya |1164/ | Caught | 12 | +------+------------------------------+---------+-----+ |David |/ | LBW | 0 | +------+------------------------------+---------+-----+ |Ben |424/ | LBW | 10 | +------+------------------------------+---------+-----+ |Cody |62/ | Bowled | 8 | +------+------------------------------+---------+-----+ |Hazel |/ | LBW | 0 | +------+------------------------------+---------+-----+ |Nina |161.6226166..44261442/ | Caught | 64 | +------+------------------------------+---------+-----+ |Kim |11/ | Caught | 2 | +------+------------------------------+---------+-----+ |Cath |6.21/ | LBW | 9 | +------+------------------------------+---------+-----+ |Lena |/ | Bowled | 0 | +------+------------------------------+---------+-----+ |Will |2 | Not Out | 2 | +------+------------------------------+---------+-----+ | Total Runs | 121 | +-----------------------------------------------+-----+ ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~650~~ ~~621~~ ~~582~~ ~~572~~ 588 bytes ``` from random import* h=str c=h.center a='+'.join(map('-'.__mul__,[0,6,30,9,5,0]))+'\n' b=lambda x,r=6:x.ljust(r,' ') j=''.join t=lambda a:sum(map(int,a[:-1].replace(*'.0'))) P=print def s(i=30): while i:x=choice('12.4/6');yield x;i=('/'!=x)*~-i def f(n,T=0): n=[*map(b,n)] P(a+f'| Name | Runs{" "*25}| How Out |Total|') for x in n[:-1]:S=j(s());T+=t(S);P(a,x,b(S,30),c(choice(['Bowled','LBW','Caught']),9),c(h(t(S)),5),sep='|',end='|\n') S=j(s());P(a,n[-1],b(S,30),' Not Out ',c(h(t(S)),5),sep='|',end='|\n');P(a+f'|{15*" "}Total Runs{15*" "} |{c(h(T),5)}|\n+{47*"-"}+{5*"-"}+') ``` [Try it online!](https://tio.run/##hVBNj9owEL3nV7hcxk5MFpaFaoN8Yatqpa7oqiDtgSJkiNMYJXaUOCUsoX@d2oHutT74jebjvXlTHE2q1ehySUqdo5Kr2ILMC10a30tZZUpvx9JwJ5QRpccZBBDutVQ45wWGPoSbTV5nmw1dDeiEjgb0kY7pYE1IAD8VeFuW8Xwbc9TQkk2iJsz2dWVwSQEB8fYMrmye@dfHo6rOO3KpDOWrqD9ch6UoMr4T2IdwAIQQ75UVpa17sUhQhSUbDUjkoUMqM4Fk1LBdqqXth@F9@HA3ATI9SpHFqJlKhuEOPrGG@H/6sptPsKJL1hEotvKd9JYqsvbQK@ZBAi2a81ygFv2oVXXqoZ5/Pz636Fkf0PfaoHapDc9a6wYlukQNkgqpbu1owfa4woRMlwEzeEGmlpA2dIsX9lCE7vBtzRXM9CETMVB4mb3Z/4nXv1IDa0IfXVuK3TShY0IrUTBogQoVW7QXtrIfMo5erazyhwSguTbdmvA/nunN7Wk49q3Jc2fr6vmWQdfXnhzT0tGc7WRwevjs9/q9c3AaXxHIJbGevpbOEYKFVkfugi/8t@wyM6EcPOn46PCZv4vMBXOpusZvMu/q3KQOX8Q1/SazzN7k8hc "Python 3 – Try It Online") Well, it's been over 24 hours and this took me about an hour to whip up, so I hope I'm not FGITW'ing anyone, and I haven't golfed in Python in a while, so this was fun (although this is the second time I've answered one of my own questions with a long Python answer) Please feel free to post golf suggestions, Python isn't my best language for golfing. -68 bytes thanks to [FlipTack](https://codegolf.stackexchange.com/users/60919/fliptack)! -8 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) +16 bytes due to a bug [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~277~~ 255 bytes ``` ≔E¹¹⟦⟦⟧⁰S⟧θ≔⮌θηW⊖Lη«≔⊟ηι≔‽12.4/6ζ⊞υζ⊞§ι⁰ζ≔⎇⁼ζ/⁺²‽³⁼³⁰L§ι⁰ζ¿ζ§≔ι¹ζ⊞ηι¿⊖Lη¿⁼¬﹪Lυ⁶¬εF⟦⊟η⊟η⟧⊞ηκ»”|⁴B\[⎇⁻℅↧T`⁵·5KMK⟲M≦»→´⁶_⭆∨R▷↥l⁹KG…≦”Fθ«◨⊟ι⁷◨Σ§ι⁰¦³²§⪪”(3⪪⪫⧴πZJL:∨XI±URD↗Σ9⟦FZ∕↖l⪪”⁷⊟ι◧IΣE⊟ιΣκ⁶⸿⸿»”|QºWPD⟧zNφ[v?Π'vG”◧IΣEυΣι²⁸J±¹±¹FE¹³⁻²⁷⊗ι«B⁵⁵ιB⁴⁹ι¿‹ι²⁷«B³⁹ιB⁸ι ``` [Try it online!](https://tio.run/##fVPBbhoxED2XrxjtBVvaNgUSSNVTIK2SFigCpBwIB5c1rBWvDbs2BCq@nXq86wiqKnuxZ@Z53syb2UXK8oVm8nS6KwqxUmTA1qTRiGE2m8fwOYZHtbZmYnKhVoTOaQwb@rVWYcd8y/OCk41zp869S4XkQO75IucZV4YnpM/VyqQkpRT@1D5U70Z67TwxCPcm@MZMJTojUaP56fqqHbnoAaMjW6TEnht35lEl/JUIV15AVTmmPFcs35NvG8tkQQ4xRFeYaSRtQZoxVBwt6nwVpuVarGq8SExpyC2WQA4USoozTKOKc1lw8JWlVUf44v8aUMBYRT3Uhgx0YqUOCOs420iMoQPClzoHMgt6leecvtG9OLpjbeSGY0g0ZBkHgLFVBbzzPegd/LIGYKoNk8/5cx65LJ5o44dUphuxZCxWqfHDEo68Q/0ILoMTm/2jWwyt5hkyBCdrKbBGbZB8zI3IedLVO8kT6DHrcrnS@t0ngAipyl4FveTs86UhPVaUvLipoTi0X8qhtc/eRKG9N5EutfASeMUQ9A6PLSlESdG8RY4fNltPNRnyFTOcNHBs4RoE9T9TK4aBULiBnRjutf3tei4zodpd/UpubqrNQeP6y9ka9XlRoLDNTon2iFZAeOu2Mo614@k0q393utZjqE@02jO83LOt8J4uV3j0dLLH84EduMTLUCgP/CkyH2cmxdPtpHc/CSnr89PHrfwL "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔E¹¹⟦⟦⟧⁰S⟧θ ``` Read in the 11 names (input is flexible: JSON, space separated, or newline separated) and create an array `q` of 11 batters, represented by their balls (as an array), status (as an integer) and name. ``` ≔⮌θη ``` Create a reversed copy of the batters `h`. This represents the batters that are not out. The last two elements are the off and current batters. ``` W⊖Lη« ``` Repeat while there are at least two batters available. ``` ≔⊟ηι ``` Extract the current batter to `i`. ``` ≔‽12.4/6ζ ``` Generate a random ball in `z`. ``` ⊞υζ ``` Add it to the overall list of balls using the predefined empty list `u`. ``` ⊞§ι⁰ζ ``` Add it to the current batter's balls. ``` ≔⎇⁼ζ/⁺²‽³⁼³⁰L§ι⁰ζ ``` If the ball is a `/`, then generate a random status `2..4`, otherwise if this is the batter's 30th ball then set the status to `1` otherwise `0`. ``` ¿ζ§≔ι¹ζ⊞ηι ``` If the batter is out then store the batter's status otherwise put the batter back in to bat. ``` ¿⊖Lθ¿⁼¬﹪ΣEηLκ⁶¬ζ ``` If there are at least two batters left, and the batter was out xor 6 balls have been played, then... ``` F⟦⊟η⊟η⟧⊞ηκ» ``` ...take the off and current batters and put them back in reverse order. ``` ”|⁴B\[⎇⁻℅↧T`⁵·5KMK⟲M≦»→´⁶_⭆∨R▷↥l⁹KG…≦” ``` Print the header. ``` Fθ« ``` Loop over the batters. ``` ◨⊟ι⁷ ``` Print the batter's name. ``` ◨Σ§ι⁰¦³² ``` Print the batter's balls. ``` §⪪”(3⪪⪫⧴πZJL:∨XI±URD↗Σ9⟦FZ∕↖l⪪”⁷⊟ι ``` Print the batter's status by indexing into the string `Not OutRetiredBowled Caught LBW` split into substrings of length 7. ``` ◧IΣE⊟ιΣκ⁶ ``` Print the batter's score. ``` ⸿⸿» ``` Move to the start of the next line but one. ``` ”|QºWPD⟧zNφ[v?Π'vG”◧IΣEυΣι²⁸ ``` Print the total. ``` J±¹±¹FE¹³⁻²⁷⊗ι«B⁵⁵ιB⁴⁹ι¿‹ι²⁷«B³⁹ιB⁸ι ``` Draw boxes around everything. ]
[Question] [ I have a bunch of boards I need to stack in as small a space as possible. Unfortunately, the boards fall over if I stack them more than 10 high. I need a program to tell me how to stack the boards to take as little horizontal space as possible, without stacking boards more than ten high, or having boards hanging out over empty space. ## Your Task: Write a program or function, that when given an array containing the lengths of boards, outputs as ASCII art the way to stack the boards to conserve as much horizontal space as possible, without stacking the boards more than 10 high or having any part of any board hanging out over empty space. Your ASCII art should show the configuration of the boards, with each one shown using a different character. There will be a maximum of 20 boards. For example, if the input was [2,2,4,2,2,4,4,4], a possible output is: ``` dhh dgg dff dee abc abc abc abc ``` which is a stable configuration (although this would fall over in ~0.1 seconds in real life). ## Input: An array containing up to 20 integers, showing the lengths of the boards. ## Output: ASCII art showing the configurations of the boards, as outlined above. ## Test Cases: Note that there may be other solutions for the test cases, and the characters shown for each board may be different. ``` [12,2,2,2,3,4,4,8,8] -> ffgghhiii ddddeeeeeeee bbbbbbbbcccc aaaaaaaaaaaa [4,4,4,4,4,4,4,4,4,4,4,4] -> llll aaaa cfghk cfghk cfghk cfghk debij debij debij debij [4,4,4,4,4,4,3,3,3,2,2,2,1] -> jjml iiil hhhk gggk ffff eeee dddd cccc bbbb aaaa ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins [Answer] # [Python 3](https://docs.python.org/3.6/), 513 512 511 509 499 497 485 465 459 458 444 bytes Incredibly bad runtime, will finish at some point ``` e,j,c=enumerate,len,range def f(n,p=[],o=97): r,l,m=lambda x:min(b,f(n[:i]+n[i+1:],x,o+1),key=j),chr(o),j(p) b=[p,l*(sum(n)*2+m)][n>[]] for i,a in e(n): for h,d in e(p): if a<11-j(d):b=r([p[f]+l*a*(f==h)for f in c(m)]) if(j(d)<10)*all(j(x)==j(d)for x in p[h:h+a])*(a<=m-h):b=r([p[f]+l*(h<=f<h+a)for f in c(m)]) if a<11:b=r(p+[l*a]) b=r(p+[l]*a) return["\n".join("".join(9-u<j(x)and x[9-u]or" "for x in b)for u in c(10)),b][o>97] ``` [Try it online!](https://tio.run/##bVDBjoMgFDzXryCeQF83a3vo1kh/hOWACouuAqGa2K93QdtNNtkTmXkzb4bnHpO25ryuEnpoqDTzKL2YJAzSgBfmSyatVEhhA44yDpZeL6RMDh4GGOkgxroVaCnHzuAagoqVHc8N6/Ki5LCAzQsC3/JBewKN9tgS6LEjyaGmzMGQ4fs8YkOyUz4SzsyNcZ4clPWoA4E6g2QYhrSN0tDulNuoQ6eQqIri2OOWlDX1mDmmeD5kIsOKUk2iSUVLg8N2sntwlFfFO8nEMASwEEojFcVLFDumS50LTjIsKjoe9d/lWFdUVUHwz/pno03vchaabPQL8kwE6OU0e8PST5O@9TbcLX2@1@NcxT7CtGhhAXHrU5T@Fqu3xHlPDB8gUHNmb9cLXxtxl3dEEWYFnDiw4gRn@Ajh0RGHmymKwuWc78yEIyIvoHZI1h8) Edit: -2 -8 bytes thanks to [@Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) Edit: -8 bytes thanks to [@notjagan](https://codegolf.stackexchange.com/users/63641/notjagan) ## Explanation ``` e,j,c=enumerate,len,range # These built-ins are used a lot def f(n,p=[],o=97): # n is the remaining blocks # p is the current stack # o is the ASCI code for the next letter to use r,l,m=lambda x:min(b,f(n[:i]+n[i+1:],x,o+1),key=j),chr(o),j(p) # r is the recursive call, that also selects the smallest stack found # l is the letter to use next # m is the length of the current stack b=[p,l*(sum(n)*2+m)][n>[]] # Sets the current best, if there are no remaining blocks, select the found stack, else we set it to be worse than the possible worst case for i,a in e(n): # Loop through all the remaining blocks for h,d in e(p): # Loop through all the columns in the current stack if a<11-j(d):b=r([p[f]+l*a*(f==h)for f in c(m)]) # If we can place the current block vertically in the current column, try it if(j(d)<10)*all(j(x)==j(d)for x in p[h:h+a])*(a<=m-h):b=r([p[f]+l*(h<=f<h+a)for f in c(m)]) # If we can place the current block horizontally starting in the current column, try it if a<11:b=r(p+[l*a]) # If the current block is lower than 10, try place it vertically to the right of the current stack b=r(p+[l]*a) # Try to place the current horizontally to the right of the current stack return["\n".join("".join(9-u<j(x)and x[9-u]or" "for x in b)for u in c(10)),b][o>97] # Return the best choice if we aren't in the first call to the function, that is the next letter is a. Else return the found best option formatted as a string ``` # [Python 3](https://docs.python.org/3.6/), 587 bytes Actually runnable on TIO for some of the test cases ``` e,j,c=enumerate,len,range def f(n,p=[],o=97,b=[]): if(not n):return p if not b:b="a"*sum(n)*2 r,q,s,l,m=lambda x:q(f(n[:i]+n[i+1:],x,o+1,b)),lambda x:[b,x][j(b)>j(x)],b,chr(o),j(p) if j(b)<=m:return b for i,a in e(n): for h,d in e(p): if a<11-j(d):b=r([p[f]+l*a*(f==h)for f in c(m)]) if j(d)<10 and a<=m-h and all(map(lambda x:j(x)==j(d),p[h:h+a])):b=r([p[f]+l*(h<=f<h+a)for f in c(m)]) if s==b: if a<11and m+1<j(b):b=r(p[:]+[l*a]) if m+a<j(b):b=r(p[:]+[l for r in c(a)]) return["\n".join("".join(map(lambda x:" "if u>=j(x)else x[u],b))for u in c(9,-1,-1)),b][o>97] ``` [Try it online!](https://tio.run/##bVHdbrQgEL3efQriFayzTXWbtGtkX4SPC1ixagQpamKffj9G203/MkbgzMw5Z8C/T83gTrebgQ6u3LjZmqAmA71xEJR7NfvK1KSmDjwXEgZ@fgYdd6zY79oIDxNxrAhmmoMjHjGCmC40T1RyGGdLHTvk@12ANxihB8t7ZXWlyFK80UggilamTrRpVkhYYEgz0IzBvUhoWKToqGaXji5MgoZrE@jAoKOerYKYLLn9dKH3u3oIpAVFWkdM1I9eV6iBaoP8CmGvKrPs2NGKRcOBCi9qmfYHdaA15w3DphpbrtQyyT56sLzMHolyVezn9ths276nVnl6t45@Ocdq8KIpmlRJ9l2HNiWvy5j4QykKjZzrr0ZRxaZZiQOvPF4UMhXR792bTdWvNEHysJGrlXy7KZH8c8lDN7SOJh/rN/8JSSLjfOE4iOlHQxYxS3weJJw3wjMcs/jFJ9NSDJfzs7xd1WhGwgkVOeTwBNs/hgSR5bDFaYVe4CWCT/Bn/Mic1ti6szgFmkCp1QdKiiKX8bp8aN1EEWGfh3o7stt/) Both solutions could probably be golfed quite a bit. [Answer] # Python3, 1081 bytes Rather long, but crunches every test case, including several additional ones, in ~0.184 seconds ``` E=enumerate R=range from itertools import* G=lambda l:[[j for j,_ in b]for a,b in groupby(E(l),key=lambda x:x[1]=='')if a] def C(l,L,H): q=[([a],[i])for i,a in E(l)if a<=L] while q: A,I=q.pop(0) if sum(A)<=L and(H==0 or sum(A)==L):yield(tuple(A),I) for i,a in E(l[max(I)+1:],max(I)+1): if sum(T:=A+[a])<=L:q+=[(T,I+[i])] def P(b,l,Q,t): for i,a in E(b): if''in a: F=0 B,Y=eval(str(b)),[] for g in G(a): if(O:=[*C(l,len(g),t)]): F,d=1,{} for J,K in O:d[J]=K O=[*d.items()] M=max(sum(A)for A,_ in O) V,I=min([(o,p)for o,p in O if sum(o)==M],key=lambda x:len(x[0]));Y+=I for v in V: Q+=1 for _ in R(v):B[i][g.pop(0)]=chr(Q) if F or t:return(B,[y for x,y in E(l)if x not in Y],Q) def f(l): I,Q=1 if max(l)<11 else max(l),96 while I: q,S=[(B:=[[''for _ in R(I)]for _ in R(10)],[*l],96)],[B] while q: b,L,Q=q.pop(0) if[]==L:return b if(C:=P(b,L,Q,1))and C not in S:q+=[C];S+=[C] if(C:=P([*map(list,zip(*b))],L,Q,0)): B,L,Q=C; if(B:=[*map(list,zip(*B))])not in S:q+=[(B,L,Q)];S+=[B] I+=1 ``` [Try it online!](https://tio.run/##dVPbbtpAEH3nK/aNXRhFOEQVdbIPGOXilIiSRJGi1aqyy0Kcri8Yk0KrfjudWZsUqlaLsGdnzpkzFxfb6iXP@oOi3O0upcnWqSmjyrTuZRllC9Oal3nKksqUVZ7bFUvSIi@rTuta2iiNZxGzvlKvbJ6X7BW@sCRjsSYjgpiMRZmvi3jLL7kV8M1s96iNv1GelrLdFsmcRZq1ZmbORtzCGG6E32JLqbiKNKhEC@JLICI@4iHAhRzrFvv@kljDlhjOhhDK5UmRF7wn0MSY1TrlQ4GBLMpm/EbKHkOe@lbKsfC3ibEzXq0La/AKQsIdp1JptOGh6Hq@hv0riXvnf/TlsIsyKY2/7KLmRwi7pFm7gj7zGCxMoSLUEXfseJJ5u41m5DivZI8eATxL8xZZvqpKDBOgNF0TekHYax7VGhDNJ75UHWqbNRlfCEykGye7gpn04Oev2iL4LXwigok/U7dafqodEySYneCA0xUXur67k1Rt3SoCDuvJTkTtfsJep0nGFc@hcAH4dAH7vuTY4Tt9PHBSuFE9LcT5c1eGf2S9EfSpUc2mXek1r@R0ie/5m/ADbKtaNCPW8utLyaeimcUVjbbyS1Oty4wHoLYOvIHtwdJsWJZXZD9rQCTNZ44eTBzCVHrEQ2VbceF5zNiVaUz4@GG/aiGpXMIDDjrAzqt2@0BjKPSB5aFIUB2rEU5vAfX2YGFZjKs@PdxZFKDwkxg3ZbC4vuMjX9IeYTR4QuAys9G@kge3dCN9/uAehwDVSaOC22RVwY@k4B3cJO04eqLZkMAJGJ3vd4kq@gsUIEgc5eIOJeqMrqYQB7YryiSr@JyrAbD618dBt96vT@EUzqD@x3Pk806hPn3nHMDgyH0G/zz/jem7UzN6GLX7DQ) ]
[Question] [ A superior highly composite number is an integer where the ratio of its count of divisors to some power of the number is as high as possible. Expressing this as a formula: Let d(n) be the number of divisors of n, including the number itself. For a given integer n, if there exists a number e such that d(n)/n^e is greater than or equal to d(k)/k^e for every integer k, then n is a highly composite number. For more, see [Superior highly composite number](https://en.wikipedia.org/wiki/Superior_highly_composite_number) at Wikipedia, or [A002201](https://oeis.org/A002201) at OEIS. Here are the initial values: ``` 2, 6, 12, 60, 120, 360, 2520, 5040, 55440, 720720, 1441440, 4324320, 21621600, 367567200, 6983776800, 13967553600, 321253732800, 2248776129600, 65214507758400, 195643523275200, 6064949221531200 ``` Your challenge is to take an index n, and output the nth number in this sequence. You may use 0 or 1 indexing, and you may make a program which is only correct up to the limits of your language's data type(s), as long as it can handle the first 10 values at a minimum. This is code golf. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Answer] # Mathematica, 277 bytes ``` (A=AppendTo;p[f_]:=Module[{p=f[[1]],k=f[[2]]},N[Log[(k+2)/(k+1)]/Log[p]]];m=#;f={{2,1},{3,0}};o=1;l={2};x=Table[p[f[[i]]],{i,o+1}];For[n=2,n<=m,n++,i=Position[x,Max[x]][[1,1]];A[l,f[[i,1]]];f[[i,2]]++;If[i>o,o++;A[f,{Prime[i+1],0}];A[x,p[f[[-1]]]]];x[[i]]=p[f[[i]]]];Times@@l)& ``` input > > [21] > > > output > > 6064949221531200 > > > input > > [50] > > > output > > 247899128073275948560051200231228551175691632580942972608000 > > > ]
[Question] [ # Backstory You wake up dizzy in a chemistry laboratory, and you realize you have been kidnapped by a old mad chemist. Since he cannot see very well because of his age, he wants you to work for him and only then, you can escape the laboratory. # Task It is your task to return the [structural formulae](https://en.wikipedia.org/wiki/Structural_formula) of the molecules whose [chemical formula](https://en.wikipedia.org/wiki/Chemical_formula) will be given as input. Note that only the carbon (`C`), oxygen (`O`) and hydrogen (`H`) atoms will be used as input. Unlike in chemical formulas, a `0` is a valid quantifier and a `1` cannot be omitted (e.g. `C1H4O0` is valid input, but `CH4` isn't). To prevent ambiguity, we assume double and triple bonds do not appear in the molecules. All carbon atoms need 4 single bonds, all oxygen atoms need 2, and hydrogen atoms need one. We also assume that `O-O` bonds do not exist as well. The molecule does not have to exist nor be stable. The input will never contain more than `3` carbon atoms to ensure lightness in the output's display. You only should display the molecules whose carbons atoms are arranged in a straight line without interruption. Ergo, no `C-O-C` bonds. You must return **all** possible molecules not excluded by the previous rules. You do not need to handle invalid inputs. The following example displays all the solutions you have to handle for that molecule. A rotation by 180 degrees in the plane of the page of one of the molecule's formula is considered a redundancy and does not need to be displayed. In the example below I'll show all of the possible formulae for a molecule, then point out the ones that do not need to be displayed. # Example Input: `C2H6O2` First, here are all the possible formulae for this input (Thank you to @Jonathan Allan) ``` 01 H | O H | | H - O - C - C - H | | H H 02 H | H O | | H - O - C - C - H | | H H 03 H H | | H - O - C - C - O - H | | H H 04 H H | | H - O - C - C - H | | H O | H 05 H H | | H - O - C - C - H | | O H | H 12 H H | | O O | | H - C - C - H | | H H 13 H | O H | | H - C - C - O - H | | H H 14 H | O H | | H - C - C - H | | H O | H 15 H | O H | | H - C - C - H | | O H | H 23 H | H O | | H - C - C - O - H | | H H 24 H | H O | | H - C - C - H | | H O | H 25 H | H O | | H - C - C - H | | O H | H 34 H H | | H - C - C - O - H | | H O | H 35 H H | | H - C - C - O - H | | O H | H 45 H H | | H - C - C - H | | O O | | H H ``` And here are the formulae that should be in the output if we take out the rotations of 180° in the plane of the page : ``` 01 H | O H | | H - O - C - C - H | | H H 03 H H | | H - O - C - C - O - H | | H H 12 H H | | O O | | H - C - C - H | | H H 13 H | O H | | H - C - C - O - H | | H H 14 H | O H | | H - C - C - H | | H O | H 15 H | O H | | H - C - C - H | | O H | H 23 H | H O | | H - C - C - O - H | | H H 25 H | H O | | H - C - C - H | | O H | H 35 H H | | H - C - C - O - H | | O H | H ``` You do not need to output the labels of the formulae and you can output either of the rotations when two exist. For example you can output either 02 or 35. Here are some valid inputs to test your code: ``` C3H8O2 C1H4O0 C2H6O2 C1H4O1 C2H6O2 ``` The PC the chemist gave you to complete your task is quite old so you do not have a lot of memory on it to save your code, thus this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and the shortest amount of byte wins! [Answer] # Ruby, 275 ``` ->s{(k=4<<2*c=s[1].to_i).times{|i|z=" "*8 t=(" H|O|"[i%2*2,4]+"C|"*c+"O|H "[i>>c&2^2,4]).chars.map{|j|z+j+z} (c*2).times{|j|t[4+j&-2][j%2*10,7]=" H - O - H "[[i>>j/2-1&4,-7-(i>>c*2-j/2-1&4)][j%2],7]} i*(k+1)>>c+1&k-1<i||("%b"%i).sum%16!=s[5].to_i||i%7>c*3||puts(t)}} ``` Combined formulas for left and right sidechains and eliminated variable `h` # Ruby, 279 ``` ->s{(k=1<<h=2+2*c=s[1].to_i).times{|i|t=(" H|O|"[i%2*2,4]+"C|"*c+"O|H "[i>>c&2^2,4]).chars.map{|j|(z=" "*8)+j+z} c.times{|j|t[4+j*2][0,7]=" H - O -"[i>>j-1&4,7] t[4+j*2][10,7]="- O - H "[i>>h-j-3&4^4,7]} i*(k+1)>>h/2&k-1<i||("%b"%i).sum%16!=s[5].to_i||i%7>c*3||puts(t)}} ``` **Ungolfed in test program** ``` f=->s{ (k=1<<h=2+2*c=s[1].to_i).times{|i| #c=number of C atoms. h=number of H (calculated) #iterate i from 0 to (k=1<<h)-1 t=(" H|O|"[i%2*2,4]+"C|"*c+"O|H "[i>>c&2^2,4]). #compose a backbone string H-C...C-H. Insert O at the top where bit 0 of i set, and O at the bottom where bit c+1 of i set chars.map{|j|(z=" "*8)+j+z} #convert string to an array of characters, pad each character left and right with 8 spaces c.times{|j|t[4+j*2][0,7]=" H - O -"[i>>j-1&4,7] #overwrite spaces on left with H or HO according to bits 1 up to c t[4+j*2][10,7]="- O - H "[i>>h-j-3&4^4,7]} #overwrite spaces on right with H or OH according to bits h-1 down to c+1 i*(k+1)>>h/2&k-1<i|| #rotate the bits of i by h/2. if this is less than i, do not output the structure (eliminates rotations by 180deg by outputtng the lexically highest) ("%b"%i).sum%16!=s[5].to_i|| #if the number of 1's in i differs from the number of O's indicated in the input, do not output i%7>c*3|| #if i%7>c*3, do not output (empirical solution to avoid 90deg rotations for C=1) puts(t) #if the above are all false, output the current structure. } } f[gets] ``` **Output** Spacing is as per question output. Backbone vertical instead of horizontal allowed per comments. Rotations of the entire display through 90 or 180 degrees considered equivalent. ``` C2H6O2 H | O | H - O - C - H | H - C - H | H H | O | H - C - H | H - O - C - H | H H | H - O - C - H | H - O - C - H | H H | O | H - C - H | H - C - H | O | H H | H - O - C - H | H - C - H | O | H H | H - C - H | H - O - C - H | O | H H | H - O - C - H | H - C - O - H | H H | H - C - H | H - O - C - O - H | H H | H - C - O - H | H - O - C - H | H ``` ]
[Question] [ ### Challenge: Given a checkerboard, output the smallest amount of moves it would take (assuming black does not move at all) to king a red piece, if possible. **Rules**: Red's side will always be on the bottom, however their pieces may start in any row (even the king's row they need to get to). Black pieces are **stationary**, meaning they do not move in between red's movements, but they are removed from the board when captured. Note that pieces can start on *any* space on the board, including right next to each other. This is not how normal checkers is played, but your program must be able to solve these. (See input 5) However, checker pieces must only move **diagonally** (see input 3). Backward-capturing is allowed if the first capture is forward in the chain (see input 7). **Input:** An 8x8 checkerboard, with board spaces defined as the following characters(feel free to use alternatives as long as they're consistent): . - Empty R - Red piece(s) B - Black piece(s) **Output:** The *smallest* number of moves it would take a red piece to be 'kinged' by entering the king's row on the top row of the board (black's side), 0 if no moves are required (a red piece started on king's row), or a negative number if it is impossible to king a red piece (ie black occupies it's entire first row). Input 1: ``` . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . R . . . . . . . ``` Output 1: ``` 7 ``` Input 2: ``` . . . . . . . . . . . . . . . . . . . . . B . . . . . . . . . . . . . B . . . . . . . . . . . . . B . . . . . . R . . . . . . . ``` Output 2: ``` 2 ``` Input 3: ``` . B . B . B . B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . R . . . . . . . ``` Output 3: ``` -1 ``` Input 4: ``` . . . . . . . R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . R . . . . . . . ``` Output 4: ``` 0 ``` Input 5: ``` . . . . . . . . . . . . . . . . . . . . . . . . . B . . B . . . B . . . . B . . . B . B . . . . . . B . . B . . . . . R R . . . ``` Output 5: ``` 4 ``` Input 6: ``` . . . . . . . . . . . . . . . . . B . . . . . . . . B . . . . . . B . B . . . . . . . . R . . . . . . B . . . . . . . . R . . . ``` Output 6: ``` 2 ``` Input 7: ``` . . . . . . . . . . . . . . . . . . B . . . . . . . . . . . . . . . B . . . . . . B . B . B . . . . . . B . . . . . . . . R . R ``` Output 7: ``` 4 ``` **Scoring:** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Answer] ## JavaScript (ES6), ~~354~~ 322 bytes Takes an array as input with: * 0 = empty square * 1 = red piece * 2 = black piece Returns the optimal number of moves, or 99 if there's no solution. It's very fast but could be golfed much more. ``` F=(b,n=0,C=-1,i)=>b.map((v,f,X,T,x=f&7,y=f>>3)=>v-1||(y&&n<m?[-9,-7,7,9].map(d=>(N=c=X=-1,r=(d&7)<2,T=(t=f+d)>=0&t<64&&(x||r)&&(x<7||!r)?(!b[t]&d<0)?t:b[t]&1?N:b[t]&2&&(d<0&y>1|d>0&C==f)?(X=t,x>1||r)&&(x<6|!r)&&!b[t+=d]?c=t:N:N:N)+1&&(b[f]=b[X]=0,b[T]=1,F(b,n+!(C==f&c>N),c,1),b[f]=1,b[X]=2,b[T]=0)):m=n<m?n:m),m=i?m:99)|m var test = [ [ 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0 ], [ 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,2,0,0, 0,0,0,0,0,0,0,0, 0,0,0,2,0,0,0,0, 0,0,0,0,0,0,0,0, 0,2,0,0,0,0,0,0, 1,0,0,0,0,0,0,0 ], [ 0,2,0,2,0,2,0,2, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0 ], [ 0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0 ], [ 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,2,0,0,2,0,0,0, 2,0,0,0,0,2,0,0, 0,2,0,2,0,0,0,0, 0,0,2,0,0,2,0,0, 0,0,0,1,1,0,0,0 ], [ 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,2,0,0,0,0,0,0, 0,0,2,0,0,0,0,0, 0,2,0,2,0,0,0,0, 0,0,0,0,1,0,0,0, 0,0,0,2,0,0,0,0, 0,0,0,0,1,0,0,0 ], [ 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,2,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,2,0,0,0,0,0, 0,2,0,2,0,2,0,0, 0,0,0,0,2,0,0,0, 0,0,0,0,0,1,0,1 ] ]; test.forEach((b, n) => { console.log("Test #" + (n + 1) + " : " + F(b)); }); ``` ]
[Question] [ *Inspired by [this question](https://math.stackexchange.com/q/1609248) over on Math.* Let the prime factorization of a number, *n*, be represented as: \$P(n) = 2^a\times3^b\times5^c\times\cdots\$. Then the number of divisors of *n* can be represented as \$D(n) = (a+1)\times(b+1)\times(c+1)\times\cdots\$. Thus, we can easily say that the number of divisors of \$2n\$ is \$D(2n) = (a+2)\times(b+1)\times(c+1)\times\cdots\$, the number of divisors of \$3n\$ is \$D(3n) = (a+1)\times(b+2)\times(c+1)\times\cdots\$, and so on. ### Challenge Write a program or function that uses these properties to calculate \$n\$, given certain divisor inputs. ### Input A set of integers, let's call them \$w, x, y, z\$, with all of the following definitions: * all inputs are greater than 1 -- \$w, x, y, z > 1\$ * \$x\$ and \$z\$ are distinct -- \$x\ne z\$ * \$x\$ and \$z\$ are prime -- \$P(x)=x, D(x)=2, P(z)=z \text{ and } D(z)=2\$ * \$w\$ is the number of divisors of \$xn\$ -- \$D(xn)=w\$ * \$y\$ is the number of divisors of \$zn\$ -- \$D(zn)=y\$ For the problem given in the linked question, an input example could be \$(28, 2, 30, 3)\$. This translates to \$D(2n)=28\$ and \$D(3n)=30\$, with \$n=864\$. ### Output A single integer, \$n\$, that satisfies the above definitions and input restrictions. If multiple numbers fit the definitions, output the smallest. If no such integer is possible, output a [falsey](http://meta.codegolf.stackexchange.com/a/2194/42963) value. ### Examples: ``` (w, x, y, z) => output (28, 2, 30, 3) => 864 (4, 2, 4, 5) => 3 (12, 5, 12, 23) => 12 (14, 3, 20, 7) => 0 (or some other falsey value) (45, 13, 60, 11) => 1872 (45, 29, 60, 53) => 4176 ``` ### Rules: * Standard code-golf rules and [loophole restrictions](http://meta.codegolf.stackexchange.com/q/1061/42963) apply. * [Standard input/output rules](http://meta.codegolf.stackexchange.com/a/1326/42963) apply. * Input numbers can be in any order - please specify in your answer which order you're using. * Input numbers can be in any suitable format: space-separated, an array, separate function or command-line arguments, etc. - your choice. * Similarly, if output to STDOUT, surrounding whitespace, trailing newline, etc. are all optional. * *Input parsing and output formatting are not the interesting features of this challenge.* * In the interests of sane complexity and integer overflows, the challenge number \$n\$ will have restrictions such that \$1 < n < 100000\$ -- i.e., you don't need to worry about possible answers outside this range. ### Related * [Count the divisors of a number](https://codegolf.stackexchange.com/q/64944/42963) * [Give the smallest number that has N divisors](https://codegolf.stackexchange.com/q/11080/42963) * [Divisor sum from prime-power factorization](https://codegolf.stackexchange.com/q/53550/42963) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) ``` ×€ȷ5R¤ÆDL€€Z=Ḅi3 ``` This is a brute force solution that tries all possible values up to 100,000. [Try it online!](http://jelly.tryitonline.net/#code=w5figqzItzVSwqTDhkRM4oKs4oKsWj3huIRpMw&input=&args=Miwz+MjgsMzA) ### Non-competing version The latest version of Jelly has a bug fix that allows to golf down the above code to **15 bytes**. ``` ȷ5R×€³ÆDL€€=Ḅi3 ``` [Try it online!](http://jelly.tryitonline.net/#code=yLc1UsOX4oKswrPDhkRM4oKs4oKsPeG4hGkz&input=&args=Miwz+MjgsMzA&debug=on) ### How it works ``` ×€ȷ5R¤ÆDL€€Z=Ḅi3 Main link. Left input: x,z. Right input: w,y ¤ Combine the two atoms to the left into a niladic chain. ȷ5 Yield 100,000 (1e5). R Apply range. Yields [1, ..., 100,000]. x€ Multiply each r in the range by x and z. This yields [[x, ..., 100,000x], [z, ..., 100,000z]]. ÆD Compute the divisors of each resulting integer. L€€ Apply length to each list of divisors. This counts the divisors of each integer in the 2D array. Z Zip; group the divisors of kx and kz in pairs. = Compare each [divisors(kx), divisors(kz)] with [w, y]. This yields a pair of Booleans. Ḅ Convert each Boolean pair from binary to integer. i3 Find the first index of 3. Yields 0 for not found. ``` ]
[Question] [ ## Challenge Given two inputs, a positive ion and a negative ion, you must output the formula for the ionic compound which would be made from the two ions. This basically means balancing out the charges so they equal zero. Do not bother with formatting the formula with subscript numbers, but you must have brackets for the multi-atom ions (such as `NO3`). You do not have to account for any errors (for example, if someone inputs two negative ions, you can just let the program fail). **Note:** Take Fe to have a charge of 3+ ## Ions All of the ions which need to be accounted for are found along with their charges on the second part of the [AQA GCSE Chemistry Data Sheet](http://filestore.aqa.org.uk/subjects/AQA-CHEMISTRY-DATA-SHEET.PDF). ### Positive ions * H+ * Na+ * Ag+ * K+ * Li+ * NH4+ * Ba2+ * Ca2+ * Cu2+ * Mg2+ * Zn2+ * Pb2+ * Fe3+ * Al3+ ### Negative ions * Cl- * Br- * F- * I- * OH- * NO3- * O2- * S2- * SO42- * CO32- ## Examples Some examples: **H** and **O** returns:- `H2O` **Ca** and **CO3** returns:- `CaCO3` **Al** and **SO4** returns:- `Al2(SO4)3` Note the following case that you must account for: **H** and **OH** returns:- `H2O` *not* `H(OH)` [Answer] # [Lua](https://www.lua.org/pil/contents.html), ~~174~~ 242 bytes I forgot the brackets '-\_-, that got me up to 242. Oh well, it was a fun enough challenge at least. ``` i,c,a={Ba=2,Ca=2,Cu=2,Mg=2,Zn=2,Pb=2,Fe=3,Al=3,O=2,S=2,SO4=2,CO3=2},io.read(),io.read() p,d=i[c]~=i[a],{SO4=1,NO3=1,OH=1,CO3=1} k,m=p and i[c]or'',p and i[a]or'' a=k==m and a or (d[a]and'('..a..')'or a) print(c..a=='HOH'and'H2O'or c..m..a..k) ``` [Try it online!](https://tio.run/nexus/lua#RY0/C8IwEMX3fIpsaeEItHW9QQXJohHclA5nUyTU/iHoVOpXr5eAONyPe@/e41YPDRDOO8IS9glvxvHBuA6M851xaLGC7ZNhWV3i2E3M2grLBfyoQ0suy/@bmMChvzX1h0k1zLFQwIkLBVjDiN1iER30OEkanIzpMSgFP0lJCsIOsU8eyTHIzPGFlcqU1qS1yhW7xC@DH15ZwyaiMtaoGDKljWd2@5Tu8nU1wpov "Lua – TIO Nexus") Old version: ``` i,c,a={Ba=2,Ca=2,Cu=2,Mg=2,Zn=2,Pb=2,Fe=3,Al=3,O=2,S=2,SO4=2,CO3=2},io.read(),io.read() p=i[c]~=i[a] k,m=p and i[c]or'',p and i[a]or'' print(c..a=='HOH'and'H2O'or c..m..a..k) ``` Abusing Lua's tendency to initialize everything with a nil value we can cut down on storage costs. Still, Lua is still a bit clunky :( [Answer] # Java (~~619~~ ~~647~~ 667 bytes) [Fixed] Update: H + OH returns HOH even though I hard coded it not to.... working on it [Fixed] Update: Sometimes Parenthesis appear when they shouldn't **Code** ``` String f(String[]a){if(Arrays.equals(a,new String[]{"H","OH"})|Arrays.equals(a,new String[]{"OH","H"}))return "H2O";List<String>b=Arrays.asList(new String[]{"H","Na","Ag","K","Li","NH4","Ba","Ca","Cu","Mg","Zn","Pb","Fe","Al","Cl","Br","F","I","OH","NO3","O","S","SO4","CO3"});Integer[]c={1,1,1,1,1,1,2,2,2,2,2,2,3,3,1,1,1,1,1,1,2,2,2,2},d={5,18,19,22,23};List<Integer>j=Arrays.asList(d);int e=b.indexOf(a[0]),f=b.indexOf(a[1]),g=c[e],h=c[f],i;if(f<e){String p=a[0];a[0]=a[1];a[1]=p;i=g;g=h;h=i;i=e;e=f;f=i;}boolean k=j.contains(e),l=j.contains(f),m=g==h,n=g==1,o=h==1;return (k&!m&!o?"("+a[0]+")":a[0])+(m?"":h==1?"":h)+(l&!m&!n?"("+a[1]+")":a[1])+(m?"":g==1?"":g);} ``` I wasn't sure how to do this without hard coding every ions charge, so it ended up being long. Lucky cause all the charges are 1, 2, or 3 so finding the amount of each ion is easy. **Expanded** ``` import java.util.Arrays; import java.util.List; public class Compound { public static void main(String[]a){ //System.out.println(f(a)); String[] pos = new String[]{"H","Na","Ag","K","Li","NH4","Ba","Ca","Cu","Mg","Zn","Pb","Fe","Al"}; String[] neg = new String[]{"Cl","Br","F","I","OH","NO3","O","S","SO4","CO3"}; for(int i = 0; i < pos.length; i++){ for(int j = 0; j < neg.length; j++){ System.out.println(pos[i] + " + " + neg[j] + " = " + f(new String[]{pos[i],neg[j]})); System.out.println(neg[j] + " + " + pos[i] + " = " + f(new String[]{neg[j],pos[i]})); } } } static String f(String[]a){ if(Arrays.equals(a,new String[]{"H","OH"})|Arrays.equals(a,new String[]{"OH","H"})) return "H2O"; List<String>b=Arrays.asList(new String[]{"H","Na","Ag","K","Li","NH4","Ba","Ca","Cu","Mg","Zn","Pb","Fe","Al","Cl","Br","F","I","OH","NO3","O","S","SO4","CO3"}); Integer[]c={1,1,1,1,1,1,2,2,2,2,2,2,3,3,1,1,1,1,1,1,2,2,2,2},d={5,18,19,22,23}; List<Integer>j=Arrays.asList(d); int e=b.indexOf(a[0]),f=b.indexOf(a[1]),g=c[e],h=c[f],i; if(f<e){String p=a[0];a[0]=a[1];a[1]=p;i=g;g=h;h=i;i=e;e=f;f=i;} boolean k=j.contains(e),l=j.contains(f),m=g==h,n=g==1,o=h==1; return (k&!m&!o?"("+a[0]+")":a[0])+(m?"":o?"":h)+(l&!m&!n?"("+a[1]+")":a[1])+(m?"":n?"":g); } } ``` [Try it here](http://ideone.com/RgXFkV) **Data** Let me know if any of them are wrong ``` H + Cl = HCl Cl + H = HCl H + Br = HBr Br + H = HBr H + F = HF F + H = HF H + I = HI I + H = HI H + OH = H2O OH + H = H2O H + NO3 = HNO3 NO3 + H = HNO3 H + O = H2O O + H = H2O H + S = H2S S + H = H2S H + SO4 = H2SO4 SO4 + H = H2SO4 H + CO3 = H2CO3 CO3 + H = H2CO3 Na + Cl = NaCl Cl + Na = NaCl Na + Br = NaBr Br + Na = NaBr Na + F = NaF F + Na = NaF Na + I = NaI I + Na = NaI Na + OH = NaOH OH + Na = NaOH Na + NO3 = NaNO3 NO3 + Na = NaNO3 Na + O = Na2O O + Na = Na2O Na + S = Na2S S + Na = Na2S Na + SO4 = Na2SO4 SO4 + Na = Na2SO4 Na + CO3 = Na2CO3 CO3 + Na = Na2CO3 Ag + Cl = AgCl Cl + Ag = AgCl Ag + Br = AgBr Br + Ag = AgBr Ag + F = AgF F + Ag = AgF Ag + I = AgI I + Ag = AgI Ag + OH = AgOH OH + Ag = AgOH Ag + NO3 = AgNO3 NO3 + Ag = AgNO3 Ag + O = Ag2O O + Ag = Ag2O Ag + S = Ag2S S + Ag = Ag2S Ag + SO4 = Ag2SO4 SO4 + Ag = Ag2SO4 Ag + CO3 = Ag2CO3 CO3 + Ag = Ag2CO3 K + Cl = KCl Cl + K = KCl K + Br = KBr Br + K = KBr K + F = KF F + K = KF K + I = KI I + K = KI K + OH = KOH OH + K = KOH K + NO3 = KNO3 NO3 + K = KNO3 K + O = K2O O + K = K2O K + S = K2S S + K = K2S K + SO4 = K2SO4 SO4 + K = K2SO4 K + CO3 = K2CO3 CO3 + K = K2CO3 Li + Cl = LiCl Cl + Li = LiCl Li + Br = LiBr Br + Li = LiBr Li + F = LiF F + Li = LiF Li + I = LiI I + Li = LiI Li + OH = LiOH OH + Li = LiOH Li + NO3 = LiNO3 NO3 + Li = LiNO3 Li + O = Li2O O + Li = Li2O Li + S = Li2S S + Li = Li2S Li + SO4 = Li2SO4 SO4 + Li = Li2SO4 Li + CO3 = Li2CO3 CO3 + Li = Li2CO3 NH4 + Cl = NH4Cl Cl + NH4 = NH4Cl NH4 + Br = NH4Br Br + NH4 = NH4Br NH4 + F = NH4F F + NH4 = NH4F NH4 + I = NH4I I + NH4 = NH4I NH4 + OH = NH4OH OH + NH4 = NH4OH NH4 + NO3 = NH4NO3 NO3 + NH4 = NH4NO3 NH4 + O = (NH4)2O O + NH4 = (NH4)2O NH4 + S = (NH4)2S S + NH4 = (NH4)2S NH4 + SO4 = (NH4)2SO4 SO4 + NH4 = (NH4)2SO4 NH4 + CO3 = (NH4)2CO3 CO3 + NH4 = (NH4)2CO3 Ba + Cl = BaCl2 Cl + Ba = BaCl2 Ba + Br = BaBr2 Br + Ba = BaBr2 Ba + F = BaF2 F + Ba = BaF2 Ba + I = BaI2 I + Ba = BaI2 Ba + OH = Ba(OH)2 OH + Ba = Ba(OH)2 Ba + NO3 = Ba(NO3)2 NO3 + Ba = Ba(NO3)2 Ba + O = BaO O + Ba = BaO Ba + S = BaS S + Ba = BaS Ba + SO4 = BaSO4 SO4 + Ba = BaSO4 Ba + CO3 = BaCO3 CO3 + Ba = BaCO3 Ca + Cl = CaCl2 Cl + Ca = CaCl2 Ca + Br = CaBr2 Br + Ca = CaBr2 Ca + F = CaF2 F + Ca = CaF2 Ca + I = CaI2 I + Ca = CaI2 Ca + OH = Ca(OH)2 OH + Ca = Ca(OH)2 Ca + NO3 = Ca(NO3)2 NO3 + Ca = Ca(NO3)2 Ca + O = CaO O + Ca = CaO Ca + S = CaS S + Ca = CaS Ca + SO4 = CaSO4 SO4 + Ca = CaSO4 Ca + CO3 = CaCO3 CO3 + Ca = CaCO3 Cu + Cl = CuCl2 Cl + Cu = CuCl2 Cu + Br = CuBr2 Br + Cu = CuBr2 Cu + F = CuF2 F + Cu = CuF2 Cu + I = CuI2 I + Cu = CuI2 Cu + OH = Cu(OH)2 OH + Cu = Cu(OH)2 Cu + NO3 = Cu(NO3)2 NO3 + Cu = Cu(NO3)2 Cu + O = CuO O + Cu = CuO Cu + S = CuS S + Cu = CuS Cu + SO4 = CuSO4 SO4 + Cu = CuSO4 Cu + CO3 = CuCO3 CO3 + Cu = CuCO3 Mg + Cl = MgCl2 Cl + Mg = MgCl2 Mg + Br = MgBr2 Br + Mg = MgBr2 Mg + F = MgF2 F + Mg = MgF2 Mg + I = MgI2 I + Mg = MgI2 Mg + OH = Mg(OH)2 OH + Mg = Mg(OH)2 Mg + NO3 = Mg(NO3)2 NO3 + Mg = Mg(NO3)2 Mg + O = MgO O + Mg = MgO Mg + S = MgS S + Mg = MgS Mg + SO4 = MgSO4 SO4 + Mg = MgSO4 Mg + CO3 = MgCO3 CO3 + Mg = MgCO3 Zn + Cl = ZnCl2 Cl + Zn = ZnCl2 Zn + Br = ZnBr2 Br + Zn = ZnBr2 Zn + F = ZnF2 F + Zn = ZnF2 Zn + I = ZnI2 I + Zn = ZnI2 Zn + OH = Zn(OH)2 OH + Zn = Zn(OH)2 Zn + NO3 = Zn(NO3)2 NO3 + Zn = Zn(NO3)2 Zn + O = ZnO O + Zn = ZnO Zn + S = ZnS S + Zn = ZnS Zn + SO4 = ZnSO4 SO4 + Zn = ZnSO4 Zn + CO3 = ZnCO3 CO3 + Zn = ZnCO3 Pb + Cl = PbCl2 Cl + Pb = PbCl2 Pb + Br = PbBr2 Br + Pb = PbBr2 Pb + F = PbF2 F + Pb = PbF2 Pb + I = PbI2 I + Pb = PbI2 Pb + OH = Pb(OH)2 OH + Pb = Pb(OH)2 Pb + NO3 = Pb(NO3)2 NO3 + Pb = Pb(NO3)2 Pb + O = PbO O + Pb = PbO Pb + S = PbS S + Pb = PbS Pb + SO4 = PbSO4 SO4 + Pb = PbSO4 Pb + CO3 = PbCO3 CO3 + Pb = PbCO3 Fe + Cl = FeCl3 Cl + Fe = FeCl3 Fe + Br = FeBr3 Br + Fe = FeBr3 Fe + F = FeF3 F + Fe = FeF3 Fe + I = FeI3 I + Fe = FeI3 Fe + OH = Fe(OH)3 OH + Fe = Fe(OH)3 Fe + NO3 = Fe(NO3)3 NO3 + Fe = Fe(NO3)3 Fe + O = Fe2O3 O + Fe = Fe2O3 Fe + S = Fe2S3 S + Fe = Fe2S3 Fe + SO4 = Fe2(SO4)3 SO4 + Fe = Fe2(SO4)3 Fe + CO3 = Fe2(CO3)3 CO3 + Fe = Fe2(CO3)3 Al + Cl = AlCl3 Cl + Al = AlCl3 Al + Br = AlBr3 Br + Al = AlBr3 Al + F = AlF3 F + Al = AlF3 Al + I = AlI3 I + Al = AlI3 Al + OH = Al(OH)3 OH + Al = Al(OH)3 Al + NO3 = Al(NO3)3 NO3 + Al = Al(NO3)3 Al + O = Al2O3 O + Al = Al2O3 Al + S = Al2S3 S + Al = Al2S3 Al + SO4 = Al2(SO4)3 SO4 + Al = Al2(SO4)3 Al + CO3 = Al2(CO3)3 CO3 + Al = Al2(CO3)3 ``` **Note** I started in Pyth, but then I got annoyed with the order and the parenthesis, [here](https://pyth.herokuapp.com/?code=%3DG%5B%22H%22+%22Na%22+%22Ag%22+%22K%22+%22Li%22+%22NH4%22+%22Ba%22+%22Ca%22+%22Cu%22+%22Mg%22+%22Zn%22+%22Pb%22+%22Fe%22+%22Al%22+%22Cl%22+%22Br%22+%22F%22+%22I%22+%22OH%22+%22NO3%22+%22O%22+%22S%22+%22SO4%22+%22CO3%22+1+1+1+1+1+1+2+2+2+2+2+2+3+3+1+1+1+1+1+1+2+2+2+2)J%40G%2B24xG%40QZK%40G%2B24xG%40Q1%40QZ%3FkqJKK%40Q1%3FkqJKJ&input=%22Al%22%2C%22SO4%22&debug=1) is what I had if anyone wants to finish it. ``` =G["H" "Na" "Ag" "K" "Li" "NH4" "Ba" "Ca" "Cu" "Mg" "Zn" "Pb" "Fe" "Al" "Cl" "Br" "F" "I" "OH" "NO3" "O" "S" "SO4" "CO3" 1 1 1 1 1 1 2 2 2 2 2 2 3 3 1 1 1 1 1 1 2 2 2 2)J@G+24xG@QZK@G+24xG@Q1@QZ?kqJKK@Q1?kqJKJ ``` [Answer] # CJam, 176 bytes ``` "O S SO4 CO3 ""Cl Br F I OH NO3 """"H Na Ag K Li NH4 ""Ba Ca Cu Mg Zn Pb ""Fe Al "]_2{r\1$S+f#Wf=0#((z@}*_2$*_4=2*-_@/\@/@\]2/{~_({1$1>_el={'(@@')\}|0}&;}/]s"HOHH"1$#){;"H2O"}& ``` [Try it online](http://cjam.aditsu.net/#code=%22O%20S%20SO4%20CO3%20%22%22Cl%20Br%20F%20I%20OH%20NO3%20%22%22%22%22H%20Na%20Ag%20K%20Li%20NH4%20%22%22Ba%20Ca%20Cu%20Mg%20Zn%20Pb%20%22%22Fe%20Al%20%22%5D_2%7Br%5C1%24S%2Bf%23Wf%3D0%23((z%40%7D*_2%24*_4%3D2*-_%40%2F%5C%40%2F%40%5C%5D2%2F%7B~_(%7B1%241%3E_el%3D%7B'(%40%40')%5C%7D%7C0%7D%26%3B%7D%2F%5Ds%22HOHH%221%24%23)%7B%3B%22H2O%22%7D%26&input=Al%20SO4) This was somewhat painful, particularly with all the special cases for parentheses, showing counts, the H2O, etc. The data is not in a super compact format. It could be trimmed more, but the code needed to interpret it would probably compensate for the savings. So I went with an array of strings, where each string contains the atoms with the same charge, ordered from -2 to +3 (where the string for 0 is empty). Explanation: ``` [..] Data, as explained above. _ Duplicate data, will need it for both inputs. 2{ Loop over two inputs. r Get input. \ Swap data to top. 1$ Copy input to top (keep original for later). S+ Add a space to avoid ambiguity when searching in data. f# Search for name in all strings of data. Wf= Convert search results to truth values by comparing them to -1. 0# Find the 0 entry, which gives the index of the matching string. (( Subtract 2, to get charge in range [-2, 3] from index. z Absolute value, we don't really care about sign of charge. @ Swap second copy of data table to proper position for next input. }* End loop over two inputs. _2$* Multiply the two charges. _4= We need the LCM. But for the values here, only product 4 is not the LCM. 2*- So change it to 2. _@/ Divide LCM by first charge to get first count. \@/ Divide LCM by second charge to get second count. @\]2/ Make pairs of name/count for both ions... { ... and loop over the pairs. ~ Unpack the pair. _( Check if count is > 1. { Handle count > 1. 1$ Get copy of name to top of stack. 1> Slice off first character to check if rest contains upper case. _el Create lower case copy. = If they are different, there are upper case letters. { Handle case where parentheses are needed. '( Opening parentheses. @@ Some stack shuffling to get values in place. ') Closing parentheses. \ And one more swap to place count after parentheses. }| End parentheses handling. 0 Push dummy value to match stack layout of other branch. }& End count handling. ; Pop unused count off stack. }/ End loop over name/count pairs. ]s Pack stack content into single string, for H2O handling. "HOHH" String that contains both HOH and OHH, which need to be H2O. 1$#) Check if output is in that string. { If yes, replace with H2O. ; Drop old value. "H2O" And make it H2O instead. }& End of H2O handling. ``` [Answer] ## JavaScript (ES6), ~~316~~ 277 bytes ~~I've globalized the `p` and `n` variables (just like I did in CoffeeScript) for easier testing. Localizing the variables would not make a difference in character count.~~ ``` f=(x,y)=>{i='indexOf',d='~NH4KNaAgLiBa~CaCuMgZnPbFeAlSO4CO3ClBrFIOHNO3',k=d[i](x),l=d[i](y),a=k<28?x:y,b=k<28?y:x,r=Math.ceil(k/11)-1,s=b=='F'?0:l<32;if(r==s)r=s=0;a=s&&a=='NH4'?'(NH4)':a;b=r&&/[A-Z]{2}/.test(b)?`(${b})`:b;return'H'==a&&b=='OH'?'H2O':a+(s?s+1:'')+b+(r?r+1:'')} // Original attempt, 316 bytes p={H:1,Na:1,Ag:1,K:1,Li:1,NH4:1,Ba:2,Ca:2,Cu:2,Mg:2,Zn:2,Pb:2,Fe:3,Al:3},n={Cl:1,Br:1,F:1,I:1,OH:1,NO3:1,O:2,S:2,SO4:2,CO3:2},f=(x,y)=>{a=p[x]?x:y,b=p[x]?y:x,z=p[a]==2&&n[b]==2,r=+z||n[b],s=+z||p[a];a=--r&&a=='NH4'?'(NH4)':a;b=--s&&/[A-Z]{2}/.test(b)?`(${b})`:b;return'H'==a&&b=='OH'?'H2O':a+(r?r+1:'')+b+(s?s+1:'')} ``` ### ES5 variant, ~~323~~ 284 bytes Not much changes apart from getting rid of the arrow function and template string: ``` f=function(x,y){i='indexOf',d='~NH4KNaAgLiBa~CaCuMgZnPbFeAlSO4CO3ClBrFIOHNO3',k=d[i](x),l=d[i](y),a=k<28?x:y,b=k<28?y:x,r=Math.ceil(k/11)-1,s=b=='F'?0:l<32;if(r==s)r=s=0;a=s&&a=='NH4'?'(NH4)':a;b=r&&/[A-Z]{2}/.test(b)?'('+b+')':b;return'H'==a&&b=='OH'?'H2O':a+(s?s+1:'')+b+(r?r+1:'')} // Original attempt, 323 bytes p={H:1,Na:1,Ag:1,K:1,Li:1,NH4:1,Ba:2,Ca:2,Cu:2,Mg:2,Zn:2,Pb:2,Fe:3,Al:3},n={Cl:1,Br:1,F:1,I:1,OH:1,NO3:1,O:2,S:2,SO4:2,CO3:2},f=function(x,y){a=p[x]?x:y,b=p[x]?y:x,z=p[a]==2&&n[b]==2,r=+z||n[b],s=+z||p[a];a=--r&&a=='NH4'?'(NH4)':a;b=--s&&/[A-Z]{2}/.test(b)?'('+b+')':b;return'H'==a&&b=='OH'?'H2O':a+(r?r+1:'')+b+(s?s+1:'')} ``` ``` f=function(x,y){i='indexOf',d='~NH4KNaAgLiBa~CaCuMgZnPbFeAlSO4CO3ClBrFIOHNO3',k=d[i](x),l=d[i](y),a=k<28?x:y,b=k<28?y:x,r=Math.ceil(k/11)-1,s=b=='F'?0:l<32;if(r==s)r=s=0;a=s&&a=='NH4'?'(NH4)':a;b=r&&/[A-Z]{2}/.test(b)?'('+b+')':b;return'H'==a&&b =='OH'?'H2O':a+(s?s+1:'')+b+(r?r+1:'')} ;['H', 'Na', 'Ag', 'K', 'Li', 'NH4', 'Ba', 'Ca', 'Cu', 'Mg', 'Zn', 'Pb', 'Fe', 'Al'].forEach(function (q) { ['Cl', 'Br', 'F', 'I', 'OH', 'NO3', 'O', 'S', 'SO4', 'CO3'].forEach(function (w) { document.body.innerHTML += '<p>' + q + ' + ' + w + ' = ' + f(q, w); }); }); ``` [Answer] ## CoffeeScript, ~~371~~ 333 bytes This count includes newlines (some newlines can be replaced with semicolons but that wouldn't affect character count) ``` f=(x,y)->(i='indexOf';d='~NH4KNaAgLiBa~CaCuMgZnPbFeAlSO4CO3ClBrFIOHNO3';k=d[i] x;r=-1+Math.ceil k/11;l=d[i] y;a=if k<28then x else y b=if k<28then y else x s=if b=='F'then 0else 32>l r=s=0if r==s;a='(NH4)'if'NH4'==a&&s;b='('+b+')'if/[A-Z]{2}/.test(b)&&r;if'H'==a&&b=='OH'then'H2O'else a+(if!s then''else 1+s)+b+(if!r then''else 1+r)) ``` --- ``` # Original attempt, 371 bytes p={H:1,Na:1,Ag:1,K:1,Li:1,NH4:1,Ba:2,Ca:2,Cu:2,Mg:2,Zn:2,Pb:2,Fe:3,Al:3} n={Cl:1,Br:1,F:1,I:1,OH:1,NO3:1,O:2,S:2,SO4:2,CO3:2} f=(x,y)->(a=if p[x]then x else y b=if p[x]then y else x z=p[a]==n[b]==2;r=+z||n[b];s=+z||p[a];if--r&&a=='NH4'then a='(NH4)' if--s&&/[A-Z]{2}/.test(b)then b='('+b+')' if'H'==a&&b=='OH'then'H2O'else a+(if!r then''else r+1)+b+(if!s then''else s+1)) ``` [Answer] ## CJam (137 bytes) ``` {{"SO4CO3ClBrFINO3OHNaAgKLiNH4BaCaCuMgZnPbFeAl":I\#~}$_s"HOH"="HO"1/@?_{I\#G-_0<B*-B/_W>+z}%_~1$=\1?f/W%[.{:T1>{_{'a<},,1>{'(\')}*T}*}]s} ``` This is an anonymous block (function) which takes two ions as strings wrapped in a list, and returns a string. [Online demo](http://cjam.aditsu.net/#code=e%23%20Test%20cases%0A%22H%20OH%0A%20Ca%20CO3%0A%20CO3%20Ca%0A%20Al%20SO4%0A%20F%20Fe%22N%25%7BS%25_p%0A%0A%7B%7B%22SO4CO3ClBrFINO3OHNaAgKLiNH4BaCaCuMgZnPbFeAl%22%3AI%5C%23~%7D%24_s%22HOH%22%3D%22HO%221%2F%40%3F_%7BI%5C%23G-_0%3CB*-B%2F_W%3E%2Bz%7D%25_~1%24%3D%5C1%3Ff%2FW%25%5B.%7B%3AT1%3E%7B_%7B'a%3C%7D%2C%2C1%3E%7B'(%5C')%7D*T%7D*%7D%5Ds%7D%0A%0A~pNo%7D%2F). ### Dissection ``` { e# Begin a block { e# Sort the input list "SO4...Al" e# Ions in ascending order of charge :I e# Stored as I for future reuse \#~ e# Index and bit-invert to sort descending }$ _s"HOH"="HO"1/@? e# Special case for water: replace ["H" "OH"] with ["H" "O"] _{I\#G-_0<B*-B/_W>+z}% e# Copy the list and hash index in I to find the charges _~1$=\1?f/ e# Replace [2 2] by [1 1] W% e# Reverse the charges [ e# Gather in an array .{ e# Pairwise for each ion and its opponent's reduced charge... :T1>{ e# If the charge (copied to T) is greater than 1 _{'a<},, e# Count the characters in the ion which are before 'a' 1>{'(\')}* e# If there's more than one, add some parentheses T e# Append T }* } ] s e# Flatten the list to a single string } ``` [Answer] # [Python 3](https://docs.python.org/3/), 364 bytes Stores the ions by the absolute value of their charges as `index+1` in a 2-D array (0-index elements have +- 1 charge, etc.). Uses string.split() to save a few characters there. Handles the special case of `H + OH = H2O` first, then it calculates how many ions are needed of each sort as the LCM of their two charges divided by its charge. Then adds in parentheses if needed as well as the actual number of ions. ``` from math import* o=["NH4 NO3 H Na Ag K Li OH I F Br Cl".split(),"CO3 SO4 Ba Ca Cu Mg Zn Pb S O".split(),["Fe","Al"]] p=["H","OH"] def c(i): for h,k in enumerate(o): if i in k:return-~h def b(x,y): if x in p and y in p:return"H20" i,j=c(x),c(y);g=gcd(i,j);i//=g;j//=g;return((x,"(%s)"%x)[x[-1]in"34"]+str(j),x)[j==1]+((y,"(%s)"%y)[y[-1]in"34"]+str(i),y)[i==1] ``` [Try it online!](https://tio.run/##XZDBauMwFEXX1VdcNBSkVm2TODOLBC9SQ3GZaTzQXYUWjuM4ShPbyArYm/n1zFPSTmFACOnovPfEbQe/berodNq45oBD7rewh7Zx/oY1sebLdIplFiHFMseiwk/8sshSPOMJjw7Jnt937d56IRVPyHvNpnjMkdA64qXCW43fK7wi@/I0fyq54os9N4a1NCOlW5Zyw9blBoWwcsawaRy26h22RlkfD6XLfSma8AK7gQ38feZKf3T13Z/tuXIlejUEg4Q@CC3yeo3hfPxweToZcTLULi5EL1UhBjmv4qpYC2Jybh8e4mq@O@@XCkFdubjuJL/upe713djYmkdTbm4778ROKsK7OB6bWyGGT3WQevhftZK@p21QT77sfJF3ZYcYGt8Q/fjOrkRIAjzjUhFKJ1lASR4YRXuhSU7HwCk@4hT3hS/2E0EXGX21ST/7jJhhLAQapoY0/k2fsavW2dqLlQhMj4w6P@qxkfL0Fw "Python 3 – Try It Online") ]
[Question] [ # Programmer's Garden Being a professional software developer, you cannot risk exposing yourself to the harsh non-artificial light of the sun, but you also have a soft spot for flowers, and want to keep your garden in good shape all year round. To this end, a gardener is hired each month to tidy up the flowerbed at the foot of your house. However you need to make sure the gardener is doing his job properly, and work out a suitable payment for the hard working fellow. Naturally a software solution is best. ### Input Your program will be fed input describing the flowerbed as it appears current, and details of items that need to be removed. The program must output the garden devoid of the clutter, and print out a breakdown of the gardeners pay. The input can be either be from STDIN, or as a single command line argument. The first line of input is of the format ``` width height unwanted_item_type_count ``` where `width` is the width of the flowerbed, `height` is the height of the flowerbed (both in ASCII characters), and `unwanted_item_type_count` tells you how many lines will following containing a description of a type of item to be removed from the garden. Each line for each unwanted type of item is of the format ``` width height string_representation name fee_per_item ``` where `width` is the width of the item, `height` is the height of the item (both in ASCII characters), `string_representation` is the string representation of the item without line breaks, `name` is an identifier for the type of item (spaces will be replaced with underscores), and `fee_per_item` is how much the gardener must be paid for the removal of each type of item. For example ``` 3 2 .R.\|/ rouge_flower 3 ``` Represents an item type of name `rouge_flower`, which costs 3 to remove, and looks like this: ``` .R. \|/ ``` The items will not contain spaces, and no item may have a border consisting entirely of dots, and the string representation will also be the exact size described. Thusly, all of the following are invalid inputs: ``` 3 1 ( ) space 0 1 1 . dot 0 2 1 .! bang 0 3 2 .@.\|/. plant 0 ``` Note that 0 is however a valid fee (fees will always be integers greater than -1). Note also that the flowerbed is predominately made up of dots (`.`) rather than spaces, and you can safely use whitespace as delimitation for all the inputs. The flowerbed is always bounded by dots itself. After the unwanted item types are listed, then comes the ASCII representation of the flowerbed of given width and height. ### Output Output should be to STDOUT, or suitable alternative if your language doesn't support it. The output starts with a print-out of the flowerbed, but with all unwanted items removed (replaced with dots), so you can see how it should appear and check the gardener has done his job. Each item in the flowerbed will be surrounded by a rectangle of dots, and will be one-contiguous item (i.e. there will be no separating dots *inside* the item). For example ``` ..... .#.#. ..... ``` shows 2 separate items ``` ..... .\@/. ..... ``` shows 1 item ``` ...... .#.... ....|. ....|. .o--/. ...... ``` is invalid, as while the stone (#) can be matched, the snake (you couldn't tell it was a snake?) cannot because the stone interferes with the required surrounding of dots. ``` ... \@. ... ``` This is also invalid, as the snail is on the edge of the flowerbed, and the edge must always be bounded by dots in a valid input. After this, there should be a listing of each type of unwanted item, giving the count, the cost per item, and costs for all the items (count \* cost per item), in the format: ``` <count> <name> at <cost_per_item> costs <cost> ``` After this, there should be a single line yielding the total cost (the sum of the costs for unwanted items): ``` total cost <total_cost> ``` ### Example For this given input ``` 25 18 3 4 2 .\/.\\// weeds 5 2 1 \@ snails 2 1 1 # stones 1 ......................... .\@/.................\@.. ............\/........... ......O....\\//..^|^..... .#...\|/.........^|^..... ..................|...... .................\|/..... ..\@.....\/...........#.. ........\\//....#........ ....*.................... ...\|/......\/......\@/.. ...........\\//.......... ..................*...... .......\@/.......\|/..... ...O..................... ..\|/.......*............ .......#...\|/....\@..... ......................... ``` The program should produce this output ``` ......................... .\@/..................... ......................... ......O..........^|^..... .....\|/.........^|^..... ..................|...... .................\|/..... ......................... ......................... ....*.................... ...\|/..............\@/.. ......................... ..................*...... .......\@/.......\|/..... ...O..................... ..\|/.......*............ ...........\|/........... ......................... 3 weeds at 5 costs 15 3 snails at 2 costs 6 4 stones at 1 costs 4 total cost 25 ``` The output *must* be terminated by a line-break. This is code-golf, may the shortest code win. ### Additional test case *Edit: this used to contain Unicode, which isn't allowed in the flowerbed, far too modern. This has been rectified, sorry about that.* ``` 25 15 5 5 3 ..@..\\|//.\|/. overgrown_plants 3 5 3 @-o....|...\|/. semi-articulated_plant 4 3 2 .|.\@/ mutant_plants 5 1 1 $ dollars 0 1 1 # stones 1 ......................... ........@................ ....$..\|/...........@... ............|.......\|/.. ...#.......\@/........... ......................... ......................... ......@.......@......@... .....\|/....\\|//...\|/.. .............\|/......... .#....................#.. .........$.......|....... ...\/.......\/..\@/..\/.. ..\\//.....\\//.....\\//. ......................... ``` Expected Output: ``` ......................... ........@................ .......\|/...........@... ....................\|/.. ......................... ......................... ......................... ......@..............@... .....\|/............\|/.. ......................... ......................... ......................... ...\/.......\/.......\/.. ..\\//.....\\//.....\\//. ......................... 1 overgrown_plants at 3 costs 3 0 semi-articulated_plants at 4 costs 0 2 mutant_plants at 5 costs 10 2 dollars at 0 costs 0 3 stones at 1 costs 3 total cost 16 ``` [Answer] ## Perl - 636 There is definitely some more golfing that can be done. And probably better ways to do it too. ``` <>;while(<>){if(/ /){chomp;push@v,$_}else{$t.=$_}}for(@v){r(split/ /)}say$t.$y."total cost $u";sub r{my($e,$w,$c,$h,$z)=@_;($i,$f,$q,$d)=(1,0,0,"."x$e);@m=($c=~/($d)/g);@l=split/\n/,$t;while($i>0){($g,$j)=(1,0);for(0..$#l){if($j==0&&$l[$_]=~/^(.*?)\.\Q$m[$j]\E\./){$j++;$l="."x length$1}elsif($j<@m&&$l[$_]=~/^$l\.\Q$m[$j]\E\./){$j++}elsif($j>0){$l[$_-1]=~s!.\Q$m[$j-1]\E.!" ".$m[$j-1]=~s/\./ /gr." "!e;($j,$g)=(0,0)}if($j==@m){$k=$j;for($f=$_;$f>$_-$j;$f--){$k--;$o="."x length$m[$k];$l[$f]=~s/^($l)\.\Q$m[$k]\E\./$1.$o./}($g,$j)=(0,0);$q++}}if($g){$i--}}$t=join("\n",@l)."\n";$t=~s/ /./g;$p=$z*$q;$u+=$p;$y.="$q $h at $z costs $p\n"} ``` 635 characters + 1 for `-C` flag to handle the euros. If you have the input stored in `input.txt` you can run it with: ``` cat input.txt | perl -C -E'<>;while(<>){if(/ /){chomp;push@v,$_}else{$t.=$_}}for(@v){r(split/ /)}say$t.$y."total cost $u";sub r{my($e,$w,$c,$h,$z)=@_;($i,$f,$q,$d)=(1,0,0,"."x$e);@m=($c=~/($d)/g);@l=split/\n/,$t;while($i>0){($g,$j)=(1,0);for(0..$#l){if($j==0&&$l[$_]=~/^(.*?)\.\Q$m[$j]\E\./){$j++;$l="."x length$1}elsif($j<@m&&$l[$_]=~/^$l\.\Q$m[$j]\E\./){$j++}elsif($j>0){$l[$_-1]=~s!\Q$m[$j-1]\E!$m[$j-1]=~s/\./ /gr!e;($j,$g)=(0,0)}if($j==@m){$k=$j;for($f=$_;$f>$_-$j;$f--){$k--;$o="."x length$m[$k];$l[$f]=~s/^($l)\.\Q$m[$k]\E\./$1.$o./}($g,$j)=(0,0);$q++}}if($g){$i--}}$t=join("\n",@l)."\n";$t=~s/ /./g;$p=$z*$q;$u+=$p;$y.="$q $h at $z costs $p\n"}' ``` Here is the deparsed version. I went through and added some comments to help explain things. Maybe I'll go make the variable names more readable sometime. There may be some edge cases this doesn't work with but it works with the examples at least. ``` BEGIN { # These are the features we get with -C and -E flags $^H{'feature_unicode'} = q(1); # -C gives us unicode $^H{'feature_say'} = q(1); # -E gives us say to save 1 character from print $^H{'feature_state'} = q(1); $^H{'feature_switch'} = q(1); } <ARGV>; # throw away the first line while (defined($_ = <ARGV>)) { # read the rest line by line if (/ /) { # if we found a space (the garden doesn't have spaces in it) chomp $_; # remove the newline push @v, $_; # add to our array } else { # else, we construct the garden $t .= $_; } } foreach $_ (@v) { # call the subroutine r by splitting our input lines into arguments r(split(/ /, $_, 0)); # the arguments would be like r(3,2,".R.\|/","rouge_flower",3) } say $t . $y . "total cost $u"; # print the cost at the end # this subroutine removes weeds from the garden and counts them sub r { BEGIN { $^H{'feature_unicode'} = q(1); $^H{'feature_say'} = q(1); $^H{'feature_state'} = q(1); $^H{'feature_switch'} = q(1); } my($e, $w, $c, $h, $z) = @_; # get our arguments ($i, $f, $q, $d) = (1, 0, 0, '.' x $e); # initialize some variables @m = $c =~ /($d)/g; # split a string like this .R.\|/ into .R. and \|/ @l = split(?\n?, $t, 0); # split the garden into lines to process line by line while ($i > 0) { ($g, $j) = (1, 0); foreach $_ (0 .. $#l) { # go through the garden if ($j == 0 and $l[$_] =~ /^(.*?)\.\Q$m[$j]\E\./) { # this matches the top part of the weed. \Q and \E make it so the weed isn't intepreted as a regex. Capture the number of dots in front of it so we know where it is ++$j; $l = '.' x length($1); # this is how many dots we have } elsif ($j < @m and $l[$_] =~ /^$l\.\Q$m[$j]\E\./) { # capture the next line ++$j; } elsif ($j > 0) { # if we didn't match we have to reset $l[$_ - 1] =~ s[.\Q$m[$j - 1]\E.][' ' . $m[$j - 1] =~ s/\./ /rg . ' ';]e; # this line replaces the dots next to the weed and in the weed with spaces # to mark it since it didn't work but the top part matches # that way when we repeat we go to the next weed ($j, $g) = (0, 0); } if ($j == @m) { # the whole weed has been matched $k = $j; for ($f = $_; $f > $_ - $j; --$f) { # remove the weed backwards line by line --$k; $o = '.' x length($m[$k]); $l[$f] =~ s/^($l)\.\Q$m[$k]\E\./$1.$o./; } ($g, $j) = (0, 0); ++$q; } } if ($g) { --$i; # all the weeds of this type are gone } } $t = join("\n", @l) . "\n"; # join the garden lines back together $t =~ s/ /./g; # changes spaces to dots $p = $z * $q; # calculate cost $u += $p; # add to sum $y .= "$q $h at $z costs $p\n"; #get message } ``` **Feel free to suggest improvements!** [Answer] # Python 3, 459 bytes ``` from re import* E=input() W,H,C=map(int,E[0].split()) B,T,O='\n'.join(E[~H:]),0,'' for L in E[1:~H]: w,h,s,n,c=L.split();w,h,c=map(int,(w,h,c));r,t='.'*(w+2),0;a=[r]+['.%s.'%s[i:i+w]for i in range(0,w*h,w)]+[r] for L in['(%s)'%'\\n'.join('.{%d})%s(.*'%(i,escape(b))for b in a)for i in range(W)]:t+=len(findall(L,B));B=sub(L,r.join('\\%d'%b for b in range(1,h+4)),B,MULTILINE) O+='%d %s at %d costs %d\n'%(t,n,c,t*c);T+=t*c print(B+O+'total cost',T) ``` Assumes the input will be given as a list of strings. ]
[Question] [ **Scenario** I am using pattern matching lockscreen and I sadly forgot my pattern. I would like to know how much time I will need to unlock it. Here are the specifications of Google's lock screen, that we will use for this challenge. * Every 5 wrong code, the user has to wait `30 seconds` before any further entry. * A pattern must, at least, consist in `4 points` (see below) * A point can be only used once, but you can go over it several times (see image right below): ![wierd](https://i.stack.imgur.com/OR5Da.png) Here, the center point is only used once, even if we go over it again for this particular pattern. **Hypothesis & Facts** We'll assume we're superheroes and that we can draw any pattern in `1 second`, we never need to eat or sleep. Yeah, we're superhumans. I'm a very unlucky person. "Worst case scenario" is my daily life so the pattern I will attempt **last** will be the right one. **What do we have to pwn?** For those who don't know it, Android (and other phones now) offers the ability of unlocking the phone through drawing a pattern on a 9-point matrix. This matrix can be described as follow : ``` C(A) M(B) C(C) M(D) X(E) M(F) C(G) M(H) C(I) ``` * C standing for "corner point" * M for "middle point" * X for "center point" * I have given identifiers to the points to make it easier The permitted **direct** connections are as follows : **Corner point :** ![Corner](https://i.stack.imgur.com/tibRO.png) **Middle point :** ![Middle](https://i.stack.imgur.com/c2LCn.png) **Center point :** ![Center](https://i.stack.imgur.com/IgDVk.png) However, as pointed out by steveverrill, "once the centre has been used (and therefore becomes unavailable) a direct connection between the bottom left and top right corner becomes unambiguous and therefore possible". Same goes for every "middle point", if e.g. the point B has already been counted, then a direct connection between A and C is possible. If e.g. F has already been counted, then a direct connection between C and I is possible. Etc... **Rules** * The point of this challenge is to return how much time (in human readable form, aka year/day/month/hour/whatever the time you find) I will need to unlock this damn phone. * You can't hardcode the number of possible valid patterns (don't even Google it, you fool), calculate it (that's actually the fun part, isn't it ?) * Shortest piece of code wins * Good luck ! [Answer] # [Rebmu](http://hostilefork.com/rebmu/): ~~197 175 168~~ 167 characters Generates combinations as a series of numbers (ex. 12369 is top-left to top-right to bottom-right), checks if combination is valid, and increments a counter if it is. This might take a **while\*** to run. Returns the number of seconds needed to unlock the phone. ``` B[[2 13][4 17][6 39][8 79][5 19][5 28][5 37][5 46][a 0]]Fdz[Q1feCb[st[a]paStsC/1 Qa^Qa^e?NNfiAtsC/2 e?NNfiArvTSc/2]]rpJ987653088[StsADj1233iA^e?SuqSf[++K]]adKmp30dvK 5 ``` Unmushed and commented: ``` ; for each subarray c: ; the sequences c/2 and c/3 are invalid before the point c/1 is pressed ; a 0 - a is never in the sequence, therefore 0 is always invalid b: [[2 13] [4 17] [6 39] [8 79] [5 19] [5 28] [5 37] [5 46] [a 0]] ; checks (most) conditions of validity f: dz[ ; set q to 1 q: 1 ; foreach array in b as c fe c b [ ; set a to be portion of s before c/1 st [a] pa s ts c/1 ; q = q and (a does not contain c/2) and (a does not contain reverse of c/2) q: a^ q a^ e? nn fi a ts c/2 e? nn fi a ts rv c/2 ] ] ; repeat 98765308 times, with j = 1 to 98765308 ; 987653088 = 987654321 (largest valid combination) - 1234 (smallest valid combination) + 1 rp j 987653088 [ ; set s to j+1233 (smallest valid combination - 1) as a string s: ts ad j 1233 ; if f returns trues and s does not contain duplicates, increment k i a^ e? s uq s f [++ k] ] ; print k (number of combinations) + 30 * (k/5) -> number of seconds needed ad k mp 30 dv k 5 ``` The program loops from 1 to (987654321-1233), checking 1233+loop counter (therefore checking 1234 to 987654321). If the number `987653088` is replaced with, `9876-1233` or `8643`, then the program will find the time taken for all 4-point combinations. Output for `9876-1233=8643` (4-point combinations): ``` >> rebmu %combinations.rebmu == 11344 ``` Output for `98765-1233=97532` (4 and 5-point combinations): ``` >> rebmu %combinations.rebmu == 61426 ``` Output for `987654-1233=986421` (4,5,6-point combinations): ``` >> rebmu %combinations.rebmu == 243532 ``` --- \*4/5-point took me about 8 seconds to run; 4-6 took about 77 seconds. It might take ~24 hours or longer depending on who runs this to calculate number of combinations for 4-9 point combinations. ]
[Question] [ Inspired by [this question](https://gamedev.stackexchange.com/questions/3488/saves-in-exe-file). Create a program that prompts the user to store some data, and when the program is quitting, spit out the program itself, except the session data changed. The user then open the newly generated program, and can recall the data from the previous program. Commands * `KEY VALUE`: sets session variable `KEY` to `VALUE` * `*`: clear all data * `! KEY`: delete `KEY` * `? KEY`: query `KEY` (if not exist: print nothing and move on) * otherwise, quit the program Neither key or value cannot contain any spaces. The newly generated program's filename must identify the version of the program, you can use dates or counters. Example interaction: ``` name test store name = test data is now { name: test } 0 1 data is now { name: test, 0: 1 } ? name output: test ! 0 delete 0 data is now { name: test } hello good world data is now { name: test, hello: good } the extra word "world" is ignored egiwiwegiuwe the "otherwise" case: quit program ``` The user opens the newly generated program ``` ? name output: test name retest data is now { name: retest } * clear data is now { } ``` Sample implementation: <https://gist.github.com/1128876> Rules * You do not need to preserve comments or insignificant whitespaces in the quined program: just preserve the functionality and the data * You cannot use any external storage. * No cheating quines, like any other quine problems. * Shortest code wins. [Answer] ## Ruby 1.9, 159 156 This program generates files named "1", "2", "3" and so on. ``` b={} I=1 eval T="loop{c,d=gets.split c==?*?b={}:d ?c==?!?b.delete(d):c==???puts(b[d]):b[c]=d :break} open(I.to_s,?w){|f|f<<'b=%p I=%d eval T=%p'%[b,I+1,T]}" ``` [Answer] ## D (419 chars) ``` enum c=q{string[string] m;import std.stdio;import std.array;void main(){foreach(string s;lines(stdin)){auto a=s.split;if(!a.length)goto e;switch(a[0]){case "*":m.clear;break;case "!":m.remove(a[1]);break;case "?":writeln(m.get(a[1],""));break;default:if(a.length<2){goto e;}m[a[0]]=a[1];}stdout.flush;}e:write("static this(){");foreach(i,v;m)writef("m[`%s`]=`%s`;",i,v);write("}enum c=q{",c,"};mixin(c);");}};mixin(c); ``` formatted: ``` enum c=q{ string[string] m; import std.stdio; import std.array; void main(){ foreach(string s;lines(stdin)){ auto a=s.split; if(!a.length)goto e; switch(a[0]){ case "*":m.clear;break; case "!":m.remove(a[1]);break; case "?":writeln(m.get(a[1],""));break; default:if(a.length<2){goto e;}m[a[0]]=a[1]; } stdout.flush; } e:write("static this(){"); foreach(i,v;m)writef("m[`%s`]=`%s`;",i,v); write("}enum c=q{",c,"};mixin(c);"); } };mixin(c); ``` variant of my [D quine](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/2987#2987) the `*` command relies on `m.clear;` to work correctly which it doesn't in dmd 2.52 (bug in the compiler) the need for `stdout.flush;` depends whether auto flush is enabled (it isn't on my machine) [Answer] ## JavaScript, 245 ``` (function(o,N){while(a=prompt()){a=a.split(' ') b=a[0] c=a[1] if(b=='*')o={} else if(b=='?'){if(o[c]!=N)alert(o[c])} else if(b=='!')delete o[a[1]] else if(c!=N)o[b]=c else break}alert('('+arguments.callee+')('+JSON.stringify(o)+')')}({})) ``` ]
[Question] [ ## Overview Shue (Simplified Thue) is a language that was designed by AnttiP for [this challenge](https://codegolf.stackexchange.com/q/242897/107299). A Shue program consists of the possible outputs and a list of string replacements. For example, the following program prints "yes" if an unary string is even: ``` yes no 11=2 12=1 22=2 1=no 2=yes ``` [Try it online!](https://tio.run/##lVWxbtswEN35FYQmsnbVytkECJ2SqUA6FF1staCps01AIgWSSmok/nb3SFmOrMRBqsW6u8fHu8dHud37ndE3R9W0xnpqYU7d3hELGS0wSqVpWlUDs@uEseXvonxerQr@ibNiHH1LOCEVbGinwUnRAlM8JxQfCx6J1kkSIyxi9DW@b4ylkipNVY8Mj9pEiNAVloqwbrVKXsonwtmpcJEfU8e4fk1WXOEq/p9KX2tLf4xrslooB/SXqDu4tdZYtkl@COvAUghhTrfGU7kTVkiPySd5oGIT3lAFfsl9Tbe@kWwEdvDmCHsPji1l2fNOu/1Qp7f337/c3t9Ne8QNOqvDD@nd0oaVZ6sgtlFaeGMddurAs9OyrobLTK10zKjUtbXyLMrOz66qg6si5qXvJto5Sxvh5Y7VfGy5Jt1a07Xshk8ECRs/F/SJnW09QDPO5/RV9oYvs7zk/PCOyqMpA/VbzIexWiP8vO@o1w7@guw8MDmnYwEHEI7bqyv7UTutHgBjzD@pfoPGVBj9tB3E8HGH9zwkR6JFxJ3AIc45DY9/RmQvhzKo74L6A@JydtQ6VmOj@WlA99HVoSzm6wCII15WB4SJdaG3wGrQzPFZxl8jh26WJjezgBO8DBdHvA2dDh5Ozi1zU87WM@Q4MeTl4erqidiTIxlzk2vXzJqtFc1wz7RBh7S1kNCA9o4KC7Q1zqk1niIaFj2CN6Cia9iJB2U6y8M3mkhT4Yb4PU6Oe7SSNiTLigXJFkVGFovwVmBuUWDxiCD08@esJETpNhz23qXOV0qnFkTFeAo68KEB8A8jWO5sSsyiL3XLSWuV9gzLaQU9mB8zfP4B "Python 3 – Try It Online") The possible outputs here are listed as "yes" and "no". Then comes the list of replacements. Here, "11" is replaced with "2", "22" with "2", "12" with "1", "1" with "no", and "2" with "yes". All replacements are done non-deterministically. Once the program reaches a state where one of the replacements is the output, it terminates and prints the output. ## Exact definition of Shue ###### Copied from the original post The source code is interpreted as a list of bytes. The only characters with special meaning are the newline, the equals sign and the backslash. `\n` corresponds to a literal newline, `\=` to a literal equals sign and `\\` to a literal backslash. Any other use of `\` is an error. Every line must contain 0 or 1 unescaped equals signs. Or in other words, to be syntactically valid, the program has to match the following regex: `/([^\n=\\]|\\=|\\n|\\\\)*(=([^\n=\\]|\\=|\\n|\\\\)*)?(\n([^\n=\\]|\\=|\\n|\\\\)*(=([^\n=\\]|\\=|\\n|\\\\)*)?)*/` Here is the mathematical definition of a Shue program: A Shue program is a set of terminator strings \$T\_e\$, and a set of transformation rules \$T\_r\$, which are pairs of strings. The execution of a Shue program on a input string \$i\$ is defined as follows. Let \$U\$ be the minimal set, so that \$i\in U\$ and \$\forall a,x,y,b: axb \in U \land (x,y) \in T\_r \rightarrow ayb \in U\$. Let \$S=U\cap T\_e\$. If \$S=\{x\}\$, then the program will terminate, and \$x\$ will be printed to stdout. If \$S=\emptyset\$ and \$|U|=\aleph\_0\$, then the program will enter an infinite loop. In all other cases, the behavior is undefined (yes, Shue isn't memory safe). However, since most esolangs cannot process byte arrays, you may take a string or a list of lines as input. See the linked original challenge for a better definition and more examples. ## Reference Implementation Here is the Python reference implementation: ``` import re, sys re1 = re.compile(rb"(([^=]|\\=)*)(=([^=]|\\=)*)?") def unescape(i): ret = b"" esc = 0 for c in i: if esc and c == b"\\": ret+= b"\\" esc = 0 elif esc and c == b"=": ret+= b"=" esc = 0 elif esc and c == b"n": ret+= b"\n" esc = 0 elif esc: raise ValueError(f"Parser error: got character {c} after \\") elif c == b"\\": esc = 1 else: ret+= bytes([c]) if esc: raise ValueError(f"Parser error: got EOL/EOF after \\") return ret def parse(i): terminators = set() rules = set() lines = i.split(b"\n") for l in lines: m = re1.match(l) if m.group(3): rules|= {(unescape(m.group(1)), unescape(m.group(3)[1:]))} else: terminators|= {unescape(m.group(1))} return terminators, rules def execute(c, i): terms, rules = parse(c) universe = {i} mod = True while mod: mod = False new_universe = set() for s in universe: if s in terms:return s for s in universe: for a,b in rules: for o in range(len(s)+1): if s[o:o+len(a)] == a: new_universe|= {s[:o]+b+s[o+len(a):]} mod = True universe = new_universe raise ValueError(f"Program error: no replacements are possible (undefined behaviour)") code = input().encode() inp = sys.stdin.read().encode() res = execute(code, inp) print(res.decode()) ``` ## Rules * Standard loopholes are forbidden * You may take input either as a byte list, a single string, or a list of lines. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest program in bytes wins. [Answer] # Python3, 264 bytes: ``` lambda x,y:next(M(x,p(y))) def M(s,g): if s in g[0]:yield s for a,b in g[1]: for i in range(len(s)): if a==s[i:i+len(a)]:yield from M(s[:i]+b+s[i+len(a):],g) def p(s): d={} for i in s.split('\n'):d[c]=d.get((c:='='in i),[])+[[i,i.split('=')][c]] return d ``` [Try it online!](https://tio.run/##RY5BbsMgEEX3nAJlAyOjqLibCokj5ASEBQ7gIjkYAZFsVT27C2mjzmr05@n9SXv9XOP7R8qHl9djMffJGryxXUS3VXqhG0t0BwBknccXWtgMAuHgccEh4lm9abEHt1hcEPZrxoZNvweuG/eMQg@yibOji4u0QDfg7jBSFhVEGHpu4KXyeb33LiWCHqahIX@A0K3@@Ulqmmax8usb/ZeUc0lLqJRcIwFh1U1Le55dpfQmJJGkIQGY0jAoFVh40ZKAbqxGOLv6yBHbI@UQK/WU8DaEnU6n3RUUV8S5HBEfJUfj2DfZslG2Y0MAjh8) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 198 bytes ``` c=>g=(a,...b)=>c.every(s=>([_,p,q,r]=s.match(/^((?:\\?.)*?)(=(.*))?$/).map(t=>t&&eval(`"${t.split`"`.join`\\"`}"`)),q?[...a].map((_,i)=>b.push(a.slice(0,i)+a.slice(i).replace(p,r))):a!=p))?g(...b):a ``` [Try it online!](https://tio.run/##NU7RbsIwDHzvX6xCYLNg1r4Nye2HUEZCFkpYaUKTIbFpv74ugOYXn@/kuzuqiwp6sD4uevduxj2PmquWQQki2iFXmszFDFcIXMF6K7w4i2HDgU4q6gMs3wDqVdPUhPMagYHmiPVkiUn3ELmK06m5qA5kPvmOFHxno8wlHZ3tZdPk8ieXiOJcr1Oc2ty/YCtsCt6R/wwHUBQ6qw28JPL5/7BIg/GdStCLARFX6ol9Sm7hXnulRu364DpDnWthDzK7mpD1LisKLrOi5CIryxvixJV8EyXFwZ4AHyVh1vQzRJgVRVrjr/PRJsdxEaLSH4tgvwy/PuYP "JavaScript (Node.js) – Try It Online") Fixed and optimized tsh's (deleted) answer ]
[Question] [ Turn-based tactics games like Advance Wars, Wargroove, and Fire Emblem are made up of a square grid of varying terrain with units of differing movement classes requiring different costs for each terrain type. We'll be investigating a subset of that problem. ## Challenge Your task is to determine if one location is reachable from another given a grid of terrain costs and a movement speed. Units can only move orthogonally where the cost of moving onto a square is the value of the corresponding cell on the grid (moving off is free). For instance, moving from a cell valued 3 onto a cell valued 1 costs 1 movement, but going the other way requires 3. Some squares may be inaccessible. ### Example ``` 1 [1] 1 1 1 1 2 2 3 1 2 3 3 3 4 1 3 <1> 3 4 ``` Moving from `[1]` to `<1>` requires a minimum of 7 movement points by moving right one square and then down three. Thus, if given 6 or less as the movement speed, you should output a falsy answer. ## Example Test Cases These will use top-left-origin zero-indexed (row, column) coordinates rather than bracketed cells for start and end to make parsing easier. Unreachable cells will be represented with `X` Case 1a ``` 1 1 2 1 X 1 2 2 1 1 2 1 1 2 1 X X X 1 2 Speed: 5 From (2, 3) to (0, 1) Output: True ``` Case 1b ``` 1 1 2 1 X 1 2 2 1 1 2 1 1 2 1 X X X 1 2 Speed: 4 From (2, 3) to (0, 1) Output: False ``` Case 1c ``` 1 1 2 1 X 1 2 2 1 1 2 1 1 2 1 X X X 1 2 Speed: 5 From (0, 1) to (2, 3) Output: False ``` Case 2a ``` 3 6 1 1 X 4 1 2 1 X 5 1 2 2 1 1 1 X 1 5 2 1 1 1 2 1 1 1 X 1 2 1 1 3 1 2 3 4 1 2 1 1 2 1 1 4 1 1 1 2 3 2 3 5 6 1 1 X 1 4 Speed: 7 From (3, 4) to (2, 1) Output: True ``` Case 2b ``` 3 6 1 1 X 4 1 2 1 X 5 1 2 2 1 1 1 X 1 5 2 1 1 1 2 1 1 1 X 1 2 1 1 3 1 2 3 4 1 2 1 1 2 1 1 4 1 1 1 2 3 2 3 5 6 1 1 X 1 4 Speed: 4 From (3, 4) to (2, 1) Output: False ``` Case 2c ``` 3 6 1 1 X 4 1 2 1 X 5 1 2 2 1 1 1 X 1 5 2 1 1 1 2 1 1 1 X 1 2 1 1 3 1 2 3 4 1 2 1 1 2 1 1 4 1 1 1 2 3 2 3 5 6 1 1 X 1 4 Speed: 7 From (1, 8) to (2, 7) Output: True ``` Case 3a ``` 2 1 1 2 2 3 3 1 Speed: 3 From (0, 0) to (1, 1) Output: False ``` Case 3b ``` 2 1 1 2 2 3 3 1 Speed: 3 From (1, 1) to (0, 0) Output: True ``` ## Rules, Assumptions, and Notes * Standard loopholes are banned, I/O can be in any convenient format * You may assume coordinates are all on the grid * Movement speed will never be over 100 * Inaccessible cells may be represented with very large numbers (e.g. 420, 9001, 1 million) or with 0 or null, whichever is most convenient for you. * All inputs will consist of positive integers (unless using null or 0 to represent unreachable cells) [Answer] # TSQL query, ~~205~~ 191 bytes Input is a table variable @t @x=start xpos, @y=start ypos @i=end xpos , @j=end ypos @ =speed ``` DECLARE @t table(x int,y int,v int) INSERT @t values (0,0,1),(0,1,1),(0,2,2),(0,3,1),(0,4,null), (1,0,1),(1,1,2),(1,2,2),(1,3,1),(1,4,1), (2,0,2),(2,1,1),(2,2,1),(2,3,2),(2,4,1), (3,0,null),(2,1,null),(2,2,null),(2,3,1),(2,4,2) DECLARE @x INT=2,@y INT=3,@i INT=0,@j INT=1,@ INT=5; WITH C as(SELECT @y f,@x r,@ s UNION ALL SELECT f+a,r+b,s-v FROM C JOIN(values(1,0),(0,1),(-1,0),(0,-1))x(a,b)ON s>0JOIN @t ON f+a=x and r+b=y)SELECT max(iif(S>=0and f=@j and r=@i,1,0))FROM c ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1019423/terrain-reachability)** ungolfed version [Answer] # [Python 2](https://docs.python.org/2/), 220 bytes ``` def f(m,a,w,h,r,c,R,C): T=[w*[999]for _ in' '*h];T[r][c]=0;P=[(r,c)];j,k=1,0 for u,v in P:exec"U,V=u+j,v+k;j,k=-k,j\nif h>U>-1<V<w:q=T[U][V];T[U][V]=min(T[u][v]+m[U][V],q);P+=[(U,V)]*(q>T[U][V])\n"*4 return a>=T[R][C] ``` [Try it online!](https://tio.run/##zZJNb@IwEIbP@FeMeokN0xUhoSzQcKnErRKqACEZa5UFI76ShiSE7q9nx4mB3Va99LKrWLJnPO8zH3HyK1@/xq3zealXsOIRhnjCNaa4wBd8Ej0G40Ce6rLb7arVawo/YBM74NTXqj@WqZILFTT7o0ByUgjV3@IucLHJwMQesaBoGPX0m17cTXAaHBtbLBq7Mux@h9t5vFnBejAZ3LuP08dT7xCM5UTJqYGXexBtYj6WRyUL1YgqHx5Ef9SglEQUqs4PAxss5vFd3WeQ6vyYxhAOiPai5JM6Pwf7MPq5DCHryShMuLWKHrUFVEIRBM7MAb3PNFWc80Jg/i1L9pucC1H2kptOMutz5rEjFDMjG/IMCyy7R24mhvot0YtcL2l2tQgCeOYky9NNQihWS3VGPjPoAvc65pFsKlGdxHXqrJakVAY1kiFceIwNueM4zAW4LWO1yuUZq9qr5Zs7rwwzFkmxg7yJLhXqYUvgOD1qcaO6RHFhxsxuToZmvWwG5qOzobSRt9ATlgVfxfgIxAECAZHAoIYh/YCvsKB9g1ygf8M8eCilM/Cv2DZcweWNC212sf7wWp9Xer1Kz24x/kVBOcx9@5rJraYOHSrKQ/Btce670f/L0vwPpf1nc3MRvtviOu8fm30MzKgpS6nxqofQFJX2Y0OfiWzwRWwTnX8D "Python 2 – Try It Online") Takes an array `m` of integers, with `'X'` as a larger-than-100 value;, a speed `a`, `m` having width `w` and height `h`; and returns whteher we can start at the zero-indexed row/column cell `(r,c)` and get to the final cell `(R,C)`. The algorithm is a modified flood-fill. Slightly ungolfed code: ``` def f(m,a,w,h,r,c,R,C): T = [w*[999]for _ in ' '*h] # make an array same size as m, with all # values 999, whose values will represent # the cost of getting to each cell. T[r][c] = 0 # set the starting location to a cost of 0 P = [(r,c)] # initialize a set of cells whose neighbors' # cost might need to be be updated j,k = 1,0 # and also j,k which will take on values: # (1,0), (0,1), (-1,0), (0,1), used to # probe orthogonal neighbors for u,v in P: # scan the cells in P for _ in '1234': # look at each of 4 orthogonal positions U,V = u+j,v+k # U and V get the indexes of a neighbor # of the current cell. j,k = -k,j # this 'rotates' the j,k pairing. if h>U>-1<V<w: # if the coordinates are in bounds... q = T[U][V] # save the current 'cost' of getting to cell (U,V) # see if we can reduce that cost, which is calculated # by taking the cost of the currently scanned cell # + the value from m for the neighbor cell. T[U][V] = min(T[u][v]+m[U][V] ,q) # if we can reduce the cost, add the neighbor # to P because **it's** neighbors might, # in turn, need updating. P += [(U,V)]*(q>T[U][V]) return a>=T[R][C] # return if speed is enough for the cost. ``` [Answer] # JavaScript (ES7), ~~116~~ 113 bytes Takes input as `(matrix)([endRow, endCol])(speed, startRow, startCol)`. Expects large values for unreachable squares. Returns \$0\$ or \$1\$. ``` m=>e=>o=g=(s,y,x)=>m.map((r,Y)=>r.map((v,X)=>r[s<v|(x-X)**2+(y-Y)**2-1||g(s-v,Y,X,r[X]=1/0),X]=v),o|=y+[,x]==e)|o ``` [Try it online!](https://tio.run/##fVLBjoIwFLzzFb3Z6kNtC@smu/WyZ@8YwoG4aHYD1lCXaMK/s9SiFkO5lLZvZpj3pr9plapd@XM6@0f5nTV70RRinYm1FAeBFVzhQsS6mBfpCeMStu2hNIcKIn2I1WdV44sfkemUzfDV3@qNT@v6gJVfwRYiKOMoEXSxJNB@KwKyFtdZDJdEiIzUstkggWIPoRghCqhbWLdreQlYRWYX2@VetK6eCFNsJW463XJHJF7y4Xk7eVQyz@a5PODJV6oyRCekd7vHG4JjzU4IDkFLc0LQYoHO5V/mhgY2dJ/magirEUZWs2ysZ42Fa8NvdoddJ8HYvMJ@8WVCtD@O0DFIOk51sHifyl@89hId@kMwZOLO4n3d0DUco@SKmQ3GzEx2K9DawWjM7BHzEzoS88rItqbeLVk7Zebo99mqGaurIz7YETU2@e2FLcdtaoTB0sdr1Dabfw "JavaScript (Node.js) – Try It Online") ### Commented ``` m => // m[] = matrix e => // e[] = target coordinates o = // o = success flag, initialized to a non-numeric value g = ( // g = recursive depth-first search function taking: s, // s = speed y, x // y, x = starting coordinates ) => // m.map((r, Y) => // for each row r[] at position Y in m[]: r.map((v, X) => // for each value v at position X in r[]: r[ // this statement ultimately updates r[X]: s < v | // abort if s is less than v (x - X) ** 2 + // or the quadrance between (x, y) (y - Y) ** 2 - 1 // and (X, Y) is not equal to 1 || g( // otherwise, do a recursive call to g: s - v, // subtract v from s Y, X, // pass (Y, X) as the new coordinates r[X] = 1 / 0 // temporarily make this cell unreachable ), // end of recursive call X // restore r[X] ... ] = v // ... to its original value ), // end of inner map() o |= y + [, x] == e // set the flag o if (y + ',' + x) matches (e + '') ) | o // end of outer map(); return o ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 59 bytes ``` +2¦µ_2ịæ.ؽœị$Ʋ+5ịƲ$4¦01Ñḣ3Ḋ⁼/Ɗ?ḣ2=/ẸƊoF<0ẸƊƊ? çⱮØ.,U$;N$¤Ẹ ``` [Try it online!](https://tio.run/##zVI9S8NQFN37Kzpk66NN3kcr1tKtbjoJSigOmkVaIrYObtWlECd16aCTUgdFsKA0fizv0fyP5I/Em/tKElonXUp49953zr3nHh45cjqdszguUTmWb/s0/LxU47Iaye/ZDdRGMCkJyMHE4HJsWuoqnN6zcOpF51@VwGvCjTYq4cc08NzWhokFwAX1GL2@qFGZ7Bj1LUM@ABGH/pOIBre70eBO@o1mdPFsmabZy3Zt1oGW760Tt7tehK564mZ2HfqjwEuoYt9FmC3AvWPHOUSGJzJaZfu0f@B2HS2khhqEuqCGsHkvjm3b5kS0iU0Jg2gSq00EseCjSQRrWNIMyhFZIBSGl5X4/5RQQ@v92VMVbpAZ4SgFgjXCSBWnsI/nx0VOOV0lUmCB0FeGFcuE5pGnQwyPyG@10M8v7vjqubPIGrqrrdbbUUwm0Rbh6VgqkYww/HnmXcjr3uWu9g8 "Jelly – Try It Online") Not terribly fast; tries all paths until the speed units are exhausted, even retracing its steps. However, this avoids the need to check whether spaces are visited. Input is provided as `[nrows, ncols],[start_row, start_col],[end_row, end_col],speed,flattened matrix column-major` ### Explanation Helper link ``` +2¦ | add the right argument to the second item in the left argument (current location) µ | start a new monadic chain with the modified left argument 4¦ | for the fourth item (speed)... _ | subtract... ịƲ$ | the item located at... 2ịæ.ؽœị$Ʋ | the dot product of the current position and (number of columns, | right-padded with 1) +5 | plus five ? | Now, if... Ɗ | next three as a monad ḣ2=/ẸƊ | either current row or current column are equal to nrows/ncolumns respectively o | or F<0ẸƊ | any value is negative 0 | return zero ? | else if... ḣ3Ḋ⁼/Ɗ | the second and third items (current and end pos) are equal 1 | return 1 Ñ | else pass the current list back to the main link ``` Main link ``` ç | call the helper link with the current list... Ɱ | and each of Ø.,U$;N$¤ | [0,1],[1,0],[0,-1],[-1,0] Ẹ | Check if any are true ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes ``` ạƝṢ€Ḅ’¬Ạ ŒṪ’ḟŒPŒ!€ẎW€j¥@€ÇƇḊ€‘œị⁸§Ṃ’<⁵ ``` An extremely inefficient full program accepting the terrain (with unvisitables as 101) then the start and end co-ordinates then the speed. **[Try it online!](https://tio.run/##y0rNyan8///hroXH5j7cuehR05qHO1oeNcw8tObhrgVcRyc93LkKyHu4Y/7RSQFHJymC5Hf1hQOprENLHYDU4fZj7Q93dAFZjxpmHJ38cHf3o8Ydh5Y/3NkE1GbzqHHr////o6MVFBQMdYCEEYgwjOXSgYkYGoAJJBGocGwsUBuQaRSroxAN1GYIFDAHAA "Jelly – Try It Online")** (not much point trying most of the test cases!) ### How? Creates a list of all permutations of each of the power-set of "all terrain locations except the start & end", surrounds each of these with the start & end, filters to those which make only orthogonal moves of distance one, drops the start from each, indexes back into the terrain, sums each, takes the minimum, subtracts one and tests that this is less than the speed. ]
[Question] [ > > Disclaimer: The story told within this question is entirely fictional, and invented solely for the purpose of providing an intro. > > > I have a friend who is an architect, and, after explaining the concept of code-golf and this site to him, he said that I should code something actually useful for a change. I asked him what he would consider useful, and, being an architect, he replied that he would enjoy having a floor planner that gave him all possible arrangements for rooms of certain sizes within a house of a certain size. I thought I would prove that code-golf wasn't useless after all, and give him this program in the smallest number of bytes possible. ## Your Task: Write a program or function that, when given an array D containing the dimensions of the entire house, and a second array R containing the dimensions of the interior rooms, output as ASCII art, all possible configurations of the rooms inside the house. All rooms and the exterior walls of the house should be formed as standard ASCII boxes, using the | symbol for vertical walls, the - symbol as horizontal walls, and the + symbol for corners. For example, a house with the dimensions [4,4] will look like: ``` +----+ | | | | | | | | +----+ ``` As you can see, corners do not count as part of a set of dimensions. The number of - or | characters forming a side should equal the number given in the dimensions. Rooms may share walls, or share walls with the house. A room may not contain smaller rooms within itself. For example, the configuration ``` +--+---+-+ | | | | | | | | +--+---+ | | | | | +--------+ ``` is valid for D=[5,8], and R=[[2,2],[2,3]]. ## Input: Two arrays, one of which contains two integers, the dimensions for the house, and the other of which contains a series of arrays containing the dimensions for rooms. ## Output: Either an array of all possible houses as strings, or a string containing all possible houses, delimited in some consistent way. Note that rotations of the exact same configuration should only be counted once. ## Test Cases: ``` D R -> Output [4,3] [[2,1],[4,1]] -> +-+-+ +-+-+ +-+-+ Note that though there is an option to switch which side the [2,1] room and the [4,1] room are on, doing so would merely be rotating the house by 180 degrees, and therefore these possibilities do not count. | | | +-+ | | | | +-+ | | | | | | | | | | | | | +-+ | | | | +-+ | | | | +-+-+ +-+-+ +-+-+ [4,7] [[3,1],[4,2],[2,2] -> +----+--+ +----+--+ +----+--+ +----+--+ There are some more possiblities I didn't feel like adding, but it's the same four again, just with the [4,2] and the [2,2] room switched. | | | | | | | | | | | | | | | | | | | | | | | | +---++--+ +--+-+-++ +-+--++-+ ++---+--+ | | | | | || | | | | || | | +---+---+ +--+---++ +-+---+-+ ++---+--+ ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins! [Answer] # [Python 2](https://docs.python.org/2/), ~~625~~ ~~607~~ ~~602~~ ~~563~~ 551 bytes 1. -5 bytes thanks to Mr.Xcoder. 2. -12 bytes when avoiding deep-copying. 3. -39 bytes with some list simplifications. ``` r,z=range,len L,C=D;p,q,v,w=['+'],['|'],'*',' ' H=[p+['-']*C+p] P=[[e[:]for e in H+[q+[w]*C+q]*L+H]] def g(M,x,y,N): m=[e[:]for e in M] try: for i in r(z(N)): for j in r(z(N[0])): if v==N[i][j]and w!=M[x+i][y+j]:return[] m[x+i][y+j]=m[x+i][y+j]in[w,v,N[i][j]]and N[i][j]or'+' except:return[] return m for l,c in R: H=[p+['-']*c+p] P=[g(U,x,y,[e[:]for e in H+[q+[v]*c+q]*l+H])for U in P for x in r(L+2)for y in r(C+2)] F=[] for m in P: if[e[::-1]for e in m[::-1]]not in F:F+=[m] for m in F: print for e in m:print''.join(e).replace(v,w) ``` [Try it online!](https://tio.run/##bVLBjoIwED3br@ieCraa1d0Tm540xIMaY@KpmYPB4kKgYMMKmP13dwpmcZO9kHnvzbzOvFC21Wdh5velVO/iDSjZS6XmYgYC8QzgbsVN2qM5a5FpQ9ZiIZcfpbiIq6ilYpxhI/vGLxszwSgjK6lKrtiEwXjBSyA79NMqgLiwVNPE0BVXF65qJ19gvOYrAHLSMT17G9GIVmz9gNBc/h3aAKGVbVGhjkscZ72bt/Vdd0@mv6R6BcePkphepdyqBFQKR3Oi9YvcqIYjbnkKgdXVlzUKyCgfWPlUJ0bVeOnDobN41IXF2wnVTaTLajCifUVz4jbKROR22uOKT7FELhaKuZy9Q3fxf/lcXR/mk2E@vtMOTtt1hzb9oWs@75S2hwuEQEKJWzg27/rx5SR2/sFkNjyR9xhMUTkYBiGXKn@aC3GutImpCB2Ggo5hbJoWifG0P7W6zI6R9vBX8O/3Hw "Python 2 – Try It Online") **Some explanations** It is a greedy approach: 1. Find all positions where the first room can be allocated 2. Find all possible positions where the next room can be allocated from the remaining free space of the house, and so on for the other rooms. 3. If the last room was successfully allocated the code output the configuration if it is not a 180°-rotation of a previous configuration. ]
[Question] [ One of the cool features introduced in the C++11 standard is the ability to declare a template parameter as being [variadic](https://en.wikipedia.org/wiki/Variadic_template); i.e. that parameter represents a sequence of an arbitrary number of arguments (including zero!). For example, suppose the parameter pack `args` expands contains the sequence `A0, A1, A2`. To expand the pack, an expression is followed using the expansion operator `...`, and the expression is repeated for each argument with the parameter pack replaced by each element of the pack. Some example expansions (assume `f` and `g` are not variadic packs): ``` args... -> A0, A1, A2 f(args)... -> f(A0), f(A1), f(A2) args(f,g)... -> A0(f,g), A1(f,g), A2(f,g) ``` If the expansion operator is used on an expression which contains multiple un-expanded parameter packs, the packs are expanded in lock-step. Note that it is required that all parameter packs which participate in a single expansion operator must all have the same length. For example, consider the packs `args0 -> A0, A1, A2` and `args1 -> B0, B1, B2`. Then the following expressions expand to: ``` f(args0, args1)... -> f(A0, B0), f(A1, B1), f(A2, B2) g(args0..., args1)... -> g(A0, A1, A2, B0), g(A0, A1, A2, B1), g(A0, A1, A2, B2) ``` The goal of this challenge is given an expression and set of parameter packs, produce the expanded equivalent. Note that there must be at least one un-expanded parameter pack as the argument to the expansion operator. All of the following are syntax errors (assume `args0 = A0, A1, A2`, `args1 = B0, B1`): ``` f(args0, args1)... // packs must have the same length f(c)... // no un-expanded packs in expansion operator f(args0...)... // no un-expanded packs in expansion operator ``` Your program needs not handle any expressions which result in a syntax error. # Input Your program/function should take as input a dictionary-like object which associates a parameter pack name with it's arguments, and an expression to be expanded (expression syntax explained later). For example, in Python-like syntax the dictionary of packs might look something like this: ``` {'args0': ['A0', 'A1', 'A2'], 'args1': [], 'args2': ['B0', 'A1', 'B2']} ``` Feel free to adapt the parameter pack input dictionary as desired. For example, it could be a list of strings where each string is a space-separated list and the first value is the pack name: ``` args0 A0 A1 A2 args1 args2 B0 A1 B2 ``` Expressions to be expanded will contain only valid C++ identifiers (case-sensitive alpha-numerics and underscore), function call operators, parenthesis grouping, commas, and the expansion operator. Any identifiers in the expression which are not in the dictionary of parameter packs are not variadic. You may assume the given expression has a valid expansion. It is your decision on what restrictions there are on how whitespace is used (for example, every token has a space between it and other tokens, or no whitespace at all). The input may come from any source desired (stdin, function parameter, etc.) # Output The output of your program/function is a single string representing the expanded expression. You are allowed to remove/add any whitespace or parenthesis grouping so long as the expression is equivalent. For example, the expression `f(a,b,c,d)` is equivalent to all of the following: ``` (f(((a,b,c,d)))) f ( a, b, c , d ) f((a), (b), (c), (d)) ``` The output can be to any source desired(stdout, function return value, etc.) # Examples All examples are formatted as such: The dictionary of packs are expressed as lines of strings in the example format given above (space separated, first value is the pack name), followed by the expression, and the expected result. case 1: ``` args0 A0 args2 B0 A0 args1 args0... A0 ``` case 2: ``` args0 A0 args2 B0 A0 args1 args1... // nothing ``` case 3: ``` args0 A0 args2 B0 A0 args1 f(args1)... // nothing ``` case 4: ``` args0 A0 args2 B0 A0 args1 f(args1...) f() ``` case 5: ``` args0 A0 args2 B0 A0 args1 f(C0, args0..., args2)... f(C0, A0, B0), f(C0, A0, A0) ``` case 6: ``` args0 A0 A1 args1 B0 B1 args2 C0 C1 f(args0, args1, args2)... f(A0, B0, C0), f(A1, B1, C1) ``` case 7: ``` args0 A0 A1 args0(C0)... A0(C0), A1(C0) ``` case 8: ``` args0 A0 A1 args1 B0 B1 args0(args1(f))... A0(B0(f)), A1(B1(f)) ``` case 9: ``` args0 A0 A1 args1 B0 B1 f_(c) f_(c) ``` case 10: ``` args0 args1 A0 A1 f(args0..., args1)... f(A0), f(A1) ``` # Scoring This is code-golf; shortest code in bytes wins. Standard loop-holes apply. You may use any built-ins desired. [Answer] # [Python 3](https://docs.python.org/3/), 567 bytes ``` lambda v,q:w(g(v,p(q),-1)) def c(s): a=[];b=0;l="" for x in s: if x!=","or b:l+=x;b+=~-")(".find(x)%3-1 else:a+=[p(l)];l="" return a+[p(l)] p=lambda s:(0,p(s[:-3]))if"..."==s[-3:]else(1,(2,s.split("(")[0]),c(s[s.find("(")+1:-1]))if")"==s[-1]else(2,s) def g(v,q,i): if q[0]>1:return q[1]if q[1]not in v or i<0else v[q[1]][i] if q[0]:return(g(v,q[1],i),[g(v,k,i)for k in q[2]]) a=[];i=0 while 1: try:a+=[g(v,q[1],i)];i+=1 except:return a w=lambda k:",".join(q for q in[w(x)for x in k]if q)if type(k)==list else k if type(k)==str else k[0]+"("+w(k[1])+")" ``` [Try it online!](https://tio.run/##TVLLjtwgEDwPX0GQIoGMLTNz84RIST6DcPCs8S4x68GGzENR8uuTbtu72ltTTRdV1cR7fjmPh0evfz5C@3rqWnqRU3Plz/wiI5@ELJUQpHM9feJJNGTXamOPJ10fg2aM7PrzTG/UjzRBb@d7evukmWSAnppQ6NvxVOh/JROcVb0fO34Tnw@lgqsuJNe0hTaRB2E3ttnl3/NI22JFSdSbqNTwGvQk05QHK4TvWVVVTOtkykNjkYsryfcyVSkGnznjTJjaCgmqTVqfRqxQTalWArGOq3UaRlebaHySHq2CmwlIvqpm0zUZZRdQ2fGc0fWFglP/pUYOejHYscbb99ltcokTm0AsDR4GqDC7AVkms7dWbNl6XZPd9cUHRxVmmuf7ktMHCrhU6CXE25OL@U1eS65veQ0NLKH6dfYjnyi@M8E75grxvy9sWKxAEjTfo@OD0Dr4lOliBWR9wFOeNxgsFZBjceUDSBEFpPjwr/E8Z5ruiZCWaiyqlDs/VrNrOy7gMPvIBSEBuu26oeBHlxDrAPvzlxDUhSBKCwa3BOYHaCK4bRUi6gxqsICDgMYS4vAKrhFei6F9cpxRJiljwB1nP2be805SJ8SjnZ9TTb/VlGC1p9/xsNSK9PxHLelyA37WWu0FlP8B "Python 3 – Try It Online") Could use a lot of golfing but I'm pretty happy with this answer. Tested on all 10 example cases. -9 bytes thanks to Neil [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~267~~ 246 bytes ``` Reverse[R=StringReplace@{"("->"[",")"->"]","..."->"!",a:(WordCharacter|"_")..:>"\""<>a<>"\""},3]@ToString[a@ToExpression@R@#2//.a_String@b___:>a~q~b/.p@@@#//.a_?(FreeQ[_!])!:>(a//.s_/;FreeQ[s,p,{3,∞}]:>s~Thread~p/.p->(##&))/.q->Construct]& a="" ``` [Try it online!](https://tio.run/##rVTditNAGL3vU7QTKBlI89O9i@0YN1gQRLS74EUcwrfpZBtok@zMVIQ0ufYpfDhfpH5J6tK1roj2IuTjHOac8538bEGvxRZ0lsAhnR@W4rOQSkTL@Y2WWX6/FOUGEhFUxCQTRiJiEdoOHAfbtttxRCzwzY@FXIVrkJBoIfckJtS2fUY@ETJjMOuG2rriwW3RC0eA4@svpRRKZUUeLANj6jg2xD0d3MVx7DNoHpo7xy6DIDA69qW5kEJ8iOIRpyOfmYCoip0XPaqs0qqurO9fv9XcZ6q5XUsBq6ZEhQkzDWNMqWM/TFhY5ErLXaL5eABzQg7v0VNHRhRNOZ@wx4wp2lpv8nKnF4Xccj5ubhLIm2pQzfYE5L1ysYCKvHJxt8FwOOywaYddu9jQU8JriXrPEOkPtwUifxEx71Jiqdkh9MJ6KEcvpBe61vBnf/00fTYtKnlnSr3FtXfuHbZEiMRp9qOd93deJ88Xk/5rsFOVjjZT@n9aaWwmv1U4O/jLKscS2rL/8GYs8MMvZAYbPPs2Uxpv@O8QoMXq3W6zebrRM5u0edv@z9d3HzPQ40XqQX34AQ "Wolfram Language (Mathematica) – Try It Online") As far as I can tell there's no built-in way to `Thread` beyond the first level (or `Thread` heads, for that matter). ``` a="" (* ensures Reverse[R,3] works properly *) R=StringReplace@{ (* parses input: *) "("->"[",")"->"]", (* convert brackets to mathematica-style *) "..."->"!", (* `...` is costly to manipulate, so instead use something that isn't. *) a:(WordCharacter|"_")..:>"\""<>a<>"\""}; (* wrap symbols in quotes so they won't evaluate. *) a@ToExpression@R@# (* parse input and wrap it with "" to allow multiple outputs *) //.a_String@b___:>a~q~b (* convert expressions to a form suitable for calling Thread *) /.p@@@# (* substitute packed arguments *) //.a_?(FreeQ[_!])!]:> (* expand ...s from the bottom up: *) (a//.s_/;FreeQ[s,p,{3,∞}]:>s~Thread~p (* thread over packed arguments from the bottom up, *) /.p->(##&)) (* and unpack into sequences. *) /.q->Construct (* convert back into an expression *) Reverse[R,3]@ToString[ % ] (* convert to c-style output. *) ``` ]
[Question] [ A [dual graph](https://en.wikipedia.org/wiki/Dual_graph) is defined such that for every "face" in a graph `G`, there is a corresponding vertex in the dual graph, and for every edge on the graph `G`, there is an edge in the dual graph connecting the vertices corresponding to the two faces on either side of the edge of the original graph. Note that the faces on both side may be the same face, for example the graph consisting of 2 vertices connected by a single edge (see case 3). Here is a shamelessly borrowed example from Wikipedia: [![enter image description here](https://i.stack.imgur.com/dPVR9.png)](https://i.stack.imgur.com/dPVR9.png) Your goal is given a graph, find a dual graph for that graph. Note that there may not necessarily be a unique dual graph for a given graph; you need only find one. Assume all input graphs are undirected and planar. # Input Assume all vertices of the input graph have some consecutive integer numbering starting at any beginning integer value of your choice. An edge is described by an unordered pair of integers denoting the vertices the edge connects. For example, the blue graph shown above could be described with the following unordered multiset of edges (assuming the numbering of vertices starts at 0): ``` [(0,1), (0,2), (1,2), (2,3), (1,3), (1,4), (4,3)] ``` An alternative way to describe a multigraph is via an adjacency list. Here is an example adjacency list for the above graph: ``` [0:(1,2), 1:(0,2,3,4), 2:(0,1,3), 3:(1,2,4), 4:(1,3)] ``` Your program must take as input a multigraph of edges from any source (stdio, function parameter, etc.). You may assume the input graph is connected. You may use any notation desired so long as the no additional non-trivial information is communicated to your program. For example, having an extra parameter denoting the number of input edges is perfectly acceptable, but passing in a full or partially formed dual graph as an extra parameter is not. Similarly, passing in an unordered multiset of edges, adjacency list, or adjacency matrix is fine. # Output The output of your program should be in one of the formats allowed for the input; it needs not be the same as the input format. The output may be to any sink desired (stdio, return value, output parameter, etc.). # Examples All following examples use unordered multisets of edges with 0-based indices. One possible output is given. As a side note, all of the test case outputs are also valid inputs for your program, and an example output is the corresponding input. **case 1:** ``` input: [(0,1), (0,2), (1,2), (2,3), (1,3), (1,4), (4,3)] output: [(0,1), (0,2), (1,0), (0,3), (0,3), (1,2), (2,3)] ``` **case 2:** ``` input: [(0,1),(0,2),(1,2)] output: [(0,1),(0,1),(0,1)] ``` **case 3:** ``` input: [(0,1)] output: [(0,0)] ``` **case 4:** ``` input: [] output: [] ``` **case 5:** ``` input: [(0,1),(0,2),(2,1),(3,1),(3,4),(2,4)] output: [(0,2),(0,2),(1,0),(1,2),(1,2),(1,2)] ``` # Scoring This is code golf; shortest code wins. Standard loopholes apply. You may use any built-ins not specifically designed to solve this problem. [Answer] # Python3, 416 bytes: ``` S=sorted T=tuple def C(n,o,l,p=[]): if n==o and p:yield T(map(T,S(p)));return for i in l[n]: if(s:=S([n,i]))not in p:yield from C(i,o,l,p+[s]) def f(e): K,s=0,{min(r,key=len)for i in e if(r:=[*C(i,i,e)])} if not s and e:return[(0,0)] E={(K:=K+1):set(i) for i in s} l=[((a,b),j)for a in E for b in E if a<b and(j:=E[a]&E[b])] return[(0,i)for i in E for _ in E[i]-{x for _,y in l for x in y}]+[a for a,_ in l] ``` [Try it online!](https://tio.run/##jVK7jhshFK09X0EVcWMS@VVEk1BFrlzaHUIWYxgFBwMCLO3I2m93eGzW2@wmzdz3Oedexk/pl7Prbz7c73saXUhKdgeart6oTqoR/cSWOGKIp4xD3yE9IkupQ8JK5PtJKyPRAV@Exweyxx4AvgeVrsF2aHQBaaQtMszyPJpncezpHjNLNAewLpXqX5QxuEum041uziKHqmDEqhDvSKQLcrtoiwP5rSZqlIVXClXAQ0/Z54KgiQIOz01tZolVruqbMoYXZAG8Q1t6w7ue7uZL6KNKWMNDc8zThjKMBRmAnCuTKIVt7Rmam/HFj6Gg43NPt0zwT1s28AL@4NIPmW34WF2m@ZfbU0uQqd6pBk/FnZ75nIkaC1L7Db/XC52cMeqUtLMR6YvPL4bylcTVJKlPqV4suaOQ56PRMWGTbzeTiL5twqUC3ayht11MbpvJvMBX4b3K@wxQE8NrQuREWwpVEAld54O2CY/4LWNZeQkEZbMqZtnMiqxb9GI2xWxylP8E@Aio4VSYf7S@X/5PjlX11y/fTc1sPmZd1PL9Dw) ]
[Question] [ This challenge is inspired by a picture that often roams on Facebook that looks like [this](https://i.stack.imgur.com/SM0I2.jpg). Except our base square will look more like this: ``` ┌─┬───┬─┐ ├─┼─┬─┼─┤ ├─┼─┴─┼─┤ ├─┼─┬─┼─┤ └─┴─┴─┴─┘ ``` The square is made out of `n x m` 1x1 square, you have to count how many sub-squares (1x1, 2x2, 3x3, 4x4, 5x5, etc.) can fit within that square. Squares can be missing some grid lines (like in the example above) or be complete like in the example bellow. Which means a mathematical breakdown is *not* possible (as far as I know). ## Inputs: * The amount of lines (`n`) of input to build the square; * A square made from the following characters: `─` `┐` `┌` `└` `┴` `┘` `┬` `├` `┤` `┼` `|` across `n` lines of input. ## Output: * The amount of squares of any size that can fit within the input square (we only want a single number here, not a number for each size). ## Winning criterion: The smallest answer (number of bytes) wins. ## Test Cases: **In:** ``` 5 ┌─┬─┬─┬─┐ ├─┼─┼─┼─┤ ├─┼─┼─┼─┤ ├─┼─┼─┼─┤ └─┴─┴─┴─┘ ``` **Out:** 30 --- **In:** ``` 3 ┌─┬─┐ ├─┼─┤ └─┴─┘ ``` **Out:** 5 --- **In:** ``` 5 ┌─┬─┐ ├─┴─┤ ├───┤ ├─┬─┤ └─┴─┘ ``` **Out:** 7 --- **In:** ``` 4 ┌─┬─┬─┬─┬─┬─┐ ├─┼─┼─┼─┼─┼─┤ ├─┼─┼─┼─┼─┼─┤ └─┴─┴─┴─┴─┴─┘ ``` **Out:** 32 --- **In:** ``` 2 ┌─┐ └─┘ ``` **Out:** 1 --- **In:** ``` 4 ┌─┬─┬─┬─┬─┬─┐ ├─┴─┼─┼─┼─┴─┤ ├─┬─┼─┼─┼─┬─┤ └─┴─┴─┴─┴─┴─┘ ``` **Out:** 22 [Answer] # JavaScript (ES6), [292](https://mothereff.in/byte-counter#%28h%2Cz%29%3D%3E%28o%3D%3E%7Br%3Dp%3D%3E%22%20%29%2C%E2%94%8C%28%E2%94%80%E2%94%90%E2%94%AC%27%E2%94%94%E2%94%82%E2%94%9C%E2%94%98%E2%94%B4%E2%94%A4%E2%94%BC%22.search%28z%5Bp%5D%29%3Bk%3D%28p%2Cd%2Cm%29%3D%3Er%28p%29%26r%28p%2Bs%2Ad%29%26m%3Bfor%28q%3Ds%3D0%3B%2B%2Bs%3Co%2F2%26s%3Ch%3B%29for%28y%3D0%3By%3C%28h-s%29%2Ao%3By%2B%3Do%29for%28x%3D0%3Bx%3Co-s%2A2%3Bq%2B%3D!n%2Cx%2B%3D2%29for%28n%3Di%3D0%2Ct%3Dx%2Cu%3Dy%3Bi%3C%3Ds%3Bt%2B%3D2%2Cu%2B%3Do%2Ci%2B%2B%29n%3Dn%7Ci%3Cs%26%28!k%28t%2By%2Co%2C1%29%7C!k%28x%2Bu%2C2%2C2%29%29%7Ci%3E0%26%28!k%28t%2By%2Co%2C4%29%7C!k%28x%2Bu%2C2%2C8%29%29%3B%7D%29%28-~z.search%60%0A%60%29%7Cq%0A) bytes ~~306 325~~ **Edit** I did the byte count totally wrong, ~~corrected now thx <http://bytesizematters.com/>~~ correct for the last time I hope thx Cᴏɴᴏʀ O'Bʀɪᴇɴ see <https://goo.gl/LSHC1U> (and 1 byte less using a literal newline insteads of '\n') ``` (h,z)=>(o=>{r=p=>" ),┌(─┐┬'└│├┘┴┤┼".search(z[p]);for(q=s=0;++s<o/2&s<h;)for(y=0;y<(h-s)*o;y+=o)for(x=0;x<o-s*2;q+=!n,x+=2)for(n=i=0,t=x,u=y;i<=s;t+=2,u+=o,i++)n|=i<s&(!(r(t+y)&r(t+y+s*o)&1)|!(r(x+u)&r(x+u+s*2)&2))|i>0&(!(r(t+y)&r(t+y+s*o)&4)|!(r(x+u)&r(x+u+s*2)&8))})(-~z.search` `)|q ``` Longer than I expected (probably a few more byte can be shaved off) All possible squares are checked and counted. The `r` function map each character to a bitmap having * 1 : horizontal line center to right * 2 : vertical line center to bottom * 4 : horizontal line center to left * 8 : vertical line center to top A square of any size must have * 4 in all cells except the first in top and bottom row * 1 in all cells except the last in top and bottom row * 8 in all cells except the first in leftmost and rightmost column * 2 in all cells except the last in leftmost and rightmost column **Test** ``` f=(h,z)=>(o=>{r=p=>" ),┌(─┐┬'└│├┘┴┤┼".search(z[p]);k=(p,d,m)=>r(p)&r(p+s*d)&m;for(q=s=0;++s<o/2&s<h;)for(y=0;y<(h-s)*o;y+=o)for(x=0;x<o-s*2;q+=!n,x+=2)for(n=i=0,t=x,u=y;i<=s;t+=2,u+=o,i++)n=n|i<s&(!k(t+y,o,1)|!k(x+u,2,2))|i>0&(!k(t+y,o,4)|!k(x+u,2,8));})(-~z.search` `)|q console.log=(...x)=>O.textContent+=x+'\n' // Less golfed Uf=(h,z)=>{ o=-~z.search`\n`; w=o/2; r=p=>" ),┌(─┐┬'└│├┘┴┤┼".search(z[p]); k=(p,d,m)=>r(p)&r(p+s*d)&m; for(q=s=0;++s<w&s<h;) for(y=0;y<(h-s)*o;y+=o) for(x=0;x<(w-s)*2;q+=!n,x+=2) for(n=i=0,t=x,u=y;i<=s;t+=2,u+=o,i++) n|=i<s&(!k(t+y,o,1)|!k(x+u,2,2)) |i>0&(!k(t+y,o,4)|!k(x+u,2,8)); return q } ;[[5,`┌─┬───┬─┐ ├─┼─┬─┼─┤ ├─┼─┴─┼─┤ ├─┼─┬─┼─┤ └─┴─┴─┴─┘`,20] ,[5,`┌─┬─┬─┬─┐ ├─┼─┼─┼─┤ ├─┼─┼─┼─┤ ├─┼─┼─┼─┤ └─┴─┴─┴─┘`,30] ,[3,`┌─┬─┐ ├─┼─┤ └─┴─┘`,5] ,[5,`┌─┬─┐ ├─┴─┤ ├───┤ ├─┬─┤ └─┴─┘`,7] ,[4,`┌─┬─┬─┬─┬─┬─┐ ├─┼─┼─┼─┼─┼─┤ ├─┼─┼─┼─┼─┼─┤ └─┴─┴─┴─┴─┴─┘`,32] ,[2,`┌─┐ └─┘`,1] ,[4,`┌─┬─┬─┬─┬─┬─┐ ├─┴─┼─┼─┼─┴─┤ ├─┬─┼─┼─┼─┬─┤ └─┴─┴─┴─┴─┴─┘`,22], ,[6,`┌─┬─────┐ ├─┼─┬─┐ │ │ ├─┼─┼─┤ │ └─┼─┼─┤ │ └─┼─┤ └─────┴─┘`,12], ,[6,`┌─┬─┬─┬─┐ ├─┴─┼─┼─┤ │ └─┼─┤ ├─┬─┬─┼─┤ ├─┼─┼─┼─┤ └─┴─┴─┴─┘`,23]] .forEach(t=>{ var r=t[0],a=t[1],k=t[2],x=f(r,a) console.log(x==k?'OK '+x:'KO '+x+' Expected '+k,'\n'+a) }) ``` ``` <pre id=O></pre> ``` ]
[Question] [ In [ValiDate ISO 8601 by RX](https://codegolf.stackexchange.com/questions/54555/validate-iso-8601-by-rx), the challenge was to use only standard regular expressions to **validate standard date formats *and* values** (the former is a common job for RX, the latter was unusual). The winning answer used 778 bytes. This challenge is to beat that using any language of your choosing, but **without special date functions or classes**. # Challenge Find the shortest code that 1. validates every possible date in the [*Proleptic*](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar) Gregorian calendar (which also applies to all dates before its first adoption in 1582), 2. does not match any invalid date and 3. does not use any predefined functions, methods, classes, modules or similar for handling dates (and times), i.e. relies on string and numeric operations. ## Output Output is truthy or falsey. It’s not necessary to output or convert the date. ## Input Input is a single string in any of 3 expanded [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) date formats – no times. The first two are `±YYYY-MM-DD` (year, month, day) and `±YYYY-DDD` (year, day). Both need special-casing for the leap day. They are naively matched separately by these extended RXs: ``` (?<year>[+-]?\d{4,})-(?<month>\d\d)-(?<day>\d\d) (?<year>[+-]?\d{4,})-(?<doy>\d{3}) ``` The third input format is `±YYYY-wWW-D` (year, week, day). It is the complicated one because of the complex leap week pattern. ``` (?<year>[+-]?\d{4,})-W(?<week>\d\d)-(?<dow>\d) ``` # Conditions A **leap year** in the Proleptic Gregorian calendar contains the **leap day** `…-02-29` and thus it is 366 days long, hence `…-366` exists. This happens in any year whose (possibly negative) ordinal number is divisible by 4, but not by 100 unless it’s also divisible by 400. **Year zero** exists in this calendar and it is a leap year. A **long year** in the ISO week calendar contains a 53rd week `…-W53-…`, which one could term a “**leap week**”. This happens in all years where 1 January is a Thursday and additionally in all leap years where it’s a Wednesday. `0001-01-01` and `2001-01-01` are Mondays. It turns out to occur every 5 or 6 years usually, in a seemingly irregular pattern. A year has at least 4 digits. Years with more than 10 digits do not have to be supported, because that’s close enough to the age of the universe (ca. 14 billion years). The leading plus sign is optional, although the actual standard suggests it should be required for years with more than 4 digits. Partial or truncated dates, i.e. with less than day-precision, must not be accepted. Separating hyphens `-` are required in all cases. (These preconditions make it possible for leading `+` to be always optional.) # Rules This is code-golf. The shortest code in bytes wins. Earlier answer wins a tie. # Test cases ## Valid tests ``` 2015-08-10 2015-10-08 12015-08-10 -2015-08-10 +2015-08-10 0015-08-10 1582-10-10 2015-02-28 2016-02-29 2000-02-29 0000-02-29 -2000-02-29 -2016-02-29 +2016-02-29 200000-02-29 -200000-02-29 +200000-02-29 2016-366 2000-366 0000-366 -2000-366 -2016-366 +2016-366 2015-081 2015-W33-1 2015-W53-7 +2015-W53-7 +2015-W33-1 -2015-W33-1 2015-08-10 ``` The last one is optionally valid, i.e. leading and trailing spaces in input strings may be trimmed. ## Invalid formats ``` -0000-08-10 # that's an arbitrary decision 15-08-10 # year is at least 4 digits long 2015-8-10 # month (and day) is exactly two digits long, i.e. leading zero is required 015-08-10 # year is at least 4 digits long 20150810 # though a valid ISO format, we require separators; could also be interpreted as a 8-digit year 2015 08 10 # separator must be hyphen-minus 2015.08.10 # separator must be hyphen-minus 2015–08–10 # separator must be hyphen-minus 2015-0810 201508-10 # could be October in the year 201508 2015 - 08 - 10 # no internal spaces allowed 2015-w33-1 # letter ‘W’ must be uppercase 2015W33-1 # it would be unambiguous to omit the separator in front of a letter, but not in the standard 2015W331 # though a valid ISO format we require separators 2015-W331 2015-W33 # a valid ISO date, but we require day-precision 2015W33 # though a valid ISO format we require separators and day-precision 2015-08 # a valid ISO format, but we require day-precision 201508 # a valid but ambiguous ISO format 2015 # a valid ISO format, but we require day-precision ``` ## Invalid dates ``` 2015-00-10 # month range is 1–12 2015-13-10 # month range is 1–12 2015-08-00 # day range is 1–28 through 31 2015-08-32 # max. day range is 1–31 2015-04-31 # day range for April is 1–30 2015-02-30 # day range for February is 1–28 or 29 2015-02-29 # day range for common February is 1–28 2100-02-29 # most century years are non-leap -2100-02-29 # most century years are non-leap 2015-000 # day range is 1–365 or 366 2015-366 # day range is 1–365 in common years 2016-367 # day range is 1–366 in leap years 2100-366 # most century years are non-leap -2100-366 # most century years are non-leap 2015-W00-1 # week range is 1–52 or 53 2015-W54-1 # week range is 1–53 in long years 2016-W53-1 # week range is 1–52 in short years 2015-W33-0 # day range is 1–7 2015-W33-8 # day range is 1–7 ``` [Answer] # JavaScript (ES6), 236 236 bytes allowing negative 0 year (`-0000`). Returns true or false ``` s=>!!([,y,w,d]=s.match(/^([+-]?\d{4,})(-W?\d\d)?(-\d{1,3})$/)||[],n=y%100==0&y%400!=0|y%4!=0,l=((l=y-1)+8-~(l/4)+~(l/100)-~(l/400))%7,l=l==5|l==4&!n,+d&&(-w?d>`0${2+n}0101001010`[~w]-32:w?(w=w.slice(2),w>0&w<(53+l)&d>-8):d[3]&&d>n-367)) ``` Adding the check for negative 0 cut 2 bytes but adds 13. Note that in javascript the numeric value `-0` exists, and it is special cased to be equal to 0, but `1/-0` is `-Infinity`. This versione returns 0 or 1 ``` s=>([,y,w,d]=s.match(/^([+-]?\d{4,})(-W?\d\d)?(-\d{1,3})$/)||[],n=y%100==0&y%400!=0|y%4!=0,l=((l=y-1)+8-~(l/4)+~(l/100)-~(l/400))%7,l=l==5|l==4&!n,+d&&(-w?d>`0${2+n}0101001010`[~w]-32:w?(w=w.slice(2),w>0&w<(53+l)&d>-8):d[3]&&d>n-367))&!(!+y&1/y<0) ``` **Test** ``` Check= s=>!! // to obtain a true/false ( // parse year in y, middle part in w, day in d // day will be negative with 1 or 3 numeric digits and could be 0 // week will be '-W' + 2 digits // month will be negative with2 digits and could be 0 // if the date is in format yyyy-ddd, then w is empty [,y,w,d] = s.match(/^([+-]?\d{4,})(-W?\d\d)?(-\d{1,3})$/) || [], n = y%100==0 & y%400!=0 | y%4!=0, // n: not leap year l = ((l=y-1) + 8 -~(l/4) +~(l/100) -~(l/400)) % 7, l = l==5| l==4 & !n, // l: long year (see http://mathforum.org/library/drmath/view/55837.html) +d && ( // if d is not empty and not 0 -w // if w is numeric and not 0, then it's the month (negative) ? d > `0${2+n}0101001010`[~w] - 32 // check month length (for leap year too) : w // if w is not empty, then it's the week ('-Wnn') ? ( w = w.slice(2), w > 0 & w < (53+l) & d >- 8) // check long year too : d[3] && d > n-367 // else d is the prog day, has to be 3 digits and < 367 o 366 ) ) console.log=x=>O.textContent += x +'\n' OK=['1900-01-01','2015-08-10','2015-10-08','12015-08-10','-2015-08-10','+2015-08-10' ,'0015-08-10','1582-10-10','2015-02-28','2016-02-29','2000-02-29' ,'0000-02-29','-2000-02-29','-2016-02-29','+2016-02-29','200000-02-29' ,'-200000-02-29','+200000-02-29','2016-366','2000-366','0000-366' ,'-2000-366','-2016-366','+2016-366','2015-081','2015-W33-1' ,'2015-W53-7','+2015-W53-7','+2015-W33-1','-2015-W33-1','2015-08-10'] KO=['-0000-08-10','15-08-10','2015-8-10','015-08-10','20150810','2015 08 10' ,'2015.08.10','2015–08–10','2015-0810','201508-10','2015 - 08 - 10','2015-w33-1' ,'2015W33-1','2015W331','2015-W331','2015-W33','2015W33','2015-08','201508' ,'2015','2015-00-10','2015-13-10','2015-08-00','2015-08-32','2015-04-31' ,'2015-02-30','2015-02-29','2100-02-29','-2100-02-29','2015-000' ,'2015-366','2016-367','2100-366','-2100-366','2015-W00-1' ,'2015-W54-1','2016-W53-1','2015-W33-0','2015-W33-8'] console.log('Valid') OK.forEach(x=>console.log(Check(x)+' '+x)) console.log('Not valid') KO.forEach(x=>console.log(Check(x)+' '+x)) ``` ``` <pre id=O></pre> ``` ]
[Question] [ # Bob the Bowman ``` o /( )\ This is Bob. L L Bob wants to be an archer. ############# . / \ <--- bow So he bought himself a (c -)-> <--- arrow nice longbow and is about ( )/ <--- highly focused Bob shoot at a target. L L ############# ___________________________________________________________________________________________ sky Bob is a smart guy. He already knows what angle and velocity his arrow has / will have. But only YOU know the distance to the target, so Bob doesn't know if he will hit or miss. This is where you have to help him. . +-+ / \ | | (c -)-> | | ( )/ +++ L L | ########################################################################################### ``` --- ## Task Your task is to render an ASCII art picture of Bob hitting or missing the target. For the calculation: * Your program will receive `arrow_x,angle,velocity,distance` as comma-separated input in any order you wish. * One ASCII character equals `1m`. * The first character in the last line has the coordinates `(0,0)`, so the ground (rendered as `#`) is at `y=0`. * Bob always stands on the ground, his `y` position does not change. * There is no max `y`. However, the arrows apex should fit within the rendered picture. * All input is provided as decimal integer. * During calculation, assume the arrow is a point. * The arrow origin is the arrow head `>` of a shooting Bob (see above). So given `arrow_x`, you have to calculate `arrow_y`. The left foot of Bob in the output has to match the `x` coord. of the shooting Bob. * `distance` is the `x` coordinate of the target's *foot*. (ie. the middle of the target). * All measurements are supplied in meters and degrees respectively. * Attention: *The shooting Bob is never rendered, only used for calculations! See below for the two valid output-Bobs* * Hitting the target means the arrows path crosses either one of the two leftmost target walls (`|`) (That is either (distance-1,3) or (distance-1,4). If at some point the arrow is within those 2m², place the X instead of the wall it hits. The target is always the same height and only its x position can change.). Corner hits or an arrow falling from the sky onto the target does not count. * Standard earth g applies (9.81 m/s^2). * `distance+1` is the end of the field, after that, everything is a miss and no arrow should be rendered. * If the arrow hits the target in any other way (`distance-1` etc.), no arrow should be rendered. ## Miss This is an example rendering of Bob missing (arrow enters ground at 34m, angle is 45°, time in air is 10s, velocity is ~50 - but there are a lot more possible inputs to cause this output. Just show your program uses the usual formulas to calculate physically "accurate" results.): ``` +-+ | | c\ | | /( ) v +++ L L | | ########################################################################################### ``` ## Hit This is an example rendering of Bob scoring (arrow enters target (= crosses its path)): ``` +-+ >--X | \c/ | | ( ) +++ L L | ########################################################################################### ``` ## Example * `arrow_x` is 7. `arrow_y` is always 3. * `angle` is `30°` or `0.523598776` radians. * `velocity` is `13m/s`. * `distance` is 20. So in order to hit the target, the arrow has to cross `(19,3)` or `(19,4)`. Everything else will be a miss. In this case, the arrow will enter the ground (means `y` will be `<1.0`) at `12.9358m = ~13m` after `1.149s`. --- ## Limits & Scoring * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution wins. There are no bonuses. * Your *program* (as in *not function*) must accept input in the format described above, additional input is not permitted. * You don't have to handle wrong/pointless/impossible inputs. * Print to whatever is the shortest reasonable output for your language (std, file, ...). * I don't care about trailing whitespace. * *Tip:* Width of output is `distance+2`. The height is `apex+1`. [Answer] # Ruby, 482 ``` include Math def f s,e,l [s,' '*(l-s.size-e.size),e].join end alias p puts X,o,V,d=$*[0].split(?,).map &:to_i o*=PI/180 L=X+d B='| |' S='' G=' L L' p f S,'+-+',L d.times{|x|y=3+x*tan(o)-(9.81*x**2)/(2*(V*cos(o))**2) if x==d-1&&(3..5)===y s='>--X |' m=(3..4)===y p f S,m ?B: s,L p f ' \c/',m ?s: B,L p f ' ( )',?+*3,L p f G,'| ',L elsif y<=1 || x==d-1 p f S,B,L p f ' c\\',B,L print f '/( )', y<1? 'V':' ',x p f S,?+*3,L-x print f G, y<1? '|':' ',x p f S,'| ',L-x break end} p ?#*L ``` ## Ungolfed ``` include Math def fill s,e,l [s,' '*(l-s.size-e.size),e].join end arrow_x,angle,velocity,distance = $*[0].split(',').map(&:to_i) angle *= PI/180 length=arrow_x+distance loss = '| |' puts fill '','+-+',length distance.times { |x| y = 3 + x*tan(angle) - (9.81*x**2)/(2*(velocity*cos(angle))**2) if x == distance-1 && (3..5)===y puts fill '',(3..4)===y ? '| |':'>--X |',length puts fill ' \c/',(3..4)===y ? '>--X |':'| |',length puts fill ' ( )','+++',length puts fill ' L L','| ',length elsif y<=1 || x==distance-1 puts fill '',loss,length puts fill ' c\\',loss,length print fill '/( )', y<1? 'v': ' ', x puts fill '','+++',length-x print fill ' L L', y<1? '|': ' ', x puts fill '',' | ',length-x break end } puts ?#*length ``` ### Method The main equation here is: [![trajectory equation](https://i.stack.imgur.com/OtNC8.png)](https://i.stack.imgur.com/OtNC8.png) Note: image taken from <https://en.wikipedia.org/wiki/Trajectory_of_a_projectile> Where, ``` y0: initial height (of arrow) Ө: the angle x: the position of the arrow g: gravity (9.81) v: velocity ``` What I'm doing is to loop through numbers from 0 to (distance -1) and in every iteration check to see if the arrow hits the ground (or the target) ]
[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/55239/edit). Closed 2 years ago. [Improve this question](/posts/55239/edit) ## Introduction On BBC Radio 2, on Saturdays there's a show hosted by Tony Blackburn called [**Pick of the Pops**](http://www.bbc.co.uk/programmes/b006wqx7). Here, Tony selects a random week from a random year (in the range 1960-1989), and plays the songs which were in the top 20 charts at the time. ## Challenge Given a list of songs played on one Pick of the Pops episode, you must determine the year which Tony has chosen. ## Further Information ### Input The input will be given as a string (either by STDIN or function arguments), with each list item separated by a comma. The input will sorted with the number one single first, carrying on in order until the list ends with the number 20 single. On the actual show, Blackburn plays the charts for two different years. This will not be the case for your input, only the chart for your one year will be supplied. If song usually has a comma in its name, then the comma will be omitted. ### Output Your output should simply be the year in the format `YYYY` (`1989`, `2365`, `1901`). If for any reason, multiple years are found (say if the charts are form the first week of the year), then either select the *first* year or output both, comma separated. ### Rules You can read from either a file or the internet. If you use the internet, you must only use pages on the website `officialcharts.com`. ***Note:* if you read from a Wikipedia page, the page must have been created before the 23rd of August 2015.** The charts will be from the *national UK charts*, not international or of any other country. Your output must be in the range of 1960 - 1989. ## Examples ### Input ``` Ticket to Ride,Here Comes the Night,The Minute You're Gone,Concrete and Clay,Little Things,Catch the Wind,For Your Love,King of the Road,The Last Time,Pop Go the Workers,Bring It On Home to Me,Stop in the Name of Love,Times They Are A-Changin',You're Breakin' My Heart,I Can't Explain,I'll Be There,Everybody's Gonna Be Happy,It's Not Usual,A World of Our Own,True Love Ways ``` ### Output ``` 1965 ``` ## Winning The person with the shortest program in bytes wins. ## Note At the moment, I'm still downloading all of the chart information, but you can use the following Python 2 code to retrieve the necessary information and create the file. (Requires the *requests* module) ``` import requests, re, datetime, time date = datetime.date(1960,1,1) prevyear=0 year = 1960 delay = # Set the delay yourself. So far 4 seconds still makes the download fail while date.year != 1990: response = requests.get("http://www.officialcharts.com/charts/singles-chart/%d%02d%02d"%(date.year, date.month, date.day)).text time.sleep(delay) tags = re.findall("<a href=\"/search/singles/.+\">.+</a>", response)[:20] top20s = [] for i in tags[:]: tag = re.sub("<a href=\"/search/singles/.+\">", "", i) tag = re.sub("</a>","",tag) top20s.append(tag) top20s = list(map(lambda x:x.replace(",",""), top20s)) with open("songs.txt", "a") as f: if year != prevyear: string = str(year)+"\n" else: string = "" chart = ",".join(top20s) f.write(string+chart+"\n") prevyear = year date += datetime.timedelta(days=7) year = date.year ``` [Answer] ## C# (~~277, 271,~~ 223 compacted bytes) After six years, this deserves an answer, so I'm going to make some assumptions: * The data is stored in the file: `C:\songs.txt`. * The songs for each week are stored on a new line in the following format: + `yyyy:song,song,song,...` --- ``` var @in = Console.ReadLine(); var d = File.ReadAllText(@"C:\songs.txt"); foreach (var w in d.Split('\n')) { var wd = w.Split(':'); if (wd[1].Split(',').Any(a => @in.Split(',').ToList().Any(i => i.Equals(a)))) { Console.Write(wd[0]); break; } } ``` --- ***Note**: Compacted in this case means removing all line breaks and unnecessary whitespace. I'm retaining proper formatting for the sake of readability.* ]
[Question] [ ## Introduction [Tangrams](http://en.wikipedia.org/wiki/Tangram) are a classic puzzle involving arranging/fitting blocks into various shapes. From the Chinese 七巧板 - literally meaning "seven boards of skill". Let's take this idea and use the seven [Tetrominos](http://en.wikipedia.org/wiki/Tetris#Gameplay) pieces to fill a grid. ## Challenge Write a function or program that takes an array of grid coordinates as input, and outputs a completed 10 by 20 grid filled with Tetris pieces except in the specified coordinates. Optimize your score by attempting to keep the distribution of pieces uniform. ## Criteria Use [this pastebin](http://pastebin.com/0QAgFT5f) of coordinates to accomplish your task. There are five sets of coordinates. Feel free to modify the format in which the coordinates are written, but not the values. Data set #2 cannot be solved - in this case, simply output the grid with input cells filled in (i.e., `X`'s where the holes are). ## Input Grid coordinates represent 'holes' in the grid. These are cells which cannot contain any part of a Tetromino. **Grid coordinates:** ``` (0,0), (1,0), (2,0), ... (9,0) (0,1), (1,1), (2,1), ... (9,1) . . . (0,19), (1,19), (2,19), ... (9,19) ``` * Use your programming language's array style of choice to input the coordinates. * Represent holes in the grid with an `X` or other [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). ## Output Using a standard Tetris grid size of **10 cells wide by 20 cells tall**, print a solution grid if and only if the grid can be filled completely and perfectly using Tetromino pieces. Pieces constructed with letters `I`, `O`, `L`, `J`, `T`, `Z`, `S` as follows: ``` I I L J I OO L J T ZZ SS I OO LL JJ TTT ZZ SS ``` --- ## Example Output solution example with no input coordinates: ``` ZZIIIILLLI JZZTTTLLLI JJJSTLOOLI SZZSSLOOLI SSZZSLLJJI TSOOSLLJII TTOOSSLJII TZOOSSLZII ZZOOSSZZII ZJJJJSZLLI TTTJJOOILI ITZJJOOILI IZZTTTLIII IZOOTZLIII IJOOZZLLII LJJJZSSTII LLLTSSTTTI LLLTTSSZJI OOLTSSZZJI OOIIIIZJJI ``` With distribution as follows: ``` I I L J I OO L J T ZZ SS I OO LL JJ TTT ZZ SS 11 6 8 6 6 7 6 ``` --- ## Notes Coordinates represent a single `X` and `Y` position on the grid. The grid is 0 based, meaning coordinate `(0,0)` should either be the top left or the bottom left cell, author's choice. Bricks can: * be selected at author's discretion. * be rotated as author sees fit. * be placed on the grid anywhere at author's discretion (aka: no Tetris gravity) Bricks cannot: * be placed outside the bounds of the grid. * overlap an existing brick or hole in the grid. * be a non-standard Tetris tetromino piece. --- ## Scoring Your score is in the format: **( 1000 - [bytes in code] ) \* ( M / 10 + 1 )** Where M is a multiplier for the distribution of pieces used in your solution sets. Highest score by the Ides of March wins. To calculate M, add the lowest individual tetromino distribution value for each set and then take the average rounded down to calculate M. For example: ``` Set 1: 5 Set 2: 4 Set 3: 5 Set 4: 6 Set 5: 3 ``` 6 + 4 + 5 + 4 + 4 = 21 / 5 = 4.6 So you would use `4` as your **M** value. Note: If a set has no solution, do not factor that set into calculating M, since it would have no tetromino distribution. [Answer] # [Python 3](https://docs.python.org/3/), 819 bytes, M=0, Score=*181* This is a brute force DFS program. It builds a numpy array, and inserts all the inputted holes. It then takes the leftmost unfilled tile on the highest row that has one, and places a tetromino. Recursively, we now do it again - when we can't either we found a solution, or we backtrack and try another piece at the first opportunity. This has an **M** of 0, since it tries to use pieces in a determined order, and almost always finds a solution without the last one in the list. I tried using a randomly ordered list each cycle to make a more even distribution, but I only got an **M** of 2, which wasn't worth the bytes required to import *random.shuffle*. I can't comment the below code, since in my golfing I've long forgotten what much of it does. The general idea: * Import numpy and itertools product, with 1-letter names * Rename some builtins to be 1-letter functions, and define a lambda to save bytes * Build the array of possible tetrominos as numpy nd-arrays, all rotations included * In the recursive function: + Get the position of the unfilled tile desired, and cycle through the pieces list + For each piece, cycle through translations of it (moving it up and down) + If something doesn't work (piece goes off the board, hits another piece, hits a hole, etc.), try the next translation or the next entire piece + If it works, great. Try it, then recursively call the function. + If that path didn't work, it will return 'a', so we just try again. If it did work, it returns the board, and we pass it up the line. * Finally, the program. We build the 10x20 board as a numpy array of 1's. * The input is of the form *(x1, y1);(x2,y2);...* We put a 9 for each hole in it, then get the result of running the function on it. * The print statement then displays either the successful result or the empty, original board line by line, substituting the appropriate letters or symbols for the numbers. ``` import numpy as n from itertools import product as e m,s=range,len p=[n.rot90(a,k)for a,r in[([[2,2]]*2,1),([[3]*3,[1,3,1]],4),([[0]*4],2),([[1,1,6],[6]*3],4),([[7,1,1],[7]*3],4),([[4,4,1],[1,4,4]],2),([[1,5,5],[5,5,1]],2)]for k in m(r)] o=lambda a:e(m(s(a)),m(s(a[0]))) def t(l,d=0): g=list(zip(*n.where(l==1)))[0] for a in p: for u,v in o(a): w,x=l.copy(),0 for r,c in o(a): if a[r,c]!=1: i,j=g[0]+r-u,g[1]+c-v if any([i<0,i>19,j<0,j>9])or l[i,j]!=1: x=1 break w[i,j]=a[r,c] if x==0: if len(w[w==1]): f=t(w,d+1) if type(f)==str:continue return f return w return'a' b=n.ones((20,10)) b[list(zip(*[eval(k)[::-1]for k in input().split(';')]))]=9 a=t(b) for r in(a,b)[type(a)==str]: print(''.join(map(dict(zip([0,2,3,4,5,6,7,9,1],'IOTZSLJX-')).get,r))) ``` [Try it online!](https://tio.run/##VVLBbtswDD1bX@GdLKWMYTlpi2TT7hsG7LAdhgk6KImcKrElQ5brZj@f0XbWdheJfHyknki2l/jk3ep6tU3rQ0xd37SXVHepI1XwTWqjCdH7uktvhDb4Q7@PI8WQBjoRtDsaqI0jrZAuDz5uCqrhzCofUg0htU5SKUsolVqUwBmgt1KLFUgOK@BKwXrCCrVYKygnmwOHBwXyAXn/4o@IccQe32FrWE8Yx3ut3rLv4R5RPKf6JVOjmDNKSRsamCJe1LrZHXSqt4Y2tKOaMZhulMEYIwdTpZHWcBAF25LkKGrbRfrHtnTh8uHJBENrIThSMYEk01/H8i2SJ6@H59H3WHmEkgFeRJ3vfXuhDIoRGVkB9v@xElulWiKqPgg@I4mFkzjiK3dh2cNRcnW3Xz7fQsh2FyrtpwLsZ76BExqnzxvFsHYtMfNdneRF8Ju1C0afZ3uYWGJ@lMw1X4QoXuXgZOkgB/ysumlMKhHpAIc7zl5lxEtraMWE6GLY7r2L1vVmjgYT@@DSirxzBnKzMp2RnXC5d6ajtCyAF9j9nXxrtzTPuqZnJrfbJX@bo3VtHynLu7a2kWYfM4ZzU2JDNIrbMTJ1F1m4ijsmJ3l6lqfwF22wDrOy/OSR0uiWHux@flAWUOJernF3HuARNuN@ZV@@//z949vXX8uMsfxoIgSc/PX6Fw "Python 3 – Try It Online") Sample test: ``` In: (1,1);(8,1);(4,4);(5,8);(4,11);(5,15);(1,18);(8,18) Out: IIIIOOOOLL TXOOOOOOXL TTOOOOOOTL TOOIOOOOTT TOOIXOOTTI TTTITOOTTI TTTITTTTII OOTTTTTTII OOTTTXOOII TTTTOOOOII TTTTOOOOII TTTTXTOOII ITTTTTTTII ITTTTTTTII IITTTLLTTI IITOOXLTTI IITOOTLTTI IITTLTTTTI IXTLLTJTXI ILLLLLJJJI ``` ]
[Question] [ ``` 0000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000 0000001111111111111100000000000000000011111111111111100000000000000000 0000001111111111111100000000000000000011111111111111100000000000000000 0000001111111111111100000000000000000011111111111111100000000000000000 0000001111111111111100000000000000000011111111111111100000000000000000 0000000000000000000000000000000000000011111111111111100000000000000000 0000000000000000000000000000000000000011111111111111100000000000000000 0000000000011111100000000000000000000011111111111111100000000000000000 0000000000011111100000000000000000000011111111111111100000000000000000 0000000000011111100000000000000000000011111111111111100000000000000000 0000000000000000000000000000000000000011111111111111100000000000000000 0000000000000000000000000000000000000011111111111111100000000000000000 0000000000000111111000000000000000000011111111111111100000000000000000 0000000000000100001000000111111000000011111111111111100000000010000000 0000000000000100001000000111111000000000000000000000011000000000000000 0000000000000111111000000111111000000000000000000000011000000000000000 0000000000000000000000000000111111000000000000000000000000000000000000 0000000000000000000000000000111111000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000 ``` Your are given a 2 dimensional array of bytes of size m x n. It is guaranteed that all the bytes are 1's or 0's. Find the number of rectangles represented by 1's when viewed in 2d, as shown above. Only fully filled rectangles are considered for counting. Rectangles must be surrounded by 0's unless they are on edge(1's diagonally touching rectangles are Okay though (see example.)). For example, in above array there are 5 valid rectangles. You can use any language. [Answer] ### GolfScript, 107 characters ``` .n?):L;'1'/{,}%{1$+)}*;][]\{:A{{+}+[1L.~)-1]%&}+1$\,.@^\[[[A]]+{|}*]+}/{.{L%}{%$..&1$,1$,/*$=}:C~\{L/}C&},, ``` The input must be given on STDIN. Examples: ``` 11 01 - 0 111 111 - 1 100 001 001 - 2 11100 10101 11100 - 1 101 010 101 - 5 ``` ]