text
stringlengths
180
608k
[Question] [ # Introduction In the video [the best way to count](https://www.youtube.com/watch?v=rDDaEVcwIJM), binary is proposed as the best system of counting numbers. Along with this argument is a proposal on how to say numbers in this system. First, we give names to each "double power of two", \$2^{2^n}\$ for each \$n\$. ``` number = symbol = spoken ============================ 2^0 = 1 = "one" 2^1 = 2 = "two" 2^2 = 4 = "four" 2^4 = H = "hex" 2^8 = B = "byte" 2^16 = S = "short" 2^32 = I = "int" 2^64 = L = "long" 2^128 = O = "overlong" 2^256 = P = "byteplex" ``` Then, to get from [a number to its spoken binary](https://youtu.be/rDDaEVcwIJM?si=ZFzrA-zpjOc1OAXY&t=3587), we 1. Take its (big-endian) bit string and break off bits from the end equal to the number of zeros in the largest double power of two less than or equal to the number. 2. Use the name for the corresponding double power of two in the middle, and recursively name the left and right parts through the same procedure. If the left part is one, it is not spoken, and if the right part is zero, it is not spoken. This system is similar to how we normally read numbers: 2004 -> 2 "thousand" 004 -> "two thousand four". For example, 44 in binary is `101100`. Split at four bits from the end and insert "hex", meaning \$2^4\$: `10` "hex" `1100`. `10` becomes "two" and `1100` splits into `11` "four" `00`, or "two one four". So the final number is "two hex two one four" or `2H214` in symbols (note that this is not the recommended way of writing numbers, just speaking). As a longer example, we have one thousand: ``` 1111101000 11 B 11101000 2 1 B 1110 H 1000 2 1 B 11 4 10 H 10 4 00 2 1 B 2 1 4 2 H 2 4 ``` # Challenge Your program must take a positive integer \$n\$ as input and output the string of symbols for the spoken binary of that number. While numbers under \$2^{512}\$ are expressible in this system, you only need to handle integers **up to and including** \$2^{32}\$ = `I`, and as such, do not need to consider `L`, `O`, or `P`. Standard loopholes are forbidden. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest program wins. # Example Input and Output ``` 1 -> 1 2 -> 2 3 -> 21 4 -> 4 5 -> 41 6 -> 42 7 -> 421 8 -> 24 9 -> 241 10 -> 242 11 -> 2421 12 -> 214 25 -> H241 44 -> 2H214 100 -> 42H4 1000 -> 21B2142H24 4294967295 -> 21421H21421B21421H21421S21421H21421B21421H21421 4294967296 -> I ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~42~~ 41 bytes ``` ≔⁻I⮌↨N²0θF24HBSI≔E⪪θ²⪫⮌EΦκ∨μ¬ν⎇∧ν⁼μ1ωμιθθ ``` [Try it online!](https://tio.run/##PY5BDoIwEEX3nqLpaprUBIg7Vmg0YiIa8QIVqzaWAdqC8fS1EHXzNv//N1M9hKkaob3PrFV3hL3C3sJKWAcnOUhjJSxFQI5t74q@vkgDjJOEsUAa0cCOpbNbYwjQZLFdljll5CcTLZStVg66ccLJrlH4947pRmkXjE9ODgZqTorGAU7uszQozBsyvAJysu56oe1YoTEd8xcn9VRU7PvD0SgMl1jqfRxFkZ8P@gM "Charcoal – Try It Online") Link is to verbose version of code. Supports numbers from `1` to `18446744073709551615`. Explanation: ``` ≔⁻I⮌↨N²0θ ``` Convert the input to a list of `1`s and empty strings according to the reverse of its binary representation. ``` F24HBSI ``` Loop over the additional possible "digits". ``` ≔E⪪θ²⪫⮌EΦκ∨μ¬ν⎇∧ν⁼μ1ωμιθ ``` Group the existing digit blocks into pairs, then for each pair, create a new digit block by removing any second part if it is zero, or making it the empty string if it is one, switching the parts, and joining on the next digit. ``` θ ``` Output the final result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~36~~ 29 bytes ``` BUḟ€0“24HBSI”s2jœr1ɗẎḊḢ$?€ɗƒU ``` [Try it online!](https://tio.run/##AT8AwP9qZWxsef//QlXhuJ/igqww4oCcMjRIQlNJ4oCdczJqxZNyMcmX4bqO4biK4biiJD/igqzJl8aSVf///zEwMDA "Jelly – Try It Online") A full program that takes a single positive integer argument and prints the spoken binary form to STDOUT. ## Explanation ``` BUḟ€0“24HBSI”s2jœr1ɗẎḊḢ$?€ɗƒU⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣⁣‏⁠‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁣⁤⁣‏⁠‎⁡⁠⁢⁡⁢⁤⁤‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁤⁢‏⁠‏​⁡⁠⁡‌­ B # ‎⁡‎⁡Convert to binary U # ‎⁢‎⁢Reverse ḟ€0 # ‎⁣Filter out 0 from each “24HBSI” ɗƒ # ‎⁤‎⁢⁢Starting with this, reduce using each character in "24HBSI" as the right argument in turn and the following: s2 # ‎⁢⁡- Split into pieces of length 2 € # ‎⁢⁢- For each piece: ḊḢ$? # ‎⁢⁣ - If length 2 and the second part is non-empty: j # ‎⁢⁤ - Join with the relevant character œr1 # ‎⁣⁡ - Trim 1s from the end Ẏ # ‎⁣⁢ - Else: join outer lists U # ‎⁣⁣Reverse order of final string (and implicit smashing print) 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~84 79~~ 77 bytes ``` f=(n,k=6,y=1,u=2**2**--k)=>n<y?'':~k?f(n/u,k,2)+['24HBSI'[n<u||k]]+f(n%u,k):1 ``` [Try it online!](https://tio.run/##TZBda4MwGIXv31/hzTCp8ePNUjtL00Kv7HUvnaxitWw6Le0cFcr@ustHYYOQ53DO4RDyUXwX1/Lyfv7yu/5YTVMtSccaGbNRIhskn83U8f2GynW3Gjeuu/xpNjXpwoE1jFMvc7lIt/udm3Wr4X5v8txT6ZNK6RKnsu@ufVsFbX8iB0DHXzsIXIPDswGC0BQwN0CIDTksLBFeTE9AYomAkVUcEB9KmXYVBXCzlOqmMNs81TZGkV1MjbYbuFWRygUInogkXvBk/tjhmJp7/0//tcwrd3AILtW5LcqKhOT16FHtksCj4eeJOeSN3dioPi6ryY1KOTJNNuaUTr8 "JavaScript (Node.js) – Try It Online") Your 232-1 case seems wrong [Answer] # [R](https://www.r-project.org), 129 bytes ``` \(x,`~`=paste0)Reduce(\(y,z)apply(matrix(y,2),2,\(w)gsub("^0*[1"~z~"]|0","",w[1]~z~w[2])),c(2,4,"H","B","S","I"),x%/%2^(63:0)%%2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY7BSsNAEIZfZRlYmJGp3WyDSCE99FSP6jGb0BizUtCyZDckDRLwObxEwYfybVxpDx_D_D_MN59f7fxts58u2MXt74fBgffTPnOVD42ih-a5qxs0eOKRKudeT_hWhfYwxEATazbY04vvnhBKdZUnMI0TFO8KGID7PCni3ue6IOIaNacMu1htI4-ROyAe5FLqEm9Wa0VSaro8cl9XAf3ZWGOyTlNOlPpHsS5X0S0MjuRdezgGiyCvlRWLjZAeWIwsbCyjVPjGiQzMES6H5_k8_wA) An R translation (more-or-less) of my Jelly answer. A function that takes a single positive integer and returns the spoken binary form as a string. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 42 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` l2l2Ḟ WµÇ2*2*⁸d⁹jɗ×nJaƲ¹Ƈ)F$ÐLÇ»-ị“4HBSI12 ``` A full program that accepts a positive integer and prints the spoken binary. **[Try it online!](https://tio.run/##AUwAs/9qZWxsef//bDJsMuG4ngpXwrXDhzIqMirigbhk4oG5asmXw5duSmHGssK5xocpRiTDkEzDh8K7LeG7i@KAnDRIQlNJMTL///8xMDAw "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/HKMfo4Y55XOGHth5uN9Iy0nrUuCPlUePOrJPTD0/P80o8tunQzmPtmm4qhyf4HG4/tFv34e7uRw1zTDycgj0Njf4/apj7cOe0Q0u4dA63ZwHFFWztFIBimpH//xvqKBjpKBjrKJjoKJjqKJjpKJjrKFjoKFjqKBgaADFQ3hCowAgoZ2ICEjMAccxAhDmYC@SbGFmaWJqZG1maIrHNAA "Jelly – Try It Online"). ### How? ``` l2l2Ḟ - Link 1: integer, X -> floor(X log 2 log 2) Note when X = 1 l2l2 -> (-inf + nan j) and Ḟ takes the real part -> -inf WµÇ2*2*⁸d⁹jɗ×nJaƲ¹Ƈ)F$ÐLÇ»-ị“4HBSI12 - Main Link: positive integer P W - wrap P in a list ÐL - apply while distinct: $ - last two links as a monad - f(Current): µ ) - for each {V in Current}: Ç - call Link 1 -> floor(V log 2 log 2) 2* - 2 exponentiate {that} 2* - 2 exponentiate {that} -> value of the digit to use, say D ⁸ ɗ - last three links as a dyad - f(V, D): ⁹ - D d - {V} div-mod {D} j - join {that} with {D} Ʋ - last four links as a monad - f(Parts=that): J - indices {Parts} -> [1,2,3] n - {Parts} not equal {that} (vectorises) × - {Parts} multiply {that} (vectorises) a - {that} logical AND {Parts} ¹Ƈ - keep truthy values F - flatten Ç - call Link 1 (vectorises) »- - max with -1 (convert -inf to -1) ị“4HBSI12 - index into (1-based & modular) "4HBSI12" - implicit print ``` [Answer] # [Haskell](https://www.haskell.org/), 115 bytes ``` p=[2^2^i|i<-[6,5..0]] c=concat f x=c[c[f y|y>1]++c[[l]|y>0]|(l,n,m)<-zip3"ISBH421"p$tail p++[1],y<-[mod x n`div`m]] ``` [Try it online!](https://tio.run/##dY9Pi4MwEMXv@RSD7EExFpOqXUH34MmeewwpldSyYf3HKku7@N3dJG3aUthL@L1582Ymn9X4VTfNsgw5o3u6l7PMApbgeLUKOUciF30nqgmd4JwLJtgJLvPlg3DfF4w1XHHIZ7fBHW69LPiVw9rZ7ooyosQZ3qZKNjD4PiMcX9TYtj/CGbrDUf4cWs6XtpId5DB8y24CNVpCnkMPM7gSQ@9BFsBUj5OoxnrkCN1ZZRgCcAkGhzge1kwV0xuvNVsjUiK6cazZGokWNrIxwlrveoANpUZYi4RG2hwhV3m3zR3EZqneWD7Skb6Glo8GEoZmc/lUMBtIoZpUp61HNI3SZEPT@LqAktK8xRPv/qm/jtA/3zoeR8sf "Haskell – Try It Online") ]
[Question] [ You are a package handler for Big CompanyTM and your job is to load boxes into a truck. These are special, stretchy trucks: their length can be adjusted at will. But stretching trucks are expensive, so keep the truck lengths as short as possible! # The Challenge Write a full program or function that, when given the truck's height and width, and a list of cuboid boxes, outputs the minimum truck length for that sequence. # Input Your program has 2 inputs: * The truck's height and width: a 2-tuple of positive integers * The boxes to pack: a list of 3-tuples of positive integers Each box is represented as a 3-tuple of numbers, representing their height, width, and length. It is guaranteed that boxes will be smaller than or the same size as the height and width of the truck. You can freely rotate the boxes any number of times in 90-degree intervals. You can freely reorder the list of boxes. You can freely rotate the truck around its length axis, i.e. a `(3,5)` truck is the same as a `(5,3)` truck. # Output Your program must output the *minimum* length of the truck needed to pack all of the boxes. # Additional Rules * [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). * [Input and output can be in any reasonable format.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! # Test Cases ``` (truck h, w) [(box h, w, l)...] -> truck length (1,1) [(1,1,1)] -> 1 (a single box) (1,1) [(1,1,1) (1,1,1)] -> 2 (a line of two 1x1x1 boxes) (2,1) [(1,1,1) (1,1,1)] -> 1 (two boxes stacked) (1,2) [(1,1,1) (1,1,1)] -> 1 (two boxes on the floor, next to each other) (5,7) [(3,3,5) (1,1,1) (1,2,2)] -> 3 (3x3x5 box is rotated such that it is parallel long-side-wise on the floor) (5,7) [(5,3,5) (5,7,1) (5,2,2) (5,2,2)] -> 5 (the 5x7x1 box on the back wall, the 5x2x2 boxes next to each other) (4,4) [(3,2,5) (2,2,3) (2,2,4) (2,2,6)] -> 7 (3x2x5 forces 2x2x3 and 2x2x4 to be length-wise adjacent) (5,5) [(1,1,1) (2,2,2) (3,3,3) (4,4,4) (5,5,5)] -> 12 (3x3x3 4x4x4 5x5x5 boxes adjacent, 1x1x1 and 2x2x2 crammed into empty space) (5,5) [(1,1,1) (2,2,2) (3,3,3) (4,4,4) (5,5,5) (1,8,5)] -> 13 (same arrangement as above, but 1x8x5 is squeezed between the wall and 4x4x4) ``` ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~292...~~ 228 bytes ``` ->t,b{1.step.find{|l|[p].product(*b.map{|c|c.permutation.flat_map{|x,y,z|[*x..t[0]].product([*y..t[1]],[*z..l]).map{|i,j,k|[i-x...i,j-y...j,k-z...k]}}}).any?{|c|c.combination(2).none?{|a,b|a&.zip(b)&.all?{|x,y|[*x]&[*y]!=[]}}}}} ``` [Try it online!](https://tio.run/##fY7dboMwDIXv9xTbDQJkrEGFetX1QSJrSmiRskKIWJAKhGdnDt2PtGq7sn2@Y/v0gxrX@rBmLw7UnOO7O1ustTnNvvHCEtq@Ow2Vi1OFrbSzr3yF9ty3g5NOdwbrRrrXjVxhhMmL9IroxDP9rIp0DFJOBCKdEBtKbrc0vMHFC53xCvKQsQ9ZytiEF1qWJUFpxuPta9W1Spvta1wkaDpzZiJBeRnhpG2skghl0xy3KCEIRfyang4inFqW1T7WQuSQc45QuCF6uBfhDhZ/w@K/zRL2Ae5gB@U3DLXgk79M5aeJx81UbqavSrR@AA "Ruby – Try It Online") Probably still a lot left to optimize. Can get the 6th test case on TIO in 17 seconds by adding a `uniq` after `permutation`. No way to get more than that. ### Explanation: Brute force approach, pure and simple. Start with length 1, rotate all the boxes, and try all the possible translations. If there is no way to fit them, increase length and try again. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 44 bytes ``` _⁹żAƑƇŻ€,Œp€+þ@/ʋ/€Ẏ Œ!€⁹,1W;"çⱮ/pẎ€QƑƇɗ/ʋ1# ``` [Try it online!](https://tio.run/##y0rNyan8/z/@UePOo3scj0081n5096OmNTpHJxUAKe3D@xz0T3XrA5kPd/VxHZ2kCGQBleoYhlsrHV7@aOM6/QKgBFAwEKT15HSgYkPl////R2sY6gChpg6Ujv1vqGMEAA "Jelly – Try It Online") A dyadic pair of links taking a list of boxes as the left argument and the truck’s first two dimensions as the right argument. Returns the result as an integer. Very inefficient as the boxes and truck get bigger and do times out on TIO even on the fifth test case. ## Explanation ### Helper link Takes three truck dimensions on the left and a list of permuted boxes on the right. Returns a list of lists of coordinates for all possible translated and rotated versions of that box ``` _⁹ | Subtract the permuted boxes from the truck ż | Zip each with the relevant permuation AƑƇ | Keep only those that are non-negative (by checking whether the numbers are changed when absoluted) ʋ/€ | For each of the remaining ones, reduce using the following: Ż€ | - For each of the (truck-box) dimensions, generate a list from zero to that number , | - Pair with the box dimensions Œp€ | - Cartesian products of each +þ@/ | - Reduce using outer addition (generates a list of lists of coordinates for each cell of the translations of that permuation of the box) Ẏ | Tighten ``` ### Main link ``` Œ!€ | Permutations of each box’s dimensions ⁹, | Pair truck dimensions with this (call this y) 1 ʋ1# | Starting with 1, find the first integer x which satisfies the following, using y as the right argument: W;" | - Wrap and concatenate zipped; effectively prepends x to the first member of y (the truck’s two dimensions) çⱮ/ | - Call the helper link with the three truck dimensions on the left for each box’s permutations on the right ɗ/ | - Reduce the results of the helper link with the following: p | - Cartesian product Ẏ€ | - Tighten (concatenate outer lists) QƑƇ | - Check whether unchanged on uniquifying (i.e. are there any duplicates?) ``` ]
[Question] [ ### Sequence Definition Construct a sequence of positive integers `a(n)` as follows: 1. `a(0) = 4` 2. Each term `a(n)`, other than the first, is the smallest number that satisfies the following: a) `a(n)` is a composite number, b) `a(n) > a(n-1)`, and c) `a(n) + a(k) + 1` is a composite number for each `0 <= k < n`. So we start with `a(0) = 4`. The next entry, `a(1)` must be `9`. It can't be `5` or `7` since those aren't composite, and it can't be `6` or `8` because `6+4+1=11` is not composite and `8+4+1=13` is not composite. Finally, `9+4+1=14`, which is composite, so `a(1) = 9`. The next entry, `a(2)` must be `10`, since it's the smallest number larger than `9` with `10+9+1=20` and `10+4+1=15` both composite. For the next entry, `11` and `13` are both out because they're not composite. `12` is out because `12+4+1=17` which is not composite. `14` is out because `14+4+1=19` which is not composite. Thus, `15` is the next term of the sequence because `15` is composite and `15+4+1=20`, `15+9+1=25`, and `15+10+1=26` are all each composite, so `a(3) = 15`. Here are the first 30 terms in this sequence: ``` 4, 9, 10, 15, 16, 22, 28, 34, 35, 39, 40, 46, 52, 58, 64, 70, 75, 76, 82, 88, 94, 100, 106, 112, 118, 119, 124, 125, 130, 136 ``` This is [OEIS A133764](http://oeis.org/A133764). ### Challenge Given an input integer `n`, output the `n`th term in this sequence. ### Rules * You can choose either 0- or 1-based indexing. Please state which in your submission. * The input and output can be assumed to fit in your language's native integer type. * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` !üȯṗ→+fotpN ``` 1-indexed. [Try it online!](https://tio.run/##ASMA3P9odXNr/yBt4oKB4bijMzD/IcO8yK/huZfihpIrZm90cE7//w "Husk – Try It Online") ## Explanation ``` !üȯṗ→+fotpN Implicit input, a number n. N The list of positive integers [1,2,3,4,.. f Keep those p whose list of prime factors ot has a nonempty tail: [4,6,8,9,10,12,.. ü De-duplicate wrt this equality predicate: + sum → plus 1 ȯṗ is a prime number. Result is [4,9,10,15,16,.. ! Get n'th element. ``` [Answer] # [Perl 6](https://perl6.org), 70 bytes ``` {(4,->+_{first {none($^a X+0,|(_ X+1)).is-prime},_.tail^..*}...*)[$_]} ``` [Try it](https://tio.run/##NY3disIwEIXvfYq5kDVZ05C/phVZn2NBbCkaIYu20roLUvvs3RPBizlhvi@cuYX@4uffIdCfl8ft4vqgj2N3CvQ1j8yJbLeux3PshzuNbdcGtqwa@l4r8WQ1Xs25jEN26@M1TKKW9yZeKik/J4ng@2V9mOahedCr0apMbxfvlVVWcfnTxZatBK347ARtBGmFyTFekDGYUpCFsmAW3sE7uBwuh/NwBVgBX4CX4CX4xqWuVKZAtTYpyhTpiEnWpDM2fbH@Hw "Perl 6 – Try It Online") 0-indexed ## Expanded: ``` { # bare block lambda with implicit parameter $_ ( # generate the sequence 4, # seed the sequence -> +_ { # pointy block that has a slurpy list parameter _ (all previous values) first { # bare block with placeholder parameter $a none( # none junction $^a # placeholder parameter for this inner block X+ 0, # make sure $a isn't prime |( _ X+ 1 ) # check all a(k)+1 ).is-prime # make sure none are prime }, _.tail ^.. * # start looking after the previous value } ... # keep generating values until * # never stop )[$_] # index into the sequence } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~112~~ 107 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for a byte. ``` n=-1,4;v=5 exec"while any(all((v-~k)%i for i in range(2,v))for k in n):v+=1\nn+=v,;v+=1\n"*input() print~-v ``` [Try it online!](https://tio.run/##JcjBCsIwDADQ@74iDITEtYdNvWz0T7wUqS6sZKXU6C779crw9nhpK/MqQ63ibG@uk7pbE77h0X5mjgG8bOhjRFS7L3RieK4ZGFgge3kFHIwSHbccJzRq5/q7SOfUTH@3Z5b0LkhNyixlt1rr5Qc "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), ~~115~~ 109 bytes ``` n=-1,4;v=4;x=input() while x:v+=1;k=1^any(all((v-~k)%i for i in range(2,v))for k in n);n+=(v,)*k;x-=k print v ``` [Try it online!](https://tio.run/##FcgxDsMgDADAPa9gqWQ3MJBmKvJXKjGkjQVyUEQdsvTrVLnxylnXTabehZy3c1CaQyOW8q2Aw7FyXkx76kg@JPKvKCfEnAHU/RLe2Ly33bBhMXuUzwKTVcTr0nWCQUYCtXhPoTlKQ9lZqtHeH38 "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 83 bytes 1-indexed ``` f=(n,a=[-1,p=4])=>a[n]||f(n,a.some(x=>(P=n=>n%--x?P(n):x<2)(x-=~p),p++)?a:[...a,p]) ``` ### Demo ``` f=(n,a=[-1,p=4])=>a[n]||f(n,a.some(x=>(P=n=>n%--x?P(n):x<2)(x-=~p),p++)?a:[...a,p]) for(n = 1; n <= 30; n++) { console.log('a(' + n + ') = ' + f(n)) } ``` ### Commented Helper function **P()**, returning **true** if **n** is prime, or **false** otherwise: ``` P = n => n % --x ? P(n) : x < 2 ``` NB: It must be called with **x = n**. Main function **f()**: ``` f = ( // given: n, // n = target index a = [-1, p = 4] // a = computed sequence with an extra -1 at the beginning ) => // p = last appended value a[n] || // if a[n] exists, stop recursion and return it f( // otherwise, do a recursive call to f() with: n, // n unchanged a.some(x => // for each value x in a[]: P(x -= ~p), // rule c: check whether x + p + 1 is prime // rule a: because a[0] = -1, this will first compute P(p) p++ // rule b: increment p before the some() loop starts ) ? // end of some(); if truthy: a // p is invalid: use a[] unchanged : // else: [...a, p] // p is valid: append it to a[] ) // end of recursive call ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes 0-indexed ``` ®4Iµ)˜D¤N‹sN+>p_P*iN¼ ``` [Try it online!](https://tio.run/##AScA2P8wNWFiMWX//8KuNEnCtSnLnETCpE7igLlzTis@cF9QKmlOwrz//zY "05AB1E – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 65 bytes ``` ±0=-1;±1=4;±n_:=±(n-1)+1//.a_/;PrimeQ/@Array[a+1+±#&,n,0,Or]:>a+1 ``` Uses CP-1252 (default Windows) encoding. 1-indexed. [Try it online!](https://tio.run/##y00syUjNTSzJTE78///QRgNbXUPrQxsNbU2AZF68le2hjRp5uoaa2ob6@nqJ8frWAUWZuamB@g6ORUWJldGJ2obahzYqq@nk6Rjo@BfFWtkBRf5D5MDihgax@vpAPXkl/wE "Wolfram Language (Mathematica) – Try It Online") [Answer] # Java 8, ~~186~~ 173 bytes ``` n->{int a[]=new int[n+1],r=a[n]=4;a:for(;n>0;)if(c(++r)<2){for(int x:a)if(x>0&c(r-~x)>1)continue a;a[--n]=r;}return r;}int c(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;} ``` 0-indexed. Unfortunately prime-checks (or anti-prime/composite checks in this case) aren't that cheap in Java.. **Explanation:** [Try it online.](https://tio.run/##TVDBbsIwDL3zFRbSpkShpbCdCO2@YFw4Vj2EkG5h1KnSlIFQ9@udw9A2KXFiv@Q9@x3USSWuNXjYf4z6qLoOXpXF6wTAYjC@VtrAJqa3AmgWI3JJlYE2rQ0g5DBiUlwjpsoqR/MZX5coFtXM56rEKn@WalU7zyQWmeS2ZpoJ4fl6ya@xHL@eVyoC5yJ71MwnX2deLLh2GCz2BpRUZZIQk5eDN6H3CHSbSOpsPoeNC9AqH8DVEN4N7C7BJNr1GCb/@/7VsvlS2jVKzPHBCrFevGQrGutOjHIYAdp@d7QauqACHSdn99CQOWwbvMW3slL8x5joGDRkQpw7JuzmD8CfWEZiTxSE4DcEYHvpgmlS14e0JbrAmhRTapOL6Qymd4OH8Rs) ``` n->{ // Method with integer as both parameter and return-type int a[]=new int[n+1], // Integer-array of size `n+1` r=a[n]=4; // Start the result and last item at 4 a:for(;n>0;) // Loop as long as `n` is larger than 0 if(c(++r)<2){ // Raise `r` by 1, and if it's a composite: for(int x:a) // Inner loop over the array if(x>0 // If the item in the array is filled in (non-zero), &c(r-~x)>1) // and if `r+x+1` is a prime (not a composite number): continue a;} // Continue the outer loop a[--n]=r;} // Decrease `n` by 1, and put `r` in the array return r;} // Return the result // Separated method to check if a given number is a composite number // (It's a composite number if 0 or 1 is returned, otherwise it's a prime.) int c(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;} ``` [Answer] # [Ruby](https://www.ruby-lang.org/) + `-rprime`, ~~85~~ 75 bytes ``` ->n{*a=x=4 n.times{x+=1;!x.prime?&&a.none?{|k|(x+k+1).prime?}?a<<x:redo} x} ``` [Try it online!](https://tio.run/##LcvRCoIwFIDhe59i3Yg2PCh1Vc49SHSxaIKIZ2MaHNn26p0iuvz5@MPrsfOouBkwHo0idS4QtmmxaySpuuuBwIdv6rI0gA6tjmlOFclZdvWfsjZ9T5dgny4XlNmLqgWAU1vDYnwUCZMYb3gXmd/Ob5PDlZvwez8 "Ruby – Try It Online") A lambda returning the 0-indexed nth element. -10 bytes: Use `redo` and a ternary operator instead of `loop`...`break` and a conditional chain Ungolfed: ``` ->n{ *a=x=4 # x is the most recent value: 4 # a is the list of values so far: [4] n.times{ # Repeat n times: x += 1 # Increment x !x.prime? && # If x is composite, and a.none?{|k|(x+k+1).prime?} # for all k, a(n)+x+1 is composite, ? a<<x # Add x to a : redo # Else, restart the block (go to x+=1) } x # Return the most recent value } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 170 bytes ``` P(n,d,b){for(b=d=n>1;++d<n;)b=b&&n%d;n=b;}h(n,N,b,k){if(!n)return 4;for(b=N=h(n-1);b;)for(b=k=!N++;k<n;b|=P(h(k++)-~N));n=N;}f(n,j){for(j=0;n--;)if(P(h(++j)))j++;n=h(j);} ``` [Try it online!](https://tio.run/##JY1BDoIwEEXXcgohgXTSNgHjbqgHYNFwBUutUuJoCK4Qr45D2P68936n7123rq0g5ZWDObxG4Yw3dKlQSl8TgjOuKCj3SMbh8mDSKqcGmPsgUoLxNn1GOp5xV61hQleADmFfBpNaKXHglvuaVjzEICXonwXgpMUlcDLu19GUSFojcHsjpYwAEFkn7kbAZX1eexINzMlhExoWmvpU4nvsaQoiy73KVBANX3A/WdY/ "C (gcc) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~140~~ 138 bytes *Thanks to @Jonathan Frech for saving two bytes!* ``` c(n,i){for(i=1;++i<n;)i=n%i?i:n;i=i>n;}f(n){int s[n],k,j,i=0;for(*s=k=4;i++-n;i[s]=k)for(j=!++k;j-i;)2-c(k)-c(k-~s[j++])?j=!++k:f;n=n[s];} ``` 0-indexed [Try it online!](https://tio.run/##JU7LDsIwDLvvK8qkSQ1tJV6nZWEfMnZARUVZRUAbt2n8@mjBBx/s2I53d@/X1WuxDHN4jpppj8ZwIwhMUnHLtSATnwWXoAVmlreaOulttINl2mFObSeKdEI2xqXrbuopQtYH2hgTcXCMcHBeR8jkPlM3GNND@/frgEKSUrisuf5xZdFQzIVKSDVKZzVvKW6OidOD8DMzXmNygy6r20VKq4JmACyW9Qs) ]
[Question] [ Today in my statistics class, I found that some factorials can be simplified when multiplied together! For example: `5! * 3! = 5! *3*2 = 5! *6 = 6!` ## Your job: Given a string containing only Arabic numbers and exclamation points, simplify my factorial to its shortest possible string, in the least amount of bytes for your language, code golf style. ## Input A string containing only Arabic numbers and exclamation points. The factorials for the input won't be bigger than 200!. Factorials will not have more than one factorial per number. Input may be taken as a list of integers. ## Output A possibly shortened string, that has the equivalent value on the input. Order is unimportant. Factorial notation is a must, but you aren't required to use more than one factorial symbol per number. ## Test cases ``` In: 3!2!2! Out: 4! In 2!3!2!0! Out: 4! In: 7!2!2!7!2!2!2!2! Out: 8!8! In: 23!3!2!2! Out: 24! Also: 4!! In: 23!3!2!2!2! Out: 24!2! In: 127!2!2!2!2!2!2!2! Out: 128! In: 32!56!29!128! Out: 29!32!56!128! ``` Best of luck [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 18 [bytes](https://github.com/DennisMitchell/jelly) ``` !P ÇṗLÇ⁼¥ÐfÇḢḟ1ȯ0F ``` A monadic link taking and returning a list of the numbers (sticks to the one factorial per number option) **[Try it online!](https://tio.run/##ATgAx/9qZWxsef//IVAKw4fhuZdMw4figbzCpcOQZsOH4bii4bifMcivMEb/w4fFkuG5mP//WzMsMiwyXQ "Jelly – Try It Online")** ### How? A golfed (although independently written) version of Pietu1998's solution. ``` !P - Link 1, product of factorials: list ! - factorial (vectorises) P - product ÇṗLÇ⁼¥ÐfÇḢḟ1ȯ0F - Main link: list e.g. [3,2,2] Ç - call the last link (1) as a monad 24 L - length 3 ṗ - Cartesian power [[1,1,1],[1,1,2],...,[1,1,24],...,[24,24,24]] Ç - call the last link (1) as a monad 24 Ðf - filter keep if: ¥ - last two links as a dyad: Ç - call the last link (1) as a monad [1,2,...,24!,...,24!^3] ⁼ - equal? Ḣ - head ḟ1 - filter out any ones ȯ0 - or with zero (for the empty list case) F - flatten (to cater for the fact that zero is not yet a list) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ,!P€E SṗLçÐfµḢḟ1ȯ1F ``` [Try it online!](https://tio.run/##ATAAz/9qZWxsef//LCFQ4oKsRQpT4bmXTMOnw5BmwrXhuKLhuJ8xyK8xRv///1szLDUsOF0 "Jelly – Try It Online") Quick and dirty. Very slow, even the `23!2!3!2!` test case is a stretch. I/O as lists of integers. ### Explanation ``` ,!P€E Helper link. Arguments: attempt, original , Make the array [attempt, original]. Example: [[1,1,1,4], [2,3,2,0]] ! Take the factorial of each item. Example: [[1,1,1,24], [2,6,2,1]] P€ Take the product of each sublist. Example: [24, 24] E Check if the values are equal. SṗLçÐfµḢḟ1ȯ1F Main link. Arguments: original S Find the sum S of the integers in the input. L Find the number N of integers in the input. ṗ Generate all lists containing N integers from 1 to S. çÐf Take the lists whose factorial-product is the same as the original. Ḣ Take the first match. This is the one with the most ones. ḟ1 Remove any ones. ȯ1 If there were only ones, return a one instead. F Turn into a list if needed. ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~397~~ ... 317 bytes ``` import StdEnv,StdLib c=length f c m=sortBy c o flatten o map m %n=f(>)@[2..n] @1=[] @n#f=[i\\i<-[2..n]|n/i*i==n&&and[i/j*j<i\\j<-[2..i-1]]] =f++ @(n/prod f) ?l=group(f(>)%l) $l=hd(f(\a b=c a<c b)(~(?l))[0..sum l]) ~[]_=[[]] ~i n=[[m:k]\\m<-take n[hd(i!!0++[0])..],k<- ~[drop(c a)b\\a<-group(%m)&b<-i|b>a]n|i== ?[m:k]] ``` [Try it online!](https://tio.run/##TVFbS8MwFH7PrzjiNpr1tnU4LzRuiD4IPgg@pkHS28yWpKXrBGH0p1uPq4ovyXfjOyQn04W0vanygy7ASGV7ZeqqaeGlzR/su4fXk0pJxnRhN@0bKSEDw/aYuPtAWEGpZdsWFpGRNRgytqx0bumaR0FgBVnPGcfTnpeMqyRRsT8YRxuqqWLMTibS5lyF2@k2xsB2CCh/LoQgrHRdWDs2rJsqh5KSlWabpjrUzveMsaZkpNlbjiyRkLIMZJxBSp3OWWlK@SwI9gcDWlDScfHKOMfOToFFZG52IklM7LdyV4Dl2KLOzmauy2eCBoHwdrEPHc@bqnawl6ZJImN/GD42dJLGvjqmt1LYIz4DVqdC0b@0smlJGDIYAV9EXnTtXSy9eXQlgJy0pYei@E1E3gL57I9ffrv//IH/qKj3nxl@@Gbf@49P/f2HlUZlA3nGPZRVY05k2NoX "Clean – Try It Online") This takes an `[Int]`, determines the prime factors of the result, and reduces over the factors to find the smallest representation, using the largest factor at any stage as a baseline value for the next factorial term. It won't complete some test cases on TIO, but it is *fairly*\* fast, and can run them all in under 3 minutes on a midrange laptop. \* for an `O((prod(N)!)^sum(N))` complexity algorithm [Answer] # [><>](https://esolangs.org/wiki/Fish), 66 bytes ``` 1}:?\~l1=?v{! -:?!\:{*}1 v?( 4:{/}1<o"!"n-1 {:,} :{/?%}:+1 \:1-?n; ``` [Try it online!](https://tio.run/##DcgxCoAwDADAPa9oC4KoQVKdopKPdBYFqYPQpcSvR2@8/XwOM1KW9F60SakekMUnrp0SFGndzHVUWu/gQ0aCyoO6v6RR7gkSE0pezAyLTRYtfg "><> – Try It Online") Not efficient, doesn't find the smallest string, and the interpreter doesn't deal very well with extremely large numbers. But at least I tried? Takes input as a list of numbers through the `-v` flag. First it calculates the value of the input by factorialising each number and multiplying them together. Then it finds the largest factorial that divides cleanly into the total and outputs it. Repeat until it either gets a prime, (which it outputs) or a 1 and exits the program. Because of this, it sometimes doesn't find the shortest representation of the number, for example, the test case `7!2!2!7!2!2!2!2!` returns `10!224` instead of `8!8!` because it finds the total is divisible by 10! first. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~240 237~~ 233 bytes This is incredibly inefficient Accepts an array of ints as input Returns a string and chooses the shortest option between, say, `'720!'`,`'6!!'` and `'3!!!'` ``` ->i{f=->n{n>0?n*f[n-1]:1} s=->a{eval a.map{|i|f[i]}*?*} r=->e,a=[2]{e==s[a]?a:s[a]<=e&&(r[e,a[0..-2]+[a[-1]+1]]||r[e,a+[2]])} j=->v{v.join(?!)+?!} u=r[s[i]] while j[g=u.map{|i|i&&r[i]?[r[i],p]:i}.flatten].size<j[u].size;u=g;end j[u]} ``` [Try it online!](https://tio.run/##XZHpcoMgFIX/@xSQzJjFZSJNs5gQH4QwHZpgimOJ45IuyrNb0Jh2CjPA/c69hy2vXr/aE269g6hj7B1kLQ@LSM5jIr2AhoGyCk1ZzW8sBcx/Z1ndiCYmgqp5NFdWrlXuMkwQrTnGBWE0YqGZ9pjb9jQnWiUL3/cQdQgj2tQJKG2aTnB0GZ0pK9Eut/rmJ1chpxGcORFUVoVzUuiNqPXxJlIOEnLB1XACYdu51iJiRjejoVB@nLKy5JL6hfjm@4RU/WpX4cuOy7NliGqzqiwAscjkCSLdJ@5kCSfU1QBBgxZ/0brL6cd79gZuhvwn@PBAy/9wwOguBOjX5qEHaDBbo27jFeziMdDnQ/B5BdEWdknaawt71BeBMShKlqaFRe@P4oKkAQJgIPwiS0VpXtJIwA7L64vYgZGQ@vYh0G1cC3WUl2sfmfhk/vQo@WfGTyU/hxolOj7KkWp/AA "Ruby – Try It Online") ]
[Question] [ Don't you hate it when you can't remember how to craft something in Minecraft? Well, time to remedy that! # Task Your task is to take an input, either as a 1D or 2D list and output what item is a result of the crafting table! # Input You may take input as either a string or a list of length `9` or a 2D nested array. If you take input as a... ## String Each item in the table is 1 char in the printable ASCII character (`0x20` to `0x7E`). To represent an empty space, you use a `-` e.g. `WWW-W-WWW` would be the same as a crafting table like ``` +------+------+------+ | Wood | Wood | Wood | +------+------+------+ | | Wood | | +------+------+------+ | Wood | Wood | Wood | +------+------+------+ ``` You may also take input as a multiline string as long as all spaces are preserved e.g. ``` WWW W WWW ``` ## 1D array You would take the input as a char array where empty spaces on the crafting table would be an empty char e.g. the above table would be `['W','W','W','','W','','W','W','W']` ## 2D array This time, each list represents a line on the crafting table, where an empty space is an empty char e.g. `[['W','W','W'],['','W',''],['W','W','W']]` You can assume that the input will always correspond to an item that can be crafted, and if using array input, you may replace the empty char with any character not used as an abbreviated name. # Output Output will be the item crafted from the input, in any form you want, as long as it is obvious what it means. (Personally, I would use my 1 letter abbreviations of the items) # Ingredients For this challenge, `wood` means wooden planks, not wooden logs. You only have to handle the most common items when crafting. These are the ingredients for crafting but may also be products of crafting. The crafting recipe follows the format `xxxxxxxxx` like the string input above. If an item cannot be crafted, `---------` is placed instead. Some recipes are **shapeless**, meaning that just so long as all items are there, the item will be made. These are denoted be a `*`. An example of this would be `pumpkin pie` (not one in this challenge) that only needs `pumpkin`, `sugar` and `egg` to be made. ``` item name | abb. name | crafting recipe ----------------+-----------+------------------ wood | W | --------- cobblestone | C | --------- sticks | S | ----W--W- iron | I | --------- gold | G | --------- diamond | D | --------- redstone | R | --------- string | N | --------- coal | Y | --------- sugar cane | U | --------- redstone torch | E | -R--S---- paper | P | --------- book | B | ---PL-PP- wool | M | ---NN-NN- obsidian | O | --------- gunpowder | X | --------- sand | A | --------- glass | H | --------- feather | F | --------- flint | K | --------- torch | T | --------- leather | L | --------- material blocks | Z | QQQQQQQQQ (here Q represents any in `[G, I, R, D, Y]` compass | V | -I-IRI-I- ``` # Products This is a list of all the products that you could handle for crafting. if the item is also an ingredient, it will not be included here **but you must still be able to handle it**. Each one can be crafted using only the ingredients above and is designated a unique, lowercase letter to identify it. Armour (`+`) can use any ingredient in `[G, I, L, D]`. Weapons (`$`) can be made from `[W, C, I, G, D]`. As this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") site, however, we need to make these lists shorter. `[G, I, L, D]` is denoted by a `Q` and `[W, C, I, G, D]` is denoted by a `J`. ``` item name | abb. name | crafting recipe ----------------+-----------+------------------ crafting table | a | -----WWWW boots + | b | ---Q-QQ-Q pants + | c | QQQQ-QQ-Q chestplate + | d | Q-QQQQQQQ helmet + | e | QQQQ-Q--- bed | f | ---MMMWWW chest | g | WWWW-WWWW wood door | h | WW-WW-WW- iron door | i | II-II-II- furnace | j | CCCC-CCCC trap door | k | ---WW-WW- TNT | l | XAXAXAXAX anvil | m | ZZZ-I-III axe $ | n | -JJ-SJ-S- sword $ | o | -J--J--S- pickaxe $ | p | JJJ-S--S- hoe $ | q | JJ--S--S- shovel $ | r | -J--S--S- arrow | s | -K--S--F- bow | t | SN-S-NSN- bowl | u | ---W-W-W- gold nugget * | v | ----G---- bucket | w | ---I-I-I- clock | y | -G-GRG-G- map | z | PPPPVPPPP fishing rod | 1 | --S-SNS-N flint and steel | 2 | ----I---K shears | 3 | ---I---I- wood button * | 4 | ----W---- dropper | 5 | CCCC-CCRC stone button * | 6 | ----C---- jukebox | 7 | WWWWDWWWW lever | 8 | ----S--C- noteblock | 9 | WWWWRWWWW piston | 0 | WWWCICCRC pressure plate | ! | ------WW- (W can also be replaced with C/I/G) repeater | @ | ---ERECCC tripwire hook | # | -I--S--W- activator rail | ( | ISIIEIISI boat | % | ---W-WWWW minecart | ^ | ---I-IIII powered rail | & | G-GGSGGRG rail | ) | I-IISII-I stone wall | { | ---CCCCCC fence gate | } | ---SWSSWS fence panel | [ | ---SSSSSS glass pane | ] | ---HHHHHH iron bars | ; | ---IIIIII item frame | : | SSSSLSSSS ladder | ' | S-SSSSS-S sandstone | " | -----AAAA slabs | | | ---CCC--- stairs | < | W--WW-WWW bookshelves | > | WWWBBBWWW carpet | . | -------MM painting | , | SSSSMSSSS sign | ? | WWWWWW-S- cauldron | / | I-II-IIII enchant. table | ` | -B-DODOOO glass bottle | ~ | ---H-H-H- rocket * | _ | -----PXXX ``` ## Scoring As it would be unreasonable to ask you to do all of these recipes, you only have to do the ones that you want! But of course, the more that you do, the better your score. Score is defined as ``` score = length of program in bytes / number of working recipes squared ``` For example, this could be a submission. ``` input() print('S') ``` As you can assume that the input passed will be one that it can handle (`----W--W-`), it will always output `S`, which is equivalent to `sticks`. This would score **18 / 1 = 18**. **You must take input** to be a valid program and you must be able to handle at least 5 **different** inputs. The person with the lowest score wins. # Rules * Lowest score wins * You may take input using any accepted method (function parameters, STDIN etc) * You can only take input in one of the above forms. It isn't too restrictive and should be workable * Standard loopholes are disallowed * You must take input * You must output at least `5` correct results to qualify as competing. * For recipes that are shapeless, e.g. gold nuggets, different combinations *do not* count as different recipes. `----W----` is the same (recipe-wise) as `--W------` and is only 1 recipe. * On the flip side of this, for recipes that use more than one material, such as material blocks, each different material counts as a different recipe, meaning that `IIIIIIIII` is not the same (recipe-wise) as `RRRRRRRRR`. Good luck, Minecrafters! [Answer] # [Python 2](https://docs.python.org/2/), Score: 0.0636347 **715 bytes, all 106 recipes** ``` import zlib,base64 i=input() x=`sorted(i)`[2::5] W=zlib.decompress(base64.b64decode('eNpVUglywyAMfJEeEUPqaoKPQTPFzf8fUq0O6iyyLJsFLUhERMOM6Gx0ngj2HWYYijXBiZ6oid8EM7nZYhhW0orvTiS2qxK6PhHCmO+B527UYK3dA5+qVGG13gOf0lyr5YyAUjxN+SZDKPZsLXawXXxKsW3bcNB8wYrC3PWI8X6/7RiMaRlYrhQpCPSnMAIVIisCzSEVgV87yGYgm4FsBrKZJFOSKcmUZEoy1V7mv5KjaxeqRz2Og+i/rE7GaSyAfgtwcxbgOvI2DOB+/gH39ue8rkt2/drF+mfY8CpbVYVk19lT8QOHavXoDo7H/QsSa1Rg9HgXLqWXKEEvRHknIW4ebyqOgHkqhn/2p/JZmJ+s3qV6ledxvGHQP7KqyI9GlejS4lqIvm1AzhCYopmn8OAYTIx3oeKh0KzLsnjy2W1RIMe2YRNzSGH4AwHh7JI=')) d={W[l:l+9]:'SBMaZZZZZikeEVbcebcebcebcddqddqfghjlmnnnnnooooorrrrrs#`4ppppp6qvq_tuw1zy3279058|!!!!@(%q^&/){~}:\'];"><?.,['[l/9]for l in range(0,len(W),9)} if i in d:x=i print d[x] ``` [Try it online!](https://tio.run/##Nctrl5JgFAXg7/4Kq1XqUgdF5WJZoYOCqCAoN7MG5AVe5Y6DwDT9dRtWq2ftT2fvExVXNwzQ@x36UZhc66UHzY5ppAAb1uAEBtHztdmq5ZOn9K0FVhO2ng7oeDw61pRJtX2wwCn0owSkafPf24OJDaujBZoNsInkveMVt4Ja20sa0HshNkJO2O6EeWkT9j7u8RgsitUyna/2Li2u@TW2yHuBc0YZRdPgWZ1CHQuhRdBrPNA111V6YZLtoITGOYcJLjPz@fZ0hOJ7jRtY1Kgdy4tFf@Dwds8rkpFWUPtzvmlL@iMn6OlKNW6qmnOpMjBPmylx05LZQFBYQsUQXIRrQ/S0xN1GM0EK1hQrszCdlRItOzKBFwvN8YfzdJpw@nLOS9zJ3@t0WPRl3M9G3NnIQSyWKO@0IZLQ@MKQCsp2rrdTbjp8xqKP/LSNOMyAfAZEcrmiiJXM276tEbPIlDX50ie9HbHlGSNTw8cQZ5BtKhl90SEZR13FisrRdCYyl4BVhsAsYt5hLrEbIGiELHV/2U4HsYx5wMqzBbMVcC4uWHLhgbM09GI28/tU6c60MPIDgqe0HZsPQsC5Pa5cpcG5QJW@yK4BqombUlowQ@rGuPiSnTRarZo1eVEO3thrk8dxQ5quDb0CL4CWzRP4H8uK32I77tnzg0pYSSrph6dhVMHiLP51fb71y2KA4mRvRPx@9@Z782P88xPSevnzOv7ROH5@//XLt4fOoXHwEPJoh0ndq8OgnhiBA5q9jgeCptLqkK3XGrTrsKqscT6BtSiBwbVuHfLj/d7odruqqgrdbuMv "Python 2 – Try It Online") Handles all the specified recipes, including material variations. Creates a dictionary of all working recipes (with length 9). The shapeless recipes are included by sorting the input string, and checking those against the dictionary. Edit: Switched to string compression, and saved 7 bytes in the code thanks to [notjagan](https://codegolf.stackexchange.com/users/63641/notjagan) [Answer] # Mathematica, score: 0.0482378 ~~0.0540228~~ ~~0.0543788~~ 542 ~~607~~ ~~611~~ bytes, all 106 recipes -4 bytes for rearranging compressed data -65 bytes for losing the ability to deal with invalid inputs ``` "4/a[:chwpb?_oqjB%',>!6aM7^s<S@1|dfi~g38y&.nz}25#0r;]`mVe{v)b\"l9(tZE"~StringTake~{#&@@Join@@StringPosition[Uncompress@"1:eJw9UVuOgzAMrHoS9yglsGnUJkAsLYj92wv0/n+dsU3HZoAwfnL7f3f9u14uEtiKFDrIXgHc9IsXaQWEjo/uQDHjFxU6gt0MfiKy7Psuq9CVKVycACcoXrIsEQ6oF3euJBwOw+CNAUwSSNZx9NManSnGmCLmelrRH+R38ebFxO5Tn6wNFGwqjUmtK85rwHOtFVElNsWoh5mV+dbyy2ohQZbcs5hlzXx21MoBlEtbgF8SgzbMqRJJnrGfnviqsZpU7OTcIbUlftzDIIOM8zjP83EcPjy5x29aJRaXUmzekClUk/rUIbsD+2kcspOonKjXhhYaeD0hPbr6AOvmjtk=",#<>""&/@{v=#/.""->" ",Sort@v,v/.(#|##2&@@Characters@"GLIDWCYR"->"Q")}]/9+8/9}& ``` Take input as 1D-list `{"W", "W", "", "", ...}` Expanded & clear version: ``` TableOfNames~StringTake~{# & @@ Join @@ StringPosition[ Uncompress@CompressedRecipeTable, # <> "" & /@ {v = # /. "" -> " ", Sort@v, v /. (# | ##2 & @@ Characters@"GLIDWCYR" -> "Q")}]/9 + 8/9} & ``` The big `Uncompress` is a string table of all combinations, joined together. ``` " WI II IIII WWWW SSSSSSSSSSLSSSSQQQQ QQ QWW WW WW I \ I I QQQ S S W W W WWWWWW S PXXX Q Q S QQ S S CCCC CCCC \ PL PP W WWWWS SSSSS SSSSSMSSSSWWWBBBWWW QQ C WW WW \ NN NN WWWWDWWWW I IIII K S F W WW WWW W W ERECCC S SNS \ N CCC Q QQQQQQQ MMMWWWII II II H H H WWWW WWWW I I S \ C G GRG G G GGSGGRG MM QQ SQ S PPPPVPPPP SWSSWS I \ KCCCC CCRC I S W WWWCICCRC Q S S IIIIII HHHHHH B DODOOOZZZ I \ III I IRI I QQQQ Q CCCCCC GI IISII I Q QQ Q \ AAAAXAXAXAXAXWWWWRWWWWISIIEIISISN S NSN QQQQQQQQQ R S " ``` `StringPosition` looks for matching in a order of: input itself, sorted input (for shapeless recipe), armour, weapon, pressure plate. `# & @@ Join @@` returns the position of first occurence. `/9+8/9` calculates the index in result table and `StringTake` takes the character at that position. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~325~~ ~~322~~ ~~317~~ 316 bytes / 106^2 = score 0.0281238875 ``` 3∫HA"-?%mΛe*▓╔Υι§ā⅜β¬kēōΠ»t ‰CV↓ZΟΚΨpΝ∫3υ≤↕‰č⅛c╚≤Æ⁷/←;[piυ¦╗⌠⁄⁸qη╔@O;┐√)cR█9ιZ׀l»░(■DΛQ-╥76PT─ō4ο3ū^╝/9»¾κλCβ׀+!'▼vw-№█⁷$▒d`Σ⅟Ιž⁴n≡,`!m≤Σ═╥∫Κ‽∆Q>+g=¼⁾⁽D┐?─D○≠6τ╝ZTΞķ⅜∑²V=]4Æ⁴℮lT$¡sψī1 ◄δ)⅞/Σ/Δō»ņe#≥ζz⅛yB÷B⅞⁵Kβn┘g⁵ķ»<§└≡↓θ○‼¼ņΔε⁄z‼Ζ∙Φ6β⅜c≈Νycm!=V○Jεκ~ :I)ΩS‘U9ndW:? ~Δ" $*+-=\x”Z+čøŗ"SEBMZV”+W←,a‽"9╚πw⁽νQσ_‘č┌ŗD}a?□D ``` Explanation: ``` 3∫ 3 times repeat (on each it'll try something else) HA save 1-indexed iteration - 1 on variable A "..‘ push a string of the recipes U uppercase it (as lowercase was ~7 bytes shorter) 9n split into and array of strings of length 9 d load the variable D (by default string input) W get the variables 1-based index in that array, 0 if not found :? ← if [it isn't 0], leaves the input on the stack ~Δ get the ascii characters from space to ~ (inclusive) "..” push " $*+-=\x", the characters that are in the ASCII but not used Z+ add the uppercase alphabet to that (as most of it can't be outputted) čøŗ filter those out "..”+ append to it the uppercase characters that are used - "SEBMZV" W get in the finished string the character at the index gotten before the if ← exit, outputting that , push the input a‽ } if the 0-based index is not [0] (aka if this is the 1st time in the loop) "..‘ push "RDYWCDCIGL" - characters that are either of the groups of Q, J or the pressure plate č┌ŗ replace [in the pushed input, each of those characters, with a dash] D save on variable D - used in the IF above a? if the 0-based index [is == 0] (aka if this is the 2st time in the loop, soon-to-be 3rd/last) □ sort [the previously pushed input] D save on the variable D ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/comp/index.html?code=MyV1MjIyQkhBJTIyLSUzRiUyNW0ldTAzOUJlKiV1MjU5MyV1MjU1NCV1MDNBNSV1MDNCOSVBNyV1MDEwMSV1MjE1QyV1MDNCMiVBQ2sldTAxMTMldTAxNEQldTAzQTAlQkJ0JTIwJXUyMDMwQ1YldTIxOTNaJXUwMzlGJXUwMzlBJXUwM0E4cCV1MDM5RCV1MjIyQjMldTAzQzUldTIyNjQldTIxOTUldTIwMzAldTAxMEQldTIxNUJjJXUyNTVBJXUyMjY0JUM2JXUyMDc3LyV1MjE5MCUzQiU1QnBpJXUwM0M1JUE2JXUyNTU3JXUyMzIwJXUyMDQ0JXUyMDc4cSV1MDNCNyV1MjU1NEBPJTNCJXUyNTEwJXUyMjFBJTI5Y1IldTI1ODg5JXUwM0I5WiV1MDVDMGwlQkIldTI1OTElMjgldTI1QTBEJXUwMzlCUS0ldTI1NjU3NlBUJXUyNTAwJXUwMTRENCV1MDNCRjMldTAxNkIlNUUldTI1NUQvOSVCQiVCRSV1MDNCQSV1MDNCQkMldTAzQjIldTA1QzArJTIxJTI3JXUyNUJDdnctJXUyMTE2JXUyNTg4JXUyMDc3JTI0JXUyNTkyZCU2MCV1MDNBMyV1MjE1RiV1MDM5OSV1MDE3RSV1MjA3NG4ldTIyNjElMkMlNjAlMjFtJXUyMjY0JXUwM0EzJXUyNTUwJXUyNTY1JXUyMjJCJXUwMzlBJXUyMDNEJXUyMjA2USUzRStnJTNEJUJDJXUyMDdFJXUyMDdERCV1MjUxMCUzRiV1MjUwMEQldTI1Q0IldTIyNjA2JXUwM0M0JXUyNTVEWlQldTAzOUUldTAxMzcldTIxNUMldTIyMTElQjJWJTNEJTVENCVDNiV1MjA3NCV1MjEyRWxUJTI0JUExcyV1MDNDOCV1MDEyQjElMjAldTI1QzQldTAzQjQlMjkldTIxNUUvJXUwM0EzLyV1MDM5NCV1MDE0RCVCQiV1MDE0NmUlMjMldTIyNjUldTAzQjZ6JXUyMTVCeUIlRjdCJXUyMTVFJXUyMDc1SyV1MDNCMm4ldTI1MThnJXUyMDc1JXUwMTM3JUJCJTNDJUE3JXUyNTE0JXUyMjYxJXUyMTkzJXUwM0I4JXUyNUNCJXUyMDNDJUJDJXUwMTQ2JXUwMzk0JXUwM0I1JXUyMDQ0eiV1MjAzQyV1MDM5NiV1MjIxOSV1MDNBNjYldTAzQjIldTIxNUNjJXUyMjQ4JXUwMzlEeWNtJTIxJTNEViV1MjVDQkoldTAzQjUldTAzQkElN0UlMDklM0FJJTI5JXUwM0E5UyV1MjAxOFU5bmRXJTNBJTNGJTIwJTdFJXUwMzk0JTIyJTIwJTI0KistJTNEJTVDeCV1MjAxRForJXUwMTBEJUY4JXUwMTU3JTIyU0VCTVpWJXUyMDFEK1cldTIxOTAlMkNhJXUyMDNEJTIyOSV1MjU1QSV1MDNDMHcldTIwN0QldTAzQkRRJXUwM0MzXyV1MjAxOCV1MDEwRCV1MjUwQyV1MDE1N0QlN0RhJTNGJXUyNUExRA__,inputs=TCUyMExMTExMTEw_) or test by running the following (which will say what's wrong): ``` var arr = ` WW !\n CC !\n II !\n GG !\n AAAA "\n I S W #\n W WWWW %\nG GGSGGRG &\nS SSSSS S '\nISIIEIISI (\nI IISII I )\nSSSSMSSSS ,\n MM .\nI II IIII /\nWWWCICCRC 0\n S SNS N 1\n I K 2\n I I 3\n W 4\nW 4\n W 4\n W 4\nCCCC CCRC 5\n C 6\n C 6\nC 6\nWWWWDWWWW 7\n S C 8\nWWWWRWWWW 9\nSSSSLSSSS :\n IIIIII ;\nW WW WWW <\nWWWBBBWWW >\nWWWWWW S ?\n ERECCC @\n SSSSSS [\n HHHHHH ]\n I IIII ^\n PXXX _\n XP XX _\nX XP X _\nXXXP _\n B DODOOO \`\n G GG G b\nGGGG GG G c\nG GGGGGGG d\nGGGG G e\n I II I b\nIIII II I c\nI IIIIIII d\nIIII I e\n L LL L b\nLLLL LL L c\nL LLLLLLL d\nLLLL L e\n D DD D b\nDDDD DD D c\nD DDDDDDD d\nDDDD D e\n MMMWWW f\nWWWW WWWW g\nWW WW WW h\nII II II i\nCCCC CCCC j\n WW WW k\nXAXAXAXAX l\nZZZ I III m\n WW SW S n\n W W S o\nWWW S S p\nWW S S q\n W S S r\n CC SC S n\n C C S o\nCCC S S p\nCC S S q\n C S S r\n II SI S n\n I I S o\nIII S S p\nII S S q\n I S S r\n GG SG S n\n G G S o\nGGG S S p\nGG S S q\n G S S r\n DD SD S n\n D D S o\nDDD S S p\nDD S S q\n D S S r\n K S F s\nSN S NSN t\n W W W u\n G v\n G v\n G v\nG v\n I I I w\n G GRG G y\nPPPPVPPPP z\n CCCCCC {\n CCC |\n SWSSWS }\n H H H ~\n W W S\n R S E\n PL PP B\n NN NN M\nGGGGGGGGG Z\nIIIIIIIII Z\nLLLLLLLLL Z\nDDDDDDDDD Z\n I IRI I V`.split("\n"); toLog = ""; arr.forEach(f=>{ inputs.value = f.substring(0,9); runClicked(); correct = f.charAt(10); got = output.value; if (got != correct) toLog+= "\""+ inputs.value +"\": expected \""+ correct +"\", got \""+ got +"\"."; }) console.log(toLog); ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score 0.00173611111 4/(48^2) = 0.00173611111 score ``` OṢḄỌ ``` Takes input as string with hyphens for empty space, e.g. `-----WWWW`. I think this is valid because the challenge says > > Output will be the item crafted from the input, **in any form you want**, as long as it is obvious what it means. (Personally, I would use my 1 letter abbreviations of the items) > > > The 1 letter abbreviations are about as confusing as what this outputs, so this output is obvious enough what it means. This assumes the input can be one the program can handle as specified by > > you can assume that the input passed will be one that it can handle > > > [Try it online!](https://tio.run/##y0rNyan8/9//4c5FD3e0PNzd8////6ioKF1PXU9PTwA "Jelly – Try It Online") [Test Suite](https://tio.run/##bVWxcttGEO33K1C4cnJp8gGJRCk0pEg0BU8kqzsAJxLmEYccjqTTKZ7MqEgadyniJqk8Y7tJNBOPXFGTDyF/RNnFgUsA9AHE3OBx7/aw7719obT@6WF198/96/Wrd8vb4frnT6uP79fXf@xpHczy7MeZ@iZYX78BfCVonOPAeWLllcvyUeBkrFUQeHgohnjjPDbGlcEXwWbgq@FwyHAh8x1YDP2gxceqdIWWTvn/cDRugfOx0lPltuF@75OTE59arNKgOfAVJc2Z0@JtuIdD0APnVzOby0Q14Yu9@sL5s9Nn3cUvLy9FKMIwxLnM55luw@LoSER4U@bypQoedWFBdwWXC2PTxh/w1RFF13CRJZPmChUsGB6bzy6@gcuxmSu9/QfBxxX8XZWatWbRjo5OET3FZ1XQRffcRIbq8rDehUVf@IqNjE6DfDYaYdkeMxxWF0XPkoly7ei@6J/hj@BEm2TSXvwpjh/ogfOpLHZTi0R0islTQbNyTES1Jm2mFuLvmGCd5S6QeRqUTuH32aQmfGrlWElb7hzsvD7YwuCq8cw5k28OVpPpjMiUWlMUynaje3V0iWGqEV4z9aBm6ovZRMXmZTc6ogVwrtW8sTRHn9XRuXEqbnw5D/fCOrUio927Bzs8O/QysKpQqD/bhMNq76rezmbFIrMqGBsz8XAYheFhiE8iU@KyuXTGBlaSHpgttUKNdLtsqTRE0dMsV4m0rgEjE/pRHxlBmZuFsqhxv7TfW9DG@KTMZfYZKvZ6tb79N19IrZtwdB7hTXRQOYp/RNbThKvBMNqX0g34STWI51qWZQW3DhbWB8ssfvF4yyfSGI7v68Uzp6bBlZXTbXTktxYEa5mmzYJvHHkPBx0MOewP1zl3zTUt47LDFnJz4UtSOpl1eI7A/v7@pmJmglLQc1W29ibbJYVKW3QETGmf1AcrJGqMNNhmKm7unSkb5Z2KUUE3dEjkTKd2y1Xae18cDA4GgwHOsSJjbCdftTvRk@riksTGOa2amT@9uCA/t6aynsfbxd8s32br699Xd78uP8Dyb@qNN9gbHwarj3@u/v1ldfcb9cvl7Zf3N8fLW0Tg/ua/T99@vfzrOXbO@9fnj54/PPAWwHoH9g1gawRuqcAdDLhZAfcl4BYE3G2A3RvYqIE9Gdhfga0U2DWBDRLYC4FtD9jCgO0I2HmATQbYT4CtA9glgA0BWPvAMgdWNLB4gXUKLElg9QELDVhTwPIBVgqwKID5D0x1YFYDExiYq8C0BGYgMNmAefU/ "Jelly – Try It Online") (Header and footer prettify the output) This does all 48 recipes and gives their names. **How it Works** This is really just a really poor hash function. ``` OṢḄỌ - main link, input e.g. ZZZ-I-III O - character codes e.g. [90, 90, 90, 45, 73, 45, 73, 73, 73] Ṣ - sort. This helps shapeless recipes and keeps recipes such as TNT in CJK e.g. [45, 45, 73, 73, 73, 73, 90, 90, 90] Ḅ - convert from binary to integer e.g. 26670 Ọ - chr: convert from integer to character e.g.栮 ``` ]
[Question] [ **Closed**. This question is [opinion-based](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it can be answered with facts and citations by [editing this post](/posts/130434/edit). Closed 6 years ago. [Improve this question](/posts/130434/edit) [Lorem Ipsum](https://en.wikipedia.org/wiki/Lorem_ipsum) is placeholder text used when preparing layout without wanted to have content already filled. One of its key features over using some arbitrary text is **that it is nonsense**. It isn't even valid latin (though it is close). This prevents anyone being shown the layout from becoming distracted reading the text. The other key feature is that **it looks like real language**. The words are the right length, and the characters occur with the right distributions. A problem is that the Lorem Ipsum is not necessarily good gobbldy-gook for all languages, or even for all subject matter. We expect that the distribution of letters would be different in a novel, than in a scientific article. Your task thus is to create a tool that when given an example of text, generate a lorum ipsum style gobbldy-gook that is a suitable imitation of the characteristics of that text. ## The Task Given an input in UTF8 text *input-text*, and a number x. Output x characters of gobbldy-gook following the style of that text. It may be assumed that words are separated using the space character in the input text. You may take the input in any reasonable form (though it must be able to accept UTF-8). Eg reading from STDIN, reading from file, as a string passed to the function etc. Similar for output. ## Critria * Must not be real correct text in the language of *input-text* + In particular must contain no words with more than 3 characters from *input-text*. + This can be trivially avoided by using a hashset to ban all words from *input-text* from occurring in the output * Must look like it could have been real text from the language of *input-text*. + That is to say it must have the correct letter and word length distributions that is convincing to the eye of the reader. - It is up to the implementation if they take this to mean unigram, bigram, trigram or other statistics for the distributions. - The goal is for it to look right # Judging Texts For purposes of judging please provide 256 characters of output based on each of the following public domain texts: * [De Finibus, Book 1, sections 32–3, by Cicero.txt](https://gist.githubusercontent.com/oxinabox/5b97e884d5a134eafd0975a3add4ffec/raw/d62df2235d4dcd683a51204d616f52b54ad59610/De%2520Finibus,%2520Book%25201,%2520sections%252032%25E2%2580%25933,%2520by%2520Cicero.txt) * [Pride and Prejudice, By Jane Austen](https://gist.githubusercontent.com/oxinabox/5b97e884d5a134eafd0975a3add4ffec/raw/d62df2235d4dcd683a51204d616f52b54ad59610/Pride%2520and%2520Prejudice,%2520By%2520Jane%2520Austen.txt) * [Die Verwandlung, by Franz Kafka](https://gist.githubusercontent.com/oxinabox/5b97e884d5a134eafd0975a3add4ffec/raw/d62df2235d4dcd683a51204d616f52b54ad59610/Die%2520Verwandlung,%2520by%2520Franz%2520Kafka.txt) * [The Magna Carta](https://gist.githubusercontent.com/oxinabox/5b97e884d5a134eafd0975a3add4ffec/raw/d62df2235d4dcd683a51204d616f52b54ad59610/The%2520Magna%2520Carta.txt) [gist with all files](https://gist.github.com/oxinabox/5b97e884d5a134eafd0975a3add4ffec) Those that these are all UTF-8 encoded, and in particular Die Verwandlung, being in German uses many characters outside [a-zA-Z] [Answer] # Clojure This was hard! I started this last night at 9pm thinking I could knock something quick out, no problem. All the little problems I didn't realize when I started began to pile up though, so I had to put it on hold until this morning. It's still not great, but it does the job. Note: For some reason, IntelliJ/Cursive's REPL (which I used to test and generate the phrases) can't accept code greater than 65k chars in length, which means I couldn't simply paste some of the sample texts into the REPL. I tried reading them from file, and for some reason accented characters aren't being read properly, despite specifying UTF-8 encoding. As a workaround, I used subsets of the texts to act as the sample to generate from. * De Finibus: > > vitsmai qomsme tainrte,e qanerim toaurtatt roliaum veaiieq foimpq smarsu mneurutds drtameitt vndnceui cesolleqd Ambrsuou hntumetni euuhcqitu eoseiuane fusipdm,t depamme vofuuet uamsel aumsatet aaee.idu, metosa etqirtai ialisua vsleataa vellpuen aalui, celaqa eultnsec celili eolisi,t qcrm,qets qolniani earure elfucnsn donate qitua,at. aimaau dmgaim aeumltn qori,et cogerentt serlitmt. uaqua,dr aososlt dulir,m oelmmc ietiqctti aupniuon semionu aerciamti qlmomi hinldt htnuaiqa cnnoot cetultad nutcliaa aolstu puouru nfiuitmiu lapopttr rxsutea ood,rut aiseuc quoe.rmi ntiemhb ueter,sb delsrias titopduto qurorcd,t vxiupsi sem,reer iaeesit, mooila eolnoa infosmese exni,uns qtnpeet peiealna lolopt duosrtun oufmttn omsarhdsa veri,rme doilrnt hulstqo cxlusa uasputua qtlpl, certppmtd qopu,tmi oonires oosoia fu,iepa eedumtn,e sesiot,t rtioeam helnora rrnoeeas aslceiist ealimtdd qolsmnas eetgoeta tomema eemurst exoacumtn tuioeq,sa vtauctdst oarittsbt lonpstoa, famade,qa empoenuti minisatie vuiuseuis bxnmii nafuiemsi plscrt vusuiiu macirs cugaesa vttsitm dumudta ruluiqu easimin vsceicnt tuqmeiuns aoitm, inaulnac vfsioe,nu iomistaa. qalisi lanurr eiutma qesbtdi eprurni qintp,iim iuiamt setuoteee qugpeau hfge,e eosqpe dicemte vamerdm noluisi euceaaa eliiutii iinnat ioiuraa aubie,uat ctret,u ruaemi,a, noq,re dupiet eugesr nsnosema ouseipon qasupeeci axtilemt aaaedmdni tssimac ouptpicii notunein qiclo,ist eetummea aelste aictd, vanerean qulurus fenumit, ciieriste dtascec eolirliee bemuam qactiiaei cirudadn qupespase eerqednb vaiimua ltmemsia mucnpu qpmttea militu outpeqct caiomeetu mid,semd ailudtm eumcpri duniics negusqat nunnsu nobod,ntu aoss,it mopaueta dubupntao Seluoiatd atteresc ouisrmn mutdri ee,iri lonoeuo meirqudi montutut qre,ain foitute vaiupmi seilpusin eaoeei,i eetldidse heguise fetbra,sd deri,ssai qirrpcua dothii qiioutub dol,iem moacdss uocr,iit eassrreti ilouptutd qtgupc qiuicet vtiusitam aesupti qaileats qobeee, qornstesi tucpmitna sunuoqdt noclunmc eopisstr aicnppts suuimtett telom, ontimtc aosoren,i stbirstre qpctd,tb aunviu eapaott dnrutmt eoiure iiliei sulootitd iepidtsb, excpraii factm,tse outittt fbgira suaapeiut atniiet vuiireo vtes,eisi qtseueai qour,ea > > > * Pride and Predjudice: > > eoonr. Wosr sotd. siwlt aaaer” ohe” osxalp shrprc afel nhsn ttydt aetr ohtti aotu.n tonl bouno Inui woptur weomtf hhnars ohte oisms Laurl \_nje\_y thr\_ Mofl,d aist! *rdne snage iasi mier.n onen bolh myyier Nont,c hian ihl!i Bcs””r aoei jewesr Msuwh wodeed aiuwdd arssl” efae mosnlb fuqet onsm “e,eeo vereen roor tlrli” nm.p tsrtid auitl aigm yhru shurr sontav yene. esug hoyvot “odhg ahenke coufn hhcer mike:l mfol heae oadiai iooi fotzdf piey ofu? shn,tc Iied Ihnrg mhoihs naurn IIahkk mosi nfolc Mfekei gieu deoei iHnu ivtu huuti Bo.tsi rysnei mirvn ered are,e ooel wIae Temmoe qoyu fetee, ynhd nontui hgnw aaye fet.kd irro “gtp noatk inrn* isdstt tDun thde ohulie watw teness veeee, Mhntsr sai.s Lodue Iteref niergr thst luegn tsuned wii,e, taes iemtsh lhuhs ys..s hahie eehren unet haettd fam.i thurl Lptm *our hftle ar.nna ayeoeg hem.,r whnn oner foiet- Bhfe “o.mll thue yoyh cory aean Mehg ho,ncs falntn nstu tnse,. dnutni weuee olmpt ay.nnu coeso lyeteg ancy,p iffg ihele Ooreen arrn “akyan tttn cxno nomi “heh momee an.ra tosts, Efee afi! arow ynele io.z teocr aids sore ioog shrr hmrve aynri Braus guaein bouree lupa aB,.t inru hnuu todnl thdiyi hvanwa botvu hidiet Nilie toa.y wothn. nesth Ioia* mhoob whdr tYen oosl yehg Molt mokdn gonetf shrle toieg tooet He,lh bu.ead datog “aru atre soym eiomar yose mome htas, Lonr “otets oidrsi hwanes yimr! anelsh Bhst tNn; fhang, talp mirn “oklbt “eod” dorhit hopc ieddn Maae Bnelp tuuovg iWne co,ye ghsee fa!rn MTenee vodnr hu.a aatrel hoehs yfnmc Meog oenec prrn ieuwae “olei > > > * Die Verwandlung: > > inrter Bninrl aäshsi zictth ztgtee.n ireztnr ereoo«de dlifc su,rienn dicgi! duechre gädkean iafiu hbrhür,e öamk, auehse, fhgltr ernsme urcttm uGmartrt eacge wungu eeelle üaise,n dantrid s-ßenn Tamrsd, ierosne fifn, satfg decnt Firüncr goztfekh urcfenl zrg,t donet fartan eishgta eo,dt mrnagks Cutterc iirlo uufbea Wsnhdh hages iicrelnn wimbs wickon Pehuelö? uuertn eleezn üewnlnäe zeiüriti Pidhi Feldaet Banec ahleßelk Nanpüehn eedeuh elflt aüagn mogteäg wehhhorr for,tt h-trtlg öoßdrit Teaue aaedeee necmär vingrrha hai,h vidos ncsne,ne nurlurns Uomeer vrrecoü kcphtd uhrleßl neeke dcrhth amämtza dehbsn Meftet,e dnlwenei Gigrser zagnüe srrcse Wenstt asnbhn Zägele Eebeefn eerhte dihee Nernta. saheter Uihöu fitfu aibeeens Einre Banwf vaneine eardtg fnebtn Sihne hontn hemte, uecßred arrdhe dollnän. Juhno gasdee eeelhn wonlht Aänsüenr vlrssf Dowtlhin Ueeseasl iusnu namhie Binziae wieleet bucdrne maselort Süfiwr strzgdlg dGnite sifgh iusecti Dohutl eucl.g Bbrstnih amehn,üc sarlhe vcredrne krlnat dbrnra enimsnhs larwrn docdää karho Zaths »ersnnhf weire Tirhee drrhm?s iesetehu ialneke geihc disege larsuet, mrintm Ginhdrhe eoieu Msitpn rarzeut, eahßl düernäde eugchn enean zenüor dertnhe Inheuer dlctßcim fitimok hrrsnec säscl Seletete grßrtdce Kunenh bameänßn Wirmg heluhst Uensi gärnre döarrct wrnw,wel datbc Raree lonse mcrseuf aetoet rrncär wrcgelm saste Zirpe uewl,t wceeeskr Aismttme ketfer hnssen Pind,e, einsr?e! diflec mlrlcnft »umgeiß sär,ed nodfst Hbdßen Weensel finhedd lunnt dehsnrg fibsin.a hictfet« vrgturs lehntnm leektfrf brehrrnd brlen eorfem srsgenrn Ditreeen girzee iigeenie devr, daelmrs eanlecse iootohca durgt dalmce srzsh dihrugnt Bbtrwsg iDre,nil aeegesüt Irfcdr etcnruec mlaznegc setirkh Sehteeec kinlaret Ubetetlc gnßfeot eieiuen kantgr wackt -usltrm kereä eerben sahendfh nusarnd ialaac decfear hofüei wbmtee! srnper eegik nünnh woiieb« derlee« dregeeee danhele deetpi gmraeeg esaaez z-täe > > > * Magna Carta: > > giotei ooeleeg majegcg aorses fernpt sekml mhmt,p tfaGta deoel (n8rsse andpi ufaih fnoseu efaes hhod,i wieer hogd,e boeer `soin IwsoRei bed)t fogds tipdfr neylnme ouehps oedhhem Chuaee hst)sr oascs werooen ou'hin hhansn ofecdsd towsof alee, lube'a Gosisfr boceeae ahdbee laaeh tngdc hheoTct (oyce ouedoe' dnysscg beenru hocOo Jshlsee kralse juili`haerhs walreno (nlln troll onoplat dw9ed senroc aolpmdt toedhh gerdc eiype beilsr gbeibet pedns le.rsu aamtnon aoenri tsiaey torrtv oamle snvsn faaorw dhrss arrber Thvsat rafgmu thnslp pnnril rfrsrt letol whhle Ifoehog fhaeos. trthon fukmrnn hnkei otrvt bieyl armbs mneh, felycmg weter mfhte direon' Ma0slo leelo ane'r hneh, Fress snurwe seaoas poevoc, dasee heeeic, efn)lss gtct- eo9laip wnrrlit lyyei, gndosti oecoe suroe taftu bieel feolrg oortefd loatfv -rleln tacblst Nnrcr nOnnr rtimhc toahlfe Wirrn brfbo aecrhb whehri ohnmi walnn oeorlfs rhpsene cauppn woitsns toynr heapihd oanetd ofghen Nfesrtf gamerg desolsf gr.roeb i9drnf uodthn tnrehne wuae'l iutsse Eonllse poplrsa Ghoel m4teest ffest tauec i3pall, shent, gwadi sitcra ifsoo, Wivwn s1tdeur bagersa fead.,g teseus rncdrne hangss thzel aents ienus, binseae (osa.re trrrs of)io eyfgo, trrml oiado sumsn weygrch ahmlvnn tuednt utepsit iota- Ehe.lm crtlot aet)r crblras aenelf, tupmtae Eelee wtoerrd rfant ifldd fhyalt ffdog thuho tists, teadhl nadtoat tflda, Aielsd otreli trrn,mc feeneut nndcdeu hhnlv lidea, titges afrit wrkor eev)lt, fndni hrmml)d tegvee Ihr,nnf kvqoe cnentr Nedtl onmebba hhwdee eopoi aonthnl aautle uflhu. `Retan shclaer Jostsi *prdz ebnnlc ferde hiepraa oa9)eat lisvyn nilos brslbwe btyson aoncs,`vi,t tntter stret cifgile tuslene kivtle irmie aylrie Faala-e aneies gatoy wuomsne shyah snoio.d afeh'a drfree khvoget wicrsns caves, hheto (blfs sheoue > > > ``` (ns mandelbrot.loremipsum (:require [clojure.string :as s])) (defn rand-word "Generates a random word based on what letters appeared at what index. If the index doesn't exist, it pulls a random character from the sample-text." [length pos-map sample-text] (apply str (for [i (range length)] (rand-nth (get pos-map i sample-text))))) (defn safe-rand-word "Helper that loops while the produced input is in the exclusion set. May get stuck if the sample size is too small." [length pos-map sample-text exclusion-set] (loop [] (let [word (rand-word length pos-map sample-text)] (if (exclusion-set word) (recur) word)))) (defn rand-word-len "Generates a length based on avg-len +/- an amount in the (range (- deviation) deviation))." [avg-len deviation] (+ avg-len (rand-nth (range (- deviation) deviation)))) (defn pos-letters "Records what characters occured at each index of each word." [words] ; A two dimensional reduction. ; The inner reduction takes an existing pos-map, and updates it with information about the word ; The outer reduction combines all the word pos-maps together. (reduce (fn [pos-map word] (reduce (fn [acc [i chr]] (update acc i #(if % (conj % chr) [chr]))) pos-map ; Maps with the index of each letter (map vector (range) word))) {} words)) (defn gobbly [n-chars sample-text] (let [; Split the text into words, then place the words into a set ; to ensure that they aren't generated. words (s/split sample-text #"\s") word-set (into #{} words) stripped-text (s/replace sample-text #"[,.?!]" "") ; Figure out the average word length, then calculate how much ; deviation should be allowed. avg-word-len (/ (count sample-text) (count words)) length-deviation (/ avg-word-len 4) ; Find which characters appear at which positions pos-map (pos-letters words)] ; Generate n-chars many characters by... (doseq [n (range n-chars)] ; ...printing a space, then a randomly generated word. (print "" (safe-rand-word (rand-word-len avg-word-len length-deviation) pos-map stripped-text word-set))) (flush))) ``` Use it like: ``` (gobbly 256 "KNOW THAT BEFORE GOD, for the health of our soul and those of our\nancestors and heirs, to the honour of God, the exaltation of the holy\nChurch, and the better ordering of our kingdom, at the advice of our\nreverend fathers Stephen, archbishop of Canterbury, primate of all\nEngland,") ``` [Answer] # Python 3 ``` import string import random with open('lorem.txt') as f: text = f.read() number = eval(input("Input number: ")) dictionary = ''.join(ch for ch in text if ch not in set(string.punctuation)).split(" ") chars = [] for word in dictionary: for char in word: chars.append(char) chars = list(set(chars)) occurences = {} for char in chars: occurences[char] = [] for word in dictionary: for idx, char in enumerate(word): try: occurences[char].append(word[idx+1]) except IndexError: pass lengths = [len(x) for x in dictionary] result = "" for _ in range(number): length = random.choice(lengths) word = random.choice(chars) for _ in range(length): try: word += random.choice(occurences[word[-1]]) except IndexError: break result += word + " " print(result) ``` Takes text input through a file named `lorem.txt` and number of words through STDIN. Samples: De Finibus: > > bolute moresu xisi libospssev lolu ute tamqump Sercolimo mnci iaerue unt xptemp ptur xiui mumnsc ner citerum hiositius fun Set llu hibol etet mpesi amitap voserata mol iumol ospe pte ell asequmut > > > Die Verwandlung: > > Frehwauchmi « > vo ineic venzundenwasender geitende « > darenenserttem Semint estt Scklode > Zur > g Zen»e Orer urd cher > s > Bet > kun renaunn > > > Pride and Prejudice: > > paime k > hothenoc 5 > “ 230 > erth ZZWedomincab Mrevoueim Vifedrctogei Come Kidi yol qul > “Thant Kie Rag 41 > mf vate 12 > Eled 8 > Dathed 1 > mb Bed > “Y merie xto zasorl h’sh ghasst Wha quce skeniat zan dishond > othing > hare hing din > > > And finally, the Magna Carta: > > wincand zisend > s > Pes CEFured indons fequ dindshay ranen Gofun > OURore ibec 6248 Rofonestheasaven > sul nthal > 232 rend > matyont r > uiconlicend > ucriof 7 ashesevenye Gerd > BEndrouse IIns jurig 20000 UREndit mandira 0000000000s > a > wic 47 Enccet > > > It's not my best work. All I'm doing here is some simple Markov chain recreation of the original text, with word lengths taken from a list of all lengths in the given text. I sort of hoped for better results, but oh well. [Answer] # Python 3 I chose not to assume almost anything about the source language. In particular, I chose not to give any special meaning to anything except for whitespace. Therefore the code doesn't generate sentence-like constructs or valid quotations, but doesn't get worse with another language with different "syntax". The heart of my code is a [Markov chain](https://en.wikipedia.org/wiki/Markov_chain). The first part of `generate()` parses each word of the text, collecting the probabilities that a certain character appears after another one in the text, along with some extra data. The second part of the code then generates words based on those probabilities, along with some validation and modification: * The Markov chain only generates characters that appear after the previous generated character in the source text. * The lengths of the words are distributed as in the input. If the Markov chain does not know how to continue generating a word, it is discarded. * A character must have existed in the current position in a word, both from the start and end. (For example, for input `"a-bcd," e.` a dash may only exist as the third character of a word.) This removes lots of wonky punctuation. After 1000 tries the code may allow an invalid character. * Each character is made uppercase with the same probability that the character in that position is uppercase in the source. * "Real" words are discarded by a simple set lookup. * The whitespace between words is picked from the whitespace sequences in the source. ## Code ``` def generate(text): import random def increment(dic, key, mid = None): if mid is not None: if mid not in dic: dic[mid] = {} dic = dic[mid] if key not in dic: dic[key] = 0 dic[key] += 1 def pick(dic): total = sum(dic.values()) pos = random.randrange(total) for key in dic: if pos < dic[key]: return key pos -= dic[key] words = text.split() markov = {} allchrs = {} lens = {} white = {} poss = {} uppos = {} valpos = {} pos = 0 prev = 0 for word in words: increment(lens, len(word)) if prev: pos += len(prev) whi = text[pos:text.index(word, pos)] pos += len(whi) increment(white, whi) prev = word curr = 0 for p, char in enumerate(word): increment(allchrs, char.lower()) increment(markov, char.lower(), curr) increment(poss, p) increment(valpos, p, char.lower()) increment(valpos, p - len(word), char.lower()) if char.isupper(): increment(uppos, p) curr = char.lower() words = set(words) output = "" while True: append = pick(white) if output else "" wordlen = pick(lens) while True: prev = 0 word = "" valid = True for i in range(wordlen): if prev not in markov: valid = False break for _ in range(1000): char = pick(markov[prev]) if valpos[char].get(i) and valpos[char].get(i - wordlen): break upp = random.random() < uppos.get(i, 0) / poss[i] word += char.upper() if upp else char prev = char if valid and word not in words: break append += word if len(output + append) > 256: break output += append return output import os, sys for file in os.listdir(): if file.endswith(".txt"): print(file) with open(file, encoding="utf-8") as stream: print(generate(stream.read()) + "\n\n---\n") ``` ## Output examples ### De Finibus This one is probably the best for my code. Almost resembles lorem ipsum. > > do volllem ptem funsc sumoloduma arec aderodi iupen vonsteretae et, pt atisatus monce qupll remeris sasps am coria cecumaedaii ro an isii da vot esi Erenemonere lo vol lasuama min do oluaecodaer coluse ptrel bea ata, ctati vonditacetes mm oma oventquia > > > ### The Magna Carta Looks a bit like Spanish. > > bl oranr tr wighibintert han ma am mmpe "im noreervetord h > > olandiale tll afin ssh iany hor 48) touro oelllll ce rc ome bl tse pale ota Edeid fonnny," disen oc nd,- kindi ccofore mamar mo hakne fr > > beneth te byse me sur hindesweay > > ane me rciven asho shidi > > > ### Pride and Prejudice Again, English is hard. > > hendver gh th,” > > > te ther y.” wherorath pprmyo it\_t un? stro wam wllyserinof hish ac Wfey’sm sar.” wenenonto ther chu The, L ryo jounddle.” asis i > > fto ok il warano rrithiel > > amsti hes weteran ay.’sthinsti > > merlisomos, asth “llle Hellye yerg > > > mer ady syo > > > ### Die Verwandlung This one looks almost like German, but gets a lot of weird punctuation. > > h > > den. zunder an,« di grhtsck ieit erimie Len De ihttergommkor kkuc aledoht hrserogo ereschla Ateg seneichier-,« gonu imori hr sch demaßti aglfhl iht Rnde au Igeng,« ding üb ukrtl iemen dein Wehle nkt ieiei Ügenifregr En g mirgs sworer zwi blimmi er,« kb > > > ### The program's own source code ``` what(wils(le uenc rumid dent pp ren ifot inc inos(itpendi pr iss imit wor f uenete me orditp ds ourdinorkemit() ist(whar wori nserev[preval " sp iminderreralin): m um inc ``` [Answer] # Python 3 This code is very heavily based on the [text generation example program](https://github.com/fchollet/keras/blob/master/examples/lstm_text_generation.py) from the [Keras](https://github.com/fchollet/keras) machine learning library. It uses a Long Short-Term Memory (LSTM) recurrent neural network trained on the data to generate the output character by character. I would've written the LSTM implementation myself, but I didn't want to reinvent the wheel when there was already such a good implementation that was capable of performing the task at hand. The input is taken in a file named `input.txt` and is output to `out.txt`. I originally just used STDOUT, but Windows CMD didn't like trying to output `utf-8`. The output could be improved on longer corpuses (i.e. Pride and Prejudice in the four that were given) by increasing the number of epochs the model trained for, but the runtime for a long corpus was already quite high, so I didn't bother doing so. ``` from keras.models import Sequential from keras.layers import Dense, Activation from keras.layers import LSTM from keras.optimizers import RMSprop import numpy as np import random import re PATH = 'input.txt' DIVERSITY = 1.0 text = open(PATH, encoding='utf8').read() print('Corpus length:', len(text)) chars = sorted(list(set(text))) print('Total chars:', len(chars)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) regex = re.compile('[^a-zA-Z ]') words = {word for word in regex.sub('', text).split() if len(word) > 3} print('Total words:', len(words)) maxlen = 40 step = 3 sentences = [] next_chars = [] for i in range(0, len(text) - maxlen, step): sentences.append(text[i: i + maxlen]) next_chars.append(text[i + maxlen]) print('NB sequences:', len(sentences)) epochs = max(1, min(20, 200000 // len(sentences))) print('Vectorization...') X = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool) y = np.zeros((len(sentences), len(chars)), dtype=np.bool) for i, sentence in enumerate(sentences): for t, char in enumerate(sentence): X[i, t, char_indices[char]] = 1 y[i, char_indices[next_chars[i]]] = 1 print('Building model...') model = Sequential() model.add(LSTM(128, input_shape=(maxlen, len(chars)))) model.add(Dense(len(chars))) model.add(Activation('softmax')) optimizer = RMSprop(lr=0.01) model.compile(loss='categorical_crossentropy', optimizer=optimizer) def sample(preds, temperature=1.0): preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temperature exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) probas = np.random.multinomial(1, preds, 1) return np.argmax(probas) model.fit(X, y, batch_size=128, epochs=epochs) start_index = random.randint(0, len(text) - maxlen - 1) generated = '' sentence = text[start_index: start_index + maxlen] generated += sentence for i in range(1000): x = np.zeros((1, maxlen, len(chars))) for t, char in enumerate(sentence): x[0, t, char_indices[char]] = 1. preds = model.predict(x, verbose=0)[0] next_index = sample(preds, DIVERSITY) next_char = indices_char[next_index] generated += next_char sentence = sentence[1:] + next_char generated = ' '.join(word for word in generated.split(' ') if regex.sub('', word.strip()) not in words)[:256] file = open('out.txt', 'w', encoding='utf8') file.write(generated) file.close() ``` ## Examples ### De Finibus > > uos et ndllitilum lollreaces vetnocoptam llpe calateciae dorlstem veluatirem.lu ex ept is eptlet neteceppir idararer laror pt lolor.aesuptis caut doquia fiis solopet sen et at nxt at ex ditor aem oond, eo er di iolletiu pllnetaisec cec caperi mi, nd rorxme > > > ## Pride and Prejudice > > Let us at a too > appear icovoim to seen > adeain and misougnor. Mr. Coilins > count; mander it had nearbaryt tordse sithing > naly mone agains at tullnearn of alfactained, illed the eavougant one; but her tamed a retoufly gilliction of her may nos. Comberuable. > > > ## Die Verwandlung > > rer du nur ers unbeilnmit und wortst zu dinmaunn.« raue gewisch, schof sau damach.« rang, den sie ihrel erspiefen. > > > allech gegan kammer > mihr ihr, als die Gertüs»allen; den > BeHohden, umschof hatee und das höbem In > zu neune Stume, daß vornpiel gemößtigeß, am > > > ## Magna Carta > > s by as by geards, and the improved of we renaiss-fur others > of any restice of by our welr the issuen the > > > ard or is Gid insumed to a sarilly ragalint, marners, sim in. > > > B2. And oney and rentershss lard bagean, > in te heish in af any out itfordedvers foroth > > > ]
[Question] [ You're with your best bud, Jim, at the amusement park and as your favorite ride comes into view, you and Jim exchange glances. Naturally you race to get in line. Unfortunately he wins because you're a golfer and he plays a real sport (sorry friends). In fact, you're so far behind that you and Jim are separated by `x` people. Assuming the line is length `n` and you're at the back and the line zigs and zags every `j` people, at what positions in the line will you and Jim be in the same column allowing you to chat (only one row apart)? # Input 3 Integers * `n` - The length of the line. This number will always be greater than or equal to `j` and will be in the form `y * j` where `y` is a positive integer (the number of rows in the queue). * `j` - The number of people in one row of the line (the number of columns in one row). This number will always be greater than 0. * `x` - The number of people between you and Jim such that `0 <= x < 2j - 1`. Hint: If this number is odd, then your output should be empty. # Output A list of integer positions in the line at which Jim is in the same column as you. 1 These integers can be 0 or 1-indexed as long as you specify in your answer. 2 These integers can assume you start at position 0 or position n-1 as long as you specify in your answer. # Example [![Queueing Example Small](https://i.stack.imgur.com/418cQ.png)](https://i.stack.imgur.com/418cQ.png) In this example, the input would be `n = 9, j = 3, x = 0`. The output should be `2, 5` because your position is 2 or 5 when you're in the same column as Jim # Test Cases ``` [9, 3, 0] -> [2, 5] [12, 3, 0] -> [2, 5, 8] [9, 3, 1] -> [] [9, 3, 2] -> [1, 4] [14, 7, 10] -> [1] [24, 4, 6] -> [0, 4, 8, 12, 16] ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~45~~ ~~41~~ ~~40~~ 37 bytes ``` lambda n,j,x:range(j-x/2,x%2or n-x,j) ``` Pretty much the trivial solution. I just quickly scanned for patterns and found a pattern. 1-indexed, 1 is at the back of the queue. -4 bytes by avoiding ternaries and using an array for the values instead -1 byte thanks to some inspiration from @DeadPossum, by using `and` instead of ternaries or array selectors -3 bytes by switching to `or` in the opposite order. Only works because of 1-indexing Also, crossed out 4 is still 4 on all of the 4s :( [Try it online!](https://tio.run/nexus/python2#LYzBCsIwGIPve4r/ImySoq1FcbAnqT1UtLLi6ugm/G9f17lLEvKF@O6W3264PxxFBHCbXHw96yD4oMA79UkUBSM0uY/jd56oI3PFCUcLI9UWSiE3VwVoXCALURoaZ1v55Wc9WPQfpraiMfVxJsNCUhlwgb7er7yx@Qc "Python 2 – TIO Nexus") [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~22~~ 21 bytes 20 bytes of code, +1 for `-p` flag. ``` c%2?lv-c/2+b*\,a/b-1 ``` Takes `n`, `j`, and `x` as command-line arguments. 0-indexed, starting at position 0. [Try it online!](https://tio.run/nexus/pip#@5@samSfU6abrG@knaQVo5Oon6Rr@P//f92C/0Ym/03@mwEA "Pip – TIO Nexus") ### Explanation This is my original 22-byte version because it's a bit more understandable. ``` a, b, c are cmdline args; l is [] (implicit) c%2? Test c mod 2 l If it's 1 (truthy), return empty list; else: a/b-1 Number of rows in the queue minus 1 , Range(^) b* Multiply each element by b b-1-c/2+ Add (b-1)-c/2 to each element Output in [1;2;3] format (implicit, -p flag) ``` The formula was obtained by observing the pattern for `n=9`, `j=3`: ``` x Output 0 [2;5] 2 [1;4] 4 [0;3] ``` If we take `x/2` (`0`,`1`,`2`), subtract it from `j-1` (`2`,`1`,`0`), and add that to `[0;3]`, we get the correct result in all cases. [Answer] # Java 8 lambda, 101 bytes ``` (n,j,x)->{int[]i=new int[n/j-1];int c=0,k=j-x/2;for(;k<n-x;k+=j)i[c++]=k;return x/2==0?i:new int[0];} ``` Almost-direct port of my Python answer. Range doesn't exist in Java though. [Answer] # Haskell, 43 bytes ``` (n#j)x|odd$round x=[]|m<-j-x/2=[m,m+j..n-x] ``` Pretty much directly ported from the Python answer from HyperNeutrino More well-formatted code: ``` f n j x |odd$round x = [] |otherwise = let m=j-x/2 in [m,m+j..n-x] ``` EDIT: Forgot to mention it was one-indexed [Answer] # C# - 91 bytes ``` int[]r=new int[n/j-1];for(int i=1;i<n/j;i++){r[i-1]=i*j-x/2-1;}return(x%2==0)?r:new int[0]; ``` ]
[Question] [ The formatting order of dates is one of the most complex and divisive issues the world faces today. Some of us vehemently argue that Month/Day/Year is appropriate, considering that's how we say dates out loud. Others loudly proclaim that Day/Month/Year is best, because it puts the terms in ascending order of the duration they represent. Enough is enough. Computers can resolve this dispute simply and fairly. Your code, a complete function or program, will take a date string delimited by slashes, e.g. `12/1/2015`. Note this is the exact format, without leading zeroes and with a four-digit year at the end. * If it's *definitely* Month/Day/Year, e.g. `10/31/1998`, output a text representation of that date in this exact format, with the full month name, day, and year: `October 31, 1998` * If it's *definitely* Day/Month/Year, e.g. `25/12/1989`, output the same sort of text representation: `December 25, 1989`. * If it's ambiguous whether it's Month/Day/Year or Day/Month/Year, output a date that resolves the ambiguity by combining the two possible dates as follows: 1. Create a new month name by taking the first half of the name of the **earlier** month and append the second half of the **later** month. For months with odd length, the first half gets the extra letter. To be explicit, the first halves of the months are `Janu`, `Febr`, `Mar`, `Apr`, `Ma`, `Ju`, `Ju`, `Aug`, `Septe`, `Octo`, `Nove`, and `Dece` and the second halves are therefore `ary`, `uary`, `ch`, `il`, `y`, `ne`, `ly`, `ust`, `mber`, `ber`, `mber`, and `mber`. 2. Calculate the day by averaging the two possible days, taking the floor when the average is not an integer. 3. Output the text representation of this date, e.g. for `10/8/2011`, output `Augber 9, 2011`. If the input date cannot be Month/Day/Year or Day/Month/Year (e.g. `13/13/2013` or even `2/30/2002`), any behavior is acceptable. This code golf, shortest code wins! **Test cases:** `10/31/1998` gives `October 31, 1998` `25/12/1989` gives `December 25, 1989` `10/8/2011` gives `Augber 9, 2011` `8/5/1957` gives `Maust 6, 1957` `9/12/2012` (oddly enough) gives `September 10, 2012` `1/1/2000` gives `January 1, 2000` [Answer] # Mathematica ~~341 304 298 288~~ 293 bytes This uses a pure or anonymous function, that is, a function without its own name. `DateString` returns an error message if the date is ambiguous. `Check`catches the ambiguity and sends the offending date to `DateList`, which transforms it into list of 3 integers (which it believes to be `{year, month, day}`). The month and day integers are sorted by size and used to determine the month and day as per the OP's instructions. `Quiet` silences error printing. ``` t=StringSplit;v=ToString;x=t[#,"-"]&/@t["Janu-ary Febr-uary Mar-ch Apr-il Ma-y Ju-ne Ju-ly Aug-ust Septe-mber Octo-ber Nove-mber Dece-mber"]; Quiet@Check[#~DateString~{"MonthName"," ","DayShort",", ","Year"}, {m,n,o}=DateList@#;{p,q}=Sort@d[[2;;3]];x[[p,1]]<>x[[q,2]]<>" "<>v@Floor@Mean@{n,o}<>", "<>v@d[[1]]]& ``` --- ``` t=StringSplit;v=ToString;x=t[#,"-"]&/@t["Janu-ary Febr-uary Mar-ch Apr-il Ma-y Ju-ne Ju-ly Aug-ust Septe-mber Octo-ber Nove-mber Dece-mber"]; Quiet@Check[#~DateString~{"MonthName"," ","DayShort",", ","Year"}, {m,n,o}=DateList@#;{p,q}=Sort@d[[2;;3]];x[[p,1]]<>x[[q,2]]<>" "<>v@Floor@Mean@{n,o}<>", "<>v@d[[1]]]& /@ {"10/31/1998","25/12/1989", "10/8/2011", "8/5/1957", "9/12/2012", "1/1/2012"} ``` > > {"October 31, 1998", "December 25, 1989", "Augber 9, 2011", "Maust 6, > 1957", "September 10, 2012", "January 1, 2012"} > > > [Answer] # Javascript (ES6), ~~311~~ ~~295~~ ~~282~~ ~~274~~ ~~246~~ 238 bytes ``` a=>(a=a.split`/`,b=c=>e(c).length+1>>1,d=' ',e=f=>new Date(99,a[+f]-1).toLocaleString('en',{month:'long'}),g=+a[0],h=+a[1],i=g>h,j=g>12,k=h>12,(j&&!k?e(1)+d+g:k&&!j?e(0)+d+h:e(i).slice(0,b(i))+e(1-i).slice(b(1-i))+d+((g+h)>>1))+', '+a[2]) ``` **Edit:** Uses `toLocaleString` to generate month names. Change the locale to get results using month names in different locales! **Edit 2:** Now generates two month names instead of all 12! Ungolfed: ``` func = inp => ( inp = inp.split `/`, get = arg => months(arg).length + 1 >> 1, space = ' ', months = key => new Date(99, inp[+key] - 1).toLocaleString('en', { month: 'long' }), tmp1 = +inp[0], tmp2 = +inp[1], first = tmp1 > tmp2, t1greater = tmp1 > 12, t2greater = tmp2 > 12, (t1greater && !t2greater ? months(1) + space + tmp1 : t2greater && !t1greater ? months(0) + space + tmp2 : months(first).slice(0, get(first)) + months(1 - first).slice(get(1 - first)) + space + ((tmp1 + tmp2) >> 1) ) + ', ' + inp[2] ) ``` Example: ``` console.log( func('10/31/1998') + '\n' + func('25/12/1989') + '\n' + func('10/8/2011') + '\n' + func('8/5/1957') + '\n' + func('9/12/2012') + '\n' + func('1/1/2000') ); ``` *Thanks to: [@user81655](https://codegolf.stackexchange.com/users/46855/user81655), [274 => 246 bytes](https://codegolf.stackexchange.com/q/65578/#comment-158888) [@edc65](https://codegolf.stackexchange.com/users/21348/edc65), [246 => 238 bytes](https://codegolf.stackexchange.com/q/65578/#comment-159074)* [Answer] # JavaScript ES6, 204 ``` x=>(s=x=>x.split`/`,[a,b,y]=s(x).sort((a,b)=>a-b),(c=b)>12?c=a:b=a- -b>>1,s('/Janu/Febr/Mar/Apr/Ma/Ju/Ju/Aug/Septe/Octo/Nove/Dece')[a]+s('/ary/uary/ch/il/y/ne/ly/ust/mber/ber/mber/mber')[c]+` ${b}, `+y) ``` Test snippet: ``` F=x=>( s=x=>x.split`/`, [a,b,y]=s(x).sort((a,b)=>a-b), (c=b)>12?c=a:b=a- -b>>1, s('/Janu/Febr/Mar/Apr/Ma/Ju/Ju/Aug/Septe/Octo/Nove/Dece')[a] +s('/ary/uary/ch/il/y/ne/ly/ust/mber/ber/mber/mber')[c]+` ${b}, `+y ) console.log=x=>O.innerHTML+=x+'\n' ;['10/31/1998','25/12/1989','10/8/2011','8/5/1957','9/12/2012','1/1/2000'] .forEach(x=>console.log(x+' -> '+F(x))) ``` ``` <pre id=O></pre> ``` [Answer] # Python 3 (290 bytes) Similar to Ashwin Gupta's answer, but taking advantage of Python's calendar module to avoid writing out all of the month names. ``` import calendar as C M,I,P,S,L,A=C.month_name,int,print," ",len,", " def d(i): w=i.split("/") f,s,y=I(w[0]),I(w[1]),w[2] if(f>12):P(M[s]+S+w[0]+A+y) elif(s>12):P(M[f]+S+w[1]+A+y) else:l,h=min(f,s),max(f,s);P(M[l][:I(L(M[l])/2+.5)]+M[h][I(L(M[h])/2+.5):]+S+str(I((f+s)/2))+A+y) ``` Python 2 should trim a few bytes with integer division and losing the parentheses for `print`. [Answer] # Pyth - 156 bytes Really bad code, and will need to use packed strings, but its something. ``` Kc"January February March April May June July August September October November December"dJhM.g>k12=GsMcz\/?<eJ32++@KthJdtP`,eJeGss[@VCcL2KStMPGdPt`,s.OPGeG ``` [Test Suite](http://pyth.herokuapp.com/?code=Kc%22January+February+March+April+May+June+July+August+September+October+November+December%22dJhM.g%3Ek12%3DGsMcz%5C%2F%3F%3CeJ32%2B%2B%40KthJdtP%60%2CeJeGss%5B%40VCcL2KStMPGdPt%60%2Cs.OPGeG&test_suite=1&test_suite_input=10%2F31%2F1998%0A25%2F12%2F1989%0A10%2F8%2F2011%0A8%2F5%2F1957%0A9%2F12%2F2012%0A1%2F1%2F2000&debug=1). [Answer] ## Python, ~~558~~ 554 bytes A really, really, really horribly golfed example of how to do this in python. Sorry, I'm super bad at this golfing stuff `D:` . It works though. I'm sure there are plenty of ways to simplify this so let me know in the comments. **Golfed:** ``` import math def d(i): l=["","January","February","March","April","May","June","July","August","September","October","November","December"] w=i.split('/') f=int(w[0]) s=int(w[1]) S=" " y=w[2] if(f>12): e=int(w[1]) print(l[e]+S+w[0]+", "+y) elif(f<=12 and s>12): e=int(w[0]) print(l[e]+S+w[0]+", "+y) else: if(f<s): o=l[f] t=l[s] else: o=l[s] t=l[f] o=o[0:int(math.ceil(len(o)/2))] t=t[int(math.ceil(len(t)/2)):len(t)] print(o+t+S + str(math.floor((f + s)/2)) + ", " + y) ``` ***Ungolfed*** ``` import math def d(i): l = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] w = i.split('/') f = int(w[0]) s = int(w[1]) y = w[2] if(f > 12): e = int(w[1]) print(l[e] + " " + w[0] + ", " + y) elif(f <= 12 and s > 12): e = int(w[0]) print(l[e] + " " + w[0] + ", " + y) else: if(f < s): o=l[f] t=l[s] else: o=l[s] t=l[f] o = o[0:int(math.ceil(len(o)/2))] t = t[int(math.ceil(len(t)/2)):len(t)] print(o+t+" " + str(math.floor((f + s)/2)) + ", " + y) ``` Screenshot: [![enter image description here](https://i.stack.imgur.com/rRs8A.png)](https://i.stack.imgur.com/rRs8A.png) [Answer] ## PHP, ~~301~~ 294 bytes ``` function r($t){$e='return date("F",mktime(0,0,0,$o));';list($a,$b,$c)=explode('/',$t);$o=min($a,$b);$m=eval($e);$o=max($a,$b);$n=eval($e);echo(($a|$b)<13)?substr($m,0,ceil(strlen($m)/2)).substr($n,ceil(strlen($n)/2))." ".floor(($a+$b)/2).", $c":date("F j, Y",strtotime(($a>12)?"$b/$a/$c":$t));} ``` I thought I could compete with the Javascript answer. Oh well. I think I could make it smaller and I don't like the code I used for the ambiguous dates. I think there is a better way to do it. Ungolfed: ``` function r($t){ // Eval'd code to reduce char count $e='return date("F",mktime(0,0,0,$o));'; // Split the date list($a,$b,$c)=explode('/',$t); // Get the earliest month $o=min($a,$b); $m=eval($e); // Get the latest month $o=max($a,$b); $n=eval($e); // If ambiguous if ($a<13 && $b<13) { print substr($m,0,ceil(strlen($m)/2)).substr($n,ceil(strlen($n)/2))." ".floor(($a+$b)/2).", $c"; } else { print date("F j, Y",strtotime(($a>12)?"$b/$a/$c":$t)); } } ``` ]
[Question] [ # The Setup Suppose you're given *n* fuses, with 1 ≤ *n* ≤ 5, each of which is a meter long, and where each fuse has an associated burn rate of *N* meters per *D* hours. A fuse can be lit at one or both ends, subsequently extinguished at one or both ends, relit, re-extinguished, etc., as many times as needed until the fuse is fully consumed. You are able to light and extinguish fuses instantaneously, and you can observe the exact instant a fuse is fully consumed (burnt up). A fuse *cannot* be cut nor can it be lit anywhere except at its ends. Such a setup allows for an infinitely accurate timing system, by measuring the time between any two fuse lighting/consumption events. For example, given two fuses with a burn rate of 1 meter per hour, you can measure exactly 45 minutes (3/4 hours) by 1. simultaneously: lighting the first fuse at both ends, lighting the second fuse at one end, and marking the start of your time interval 2. lighting the second end of the second fuse at the instant the first fuse is consumed (30 minutes later) 3. marking the end of your time interval at the instant the second fuse is consumed (15 minutes later) # The Challenge Given a fractional number of hours *t*, and a set of *n* fractions representing exact burn rates of *n* fuses, write a program or function that outputs/returns a truthy value if *t* hours can be precisely measured through systematic burning of the fuses, or a falsy value otherwise. The input to the program can be any of the following: * command-line arguments of the form `TN/TD N1/D1 N2/D2 N3/D3 ...` * a string of the form `TN/TD N1/D1 N2/D2 N3/D3 ...` read from `stdin` or equivalent * a string of the form `TN/TD N1/D1 N2/D2 N3/D3 ...` passed as a function argument * an array of strings `["TN/TD", "N1/D1", "N2/D2", "N3/D3", ...]` passed as a function argument In all cases *t* = `TN`/`TD`, where `TN`,`TD` ∈ [1,10000]. Likewise, in all cases: burn rate for fuse *i* = *N**i* /*D**i* = `N<i>`/`D<i>`, where `N<i>`,`D<i>` ∈ [1,10] ∀ *i*. You may assume there will always be between 1 and 5 fuses (inclusive), and that all inputs are valid and in-range. You may also assume that all input fractions are given in lowest terms. **You may not use floating point numbers with fractional components for this challenge.** That is, if you use floating point numbers anywhere in your application, they may only take on integral values with zero fractional component. # Scoring This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, hence the shortest compliant submission in bytes will be awarded the win. --- ## Example Inputs/Outputs ``` input: 29/6 3/2 2/3 3/5 3/7 7/5 output: true One solution: - light both ends of fuse 1, mark start of interval - on fuse 1 consumption: light both ends of fuse 2, light one end of fuse 5 - on fuse 5 consumption: extinguish one end of fuse 2, light both ends of fuse 3, light both ends of fuse 4 - on fuse 2 consumption: extinguish one end of fuse 3, extinguish both ends of fuse 4 - on fuse 3 consumption: relight one end of fuse 4 - on consumption of fuse 4: mark end of interval (29/6 hours) input: 2/1 3/1 5/1 7/1 output: false input: 5/1 6/1 1/6 9/1 1/9 output: true One solution: - light fuse 1 at one end, light fuse 2 at both ends, light fuse 4 at both ends - on fuse 1 consumption: extinguish one end of fuse 2, mark start of interval - on fuse 4 consumption: relight one end of fuse 2 - on fuse 2 consumption: mark end of interval (5 hours) ``` Happy fusing! :) [Answer] # Python 2, 305 This is the golfed version. It is practically unusable for *n > 3*, as the time (and space) complexity is like *3n2*... actually that may be way too low for the time. Anyway, the function accepts a list of strings. ``` def f(i): Z=range;r=map(__import__('fractions').Fraction,i);R=r[1:];n=len(R);L=[[[1]*n,[0]]];g=0 for m,p in L: for d in([v/3**i%3for i in Z(n)]for v in Z(3**n)): try:x=min(m[i]/R[i]/d[i]for i in Z(n)if m[i]*d[i]>0);L+=[[[m[i]-x*R[i]*d[i]for i in Z(n)],[p[0]+x]+p]] except:g|=p[0]-r[0]in p return g ``` A slightly optimized version can finish the test cases in a couple of minutes. It might still be slow for an impossible *n=5* case though. ``` def fLessslow(i): Z=range r=map(__import__('fractions').Fraction,i) R=r[1:] n=len(R) L=[((1,)*n,(0,))] ls = set(L) for m,p in L: if p[0]-r[0]in p: return 1 for d in([v/3**i%3 for i in Z(n)]for v in Z(3**n)): if any(d[i] and m[i]<=0 for i in Z(n)):continue try: x=min(m[i]/R[i]/d[i]for i in Z(n)if m[i]*d[i]>0) thing = (tuple(m[i]-x*R[i]*d[i]for i in Z(n)),(p[0]+x,)+p) if thing not in ls:L+=[thing];ls.add(thing) except:5 return 0 print fLessslow('5/1 6/1 1/6 9/1 1/9'.split()) print fLessslow('29/6 3/2 2/3 3/5 3/7 7/5'.split()) ``` [Answer] # Python 2, 331 It's a little bit longer than feersum's version, but it's much faster. All testcases together take about 3 seconds on my laptop. A complete search for n=5 takes abount 10 minutes though. Some of the code is similar to feersum's version, but I didn't deliberately copy any code. ``` from fractions import* f=Fraction r=range g=lambda x:h(f(x[0]),[1/f(i)for i in x[1:]],[]) def h(t,x,y): for i in r(1,3**len(x)): c=[[],[],[]] for j in r(len(x)):c[i/3**j%3]+=[x[j]] n,b,w=c m=min(b+[i/2 for i in w]) if h(t,[i for i in n+[j-m for j in b]+[j-2*m for j in w]if i],[i+m for i in y]+[m]):return True return t in y ``` ### Usage: ``` print g('3/4 1/1 1/1'.split()) print g('29/6 3/2 2/3 3/5 3/7 7/5'.split()) print g('2/1 3/1 5/1 7/1'.split()) print g('5/1 6/1 1/6 9/1 1/9'.split()) ``` ### Explanation: The lambda expression g does some preprocessing of the input, like converting strings into fractions, seperating goal time from burn rates and calculating the burn times (=1/burn rate). The function h divides all burn times x into 3 sets n, b and w (n stand for non\_burning, b for one\_end\_burning, and w for both\_ends\_burning). It iterates over all those arrangements (except the arrangement n=x, b=[], w=[]), determines the fuse with the shortest burn rate (save time in m), and recursively call h with updated burn times. In y I save all possible times someone can measure using the fuses. In the recursive call these values also get updated. As soon as I find the value, it terminates alle calls with True. ]
[Question] [ This challenge consists in coding an interpreter for a [Mondrian](http://en.wikipedia.org/wiki/Piet_Mondrian) painting description language (MPDL). ## Language definition The language operates on a stack of rectangles. A rectangle is defined by its upper left coordinate and lower right coordinate. Coordinates must be integers. The stack is initialized with a single rectangle with attributes `(1,1,254,254)` Each command has the following format: `<character><integer>` There are three commands: `v<integer>` : perform a vertical split on the latest rectangle in the stack, at the position indicated by the parameter (as percentage). The source rectangle is removed from the stack and replaced with the two new rectangles that result of the split. The left rectangle is pushed on the stack, then the right rectangle. As rectangle coordinates are integers, fractions should be rounded to biggest smaller integer. `h<integer>` : horizontal split. The top rectangle is pushed on the stack, then the bottom rectangle. `c<integer>` : removes the latest rectangle from the stack and paints it to the color given as parameter. 1 = white, 2 = red, 3 = blue, 4 = yellow ## Challenge Write a program that takes as parameter a painting description and creates a 256x256 bitmap representation of the painted rectangles. The rectangles must be separated with a 3 pixel black line. A one or two pixel rectangle should have his non-black pixels hidden by the border black pixels. The input can be read as a parameter or as a file, up to you. The commands should be separated by a space. You can assume that the input file has correct syntax and does not have trailing or leading spaces, tabs, etc. The output can be directly displayed on the screen, or saved to a file, up to you. The shortest code wins. ## Test The following source: ``` v25 h71 v93 h50 c4 c1 c1 c2 h71 c3 h44 c1 c1 ``` Should produce the *Composition II in Red, Blue and Yellow*: ![enter image description here](https://i.stack.imgur.com/Zmw3O.png) [Answer] # Perl 5 + ImageMagick - 297 Something to start with: ``` sub a{my($x,$y,$X,$Y,$d)=@_;$_=shift@ARGV; /v/?a($d=$x+($X-$x)*$'/100,$y,$X,$Y).a($x,$y,$d,$Y): /h/?a($x,$d=$y+($Y-$y)*$'/100,$X,$Y).a($x,$y,$X,$d): /c/&&"-fill ".qw/white red blue yellow/[$'-1]." -draw 'rectangle $x,$y $X,$Y' "} system"convert -size 256x256 -stroke black xc: ".a(0,0,255,255)."a.gif" ``` Takes input on command line and generates `a.gif`. [Answer] # Haskell - 335 ``` import Diagrams.Prelude import Diagrams.Backend.SVG c=centerXY d((x:n):i)|x=='v'=(b#scaleX s#c|||a#scaleX(1-s)#c,k)|x=='h'=(b#scaleY s#c===a#scaleY(1-s)#c,k)|x=='c'=(square 1#fc([white,red,blue,yellow]!!(read n-1)),i)where{s=(read n)/100;(a,j)=d i;(b,k)=d j} main=getLine>>=renderSVG"a.svg"(Width 256).pad 1.02.c.lwG 0.012.fst.d.words ``` **The program reads the instructions as one line from stdin**, if this is unacceptable let me know. Compiles into a program that takes in flags -w *width* -h *height* -o *outputfile*. Outputs an "a.svg" file, if that's not immediately clear from the code. Since the output is a vector image, it's not 'pixel perfect'. This is my first time working with Diagrams -package, feel free to point out any mistakes I made. Especially any backend that would let me output with less code would be nice. You can see some of the first steps I took when developing the code in <http://paste.hskll.org/get/1737>. It differs from the code above in imports and lacks main since the paste.hskll.org provides its own main and drawing environment. [Answer] ## Python - ~~434 405 377 364~~ 361 My first python golf. This can probably be improved A LOT, so any feedback is appreciated. ``` from turtle import* a=[[1,1,254,254]] for c in input().split(): v,w,x,y=a.pop();p,b,f,g=int(c[1::1]),'hvc'.index(c[0]),x-v,y-w if b>1:goto(v,-w),color('#000',['#fff','red','#00f','#ff0'][p-1]),begin_fill(),[(fd(o),rt(90))for o in[f,g]*2],end_fill() else:a+=[[v,w,(x,v+(((x-v)/100)*p))[b],(w+(((y-w)/100)*p),y)[b]])],a+=[[[v,a[-1][2]][b],[a[-1][3],w][b],x,y]] ``` [Answer] ## HTML + JavaScript ES6 (407) Tested with Firefox 32.0.3 ``` <canvas id=c width=256 height=256><script>r=[[1,1,253,253]] p=x=>r.push(x) o=c.getContext("2d") o.lineWidth=3 prompt().split(" ").map(x=>{q=r.pop() v=q[0] b=q[1] n=q[2] m=q[3],{c:x=>{o.beginPath() o.rect(v,b,n,m) o.fillStyle=[,"#fff","red","blue","#ff0"][x] o.fill() o.stroke()},v:x=>{s=x/100*n|0 p([v,b,s,m]) p([v+s,b,n-s,m])},h:x=>{s=x/100*m|0 p([v,b,n,s]) p([v,b+s,n,m-s])}}[x[0]](+x.slice(1))})</script> ``` [Answer] # HTML+JavaScript (ES6) 335 Too similar to @mika answer - marking CW. * replace with function instead of split...map * spread operator * push 2 values at once * ternary operator instead of function properties ``` <canvas id=c><script> c.width=c.height=256, s=[[1,1,253,253]], o=c.getContext('2d'), o.translate(0.5,0.5), // to avoid anti-alias on straight lines o.lineWidth=3, prompt().replace(/(\S)(\d+)/g,(_,c,n)=>( p=s.pop(o.fillStyle=[,'#fff','red','#00f','#ff0'][n]), c<'d'?(o.fillRect(...p),o.strokeRect(...p)) :(c=c<'i'|2, q=[...p], q[c]=r=q[c]*n/100|0, p[c]-=r, p[c-2]+=r, s.push(q,p)))) </script> ``` ]
[Question] [ A [minifloat](https://en.wikipedia.org/wiki/Minifloat) is a binary representation of a floating-point number that has very few bits. The minifloat in this question will be defined as an 6-bit number `m`, which has the following representation: * 1 bit to repesent the sign of the number. This bit will be `0` if the number is positive, and `1` if the number is negative. * 3 bits to represent the exponent of the number, offset by `3` (i.e. an exponent of `110` actually represents a factor of 23, not 26). + An exponent of `000` refers to a subnormal number. The mantissa refers to the fractional part of a number with an integer part of `0` multiplied by a factor of the lowest possible exponent (in this case, 2-2). * 2 bits to represent the mantissa of the number. If the exponent is anything other than `000` or `111`, the 2 bits represent the fractional part after a `1`. + An exponent of `111` represents `infinity` if the mantissa is `0`, and `NaN` (not a number) otherwise. In the Wikipedia article, this would be referred to as a (1.3.2.3) minifloat. Some examples of this minifloat's representation: ``` 000000 = 0.00 = 0 000110 = 1.10 × 2^(1-3) = 0.375 001100 = 1.00 × 2^(3-3) = 1 011001 = 1.01 × 2^(6-3) = 10 011100 = infinity 011101 = NaN 100000 = -0.00 = -0 100011 = -0.11 × 2^(1-3) = -0.1875 (subnormal) 101011 = -1.11 × 2^(2-3) = -0.875 110100 = -1.00 × 2^(5-3) = -4 111100 = -infinity 111111 = NaN ``` Your task is to build a network of two-input NAND gates that takes 6 inputs representing a minifloat `a` and 6 inputs representing a minifloat `b`, and returns 6 outputs representing the minifloat `a + b`. * Your network must properly add subnormals. For example, `000001` + `000010` must equal `000011`, and `001001` + `000010` = `001010`. * Your network must add and subtract infinities properly. Anything finite added to an infinity is the same infinity. Positive infinity plus negative infinity is `NaN`. * A `NaN` plus anything must equal a `NaN`, although which `NaN` it equals is up to you. * How you handle adding positive zero and negative zero to each other is up to you, although zero plus zero must equal zero. Your network can implement any of the following rounding rules depending on convenience: * Round down (toward negative infinity) * Round up (toward positive infinity) * Round toward zero * Round away from zero * Round to nearest, with halves rounded according to any of the above rules To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores: * `NOT: 1` * `AND: 2` * `OR: 3` * `XOR: 4` Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate. The logic circuit that uses the fewest NAND gates to correctly implement all the above requirements wins. [Answer] # 830 NANDs It uses **24** NOTs, **145** ANDs, **128** ORs, **33** XORs. It always rounds towards zero, it may return either -0 or +0 for zero values, and I believe it treats Infinities and NaNs correctly: * ± INF ± INF = ± INF * ± INF + NaN = ± INF * ± INF ∓ INF = NaN * ± INF + *number* = ± INF * NaN + NaN = NaN * NaN + *number* = NaN Below I have a coded representation of the circuit. I have little experience annotating these types of things, so I don't really know what the typical way to do this is, but every variable is a Boolean so it's clear to see that it describes a circuit. Another thing, I have neither the know-how nor probably the tenacity to try and make a diagram of this, but if there is any easy to use software out there anyone wants to point out I would be interested in taking a look. ``` a0,a1,a2,a3,a4,a5 = mini0 b0,b1,b2,b3,b4,b5 = mini1 neg = XOR(a0,b0) nneg = NOT(neg) na1 = NOT(a1) na2 = NOT(a2) na3 = NOT(a3) a2_a3 = AND(a2,a3) a2_na3 = AND(a2,na3) na2_a3 = AND(na2,a3) na2_na3 = AND(na2,na3) a123 = AND(a1,a2_a3) l0 = AND(a1,a2_na3) l1 = AND(a1,na2_a3) l2 = AND(a1,na2_na3) l3 = AND(na1,a2_a3) l4 = AND(na1,a2_na3) l5 = AND(na1,na2_a3) l6 = AND(na1,na2_na3) a45 = OR(a4,a5) a_nan = AND(a123,a45) a_inf = AND(a123,NOT(a45)) m0 = l0 m1 = OR(l1,AND(l0,a4)) m2 = OR(l2,OR(AND(l1,a4),AND(l0,a5))) m3 = OR(l3,OR(AND(l2,a4),AND(l1,a5))) m4 = OR(l4,OR(AND(l3,a4),AND(l2,a5))) m5 = OR(l5,OR(AND(l4,a4),AND(l3,a5))) l5_l6 = OR(l5,l6) m6 = OR(AND(l4,a5),AND(l5_l6,a4)) m7 = AND(l5_l6,a5) nb1 = NOT(b1) nb2 = NOT(b2) nb3 = NOT(b3) b2_b3 = AND(b2,b3) b2_nb3 = AND(b2,nb3) nb2_b3 = AND(nb2,b3) nb2_nb3 = AND(nb2,nb3) b123 = AND(b1,b2_b3) k0 = AND(b1,b2_nb3) k1 = AND(b1,nb2_b3) k2 = AND(b1,nb2_nb3) k3 = AND(nb1,b2_b3) k4 = AND(nb1,b2_nb3) k5 = AND(nb1,nb2_b3) k6 = AND(nb1,nb2_nb3) b45 = OR(b4,b5) b_nan = AND(b123,b45) b_inf = AND(b123,NOT(b45)) n0 = k0 n1 = OR(k1,AND(k0,b4)) n2 = OR(k2,OR(AND(k1,b4),AND(k0,b5))) n3 = OR(k3,OR(AND(k2,b4),AND(k1,b5))) n4 = OR(k4,OR(AND(k3,b4),AND(k2,b5))) n5 = OR(k5,OR(AND(k4,b4),AND(k3,b5))) k5_k6 = OR(k5,k6) n6 = OR(AND(k4,b5),AND(k5_k6,b4)) n7 = AND(k5_k6,b5) first = n0,n1,n2,n3,n4,n5,n6,n7 i7 = n7 i6 = XOR(n6,n7) carry_6 = OR(n6,n7) i5 = XOR(n5,carry_6) carry_5 = OR(n5,carry_6) i4 = XOR(n4,carry_5) carry_4 = OR(n4,carry_5) i3 = XOR(n3,carry_4) carry_3 = OR(n3,carry_4) i2 = XOR(n2,carry_3) carry_2 = OR(n2,carry_3) i1 = XOR(n1,carry_2) carry_1 = OR(n1,carry_2) i0 = XOR(n0,carry_1) i_sign = OR(n0,carry_1) n7 = OR(AND(nneg,n7),AND(neg,i7)) n6 = OR(AND(nneg,n6),AND(neg,i6)) n5 = OR(AND(nneg,n5),AND(neg,i5)) n4 = OR(AND(nneg,n4),AND(neg,i4)) n3 = OR(AND(nneg,n3),AND(neg,i3)) n2 = OR(AND(nneg,n2),AND(neg,i2)) n1 = OR(AND(nneg,n1),AND(neg,i1)) n0 = OR(AND(nneg,n0),AND(neg,i0)) n_sign = AND(neg,i_sign) r7 = XOR(m7,n7) carry_7 = AND(m7,n7) hr6 = XOR(m6,n6) hcarry_6 = AND(m6,n6) r6 = XOR(hr6,carry_7) carry_6 = OR(hcarry_6,AND(hr6,carry_7)) hr5 = XOR(m5,n5) hcarry_5 = AND(m5,n5) r5 = XOR(hr5,carry_6) carry_5 = OR(hcarry_5,AND(hr5,carry_6)) hr4 = XOR(m4,n4) hcarry_4 = AND(m4,n4) r4 = XOR(hr4,carry_5) carry_4 = OR(hcarry_4,AND(hr4,carry_5)) hr3 = XOR(m3,n3) hcarry_3 = AND(m3,n3) r3 = XOR(hr3,carry_4) carry_3 = OR(hcarry_3,AND(hr3,carry_4)) hr2 = XOR(m2,n2) hcarry_2 = AND(m2,n2) r2 = XOR(hr2,carry_3) carry_2 = OR(hcarry_2,AND(hr2,carry_3)) hr1 = XOR(m1,n1) hcarry_1 = AND(m1,n1) r1 = XOR(hr1,carry_2) carry_1 = OR(hcarry_1,AND(hr1,carry_2)) hr0 = XOR(m0,n0) hcarry_0 = AND(m0,n0) r0 = XOR(hr0,carry_1) carry_0 = OR(hcarry_0,AND(hr0,carry_1)) r_sign = XOR(n_sign,carry_0) s7 = r7 s6 = XOR(r6,r7) carry_6 = OR(r6,r7) s5 = XOR(r5,carry_6) carry_5 = OR(r5,carry_6) s4 = XOR(r4,carry_5) carry_4 = OR(r4,carry_5) s3 = XOR(r3,carry_4) carry_3 = OR(r3,carry_4) s2 = XOR(r2,carry_3) carry_2 = OR(r2,carry_3) s1 = XOR(r1,carry_2) carry_1 = OR(r1,carry_2) s0 = XOR(r0,carry_1) n_r_sign = NOT(r_sign) r0 = OR(AND(n_r_sign,r0),AND(r_sign,s0)) r1 = OR(AND(n_r_sign,r1),AND(r_sign,s1)) r2 = OR(AND(n_r_sign,r2),AND(r_sign,s2)) r3 = OR(AND(n_r_sign,r3),AND(r_sign,s3)) r4 = OR(AND(n_r_sign,r4),AND(r_sign,s4)) r5 = OR(AND(n_r_sign,r5),AND(r_sign,s5)) r6 = OR(AND(n_r_sign,r6),AND(r_sign,s6)) r7 = OR(AND(n_r_sign,r7),AND(r_sign,s7)) h0 = r0 rest = h0 h1 = AND(r1,NOT(rest)) rest = OR(rest,h1) h2 = AND(r2,NOT(rest)) rest = OR(rest,h2) h3 = AND(r3,NOT(rest)) rest = OR(rest,h3) h4 = AND(r4,NOT(rest)) rest = OR(rest,h4) h5 = AND(r5,NOT(rest)) rest = OR(rest,h5) h6 = AND(r6,NOT(rest)) rest = OR(rest,h6) h7 = AND(r7,NOT(rest)) e0 = OR(h0,OR(h1,h2)) e1 = OR(h0,OR(h3,h4)) e2 = OR(h1,OR(h3,h5)) ne0 = NOT(e0) ne1 = NOT(e1) ne2 = NOT(e2) e0e1 = AND(e0,e1) e0ne1 = AND(e0,ne1) ne0e1 = AND(ne0,e1) ne0ne1 = AND(ne0,ne1) x0 = AND(e0e1, ne2) x1 = AND(e0ne1, e2 ) x2 = AND(e0ne1, ne2) x3 = AND(ne0e1, e2 ) x4 = AND(ne0e1, ne2) x5 = AND(ne0ne1,e2 ) x6 = AND(ne0ne1,ne2) u0 = AND(x0,r1) u1 = AND(x1,r2) u2 = AND(x2,r3) u3 = AND(x3,r4) u4 = AND(x4,r5) u5 = AND(x5,r6) u6 = AND(x6,r6) v0 = AND(x0,r2) v1 = AND(x1,r3) v2 = AND(x2,r4) v3 = AND(x3,r5) v4 = AND(x4,r6) v5 = AND(x5,r7) v6 = AND(x6,r7) f0 = OR(u0,OR(u1,OR(u2,OR(u3,OR(u4,OR(u5,u6)))))) f1 = OR(v0,OR(v1,OR(v2,OR(v3,OR(v4,OR(v5,v6)))))) sign = XOR(a0,r_sign) either_nan = OR(a_nan,b_nan) either_inf = OR(a_inf,b_inf) ans_nan = OR(AND(AND(a_inf,b_inf),XOR(a0,b0)),AND(NOT(either_inf),either_nan)) nans_nan = NOT(ans_nan) ans_inf = AND(nans_nan,OR(either_nan,either_inf)) ans_none = AND(nans_nan,NOT(ans_inf)) nans_none = NOT(ans_none) result0 = OR(OR(AND(a_inf,a0),AND(b_inf,b0)),AND(ans_none,sign)) result1 = OR( nans_none, AND(ans_none,e0) ) result2 = OR( nans_none, AND(ans_none,e1) ) result3 = OR( nans_none, AND(ans_none,e2) ) result4 = OR( ans_nan, AND(ans_none,f0) ) result5 = OR( ans_nan, AND(ans_none,f1) ) ``` ]
[Question] [ # Background Mu Torere is a game that is one of only two known to be played by the Maori people of New Zealand before European influence. This makes it a very unique game in that it has an "objective winning criterion" and rules of play that are different from most other games in existence. Gameplay: The board is an octagon. There are connections between each adjacent vertex, and there is a center node that is connected to all of the vertices. At any point in time, eight of the nine nodes are occupied by stones. At the start, there are four white stones and four black stones that are each take up one half of the octagon, with the center node empty. Black moves first. Each turn, a player can move one of his stones along one of the 16 edges from one node to the empty node. A stone can only be moved from an outer node to the center node if the stone is next to an opponent's stone. A player loses when he is unable to make a legal move, which occurs when there is no edge connecting a stone to the empty node. ![A diagram and explanation of the rules](https://i.stack.imgur.com/LoPTo.gif) [Here](http://www.gpj.connectfree.co.uk/games6.htm) is a website that explains the rules (with a diagram) and offers some analysis. # The Challenge Your challenge is to write the shortest program that can play a perfect game of Mu Torere against a human opponent. Your program should be able to display and update the game board, make moves and receive moves from a human opponent. Most importantly, it should play a perfect game. ## Perfect Game? Yes, perfect game. I've been doing some game analysis, and I found that the game lasts for an infinite amount of time if played perfectly by both sides. This means that your program should never lose. Also, your program should be able to force a win whenever the human opponent makes a mistake that allows the program to force a win. As for how your program finds the perfect move, this is up to you. ## Details After each move (and at the start of the game), your program should print the game board. However you choose to display the board, it must show all of the nodes and be fully connected (all 16 connection lines should be drawn with no crossed lines). At the start, the board should have the correct starting position. One way of accomplishing this is by making the game board a square. ``` w-w-w |\|/| b-o-w |/|\| b-b-b ``` The two colors are black and white, or dark/light. The board must show which nodes are occupied by which player's pieces, such as marking them with a "b" or "w", and which node is vacant. Participants are encouraged (but not required) to make the game board more graphical, rather than plain text. Your game board should have a numbering system that gives each node a unique number. You may choose to number the board any way you like, but it should be explained in your answer or by the program. The square board can be numbered as follows: ``` 1-2-3 |\|/| 4-5-6 |/|\| 7-8-9 ``` The human is the first to move. His input will be a single number. This will be the number of the node where the moved stone currently is. If I wanted to move a stone from node 4 to an empty node 5, I will type a `4`. The 5 is implied as it is the only empty node. Assume that the human will always make a legal move. After the human makes his move, an updated board should be printed. After your program decides on a legal move, it should print another updated board, and then wait for the human to enter another move. Your program should terminate once it has won. ## Notes Standard code golf rules apply, no accessing external files, etc., etc. Also, I'm going to impose a flexible time limit of 15 seconds (on a reasonable machine) for your program to make each of its moves. As stated, this game has the possibility to form infinite loops, and I don't want a depth-first search getting into an infinite loop. [Answer] ### Ruby, 390 chars ``` o=->s,c{f=s=~/o/;[*0..8].select{|t|s[t]==c&&(t<1||(t+6)%8+1==f||t%8+1==f||f<1&&(s[(t+6)%8+1]!=c||s[t%8+1]!=c))}.map{|t|k=s*1;k[f]=c;k[t]=?o;k}} v=->s,c,h{f=o[s,c];f==[]?0:h<1?1:2-f.map{|t|v[t,c>?b??b:?w,h-1]}.min} q=->g{puts"1-2-3\n|\\|/|\n8-0-4\n|/|\\|\n7-6-5\n".tr"0-8",g;$>.flush} q[g="obbbbwwww"] (g.tr!?o,?b;g[gets.to_i]=?o;q[g];q[g=o[g,?w].sort_by{|q|v[q,?w,5]}[-1]])while v[g,?b,5]>0 ``` An implementation in ruby which directly calculates the game tree (which takes quite some code) and thus always plays optimally. The board positions are spiraling outwards as shown in the following figure: ``` 1 - 2 - 3 | \ | / | 8 - 0 - 4 | / | \ | 7 - 6 - 5 ``` [Answer] ## bash and friends (463 447 chars) ``` t(){ tr 0-8a-i $b$b } p(){ t<<E 0-1-2 |\|/| 3-4-5 |/|\| 6-7-8 E } g(){ b=`tr $x$e $e$x<<<012345678|t` p e=$x } b=bbbbowwww e=4 m=0 p while [ $m != 5 ]&&read x;do g m=0 for y in {0..8};do s=0 S=05011234 grep -E "w.*($y$e|$e$y)"<<<${b:$y:1}30125876340142548746>/dev/null&&for p in wow.\*/ww wow.\*/w bbo.\*/b obb.\*/b www wbw . do ((s++)) tr $y$e $e$y<<<3012587630/4e|t|grep $p>/dev/null&&break done s=${S:$s:1} [ $s -gt $m ]&&m=$s x=$y done g done ``` Human plays as `b`, computer as `w`. Board position is numbered as in the here doc at the top. It turns out that the heuristics to play a perfect game are surprisingly simple. On the other hand, losing down the interesting path is quite hard. <http://ideone.com/sXJPy> demonstrates the shortest possible suicide against this bot. Note that the extra 0 at the end is to test that it breaks out of the loop correctly. ]
[Question] [ ## Challenge Given a matrix of digits (0-9), find the smallest (in terms of area) rectangular matrix of digits where one or more copies of itself, possibly rotated, can tile the original matrix. Reflection is not allowed (think of a collection of tiles on a wall or floor). Input can be taken in any reasonable ways to represent a matrix of integers or characters. Output format should be consistent with the input, but output in any orientation (out of four possible rotations) is allowed. If there are multiple possible tiles of same area, you may output one or all of them. It is guaranteed to be solvable for any possible input, since the entire input matrix is always an option if no smaller tiles can cover it. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` Input: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 Output: 0 1 2 3 4 5 6 7 8 9 ------------------ Input: 1 1 1 1 1 1 1 1 1 Output: 1 ------------------ Input: 1 2 3 4 5 6 7 8 9 Output: 1 2 3 4 5 6 7 8 9 ------------------ Input: 1 2 3 4 1 4 5 6 5 2 6 5 4 6 3 3 2 1 3 6 1 2 3 2 5 4 5 6 1 4 Output: 1 2 3 4 5 6 ------------------ Input: 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 Valid Output 1: 0 0 0 0 1 0 Valid Output 2: 0 1 0 0 0 0 Invalid Output (because it is an L-shape, not a rectangular matrix): 0 1 0 0 0 0 ------------------ Input: (a hard case, suggested by Arnauld) 1 2 1 2 1 1 1 1 2 1 2 2 2 1 1 2 1 2 1 2 2 1 2 1 2 1 2 1 2 2 Output: 1 2 ``` [Answer] # JavaScript (ES6), ~~354 352 345~~ 342 bytes I/O: matrix of integers. This is quite long but pretty fast -- at least with those test cases. ``` m=>m[b=P='map']((r,h)=>r[P]((_,w)=>(M=m.slice(~h)[P](r=>r.slice(~w)),a=~w*~h,g=(x,y,F)=>a>b|q.some((r,Y)=>r.some((v,X)=>~v?v^m[Y][X]:![x=X,y=Y]))?0:1/y?[...P+0][P](z=>(F=k=>!M[P]((r,Y)=>r[P]((v,X)=>k^1?q[y-Y][x-X]=v|k:(z|=~(q[y-X]||0)[x-Y],T[X]=T[X]||[])[Y]=v),T=[]))(1)&T.reverse(M=T)|z||g(F())|F(-1)):(o=M,b=a))(q=m[P](r=>r[P](_=>-1)))))&&o ``` [Try it online!](https://tio.run/##jZFNc9owEIbv@hXKBbSNcDGQtGVmzanc6DATDjCOkzFEgAO2QSbmYzT8dbKWTUNvNSNp991H767Ne5iH2UxHm10jSd/UZY6XGL3Yn@IQ63G4qQdCaLkE9LQ/pPhV7ikWA4ydbB3NlDgvoShoAq7KHkCGeN5/Oy/lAsVBHmWfLoXe1GydLI1VYTkBe8NmuRxTds57@UvsTwJ/HHTv/AOO5REnAUCv2XW/H3u@4zjD@2ZQtDvRDH1coXc3sGNVfjYu3VYvbm/rHxtkd2iMA8zNqitOBs@iUMeBMU2gyiSQI@qHxWaMHwD1xxzkCCkG4UJt5GiVK50peukRmJMxC9EXAKYvGi5AV6Q4kFMMid5ifP0WxfmKXkHQU6ulF622H5FWoj7P6kCe4Vs/WqunYzITTXB26dNOR8lCgJNt1tFO1J@T54TAeap/h7OlyDh6jPNZmmTpWjnrdCHmIvuCCaW/S2jCuL7KvFL/fMRTpWmQW@Y9jRKLQBUWJvye25PBpcld3uJt3mEP/JH/4D/5L/a/GnNJdP/ZmaVYhxPF/lL2IlWtTKvFir1DcZu1qepS/bHiWvyh4lxqRn3tz/andZOXp1VvcutSrnKmMmsxq5SZZSqKtb6YTw "JavaScript (Node.js) – Try It Online") ### How? Whatever the tiling is, it is guaranteed that each corner of the matrix is also a corner of the tile that we're looking for. The two outer `map()` loops extract each possible tile \$M\$ from the bottom-right side of the input matrix \$m\$ and compute its area \$a\$. ``` m.map((r, h) => // for each row r[] at position h in m[]: r.map((_, w) => // for each value at position w in r[]: ( // M = // build M[]: m.slice(~h) // keep the last h + 1 rows of m[] .map(r => // for each of them: r.slice(~w) // keep the last w + 1 columns ), // a = ~w * ~h, // area = (w + 1) * (h + 1) ... // attempt to do a tiling with M ) // ) // end of map() ) // end of map() ``` We build a matrix \$q\$ with the same dimensions as \$m\$, initially filled with \$-1\$. ``` q = m.map(r => r.map(_ => -1)) ``` At each iteration of the recursive function \$g\$, we look for the position \$(x,y)\$ of the last cell in \$q\$ still set to \$-1\$, going from left to right and from top to bottom. By definition, this cell has either a cell already set or a border on its right, and ditto below it. So it must be the bottom-right corner of a new tile, such as the cell marked with an 'x' below: [![matrix](https://i.stack.imgur.com/WQGXD.png)](https://i.stack.imgur.com/WQGXD.png) Simultaneously, we test whether there's a cell in \$q\$ whose value is not \$-1\$ and is different from the value in \$m\$ at the same position. If such a tile is found, we abort the recursion. ``` q.some((r, Y) => // for each row r[] at position Y in q[]: r.some((v, X) => // for each value v at position X in r[]: ~v ? // if v is not equal to -1: v ^ m[Y][X] // abort if v is not equal to M[Y][X] : // else: ![x = X, y = Y] // set (x, y) = (X, Y) ) // end of some() ) // end of some() ``` If all cells of \$q\$ are matching the cells of \$m\$ and the area of \$M\$ is less than (or equal to) the best area found so far, we update the output \$o\$ to \$M\$. Otherwise, we invoke the following code 4 times: ``` F(1) & T.reverse(M = T) | z || g(F()) | F(-1) ``` The behavior of the helper function \$F\$ depends on the parameter \$k\$: * If \$k=1\$, it computes the transpose \$T\$ of \$M\$ and checks whether all cells in \$q\$ between \$(x-w,y-h)\$ and \$(x,y)\$ are set to \$-1\$. The result of this test is saved in \$z\$. * If \$k\$ is undefined, it copies the content of \$M\$ to \$q\$ at \$(x-w,y-h)\$. * If \$k=-1\$, it cancels the previous operation by restoring all updated values to \$-1\$. It is defined as follows: ``` F = k => // k = parameter !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[]: k ^ 1 ? // if k is not equal to 1: q[y - Y][x - X] = // set q[y - Y][x - X] v | k // to v if k is undefined, or -1 if k = -1 : // else: ( z |= // update z: ~( q[y - X] // read q at (x - Y, y - X) || 0 // )[x - Y], // set z if it's not equal to -1 T[X] = // compute T by writing v at the T[X] || [] // relevant position )[Y] = v // ), // end of inner map() T = [] // initialize T to an empty array ) // end of outer map() ``` Therefore, the code block mentioned above can be interpreted as follows: ``` F(1) // compute the transpose T[] of M[] and test whether & // M[] can be copied at (x-w, y-h) in q[] T.reverse(M = T) // reverse T[] and assign it to M[], which means | // that M[] has been rotated 90° counterclockwise z || // if z = 0: g(F()) | // copy M[] to q[] and do a recursive call F(-1) // restore q[] to its previous state ``` [Answer] # [J](http://jsoftware.com/), 195 bytes A bit long, but blazing fast! There should be some micro-optimizations still left, but I believe there could be an overall better strategy, maybe one without boxes. ``` ((]>@{.@\:[:>./@(*i.@#)[:(#*0*/@,@:=])&>]([:(~.@#~0,@:=(_&e.&,+0+/@,@:>])"2)[:,/|:@|.^:(<4)@[(-~%2*/@,@:>[+&*-~)/@,:"2/(|.~*{.@#&(,/)(#:i.)@$)"2@])&.>^:(<_)<@,:@[)[:(/:*/@:$&>)[:,/<@|:\@|:\)&.:>: ``` [Try it online!](https://tio.run/##jY/BTsMwDIbveQqrHZndtWmadQO8LYqExIkT1670xKTxClR99eKmOwyJAYqc5re//rY/xsQsT3BgWEIOFliiMPD0@vI8IrY@fJpw5Ia9KQNmZxNSahjTzGZlyAMfWtK@RUkNUhrslMJOvxudr@wqIr6lxMlPedlz6M0b476m0GAx3LnZxDcrnRUDieDEldibIZO2qca8JEz5bCgsxCRIM@Mng472woZmmqVkceGF9rHHPvR8nEJQ9jzSiLsTgdWJ2ZnOAcYVSVmowMEaarWBLdzDAzz@O0fqZ89K2OrbfZsUT1WDeKq/PGN38Yq0hFPTXct7rdZSraS@vXAONheukolveVqIJ@4mcaXnb8xeaVK/DDfHvPCsnIqZWUXmQil3xdAX "J – Try It Online") ### How it works ``` &.:>: ``` Add 1 to the matrix, so we can use 0 as a special value. ``` [:,/<@|:\@|:\ ``` Get all possible tiles that contain the upper left digit. ``` [:(/:*/@:$&>) ``` Sort them according to their dimension. ``` ](…)&.>^:(<_)<@,:@[ ``` Use the initial matrix as seed, and execute – with the possible tiles on the left side – until the result does not change, while storing the results: ``` (|.~*{.@#&(,/)(#:i.)@$)"2@] ``` Shift the matrices so the first non-zero digit is in the upper left. ``` |:@|.^:(<4)@[ ``` On the left side, rotate all the tiles. ``` (-~%2*/@,@:>[+&*-~)/@,:"2/ ``` For each tile and each matrix, pad the tile and matrix to the same size (`/@,:"2`). The final result will be the subtraction, but we'll do some checks here by setting faulty results to infinity. With this we later don't have to keep track which tile produced which result. We add the signum of the tile and the matrix, then everything should be 1 (or 0, if the rotated tile stuck out and we added some 0 with padding. But it these cases, as every tile is >0, we'll have some negative numbers there.) We divide the subtraction by this check and it's either the original number or infinity. ``` (_&e.&,+0+/@,@:>])"2 ``` We check if there is infinity in a matrix or a value below 0. ``` [:(~.@#~0,@:=(…) ``` And filter these out. The `~.` is not necessary, but it reduces duplicates and speeds things quite a lot in the `1 1 1,1 1 1,1 1 1` cases. ``` [:(#*0*/@,@:=])&> ``` After the function's result does not change anymore, we have a matrix where each column represents a tile, and each row contains the possible placements for N tiles. We're interested in placements that result in a matrix filled with 0, so we check for them. We now have something like ``` 0 0 0 0 0 0 0 0 0 0 tiles 0 0 0 0 0 0 0 0 1 1 tiles (the right-most tile is the whole matrix) 0 0 1 0 0 0 1 0 0 2 tiles ``` --- ``` [:>./@(*i.@#) ``` We multiple each row with its index and reduce them, so we get for example `0 0 2 0 0 0 2 0 1`. ``` >@{.@\: ``` Using this as an index we sort the tiles, take the first one, unpack it and with the decrement we have the final tile. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~189~~ 173 bytes ``` {{A[⍵]⍴⍨⊃⌽⍵}{{⊃⍵[⊃⍋⍴¨⍵]},↑⍵[⍸(~0∊∊)¨⍵]}{⊃((×/⍵)÷⍨⍴,A){⍺≤1:⊂¨↓⍵⋄R←⍵∇⍨⍺-1⋄,{0<≢R:⍵[⍸{((⊢≡∪)⊃,/⍵)∧((1≡⊃∘⍴∘∪)¨↓{A[⍵]}¨⍵)}¨⍵]⋄⍬}R∘.(,∘⊂)↓⍵}⊃⍪/{(,⍳1-⍵-⍴A)∘.+,¯1+⍳⍵}¨⍵(⌽⍵)}¨,⍳⍴A←⍵} ``` [Try it online!](https://tio.run/##7VE9S8RAEO39FdPdLtnzEuOdetjkL6Q9LA5EmwNtZYmFHjEfrigi2iqCEgQLExTB5u6fzB@JM5soBzY2dkLYnZ33Zt6byXh/0t0@GE/2dutaa4HZMZ5@oKkkmjIYUbAVac1ZU43slRMwe7SAwvjC5s2bPnQxyfgzVdTCXCbE/LrH7eavaChdqkBqNO@Y3ntDzI6IGl8Sjvk0xPhcCMK6nsTkxHrIp0q7m5jehcMvIaGZnt5iUrAWaSgrgMmDEB4D5DK5ISk@k0JaCd3OYq3J1iG1R/MUhURcZlOKDNme1lIkmrmLnhYKzQt7KwPpeF1uIbnIUbNnzyHse2rRbi9qZZQFy4BmY069Q4HGsyu6OtBhAzb@3/xfb76Z9OfmKaa/As2DtjqAPlW54MEK@LAKfRjAGqzDxtICyQefSL@mLJz1Jw "APL (Dyalog Unicode) – Try It Online") Slow when there are few distinct values in the grid (can't eliminate possibilities quickly). Enumerates all possible rectangles (not many), then tries adding one at a time, checking for overlap and equal elements. **Explanation** ``` ⍳⍴A←⍵ ⍝ Set A to be the given matrix, and generate all dimensions of smaller rectangles ¨, ⍝ For each smaller dimension (e.g. 5 4): ¨⍵(⌽⍵) ⍝ Apply the following for both the dimension and its transpose: {(,⍳1-⍵-⍴A)∘.+,¯1+⍳⍵} ⍝ Get all possible vectors of the indices of each cell in each possible translated submatrix ((×/⍵)÷⍨⍴,A) ⍝ The number of these matrices needed to get the right area to tile the grid {⍺≤1:...∇⍺-1⋄⍬} ⍝ Repeat that many times, starting with ⍬ (empty vector): R←⍵∇⍨⍺-1 ⍝ Take R to be the result of the previous step R∘.(,∘⊂)↓⍵}⊃⍪/ ⍝ Add to R all possible existing submatrix sequences ⍵[⍸...] ⍝ Filter for those that: ((⊢≡∪)⊃,/⍵) ⍝ Have no overlapping tiles and ((1≡⊃∘⍴∘∪)¨↓{A[⍵]}¨⍵) ⍝ Consist of the same sequence of entries {⊃⍵[⊃⍋⍴¨⍵]} ⍝ Get the first possibility, sorted by area {A[⍵]⍴⍨⊃⌽⍵} ⍝ Get the corresponding elements from the original matrix, and correct the shape ``` ]
[Question] [ ## Background This challenge is about [A004001](https://oeis.org/A004001), a.k.a. **Hofstadter-Conway $10000 sequence**: $$ a\_1 = a\_2 = 1, \quad a\_n = a\_{a\_{n-1}} + a\_{n-a\_{n-1}} $$ which starts with ``` 1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 7, 8, 8, 8, 8, 9, 10, 11, 12, 12, 13, 14, 14, 15, 15, 15, 16, 16, 16, 16, 16, ... ``` [John Conway](https://en.wikipedia.org/wiki/John_Horton_Conway) proved the following property of the sequence: $$ \lim\_{n\rightarrow\infty}{\frac{a\_n}{n}}=\frac12 $$ After the proof, he offered $1(0),000 for the smallest \$k\$ such that all subsequent terms of \$a\_j/j\$ after the \$k\$-th term are within 10% margin from the value \$1/2\$, i.e. $$ \left|\frac{a\_j}{j}-\frac12\right|<\frac1{20},\quad j > k $$ To quote Sloane's comment on the OEIS page (which explains the title): > > John said afterwards that he meant to say $1000, but in fact he said $10,000. [...] The prize was claimed by Colin Mallows, who agreed not to cash the check. > > > Here are some graphs to get some feel of the sequence (copied from [this MathOverflow.SE answer](https://mathoverflow.net/a/357297)): ![](https://i.stack.imgur.com/N5udr.gif) Also check out [A004074](https://oeis.org/A004074), which lists the values of \$2a\_n-n\$. ## Challenge Given the amount of margin \$r\$, solve the generalized Conway's challenge: find the smallest \$k\$ which satisfies $$ \left|\frac{a\_j}{j}-\frac12\right|<\frac{r}{2},\quad j > k $$ This can be also phrased as the largest \$k\$ that satisfies \$\left|\frac{a\_k}{k}-\frac12\right|\ge\frac{r}{2}\$. You can assume \$0<r<1\$, so that the task is well-defined in both ways. (The original challenge is \$r=0.1\$, and the answer by Colin Mallows is 1489, according to [Mathworld](https://mathworld.wolfram.com/Hofstadter-Conway10000-DollarSequence.html) (which agrees with my own implementation). The value of 3173375556 on the MO answer is probably the one for \$r=0.05\$.) For simplicity, you may assume a few conjectured properties of the sequence: * \$a\_n = n/2\$ when \$n = 2^k, k \in \mathbb{N}\$. * \$2a\_n - n\$ + is nonnegative everywhere, + is 0 when \$n = 2^k, k \in \mathbb{N}\$, + follows the [Blancmange curve-like](https://en.wikipedia.org/wiki/Blancmange_curve) pattern between the powers of two (as visible in the second figure above), and + when divided by \$n\$, has the maximum values between powers of two decreasing as \$n\$ increases (as visible in the first figure above). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` r | answer ------+------- 0.9 | 1 0.4 | 1 0.3 | 6 0.2 | 25 0.15 | 92 0.13 | 184 0.12 | 200 0.11 | 398 0.1 | 1489 0.09 | 3009 0.085 | 6112 0.08 | 22251 ``` [Reference implementation in Python](https://tio.run/##lVLBboMwDL3zFZZ2KIHQkdJOGxv9EZRDtpo2Ek1ZoFqnrt/O4qRVu0k7DKFHYj8/vzh0n8NmZ4px7PEdKqhzDsK9Mmp2FjRoA1aZNcYFF7l/WBmBMlvhyK6k1pnj0mqqug7NKqYg5SWkgQCZ50sW3XVWm8EzRFlQZFB2jYPvC7oBXVU5YNsjxLPEZJrda/A@uCEnaPZbtGpAkmDyohdESHJOTX4ZF3zmPEOgzpJEc3AY61QwDlt1uJRTqrxkJOW0@SPHohU20O/a2NI0tPMvnqFV/YCHN8RV2Pf7V2WtW59FrvlUlNdNMk9pgh8b3aL3E@rYsrJO@6dqfR7H9XS3OvyGzCETjEZ6bq4lLCuwsvbX9U9vFoe9NTfqkf87LNmo8@kTh3w6JygIZgRi4dEHRIgIjwS5r8gfF@Ej3TnD9TSToy1fHk5fcAzTPU3YOH4D). (A hint for termination check: A value of \$k\$ is the answer if \$\frac{2a\_k}{k}-1\ge r\$ and \$\frac{2a\_j}{j}-1< r\$ for \$k < j \le 4k\$.) [Answer] # JavaScript (ES6), 83 bytes Slow as hell. ``` g=n=>n<3||g(n-g(--n))+g(g(n)) f=(r,n=1,m)=>(x=g(n)*2-n)|m?f(r,n+1,x<r*n?x&&m:o=n):o ``` [Try it online!](https://tio.run/##dcpBDoIwEIXhPafoisxACyLERMLAWQhCo6EzphjDgrtXWLgxcfn@7z36d78M/v58GZbbGIIlppabctsssLFgDCOmFvaFGE0EXjMV2iG1sNJRk/N@2Vw3HZQWem18wt0ax64WYqwlDMKLzGM2i4UJTtlVKUSV56qIfqn6T@WXLuED "JavaScript (Node.js) – Try It Online") ### How? We look for the highest \$n\$ such that: $$2\cdot a(n)-n \ge r\cdot n$$ We stop when no greater value is found in a whole interval: $$[2^k+1,2^{k+1}], k>0$$ whose upper bound is characterized by \$2\cdot a(n)-n=0\$. --- # JavaScript (ES6), 94 bytes A much faster version using a cache to prevent too many recursive calls. ``` g=n=>g[n]=g[n]||n<3||g(n-g(--n))+g(g(n)) f=(r,n=1,m)=>(x=g(n)*2-n)|m?f(r,n+1,x<r*n?x&&m:o=n):o ``` [Try it online!](https://tio.run/##dc/BCoMwDAbg@56iJ2nVqq06rFh9kLGDOC0bmg4dw0Pf3SnoDiu7BJIvJPyP@l1PzXh/vijoW7ssSoIs1QWucivGQBEbozBQhSkFQjyF146QUyfx6INk/kBkiWe5TV2@rpih6jbymD8XowvV7DhDriWQXC@Nhkn3bdBrhTscBQIhQlAYInb6peQ/xQedLeIH8dQylu4muG3x8S1LbOTH0Siyke0Yi8zGb4gkE8sH "JavaScript (Node.js) – Try It Online") [Answer] # Pure [Bash](https://www.gnu.org/software/bash/), ~~110~~ ~~109~~ ~~108~~ 105 bytes ``` a=(0 1 1) v=1 m=1 for((n=3;c<2;n++)){ c=$[a[n]=v=a[v]+a[n-v],(2*v-n)*$2>=$1*n?m=n,0:c+!(n&n-1)] } echo $m ``` [Try it online!](https://tio.run/##NY/NToQwFIX39ymOpGP4GRxaxsRxKK506wMQFqVlZBJpDY5oYnx2LExY9PtOm5Pc20Z9dpNWF5T4GNzboHoURfD8@hJMSoYZOHhEo@TU@3NyQxhamR91IY42SaLol7RklapsLUepqrFOfE7HehuKeExtFDNRSsZj@9RLu80edXIT2lub8qimP2p158D6yY8j0l3vDL6Sn3URou/u/N5iaJWBQkOAcR7whbO9nBBshMEOm72BLBGAKbBmKdzt1s@sb8bZdjqAZ7Sfkc8QM/i9p1d@lbiKXzUXDkt8WGrey@0f "Bash – Try It Online") *3 bytes off due to the same improvements made by ceilingcat for my C answer.* Input is a fraction, passed as arguments -- the numerator in the first argument, and the denominator in the second argument. For example, to pass 0.13, the command would look like: `./program 13 100` (Bash doesn't support floating-point numbers natively, but rational numbers are perfect for this challenge.) The program runs quickly enough that it can get through all the OP's test cases in a single run at TIO, even though bash is a relatively slow interpreted language. Output is on stdout. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~49~~ ~~48~~ 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞oüŸvy¦R.ΔтS_λè₅N₁-₅+}·yαIy*@}Dˆ(i¯àDdiq ``` -1 byte thanks to *@Grimmy*. [Try it online.](https://tio.run/##AUoAtf9vc2FiaWX//@KInm/DvMW4dnnCplIuzpTRglNfzrvDqOKChU7igoEt4oKFK33Ct3nOsUl5KkB9RMuGKGnCr8OgRGRpcf//MC4xMQ) (No test suite, because of the `q`.) **Explanation:** Inspired by [*@Arnauld*'s approach](https://codegolf.stackexchange.com/a/203724/52210), so I too look for the largest \$n\$ such that: $$2\cdot a(n)-n \ge r\cdot n$$ And I also stop when no greater value is found in a whole interval: $$\left(2^k,2^{k+1}\right],k>0$$ ``` ∞ # Push an infinite positive list: [1,2,3,...] o # Take each as 2 to the power: [2,4,8,...] ü # For each overlapping pair: Ÿ # Create a list in that range: # [[2,3,4],[4,5,6,7,8],[8,9,10,11,12,13,14,15,16],...] vy # Loop over each inner list in the range [a,b]: ¦ # Remove the first value to make the range (a,b] R # Reverse it to [b,a) .Δ # Find the first value `y` in this list which is truthy for, # or -1 if none are found: λ # Create a recursive environment, è # to output the `y`'th value afterwards тS_ # Start it at a(0)=0, a(1)=a(2)=1 # (push 100 as list [1,0,0] and invert booleans to [0,1,1]) # (implicitly push a(n-1)) ₅ # And use that for a(x): a(a(n-1)) N₁- # Push n-a(n-1) ₅ # And use that for a(x) as well: a(n-a(n-1)) + # And add those together }· # After the recursive environment, double it: 2*a(y) yα # Take the absolute difference with `y`: |2*a(y)-y| Iy* # Push the input multiplied by `y` @ # Check |2*a(y)-y| >= input*y }Dˆ # After the found_first, add a copy to the global_array (i # If this value was -1 (thus none were found): ¯ # Push the global_array à # Pop and push its maximum D # Duplicate it di # Pop the copy, and if this maximum is NOT -1: q # Terminate the program # (after which this maximum is output implicitly as result) ``` NOTE: The `vy` cannot be `ε` or `ʒ` to act as a foreach with implicit `y`, because we'd need a `--no-lazy` flag in order to have a proper output, which isn't possible due to the lazy infinite recursive list. [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 178 bytes ``` a(X)->case X>2 of true->a(a(X-1))+a(X-a(X-1));_->1end. c(R)->c(R,1,0,0). c(R,N,M,O)->case 2*a(N)-N>R*N of true->c(R,N+1,N,N+1);_->case N>O bsl 1of true->M;_->c(R,N+1,M,O)end end. ``` [Try it online!](https://tio.run/##fY3RCsIgFIbv9xReHjcdc3VTgW8wB7saRIQtC2G5cIse31RWuwjmhcr5vvP/yvbS3KkaO6ufk0uchBZT3slRoZaXaLihyb4U5RI8oQzjLLzz/3CmnClzzZMOmrAGDWGkIAWOEyJIRepvXJlKEJgK3qRiyY1axrzq7xgYZcFrdBl7xH5iFdlsh1jfi0K3e0ht4HjyPQnyRw/7t9WTgg6KfIcx8QPTAyb/dLtKN6u0XGjuPg "Erlang (escript) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~119~~ ~~116~~ 113 bytes ``` f(float r){int a[99999]={0,1,1},v=1,m=1,n=2,c=0;for(;c<2;c=2*v>=r*n+n?m=n,0:c+!(n&n-1))a[n]=v=a[v]+a[++n-v];v=m;} ``` [Try it online!](https://tio.run/##LY5NasMwEIX3PsU0kCBFsiM5DTRVJz2I64VQotYQj4sa1IXx2V1JdOB78Jg3P67@dG5dPfP3yT4g8HmgB9junKvHWUkt9SIjajkmCFvpUBk/BWbcW2sctvt4wbAnQe8jklSvTjwx2lGtObcd9RjRdrEXthOC6tibiKNZ1nxmtAOxOA1XXgHAnAX@/zBVcb9fw/0GTAMi/DhLnm22fiNhF3iZyfUd0i4PqdMcPeAFttcPSpkgwbOUMzm4wOFQ7q2qOVeqeU4cE21Cn7Jkp4vVWRIqB9XLqWj1Bw "C (gcc) – Try It Online") *3 bytes off thanks to ceilingcat.* *And now 3 more bytes off from ceilingcat.* This is a port of my bash answer. It's a function which accepts `r` as an argument (a float this time) and returns the desired result. ]
[Question] [ Roman numerals can be (mostly) written in a one column format, because each letter intersects the top and the bottom of the line. For example: `I`, or 1 intersects both the top and bottom of the line, and `V` or 5 intersects the bottom and top lines, the top twice and the bottom at one place. The value of all roman numerals is as follows: `I = 1` `V = 5` `X = 10` `L = 50` `C = 100` `D = 500` `M = 1000` and the number of intersections (top, bottom) is: `I = 1,1` `V = 2,1` `X = 2,2` `L = 1,2` `C = 1,1` `D = 1,1` `M = 2,3` Your job is to take in 2 numbers, which represent the number of intersections on the top and bottom of your line (in that order), and output all possible *valid* combinations of roman numerals, from smallest by literal value to largest. Inputs will always be at or above 1. Here are some test cases: ``` Input: 1,1 Output: I,C,D Input: 1,2 Output: L Input: 2,1 Output: V Input: 2,2 Output: II, X, IC, CI, CC, ID, DI (note that DD is not a valid roman numeral, and thus should not be outputted, the value of all of these is (in order) 2, 10, 99, 101, 499, 501) Input: 3,3 Output: III, IX, XI, LV, XC, CII, CX, CCI, CCC, DII, DX, DCI, DCC (note that IIC, and IID are not valid numbers. DD (1000) is also not a valid number, as the correct numeral is M) The value of these numbers (in order) is: 3, 9, 11, 55, 90, 102, 110, 201, 300, 502, 510, and 601) ``` This is a usual code-golf, and needless to say, I'm interested to see how golf languages implement roman numeral counting rules. Best of luck! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~32~~ ~~29~~ 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žDL.Xʒ•BÌË"•4в2ôsÇ87%èøOQ ``` -7 bytes thanks to *@Grimy*. [Try it online](https://tio.run/##yy9OTMpM/f//6D4XH72IU5MeNSxyOtxzuFsJyDC5sMno8Jbiw@0W5qqHVxze4R/4/3@0sY5xLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeWilvZLCo7ZJCkr2/4/uc/HRizg16VHDIqfDPYe7lYAMkwubjA5vKT7cbmGuenjF4R3@h9YF/q/V@R8dbahjGKsDJI2ApBGYbQRmG@sYx8YCAA). **Explanation:** ``` žD # Push builtin 4096 (the maximum Roman number is 3999) L # Create a list in the range [1,4096] .X # Convert each integer to a Roman number ʒ # Filter this list by: •BÌË"• "# Push compressed integer 195646806 4в # Convert it to base-4 as list: [2,3,2,2,2,1,1,1,1,1,1,1,1,2] 2ô # Split it into parts of size 2: # [[2,3],[2,2],[2,1],[1,1],[1,1],[1,1],[1,2]] s # Swap to get the current Roman number we're filtering on Ç # Convert its characters to their unicode values 87% # Take modulo-87 for each (I=73; V=86; X=1; L=76; C=67; D=68; M=77) è # Index those into the list of pairs (with automatic wrap-around) ø # Zip/transpose; so we have inner lists of top/bottom values O # Sum each inner list Q # And check if it's equal to the (implicit) input-pair # (after the filter, the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•BÌË"•` is `195646806` and `•BÌË"•4в` is `[2,3,2,2,2,1,1,1,1,1,1,1,1,2]`. [Answer] My first try on Code Golf, please point out some optimizations! **Python 3.7, ~~465~~ ~~449~~ ~~364~~ ~~363~~ 284 Bytes** Edit: Thanks for the improvements! Jo King managed to squeeze this logic from 449 to just 364 bytes, I took a single Byte off it so I felt justified to update it. :D Description of the old function, which remains can still be found in the code: To formulate all numerals with certain amount (a and b) of cross points, m() subtracts number of cross points of every numeral from a and b, and recursively calls the function again for every case. If a and b are negative when called, the function exits, and if both are zero, the next function checks if it is a valid roman number, and prints accordingly. To check if a character string is a roman number, t(c) checks if there are any 4 characters in a row, or two in the case of 50 and 500. It then checks for the possible subtraction numeral before any numeral (The possible subtraction roman numeral is either 2 or 1 positions after the real roman numeral in the list of 'MDCLXVI', depending on the **parity** of the roman numerals index on that list!) If any are found, they are replaced for the next part as with just the real numeral, without the subtraction numeral. SUB-NBR-SUB sandwiches, like IVI are falsified. The next part just checks if the list is ordered. ``` def m(c,i,a=''): d,e,s,*p=a,c|i,str,2,3,*[1]*5,*[2]*4,1,1,1 for x in range(7):c+i>0==m(c-p[x*2],i-p[x*2+1],a+s(x));e|=any(s(z)in d for z in[s(x)*4,11,33,f"{x+~x%2+1}{x}{x+~x%2+1}"]);d=d.replace(s(x+~x%2+1)+s(x),s(x)) e or[*d]==sorted(d)==print(''.join('MDCLXVI'[int(x)]for x in a)) ``` [Answer] # [Perl 5](https://www.perl.org/), ~~230~~ 213 bytes ``` sub f{grep{($t,$b)=@_;map{($h='I1V21X2L12C1D1M23')=~/$_(.)(\d?)/;$t-=$1;$b-=$2||$1}/./g;!$t&&!$b}map{$r='I'x$_;for(qw(IVX XLC CDM)){($I,$V,$X)=/./g;$r=~s,$I{4}($I?),$1?$V:$I.$V,ge;$r=~s,$V($I?)$V,$1$X,g}$r}1..4e3} ``` [Try it online!](https://tio.run/##RZDLbsIwEEX3@YoBjUgsuYlsYENqHko2lmCHoiyQolJMSsWrSVCpIP11Ok5L8SL2zDl3HPloim3/ditPS1hf8sIcLx5WHJdMjbNw92LLN@VqkUiRyqmQkYjFTHZdpr4DzDyfeYvViAUhVk8KRYhL2uT1iqIO/CAPW1h1Oi1c1nYUFjTJPWMWrg@F9/Hp6SSFdBpBFM8Yo5s0x4RjylSTJf275KgvvZrQiHEUI0wGqH2ycnPnSQNtUGDK8xqLWvh@z3Tr26k0MDdlNRjMDoWBio6lGvZDx95fHrebKljsA/5@2Oxdlz/Hk/lkyC4O0Np9ebgXHPeSj835aF4rs2KqyYR/AiABZcNtaHP41x48P1QPvr4PZL/CpvQagzdzOLQJA2FQw6bTBhJrJ8vsb2WZI0CAhghiOkmYOpLqhL4StIYUImL2JSHWEEdOF7rU16DphTVME0gJUh2R2ajWJZNacUoBG4puPw "Perl 5 – Try It Online") With spaces and newlines added for readability: ``` sub f{ grep{ ($t,$b)=@_; map{ ($h='I1V21X2L12C1D1M23')=~/$_(.)(\d?)/; $t-=$1; $b-=$2||$1 } /./g; !$t&&!$b } map{ $r = 'I' x $_; for( qw(IVX XLC CDM) ){ ($I,$V,$X) = /./g; $r =~ s,$I{4}($I?),$1?$V:$I.$V,ge; $r =~ s,$V($I?)$V,$1$X,g } $r } 1..4e3 } ``` The `map` at the end turns all integers 1 – 4000 into their roman equivalent. Since there is no letter for 5000 and 10000 and so on, it's reasonable to say that the maximum roman number is 3999=MMMCMXCIX. (One could just add more M's to get larger numbers, if so, just increase `4e3` here to whatever time you have to wait for the result...this is code golf where we optimize for code length, not runtime:) The `grep` filters that list so that only the ones with the wanted input `$t` (top) and `$b` (bottom) numbers are returned. The `map`s inside `grep` decreases $t and $b by the right amount of "intersections" for each roman letter and the grep ends up being true for each roman number by `!$t&&!$b` if both $t and $b are zero (which means they started as the numbers we wanted in the input parameters). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~144~~ 97 bytes ``` NθNηΦE×φθ⁺×M÷ιφ⮌⭆⪪”{⧴9i…⪫χM⎚GOWbπ↗sP÷n“<BÞD‴!w≡θ⟧L≡§A≦I⍘∨Φ…ok”²⁹§⪪λ ÷ιXχμ∧⁼θΣEι⊕№VXMλ⁼ηΣEι⊕№LXMMλ ``` [Try it online!](https://tio.run/##hZBNS8QwEIbv/oohpxQidN2T7EmyCoGtFCtLrrUNNpCkbZpU/32c1ILixfDMwAzzzke6ofXd2JqUhJtieI72TXk6F6eb3/GAce21C/RJm4CJqp3oq7ZqoYeyLBnMBYPaxGVPkoowEC6c9ap7RTWDXFZg0YtalV8UbQK2e89tmsnoQAkIEBkBVwQEshk6KUCCzEi4ICCRzdBxCRx4hsMZAY5shq7iuMfdPc59CML16nOfZhgQIMWfHevxA0874Dm2@H6ocz19nGNrFjozaKLdTtdZ2XlllQuqp3yM@DXkKvPZZlfuquE/1UVWPzJ8p5SOcEy3q/kC "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNη ``` Input the two values. ``` ΦE×φθ ``` Loop up to 1000 times the first number, which is well past the largest valid Roman numeral, keeping only those that satisfy the validity of both the top and bottom intersections (according to the condition at the end of the code). ``` ⁺×M÷ιφ⮌⭆⪪”{⧴9i…⪫χM⎚GOWbπ↗sP÷n“<BÞD‴!w≡θ⟧L≡§A≦I⍘∨Φ…ok”²⁹§⪪λ ÷ιXχμ ``` The compressed string expands to `I II III VI V IV IIV IIIV XI X XX XXX LX L XL XXL XXXL CX C CC CCC DC D CD CCD CCCD MC`. This is used to calculate the Roman numeral in reverse, working from the units up to the 100s, and then the reverse is concatenated to any further `M`s needed. ``` ∧⁼θΣEι⊕№VXMλ⁼ηΣEι⊕№LXMMλ ``` For each Roman numeral, count the number of times each letter thereof appears in the strings `VXM` and `LXMM` respectively, then add one for each letter, and compare the totals to the inputs. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 129 bytes ``` ŒṗŒ!€ẎQ)p/ẈE$ƇZ€“(³l’ḃ9¤ḃ3¤ẹⱮŒpƊ€ẎŒgQ€QƑƊƇḂÐḟQƑ$ƇI<1kƲ€ḂḢ€ạẈƲỊẠƊƇIFṀ<ʋƇ3ị“¢¦½2d‘;.ȷ,ȷ¤ạ/€€S€Ụf<ƇS<ɗⱮ⁵*Ɱ3¤ẠaNÞƑƲ€T$ƲƊị$ị“IVXLCDM”K ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7px@dpPioac3DXX2BmgX6D3d1uKoca48CijxqmKNxaHPOo4aZD3c0Wx5aAiSNgeSunY82rjs6qeBYF0TX0UnpgUBW4LGJx7qOtT/c0XR4wsMd84FcoDGeNobZxzaB1O1oerhjEVjDQqAVxzY93N31cNcCkA5Pt4c7G2xOdR9rN364uxto6aFFh5Yd2muU8qhhhrXeie06J7aDbF2oD3JS05pgkCG7l6TZHGsPtjk5HeiWR41btYAU2G0LEv0OzwO6BGRniMqxTce6gGaqQMz1DIvwcXbxfdQw1xvs8RnWQEEFXTsFoIj14XYu84KEw@1AfZH//wMA "Jelly – Try It Online") A full program taking a pair of integers as its argument and printing to STDOUT a space-separated list of Roman numerals. Should produce all valid Roman numerals following the [rules on Project Euler](https://projecteuler.net/about=roman_numerals) (so `VIIII`, `IX` and `IIIIIIIII` are all valid forms for 9, but `VIV` is not, and `X` is the only valid form for 10.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 61 bytes ``` 1xⱮ4Ḷ¤$ؽṭ;2;Ɱ$Ʋ1,3ṭ+þ3Ḥ€Ż¤ṚŒpḣ4ȷF€ị“(³l’ḃ9¤ḃ3¤S⁼ɗƇị“IVXLCDM” ``` [Try it online!](https://tio.run/##y0rNyan8/9@w4tHGdSYPd2w7tETl8IxDex/uXGttZA0UUzm2yVDHGMjVPrzP@OGOJY@a1hzdfWjJw52zjk4qeLhjscmJ7W5AsYe7ux81zNE4tDnnUcPMhzuaLYFKdjQbH1oS/Khxz8npx9ohCjzDInycXXwfNcz9f7jdm@vopIc7Z1gDxRV07RSAgtaH27mMCxIOtwNNjPwPAA "Jelly – Try It Online") This monadic link takes a pair of integers as its argument and returns a list of strings representing the Roman numerals. Unlike my other Jelly answer, this one only uses the minimal (canonical?) representation of each Roman numeral, so it’s more straightforward to generate a list of all Roman numerals in order and filter them. It only generates Roman numerals up to 3999, but could be adapted to work for higher Roman numerals if needed. L ]
[Question] [ Who doesn't like to chill on a Sunday morning in summer with a chilled beer and TV or in winter playing badminton or ultimate with friends? I always think knowing how many days you have to chill in a month keeps you well-informed and helps you plan what you want to do. Be it sitting in front of your pc and solving a code-golf problem or going out to play football. So, help me write a program or function which takes as input 2 positive integers, `Y` and `M` and outputs the number of Sundays in that particular year(`Y`) and month(`M`) (according to the Gregorian Calendar), followed by the date of each Sunday. Also, do keep in mind that the shortest code wins. ## Input Constraints 1000 <= Y <= 9999 1 <= M <= 12 ## Output These test cases will have output will have the dates of each Sunday of that month in that year in the format `DD-MM-YYYY`. # Sample Test Cases ## Test Case 1 Sample Input ``` 2017 1 ``` Sample Output ``` 5 01-01-2017 08-01-2017 15-01-2017 22-01-2017 29-01-2017 ``` ## Test Case 2 Sample Input ``` 2018 2 ``` Sample Output ``` 4 04-02-2018 11-02-2018 18-02-2018 25-02-2018 ``` ## Test Case 3 Sample Input ``` 2016 11 ``` Sample Output ``` 4 06-11-2016 13-11-2016 20-11-2016 27-11-2016 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~150,148,~~145 bytes ``` from calendar import* y,m=map(int,input().split()) z=filter(None,zip(*monthcalendar(y,m))[6]) print len(z) for i in z:print'%02d-%02d-%s'%(i,m,y) ``` [Try it online!](https://tio.run/nexus/python2#NY1BCsIwEEX3OUUolM6UKLULEaFX8ALiItgEBzJJSOOiuXwMipv/4cF/v9oUWD61M37VSRLHkPIodsUL6wjksyIf3xnwuEVHrVGUxZLLJsEteKMKRRg5@Pz6W6CtEe/nB4qYmkE2DAWFDe1Akpfl@uVDP83r4Rfb0AMpVjvW2s3T6SLn7gM "Python 2 – TIO Nexus") -3 bytes making stuff more pythonic (using zip and filter!) [Answer] ## JavaScript (ES6), 107 bytes ``` f= (y,m,a=[...Array(32)].map((_,i)=>new Date(y,m-1,i)).filter(d=>d.getMonth()==m-1&!d.getDay()))=>[a.length,a] ``` ``` <div oninput=o.textContent=[].concat(...f(y.value,m.value)).map((d,i)=&gt;i?d.toDateString():d).join`\n`><input id=y type=number min=1000 max=9999 value=2017><input id=m type=number min=1 max=12><pre id=o> ``` Edit: Adding an explicit count cost 15 bytes. Formatting the output would cost at least another 33 bytes depending on how strict the output format is. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 91 bytes ``` param($y,$m)($a=(1..31|%{Date "$m/$_/$y"}|?{!$_.dayofweek})).count;$a|%{"{0:d-M-yyyy}"-f$_} ``` [Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6FSqaOSq6mhkmirYainZ2xYo1rtkliSqqCkkquvEq@vUqlUW2NfragSr5eSWJmfVp6aml2rqamXnF@aV2KtkghUrlRtYJWi66tbCQS1SrppKvG1////NzIwNPtvaAgA "PowerShell – TIO Nexus") *(Special note - this is locale and culture settings dependent. Since TIO is [running as `en-us`](https://tio.run/nexus/powershell#@5@eWqKbXJpTUlqU@v8/AA), it works correctly there as-is. This code may need to be changed for different locales.)* Takes input as two integers `$y` and `$m`. Loops from `1` to `31`, getting a new `datetime` object for each possible date (via the `Get-Date` cmdlet). Will toss errors to STDERR (ignored by default on code-golf challenges) for months with fewer than 31 days, but that doesn't affect output. We take each of those `datetime` objects and use a `Where-Object` (`|?{...}`) on them, with the clause of `!$_.dayofweek`. The property `.dayofweek` is a number from `0` to `6`, with `0` conveniently corresponding to `Sunday`, so the `!` of that is truthy, which saves a couple bytes compared to an equality check like `-eq0`. The Sundays are then gathered in parens and stored into `$a`. We then take the `.count` thereof, and that's placed on the pipeline. Next, we loop through `$a` and use the `-f`ormat operator to construct the correct output format. Note that this doesn't output leading zeros for days or months. Those date strings are also left on the pipeline, and an implicit `Write-Output` at program completion prints them with newline separators. --- NB - if the output format was more flexible, we could just leave `$a` on the pipeline and not need to loop through it. That will stringify the `datetime` objects as the long-date format including time information, but gets us down to [69 bytes](https://tio.run/nexus/powershell#@1@QWJSYq6FSqaOSq6mhkmirYainZ2xYo1rtkliSqqCkkquvEq@vUqlUW2NfragSr5eSWJmfVp6aml2rqamXnF@aV2Ktkvj//38jA0Oz/4aGAA "PowerShell – TIO Nexus"), which would (currently) only be beaten by Mathematica and MATL. [Answer] # Octave, 72 bytes ``` @(y,m)cellfun(@disp,flip({datestr(x=nweekdate(1:6,1,y,m)(x>1)),nnz(x)})) ``` `nweekdate` returns the date number corresponding to the `N`-th occurrence of a particular weekday in the specified month/year. We use the array `1:6` in place of `N` to get *all* occurrences in a month. If there are fewer than `N` occurrences of that weekday in a month, then the resulting date number is `0`. For this reason, we select only the valid dates using `(x>1)` and then convert them to strings using `datestr`. Then to count the number of Sundays, we count the number of non-zero (`nnz`) date numbers in the result. We then wrap the entire thing in `cellfun` to display each value. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~46~~ ~~45~~ ~~42~~ 35 bytes ``` 8BhtYOw47B~+YOq&:t8XO!s310=)tnw24XO ``` Input is an array of the form `[2017 1]`. Output format is `29/01/2017`. [Try it online!](https://tio.run/nexus/matl#@2/hlFES6V9uYu5Upx3pX6hmVWIR4a9YbGxoYKtZklduZBLh//9/tJGBobmCYSwA) Or [verify all test cases](https://tio.run/nexus/matl#S/hv4ZRREulfbmLuVKcd6V@oZlViEeGvWGxsaGCrWZJXbmQS4f8/wiXkf7SRgaG5gmEsF4hhoWAEYZgpGBrGAgA). ### Explanation ``` 8B % Push [1 0 0 0] (8 in binary) h % Implicit input. Concatenate. Gives something like [2017 1 1 0 0 0], % corresponding to the first day of input year and month tYO % Duplicate. Convert to serial date number w % Swap 47B~ % Push [0 1 0 0 0 0] (47 in binary, then negated) + % Add. Gives something like [2017 2 1 0 0 0]: first day of next month YO % Convert to serial number q % Subtract 1. This corresponds to last day of input month &: % Binary range. Gives an array with 28, 29, 30 or 31 days t8XO % Duplicate. Convert each number to three letters telling day of the week !s % Transpose, Sum of each column 310= % True for values that equal 310, which is the sum of 'Sun' in ASCII ) % Apply as a logical index tnw % Duplicate, number of elements, swap. This is the first part of output 24XO % Convert to date format 'dd/mm/yyyy'. Gives 2D char array. Implicit display ``` [Answer] # Ruby, ~~140~~ ~~132~~ ~~129~~ 118 bytes ``` require'date' d=Date.parse gets.split*?-+'-1' s=(d...d>>1).select &:sunday? puts s.size,s.map{|d|d.strftime'%d-%m-%Y'} ``` [Answer] # Excel – 103 characters Put the year in cell `A1`, and month in cell `A2`. The count is in cell `D1`, and Sundays in cells `D2:D6`. Assumes `D2:D6` are formatted DD-MM-YYYY. ``` A B C D 1 [year] [month] =DATE(A1,B1,1) =COUNTIF(D2:D7,">0") 2 =C1+7-WEEKDAY(C1,2) 3 =D2+7 4 =D3+7 5 =D4+7 6 =IF(MONTH(D5+7)=MONTH(C1),D5+7,"") ``` [Answer] # Mathematica, ~~82~~ 68 bytes ``` d=DateObject;{Length[x=DayRange[d@{#,#2,1},d@{#,#2+1,0},Sunday]],x}& ``` Anonymous function. Outputs a list of the number of days, followed by a list of the Sundays as `DateObject`s. Turns out, in Mathematica the 0th day of a month is interpreted as the last day of the previous month. [Answer] # C#, 183 bytes ``` y=>m=>{var s=new string[6];int i=1,n=0;for(DateTime d;i<=DateTime.DaysInMonth(y,m);)if((int)(d=new DateTime(y,m,i++)).DayOfWeek<1)s[++n]=d.ToString("dd-MM-yyyy");s[0]=n+"";return s;}; ``` Anonymous method which returns an array of string, containing first the number of Sundays and then each Sunday in the specified format. If there are only 4 Sunday in a month, the last string is null. Full program with ungolfed method and test cases: ``` using System; class P { static void Main() { Func<int, Func<int, string[]>> f = y=>m=> { var s=new string[6]; int i=1,n=0; for(DateTime d;i<=DateTime.DaysInMonth(y,m);) if((int)(d=new DateTime(y,m,i++)).DayOfWeek<1) s[++n]=d.ToString("dd-MM-yyyy"); s[0]=n+""; return s; }; // test cases: var result = f(2017)(1); foreach (var x in result) Console.WriteLine(x); result = f(2018)(2); foreach (var x in result) Console.WriteLine(x); result = f(2016)(11); foreach (var x in result) Console.WriteLine(x); } } ``` [Answer] ## REXX, 168 bytes ``` arg y m signal on syntax do d=1 to 31 m=right(m,2,0);d=right(d,2,0) if date(w,y||m||d,s)='Sunday' then queue d'-'m'-'y end syntax:n=queued() say n do n pull a say a end ``` [Answer] # Bash + bsdmainutils, 94 bytes ``` a=(`for i in $(cal $2 $1|cut -b1-2);{ echo $i-$2-$1;}`);echo $[${#a[@]}-1];fmt -1 <<<${a[@]:1} ``` Uses the command `cal` which prints a calendar, is installed by default in several UNIX/LINUX/BSD (unfortunately not in TIO). To try it save to `file`, `chmod +x file`, and run `./file 2017 9` Saves to array a the first two bytes of cal output appended with the string "MM-YYYY" passed as second and first parameters (needs change if your locale does not starts weeks on sundays). Next echoes array length substracted by one (first element is the word representing sunday) and the array without the first elemet, one per line `fmt -1` [Answer] # SAS, 182 bytes ``` %macro s(y,m);%let c=%eval(%sysfunc(intck(week,%sysfunc(nwkdom(1,1,&m,&y)),%sysfunc(nwkdom(5,1,&m,&y))))+1);%put&c;%do i=1%to&c;%put%sysfunc(nwkdom(&i,1,&m,&y),ddmmyy10.);%end;%mend; ``` [Answer] # T-SQL, 316 311 bytes ``` DECLARE @ DATE=DATEADD(ww,-52*(2017-@y),'20170101')IF DATEPART(d,@)>7SET @=DATEADD(ww,-1,@);WITH c(d)AS(SELECT d FROM(SELECT DATEADD(ww,ROW_NUMBER()OVER(ORDER BY name)-1,@)d FROM sys.stats)a WHERE @y=DATEPART(yy,d)AND @m=DATEPART(m,d))SELECT CAST(COUNT(*)AS CHAR(1))FROM c UNION SELECT CAST(d AS CHAR(10))FROM c ``` I don't know if it is a valid answer though, since it outputs the number of sundays after the dates [Try it here](http://rextester.com/AYY17164) ungolfed: ``` DECLARE @m INT = 1,@y INT = 2017 DECLARE @ DATE=DATEADD(ww,-52*(2017-@y),'20170101') IF DATEPART(d,@)>7 SET @=DATEADD(ww,-1,@) ;WITH c(d) AS (SELECT d FROM (SELECT DATEADD(ww,ROW_NUMBER()OVER(ORDER BY name)-1,@)d FROM sys.stats) a WHERE @y = DATEPART(yy,d) AND @m = DATEPART(m,d) ) SELECT CAST(COUNT(*) AS CHAR(1)) FROM c UNION SELECT CAST(d AS CHAR(10)) FROM c ``` [Answer] # PHP, ~~127 118 112~~ 107 bytes ``` for([,$y,$m]=$argv;$d++<date(t,($t=strtotime)($y.-$m));)date(w,$t($s=" $d.$m.$y"))?:$r.=$s.!++$c;echo$c,$r; ``` takes input from command line arguments; run with `-r` or [test it online](http://sandbox.onlinephpfunctions.com/code/9fa74673bf844338da51cff2b5385f0018ad9763). **breakdown** ``` for([,$y,$m]=$argv; # import arguments to $y and $m $d++<date(t,strtotime($y.-$m)) # loop while ($d < number of days in that month) ;) date(w,strtotime($s="\n$d.$m.$y"))?: # if date(w) is falsy (0 == sunday) $r.=$s.!++$c; # then append date to $r and increment $c echo$c,$r; # print result ``` [Answer] # Excel VBA, 190 bytes ``` Function p(y, m) d = CDate("1/" & m & "/" & y) e = DateAdd("m", 1, d) Do While d < e If Weekday(d) = 1 Then Debug.Print d: i = i + 1 d = d + 1 Loop Debug.Print i End Function ``` > > Sample Output for **p(2000, 1)** (not sure if this qualifies) > > > ``` 02-01-2000 09-01-2000 16-01-2000 23-01-2000 30-01-2000 5 ``` ]
[Question] [ A program is ***bit primed*** if bits in prime positions must alternate between zero and one, starting with one. For example, this is a template for a bit primed program with [0..47] bits. ``` ..10.1.0 ...1.0.. .1.0...1 .....0.1 .....0.. .1.0...1 01234567 89012345 67890123 45678901 23456789 01234567 ``` --- **Create a bit primed program** that takes as input a string and checks if the string is bit primed. The string will be in ASCII and it will be a maximum of 1000 chars. ## Rules * For the purposes of this challenge, the bit string for `ABCD` is ``` 01000001 01000010 01000011 01000100 ``` * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # Mathematica, 5432 bytes ``` f[gQqGCStZu2yl3mIEL5mBpO43ulpBaJP4g2sCvYht09xS9XvYv2XK7aZ6P2yh47J2y2Z8s42u91aKQT8dDQ7NZQFDShTWXW7ldVB8IorrV2Fu6ItvMF2y285nz52GizM3X1q0t3F7KMa@Print[29RshFOc0Zh3HKaau;i=0;1Kv6jpY40n3fmIl0YYfiskcIZaATpT76lc6ph3FhR1INU2ptKd8SJ8GXC54akjX4s08vjnaliCS5AQcSh56YS8hQ3xe2xtCV36Gn6lTDAg1tX3cz6G1tn2NB5NLk9Nx4O7Ygfmf3fAs6mnD3PjIzFw2FAK5Qj6i4wW0Gq0RSo7K6aV93L8N75ioRr6oZlCBRzeq3fiQI71KXLADrcO9sJVh24vMZr84plVXqzo52bmuRO6v6LoP47mggmS00gFtCXnwr64YntzbVjNpiyxQMDLXJnd1vUeUvvy0P6CodeGolfib1psOCu9iMxiT2oGesnIoDrqnKHqExqxgh30kFJRwJJk6LvY4M3ZCkKn43oFERtHe7d5qO7AvaF9T4o9T4Cf97MN1anz4TEPlR7FjoqQXaBVV57a5NfSZW97EFeIVn8LsqHjCgg72Vl6usW8L3RWlIo05Lfd8u7jUD0B8SP1fWymaP7kwYNLCg5OUQtLk479hUsE8bJungHwanMinm1xV9naf97dMqobj6jVAM1EzvXguLOal4OXO6DBFtmhHNwzx6u47fVRy7f;AllTrue[XF2uhxta8qS5K0ZeL9pmX3Zhrqn4IHD2hNTdEb9rsQw8raVJvbgSP1uk9OByu;Pick[l=(2EOFI4khaVxpn5d01z8kaARZNiz1oNZkcniL0sD13Sfqrapri0sq9AV12Wh9F1NtYjwbvHtM73G;Join@@(XX9giynmc3Y6ZScD3SIq0QdKvDHh30p3JAlYizir8xzW4d1AfMEIGKom1Hn3m4oGmSZACY012g1a1YRGaFY6YvI5zuzoseFjEDOn002W0qTCFdsmFMO0Wq05jPvEotODJ688d1Ef2iknRra301eEwXtCYAigA294p3Rn1i6dFvhOuIm9Omn1q6w9l4hY3skRZ4Yqc5IAEE0Ncv1eBg3PlT36YUzEEYhK3ekb5EXhrQEjkpJ3kQxL5m1sxu14N971gI8owjVUNyqzPXZ1YrTJ1i6lydT51gFZZzR9e1HPCG2fPzdY96udYT8m7TWZ6L3RnIzapDbrHJU86K4cLk280pmI0VQna8n5F9TsXzUSLkPY6defMJL7z4nPnSLTMFTtO5tYZ48bA723cK4GEM8Vx1oCSuhdn0OKl13tcKo1fenOJO39E5wIHFk35dButjorAWq8bGDteoHS1xt93x71gRJybCd4ruGl9kdZpwml4c8DRO3RlJAOF7nNwcjGzcLDeBS0VW6gOxGjO6LWEk6FgXEMzEmDHbVp0orIRb7jxeTY6QL0ReWS5E1iuqq0mU1ylo5uFjVuHUDobcBxKbajLjzuMuol57II7YxJrT72A0F0mHxP2EMwFtd6vha5DGtLonviT8osn3RVk7fJeY9pv1Dtxoz56Wd1kUcdL5N5PWPhJA118QlaQbPVQCxxbYXNQzi1PSatEcMIlJ3peMac6FOo6EvhpcIEmKJFCMxsO45dEYmoFf0EB3PTEhIVjX3wCvDvuK5FRrFwkB7CUOhSTlGEG61g8wblwOz9Ws3cu7L9LFDMPFn9rInZg1fq57GvB4VEAGQ02eIz6FbiDCK856Ou4uw2QwpDw8po190u7iQFhz9r74bz3exo2cokT1x059vpuKlnlS8iqc8CArq43qahewU4Kstn3gJKHbplFZrZbiX36tGoS5wY80RiosSf981WS8sGJabtcANl9ckq0nz4JS8y4150SVepw07KE2z7TvkyjA0ZBzIo7nxcrn7E2nGiCcsAT8Fv6mArN4b5v9fYWdZqA8a7gabW0ha8pykl63brXwLF3GJDAL0W376IvWk8IKYD7zTdnLCszD4Za8P7b4ExMeseyRXnuv1asg7sjRul9zQP3WryaMPCyB67gCDpt5n5AuSgC9nr7tEzWQCbBI2XFa5ogOgVdF3mkshjAU6sNuSxksnQdx0f1ZxS93Ioq3422Q1zB3BjML7i6NMF0yzxEiVTN2ENDUtK7V9uXrH1rva7TsXx9v9QE5sLf5gsP38LPUh5ZrDxXhfcCjtGDb9r1c00R9gM1xMjTj4cMEWJlXSfkeSM3yU52ZKsUDCq3fDqDE0plp96k8Ra9M84tz5uJ5mNXM8GxuXSS97c9sXXlFB0CaG4n0EP8lbyuUhOLaKUY9EelL68qSq5zlJFTIZf5u7SDEKFSkGU7ml97Gd7gtZ2NBq4hxOTR4uHZaS4ALmvN8o93fipy088oWKynoJSFjIkkZOw3mbSnHnfexKyYpp2Rv4SW3r3kPQ7UonY3Sm;IntegerDigits[3LpjdCIvIK7J5Cn3YbY9D3c6GuzGa8pUJ5O14ruPrrPcbXqb7z7qA8Q4hrTsWvSBbIIReq7mnIW5lakuMkPMgqg9Zt18pqfjOVQs6ZuYGp5NNds0rX65melVZKRlNCHaGskSIsl3QeApWc0rf8yT12zKI8SFm3SEgcxF4KfE8yHtcLJy8B3Pz06vOy78rg6Y6zSWnInE2pLBj6tYBspKs6YXNL8D6C4P2Y7EcozkoR6aKx2zs0Zfo6lryRqnGds6kg22M472LCJIZ470XGPAkH3QLA7zuST81EjwyqVvFR2p9AEtKiEJc14TVWXFZvsyMuic76ZoQox6B5p295GJVU0SyU5xvtb0CCKTnIvFdPzFFbwMocknxFpoBDbLqFGsaxg7J71Ls3vBkgnlN1Rc5w4PDNTCGQC2RCk1A2L43s3bnkgMAsUNYhGeJDAcNfWUNswuo7A97RYEJEcZRgGQ0upJHX77PZLzJr09HM6HNs1EuDPBslPTEHG4M4wIvx4Vf4rVwXvG3G8i8pORtYJUMzEaYz7X9zsRNAOZ3gXqnRYC5l3qUe28NlHMuiaRuywS1NkaF89bOxLxv4nyHZ9ueHf49L2Co0UqOtzFPs99pwjSDreIyQxioa6CMR9Ht17T9N7GMD7aWaxeBSK48J2pVn04yoQTB0BJMnm9e343KBUw6742VFgTajnRVv16LXtn0jpuOCWFVM2N4CGMzgCBdQZROOl2S4CE6AecPJOaVLWg5Z1GSqeXQmHwB9AjgxRdakpTrvAad0Wb5OLkZXQIKqFxQ7R8wBd79t8L4X9pwj4SJTVKFm1LDn5qeaOw54aJRFqQ0z5GvOd1Xt24TjH7y676nR42CMY91PoBcV2FyRdv8vmjQ8932IHn5LU3up9ZxbqrXPednbFmi6vyLODt8KlhM7ELfYp223GWMrTHVu34nKgdiM5Vlq1bWTaMq2mbM5AcQB52zXgy7pSVvlXdrLqdFwGrFRDrQ03DXm0r9ZbRitrU2tEzVmE9og9AKeAq7pZb68ypniGn5VVBM3mUMZjAACaVmgn5uZS0xsQcE84rblzkK1DAIa2yQ6ixAkGdlezfe6o94B3SJIgjujkBb876db31RXQVSX7aCLWm9DXr1ie7hc2U1M3y3Y3LK4eFbzM69Bg6B5TWVmY6AfBJsC8iYpfICgCpCNDUgGx53EzoWhatALongProgramuqO6XCaRvMePL0QFjx8ojo8IHbEIwbbat4DtRF4vTgRC0wQFzzSyrx2XoajV2DX70042W3x1o99Y4ms9dHATupNeeA57BtUU6rJ2li2i9mQHb1EftkNG5fnSSxWORLqdxw1uki88bxwf2sb7e1Sv4DHEA81ixwR74lT7k2FQ8qvL8ZyPN1iLn1NbpgOFXKAXOioKpoW2OHX6RNDRrL0rOBuLLugIiPg3SJ4n7kr0Ozm5N6nrGNNY5XlVIzE3i7Fqw96cGL8L7bNJBr3AIBaK5Il7RuIQT1nsFPJS810Ery0N9Hi5k96xn90UI80Joqg5DF7QRCWJF314159265358979323846dTVFQxiECjT5nYFX6Uw47fS3lhiEApOtuy1ghNiQbJzpjm67LKaxiEq8bAEXDQeEneLlixqi8AlYgan30RVlWJz2WEykIYH5LMcykwgPGNXOrPBzy63MCS3TB71I9yYar9eMqGRc4sz30GzU19v3rNohnMX5iaPSlkVPQB7kY2qpWaHe4gDjkOi69vErtRXON0Xqo6mvr1a8Ce980LT3X9jreKoDX5q33lSVxjlYBBlDYrRzNIWqrZr1YYkupuZM0wn9q8P9W86iTGf5GR705WWj5OKUjE6f1Z7Ro3P838mqrqYImc3qMV8wbnQ8Ogz8Fkxscc7F7lq06q0DkpUK7BK5mxBe046QrtyiuEYj999qFdo4nA9Exfw9xvi77WofVQ31tTBu3HZJsB3ypyZp3Omn2I7gsOQm89nXrDXOXalI4N1nvGRARtExOo5tN3WIlVVkrKeyvrDOQpT2rEIgsnDoTiy2jRZig0RmPA2718281828459045235w5f9780gQetd63mnIF4sg4tkhx0g2lR9ZNn70ZUZNzkxvIYfO4jnMPtcM7a1ek8f2rp0znURrnA8VB1Ak0uY3AmK9DoEHcJmodGNGliF7L5LVP7ABzPfKKMCdtAu6zZgW0XsPPs4WYy9jlkG25973qp678lKmN0LAdOaHT72lFrr9frau1402jqCHZqIy4qcRYyeCOrD0IkqZT9izDv59Z3b9fdkyoo5sO8AWFGerJ9vVT5m5mSzd8bWZZ7dss4XYHk3UORyLi1gpbKlT1QZbypPx0eF18TA6wuban93JZmfOngzx2kTNoRXa911ififrUt56nIuRtY324NPpvt7Rixl4X2YZzbOLm4L5kew9fv1BZvZQOPtLuQ7If368aUQnpV04D7TAkb1qbQbOKmkOVPgA7d0LMtlYwZbNRI97KiRHtsqGbNf70mvGj2lj1QF3Uv0sW1e7YliNp1w5M8lyHGpVVW7uBdyqKqXzGkqSa9DW527qbPHZPM1nCN;ToCharacterCode@#,wm;2,Yr3TLDuNJKQ2NHCv9;8])),hmPvHeg3R2mw02;Array[yruQ95uaGFdJu1;PrimeQ,Tr[GjbUXt;0l+1],Xxt;0]],8La1ktK9xi3XXf;#==(UISzsyNOrrXj0eSRMrbIzDOVjfKK0IazH6JdZQY7lzBolXGwU98mJjINCzp7pROIx1rwaTo1JdOSyw6Lw3KVXu85AxiKM7Q2EsvUEQaq8rMhAwdsgWYO21aAVLwuoz5Uz8NnASPJmW4f04z1kgUrAfMjZ0VAFaM2405222oU3y0yc5nxVmKd7AcA5gwCa3labMkKF7lMq5o8prUSy1AVTxNH7E46LVYWjxyw6Q6YRzNPSRJJWtjhVGt8tMkj;i=1-i)&]]Df]& ``` Takes a string as an input. Prints `True` or `False`. This works because Mathematica ignores undefined variables/functions. Because this code is so long, I stuck some easter eggs in there. :) I'm sure this can be golfed more... **Explanation** Without all the gibberish (99 bytes): ``` AllTrue[Pick[l=Join@@IntegerDigits[ToCharacterCode@#,2,8],Array[PrimeQ,Tr[0l+1],i=0]],#==(i=1-i)&]& ``` --- ``` ToCharacterCode@# ``` Convert the input into character codes. ``` IntegerDigits[ToCharacterCode@#,2,8] ``` Convert the character codes into binary numbers, length 8. ``` l=Join@@IntegerDigits[ToCharacterCode@#,2,8] ``` Flatten the result and store that in `l`. This generates the bit list of the input. --- ]
[Question] [ There's a river and there are wolves and chickens on one side of the river. They have a raft and they all need to get to the other side. However, the raft cannot travel on its own. The raft will sink if more than two animals are on it. None of the animals want to get wet because the river's cold and dirty. None of the animals can jump or fly over the river. Also, if there are chickens on one side, there cannot be more wolves on that side than there are chickens on that side -- the wolves will then decide to eat the chickens. This means that you cannot take two wolves on the raft to a side with one chicken. Your task is to make a program/function that takes a number of wolves and a number of chickens (greater than or equal to the number of wolves) as input and finds the smallest number of times the raft has to move across the river. If the task is not possible, the program/function should output/return an empty string. It will then print/return one method as to how this is done in the following way: ``` W if a wolf crosses the river on its own C if a chicken crosses the river on its own CW if a chicken and a wolf cross the river -- WC is also fine CC if two chickens cross the river WW if two wolves cross the river ``` As you can deduce, the raft will automatically move in alternating directions (left and right, starting from left to right as the first one or two animals cross the river). This doesn't need to be outputted/returned. 'W', 'C', 'CW', 'CC' or 'WW' in the output may be separated by at least one of the following: ``` spaces (' ') commas (',') newlines ``` Alternatively, you may store the directions as items in a list (an empty list means no solution). Test cases (output separated by commas -- input takes the form `wolves,chickens`): ``` 1,1 -> CW 2,2 -> CW,C,CC,C,CW 1,2 -> CW,W,CW 0,10 -> CC,C,CC,C,CC,C,CC,C,CC,C,CC,C,CC,C,CC,C,CC 3,2 -> no solution ``` Try to make your code as short in bytes as possible. [Answer] # Perl, ~~179~~ ~~165~~ ~~164~~ ~~163~~ ~~157~~ 156 bytes Includes +4 for `-p` Give wolves followed by chickens on STDIN ``` river.pl <<< "2 3" ``` Outputs the boat contents per line. For this example it gives: ``` WC C CC C CC W WW ``` `river.pl`: ``` #!/usr/bin/perl -p / /;@F=w x$`.c x$'."\xaf\n";$a{$`x/\n/}++||grep(y/c//<y/w//&/c/,$_,~$_)or$\||=$' x/^\w*\n|(\w?)(.*)(c|w)(.+)\n(?{push@F,$1.$3.~"$`$2$4\xf5".uc"$'$1$3\n"})^/ for@F}{ ``` Works as shown, but replace `\xhh` and `\n` by their literal versions to get the claimed score. This will probably be beaten by a program that solves the general case (C>W>0) ``` * output `WC W WC C` until there is only one wolf left on the left bank (--w, --c) * output `CC C` until there is only one chicken left on the left bank (--c) * output `WC` ``` Add to that the trivial solutions for only wolves and only chickens and a hardcoded special case for `2 2` and `3 3` (`4 4` and higher have no solution). But that would be a boring program. ## Explanation The current state of the field is stored as a single string consisting of: * `w` for a wolf on the bank with the boat * `c` for a chicken on the bank with the boat * `\x88` (bit reversed `w`) for a wolf on the other bank * `\x9c` (bit reversed `c`) for a chicken on the other bank * A character indicating the side the boat is on `P` for the right bank, `\xaf` (bit reversed `P`) for the left bank (starting side) * a newline `\n` * all the moves that have been done upto now terminated with newlines, e.g. something like `WC\nW\nWC\nC\n` (notice the `W`s and `C` are in uppercase here) The array `@F` will contain all reachable states. It is initialised by the starting string `wolves times "w", chickens times "c", \xaf \n` The program then loops over `@F` which will get extended during the looping so new states get processed too. For every element it then does: * Look at the string part left of the first `\n` which represents the current position of the animals and the boat. If that has been seen before skip `$a{$`x/\n/}++` * Check if there are chickens together with more wolves on any side. Skip if so `grep(y/c//<y/w//&/c/,$_,~$_)` * Check if the boat is the far side together with all animals. If so we have a solution. Store that in `$\` and keep that since the first solution found is the shortest `$\||=$' x/^\w*\n/` * Otherwise try all ways of selecting 1 or 2 animals on the side with the boat. These are the `c` and `w` characters. (The animals at the other side won't match `\w`) `/(\w?)(.*)(c|w)(.+)\n(?{code})^/`. Then bit reverse the whole string before the `\n` except the animals that were selected for the boat `push@F,$1.$3.~"$`$2$4\xf5"`. Add the selected animals to the moves by uppercasing them: `uc"$'$1$3\n"` The animal selection process effectively shuffles the string part representing them in many ways. So e.g. `wcwc` and `wwcc` can both get to represent 2 wolves and 2 chickens. The state check `$a{$`x/\n/}++` will unnessarily distinguish these two so many more states than necessary will be generated and checked. Therefore the program will run out of memory and time as soon as the number of different animals gets larger. This is mitigated only a bit by the fact that the current version will stop adding new states once a solution is found [Answer] ## JavaScript (ES6), ~~251~~ ~~264~~ ... ~~244~~ 240 bytes Takes the number of wolves and chickens `(w, c)` and returns one of the optimal solutions, or `undefined` if there's no solution. ``` (w,c,v={},B=1/0,S)=>(r=(s,w,c,W=0,C=0,d=1,N=0,k=w+'|'+c+d)=>v[k]|c*w>c*c|C*W>C*C|w<0|c<0|W<0|C<0?0:w|c?[v[k]=1,2,4,8,5].map(n=>r(s+'C'.repeat(b=n>>2)+'W'.repeat(a=n&3)+' ',w-d*a,c-d*b,W+d*a,C+d*b,-d,N+1))&(v[k]=0):N<B&&(B=N,S=s))('',w,c)||S ``` ### Formatted and commented Wrapper function: ``` ( // given: w, // - w : # of wolves c, // - c : # of chickens v = {}, // - v : object keeping track of visited nodes B = 1 / 0, // - B : length of best solution S // - S : best solution ) => ( // r = (...) => ... // process recursive calls (see below) )('', w, c) || S // return the best solution ``` Main recursive function: ``` r = ( // given: s, // - s : current solution (as text) w, c, // - w/c : # of chickens/wolves on the left side W = 0, C = 0, // - W/C : # of chickens/wolves on the right side d = 1, // - d : direction (1:left to right, -1:right to left) N = 0, // - N : length of current solution k = w + '|' + c + d // - k : key identifying the current node ) => // v[k] | // abort if this node was already visited c * w > c * c | C * W > C * C | // or there are more wolves than chickens somewhere w < 0 | c < 0 | W < 0 | C < 0 ? // or we have created antimatter animals 0 // : // else: w | c ? // if there are still animals on the left side: [v[k] = 1, 2, 4, 8, 5].map(n => // set node as visited and do a recursive call r( // for each combination: W, WW, C, CC and CW s + 'C'.repeat(b = n >> 2) + // append used combination to current solution 'W'.repeat(a = n & 3) + ' ', // wolves = bits 0-1 of n / chickens = bits 2-3 w - d * a, // update wolves on the left side c - d * b, // update chickens on the left side W + d * a, // update wolves on the right side C + d * b, // update chickens on the right side -d, // use opposite direction for the next turn N + 1 // increment length of current solution ) // ) & // once we're done, (v[k] = 0) // set this node back to 'not visited' : // else: N < B && // save this solution if it's shorter than the (B = N, S = s) // best solution encountered so far ``` ### Test cases ``` let f = (w,c,v={},B=1/0,S)=>(r=(s,w,c,W=0,C=0,d=1,N=0,k=w+'|'+c+d)=>v[k]|c*w>c*c|C*W>C*C|w<0|c<0|W<0|C<0?0:w|c?[v[k]=1,2,4,8,5].map(n=>r(s+'C'.repeat(b=n>>2)+'W'.repeat(a=n&3)+' ',w-d*a,c-d*b,W+d*a,C+d*b,-d,N+1))&(v[k]=0):N<B&&(B=N,S=s))('',w,c)||S console.log(f(1, 1)); console.log(f(2, 2)); console.log(f(1, 2)); console.log(f(0, 10)); console.log(f(3, 2)); ``` [Answer] # CJam, 133 ``` q~[0_]]_0+a:A;a{{28e3Zb2/{[YT2*(f*_Wf*]X..+:Bs'-&B2<{~_@<*},+{B2<T!+a:CA&{AC+:A;BY"WC".*a+}|}|}fY}fX]T!:T;__!\{0=:+!},e|:R!}g;R0=2>S* ``` [Try it online](http://cjam.aditsu.net/#code=q~%5B0_%5D%5D_0%2Ba%3AA%3Ba%7B%7B28e3Zb2%2F%7B%5BYT2*(f*_Wf*%5DX..%2B%3ABs'-%26B2%3C%7B~_%40%3C*%7D%2C%2B%7BB2%3CT!%2Ba%3ACA%26%7BAC%2B%3AA%3BBY%22WC%22.*a%2B%7D%7C%7D%7C%7DfY%7DfX%5DT!%3AT%3B__!%5C%7B0%3D%3A%2B!%7D%2Ce%7C%3AR!%7Dg%3BR0%3D2%3ES*&input=%5B3%203%5D) **Explanation:** Basically the program does a BFS and remembers every state it reached in order to avoid infinite cycles. The working states are represented like [[Wl Cl] [Wr Cr] M1 M2 … Mn] where W = wolves, C = chickens, l = left side, r = right side, M = moves made so far (initially none), and the moves are like "C", "WC" or "WW" etc (practically more like ["" "C"], ["W" "C"], ["WW" ""], but it's the same when printing). The remembered states are represented like [[Wl Cl] [Wr Cr] S] where S is the side with the boat (0=left, 1=right). ``` q~ read and evaluate the input ([Wl Cl] array) [0_] push [0 0] as the initial [Wr Cr] array ]_ wrap both in an array (initial working state) and duplicate it 0+a append 0 (representing left side) and wrap in an array :A; store in A and pop; this is the array of remembered states a wrap the working state in an array {…}g do … while {…}fX for each working state X 28e3Zb2/ convert 28000 to base 3 and group the digits into pairs this generates [[1 1] [0 2] [1 0] [2 0] [0 1]] which are all possible moves represented as [Wb Cb] (b=boat) {…}fY for each "numeric move" pair Y […] make an array of… YT2*(f* Y negated if T=0 (T is the current boat side, initially 0) _Wf* and the (arithmetic) negation of the previous pair X..+ add the 2 pairs to X, element by element this performs the move by adding & subtracting the numbers from the appropriate sides, determined by T :Bs store the updated state in B, then convert to string '-& intersect with "-" to see if there was any negative number B2< also get just the animal counts from B (first 2 pairs) {…}, filter the 2 sides by checking… ~_@<* if W>C>0 (it calculates (C<W)*C) + concatenate the results from the negative test and eating test {…}| if it comes up empty (valid state)… B2< get the animal counts from B (first 2 pairs) T!+ append !T (opposite side) a:C wrap in an array and store in C A& intersect with A to see if we already reached that state {…}| if not, then… AC+:A; append C to A BY push B and Y (updated state and numeric move) "WC".* repeat "W" and "C" the corresponding numbers of times from Y to generate the alphabetic move a+ wrap in array and append to B (adding the current move) ] collect all the derived states in an array T!:T; reverse the side with the boat __! make 2 copies of the state array, and check if it's empty \{…}, filter another copy of it, checking for each state… 0=:+! if the left side adds up to 0 e|:R logical "or" the two and store the result in R ! (logically) negate R, using it as a do-while condition the loop ends when there are no more working states or there are states with the left side empty ; after the loop, pop the last state array R0=2>S* if the problem is solved, R has solution states, and this extracts the moves from the first state and joins them with space if there's no solution, R=1 and this repeats a space 0 times, resulting in empty string ``` [Answer] # [Perl 6](http://perl6.org/), 268 bytes ``` ->*@a {( [X](0 X..@a)[1..*-2] .grep({![>](|$_,0)&![>](|(@a Z-$_),0)}) .combinations(2) .combinations .map(|*.permutations) .map({.map(|*)»[*]}) .map({((|$_,(0,0)ZZ-@a,|$_)ZX*|(-1,1)xx*)»[*]}) .grep({.all.&{.all>=0&&3>.sum>0}}) .map({.map:{[~](<W C>Zx$_)}}) if [<=] @a )[0]//()} ``` Generates increasingly longer chains of `(wolf count, chicken count)` states for the left bank, and returns the first one that matches all the rules. Turns out this approach is neither efficient nor very concise, but at least it was fun to write. I don't think I've never stacked the `Z` (zip) and `X` (cross) meta-operators before, like the `ZZ-` and `ZX*` here - kinda surprised that actually worked. *(The newlines are just added for display purposes, and aren't part of the byte count.)* [Answer] # JavaScript (ES6), 227 ~~237~~ Basically it does a BFS and remembers every state it reached in order to avoid infinite cycles. ~~Unlike @aditsu's, I don't think there's any room for golfing~~ ``` v=>g=>eval("o=[],s=[[v,g,0,k=[]]];for(i=0;y=s[i++];k[y]=k[y]||['WW','C','CC','W','CW'].map((u,j)=>(r=w-(j?j/3|0:2),q=c-j%3,d=g-q,e=v-r,r<0|q<0|!!q&r>q|!!d&e>d)||s.push([e,d,!z,[...p,u]])))o=([w,c,z,p]=y,y[3]=!z|c-g|w-v)?o:i=p") ``` *Less golfed* ``` (v,g) => { o = []; // output k = []; // hashtable to check states already seen s=[[v, g, 0, []]]; // states list: each element is wolves,chickens,side,path for(i = 0; y = s[i++]; // exit loop when there are no more states to expand ) { [w, c, z, p] = x; // wolves on this side, chickens on this side, side, path if (z && c==g && w==v) // if all chicken and wolves on the other side o = p, // the current path is the output i = p // this will force the loop to terminate y[3] = 0; // forget the path, now I can use y as the key to check state and avoid cycles if (! k[y]) // it's a new state { k[y] = 1; // remember it ['WW','C','CC','W','CW'].map( (u,j)=> ( a = j ? j/3|0 : 2, // wolves to move b = j % 3, // chicken to move r = w - a, // new number of wolves on this side q = c - b, // new number of chickens on this side e = v - r, // new number of wolves on other side d = g - q, // new number of chickens on other side // check condition about the number of animals together // if ok, push a new state r<0 |q<0 | !!q&r>q | !!d&e>d || s.push([e, d, !z, [...p,u]) ) } } return o } ``` **Test** ``` F= v=>g=>eval("o=[],s=[[v,g,0,k=[]]];for(i=0;y=s[i++];k[y]=k[y]||['WW','C','CC','W','CW'].map((u,j)=>(r=w-(j?j/3|0:2),q=c-j%3,d=g-q,e=v-r,r<0|q<0|!!q&r>q|!!d&e>d)||s.push([e,d,!z,[...p,u]])))o=([w,c,z,p]=y,y[3]=!z|c-g|w-v)?o:i=p") function update() { var c=+C.value, w=+W.value O.textContent=F(w)(c) } update() ``` ``` input { width: 4em } ``` ``` Chickens <input id=C value=2 type=number min=0 oninput='update()'> Wolves <input id=W value=2 type=number min=0 oninput='update()'> <pre id=O></pre> ``` ]
[Question] [ # History My company sends out a weekly newsletter to everyone within the company. Included in these newsletters is a riddle, along with a shoutout to whomever in the company was the first to email/provide a solution to last week's riddle. Most of these riddles are quite trivial, and honestly pretty dull for a tech company, but there was one, several months back, that caught my attention. ## The Original Riddle: Given the shape below: [![Puzzle Image](https://i.stack.imgur.com/6ebSZ.png)](https://i.stack.imgur.com/6ebSZ.png) You have the Natural Numbers from 1 to 16. Fit them all into this shape, such that all the contiguous rows and contiguous columns sum up to 29. For example, one such solution to this puzzle (which was the "canonical" solution I submitted to the newsletter) was the following: [![Solved Puzzle Image](https://i.stack.imgur.com/1531F.png)](https://i.stack.imgur.com/1531F.png) However, in the course of solving it, I found some rather interesting information: * There are significantly more solutions than just that one; in fact, there are 9,368 Solutions. * If you expand the ruleset to only require that rows and columns be equal to each other, not necessarily 29, you get 33,608 solutions: + 4,440 Solutions for a sum of 27. + 7,400 Solutions for a sum of 28. + 9,368 Solutions for a sum of 29. + 6,096 Solutions for a sum of 30. + 5,104 Solutions for a sum of 31. + 1,200 Solutions for a sum of 32. So me and my coworkers (though mostly just my manager, since he was the only other person than me with "General Purpose" programming skills) set out on a challenge, that lasted for most of the month—we had other, actual job-related obligations we had to attend to—to try to write a program which would find every single solution in the fastest way possible. ## Original Statistics The very first program I wrote to solve the problem simply checked random solutions over and over, and stopped when it found a solution. If you've done Mathematical analysis on this problem, you probably already know that this shouldn't have worked; but somehow I got lucky, and it took the program only a minute to find a single solution (the one I posted above). Repeat runs of the program often took as much as 10 or 20 minutes, so obviously this wasn't a rigorous solution to the problem. I switched over to a Recursive Solution which iterated through every possible permutation of the puzzle, and discarded lots of solutions at once by eliminating sums that weren't adding up. I.E. if the first row/column I was comparing already weren't equal, I could stop checking that branch immediately, knowing that nothing else permuted into the puzzle would change that. Using this algorithm, I got the first "proper" success: the program could generate and spit out all 33,608 solutions in about 5 minutes. My manager had a different approach: knowing based on my work that the only possible solutions had sums of 27, 28, 29, 30, 31, or 32, he wrote a multi-threaded solution which checked possible sums only for those specific values. He managed to get his program to run in only 2 minutes. So I iterated again; I hashed all possible 3/4 digit sums (at the start of the program; it's counted in the total runtime) and used the "partial sum" of a row to look-up the remaining value based on a previously completed row, rather than testing all remaining values, and brought the time down to 72 seconds. Then with some multi-threading logic, I got it down to 40 seconds. My manager took the program home, performed some optimizations on how the program ran, and got his down to 12 seconds. I reordered the evaluation of the rows and columns, and got mine down to 8 seconds. The fastest either of us got our programs after a month was 0.15 seconds for my manager, and 0.33 seconds for me. I ended up claiming that my program was faster though, since my manager's program, while it did *find* all solutions, wasn't printing them out into a text file. If he added that logic to his code, it often took upwards of 0.4-0.5 seconds. We've since allowed our intra-personal challenge to subsist, but of course, the question remains: *can* this program be made faster? That's the challenge I'm going to pose to you guys. # Your Challenge The parameters we worked under relaxed the "sum of 29" rule to instead be "all rows/columns' sums equal", and I'm going to set that rule for you guys too. The Challenge, therefore, is: Write a program that finds (and Prints!) all solutions to this riddle in the shortest time possible. I'm going to set a ceiling on submitted solutions: If the program takes more than 10 seconds on a relatively decent computer (<8 years old), it's probably too slow to be counted. Also, I have a few Bonuses for the puzzle: * Can you generalize the solution so that it works for any set of 16 numbers, not just `int[1,16]`? Timing score would be evaluated based on the original prompt number set, but passed through this codepath. (-10%) * Can you write the code in a way that it gracefully handles and solves with duplicate numbers? This isn't as straightforward as it might seem! Solutions which are "visually identical" should be unique in the result set. (-5%) * Can you handle negative numbers? (-5%) You can also *try* to generate a solution that handles Floating-Point Numbers, but of course, don't be shocked if that fails utterly. If you do find a robust solution though, that might be worth a large bonus! For all intents and purposes, "Rotations" are considered to be unique solutions. So a solution that is just a rotation of a different solution counts as its own solution. The IDEs I have working on my computer are Java and C++. I can accept answers from other languages, but you may need to also provide a link to where I can get an easy-to-setup runtime environment for your code. [Answer] # C - near 0.5 sec This very naive program give all the solutions in half a second on my 4 years old laptop. No multithread, no hashing. Windows 10, Visual Studio 2010, CPU core I7 64 bit Try online on [ideone](http://ideone.com/QSC0G3) ``` #include <stdio.h> #include <time.h> int inuse[16]; int results[16+15+14]; FILE *fout; int check(int number) { if (number > 0 && number < 17 && !inuse[number-1]) { return inuse[number-1]=1; } return 0; } void free(int number) { inuse[number-1]=0; } void out(int t, int* p) { int i; fprintf(fout, "\n%d",t); for(i=0; i< 16; i++) fprintf(fout, " %d",*p++); } void scan() { int p[16]; int t,i; for (p[0]=0; p[0]++<16;) if (check(p[0])) { for (p[1]=0; p[1]++<16;) if (check(p[1])) { for (p[2]=0; p[2]++<16;) if (check(p[2])) { t = p[0]+p[1]+p[2]; // top horiz: 0,1,2 for (p[7]=0; p[7]++<16;) if (check(p[7])) { if (check(p[11] = t-p[7]-p[2])) // right vert: 2,7,11 { for(p[9]=0; p[9]++<16;) if (check(p[9])) { for (p[10]=0; p[10]++<16;) if (check(p[10])) { if (check(p[12] = t-p[9]-p[10]-p[11])) // right horiz: 9,10,11,12 { for(p[6]=0; p[6]++<16;) if (check(p[6])) { if (check(p[15] = t-p[0]-p[6]-p[9])) // middle vert: 0,6,9,15 { for(p[13]=0; p[13]++<16;) if (check(p[13])) { if (check(p[14] = t-p[13]-p[15])) // bottom horiz: 13,14,15 { for(p[4]=0; p[4]++<16;) if (check(p[4])) { if (check(p[8] = t-p[4]-p[13])) // left vert: 4,8,13 { for(p[3]=0; p[3]++<16;) if (check(p[3])) { if (check(p[5] = t-p[3]-p[4]-p[6])) // left horiz: 3,4,5,6 { ++results[t]; out(t,p); free(p[5]); } free(p[3]); } free(p[8]); } free(p[4]); } free(p[14]); } free(p[13]); } free(p[15]); } free(p[6]); } free(p[12]); } free(p[10]); } free(p[9]); } free(p[11]); } free(p[7]); } free(p[2]); } free(p[1]); } free(p[0]); } for(i=0;i<15+16+14;i++) { if(results[i]) printf("%d %d\n", i, results[i]); } } void main() { clock_t begin, end; double time_spent; begin = clock(); fout = fopen("c:\\temp\\puzzle29.txt", "w"); scan(); fclose(fout); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("Time %g sec\n", time_spent); } ``` [Answer] # C++ - 300 Milliseconds Per request, I've added my own code to solve this puzzle. On my computer, it clocks in at an average of 0.310 seconds (310 milliseconds) but depending on variance can run as quickly as 287 milliseconds. I very rarely see it rise above 350 milliseconds, usually only if my system is bogged down with a different task. These times are based on the self-reporting used in the program, but I also tested using an external timer and get similar results. Overhead in the program seems to add about 10 milliseconds. Also, my code doesn't *quite* handle duplicates correctly. It can solve using them, but it doesn't eliminate "visually identical" solutions from the solution set. ``` #include<iostream> #include<vector> #include<random> #include<functional> #include<unordered_set> #include<unordered_map> #include<array> #include<thread> #include<chrono> #include<fstream> #include<iomanip> #include<string> #include<mutex> #include<queue> #include<sstream> #include<utility> #include<atomic> #include<algorithm> //#define REDUCE_MEMORY_USE typedef std::pair<int, std::vector<std::pair<int, int>>> sumlist; typedef std::unordered_map<int, std::vector<std::pair<int, int>>> summap; typedef std::array<int, 16> solution_space; class static_solution_state { public: std::array<int, 16> validNumbers; summap twosums; size_t padding; std::string spacing; static_solution_state(const std::array<int, 16> & _valid); summap gettwovaluesums(); std::vector<sumlist> gettwovaluesumsvector(); }; static_solution_state::static_solution_state(const std::array<int, 16> & _valid) : validNumbers(_valid) { twosums = gettwovaluesums(); padding = 0; for (int i = 0; i < 16; i++) { size_t count = std::to_string(validNumbers[i]).size(); if (padding <= count) padding = count + 1; } spacing.resize(padding, ' '); } class solution_state { private: const static_solution_state * static_state; public: std::array<int, 16> currentSolution; std::array<bool, 16> used; std::array<int, 7> sums; size_t solutions_found; size_t permutations_found; size_t level; std::ostream * log; solution_state(const static_solution_state & _sstate); solution_state(static_solution_state & _sstate) = delete; void setLog(std::ostream & out); const int & operator[](size_t index) const; }; solution_state::solution_state(const static_solution_state & _sstate) { static_state = &_sstate; sums = { 0 }; used = { false }; currentSolution = { -1 }; solutions_found = 0; permutations_found = 0; level = 0; } void solution_state::setLog(std::ostream & out) { log = &out; } const int & solution_state::operator[](size_t index) const { return static_state->validNumbers[currentSolution[index]]; } int getincompletetwosum(const static_solution_state & static_state, const solution_state & state); void permute(const static_solution_state & static_state, solution_state & state, volatile bool & reportProgress, const volatile size_t & total_tests, volatile bool & done); void setupOutput(std::fstream & out); void printSolution(const static_solution_state & static_state, const solution_state & state); constexpr size_t factorial(const size_t iter); const bool findnext2digits[16]{ false, false, false, true, false, false, true, false, true, false, true, false, true, false, true, false }; const int currentsum[16]{ 0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6 }; const int twosumindexes[7][2]{ { 0, -1}, { 2, -1}, { 5, -1}, { 5, -1}, { 0, 7}, { 11, 4}, { 10, 9} }; const std::array<size_t, 17> facttable = [] { std::array<size_t, 17> table; for (int i = 0; i < 17; i++) table[i] = factorial(i); return table; }(); const int adj = 1; std::thread::id t1id; int main(int argc, char** argv) { //std::ios_base::sync_with_stdio(false); std::array<int, 16> values = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 }; if (argc == 17) { for (int i = 0; i < 16; i++) { values[i] = atoi(argv[i + 1]); } } auto start = std::chrono::high_resolution_clock::now(); const static_solution_state static_state(values); #if defined(REDUCE_MEMORY_USE) const int num_of_threads = max(1u, min(thread::hardware_concurrency(), 16u)); #else const int num_of_threads = 16; #endif std::vector<solution_state> states(num_of_threads, static_state); for (int i = 0; i < num_of_threads; i++) { int start = i * 16 / num_of_threads; states[i].permutations_found += start * factorial(16) / 16; } std::fstream out; setupOutput(out); std::locale loc(""); std::cout.imbue(loc); volatile bool report = false; volatile bool done = false; volatile size_t tests = 0; std::thread progress([&]() { auto now = std::chrono::steady_clock::now(); while (!done) { if (std::chrono::steady_clock::now() - now > std::chrono::seconds(1)) { now += std::chrono::seconds(1); size_t t_tests = 0; for (int i = 0; i < num_of_threads; i++) t_tests += states[i].permutations_found - i * factorial(16) / num_of_threads; tests = t_tests; report = true; } std::this_thread::yield(); } }); if (num_of_threads <= 1) { states[0].setLog(out); permute(static_state, states[0], report, tests, done); } else { std::vector<std::thread> threads; #if defined(REDUCE_MEMORY_USE) std::vector<std::fstream> logs(num_of_threads); #else std::vector<std::stringstream> logs(num_of_threads); #endif for (int i = 0; i < num_of_threads; i++) { threads.emplace_back([&, i]() { if (i == 0) t1id = std::this_thread::get_id(); int start = i * 16 / num_of_threads; int end = (i + 1) * 16 / num_of_threads; #if defined(REDUCE_MEMORY_USE) logs[i].open("T"s + to_string(i) + "log.tmp", ios::out); #endif logs[i].imbue(loc); states[i].setLog(logs[i]); for (int j = start; j < end; j++) { states[i].currentSolution = { j }; states[i].level = 1; states[i].used[j] = true; permute(static_state, states[i], report, tests, done); } }); } std::string buffer; for (int i = 0; i < num_of_threads; i++) { threads[i].join(); #if defined(REDUCE_MEMORY_USE) logs[i].close(); logs[i].open("T"s + to_string(i) + "log.tmp", ios::in); logs[i].seekg(0, ios::end); auto length = logs[i].tellg(); logs[i].seekg(0, ios::beg); buffer.resize(length); logs[i].read(&buffer[0], length); logs[i].close(); remove(("T"s + to_string(i) + "log.tmp").c_str()); out << buffer; #else out << logs[i].str(); #endif } } done = true; out.close(); if (num_of_threads > 1) { size_t t_tests = 0; for (int i = 0; i < num_of_threads; i++) t_tests += states[i].permutations_found - i * factorial(16) / num_of_threads; tests = t_tests; } size_t solutions = 0; for (const auto & state : states) { solutions += state.solutions_found; } auto end = std::chrono::high_resolution_clock::now(); progress.join(); auto duration = end - start; auto secondsDuration = std::chrono::duration_cast<std::chrono::milliseconds>(duration); std::cout << "Total time to process all " << tests << " results: " << std::setprecision(3) << std::setiosflags(std::ostream::fixed) << (secondsDuration.count()/1000.0) << "s" << "\n"; std::cout << "Solutions found: " << solutions << std::endl; //system("pause"); return 0; } void permute(const static_solution_state & static_state, solution_state & state, volatile bool & reportProgress, const volatile size_t & total_tests, volatile bool & done) { if (done) return; if (state.level >= 16) { if (reportProgress) { reportProgress = false; std::cout << "Current Status:" << "\n"; std::cout << "Test " << total_tests << "\n"; std::cout << "Contents: {"; for (int i = 0; i < 15; i++) std::cout << std::setw(static_state.padding - 1) << state[i] << ","; std::cout << std::setw(static_state.padding - 1) << state[15] << "}" << "(Partial Sum: " << state.sums[0] << ")" << "\n"; std::cout << "=====================" << "\n"; } printSolution(static_state,state); state.solutions_found++; state.permutations_found++; } else { if (state.level == 3) state.sums[0] = state[0] + state[1] + state[2]; if (!findnext2digits[state.level]) { for (int i = 0; i < 16; i++) { if (!state.used[i]) { state.currentSolution[state.level] = i; state.used[i] = true; state.level++; permute(static_state, state, reportProgress, total_tests, done); state.level--; state.used[i] = false; } } } else { int incompletetwosum = getincompletetwosum(static_state, state); if (static_state.twosums.find(incompletetwosum) == static_state.twosums.end()) { state.permutations_found += facttable[16 - state.level]; } else { size_t successes = 0; const std::vector<std::pair<int, int>> & potentialpairs = static_state.twosums.at(incompletetwosum); for (const std::pair<int, int> & values : potentialpairs) { if (!state.used[values.first] && !state.used[values.second]) { state.currentSolution[state.level] = values.first; state.currentSolution[state.level + 1] = values.second; state.used[values.first] = true; state.used[values.second] = true; state.level += 2; permute(static_state, state, reportProgress, total_tests, done); state.level -= 2; state.used[values.first] = false; state.used[values.second] = false; successes++; } } state.permutations_found += facttable[16 - state.level - 2] * ((16 - state.level) * (15 - state.level) - successes); } } } } int getincompletetwosum(const static_solution_state & static_state, const solution_state & state) { int retvalue = state.sums[0]; int thissum = currentsum[state.level]; for (int i = 0; i < 2 && twosumindexes[thissum][i] >= 0; i++) { retvalue -= state[twosumindexes[thissum][i]]; } return retvalue; } constexpr size_t factorial(size_t iter) { return (iter <= 0) ? 1 : iter * factorial(iter - 1); } void setupOutput(std::fstream & out) { out.open("puzzle.txt", std::ios::out | std::ios::trunc); std::locale loc(""); out.imbue(loc); } void printSolution(const static_solution_state & static_state, const solution_state & state) { std::ostream & out = *state.log; out << "Test " << state.permutations_found << "\n"; static const auto format = [](std::ostream & out, const static_solution_state & static_state, const solution_state & state, const std::vector<int> & inputs) { for (const int & index : inputs) { if (index < 0 || index >= 16) out << static_state.spacing; else out << std::setw(static_state.padding) << state[index]; } out << "\n"; }; format(out, static_state, state, { -1, -1, -1, 0, 1, 2 }); format(out, static_state, state, { 15, 9, 14, 10, -1, 3 }); format(out, static_state, state, { -1, 8, -1, 11, 12, 4, 13 }); format(out, static_state, state, { -1, 5, 6, 7}); out << "Partial Sum: " << (state.sums[0]) << "\n"; out << "=============================" << "\n"; } summap static_solution_state::gettwovaluesums() { summap sums; for (int i = 0; i < 16; i++) { for (int j = 0; j < 16; j++) { if (i == j) continue; std::pair<int,int> values( i, j ); int sum = validNumbers[values.first] + validNumbers[values.second]; sums[sum].push_back(values); } } return sums; } std::vector<sumlist> static_solution_state::gettwovaluesumsvector() { std::vector<sumlist> sums; for (auto & key : twosums) { sums.push_back(key); } std::sort(sums.begin(), sums.end(), [](sumlist a, sumlist b) { return a.first < b.first; }); return sums; } ``` [Answer] # Prolog - 3 minutes This kind of puzzle seems like a perfect use-case for Prolog. So, I coded up a solution in Prolog! Here it is: ``` :- use_module(library(clpfd)). puzzle(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) :- Vars = [P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15], Vars ins 1..16, all_different(Vars), 29 #= P0 + P1 + P2, 29 #= P3 + P4 + P5 + P6, 29 #= P9 + P10 + P11 + P12, 29 #= P13 + P14 + P15, 29 #= P0 + P6 + P9 + P15, 29 #= P2 + P7 + P11, 29 #= P4 + P8 + P13. ``` Unfortunately, it's not as fast as I expected. Maybe someone more well-versed in declarative programming (or Prolog specifically) can offer some optimization tips. You can invoke the rule `puzzle` with the following command: ``` time(aggregate_all(count, (puzzle(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15), labeling([leftmost, up, enum], [P9, P15, P13, P0, P4, P2, P6, P11, P1, P5, P3, P7, P14, P12, P10, P8])), Count)). ``` Try it out online [here](http://swish.swi-prolog.org/p/lTHeFADF.pl). You can substitute any number in place of the `29`s in the code to generate all solutions. As it stands, all 29-solutions are found in approximately 30 seconds, so to find all possible solutions should be approximately 3 minutes. ]
[Question] [ ## Introduction A *pointer array* is an array `L` of nonzero integers where `0 ≤ L[i]+i < len(L)` holds for all indices `i` (assuming 0-based indexing). We say that the index `i` *points* to the index `L[i]+i`. A pointer array is a *loop* if the indices form a single cycle of length `len(L)`. Here are some examples: * `[1,2,-1,3]` is not a pointer array, because the `3` does not point to an index. * `[1,2,-1,-3]` is a pointer array, but not a loop, because no index points to the `-1`. * `[2,2,-2,-2]` is a pointer array, but not a loop, because the indices form two cycles. * `[2,2,-1,-3]` is a loop. ## Input Your input is a non-empty list of nonzero integers, in any reasonable format. It may be unsorted and/or contain duplicates. ## Output Your output shall be a loop that contains all the integers in the input list (and possibly other integers too), counting multiplicities. They need not occur in the same order as in the input, and the output need not be minimal in any sense. ## Example For the input `[2,-4,2]`, an acceptable output would be `[2,2,-1,1,-4]`. ## Rules and scoring You can write a full program or a function. The lowest byte count wins, and [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/) are disallowed. Including a couple of example inputs and outputs in your answer is appreciated. ## Test cases These are given in the format `input -> some possible output(s)`. ``` [1] -> [1,-1] or [1,1,1,-3] [2] -> [2,-1,-1] or [1,2,-2,-1] [-2] -> [1,1,-2] or [3,1,2,-2,-4] [2,-2] -> [2,-1,1,-2] or [2,-1,2,-2,-1] [2,2,2] -> [2,-1,2,-2,2,-2,-1] or [2,2,2,2,-3,-5] [2,-4,2] -> [2,2,-1,1,-4] or [2,5,1,1,1,-4,2,-7,-1] [3,-1,2,-2,-1,-5] -> [2,3,-1,2,-1,-5] or [3,3,-1,-1,2,2,-1,6,1,1,1,1,-12,-5] [-2,-2,10,-2,-2,-2] -> [10,-1,1,-2,-2,1,-2,-2,1,-2,-2] [-15,15,-15] -> [15,-1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,-15,-15] [1,2,3,4,5] -> [1,2,3,-1,4,-1,5,-1,-1,-9,-1,-1] ``` [Answer] # Jelly, 12 bytes ``` ż~Ṣ€FxA$;L$U ``` [Try it online!](http://jelly.tryitonline.net/#code=xbx-4bmi4oKsRnhBJDtMJFU&input=&args=WzMsIC0xLCAyLCAtMiwgLTEsIC01XQ) ### Background Consider the pair of integers **n, ~n**, where **n ≥ 0** and **~** denotes bitwise NOT, i.e., **~n = -(n + 1)**. By placing **n** copies of **n** to the left of **n + 1** copies of **~n**, if we start traversing the pointer array from the rightmost **~n**, we'll traverse all **2n + 1** elements and find ourselves at the left of the leftmost **n**. For example, if **n = 4**: ``` X 4 4 4 4 -5 -5 -5 -5 -5 ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ``` For the special case **n = 0**, the element **n** itself is repeated **0** times, leaving this: ``` X -1 ^ ^ ``` For each integer **k** in the input, we can form a pair **n, ~n** that contains **k** by setting **n = k** if **k > 0** and **n = ~k** if **k < 0**. This works because **~** is an involution, i.e., **~~k = k**. All that's left to do is chain the generated tuples and prepend their combined lengths, so the leftmost element takes us back to the rightmost one. ### Examples ``` [1] -> [3, 1, -2, -2] [2] -> [5, 2, 2, -3, -3, -3] [-2] -> [3, 1, -2, -2] [2, -2] -> [8, 1, -2, -2, 2, 2, -3, -3, -3] [2, 2, 2] -> [15, 2, 2, -3, -3, -3, 2, 2, -3, -3, -3, 2, 2, -3, -3, -3] [2, -4, 2] -> [17, 2, 2, -3, -3, -3, 3, 3, 3, -4, -4, -4, -4, 2, 2, -3, -3, -3] [3, -1, 2, -2, -1, -5] -> [26, 4, 4, 4, 4, -5, -5, -5, -5, -5, -1, 1, -2, -2, 2, 2, -3, -3, -3, -1, 3, 3, 3, -4, -4, -4, -4] [-2, -2, 10, -2, -2, -2] -> [36, 1, -2, -2, 1, -2, -2, 1, -2, -2, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, -11, -11, -11, -11, -11, -11, -11, -11, -11, -11, -11, 1, -2, -2, 1, -2, -2] [-15, 15, -15] -> [89, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15] [1, 2, 3, 4, 5] -> [35, 5, 5, 5, 5, 5, -6, -6, -6, -6, -6, -6, 4, 4, 4, 4, -5, -5, -5, -5, -5, 3, 3, 3, -4, -4, -4, -4, 2, 2, -3, -3, -3, 1, -2, -2] ``` ### How it works ``` ż~Ṣ€FxA$;L$U Main link. Argument: A (list of integers) ~ Yield the bitwise not of each k in A. ż Zipwith; pair each k in A with ~k. Ṣ€ Sort each pair, yielding [~n, n] with n ≥ 0. F Flatten the list of pairs. $ Combine the previous two links into a monadic chain: A Yield the absolute values of all integers in the list. |n| = n and |~n| = |-(n + 1)| = n + 1 x Repeat each integer m a total of |m| times. $ Combine the previous two links into a monadic chain: L Yield the length of the generated list. ; Append the length to the list. U Upend; reverse the generated list. ``` ]
[Question] [ I've been doing word searches recently, and I thought it would be *so* much easier if all of the words read left-to-right. But rewriting all the lines takes a lot of effort! So I'm enlisting code golfers to help. (Disclaimer: The above story may or may not be remotely accurate.) Your code will take a rectangular grid and output all of the lines through it in both directions. The output must contain all 8 rotations of the grid (cardinals and main diagonals), 'read off' top to bottom, left to right. (This means that every "row" will be duplicated - once forwards, and once backwards.) The line divisions can either be a space or a line break. If you choose spaces, the grid rotation divisions must be line breaks; otherwise, the grid rotation divisions must be two line breaks. **Example input** (taken as an array of characters, multiline string, or other reasonable format) ``` ABCDE FGHIJ KLMNO PQRST ``` **Example output** (using the first option for divisions) ``` ABCDE FGHIJ KLMNO PQRST E DJ CIO BHNT AGMS FLR KQ P EJOT DINS CHMR BGLQ AFKP T OS JNR EIMQ DHLP CGK BF A TSRQP ONMLK JIHGF EDBCA P QK RLF SMGA TNHB OIC JD E PKFA QLGB RMHC SNID TOJE A FB KGC PLHD QMIE RNJ SO T ``` The order of the rotations "read off" does not matter as long as all eight cardinals and primary intercardinals are done once. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. Standard loopholes apply. [Answer] ## Python 3, 181 bytes ``` def f(s): for k in [1,0]*4: b=list(zip(*[([' ']*(len(s)-1-n)*k+list(i)+[' ']*n*k)[::-1] for n,i in enumerate(s)])) print([' '.join(i).replace(' ','') for i in b]) if k==0:s=b ``` ## Explanation ``` def f(s): for k in [0]*4: # loop 4 times, we don't need the index so [0]*4 is shorter than range(4) l=len(s)-1 # number of line # rotation of 45° a=[(['.']*(l-n)+list(i)+['.']*n)[::-1] for n,i in enumerate(s)] # tranform matrice : # ABC ..ABC CBA.. # DEF --> .DEF. --> .FED. # GHI GHI.. ..IHG b=list(zip(*a)) # transpose # CBA.. C.. # .FED. --> BF. # ..IHG AEI # .DH # ..G print(' '.join(''.join(i).replace('.','') for i in b)) # rotation of 90° a=[(list(i))[::-1] for n,i in enumerate(s)] # tranform matrice : # ABC CBA # DEF --> FED # GHI IHG b=list(zip(*a)) # transpose # CBA CFI # FED --> BEH # IHG ADG print(' '.join(''.join(i) for i in b)) s=b ``` ## Results ``` >>> f(['ABCDE','FGHIJ','KLMNO','PQRST']) ['E', 'DJ', 'CIO', 'BHNT', 'AGMS', 'FLR', 'KQ', 'P'] ['EJOT', 'DINS', 'CHMR', 'BGLQ', 'AFKP'] ['T', 'OS', 'JNR', 'EIMQ', 'DHLP', 'CGK', 'BF', 'A'] ['TSRQP', 'ONMLK', 'JIHGF', 'EDCBA'] ['P', 'QK', 'RLF', 'SMGA', 'TNHB', 'OIC', 'JD', 'E'] ['PKFA', 'QLGB', 'RMHC', 'SNID', 'TOJE'] ['A', 'FB', 'KGC', 'PLHD', 'QMIE', 'RNJ', 'SO', 'T'] ['ABCDE', 'FGHIJ', 'KLMNO', 'PQRST'] >>> f(['ABCDEF','GHIJKL','MNOPQR','STUVWX']) ['F', 'EL', 'DKR', 'CJQX', 'BIPW', 'AHOV', 'GNU', 'MT', 'S'] ['FLRX', 'EKQW', 'DJPV', 'CIOU', 'BHNT', 'AGMS'] ['X', 'RW', 'LQV', 'FKPU', 'EJOT', 'DINS', 'CHM', 'BG', 'A'] ['XWVUTS', 'RQPONM', 'LKJIHG', 'FEDCBA'] ['S', 'TM', 'UNG', 'VOHA', 'WPIB', 'XQJC', 'RKD', 'LE', 'F'] ['SMGA', 'TNHB', 'UOIC', 'VPJD', 'WQKE', 'XRLF'] ['A', 'GB', 'MHC', 'SNID', 'TOJE', 'UPKF', 'VQL', 'WR', 'X'] ['ABCDEF', 'GHIJKL', 'MNOPQR', 'STUVWX'] ``` **with a cleaner output (189 bytes)** ``` j=' '.join def f(s): for k in [1,0]*4: b=list(zip(*[([' ']*(len(s)-1-n)*k+list(i)+[' ']*n*k)[::-1] for n,i in enumerate(s)])) print(j(j(i).replace(' ','') for i in b)) if k==0:s=b ``` . ``` >>> f(['ABCDE','FGHIJ','KLMNO','PQRST']) E DJ CIO BHNT AGMS FLR KQ P EJOT DINS CHMR BGLQ AFKP T OS JNR EIMQ DHLP CGK BF A TSRQP ONMLK JIHGF EDCBA P QK RLF SMGA TNHB OIC JD E PKFA QLGB RMHC SNID TOJE A FB KGC PLHD QMIE RNJ SO T ABCDE FGHIJ KLMNO PQRST ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 40 bytes ``` t!tP!tP!GXKZyqXI"IZ}w_w2$:"K@2$Xd!]K!XKx ``` Input is a 2D char array in Matlab notation: ``` ['ABCDE'; 'FGHIJ'; 'KLMNO'; 'PQRST'] ``` The output contains each "word" on a separate line. [**Try it online!**](http://matl.tryitonline.net/#code=dCF0UCF0UCFHWEtaeXFYSSJJWn13X3cyJDoiS0AyJFhkIV1LIVhLeA&input=WydBQkNERSc7ICdGR0hJSic7ICdLTE1OTyc7ICdQUVJTVCdd) ``` t % input 2D char array. Duplicate. The original copy will produce % the words left to right when displayed ! % transpose. This will produce the words up to down tP! % duplicate, flip upside down, transpose. This will produce the % words right to left tP! % Same. This will produce the words down to up GXK % push input again. Copy to clipboard K Zy % get size (length-2 vector; [4 5] in the example) q % decrement by 1 (gives [3 4] in the example) XI % copy to clipboard I " % loop: do this twice, consuming the decremented length-2 vector I % push decremented size vector again Z} % split into its two elements (pushes 3 and 4 in the example) w_w % swap, negave, swap (results in -3, 4 in the example) 2$: % binary range: indices of diagonals ([-3 -2 -1 0 1 2 3 4] % in the first iteration in the example, [-4 -3 -2 -1 0 1 2 3] % in the second) " % for each K % push input (first iteration) or its tranposed version (second) @ % push index of diagonal 2$Xd! % extract that diagonal as a row vector ] % end for each K!XKx % update clipboard K with transposed version for next iteration % end loop. Display ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 4F=íøDεÐS0:«NFÁ}}øí0мõK, ``` Input as a list of lines; outputs as list of strings as well, each on a separated newline to STDOUT. [Try it online.](https://tio.run/##MzBNTDJM/f/fxM328NrDO1zObT08IdjA6tBqP7fDjbW1h3ccXmtwYc/hrd46//9HKzk6Obu4Kukoubl7eHoBaW8fXz9/IB0QGBQcohQLAA) **Explanation:** Unfortunately 05AB1E doesn't have an (anti-)diagonals builtin, so 17 of the bytes are to accomplish that in a similar matter as [my 05AB1E answer for the *Diamondize a Matrix* challenge](https://codegolf.stackexchange.com/a/203697/52210). Uses the legacy version of 05AB1E, since it can zip/transpose on a list of strings, whereas the new 05AB1E version requires it to be a character-matrix. ``` 4F # Loop 4 times: = # Print the current list with trailing newline (without popping) # (which will use the implicit input-list in the first iteration) íø # Rotate once 90 degrees clockwise: í # Reverse each line ø # Zip/transpose; swapping rows/columns D # Duplicate this rotated grid ε # Map over each line: ÐS0:« # Append the length amount of "0"s: Ð # Triplicate the string S # Convert the top copy to a list of characters 0: # Replace all these characters in another copy to "0" NF # Loop the (0-based) map-index amount of times: Á # Rotate once towards the right } # Close the loop } # Close the map øí # Rotate once 90 degrees counterclockwise 0м # Remove all "0"s from each inner string õK # Remove potential empty strings , # Pop and output this list of diagonals with trailing newline ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` KṄḲ ZUÇƊƬŒDÇ€ ``` [Try it online!](https://tio.run/##AUsAtP9qZWxsef//S@G5hOG4sgpaVcOHxorGrMWSRMOH4oKs/@G7tMOHxZLhuZjIp@KAnOKAnf//QUJDREUKRkdISUoKS0xNTk8KUFFSU1Q "Jelly – Try It Online") Ok, so this is fairly liberal with I/O, but I don't think any of the assumptions are a major issue: * The output for each row is in a different order than specified in the question. Because of > > The order of the rotations "read off" does not matter as long as all eight cardinals and primary intercardinals are done once. > > > I assumed this was OK * The output for half of the diagonals is in "reverse" order (i.e. the output includes `PLHD` instead of `DHLP`) If this isn't ok, then [+3 bytes](https://tio.run/##AU8AsP9qZWxsef//S@G5hOG4sgpaVcOHxorGrMWSRFXDkGXDh@KCrP/hu7TDh8WS4bmYyKfigJzigJ3//0FCQ0RFCkZHSElKCktMTU5PClBRUlNU) * This is a "link" in Jelly, which is Jelly's version of a function. This takes takes input via ARGV and outputs to STDIN rather than "returning" a value. The `ȧ“”` in the Footer suppresses Jelly implicitly outputting the return value for the link * This takes input as a matrix of characters. This seems to be allowed by > > Example input (taken as an array of characters, multiline string, or other reasonable format) > > > --- ## How it works ``` KṄḲ - Helper link. Takes a string S on the left K - Join S by spaces Ṅ - Print S Ḳ - Split S on spaces ZUÇƊƬŒDÇ€ - Main link. Takes a matrix M of characters Ɗ - Group the previous 3 links into a monad f(M): Z - Transpose U - Reverse Ç - Call the helper link Ƭ - Yield [f(M), f(f(M)), f(f(f(M))), f(f(f(f(M))) = M] This outputs and returns all rotations of M ŒD - Get the diagonals of each Ç€ - Call the helper link on each diagonal ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 135 bytes ``` f=(s,n=8)=>n?[s.flatMap(t=>t.join``||[]),...f([...Array(L=(s+0).length)].map((_,y,p)=>p.map((_,x)=>(s[y+x-L>>1]||0)[(x-y)/2])),n-1)]:[] ``` [Try it online!](https://tio.run/##NY5NDoIwFISPQ18oFVwZEzDu8QRNI5V/LG2ljYGEu9dnjJuZzOKbmUm@pauX0fpEm6YNocuJozo/QV7oC3esU9LfpCU@LzybzKirat@5AMoY6whHvS6L3EiJXJwCU63u/QCCzQiRO92oxSr7jysG4vgWr0lZFJnY9xQ4WZMNDkcBQHWSgThzEWqjnVEtU6YnuBPJR920EY26fhgn9KeatUG3r8X56DeHH7@HPBZB@AA "JavaScript (Node.js) – Try It Online") Slow. Complexity O(n^256) [Proof that the rotation work](https://tio.run/##NY5LDoMgGISPA0Sg2pVpok339gSEVOrbIlAhjSbe3f6m6WYms5hvZlQf5at5cIEZWzf73mbYU5OlJMvNVVTWeKsbrm2HPW@1CnflcMjywEc7mLLcNiEJoZzzFgvQ2zyrFRcAiWLCdWO60EcpkXyCHn7QlTogu39cIGAv1mhhRZ4ncttiIvDCVnI6H1zDEiIvQu5AR@pZ1Q2iqO36YQR/6clYcPeefUC/Cbh23AhQ3r8) [Fast run](https://tio.run/##PY9BbsMgEEX3OYV3BsWmTldVI6iqbNMTINQQBxxcDC6QyKju2V3s1t3MaJj//zxafue@dqoPpbEXMR2wvJk6KGuALwz82mSZz3DmkVQ6CAcGTAbUWmVOJ7hPyzt32XkW0IqhjvcAvBcKYuKRt50AEZNIFYOL1olwcyaTwC/KgElYY/9c50Wb7u4335PEMwJ@Su/mhSYCzcPb6vtFGEfKYIEQOgCa6qtzPIJj8m0riLQwTbjCf6xY9CmqX8chDcDTuB3KIyE7No4VpGAoI3x4XCDKHWTPlE21Nd5qgbRtgAQ05@f6IvIil81Vtal/6M7Y1PtP50PO1r/NQCEFwekH) ]
[Question] [ # The Challenge Given a `n x n` matrix of integers with `n >= 2` ``` 1 2 3 4 ``` and a list of integers with exactly `2n`elements ``` [1,2,-3,-1] ``` output the rotated matrix. This matrix is contructed in the following way: * Take the first integer in the list and rotate the first row to the right by this value. * Take the next integer and rotate the first column down by this value. * Take the next integer and rotate the second row to the right by this value, etc. until you rotated every row and column of the matrix once. The list can contain negative integers which means that you shift the row/column left/up instead of right/down. If the integer is zero, don't rotate the row/column. **Example using the input above** ``` List element Matrix Explanation ------------------------------------------------------------ 1 2 1 Rotate 1st row right by 1 3 4 2 2 1 Rotate 1st column down by 2 3 4 -3 2 1 Rotate 2nd row left by 3 4 3 -1 2 3 Rotate 2nd column up by 1 4 1 ``` # Rules * You may choose the most conventient input format. Just make it clear which one you use. * Function or full program allowed. * [Default rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission. # Test cases Input format here is a list of lists for the matrix and a normal list for the integers. ``` [[1,2],[3,4]],[1,2,-3,-1] -> [[2,3],[4,1]] [[1,2],[3,4]],[1,1,1,1] -> [[3,2],[4,1]] [[1,2],[3,4]],[0,0,0,0] -> [[1,2],[3,4]] [[1,2,-3],[-4,5,6],[7,-8,0]],[1,-2,0,-1,3,4] -> [[7,5,0],[-3,-8,2],[-4,1,6]] [[1,2,-3],[-4,5,6],[7,-8,0]],[3,12,-3,0,-6,-3] -> [[1,2,-3],[-4,5,6],[7,-8,0]] ``` **Happy Coding!** [Answer] ## CJam, 13 bytes ``` {{a.m>1m<z}/} ``` An unnamed block (function) that takes the matrix and the list on top of the stack (in that order) and leaves the new matrix in their place. [Run all test cases.](http://cjam.aditsu.net/#code=%5B%5B1%202%5D%20%5B3%204%5D%5D%20%5B1%202%20-3%201%5D%0A%5B%5B1%202%5D%20%5B3%204%5D%5D%20%5B1%201%201%201%5D%0A%5B%5B1%202%5D%20%5B3%204%5D%5D%20%5B0%200%200%200%5D%0A%5B%5B1%202%20-3%5D%20%5B-4%205%206%5D%20%5B7%20-8%200%5D%5D%20%5B1%20-2%200%20-1%203%204%5D%0A%5B%5B1%202%20-3%5D%20%5B-4%205%206%5D%20%5B7%20-8%200%5D%5D%20%5B3%2012%20-3%200%20-6%20-3%5D%0A%5D2%2F%7B~%0A%0A%7B%7Ba.m%3E1m%3Cz%7D%2F%7D%0A%0A~%7D%25%3Ap) Same idea, same byte count, different implementations: ``` {{\(@m>a+z}/} {{(Im>a+z}fI} {{:\Im>]z}fI} ``` ### Explanation Ideally we want to treat each instruction in the list the same, and just use it to rotate the first row of the matrix. This can be done quite easily by transforming the matrix after each instruction a bit and making sure that all those extra transformations cancel out in the end. So after processing each instruction, we rotate *all* rows one up (such that the next instruction along the same dimension processes the next row) and then transpose the matrix, such that we're actually processing columns next. These additional transformations are orthogonal to the instructions in the list and have a period of exactly `2n`, just what we need. As for the code: ``` { e# For each instruction... a e# Wrap it in a singleton array. .m> e# Combine it element-wise with the matrix to rotate right. This is e# a fairly common idiom to apply a binary operation only to the first e# element of an array, since element-wise operations just retain all the e# unpaired elements of the longer array. 1m< e# Rotate the rows one up. z e# Transpose. }/ ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~17~~ ~~15~~ ~~14~~ 13 bytes *-3 bytes by Adám* ``` (⍉1⊖⌽`@1⍢⌽)/⌽ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NRb6fho65pj3r2JjgYPupdBGRo6gOJ/2mP2iY86u171DfV0/9RV/Oh9caP2iYCecFBzkAyxMMz@L9CmoLGo64mYwXjR71bDBWMFICKgNhEwVTBTMEcyLJQMNDUUTAEsowUDICkoYKxgonCfwA "APL (Dyalog Extended) – Try It Online") Takes input as a list where the first element is the matrix, and the remaining elements are the rotation amounts. If ⌽ rotated to the right instead of left, this would beat CJam. ``` (⍉1⊖⌽@1 1⍢⌽)/⌽ Monadic train: (⍉1⊖⌽@1 1⍢⌽) Helper function to rotate and transpose once. Takes args ⍺ (amount to rotate) and ⍵ (current array) ⌽ Function to rotate left 1 1 2-element vector containing 1. The second 1 is redundant, but saves 1 byte over (,1). ⌽@1 1 Function to rotate the 1st row left by ⍺. ⌽@1 1⍢⌽ Reverse ⍵, rotate 1st row left by ⍺, then reverse again. This rotates the first row of ⍵ to the *right*. 1⊖ Rotate all the rows upward, ⍉ then transpose. (⍉1⊖⌽@1 1⍢⌽)/⌽ Fold (/) this function over the reversed input. If our input is ⍵, ⍺_1, ⍺_2, ..., ⍺_2n, the reversed input will be ⍺_2n, ..., ⍺_1, ⍵. The / operator applies the function right to left, so the ⌽ is necessary. ``` [Answer] ## Python 2, 96 bytes ``` def f(m,v): for i,x in enumerate(v):x%=len(m);r=m[i/2];m[i/2]=r[-x:]+r[:-x];m=zip(*m) return m ``` [*Tests*](http://ideone.com/EOB24M) `f` returns a list of tuples. Each line in the function body is indented with 1 tab character. [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÄBí•`»O╒┬g½ë ``` [Run and debug it](https://staxlang.xyz/#p=8e42a10760af4fd5c267ab89&i=[[1,2],[3,4]]+++++++++++++++%09[1,2,-3,-1]%0A[[1,2],[3,4]]+++++++++++++++%09[1,1,1,1]%0A[[1,2],[3,4]]+++++++++++++++%09[0,0,0,0]%0A[[1,2,-3],[-4,5,6],[7,-8,0]]%09[1,-2,0,-1,3,4]%0A[[1,2,-3],[-4,5,6],[7,-8,0]]%09[3,12,-3,0,-6,-3]&a=1&m=2) ]
[Question] [ This challenge is inspired by this Oliver Sacks quote: > > “At 11, I could say ‘I am sodium’ (Element 11), and now at 79, I am > gold.” ― Oliver Sacks > > > I want you you find numbers in a string and replace them with their corresponding elements' symbols. (1 is H, 2 is He, 3 is Li, etc.) There are a few rules to follow: * Single and double digits get replaced with their corresponding elements as normal. Ignore 0s at the start of numbers. If there are just 0s in a number, ignore it. E.g. `1 01 10 0 00` becomes `H H Ne 0 00` * More than 2 digits together get divided into groups of 2. An odd number of digits should have the extra single digit at the end. E.g. `0153 5301 153` would become `HI IH PLi` Because of this rule, you will only need to know the elements from 1 to 99 * Numbers shall be treated the same no matter what characters surround them and commas and decimal points are not parts of numbers. `P90X 42,800 3.14159` would become `PThX Mo,Hg0 Li.SiPF` Example Inputs/Outputs (I/O): ``` I: 32289216 O: GeNiUS I: J08017 5811 O: JOHN CeNa I: M18227 0592tt10r O: MArTiN BUttNer I: De072816 O: DeNNiS I: D088r1907085 O: DOOrKNOB I: 13ex A. O: Alex A. ``` Input will be in the closest format to a string that your language has. A periodic table for reference: ![](https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Periodic_table_%28polyatomic%29.svg/2000px-Periodic_table_%28polyatomic%29.svg.png) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so your program will be scored in bytes. [Answer] # Mathematica, ~~96~~ ~~94~~ 89 bytes ``` StringReplace[#,n:DigitCharacter~Repeated~2/;(d=FromDigits@n)>0:>d~ElementData~"Symbol"]& ``` Mma has several datasets... [Answer] # JavaScript (ES6), 202 bytes ``` x=>x.replace(/\d\d?/g,y=>+y?btoa`(139 bytes; see hexdump below)`.match(/[A-Z][a-z]?/g)[+y]:y) ``` The omitted string contains unprintable characters, so here is a (hopefully reversible) hexdump: ``` 00000000: 0071 de2e 205e 0423 4e14 d78d 68c8 0095 288f .qÞ. ^.#N.×.hÈ..(. 00000012: 4829 40ac a09a 49c4 e254 2acc 9c57 82a0 d882 H)@¬ .IÄâT*Ì.W. Ø. 00000024: b999 c668 6780 b127 81ac aad1 6d2a d866 b35b ¹.Æhg.±'.¬ªÑm*Øf³[ 00000036: 3284 dc46 e461 3dd0 2009 d227 4a74 9b4d e217 2.ÜFäa=Ð .Ò'Jt.Mâ. 00000048: 782b 0168 b682 78fa cd74 f992 984b 8675 36c3 x+.h¶.xúÍtù..K.u6à 0000005a: c87a 04ad 3998 6cbb 877d 3696 45e3 ac22 b3ed Èz..­9.l».}6.Eã¬"³í 0000006c: 02e1 e04e 53db 0623 e802 d467 16b4 5a01 c4e1 .áàNSÛ.#è.Ôg.´Z.Äá 0000007e: 3da5 0da4 fb80 9829 8190 27c4 b0 =¥.¤û..)..'İ ``` The technique here was to put all the element abbreviations in one string, separated by nothing—that's what the second regex `/[A-Z][a-z]?/g` is for; it matches each capital letter, optionally followed by a lowercase letter. The first regex, `/\d\d?/g`, matches each set of 2 (or 1) digits in the input, so this replaces each set of digits *N* with the element at index *N* in the decompressed, matched string. Here's the original string, if anyone else would like to use it: (the `A`'s at the ends are fillers) ``` AHHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsA ``` Questions and suggestions welcome! [Answer] # Python 3, ~~278~~ 285 bytes ``` import re;f=lambda a:re.sub('(?!00)\d\d?',lambda m:'0HHLBBCNOFNNMASPSCAKCSTVCMFCNCZGGASBKRSYZNMTRRPACISSTIXCBLCPNPSEGTDHETYLHTWROIPAHTPBPARFRATPUNPACBCE eie eagli lr aci rneoiunaeserrbr rbocuhdgdnnbe esaaerdmmudbyormbufa esrtuglbiotnracha pummkfs'[int(m.group())::100].strip(),a) ``` Test cases: ``` >>> f('32289216') 'GeNiUS' >>> f('J08017 5811') 'JOHN CeNa' >>> f('M18227 0592tt10r') 'MArTiN BUttNer' >>> f('De072816') 'DeNNiS' >>> f('D088r1907085') 'DOOrKNOB' >>> f('13ex A.') 'Alex A.' >>> f('P90X 42,800 3.14159') 'PThX Mo,Hg0 Li.SiPF' >>> f('1 01 10 0 00') 'H H Ne 0 00' ``` [Answer] # Python 2, ~~312~~ 304 bytes ``` import re f=lambda a:''.join([j or'0HHLBBCNOFNNMASPSCAKCSTVCMFCNCZGGASBKRSYZNMTRRPACISSTIXCBLCPNPSEGTDHETYLHTWROIPAHTPBPARFRATPUNPACBCE0 eie eagli lr aci rneoiunaeserrbr rbocuhdgdnnbe esaaerdmmudbyormbufa esrtuglbiotnracha pummkfs'[int(i)::100].strip() for i,j in re.findall('(\d\d|[1-9])|(.)',a)]) ``` This one creates a function **f** which takes a string of numbers as argument and returns the corresponding string with element symbols replaced. The function iterates over strings of one to two digits (**'1'**, **'01'**, **'10'**, **'00'** but not **'0'**) or one character (**'a'**, **'0'** but not **'1'**). In the case of digits, the string is converted to an integer and looked up in a concatenated string of element symbols where each symbol is padded to two characters. In the case of characters, the string is simply used without lookup. The tests for each example in the question all pass: ``` assert f('P90X 42,800 3.14159') == 'PThX Mo,Hg0 Li.SiPF' assert f('1 01 10 0 00') == 'H H Ne 0 00' assert f('0153 5301 153') == 'HI IH PLi' assert f('32289216') == 'GeNiUS' assert f('J08017 5811') == 'JOHN CeNa' assert f('M18227 0592tt10r') == 'MArTiN BUttNer' assert f('De072816') == 'DeNNiS' assert f('D088r1907085') == 'DOOrKNOB' assert f('13ex A.') == 'Alex A.' ``` ]
[Question] [ Recently at Puzzling.SE, there was a problem that I wrote about determining which two bottles out of a larger number are poisoned when the poison only activates if both components are drunk. It ended up being quite the ordeal, with most people managing to get it down to 18 or 19 prisoners using completely different algorithms. The original problem statement is as follows: > > You are the ruler of a medieval kingdom who loves throwing parties. The courtier who tried to poison one of your wine bottles last time was furious to learn that you managed to identify which bottle he had poisoned out of 1,000 with just ten prisoners. > > > This time he's a bit craftier. He's developed a **composite poison** `P`: a binary liquid that's only deadly when two individually harmless components mix; this is similar to how epoxy works. He's sent you another crate of 1,000 wine bottles. One bottle has component `C_a` and another one has component `C_b`. (`P = C_a + C_b`) > > > Anyone who drinks both components will die on the stroke of midnight on the night they drank the final component, regardless of when in the day they imbibed the liquid. Each poison component stays in the body until the second component activates, so if you drink one component one day and another component the next, you will die on midnight at the end of the second day. > > > You have two days before your next party. What is the minimum number of prisoners you need to use for testing in order to identify which two bottles are tainted, and what algorithm do you need to follow with that number of prisoners? > > > > > --- > > > **Bonus** > > Additionally, suppose that you had a fixed limit of 20 prisoners at your disposal, what's the maximum number of bottles you could theoretically test and come to an accurate conclusion about which bottles were affected? > > > Your task is to build a program to solve the bonus problem. Given `n` prisoners, your program will devise a testing schedule that will be able to detect the two poisoned bottles among `m` bottles, where `m` is as large as possible. Your program will initially take as input the number `N`, the number of prisoners. It will then output: * `M`, the number of bottles you will attempt to test. These bottles will be labelled from `1` to `M`. * `N` lines, containing the labels of the bottles each prisoner will drink. Your program will then take as input which prisoners died on the first day, with the prisoner on the first line being `1`, the next line being `2`, etc. Then, it will output: * `N` more lines, containing the labels of the bottles each prisoner will drink. Dead prisoners will have blank lines. Your program will then take as input which prisoners died on the second day, and output two numbers, `A` and `B`, representing which two bottles your program thinks contains the poison. An example input for two prisoners and four bottles might go as such, if bottles `1` and `3` are poisoned: ``` > 2 // INPUT: 2 prisoners 4 // OUTPUT: 4 bottles 1 2 3 // OUTPUT: prisoner 1 will drink 1, 2, 3 1 4 // OUTPUT: prisoner 2 will drink 1, 4 > 1 // INPUT: only the first prisoner died // OUTPUT: prisoner 1 is dead, he can't drink any more bottles 3 // OUTPUT: prisoner 2 drinks bottle 3 > 2 // INPUT: prisoner 2 died 1 3 // OUTPUT: therefore, the poisoned bottles are 1 and 3. The above algorithm may not actually work in all cases; it's just an example of input and output. ``` Your program's testing schedule must successfully determine each possible pair of poisoned bottles in order for it to be a valid submission. Your program will be scored on the following criteria, in order: * The maximum number of bottles it can discern for the case `N = 20`. * The number of bottles for the case `N = 21`, and successively higher cases after that. * The length of code. (Shorter code wins.) [Answer] # **Python 2.7.9 — 21 bottles** Assuming that ESultanik's speculation is right on what the input is when multiple prisoners die ``` r=raw_input;s=str;j=s.join;p=int(r());z=range;q=z(p);x=z(p+1) print s(p+1)+"\n"+j("\n",(j(" ",(s(a) for a in x if a!=b)) for b in q)) v=r().split();d=[s(a) for a in q if s(a) not in v];d+=[p]if len(d)==1 else []; print "\n"*p,;r();print j(" ",[s(a) for a in d]) ``` Algorithm: every prisoner drinks from every bottle except their number (1st prisoner doesn't drink first bottle). If they don't die, their number bottle is poisoned. If only one prisoner survives, the extra bottle is poisoned. [Answer] # [Perl 5](http://www.perl.com/), 66 bottles ## (72 bottles for 21 prisoners) The prisoners are divided optimally into 2 groups. The bottles are grouped in sets. Each prisoner of group 1 will drink from all sets except for one. There will be 1 or 2 survivors. The 1 or 2 sets that weren't drank by them will continue to day 2. On day 2 the remaining prisoners (including the survivors) drink from all remaining bottles except for one. When 2 prisoners survive then the bottles they didn't drink are poisoned. If only 1 prisoner remains then the bottle they all drank is also suspicious. The code includes extra functionality to facilitate testing. When the poisened bottles are added as additional parameters, then it won't ask for input about who died. ``` ($p,$f,$l)=@ARGV; $p=9if!$p; $m=$p-(2*int($p/4))+1; $n=$p-$m+2; $b=$m*(($n+1)/2); @M=(1..$m); print"Prisoners: $p\nBottles: $b\n"; # building the sets of items for$x(@M){ $j=$k+1;$k+=($n+1)/2; $s=join",",($j..$k); $A[$x]=$s } # assigning the sets to the actors for$x(@M){ @T=(); for$j(@M){if($x!=$j){push@T,split/,/,$A[$j]}} print"Prisoner $x drinks @T\n"; $B[$x]=join",",@T } if(!$f||!$l){ # manual input print"Who dies: "; $_=<STDIN>;chomp; @D=split/ /; %h=map{($_,1)}@D; @S=grep{!$h{$_}}(@M) } else{ # calculate who dies based on the parameters for$x(@M){ $d=0; map{if($_==$f||$_==$l){$d++}}split/,/,$B[$x]; if($d>1){push@D,$x}else{push@S,$x} } } for(@D){print"Prisoner $_ dies\n"} # calculate the remaining items for(@S){push@R,split/,/,$A[$_]}@R=sort{$a<=>$b}grep{!$g{$_}++}@R; # different set of actors if there were 1 or 2 sets remaining if(@S>1){@S=($S[0],$m+1..$p,$S[1],0)}else{@S=($m+1..$p)}; $i=0;@B=@D=(); # assign an item to each actor for$x(@S){ @T=(); for($j=0;$j<@R;$j++){ if($i!=$j){push@T,$R[$j]} }$i++; print"Prisoner $x drinks @T\n"if$x>0; $B[$x]=join",",@T } if(!$f||!$l){ # manual input print"Who dies: "; $_=<STDIN>;chomp; @D=sort split/ /; if(@D<@S-1){push@D,0} # because the set that noone drinks isn't manually put in %h=map{($_,1)}@D; @L=grep{!$h{$_}}(@S); } else{ # calculate who dies based on the parameters @D=(); for$x(@S){ $d=0; map{if($_==$f||$_==$l){$d++}}split/,/,$B[$x]; if($d>1){push@D,$x}else{push@L,$x} } } for(@D){print"Prisoner $_ dies\n"if$_>0} # calculate the remaining items for(@L){push@F,split/,/,$B[$_]} map{$c{$_}++}@F; for(keys%c){push(@Z,$_)if$c{$_}==1} @R=sort{$a<=>$b}@Z; print"Suspected bottles: @R" ``` ## Test ``` $ perl poisened_bottles.pl 20 Prisoners: 20 Bottles: 66 Prisoner 1 drinks 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Prisoner 2 drinks 1 2 3 4 5 6 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Prisoner 3 drinks 1 2 3 4 5 6 7 8 9 10 11 12 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Prisoner 4 drinks 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Prisoner 5 drinks 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Prisoner 6 drinks 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Prisoner 7 drinks 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Prisoner 8 drinks 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Prisoner 9 drinks 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 55 56 57 58 59 60 61 62 63 64 65 66 Prisoner 10 drinks 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 61 62 63 64 65 66 Prisoner 11 drinks 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 Who dies: 2 3 4 5 6 7 8 9 10 Prisoner 2 dies Prisoner 3 dies Prisoner 4 dies Prisoner 5 dies Prisoner 6 dies Prisoner 7 dies Prisoner 8 dies Prisoner 9 dies Prisoner 10 dies Prisoner 1 drinks 2 3 4 5 6 61 62 63 64 65 66 Prisoner 12 drinks 1 3 4 5 6 61 62 63 64 65 66 Prisoner 13 drinks 1 2 4 5 6 61 62 63 64 65 66 Prisoner 14 drinks 1 2 3 5 6 61 62 63 64 65 66 Prisoner 15 drinks 1 2 3 4 6 61 62 63 64 65 66 Prisoner 16 drinks 1 2 3 4 5 61 62 63 64 65 66 Prisoner 17 drinks 1 2 3 4 5 6 62 63 64 65 66 Prisoner 18 drinks 1 2 3 4 5 6 61 63 64 65 66 Prisoner 19 drinks 1 2 3 4 5 6 61 62 64 65 66 Prisoner 20 drinks 1 2 3 4 5 6 61 62 63 65 66 Prisoner 11 drinks 1 2 3 4 5 6 61 62 63 64 66 Who dies: 1 12 14 15 16 17 18 20 11 Prisoner 1 dies Prisoner 11 dies Prisoner 12 dies Prisoner 14 dies Prisoner 15 dies Prisoner 16 dies Prisoner 17 dies Prisoner 18 dies Prisoner 20 dies Suspected bottles: 3 63 ``` ## Test without manual input ``` $ perl poisened_bottles.pl 7 2 5 Prisoners: 7 Bottles: 12 Prisoner 1 drinks 3 4 5 6 7 8 9 10 11 12 Prisoner 2 drinks 1 2 5 6 7 8 9 10 11 12 Prisoner 3 drinks 1 2 3 4 7 8 9 10 11 12 Prisoner 4 drinks 1 2 3 4 5 6 9 10 11 12 Prisoner 5 drinks 1 2 3 4 5 6 7 8 11 12 Prisoner 6 drinks 1 2 3 4 5 6 7 8 9 10 Prisoner 2 dies Prisoner 4 dies Prisoner 5 dies Prisoner 6 dies Prisoner 1 drinks 2 5 6 Prisoner 7 drinks 1 5 6 Prisoner 3 drinks 1 2 6 Prisoner 1 dies Suspected bottles: 2 5 ``` [Answer] As is tradition, I will post a last-place reference answer. # Python — 7 bottles ``` prisoners = int(raw_input()) bottles = 0 while (bottles * (bottles + 1) / 2 - 1) <= prisoners: bottles += 1 print bottles pairs = [] for i in range(bottles): for j in range(i + 1, bottles): pairs += [str(i + 1) + " " + str(j + 1)] for i in range(prisoners): if i < len(pairs): print pairs[i] else: print dead_prisoner = raw_input() for i in range(prisoners): print raw_input() # discard the second day entirely if dead_prisoner == "": print pairs[-1] else: print pairs[int(dead_prisoner) - 1] ``` Make each prisoner drink one possible pair of bottles except for the pair of the last two. If any prisoner dies, the pair that that prisoner drank were the poisoned ones. Otherwise, it was the last two bottles that were poisoned. For allotments of at least `n(n-1)/2 - 1` prisoners, you can do up to `n` bottles. For `n = 7`, this lower limit is `20`. We only actually need *one* day for this solution to work. A two-day solution with a similar scope might get up to 20 bottles for `N = 20`, but it's too much work for a trivial answer. ]
[Question] [ The [Kolmogorov complexity](http://en.wikipedia.org/wiki/Kolmogorov_complexity) of a string *S* is the length of the shortest program *P*, written in some programming language *L*, whose output is exactly *S*. (Yes, the real definition is more formal but this will suffice for the challenge.) Your task in this challenge is to write the shortest possible "Kolmogorov complexity solver", that is, a program written in *L* itself that takes in a string *S* and returns the shortest *P* written in *L* that outputs *S*. The naive approach to this is to iterate over all length 1 programs, then all length 2 programs, then all length 3 programs, and so on, running each of them and measuring the output until a program that outputs *S* is found. The issue with this approach is that some of these programs may never stop running, which means that the solver itself may never stop. And due to [the halting problem](http://en.wikipedia.org/wiki/Halting_problem) there is no surefire way to avoid the programs that don't stop. A simple, though imperfect solution is to put a time limit on the execution time of each of the potential *P*'s. Programs that don't happen to halt in time may be passed over, but the solver will definitely stop (assuming that a program in *L* can indeed output *S* within the time limit). # Challenge Write your solver as a program or function that takes in three things: * The string *S*. * A positive integer *T* that is the time limit in seconds or some smaller time span (e.g. milliseconds). * A string *A* of the alphabet of characters to use for potential *P*'s. And outputs the shortest *P* that only contains characters in *A*, runs in less than *T* time units, and outputs *S*. This is the general pseudocode: ``` Function KolmogorovComplexitySolver(S, T, A): Assign N to 0 Loop until function returns: In any order, iterate over all strings of length N that only contain characters from *A*. Call the current string P: Execute P, saving the output to O, stopping the execution if it takes longer than time T If (P did not throw any errors) and (P did not timeout) and (O and S are identical): Return P Add 1 to N ``` # Details * You may assume that there will always be a *P* made from the characters in *A* that runs in time *T* that outputs *S*. * You may assume that the execution of the potential *P*'s will not have side effects that prevent the solver from running or working correctly (like messing with the solver's allocated memory). * You may *not* assume that the potential *P*'s are error free. Be sure to include `try`/`catch` blocks or whatever applicable around the execution call. * If there are multiple shortest *P*'s, then any will suffice. "Shortness" is measured in characters not bytes. * The output of potential *P*'s is what's printed to stdout (or your language's usual output area). The empty string is a potential *P*. * Ideally your solver will allow *A* to contain any characters. *A* must at least to be able to contain [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters plus tabs and newlines. * Input may come from file/stdin/command line/function args. Output goes to stdout or similar, or can be returned as a string if you wrote a function. # Scoring The submission with the [fewest bytes](https://mothereff.in/byte-counter) wins. Tiebreaker goes to earliest posted submission. [Answer] # Python 3, ~~240~~ 236 bytes ``` import subprocess as s,itertools as i def f(S,T,A,N=0): while 1: for P in i.product(A,repeat=N): try: P="".join(P);open("a","w").write(P) if s.check_output(["py","-3","a"],timeout=T).decode()==S:return P except:1 N+=1 ``` **Don't run this.** On my computer, at least, I found the program really hard to stop once it started running due to the pop-up windows created per process. `timeout`s were only added to `subprocess.check_output` in Python 3, which is why we're using this rather than Python 2. Here's an alternative version with a `time.sleep` that also prints all valid programs found along the way, as well as their corresponding output: ``` import subprocess as s,itertools as i import time def f(S,T,A,N=0): while 1: for P in i.product(A,repeat=N): time.sleep(0.2) try: P="".join(P);open("a","w").write(P);C=s.check_output(["py","-3","a"],timeout=T).decode() print(P,repr(C)) if C==S:return P except:1 N+=1 ``` The program uses the filename `a` for each program `P` to be tested, so if you run this make sure you don't already have a file of that name. Replace `["py","-3","a"]` with the appropriate command for your setup (e.g. `["python","a"]` or `["python3","a"]`). Feel free to change the `sleep` duration at your own risk :). Call like `f("1\r\n",1,"1()print")`, where `T` is timeout in seconds. First few lines of output from the tester with the above call: ``` '' 1 '' 11 '' () '' 111 '' (1) '' int '' 1111 '' ``` (If you want to help the program along a bit you can change `P="".join(P)` to `P="print"+"".join(P)`) Since the above programs all have no output, here's the result for `f("1\r\n",1,["print","(",")","1"])` (tokens aren't part of the challenge, but I wanted to show what happens): ``` '' print '' 1 '' () '' 11 '' print() '\r\n' (print) '' (1) '' 111 '' print(print) '<built-in function print>\r\n' print(1) '1\r\n' ``` The return value is the string `'print(1)'`. Finally, just for fun, here's what happens if the alphabet is `string.printable`, i.e. ``` 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c ``` [Pastebin link of all valid 0-2 char Python 3 programs](http://pastebin.com/jXNYm36c) ]
[Question] [ Some positive integers can be shown to have a property called *Chain divisibility.* For a number to be chain-divisible by *n*, it must fulfil three requirements: 1. > > Each digit divides the number formed by the *n*  digits that follow it. > > > For example, the number 7143 is chain-divisible by 2 because 7 divides 14 and 1 divides 43. It is *not* chain-divisible by 3 because 7 does not divide 143. 2. > > Each subsequence taken into account for divisibility must not have leading zeros. > > > For instance, the number 14208 is not chain-divisible by 2 because 08 has a leading zero. It is, however, chain-divisible by 3, because 208 does not have a leading zero. 3. > > All digits in the number must be unique. > > > For instance, the number 14280 is chain-divisible by 2, 3 and 4. If my explanation of chain divisibility is unclear please ask questions in the comments. **Input** The input to the program consists of a single integer `n`, followed by a space, then a number that has had certain digits replaced by underscores. For example, the following is a possible input: ``` 3 6__2__4508 ``` *n* will be greater than 1. The number will never be entirely underscores. You are not guaranteed that the first digit is not an underscore. The first digit will never be 0. *n* will never be greater or equal to the number of digits in the number. **Output** Output the number, with the digits replaced by integers such that the resulting number is chain-divisible by *n*. If more than one way of completing the chain-divisible number exists, any may be used as output. If there is no numbers that can complete it, output `no answer`. For instance, the output of the example input could be: ``` 6132794508 ``` This is code golf, so the shortest code wins. [Answer] # Bash+coreutils, 197 bytes ``` for i in $(eval printf '%s\\n' ${2//_/{0..9\}}|grep -vP '(\d).*\1');{ for((f=d=0;d<${#i}-$1;d++));{ ((${i:d+1:1}==0||10#${i:d+1:$1}%${i:d:1}))&&f= } [ $f ]&&echo $i&&((c++)) } ((c))||echo no answer ``` ### Output: ``` $ ./chain.sh 3 714_ 7140 $ ./chain.sh 2 7141 no answer $ ./chain.sh 2 14208 no answer $ ./chain.sh 3 14208 14208 $ ./chain.sh 2 1_208 no answer $ ./chain.sh 3 1_208 14208 $ ./chain.sh 2 6__2__4508 no answer $ ./chain.sh 3 6__2__4508 6132794508 $ ``` ### Explanation * The parameter expansion `${2//_/{0..9\}}` replaces all underscores with `{0..9}`. * The resulting string is `eval`ed to expand all these brace expressions. * The `grep` weeds out all possibilities where there are any repeated digits. * Then each remaining number is checked, digit-by-digit for conditions 1 and 2. [Answer] # Python - ~~239~~ 267 ``` from itertools import* T=raw_input() n=int(T[0]) N=len(T)-2 J=''.join for i in permutations('0123456789',N): if all([S in[I,'_']for S,I in zip(T[2:],i)])*all([i[j]>'0'<i[j+1]and int(J(i[j+1:j+n+1]))%int(i[j])<1for j in range(N-n)]):print J(i);exit() print'no answer' ``` Slow, but short. Simply compare every possible N-digit permutation with the given pattern and check all requirements. I've tested it only with 7 or 8 digits. Should work for 9 or 10 as well, but will take quite a while. **Edit:** I added the missing default output "no answer". [Answer] ## ~~Mathematica~~ Ruby, ~~349~~ ~~224~~ 229 bytes ``` n=$*[0].to_i r='no answer' (?0..?9).to_a.permutation($*[1].count'_'){|q|s=$*[1] q.map{|d|s=s.sub'_',d} c=s.chars (t=1 c.each_cons(n+1){|c|e=c.shift.to_i (t=!t break)if e<1||c[0]==?0||c.join.to_i%e>0} (r=s)if t)if c==c.uniq} $><<r ``` This is a very naive implementation. I count the number of underscores, and then simply create a list of all digit-permutations of that length, to brute force every possible combination. This will perform horribly for larger numbers of underscores, but this is code golf and not fastest-code. :) **Edit:** Ported this from Mathematica. See the edit history for the original version. **Edit:** Fixed leading underscore cases. [Answer] ## Java, 421 ``` class C{static int n;public static void main(String[]a){n=new Short(a[0]);f(a[1]);System.out.print("no answer");}static void f(String s){if(s.contains("_"))for(int i=0;i<=9;i++)f(s.replaceFirst("_",i+""));else{for(int i=1;i<s.length()-n+1;){String t=s.substring(i,i+n);if(t.charAt(0)<49||new Long(t)%new Long(s.substring(i-1,i++))>0||s.chars().distinct().count()<s.length())return;}System.out.print(s);System.exit(0);}}} ``` Less golfed, with explanation: ``` class C { static int n; public static void main(String[] a) { n = new Short(a[0]); f(a[1]); System.out.print("no answer"); } /** * This method is called recursively, each time with * another underscore replaced by a digit, for all possible digits. * If there is a solution, the method prints it and exits the program. * Otherwise, it returns. */ static void f(String s) { if (s.contains("_")) { for (int i = 0; i <= 9; i++) { f(s.replaceFirst("_", i + "")); } } else { for (int i = 1; i < s.length() - n + 1;) { String t = s.substring(i, i + n); // on each substring... if ( // test for the three rules t.charAt(0) < 49 || new Long(t) % new Long(s.substring(i - 1, i++)) > 0 || s.chars().distinct().count() < s.length() ) { return; // a rule was broken } } System.out.print(s); // if we made it this far, it's a success! System.exit(0); } } } ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 179 bytes ``` d←≠⊆⊢ p←≢¨'|'d'\d'⎕R'|'⊢n←2⊃a←' 'd⍞ ⊃(t/⍨t≡¨∪¨t←r/⍨(⍎⊃a)∘{(∧/'0'≠⊃¨x)>1∊×(⊖⍺↓⊖⍎¨⍵)|⍎¨x←1↓⍺,/⍵}¨r←{×≢p:{⍕⍎∊⍉↑('_'d n)(⍵⊆⍨p/⍳≢p)}¨(⊂p/⍕0),⍕¨{⍵~⍳⌊⊃⌽⍵÷10}⍳1-⍨10*+/p⋄⊂n}0),⊂'no answer' ``` [Try it online!](https://tio.run/##dZC/T8JAFMf3@yu6XasQem0FdHB0JswmlyYVF1IaJBGDOICp5eQIxiAuGmWxcTWNCYlL@U/eP1Lf1WCMgaX9/nife9e6QbPoXbjN1mkGk9lRHcIps6oVgqZWQ2M7BKKbRuahhtELiBDEggS5W6QxvaQePfYojtdRY@djZYEYuvimGvVAPhO0eqcEMu7A6DWNIXpPUYbTtsp0kBM1b0D02NMheitRk@arhmncNQ4ZRGI110E8gFxCeJ@LCZ4iE@MyV111adXIZQFPTPpp3Maot5rjHYODHsiZ2hEJkCMI73TKqaf5Bi5O1PfIOEDqQ80aiOKmgQpmplHAZxojn1ypgbHAO8H4C/3qk5l9zFgRcWbu7JYCuL1G0u8rTAyo39Jc/@z8pE0z/IGZpjWIrVWYwwnIJyVMQlRoKc3y8BdZN8yxzOqmyv5T/ag1wbcTfCNR5tzi3Nnbhv3ry8y2KvvKfgM "APL (Dyalog Unicode) – Try It Online") -4 bytes from dzaima. -9 bytes from ngn. -4 bytes from Adam. Golfed by a lot at The APL Orchard. ## Explanation `d←≠⊆⊢` splitting function: takes character on left, string on right. `p←≢¨'|'d'\d'⎕R'|'⊢n←2⊃a←' 'd⍞` a multiple assignment: `a←' 'd⍞` a - holds input split on spaces. `n←2⊃` n - holds the number string. `p←≢¨'|'d'\d'⎕R'|'⊢` p - holds the length of each blank space. ### Part 1: generating the required number partitions `r←{×≢p:{⍕⍎∊⍉↑('_'d n)(⍵⊆⍨p/⍳≢p)}¨(⊂p/⍕0),⍕¨{⍵~⍳⌊⊃⌽⍵÷10}⍳1-⍨10*+/p⋄⊂n}0` `×≢p: ... ⋄⊂n` If there are no underscores, return the number, wrapped. Otherwise: `⍳1-⍨10*+/p` generate range 1..(9 repeated sum(p) times) `{⍵~⍳⌊⊃⌽⍵÷10}` remove 1..10^(sum(p)-1), getting all sum(p) digit numbers. `⍕¨` convert each to string `(⊂p/⍕0),` prepend 0 repeated sum(p) times to it `{⍕⍎∊⍉↑('_'d n)(⍵⊆⍨p/⍳≢p)}¨` execute the following for each no. string: `(⍵⊆⍨p/⍳≢p)` split into pieces of sizes in p `↑('_'d n)` add the input to it and make a 2xn matrix `⍕⍎∊⍉` transpose the fillers and enlist them, then remove all spaces using `⍕⍎` `r/⍨` filter this list by: ### Part 2: checking chain divisibility `(⍎⊃a)∘{(∧/'0'≠⊃¨x)>1∊×(⊖⍺↓⊖⍎¨⍵)|⍎¨x←1↓⍺,/⍵}¨` `(⍎⊃a)∘{...}` execute the following, using the first number as constant left argument: `⍎¨x←1↓⍺,/⍵` store overlapping groups of 3 in x, convert to int `|` modulo: `(⊖⍺↓⊖⍎¨⍵)` list of numbers they should be divisible by `1∊×` are any of them truthy? `>` check if the result is lesser than: `(∧/'0'≠⊃¨x)` whether any of the groups have a leading zero filter complete! ### Part 3: checking uniqueness `t≡¨∪¨t←` boolean mask for whether each number matches itself uniquified. `t/⍨` filter to get the final array `⊃(...),⊂'no answer'` pick the first item of the result with 'no answer' appended. if there are no results, it will default to that. ]
[Question] [ # Challenge Write a calculator that takes input in a verbal form (as one might speak an equation) and also outputs in a verbal form (as one might speak a number). # Rules The calculator should be able to: * add, subtract, multiply and divide * handle operands between negative one million and one million * handle outputs between negative one billion and one billion * handle decimal points in its input and place them correctly in its output * handle decimal output to the hundredths place, rounding where needed All operations yielding fractional results should round to the nearest hundredths place (identically to the output formatting). Report with output "E" (for error) when input would cause the program to fail due to being incorrectly formatted or dividing by 0; basically, the program shouldn't crash on bad input, because that would be a lousy calculator. The calculator is *allowed*, but *not required* to report errors when operands or output escape their bounds. This is meant to simplify the problem, but if you disagree with me, feel free to make a calculator capable of correctly handling greater operands and outputs without reporting errors. Output "E" in the event that an operand for an operation exceeds the bounds defined for operands. Output "E" in the event that the output exceeds the bounds described for outputs How the program handles case-sensitivity and whitespace are left up to the golfer, as is the choice of British or American English.[1](http://en.wikipedia.org/wiki/English_numerals) Programs that bypass the implementation of the calculator by using a language or library that has already implemented the functionality described above will be ineligible for victory. # Winner The program with the lowest number of characters wins. # Examples **Input:** two plus two **Output:** four **Input:** twenty-one point five minus one point five **Output:** twenty **Input:** one minus two **Output:** negative one **Input:** five times five **Output:** twenty-five **Input:** twenty-five divided by five **Output:** five **Input:** two plus two minus five times five divided by negative zero point five **Output:** ten **Input** one million times one thousand **Output:** one billion **Input:** one million times one thousand plus one **Output:** E **Input:** two million plus one million **Output:** E **Input:** one million plus one million plus one million **Output:** E [Answer] First of all, this is totally cheaty, and not complete to the specs. *requires the `--disable-web-security` flag on chrome, +22* # Javascript 509 + 22 = 531 ``` x=new XMLHttpRequest;y=Object.keys(x);b=alert;q="querySelectorAll";s="send";x[y[3]]="document";x.open("GET","http://www.wolframalpha.com/input/?i="+escape(prompt()));x[y[10]]=function(c){4===x.readyState&&(w=[].filter.call(x.response[q](".pod h2"),function(a){return"ame:"==a.innerText.slice(-4)})[0].parentElement,(k=w[q]("a")[0])&&"Words only"==k.innerText?(x.open("GET",k.href),x.send()):alert(JSON.parse([].pop.call(x[y[2]][q]("script")).innerHTML.match(/d_0.00\.push\((.+?)\)/)[1]).stringified))};x[s]() ``` The first off the spec is as well the example output The input `two plus two minus five times five divided by negative zero point five` outputs ![enter image description here](https://i.stack.imgur.com/Gk9bt.png) Any other case should get handled fine (now), this is yet pretty ungolfed as is, I just wanted it to get fixed. ``` input: two plus two output: four input: twenty-one point five minus one point five output: twenty input: one minus two output: negative one input: five times five output: twenty-five input: twenty-five divided by five output: five input: two plus two minus five times five divided by negative zero point five output: fifty-four input: one million times one thousand output: one billion input: one million times one thousand plus one output: one billion, one input: two million plus one million: output: three million input: one million plus one million plus one million output: three million ``` Oh, and if you actually going to test it, it may take a few seconds, as it loads the complete Wolfram Alpha page up to two times. Well, there might be a lot to enhance though. [Answer] ## Python, 982 ``` from re import* S=split U=sub a=S(' ',U('_','teen ','zero one two three four five six seven eight nine ten eleven twelve thir_four_fif_six_seven_eigh_nine_')+U('_','ty ','twen_thir_for_fif_six_seven_eigh_nine_')) b=range(20)+range(20,99,10) d=dict(zip(a,b)) D=dict(zip(b,a)) p='point' v='negative' def f(s): s=S('[ -]',s);n=0.;m=10**(p in s and(s.index(p)-len(s))) for x in s[::-1]:m*=10*(m<1)+100*('hu'in x)+1e3*('ho'in x)+1e6*('m'in x)or 1;n+=(x in d)and m*d[x] return n-2*n*(v in s) def F(n): l=[v]*(n<0);x=abs(n) for i in(9,6,3,0):z=int(x/10**i);h=z%100;g=(z>99)*[D[z/100],'hundred']+(h>0)*[h in D and D[h]or D[h-z%10]+'-'+D[z%10]];l+=g and g+[[],['thousand'],['million'],['billion']][i/3];x%=10**i l+=[c=='.'and p or D[int(c)]for c in'%.2g'%x][n**2>=1:];return' '.join(l) c=lambda n,l:c(eval(`n`+l[0]+`f(l[1])`),l[2:])if l else n i=S(' (?=. )|(?<= .) ',U('di.*?y','/',U('times','*',U('minus','-',U('plus','+',raw_input()))))) try:print F(c(f(i[0]),i[1:])) except:print'E' ``` I think it works as it should according to the specs, but there are probably a few more bugs. It might act weirdly for input >= one billion or any unexpected words that it interprets incorrectly. Here's a slightly more readable version with a few changes: ``` import re words = re.split(' ', re.sub('_', 'teen ', 'zero one two three four five six seven eight nine ten eleven twelve thir_four_fif_six_seven_eigh_nine_') + re.sub('_', 'ty ', 'twen_thir_for_fif_six_seven_eigh_nine_')) values = range(20) + range(20, 99, 10) d = dict(zip(words, values)) D = dict(zip(values, words)) def str_to_num(s): s = re.split('[ -]', s) n = 0.0 multiplier = 10 ** ('point' in s and (s.index('point') - len(s))) for word in s[::-1]: multiplier *= 10 * (multiplier < 1) + 100 * ('hundred' == word) + 1e3 * ('thousand' == word) + 1e6 * ('million' == word) or 1 n += (word in d) and multiplier * d[word] return n - 2 * n * ('negative' in s) three_digit_num_to_str = lambda n: (n > 99) * [D[n / 100], 'hundred'] + (n % 100 > 0) * [n % 100 in D and D[n % 100] or D[n % 100 - n % 10] + '-' + D[n % 10]] def num_to_str(n): word_list = ['negative'] * (n < 0) x = abs(n) for i in (9, 6, 3, 0): three_digit_str = three_digit_num_to_str(int(x / 10 ** i)) if three_digit_str: word_list += three_digit_str + [[], ['thousand'], ['million'], ['billion']][i / 3] x %= 10 ** i word_list += [char == '.' and 'point' or D[int(char)] for char in '%.2g' % x][n ** 2 >= 1:] return ' '.join(word_list) calculate = lambda n, l: calculate(eval(str(n) + l[0] + str(str_to_num(l[1]))), l[2:]) if l else n i = re.split(' (?=. )|(?<= .) ', re.sub('di.*?y', '/', re.sub('times', '*', re.sub('minus', '-', re.sub('plus', '+', raw_input()))))) try: print num_to_str(calculate(str_to_num(i[0]), i[1:])) except: print 'E' ``` [Answer] There we go. Golfing the version before broke it, but now we're back online. I'm positive it can be further golfed. I'll work on it more tomorrow. It was hard enough to get it working properly WITHOUT golfing it, though, and my eyes are tired of staring at it. Haha # Java - 3220 ``` import java.util.*;class a{int D=0,i,l,j;static boolean T=true,F=false;enum O{A("plus"),S("minus"),M("times"),D(""),P("point");String t;O(String u){t=u;}double p(double f,double s){if(this==A)f+=s;if(this==S)f-=s;if(this==M)f*=s;if(this==D)f/=s;return f;}static O f(String s){O r=null;for(O o:values())if(s.equals(o.t))r=o;return r;}}enum N{A("zero",0,F),B("one",1,F),C("two",2,F),D("three",3,F),E("four",4,F),AG("five",5,F),G("six",6,F),H("seven",7,F),I("eight",8,F),J("nine",9,F),K("ten",10,F),L("eleven",11,F),M("twelve",12,F),N("thirteen",13,F),O("fourteen",14,F),P("fifteen",15,F),Q("sixteen",16,F),R("seventeen",17,F),S("eighteen",18,F),AH("nineteen",19,F),U("twenty",20,F),V("thirty",30,F),W("forty",40,F),X("fifty",50,F),Y("sixty",60,F),Z("seventy",70,F),AA("eighty",80,F),AB("ninety",90,F),AC("hundred",100,T),AD("thousand",1000,T),AE("million",1000000,T),AF("billion",1000000000,T);String t;double v;boolean q;N(String u,int w,boolean r){t=u;v=w;q=r;}static N f(String s){N r=null;for(N n:values())if(s.equals(n.t))r=n;return r;}static N f(char s){return d(q(""+s));}static N d(double v){N r=null;for(N n:values())if(v==n.v)r=n;return r;}static String c(double n){return d(n).t;}}public static void main(String[]a){new a();}a(){while(T){try{List p=p(new Scanner(System.in).nextLine()),t=new ArrayList();double d=0;for(j=0;j<p.size();j++){Object o=p.get(j);if(o(o)){if((O)o==O.P){t.add((d(t.get(t.size()-1))+((d=d(p.get(j+1)))<10?d*=100:d<100?d*=10:d)/1000));t.remove(t.size()-2);j++;}else t.add(o);}else {N n=N.d(d(o));if(n!=null&&n.q){t.add((d(o))*d(t.get(t.size()-1)));t.remove(t.size()-2);}else t.add(o);}}double r=d(t.get(0));for(j=1;j<t.size();j++){Object c=t.get(j),l=t.get(j-1);if(o(c))continue;if(c instanceof Double&&l instanceof Double)r+=d(c);else r=((O)t.get(j-1)).p(r,d(t.get(j)));}System.out.println(p(r));}catch(Exception e){System.out.println("E");}}}List p(String s) {List r=new ArrayList();Scanner i=new Scanner(s);while(i.hasNext()){String c=i.next();if(c.equals("divided")){r.add(O.D);i.next();}else if(c.indexOf("-")!=-1){String[] num=c.split("-");r.add(N.f(num[0]).v+N.f(num[1]).v);}else{Object o=N.f(c);r.add(o!=null?((N)o).v:O.f(c));}}return r;}String p(double n){String a=String.valueOf(n),w,d=null,b="";l=a.indexOf(".");if(l!=-1){w=a.substring(0,l);d=a.substring(l+1);}else w=a;if(d.equals("0"))d=null;D=0;while(w.length()%3!=0)w=" "+w;for(i=w.length();i>0;i-=3,D++)b=w(w.substring(i-3,i))+b;return b+d(d);}String w(String w) {if(w==null)return "";w=w.trim();String b="";l=w.length();if(l>1&&w.charAt(l-2)!='0'){if(w.charAt(l-2)=='1')b=N.d(q(w.substring(l-2))).t;else b+=N.d(q(w.charAt(l-2)+"0")).t+"-"+N.f(w.charAt(l-1)).t;}for(j=(b.equals("")?l-1:l-3);j>-1;j--){N n=N.f(w.charAt(j));if(n==N.A)continue;if(j==l-1)b=n.t;else if(j==l-2)b=N.f(n.t+"0")+"-"+b;else if(j==l-3)b=n.t+" hundred "+b;}if(!b.trim().equals("")){if(D==1)b+=" thousand ";if(D==2)b+=" million ";if(D==3)b+=" billion ";}return b;}String d(String d) {if(d==null)return"";if(d.length()>3)d=d.substring(0,3);String b = " point ";for(char n:d.toCharArray())b+=N.f(n).t+" ";return b;}boolean o(Object o){return o instanceof O;}Double d(Object o){return (Double)o;}static double q(String s){return Double.parseDouble(s);}} ``` **With line breaks and tabs** ``` import java.util.*; class a{ int D=0,i,l,j; static boolean T=true,F=false; enum O{ A("plus"), S("minus"), M("times"), D(""), P("point"); String t; O(String u){ t=u; } double p(double f,double s){ if(this==A)f+=s; if(this==S)f-=s; if(this==M)f*=s; if(this==D)f/=s; return f; } static O f(String s){ O r=null; for(O o:values())if(s.equals(o.t))r=o; return r; } } enum N{ A("zero",0,F), B("one",1,F), C("two",2,F), D("three",3,F), E("four",4,F), AG("five",5,F), G("six",6,F), H("seven",7,F), I("eight",8,F), J("nine",9,F), K("ten",10,F), L("eleven",11,F), M("twelve",12,F), N("thirteen",13,F), O("fourteen",14,F), P("fifteen",15,F), Q("sixteen",16,F), R("seventeen",17,F), S("eighteen",18,F), AH("nineteen",19,F), U("twenty",20,F), V("thirty",30,F), W("forty",40,F), X("fifty",50,F), Y("sixty",60,F), Z("seventy",70,F), AA("eighty",80,F), AB("ninety",90,F), AC("hundred",100,T), AD("thousand",1000,T), AE("million",1000000,T), AF("billion",1000000000,T); String t; double v; boolean q; N(String u,int w,boolean r){ t=u; v=w; q=r; } static N f(String s){ N r=null; for(N n:values())if(s.equals(n.t))r=n; return r; } static N f(char s){ return d(q(""+s)); } static N d(double v){ N r=null; for(N n:values())if(v==n.v)r=n; return r; } static String c(double n){ return d(n).t; } } public static void main(String[]a){ new a(); } a(){ while(T){ try{ List p=p(new Scanner(System.in).nextLine()),t=new ArrayList(); double d=0; for(j=0;j<p.size();j++){ Object o=p.get(j); if(o(o)){ if((O)o==O.P){ t.add((d(t.get(t.size()-1))+((d=d(p.get(j+1)))<10?d*=100:d<100?d*=10:d)/1000)); t.remove(t.size()-2); j++; } else t.add(o); } else { N n=N.d(d(o)); if(n!=null&&n.q){ t.add((d(o))*d(t.get(t.size()-1))); t.remove(t.size()-2); } else t.add(o); } } double r=d(t.get(0)); for(j=1;j<t.size();j++){ Object c=t.get(j),l=t.get(j-1); if(o(c))continue; if(c instanceof Double&&l instanceof Double)r+=d(c); else r=((O)t.get(j-1)).p(r,d(t.get(j))); } System.out.println(p(r)); } catch(Exception e){ System.out.println("E"); } } } List p(String s) { List r=new ArrayList(); Scanner i=new Scanner(s); while(i.hasNext()){ String c=i.next(); if(c.equals("divided")){ r.add(O.D); i.next(); } else if(c.indexOf("-")!=-1){ String[] num=c.split("-"); r.add(N.f(num[0]).v+N.f(num[1]).v); } else{ Object o=N.f(c); r.add(o!=null?((N)o).v:O.f(c)); } } return r; } String p(double n){ String a=String.valueOf(n),w,d=null,b=""; l=a.indexOf("."); if(l!=-1){ w=a.substring(0,l); d=a.substring(l+1); } else w=a; if(d.equals("0"))d=null; D=0; while(w.length()%3!=0)w=" "+w; for(i=w.length();i>0;i-=3,D++)b=w(w.substring(i-3,i))+b; return b+d(d); } String w(String w) { if(w==null)return ""; w=w.trim(); String b=""; l=w.length(); if(l>1&&w.charAt(l-2)!='0'){ if(w.charAt(l-2)=='1')b=N.d(q(w.substring(l-2))).t; else b+=N.d(q(w.charAt(l-2)+"0")).t+"-"+N.f(w.charAt(l-1)).t; } for(j=(b.equals("")?l-1:l-3);j>-1;j--){ N n=N.f(w.charAt(j)); if(n==N.A)continue; if(j==l-1)b=n.t; else if(j==l-2)b=N.f(n.t+"0")+"-"+b; else if(j==l-3)b=n.t+" hundred "+b; } if(!b.trim().equals("")){ if(D==1)b+=" thousand "; if(D==2)b+=" million "; if(D==3)b+=" billion "; } return b; } String d(String d) { if(d==null)return""; if(d.length()>3)d=d.substring(0,3); String b = " point "; for(char n:d.toCharArray())b+=N.f(n).t+" "; return b; } boolean o(Object o){ return o instanceof O; } Double d(Object o){ return (Double)o; } static double q(String s){ return Double.parseDouble(s); } } ``` ]
[Question] [ It is a well-known fact that you can colour a two-dimensional map with four colours in such a way that two countries with a common border always have different colours. There have already been enough challenges on this topic. However, the prerequisite for this is that there must be no enclaves, i.e. non-contiguous areas that must be coloured in the same colour (otherwise, in the worst case, you would always need as many colours as countries, because each one could have an enclave in every other one). In this task there is only one dimension, so without enclaves, you would get by with two colours. But, alas, the world and this challenge allow enclaves. **The task**: Colour a one-dimensional map with as few colours as possible, so that adjacent countries always have different colours, but enclaves have the same colour as the rest of the country. Of course, there can be more than one optimal solution, but output only one. **Input**: A list of whatever, e.g. a character string in which a certain character stands for a country. **Output**: The corresponding "coloured" list, e.g. the corresponding character string in which a certain character stands for a certain colour. **Test data**: ``` abcdddeefghhhi x2x222xx2x222x abcdddeefgahhi 12122211231221 abcdadcbaaaeb1 12321232111321 #Aa#Bb#Ccabc# 1231321243241 #Aa#Bb#CcabC# 1231321323231 ``` **Test data for languages that do not support strings, but lists**: ``` [5,6,3,8,8,8,9,9,1,12,2,2,2,17] [9,2,9,2,2,2,9,9,2,9,2,2,2,9] [5,6,3,8,8,8,9,9,1,12,5,2,2,17] [1,2,1,2,2,2,1,1,2,3,1,2,2,1] [5,6,3,8,5,8,3,6,5,5,5,9,6,1] [1,2,3,2,1,2,3,2,1,1,1,3,2,1] [1,2,3,1,4,5,1,6,7,3,5,7,1] [1,2,3,1,3,2,1,2,4,3,2,4,1] [1,2,3,1,4,5,1,6,7,3,5,6,1] [1,2,3,1,3,2,1,3,2,3,2,3,1] ``` [Answer] # JavaScript (ES6), 121 bytes Expects an array of characters, returns a string of digits. ``` f=(a,x)=>(g=([v,...b],m,p,o)=>v?(h=j=>j?h(j-1)||!(m[v]-j)&&p==v|j^m[p]&&g(b,{...m,[v]:j},v,[o]+j):0)(x):o)(a,g)||f(a,-~x) ``` [Try it online!](https://tio.run/##VY/BboMwDIbvfYqsrlCiBbReqdKq0B73BIipTgjQqDQIKoRE2aszS9sOPdn@/f2/ZYcD9qa7to/w7gu7LKXiKEeh9rxSPBtkFEU6l41spSdxOPBaObV3h5q7cCuezzfeZEMeOhEErVLD0301WZsHQcW1nMjcSFrHbpaDzHz@7kT8IfgoYi/oTkUBJdXwexTLLlsxtkZtiqKwtqzqur6u5auGLxoWRiOi1dtfDY6QQAonOAOCBgMFWDgiJBpSA6cCzjQmkKSQnuBEkAFjwWrQBOJ/xh9PB2C9yldR6bszmpr3TO3ZxDpLDSt5Rs/1udgx4@@9v9no5it@2Uyf@KijBkdOe2LFTMDNd33MNhPN84Uss1h@AA "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: a, // a[] = input array x // x = maximum color index, initially undefined ) => // ( g = ( // g is a recursive function taking: [v, // v = next value from a[] ...b], // b[] = remaining values m, p, o // m = mapping, p = previous value, o = output ) => // v ? // if v is defined: ( h = // h is yet another recursive function taking: j => // j = color index candidate j ? // if j is not 0: h(j - 1) || // try a recursive call with j - 1 !( // if either m[v] is undefined m[v] - j // or m[v] is equal to j ) && // and p == v | // either p = v j ^ m[p] && // or j is not equal to m[p], g( // then do a recursive call to g: b, // pass the remaining values { ...m, // build a new object m' with all properties [v]: j }, // of m and a new property m'[v] = j v, // set the previous value to v [o] + j // append j to the output ) // end of recursive call : // else: 0 // failure: return 0 )(x) // initial call to h with j = x : // else: o // success: return the output )(a, g) || // initial call to g, using m = g f(a, -~x) // if it failed, try again with one more color ``` [Answer] # [Python](https://www.python.org), 111 bytes ``` f=lambda s:min([f(s.replace(x,y))for x in s for y in s if y<x<x+y not in s+s[::-1]]+[s],key=lambda t:len({*t})) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VU7LbsMgELz7K1byBRonKjiHyooPbe79gSiqMIYaFYNlYwmrSn-ix15yaf8pf1OIkz4OsLM7uzPz8dVNrrHmePwcnVzenawsNWurmsFQtMqgnUTDqhedZlwgn00YS9uDB2VggAinGSoJ08Zv_GICY915thh2RbEk-_1iN-yzFzFdlV2hhUGvN-6A8cX2Tfa2BTka7qzVQa7tbO9A9-MTZ7wRSRJyXRv0aI3ASOIwDQl0dLNdkLzFRQIqs1CCXg2dVg7hBLpeGYckUjibfSM84LKcO_uT4nh6ZxWvWc0rxpioCBCa0_MjJHxJZOtaCPncNI0CTz2l1F_KH5ZFloRLGi5pHipJ0nuWPlTploe1FKJylKTrnK7_kdtfMg_OOZmzfQM) Takes and returns a string. ## How? Recursively replaces one colour a time for a non neighbouring one. Of all possible such replacements returns the best one as found recursively. This would be very slow, so in the footer I inject the Python standard lib magic memoiser which doesn't change the outcome of a function but very much its speed. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~33~~ 30 bytes ``` ⊞υθFυFιFΦ⁻ικ¬№⁺ι⮌ι⁺κλ⊞υ⪫⪪ιλκ⊟υ ``` [Try it online!](https://tio.run/##NY3BCsIwEETvfsUedyF@QY@CB0EJ@gVpjHTpkq1p0t@PSdW5DMww8/zkklcntdqyTlgMvGk4vDQBFoLd@ednlhwSXjmWFdnATAZumvGkJWa08k3vYQtpDW3V6j2cDQh1wR9xUY74WIRzXwj1r0a1ifuRLg1NQ61u9M/g6nGTDw "Charcoal – Try It Online") Link is to verbose version of code. Exponentially slow, as it generates multiple copies of all legal colourings and then outputs one with the fewest colours, so test case is pretty short. Uses the input character set as the colour characters. Explanation: ``` ⊞υθFυ ``` Start a breadth-first search for legal colourings. ``` FιFΦ⁻ικ¬№⁺ι⮌ι⁺κλ ``` Loop over all possible parings of countries that could be coloured with the same colour. ``` ⊞υ⪫⪪ιλκ ``` Generate the resulting colouring and add it to the search list. ``` ⊟υ ``` Output one of the colourings that uses the fewest colours. ~~41~~ 38 bytes for a somewhat faster version that saves fewer duplicate colourings and can therefore handle one of the provided test cases: ``` ⊞υθFυFιFEΦι›‹κλ№⁺ι⮌ι⁺κλ⪫⪪ιλκF¬№υλ⊞υλ⊟υ ``` [Try it online!](https://tio.run/##NU7LDsIwDLvzFTmmUvmCHZFAQoAm@IKyZTRatG597PdLu8HJiWPH7qzxnTOSc5uCxaRhUc1hcB4wKdiQf3g3M55ZInlkDRdPpo43CgFHDaI0nFyaIraSQlU8aSUfqPjLaSM3marr1fGEr1k4VmX1joXfcx4u4v4p7Xr4V5NSrfVcM9xc@qkmZ/Pu@r4nGj7GWs7HVb4 "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # Python3, 318 bytes: ``` def f(s): q,F,T=[(s,'','',{})],0,'' while q: s,S,L,d=q.pop(0) if''==s: if(T==''or len({*S})<F):F,T=len({*S}),S continue K=[*{*sum(d.values(),[])}] for i in d.get(s[0],K+[max(K+[0])+1]): if(''==S or S[-1]!=str(i)or s[0]==L)and(T==''or len({*S})<F):q=[(s[1:],S+str(i),s[0],{**d,s[0]:[i]})]+q return T ``` [Try it online!](https://tio.run/##dZA9a8MwEIZ3/woVD9LZarDpUkw1tIEsyeZsQoNsybEgkT9k9wOT3@5KLS0UUhDovXvuvTup/5jazj489uO6Kt2ghjgoIjTQHT0yThzFOJzlCoJmXkXorTVnjQZfhBwt6YEqNmz6ricZ@JRpMGbMBeo1OTKGcTeis7ZkScorPO2gCK1/E7QMpXVnJ2Nn7fWe8WRJ3HwhavMqz7N2BCgXcBUeNr6XQcYitTnpiTieCbpP@UW@E39lAtJcwM/wsEmJvKPk97m4Y24aiQEfBxtjB5BW3d5wCE/neSFomX676NeoJUnUlyq4Ef5L0iFCo57m0aLj2o/GTsSPlVWtlNK6ObVtazBAdAPJW0iqupJS6ir/g@JnGb9U8bb2NfF/ZBvI@gk) [Answer] # [Haskell](https://www.haskell.org), 138 bytes ``` import Data.List f x|b<-nub x,y<-[elemIndices j b!!0|j<-x]=[v|n<-[1..],t<-mapM id$[1..n]<$b,v<-[map(t!!)y],z y==z v]!!0 z=map length.group ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZLNToQwEMfjlacYYLOBBIgtHjzAQVcPJvoEGw4FCnTlK1BW2PAEvoKXvRifSZ_GYT_VeGimM__f_KdN-_aRsfaZ5_l2-97JxL7-fBVFXTUS7phkzqNopZJAP4aeXXYh9Nbg2Uue8-KhjEXEW1hBqKqX48qz-8BfrscSdeI4gSU9u2D1E4h4NhXKwJuF1hpVrBpSVc0hsDYw-P4G1gFaKBsfFch5mcrMSZuqq_cn-roYoqppeCShb2FowYdk2vlTxHQ-h_SQp1P-kvGGK4CiD2dHcGDniUKKwqmIt1KUgokSi3UjSgnL4zRj6k6aqrgvuwIqE4wEhAkjGMKaUs8GyVsZsZa3gaKc9ui0xDGGxsIojmPOkzTLMqFZoPW0p5T2h6CZ1h-OHThCCQKEUBcj-cmxOAoZYzwke86lu0WIe-b0G6bfhvoiwgYdsR03AfTKpVf_YYtfmIuOLmKBsn-B49_4Bg) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 19 bytes ``` QŒcw@ÐḟŒBy€)Ẏ WÇƬẎṪ ``` [Try it online!](https://tio.run/##y0rNyan8/z/w6KTkcofDEx7umH90klPlo6Y1mg939XGFH24/tgbIeLhz1X/rRw1zFHTtFB41zLU@3M71cPeWw@1AdZH//ycmJaekpKSmpqVnZGRwIXiJUF5iSnJSYmJiapIhl7JjorJTkrJzMlBcGZnnrAwA "Jelly – Try It Online") A pair of links called as a monad and taking a string and returning a string. Uses a subset of the input characters for output. In brief this iteratively finds all possible merges of characters in a breadth-first search. The last remaining group of possibilities will be the ones with most characters merged. Slow for the first two test cases as written so TIO link uses slightly shorter versions. ## Explanation ``` QŒcw@Ðḟ;U$y€)Ẏ # ‎⁡Helper link: takes a list of strings and for each one generates a list of strings with one pair of valid characters merged before joining these outer lists ) # ‎⁢For each string: Q # ‎⁣- Uniquify Œc # ‎⁤- Combinations length 2 w@Ðḟ # ‎⁢⁡- Filter out those which are a substring of: ŒB # ‎⁢⁢ - The string palindomised y€ # ‎⁢⁣- Use each of the remaining combinations to ‘translate’ the string Ẏ # ‎⁢⁤Join outer lists ‎⁣⁡ WÇƬẎṪ # ‎⁣⁢Main link: takes a string and returns the simplified string W # ‎⁣⁣Wrap in a list ÇƬ # ‎⁣⁤Call the helper link until no further changes, collecting up intermediates Ẏ # ‎⁤⁡Join outer lists Ṫ # ‎⁤⁢Tail 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Perl 5](https://www.perl.org/), 150 bytes ``` sub{$_=pop;sub L{pop=~s/(.)\1*/X.length$&/egr}@c=/./g;for$n(1..@c){for$t(0..$n**@c){$c{$_}=$t%$n,$t/=$n for@c;L($s=s/./$c{$&}/gr)eq L($_)&&return$s}}} ``` [Try it online!](https://tio.run/##vVLRbpswFH2ev@Iq8QJUGQzSvYSihaZ0QSMhKkRttU4RIYSgpoRiR8oWsV/Prknapo97GRL29Tn3HF/7ukjK1Zc9XVh7tpnt6NQq1oWJIXg7jKw/TJNV5UE/0@7UVZKnfElbWpKWVS@2NFVLzcW6pLmsq2ovVnZiweXPqkrzszMB0BgtK4vyjzRvU65ZNAdM6sWmJ1NmMbQQKa1KS0sleQZEp0qrVSZ8U@aUVVW1NwlpAoQDB659z/Nv3dE3oAtwgxoL7KEDolznru@MQ7h1wwEEY8e5mozh8h7sqyshuPYnN9Af2DdBFzZ59iwsRao/Cev1B@EVOkEYCPEohA4M3dEEEfBHMLwHzx6HPjpOjlu87n3jBBMvDIThkvOCdTWNZ2u13OQaDOwAbAhdTPPcoRuCHaKdc7QmZMMS8DLGu90Jz1YgiUokk2AzyD83Q2j/S0MINgQV8lNU/GDFKuM/2/WkPeRa@@JCkkg0i@fzeZIs0uVymcHW2BqGsT1OJ2wkWN3QEdZ1o4OzXrPRPJ5FUZTMdGQ7Rv3rOg6kaUfNy1mzH2MaXrgQCf68Y5y/I/tvZAfVHZ0QZUcAv2ZRZjkHVq5@48na0lRSzDzZcrNmn37JNGvTRLF6dPoCUXaImmKg2UkXKFOt0z4c8rBtNHsVp1aLLtBVOSCH7VHEeCnTVAG845dVosBXkNaPEnRBGvn4Vr5Lp6oGRlledLEIjNI1xygV9KEG9gnJDYIN9cUxU9TGaUKteaNTpB/yhkkq8d6OdewAn5qsnB6z8e61QUX2fwE "Perl 5 – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/) I was trying to rewrite [@Ajax1234's Python answer](https://codegolf.stackexchange.com/a/267220/110802) in scala. **But the scala code fails on some cases. Any help would be appreciated.** [Try it online!](https://tio.run/##nVRNb5tAEL3zK6b4kEWmJL5a4ZBaiVS5VQ92T5ZVDbCYbfFClyVt2vDbnYHly8RKpV5gd@fNzHszO1uEmOLplAXfeajhMwoJfy2AiMcQs2IJG62EPDjdAvzGDPCICn6WvOR08kkUmrHCBdt24QquXIqT71YJKrex7T5Kvd8zx3F61wdyu@l3W9rZttXsfyUi5cCa2J7M5P0x109Om7WGp8DCUikutaHkQq7448aFFAttkkYi1CKTqMjRNzS9hGPUxuh4G4NGkVqtRcST4J4oJgQMaNsZ4PnZ5Pd0tuHaK8QfDrfwMHaARu4UNTJvO3N/VrWrCnha8FGsWv@a4INEj45KXnhxilpz2WbQWV353i3OFDABt@/Hjgeuv6h7ij/RXJfKpSzLOfmQ2PVQhRvDZ@0d8TfMYUE9PRNaw43QV/Wp21OTM/fonQ9i2BHoNQXw/b6n51n@qwfjzk8E11egvUYkauDlwqXCjCpY5hFqHrF/wN4udDM@VEcqt6h/S0PzjHplXVr3t8Qy3@a39Yo8FZrZtkNdytk3kkMDOF8M23aoveMPs7Ja53rqj/QEMFQHmv07pfBpZyB7egK@SqH7ByCnU51KFjMbgzCKIs7jQ5Ikwm7H/Pr6IgTfgmAUBojIg0UHGQFmdzj7EMxWISFnF0OMEKsWUVnV6fQC) ``` object Main { def f(s: String): String = { var queue = List((s, "", ' ', Map[Char, List[Int]]())) var F = 0 var T = "" while (queue.nonEmpty) { val (currentString, prevS, lastChar, dictionary) = queue.head queue = queue.tail if (currentString.isEmpty) { if (T.isEmpty || prevS.toSet.size < F) { F = prevS.toSet.size T = prevS } } else { val K = dictionary.values.flatten.toSet.toList for (i <- dictionary.getOrElse(currentString.head, K :+ (if (K.isEmpty) 0 else K.max + 1))) { if (prevS.isEmpty || prevS.last.toString != i.toString || currentString.head == lastChar) { if (T.isEmpty || prevS.toSet.size < F) { queue = (currentString.tail, prevS + i.toString, currentString.head, dictionary.updated(currentString.head, dictionary.getOrElse(currentString.head, List()) :+ i)) :: queue } } } } } T.split("").map(_.toInt+1).map(_.toString).mkString } def main(args: Array[String]): Unit = { println(f("abcdddeefghhhi")) //println(f("abcdddeefgahhi")) //println(f("abcdadcbaaaeb1")) println(f("#Aa#Bb#Ccabc#")) //println(f("#Aa#Bb#CcabC#")) } } ``` ]
[Question] [ # Santa's Shortest Path Problem Trying to be as time-efficient as possible Santa needs to plan his trips carefully. Given a 5X5 grid representing a map of villages it is your task to be Santa's flight controller. Show santa the shortest and therefor fastest route to fly his sleigh and give him a list of coördinates (or directions) to follow. Be carefull though, do not let Santa crash, nor get him arrested! --- **1. Examples** [![enter image description here](https://i.stack.imgur.com/99wHO.png)](https://i.stack.imgur.com/99wHO.png) ###### A2,B2,B3,B4,C4,D4,D3,D2,D1,E1 [![enter image description here](https://i.stack.imgur.com/sLjhO.png)](https://i.stack.imgur.com/sLjhO.png) ###### B1,B2,C3,D2,D1,E1 [![enter image description here](https://i.stack.imgur.com/bVUAe.png)](https://i.stack.imgur.com/bVUAe.png) ###### B1,B2,C2,D2,D1,D2,E2,E3,E4,E5,D5,C5,C4,B4,A4,A5 [![enter image description here](https://i.stack.imgur.com/TrZZS.png)](https://i.stack.imgur.com/TrZZS.png) ###### A2,A3,B3,C3,D3,C3,C2,C3,C4 [![enter image description here](https://i.stack.imgur.com/9GeEI.png)](https://i.stack.imgur.com/9GeEI.png) ###### B1,A1,A2,A3 [![enter image description here](https://i.stack.imgur.com/Sx48s.png)](https://i.stack.imgur.com/Sx48s.png) ###### B1,A1,A2,A3,A4,A5,B5,A5,A4,A3,B3,C3,C2,C3,C4,C3,D3,E3,E2,E1,D1,E1,E2,E3,E4,E5,D5 [![enter image description here](https://i.stack.imgur.com/uYKpM.png)](https://i.stack.imgur.com/uYKpM.png) ###### empty --- **2. Rules** * In the examples '□' represents a village on the map Santa has to visit; * In the examples '■' represents a no-fly zone *or* obstacle (antenna, mountain etc.) Santa *can't* cross; * Input is any representation of a 'grid' with villages and obstacles; * POI's can be any given character to help you make a distinction between villages and obstacles (1's and 0's for example); * Santa can only fly horizontally and vertically on this grid; * Santa has to *start* at `A1` on the grid. His starting position is excluded from the result; * Santa can go back the way he came, meaning: he can visit the same coördinates multiple times; * Return Santa an array (or concatenated string) of coördinates ranging from A1-E5 which represents a route that visits all villages in the *shortest* manner possible; * Coördinates ranging from A1-E5 are prefered, but smart Santa could read any list of clues that could lead him as long as it takes him step-by-step through the grid, e.g: `^˅<>`; * In case of a tie, present Santa with a single option; * One can assume all villages are reachable; * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! --- I did come across some related posts: * [Travelling Salesman](https://codegolf.stackexchange.com/q/31898/100057) * [What path will santa take?](https://codegolf.stackexchange.com/q/102400/100057) But the tasks seem to be quite different. --- [Sandbox](https://codegolf.meta.stackexchange.com/a/25378/100057) [Answer] # Python3, 329 bytes: ``` E=enumerate def f(b): q=[(0,0,[],{(x,y)for x,J in E(b)for y,t in E(J)if t==1}-{(0,0)},{})] while q: x,y,p,m,M=q.pop(0) if not m:return p for X,Y in[(1,0),(-1,0),(0,-1),(0,1)]: if len(b)>(J:=x+X)>=0<=(K:=y+Y)<len(b[0])and b[J][K]!=2and(J,K)not in(u:=M.get((x,y),[])):q+=[(J,K,p+[(J,K)],m-{(J,K)},{**M,(x,y):u+[(J,K)]})] ``` [Try it online!](https://tio.run/##hZFNj9owEIbPza9wuawNA7LNfqBovYeV9gKi512lUQXC6UYijglGJUL8djrjsKuqSlUfbM/rZ97JTHwb3ms3nfnmcnkx1h0q26yCTTa2YAVfizRhO5NxCRKyHE78CK0o6oYdYc5Kx14QobCF0IVzURYsGKPO4xNliTOcziJP2K/3cmvZDv0wtwUPFSzNbuJrz6VAEdNcHViVNjYcGsc8auT8Cm/onHGFXsDH3SFhrOKhRE6OlL21Dj/mic9Tcxy9iicjHw1fpKYdvYnH@JjJXKzchq2zeZ4t8q9GY8TnsBBUuXT8kJrl5KcNPLaJDQuR7kbYPjLgR/EUOVTYGt2wteFwCRFODx/P2O2FphfqH@t61Wz4Mw7xy7WrLBtWK89LF4CVIqcGSxpcUW6Dbfi32llgz5O935aB33x3NwJnl@yVGQwGUkupEqmk1ImmIJEU4I4L35O9JgwJTRytnj2C0@intNJXVeOKBO6YfvW7jVhXCllJxSmlu5MesbvOLdbQBKu/q0bs4ePr1KddR1ytSY/gfQf@o4E/2phFUP0X9A0OnBf885fslRCiR9b98rRfvu2X7/rlh375vl@eoXz5DQ) [Answer] # JavaScript (ES7), 158 bytes *+1 to support a village at A1* *-1 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects a matrix of integers: `0` = empty cell, `1` = target, `2` = blocked. ``` f=(m,n=0)=>(g=(X,Y=0,p=[])=>/.1/.test(m)?m.some((r,y)=>r.some((v,x)=>p[n]||v&2|(x-X)**2+(y-Y)**2-1?0:g(x,y,[...p,[x,y]],r[x]=0)||v&&r[x]++)):o=p)``?o:f(m,n+1) ``` [Try it online!](https://tio.run/##fU6xbsIwFNzzFREDPBPH2B6pDFM7dKADCyhEIg1OmiqJUzugRKXfTu2A1EoV9fD07t2d796TU2JSXTRtWKuDvFwyARWuBUViAbmADd4KihsRxfYwI2xGWmlaqNCyIkZVEkDj3lL6hk64s6iJ6vh8Po35Gbpwg6ZTHkAfbt0SsiWd59DhHkeEkAZHdo1jrKMutqnONXZ7ECA0V6JB@/1SzTNXKmDoouXHsdASJpmZIKJlcngqSrnu6xQoIq1at7qoc0DENGXRwmhX7@oRIpnSj0n6BsYXC//T8/1Stn7lC9/8CK2sSpqrxFUz8YBXx@pVaoQerCtVtVGlJKXK4Xn9siJmiCuyHmxD5ERf6ELd8@5Nj/1PU04p86hVcY87YAn2i2bc0XfdjDN@A9y@gbDTugb6@qHVUBfhpNd9uA@pjnbgT81v "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: m, // m[] = input matrix n = 0 // n = maximum number of moves - 1 ) => ( // g = ( // g is a recursive function taking: X, Y = 0, p = [] // (X, Y) = current position, p[] = path ) => // /.1/.test(m) ? // if there's a village anywhere except at A1: m.some((r, y) => // for each row r[] at index y in m[]: r.some((v, x) => // for each value v at index x in r[]: p[n] || // if the max. number of moves is reached v & 2 | // or this cell is an obstacle (x - X) ** 2 + // or the squared Euclidean distance (y - Y) ** 2 // between (X, Y) and (x, y) - 1 ? // is not equal to 1: 0 // do nothing : // else: g( // do a recursive call to g: x, y, // pass the new position [ ...p, // append the new coordinates [x, y] ], // to the path r[x] = 0 // set this cell to 0 ) // end of recursive call || v && r[x]++ // if v = 1, set the cell back to 1 ) // end of inner some() ) // end of outer some() : // else: o = p // success: save the path in o )`` // initial call to g with X zero'ish ? o // if successful, return the solution : f(m, n + 1) // or try again with an extra move ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 99 bytes ``` ⊞υ#F⁵⊞υ⁺S#≔ΣEυE⌕Aι@⟦κλ⟧θ≔⟦⟦E²¬ι⟧⟧ηW⬤η⁻θκ≔ΣEηEΦE⁴E§κ⁰⁺ξ∧⁼π&μ¹⊖&μ²⁻#§§υ§μ⁰§μ¹⁺⟦μ⟧κη✂E⮌⊟Φη¬⁻θι⁺§α⊟ι⊟ι¹ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVGxTsMwEBVrvsJKBtuSK9EKJKQuDQKkDqCIjlGGkLiNVcdpY7vtv7B0AMFP8COs_AjnuGkpi-179-7evfPrZ1HlbdHkcr9_t2Y-uPm--EmsrohlKIxCOg7mTYvINUU9mkiryVStrJmZVqgFoZ4J1FhrsVBkZmvymK8c2V0PQpWxlEQAbxICO10yJDNK4bk-VaWpI48YemoMEZRmGUMVpLeVkBwR16GChkKB_JqhJdSjf4JVLygNbzvkyiOxmaqS7wgIX9KDhR1DsSrJ_drmUpMVQ7fCbIXmDqwZGrrx7njR8porw0tynh5R2hnw84B_6HYQ6W97gmqnS8_ioa_vRknrzBui3nICezVkJkXBOxfPfMNbzUnSHM1Vfk_HdQj6p18vk0MMJaJL-AftlMdv-qXQhx__SMPBRobZF44wngR4gnEURC4IMADdibHn_gI) Link is to verbose version of code. Takes input as a 5×5 character grid where villages are marked with `@` and obstacles with `#`. (In the link I've filled in the rest of the grid with `'` as it's the least worst character I could find; most symbols have some sort of ligature that messes up the display.) Explanation: ``` ⊞υ# ``` Start with an obstacle. Due to Charcoal's cyclic indexing, this prevents Santa from flying off the top or bottom of the grid. ``` F⁵⊞υ⁺S# ``` Input the grid, appending an obstacle to the right side. (But cyclic indexing also prevents Santa from flying off the left side.) ``` ≔ΣEυE⌕Aι@⟦κλ⟧θ ``` Find the positions of all of the villages. ``` ≔⟦⟦E²¬ι⟧⟧η ``` Start a breath-first search with Santa at `A1`. ``` W⬤η⁻θκ ``` Repeat until a route which reaches all of the villages is found. ``` ≔ΣEη ``` For all of the routes searched so far... ``` EΦE⁴E§κ⁰⁺ξ∧⁼π&μ¹⊖&μ² ``` ... for all four possible next steps... ``` ⁻#§§υ§μ⁰§μ¹ ``` ... which don't run into an obstacle... ``` ⁺⟦μ⟧κη ``` ... generate a route with the additional step. ``` ✂E⮌⊟Φη¬⁻θι⁺§α⊟ι⊟ι¹ ``` Output any route which reaches all of the villages, but remove the `A1` at the start. Note: `⁻#§§υ§μ⁰§μ¹` should be `⁻#§υμ` but I haven't implemented multidimensional indexing in Charcoal yet. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~75~~ ~~79~~ 76 bytes ``` Þ¾0£00"n`^v`*¨^(n+D→ Du>A[÷?ii:u≠[¾← c¬[&+|_]]|X]⅛)¥?f1O=)`<>^v`₈*Þ×vṖ1Þf¤pc ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnsK+MMKjMDBcIm5gXnZgKsKoXihuK0TihpIgRHU+QVvDtz9paTp14omgW8K+4oaQIGPCrFsmK3xfXV18WF3ihZspwqU/ZjFPPSlgPD5edmDigogqw57Dl3bhuZYxw55mwqRwYyIsIiIsIltbMCwgMCwgMCwgMCwgMF0sIFswLCAwLCAwLCAwLCAwXSwgWzAsIDAsIDAsIDAsIDBdLCBbMCwgMCwgMCwgMCwgMF0sIFswLCAwLCAwLCAwLCAwXV0iXQ==) Times out for solutions longer than 3 moves. Takes a list of lists where `0` represents a blank space, `1` represents a village and `-1` represents an obstacle. Returns a string of `><^v` if it does return a solution, indicating the directions to move. Because it's 12:57am, I'll give a quick high-level explanation. The algorithm here is to: * Generate all possible combinations of directions of all possible lengths less than or equal to 256 (``<>^v`256*Þ×vṖ1Þf`) * Find the first solution (which will be the first shortest) where (`...)...c`): + After a little initalisation of some variables (`Þ¾0£`) + And starting at [0, 0] (`00"`) + Moving around the grid in the directions provided by each string (``^v`*¨^(n+D→ Du>A[÷?ii`) + Making sure no obstacles are hit in the path (`:u≠`) + And tallying the villages that have been visited (`[¾← c¬[&+|_]]`) + Results in visiting a number of villages that is equal to the count of villages in the input (`¥?f1O=`) So basically, get the first solution by brute force from all possible solution strings. [Answer] # [Haskell](https://www.haskell.org), 214 bytes ``` r=[0..4];a#v=[[i,j]|i<-r,j<-r,a!!i!!j>=v] a?p@([x,y]:_)=[k:p|k<-[[x+1,y],[x-1,y],[x,y+1],[x,y-1]],k`elem`a#0] g a=filter(\q->all(`elem`q)$a#1) s a=until((([])/=).g a)((a?)=<<)[[[0,0]]] f a=tail$reverse$head$g a$s a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVFBbsIwEFR79Cs2kIOt2Gki9VClCfQDPfVorOKCgRAnhMShIPGTXrhU_VGl9jU1BGhRZa13tTOz2rHfPmayzpTWu917Yybs7uuzSnjg-7fiXnZXCecpnYttGrOKzveXdJzUcea9ZCWQ7JcPmK_pRkTPJOFZVG6zmHG-9kLbo3zNjpluvLDNLBSCZkOlVT6U3UCgKchkkmqjKjxYsp7UGrfokriyGxJUW0JTmFRjjLkgNwnxrYZgLPskiWPCOQ9oIIRAE8s0MtVupVaqqpU7U3LsWrJrZ7Tuvq-uGYMgApWXZgMja5xCGIGR1VQZCszWL3oxytQYGVWbGhLgCIDbE-xhCvt8COvIItAi8AdhZ-TE_9VdaC50_5BzWGsAAqFK1Y0-rJTLEiZwWBChXKaF7ZWNeTIVuDBaFCNpHi0FY8_rDIoO8evZ4pXAcUD7FKcP_wE) [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~429~~ ~~390~~ ~~380~~ ~~373~~ ~~370~~ ~~358~~ ~~341~~ ~~331~~ 328 bytes * -47 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c) * -19 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ``` #import<map> #define q(d)5&&k(g,i+d,r,v,c),i #define S size() #define z&(!b.S|r.S<b.S) using m=std::map<int,int>;m b;int i,c;int k(m g,int i,m r,m v,int c){g[i]<50&r.S<20&3>v[i]z?v[r[r.S]=i]++,g[i]&1?c--,g[i]=0:0,b=!c z?r:b,~i%q(1)%q(-1)/q(-5)<4*q(5):0;} #define f(o,s)m g;b=g;c=0;for(i=25;i--;c+=(g[i]=s[i])&1);k(g,0,b,b,c);o=b ``` [Try it online!](https://tio.run/##dVPbkqIwFHyWr8gwNZhIcAK7vBDQ2m/w0eVBIrqpGUADWuqs@@vOSVjxUpoUyUmn6ZPTBLFaeUshTqdXWawq1cTFbDWyXuf5QpY5WuM5CR3nAy@pdOdU0S0VhMpuf4Jqecgx6YCDg1@y4eSvGk5imIm1qWW5REVSN/MoAu1Ylg2FZ8QLlHEIkKTCzB@4QEvaIgVS8GzNSpCv5VSmccgcrRow58doC8BhvJ2qKUBpIlPXpZrk@GPheSZMWMRolrwIdBirKKP/5Nsa@wQGzyfvMIYk/jlY45BEjB@7Aha4ojWBk/AsWXKRML6oFJZJEHLpeVy4CTbqNQzE8QnX3kAi6ILwKsnAyFJ8buY5imVVNyqfFSPL0oUUM1mCVV8Wgiaqsoba/szUADV53dTTFCWo3dPNZs@aTa9IAWM@dBYEOtSLByQ/6PDnSn7gGwWQCkwQMAPckEwSQ/T1bvtKcK/UqrD7pFckZqIjt8wMDiOsHWrAAsb/@9GkELkuMZSLMRfLgIzNinQvWD24ObzjLrCihkqusHOyPXxbtI9DGM5ZbjPdsHeavdPs3TX73Mz1FtWmQXHcnX@6H4TuLuXWU6b9u7Qv28dez3pMU3m9@WwiZD@oQ4IPPocpRmrY/o6wuj/kjZ6xjeD@r76r4B6/hUSjGsR9v8XeWwxfyyIP@WiMbIpsBGexr1y9r6qr62gdT98 "C++ (gcc) – Try It Online") ]
[Question] [ ## Background [Combinatory logic](https://en.wikipedia.org/wiki/Combinatory_logic) is a system where a term is written using a finite set of combinators and function application between terms, and reduction rules are defined for each combinator. The well-known S and K combinators have the following reduction rules: $$ \begin{aligned} S\;x\;y\;z & \overset{S}{\implies} x\;z\;(y\;z) \\ K\;x\;y & \overset{K}{\implies} x \end{aligned} $$ A term is in *normal form* when no reduction is possible. A term has a normal form if a series of reductions applied to it gives a normal form. The halting problem in combinatory logic is essentially about determining whether a term has a normal form. It is known that [any lambda calculus expression can be converted to an expression in SK combinatory logic](https://en.wikipedia.org/wiki/Combinatory_logic#Completeness_of_the_S-K_basis), and therefore the halting problem for SK combinatory logic is undecidable. However, neither K nor S alone has such property, and it turns out that the halting problem for each of them is decidable. But K is too trivial (it always terminates), so we turn to S. A paper titled [The Combinator S](https://www.sciencedirect.com/science/article/pii/S0890540100928748/pdf?md5=d3887848b1976953801f88798b8dc834&pid=1-s2%20.0-S0890540100928748-main.pdf&_valck=1), by Johannes Waldmann, describes how to decide if a term in S combinatory logic has a normal form. Theorem 55 is the main result, and the regular tree grammar is also presented in Appendix 2. ## Examples The expression \$S(SS)(SS)S\$ halts in two steps: $$ \begin{aligned} S(SS)(SS)S & \overset{S}{\implies} SSS(SSS) \\ & \overset{S}{\implies} S(SSS)(S(SSS)) \\ \end{aligned} $$ But the two expressions \$S(SS)(SS)(S(SS)(SS))\$ and \$SSS(SSS)(SSS)\$ can be proven to be non-halting, as shown in the paper linked above. ## Challenge Solve the halting problem for S combinatory logic. In this system, a term is simply a binary tree where each leaf represents S and each internal node represents application. You may take the input using any suitable structure that can directly represent the term, such as * a binary tree data type, * a nested array, * or a string representation using parentheses (e.g. `S(SS)(SS)(SS)` or `(((S(SS))(SS))(SS))`) or in prefix notation (e.g. `@@@S@SS@SS@SS`). For output, you can choose to 1. output truthy/falsy using your language's convention (swapping is allowed), or 2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~264~~ ~~260~~ ~~257~~ 235 bytes ``` ⊞υθFυF⊖LιFι⊞υλF⮌υF⊖Lι⊞ι⍘§⁺§⪪”}∨M.⁶C¬²2´#±³¹⊗I↧β.|eBTXmê�…⊟→⁼‹R$➙≧→↧ÀZLq);p↶⁷b⬤Jⅈ⁺7ς⧴Wn7bZpïX|.➙K!μ…⁼@|v‹℅↨Sθ?mY,KV}⟧⎇Φ/◨7⁹¶↧πºwT~B0⁸!✳[➙↘↨cjf^{Mg‽bQⅉ→↥Za?↶⁶⊖J↘D⁻D⟲σ7r⬤?φ'⟦6f▷M↖¡[i⌊⊟\2ν|¶x2;¹±&~⁴K∨ρ‽↨⌕HMν(T‖β→⁵ⅈÞ↑«…i⊟D»”0⊟⊟ι×Cφ⊟⊟ιφ›³⁸⊟θ ``` [Try it online!](https://tio.run/##lZRbT4MwFIDf9ysankqCCTovmD1RTYyJD8T5ZnxgrBso17bQcf48dihsbgW3k9DS7@vp5Tw0CH0WZH7cNF7JQ1xaqDBnk1XGEC5N1PaPNGA0oamgS/xC07UIcWSavzIyUZcYd4mvtKKMU7XAPyu0mZGFiM/pXLAoXWNXPKdLusFeXPJ@MM/jSGDjqxSJrCBy4gRkKSogTnyXAwAhQDgD4gKp7fV2/Df4svvTWtrba2hjTwL3R3ODUbvqbaixi95eujXsByEuc9TmbY59dWTrPXujOfP9iTcaP9X59z21zufXaj1qw96O12oKh@WAfFerz01VSAk55xykCkJYFgGBmnQJ9u1hNdXm8fC5kmGVnsnzAV4McDbAueKL41tIoaWlbg1ZaanU0o2OQq2loKWuHRJN2IaFDNswLeRlOd5@2zfFQm9RQjk2HpRemUdWodnEU0@NwE@M@oIyPHV@JhVqwqxp3tuwPyykml17iLTso7mo4m8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a nested array where `S` is represented by `[0]` so e.g. `S(SS)` is represented by `[[[0], [[0], [0]]]]` (note that an extra set of `[]`s is required to input an array to Charcoal since it accepts an array of arguments). Explanation: Based on the look-up table on p. 16 of [http://www.cs.ru.nl/~henk/BEKW.pdf](http://www.cs.ru.nl/%7Ehenk/BEKW.pdf) but with the values translated to make the resulting table more compressible. ``` ⊞υθFυF⊖LιFι⊞υλ ``` Perform a breadth-first traversal to collect all of the nodes. ``` F⮌υF⊖Lι ``` Loop through the non-leaf nodes in reverse order. This effectively produces a depth-first traversal. ``` ⊞ι⍘§⁺§⪪”...”0⊟⊟ι×Cφ⊟⊟ιφ ``` Turn the node into a leaf by replacing its children with the value from the compressed lookup table. ``` ›³⁸⊟θ ``` If the value is still less than `38` then the expression halts. The following rearrangement of the table values is used as this places as many `38`s at the bottom of each column as possible. These are then discarded from the compressed string and reconstructed afterwards. ``` Rearranged Original 0 0 20 1 19 2 3 3 4 4 16 5 17 6 7 7 1 8 18 9 2 10 9 11 5 12 10 13 12 14 8 15 13 16 14 17 15 18 21 19 6 20 11 21 24 22 23 23 25 24 28 25 27 26 22 27 26 28 35 29 37 30 32 31 30 32 33 33 36 34 34 35 29 36 31 37 38 ∞ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 248 bytes ``` Œœżs2Œṙ$€}¥/F^Ị$;0xȷ¤s36 “ƙŀṂƒḂʂŻ⁷Ȧ¿ẏƑ<ọṭẹọ\Ṿ!µɗ⁻ȥƭĊƊġȯ;ŻxḂøCFO)1ɲŒṅ€+ṪʂU-Ɲ¿Ụ£þ^¶ ẹZ361PHc&ẓḟẉẹ⁴Ƒ@G⁶W6ṭ⁽A2K%Ṿ{ẉȯaỊ;ṆẊ:ḄtJ&ß>r³ɲȮ=Ŀ⁼ıɗt¦ÄɦñṙÇ⁹]ḷṡ⁸\]*<f6<U⁷ƲṬðẸG¬db⁾ƭɠ⁹S®w|XƈẎḤ⁴Ȯ⁺2BæƤḋ§Ḷọapæ4%ỊḞḟ¬v⁴ṇW^ŀ$ƈİƥX÷Ð{ṛƈ⁼T4\®ZṆ’b39ṣ0µṪ’s2;"Ç;€0 ,߀ŒḊ’$¿œị¢ʋ/ ``` [Try it online!](https://tio.run/##bVFbaxNBFH7Pr4iSFtSW5lICurF4gVb0QUFLa5sNtF4epA9iilaqsLtUExO8NHmoQWusTSLIJm2jTWZ2awIz2WE3/@LMH1lP0NKiDjOcy5z5zne@eXBvaemp7zsFp@gcpKNOAWgpJA3zOauOTabAzoWU8IrbZpV0LB6Q2kdRcjSghigAMfqGY0u97dZYF6y3Yj0B9mugdbAoOkmgnRNs39uQuu1WRb2XE7nelrujOPYKvuXk8uT1UxGvOej4AhueAfqtb0yPik1Esytsm3dSrBVEsLlYPHLjyp1hsIpAymC9wpzUf4j1C1NSb83EsaXUf16MXhvClqt47@4sIHEF6EuwcueArC1fHebliUfsu9d0G@d7Xakf9Pa8jWVW42teje/hzDwjdaoCaQPdkjpJqqcT9@OJaRxPNIGafBcsMsXMu4tS74i69xmrb7LGk2ezIgvWGyAVZOQ2pG5FL/GaqADJs69AWijEwkNeGx9CQkA@IX9mPsZSoJmZlKOFRLa3K6qzvM3frQL9ILJI7dZ4kjXmkL3USouxs0C3w2wf1cEwHVVO8oyCcoUDI7yMFuUjObwJsa5TBDvPvvTzY/5A1PcKfldwdCIotU2FZwI4oWHe9v35wHxkJDg4EfXI4vlv/t@c@qfy9z701GPuoADXEXLwWPB3hFiHgGpA/QU "Jelly – Try It Online") A full program that takes a single argument consisting of a list of S terms. S is represented by 1, and the parentheses are represented using nested lists. For example, \$S(SS)(SS)(S(SS)(SS))\$ becomes `[1, [1, 1], [1, 1], [1, [1, 1], [1, 1]]]`. Returns 0 for inputs that do not halt and a positive integer (which is regarded as truthy by Jelly) for ones that halt. This uses a rearranged version of [the table](http://www.cs.ru.nl/%7Ehenk/BEKW.pdf) found by @Neil for [his answer](https://codegolf.stackexchange.com/a/229036/42248). Most of the work and the bytes were spent on optimally compressing this table from a 38 x 38 table of numbers from 1 to 38 down to 231 bytes. The code that actually solves the problem is a mere 13 bytes (not counting the newline that separates the two). ## Explanation ### Helper link 1 Expand the run-length encoded segments and append lots of zeros before splitting into 36-length rows. Takes a single argument that alternates between integers to be used as is and run-length encoded runs of integers. ``` Œœ | Split into lists of the odd-indexed and even-indexed members of the original argument ¥/ | Reduce using the following: ż | - Zip with the following: €} | - For each member of the right-hand argument (i.e. the even-indexed members of the original list): s2 | - Split into twos Œṙ | - Run-length decode F | Flatten ^Ị$ | Xor with whether the numbers are <=1 (effectively turns 1s to 0s) ;0xȷ¤ | Append 1000 zeros s36 | Split into lists of length 36 ;€0 | Append 0 to each ``` ### Helper link 2 Niladic link that generates the look-up table to reduce a pair of S terms ``` “ƙ…Ṇ’ | Large integer b39 | Convert to base 39 ṣ0 | Split at zeros µ | Start a new monadic chain Ṫ | Tail (which holds the first two cells for each row) ’ | Reduce by 1 s2 | Split into twos ;"Ç | Concatenate zipped to the result of calling helper link 2 on the other members of the list generated in the first part of this link ``` ### Main link Takes an S expression as its argument and returns 0 for non-halting and a positive integer for halting. ``` ʋ/ | Reduce using the following: , | - Pair ŒḊ’$¿ | - While depth >1: ߀ | - Recursively call the current link for each member of the pair œị¢ | - Multidimensional index into the look-up table generated by helper link 2 ``` ]
[Question] [ Implement a function \$f\$ (as a function or complete program), such that \$ \displaystyle\lim\_{n\rightarrow \infty} f(n) \$ converges to a number which is *not* a [computable number](https://en.wikipedia.org/wiki/Computable_number). Answers will be scored in bytes with fewer bytes being better. # IO formats Your answer may be in any of the following formats * A program or function that takes \$n\$ as input and outputs \$f(n)\$. * A program or function that takes \$n\$ as input and outputs all \$f(m)\$ where \$m \leq n\$. * A program or function that outputs successive members of the sequence indefinitely. Numeric output can be given as any of the following * An arbitrary precision rational type. * A pair of arbitrary precision integers representing a numerator and denominator. e.g. \$(2334, 888)\$ * A string representing a rational expressed as a fraction. e.g. `2334/888` * A string representing a rational expressed as a decimal expansion. e.g. `3.141592` Use of fixed precision floating point numbers is unfortunately not accepted. They end up being messy when dealing with limits, I hope the options permitted allow the majority of languages to compete in this challenge relatively unencumbered. Neither of the fractional outputs are required to be in reduced form. # Examples Here are some numbers which are not computable, but are [computable in the limit](https://en.wikipedia.org/wiki/Computation_in_the_limit). That is any of the following numbers are potential limits for valid solutions to the challenge. This list is obviously not exhaustive. * The real whose binary expansion encodes the halting problem. * The real whose binary expansion encodes the busy beaver numbers. * The real whose binary expansion encodes the truth set of first order logic. * [Chaitin's constant](https://en.wikipedia.org/wiki/Chaitin%27s_constant) ### Example algorithm The following is an example algorithm which solves the problem by converging to the first example. Take a positive integer \$n\$ as input. Take the first \$n\$ Turing machines and run each of them for \$n\$ steps. Output \$ \displaystyle\sum\_{m=0}^n \begin{cases}2^{-m}& \text{if machine }m\text{ halted before }n\text{ steps}\\0 & \text{otherwise}\end{cases} \$ That is to say we start at zero and add \$1/2^m\$ for each machine \$m\$ that halts in our simulation. Now since computing a Turing machine for \$n\$ steps is computable, and adding rational numbers certainly is computable, this algorithm is as a whole computable. However if we take the limit, we get a string that exactly encodes the solutions halting problem. The limit is: \$ \displaystyle\sum\_{m=0}^\infty \begin{cases}2^{-m}& \text{if machine }m\text{ halts}\\0 & \text{otherwise}\end{cases} \$ I think it is intuitive that this sort of thing is not something that can be computed. But more concretely if we were able to compute this number then we could use it to solve the halting problem, which is not possible. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ 24 bytes ``` LεÅγιøIãʒηεøJË}à}gĀ}'.šJ ``` [Try it online!](https://tio.run/##ATIAzf9vc2FiaWX//0zOtcOFzrPOucO4ScOjypLOt861w7hKw4t9w6B9Z8SAfScuxaFK//8zMw "05AB1E – Try It Online") -1 thanks to @ovs f(n) is a decimal number such that it's xth digit is 1 iff x<=n and when you run length encode x and convert it to matching pairs, it has a solution to [PCP](https://en.wikipedia.org/wiki/Post_correspondence_problem) with a length of at most n pairs. outputs as `.digits after the dot`. In case the 0 is needed, it's +1 to replace `'.` with `„0.` Code explaination: ``` L all numbers from 1 to N ε map each to Åγ run length encode ι uninterleave to two lists ø tranpose Iã cartesian power N, all choices of N such pairs ʒ only keep those such that η its prefixes ε map each to ø itself transposed J joined Ë both elements are equal } à maximum - if any of those are 1 } gĀ the length of the filtered list isn't 0 } '.š prepend . J join, and implicitly print ``` We can show a reduction from PCP with two symbols (which is known to be undecidable): given an instance of PCP with two symbols, 1 and 2 (for example [2,1], [11,2], [2212,111]), unflatten the pairs (which would give [2,1,11,2,2212,111] in the example) and run length decode with alternating 1, 0. That number would be x. The solution to the PCP instance is 1 iff the xth digit of the limit of this function is 1. [Answer] # [Python 2](https://docs.python.org/2/), ~~189~~ ~~188~~ 186 bytes -2 thanks to @Wheat Wizard ``` from itertools import* j=input() s='.' for x in range(j):d=`x`.split('0');s+='X10'[min(len(set(map(''.join,zip(*l))))for l in product(*[[d[i:i+2]for i in range(0,len(d),2)]]*j))] print s ``` [Try it online!](https://tio.run/##Rc1LCoMwFIXhuavILDcqEh1aso9CCChV2yt5kVzBdvNpHfVMf/hOfNMr@KGULQXHkNZEIdjM0MWQqK52hT4eBKLKine82kJiJ0PP0uyfK@xiXNR0Tl2OFgm45OKWG8XvveTaoQe7esgrgZsjcN7tAX37wQi1Fb9dmr20mMJyPAhqrReNIzaDuRr@n2R7UYtoB2FMvQthqpjQE8ul9FJ@AQ "Python 2 – Try It Online") A port of my 05AB1E answer to python, using a 0 seperator instead of run length encoding. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~34~~ 32 bytes ``` ƛ0€y"ÞT:£⁰(¥J)ṖƛKƛÞTƛṅ;≈;a;a;\.p ``` -2 thanks to @Aaron Miller [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%C6%9B0%E2%82%ACy%22%C3%9ET%3A%C2%A3%E2%81%B0%28%C2%A5J%29%E1%B9%96%C6%9BK%C6%9B%C3%9ET%C6%9B%E1%B9%85%3B%E2%89%88%3Ba%3Ba%3B%5C.p&inputs=9&header=&footer=) This is a port of my 05AB1E answer, with seperating by 0 instead of run length decoding required, and a different behavior when the length of it isn't even. Also, instead of up to N pieces, it's up to N uses of each piece, but all of that shouldn't matter to the limit's uncomputablity. This is my first time golfing in vyxal, so any improvements would be helpful. ``` ƛ map each in range to 0€ split by 0 y"ÞT uninterleave and transpose :£ save in register ⁰(¥J) merge with itself input times Ṗ take all permutations ƛ and map each to K its prefixes ƛ map each to ÞT it transpose ƛṅ; join each ≈ all are equal? ; a are any of those 1? ; a are any of those 1? ; \.p prepend . implicitly output as a string ``` ]
[Question] [ Inspired by *Flow Fit: Sudoku*, a brand-new mobile puzzle game (as of Nov 2019). ## Background A [**Latin square**](https://en.wikipedia.org/wiki/Latin_square) is a square grid of side length \$ n \$ filled with \$ n \$ different symbols, where each row and column contains each symbol exactly once. Let's define a **row** (resp. a **column**) as a **maximally consecutive group of cells** in horizontal (resp. vertical) direction. For example, the following board (`O` is a cell, `-` is a hole) has 8 rows and 8 columns in total: ``` The board | Rows | Columns O O O O O O | A A A A A A | A B C E G H O O O O O O | B B B B B B | A B C E G H O O - O O O | C C - D D D | A B - E G H O O O - O O | E E E - F F | A B D - G H O O O O O O | G G G G G G | A B D F G H O O O O O O | H H H H H H | A B D F G H ``` Then, place the numbers \$ 1, \cdots, k \$ exactly once on each row and column, where \$ k \$ is the length of that row or column. For the board above, here is one solution: ``` 3 4 1 2 5 6 4 3 2 1 6 5 1 2 - 3 1 2 2 1 3 - 2 1 5 6 1 2 3 4 6 5 2 1 4 3 ``` A board is **Latin-style** if such a placement is possible. Note that a row/column of size 1 is still a row/column, and therefore it can only have a single 1. ## Challenge Given a grid, **determine if it is Latin-style**, i.e. it is possible to place numbers on the grid so that each row/column of length \$ k \$ contains each of the numbers \$ 1, \cdots, k \$ exactly once. ### Example Latin-style boards ``` O O O O O - O O O O - - O O O - - - O O - - - - O ``` ``` - O O O - O O O O O O O O O O O O O O O - O O O - ``` ``` - - O O O - O O O O O O O O O O O O O - O O O - - ``` ``` O O - - O O O O O O O O - O O O O - - O O O O - O O O O O O O O - - O O ``` ``` O O O - O O O O O O O O O O O O O O O O O O O O O O O O O O O - - O O O O O O O O O O O O O O O O O O O O O O O O O O O - O O O ``` ``` O O O - O O O - O O O - O O O ``` ``` - - O - - - O O O - O O - O O - O O O O O O O - O ``` ### Example non-Latin-style boards ``` - O - O O O - O - ``` ``` O O O ``` ``` O O - - - O O - - - O O - - - O O O O O O O O O O ``` ``` O O O - - O O O - - O O O O O - - O O O - - O O O ``` ``` - - - O O - - - - O O O - - O O O O O O - O O O O O O O - O O O O O O - - O O O - - - - O O - - - ``` ``` O O - - - - O O - O O O O O - O O O ``` ``` O O - - - O O - - - O O O - - - - O O O - - O O O ``` ## Input and output You can take the grid input in any reasonable way. The grid's bounding box can be non-square, and the grid may contain multiple connected components. You can give the output in one of two ways: * Truthy/falsy values following the language's convention + Swapping truthy/falsy is ~~not allowed~~ also allowed. * One consistent value for true, another consistent value for false ## Scoring and winning criterion The standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` ,ZµŒgaS$€F)Zṣ€0Ṣ<JƊ€€)FẸ ``` [Try it online!](https://tio.run/##y0rNyan8/18n6tDWo5PSE4NVHjWtcdOMerhzMZBh8HDnIhuvY11AJhBpuj3cteN/pPWjhjmHtino2ik8aphrfbid6@GO@Y8atz3cvcUWKOAPFDg6GaS9cd@hbYe2HW4H6syCcv7/91eAQi5dJJYuEksXiQVkc8EV6nIhNGNjIdShmIhbC8xAXZAWKANVKbIBQEXIbGQ1yHrhZmLYSxQf2RLS9MN8jHAAF1yYC0ka4lBdJJt0kRSiuxseA1AfQ9lcSHaBIwonCz3wkcIcnYWZFpCcrAtXDJdA1YoeKyhxh2Igiim6qNGvixwayEGo4A8A "Jelly – Try It Online") A monadic link taking as its argument the grid as a matrix with 1 representing squares needing a number and 0 representing the spacers. Returns 0 if the grid is Latin and 1 if not. ## Explanation ``` Main link, takes a matrix of 1s and 0s as its argument, z , | Pair with: Z | - z transposed µ | Start a new monadic chain ) | For each matrix (z and transpose(z)): ) | - For each row: Œg | - Group runs of equal elements $€ | - For each group: a | - And with: S | - Sum of group F | - Flatten Z | - Transpose ṣ€0 | - Split each at zeros Ɗ€€ | - For each group: Ṣ< | - Check whether sorted group is less than: J | - Sequence along group F | Finally, flatten Ẹ | And check if any group returned true ``` # Alternative in case true=true/false=false required: ## [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` ,ZµŒgaS$€F)Zṣ€0Ṣ_JƊ€€)AƑ ``` [Try it online!](https://tio.run/##y0rNyan8/18n6tDWo5PSE4NVHjWtcdOMerhzMZBh8HDnonivY11AJhBpOh6b@D/S@lHDnEPbFHTtFB41zLU@3M71cMf8R43bHu7eYgsU8AcKHJ0M0t2479C2Q9sOtwM1ZkE5///7K0Ahly4SSxeJpYvEArK54Ap1uRCasbEQ6lBMxK0FZqAuSAuUgaoU2QCgImQ2shpkvXAzMewlio9sCWn6YT5GOIALLsyFJA1xqC6STbpICtHdDY8BqI@hbC4ku8ARhZOFHvhIYY7OwkwLSE7WhSuGS6BqRY8VlLhDMRDFFF3U6NdFDg3kIFTwBwA "Jelly – Try It Online") [Answer] # [Prolog (SWI)](http://www.swi-prolog.org) + [CLPFD](https://www.swi-prolog.org/pldoc/man?section=clpfd), 192 bytes ``` A/B:-transpose(A,B). []*[]*_*1*_. [0|T]*[0|B]*_*1*_:-T*B*L*L*[]. [1|T]*[A|B]*L*C*Z:-all_distinct([A|Z]),A#>0,A#<L,R#=C-1,T*B*L*R*[A|Z]. []-[]. [X|T]-[Y|B]:-X*Y*L*L*[],T-B. +A:-A-B,A/T,B/U,T-U. ``` [Try it online!](https://tio.run/##nVNdb4IwFH33Vzh9obXFyyvbTMBXnwwmKCGEad1IKpCCMUv876zyJQWWLAuEnNt7z7lfJRUJTz5pdosKk14zFlyS05UzjUcfIhTf2pGn5xNCemEtbZPmIoyzNMmYZhEb6RPPx/INsIEDacDdkTbc7frIpA628UY@ni/dRum2Hu4NXuODSUPOg1OU5VF8zDXpOfiIWPMVyM/bhmzn72tqkEpji0v/IyUt1VypRr29VDOpi/d1GuJQW58sLJNa1CbW0iH2cicPd3rxxXjKhOYik2qpiOJcQnITUc602ZSupjNEFi6pPLm4MvRa4XPIM4YQibleXMKUy3q1Sot4nmeQ@vGJBwoGBYOCpeVLo2WANLpKv@FnfMWG0dxj7GcGqNk17nNUtZKnWmpkV6VRNchoNX8@UXP@R6eZi1JRW20T242qegAlN/QYw666e2xnU0c@p2wo84bO1MbwcIvdLtQ99m8HjOCmO@iwWm9fZbjj3n3oqff0YHC7QJ2iuoVHdfKXf9F/AA "Prolog (SWI) – Try It Online") The main predicate is `+/1`. ### Verbose ``` t(A,B):-transpose(A,B). h([],[],_,1,_). h([0|T],[0|B],_,1,_):-h(T,B,L,L,[]). h([1|T],[A|B],L,C,Z):-all_distinct([A|Z]),A#>0,A#<L,R#=C-1,h(T,B,L,R,[A|Z]). q([],[]). q([X|T],[Y|B]):-h(X,Y,L,L,[]),q(T,B). g(A):-q(A,B),t(A,T),t(B,U),q(T,U). ``` [Try it online!](https://tio.run/##bU/LasMwELznKwq5SDAy8tW0BTtXn4IDSYwwbuw4BjV@yKEU8u/uSqoPpmWFNLszmt3tx053jTBf7RyJh6mLz6566Jrp9mMsx2920f214jyYJxYj4ZGYxvJu@s7ULg82N5Yr0CkQovC5fGZUks9kqUbixjIkSCly5UWhE8VWlGKHM4lKrYuqNVN7v0yMqLPiiLfvkq7XFPvt206EWJz28IpgM/gJePBC6OhsT2Truh5xWrpisD9J37CYuMHND7tWZp8EBy850LJzw/I8xG/YZVZYrrBcYcqUcl0WB6oR@xf/7@YxOfwA "Prolog (SWI) – Try It Online") `g/1` takes the grid as a list of lists, each element being a 1 for a cell or a 0 for a hole. `q/2` takes a grid as the first argument and unifies the second argument with a solution of the grid. `h(A,B,L,L,[])` takes a row of this grid as A, and unifies a solution for the row to B, and `q/2` recursively calls `h/5` on each of its rows. `h(A,B,L,C,Z)` has row A of the grid, a solution B, L is the length of the current length of 1s plus one so that the cells of B can be constrained to the exclusive range (1, L), C is the count of the remaining length so that L is unified to the length, and Z is the solution for the current contiguous sequence of cells so that `all_distinct/2` can be called. The end cases are stated as conditions so that these constraints are fulfilled. Because this is Prolog, converting the main predicate to take two arguments, like `A+B` or `g(A,B)`, Prolog will unify the solutions with the variable B, thus also allowing you to see all available solutions. It can also generate valid grids, but running this makes Prolog list all grids with empty rows. [Answer] # [R](https://www.r-project.org/), 169 bytes ``` function(x)any(unlist(lapply(1:2,function(m)apply(apply(x,m,function(y,r=rle(y))rep(r$l*r$v,r$l)),1,function(a)tapply(a,cumsum(!a),function(d)sort(e<-d[!!d])<seq(e)))))) ``` [Try it online!](https://tio.run/##lVPNbsMgDL7zFC7qATY4dMcp2SvkAdYdopRISORnkGyNpj17RlsKTrpKWyKFj/j7bGNjO9eZnOuxrQbdtezIy3ZiY2u0G5gp@95MbPf8JCKh4Zefl@9RNMk0CZtbo9jEuVU9s1vzYLcfwq@ci13ilXwIPkQ1Nm5s2KbkyXzgrrMDU5k8vG42hzeeOfXOFD8/sy0/IZMQUnODdb3Rnm0SpgWEl0iEJEISIY9JJEqSxL@hxFt4vC@5OpQnSQBLKnbgSRhjDtZGnzdx/7THQf6nv544JUDib4LMl0QliiQRcZ137EA4ccAE9SvVTt5F6xagyq/R7Y1AictIjoaldN2bRQcXDhde1gfBNcGFhIIKum/3LfVzQ0@LQPP56FZX/ygoeArNcy8rvIbUnQWmQbfgp4XDFwGoyiGMrPaj2JduUKLqjB8jp3Lq5UBBvgAVUDN92nnkVJ@fw5Pv@Qc "R – Try It Online") An R translation of [my Jelly answer](https://codegolf.stackexchange.com/a/196658/42248). I’m not sure it’s much easier to follow! Takes a matrix of 0s and 1s and returns a logical scalar (`FALSE` if Latin, `TRUE` if not). Note because of the way base R tends to collapse matrices to vectors, the input has to have at least 2 rows and columns, but this can be done by padding input with an extra row or column of `FALSE`s. If this is unacceptable, I can work around it at the cost of extra bytes to handle the edge case. ]
[Question] [ This challenge is a prize for [ais523](https://codegolf.stackexchange.com/users/62131/ais523) for [winning](https://codegolf.meta.stackexchange.com/questions/11186/cast-your-vote-for-best-of-ppcg-2016/11191#comment37192_11191) the "[Rookie of the Year](https://codegolf.meta.stackexchange.com/a/11191/26997)" category in "[Best of PPCG 2016](https://codegolf.meta.stackexchange.com/q/11186/26997)". Congratulations! --- [BackFlip](https://esolangs.org/wiki/BackFlip) is an esoteric programming language made by user [ais523](https://codegolf.stackexchange.com/users/62131/ais523), who has created [well over 30 other interesting esolangs](https://esolangs.org/wiki/User:Ais523). BackFlip is a 2D language like [Befunge](https://esolangs.org/wiki/Befunge) or [><>](https://esolangs.org/wiki/Fish) where the instruction pointer traverses a grid of text (the program), moving up, down, left, and right, changing direction depending on the character it's on. Critically, the grid in a BackFlip program changes as it is being traversed, a bit like [Langton's Ant](https://en.wikipedia.org/wiki/Langton%27s_ant). For this challenge you may assume that a BackFlip program is always a rectangular grid of text (all lines the same length), 1×1 in size at minimum, only containing the characters `./\<>^V`. (`.` is used for visibility rather than space.) Semantically the BackFlip we'll use here is identical to the [original spec](https://esolangs.org/wiki/BackFlip#Syntax). The instruction pointer (IP) in BackFlip always starts just left of the top-left corner of the program, heading right. There are three types of commands it can encounter: 1. `.` is a no-op. The IP continues on in the direction it was going. The no-op stays a no-op. 2. `/` and `\` are mirrors. They reflect the IP in the direction indicated by their angle, then **they change into the other type of mirror**. * For example, if the IP heads left into a `\`, it starts moving upward instead of left and the `\` becomes a `/`. 3. `<`, `>`, `^`, and `V` are arrows. They redirect the IP to the direction they point in, then **they change into an arrow that points in the direction the IP came from (opposite the direction the IP was moving)**. * For example, if the IP heads downward into `>`, it starts moving right instead of downwards and the `>` becomes a `^` because that is the direction the IP came from. A BackFlip program terminates when the IP moves out of bounds, i.e. goes off the grid. It turns out *all* BackFlip programs eventually end because infinite loops are impossible. (You may assume this is true.) Your goal in this challenge is to write a program or function that takes in a BackFlip program and outputs the number of moves the instruction pointer takes before the program terminates. That is, **how many steps does the IP take in the course of running a program?** This includes the initial step onto the grid and the final step off of it. For example, the instruction pointer takes 5 steps in the trivial grid `....`: ``` .... <- empty 4×1 grid 012345 <- step number of the IP ``` So the output to `....` is `5`. In the more complex 4×2 grid ``` \... \.>< ``` the IP exits the grid on its 9th step, so the output is `9`: ``` step grid IP position (@) 0 \... @.... \.>< .... 1 \... @... \.>< .... 2 /... .... \.>< @... 3 /... .... /.>< .@.. 4 /... .... /.>< ..@. 5 /... .... /.<< ...@ 6 /... .... /.<< ..@. 7 /... .... /.>< .@.. 8 /... .... /.>< @... 9 /... .... \.>< .... @ ``` **The shortest code in bytes wins.** You may take input as an array of lines or matrix of characters instead of a multiline string if desired, but you must use the characters `./\<>^V` (not integer opcodes). You may use space instead of `.` if preferred. It's fine if characters like `\` need to be escaped in input. Output is always an integer more than one. # Test Cases ``` .... 5 \... \.>< 9 . 2 .. 3 . . 2 \ 2 ^ 2 .^. 3 <. 2 \\ \/ 7 >V ^< 6 >\ >/ 6 \>< 2 \>< \>< 7 \>< \>< \>< 12 \.V. \.\< 5 \.V. \./< 9 V./\ V./\ >./< ..\/ 14 \V.. .^.. \/>< .V.. .^.. 20 \.V.V. \./.\< .>\<.. ..^.^. 31 \.V.V.V. \./>/.\< .>\>\<.. ..^.^.^. 69 \.V.V.V.V. \./>/>/.\< .>\>\>\<.. ..^.^.^.^. 145 \.V.V.V.V.V.V.V.V.V.V. \./>/>/>/>/>/>/>/>/.\< .>\>\>\>\>\>\>\>\>\<.. ..^.^.^.^.^.^.^.^.^.^. 9721 ``` [Answer] ## JavaScript (ES6), 158 bytes ``` f=(a,x=0,y=0,d=3)=>a[x]&&(c=a[x][y])?(a[x][y]=c=='.'?c:c=='/'?(d^=3,'\\'):c=='\\'?(d^=1,'/'):'v>^<'[d][d='^<v>'.search(c),0],f(a,d<3?x+d-1:x,d?y+d-2:y,d)+1):1 ``` Developed independently from @tsh's answer although strikingly similar. The mapping of directions `^<v>` to integers 0-3 is governed by the fact that `.search('^')` returns 0 since `^` is a regexp metacharacter. [Answer] # [Haskell](https://www.haskell.org/), ~~333~~ 325 bytes EDIT: * -8 bytes: Made `f` pointfree and merged into `b`. `b` takes a list of `String`s and returns an `Integer`. ``` data C a=C{c::a->(a,C a)} b g=[0,0]#([0,1],map(maybe(C$m 1)C.(`lookup`zip"./^>V<"[n,m(-1),a[-1,0],a[0,1],a[1,0],a[0,-1]]))<$>g) [y,x]#(d,g)|g&y||g!!0&x=1|n@([f,e],_)<-(($d).c)?x?y$g=1+[y+f,x+e]#n l&i=i<0||i>=length l (f?i)l|(p,a:r)<-splitAt i l=(p++).(:r)<$>f a n d=(d,C n) a v d=(v,C$a$(0-)<$>d) m s[d,e]=([s*e,s*d],C$m(-s)) ``` [Try it online!](https://tio.run/nexus/haskell#bU/LbsIwELz7KwxYyEsck1xRHFrlH7g4oTjkgVXHRCSlSZt@OzU99IDQHEazmtmdbZS2Qtu@vKhjT7rT@ZPn3GhbdrdC9QonWInk@7jZKD@mijkJPyjHtZABC7IFdRRmrFEtbdSYlzQhDQ4h4fRgzuf3j/bwpds5X@/jXTSXljXUD4Ep6Ycu7fgvreS/8sMsA4hIXAOSIxvchYLVMNXLcZrq2SxYDiKc7AuVFSsz9gaRTykpgB9hO2xHUovQk6NXscErs4VFZqmFjoJp0rEwpa37EzaIVlsNZqItU5uL29C1RvevPdbYCNp6HnB6n5O4wgpZXAjXIcEWkMLXu7qyhChCA//uKQA1uJOFqyOo7FYl61ZF5hzu1Q7gdkv57glQytfxA3gaIR6nj4g4R5zvnwD9Ag "Haskell – TIO Nexus") # How it works * `C a` is a data type used because Haskell won't allow a type to be recursive without declaring it explicitly. `C` is also a wrapping constructor and `c` is its corresponding unwrapping function. It is only used with `a=[Int]`. + The type `C [Int]` represents a cell command, as a function that takes a direction (`[Int]`) argument, and returns a pair of a new direction, and a new `C [Int]` value. * `b` is the main function. It converts each character into a `C` value, then it calls `#`. + `g` is the grid as a list of strings. + Since `\` needs to be escaped and so is the longest character to mention, its result is instead used as the default value for the list lookup. * `#` runs the main simulation, checking bounds with `&` and generating new grids with `?`. `[y,x]` is the current position, `d` the current direction, and `g` the current grid. `[f,e]` is the next direction, and `n` is a pair of it and the next grid. * `l&i` checks if the index `i` is out of bounds for the list `l`. (It returns `True` for out of bounds, since that avoids a dummy guard condition in `#`.) * When `f(l!!i)==(d,x)`, `(f?i)l==(d,m)` where `m` is the list `l` with the `i`th element replaced with `x`. + Technically `(?i)` is a more general lens, focusing on the i'th element of a list, in this case used with the `(,) [Int]` functor instance. * `n` is the function representing a dot. * `a v` is a function representing an arrow in direction `v`. * `m s` is a function representing a mirror; `s==1` for `\\` and `s==-1` for `/`. [Answer] # JavaScript, 172 bytes ``` f=(a,d=3,x=0,y=0,n=1)=>(p=a[y]||[],q=p[x])?(p[x]=~(t='^<V>'.indexOf(q))?'^<V>'[d^2]:q=='/'?(t=3-d,'\\'):q=='\\'?(t=d^1,'/'):(t=d,q),f(a,t,x+(t&1&&t-2),y+(~t&1&&t-1),n+1)):n ``` But i cannot test last testcase since i got stack overflow on my machine. (should work if there is a machine with larger ram) We use a number for direction: * 0: ^ * 1: < * 2: V * 3: > Let `d` be the direction number... * if we meet a '/', we need d = 3 - d; * if we meet a '\' we need d = d ^ 1; * if we meet a '^<V>' we need d = '^<V>'.indexOf(note) Let `(x, y)` be current position, the next position is: `x+(t&1&&t-2)`, `y+(~t&1&&t-1)` **Note:** The function takes one paramter with the following format: ``` [ [ '\\', '.', 'V', '.', 'V', '.', 'V', '.', 'V', '.' ], [ '\\', '.', '/', '>', '/', '>', '/', '.', '\\', '<' ], [ '.', '>', '\\', '>', '\\', '>', '\\', '<', '.', '.' ], [ '.', '.', '^', '.', '^', '.', '^', '.', '^', '.' ] ] ``` **Test it here** ``` f=(a,d=3,x=0,y=0,n=1)=>(p=a[y]||[],q=p[x])?(p[x]=~(t='^<V>'.indexOf(q))?'^<V>'[d^2]:q=='/'?(t=3-d,'\\'):q=='\\'?(t=d^1,'/'):(t=d,q),f(a,t,x+(t&1&&t-2),y+(~t&1&&t-1),n+1)):n ;k=x=>x.split('\n').map(t=>t.split('')); ``` ``` <textarea id=v>\.V.V.V.V. \./>/>/.\< .>\>\>\<.. ..^.^.^.^.</textarea><br/><button onclick="r.textContent=f(k(v.value))">Solve</button> <p>Result: <output id=r></output></p> ``` [Answer] # C, ~~232~~ 221 bytes ``` d,n,t,m[4]={1,-1};char*w="><^V/\\.",*P;main(o,v)char**v;{for(P=v[1],m[2]=-(m[3]=strchr(P,10)-P+1);P>=v[1]&&P<strchr(v[1],0)&&*P^10;++n)*P=w[((o=d,t=strchr(w,*P)-w)<4)?d=t,o^1:(t<6)?d^=t-2,9-t:6],P+=m[d];printf("%d",n+1);} ``` Takes input in first argument, prints result. Requires that input contains at least 1 newline (so if there's only 1 row, it must end with a newline) Example usage: ``` ./backflip '.... '; ``` Breakdown: ``` d, // Direction n, // Step counter t, m[4]={1,-1}; // Movement offsets char*w="><^V/\\.", // Command lookup *P; // Cursor location main(o,v)char**v;{ for(P=v[1], // Begin at 0,0 m[2]=-(m[3]=strchr(P,10)-P+1); // Find width of grid P>=v[1]&&P<strchr(v[1],0)&&*P^10; // While inside grid: ++n) // Increment step *P=w[ // Update the current cell ((o=d,t=strchr(w,*P)-w) // (store current direction & command) <4)?d=t,o^1: // If <>^V, write backflip & set dir (t<6)?d^=t-2,9-t: // If / or \, write flip & bounce 6], // If ., write unchanged & continue P+=m[d]; // Move printf("%d",n+1); // Print result } ``` [Answer] # [Python 3](https://docs.python.org/3/), 286 bytes [f() takes input in the form of `{(0,0):'/',(0,1):'.'}` so I have also written a function g() for converting an array of lines to that form] ``` def f(r): x=y=0;d='>';s=1 while 1: try:c=r[y,x];m='>^<V'.find(d) except:break if(c=="\\"):d='V<^>'[m];r[y,x]="/" elif(c=="/"):d='^>V<'[m];r[y,x]="\\" elif(c!="."):r[y,x]='<V>^'[m];d=c x+=1if(d=='>')else-1if(d=='<')else 0;y+=1if(d=='V')else-1if(d=='^')else 0;s+=1 return s ``` [Try it online!](https://tio.run/nexus/python3#bZBNboMwEIX3nMJlY6OkhmzB42OwMSCl2KROCY0MVUFVz07H5Kclqt5mxu@bZ3u0aciBDVEaEAdf3wFp3h2xxHbE7buDYa3p0PX24hwfHJWUaDplt8cSBmVLdSwxyQwfDrlZY3rDnB8fYYIk00AlzXrYBeTz1baG7Hzy4Ka0Bqem7VhmJ0QqkVPe2E4zHaFvxtqch/TFmf0btrZhNUBYFGGUYmAuKknVqcwuARDGoZ9pr1h8oSqZixWF43fsCUIe@n8sFhW5rBZWQ43MuIEdUhr84yPT9ub51otLT5Js@oXyB6i6Q/3G//y6nn4@O9sNrGEHpmjB80V0i2UsY14ILLksZCG4P@W8WkRx41Hw3@hat6C1/sSutb5kreXK@Qc "Python 3 – TIO Nexus") ]
[Question] [ A string whose length is a positive [triangular number](https://en.wikipedia.org/wiki/Triangular_number) (1, 3, 6, 10, 15...) can be arranged into an "equilateral text triangle" by adding some spaces and newlines (and keeping it in the same reading order). For example, the length 10 string `ABCDEFGHIJ` becomes: ``` A B C D E F G H I J ``` Write a program or function that takes in such a string, except it will only contains the characters `0` and `1`. (You may assume the input is valid.) For the resulting "equilateral text triangle", output (print or return) one of four numbers that denotes the type of symmetry exhibited: * Output `2` if the triangle has bilateral symmetry. i.e. it has a line of symmetry from any one corner to the opposite side's midpoint. Examples: ``` 0 1 1 1 0 1 0 0 1 0 1 0 1 1 1 1 0 1 0 1 1 1 ``` * Output `3` if the triangle has rotational symmetry. i.e. it could be rotated 120° with no visual change. Examples: ``` 0 1 0 0 1 1 0 1 0 0 0 0 1 1 0 0 0 0 1 0 1 0 1 1 1 1 1 1 1 0 1 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 0 0 0 0 1 0 0 1 1 1 ``` * Output `6` if the triangle has **both** bilateral and rotational symmetry. i.e. it matches the conditions for outputting both `2` and `3`. Examples: ``` 0 1 0 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 0 0 0 ``` * Output `1` if the triangle has neither bilateral nor rotational symmetry. Examples: ``` 1 1 0 0 0 0 0 0 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 ``` **The shortest code in bytes wins. Tiebreaker is earlier answer.** Aside from an optional trailing newline, the input string may not have space/newline padding or structure - it should be plain `0`'s and `1`'s. If desired you may use any two distinct [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of `0` and `1`. # Test Cases Taken direct from examples. ``` 011 -> 2 101 -> 2 001010 -> 2 1111010111 -> 2 0100110100 -> 3 0011000010 -> 3 101111111010111 -> 3 101001100010000100111 -> 3 0 -> 6 1 -> 6 000 -> 6 100101 -> 6 0000100000 -> 6 110000 -> 1 001101 -> 1 1101111111 -> 1 111111000111111 -> 1 ``` "Rotating" any input by 120° will of course result in the same output. [Answer] ## CJam, ~~37~~ ~~29~~ ~~28~~ 27 bytes *Thanks to Sp3000 for saving 3 bytes.* ``` q{T):T/(\s}h]{z_Wf%_}3*])e= ``` [Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%22%20%22%2F0%3D%3AQ%3B0%3AT%3B%0A%0AQ%7BT)%3AT%2F(%5Cs%7Dh%5D%7Bz_Wf%25_%7D3*%5D)e%3D%0A%0A%5DoNo%7D%2F&input=011%20-%3E%202%0A101%20-%3E%202%0A001010%20-%3E%202%0A1111010111%20-%3E%202%0A0100110100%20-%3E%203%0A0011000010%20-%3E%203%0A101111111010111%20-%3E%203%0A101001100010000100111%20-%3E%203%0A0%20-%3E%206%0A1%20-%3E%206%0A000%20-%3E%206%0A100101%20-%3E%206%0A0000100000%20-%3E%206%0A110000%20-%3E%201%0A001101%20-%3E%201%0A1101111111%20-%3E%201%0A111111000111111%20-%3E%201) This reuses some triangle rotation tricks from [this challenge](https://codegolf.stackexchange.com/a/69473/8478). This also works for the same byte count: ``` q{T):T/(\s}h]3{;z_Wf%_}%)e= ``` ### Explanation First, a quick recap from the triangle post I linked to above. We represent a triangle as a 2D (ragged) list, e.g. ``` [[0 1 1] [0 0] [0]] ``` The symmetry group of the triangle has 6 elements. There are cycles of length 3 by rotating the triangle and cycles of 2 by mirroring it along some axis. Conveniently, the rotations correspond to perform to two different reflections. We will use the following reflections to do this: 1. Transpose the list means reflecting it along the main diagonal, so we'd get: ``` [[0 0 0] [1 0] [1]] ``` 2. Reversing each row represents a reflection which swaps the top two corners. Applying this to the result of the transposition we get: ``` [[0 0 0] [0 1] [1]] ``` Using these two transformations, and keeping the intermediate result, we can generate all six symmetries of the input. A further point of note is the behaviour of transposition on a list like this: ``` [[0] [1 0] [1 0 0] []] ``` Because that's what we'll end up with after splitting up the input. Conveniently, after transposing, CJam flushes all lines to the left, which means this actually gets rid of the extraneous `[]` and brings it into a form that's useful for the above two transformations (all without changing the actual layout of the triangle beyond reflectional symmetry): ``` [[0 1 1] [0 0] [0]] ``` With that out of the way, here's the code: ``` q e# Read input. { e# While the input string isn't empty yet... T):T e# Increment T (initially 0) and store it back in T. / e# Split input into chunks of that size. ( e# Pull off the first chunk. \s e# Swap with remaining chunks and join them back together e# into a single string. }h ] e# The stack now has chunks of increasing length and an empty string e# as I mentioned above. Wrap all of that in an array. { e# Execute this block 3 times... z_ e# Transpose and duplicate. Remember that on the first iteration e# this gets us a triangle of the desired form and on subsequent e# iterations it adds one additional symmetry to the stack. Wf%_ e# Reverse each row and duplicate. }3* e# The stack now has all 6 symmetries as well as a copy of the e# last symmetry. ] e# Wrap all of them in a list. ) e# Pull off the copy of the last symmetry. e= e# Count how often it appears in the list of symmetries. ``` ]
[Question] [ Given an input of an integer *n* and a list of positive integers *m1*, *m2*, ..., output a list of integers *m1'*, *m2'*, ... where *mx'* is defined as the average of *mx-n* through *mx+n*. When calculating these averages, ignore indices that are out of bounds (and adjust what you are dividing the sum by accordingly). *n* will always be ≥ 1 but never half of the length of *m* (rounded down) or more. This means that the minimum length of *m* is 4. The elements in *m* will be positive integers, but the output must be accurate to at least 3 decimal places. The input / output elements that are lists may be either whitespace-/comma-separated strings or arrays/lists/etc. For input, if your solution is a function, you may additionally take a first argument of *n* and additional arguments as *mx* (this applies to command line arguments as well). Here is a visual representation of `n=1`: ``` 1 4 5 7 10 __/ | | | L avg(1,4) = 2.5 | | | \___/ | | L avg(1,4,5) = 3.333 | | \___/ | L avg(4,5,7) = 5.333 | \___/ L avg(5,7,10) = 7.333 \___ L avg(7,10) = 8.5 Final output: 2.5 3.333 5.333 7.333 8.5 ``` Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. Test cases (*these were done manually; please notify me of any errors*): ``` In Out ---------------------------------------------------------------------- n=1, m=12 6 3 9 9 7 6 6 n=1, m=1 4 5 7 10 2.5 3.333 5.333 7.333 8.5 n=1, m=1 3 3 7 4 2 4 2 2 2.333 4.333 4.666 4.333 3.333 2.666 3 n=2, m=1 3 5 9 10 14 15 16 23 3 4.5 5.6 8.2 10.6 12.8 15.6 17 18 n=3, m=1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 n=3, m=1 2 3 4 5 6 7 8 2.5 3 3.5 4 5 5.5 6 6.5 ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~30~~ ~~28~~ ~~26~~ 24 bytes ``` 2*1+:g2X53$X+1Mbgbb3$X+/ ``` Tested on Matlab and on Octave. Uses [current version (9.1.0)](https://github.com/lmendo/MATL/releases/tag/9.1.0) of the language/compiler. Input is: first the number controlling window length, then the array with format `[1 4 5 7 10]`. *EDIT (20 May 2016): [Try it online!](http://matl.tryitonline.net/#code=MioxKzpnMlg1MyRZKzFNYmdiYjMkWSsv&input=MQpbMSA0IDUgNyAxMF0) The code in the link has `X+` replaced by `Y+` to conform to version 18.0.0 of the language.* ### Example ``` >> matl > 2*1+:g2X53$X+1Mbgbb3$X+/ > > 1 > [1 4 5 7 10] 2.5 3.333333333333333 5.333333333333333 7.333333333333333 8.5 >> matl > 2*1+:g2X53$X+1Mbgbb3$X+/ > > 2 > [1 3 5 9 10 14 15 16 23] 3 4.5 5.6 8.199999999999999 10.6 2.8 15.6 17 18 ``` ### Explanation The equivalent Matlab code would be ``` n = 1; %// first input: number controlling window length x = [1 4 5 7 10]; %// second input: array result = conv(x,ones(1,2*n+1),'same')./conv(ones(size(x)),ones(1,2*n+1),'same'); ``` The MATL code makes use of the recently added features of implicit input and automatic function-input clipboard: ``` 2*1+ % get implicit input "n". Multipliy by 2 and add 1 :g % create a vector of 2*n+1 "true" values (will act as "one" values) 2X5 % 'same' string literal 3$X+ % get implicit input "x" (array). Convolution using three inputs 1M % push all three inputs from last function bgbb % convert first input to "true" values. Will act as "one" values 3$X+ % convolution using three inputs / % divide element-wise. Implicitly print ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~18~~ 16 [bytes](https://github.com/abrudz/SBCS) ``` {⍵⌹×⍵}⌺(1+2×⎕)⊢⎕ ``` [Try it online!](https://tio.run/##ZVCxTgMxDJ3JV3grFRBh5@K7G7p25RsqobIU6IpQNyQQ9LohdiYGNsQAI/xJfuR4Se@uSokVx7GfX54zWy5Ozm9mi@uLNjzcz9vb0HyG9dfvC85VWH8f8pHgsnkeh8dXHBHVHgC1Gc3D011o3kern7fQfKhhISVHtWHDVJCnkvg0XRysREri7jKeapSJC2JPrCTOoESZGYeMABzZFBQVMmZ8Np2aqwkf0@Wkf5P2Vg2wkg6wQU8OE@vJWecgJ/ky@cr6XWOmfdeI1ggtOq@qXbylk5RxoJGe5v/AFCeDAm8VbwqqCFhsBUSMoLcCg9sy5Nav/R8b4Nm35QNDo081b2Ndrf8D "APL (Dyalog Unicode) – Try It Online") [@ngn suggested an average trick using `⌹`](https://chat.stackexchange.com/transcript/message/55034296#55034296), and I took it further to shorten it by two bytes, eliminating the need of `↓`. Since the input is positive integers and the Stencil's padding gives only zeros, it suffices to average the nonzero entries. The default trick for average using `⌹` (matrix divide/solve linear equation/least squares fit) is "divide a vector by its all ones version", which solves the least squares of something like this: ``` 1x = 1 1x = 3 1x = 5 ``` where the least square solution is exactly the average. I modified it to ignore the zeros when calculating the average: ``` {⍵⌹×⍵} Input: a vector of positive integers, possibly with zeros to ignore ×⍵ Signum of each number, which gives 1 for positives and 0 for zeros ⍵⌹ Matrix-divide the original vector by the above, which gives the system of equations, e.g. for 0 0 1 3 5: 0x = 0 0x = 0 1x = 1 1x = 3 1x = 5 Then the zero-coefficient equations are ignored in the least squares, which leads to the average of only positive entries. ``` Alternatively, Extended can do the same in 15 bytes, exploiting the fact that the left argument is always zero (as opposed to the "padding size" in regular Dyalog version): # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 15 bytes ``` (⊢⌹<)⌺(1+2×⎕)⊢⎕ ``` [Try it online!](https://tio.run/##ZVCxTsMwEJ3xV9zWRlCLO8eXRKJrV76hUlKW0jIwgBAbEgiabBU7EwMbE4zwJ/6RcHaTVC4@5XR59@75nedXy0l5O1@uLybVzXW1KquydU@Pi3bsnt/c5usscZvvMR7T76trtokHm61ntEd3rm5GC/fy4OqP0f3Pu6s/WSEBg4FCoUJIwUIGeBp@jEQmEPmvQywU0gZMAS0gAxklLYhCGUFIyF6NRSIXRCXns5laTfEELqf9nXBwCiEz8EAb/MQ00haMNkbshJyFnGu7H4y87wdl1FPTLjNzV@/kKCBGZKiX@b8w@M3EgdUsd5J0pUDSuTB8JX5zUTA7hTj6c/hiAz16tnhh8WhDz2rfZ23/AA "APL (Dyalog Extended) – Try It Online") --- # [APL (Dyalog Unicode)](https://www.dyalog.com/) 18.0, 18 [bytes](https://github.com/abrudz/SBCS) ``` (+/÷≢)⍤↓⌺(1+2×⎕)⊢⎕ ``` [Try an equivalent 17.x program online!](https://tio.run/##ZVA9T8MwEJ3xr7itiQqGs@NLMnTtym@ohMpSPlaE2BDf6YIQeycGNgYkRvpP/EfCs5ukcvHJ5/Pdu@d3nl0uDk6uZouL09Y/3M/bLBsfrr/94yr3d6@5f/nJeGzW7375lvunFY4Aa/eufbMczf3zrW8@Rze/H775EsWGhCzVihVTQY5K4qN4sbASKRN2l3FUo0xcEDtiIWMVSpSYssgYgAObgKJCRuXH06k6n/A@nU36N2ln1QALyQAb9KQwox1ZbS3kRF9GX2m3bUy0bxvRGqBF50Wkizd0JmYsaExP839gCpNBgdOCNw2qCNjoCogQQW8FBrthSK1fuz82wJNvSweGRhdrToe6aPcH "APL (Dyalog Unicode) – Try It Online") What a fitting challenge for Dyalog APL's Stencil `⌺`. The Stencil operator extracts the moving window over an array exactly as described in the challenge. Specifically, for odd window size, the window is centered over each element, padded with zeros outside the array as necessary, and then the amount of padding is given as an extra information so that single Drop `↓` will remove such padding. The rest is just specifying the right window size and taking average `(+/÷≢)` over each subarray. ### Illustration ``` Input array: 12 6 3 9 Input n: 1 Window size: 3 (1+2×n) Arguments to left operand of Stencil: Left Right 1 0 12 6 ⍝ Zero padding 1 unit to the left; 1↓ drops 0 from the front 0 12 6 3 0 6 3 9 ¯1 3 9 0 ⍝ Zero padding 1 unit to the right ¯1↓ drops 0 from the back ``` --- Matrix multiplication approach is also possible, but it is not short enough: # [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 [bytes](https://github.com/abrudz/SBCS) ``` {÷/⍵1+.ר⊂⍺≥|∘.-⍨⍳≢⍵} ``` [Try it online!](https://tio.run/##ZVC9SgNBEO73KaYVzeru3M7dFamEoJVgfIGAxCb@tKI2CsEENmghWgtCOgsRwTJ5k3mRc3Zzd2HjDjvMznzzzTc7uBp1Tq8Ho8uzqrpZ/uyy/zbbevm6mPP0nv0vTz5u@fFNd9jP2X/x5F0Qd9WQx0/sZzx9WHwij5959tI/3hd/cnDYrwwMwVggQChVfEAGDnIwe/UTxXJJ2nCVrXMOSoGAycA4MAQWFcZSYnXOSkNgJSEqlNo66vXURdfswHm3mQ0bpxQoAbWwVlUKs9oBakQRFH0efaHdujHRv26U1gDNak9EdbyiszGDQmMbmv8rQ9hLFDhNMtNKVQJjdSGIEIneQhhwxZBaczZ/rIUnn5YuLBpdrDkd6qTdHw "APL (Dyalog Unicode) – Try It Online") ### How it works ``` {÷/⍵1+.ר⊂⍺≥|∘.-⍨⍳≢⍵} ⍝ Left:n, Right:m ⍳≢⍵ ⍝ 1..length of m ∘.-⍨ ⍝ Self outer product by difference ⍺≥| ⍝ 1 if abs diff is at most n, 0 otherwise ⍝ which gives the band matrix ⍵1+.ר⊂ ⍝ Inner product with m and all-one vector ÷/ ⍝ Divide left by right ``` [Answer] ## CJam, ~~31~~ 30 bytes ``` ri_S*l~1$++\2*)ew{S-_:+\,d/}%` ``` Input format is `n [m1 m2 ... mx]`. [Run all test cases.](http://cjam.aditsu.net/#code=qN%2F%7BS2*%2F0%3D2%3E%22%2C%20m%3D%22%2F(s%3AR%3Bs%22%5B%5D%22%5C*%3AL%3B%0A%0ARi_S*L~1%24%2B%2B%5C2*)ew%7BS-_%3A%2B%5C%2Cd%2F%7D%25%60%0A%0A%5DoNo%7D%2F&input=n%3D1%2C%20m%3D12%206%203%209%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%209%207%206%206%0An%3D1%2C%20m%3D1%204%205%207%2010%20%20%20%20%20%20%20%20%20%20%20%20%20%202.5%203.333%205.333%207.333%208.5%0An%3D1%2C%20m%3D1%203%203%207%204%202%204%202%20%20%20%20%20%20%20%20%202%202.333%204.333%204.666%204.333%203.333%202.666%203%0An%3D2%2C%20m%3D1%203%205%209%2010%2014%2015%2016%2023%20%203%204.5%205.6%208.2%2010.6%2012.8%2015.6%2017%2018%0An%3D3%2C%20m%3D1%201%201%201%201%201%201%201%20%20%20%20%20%20%20%20%201%201%201%201%201%201%201%201%0An%3D3%2C%20m%3D1%202%203%204%205%206%207%208%20%20%20%20%20%20%20%20%202.5%203%203.5%204%205%205.5%206%206.5) (Automatically converts the test suite to the required input format.) This works by pre- and append `n` spaces, then taking all substrings of length `2n+1`, and removing the spaces again before computing their means. [Answer] # Pyth, 20 bytes ``` m.O:vzeS,0-dQh+dQUvz ``` [Test suite](https://pyth.herokuapp.com/?code=m.O%3AvzeS%2C0-dQh%2BdQUvz&test_suite=1&test_suite_input=12%2C+6%2C+3%2C+9%0A1%0A1%2C+4%2C+5%2C+7%2C+10%0A1%0A1%2C+3%2C+3%2C+7%2C+4%2C+2%2C+4%2C+2%0A1%0A1%2C+3%2C+5%2C+9%2C+10%2C+14%2C+15%2C+16%2C+23%0A2%0A1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%0A3%0A1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%0A3&debug=0&input_size=2) Pretty straightforward, just slice the appropriate section out of the list, then average. [Answer] # Julia, 57 bytes ``` f(n,m)=[mean(m[max(1,i-n):min(end,i+1)])for i=1:endof(m)] ``` This is a function that accepts two integers and returns an array of floats. The approach here is very straightforward. We construct a new array by taking the mean of sections of the input array, truncating at the front and back. [Answer] ## Haskell, ~~97~~ 95 bytes ``` import Data.List n#x|t<-2*n+1=[sum a/sum(1<$a)|a<-take t<$>take t(inits x)++tails x,length a>n] ``` Usage example: `2 # [1,3,5,9,10,14,15,16,23]` -> `[3.0,4.5,5.6,8.2,10.6,12.8,15.6,17.0,18.0]`. How it works: ``` t<-2*n+1 -- assign t to the maximum number of elements of a -- of sublist take t(inits x) -- build the sublists from t elements of the inits ++tails x -- of the input and the tails of the input, -- e.g. x=[1,2,3,4], t=3: -- [[],[1],[1,2]] ++ [[1,2,3,4],[2,3,4],[3,4],[4],[]] a<-take t<$> -- take at most t elements from every sublist ,length a>n -- keep those with a minimum length of n+1 sum a/sum(1<$a) -- calculate average, "sum(1<$a)" is the length of a ``` [Answer] ## Pyth, 22 bytes ``` .OMsM.:++J*]YKE]MQJhyK ``` Explanation: ``` .OM sM .: + Means of flattens of sublists of length 2K+1 of + J * ] Y J is E copies of []. K E Save E to a variable to use it later. ]MQ the input J Put J on both sides of ]MQ. h y K 2K+1 ``` Try it [here](https://pyth.herokuapp.com/?code=.OMsM.%3A%2B%2BJ%2a%5DYKE%5DMQJhyK&input=%5B1%2C3%2C5%2C9%2C10%2C14%2C15%2C16%2C23%5D%0A2&test_suite_input=0%0A1%0A1101%0A01100111%0A0110001111%0A1100011111111110%0A00110000000011111111000000000000011111111111111111111110000000000000000000000000000000000000011&debug=0). [Answer] # JavaScript (ES6), 104 Running total / running sample size. In Javascript, reading a value outside the bounds of an array gives undefined, that can be converted to 0 using ~~ ``` (l,n,p=0)=>l.map((v,i)=>(p+=~l[i-n-1]-~l[i+n])/(n+1+Math.min(n,l.length-1-i,i)),l.map((v,i)=>p+=i<n&&v)) ``` **Ungolfed** ``` (l, n) => { p = 0; for (i = 0; i < n; i++) p += v; r = []; for (i = 0; i < l.length; i++) { p += (l[i + n] || 0) - (i > n ? l[i - n - 1] : 0); r.push(p / Math.min(n, l.length - i - 1, i); } return r; } ``` **Test** ``` f=(n,l,p=0)=>l.map((v,i)=>(p+=~l[i-n-1]-~l[i+n])/(n+1+Math.min(n,l.length-1-i,i)),l.map((v,i)=>p+=i<n&&v)) console.log=x=>O.textContent+=x+'\n'; ;[ [1,[12,6,3,9],[9,7,6,6]] , [1,[1,4,5,7,10],[2.5,3.333,5.333,7.333,8.5]] , [1,[1,3,3,7,4,2,4,2],[2,2.333,4.333,4.667,4.333,3.333,2.667,3]] , [2,[1,3,5,9,10,14,15,16,23],[3,4.5,5.6,8.2,10.6,12.8,15.6,17,18]] , [3,[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]] , [3,[1,2,3,4,5,6,7,8],[2.5,3,3.5,4,5,5.5,6,6.5]] ].forEach(t=>{ var n=t[0],l=t[1],x=t[2],r=f(n,l) // verify (limited to 3 decimals) var ok = r.every((v,i)=>v.toFixed(3)==x[i].toFixed(3)) console.log((ok?'OK ':'Fail ')+n+' '+l+' -> '+r+' ('+x+')') }) ``` ``` <pre id=O></pre> ``` [Answer] # JavaScript (ES6), 82 bytes **code:** ``` F=(n,a)=>a.map((e,i)=>(s=a.slice(i<n?0:i-n,i+n+1))&&s.reduce((l,c)=>l+c)/s.length) ``` **test:** ``` F=(n,a)=>a.map((e,i)=>(s=a.slice(i<n?0:i-n,i+n+1))&&s.reduce((l,c)=>l+c)/s.length) document.write('<pre>' + [ [1, [12, 6, 3, 9], [9, 7, 6, 6] ], [1, [1, 4, 5, 7, 10], [2.5, 3.333, 5.333, 7.333, 8.5] ], [1, [1, 3, 3, 7, 4, 2, 4, 2], [2, 2.333, 4.333, 4.667, 4.333, 3.333, 2.667, 3] ], [2, [1, 3, 5, 9, 10, 14, 15, 16, 23], [3, 4.5, 5.6, 8.2, 10.6, 12.8, 15.6, 17, 18] ], [3, [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1] ], [3, [1, 2, 3, 4, 5, 6, 7, 8], [2.5, 3, 3.5, 4, 5, 5.5, 6, 6.5] ] ].map(t => { var [n, m, e] = t; var r = F(n, m); // verify to precision of 3 decimals var test = r.every((v, i) => v.toPrecision(3) === e[i].toPrecision(3)); return 'F(' + n + ', [' + m + '])\t' + (test ? 'Pass' : 'Fail') + '\n\t{' + r + '} ' + (test ? '=' : '≠') + ' {' + e + '}'; }).join('\n\n') + '</pre>'); ``` [Answer] ## [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes ``` ćU˜©ε®NX@iX·>£ÅAV®¦©YëN>X+£ÅA} ``` Input is: `[n,[list_m]]` Output is: `[list\_of\_avgs] **Explanation** ``` ćU˜©ε®NX@iX·>£ÅAV®¦©YëN>X+£ÅA} ć Head extract (get n) U Save in variable X ˜ Flat the list © Save the list in register c ε } Map ® Get the list from register c NX@ Is the iteration greater than or equal to n i if true ë if false X·> push (n*2)+1 £ extract (n*2)+1 elements from head ÅA Arithmetic mean V Save the result in variable Y ® Push the list from register c again ¦ remove head (first element) © save the new list in register c Y get variable Y (to apply on map returned value) N>X+ push i+1+n (i=iteration index, loop count) £ extract i+1+n elements from head ÅA Arithmetic mean ``` [Try it here :)](https://tio.run/##yy9OTMpM/f//SHvo6TmHVp7bemidX4RDZsSh7XaHFh9udQw7tO7QskMrIw@v9rOL0AYL1f7/H22koxBtqGOsY6pjqWNooGNoomNoqmNopmNkHBv7HwA) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes ``` Mean/@N@Partition[#2,UpTo[2#+1],1,{-#-1,#+1}]& ``` [Try it online!](https://tio.run/##ZY29CsJAEIR7n0II2DhBdy8/phDyAkoKrY4rDgnxiiQSrpM8@7mHTUIYttj5Znd6699tb7172dBdw621w6m@142dvPNuHHTCeH4eo@bkSAaEb5qkBFlmcwjN5Aa/rzstPjEKKFSz2a1sZMhRgs4boESlYI6zpPynOSo5A2WgHFSA1TKkYmilDWV5EtsLqbnMJoQf "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ I've been working on *another* stack-based golfing language called [Stackgoat](https://github.com/vihanb/Stackgoat). In this challenge you'll be writing a Tokenizer for Stackgoat (or really any general stack-based languages). ## Examples ``` "PPCG"23+ ["PPCG", '23', '+'] 'a "bc" + ['"a"', '"bc"', '+'] 12 34+-"abc\"de'fg\\" ['12', '34', '+', '-', '"abc\"de'fg\\"'] "foo ['"foo"'] (empty input) [] ' "" ['" "', '""'] ``` ## Specification The three types you'll need to handle are: * Strings, *anything* within `""` * Numbers, any sequence of digits * Operators, any other single character besides whitespace Whitespace is essentially ignored unless it is within a string or separates two numbers. String / char spec: * Strings are delimited by a `"`, and when a `\` is encountered, the next character should be escaped. * Chars are prepended by a `'` and the character after the `'` should be converted into a string literal. `'a` -> `"a"` * `'` will always have a character after it * Closing quotes should be auto-inserted Rules: * No form of `eval` is allowed Input / Output: * Input can be taken through STDIN, function parameters, or your language's equivalent. * Output should be an array or your language's closest equivalent. [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~68~~ ~~64~~ 63 bytes ``` M!s`"(\\.|[^"])*"?|'.|\d+|\S ms`^'(.)|^"(([^\\"]|\\.)*$) "$1$2" ``` or ``` s`\s*((")(\\.|[^"])*(?<-2>")?|'.|\d+|.)\s* $1$2¶ \ms`^'(.) "$1" ``` I think this covers all the funky edge cases, even those not covered by the test cases in the challenge. [Try it online!](http://retina.tryitonline.net/#code=TSFzYCIoXFwufFteIl0pKiI_fCcufFxkK3xcUwptc2BeJyguKXxeIigoW15cXCJdfFxcLikqJCkKIiQxJDIi&input=IlBQQ0ciMjMrJ2EgImJjIiArMTIgMzQrLSJhYmNcImRlJ2ZnXFwiImZvbw) [Answer] ### Ruby, 234 bytes ``` puts"[#{$stdin.read.scan(/("(?:(?<!\\)\\"|[^"])+(?:"|$))|'(.)|(\d+)|(.)/).map{|m|(m[0]?(m[0].end_with?('"')?m[0]: m[0]+'"'): m[1]?"\"#{m[1]}\"": m.compact[0]).strip}.reject(&:empty?).map{|i|"'#{/\d+|./=~i ?i: i.inspect}'"}.join', '}]" ``` I tried using the `find(&:itself)` trick that I saw... somewhere, but apparently `.itself` isn't actually a method. Also, I'm working on golfing the regex down, but it's already unreadable. If we don't have to output in any fancy way (i.e. strings don't have to be quoted in the array) I can save a whole lotta bytes: ### Still Ruby, 194 bytes: ``` p$stdin.read.scan(/("(?:(?<!\\)\\"|[^"])+(?:"|$))|'(.)|(\d+)|(.)/).map{|m|(m[0]?(m[0].end_with?('"')?m[0]: m[0]+'"').gsub(/\\(.)/,'\1'): m[1]?"\"#{m[1]}\"": m.compact[0]).strip}.reject(&:empty?) ``` I'm sure I can golf it more, but I'm not quite sure how. --- Ungolfed coming soon. I started fiddling with the golfed directly at some point and I'll have to tease it out. [Answer] # Python 3, 228 bytes ``` import re;L=list print(L(map(lambda i:i+'"'if i[0]=='"'and not i[-1]=='"'else i,map(lambda i:'"%s"'%i[1]if i[0]=="'"else i,filter(None,sum([L(i)for i in re.findall('(\'.)|(".*")|(\d+)|([^\w\"\'\s\\\])|(".*"?)',input())],[])))))) ``` Here's a nice, long, two-liner. --- Test it out in Python 3. Here's some examples: ``` $ python3 test.py "PPCG"23+ ['"PPCG"', '23', '+'] $ python3 test.py 'a "bc" + ['"a"', '"bc"', '+'] $ python3 test.py 12 34+-"abc"de'fg\" ['12', '34', '+', '-', '"abc"de\'fg\\"'] $ python3 test.py "foo ['"foo"'] $ python3 test.py [] $ python3 test.py ' "" ['" "', '""'] ``` ]
[Question] [ **If you haven't played golf before, here's a list of golf-related terms I use in this question** * *Shot*, also called a *stroke*: Every time the ball is hit, this is a shot. * *Hole*: A golf course is split into holes, in which the goal is to hit a ball from one designated location to another in as few shots as possible. * *Tee*: Where you start a hole. * *Pin* or *Flag*: Where you finish a hole * *Fairway*, *Rough*, *Water*, and *Green*: Features on a golf course that affect how one plays the ball in real life. (How they affect the program is specified below) --- I'm going out to play golf tomorrow, and I find that sometimes, I have trouble figuring out what club to use to hit a certain yardage. So I decided to write down my clubs and their yardages per shot. **First Assumption: All holes are due north of their tee boxes.** All of these yardages measure the possibilities for how far north the ball travels. The ball will travel a random integer distance between the bounds specified for each club (inclusive). As a master golfer, none of my shots have any horizontal shift. This means that all of my shots go in a straight line directly at the flag. ``` Club # Club Yardage 1 Driver 300-330 2 3-Wood 270-299 3 5-Wood 240-269 4 3-Iron 220-239 5 4-Iron 200-219 6 5-Iron 180-199 7 6-Iron 160-179 8 7-Iron 140-159 9 8-Iron 120-139 10 9-Iron 100-119 11 P-Wedge 80-99 12 S-Wedge 50-79 13 L-Wedge 0-49 14 Putter (only on green) ``` As a person who enjoys programming, I decide that I want to model a round of golf and set a goal for how well I want to do tomorrow. However, like any amateur programmer, after ten minutes, I gave up and asked for help on Stack Overflow (just kidding). Here are some more data about the course. **Second Assumption: Hole Geography** * All numbers that describe distances on the course are integers. * Each hole is a straight line. The straight line distance between each hole and the pin (the end of the hole) is `Length`. * Fairways are segments with length defined by `flen`. The value listed for `flen` is the range of yardages north from the tee where fairway is. * Water hazards are segments that have length defined by `wlen`, which has the same properties as `flen`. * The green has a length defined by `glen`. * All parts of the course that are not fairway, water, or green are rough. Here is a chart describing each hole on the course. ``` Hole # Length flen wlen glen 1 401 54-390 391-425 2 171 1-165 166-179 3 438 41-392 393-420 421-445 4 553 30-281,354-549 282-353 550-589 5 389 48-372 373-404 6 133 125-138 7 496 37-413 414-484 484-502 8 415 50-391 392-420 9 320 23-258 259-303 304-327 ``` **How to play Golf** (for this program) * Always aim exactly at the flag. * Hit the ball as close to the pin as possible, trying to keep the ball on the fairway or (preferably) on the green. * When you land a shot in the water, your next shot must be played from the same place as the shot that went into the water. * Once the ball lands on the green, only the putter can be used. If the ball lands strictly more than 5 yards from the pin, then I putt twice. Otherwise, I putt once. * It is possible to hit a shot past the pin. **Scoring** My score on a hole is the number of shots I take, plus one stroke for every time I land in rough or the water. **The program** Okay, that was a lot of rules, now let's talk about the program. The course should be defined as above *in the program*, because the course is constant. Different golfers, however, have different distances for each shot, so the input to STDIN should be a set of ranges of yardages, arranged in increasing order of club number and separated by commas (with no whitespace). The output should be how I "play" the round of golf. The hold number should be specified at the beginning of each line as `Hole #:` where `#` is the current hole. Each shot that is not a putt is of the following form: `{club,distance of shot,condition of ball,distance to pin}`. The details of the shot should be separated by commas but no whitespace in the above order. The shots themselves should be written in order of how they are played and separated by a space. Once the ball lands on the green, the program should print how many putts I take, in the format `{# putts}`. At the end of each line, the number of shots I took on the hole should be separated from the other shots by a space and printed as `(#)`. Each hole should be on its own line and written in order. Finally, on the last (tenth) line of the program, the total number of shots for the round should be printed as `Total: # shots`. There is no set "strategy" that your program is required to take. You can write a program with any strategy you want. Example strategies include maximizing the percent chance of landing on the green and maximizing the distance of each shot until reaching the hole. SAMPLE INPUT ``` 300-330,270-299,240-269,220-239,200-219,180-199,160-179,140-159,120-139,100-119,80-99,50-79,0-49 ``` SAMPLE OUTPUT ``` Hole 1: {Driver,324,Fairway,77} {S-Wedge,70,Green,7} {Two putts} (4) Hole 2: {6-Iron,162,Water,171} {6-Iron,168,Green,3} {One putt} (4) Hole 3: {Driver,301,Fairway,137} {8-Iron,131,Green,6} {Two putts} (4) Hole 4: {3-Wood,288,Water,553} {3-Wood,276,Fairway,277} {3-Wood,291,Green,14} {Two putts} (6) Hole 5: {Driver,322,Fairway,67} {S-Wedge,62} {One putt} (3) Hole 6: {8-Iron,120,Rough,18} {L-Wedge,10,Green,8} {Two putts} (5) Hole 7: {Driver,325,Fairway,171] {6-Iron,170,Green,1} {One putt} (3) Hole 8: {Driver,306,Fairway,109} {9-Iron,100,Green,9} {Two putts} (4) Hole 9: {Driver,308,Green,12} {Two putts} (3) Total: 36 shots ``` --- I'll admit, this is a rather ambitious challenge for a first post on CG.SE, so I'd be glad to talk about how to improve this challenge in comments. Thank you for your help. [Answer] # Python 2.7: ~~43~~ 40.5 shots average This is my first post here so bear with me. Since the poster was thinking of treating this like a programming challenge, not code golf, I tackled it as more a programming challenge. I attempted to keep my solution and shot logic simple but it turned out more ugly as things got complicated quickly. ## My Code Some things to think of while reading: the program creates a list of clubs used called 'clubs', and a list called 'distances' that is distance the ball has traveled from the tee, hlen is the length of the hole, d1s is the distance each shot travels. First I define the course. Each fairway, water, and green length had to be defined so later the program could check the condition of the ball, so I added non-integers values for the parts of the course that did not exist. ``` from random import randint import numpy as np #Hole Length flen wlen glen Name hole1 = [ 401, 54, 390, 390.5, 390.5, 391, 425, 'Hole 1'] hole2 = [ 171, 0.5, 0.5, 1, 165, 166, 179, 'Hole 2'] hole3 = [ 438, 41, 392, 393, 420, 421, 445, 'Hole 3'] hole4 = [ 553, 30, 549, 282, 353, 550, 589, 'Hole 4'] hole5 = [ 389, 48, 372, 1.5, 1.5, 373, 404, 'Hole 5'] hole6 = [ 133, 0.5, 0.5, 1.5, 1.5, 125, 138, 'Hole 6'] hole7 = [ 496, 37, 413, 414, 484, 484, 502, 'Hole 7'] hole8 = [ 415, 50, 391, 1.5, 1.5, 392, 420, 'Hole 8'] hole9 = [ 320, 23, 258, 259, 303, 304, 327, 'Hole 9'] holes = [hole1, hole2, hole3, hole4, hole5, hole6, hole7, hole8, hole9] ``` Here I defined the main logic for choosing a club. The program attempts to maximize distance by choosing the driver for all lengths greater than the max driver distance and chooses a club with range that contains the distance to the hole otherwise. This requires the range provides by the club input to be continuous, i.e. no gaps in shot distance. A realistic requirement since one can hit a club without a full backswing to limit the distance of their shot to the maximum distance of the next most powerful club. ``` def stroke(distance): Length = abs(hlen - distance) if Length >= Driver_a: club = 'Driver' d = randint(Driver_a,Driver_b) elif Length >= Wood3_a and Length <= Wood3_b: club = '3-Wood' d = randint(Wood3_a,Wood3_b) elif Length >= Wood5_a and Length <= Wood5_b: club = '5-Wood' d = randint(Wood5_a,Wood5_b) elif Length >= Iron3_a and Length <= Iron3_b: club = '3-Iron' d = randint(Iron3_a,Iron3_b) elif Length >= Iron4_a and Length <= Iron4_b: club = '4-Iron' d = randint(Iron4_a,Iron4_b) elif Length >= Iron5_a and Length <= Iron5_b: club = '5-Iron' d = randint(Iron5_a,Iron5_b) elif Length >= Iron6_a and Length <= Iron6_b: club = '6-Iron' d = randint(Iron6_a,Iron6_b) elif Length >= Iron7_a and Length <= Iron7_b: club = '7-Iron' d = randint(Iron7_a,Iron7_b) elif Length >= Iron8_a and Length <= Iron8_b: club = '8-Iron' d = randint(Iron8_a,Iron8_b) elif Length >= Iron9_a and Length <= Iron9_b: club = '9-Iron' d = randint(Iron9_a,Iron9_b) elif Length >= Pwedge_a and Length <= Pwedge_b: club = 'P wedge' d = randint(Pwedge_a,Pwedge_b) elif Length >= Swedge_a and Length <= Swedge_b: club = 'S wedge' d = randint(Swedge_a,Swedge_b) elif Length >= Lwedge_a and Length <= Lwedge_b: club = 'L wedge' d = randint(Lwedge_a,Lwedge_b) else : print 'stroke error' return club, d ``` Next, I define a put function that two putts for all lengths greater than 5 yards to the hole and one putt for 5 and less. I also include an option for hitting the ball directly into the hole called 'chip in'. ``` def putt(distance): Length = abs(hlen - distance) if Length > 5: club = '2 putts' elif Length == 0: club = 'chip in' else: club = '1 putt' return club ``` Here is where the strategy gets a little funky. In order to keep it simple and also prevents getting stuck in a loop of driving into water only to drop the ball at the location of the previous shot and drive into the water again, I actually backtrack, hitting the ball backward with the sand wedge and then have the code evaluate the shot again this time hopefully shooting just in front of the water so the next shot can clear it. This strategy is penalized by the rough penalty but is effective for clearing water. ``` def water(): club = 'S wedge' d = randint(50,79) return club, d ``` This program counts the number of strokes per hole after that hole has been played. It adds the penalties for the shots in the rough and adds the penalties for hitting into the water by summing a array called water that is appended after each water shot. This takes advantage of the fact that fairway always leads to water or to the green for every hole in the course. It would have to be changed for courses that contained rough in the middle of the fairway. ``` def countstrokes(clubs, distances, waters): distances = np.array(distances) mask1 = distances < flen1 mask2 = distances > grn2 extra = sum(mask1*1)+sum(mask2*1) + sum(waters) if clubs[-1] == 'chip in' : strokes = len(clubs)-1+extra elif clubs[-1] == '2 putts' : strokes = len(clubs) +1+extra elif clubs[-1] == '1 putt' : strokes = len(clubs)+extra else : print 'strokes error' return strokes ``` After the main code runs, condition looks at the distances the ball was at during the hole and reports the condition of the ball. I ran into one issue with condition because of the way I treated hitting the ball into the water in the main program. In the program, if the ball was hit into the water, it was immediately moved back to the location of where the shot was hit. The distance was recorded after the ball is moved back so the condition of the ball cannot be ‘water’. If you hit the ball off the tee on hole 4 into the water, the program prints the distance you hit the ball and the club but the length to the hole will remain unchanged and the condition will be 'rough' since the ball is dropped at 0 distance which is in the rough. You can uncomment a print 'water' flag if you want to be told how many times the ball is hit into the water before each hole. ``` def condition(distances): conditions=[] for distance in distances: if distance >= grn1 and distance <= grn2: conditions.append('green') elif distance >= flen1 and distance <= flen2: conditions.append('fair') else: conditions.append('rough') return conditions ``` Here is the main part of the code which loads the holes and plays the game. After initializing some conditions the code runs 'stroke' hitting the ball towards the hole, including reverse if the hole was overshot, until either water or green is encountered. If water is encountered, it adds to a penalty counter and runs the program water and after moving the ball back to the location it was hit from. If the green is encountered, put is called and the hole is terminated. After the distances and clubs are analyzed to determine the condition of each shot and the shots are tallied. ``` def golf(driver_a, driver_b, wood3_a, wood3_b, wood5_a, wood5_b, iron3_a, iron3_b, iron4_a, iron4_b, iron5_a, iron5_b, iron6_a, iron6_b, iron7_a, iron7_b, iron8_a, iron8_b, iron9_a, iron9_b, pwedge_a, pwedge_b, swedge_a, swedge_b, lwedge_a, lwedge_b): global Driver_a, Driver_b, Wood3_a, Wood3_b, Wood5_a, Wood5_b, Iron3_a, Iron3_b, Iron4_a, Iron4_b, Iron5_a, Iron5_b, Iron6_a, Iron6_b, Iron7_a, Iron7_b, Iron8_a, Iron8_b, Iron9_a, Iron9_b, Pwedge_a, Pwedge_b, Swedge_a, Swedge_b, Lwedge_a, Lwedge_b Driver_a, Driver_b, Wood3_a, Wood3_b, Wood5_a, Wood5_b, Iron3_a, Iron3_b, Iron4_a, Iron4_b, Iron5_a, Iron5_b, Iron6_a, Iron6_b, Iron7_a, Iron7_b, Iron8_a, Iron8_b, Iron9_a, Iron9_b, Pwedge_a, Pwedge_b, Swedge_a, Swedge_b, Lwedge_a, Lwedge_b = driver_a, driver_b, wood3_a, wood3_b, wood5_a, wood5_b, iron3_a, iron3_b, iron4_a, iron4_b, iron5_a, iron5_b, iron6_a, iron6_b, iron7_a, iron7_b, iron8_a, iron8_b, iron9_a, iron9_b, pwedge_a, pwedge_b, swedge_a, swedge_b, lwedge_a, lwedge_b totals =[] for hole in holes: distance = 0 strokes = 0 clubs = [] distances = [] d1s = [] waters=[] global hlen, flen1, flen2, wtr1, wtr2, grn1, grn2 hlen, flen1, flen2, wtr1, wtr2, grn1, grn2, name = hole while True: club1, d1 = stroke(distance) clubs.append(club1) if distance > hlen: d1 = -d1 distance = distance + d1 d1s.append(d1) if distance >= wtr1 and distance <= wtr2: #print 'water' waters.append(1) distance = distance - d1 distances.append(distance) club1, d1 = water() if distance < wtr1: d1 = - d1 distance = distance + d1 d1s.append(d1) clubs.append(club1) distances.append(distance) if distance >= grn1 and distance <= grn2: club1 = putt(distance) clubs.append(club1) break strokes = countstrokes(clubs, distances, waters) totals.append(strokes) conditions = condition(distances) shots = len(d1s) print name, ':', for x in xrange(0,shots): print '{', clubs[x], ',', d1s[x],',', conditions[x],',', hlen-distances[x], '}', print '{',clubs[-1], '}', '{',strokes ,'}' print 'Total:', sum(totals), 'shots' return sum(totals) ``` The code is run like ``` golf(300,330,270,299,240,269,220,239,200,219,180,199,160,179,140,159,120,139,100,119,80,99,50,79,0,49) ``` and the out looks like this: ``` Hole 1 : { Driver , 308 , fair , 93 } { P wedge , 96 , green , -3 } { 1 putt } { 3 } Hole 2 : { 6-Iron , 166 , green , 5 } { 1 putt } { 2 } Hole 3 : { Driver , 321 , fair , 117 } { 9-Iron , 105 , green , 12 } { 2 putts } { 4 } Hole 4 : { Driver , 305 , rough , 553 } { S wedge , -62 , rough , 615 } { Driver , 326 , fair , 289 } { 3-Wood , 293 , green , -4 } { 1 putt } { 8 } Hole 5 : { Driver , 323 , fair , 66 } { S wedge , 73 , green , -7 } { 2 putts } { 4 } Hole 6 : { 8-Iron , 125 , green , 8 } { 2 putts } { 3 } Hole 7 : { Driver , 314 , fair , 182 } { 5-Iron , 181 , green , 1 } { 1 putt } { 3 } Hole 8 : { Driver , 324 , fair , 91 } { P wedge , 91 , green , 0 } { chip in } { 2 } Hole 9 : { Driver , 317 , green , 3 } { 1 putt } { 2 } Total: 31 shots ``` This was one the lowest score of many trials, with an absolute lowest of 26 in 100,000 runs. But still under a typical par of 34-36 even with 8 strokes on hole 4. I'll include the code I used to find the distribution of games with the above specified clubs. ``` import matplotlib.pyplot as plt class histcheck(object): def __init__(self): self = self def rungolf(self, n=10000): results=[] for x in xrange(0,n): shots = golf(300,330,270,299,240,269,220,239,200,219,180,199,160,179,140,159,120,139,100,119,80,99,50,79,0,49) results.append(shots) self.results = results def histo(self, n=20): plt.figure(figsize=(12,12)) plt.hist(self.results, bins=(n)) plt.title("Histogram") plt.xlabel("Shots") plt.ylabel("Frequency") plt.show() ``` Running ``` play = histcheck() play.rungolf() play.hist() ``` gives the following histogram [![Golf Histogram](https://i.stack.imgur.com/DgBqc.png)](https://i.stack.imgur.com/DgBqc.png) and the mean and median can be found using ``` np.mean(play.results) np.meadian(play.results) ``` a mean of about 43 and a median of 41. Not too bad for 9 holes with simple shot optimization. ## It is all yours now Go ahead and copy and tweak my program and evaluate it using my tools in order to lower the average number of shots. Let me know if there is anything scenario I didn't account for or go ahead and make a golfed version. I think that the best program would be one that returned the lowest average shots for a number of club inputs. My code isn't the best option for that but I thought I'd get the ball rolling. ## Update ``` def water(): if clubs[-1] =='S wedge': club = 'S wedge' d = randint(50,79) elif clubs[-1] !='S wedge': club = 'S wedge' d = -randint(50,79) else: print 'water error' return club, d ``` By changing the water logic so that it attempts to hit the ball forward by a small amount after encountering water instead of backwards if the previous club used was not the sand wedge, it improved the mean to 40.5 and the median to 39 after testing with *one million* runs. Minimum of 23, maximum of 135. Sometimes you get lucky, sometimes you don't. Check out the new histogram. [![Histogram2](https://i.stack.imgur.com/Env1q.png)](https://i.stack.imgur.com/Env1q.png) ]
[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/3726/edit) Just an idea I had the other day: Making beats following a [Markov Chain](http://en.wikipedia.org/wiki/Markov_chain) of predefined sounds. I remember someone did a beatbox with Google Translate and the German language (follow the [link](http://translate.google.com/#de%7Cde%7Cpvzk%20bschk%20pv%20zk%20pv%20bschk%20zk%20pv%20zk%20bschk%20pv%20zk%20pv%20bschk%20zk%20bschk%20pv%20bschk%20bschk%20pv%20kkkkkkkkkk%20bschk%0A%0A) and press listen). So, the challenge is to build a text input to Google Translate from a given chain. Or you can use musical notes and play it yourself :). ![Markov Chain](https://i.stack.imgur.com/gZM9P.png) You can make a program reading a line with the number of beats, another with their names and a matrix representation of the probabilities (you can choose the representation). You may also make a function with those three arguments. E.g. [input] ``` 20 pv zk bschk kkkk [[.1, .4, .5, 0.], [.3, .2, .3, .2], [0., .3, .2, .5], [.1, .8, .1, 0.]] ``` [output] something like: ``` pv zk bschk zk pv bschk zk pv zk bschk kkkk pv bschk zk bschk bschk bschk zk kkkk bschk ``` The starting probability is the same for each beat. That's not a code-golf challenge because I would like to see some nice solutions (be creative). Extra points if you invent new beats and/or choose a table of probabilities that gives nice beats most of the time. If you want, you can use real beats (In many languages it's easy to open `.wav` files, like the `wave` module in Python) and generate music! [Here](http://samples.kb6.de/downloads.php) are some free sample beats. I may post a reference implementation if needed. [Answer] I made these tracks: <http://soundcloud.com/belisarius/sets/golf-music> Using the following transition matrix: ``` {{10, 1, 3/2, 2}, {1/2, 10, 3/2, 2}, {1/2, 1, 10, 2}, {1/2, 1, 3/2, 10}} ``` And the following program in Mathematica: ``` musicGen[n_, notes_, transMatrix_] := Module[{ im := IdentityMatrix[Length@notes], a := Array[2^(# - 1) &, Length@notes], soundLength = .1 n, which }, which[x_] := Position[x, 1][[1, 1]]; Sound[Join[ (SoundNote /@ notes[[ which[#] & /@ NestList[ RandomChoice[transMatrix[[which@#]] -> im] &, RandomChoice@im, n - 1] ]] ) ], soundLength] ] tm = {{10, 1, 3/2, 2}, {1/2, 10, 3/2, 2}, {1/2, 1, 10, 2}, {1/2, 1, 3/2, 10}} notesSet = {"Snare", {"Slap", "Shaker"}, {"OpenTriangle", "Maracas"}, "RideBell"}; m = Array[If[#2 == 5 || #2 == #1, 10, #2/2] &, {Length@notesSet,Length@notesSet}]; mg = musicGen[100, notesSet, tm] ``` [Answer] Being German, I was almost falling off my chair laughing at this creative abuse of our language. :-) Here is some Scala. I am encoding the probabilities in a map that maps the beat to a list of successor beats in which the beats occure with a frequency proportional to their probability. An infinite lazy evaluated stream of beats is created, whose first 10 beats are skipped to get the appropriate randomness of the first output beat. We return the appropriate number of beats from the beginning of that stream. I use the type parameter T to be shorter and generic. ``` def markovChain[T](length : Int, nodes : Seq[T], probabilities : Map[T, Seq[T]]) : Seq[T] = { def randomElement(seq : Seq[T]) = seq(Random.nextInt(seq.length)) def chain(node: T): Stream[T] = Stream.cons(node, chain(randomElement(probabilities(node)))) return chain(randomElement(nodes)) drop(10) take(length) } ``` which can be called like this: ``` val nodes = List("pv", "zk", "bschk", "kkkk") val probabilities = Map( "pv" -> List("pv", "zk", "zk", "zk", "zk", "bschk", "bschk", "bschk", "bschk", "bschk"), "zk" -> List("pv", "pv", "pv", "zk", "zk", "bschk", "bschk", "bschk", "kkkk", "kkkk") , "bschk" -> List("zk", "zk", "zk", "bschk", "bschk", "kkkk", "kkkk", "kkkk", "kkkk", "kkkk"), "kkkk" -> List("pv", "zk", "zk", "zk", "zk", "zk", "zk", "zk", "zk", "bschk")) markovChain(20, nodes, probabilities) foreach (s => print (s + " ")) ``` [Answer] I wrote a Javascript function. However, it have begun beatboxing itself... ``` function bschk(jk,pv,kkkk){jkjk='pv jk bschk kkkk'.split(' ');boom='indexOf';eval( function(jkpv){for(pvpv=0,bschkpv='';pvpv<jkpv.length;jkpvpv=jkpv[pvpv++].split(' '), bschkpv+=String.fromCharCode(jkjk[boom](jkpvpv[0])+jkjk[boom](jkpvpv[1])*4+jkjk[ boom](jkpvpv[2])*16+jkjk[boom](jkpvpv[3])*64));return bschkpv}(( 'bschk jk bschk jk kkkk kkkk bschk jk bschk pv kkkk jk pv bschk bschk pv bschk ' +'jk kkkk jk jk pv bschk jk bschk pv kkkk jk pv pv bschk pv jk jk bschk jk jk ' +'kkkk kkkk pv bschk kkkk kkkk jk bschk kkkk kkkk jk pv bschk bschk pv jk kkkk ' +'pv jk jk pv bschk jk pv jk kkkk jk pv bschk bschk jk bschk kkkk bschk pv bsc' +'hk pv kkkk jk jk pv bschk jk bschk kkkk bschk jk pv jk bschk jk kkkk kkkk bsc' +'hk jk jk kkkk bschk jk pv bschk bschk pv jk bschk bschk pv bschk bschk bschk ' +'pv pv pv kkkk jk bschk jk kkkk jk bschk kkkk bschk pv pv kkkk bschk jk jk jk' +' bschk jk bschk kkkk bschk jk kkkk jk bschk jk pv jk kkkk jk pv bschk bschk j' +'k jk bschk bschk pv pv kkkk bschk pv jk bschk bschk jk jk kkkk kkkk pv pv pv' +' kkkk pv pv kkkk bschk pv bschk jk bschk jk pv kkkk bschk pv kkkk jk bschk jk' +' pv kkkk bschk pv kkkk pv bschk jk kkkk bschk bschk jk kkkk pv bschk jk kkkk' +' bschk bschk jk bschk pv bschk jk kkkk kkkk bschk jk kkkk kkkk bschk jk jk kk' +'kk bschk jk jk kkkk kkkk pv kkkk jk bschk pv kkkk jk bschk pv kkkk bschk kkkk' +' pv jk bschk bschk jk pv kkkk kkkk pv bschk bschk bschk jk kkkk bschk bschk j' +'k kkkk bschk kkkk pv jk bschk bschk jk kkkk bschk bschk pv kkkk bschk bschk p' +'v jk bschk bschk pv kkkk bschk kkkk jk kkkk pv bschk jk kkkk bschk bschk jk ' +'kkkk pv bschk jk kkkk bschk bschk jk bschk pv bschk jk kkkk kkkk bschk jk kkk' +'k kkkk bschk jk jk kkkk bschk jk kkkk bschk bschk pv jk kkkk kkkk pv pv pv kk' +'kk jk bschk jk kkkk jk kkkk bschk jk jk jk jk bschk jk jk kkkk jk jk kkkk bs' +'chk bschk pv kkkk jk bschk pv pv pv bschk pv kkkk jk bschk pv kkkk bschk kkkk' +' pv kkkk jk bschk jk jk kkkk kkkk pv jk kkkk pv jk jk pv bschk jk pv jk kkkk' +' jk pv bschk bschk jk bschk kkkk bschk pv bschk pv kkkk jk jk pv bschk jk bs' +'chk kkkk bschk jk pv jk bschk jk kkkk kkkk bschk jk jk kkkk bschk jk pv bschk' +' bschk pv jk bschk bschk pv kkkk bschk kkkk pv bschk jk bschk jk jk kkkk kkkk' +' pv jk kkkk bschk pv jk pv kkkk pv kkkk bschk kkkk pv kkkk jk kkkk jk pv bsc' +'hk bschk jk jk bschk bschk jk pv kkkk bschk jk jk jk bschk jk pv bschk bschk ' +'pv kkkk jk bschk jk bschk kkkk kkkk pv jk kkkk kkkk pv pv pv kkkk pv jk bsch' +'k bschk pv kkkk jk bschk jk jk kkkk bschk pv jk kkkk kkkk pv kkkk bschk bschk' +' jk kkkk bschk bschk jk kkkk bschk bschk jk kkkk bschk bschk jk kkkk bschk jk' +' jk jk jk bschk jk jk kkkk jk jk kkkk bschk jk jk kkkk bschk bschk pv kkkk b' +'schk bschk pv bschk jk bschk jk jk kkkk jk jk kkkk bschk kkkk pv jk jk bschk ' +'jk jk kkkk kkkk pv bschk jk bschk jk kkkk bschk kkkk pv jk kkkk kkkk jk').split (' ')));return ckckboom;} ``` Usage example : `bschk(20,'pv jk bschk kkkk'.split(' '),[[.1,.4,.5,0],[.3,.2,.3,.2],[0,.3,.2,.5],[.1,.8,.1,0]])` [Answer] Just a reference implementation in Python: ``` from random import random def find(num, pdf): ''' Find position of number in CDF from PDF (must sum 100%) ''' cdf = (sum(pdf[:i+1]) for i in range(len(pdf))) for i,j in enumerate(cdf): if num < j: return i def build(t, beats, table): node = int(random()*len(table)) nodes = [node] for i in range(t-1): node = find(random(), table[node]) nodes.append(node) return ' '.join(beats[i] for i in nodes) ``` And a test program: ``` table = [[.1, .4, .5, 0.], [.3, .2, .3, .2], [0., .3, .2, .5], [.1, .8, .1, 0.]] print(build(20, 'pv zk bschk kkkk'.split(), table)) ``` And some outputs: ``` pv zk bschk zk kkkk zk bschk kkkk zk zk zk bschk kkkk zk bschk zk pv bschk kkkk zk zk bschk kkkk zk zk kkkk zk bschk kkkk zk bschk zk pv zk pv zk zk bschk kkkk bschk kkkk zk zk pv bschk bschk zk zk kkkk zk kkkk zk zk kkkk zk pv zk bschk kkkk zk ``` But none of them makes a really good beatbox because there's too much `kkkk` :). ]
[Question] [ In this challenge, we consider an encoding from positive integers (up to a limit) to binary sequences. Some examples: ``` A. 1 -> 00, 2 -> 01, 3 -> 10, 4 -> 11 B. 1 -> 0, 2 -> 1, 3 -> 01 C. 1 -> (empty sequence) ``` A [prefix code](https://en.wikipedia.org/wiki/Prefix_code) is a coding where no code is a prefix of another. `B` is not a prefix code because the code for 1 (`0`) is a prefix of that for 3 (`01`). [Fibonacci coding](https://codegolf.stackexchange.com/q/222676/78410) and [Elias omega coding](https://codegolf.stackexchange.com/q/219109/78410) are examples of prefix codes that can encode all positive integers. It is possible to construct a prefix code where 1 encodes to a code of length \$l\_1\$, 2 to \$l\_2\$, ..., \$n\$ to \$l\_n\$ if the sum of \$\tfrac{1}{2}\$ raised to the power of each length does not exceed 1, i.e. \$\sum\_{i=1}^{n}{\tfrac{1}{2^{l\_i}}} \le 1\$. Your task is to construct such a prefix code where \$l\_1, \cdots, l\_n\$ is the input. The following I/O are allowed: * Take the list as input, and output the list or mapping of encodings for each positive integer * Take the list and a number to encode as input, and output the encoding for the given number Each encoding (binary sequence) can be given as a list or a string. Outputting as a single integer is not allowed, as leading zeros are not representable. You can choose to output an encoding for \$0, \cdots, n-1\$ instead of \$1, \cdots, n\$. ### Examples ``` [0] -> {1 -> ""} [1, 1] -> {1 -> "0", 2 -> "1"} [2, 3, 4, 4, 5, 5, 5] -> {1 -> "11" 2 -> "011" 3 -> "0011" 4 -> "1011" 5 -> "00011" 6 -> "10011" 7 -> "01011"} [3, 3, 3, 1, 3] -> {1 -> "101" 2 -> "111" 3 -> "110" 4 -> "0" 5 -> "100"} [5, 4, 3, 2, 5, 4, 3, 2] -> {1 -> "10101" 2 -> "1011" 3 -> "000" 4 -> "01" 5 -> "10100" 6 -> "1001" 7 -> "001" 8 -> "11"} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes ``` āø{ø`soDzηO>*<b€¦sākè ``` [Try it online!](https://tio.run/##yy9OTMpM/f//SOPhHdWHdyQU57tUndvub6dlk/Soac2hZcVHGrMPr/j/P9pUR8FER8FYR8FIRwHBjgUA "05AB1E – Try It Online") Uses the same idea as arithmetic coding. Fails for lengths greater than 53 due to floating-point inaccuracies. If we can output sorted by length, we can we 12 bytes: # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` {oDzηO>*<b€¦ ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/Ot@l6tx2fzstm6RHTWsOLfv/P9pUR8FER8FYR8FIRwHBjgUA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` eƤ€`Ḅ=QƑẠ Ø.ṗŒpÇƇṪ ``` A monadic Link that accepts the lengths and yields a list of prefix-codes in the same order. **[Try it online!](https://tio.run/##ATcAyP9qZWxsef//Zcak4oKsYOG4hD1RxpHhuqAKw5gu4bmXxZJww4fGh@G5qv///1syLDMsNCw0LDFd "Jelly – Try It Online")** Save a byte by outputting symbols \$1\$ and \$2\$ by replacing `Ø.` with `2`. ### How? ``` eƤ€`Ḅ=QƑẠ - Link 1: isValid?: list of codes, Assignment ` - use {Assignment} as both arguments of: € - for each Code in {Assignment}: Ƥ - for each prefix of {Code}: e - exists in {Assignment}? Ḅ - convert {each exists-in vector} from binary -> PrefixFoundIds, a list of ints ...a value is greater than 1 when a prefix was in Assignments otherwise it equals 1 (only the full code was in Assignments) Ƒ - is {Assignments} invariant under?: Q - deduplication -> AllDifferent = 0 if there are repeats, 1 if not = - {PrefixFoundIds} equals {AllDifferent} (vectorises) Ạ - all? Ø.ṗŒpÇƇṪ - Main Link: list of integers, CodeLengths Ø. - [0,1] ṗ - Cartesian product {CodeLengths} (vectorises) -> all codes for each of the respective lengths Œp - Cartesian product -> all possible Assignments of codes Ƈ - filter keep those {Assignments} for which: Ç - call Link 1 as a monad - f(Assignment) Ṫ - tail ``` --- ## 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (non-compliant) Less brute force, so much faster, but outputs the prefix codes sorted by their lengths. Again `Ø.` could be replaced with `2` to save a byte. If the input were guaranteed to be sorted too, then `2ṗeƤẸ¥ÐḟḢṭð@ƒḟ` does the job at \$14\$ bytes. ``` Ø.ṗeƤẸ¥ÐḟḢṭ Ṣç@ƒḟ ``` **[Try it online!](https://tio.run/##y0rNyan8///wDL2HO6enHlvycNeOQ0sPT3i4Y/7DHYse7lzL9XDnosPLHY5NAor8//8/2kwHPzTSMYwFAA "Jelly – Try It Online")** ### How? ``` Ø.ṗeƤẸ¥ÐḟḢṭ - Link 1: integer NextCodeLength, list of codes, FoundAlready Ø. - [0,1] ṗ - Cartesian power {NextCodeLength} -> PotentialCodes Ðḟ - filter discard those for which: ¥ - last two links as a dyad - f(PotentialCode, FoundAlready) Ƥ - for prefixes of {PotentialCode} e - exists in {FoundAlready}? Ẹ - any? Ḣ - head -> first valid PotentialCode ṭ - tack to {FoundAlready} Ṣç@ƒḟ - Main Link: list of integers, CodeLengths Ṣ - sort {CodeLengths} ḟ - {CodeLengths} filter discard {CodeLengths} -> [] (initial FoundAlready) ƒ - starting with {[]} reduce {sorted CodeLengths} by: @ - with swapped arguments: ç - call the dyadic helper above, Link 1 = f(NextCodeLength, FoundAlready) ``` [Answer] # [Python](https://www.python.org), 88 bytes ``` lambda s,k=0,r=2:{j:bin(r:=(r<<-k+(k:=i))-1)[3:]for i,j in sorted(zip(s,range(len(s))))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZHRToMwFIbjLU9x0qs2FtPCpgsZew4T3AXLwHVDIKVqdOFJ9GKJ0XfSp_EUSoRJTkj__n_P1wNvX_WL2VXl6SOP7z4fTe4vvm-L9GGzTaHhh1hwHQfRcR9tVEl1FFO9XPqHS3qIYsWYL1kSRuu80qD4HlQJTaVNtqWvqqYN12l5n9EiK2nD8Gld_8zmC5uuavQEizxQORRXjUm1aZ6V2VGSELsNCmJr1IUylPgrwhKxxpzG_szZ2VNaUGVVrVVpqOI5StbDTj8X73gE_BUcpX0T0nqJ5CDHe4JwCLqVtHbAIeQw62rel00jweWlJCjcEeFU2KtBzvrkIOfOHfS1swd943pZjVcIuytg4VXDM7gY0-WELqUYwcWIjCTbd94NhX2Dbi63_geYIs4nnDDkBCKd-TfeeDqnFsNHbL3-L_0C) Takes a list of integers and returns a dictionary. ## How? Sorts the prescribed lengths and then simply counts down binary numbers of that length appending zeros when the length increases. [Answer] # JavaScript (ES6), 115 bytes A simple but quite long algorithm. ``` a=>a.map((v,i)=>(h=x=>b.some(s=>c.match("^"+s)+s.match("^"+c),c=x.toString(2).padStart(v,0))?h(-~x):b[i]=c)``,b=[]) ``` [Try it online!](https://tio.run/##bYzNCoMwEITvfQrxtEtj8KdeCmsfwqNYjKl/RY2YIJ766jbYHkoRvsPszOw8xSK0nLvJeKN6VFtNm6BE8EFMAAvrkBJoaaWk5FoNFWhKpA2NbMG9u2eNZ/1zSmSSVm5UauZubCBEPolHasRs7JiPeGvBe614LbMuJ4lFwUrKctykGrXqK96rBmrI/Bzx9OcFzAkO7JA5EXMuO/GHg1a0tyx2JTrI4/3f5uE@8dW2uL0B "JavaScript (Node.js) – Try It Online") ### Method We process all entries in the input order. For each entry, we simply start with \$x=0\$ and increment it while \$x\$ is a prefix of a previous output or a previous output is a prefix of \$x\$, in left-padded binary format. ### Note Because \$x\$ is actually initialized to `['']`, `x.toString(2).padStart(0,0)` returns an empty string rather than `"0"`, which is the expected behavior for the edge case `a = [0]`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` →F⊕⌈θ«F⌕Aθι«§≔θκΦ⍘ⅈ²μ→»Mⅈ→»θ ``` [Try it online!](https://tio.run/##VY49C4MwEIbn@CtuvEC69GOpkx0EB6G0S0EcgqYamkSMqQjF356mCi0dDo7n3o@rWm6rjivv824UeLzIpnU0ju6dBcxMZYUWxokacz5J/dTYU0rhFZFFkEpTJ0phz0CumCTDIBuTuMzUYvocHgxSqZyweOKDuDorTYM3pAy2YTQNZYT8l5M5Wski@@I5OgezCy/E3hfFgcGewS7kMPjtZek3o3oD "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` → ``` Start with a next code number of `1`, but all the codes will have their leading `1` removed again later. ``` F⊕⌈θ« ``` Loop over all possible code lengths. ``` Mⅈ→ ``` Double the next code number. ``` F⌕Aθι« ``` Loop over all indices with this length. ``` §≔θκΦ⍘ⅈ²μ ``` Generate the code of this length, but remove the leading `1`. ``` → ``` Increment the next code number. ``` »»θ ``` Output the resulting codes. ]
[Question] [ This problem is based on, [A337517](https://oeis.org/A337517), the most recent OEIS sequence with the keyword "nice". > > \$a(n)\$ is the number of distinct resistances that can be produced from a circuit with exactly \$n\$ unit resistors. > > > The sequence begins `1, 2, 4, 9, 23, 57, 151, 427, 1263, 3823, 11724, 36048, 110953, 342079`. The goal of this challenge is to write a program that takes a positive integer `n` and outputs the possible resistances that can be formed with \$n\$ unit resistors, written as fractions (or floats, ordered pairs representing fractions, or in another essentially similar format) as in the following: ``` f(3) = [3/1, 3/2, 2/3, 1/3] = [(3,1), (3,2), (2,3), (1,3)] = [[3,1], [3,2], [2,3], [1,3]] ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so shortest code wins. Your program needs to be able to handle inputs up to \$n = 6\$ on [TIO](https://tio.run/#). ### Examples * With \$n = 1\$ resistor, the only possibility is a circuit with \$1 \Omega\$ total resistance. * With \$n = 2\$ resistors, there are only \$a(2) = 2\$ possibilities: 1. Resistors in sequence resulting in \$2 \Omega\$ total resistance. 2. Resistors in parallel resulting in \$\frac 12 \Omega\$ total resistance. * With \$n = 3\$ resistors, there are \$a(3) = 4\$ possibilities with resistances \$3 \Omega, \frac 32 \Omega, \frac 23 \Omega\$, and \$\frac 13 \Omega\$: 1. [![Resistors in series: 3 Ohms](https://i.stack.imgur.com/rtc1D.png)](https://i.stack.imgur.com/rtc1D.png) 2. [![Resistors in series, then parallel: 3/2 Ohms](https://i.stack.imgur.com/JsDEd.png)](https://i.stack.imgur.com/JsDEd.png) 3. [![Resistors in series within parallel: 2/3 Ohms](https://i.stack.imgur.com/nS8FB.png)](https://i.stack.imgur.com/nS8FB.png) 4. [![Resistors in parallel: 1/3 Ohms](https://i.stack.imgur.com/uPxUn.png)](https://i.stack.imgur.com/uPxUn.png) [Answer] # [Python 2](https://docs.python.org/2/), 734 bytes ``` import fractions as F,itertools as I r=range s=set P=lambda G,p=[0]:[x for a,b in G if(p[-1]==a)*(1-(b in p))for x in(P(G,p+[b])if b-1else[p+[b]])] def R(G): G+=tuple((b,a)for a,b in G);B=s(b for a,b in G);n=1+max(B) if s(G)-s(x for p in P(G)for e in zip(p,p[1:])for x in[e,e[::-1]])or len(B)-n:return 0 M=[[0]*(n+1)for _ in B];M[0][0],M[0][n],M[1][1]=[F.Fraction(1)]*3 for a,b in G:M[a][a]+=a>1;M[a][b]-=a>1 for i in r(n): for j in r(i,n): if M[j][i]:break M[i],M[j]=M[j],M[i];M[i]=[x/M[i][i]for x in M[i]] for j in r(n):M[j]=[a-(j!=i)*b*M[j][i]for a,b in zip(M[j],M[i])] return 1/sum(M[a][n]-M[b][n]for a,b in G if a==0) f=lambda n:s(map(R,I.combinations_with_replacement([(a,b)for a in r(n)for b in r(a,n+1)],n)))-s([0]) ``` [Try it online!](https://tio.run/##XVLBbtswDD3XX8EeglKJ3MYbsIMD7ZBDgh4MFL0KQiAncqvMlgVZwbL9fEY5SdsMIEQ9gnoiH@n/xPfefTudbOf7EKEJehtt7wbQA6y4jSbEvm9H@JwFEbR7M9kgBhOzF9Hqrt5pWHMv5FyV8ghNH0DzGqyDNdgGvcwLJYRmUyxyHOOesZR1pDu@IL2dyVox20CdF6YdjBwDiqlsZxp4xTUrM1jPRDz41iDWXLOvv7DFUgzEfBtzoph1@ohLllEZMBBLPuC5Pp9y6OeRxiTw13r03MuiVB@1ScONLEsqXzEKtcYRWe7KYOIhOJhnUAlJXU/RzYrx1SZRLdWioigZH71LvlBkQq4eVxd5sWBq@j27KbqspFZkM6F/FosR1CpP4JxnU1ZAR3LcJbw/Y8vHSOqyknslrSrrYPSv7K6iO08xkQ6e4CIdQh6fkie7NgsJqxteYh3fSp3j/l5YNq2nlw@@VJ2U@2CnkcFFnuJpOHQ4NuFUXlEn5P9bDtBCzFnWXNfIlQN22uMrf37c9l1tnR5XcfPbxvdNML7VW9MZF1Ei0Zy34FpsAvUZaJ4mokgXloZOU2CnTwHTAmPBf1AKyeaDdREeGpzsGAiYDA8wAdK0QcvY6R8 "Python 2 – Try It Online") I probably missed a bunch of golfing opportunities, but it's under 1000 bytes at least! I could have used SymPy for row reduction but went for a pure python answer instead. Graphs are represented as lists of edges. `P` generates all paths from vertex 0 to 1, used to determine if any resistors are unused (if they don't appear in any path). `R` accepts a graph and returns the resistance between vertex 0 and 1, or `0` if the graph is invalid (it has unused edges/resistors or unused vertices). It does this by solving a system of linear equations of the voltages at each vertex. `f` enumerates all graphs and generates the distinct resistances as a `set`. `0` from invalid graphs is removed. Here are the results for 1 to 6 (as output by the footer in TIO): ``` f(1) = set([Fraction(1, 1)]) f(2) = set([Fraction(1, 2), Fraction(2, 1)]) f(3) = set([Fraction(3, 2), Fraction(3, 1), Fraction(1, 3), Fraction(2, 3)]) f(4) = set([Fraction(1, 4), Fraction(3, 4), Fraction(4, 1), Fraction(5, 2), Fraction(1, 1), Fraction(4, 3), Fraction(2, 5), Fraction(3, 5), Fraction(5, 3)]) f(5) = set([Fraction(3, 8), Fraction(7, 4), Fraction(4, 7), Fraction(5, 1), Fraction(5, 8), Fraction(7, 3), Fraction(5, 6), Fraction(2, 1), Fraction(3, 7), Fraction(8, 5), Fraction(1, 2), Fraction(6, 7), Fraction(7, 6), Fraction(1, 5), Fraction(1, 1), Fraction(5, 4), Fraction(4, 5), Fraction(7, 5), Fraction(6, 5), Fraction(7, 2), Fraction(2, 7), Fraction(8, 3), Fraction(5, 7)]) f(6) = set([Fraction(1, 2), Fraction(5, 9), Fraction(2, 1), Fraction(1, 3), Fraction(8, 13), Fraction(6, 1), Fraction(1, 1), Fraction(7, 12), Fraction(3, 11), Fraction(13, 5), Fraction(12, 5), Fraction(3, 1), Fraction(1, 6), Fraction(7, 11), Fraction(10, 3), Fraction(3, 4), Fraction(11, 13), Fraction(11, 10), Fraction(4, 9), Fraction(2, 9), Fraction(11, 5), Fraction(10, 7), Fraction(3, 10), Fraction(5, 6), Fraction(3, 2), Fraction(13, 7), Fraction(13, 11), Fraction(7, 10), Fraction(7, 9), Fraction(13, 8), Fraction(10, 9), Fraction(5, 4), Fraction(11, 8), Fraction(5, 11), Fraction(4, 5), Fraction(8, 11), Fraction(6, 11), Fraction(5, 13), Fraction(9, 10), Fraction(2, 3), Fraction(11, 4), Fraction(6, 5), Fraction(9, 4), Fraction(11, 7), Fraction(7, 13), Fraction(13, 6), Fraction(11, 3), Fraction(4, 3), Fraction(6, 13), Fraction(12, 7), Fraction(9, 5), Fraction(10, 11), Fraction(9, 7), Fraction(9, 2), Fraction(5, 12), Fraction(11, 6), Fraction(4, 11)]) ``` ]
[Question] [ (This challenge exists to extend sequence [A276272](http://oeis.org/A276272) in the On-Line Encyclopedia of Integer Sequences, and perhaps create a new OEIS sequence1.) This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), which will have you write code to compute as many terms of this sequence as possible. --- ### Background [![First polytet (achiral)](https://i.stack.imgur.com/F6Mvq.gif)](https://i.stack.imgur.com/F6Mvq.gif) [![Second polytet (achiral)](https://i.stack.imgur.com/q4cWr.gif)](https://i.stack.imgur.com/q4cWr.gif) [![Third polytet (chiral)](https://i.stack.imgur.com/FL6H6.gif)](https://i.stack.imgur.com/FL6H6.gif) [![Fourth polyet (chiral pair)](https://i.stack.imgur.com/lvKQ5.gif)](https://i.stack.imgur.com/lvKQ5.gif) A *polytet* is a kind of [polyform](https://en.wikipedia.org/wiki/Polyform) which is constructed by gluing regular tetrahedra together face-to-face in such a way that none of the interiors of the tetrahedra overlap. These are counted up to rotation in 3-space but *not* reflection, so if a particular shape is chiral it is counted twice: once for itself and once for its mirror image. * \$A267272(1) = 1\$ because there is one such configuration you can make out one tetrahedron. * \$A267272(2) = 1\$ because due to symmetry of the tetrahedra, gluing to a face is the same as any other face. This gives you the [triangular bipyramid](https://en.wikipedia.org/wiki/Triangular_bipyramid). * \$A267272(3) = 1\$ because the triangular bipyramid itself is symmetric, so adding a tetrahedron to any face results in a [biaugmented tetrahedron](https://en.wikipedia.org/wiki/Deltahedron#/media/File:Biaugmented_tetrahedron.png). * \$A267272(4) = 4\$ because there are three distinct ways to add a tetrahedron to the biaugmented tetrahedron, and one is chiral (so it's counted twice). These are shown in the animated GIFs above. * \$A267272(5) = 10\$ as shown in [George Sicherman's catalog](https://userpages.monmouth.com/%7Ecolonel/polytets/index.html). Three are chiral and four are achiral. --- ### Rules Run your code for as long as you'd like. The winner of this challenge will be the user who posts the most terms of the sequence, along with their code. If two users post the same number of terms, then whoever posts their last term earliest wins. (Once more terms are computed, then whoever computed the code can add the new terms to the OEIS or I can add them and list the contributor if he or she desires.) --- 1 A sequence which (presumably) isn't already in the OEIS is the number of polytets up to reflection (i.e. chiral compounds are counted once, not twice). The first few values of this alternative sequence can be found in the George Sicherman link. [Answer] # [Rust](https://www.rust-lang.org/), 11 (hopefully correct) terms ``` use ::std::ops::{Add, Sub, Mul}; use ::std::rc::Rc; use ::std::hash::{Hash, Hasher}; use ::std::collections::HashSet; use ::std::iter; use ::std::fmt::{self, Formatter, Display}; use ::std::time::Instant; type Coord = i128; #[derive(Copy, Clone, PartialEq, Eq, Debug)] struct Vec3([Coord; 3]); impl Vec3 { fn dot(self, other: Vec3) -> Coord { self.0.iter().zip(other.0.iter()).map(|(a, b)| a * b).sum() } } impl Display for Vec3 { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "({}, {}, {})", self.0[0], self.0[1], self.0[2]) } } impl Mul<Vec3> for Coord { type Output = Vec3; fn mul(self, mut vec: Vec3) -> Vec3 { for i in &mut vec.0 { *i *= self; } vec } } impl Add for Vec3 { type Output = Vec3; fn add(mut self, other: Vec3) -> Vec3 { for (i, n) in self.0.iter_mut().enumerate() { *n += other.0[i]; } self } } impl Sub for Vec3 { type Output = Vec3; fn sub(self, other: Vec3) -> Vec3 { self + (-1 * other) } } #[derive(Clone, Debug)] struct Tetrahedron([Vec3; 4]); impl Default for Tetrahedron { fn default() -> Tetrahedron { Tetrahedron([ Vec3([-1, -1, -1]), Vec3([-1, 1, 1]), Vec3([ 1, -1, 1]), Vec3([ 1, 1, -1]), ]) } } impl Display for Tetrahedron { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "Tetrahedron({}, {}, {}, {})", self.0[0], self.0[1], self.0[2], self.0[3]) } } impl Tetrahedron { fn collides(&self, other: &Tetrahedron) -> bool { let mut othervecs = [3 * self.0[1], 3 * self.0[2], 3 * self.0[3]]; let sum = self.0[0] + self.0[1] + self.0[2] + self.0[3]; let mut same = 0; for (i, &vec) in self.0.iter().enumerate() { let sum = sum - vec; let vec = 3 * vec; let through = vec - sum; for (j, &u) in other.0.iter().enumerate() { let u = 3 * u; if u == vec { same += 1 } let up = (sum - u).dot(through); for &v in &other.0[j+1..] { let v = 3 * v; let edge = v - u; let ep = edge.dot(through); if up.signum() != ep.signum() || up.abs() >= ep.abs() { continue } let intersection = ep * u + up * edge; if othervecs.iter().enumerate().all(|(i, &ov)| { let mid = othervecs[(i+1)%3] + othervecs[(i+2)%3]; let ov = 2 * ov - mid; (2 * intersection - ep * mid).dot(ep * ov) > 0 }) { return true } } } if i != 3 { othervecs[i] = vec; } } if same == 4 { panic!("EQUAL TETRAHEDRA IN .collides()"); } false } // Mirroring also scales by 3 fn mirror(&self, i: usize) -> Tetrahedron { let mut sum = Vec3([0; 3]); for (j, &vec) in self.0.iter().enumerate() { if j != i { sum = sum + vec; } } let mut copy = self.clone(); copy.scale(); copy.0[i] = 2 * sum - copy.0[i]; copy.swap(i, 3); copy.rotate_left(i); copy } fn scale(&mut self) { for vec in self.0.iter_mut() { *vec = 3 * *vec; } } fn rotate_left(&mut self, n: usize) { self.0[..3].rotate_left(n) } fn swap(&mut self, a: usize, b: usize) { self.0.swap(a, b) } fn reverse(&mut self) { self.0.reverse() } } type EndpointIter<'a> = Box<dyn Iterator<Item = Endpoint> + 'a>; #[derive(Debug, Clone)] struct Endpoint { tree: Rc<TetraTree>, hedron: Rc<Tetrahedron>, } impl Endpoint { fn iter_endpoints(&self) -> EndpointIter { let mut hedron = Rc::clone(&self.hedron); //Rc::make_mut(&mut hedron).swap(0, 3); Rc::make_mut(&mut hedron).reverse(); Box::new(self.clone().into_iter_directions() .chain(self.tree.iter_endpoints( Rc::new(TetraTree { subtrees: [None, None, None], hedron, }) )) ) } fn into_iter_directions(self) -> EndpointIter<'static> { Box::new(iter::successors(Some(self), |this| { let mut this = this.clone(); Rc::make_mut(&mut this.tree).rotate_left(1); Rc::make_mut(&mut this.hedron).0[1..].rotate_left(1); Some(this) }).take(3)) } fn iter_extensions(&self) -> EndpointIter { let mut tree = self.tree.as_ref().clone(); tree.scale(); let mut hedron = self.hedron.as_ref().clone(); //hedron.swap(0, 3); hedron.reverse(); hedron.scale(); Box::new(Endpoint { tree: Rc::new(tree), hedron: Rc::clone(&self.hedron), }.into_iter_directions().filter_map(|endpoint| { let mut new = endpoint.hedron.mirror(3); new.swap(0, 3); if endpoint.tree.collides(&new) { None } else { let mut hedron = endpoint.hedron; Rc::make_mut(&mut hedron).scale(); Some(Endpoint { tree: Rc::new(TetraTree { subtrees: [Some(endpoint.tree), None, None], hedron, }), hedron: Rc::new(new), }) } }).chain(self.tree.iter_extensions(Rc::new(TetraTree { subtrees: [None, None, None], hedron: Rc::new(hedron), })))) } fn iter_tetrahedra<'a>(&'a self) -> Box<dyn Iterator<Item = &Tetrahedron> + 'a> { Box::new( iter::once(self.hedron.as_ref()).chain(self.tree.iter_tetrahedra()) ) } } impl Default for Endpoint { fn default() -> Endpoint { Endpoint::from(Tetrahedron::default()) } } impl From<Tetrahedron> for Endpoint { fn from(mut hedron: Tetrahedron) -> Endpoint { let mirrored = hedron.mirror(0); hedron.scale(); Endpoint { tree: Rc::new(TetraTree { subtrees: [None, None, None], hedron: Rc::new(mirrored), }), hedron: Rc::new(hedron), } } } impl Hash for Endpoint { fn hash<H: Hasher>(&self, hasher: &mut H) { let mut stuff: Vec<_> = self.tree.hash_helper(1).collect(); stuff.push(self.tree.len()); stuff.sort(); stuff.hash(hasher); } } impl PartialEq for Endpoint { fn eq(&self, other: &Endpoint) -> bool { self.iter_endpoints().any(|ep| ep.tree == other.tree) } } impl Eq for Endpoint {} #[derive(Debug, Clone)] struct TetraTree { subtrees: [Option<Rc<TetraTree>>; 3], hedron: Rc<Tetrahedron>, } impl TetraTree { fn iter_endpoints<'x>(&'x self, behind: Rc<TetraTree>) -> EndpointIter<'x> { let mut iterator = self.subtrees.iter().enumerate() .filter_map(|(i, opt)| opt.as_ref().map(|some| (i, some))); if let Some(first) = iterator.next() { let closure = move |(i, subtree): (usize, &'x Rc<TetraTree>)| -> EndpointIter<'x> { let mut behind = behind.as_ref().clone(); behind.rotate_left(3-i); let mut this = self.clone(); this.rotate_left(i); Rc::make_mut(&mut this.hedron).reverse(); this.subtrees.swap(1, 2); this.subtrees[0] = Some(Rc::new(behind)); for (j, subtree) in this.subtrees.iter_mut().enumerate().skip(1) .filter_map(|(j, s)| s.as_mut().map(|s| (j, s))) { Rc::make_mut(subtree).rotate_left(j); } subtree.iter_endpoints(Rc::new(this)) }; Box::new(closure(first).chain(iterator.flat_map(closure))) } else { let mut hedron = self.hedron.as_ref().clone(); //hedron.swap(0, 3); hedron.reverse(); Endpoint { tree: Rc::clone(&behind), hedron: Rc::new(hedron), }.into_iter_directions() } } fn rotate_left(&mut self, i: usize) { self.subtrees.rotate_left(i); Rc::make_mut(&mut self.hedron).rotate_left(i); } fn collides(&self, hedron: &Tetrahedron) -> bool { self.hedron.collides(hedron) || self.subtrees.iter() .filter_map(Option::as_ref) .any(|subtree| subtree.collides(hedron)) } fn scale(&mut self) { for subtree in self.subtrees.iter_mut().filter_map(Option::as_mut) { Rc::make_mut(subtree).scale(); } Rc::make_mut(&mut self.hedron).scale(); } fn iter_extensions(&self, behind: Rc<TetraTree>) -> EndpointIter { Box::new(self.subtrees.iter().enumerate().flat_map(move |(i, next)| { let mut behind = behind.as_ref().clone(); behind.rotate_left(3-i); let mut this = self.clone(); this.rotate_left(i); let hedron = Rc::make_mut(&mut this.hedron); hedron.reverse(); this.subtrees.swap(1, 2); this.subtrees[0] = Some(Rc::new(behind)); for (j, subtree) in this.subtrees.iter_mut().enumerate().skip(1) .filter_map(|(j, s)| s.as_mut().map(|s| (j, s))) { let subtree = Rc::make_mut(subtree); subtree.scale(); subtree.rotate_left(j); } if let Some(next) = next { hedron.scale(); next.iter_extensions(Rc::new(this)) } else { let mut mirrored = hedron.mirror(3); mirrored.swap(0, 3); hedron.scale(); if this.collides(&mirrored) { Box::new(iter::empty()) as EndpointIter } else { Box::new(iter::once(Endpoint { tree: Rc::new(this), hedron: Rc::new(mirrored), })) } } })) } fn iter_tetrahedra<'a>(&'a self) -> Box<dyn Iterator<Item = &Tetrahedron> + 'a> { Box::new(iter::once(self.hedron.as_ref()).chain( self.subtrees.iter() .filter_map(Option::as_deref) .flat_map(TetraTree::iter_tetrahedra) )) } fn len(&self) -> usize { 1usize + self.subtrees.iter() .filter_map(Option::as_deref).map(TetraTree::len).sum::<usize>() } fn hash_helper<'a>(&'a self, behind: usize) -> Box<dyn Iterator<Item = usize> + 'a> { let sub: Vec<_> = self.subtrees.iter().filter_map(Option::as_deref) .map(|a| (a, a.len())).collect(); let sum = sub.iter() .map(|&(_, len)| len).sum::<usize>() + behind + 1; Box::new(iter::once(behind).chain( sub.into_iter().flat_map(move |(sub, len)| iter::once(len).chain(sub.hash_helper(sum - len))) )) } } impl PartialEq for TetraTree { fn eq(&self, rhs: &TetraTree) -> bool { self.subtrees == rhs.subtrees } } impl Eq for TetraTree {} fn main() { let verbose = std::env::args().skip(1).any(|arg| arg == "-v"); let begin = Instant::now(); println!("1: 1 [{}ms]", begin.elapsed().as_millis()); if verbose { println!("{}\n--", Tetrahedron::default()); } let mut polytets = HashSet::new(); polytets.insert(Endpoint::default()); for i in 2.. { println!("{}: {} [{}ms]", i, polytets.len(), begin.elapsed().as_millis()); if verbose { for polytet in &polytets { for hedron in polytet.iter_tetrahedra() { println!("{}", hedron); } println!("--"); } } polytets = polytets.iter() .flat_map(Endpoint::iter_extensions) .collect(); } } ``` [Try it online!](https://tio.run/##vVrrb9vIEf8s/xUbF3XIWKYt6z4UlCwgTXJIgN4rcfvFFQxKWlnMUSSPSzr2Wfrb05nZN0VFvmvRAFbIfcxrZ34zs1LViPrr16NGcBbHol7EcVGKOH56vVj02adm1mc/NNl25C6o5nH8ce4NrRKxgk3v4b8@w09e@XvmRZbxeZ0WORDHBZ947S1Ia155A8t1DRQFz5Z99n1RrZMaVvTZ21SUWfLoU6/TNY/jD7mokxzIHtWPJWdviqJasCuWDi7/BmN/uVnwKr3nwZuifOyzN1mR8z77OanqNMne/dZn@PeWz5q7cHok6qqZ1@xffD4MbojQiA2nIZBJ12VG4@zpqLfM2aKoAylkUYPWMc2F7Gyi@MOqHs5HFxGqGITR72kZ0FozFEbrpAw2QdJns3DDEvYK/o9Esw7Co972aKu4KtXZsqhcCcBQwYkUYRmzk3VTW3uRIGTJj1w0WU3ifKmA7YsA1h8HT9s@k3/hcZ9JQW8upuZxYB8vp5404BZjlGJC8hhlyfQ/NXUJYlyRmGA0FHPdZMpQKOE9nzum0tr0kFTK0lyqAYuiCxrvvUrZqyuSZASvW/iDSVcc8FfPMHvlSBaLAIl3H5onSZD2WR6iOM4J3sJmOEWeN2teJTUPQiVhzk6vmDrYm3Sq5cStrqAQU88TVDSz4ICQOM1OWXA2AJehVfqIrLdLP2859jWvq2TFF1WRBzfEk31n3fstXyboLCims1J7vJwNSJTWdM8jjGaRIXQ26DP5Nw37/jCjP2@YqdUdw8whMt0bHbtC/zdB4upk4@WZMWMeh764uyIiRKYLLrSc6tRPnJUk6awoMhIx4zXFEi2EcBDgPzdD8ARHDuf10n8dTslFkQggDbuyioBHGQr2@dJ5HpqtFEnJmsP@C/RbEzcnIFA7dLrCxuEPn2cY8yM9Ds8wjjK7o/WqKpq7Fczg/Bnuozni/Bk4N8TXh9hdxkSrUfQbotBLlzgiCT9JvSCmB2xrN5SwI5CiNmGE6K/kCSUJlOLkniBMY8Hn00EUTRVXqZhWa2TH@OIOrXiPhN1hZIhzLV5yBQpcRiK9yzFZsBew1HndbHA2mQl4ntCUfFaS9OZFXqd5w@Xr9shyTXOwmpAJG/mXaCM4/wYfUJqR4W@8r8PSUZJlkNfQHYp7yGyaMXlOisnZ7L4J0tNB@Nchepk3eImDI2djgda7RMBDWwEZPRngoCf5mZQc1sijojeQhE3YhVLaWqPidVPlDADSGMR8StuAtinaGMDXkTGdSlcckZvgH6yTMXHFvoOlZZKn8xfB8btf/vn6H@z63fXH1@/fvf34mn34kUUm6sPjUFJYJpngR8Ty/Jz9kFZVUaX5HYPhgol5knHBZo9sKLMqTWvISGPWiPR33gnNJlwp2iSkXqiyxomeZ8Yt6PgZbZFioJj4PXUN4fCcQ82lIWaOGSkgpjgckUqBdGkauJAmxdOUgWZG7Z4vUDCBWw0tmaqoQbzbjC/rILXUpCExnRKbE536Q5PlMdi7UrxK6xaEXikU2hqaLs8TW1Tk5hhs9XcTRcOpJ2QeWtlQHYdAoghAPdhBSmpPxaKVhN@j27f1Uxv0rM5AVHO8yxdlAeHyATQev0wmoOXfi4fx4jFnOJTURTWGBzxavXQCBwwr3WqaCgtVTtv6Qm@gAqfiPGYf52NyyGt4m0D2lo5px@U7zOgE6ZIABelcuBpTOZLc3FXD83Pl@lfAAvoPcjraFalcikd5fo6T6@RXTmd@YveF0soX2sf2rzPGJZ8DE8Zxzr8Erq9HIF9xSyos0kr1QXgavV40XyVpLlejpaKWooRByBxpGgtq0IIaETeJmN38SHWe/Zz25RIppnzZEssQP63rdMrWad7xS2iw6nQ@IfZGU9wLjVgzn3MhikoEn4o1lxT6bFOvUrGxuR4th0NwLvifiwYdNqYlqGHohc7gm@v1wUD9Anm3ayMJiGvREtswqoFIMAwdm9AhPNQ8F2SOZ7gbSqkhjg4yEbcVX8LhOyrShAt4O87qeGgnhfNzNem7pxp0fNGMuezMmbnR1TMhKufI3uQwNkg7IwjXbPf4drRMM4JS7Gy1O7f8AJhhcaEmtdYqpUm9erCmpSqmHrOHDGorZ1itEzrGAKVuxiGfOjWfZ@4W85EJtz2Y4NhSuZFvybYtdyLWDVna76kSdkWwF8Lgrl5gW1aouxvmW@nb3fhiXXuPpAeRpc3e9YkwbMdSrTE@wVQTnLxMZJY66jGMqn2Jx21@VPLxsQeeGZMAVORziTrt8NljAytSYBFx29ECtzKR1/96p69f4nhZFevAkT2OzS6Pzfewzst/XQyJmPXCmLU7Qk8IWVtjCHEssP2gutgHDN/Cg7YPH046bd/Q8kj/3IYHHci1Ed4WdpkF7xzH72N13TjRNfCKXlWP/z70S9@6WS7pImV8O/HAGnfdrnhWQrU7CCN1XSlxlHZFZSNWjgtlPIeztNOQ@LzlSDCQsuCoVcfcOHbpxH9rd/96gd/6kxytSgG6rfwRsLbcYKcn05G@kCJscaXYYb89WNN5buD4wE8lQv7YK/Am2Fc8p8rziO6UeeOXD4gVD6osnvFVmi9atWRHlfIw8U49VaCiD1zL3tHbEJx4qQu7jKKsoXmFT5uRaU4Afm/otgOfwlCGEqQn5EzgvkwrAUd3ZWSIcoBe9@4D0qpoKqwc1sU9Z8RPCRjGLFBtANrA13qzV22ruLQXkJYPnfVEr6cm3TJpeJbqHNeq2dodHGAFllwdzdfB8syvmxUhczaU8wd9dumy0bN4SXUlLazRQ2oRamK6ndWmxA7PZ9B9lxuJX1PgSwl0xxWQHhheoCHlTukGG8kKHEBneU91LYNnpc9KL3Xrota0Y9qUZFiryqxO20z@U@6jHE0lOuNsyyypSXa1jNKyVxH94fpzXwHaWYG20oqTV1Q1qU6tO2s4CWFvmfmcdjzd7aGNF7Qdt8tr3ZJ3d4Pi3b691crsv751LW1264WbDUFRF17RhO@aEoLjWB6YWUH5QO3e6FDY4RUeviJRW801SVcQdYsDcyooukPC1CCyXj1gfLv6W33acxOFX0keSg02mCxQI5iHrabmWaD7Tcw9BLl7ERc3erce@9F3T8geHcLhPwbD/wsU/tMgLL9ZmKm@vNP9Rh72Or5oBzsw21wGmzRPfgBM8H/FvV1j96iXfaj39l8OxHd1rHtLegW/Pb2gjctd1T5JL69fDGyZGl3nsNb9Dl@X9SOUvCwRXhTJLOaK3N5JjVm7TW7fOaD2fr@7r32g/tK9mlcD/49285md5p/Ebii/HfQ2eGMgTP5KwlGO2larOvYk9qaKch6JP5CPp98S6YBQUUsQYEW/UIjjMRGfBFYMp5fyrG9xWabjA4ch6TqnoAK63b@1MfugbSVgJAAYSZ8lqpNr9Xzu15Iz11Jy80lw20dzAxB1WAJkVlnglA1Ge/xHIaX1mB5x0lVOR8IR@GscYipx0f5zyJI46r4D6Ll9rfwyBReE1nG629J2W2b70moldFFzTZC@U9Lo88DuE1ab947202EDM/h1FspNCCS//61mhaBbVfyVD8/v4SirO2EThCxxYGzD4AM5Hp/dH@MJ4v4Zv0sxFaofBsERFF8kApYVGDrLXwTHg5gN2M3Tdi2mx325I@JZUgq@wI4ackwKCClkrw@oqWVCdS2Vp@2/87MzILDnzkdVLBrMyyJ7hCjG7K5@CyXdA9fpOXAFwas6sJdKLrkj@1OZyyjakSYGg1qtoFIxVMnbDykqu1hXVWKniNCX20aFJ9NvqdIDZtXk7j2bRn9X1mNdLJuOyF8BdtV5V@Vex3zWWk6ImsCxtmtlXbXQDXl0Tvk7OPsruLcIGvh7sipJa/Za0PtY4RF9iXYNbgenBxg1kr8uUkhjUw4GyCd4iGO5dqSDAOiAv@BWgAmiPPFYoEnV3cp1myForqaQz/gak7IkodlMniuPDVz/cgPwMYnkXoUUX/8D "Rust – Try It Online") The footer contains some compatability implementations because TIO's Rust is a little old. (This has already been [reported](https://chat.stackexchange.com/transcript/message/54872387#54872387) and added to the [list](https://gist.github.com/cairdcoinheringaahing/46f79623ea7b5cfe67286d0a5e96d307).) Output: ``` 1: 1 [0ms] 2: 1 [0ms] 3: 1 [2ms] 4: 4 [8ms] 5: 10 [35ms] 6: 39 [139ms] 7: 164 [738ms] 8: 767 [4328ms] 9: 3656 [31298ms] 10: 18186 [287871ms] 11: 91532 [3154716ms] ``` As you can see, it also reports how long it took. (These are cumulated times.) You can use the `-v` option to list all tetrahedra for each polytet. I don't really have a good way of verifying the results beyond A267272(5). I hope it works, but I'm not sure. The idea is that we store the polytet as a tree of tetrahedra that also encodes orientation. But for collision detection we need actual tetrahedra. We start with the tetrahedron with vertices (-1, -1, -1), (-1, 1, 1), (1, -1, 1), (1, 1, -1) and scale all tetrahedra by 3 for every term. This avoids the need for fractions. Can probably be made faster, but I don't know how. ]
[Question] [ In [@Adám's](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m) [Dyalog APL Extended](https://github.com/abrudz/dyalog-apl-extended), the `⍢` (under) operator means conjugation: apply one function, then a second function, then the inverse of the first. It's fun to think of real-life actions in terms of conjugation: > > A problem is transformed by g into another domain where it more > readily solved by f , and then transformed back into the original > domain. An example from real life is “under anesthetics”: > > > > ``` > apply anesthetics > perform surgery > wake up from anesthetics > ``` > > ## Challenge The inverse of a line `g` is "un" prepended to `g`, and vice versa. Define any line between `s` and its inverse, in that order, as being "under" `s`. For each line `f` in input in order: * If `f` and its inverse both occur, do nothing * If `f` is not "under" any other action, print `f` * If `f` is "under" a line `g`, print `f + " under " + g` where `+` is concatenation. ### Input A nonempty multiline string, or list of strings, etc., consisting of spaces and lowercase letters (you may instead use uppercase). Exactly one line will begin with "un"; and it will be the inverse of some other line. No line will be empty. ### Output Output in the same format you took input in, or as allowed by Standard I/O. ### Test cases: ``` Input: apply anesthetics perform surgery unapply anesthetics Output: perform surgery under apply anesthetics Input: unite asia establish the silk road ite asia Output: establish the silk road under unite asia Input: desire a book walk to store take the book pay for the book unwalk to store read the book Output: desire a book take the book under walk to store pay for the book under walk to store read the book Input: drink excessively undrink excessively Output: [empty string] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 90 bytes ``` ;Ṡ{hhH↰₂gB&hb~c[A,B,C]&tT;C↔↰U∧" under ",H,T;A↔↰,U|tT&hh,TgJ&hb;T↰Q∧J,Q|h} ~↰₃|↰₃ ∧"un";?c ``` I made this while being under the impression that this could be recursive and multiple unders could be stacked. Probably not optimized. Also as this is bracylog, plumbing takes quite some bytes. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3/rhzgXVGRkej9o2PGpqSndSy0iqS4521HHScY5VKwmxdn7UNgUoF/qoY7mSQmleSmqRgpKOh06ItSNEQie0piRELSNDJyTdC6jXOgQoFghU7KUTWJNRy1UHNre5BkJxgUwpzVOytk/@/z8ayCrOSU0tUNJRUEpJLc4sSlVIVEjKz88GCZQn5mQrlOQrFJfkF6WCBEoSs1MVSjJS4SoKEisV0vKLUMRK8zD0FaUmpqCogdgZ@z8KAA "Brachylog – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 82 bytes ``` m{A`^(un)?(.+)¶(?(1)|un)\2$ ^((un)?(.+)¶)(.+)¶((.+¶)*(?(2)|un)\3)$ $4 under $1$1$5 ``` [Try it online!](https://tio.run/##ZY5BTgMxDEX3PoUXs0hAQpoC64p7VBVuY2g002RkJy0jeq4egIsNplQtqPLC@v8/61u4xETtNG0/X16XriY/dw/3/uvo5q71B9OLWQNL9yfxZ8CWiTsDZ7/go2@gecKaAgs2rc3zNNEw9CNSYi0b61orDCxvWbaoVd5ZRqjpljEzFkbSSGAurfqoG7QUNfYdSqYAFwACaxQTuMq5gz0ZUTJqycJQqOPT4SkbaEQrvxo1/ceFKVxTCBJTh/yxZtW44/7n2xvvGw "Retina – Try It Online") Link includes test cases. Explanation: ``` m{ ``` Run the whole program in multiline mode (so that `^` and `$` match the beginning and end of individual lines) and repeat until there are no changes. ``` A`^(un)?(.+)¶(?(1)|un)\2$ ``` Look for lines that might begin with `un` and are followed by a line that begins with `un` only if the previous line does not while the rest of the line is the same, and delete both lines. (This is a change of behaviour from Retina 0.8.2, which splits the lines before trying to match and therefore can never delete lines if the match needs to span more than one line at once.) ``` ^((un)?(.+)¶)(.+)¶((.+¶)*(?(2)|un)\3)$ ``` Look for lines that might begin with `un`, followed by at least one line, followed by a line that begins with `un` only if the original line does not while the rest of the line is the same. ``` $4 under $1$1$5 ``` Move the original line down one line, and also append it with `under` to the line just traversed. (Additional lines will be handled by the repeat.) [Answer] # [Python 2](https://docs.python.org/2/), 106 bytes ``` s=input() x='' l=[] for i in s: if'un'==i[:2]or'un'+i in s:x=(' under '+i)*(not x) else:l+=[i+x] print l ``` [Try it online!](https://tio.run/##ZY47CsMwEER7nWK7teNULg06iVCh4DVZLFZCHyKfXokhJIGU8@YNTDzKPcjce9YssZZhVE0jKq@NVVtIwMACeVHAG1ZBrdkssw3pDNO7bHpAqLJSghcbL4OEAm1UQD7T4idteGpWxcRSwPducKXMicDBLYQdr4AP53coAXIJiU5Q3E5Q7vQxojvgPPTLqvztErn169gn "Python 2 – Try It Online") If the input can be a list from STDIN and the output be newline-separated, we then have this 94-byte solution: ``` s=input() x='' for i in s: if'un'==i[:2]or'un'+i in s:x=(' under '+i)*(not x) else:print i+x ``` [Answer] # [JavaScript (Babel Node)](https://babeljs.io/), 91 bytes Takes input as an array of strings in lowercase. Returns another array of strings. ``` a=>a.flatMap(s=>s==r|'un'+s==r?(u=u?'':' under '+s,[]):s+u,u='',r=a.find(s=>/^un/.test(s))) ``` [Try it online!](https://tio.run/##dZBBbsIwEEX3nGJ2jkUIeyTDCXoCRKVJMgE3rh3N2LSRevfUaSSQCuxGf977GvsDrygN2yFuaqzJbXxoaerMhGaPVecwvuFQiNmLMfyjklfreToUyaSDUjsFybfEkOPyeNI7WacyGaVKNlm3vp3d7Xvy2yqSxEK01lMTvARHlQvnoiuOKwCFw@BGQJ@ZC0XbiCrneCDuAn@CJD4Tj0uY/CO9Omm9etKbvI0EKBYXNxtYOysXyCaIdT1wwHZZ3tBXbS2J5cxAHUK/OF@YK2IAiYFpiSL29Fd/pwYcIT/kX5r8E5sJ2zv38hK2vgf6bkjEXsndvuZxMVdMvw "JavaScript (Babel Node) – Try It Online") ### Commented ``` a => // a[] = input array a.flatMap(s => // for each string s in a[]: s == r | // if s matches the reference string 'un' + s == r ? ( // or its opposite: u = // update u: u ? // if u is not an empty string: '' // turn it to an empty string : // else: ' under ' + s, // set it to s with the ' under ' prefix [] // yield an empty array so that this entry is removed ) : // else: s + u, // yield s followed by u u = '', // initialize u to an empty string r = a.find(s => // initialize r ... /^un/.test(s) // ... to the string beginning with 'un' ) // ) // end of flatMap() ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 147 bytes ``` import StdEnv,Data.List a=inits;b=tails $l=hd[w++[e++[' under ':u]\\e<-z]++y\\i<-a l&t<-b l,w<-a i&u<-i,z<-a t&[x:y]<-b t|u==['un':x]||x==['un':u]] ``` [Try it online!](https://tio.run/##bZDPjoIwEMbP8hQT1/gngA/A0pt7MDFxE4/QwwBVG0sxdCpiePZlAVfdTfbQZL5@v/lm2lQJ1G1eZFYJyFHqVubnoiTYUfahL94KCZcbachBJrUk854wQqmMM1HsmEWV60aiOzOwOhMlzALL41iE/o27bh3HMvQR1JRCPwHlVb2SUxv60rv1NU2ja1Dz3qXGMhbNrJ4FV94014ewnD93qg2JfLneOjvCTlfO6A3mSmphPKgWwOAgaNPL3mKwV0iDC/MJDMXCqY6iFM7oN/gI@ckQF1Tr7SNqAJqhGxiD8bgj5hHv2Vfnf@NHPRelEMeQQugHQwQPBpx71aLNhJGlAISkKE5OheoEVIChotuP8CSAjuLunbGGfVG@Lqz@i5cCs6f7lXbvPpjWX2/aVa0xl@ldfHbf0cXkrZ98Aw "Clean – Try It Online") ]
[Question] [ Let's define a simple language that operates on a single 8-bit value. It defines three bitwise operations (code explanation assumes 8-bit `value` variable): * `!` Negate the least significant bit (`value ^= 1`) * `<` Wrapping left-shift (`value = value << 1 | value >> 7`) * `>` wrapping right-shift (`value = value >> 1 | value << 7`) ## Input: Two 8-bit numbers, *a* and *b*. As they are 8-bit, you can alternatively take them as characters. ## Output: The shortest way to get from a to b, with the three operations defined above. You can return a string or an array of characters, or define a constant, distinct values for each operation and return an array of those (yes, you could also say `<` means `>` and `>` means `<`), but please explain your output format in your answer. If there are multiple, equally long ways, you can output any or all of them. ## Rules: * You can submit a program or function * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply * The submission with fewest bytes **in each language** wins (no answer will be accepted) Solutions without brute-forcing (or at least not only brute-forcing) might get my upvote. ## Test cases: ``` 12, 13 => '!' 1, 2 => '<' 254, 253 => '<' 5, 5 => '' 98, 226 -> '<!>' 64, 154 -> '!>!>>>!>' 177, 164 -> '!>>!>>>!' 109, 11 -> '>>!>!>>' 126, 92 -> '!>!>!>!<' or '!>!>>!<!' 26, 85 -> '<!<<!<!<' or '<!<<!<!>' or '<!<<<!>!' 123, 241 -> '!>!<<!' or '>!<!<!' 236, 50 -> '<<!<!>' or '<<<!>!' 59, 246 -> '<<!>' 132, 95 -> '!<<!<!<!' 74, 53 -> '!>>>!>!' 171, 127 -> '<<!<<!<' 109, 141 -> '!>>>' 185, 92 -> '!>' 166, 201 -> '!<!>>>' or '<!>!>>' 77, 155 -> '<!' 124, 181 -> '!<<<<!>>' or '!>>>>!>>' 108, 85 -> '!<<<!<!<!<' or '!<<<!<!<!>' or '!<<<!<<!>!' or '!>>>!>!>!<' or '!>>>!>!>!>' or '!>>>!>>!<!' 185, 144 -> '<!<<!<!' 70, 179 -> '<<<!<!>' or '<<<<!>!' or '>>>>!>!' ``` [Here](https://tio.run/##fVHRToMwFH3nK85IEIi4DOKcWSif4A8YzRh0rgbaputmTPx3vC1saqL2hXLPOfeee6rf7V7JYhhEr5WxMLVsVZ9BWG6sUt0hCFq@g5D0rw23SZ1hm6FRLU/XAeicwFDDX3fKENL3RPeMkeCO2I0AY4hn8ZpEzwz5Bebdd0LpCQzJCWWJHFcolrcpPqhYVVj9oaomlSflxB7lK5LnxX3qVbTA0UhHY9gGgfMrnFna@oUnQuqjTdJpr5p6jWnM3WekFMu7sdP2X7TjkvDFmEqjjOGNpcKDktyX3vai45DKnsGvpL7Yjy7CKVO6kM3Lo8y1Ue2xsUk4K6swo700ry2jsamL@tfXerqMcO6uz/FrQ2yEUZshanFTITqEiDApY9D4eP6qhEw28XTx7TY/nE2u03QYisUn) is a program to generate a few more. [Answer] ## JavaScript (ES6), ~~100~~ ~~96~~ 86 bytes ``` f=(a,b,[c,d,...e]=[a,''])=>c-b?f(a,b,[...e,c^1,d+1,c/2|c%2<<7,d+2,c%128*2|c>>7,d+0]):d ``` ``` <div oninput=o.textContent=f(a.value,b.value).replace(/./g,c=&gt;`&lt;!&gt;`[c])>a: <input type=number min=0 max=255 value=0 id=a> b: <input type=number min=0 max=255 value=0 id=b><pre id=o> ``` Somewhat slow breadth-first search without double-checking. Slightly more efficient 114-byte version: ``` f=(a,b,c=[],[d,e,...g]=[a,''])=>c[d]?f(a,b,c,g):d-b?f(a,b,c,[...g,d^1,c[d]=e+1,d/2|d%2<<7,e+2,d%128*2|d>>7,e+0]):e ``` ``` <div oninput=o.textContent=f(a.value,b.value).replace(/./g,c=&gt;`&lt;!&gt;`[c])>a: <input type=number min=0 max=255 value=0 id=a> b: <input type=number min=0 max=255 value=0 id=b><pre id=o> ``` Both versions encode `<!>` as `012` but the snippets decode this for you. Edit: Saved 10 utterly useless bytes thanks to @RickHitchcock. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes ``` ṃ“ṙ1“ṙ-“¬8¦” +⁹BḊ€0ÇẎv¥⁼ƭƒ@¥1#ḢÇ ``` [Try it online!](https://tio.run/##y0rNyan8///hzuZHDXMe7pxpCKF0gdShNRaHlj1qmMul/ahxp9PDHV2PmtYYHG5/uKuv7NDSR417jq09Nsnh0FJD5Yc7Fh1u/3@4/eikhztn/P8fbW6go2BobhkLAA "Jelly – Try It Online") **<**: `['ṙ', '1']` **>**: `['ṙ', '-']` **!**: `['¬', '8', '¦']` Note: This is a function, that's why the footer is there. Brute force. :( [Answer] # [Python 2](https://docs.python.org/2/), 111 bytes ``` l=[input()+('',)] for(a,b,i)in l:a==b>exit(i);l+=[(x,b,i+y)for x,y in zip((a*2%256|a>>7,a/2|a%2<<7,a^1),'<>!')] ``` [Try it online!](https://tio.run/##FcrdCgIhEEDh@57CLhZnciCU/ij1RZYNXCgSxJUw0Nh3N7s7cL5U82uJqrVgRh/TJwMK4Jxw2jyXNziayaOPLFydMbN9FJ/B4y0IM0L5T1GxQ1aoss6@PgG4nRrU8bQ6a8/k9mp1g9K6510icW23HKfWpDoQkxf5Aw "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 105 bytes Takes the 2 bytes in currying syntax `(a)(b)`. Returns a string with: * `0` = `!` * `1` = `>` * `2` = `<` or an empty array if **a** is equal to **b**. ``` a=>g=(b,m=1)=>(h=(n,s=[])=>n^b?s[m]?0:h(n^1,s+0)+h(n/2|n%2<<7,s+1)+h(n%128*2|n>>7,s+2):r=s)(a)?r:g(b,m+1) ``` [Try it online!](https://tio.run/##fZLJbsIwEIbvfYrhUMUuaYidOAuKzYMgKoWWVcWpCOqp707HrrMgORU5MKNvFv/zn@vvun2/nr5ur7r52N338l5LdZBkG14ko1KRoyQ6bOV6g4F@267a9WWzipdHot9Y2M5jOse/C/6jn3lV5ZhhNvPMePGCWaVMjtPlVbaU1HR1XR5Mc8Tut117AwmkDmFLQSpYR1G0R4hs6Sa61F9Em2wwU1WwnusNjc7NSZMgoE9P741um89d9NkciOlDgPEQgCWUwmKBNYEHAYYIcIdUHoSLNAQukn8QAGG6CIf4iLLAJjzrmsyUD8pwEhNpt6@aKaW8JMtzJLOB/EN9ZFwaDZgjDYioD@QZgiUfDcdfFUBzdavMKq@Ctq4Q/csq/Lo6F6khwsC7Jk9Qn5QN05H8qzJzvZN5YiaLuJs8njQ1B0Rp5mRDjVeLxBin7N7knuTtl6dmh2Q4hJp4YI5GYzwfLWtUmjgYGynhv1YhHq/lYzLUh8d9p8r2cpeYcAFYY4nhmt5bGZsWQ1@rtuqcYiXw7hMXY6dYM4y80sdqHNs79p0fPeliNY4nXGr1Ymn66FKvADGCednf6dFVwzrKnfr@Cw "JavaScript (Node.js) – Try It Online") (with codes translated back to `!<>`) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~201~~ ~~199~~ ~~198~~ ~~196~~ 193 bytes * Saved two bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat); golfing `a/2+a*128` to `(a+2*a*128)/2` to `a*257/2`. * Saved a byte; golfing `a*2+a/128` to `(a*2*128+a)/128` to `(257*a)/128` to `257*a>>7`. * Saved ~~two~~ five bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat), golfing the return type. # [C (gcc)](https://gcc.gnu.org/), 193 bytes ``` *P,D,Q,j;f(a,b,d){if(a&=255,Q&&a==b)for(Q=j=0;++j<D;printf("%d",j[P]));Q&&++d<D&&f(a^1,b,d,P[d]=1)&f(257*a>>7,b,d,P[d]=2)&f(a*257/2,b,d,P[d]=3);}F(a,b){for(D=Q=1;Q;D++){int p[D];f(a,b,0,P=p);}} ``` [Try it online!](https://tio.run/##dZFbb6MwEIWft7/CWNqAwdVig7nU2PtC@xy0b0lTiRKlm0jLRlHfovz27Jh7aBZQNLK/nDkzp3r8qKrr1V3SnBb0IHdOSd/plpz3UC0UF4IWi0Wp1DvZ/T05hTooX3reIcvl8bSvP3cO/r7F9LBebgiRgHreNssXC/j3GzNKdLnebhQjcMJF7JZax@MxN8elCxc/@HgaEHl5MT7I2fTMVaGYLGTueWCr/kTHdb7pjPp0qY6AX66/HHLuHSF4MJw@O9Xv8uSuxpvXOnvU5s4IS3clVyA6DFJh6q6Usi37p83sp6bOoOZdraEO7Cf4JXJUfK1Nr4c/5b4GDw/fwIl8cRDjFCEGszw72GosNQ@RA4EYEIg3RHaP4CKkiIvg/wRCwmiIhhiBKZEmoMGjVsPS@CsRQRcmwtaptrTWDTYSLI6BiHqiRW4JPzXTsoYwACD4pgvjERApH7rAm91ooIZIROc0g29GMB7ALCHrNQDBs40FRkP4rYZR0DMCidRoRD3RL2TSJTDJpa2PzsbttCgOTZeg34eZZTZtDNkyHg8@2lHmG2PDLPqOj0RMN4a/ZssimJb7nUY2qEydmuREv9N7Gtykn/QamVnJLH0/GXMxhNUmM3PKwnCaHJ758IGI024fQzBAXK7/AA "C (gcc) – Try It Online") ]
[Question] [ ## Introduction Sometimes I get bored and there are no new questions on PPCG, so I want you to dig a random question from PPCG's past. ## Challenge Given a user's PPCG ID as input (e.g. my ID is *30525*), output the URL of a randomly chosen PPCG question. If the question does not meet the following criteria, you must choose another question until it does meet the criteria: * The question asker must not be the user whose ID was inputted to the question * The question must not have already been answered by the user whose ID was inputted to the question * The question must not be unanswered: it's probably too hard * The question must not have over 10 answers: it's probably too easy * The question must be tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ## Rules URL shorteners are disallowed. You may use the Stack Exchange API and the Stack Exchange Data Explorer. You will only ever be given a real PPCG user's ID. In the unlikely event that there are no suitable questions, you do not have to output anything (undefined behaviour is fine). ## Side Challenge Although you won't be awarded extra points, it would be appreciated if someone designed a ***usable*** bookmarklet which, when run, opened the browser window to a random PPCG question that follows the above criteria. The user ID should be hardcoded into program (for the bookmarklet *only*). ## Challenge The shortest code in bytes wins. [Answer] # JavaScript (ES6), ~~333~~ ~~329~~ ~~327~~ ~~323~~ 283 bytes Needs to be run from within the `api.stackexchange.com` domain ([relevant meta](https://codegolf.meta.stackexchange.com/q/13621/58974)). Returns a `Promise` containing the URL ([relevant meta](https://codegolf.meta.stackexchange.com/a/12327/58974)). ``` f=async i=>await(u="/questions/",s="?tagged=code-golf&site=codegolf",q=await(await(await fetch(u+s)).json()).items.filter(x=>x.owner.user_id!=i&x.answer_count<11).sort(_=>.5-Math.random())[0],await(await fetch(u+q.question_id+s)).json()).items.some(x=>x.owner.user_id==i)?f(i):q.link ``` --- ## Try it ``` f=async i=>await(u="//api.stackexchange.com/questions/",s="?tagged=code-golf&site=codegolf",q=await(await(await fetch(u+s)).json()).items.filter(x=>x.owner.user_id!=i&x.answer_count<11).sort(_=>.5-Math.random())[0],await(await fetch(u+q.question_id+s)).json()).items.some(x=>x.owner.user_id==i)?f(i):q.link k.previousSibling.value=58974 // me k.onclick=_=>f(+k.previousSibling.value).then(p=>k.nextSibling.innerText=p) ``` ``` <input type=number><button id=k>Fetch</button><pre> ``` --- ## Bookmarklet And here it is as a customisable bookmarklet, which will load a random question you've yet to answer. To use it, simply add a new bookmark to your browser's toolbar and drop the full code into the URL field. Unlike the above solution, this works with all questions on a site therefore it may be slow to run (depending on the site and tags) and could also be expensive in the number of queries it needs to make to the API, as the API can only return 100 questions at a time. To customise, change the following variables * `k`: Your API key - you can register for one [here](https://stackapps.com/apps/oauth/register). * `s`: The Stack Exchange site you want to grab a question for. * `i`: Your user ID on that site. * `t`: The tags you want to filter by. There are 4 options available for this one: 1. `""`: An empty string; if you don't want to filter by any tags, 2. `"code-golf;string"`: A semi-colon separated list of tags you want to filter by, 3. `prompt("Tags:")`: You will be prompted to enter the tags you want to filter by, or, 4. `prompt("Tags:","code-golf;string")`: You will be prompted to enter the tags you want to filter by, with a default list provided. ``` javascript:(f=( /* See https://codegolf.stackexchange.com/a/122400/58974 for documenation */ k="", s="codegolf", i=58974, t="code-golf", p=1,q=[],r=1)=>fetch((u="//api.stackexchange.com/questions/")+(d=`?key=${k}&tagged=${t}&site=`+s)+`&page=${p}&pagesize=100`).then(r=>r.json()).then(j=>r&&(q=[...q,...j.items.filter(x=>x.owner.user_id!=i&(a=x.answer_count)&a<11)])^j.has_more?f(i,k,s,t,p+1,q,1):q.sort(_=>.5-Math.random())[0]).then(y=>fetch(u+y.question_id+"/answers"+d).then(r=>r.json()).then(j=>j.items.some(x=>x.owner.user_id==i)?f(i,k,s,t,q,0):window.location=y.link)))() ``` [Answer] # PowerShell, 261 Bytes ``` param($i)$q=irm (($u="api.stackexchange.com/questions/")+($s="?tagged=code-golf&site=codegolf")) do{$t=$q.items|?{$c=$_|% an*;$_.owner.user_id-ne$i-and$c-gt0-and$c-lt10}|random}while((irm($u+$t.question_id+'/answers'+$s)).items.owner.user_id-contains$i) $t.link ``` Explanation: ``` param($i) $q=irm (($u="api.stackexchange.com/questions/")+($s="?tagged=code-golf&site=codegolf")) #run this query do{ #until we find a valid question, get a random one that fits the basic specs $t=$q.items|?{$c=$_|% an*;$_.owner.user_id-ne$i-and$c-gt0-and$c-lt10}|random }while( #Get all of the answers, and their owners into an array, check it doens't contain the provided id (irm($u+$t.question_id+'/answers'+$s)).items.owner.user_id-contains$i ) $t.link #output the question link ``` add 4 bytes for a version which opens it in webbrowser ``` param($i)$q=irm (($u="api.stackexchange.com/questions/")+($s="?tagged=code-golf&site=codegolf")) do{$t=$q.items|?{$c=$_|% an*;$_.owner.user_id-ne$i-and$c-gt0-and$c-lt10}|random}while((irm($u+$t.question_id+'/answers'+$s)).items.owner.user_id-contains$i) saps $t.link ``` ]
[Question] [ # Introduction Here in Germany the ruling on work times is very strict. If you work 6 or more hours a day, you have to take at least a 30 minute break. If you work 9 or more hours, you need to take a 45 minute break. If you work less than 6 hours, you don't have to take any breaks. Of course you can split those breaks, but each part has to be at least 15 minutes long to be counted. # The Challenge In this challenge you will get a list of work periods and you have to check if enough breaks were taken, using the following rules: Let `w` be the work time in hours: ``` w < 6 -> No breaks needed 6 <= w < 9 -> 30 minute break needed w >= 9 -> 45 minute break needed ``` Additionally, each break has to be at least 15 minutes long. Also you can always take more breaks than needed. Those are all "at least" values. # Input Your input will be a list of work periods. The exact format is up to you, but it has to contain only time values as hours and minutes. **Example:** Format here is a list of tuples while each tuple represents a working period. The first element in a tuple will be the start time, the second one will be the end time. ``` [("07:00","12:00"),("12:30","15:30"),("15:45","17:15")] ``` This results in a total work time of 9.5 hours and a total break time of 45 minutes. Note that those working periods don't have to be separated by breaks. There can also be working periods which just follow each other (example see test cases). Also note that breaks don't count into the working time. Those are two separate values. You may assume that the working periods are ordered. # Output Given this input, output a *truthy* value if enough breaks were taken and a *falsy* value if not. # Rules * Specify the input format you are using in your submission. * You don't have to handle empty input. There will always be at least one working period. * The working periods will only span one day, so you don't have to handle work over midnight. * Date-/Time-/Whatever- Builtins allowed, as long as it comes with your language. * Function or full program allowed. * [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tie-breaker is earlier submission. # Test cases Same input format as in the example above. ``` [("07:00","12:00"),("12:30","15:30"),("15:45","17:15")] -> TRUE // 9:30h work, 45 minutes break -> OK [("07:20","07:45"),("07:59","11:30"),("11:55","15:00")] -> FALSE // 7:01h work, 39 minutes break, but first break does not count because < 15 minutes [("06:00","09:00"),("09:00","11:50")] -> TRUE // Only 5:50h work, so no break needed [("07:30","12:00"),("12:30","16:00")] -> TRUE // 8h work, 30 minutes break -> OK [("08:00","12:30"),("13:05","17:45")] -> FALSE // 9:10h work, only 35 minutes break instead of the needed 45 [("08:00","14:00")] -> FALSE // 6h work, no breaks, but 30 minutes needed ``` **Happy Coding!** [Answer] # Javascript, ~~108~~ 106 bytes ``` m=>(k=t=0,m.map(l=>(a=l[0]*60+l[1],k+=t?a-b<15?0:a-b:0,b=l[2]*60+l[3],t+=b-a)),t/=60,t<6||k>44||t<9&&k>29) ``` Takes an array of arrays. Each inner array has the start hour and minute and end hour and minute respectively for each period. ``` f=m=>( // assign function to f k=t=0, // k break // t work m.map(l=>( // for each period a=l[0]*60+l[1], // started time in minutes k+=t?a-b<15?0:a-b:0, // if there was a break add it b=l[2]*60+l[3], // ended time in minutes t+=b-a // sum worked time (the difference) )), // t/=60, // turn t from minutes to hours t<6||k>44||t<9&&k>29 // the main logic ) // document.body.innerHTML = '<pre>' + f([[07,00,12,00],[12,30,15,30],[15,45,17,15]]) + '\n' + f([[07,20,07,45],[07,59,11,30],[11,55,15,00]]) + '\n' + f([[06,00,09,00],[09,00,11,50]]) + '\n' + f([[07,30,12,00],[12,30,16,00]]) + '\n' + f([[08,00,12,30],[13,05,17,45]]) + '\n' + f([[08,00,14,00]]) + '\n' + '</pre>' ``` [Answer] # Python 3, 135 Saved 3 bytes thanks to DSM. This is one of my mathier solutions in a while. ``` def f(l): h=r=e=0 for(a,b)in l:a+=a%1*2/3;b+=b%1*2/3;h+=b-a;r-=(e-a)*(e and(a-e)>.24);e=b return(h<6)|(6<=h<9and.5<=r)|(h>9and.74<r) ``` Here're my test cases, it also shows how I expect the function to be called. ``` assert f([(07.00, 12.00), (12.30, 15.30), (15.45, 17.15)]) assert not f([(07.20, 07.45), (07.59, 11.30), (11.55, 15.00)]) assert f([(06.00, 09.00), (09.00, 11.50)]) assert f([(07.30, 12.00), (12.30, 16.00)]) assert not f([(08.00, 12.30), (13.05, 17.45)]) assert not f([(08.00, 14.00)]) ``` [Answer] # Pyth, ~~56~~ 52 bytes ``` La.*bgsm*ydgyd15cPt_Jmid60Q2@[0030 45)hS,/syRcJ2C\´3 ``` Takes input in the form `[[hh,mm], [hh,mm], ...]` with no leading `0`s Explanation: ``` La.*bgsm*ydgyd15cPt_Jmid60Q2@[0030 45)hS,/syRcJ2C\´3 La.*b - def y(b): return absdiff(*b) Jmid60Q - Unpack the input to mins and assign to J J - autoassign J = V m Q - [V for d in Q] id60 - conv_base(V, 60) sm*ydgyd15cPt_J 2 - Get the total break _J - reverse(J) Pt - ^[1:-1] c 2 - chop(2, ^) - m - [V for d in ^] yd - y(d) g 15 - >= 15 yd - y(d) * - y(d) * (y(d)>=15) - s - sum(^) @[0030 45)hS,/syRcJ2C\´3 - Get the break required cJ2 - chop(J, 2) yR - map(y, ^) s - sum(^) - Now have the total time worked in mins / C\´ - ^/ord("`") - (^/180) - Now have the time worked in 3 hour intervals hS, 3 - sorted([^, 3])[0] - (min(^, 3)) - Now have hours worked in 3 hour intervals capped at 9 hours @[0030 45) - [0,0,30,45][^] - Get the break required for that time g - break >= break required ``` [Try it here](http://pyth.herokuapp.com/?code=La.*bgsm*ydgyd15cPt_Jmid60Q2%40[0030+45%29hS%2C%2FsyRcJ2C%5C%C2%B43&input=[[7%2C0]%2C[12%2C0]%2C[12%2C30]%2C[15%2C30]%2C[15%2C45]%2C[17%2C15]]&test_suite_input=[[7%2C0]%2C[12%2C0]%2C[12%2C30]%2C[15%2C30]%2C[15%2C45]%2C[17%2C15]]%0A[[7%2C20]%2C[7%2C45]%2C[7%2C59]%2C[11%2C30]%2C[11%2C55]%2C[15%2C0]]%0A[[6%2C0]%2C[9%2C0]%2C[9%2C0]%2C[11%2C50]]%0A[[7%2C30]%2C[12%2C0]%2C[12%2C30]%2C[16%2C0]]%0A[[8%2C00]%2C[12%2C30]%2C[13%2C5]%2C[17%2C45]]%0A[[8%2C0]%2C[14%2C0]]&debug=0) [Or try all the test cases here](http://pyth.herokuapp.com/?code=La.*bgsm*ydgyd15cPt_Jmid60Q2%40[0030+45%29hS%2C%2FsyRcJ2C%5C%C2%B43&input=[[7%2C0]%2C[12%2C0]%2C[12%2C30]%2C[15%2C30]%2C[15%2C45]%2C[17%2C15]]&test_suite=1&test_suite_input=[[7%2C0]%2C[12%2C0]%2C[12%2C30]%2C[15%2C30]%2C[15%2C45]%2C[17%2C15]]%0A[[7%2C20]%2C[7%2C45]%2C[7%2C59]%2C[11%2C30]%2C[11%2C55]%2C[15%2C0]]%0A[[6%2C0]%2C[9%2C0]%2C[9%2C0]%2C[11%2C50]]%0A[[7%2C30]%2C[12%2C0]%2C[12%2C30]%2C[16%2C0]]%0A[[8%2C00]%2C[12%2C30]%2C[13%2C5]%2C[17%2C45]]%0A[[8%2C0]%2C[14%2C0]]&debug=0) ]
[Question] [ (massive thanks to El'endia Starman and Sp3000 for helping me design test cases for this!) Given a positive integer `n` and a list of positive integer rotational periods for a number of clock hands (in seconds), output the smallest positive integer `x` where `x` seconds after starting the clock with all of the hands aligned, exactly `n` of the hands are aligned. They do not have to be aligned at the starting position - any position is fine, as long as `x` is an integer and is minimized. In addition, not all of the hands have to be aligned at the same position - for `n=4`, a solution where 2 groups of 2 hands are aligned is valid. Groups must be of size 2 or greater - two unaligned hands do not constitute 2 groups of 1 aligned hand, and thus is not a valid solution. You may assume that only inputs where it is possible to have exactly `n` hands aligned after an integer number of seconds will be given - `2, [3,3,3]` is not a valid input, because after any number of seconds, all 3 hands will be aligned, and so it is impossible to get exactly 2 aligned. Examples: ``` 2, [3,4] -> 12 (the only option is a multiple of 12, so we pick 12 - 4 and 3 full rotations, respectively) 3, [3,5,6,9,29] -> 18 (picking 3, 6, and 9, the hands would align after 6, 3, and 2 rotations, respectively) 2, [1,1,4,5,10] -> 1 (picking 1 and 1 - note that 0 is not a valid answer because it is not a positive integer) 3, [2,2,6,7,11] -> 3 (picking 2, 2, and 6 - the 2s would be halfway through their second revolution, and the 6 would be halfway through its first revolution) 2, [2,7,5,3,3] -> 1 (picking 3 and 3, they are always aligned, so 1 is the minimum) 5, [4, 14, 36, 50, 63, 180, 210] -> 45 (after 45 seconds, the first, third, and sixth are aligned, as well as the second and seventh, for a total of 5) ``` ### Test Data: ``` 7, [10, 22, 7, 6, 12, 21, 19] -> 87780 6, [25, 6, 2, 19, 11, 12] -> 62700 6, [23, 1, 8, 10, 9, 25] -> 41400 7, [6, 4, 1, 8, 10, 24, 23] -> 920 3, [18, 5, 23, 20, 21] -> 180 5, [10, 8, 14, 17, 5, 9] -> 2520 6, [1, 18, 12, 9, 8, 10, 23] -> 360 6, [12, 11, 6, 23, 25, 18, 13] -> 118404 4, [18, 11, 2, 9, 12, 8, 3] -> 8 7, [18, 25, 9, 13, 3, 5, 20] -> 11700 2, [17, 20, 15, 8, 23, 3] -> 15 3, [16, 3, 24, 13, 15, 2] -> 24 5, [7, 23, 24, 8, 21] -> 1932 6, [16, 10, 12, 24, 18, 2, 21] -> 720 6, [1, 17, 16, 13, 19, 4, 15] -> 53040 2, [3, 4, 20] -> 5 3, [9, 4, 16, 14, 1, 21] -> 16 5, [5, 17, 10, 20, 12, 11] -> 330 2, [21, 5, 22, 18] -> 90 4, [7, 25, 2, 8, 13, 24] -> 84 4, [13, 19, 2, 20, 7, 3] -> 420 5, [4, 14, 36, 50, 63, 180, 210] -> 45 5, [43, 69, 16, 7, 13, 57, 21] -> 27664 3, [22, 46, 92, 43, 89, 12] -> 276 4, [42, 3, 49, 88, 63, 81] -> 882 6, [2, 4, 7, 10, 20, 21, 52, 260] -> 65 6, [2, 3, 4, 7, 10, 20, 21, 52, 260] -> 35 2, [3, 4] -> 12 3, [3, 5, 6, 9, 29] -> 18 2, [1, 1, 4, 5, 10] -> 1 3, [2, 2, 6, 7, 11] -> 3 3, [41, 13, 31, 35, 11] -> 4433 3, [27, 15, 37, 44, 20, 38] -> 540 5, [36, 11, 14, 32, 44] -> 22176 3, [171, 1615, 3420] -> 3060 3, [46, 36, 12, 42, 28, 3, 26, 40] -> 36 5, [36, 25, 20, 49, 10, 27, 38, 42] -> 1350 4, [40, 28, 34, 36, 42, 25] -> 2142 5, [24, 26, 47, 22, 6, 17, 39, 5, 37, 32] -> 1248 4, [9, 27, 12, 6, 44, 10] -> 108 ``` ### Rules: * Standard loopholes are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! # Leaderboard The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. 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 ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 64424; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # Pyth, ~~28~~ ~~27~~ 24 bytes ``` fqs-hMrS.RR7%R1cLTQ8 1vz ``` Try it online in the [Pyth Compiler](https://pyth.herokuapp.com/?code=fqs-hMrS.RR7%25R1cLTQ8+1vz&input=5%0A%5B4%2C+14%2C+36%2C+50%2C+63%2C+180%2C+210%5D&debug=0). ### How it works ``` fqs-hMrS.RR7%R1cLTQ8 1vz (implicit) Save the input number in z (as string). (implicit) Save the input list in Q. f Find the first positive integer T such that: cLTQ Compute T/α for each α in Q. %R1 Get the fractional part of each result. .RR7 Round each fractional part to 7 decimal digits. S Sort the resulting numbers. r 8 Perform run-length encoding. hM Get the lengths of the runs. - 1 Discard runs of length 1. s Add the remaining runs. q vz Check is the sum matches the input number. If it does, break and return T. ``` ### Test cases ``` $ cat input 7\n[10, 22, 7, 6, 12, 21, 19]\n87780 6\n[25, 6, 2, 19, 11, 12]\n62700 6\n[23, 1, 8, 10, 9, 25]\n41400 7\n[6, 4, 1, 8, 10, 24, 23]\n920 3\n[18, 5, 23, 20, 21]\n180 5\n[10, 8, 14, 17, 5, 9]\n2520 6\n[1, 18, 12, 9, 8, 10, 23]\n360 6\n[12, 11, 6, 23, 25, 18, 13]\n118404 4\n[18, 11, 2, 9, 12, 8, 3]\n8 7\n[18, 25, 9, 13, 3, 5, 20]\n11700 2\n[17, 20, 15, 8, 23, 3]\n15 3\n[16, 3, 24, 13, 15, 2]\n24 5\n[7, 23, 24, 8, 21]\n1932 6\n[16, 10, 12, 24, 18, 2, 21]\n720 6\n[1, 17, 16, 13, 19, 4, 15]\n53040 2\n[3, 4, 20]\n5 3\n[9, 4, 16, 14, 1, 21]\n16 5\n[5, 17, 10, 20, 12, 11]\n330 2\n[21, 5, 22, 18]\n90 4\n[7, 25, 2, 8, 13, 24]\n84 4\n[13, 19, 2, 20, 7, 3]\n420 5\n[4, 14, 36, 50, 63, 180, 210]\n45 5\n[43, 69, 16, 7, 13, 57, 21]\n27664 3\n[22, 46, 92, 43, 89, 12]\n276 4\n[42, 3, 49, 88, 63, 81]\n882 6\n[2, 4, 7, 10, 20, 21, 52, 260]\n65 6\n[2, 3, 4, 7, 10, 20, 21, 52, 260]\n35 2\n[3, 4]\n12 3\n[3, 5, 6, 9, 29]\n18 2\n[1, 1, 4, 5, 10]\n1 3\n[2, 2, 6, 7, 11]\n3 3\n[41, 13, 31, 35, 11]\n4433 3\n[27, 15, 37, 44, 20, 38]\n540 5\n[36, 11, 14, 32, 44]\n22176 3\n[171, 1615, 3420]\n3060 3\n[46, 36, 12, 42, 28, 3, 26, 40]\n36 5\n[36, 25, 20, 49, 10, 27, 38, 42]\n1350 4\n[40, 28, 34, 36, 42, 25]\n2142 5\n[24, 26, 47, 22, 6, 17, 39, 5, 37, 32]\n1248 4\n[9, 27, 12, 6, 44, 10]\n108 $ while read -r; do echo -e "$REPLY" | pyth -c 'qvwfqs-hMrS.RR7%R1cLTQ8 1vz'; done < input True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 16 bytes ``` P:×ⱮP%PĠẈḟ1Sʋ€iƓ ``` Takes the array as argument, the integer from STDIN. Way too slow and memory hungry for most of the test cases. [Try it online!](https://tio.run/##ATcAyP9qZWxsef//UDrDl@KxrlAlUMSg4bqI4bifMVPKi@KCrGnGk///M/9bMywgNSwgNiwgOSwgMjld "Jelly – Try It Online") ### Alternate version, 14 bytes ``` P÷€%1ĠẈḟ1Sʋ€iƓ ``` This works in theory, but it may fail due to floating-point inaccuracies. [Try it online!](https://tio.run/##y0rNyan8/z/g8PZHTWtUDY8seLir4@GO@YbBp7qBApnHJv//b/w/2lhHwVRHwUxHwVJHwcgyFgA "Jelly – Try It Online") ### How it works ``` P:×ⱮP%PĠẈḟ1Sʋ€iƓ Main link. Argument: A (array) P P P Yield the product of A. : Divide the product by each n in A. ×Ɱ Multiply the quotients by each k in [1, ..., prod(A)]. % Take the results modulo the product. € Map the link to the left over the array of remainders. ʋ Combine the links to the left into a dyadic chain. Ġ Group indices of identical elements. Ẉ Widths; yield the lengths of the groups. ḟ1 Filterfalse; remove all copies of 1. S Take the sum. Ɠ Read an integer j from STDIN. i Find the first index of j in the array of sums. ``` [Answer] # CJam, ~~42~~ ~~34~~ 33 bytes ``` 0{)_eas~@d\f/1f%7fmO$e`0f=1m1b-}g ``` Try [this fiddle](http://cjam.aditsu.net/#code=q%3AE%3B%20e%23%20Implement%20%60ea'%20as%20%60Ea'.%0A%0A0%7B)_Eas~%40d%5Cf%2F1f%257fmO%24e%600f%3DX-Xb-%7Dg&input=5%20%5B4%2014%2036%2050%2063%20180%20210%5D) or [this test suite](http://cjam.aditsu.net/#code=qN%2F%7B'%2C-%22-%3E%22%2F~%3AR%3B%3AE%3B%0A%20%200%7B)_Eas~%40d%5Cf%2F1f%257fmO%24e%600f%3DX-Xb-%7Dg%0AR~%3Do%7D%2F&input=7%2C%20%5B10%2C%2022%2C%207%2C%206%2C%2012%2C%2021%2C%2019%5D%20-%3E%2087780%0A6%2C%20%5B25%2C%206%2C%202%2C%2019%2C%2011%2C%2012%5D%20-%3E%2062700%0A6%2C%20%5B23%2C%201%2C%208%2C%2010%2C%209%2C%2025%5D%20-%3E%2041400%0A7%2C%20%5B6%2C%204%2C%201%2C%208%2C%2010%2C%2024%2C%2023%5D%20-%3E%20920%0A3%2C%20%5B18%2C%205%2C%2023%2C%2020%2C%2021%5D%20-%3E%20180%0A5%2C%20%5B10%2C%208%2C%2014%2C%2017%2C%205%2C%209%5D%20-%3E%202520%0A6%2C%20%5B1%2C%2018%2C%2012%2C%209%2C%208%2C%2010%2C%2023%5D%20-%3E%20360%0A6%2C%20%5B12%2C%2011%2C%206%2C%2023%2C%2025%2C%2018%2C%2013%5D%20-%3E%20118404%0A4%2C%20%5B18%2C%2011%2C%202%2C%209%2C%2012%2C%208%2C%203%5D%20-%3E%208%0A7%2C%20%5B18%2C%2025%2C%209%2C%2013%2C%203%2C%205%2C%2020%5D%20-%3E%2011700%0A2%2C%20%5B17%2C%2020%2C%2015%2C%208%2C%2023%2C%203%5D%20-%3E%2015%0A3%2C%20%5B16%2C%203%2C%2024%2C%2013%2C%2015%2C%202%5D%20-%3E%2024%0A5%2C%20%5B7%2C%2023%2C%2024%2C%208%2C%2021%5D%20-%3E%201932%0A6%2C%20%5B16%2C%2010%2C%2012%2C%2024%2C%2018%2C%202%2C%2021%5D%20-%3E%20720%0A6%2C%20%5B1%2C%2017%2C%2016%2C%2013%2C%2019%2C%204%2C%2015%5D%20-%3E%2053040%0A2%2C%20%5B3%2C%204%2C%2020%5D%20-%3E%205%0A3%2C%20%5B9%2C%204%2C%2016%2C%2014%2C%201%2C%2021%5D%20-%3E%2016%0A5%2C%20%5B5%2C%2017%2C%2010%2C%2020%2C%2012%2C%2011%5D%20-%3E%20330%0A2%2C%20%5B21%2C%205%2C%2022%2C%2018%5D%20-%3E%2090%0A4%2C%20%5B7%2C%2025%2C%202%2C%208%2C%2013%2C%2024%5D%20-%3E%2084%0A4%2C%20%5B13%2C%2019%2C%202%2C%2020%2C%207%2C%203%5D%20-%3E%20420%0A5%2C%20%5B4%2C%2014%2C%2036%2C%2050%2C%2063%2C%20180%2C%20210%5D%20-%3E%2045%0A5%2C%20%5B43%2C%2069%2C%2016%2C%207%2C%2013%2C%2057%2C%2021%5D%20-%3E%2027664%0A3%2C%20%5B22%2C%2046%2C%2092%2C%2043%2C%2089%2C%2012%5D%20-%3E%20276%0A4%2C%20%5B42%2C%203%2C%2049%2C%2088%2C%2063%2C%2081%5D%20-%3E%20882%0A6%2C%20%5B2%2C%204%2C%207%2C%2010%2C%2020%2C%2021%2C%2052%2C%20260%5D%20-%3E%2065%0A6%2C%20%5B2%2C%203%2C%204%2C%207%2C%2010%2C%2020%2C%2021%2C%2052%2C%20260%5D%20-%3E%2035%0A2%2C%20%5B3%2C%204%5D%20-%3E%2012%0A3%2C%20%5B3%2C%205%2C%206%2C%209%2C%2029%5D%20-%3E%2018%0A2%2C%20%5B1%2C%201%2C%204%2C%205%2C%2010%5D%20-%3E%201%0A3%2C%20%5B2%2C%202%2C%206%2C%207%2C%2011%5D%20-%3E%203%0A3%2C%20%5B41%2C%2013%2C%2031%2C%2035%2C%2011%5D%20-%3E%204433%0A3%2C%20%5B27%2C%2015%2C%2037%2C%2044%2C%2020%2C%2038%5D%20-%3E%20540%0A5%2C%20%5B36%2C%2011%2C%2014%2C%2032%2C%2044%5D%20-%3E%2022176%0A3%2C%20%5B171%2C%201615%2C%203420%5D%20-%3E%203060%0A3%2C%20%5B46%2C%2036%2C%2012%2C%2042%2C%2028%2C%203%2C%2026%2C%2040%5D%20-%3E%2036%0A5%2C%20%5B36%2C%2025%2C%2020%2C%2049%2C%2010%2C%2027%2C%2038%2C%2042%5D%20-%3E%201350%0A4%2C%20%5B40%2C%2028%2C%2034%2C%2036%2C%2042%2C%2025%5D%20-%3E%202142%0A5%2C%20%5B24%2C%2026%2C%2047%2C%2022%2C%206%2C%2017%2C%2039%2C%205%2C%2037%2C%2032%5D%20-%3E%201248%0A4%2C%20%5B9%2C%2027%2C%2012%2C%206%2C%2044%2C%2010%5D%20-%3E%20108) in the CJam interpreter. ### How it works ``` 0 e# Push 0 (accumulator). { e# Do: )_ e# Increment the accumulator and push a copy. eas~ e# Push the command-line args, flatten and evaluate. e# This pushes a number and an array. @d e# Rotate the accumulator copy on top and cast to Double. \f/ e# Divide it by each of the integers in the array. 1f% e# Get the fractional part of each result. 7fmO e# Round all fractional parts to seven decimal digits. $e` e# Sort and perform run-length encoding. 0f= e# Select the lengths of the runs. X- e# Discard runs of length 1. Xb e# Compute the sum of the remaining runs. - e# Subtract the sum from the input number (target). }g e# If this pushes a non-zero value, we've missed the target; e# repeat the loop. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ÷_:ĠẈḟ1S⁼⁴ 1ç1# ``` [Try it online!](https://tio.run/##y0rNyan8///w9nirIwse7up4uGO@YfCjxj2PGrdwGR5ebqj8////aEsdBSNzHQVDIx0FMx0FExMg0yD2vwkA "Jelly – Try It Online") Full program. Suffers from floating-point inaccuracies. ]
[Question] [ Given the number of vertices `n ≥ 3` and the "step size" `1 ≤ m < n/2` (indicating the distance between two connected vertices), output a graphical representation of the corresponding [regular polygram](https://en.wikipedia.org/wiki/Polygram_(geometry)). If the polygram consist of multiple closed loops, each loop must be rendered in a different line colour. (If this sounds confusing, the examples below should hopefully clear things up.) ## Rules Any reasonable solution to the problem will likely satisfy these rules automatically - they are just there to put some constraints on the parameters of the output in order to prevent answers like "This black block is totally a polygram, but you can't see it because I set the line width to over 9000." * You can render the polygram either to a file (which may be written to disc or to the standard output stream) or display it on the screen. * You may use either vector or raster graphics. If your output is rasterised, your image must have dimensions of 400x400 pixels or more, and the polygram's *radius* (the distance from the centre to each vertex) must be between 35% and 50% of the side length. * The aspect ratio of the polygram must be 1 (so that its vertices lie on a proper circle) - the canvas of the image may be rectangular. * The lines of the polygram must be no thicker than 5% of the radius (and of course, they must have non-zero thickness to be visible). * You may render axes or a frame in addition to the polygram, but nothing else. * You may choose any (solid) background colour. * For polygrams consisting of multiple closed loops, you must support at least 6 *visually distinct* colours, all of which must be different from the background. (Grey-scale is fine, provided the shades are sufficiently spread out through the spectrum.) Your code must still work for more than 6 loops, but the colours don't have to be distinguishable for any additional loops (i.e. you may also reuse colours from previous loops at that point). This is code golf, so the shortest answer (in bytes) wins. ## Examples Here are all the outputs up to `n = 16` (where the column corresponds to `n` and the row to `m`): [![enter image description here](https://i.stack.imgur.com/ZjcNs.png)](https://i.stack.imgur.com/ZjcNs.png) Click for larger version. As examples for larger `n`, here are `(n, m) = (29, 11)` and `(30, 12)`: [![enter image description here](https://i.stack.imgur.com/1jrKDm.png)](https://i.stack.imgur.com/1jrKD.png)[![enter image description here](https://i.stack.imgur.com/yXSiXm.png)](https://i.stack.imgur.com/yXSiX.png) [Answer] # MATLAB, ~~85~~ 81 The function displays a plot on the screen. ``` function f(n,m) hold all axis equal for k=1:gcd(m,n) plot(i.^(4*(k:m:n^2)/n)) end ``` Result for n=30, m=12: [![f(30,12)](https://i.stack.imgur.com/z8esS.png)](https://i.stack.imgur.com/z8esS.png) [Answer] # CJam, 114 ``` "P2"N400:ASAN6N0aA*aA*q~:M;:K{:CK,f{M*+K%P*2*K/_[mc)\ms)]199f*}_+2ew{~1$.-Af/A,\ff*\f.+{:mo~_3$=@C6%)tt}/}/}/Sf*N* ``` It outputs the image in ASCII PGM format. You can [try it online](http://cjam.aditsu.net/#code=%22P2%22N400%3AASAN6N0aA*aA*q~%3AM%3B%3AK%7B%3ACK%2Cf%7BM*%2BK%25P*2*K%2F_%5Bmc)%5Cms)%5D199f*%7D_%2B2ew%7B~1%24.-Af%2FA%2C%5Cff*%5Cf.%2B%7B%3Amo~_3%24%3D%40C6%25)tt%7D%2F%7D%2F%7D%2FSf*N*&input=6%202), but the output is pretty long. You can change `400` and `199` to smaller numbers to reduce the image size. CJam has no concept of images, drawing, lines or shapes, so I generated the image in a square matrix, pixel by pixel (one number representing a grey shade for each pixel). This is what the result looks like for `30 12`: [![polygram](https://i.stack.imgur.com/qxel8.png)](https://i.stack.imgur.com/qxel8.png) [Answer] # Mathematica, 70 bytes ``` ListPolarPlot[Table[{2Pi(i+j#2)/#,1},{i,GCD@##},{j,#+1}],Joined->1>0]& ``` Well... this is my reference implementation which beats both submissions so far. I'm not intent on winning my own challenge, so I'm hoping someone will beat this. The output is like the plots in the challenge itself, except I'm not removing the axes here: [![enter image description here](https://i.stack.imgur.com/AKXDT.png)](https://i.stack.imgur.com/AKXDT.png) ]
[Question] [ ## Background There are two people, Bill and John. One of them is a knight, which always tells the truth, and the other is a knave, which always tells a lie. You don't know who is the knight and who is the knave. Each person then says several statements about who is the knave and who is the knight. Using this information, you must come to a conclusion as to who is the knight and who is the knave. The [Knights and Knaves logic problem](http://en.wikipedia.org/wiki/Knights_and_Knaves) is based on Booleen algebra. The words that a person says form a Booleen satisfiability problem. The knave's statements must always be false and the other knight's statements must always be true. John says "Both I am a knave and Bill is a knave". If John were the knight, then this statement would be false, so he can't be the knight. If he were the knave and Bill were the knight, this statement would still be false, even thought the first part is true. So, John is the knave. # The Challenge Your challenge is to write the shortest program possible that will take a list of statements made by each person and will figure out who is the knave and who is the knight. There are a lot of details to cover, so this problem is described in three sections. ## Input Input will be two lines followed by a newline. Each line will give the name of one of the characters, followed by a colon, followed by several sentences said by that person. If one person is the knight, then all of his sentences will be true, and all of the knave's sentences will be false. The first letter of a sentence will always be capitalized, and every sentence will end with a period. Here is an example: ``` Joe: Both I am a knight and neither Steve is a knave nor I am a knave. Steve: Joe is a knave. Either Joe is a knight or I am a knight. ``` ## Parsing Each sentence consists of at least one clause. Each clause contains one of several things (hopefully you can understand my notation): ``` both [clause] and [clause] either [clause] or [clause] neither [clause] nor [clause] [I am | (other person's name) is] a [knight | knave] ``` This is unambigious becuase it can be understood in a way similar to Polish notation. Here is an example of a sentence: ``` Both I am a knight and neither Steve is a knave nor I am a knave. ``` The translation into Booleen algebra is straightforward. The "both" statements are ANDs, the "either" statements are XORs, and the "neither" statements are NORs. ``` (I am a knight) AND ((Steve is a knave) NOR (I am a knave)) ``` ## Output Output will consist of two lines. Each line consists of a person's name (in order) and then says whether he is the knight or the knave. There will always be one knight and one knave. Here is the output for the above example: ``` Joe is the knave. Steve is the knight. ``` If the problem is unsolvable (either you can't tell who is what, or there is no solution), then your program can do anything EXCEPT produce a valid output. # More examples Input ``` Sir Lancelot: Either both I am a knight and Merlin is a knave or both I am a knave and Merlin is a knight. Merlin: Either both I am a knight and Sir Lancelot is a knight or both I am a knave and Sir Lancelot is a knave. ``` Output ``` Sir Lancelot is the knight. Merlin is the knave. ``` Input ``` David: Neither I am a knave nor Patrick is a knight. Either I am a knight or Patrick is a knave. Patrick: Either I am a knight or both I am a knight and David is a knight. ``` Output ``` David is the knave. Patrick is the knight. ``` Input ``` Lizard: I am a knight. Spock: I am a knave. ``` One possible output ``` Rock Paper Scissors ``` ## Rules, Regulations and Notes 1. Standard code golf rules apply 2. Your program must be only made up of printable ASCII 3. All input and output will be from STDIN and STDOUT [Answer] ## Python, 491 chars Works by converting each line to a Python expression, and eveluating it. The knave and knight are evaluated as 0 and 1. For the two people, we try both options. For example, `Joe: Steve is a knave` becomes `Joe==(Steve==knave)`. This way, if `Joe` is a knave, the result is true only if he's lying. You get ugly errors when it's impossible or undecided. If impossible, `r[0]` is an index error, because `r` is empty. If undecidable, concatenating `r[1:]` to a list of strings causes trouble. ``` import sys def p(): a=s.pop(0) try:return{"both":"(%s*%s)","either":"(%s|%s)","neither":"(1-(%s|%s))"}[a.lower()]%(p(),p()) except KeyError:r=s[2];del s[:4];return"(%s==%s)"%((a,m)[a=="I"],r) x=[];w=[] for l in sys.stdin: m,l=l.split(":");w+=[m] for s in l.split("."): s=s.split() while s:x+=["%s==%s"%(m,p())] k=("knave","knight") r=[a for a in[{w[0]:z,w[1]:1-z}for z in(0,1)]if all(eval(l,{k[0]:0,k[1]:1},a)for l in x)] print"\n".join(x+" is the "+k[r[0][x]]+"."for x in w+r[1:]) ``` [Answer] ### Ruby, 352 characters The solution became quite long so there might still be some place to golf. It requires the input to be well-formed (as all the examples above are - but don't try to name a person "Both"...). ``` q=->{gets.split /: |\.\s/} C,*E=q[] D,*F=q[] r=->c,m{t=c.shift;t[1]?(x=r[c,m];c.shift;y=r[c,m];t[0]==?B?x&y :t[0]==?E?x^y :1-(x|y)):(c.shift(2);h=c.shift[2]==?I?m : 1-m;t==?I?h :1-h)} s=->u,v,b{u.map{|c|r[c.gsub(v,?J).upcase.split,b]==b}.all?} t=->b{s[E,D,b]&&s[F,C,1-b]} u=->v,b{v+" is the kn#{b ?:ight: :ave}."} puts t[1]^t[0]&&u[C,t[1]]+$/+u[D,t[0]] ``` [Answer] # Perl - 483 bytes ``` (($a,$b),($c,$d))=map{split':'}@ARGV;$h='y';$i='x';$s=' is the kn';$g='ight.';$v='ave.';for($b,$d){$_.=' 1';s/ am a | is a /==/g;s/knight/1)/g;s/knave/0)/g;s/I=/(\$$i=/g;s/($a|$c)=/(\$$h=/g;s/([^.]+)\./($1)and/g;s/ or / xor /g;s/ nor / or /g;while(s/(?<= )(\w+ \((?:[^()]+|(?1))\) \w+ \((?:[^()]+|(?1))\))/($1)/g){}s/neither/!/gi;s/both|either//gi;$h=$i++}$x=0;$y=1;$k=!eval($b)&&eval($d);$x=$y--;$n=!eval($d)&&eval($b);print"$a$s$v $c$s$g"if($k&&!$n);print"$a$s$g $c$s$v"if($n&&!$k) ``` Similar to the Python solution. It reduces the sentences to Perl code and then `eval`s them. It can print almost-valid output if the input is weird but doesn't print anything if it's undecidable. Well-formed input works as expected. The sentences are passed in on the command line inside quotes and no special flags are needed. ]
[Question] [ In this challenge you must write a computer program that creates a stack of a thousand identical \$1 \times 1\$ frictionless homogeneous blocks such that each block is supported and the stack is stable under gravity when placed on the edge of a table which spans from \$x = -\infty\$ to \$0\$ horizontally, with the surface at \$y = 0\$. The winning criterion is the amount of *overhang* you manage to create, that is, the \$x\$ coordinate of the rightmost edge of the stack. Highest overhang wins. This problem is analyzed in [*Overhang*](https://www.maa.org/sites/default/files/pdf/upload_library/22/Robbins/Patterson1.pdf) by Mike Paterson and Uri Zwick. Using their algorithm I wrote [a judging program](https://gist.github.com/orlp/b7b62a904f9152acb1363b4a1240f9f8) in Python that given a list of \$(x, y)\$ coordinates of the bottom left corners of the blocks returns whether the solution is valid and how much overhang it achieves. You will need Python 3 and the `pulp` library to run this program. You can get the latter using `python3 -m pip install --user pulp`. The program expects one pair of coordinates per line, separated by whitespace, on stdin. To prevent rounding issues the judging program rounds the \$x\$ coordinates to six decimal places (and the \$y\$ coordinates are expected to be non-negative integers). Your answer must include (a link to) a list of coordinates that passes the judging program, and contain the score it reports. Yes, this does mean you need to be able to run your program to completion to get your output—you can't get away with "end of the universe" brute force. As an example, the optimal stack with thirty blocks (2.70909 units of overhang): [![optimal stack with 30 blocks](https://i.stack.imgur.com/cEjO6.png)](https://i.stack.imgur.com/cEjO6.png) Note that since the blocks are homogeneous and frictionless all forces are strictly vertical (in a balanced stack) and the actual width : height ratio of the blocks does not matter, so for clarity the blocks are shown elongated. [Answer] # [Python 3](https://python.org), 3.742717 units I figured just to get something out there I'd implement the harmonic stack, it's a pretty bad algorithm but being the first submitter that makes me the current winner ;) # stack.py ``` # Number of blocks N = 1000 # Evaluate 0.5*H(n) def harmonic(): h = 0 i = 0 yield 0 # Avoid divide by zero errors by defining H(0) to be 0 while True: i += 1 # Stupid rounding error means we need to divide by *sliightly* more than 2 h += 1/(2.00000202478*i) yield h # Generators are sexy # Get the harmonic number up to N def nth_harmonic(n): return next(x for i,x in enumerate(harmonic()) if i==n) def main(): # Calculate the block offset offset = nth_harmonic(N) - 1 for i, x in enumerate(harmonic()): # Spit the 6 decimal place formatted value to stdout along with the height print(format(offset - x, '.6f'), N - 1 - i) if i == N - 1: # We gotta stop at some point break if __name__ == "__main__": main() ``` ]
[Question] [ As the title says, you are to create a pristine program in as many languages as possible. A pristine program, taken from [here](https://codegolf.stackexchange.com/q/63433/66833), is: > > Let's define a *pristine program* as a program that does not have any errors itself but will error if you modify it by removing any contiguous substring of \$N\$ characters, where \$1 \le N < \text{program length}\$. > > > For example, the three character Python 2 program > > > > ``` > `8` > > ``` > > is a pristine program ([thanks, Sp](https://chat.stackexchange.com/transcript/message/25274283#25274283)) because all the programs resulting from removing substrings of length 1 cause errors (syntax errors in fact, but any type of error will do): > > > > ``` > 8` > `` > `8 > > ``` > > and also all the programs resulting from removing substrings of length 2 cause errors: > > > > ``` > ` > ` > > ``` > > If, for example, ``8` had been a non-erroring program then ``8`` would not be pristine because **all** the results of substring removal must error. > > > You are to write, in as many languages as possible, a pristine program. * Your program must produce a non-empty output when unaltered. + This output can be anything you like, can vary depending on different inputs, or anything else, so long as, when run, unaltered and with no/empty input, it produces a non-empty output (note that `0`, or your language's null value is non-empty). + The output may **not** be to STDERR (or your language's equivalent), as this would fall under the definition of an "erroring program" below. + The output does not have to consistent across languages, or when executed twice in the same language. * Your code must work in a minimum of two distinct languages and must be at least 2 bytes long * Different versions of a language do not count as different languages. Therefore, Python 2 and Python 3 are considered the same language. * Your program must be pristine in all languages used * An error is defined as anything that causes the program to either entirely fail to run or to terminate with a nonzero exit code after a finite amount of time. * This is [rosetta-stone](/questions/tagged/rosetta-stone "show questions tagged 'rosetta-stone'"), so the answer with the most languages wins + In case of a tie breaker, the *longest* solution, in bytes, wins --- I would also be interested in proofs of impossibility for certain pairs/groups of languages. If you find a particularly interesting proof, please leave it in the comments (or, preferably, a link to the full write up), and I'll invite you to post as an answer so I can award it a bounty if I agree that its especially interesting. Please **do not** post these proofs unless I have said I will award it a bounty, I don't want all the answers to be filled by such proofs and actual answers be buried. Proofs posted without me asking you to will not be considered valid [Answer] # 6 languages ## [Bash](https://www.gnu.org/software/bash/), 4 bytes ``` echo ``` [Try it online!](https://tio.run/##S0oszvj/PzU5I///fwA "Bash – Try It Online") ## [Zsh](https://www.zsh.org/), 4 bytes ``` echo ``` [Try it online!](https://tio.run/##qyrO@P8/NTkj//9/AA "Zsh – Try It Online") ## [fish](https://fishshell.com/), 4 bytes ``` echo ``` [Try it online!](https://tio.run/##S8ssztAtzkjNyfn/PzU5I///fwA "fish – Try It Online") ## [tcsh](http://www.tcsh.org/), 4 bytes ``` echo ``` [Try it online!](https://tio.run/##K0kuzvj/PzU5I///fwA "tcsh – Try It Online") ## [ksh](http://www.kornshell.com/), 4 bytes ``` echo ``` [Try it online!](https://tio.run/##yy7O@P8/NTkj//9/AA "ksh – Try It Online") ## [J](http://jsoftware.com/), 4 bytes ``` echo ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/U5Mz8v9rcoEohTQFdfX/AA "J – Try It Online") Kicking things off with a boring one. If I understand the rules, I think it's legal though. The shells are clear enough and output a newline. Removing any contiguous substring will result in "command not found". In J, `echo` is a built in function, and prints its argument with a newline appended. J doesn't have 0-argument functions, so you have to call it with something. However, anything works, including the empty string `''`, which is the conventional choice for calling a function when the argument doesn't matter. [Answer] # 3 languages, 5 bytes ## Ruby `print` ## Python 2 `print` ## Perl 5 `print` # 2 languages, 20 bytes ## Scala `System.out.println()` ## Javascript `System.out.println()` This does about the same thing that the answer by Jonah does, except because a lot less languages use `print`, it features 3 or 2 languages. Still felt like answering however. These all print the empty string. ]
[Question] [ # Satisfying Rounding You know when you're in science class, and asked to round to 2 sig figs, but your answer is `5.2501...`? You should round to `5.3`, but that's just so unsatisfying! By rounding to `5.3`, you're off by a whole 0.05, which is a large amount compared to 0.1 (the place value you're rounding to)! So help me round in a satisfying way. To round in a satisfying way, you must round at the first digit you come across that produces a relatively small error - less than half of the maximum error possible when rounding. Basically, you need to round whenever you encounter 0, 1, 8, or 9. If that never happens, return the input as is. Do not round on leading zeroes or ones - that just doesn't feel satisfying. # Input A string or float value that represents a nonnegative decimal number. # Output The same decimal number rounded satisfactorily, in either string or float format. # Examples ``` Input -> Output 0 -> 0 0.5 -> 0.5 0.19 -> 0 0.8 -> 1 5.64511 -> 5.645 18.913 -> 20 88.913 -> 100 36.38299 -> 36.4 621 -> 620 803.22 -> 1000 547.4726 -> 547.4726 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so shortest code wins! [Answer] # JavaScript (ES6), ~~100 99 98~~ 78 bytes Takes input as a string. Returns a float. ``` s=>+(0+s).replace(/\d/g,(d,i)=>j&&+d+((n=s[i+!++s[i]])<2&&i?--j:n>7&&j--),j=1) ``` [Try it online!](https://tio.run/##fY7RaoMwFIbv@xQ2FyEh5pgTTdSxuAdZeyFqi0G0NGOv78ragtPR3ISf7@P/j6@/69Bc@8uXHKe2m09uDq4STInA4dpdhrrpWHJok3PM2rjnrvKUilYwNrrw2Yu9ELfveOTvmtL@Q0r/NlY5pV5KHnuHfG6mMUxDB8N0ZidGFInuj/MoSSK1W3MwZMnBbA0sycuGYtmAa27AZgaRPPhvXDtYQIkpeXbozUjxV0C1MVILaaHLktyNW8zWitW4vNT@M6NS0Ho5s1FMlkOWa/vYecb5Bw "JavaScript (Node.js) – Try It Online") ### How? We first prepend a leading \$0\$ to the input string, so that we're guaranteed to have a digit before a possible leading \$8\$ or \$9\$, that must trigger the rounding right away. The flag \$j\$ is set to \$1\$ as long as we are looking for a digit on which we can do a satisfying rounding, and set to \$0\$ afterwards. Because a leading \$0\$ was added to the string that we're walking through but \$s\$ was left unchanged, \$d\$ contains the current character and \$s[i]\$ is pointing to the *next* character. We use the following code to load the next digit in \$n\$, skipping a possible decimal separator: ``` n = s[i + !++s[i]] ``` Although strings are immutable in JavaScript, the expression `++s[i]` will return \$s[i]+1\$ if it contains a numeric value, even though \$s[i]\$ is not actually incremented. Therefore, the expression `!++s[i]` is evaluated to \$false\$ (coerced to \$0\$) for all digits (including \$0\$) and to \$true\$ (coerced to \$1\$) for the decimal separator `"."`. When the rounding occurs, we yield `d + --j` if the next digit \$n\$ is \$0\$ or \$1\$ (and it's not the leading digit of the original input) and `d + j--` if \$n\$ is \$8\$ or \$9\$. Therefore, \$j\$ is set to \$0\$ in both cases but we add \$0\$ to \$d\$ in the first case (rounding down) and \$1\$ in the second case (rounding up). [Answer] # [Ruby](https://www.ruby-lang.org/), ~~79~~ ~~77~~ ~~69~~ ~~67~~ 65 bytes ``` ->n,z=n+".0"{z[i=z=~/\./]='';n.to_f.round (z=~/(?!^)[01]|8|9/)-i} ``` [Try it online!](https://tio.run/##NY7NDoIwEITvfQrEAxJh2RZaSkz1QRCNf0QuYBAO8uOrY6t4mm93ZyZbt@fXlKvJ35Zep8q1DWj3XVqoTr2DPQSZcpxNCU11zKGu2vJqrcxltVsc3BRpNsghCVy/GKcUvaWFBIEbBa6JJvNKaqWEg4g4pZq/RKiEhIZ6ZEjknykiCQWEkiUmrTEigpmQMDYMgbGfDQmPYohiJkzjjCSD2@ly74dmeFh52pjPn9k4fQA "Ruby – Try It Online") ### Explanation * `->n` Take input as a string * `z=n+".0"` Create a temporary string `z` that is guaranteed to contain a dot and a relevant digit. * `i=z=~/\./` Determine the position of the decimal dot in `z` and assign to `i`. * `z[i]=''` Drop the dot so that it doesn't get in the way further on. * `z=~/(?!^)[01]|8|9/` Determine the position of non-starting `0-1` or any `8-9`, whichever comes first. * `(...)-i` This difference will be the number of decimal places to keep, negative if we will be rounding left of the dot. * `n.to_f.round ...` Convert to float and do the rounding. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes ``` ;”.ḟ$µ»"”2e€⁽¡XṾ¤;1i1_i”.$_>¥0ɓVær ``` [Try it online!](https://tio.run/##y0rNyan8/9/6UcNcvYc75qsc2npotxKQY5T6qGnNo8a9hxZGPNy579ASa8NMw/hMkCqVeLtDSw1OTg47vKzo////6gZ6puoA "Jelly – Try It Online") -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Erik the Outgolfer (use of dyadic quick `¥` from his answer) ``` O;0µ_8H1¦%8ỊTḢ_<48TḢƊ_>¥0ɓVær ``` A monadic link accepting a list of characters which yields a float. **[Try it online!](https://tio.run/##y0rNyan8/9/f2uDQ1ngLD8NDy1QtHu7uCnm4Y1G8jYkFiD7WFW93aKnByclhh5cV/f//X93YTM/YwsjSUh0A "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/f2uDQ1ngLD8NDy1QtHu7uCnm4Y1G8jYkFiD7WFW93aKnByclhh5cV/T/c/qhpzf//0VzqBuo6CgrKCrp2CgZAjp4pgqtnChIwtERVYAHnGnKpm@qZmZgaGsKFwHwudUMLPUtDY7ioEVCjBaqQoQFQzNhMz9jCyBJhAVDAhEvdzAhhoBlYr4GxnpERsl6goKmJuZ6JuZEZwm6oAFcsAA "Jelly – Try It Online"). ### How First note that the input string is made exclusively from the characters `0123456789.` which have ordinals `[48,49,50,51,52,53,54,55,56,57,46]`, which have remainders when divided by eight of `[0,1,2,3,4,5,6,7,0,1,6]`. The only characters which are between `-1` and `1` inclusive are `0`, `1`, `8`, and `9`. Furthermore if we subtract eight from the ordinals (`[40,41,42,43,44,45,46,47,48,49,38]`) the same (fairly obviously) holds. If we halve these (`[20,20.5,21,21.5,22,22.5,23,23.5,24,24.5,19]`) the only characters which have remainders when divided by eight which are between `-1` and `1` inclusive are `8` and `9`. ``` O;0µ_8H1¦%8ỊTḢ_<48TḢƊ_>¥0ɓVær - Link: list of characters, S O - ordinal (vectorises across S) ;0 - concatenate a zero - (to cater BOTH for no '0', '1', '8', or '9' AND for no '.') µ - start a new monadic link (call that X) _8 - subtract eight (vectorises across X) ¦ - sparse application... 1 - ...to: indices: one H - ...do: halve (i.e. halve first ordinal) %8 - modulo by eight (vectorises) Ị - insignificant (abs(v)<=1?) (vectorises) T - truthy indices Ḣ - head Ɗ - last three links as a monad (i.e. f(X)): <48 - less than 48? (i.e. was it a '.' in S or the added 0?) T - truthy indices Ḣ - head _ - subtract ¥ - last two links as a dyad < 0 - less than zero? (1 if so 0 otherwise) _ - subtract ɓ - start a new dyadic chain (i.e. f(S,X)) V - evaluate S as Jelly code (i.e. get S as a float) ær - round to the nearest multiple of 10^(-X) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 75 bytes ``` ^[89] 10 T`d`0`(?<=.)[01].*|(?<=8|9).* T`89d`0d`.\.?[89] (\.|(\..+?))0+$ $2 ``` [Try it online!](https://tio.run/##JYuxCsJAEET7/Y4IuQSG3bvcZReUlP6AXRI5IRY2FmKZfz9PLd4Mw2Ne9/fjeSuH9pzLdVZbSZguecuc2@l4gptZVnT7d@huDl21atVvGQum36VdsFfQT85x31DjS2FixIpYDaWINEQREoVJIP1XSAjqzSh5IeUA7ykOI4bRpw8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^[89] 10 ``` Handle the case of a leading `8` or `9`. ``` T`d`0`(?<=.)[01].*|(?<=8|9).* ``` If there's a non-leading `0` or `1`, then zero it and the rest of the string out. Also, if there's an `8` or `9`, then leave it, but zero out the rest of the string. (But leave the decimal point unchanged in either case.) ``` T`89d`0d`.\.?[89] ``` If there's still an `8` or a `9` at this point, then zero it out, and increment the preceding digit (possibly before the decimal point). ``` (\.|(\..+?))0+$ $2 ``` Delete trailing zeros if they are after a decimal point, but only delete the decimal point if there are no other digits in between. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~111~~ 102 bytes ``` g(_,i,j,k)char*_;{for(i=*_<56?*_++:48,j=3;j;j&=k%8>1|(i=*_++)/48*2)putchar(j&1?i+(k=_[*_<48])/56:48);} ``` [Try it online!](https://tio.run/##bc5LDoIwEIDhvacwJJqWYrFPBit6EGMa0kSkxEdQV8rZEd1J3TXf5J@pW1TO9X2FbFInPmmwO5ZtbM3zcGlRXcR2rfQ2toSsJCS@EMYbPy@aGWzY6zsnBKcSYo6vj/unRX7OtjVBTWF3Qy1hj1Olhxqbrj@V9Rnh6XNSoWgZYTM0NxQNjy9QFRLLQ4MxKaqlYmzMDGjOxFjhrwpNBfA8uKZ5sBaWgnIe/EFmVGZc/3jXvwE "C (gcc) – Try It Online") ``` //_: input, as string //i: current digit, rounded if applicable //j: tracks whether number is rounded, and whether \0 or '.' has been encountered //k: digit to test rounding (round if k is one of 0,1,8,9) //'0'==48, '8'==56 g(_,i,j,k)char*_;{ for(i=*_<56?*_++:48,j=3; //special case: if first digit is 8 or 9, use a //placeholder digit with value 0. initialize j. j; //only stop execution when number is rounded and //'.' or \0 has been encountered. j&=k%8>1|(i=*_++)/48*2) //check if execution should stop. putchar(j&1?i+(k=_[*_<48])/56:48); //print '0' if rounding had already been done; //otherwise, print digit. round up as needed. } ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 280 bytes ``` c=>{int d=c.IndexOf('.');int t=c.IndexOfAny(new char[]{'8','9','0','1'},1);var m=c[0]=='8'||c[0]=='9'?1>0:0>1;var z=decimal.Parse(c);Func<decimal>q=()=>(decimal)Math.Pow(10,m?d<0?c.Length:d:d<0?c.Length-t:d>t?d-t:d-t+1);return m?Math.Round(z/q())*q():t<0?z:Math.Round(z/q())*q();} ``` [Try it online!](https://tio.run/##bVDLboMwELzzFRYX7AZcDHnwiEFVpUqVUjXqpYcoB2ScgBSMYpymDcm3Ux5J20MPuzO7O2uPllUWq/Lm6SDYvFIyF1sz5Swvkl0EEkBBw2hU50KBlDL8LFL@@bqBBjZQ2DXVb/NBfEHBj4BliVyta8MzTMNvw26DGBeToPAjkaCgbGWvKW3n5/OV@kZMIjuwI9JLTvTqAC8TWXHIUNjbu/naU4hoBK8leklUhpflERLbLOJ0bscML7jYqixIg7@lpYI0UnHaoaVGrSHJ1UEKUMT9G2/lQaTwdL@HCN21KVDt8in4dxZemlAb7rVaA8UrxWXVnqvWdFs324QnAxB/QK@DCZ6OJ4R0lHjYJ27HvB/mTrHrOX6/MXV6mWe72HH63fEMj2fOVNcuoaZtSskTlsHuXt3vFcjFzQbSau2xFFW54/hd5oovcsHhoBoBHVgR0EfJ0EAo1C7NNw "C# (Visual C# Interactive Compiler) – Try It Online") It can be shorter if I used doubles instead of decimals, but I used decimals to preserve accuracy, or else a number like 547.4726 would be 547.472595214844. # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 268 bytes ``` c=>{int d=c.IndexOf('.');int t=c.IndexOfAny(new char[]{'8','9','0','1'},1);var m=c[0]=='8'||c[0]=='9'?1>0:0>1;var z=float.Parse(c);Func<double>q=()=>Math.Pow(10,m?d<0?c.Length:d:d<0?c.Length-t:d>t?d-t:d-t+1);return m?Math.Round(z/q())*q():t<0?z:Math.Round(z/q())*q();} ``` [Try it online!(Less accurate version)](https://tio.run/##bVDLbsIwELznK6xcYpfgxgmEPHCiqlKlSlRFvfSAOKSOgUjgCNuUlpBvp3nQx6GH3Rnvzq5Hy9SQqeLycBBsqrQsxNrOy8PblicgAxRcGE2qQmiQU4YfRc4/nlfQwhaK26L@Ld6JTyj4EbBNJhfLygos2wqbcJogVm0TFL9nEuwoWzhLSpv@@XyloZWSxImchHSSE11ty0zjeSYVhwzFnberqT2FiCZPmd7geXmExLF3aT51UoZnXKz1Jsqjv8@hjvJEp3mLQz1oTEiuD1KAXdrteCkPIoen2z1E6KZJkW6GT9G/vbi@xEZ/osUSaK40l6o5UWWYjmk3CY97IGGPQQtj7I/GhLSUBDgkXsuCH@b52AvcsJvw3U4WOB523W52NMGjieubRh0bxqqUPGMb2N6o/V2BQnzbQEZl3JdClVuOX2Wh@awQHPaqATDBMAHmIOsLCMVGffkC "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ **Given, in any way and order,** * dimensions (in whichever order you want) * a probability (in whatever format you want) * number of iterations (you may choose whether to count the initial state or not) **do *one* of the following:** * animate, or * output each step of, or * return a list of states of **a spaces-filled sky of those dimensions.** **For each iteration:** * every sky character has the given probability of becoming a `*` * the eight characters that surround any `*` become `\` `|` `/` `-`      `-` `/` `|` `\`, if they don't become stars, however, * if a character is within range of two `*`s, make it an `X` ### Example The 7×22 sky (frame for clarity only – don't output the frame) ``` ┌──────────────────────┐ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └──────────────────────┘ ``` could with 1% probability become ``` ┌──────────────────────┐ │ * │ │ │ │ │ │ │ │ │ │ * │ │ │ └──────────────────────┘ ``` and the next step ``` ┌──────────────────────┐ │ - - * │ │ /|\ │ │ * │ │ │ │ \|/ │ │ - - │ │ /|\ │ └──────────────────────┘ ``` and then ``` ┌──────────────────────┐ │ - - │ │ /|\ \|/ │ │ - - │ │ /|\ │ │ │ │ * * │ │ │ └──────────────────────┘ ``` and ``` ┌──────────────────────┐ │ │ │ │ │ │ │ │ │ \|X|/ │ │ - X - │ │ /|X|\ * │ └──────────────────────┘ ``` and so on ``` ┌──────────────────────┐ │ │ │ │ │ │ │ * │ │ │ │ \|/│ │ - -│ └──────────────────────┘ ``` [Answer] # ES6, 520 496 bytes Clipping and everything else should work now. ``` (w,h,p,i,r=0,s=($=>{while(++r<i)for(j=0,_=$[r]=[],z=$[r-1]||[];j<w*h;){k=j+1,l='*',c=0 n=(j%w&&z[j-1]==l&&++c)|(k%w&&z[k]==l&&++c)?'-':' ' n=(z[j-w]==l&&++c)|(z[j+w]==l&&++c)?'|':n n=(j%w&&z[j-w-1]==l&&++c)|(k%w&&z[k+w]==l&&++c)?'\\':n n=(k%w&&z[k-w]==l&&++c)|(j%w&&z[j+w-1]==l&&++c)?'/':n _[j++]=Math.random()<p?l:c>1?'X':n}})(x=[])||x)=>{c=document.body.children[0],r=0;while(++r<i)setTimeout((k=0)=>{for(r++,c.innerHTML='';k<h;)c.innerHTML+=s[r].slice(k*w,++k*w).join('')+'\n'},90*r);r=0} ``` [View animation!](https://jsfiddle.net/2ndAttmt/utt4phee/2/) Saved 24 bytes thanks to Zacharý's tip. ## Old solution, 478 bytes (with clipping bug) I think I got all the rules correct, however the solution has a clipping problem where everything exiting right/left wraps around one line lower/higher on the opposite side. ``` (w,h,p,i,r=0,s=($=>{while(++r<i)for(j=0,_=$[r]=[],z=$[r-1]||[];j<w*h;){c=0 n=(z[j-1]=='*'&&++c)|(z[j+1]=='*'&&++c)?'-':' ' n=(z[j-w]=='*'&&++c)|(z[j+w]=='*'&&++c)?'|':n n=(z[j-w-1]=='*'&&++c)|(z[j+w+1]=='*'&&++c)?'\\':n n=(z[j-w+1]=='*'&&++c)|(z[j+w-1]=='*'&&++c)?'/':n _[j++]=Math.random()<p?'*':c>1?'X':n}})(x=[])||x)=>{c=document.body.children[0],r=0;while(++r<i)setTimeout((k=0)=>{for(r++,c.innerHTML='';k<h;)c.innerHTML+=s[r].slice(k*w,++k*w).join('')+'\n'},90*r);r=0} ``` [View old.](https://jsfiddle.net/2ndAttmt/utt4phee/) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 65 chars or 71 bytes\* Prompts for dimensions (rows, columns), then for iterations (not counting initial state), then for probability (as *n* in ¹⁄*ₙ*). ``` ⎕{1=?⍺⍺:'*'⋄2≤+/b←'*'=1↓4⌽,⍵:'X'⋄⊃b/'-/|\\|/-'}⌺3 3{⍺⍺⎕←⍵}⍣⎕⊢⎕⍴'' ``` [Try it online!](https://tio.run/##JY/BTgIxEIbv@xRza4Ksy4KGhGRjFPWkJzTRhEuBXWhSWrItEQKcNKjIEhPj0Yv6CHoh8WXmRdbp0jSd/plv/pnhI@n3plzqfo7ZhuHmvXnLWGcsZM/EjAG@PMCJ1rZ1fHFVCCJaZ/vXzctTIE5PQCvwE2UiF42dyjga8glzpdkHJDoFJbox9IQZST71PHx6PBdpnJPPLIyOMNvSbbASI/MqPn/vBR1cvpKOQly@HeD6r4zZb4PdOABX952A@cG83Z4HPlvgeluD2mxnQo5USfACsy8nVp/uzX4Yy6lrDsVxzb06VKvFfHVI9Z0pO9nVcjxUxjt0lMsJG6fcCq0or7QlYKysUH0QSljBJRjLbeyFlcqODwP62gF0B1zRxjqB0j8 "APL (Dyalog Unicode) – Try It Online") `⎕⍴''` prompt for input and use that to **r**eshape an empty string, padding with spaces as needed `⊢` yield that …`⍣⎕` prompt for input and apply the following function on the above (*⍵*) that many times:  …`{`…`}` derive a function using the below function as operand (*⍺⍺*), as follows:   `⎕←⍵` print the argument   `⍺⍺` apply the following function:    …`⌺3 3` apply the following function on each element's 3×3 Moore neighborhood:     `⎕{`…`}` get input and use it as operand (*⍺⍺*) to derive a new function      `?⍺⍺` random integer among the first *⍺⍺* integers      `1=` Boolean if equal to one      `:` if true:       `'*'` return a star      `⋄` else:       `,⍵` ravel (flatten) the argument (the Moore neighborhood)       `4⌽` rotate it cyclically four steps to the left       `1↓` drop one element (the original center)       `'*'=` Boolean list where equal to a star       `b←` store that as *b*       `+/` sum that       `2≤` Boolean if two or higher       `:` if true:        `'X'` return an X       `⋄` else:        `b/'-/|\\|/-'` use the *b* to to filter the string        `⊃` pick the first one, if there are none, pick the prototype (a space) --- \* To run in Dyalog Classic, simply replace `⌺` with `⎕U233A` . ]
[Question] [ Given a non-negative integer `N`, output the smallest odd positive integer that is a strong pseudoprime to all of the first `N` prime bases. This is OEIS sequence [A014233](https://oeis.org/A014233). ## Test Cases (one-indexed) ``` 1 2047 2 1373653 3 25326001 4 3215031751 5 2152302898747 6 3474749660383 7 341550071728321 8 341550071728321 9 3825123056546413051 10 3825123056546413051 11 3825123056546413051 12 318665857834031151167461 13 3317044064679887385961981 ``` Test cases for `N > 13` are not available because those values have not been found yet. If you manage to find the next term(s) in the sequence, be sure to submit it/them to OEIS! ## Rules * You may choose to take `N` as a zero-indexed or a one-indexed value. * It's acceptable for your solution to only work for the values representable within your language's integer range (so up to `N = 12` for unsigned 64-bit integers), but your solution must theoretically work for any input with the assumption that your language supports arbitrary-length integers. --- ## Background Any positive even integer `x` can be written in the form `x = d*2^s` where `d` is odd. `d` and `s` can be computed by repeatedly dividing `n` by 2 until the quotient is no longer divisible by 2. `d` is that final quotient, and `s` is the number of times 2 divides `n`. If a positive integer `n` is prime, then [Fermat's little theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem) states: [![Fermat](https://i.stack.imgur.com/R8xNG.png)](https://i.stack.imgur.com/R8xNG.png) In any [finite field](https://en.wikipedia.org/wiki/Finite_field) `Z/pZ` (where `p` is some prime), the only square roots of `1` are `1` and `-1` (or, equivalently, `1` and `p-1`). We can use these three facts to prove that one of the following two statements must be true for a prime `n` (where `d*2^s = n-1` and `r` is some integer in `[0, s)`): [![Miller-Rabin conditions](https://i.stack.imgur.com/dss7f.png)](https://i.stack.imgur.com/dss7f.png) The [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) operates by testing the contrapositive of the above claim: if there is a base `a` such that both of the above conditions are false, then `n` is not prime. That base `a` is called a *witness*. Now, testing every base in `[1, n)` would be prohibitively expensive in computation time for large `n`. There is a probabilistic variant of the Miller-Rabin test that only tests some randomly-chosen bases in the finite field. However, it was discovered that testing only prime `a` bases is sufficient, and thus the test can be performed in an efficient and deterministic manner. In fact, not all of the prime bases need to be tested - only a certain number are required, and that number is dependent on the size of the value being tested for primality. If an insufficient number of prime bases are tested, the test can produce false positives - odd composite integers where the test fails to prove their compositeness. Specifically, if a base `a` fails to prove the compositeness of an odd composite number, that number is called a *strong pseudoprime* to base `a`. This challenge is about finding the odd composite numbers who are strong psuedoprimes to all bases less than or equal to the `N`th prime number (which is equivalent to saying that they are strong pseudoprimes to all *prime* bases less than or equal to the `N`th prime number). [Answer] # C, ~~349~~ ~~295~~ ~~277~~ ~~267~~ 255 bytes ``` N,i;__int128 n=2,b,o,l[999];P(m){i<N&&P(m<2?l[i++]=n:n%m?m-1:n++);}main(r){for(P(scanf("%d",&N));r|!b;)for(++n,b=i=N;i--&&b;){for(b=n-1,r=0;~b&1;b/=2)++r;for(o=1;b--;o=o*l[i]%n);for(b=o==1;r--;o=o*o%n)b|=o>n-2;for(o=r=1;++o<n;r&=n%o>0);}printf("%llu",n);} ``` Takes 1-based input on stdin, e.g.: ``` echo "1" | ./millerRabin ``` --- It certainly isn't going to discover any new values in the sequence any time soon, but it gets the job done. UPDATE: now even slower! * Slightly faster and shorter, with inspiration from Neil A's answer (`a^(d*2^r) == (a^d)^(2^r)`) * Significantly slower again after realising that *all* solutions to this challenge will be odd, so there is no need to explicitly enforce that we only check odd numbers. * Now using GCC's `__int128`, which is shorter than `unsigned long long` while also working with larger numbers! Also on little-endian machines, the printf with `%llu` still works fine. ### Less-minified ``` N,i; __int128 n=2,b,o,l[999]; P(m){i<N&&P(m<2?l[i++]=n:n%m?m-1:n++);} main(r){ for(P(scanf("%d",&N));r|!b;) for(++n,b=i=N;i--&&b;){ for(b=n-1,r=0;~b&1;b/=2)++r; for(o=1;b--;o=o*l[i]%n); for(b=o==1;r--;o=o*o%n)b|=o>n-2; for(o=r=1;++o<n;r&=n%o>0); } printf("%llu",n); } ``` ### (Outdated) Breakdown ``` unsigned long long // Use the longest type available n=2,N,b,i,d,p,o, // Globals (mostly share names with question) l[999]; // Primes to check (limited to 999, but if you // want it to be "unlimited", change to -1u) m(){for(o=1;p--;o=o*l[i]%n);} // Inefficiently calculates (l[i]^p) mod n // I cannot possibly take credit for this amazing prime finder; // See https://codegolf.stackexchange.com/a/5818/8927 P(m){i<N&&P(m<2?l[i++]=n:n%m?m-1:n++);} main(r){ for( P(scanf("%llu",&N)); // Read & calculate desired number of primes r|!b;){ // While we haven't got an answer: n=n+1|1; // Advance to next odd number for(b=1,i=N;i--&&b;){ // For each prime... for(d=n-1,r=0;~d&1;d/=2)++r; // Calculate d and r: d*2^r = n-1 // Check if there exists any r such that a^(d*2^r) == -1 mod n // OR a^d == 1 mod n m(p=d); for(b=o==1;r--;b|=o==n-1)m(p=d<<r); // If neither of these exist, we have proven n is not prime, // and the outer loop will keep going (!b) } // Check if n is actually prime; // if it is, the outer loop will keep going (r) for(i=r=1;++i<n;r&=n%i!=0); } printf("%llu",n); // We found a non-prime; print it & stop. } ``` --- As mentioned, this uses 1-based input. ~~But for n=0 it produces 9, which follows the related sequence <https://oeis.org/A006945>.~~ Not any more; now it hangs on 0. Should work for all n (at least until the output reaches 2^64) but is incredibly slow. I have verified it on n=0, n=1 and (after a **lot** of waiting), n=2. [Answer] # Python 2, ~~633~~ ~~465~~ ~~435~~ ~~292~~ ~~282~~ ~~275~~ ~~256~~ 247 bytes 0-indexed > > Question your implementation and try something new > > > Converting from a function to a program saves some bytes somehow... If Python 2 gives me a shorter way to do the same thing, I'm going to use Python 2. Division is by default integer, so an easier way to divide by 2, and `print` doesn't need parentheses. ``` n=input() f=i=3 z={2} a=lambda:min([i%k for k in range(2,i)]) while n: if a():z|={i};n-=1 i+=2 while f: i+=2;d,s,f=~-i,0,a() while~d&1:d/=2;s+=1 for y in z: x=y**d%i if x-1: for _ in[]*s: x*=x if~x%i<1:break else:f=1 print i ``` [Try it online!](https://tio.run/##LY1Rj4IwEITf@yv2BQNYcoJv1f0lxlxq2uoGXAlgLHjy17mWu7fZb2Z22nG4PbhaFkbi9jmkmXBIuBcTvquP0Njo@8VodSdOT5TU4B4d1EAMnearTStJ2TkTrxs1FlgJIAc6zdT0g2/6HLjAMrAtVv8Rp/7Og5G9dDgXJHcyFASs/mw2pTJfwe@3sRnXxrg2hR54HPPcJBRkmPFFGeGa@Q6Z0znvVwA@R78KcrNP6FiqS2d1HZFteqtceN12xAPQsux@AQ "Python 2 – Try It Online") Python is notoriously slow compared to other languages. Defines a trial division test for absolute correctness, then repeatedly applies the Miller-Rabin test until a pseudoprime is found. [Try it online!](https://tio.run/##LY3BboMwEETvfMVeqIAsakxvTvwlURQ5sV1WkAUBVYA0/HXP1Ka9zb6Z2WmnoWy4WFdGwhkdakXcfg1Jih/4LF4osNb3q9HyTpycKK7ANR1UQAyd5k@bFEjpOY0eJdUWWEZADnSSyvlbPel14FwJz3aq@I84@XceDPbo1JIT7tEXItj8xbwJad693@9CM6xNYW32PRjVlGUmJi/9zJiLALfMxWdO56zfAIyZGjdBbhljOgp57ayuArJ1b6Xzr9uOeABa1/0PN/lN30r7Cw "Python 2 – Try It Online") **EDIT**: Finally golfed the answer **EDIT**: Used `min` for the trial division primality test and changed it to a `lambda`. Less efficient, but shorter. Also couldn't help myself and used a couple of bitwise operators (no length difference). In theory it should work (slightly) faster. **EDIT**: Thanks @Dave. My editor trolled me. I thought I was using tabs but it was being converted to 4 spaces instead. Also went through pretty much every single Python tip and applied it. **EDIT**: Switched to 0-indexing, allows me to save a couple of bytes with generating the primes. Also rethought a couple of comparisons **EDIT**: Used a variable to store the result of the tests instead of `for/else` statements. **EDIT**: Moved the `lambda` inside the function to eliminate the need for a parameter. **EDIT**: Converted to a program to save bytes **EDIT**: Python 2 saves me bytes! Also I don't have to convert the input to `int` [Answer] # Perl + Math::Prime::Util, 81 + 27 = 108 bytes ``` 1 until!is_provable_prime(++$\)&&is_strong_pseudoprime($\,2..nth_prime($_));$_="" ``` Run with `-lpMMath::Prime::Util=:all` (27-byte penalty, ouch). ## Explanation It's not just Mathematica that has a builtin for basically anything. Perl has CPAN, one of the first large library repositories, and that has a huge collection of ready-made solutions for tasks like this one. Unfortunately, they aren't imported (or even installed) by default, meaning that it's basically never a good option to use them in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), but when one of them happens to fit the problem perfectly… We run through consecutive integers until we find one that's not prime, and yet a strong pseudoprime to all integer bases from 2 to the *n*th prime. The command-line option imports the library that contains the builtin in question, and also sets implicit input (to line-at-a-time; `Math::Prime::Util` has its own builtin bignum library that doesn't like newlines in its integers). This uses the standard Perl trick of using `$\` (output line separator) as a variable in order to reduce awkward parses and allow the output to be generated implicitly. Note that we need to use `is_provable_prime` here to request a deterministic, rather than probabilistic, prime test. (Especially given that a probabilistic prime test is likely using Miller-Rabin in the first place, which we can't expect to give reliable results in this case!) # Perl + Math::Prime::Util, 71 + 17 = 88 bytes, in collaboration with @Dada ``` 1until!is_provable_prime(++$\)&is_strong_pseudoprime$\,2..n‌​th_prime$_}{ ``` Run with `-lpMntheory=:all` (17 byte penalty). This uses a few Perl golfing tricks that I either didn't know (apparently Math::Prime::Util has an abbreviation!), knew about but didn't think of using (`}{` to output `$\` implicitly once, rather than `"$_$\"` implicitly every line), or knew about but somehow managed to misapply (removing parentheses from function calls). Thanks to @Dada for pointing these out to me. Apart from that, it's identical. ]
[Question] [ **Example run added 4/11** **Rules Clarification 4/8: All submissions will be competing in one giant free-for-all tournament consisting of as many matches as my computer can perform in 48 hours.** Anyone who's spent any time watching streams on Twitch is aware of the prevalence of [DeepBot](http://deepbot.deep.sg/), and is perhaps even familiar with its [Bank Heist](http://wiki.deepbot.tv/bankheist) betting game. This King of the Hill tournament is directly inspired by that game. Don't worry, though. I think I've thrown enough extra kinks into this version to keep things interesting. ## A quick example ``` #####GAME 13: 16 players###### Round 1: gunHeCK bet 0. PassivePanga bet 69. SnitcherKing bet 1. Lurker bet 0. OC'sRandomTpyos bet 1. MonisAddiction bet 69. RaysFive01K bet 28. LimeadeSneaktar bet 1. KaylorrCriterion bet 0. HardHatUmar bet 0. HeCKuSumer bet 185. Round 2 HeCKuSumer decided to !guncheck. LimeadeSneaktar decided to double cross. MonisAddiction decided to all in. OC'sRandomTpyos decided to acquire intel. RaysFive01K decided to deposit. SnitcherKing decided to finger. PassivePanga decided to !guncheck. Results PassivePanga failed. :( SnitcherKing failed. :( OC'sRandomTpyos was successful, and may gain ¥0 MonisAddiction failed. :( RaysFive01K was successful, and may gain ¥0 LimeadeSneaktar was successful, and may gain ¥1 HeCKuSumer failed. :( Results: 0. KaylorrCriterion: 3600 1. Lurker: 3600 2. gunHeCK: 3600 3. SnitcherKing: 3586 4. PassivePanga: 2634 5. LimeadeSneaktar: 2496 6. HeCKuSumer: 1909 7. HardHatUmar: 490 8. RaysFive01K: 255 9. OC'sRandomTpyos: 170 10. MonisAddiction: 0 (In this round, 7 players joined the heist, but the dice only rolled right for 3 of them. Of those, only LimeadeSneaktar brought any home--having stolen it from OcsRandomTpyos. RaysFive01K won significantly more, but deposited it all at the bank before leaving. At this point, the players who did not heist are doing well, living off their day jobs.) #####GAME 14: 231 players###### Round 1: Lurker bet 0. HeCKuSumer bet 190. KaylorrCriterion bet 0. HardHatUmar bet 0. MonisAddiction bet 0. OC'sRandomTpyos bet 1. gunHeCK bet 0. LimeadeSneaktar bet 1. RaysFive01K bet 25. PassivePanga bet 69. SnitcherKing bet 1. Round 2 PassivePanga decided to !guncheck. OC'sRandomTpyos decided to buy guard. HeCKuSumer decided to !guncheck. SnitcherKing decided to finger. RaysFive01K decided to deposit. LimeadeSneaktar decided to double cross. Results HeCKuSumer failed. :( OC'sRandomTpyos failed. :( LimeadeSneaktar failed. :( RaysFive01K failed. :( PassivePanga failed. :( SnitcherKing failed. :( Results: 0. KaylorrCriterion: 3840 1. Lurker: 3840 2. gunHeCK: 3840 3. SnitcherKing: 3825 4. PassivePanga: 2805 5. LimeadeSneaktar: 2495 6. HeCKuSumer: 1959 7. HardHatUmar: 490 8. MonisAddiction: 240 9. RaysFive01K: 229 10. OC'sRandomTpyos: 161 Six players heisted--but should have been paying more attention to the rabble and backed out, because the probabilities dropped too low to win, and all failed. #####GAME 15: 300 players###### Round 1: OC'sRandomTpyos bet 1. Lurker bet 0. SnitcherKing bet 1. MonisAddiction bet 69. LimeadeSneaktar bet 1. gunHeCK bet 0. HardHatUmar bet 0. RaysFive01K bet 22. KaylorrCriterion bet 0. HeCKuSumer bet 195. PassivePanga bet 69. Round 2 HeCKuSumer decided to !guncheck. OC'sRandomTpyos decided to buy guard. MonisAddiction decided to all in. PassivePanga decided to !guncheck. LimeadeSneaktar decided to double cross. RaysFive01K decided to deposit. SnitcherKing decided to finger. Results OC'sRandomTpyos failed. :( SnitcherKing failed. :( MonisAddiction was successful, and may gain ¥0 LimeadeSneaktar failed. :( RaysFive01K failed. :( HeCKuSumer failed. :( PassivePanga failed. :( And here, the probabilities dropped too low to win again--except for MonisAddiction, who went all in, and therefore avoided the probability modification incurred by the rabble backing out. No winnings are listed here, because a player who wins going all in immediately adds all winnings to its holdings without any possible modification by other players' actions. ``` ## Game Rules ### Tournament/Game Structure * The tournament will consist of a number of games chosen uniformly at random between 1000 and 1100, in which every *serious* submission will be competing simultaneously in a free-for-all. * Every player starts the first game with 240 *credits* and each subsequent game with the number of credits it had at the end of the previous game. * Each game proceeds in 2 rounds, and in each round, players are called in an order determined uniformly at random to make one decision: + In the first round, a player may pay any integer number of credits between 0 and its current credit holdings to stake participation in a bank heist. + In the second round, each player that elected to participate in the heist by wagering at least one credit (hereafter referred to as "heisters") may decide to let its bet ride (and, while doing so, possibly perform some other action), opt out of the heist, or go all-in. (These options are further described below.) * Based on the number of heisters and the total number of credits they paid, one of five banks is selected on which to stage a heist. This selection affects the individual probability of victory and the odds by which the payout is determined. (The banks are described below.) * Each heister that did not opt out will, with the bank's (modified) probability, win its stake multiplied by the bank's (modified) betting odds (rounded down), or else lose its stake. Note that each player's success or failure is determined *individually*--some will succeed where others fail. * All players, whether they participated or not, succeeded or failed, then receive a paycheck (with exceptions described below). * Note that it is impossible to permanently leave the game. At worst, a player may have to wait a game to receive its next paycheck. * After all 1000-1100 games, the player with the greatest number of credits will be declared the winner of that tournament. * The tournament will be repeated an unspecified number of times (as many as can be computed in 48 hours) and the player earnings across all tournaments summed in order to determine the overall winner of this contest. ### The Second Betting Round * Any player who has wagered a positive stake in the first round may participate in the second round. * In this round, a player may: + reply with the string "back out" to cancel its bet. This will set its wager to zero for the current heist and also slightly decrease the probability the players remaining in the heist will succeed. By taking this option, a player forgoes the 240 credit paycheck that follows the heist as punishment for putting the remaining heisters at risk. (The remaining heisters will succeed with a probability equal to the bank's probability times the fraction of heisters that did not "back out".) + reply with the string "all in" to blow its entire credit holdings--and take out a payday loan on its next 240 credit paycheck--to buy all the best gear and intel for a heist and go in alone, guns blazing, without relying on anyone. Such a player's victory probability cannot be affected by other heisters dropping out of the heist, nor can its winnings be stolen by double-crossers. Winning payouts will be determined as if its bet were its entire credit holdings plus 240, while loss will set its holdings to zero. + Reply with any other string (including the empty string) in order to stick with the previous bet and go through with the heist as normal. (Recommended reply: "!guncheck"). Certain replies will have additional side effects: - A reply of "change jobs" will cause the player to quit its job. Beginning this round, at the end of each round, the player will have a 5% chance to get hired in a new position. If this succeeds, the player is hired and immediately receives its first paycheck. Each new job is guaranteed to pay exactly 5% more than the last (rounded down). This action will succeed whether or not the heist succeeds. - A reply of "acquire intel" will, if the heist succeeds, cause the player to spend all of its winnings from that heist to get an extra 0.00001 per credit thus spent on the odds for the bank that was heisted *for that player only*. This odds modification is permanent. As an example, if a player chooses this action when heisting bank 1 and wins 6969 credits in a heist, bank 1's odds for that player will be permanently increased by 0.06969 and the player will receive nothing from that heist. - A reply of "buy guard" will cause the player to buy off one of the security guards at the bank being heisted. In exchange for a permanent reduction of 1 credit on that player's paycheck (the guard's regular bribe), the player will receive a "permanent" increased victory probability *at that bank* (due to the guard "forgetting to mention" that player to the cops when asked). The probability will increase by exactly 1% of the difference between the player's current victory probability at that bank and 100%. This action will succeed even if the heist fails. NOTE: If at any time, a player has not enough credits to pay all of its guard bribes, it immediately and "permanently" loses as many probability bonuses as the number of bribes that could not be paid, selected uniformly at random from all bribes registered. - A reply of "deposit" will, if the heist succeeds, leave a player's entire winnings in an account at the bank heisted. The credits will not be accessible for any purpose nor be counted towards a player's score until withdrawn. This account will pay interest at a rate of 0.14% per game. - A reply of "withdraw" will, if the heist succeeds, add to a player's winnings the entire contents of its account at the bank heisted. The account will be zeroed as a result. Note that these additional winnings *can* be stolen by double-crossers. - A reply of "double cross" will do one of two things: * If the number of heisters who played "double cross" is at most 1/10th (rounded down) of the total number of non-rabble heisters who decided to go through with the heist (or exactly one if there are less than 10 such players), the player will receive additional winnings equal to the total winnings of all non-double-crossers divided by the number of double-crossers (rounded down). All non-double-crossers in this case receive 0 credits from the heist. In other words, the double-crossers steal everyone else's credits and divide it evenly amongst themselves. * If the number of heisters who played "double cross" exceeds the threshold, the player will receive no winnings (if its heist was successful), have its paycheck cut in half, and be fired from its job. (See "change jobs".) All non-double-crossers (including rabble) in this case will receive a bonus payment of the total winnings of all double-crossers divided by the total number of non-double-crossers. In other words, the conspiracy got too big to keep a secret, the conspirators were rooted out and excluded from the heist, and everyone divided up their stakes for punishment--and their reputation for dirty dealing lost them their jobs as well. - A reply of "finger" (as in "fingering a double-crossing scoundrel rat") will, if the heist succeeds, give the player eight opportunities (drawing uniformly with replacement from the set of non-rabble heisters) to identify a double-crosser *which has not already been so identified*. * Each double-crosser identified this way will immediately pay the fingerer 25% of its current credit holdings (rounded down) in lieu of being shot, lose its job and have its paycheck cut in half (because the boss won't tolerate bad behavior), and lose 5% of its probability of victory at the bank being heisted (as other heisters are extra suspicious in the future and likely to throw it under the bus if things get hairy). Double-crossers identified this way do not affect whether the double-cross was successful for other double-crossers, but they do not receive any of the stolen credits from the double-cross, and said stolen credits will be redistributed back to the non-double-crossers. * If no double-crossers are identified this way, the snitch will get stitches for wasting everyone's time--and also pay half its winnings from the current heist, take a 5% cut on its paycheck (boss cuts the tattletale's hours), and lose 5% of its betting odds at the current bank (as other heisters are less likely to be generous/fair with their winnings in the future). The half of its winnings thus lost will be distributed to the unfingered double-crossers if the double-crossers succeeded, or the non-double-crossers (including rabble) if the double-crossers failed. ### The Banks The bank is selected using the index `numheisters + int(totalamountbet/100000)`, where numheisters is the number of players which wagered a positive stake in round 1 and totalamountbet is the sum of the stakes of all of those players. In other words, a hundred thousand credits is as good as 1 additional heister. Based on this index one of the following banks will be chosen, the bank with the highest threshold that the index meets or exceeds: ``` Bank Index Threshold Victory Prob. Bet Odds ---- --------------- ------------- -------- 0:Municipal 0 0.540 0.80 1:City 20 0.488 1.10 2:State 40 0.425 1.30 3:National 60 0.387 1.65 4:Federal Reserve 80 0.324 1.95 ``` Note that as a tournament continues, the probability of reaching the highest bank level will increase, as the amount each player can bet trends upwards. Note also that these are only *initial* odds and probabilities, before they have been modified by any "acquire intel" or "buy a guard" actions. With the initial probabilities and odds, only the City and National banks have expected winnings exceeding expected losses. ### The Rabble * The tournament also contains 500 other players, called the "rabble", who participate as regular players in heists but are not scored in the end. These serve to make each game different and somewhat less predictable, and make it possible to reach the riskier/more rewarding banks even with only a few "real" players. * Each game will include some subset of rabble to participate chosen uniformly at random over all subsets of rabble. * All rabble use the following strategy: + Randomly choose to bet with probability equal to the probability of succeeding at the bank that would be selected based on the decisions of the players *who have already made their decision this round*. + If betting a nonzero amount, choose the largest of the following amounts that would not exceed its current holdings: 69, 420, 6969, 80085. + In the second round, "back out" with probability equal to 5% plus 50% of the proportion of bettors that have already backed out, otherwise heist as normal. (Note that this means early players in the second round that back out can have huge cascading effects among the rabble--pay attention and be ready for the heist to collapse before it even starts.) ### Inputs and Outputs In both rounds, programs will be given the following information, in *exactly* this order, *as command line arguments*. Unless otherwise stated, all values are integers containing no decimal. 1. The current game number (zero-indexed) 2. The round number of the current game (1 or 2) 3. The number of players in the current game (including rabble). 4. The number of players that have already taken their turns this round. 5. The number of heisters that have committed a positive stake so far. (In the second round, this will actually be the total number of heisters who bought in in the first round.) 6. The total number of credits invested so far. (In the second round, this will actually be the total number of credits invested in the first round--in particular, it *does not* include more than the initial stakes of "all in" heisters and *does* include the stakes of "back out" heisters.) 7. The number of heisters who have confirmed in the second round (i.e. did not "back out"). This will be zero during the first round. 8. The (zero-indexed) number of the bank to be heisted (during the first round, the bank that would be heisted if no one else bet) 9. The number of credits currently available to the player. 10. The number of credits the player bet in the first round. (This is always zero in the first round.) 11. The number of credits the player will receive in its paycheck at the end of each game. 12. 1 if the player is currently receiving a paycheck, 0 if the player is unemployed 13. Player's rank on the leaderboard (not including rabble) as of the end of the previous game, 1-indexed. (Defined as 1+the number of players with strictly more credits at that time. E.g. during the first game, all players have rank 1.) 14. The mean number of credits held by all players (not including rabble) (represented as a decimal number) 15. The mean absolute deviation in the number of credits held by all players (not including rabble) (represented as a decimal number) 16. The maximum number of credits held by any player (i.e. the number of credits held by a rank 1 player, not including rabble) 17. The number of credits the player has stored in bank 0 account 18. Bank 1 account 19. Bank 2 account 20. Bank 3 account 21. Bank 4 account 22. The player's individual probability of victory at bank 0 23. Bank 1 probability 24. Bank 2 probability 25. Bank 3 probability 26. Bank 4 probability 27. The player's individual payout odds upon a successful heist at bank 0 28. Bank 1 odds 29. Bank 2 odds 30. Bank 3 odds 31. Bank 4 odds In the first round of a game, a player program must print to stdout an integer between 0 and the total number of credits in that player's account. Any bet amount greater than the available credit balance is taken to be a max bet. Any other output (or error condition) will be interpreted as a zero bet. In the second round of a game, a player program must print to stdout a string as described in the section "The Second Betting Round" above. An error condition here is taken to be the default action: go through with the heist as normal. ## Controller The tournament will be run using [this controller](https://github.com/quintopia/BankHeist). Bot examples there as well. Still being tested. More code to come. Feel free to submit bug fixes (on github). Will be updated if any rules change as well. To run a single tournament on your own machine, add a line to competitors.txt and then use: ``` python bankheist.py 1000 ``` ## Contest Rules * Players may submit any number of player programs in any freely available language the programs of which may receive command line arguments. * Submissions must include fairly explicit instructions for how to compile programs and run them on my PC, including names of tools needed and exact commands to be issued. Submission must include at least one command which executes the program and may have command line arguments appended directly to it. * Submissions must also have a unique name to identify them (which contains no spaces). * Programs must run in a reasonably short amount of time. (I'm not setting an upper bound on what constitutes reasonable. Rather, I will simply advise the creator any entry that seems to have an outsize execution time to speed it up.) * Programs may *not* read or write to files. Nor may they use any other method of storing information between runs. The point of this challenge is to make complex decisions on the basis of limited/summarized information. * Any and all of these rules are subject to change at any time if necessary. A message will be added at the *top* of this post indicating any such changes. * This contest ends no sooner than one week after the last *user* submits posts his or her *first submission*. Modifications of existing submissions are allowed at any time up until the contest ends. I'll do my best to keep the current deadline updated in a message at the *top* of this post. * This contest ends no sooner than one week after the last time the rules were changed, if any. I will do my best to leave comments for any users affected by any rule changes. * You better bet I'll be participating in this contest myself. ;) [Answer] # Some "bad" examples of programs. These are some bots I've written to test the controller. Mostly, they just do the minimum necessary thing to test one specific type of action. Depending on the level of participation in this KotH, anywhere from a few to all of these will be included in the final tournament, since a lot of the strategy in the game will come from dealing with the behaviors of lots of different bots. I include them all here mostly as "usage" examples. ## Lurker Never bet. If you're not beating this, rethink your strategy. ``` print 0 ``` ## PassivePanga Always bet 69. ``` import sys round = int(sys.argv[2]) myyattas = int(sys.argv[9]) if round == 1: if myyattas > 69: print "69" else: print "0" else: print "!guncheck" ``` ## KaylorrCriterion Make a Kelly bet if and only if the Kelly Criterion is met. As this rarely happens with doing some "acquire intel" and "buy guard" first, this generally gets the same result as Lurker. ``` import sys import ast game,round,numplayers,alreadyplayed,numbet,yattasbet,numready,bankid,myyattas,mybet,mypayment,hired,myrank,mu_yattas,sigma_yattas,max_yattas = map(ast.literal_eval,sys.argv[1:17]) bankholdings = map(int,sys.argv[17:22]) bankprobs = map(float,sys.argv[22:27]) bankodds = map(float,sys.argv[27:32]) def get_bank(bettors,credits): selector = min(4,int(bettors+int(credits/100000.)/20)) return bankprobs[selector],bankodds[selector] if round == 1: if alreadyplayed < 0.37*numplayers or numbet==0: print 0 #sys.stderr.write("1: %d,%d\n"%(alreadyplayed,numbet)) else: ratiosofar = numbet/float(alreadyplayed) bettors = ratiosofar * numplayers ratesofar = yattasbet/float(numbet) credits = bettors*ratesofar p,b = get_bank(bettors,credits) f = (p*(b+1)-1)/b print max(int(f*myyattas),0) #sys.stderr.write("2: %d,%d\n"%(p,b)) else: if alreadyplayed < 0.37*numbet or numbet==0: print "!guncheck" else: p,b = get_bank(numbet,yattasbet) realp = p*numready/float(alreadyplayed) f = (realp*(b+1)-(1-240./(myyattas+240.)))/b print "!guncheck" if f>0 else "back out" ``` ## gunHeCK Make a Kelly bet if and only if the number of heisters seen so far indicate that the bet *will* meet the Kelly criterion (but don't back out if wrong). Typically does worse than Lurker ``` import sys import ast game,round,numplayers,alreadyplayed,numbet,yattasbet,numready,bankid,myyattas,mybet,mypayment,hired,myrank,mu_yattas,sigma_yattas,max_yattas = map(ast.literal_eval,sys.argv[1:17]) bankholdings = map(int,sys.argv[17:22]) bankprobs = map(float,sys.argv[22:27]) bankodds = map(float,sys.argv[27:32]) def get_bank(bettors,credits): selector = min(4,int(bettors+int(credits/100000.)/20)) return bankprobs[selector],bankodds[selector] if round == 1: if alreadyplayed < 0.37*numplayers or numbet==0: print 0 #sys.stderr.write("1: %d,%d\n"%(alreadyplayed,numbet)) else: ratiosofar = numbet/float(alreadyplayed) bettors = ratiosofar * numplayers ratesofar = yattasbet/float(numbet) credits = bettors*ratesofar p,b = get_bank(bettors,credits) f = (p*(b+1)-1)/b print max(int(f*myyattas),0) #sys.stderr.write("2: %d,%d\n"%(p,b)) else: print "!gunHeCK" ``` ## Moni'sAddiction Go "all in" unless already winning. ``` import sys import random round = int(sys.argv[2]) myrank = int(sys.argv[13]) mybet = int(sys.argv[10]) if round == 1: if random.random()<0.1: print 1 else: print 69 else: if myrank>1: print "all in" else: if mybet==1: print "back out" else: print "!guncheck" ``` ## HeCKuSumer Always bet a small constant fraction of holdings. ``` import sys round = int(sys.argv[2]) myyattas = int(sys.argv[9]) if round==1: print int(0.1*myyattas) else: print "!guncheck" ``` ## OC'sRandomTpyos Change jobs a lot in early tournament. Spend all that money improving probabilities and odds. Then spend the last few games going all in. This would probably do a lot better without the going all in unless already in a top spot. ``` import sys import ast import random game,round,numplayers,alreadyplayed,numbet,yattasbet,numready,bankid,myyattas,mybet,mypayment,hired,myrank,mu_yattas,sigma_yattas,max_yattas = map(ast.literal_eval,sys.argv[1:17]) bankholdings = map(int,sys.argv[17:22]) bankprobs = map(float,sys.argv[22:27]) bankodds = map(float,sys.argv[27:32]) if round == 1: if game<800 or myrank>3: print 1 else: print myyattas/4 else: if game<800: if hired: print "change jobs" else: print random.choice(["acquire intel","buy guard"]) else: if myrank>3: print "all in" else: print "!guncheck" ``` ## HardHatUmar Changes jobs whenever possible for most of the tournament. Avoids betting more than the minimum necessary. Does decently well, but not great. ``` import sys game = int(sys.argv[1]) round = int(sys.argv[2]) hired = int(sys.argv[12]) if round==1: if game < 900 and hired: print 1 else: print 0 else: print "change jobs" ``` # LimeadeSneaktar Change jobs whenever possible during the first part of the tournament. Spend every other game double crossing. Does decently well even against SnitcherKing. Will probably fare more poorly once many other bots are double crossing and fingering. If not--the rules may need changing. ``` import sys import ast game,round,numplayers,alreadyplayed,numbet,yattasbet,numready,bankid,myyattas,mybet,mypayment,hired,myrank,mu_yattas,sigma_yattas,max_yattas = map(ast.literal_eval,sys.argv[1:17]) bankholdings = map(int,sys.argv[17:22]) bankprobs = map(float,sys.argv[22:27]) bankodds = map(float,sys.argv[27:32]) if round==1: print 1 else: if hired and game<900: print "change jobs" else: print "double cross" ``` ## SnitcherKing Always bet the minimum, and always finger. Does pretty well in small tournaments that include LimeadeSneaktar. ``` import sys round = int(sys.argv[2]) if round == 1: print 1 else: print "finger" ``` ## RaysFive01K A bit more complicated--and therefore actually pretty good. Most of its advantage comes from depositing all winnings in early tournament (protecting them from double crossers) while driving up its win probabilities (and changing jobs to pay for all those guards and heists), then withdrawing them all at the end of the game (once they have earned serious interest and the probability of failing to withdraw is sufficiently low--though here losses to double crossers is a serious risk). This will definitely be in the tournament, and may or may not be a serious contender. ``` import sys import ast import random game,round,numplayers,alreadyplayed,numbet,yattasbet,numready,bankid,myyattas,mybet,mypayment,hired,myrank,mu_yattas,sigma_yattas,max_yattas = map(ast.literal_eval,sys.argv[1:17]) bankholdings = map(int,sys.argv[17:22]) bankprobs = map(float,sys.argv[22:27]) bankodds = map(float,sys.argv[27:32]) if round ==1: if game < 900: print myyattas/10 else: print 1 else: if game < 500 and hired: print random.choice(["change jobs","finger","buy guard"]) elif game < 900: print "deposit" elif bankholdings[bankid]>0: print "withdraw" else: if alreadyplayed/float(numplayers)<0.5: print "finger" else: print "back out" ``` [Answer] # Lone John ``` import sys import ast game,round,numplayers,alreadyplayed,numbet,creditsbet,numready,bankid,mycredits,mybet,mypayment,hired,myrank,mu_credits,sigma_credits,max_credits = map(ast.literal_eval,sys.argv[1:17]) bankholdings = map(int,sys.argv[17:22]) bankprobs = map(float,sys.argv[22:27]) bankodds = map(float,sys.argv[27:32]) if round == 1: if mycredits > 100 or hired: print(int(mycredits)/2) else: print(0) else: if bankprobs[int(bankid)] > 0.6: print("all in") elif int(mypayment) > 50 : print("buy guard") elif int(mycredits) > 200 and int(game) < 900 and hired == "1": print("change jobs") elif bankprobs[int(bankid)] * (float(numready)+1)/(float(alreadyplayed)+1) < 0.30: print "withdraw" else: print "!guncheck" ``` Bribes guards until he has the probability to win, then goes all in. Alone. Changes jobs when he needs more money to bribe guards. ]
[Question] [ Referencing [xkcd 1688](https://xkcd.com/1688/): [![guide](https://i.stack.imgur.com/xYMpp.png "Does the screeching chill your blood and herald death? If yes, banshee. If no, seagull.")](https://i.stack.imgur.com/xYMpp.png "Does the screeching chill your blood and herald death? If yes, banshee. If no, seagull.") Your task is to deduct the age of a map by asking the user questions. These question must be exactly the same as in the xkcd guide, except from the capitalisation and additional newline(s). Additionally, you should give the user some options to choose from, which don't have to be in the order as in the xkcd image. If the input doesn't match any of the expected answers, your program/function may behave in any undefined way. At the end, you should output the year/timespan the map was created. ## Examples (`>` denotes input, but you may choose something else): ### Example 1: ``` ISTANBUL OR CONSTANTINOPLE? (CONSTANTINOPLE, NEITHER, ISTANBUL) >ISTANBUL DOES THE SOVIET UNION EXISTS? (YES, NO) >NO ZAIRE? OR: 'HONG KONG (UK)' (YES, NO) >NO SERBIA / MONTENEGRO ARE? (ONE COUNTRY, TWO COUNTRIES) >TWO COUNTRIES HOW MANY SUDANS ARE THERE? (ONE, TWO) >ONE 2007-11 ``` ### Example 2: ``` ISTANBUL OR CONSTANTINOPLE? (CONSTANTINOPLE, NEITHER, ISTANBUL) >how are you error ``` [Answer] # Game Maker Language (GM 8.0), ~~10262~~ ~~10228~~ ~~10152~~ ~~10115~~ ~~8746~~ 1 + 8699 = 8700 bytes We define a script named `X` (1 byte). Each question is labelled with an integer. `X` takes such an integer, prompts the user with the corresponding question, and either returns the appropriate message or calls the next question. At each question, the user is prompted for an integer corresponding to the possible options. If the user does not match any of the options, then the prompt is exited. ``` A=argument1 Y="##YES (1), NO (2)"I="IS THERE A BIG LAKE IN THE MIDDLE OF "H="HOW MANY "switch argument0{case H:return show_message(A)break case I:return get_integer(A,1)break case 1:switch X(I,"ISTANBUL OR CONSTANTINOPLE##CONSTANTINOPLE (1), NEITHER (2), ISTANBUL(3)"){case 1:X(2)break case 2:X(19)break case 3:X(74)}break case 2:switch X(I,"DO ANY OF THESE EXIST?#- INDEPENDENT CANADA#- US TERRITORY OF ALASKA#- TOKYO"+Y){case 2:X(3)break case 1:X(11)}break case 3:switch X(I,"THE HOLY ROMAN EMPIRE?"+Y){case 1:X(H,"1805 OR EARLIER (BEFORE THIS POINT, THE MODERN IDEA OF A COMPLETE POLITICAL MAP OF THE WORLD GETS HARD TO APPLY.)")break case 2:X(4)}break case 4:switch X(I,"THE UNITED STATES?"+Y){case 2:X(H,"HOW SURE ARE YOU THAT THIS MAP IS IN ENGLISH")break case 1:X(5)}break case 5:switch X(I,"TEXAS IS...##PART OF MEXICO (1), INDEPENDENT (2), PART OF THE US (3)"){case 1:X(6)break case 2:X(H,"1834-45")break case 3:X(9)}break case 6:switch X(I,"FLORIDA IS PART OF...##SPAIN (1), THE US (2)"){case 1:X(7)break case 2:X(8)}break case 7:switch X(I,"PARAGUAY?"+Y){case 2:X(H,"1806H0")break case 1:X(H,"1811H7")}break case 8:switch X(I,"VENEZUELA AND/OR ECUADOR?"+Y){case 2:X(H,"1818-29")break case 1:X(H,"1830-33")}break case 9:switch X(I,"DOES RUSSIA BORDER THE SEA OF JAPAN?"+Y){case 2:X(10)break case 1:X(H,"1858-67")}break case 10:switch X(I,"THE US'S SOUTHERN BORDER LOOKS...##WEIRD (1), NORMAL (2)"){case 1:X(H,"1846-53")break case 2:X(H,"1854-56")}break case 11:switch X(I,"SOUTH AFRICA?"+Y){case 2:X(12)break case 1:X(16)}break case 12:switch X(I,"RHODESIA?"+Y){case 2:X(13)break case 1:X(15)}break case 13:switch X(I,"IS BOLIVIA LANDLOCKED?"+Y){case 2:X(14)break case 1:X(H,"1884-95")}break case 14:switch X(I,'"BUDA" AND "PEST" OR "BUDAPEST"?##BUDA AND PEST (1), BUDAPEST (2)'){case 1:X(H,"1868-72")break case 2:X(H,"1873-83")}break case 15:switch X(I,"IS NORWAY PART OF SWEDEN?"+Y){case 1:X(H,"1896H905")break case 2:X(H,"1906-09")}break case 16:switch X(I,"AUSTRIA-HUNGARY?"+Y){case 1:X(17)break case 2:X(18)}break case 17:switch X(I,"ALBANIA?"+Y){case 2:X(H,"1910H2")break case 1:X(H,"1913H8")}break case 18:switch X(I,"LENINGRAD?"+Y){case 2:X(H,"1919-23")break case 1:X(H,"1924-29")}break case 19:switch X(I,"DOES THE OTTOMAN EMPIRE EXIST?"+Y){case 1:X(2)break case 2:X(20)}break case 20:switch X(I,"THE SOVIET UNION?"+Y){case 2:X(21)break case 1:X(63)}break case 21:switch X(I,"NORTH KOREA?"+Y){case 2:X(22)break case 1:X(56)}break case 22:switch X(I,"SAINT TRIMBLE'S ISLAND?"+Y){case 2:X(23)break case 1:X(H,"NO, I MADE THAT ONE UP.")}break case 23:switch X(I,"IS JAN MAYEN PART OF THE KINGDOM OF NORWAY?##NOT YET (1), WHAT? (2), YES (3)"){case 1:X(2)break case 2:X(24)break case 3:X(49)}break case 24:switch X(I,"CAN YOU SEE THE FAMILIAR CONTINENTS?"+Y){case 1:X(25)break case 2:X(31)}break case 25:switch X(I,"THIS SOUNDS LIKE A PHYSICAL MAP OR SATELLITE PHOTO.##YES, THAT'S IT (1)"){case 1:X(26)}break case 26:switch X(I,"IS LAKE CHAD MISSING?"+Y){case 2:X(27)break case 1:X(30)}break case 27:switch X(I,"HOW FAR EAST DO THE AMERICAN PRAIRIES REACH?##INDIANA (1), THE MISSISSIPPI (2), NEBRASKA (3), WHAT PRAIRIES? (4)"){case 1:X(H,"BEFORE 1830")break case 2:X(H,"1830s-80s")break case 3:X(28)break case 4:X(29)}break case 28:switch X(I,I+"SOUTHERN CALIFORNIA? (CREATED BY MISTAKE)"+Y){case 2:X(H,"1860sH900s")break case 1:X(H,"1910s")}break case 29:switch X(I,I+"GHANA? (CREATED ON PURPOSE)"+Y){case 2:X(H,"1920s-50s")break case 1:X(H,"1960s-70s")}break case 30:switch X(I,"IS THE ARAL SEA MISSING?"+Y){case 2:X(H,"1970s-90s")break case 1:X(H,"2000s+")}break case 31:switch X(I,'RIVERS "SIRION" OR "ANDUIN"?'+Y){case 1:X(32)break case 2:X(36)}break case 32:switch X(I,"MORDOR?"+Y){case 2:X(33)break case 1:X(34)}break case 33:switch X(I,"BELERIAND?"+Y){case 1:X(H,"FIRST AGE")break case 2:X(H,"EARLY SECOND AGE")}break case 34:switch X(I,"NÚMENOR?"+Y){case 1:X(H,"LATE SECOND AGE")break case 2:X(35)}break case 35:switch X(I,"THE FOREST EAST OF THE MISTY MOUNTAINS IS...##GREENWOOD THE GREAT (1), MIRKWOOD (2), THE WOOD OF GREENLEAVES (3)"){case 1:X(H,"EARLY THIRD AGE")break case 2:X(H,"LATE THIRD AGE")break case 3:X(H,"FOURTH AGE")}break case 36:switch X(I,"CAIR PARAVEL?"+Y){case 1:X(37)break case 2:X(41)}break case 37:switch X(I,"CALORMEN?"+Y){case 2:X(38)break case 1:X(40)}break case 38:switch X(I,"LOTTA ISLANDS?"+Y){case 2:X(39)break case 1:X(H,"DAWN TREADER")}break case 39:switch X(I,"BERUNA##FORD (1), BRIDGE (2)"){case 1:X(H,"THE LION, THE WITCH, AND THE WARDROBE")break case 2:X(H,"PRINCE CASPIAN")}break case 40:switch X(I,"WEIRD RECURSIVE HEAVEN?"+Y){case 2:X(H,"ONE OF THE RANDOM LATER BOOKS")break case 1:X(H,"THE LAST BATTLE")}break case 41:switch X(I,"MOSSFLOWER?"+Y){case 1:X(H,"REDWALL")break case 2:X(42)}break case 42:switch X(I,"IS THE WORLD ON THE BACK OF A TURTLE?"+Y){case 1:X(H,"DISCWORLD")break case 2:X(43)}break case 43:switch X(I,"ARE YOU SURE THIS IS A MAP?"+Y){case 1:X(44)break case 2:X(46)}break case 44:switch X(I,"DID YOU MAKE IT YOURSELF?##YES (1)"){case 1:X(45)}break case 45:X(I,"IT'S VERY NICE.##THANK YOU! (1)")break case 46:switch X(I,"IS IT TRYING TO BITE YOU?"+Y){case 2:X(47)break case 1:X(48)}break case 47:switch X(I,"IS IT LARGER THAN A BREADBOX?"+Y+", ABOUT THE SAME (3)"){case 1:X(H,"TUBA")break case 2:X(H,"STAPLER")break case 3:X(H,"BREADBOX")}break case 48:switch X(I,"IF YOU LET IT GO, WHAT DOES IT DO?##HISSES AND RUNS AWAY (1), SCREECHES AND FLAPS AROUND THE ROOM BREAKING THINGS (2)"){case 1:X(H,"CAT")break case 2:X(H,"SEAGULL")}break case 49:switch X(I,"PAKISTAN?"+Y){case 2:X(50)break case 1:X(52)}break case 50:switch X(I,H+"GERMANYS ARE THERE?##ONE (1), ONE, BUT IT'S HUGE (2), TWO (3)"){case 1:X(51)break case 2:X(H,"1941-45")break case 3:X(H,"1946-47")}break case 51:switch X(I,"PERSIA OR IRAN?##PERSIA (1), IRAN (2)"){case 1:X(H,"1930-34")break case 2:X(H,"1935-40")}break case 52:switch X(I,"CAMBODIA?"+Y){case 2:X(53)break case 1:X(55)}break case 53:switch X(I,"ERITREA IS A PART OF...##ITALY (1), ETHIOPIA (2)"){case 1:X(54)break case 2:X(H,"1952-53")}break case 54:switch X(I,"CANADA IS...##MISSING A PIECE (1), FINE (2)"){case 1:X(H,"1948")break case 2:X(H,"1949-52")}break case 55:switch X(I,"THE UNITED ARAB REPUBLIC?"+Y){case 2:X(H,"1954-57")break case 1:X(H,"1958-60")}break case 56:switch X(I,'ZAIRE? OR: "HONG KONG (UK)"'+Y){case 1:X(H,"1992-96")break case 2:X(57)}break case 57:switch X(I,"SERBIA AND MONTENEGRO ARE...##ONE COUNTRY (1), TWO COUNTRIES (2)"){case 1:X(58)break case 2:X(59)}break case 58:switch X(I,"EAST TIMOR?"+Y){case 2:X(H,"1997-2001")break case 1:X(H,"2002-06")}break case 59:switch X(I,H+"SUDANS ARE THERE?##ONE (1), TWO (2)"){case 1:X(H,"2007H1")break case 2:X(60)}break case 60:switch X(I,"IS CRIMEA DISPUTED?"+Y){case 1:X(61)break case 2:X(H,"2012H3")}break case 61:switch X(I,'"COLORADO" OR "DANGER-RADIOACTIVE EXCLUSION ZONE-AVOID"?##COLORADO (1), DANGER (2)'){case 1:X(H,"2014-21")break case 2:X(62)}break case 62:switch X(I,"DOES THE WARNING MENTION THE SPIDERS?"+Y){case 2:X(H,"2022")break case 1:X(H,"2023 OR LATER")}break case 63:switch X(I,"SAUDI ARABIA?"+Y){case 2:X(H,"1922-32")break case 1:X(64)}break case 64:switch X(I,"IS MOST OF WEST AFRICA A GIANT FRENCH BLOB?"+Y){case 1:X(49)break case 2:X(65)}break case 65:switch X(I,H+"VIETNAMS ARE THERE?##TWO (1), ONE (2)"){case 1:X(66)break case 2:X(69)}break case 66:switch X(I,"BANGLADESH?"+Y){case 2:X(67)break case 1:X(H,"1972-75")}break case 67:switch X(I,"IS THE AREA SOUTH OF LAKE VICTORIA...##BRITISH (1), TANGANYIKA (2), TANZANIA (3)"){case 1:X(68)break case 2:X(H,"1961-64")break case 3:X(H,"1965-71")}break case 68:switch X(I,"THE TOWN ON I-25 BETWEEN ALBUQUERQUE AND EL PASO IS...##HOT SPRINGS (1), TRUTH OR CONSEQUENCES (2)"){case 1:X(H,"1948-49")break case 2:X(H,"1950-52")}break case 69:switch X(I,"JIMMY CARTER IS...##BEING ATTACKED BY A GIANT SWIMMING RABBIT (1), FINE (2)"){case 1:X(H,"APRIL 20, 1979")break case 2:X(70)}break case 70:switch X(I,"THE SINAI IS PART OF WHAT COUNTRY?## ISRAEL (1), MOSTLY ISRAEL (2), MOSTLY EGYPT (3), EGYPT (4)"){case 1:X(H,"1976-79")break case 2:X(H,"1980")break case 3:X(H,"1981")break case 4:X(71)}break case 71:switch X(I,"WHAT'S THE CAPITAL OF MICRONESIA?## KOLONIA (1), PALIKIR (2)"){case 1:X(72)break case 2:X(73)}break case 72:switch X(I,"REPUBLIC OF THE UPPER VOLTA OR BURKINA FASO?## UPPER VOLTA (1), BURKINA FASO (2)"){case 1:X(H,"1982-84")break case 2:X(H,"1985-88")}break case 73:switch X(I,"(NUMBER OF YEMENS)+(NUMBER OF GERMANYS)=?## FOUR (1), THREE (2), TWO (3)"){case 1:X(H,"1989-EARLY 1990")break case 2:X(H,"MIDH990")break case 3:X(H,"LATE 1990H991")}break case 74:switch X(I,"DOES THE SOVIET UNION EXIST?"+Y){case 1:X(64)break case 2:X(56)}break} ``` `#` is the newline character. **How to run** * New `.gmk` file * Create a script `X` with contents as above * Create an object `O` with Create Event: execute code: `X(1)` * Create a room `R` and put one instance of `O` in it * Run the game **Golfing** * The option `YES` now always precedes `NO`, and we define the string `Y="##YES (1), NO (2)"` for reuse. * `"IS THERE A BIG LAKE IN THE MIDDLE OF "` and `"HOW MANY "` are long enough and occur sufficiently many times for abbreviation to pay off. They are assigned to `I` and `H`. * In Game Maker, any user-defined function usually must be done in a separate script. The consensus on the [policy for counting bytes for multi-file programs](http://meta.codegolf.stackexchange.com/questions/4933/counting-bytes-for-multi-file-programs), was that *"If files are reused ... count the contents of that file as many times as you use it"*. As such, we use `X` itself, rather than a separate script, to abbreviate `get_integer` and `show_message`. Explicitly, + If `X` is called with zeroth argument `H`, then it returns `show_message` of the first argument. + If `X` is called with zeroth argument `I`, then it returns `get_integer` of the first argument, showing default input `1`. **Ungolfed**, with options in the original order and no abbreviations at all: ``` // script X, takes node number, prompts question and returns message or calls X with next node number switch argument0 { case 1: switch get_integer("ISTANBUL OR CONSTANTINOPLE##CONSTANTINOPLE (1), NEITHER (2), ISTANBUL(3)",1) { case 1: X(2); break; case 2: X(19); break; case 3: X(74); break; }; break; case 2: switch get_integer("DO ANY OF THESE EXIST?#- INDEPENDENT CANADA#- US TERRITORY OF ALASKA#- TOKYO##NO (1), YES (2)",1) { case 1: X(3); break; case 2: X(11); break; }; break; case 3: switch get_integer("THE HOLY ROMAN EMPIRE?##YES (1), NO (2)",1) { case 1: show_message("1805 OR EARLIER (BEFORE THIS POINT, THE MODERN IDEA OF A COMPLETE POLITICAL MAP OF THE WORLD GETS HARD TO APPLY.)"); break; case 2: X(4); break; }; break; case 4: switch get_integer("THE UNITED STATES?##NO (1), YES (2)",1) { case 1: show_message("HOW SURE ARE YOU THAT THIS MAP IS IN ENGLISH"); break; case 2: X(5); break; }; break; case 5: switch get_integer("TEXAS IS...##PART OF MEXICO (1), INDEPENDENT (2), PART OF THE US (3)",1) { case 1: X(6); break; case 2: show_message("1834-45"); break; case 3: X(9); break; }; break; case 6: switch get_integer("FLORIDA IS PART OF...##SPAIN (1), THE US (2)",1) { case 1: X(7); break; case 2: X(8); break; }; break; case 7: switch get_integer("PARAGUAY?##NO (1), YES (2)",1) { case 1: show_message("1806-10"); break; case 2: show_message("1811-17"); break; }; break; case 8: switch get_integer("VENEZUELA AND/OR ECUADOR?##NO (1), YES (2)",1) { case 1: show_message("1818-29"); break; case 2: show_message("1830-33"); break; }; break; case 9: switch get_integer("DOES RUSSIA BORDER THE SEA OF JAPAN?##NO (1), YES (2)",1) { case 1: X(10); break; case 2: show_message("1858-67"); break; }; break; case 10: switch get_integer("THE US'S SOUTHERN BORDER LOOKS...##WEIRD (1), NORMAL (2)",1) { case 1: show_message("1846-53"); break; case 2: show_message("1854-56"); break; }; break; case 11: switch get_integer("SOUTH AFRICA?##NO (1), YES (2)",1) { case 1: X(12); break; case 2: X(16); break; }; break; case 12: switch get_integer("RHODESIA?##NO (1), YES (2)",1) { case 1: X(13); break; case 2: X(15); break; }; break; case 13: switch get_integer("IS BOLIVIA LANDLOCKED?##NO (1), YES (2)",1) { case 1: X(14); break; case 2: show_message("1884-95"); break; }; break; case 14: switch get_integer('"BUDA" AND "PEST" OR "BUDAPEST"?##BUDA AND PEST (1), BUDAPEST (2)',1) { case 1: show_message("1868-72"); break; case 2: show_message("1873-83"); break; }; break; case 15: switch get_integer("IS NORWAY PART OF SWEDEN?##YES (1), NO (2)",1) { case 1: show_message("1896-1905"); break; case 2: show_message("1906-09"); break; }; break; case 16: switch get_integer("AUSTRIA-HUNGARY?##YES (1), NO (2)",1) { case 1: X(17); break; case 2: X(18); break; }; break; case 17: switch get_integer("ALBANIA?##NO (1), YES (2)",1) { case 1: show_message("1910-12"); break; case 2: show_message("1913-18"); break; }; break; case 18: switch get_integer("LENINGRAD?##NO (1), YES (2)",1) { case 1: show_message("1919-23"); break; case 2: show_message("1924-29"); break; }; break; case 19: switch get_integer("DOES THE OTTOMAN EMPIRE EXIST?##YES (1), NO (2)",1) { case 1: X(2); break; case 2: X(20); break; }; break; case 20: switch get_integer("THE SOVIET UNION?##NO (1), YES (2)",1) { case 1: X(21); break; case 2: X(63); break; }; break; case 21: switch get_integer("NORTH KOREA?##NO (1), YES (2)",1) { case 1: X(22); break; case 2: X(56); break; }; break; case 22: switch get_integer("SAINT TRIMBLE'S ISLAND?##NO (1), YES (2)",1) { case 1: X(23); break; case 2: show_message("NO, I MADE THAT ONE UP."); break; }; break; case 23: switch get_integer("IS JAN MAYEN PART OF THE KINGDOM OF NORWAY?##NOT YET (1), WHAT? (2), YES (3)",1) { case 1: X(2); break; case 2: X(24); break; case 3: X(49); break; }; break; case 24: switch get_integer("CAN YOU SEE THE FAMILIAR CONTINENTS?##YES (1), NO (2)",1) { case 1: X(25); break; case 2: X(31); break; }; break; case 25: switch get_integer("THIS SOUNDS LIKE A PHYSICAL MAP OR SATELLITE PHOTO.##YES, THAT'S IT (1)",1) { case 1: X(26); break; }; break; case 26: switch get_integer("IS LAKE CHAD MISSING?##NO (1), YES (2)",1) { case 1: X(27); break; case 2: X(30); break; }; break; case 27: switch get_integer("HOW FAR EAST DO THE AMERICAN PRAIRIES REACH?##INDIANA (1), THE MISSISSIPPI (2), NEBRASKA (3), WHAT PRAIRIES? (4)",1) { case 1: show_message("BEFORE 1830"); break; case 2: show_message("1830s-80s"); break; case 3: X(28); break; case 4: X(29); break; }; break; case 28: switch get_integer("IS THERE A BIG LAKE IN THE MIDDLE OF SOUTHERN CALIFORNIA? (CREATED BY MISTAKE)##NO (1), YES (2)",1) { case 1: show_message("1860s-1900s"); break; case 2: show_message("1910s"); break; }; break; case 29: switch get_integer("IS THERE A BIG LAKE IN THE MIDDLE OF GHANA? (CREATED ON PURPOSE)##NO (1), YES (2)",1) { case 1: show_message("1920s-50s"); break; case 2: show_message("1960s-70s"); break; }; break; case 30: switch get_integer("IS THE ARAL SEA MISSING?##NO (1), YES (2)",1) { case 1: show_message("1970s-90s"); break; case 2: show_message("2000s+"); break; }; break; case 31: switch get_integer('RIVERS "SIRION" OR "ANDUIN"?##YES (1), NO (2)',1) { case 1: X(32); break; case 2: X(36); break; }; break; case 32: switch get_integer("MORDOR?##NO (1), YES (2)",1) { case 1: X(33); break; case 2: X(34); break; }; break; case 33: switch get_integer("BELERIAND?##YES (1), NO (2)",1) { case 1: show_message("FIRST AGE"); break; case 2: show_message("EARLY SECOND AGE"); break; }; break; case 34: switch get_integer("NÚMENOR?##YES (1), NO (2)",1) { case 1: show_message("LATE SECOND AGE"); break; case 2: X(35); break; }; break; case 35: switch get_integer("THE FOREST EAST OF THE MISTY MOUNTAINS IS...##GREENWOOD THE GREAT (1), MIRKWOOD (2), THE WOOD OF GREENLEAVES (3)",1) { case 1: show_message("EARLY THIRD AGE"); break; case 2: show_message("LATE THIRD AGE"); break; case 3: show_message("FOURTH AGE"); break; }; break; case 36: switch get_integer("CAIR PARAVEL?##YES (1), NO (2)",1) { case 1: X(37); break; case 2: X(41); break; }; break; case 37: switch get_integer("CALORMEN?##NO (1), YES (2)",1) { case 1: X(38); break; case 2: X(40); break; }; break; case 38: switch get_integer("LOTTA ISLANDS?##NO (1), YES (2)",1) { case 1: X(39); break; case 2: show_message("DAWN TREADER"); break; }; break; case 39: switch get_integer("BERUNA##FORD (1), BRIDGE (2)",1) { case 1: show_message("THE LION, THE WITCH, AND THE WARDROBE"); break; case 2: show_message("PRINCE CASPIAN"); break; }; break; case 40: switch get_integer("WEIRD RECURSIVE HEAVEN?##NO (1), YES (2)",1) { case 1: show_message("ONE OF THE RANDOM LATER BOOKS"); break; case 2: show_message("THE LAST BATTLE"); break; }; break; case 41: switch get_integer("MOSSFLOWER?##YES (1), NO (2)",1) { case 1: show_message("REDWALL"); break; case 2: X(42); break; }; break; case 42: switch get_integer("IS THE WORLD ON THE BACK OF A TURTLE?##YES (1), NO (2)",1) { case 1: show_message("DISCWORLD"); break; case 2: X(43); break; }; break; case 43: switch get_integer("ARE YOU SURE THIS IS A MAP?##YES (1), NO (2)",1) { case 1: X(44); break; case 2: X(46); break; }; break; case 44: switch get_integer("DID YOU MAKE IT YOURSELF?##YES (1)",1) { case 1: X(45); break; }; break; case 45: switch get_integer("IT'S VERY NICE.##THANK YOU! (1)",1) { case 1: break; }; break; case 46: switch get_integer("IS IT TRYING TO BITE YOU?##NO (1), YES (2)",1) { case 1: X(47); break; case 2: X(48); break; }; break; case 47: switch get_integer("IS IT LARGER THAN A BREADBOX?##YES (1), NO (2), ABOUT THE SAME (3)",1) { case 1: show_message("TUBA") break; case 2: show_message("STAPLER") break; case 3: show_message("BREADBOX") break; }; break; case 48: switch get_integer("IF YOU LET IT GO, WHAT DOES IT DO?##HISSES AND RUNS AWAY (1), SCREECHES AND FLAPS AROUND THE ROOM BREAKING THINGS (2)",1) { case 1: show_message("CAT") break; case 2: show_message("SEAGULL") break; }; break; case 49: switch get_integer("PAKISTAN?##NO (1), YES (2)",1) { case 1: X(50); break; case 2: X(52); break; }; break; case 50: switch get_integer("HOW MANY GERMANYS ARE THERE?##ONE (1), ONE, BUT IT'S HUGE (2), TWO (3)",1) { case 1: X(51); break; case 2: show_message("1941-45") break; case 3: show_message("1946-47") break; }; break; case 51: switch get_integer("PERSIA OR IRAN?##PERSIA (1), IRAN (2)",1) { case 1: show_message("1930-34") break; case 2: show_message("1935-40") break; }; break; case 52: switch get_integer("CAMBODIA?##NO (1), YES (2)",1) { case 1: X(53); break; case 2: X(55); break; }; break; case 53: switch get_integer("ERITREA IS A PART OF...##ITALY (1), ETHIOPIA (2)",1) { case 1: X(54); break; case 2: show_message("1952-53"); break; }; break; case 54: switch get_integer("CANADA IS...##MISSING A PIECE (1), FINE (2)",1) { case 1: show_message("1948"); break; case 2: show_message("1949-52"); break; }; break; case 55: switch get_integer("THE UNITED ARAB REPUBLIC?##NO (1), YES (2)",1) { case 1: show_message("1954-57"); break; case 2: show_message("1958-60"); break; }; break; case 56: switch get_integer('ZAIRE? OR: "HONG KONG (UK)"##YES (1), NO (2)',1) { case 1: show_message("1992-96"); break; case 2: X(57); break; }; break; case 57: switch get_integer("SERBIA AND MONTENEGRO ARE...##ONE COUNTRY (1), TWO COUNTRIES (2)",1) { case 1: X(58); break; case 2: X(59); break; }; break; case 58: switch get_integer("EAST TIMOR?##NO (1), YES (2)",1) { case 1: show_message("1997-2001"); break; case 2: show_message("2002-06"); break; }; break; case 59: switch get_integer("HOW MANY SUDANS ARE THERE?##ONE (1), TWO (2)",1) { case 1: show_message("2007-11"); break; case 2: X(60); break; }; break; case 60: switch get_integer("IS CRIMEA DISPUTED?##YES (1), NO (2)",1) { case 1: X(61); break; case 2: show_message("2012-13"); break; }; break; case 61: switch get_integer('"COLORADO" OR "DANGER-RADIOACTIVE EXCLUSION ZONE-AVOID"?##COLORADO (1), DANGER (2)',1) { case 1: show_message("2014-21"); break; case 2: X(62); break; }; break; case 62: switch get_integer("DOES THE WARNING MENTION THE SPIDERS?##NO (1), YES (2)",1) { case 1: show_message("2022"); break; case 2: show_message("2023 OR LATER"); break; }; break; case 63: switch get_integer("SAUDI ARABIA?##NO (1), YES (2)",1) { case 1: show_message("1922-32"); break; case 2: X(64); break; }; break; case 64: switch get_integer("IS MOST OF WEST AFRICA A GIANT FRENCH BLOB?##YES (1), NO (2)",1) { case 1: X(49); break; case 2: X(65); break; }; break; case 65: switch get_integer("HOW MANY VIETNAMS ARE THERE?##TWO (1), ONE (2)",1) { case 1: X(66); break; case 2: X(69); break; }; break; case 66: switch get_integer("BANGLADESH?##NO (1), YES (2)",1) { case 1: X(67); break; case 2: show_message("1972-75"); break; }; break; case 67: switch get_integer("IS THE AREA SOUTH OF LAKE VICTORIA...##BRITISH (1), TANGANYIKA (2), TANZANIA (3)",1) { case 1: X(68); break; case 2: show_message("1961-64"); break; case 3: show_message("1965-71"); break; }; break; case 68: switch get_integer("THE TOWN ON I-25 BETWEEN ALBUQUERQUE AND EL PASO IS...##HOT SPRINGS (1), TRUTH OR CONSEQUENCES (2)",1) { case 1: show_message("1948-49"); break; case 2: show_message("1950-52"); break; }; break; case 69: switch get_integer("JIMMY CARTER IS...##BEING ATTACKED BY A GIANT SWIMMING RABBIT (1), FINE (2)",1) { case 1: show_message("APRIL 20, 1979"); break; case 2: X(70); break; }; break; case 70: switch get_integer("THE SINAI IS PART OF WHAT COUNTRY?## ISRAEL (1), MOSTLY ISRAEL (2), MOSTLY EGYPT (3), EGYPT (4)",1) { case 1: show_message("1976-79"); break; case 2: show_message("1980"); break; case 3: show_message("1981"); break; case 4: X(71); break; }; break; case 71: switch get_integer("WHAT'S THE CAPITAL OF MICRONESIA?## KOLONIA (1), PALIKIR (2)",1) { case 1: X(72); break; case 2: X(73); break; }; break; case 72: switch get_integer("REPUBLIC OF THE UPPER VOLTA OR BURKINA FASO?## UPPER VOLTA (1), BURKINA FASO (2)",1) { case 1: show_message("1982-84"); break; case 2: show_message("1985-88"); break; }; break; case 73: switch get_integer("(NUMBER OF YEMENS)+(NUMBER OF GERMANYS)=?## FOUR (1), THREE (2), TWO (3)",1) { case 1: show_message("1989-EARLY 1990"); break; case 2: show_message("MID-1990"); break; case 3: show_message("LATE 1990-1991"); break; }; break; case 74: switch get_integer("DOES THE SOVIET UNION EXIST?## YES (1), NO (2)",1) { case 1: X(64); break; case 2: X(56); break; }; break; } ``` **Numbering system** * [Version 1](https://i.stack.imgur.com/vCTNX.png): before reordering of `YES`, `NO` options to save bytes * Version 2 (current): (reordered option numbers in black) [![Numbered map Version 2](https://i.stack.imgur.com/Q3D5g.png)](https://i.stack.imgur.com/Q3D5g.png) ]
[Question] [ This is essentially the same thing as [this](https://codegolf.stackexchange.com/questions/76893/optimal-solution-to-go-to-opposite-corner-of-a-rectangle) question, except harder. You are again to write a program that gets from the lower-left corner of a rectangle to the upper-right corner. **However, this time diagonal moves are allowed.** The program will accept an ordered pair `(width, height)`, and use these as the dimensions for a rectangle. Your program will then create an ASCII-art of the solution (use `.` for an empty square, `#` for part of the solution, and `X` for starting square) and count the number of moves it takes to reach the endpoint. **Example** Input: `(5, 6)` Output: ``` ....# ....# ...#. ..#.. .#... X.... Move count: 5 ``` Shortest answer in bytes wins! [Answer] ## Pyth, ~~46~~ ~~45~~ 44 bytes ``` eSKtMQjsM_mm?sJ,kd?q#J.umtWbbNeSKK\#\.\XhQeQ ``` [Try it here.](https://pyth.herokuapp.com/?code=eSKtMQjsM_mm%3FsJ%2Ckd%3Fq%23J.umtWbbNeSKK%5C%23%5C.%5CXhQeQ&input=%5B5%2C8%5D&debug=0) Explanation: ``` move-count-printing: K assign K to... Q the input, a 2-length array... tM with each element decremented eS take the max and output it (this is the number of moves) main path-finding logic: mm hQeQ map over x-values and y-values... J,kd assign J to [x,y] ?s if both x and y are NOT zero (sum is truthy)... ?q#J[...] if [x,y] is present in [...] (see below)... \# ... put a # at this position in the output \. ... else, put a . at this position \X ... else, put the X here (at [0,0]) jsM_ reverse and output in the proper format the [...] part in the code above, which finds positions where #s go: .u eSKK cumulative reduce on <number of moves> elements, starting at K, which is [max_x, max_y] as assigned at the beginning m N map over x and y... tWbb decrement, only if the value is > 0 ``` [Answer] # JavaScript (ES6), 132 *Edit* 2 bytes saved thx @Neil ``` (w,h)=>[...Array(--h)].map((_,i)=>R(w-i)+'#'+R(i),--w,R=(n,c='.')=>c.repeat(n>w?w:n>0&&n)).join` `+` x${R(w-h,'#')+R(h)} `+(h>w?h:w) ``` **Test** ``` f=(w,h)=>[...Array(--h)].map((_,i)=>R(w-i)+'#'+R(i),--w,R=(n,c='.')=>c.repeat(n>w?w:n>0&&n)).join` `+` x${R(w-h,'#')+R(h)} `+(h>w?h:w) function test() { var w,h [w,h]=I.value.match(/\d+/g) O.textContent=f(w,h) } test() ``` ``` Test <input id=I value="4 5"><button onclick="test()">-></button> <pre id=O></pre> ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 38 bytes ``` '.#X'!iSPXytf0)Jh1w(tzqDQI1()Gd0<?!]XP ``` [**Try it online!**](http://matl.tryitonline.net/#code=Jy4jWCchaVNQWHl0ZjApSmgxdyh0enFEUUkxKClHZDA8PyFdWFA&input=WzUgNl0) ### Explanation Let `m` and `n` be the sorted inputs, such that `m` is greater than or equal to `n`. The code initially builds an `m`x`n` matrix as follows: * Value 2 along the main diagonal, and on the lower part of the last column. This corresponds to character `#`. The number of these entries minus 1 is the move count. * Value 3 at entry (1,1), corresponding to the `X`. * The remaining entries contain 1, corresponding to character `.` If needed, the matrix is now transposed so that it has the desired shape. Note that the first dimension of a matrix is its height, not width, so it corresponds to the second input. The matrix is then flipped upside down so that `X` appears at the bottom of the first column, and its entries are used as indices into the string `'.#X'` to produce the desired 2D char array. ``` '.#X' % push this string ! % transpose into a column i % input array SP % sort it in non-increasing order Xy % identity matrix with that size: fill diagonal with 1, rest entries are 0 tf0) % linear index of last 1 Jh % append 1j (imaginary unit): linear index of lowest part of last column 1w( % fill those entries with 1 tzq % duplicate. Number of nonzero entries minus 1: this is the move count D % display move count (and remove it from the stack) Q % add 1. Matrix now contains values 1 and 2 I1( % set first entry (in linear order) to value 3 ) % use matrix as index into the initial string. Gives 2D char array Gd0< % push input array again. Is it decreasing? ? % if so ! % transpose char array ] % end XP % flip upside down. Implicitly display ``` [Answer] ## Javascript (using external library) (235 bytes) Jeez this was hard! Well...my library wasn't really the right task for this haha. But I liked the challenge ``` (x,y)=>{r=x-1;s=y-1;m=Math.max(r,s);n=Math.min(r,s);l=_.RangeDown(s,y).WriteLine(z=>_.Range(0,x).Write("",w=>z==0&&w==0?"X":(z==w||(z==s&&w>=n)||(w==r&&z>=n))?"#":"."));return l+"\r\nMove count: "+(l.length-l.split("#").join("").length)} ``` Link to lib: <https://github.com/mvegh1/Enumerable> Code explanation: Create function of 2 variables. Store x-1 and y-1 into variables. Store max and min of those into variables. Create a vertically descending range of numbers from (y-1) for a count of y. For each element on the vertical range, write a line for the current element, according to the complex predicate. That predicate creates an ascending range of integers from 0, for a count of x. For each element in that range, concatenate into 1 string according to a complex predicate. That predicate checks if on bottom left, else checks if on diagonal, else checks we're at X or Y border. Finally, all of that was stored in a variable. Then to get the move count, we basically just count the #'s. Then concatenate that to the stored variable, and return the result That was a mouthful haha. The screenshot has the wrong bytecount because I found a way to save 4 bytes while posting this EDIT: I see other answers aren't putting "Move count: " in their output, but mine is. If that isn't a requirement, that shaves a bunch of bytes... [![enter image description here](https://i.stack.imgur.com/S7HDj.png)](https://i.stack.imgur.com/S7HDj.png) [Answer] # Python 3, ~~161~~ 156 bytes ``` def f(w,h): x=[['.']*w for i in[0]*h];i=0 while i<w or i<h:x[~min(i,h-1)][min(i,w-1)]=['#','X'][i<1];i+=1 for i in x:print(''.join(i)) print(max(w,h)-1) ``` A function that takes input via argument and prints the ascii-art, followed by the move count, to STDOUT. **How it works** The program first creates a list of lists, where each list represents one row of the grid and each element of the component lists is `.`. Each element that should be `#` has the property that if the output grid was square, the ordinates representing its location would be equal; hence, looping over some index `i` and inserting `#` at location `(i, i)` would give the desired output. However, the grid is not always square, and thus the indices are clamped to the grid by taking the minimum of the index and width/height (decremented due to zero-indexing) as required. If the index is zero, the current position must be the bottom-left entry, and thus `X` is instead inserted. Next, the elements in each line are concatenated, and each line is printed to STDOUT. The number of moves is the maximum of the width/height decremented; this is also printed. [Try it on Ideone](https://ideone.com/79CzpA) ]
[Question] [ # Bounties *No. 1 (**awarded**)* > > I'll throw in 50 rep for the first valid answer > > > *No. 2 (**awarded**)* > > I'll throw in another 100 rep for the shortest valid answer. > > > *No. 3 (**open for submissions**)* > > I'll throw in 200 rep for the first one with a significant shorter valid answer. > Significant being at most 45% of currently shortest answer (*564 bytes x 0.45* = **max 254 bytes**). > > > --- ## The Game You remember the classic game "[Nine Men's Morris](https://en.wikipedia.org/wiki/Nine_Men%27s_Morris)" or simply "**Mill**"? There's a variation called [Three Men's Morris](https://en.wikipedia.org/wiki/Nine_Men%27s_Morris#Three_Men.27s_Morris) which is a bit like a mutable tic-tac-toe. ## Rules This is the blank board of the game: ``` a b c 1 [ ]–[ ]–[ ] | \ | / | 2 [ ]–[ ]–[ ] | / | \ | 3 [ ]–[ ]–[ ] ``` `[ ]` is a field and `|–/\` represent routes between those fields. The game is played by two players `1` and `2` who each place 3 tokens on the board. This actually happened already and we are in the game. The game is won if one player can form a `mill` which is a vertical or horizontal row of the player's 3 tokens. Tokens can be moved on the board along the connecting lines, according to this rule: > > To any adjacent empty position (i.e. from an edge position to the center, or from the center to an edge position, or from an edge position to an adjacent edge position > > > A player must make a move unless there's no adjacent empty position, in which case the move is skipped. ## The Challenge You're player `1` and your move is next. Write a program or a function, that determines whether: * you can force a win with 2 or less moves (**definite win**) * you can win with 2 or less moves, if your opponent makes a mistake (**possible win**) * you cannot win with 2 or less moves, because you'll need more moves or because forced moves lead your opponent to win (**impossible to win**) ## Requirements * Even though you definitely win when you bore your opponent to death, your program must finish in finite time. * You can write a program or a function. ## Input The players are represented by `1` and `2`. `0` defines a free field. You can take input as a matrix or an array. **Definite** ``` A B C D 2 1 0 | 2 1 0 | 1 0 1 | 1 2 2 2 1 2 | 0 1 0 | 1 0 2 | 2 1 O 0 0 1 | 2 2 1 | 0 2 2 | O O 1 A: [2,1,0,2,1,2,0,0,1] B: [2,1,0,0,1,0,2,2,1] C: [1,0,1,1,0,2,0,2,2] D: [1,2,2,2,1,0,0,0,1] ``` **Possible** ``` A B C 1 0 1 | 1 0 1 | 1 2 2 1 2 2 | 1 2 0 | 0 0 1 2 0 0 | 2 0 2 | 2 1 0 A: [1,0,1,1,2,2,2,0,0] B: [1,0,1,1,2,0,2,0,2] C: [1,2,2,0,0,1,2,1,0] ``` **Impossible** ``` A B 1 0 0 | 1 2 0 1 2 2 | 2 1 0 2 0 1 | 1 2 0 A: [1,0,0,1,2,2,2,0,1] B: [1,2,0,2,1,0,1,2,0] ``` ## Output Your program should output/return a smiley: * Definite win: `:)` * Possible win: `:|` * Impossible to win: `:(` ## Examples *Definite win in two moves:* ``` [2][1][ ] 1. [2][1][ ] [2][1][2] -> [2][1][2] [ ][ ][1] [ ][1][ ] [2][1][ ] 1. [2][1][ ] [ ][1][ ] 2. [ ][ ][1] [ ][1][ ] -> [ ][ ][1] -> [2][ ][1] -> [2][ ][1] [2][2][1] [2][2][1] [2][2][1] [2][2][1] [1][ ][1] 1. [ ][1][1] [ ][1][1] 2. [1][1][1] [1][ ][2] -> [1][ ][2] -> [1][ ][2] -> [ ][ ][2] [ ][2][2] [ ][2][2] [2][ ][2] [2][ ][2] ``` *Possible win in two moves:* ``` [1][ ][1] 1. [ ][1][1] [ ][1][1] 2. [1][1][1] [1][2][ ] -> [1][2][ ] -> [1][2][2] -> [ ][2][2] [2][ ][2] [2][ ][2] [2][ ][ ] [2][ ][ ] [1][ ][1] 1. [ ][1][1] [ ][1][1] 2. [1][1][1] [1][2][ ] -> [1][2][ ] -> [1][2][2] -> [ ][2][2] [2][ ][2] [2][ ][2] [2][ ][ ] [2][ ][ ] [1][2][2] 1. [ ][2][2] [2][ ][2] 2. [1][2][2] [ ][ ][1] -> [1][ ][1] -> [1][ ][1] -> [1][1][1] [2][1][ ] [2][1][ ] [2][1][ ] [2][ ][ ] ``` *Impossible to win in two moves:* ``` [1][ ][ ] [1][2][2] [2][ ][1] ``` ## Bonus In case a definite win is possible and your program outputs the moves of one way to success as well like `a1:a2` (1 move) or `a1:a2,a3:b2` (2 moves), you can withdraw **30%** of your byte count. --- This is code golf – so shortest answer in bytes wins. Standard loopholes are disallowed. --- Thanks to [Peter Taylor](http://meta.codegolf.stackexchange.com/users/194/peter-taylor) who fixed some flaws and improved wording in the [Sandbox](http://meta.codegolf.stackexchange.com/q/2140/41859). [Answer] # C# - ~~739~~ 663 bytes Complete program, reads input from argv, and appears to work. Run it like ``` ThreeMill 1 2 1 1 2 0 0 0 2 ``` If this method of input is unacceptable, I'll be glad to change it (never like using argv). ``` using System;using System.Linq;class P{static void Main(string[]A){var I=new[]{0,3,6,1,4,7,2,5,8};Func<string[],string>J=S=>S[0]+S[1]+S[2]+" "+S[3]+S[4]+S[5]+" "+S[6]+S[7]+S[8]+" ";Func<string[],string,int>W=(B,p)=>(J(B)+J(I.Select(i=>B[i]).ToArray())).Contains(p+p+p)?1:0;Func<string[],string,string[][]>V=(B,p)=>I.SelectMany(a=>I.Where(b=>a!=b&B[a]==p&B[b]=="0"&(a==4|b==4|a-b==3|b-a==3|((a-b==1|b-a==1)&a/3==b/3))).Select(b=>{var N=(string[])B.Clone();N[b]=p;N[a]="0";return N;})).DefaultIfEmpty(B).ToArray();int h,G;Console.WriteLine(":"+"(|))"[V(A,"1").Max(z=>((h=0)<(G=V(z,"2").Sum(j=>V(j,"1").Max(q=>W(q,"1")-W(q,"2"))+h++*0))?1:0)+(h>G?W(z,"1")*2:2))]);}} ``` I was disinclined to post this yesterday, because I've not been able to golf it down much (not had all that much time, and I might be out of practice), but since there hasn't been a response yet, I'll post it anyway, I certainly don't expect the bounty, I'd rather it went to someone who's put a bit more effort into theirs before posting! *Edit:* replaced all the bools with ints, which meant I could make better use of Linq, and managed to collapse both foreach loops, giving big savings. I am slightly amazed that the `h` counter works... ++ is such a subtle utility. The program is very simple, it just explores every possible set of moves (stores board state in a string[]). It iterates over all of our possible moves (the boards that result thereof), and counts the number of responses by our opponent that we can successful beat (`G`) (i.e. those that we win, and he doesn't). It also counts the number of possible responses (`h`). If we can win any, then it's a possible, and we add 1 to the sum, if we can win them all, it's a definite, and we add 2 to the sum. The maximum some is therefore our best possible outcome, and we index into the string "(|))" to return the appropriate face. Note that we need the extra ")" because the sum can be 2 or 3 if it's a definite (it's possible that we don't appear to be able to beat any responses having already won on the first go, so the possible check is a tad misleading). The program checks for a victory by producing a string from the board, that is space-separated rows and columns, and just looks for a string of 3 of the player's character in this string (e.g. "201 201 021 220 002 111 " is a win for us) ``` using System; using System.Linq; // all important class P { static void Main(string[]A) // transform to int? { var I=new[]{0,3,6,1,4,7,2,5,8}; // vertical indexes Func<string[],string>J=S=>S[0]+S[1]+S[2]+" "+S[3]+S[4]+S[5]+" "+S[6]+S[7]+S[8]+" "; // joins the strings up, so that there is a space separating each group of three (including at end) Func<string[],string,int>W=(B,p)=>(J(B)+J(I.Select(i=>B[i]).ToArray())).Contains(p+p+p)?1:0; // checks if a particular player wins Func<string[],string,string[][]>V=(B,p)=>I.SelectMany(a=>I // for each imagineable move .Where(b=>a!=b&B[a]==p&B[b]=="0"&(a==4|b==4|a-b==3|b-a==3|((a-b==1|b-a==1)&a/3==b/3))) // where it's legal .Select(b=>{var N=(string[])B.Clone();N[b]=p;N[a]="0";return N;}) // select the resulting board ).DefaultIfEmpty(B) // allow not-moving .ToArray(); int h, // h stores the number of responses the opponent has to each move G; // G stores the number of responses by the opponent we can beat Console.WriteLine(":"+"(|))"[ // we index into this to decide which smiley V(A,"1").Max(z=> ((h=0)<(G=V(z,"2").Sum(j=>V(j,"1").Max(q=>W(q,"1")-W(q,"2"))+h++*0))?1:0) // if there is atleast 1 reponse by the opponent we can beat, we can possibly win +(h>G?W(z,"1")*2:2) // if there are moves which we can't win, then if we have already won (one-move), else, we can definitely win ) // sum is therefore 0 if impossible, 1 if possible, >2 (no more than 3) if definite ]); } } ``` Here is my test script: ``` ThreeMill 2 1 0 2 1 2 0 0 1 ThreeMill 2 1 0 0 1 0 2 2 1 ThreeMill 1 0 1 1 0 2 0 2 2 ThreeMill 1 2 2 2 1 0 0 0 1 ThreeMill 1 0 1 1 2 2 2 0 0 ThreeMill 1 0 1 1 2 0 2 0 2 ThreeMill 1 2 2 0 0 1 2 1 0 ThreeMill 1 0 0 1 2 2 2 0 1 ThreeMill 1 2 1 1 2 0 0 0 2 ThreeMill 1 0 1 2 0 2 1 0 2 ``` Which outputs ``` :) :) :) :) :| :| :| :( :| :) ``` [Answer] # Haskell, ~~580~~ ~~564~~ 441 bytes This is how far I can golf it for now. Not sure if the other languages can beat it. Call `m` on a list of lists like `[[2,1,0],[2,1,2],[0,0,1]]` (Definite A). ``` import Data.Array r=[0..2] p?f=[(x,y)|x<-r,y<-r,f!y!x==p] p%f=all(==x)xs||all(==y)ys where(x:xs,y:ys)=unzip$p?f s p x y f=f//[(y,f!y//[(x,p)])] p#f=[s 0 x y$s p u v f|a@(x,y)<-p?f,b@(u,v)<-0?f,((x-u)*(y-v)==0&&abs(x+y-u-v)==1)||elem(1,1)[a,b]] p&f|p#f>[]=p#f|0<1=[f] e=any i a p f=e(a$e(p%))(map(map(p&))(map((3-p)&)$p&f))||e(p%)(p&f) l=listArray(0,2) f(True,_)=":)" f(False,True)=":|" f _=":(" m=putStrLn.f.(\f->(i all 1 f,i e 1 f)).l.map l ``` Test code: ``` da = [[2,1,0],[2,1,2],[0,0,1]] db = [[2,1,0],[0,1,0],[2,2,1]] dc = [[1,0,1],[1,0,2],[0,2,2]] dd = [[1,2,2],[2,1,0],[0,0,1]] pa = [[1,0,1],[1,2,2],[2,0,0]] pb = [[1,0,1],[1,2,0],[2,0,2]] pc = [[1,2,2],[0,0,1],[2,1,0]] ia = [[1,0,0],[1,2,2],[2,0,1]] ib = [[1,2,0],[2,1,0],[1,2,0]] al = [da,db,dc,dd,pa,pb,pc,ia,ib] ``` `mapM_ m al` returns: ``` :) :) :) :) :| :| :| :( :( ``` [Answer] # PowerShell ~~576~~ 550 bytes I shall not be so easily deterred - if I can't get C# below 631 bytes, I'll have to use a different language instead! I'm hoping that Leif Willerts will knock 5 bytes off his answer, because I've decided I'm not overly fond of PowerShell, maybe I just need to look at it objectively in terms in byte counts... This is a script, you run it by `. .\mill.ps1 "201102021"`. It's pretty well a copy of my C# answer, only in a language I've little experience with. I've not made too much of an effort to golf this, because it took so bloomin' long to get working in the first instance, and is reasonably compact already. *Edit: couldn't just leave those `[Math]::Floor` calls in there* ``` param($U);$I=0,3,6,1,4,7,2,5,8;function J($S){($S[0..2]+" "+$S[3..5]+" "+$S[6..8]-join"").Contains($p*3)}function W($D,$p){(J $D)-or(J $D[$I])}function V($Q,$C){$I|%{$a=$_;$I|?{$a-ne$_-and$Q[$a]-eq$c-and$Q[$_]-eq"0"-and($a-eq4-or$_-eq4-or$a-$_-eq3-or$_-$a-eq3-or(($a-$_-eq1-or$_-$a-eq1)-and$a/3-$a%3/3-eq$_/3-$_%3/3))}|%{$b=$Q[0..8];$b[$_]=$c;$b[$a]=0;$b-join''}}|%{$n=1}{$n=0;$_}{if($n){$Q}}}$e=$f=0;V $U "1"|%{$h=0;$x=$_;V $x "2"|%{$k=0;(V $_ "1"|%{if((W $_ "1")-and!(W $_ "2")){$k=$e=1}});$h+=1-$k};if($h-eq0-or(W $x "1")){$f=2}};":"+"(|))"[$e+$f] ``` If you a description of how it works... the C# answer is for you, but hopefully the comments make it clear enough. The semicolons may not match perfectly with the single-line command, I'm not sure yet where they are needed and aren't, and didn't copy them back when I put the whole thing on one line. ``` param($U); # take input as argument $I=0,3,6,1,4,7,2,5,8; # cols function J($S){ # checks if this is a winning string ($S[0..2]+" "+$S[3..5]+" "+$S[6..8]-join"").Contains($p*3)} function W($D,$p){ # checks if this is a winning board (J $D)-or(J $D[$I])} # $D[$I] reorganises into columns function V($Q,$C){ # yields all valid moves from position $Q for player $C $I|%{$a=$_;$I| # for each possible move ?{$a-ne$_-and$Q[$a]-eq$c-and$Q[$_]-eq"0"-and($a-eq4-or$_-eq4-or$a-$_-eq3-or$_-$a-eq3-or(($a-$_-eq1-or$_-$a-eq1)-and$a/3-$a%3/3-eq$_/3-$_%3/3))}| # where legal %{$b=$Q[0..8];$b[$_]=$c;$b[$a]=0;$b-join''}}| # make the move (copy $Q to an array, modify, join into a string) %{$n=1}{$n=0;$_}{if($n){$Q}}} # if empty, return $Q - I am confident this can be achieved with commas, and [0], and maybe a +, but I don't want to think about it $e=$f=0; # possible, definite V $U "1"|%{ # for all our possible moves $h=0;$x=$_; # $k is whether we win all of these V $x "2"| # for all opponent's responses %{$k=0;(V $_ "1"| # for all our responses %{if((W $_ "1")-and!(W $_ "2")){$k=$e=1}});$h+=1-$k}; # if we can win and he can't, then things are looking good, set $e to 1 (possible win) if($h-eq0-or(W $x "1")){$f=2} # if we win every move, or we have already won, it's a definite }; ":"+"(|))"[$e+$f] # smile, it's all over ``` Test script (PowerShell): ``` . .\mill.ps1 "210212001" . .\mill.ps1 "210010221" . .\mill.ps1 "101102022" . .\mill.ps1 "122210001" . .\mill.ps1 "101122200" . .\mill.ps1 "101120202" . .\mill.ps1 "122001210" . .\mill.ps1 "100122201" . .\mill.ps1 "121120002" . .\mill.ps1 "101202102" . .\mill.ps1 "100122201" . .\mill.ps1 "120210120" ``` Output thereof: ``` :) :) :) :) :| :| :| :( :| :) :( :( ``` [Answer] # Python 3, ~~566~~ 557 bytes I'll have to see if I can golf it down further, or if I can get the 30% bonus, but after much procrastination, here is my answer. ``` def t(g,x=1,r=0,z=0): m=[[1,3,4],[0,2,4],[2,4,5],[0,4,6],[0,1,2,3,5,6,7,8],[2,4,8],[3,4,7],[4,6,8],[4,5,7]];a=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];z=z or[[],[],[],[]];s=0 if r>3:return z for i in a: if g[i[0]]==g[i[1]]==g[i[2]]>0:s=g[i[0]];break z[r]+=s, for q in range(9): i=g[q] if i==x: for p in m[q]: if g[p]<1:n=g[:];n[q],n[p]=n[p],n[q];z=t(n,3-x,r+1,z) if r:return z else: w=l=0 for j in range(4):w=w or 1in z[j];l=l or 2in z[j] if l<1and w:return":)" elif w<1and l:return":(" else:return":|" ``` Ungolfed: ``` def three_mens_morris(grid, player=1, rec=0, w_l=0, p=0): moves = [[1,3,4],[0,2,4],[2,4,5],[0,4,6],[0,1,2,3,5,6,7,8],[2,4,8],[3,4,7],[4,6,8],[4,5,7]] w_l = w_l or [[],[],[],[]] if rec == 4: return w_l result = check_grid(grid) w_l[rec].append(result) for sq_1 in range(len(grid)): piece = grid[sq_1] if piece == player: for sq_2 in moves[sq_1]: if grid[sq_2] == 0: new_grid = grid.copy() new_grid[sq_1],new_grid[sq_2]=new_grid[sq_2],new_grid[sq_1] w_l = three_mens_morris(new_grid,3-player,rec+1,w_l) if p: print(w_l) if rec: return w_l else: win = loss = 0 for i in range(4): if 1 in w_l[i]: win = 1 elif 2 in w_l[i]: loss = 1 if p:print(win,loss) if loss==0 and win: return ":)" elif loss and win==0: return ":(" else: return ":|" def check_grid(grid): rows = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]] for i in rows: if grid[i[0]]==grid[i[1]]==grid[i[2]] and grid[i[0]]: return grid[i[0]] return 0 ``` ]
[Question] [ # Express a number Back in the 60s, the French invented the TV game show "Des Chiffres et des Lettres" (Digits & Letters). The goal of the Digits-part of the show was to come as close as you can to a certain 3-digit target number, using some semi-randomly selected numbers. The contestants could use the following operators: * concatenation (1 and 2 is 12) * addition (1 + 2 is 3) * subtraction (5 - 3 = 2) * division (8 / 2 = 4); division is only allowed if the result is a natural number * multiplication (2 \* 3 = 6) * parentheses, to override the regular precedence of operations: 2 \* ( 3 + 4 ) = 14 Each given number can only be used once or not at all. For example, the target number 728 can be matched exactly with the numbers: 6, 10, 25, 75, 5 and 50 with the following expression: ``` 75 * 10 - ( ( 6 + 5 ) * ( 50 / 25 ) ) = 750 - ( 11 * 2 ) = 750 - 22 = 728 ``` ![Still from the original Frensh "Des Chiffres et des Lettres"](https://i.stack.imgur.com/8uW4w.jpg) In this code challenge, your are given the task to find an expression as close as possible to a certain target number. Since we're living in the 21st century, we'll introduce bigger target numbers and more numbers to work with than back in the 60s. ## Rules * Allowed operators: concatenation, +, -, /, \*, ( and ) * The concatenation operator has no symbol. Just concatenate the numbers. * There is no "inverse concatenation". 69 is 69 and can't be split in a 6 and a 9. * The target number is a positive integer and has a maximum of 18 digits. * There are at least two numbers to work with and a maximum of 99 numbers. These numbers are also positive integers with a maximum of 18 digits. * It is possible (actually quite probably) that the target number can't be expressed in terms of the numbers and the operators. The goal is to get as close as possible. * The program should finish in a reasonable time (a few minutes on a modern desktop PC). * Standard loopholes apply. * Your program may **not** be optimized for the test set in the "scoring" section of this puzzle. I reserve the right to change the test set if I suspect anyone violating this rule. * This is *not* a codegolf. ## Input The input consists of an array of numbers that can be formatted in any convenient way. The first number is the target number. The rest of the numbers are the numbers you should work with to form the target number. ## Output The requirements for the output are: * It should be a string that consists of: + any subset of the input numbers (except the target number) + any number of operators * I prefer the output to be single line without spaces, but if you must, you may add spaces and newlines as you see fit. They will be ignored in the controlling program. * The output should be a valid mathematical expression. ## Examples For readability, all these examples have an exact solution and each input number is used exactly once. Input: `1515483, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1` Output: `111*111*(111+11+1)` Input: `153135, 1, 2, 3, 4, 5, 6, 7, 8, 9` Output: `123*(456+789)` Input: `8888888888, 9, 9, 9, 99, 99, 99, 999, 999, 999, 9999, 9999, 9999, 99999, 99999, 99999, 1` Output: `9*99*999*9999-9999999-999999-99999-99999-99999-9999-999-9-1` Input: `207901, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0` Output: `1+2*(3+4)*(5+6)*(7+8)*90` Input: `34943, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0` Output: `1+2*(3+4*(5+6*(7+8*90)))` But also valid output is: `34957-6-8` ## Scoring The penalty score of a program is the sum of the relative errors of the expressions for the testset below. [![Scoring equation](https://i.stack.imgur.com/bwOdH.png)](https://i.stack.imgur.com/bwOdH.png) For example if the target value is 125 and your expression gives 120, your penalty score is abs( 1 - 120/125 ) = 0,04. The program with the **lowest** score (lowest total relative error) wins. If two programs finish equally, the first submission wins. Finally, the testset (8 cases): ``` 14142, 10, 11, 12, 13, 14, 15 48077691, 6, 9, 66, 69, 666, 669, 696, 699, 966, 969, 996, 999 333723173, 3, 3, 3, 33, 333, 3333, 33333, 333333, 3333333, 33333333, 333333333 589637567, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 8067171096, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199 78649377055, 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462, 506, 552, 600, 650, 702, 756, 812, 870, 930, 992 792787123866, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169 2423473942768, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 2000000, 5000000, 10000000, 20000000, 50000000 ``` # Previous similar puzzles After creating this puzzle and posting it on the sandbox, I noticed something similar (but not the same!) in two previous puzzles: [here](https://codegolf.stackexchange.com/questions/41872/solving-des-chiffres-et-des-lettres-the-total-is-right) (no solutions) and [here](https://codegolf.stackexchange.com/questions/10790/generate-a-number-by-using-a-given-list-of-numbers-and-arithmetic-operators). This puzzle is somewhat different, because it introduces the concatenation operator, I don't seek and exact match and I like to see strategies for coming close to the solution without brute force. I think it is challenging. [Answer] # C++17, score .0086 This program has non-deterministic penalty score due to thread races, so I'm declaring based on an average of three runs, each of which handled the test suite in under a minute: ``` score 0.000071 for 14(11*13) = 14143 score 0.000019 for (696699+66)*69 = 48076785 score 0.000069 for 333333+333333333+33333 = 333699999 score 0.000975 for 5(1((((555555255-1-1-4-5-5-5-5-4-4-4-4-4-4-4-4-4-4-4-4-4-5-3-3-3-3-3-3-3-3-3-3-3-3-3-5)/2*3/2-2)/2*3+2+1+1+1+1-1-1)/2*2/2/2/2)/2) = 589062470 score 0.000462 for (((199181197*41-193-191-179-173-167-163-157-151-149-139-137-131-127-113-109-107-103-101-97-89-83-79-73-71-67-61-59-53-47-43-17-3)/5*7+23)/2/11*13+19)/31*37 = 8063447296 score 0.000118 for (992930870*72+812+756+702+650+600+552+506+462+420+380+342-42-56-182-12-210-156-90-20-272-30-6-306)/240*132*2 = 78640130184 score 0.000512 for (((317811*832040*3-39088169-24157817-14930352-9227465-5702887-2178309-1346269-3524578-514229-196418-121393-17711-233-75025-46368-89-28657-4181-10946-6765-34-987-2584-13-610-8-1)/2-377-144)/5-1597)1 = 793193194211 score 0.005725 for 2(20((120000000*20000+50000000+10000000+5000000+2000000+100000+50000+10000+5000+2000-500-1000)/50)/5)+200+100+10 = 2409600268972 total score = .007951 real 0m57.876s user 4m24.396s sys 0m0.684s score 0.000071 for 14(11*13) = 14143 score 0.000019 for (696699+66)*69 = 48076785 score 0.000069 for 333333+333333333+33333 = 333699999 score 0.001675 for (3((((((((555555455+5+5+5+5-1-1-4-4-4-4-4-4-4-4-4-1-4-4-4-4-5-3-3-3-3-3-4)/2*3/2-1)*2+5)/3*3+3)/2-3-3)/2*3/2*2+2)/2*2/2*3+2+1)/5/2)-1-1-1-1-1-1-1-1-1-2)/2*3 = 590624943 score 0.000973 for ((199181197*41-193-191-179-173-167-163-157-151-149-139-137-131-127-113-107-101-59-97-79-3-71-67-83-2-47-37-73-89-103-19-11-29)/5*7+109-23)/61*43 = 8059325224 score 0.000118 for ((992930870*72+812+756+702+650+600+552+506+462+420+380+342+306+272+240+210+182-0-56-110-20-90)/2-42-156)/30*132/12*6 = 78640132296 score 0.000512 for (((317811*832040*3-39088169-24157817-14930352-9227465-5702887-3524578-514229-196418-2178309-1346269-121393-75025-28657-10946-233-46368-89-17711-2584-6765-610-4181-34-987-55-1)/2-8-144-377)/5-1597)1 = 793193194161 score 0.004734 for 2(20((120000000*20000+50000000+10000000+5000000+2000000+100000+50000+10000+5000+2000-100-1000-500)/200*50/10)/5) = 2412000335827 total score = .008171 real 0m45.636s user 3m30.272s sys 0m0.720s score 0.000071 for 14(11*13) = 14143 score 0.000019 for (696699+66)*69 = 48076785 score 0.000069 for 333333+333333333+33333 = 333699999 score 0.002963 for 1(((((((555555555+5+5+5+5+5+5+4+4+4+4-1-2-4-4-4-4-4-4-4-4-4-4-4-3-3-3-3)/2*3+3+2)/2*2+3+3)/2*2/2/2*3+3)/2-3-3)*3/2-1-3)/2*3/2/2)/2 = 587890622 score 0.000069 for ((((199181197*41-193-191-179-173-167-163-157-151-149-139-137-131-127-113-109-107-103-101-97-89-83-79-73-71-67-61-59-53-47-43-37-11)/7)2+3)/23*17-13-5)/31*29 = 8066615553 score 0.000118 for ((992930870*72+812+756+702+650+600+552+506+462+420+380-0-6-90-56-42-272-182-110-210-342-30-306)*2+12)/240*132 = 78640129524 score 0.000512 for (((317811*832040*3-39088169-24157817-14930352-9227465-5702887-2178309-1346269-3524578-514229-196418-121393-75025-46368-28657-144-55-17711-2584-10946-4181-6765-21-610-987-377-8-1)/2-89-13)/5-233-1597)1 = 793193192491 score 0.005725 for 2(20((120000000*20000+50000000+10000000+5000000+2000000+100000+50000+10000+5000+2000-500-1000)/50)/5)+200+100+10 = 2409600268972 total score = .009546 real 0m57.289s user 4m19.488s sys 0m0.708s ``` Here's the program; explanation is provided in comments. You can define `CONCAT_NONE` for traditional Countdown rules that don't permit concatenation, or `CONCAT_DIGITS` to allow concatenation of the input values, but not of any intermediate results. By default, without either defined, the most liberal rules are used. ``` #include <omp.h> #include <algorithm> #include <cmath> #include <memory> #include <set> #include <string> #include <utility> #include <vector> // We apply some principles to help us arrive at a good enough solution // in a reasonable time: // 1. Ruthlessly prune duplicate expressions from the candidate // list. If we've seen a+b, then there's no need to consider // b+a. Similarly, having seen (a+b)+c, then (a+c)+b can be // discounted. // 2. Detect duplicates by storing batches of part-processed results // in sets before sending to the next pass. // 3. Sort our candidates so that those containing a term near to the // target are first in line for further processing. // 4. Gradually widen our acceptance margin as we proceed. This // allows us to terminate quickly without exhaustively searching // the full problem space. // 5. Parallelize the generation of candidate solutions using OpenMP. // Define precedence values for our operators, so that we can print // with the minimum sufficient parentheses. The values are grouped // into tens so that add/10 == subtract/10 and mult/10 == divide/10 - // the operators use that for avoiding duplicate expressions. static const int PREC_ADD = 26; static const int PREC_SUBTRACT = 24; static const int PREC_MULT = 16; static const int PREC_DIVIDE = 14; static const int PREC_CONCAT = 2; static const int PREC_LITERAL = 0; static const int PREC_MAX = 1000; class LiteralTerm; struct Term { long value; int precedence; Term(long value, int precedence) : value(value), precedence(precedence) {} Term(const Term&) = default; virtual ~Term() = default; virtual std::string to_string(int p = PREC_MAX) const = 0; virtual LiteralTerm as_literal() const = 0; long distance(long target) const { return std::abs(value - target); } // We sort large values first, in the hope that this will approach // the target faster. bool operator<(const Term& o) const { return value > o.value; } }; // We have two kinds of Term: a LiteralTerm is a leaf node of the // expression tree, and a BinaryTerm is an internal node. struct Operator; class LiteralTerm : public Term { std::string s; public: LiteralTerm(std::string s) : Term(std::stol(s), 0), s(s) {} LiteralTerm(std::string s, long value) : Term(value, 0), s(s) {} std::string to_string(int = PREC_MAX) const override { return s; } LiteralTerm as_literal() const override { return *this; } }; struct BinaryTerm : public Term { Operator const *op; std::shared_ptr<const Term> a; std::shared_ptr<const Term> b; BinaryTerm(long value, const Operator* op, std::shared_ptr<const Term> a, std::shared_ptr<const Term> b); BinaryTerm(const BinaryTerm&) = default; BinaryTerm& operator=(const BinaryTerm&) = default; std::string to_string(int p = PREC_MAX) const; LiteralTerm as_literal() const override { return { to_string(), value }; } }; struct TermList { std::vector<std::shared_ptr<const Term>> terms; std::vector<long> values; long target_value; long badness; TermList(std::vector<std::shared_ptr<const Term>> terms, long target_value) : terms(std::move(terms)), values(), target_value(target_value), badness(min_badness(this->terms, target_value)) { values.reserve(terms.size()); std::transform(terms.begin(), terms.end(), std::back_inserter(values), [](auto t) { return t->value; }); // Literals that begin with "0" need to be distinct from (but // adjacent to) equivalent non-literals. Append a negative // value for each term with leading zeros. There's an edge // case involving multiple leading zeros, but we'll ignore // that. for (const auto& v: terms) if (v->precedence <= PREC_CONCAT && v->value > 0 && v->to_string()[0] == '0') values.push_back(-v->value); } // Sort according to the term that's nearest to the target. bool operator<(const TermList& o) const { return std::make_tuple(std::cref(badness), std::cref(values)) < std::make_tuple(std::cref(o.badness), std::cref(o.values)); } private: static long min_badness(const std::vector<std::shared_ptr<const Term>>& t, long target_value) { auto less_bad = [target_value](const auto& a, const auto&b) { return a->distance(target_value) < b->distance(target_value); }; auto const& e = *std::min_element(t.begin(), t.end(), less_bad); return std::abs(e->value - target_value); } }; using Set = std::set<TermList>; // Detect duplicate expressions. This will discount "3+2-3", "8*5*2/3/5" // and similar expressions that contain simple pairs of inverse operands. static bool contains_value(const Term& t, int precedence, long value) { auto *const b = dynamic_cast<const BinaryTerm*>(&t); if (t.precedence == precedence) return t.value == value || b && b->b->value < value || b && contains_value(*b->a, precedence, value) || b && contains_value(*b->b, precedence, value); if (t.precedence/10 == precedence/10) // Advance through the subtractions to inspect the additions // (or through the divides to inspect the multiplications). return b && contains_value(*b->a, precedence, value); return false; } // An Operator is a factory producing binary terms of a given type, // and for printing those terms. Here's the abstract base class. struct Operator { using TermPointer = std::shared_ptr<const Term>; using BinaryTermPointer = std::shared_ptr<const BinaryTerm>; int const precedence; std::string const joiner; virtual std::string to_string(const Term &a, const Term &b) const { return a.to_string(precedence) + joiner + b.to_string(precedence); } virtual BinaryTermPointer make_term(TermPointer a, TermPointer b) const { long r = evaluate(*a, *b); return r ? std::make_shared<BinaryTerm>(r, this, a, b) : BinaryTermPointer(); } virtual ~Operator() = default; protected: Operator(int precedence, std::string joiner) : precedence(precedence), joiner(joiner) {} virtual long evaluate(const Term& a, const Term& b) const = 0; }; // Now we define a subclass for each permitted operator struct AddOperator : Operator { AddOperator() : Operator(PREC_ADD, "+") {} long evaluate(const Term& a, const Term& b) const override { const auto *d = dynamic_cast<const BinaryTerm*>(&a); long r; return b.precedence/10 != PREC_ADD/10 && a.precedence != PREC_SUBTRACT && b.value > 0 && ! (d && d->precedence == this->precedence && d->b->value < b.value) && !__builtin_add_overflow(a.value, b.value, &r) ? r : 0; } }; struct SubtractOperator : Operator { SubtractOperator() : Operator(PREC_SUBTRACT, "-") {} long evaluate(const Term& a, const Term& b) const override { return b.precedence < PREC_SUBTRACT && a.value > b.value && !contains_value(a, PREC_ADD, b.value) ? a.value - b.value : 0; } }; struct MultiplyOperator : Operator { MultiplyOperator() : Operator(PREC_MULT, "*") {} long evaluate(const Term& a, const Term& b) const override { const auto *d = dynamic_cast<const BinaryTerm*>(&a); long r; return b.precedence/10 != PREC_MULT/10 && b.value > 1 && (b.value > 2 || a.value > 2) && ! (d && d->precedence == this->precedence && d->b->value < b.value) && !__builtin_mul_overflow(a.value, b.value, &r) ? r : 0; } }; struct DivideOperator : Operator { DivideOperator() : Operator(PREC_DIVIDE, "/") {} long evaluate(const Term& a, const Term& b) const override { return b.precedence/10 != PREC_DIVIDE/10 && b.value > 1 && a.value % b.value == 0 && !contains_value(a, PREC_MULT, b.value) ? a.value / b.value : 0; } }; struct ConcatOperator : Operator { ConcatOperator() : Operator(PREC_CONCAT, "") {} long evaluate(const Term& a, const Term& b) const override { #ifdef CONCAT_DIGITS if (a.precedence > PREC_CONCAT || a.value == 0 || b.precedence >= PREC_CONCAT) return 0; #else // CONCAT_FULL if (b.precedence == PREC_CONCAT || a.value == 0) return 0; #endif long bv = b.value, av = a.value, x = 1, r; if (b.precedence > PREC_CONCAT) while (x <= bv) x*= 10; else { int d = b.to_string().length(); while (d--) x*= 10; } return __builtin_mul_overflow(av, x, &r) || __builtin_add_overflow(r, bv, &r) ? 0 : r; } }; struct ReverseConcatOperator : ConcatOperator { BinaryTermPointer make_term(TermPointer a, TermPointer b) const override { return ConcatOperator::make_term(b, a); } }; static const std::vector<std::shared_ptr<const Operator>> ops{ #ifndef CONCAT_NONE std::make_shared<ConcatOperator>(), std::make_shared<ReverseConcatOperator>(), #endif std::make_shared<MultiplyOperator>(), std::make_shared<AddOperator>(), std::make_shared<SubtractOperator>(), std::make_shared<DivideOperator>(), }; // Implement the BinaryTerm members that use Operator BinaryTerm::BinaryTerm(long value, const Operator* op, std::shared_ptr<const Term> a, std::shared_ptr<const Term> b) : Term(value, op->precedence), op(op), a(std::move(a)), b(std::move(b)) {} std::string BinaryTerm::to_string(int p) const { auto const s = op->to_string(*a, *b); return (p/10) < (precedence/10) ? "("+s+")" : s; } // An object to represent our target value, and how close we have // reached so far. struct Target { const long value; double max_badness = 0; LiteralTerm best = {"0"}; long best_badness = value; bool done() const { return best_badness < max_badness; } double score() const { return 1.*best_badness/value; } void update(const Term& t) { auto badness = std::abs(t.value - value); if (badness < best_badness) { best = t.as_literal(); best_badness = badness; } } void update(const TermList& terms) { for (auto t: terms.terms) update(*t); } void increase_threshold(size_t items_seen) { // Adjust our acceptance threshold nearer to accepting 0 by // 0.01% for every million values seen. max_badness += (value - max_badness) * .0001 * std::exp(items_seen / 1000000); } }; // OpenMP reduction for sets auto merge(auto& a, auto& b) { auto it = a.begin(); for (auto&& e: b) it = a.insert(std::move(e)).first; return a; } #pragma omp declare reduction(merge: Set: merge<Set>(omp_out, omp_in) ) \ initializer(omp_priv = Set()) // We run a cascade of pair-wise combination steps, where for each // input TermList, we generate every possible allowed pairing of its // terms, and pass that through (in batches) to the next stage. struct Combiner { std::unique_ptr<Combiner> const next; Target& target; size_t const max_output_size; size_t const nterms; Set input = {}; size_t output_size = 0; Combiner(Target& target, size_t nterms, size_t max_output_size) : next(nterms > 0 ? std::make_unique<Combiner>(target, nterms-1, max_output_size) : nullptr), target(target), max_output_size(max_output_size), nterms(nterms) {} inline void insert(const TermList&& t) { target.update(t); if (target.done()) return; if (next) { if (input.insert(t).second) output_size += count_distinct_pairs(t); if (output_size >= max_output_size) process_input(); } } void finish() { process_input(); if (next) next->finish(); } private: // Here's where we do the real work - generating and sifting the // combined terms for the next pass. void process_input() { if (target.done()) { return; } if (!next) return; // Move the elements into a vector, so we can parallelize the // for-loop. auto in = std::vector<Set::value_type>(); in.reserve(input.size()); std::move(input.begin(), input.end(), std::back_inserter(in)); input.clear(); output_size = 0; auto out = Set(); #pragma omp parallel reduction(merge:out) { #pragma omp for for (auto it = in.begin(); it < in.end(); ++it) { try { const auto end = it->terms.cend(); for (auto i = it->terms.cbegin(); i != end; i = std::upper_bound(i, end, *i)) for (auto j = i+1; j != end; j = std::upper_bound(j, end, *j)) { for (const auto& op: ops) { auto x = op->make_term(*i, *j); if (x) out.insert(replace(*it, i, j, x)); } } } catch (const std::bad_alloc&) { // Ignore it; process what we've generated so far. } } } // Now we're in single-threaded code, we can pass the combined // results to the next combiner. for (auto& o: out) next->insert(std::move(o)); target.increase_threshold(out.size()); } // Helper methods used by the above // An upper bound on the possible number of output TermLists, // assuming every combination is valid. If all n terms in the // input list are distinct, that's just ½n(n-1), but if values // are duplicated, we need to reduce n to the number of distinct // values, and then add in the cases where we pick two of the // same value. static int count_distinct_pairs(const TermList& terms) { int distinct = 0, duplicated = 0; auto it = terms.terms.begin(), end = terms.terms.end(); while (it != end) { ++distinct; auto const& v = (*it)->value; if (++it == end || (*it)->value != v) continue; ++duplicated; while (++it != end && (*it)->value == v) ; } return distinct * (distinct - 1) / 2 + duplicated; } // Create a new TermList from o by replacing elements i and j with // newly-created term n. static TermList replace(const TermList& o, auto i, auto j, std::shared_ptr<const Term> n) { std::vector<std::shared_ptr<const Term>> r; r.reserve(o.terms.size() - 1); auto added = false; for (auto k = o.terms.begin(); k != o.terms.end(); ++k) { if (!added && (*k)->value < n->value) { r.push_back(n); added = true; } if (k != i && k != j) r.push_back(*k); } if (!added) r.push_back(n); return { r, o.target_value }; } }; #include <iostream> std::ostream& operator<<(std::ostream& o, const Term& t) { return o << t.to_string()<< " = " << t.value; } std::ostream& operator<<(std::ostream& o, const TermList& t) { auto *sep = ""; o << "[" << t.badness << "] "; for (auto const& x: t.terms) o << sep << *x, sep = ", "; return o; } int main(int argc, char **argv) { if (argc < 3) { std::cerr << "Usage: " << argv[0] << " target term ..."; return EXIT_FAILURE; } auto target = Target{std::stol(*++argv)}; std::vector<std::shared_ptr<const Term>> terms; while (*++argv) { auto t = std::make_shared<LiteralTerm>(*argv); target.update(*t); terms.push_back(t); } std::sort(terms.begin(), terms.end()); // Construct the sieve Combiner search{target, terms.size(), 2500000/terms.size() + 1}; // tunable - max set size search.insert({terms, target.value}); search.finish(); std::cout << "score " << std::fixed << target.score() << " for " << target.best << std::endl; } ``` I compiled this using GCC 6.2, using `g++ -std=c++17 -fopenmp -march=native -O3` (along with some debugging and warning options). [Answer] # Python 2.7. Score: 1,67039106 So, I decided to have a throw at it myself. Nothing too fancy. This program sorts the numbers in reverse order (big to small), and tries all operators sequentially on the numbers. Blazing fast, but a performance that deserves to be superseded. Here is the program: ``` import sys def score(current,target): return abs(1.0-current/float(target)) # Process input and init variables targetvalue=int(sys.argv[1].strip(',')) numbers=[int(a.strip(',')) for a in sys.argv[2:]] numbers.sort(reverse=True) expression='('+str(numbers[0])+')' currentvalue=nextvalue=testvalue=numbers[0] # Loop over all values (except the first one) for value in numbers[1:]: # Set multiplication as the reference operator... testvalue=currentvalue*value minscore=score(testvalue,targetvalue) operator="*" nextvalue=testvalue # then try division (only if result is integer and not divided by zero)... if value!=0 and currentvalue%value==0: testvalue=currentvalue/value if score(testvalue,targetvalue)<minscore: operator="/" minscore=score(testvalue,targetvalue) nextvalue=testvalue # and addition... testvalue=currentvalue+value if score(testvalue,targetvalue)<minscore: operator="+" minscore=score(testvalue,targetvalue) nextvalue=testvalue # and subtraction... testvalue=currentvalue-value if score(testvalue,targetvalue)<minscore: operator="-" minscore=score(testvalue,targetvalue) nextvalue=testvalue # and concatenation testvalue=int(str(currentvalue)+str(value)) if score(testvalue,targetvalue)<minscore: operator="" minscore=score(testvalue,targetvalue) nextvalue=testvalue # finally check if any operator improces the score. If so, append to the expression if score(nextvalue,targetvalue)<score(currentvalue,targetvalue): expression='('+expression+operator+str(value)+')' currentvalue=nextvalue print(expression) ``` The output for all the test cases is: ``` ((((((15)14)*13)-12)-11)-10) ((((((((((((999)996)+969)+966)+699)+696)+669)+666)*69)-66)-9)-6) (((((((((333333333)+333333)+33333)+3333)+333)+33)+3)+3)+3) (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((5)5)5)5)5)5)5)5)5)+5)+5)+5)+5)+5)+5)+4)+4)+4)+4)+4)+4)+4)+4)+4)+4)+4)+4)+4)+4)+4)+3)+3)+3)+3)+3)+3)+3)+3)+3)+3)+3)+3)+3)+3)+3)+2)+2)+2)+2)+2)+2)+2)+2)+2)+2)+2)+2)+2)+2)+2)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1) ((((((((((((((((((((((((((((((((((((((((((((((199)197)193)+191)+181)+179)+173)+167)+163)+157)+151)+149)+139)+137)+131)+127)+113)+109)+107)+103)+101)+97)+89)+83)*79)-73)-71)-67)-61)-59)-53)-47)-43)-41)-37)-31)-29)-23)-19)-17)-13)-11)-7)-5)-3)/2) (((((((((((((((((((((((((((((((992)930)870)+812)+756)+702)+650)+600)+552)+506)+462)+420)+380)+342)+306)+272)+240)+210)+182)*156)-132)-110)-90)-72)-56)-42)-30)/20)*12)-6)-2) ((((((((((((((((((((((((((((((((((((((39088169)+24157817)+14930352)+9227465)+5702887)+3524578)+2178309)+1346269)+832040)+514229)+317811)+196418)+121393)+75025)+46368)+28657)+17711)*10946)-6765)-4181)-2584)-1597)-987)-610)-377)-233)-144)-89)-55)-34)-21)-13)-8)-5)-3)/2)+1)+1) (((((((((((((((((((((50000000)+20000000)+10000000)+5000000)+2000000)+100000)*50000)-20000)-10000)-5000)-2000)-1000)-500)-200)-100)-50)-20)-10)/5)*2)+1) ``` ]
[Question] [ The [MU puzzle](https://en.wikipedia.org/wiki/MU_puzzle) is a puzzle in which you find out whether you can turn `MI` into `MU` given the following operations: 1. If your string ends in `I`, you may add a `U` to the end. (e.g. `MI -> MIU`) 2. If your string begins with `M`, you may append a copy of the part after `M` to the string. (e.g. `MII -> MIIII`) 3. If your string contains three consecutive `I`'s, you may change them into a `U`. (e.g. `MIII -> MU`) 4. If your string contains two consecutive `U`'s, you may delete them. (e.g. `MUUU -> MU`). Your task is to build a program that determines whether this is doable for any start and finish strings. Your program will take two strings as input. Each string will consist of the following: * one `M`. * a string of up to twenty-nine `I`'s and `U`'s. Your program will then return `true` (or your programming language's representation thereof/YPLRT) if the second string is reachable from the first string, and `false` (or YPLRT) if it is not. Example inputs and outputs: ``` MI MII true MI MU false MIIIIU MI true ``` The shortest code in any language to do this wins. [Answer] # SWI Prolog, 183 characters ``` m(A,A). m([i],[i,u]). m([i,i,i|T],B):-m([u|T],B). m([u,u|T],B):-m(T,B). n([m|A],[m|B]):-(m(A,B);append(A,A,X),m(X,B)). n(A,B):-m(A,B). s(A,B):-atom_chars(A,X),atom_chars(B,Y),n(X,Y). ``` How about some Prolog, (since nobody has answered in 6 months). To run, just use "s(mi,mu)." The code breaks up atoms into chars, then searches for the solution. ]
[Question] [ Write a program that prints the following 80-character line: > > This program from codegolf.stackexchange.com permutes itself to encode a string. > > > then accepts one line of input, then prints its source code with its [code points](//en.wikipedia.org/wiki/Code_point) possibly reordered (none added and none deleted). When that code is executed, the same has to happen, except the printed line would be the most recent line of input. The Perl-style regex `^[A-Za-z0-9. ]{80}$` will match any line of input. You cannot make any additional assumption. A submission's score is the number of **code points** in its source code **less 94**. Lower is better. The code must not do anything that would be unacceptable in a quine (*e.g.* file reading). In particular, any submission with a negative score must be cheating somehow, as 93! is less than 6480. **Added 2014-04-21:** Your program's entire source code must be well-formed in the character encoding under which you count code points. For example, you cannot use 80 consecutive bytes in the UTF-8 trailing byte range (80..BF) and count each as a single U+FFFD REPLACEMENT CHARACTER (or worse, as not a code point at all). Additionally, if the encoding allows multiple ways to encode a code point (*e.g.* [SCSU](//en.wikipedia.org/wiki/Standard_Compression_Scheme_for_Unicode)), your program, as well as all programs it directly or indirectly generates, must only use one of them (or at least all must be treated equivalently throughout the code). [Answer] # GolfScript, ~~231~~ ~~162~~ 131 ``` '1àâ4ÿaVo5GùpZBtiXOürsóNîMmWåKHc09JdñúêyzíECäYïhDU ãáIFõ6é8òRìjTv23ønuðLwxfSkôbëAelqý.çèPQ öûg7'{0@.$[{}/]:&\{@2$,*2$2$?+@@^}/{;65base}:b~{&=}%''+puts'"#{`head -1`}"'~{&?}%)b[94,{)1$1$%@@/}/;]-1%&\[{1$=.@^}/]"'".@+\+\'.~'}.~ ``` ### How it works We start by choosing 94 different characters that will get permuted to encode a string. Any 94 characters would work, but we choose the following for golfing purposes: ``` \n .0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz àáâãäåçèéêëìíîïðñòóôõöøùúûüýÿ ``` Let's call the array of these characters “&”. The line of input will always contain 81 characters (including the LF). All of those characters are present in the first 65 characters of “&”. This is the sole reason for choosing characters in the upper 128 bytes. We replace each character of the string by its index in “&”, so LF becomes 0, space becomes 1, etc. We consider the 81 obtained numbers the digits of a single base 65 number. Let's call this number “N”. Now, we enumerate all possible permutations of “&” and retrieve the permutation corresponding to the number from above. This is achieved in the following manner: 1. Set `c = 1` and `A = []`. 2. Prepend `N % c` to `A`. 3. Set `N = N / c` and `c = c + 1`. 4. If `c < 95`, go back to 2. 5. Set `i = 0` and `s = ""`. 6. Retrieve the charcter `&[A[i]]`, append it to “s” and remove it from “&”. 7. Set `i = i + 1`. 8. If `i < 94` go back to 6. Suppose we have code blocks “E” and “D” that encode and decode a string as explained above. Now, we need a wrapper for those code blocks that complies with the requirements of the question: ``` 'encoded string'{\.$[{}/]:&; D puts '"#{`head -1`}"'~ E "'".@+\+\'.~'}.~ ``` This does the following: * `{…}.~` defines a block, duplicates it and executes the second copy. The first copy will remain on the stack. * `\.$` swaps the encoded string with the block and creates a copy of the encoded string, with sorted characters. * `[{}/]:&;` converts the string from above into an array, saves it in “&” and discards it. * `D puts` decodes the encoded string and prints the result. * `'"#{`head -1`}"'~` reads one line of input by executing `head -1` in the shell. * `E "'".@+\+` encodes the string and prepends and appends a single quote. * `\'.~'` swaps the encoded string and the block and appends the string `'.~'`. * After the block has been executed, GolfScript prints the contents of the stack (encoded string, block, `'.~'`) and exits. “E” can be defined as follows: ``` {&?}% # Replace each character by its index in “&”. ); # Remove the last integer from the array, since it corresponds to the LF. 65base # Convert the array to an integer “N” by considering it a base 65 number. [ # 94, # For each integer “c” in 0 … 93: { # ) # Increment “c”. 1$1$% # Push “N % c”. @@/ # Rotate “N % c” below “N” and “c” and divide the first by the latter. }/; # Discard “N”. ] # Collect the results of “N % c” in an array “A”. -1% # Reverse “A”. &\ # Push “&” and swap it with “A”. [ # { # For each “j” in “A”: 1$=.[]+ # Push “&[j] [&[j]]”. @^ # Rotate “&” on top of “[&[j]]” and take their symmetric difference. }/ # ] # Collect the charcters into an array. ``` “D” can be defined as follows: ``` 0& # Push 0 (initial value of the accumulator “A”) and “&”. @ # Rotate the encoded string on top of “&”. { # For each character “c” of the encoded string: @2$,* # Rotate “A” on top of the stack and multiply it by the length of “&”. 2$2$?+ # Get the index of “c” in “&” and add it to “A”. @@^ # Rotate “A” below “&” and “c” and take their symmetric difference. }/; # Discard “&”. 65base # Convert “A” into the array of its digits in base 65. {&=}% # Replace each digit by the corresponding character in “&”. ''+ # Convert the resulting array into a string. ``` Final golfing: * Replace `\.$[{}/]:&;0&@` with `0@.$[{}/]:&\` to save two characters. * Define the function `{;65base}:b` to save one character. * Remove all whitespace except the trailing LF and the LF in the string. ### Example ``` $ # Create GolfScript file using base64 to avoid encoding issues. $ base64 > permute.gs -d <<< JzHg4jT/YVZvNUf5cFpCdGlYT/xyc/NO7k1tV+VLSGMwOUpk8frqeXrtRUPkWe9oRFUg4+FJRvU26TjyUuxqVHYyM/hudfBMd3hmU2v0YutBZWxx/S7n6FBRCvb7ZzcnezBALiRbe30vXTomXHtAMiQsKjIkMiQ/K0BAXn0vezs2NWJhc2V9OmJ+eyY9fSUnJytwdXRzJyIje2BoZWFkIC0xYH0iJ357Jj99JSliWzk0LHspMSQxJCVAQC99LztdLTElJlxbezEkPS5AXn0vXSInIi5AK1wrXCcufid9Ln4K $ $ # Set locale to en_US (or any other where one character is one byte). $ LANG=en_US $ $ # Go back and forth between two different strings. $ # Second and sixth line are user input, not output from the script. $ $ golfscript permute.gs | tee >(tail -n+2 > tmp.gs) && golfscript tmp.gs && rm tmp.gs This program from codegolf.stackexchange.com permutes itself to encode a string. Permuting source code code points to encode a string is a certain quine variant. '18äJoS3sgV9qdçëxm0ÿKMNe5íPî.Htn2ciâIuøbRZéð4AwB7áìUüöôWõèûfñåLàóDrhQlO6 pTaýzòkùYCyFêïãG júEvX'{0@.$[{}/]:&\{@2$,*2$2$?+@@^}/{;65base}:b~{&=}%''+puts'"#{`head -1`}"'~{&?}%)b[94,{)1$1$%@@/}/;]-1%&\[{1$=.@^}/]"'".@+\+\'.~'}.~ Permuting source code code points to encode a string is a certain quine variant. This program from codegolf.stackexchange.com permutes itself to encode a string. '1àâ4ÿaVo5GùpZBtiXOürsóNîMmWåKHc09JdñúêyzíECäYïhDU ãáIFõ6é8òRìjTv23ønuðLwxfSkôbëAelqý.çèPQ öûg7'{0@.$[{}/]:&\{@2$,*2$2$?+@@^}/{;65base}:b~{&=}%''+puts'"#{`head -1`}"'~{&?}%)b[94,{)1$1$%@@/}/;]-1%&\[{1$=.@^}/]"'".@+\+\'.~'}.~ $ $ # Sort all characters from the original source code and hash them. $ fold -1 permute.gs | sort | md5sum b5d978c81df5354fcda8662cf89a9784 - $ $ # Sort all characters from the second output (modified source code) and hash them. $ golfscript permute.gs | tail -n+2 | fold -1 | sort | md5sum Permuting source code code points to encode a string is a certain quine variant. b5d978c81df5354fcda8662cf89a9784 - $ $ # The hashes match, so the characters of the modified source code are a permutation $ # of the character of the original one. ``` [Answer] # Perl, ~~1428~~ 1099 This has 1193 ASCII characters (including 960 permuted binary digits). 1193 - 94 = **1099** ``` $s='010011100001100010101100111111101001101011101000100000101011011010100110111111011111101011101000100110111111011100101000011101011110100000101000100101011111111110101100101101011010011100100100011110110001011100100001011010100111100000011110111110011100101000100110111111101001011110101011100110101110101101011110101100111111100010101101101100011110100101011111111111101101101000111111011110100111011100101000011101011110111111011010111111101100101101101011100010100111100000111110';$_=q{$i=join'',A..Z,a..z,0..9,'. ';print map({substr$i,oct'0b'.$_,1}$s=~/.{6}/g),$/;chop($s=<>);$s=join'',map{sprintf"%06b",index$i,$_}$s=~/./g;$t=join'',map{$_ x(480-(()=$s=~/$_/g))}0,1;print"\$s='$s';\$_=q{$_};eval#$t"};eval#000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 ``` ## My first design Before I took a suggestion from Dennis to switch to binary, my program permuted octal digits. My first design encodes each string in 160 octal digits, with 2 digits per character. This encoding has 1008=64 different characters. The octal system has 8 different digits. The program must have 160 copies of each digit, so it permutes 8×160=1280 digits. I keep 160 digits in `$s` and the other 1120 digits in `$t`. I start with a program that is not a quine, but only prints the assignments to `$s` and `$t` for the next run. This is it: ``` $s = '2341425477515350405332467737535046773450353640504537765455323444366134413247403676345046775136534656553654774255543645377755507736473450353677327754555342474076'; $t = '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222223333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333334444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666667777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777'; # $i = character map of 64 characters, such that: # substr($i, $_, 1) is the character at index $_ # index($i, $_) is the index of character $_ $i = join '', 'A'..'Z', 'a'..'z', '0'..'9', '. '; # Decode $s from octal, print. # 1. ($s =~ /../g) splits $s into a list of pairs of octal digits. # 2. map() takes each $_ from this list. # 3. oct() converts $_ from an octal string to a number. # 4. substr() on $i converts number to character. # 5. print() outputs the characters from map() and a final "\n". print map({ substr $i, oct, 1 } $s =~ /../g), "\n"; # Read new $s, encode to octal. # 1. ($s = <>) reads a line. # 2. chop($s) removes the last character of $s, the "\n". # 3. ($s =~ /./g) splits $s into characters. # 4. map() encodes each character $_ as a pair of octal digits. # 5. join() concatenates the pairs from map(). chop($s = <>); $s = join '', map { sprintf "%02o", index $i, $_ } $s =~ /./g; # Make new $t. # 1. map() takes each $_ from 0 to 7. # 2. $_ x (160 - (() = $s =~ /$_/g)) makes a string where $_ repeats # 160 times, minus the number of times that $_ appears in $s. # 3. join() concatentates the strings from map(). $t = join '', map { $_ x (160 - (() = $s =~ /$_/g)) } 0..7; # Print the new assignments for $s and $t. This is not yet a quine, # because it does not print the rest of the program. print "\$s = '$s';\n\$t = '$t';\n"; ``` `(() = $s =~ /$_/g))` is an assignment to an empty list of variables. I take this trick from the [context tutorial at PerlMonks](http://www.perlmonks.org/?node_id=738558). It forces list context on the match operator `=~`. In scalar context, the match would be true or false, and I would need a loop like `$i++ while ($s =~ /$_/g)` to count the matches. In list context, `$s =~ /$_/g` is a list of matches. I put this list in the scalar context of a subtraction, so Perl counts the list elements. To make a quine, I take the form `$_=q{print"\$_=q{$_};eval"};eval` from the [Perl quines at Rosetta Code](http://rosettacode.org/wiki/Quine#Perl). This one assigns a string `q{...}` to `$_` and then calls `eval`, so I can have my code in a string and also run it. My program becomes a quine when I wrap my third to last lines in `$_=q{` and `};eval`, and change my last `print` to `print "\$s = '$s';\n\$t = '$t';\n\$_=q{$_};eval"`. Finally, I golf my program by changing the first assignment to `$t` to a comment, and by removing extra characters. This has 1522 ASCII characters (including 1280 permuted octal digits). 1522 - 94 = **1428** ``` $s='2341425477515350405332467737535046773450353640504537765455323444366134413247403676345046775136534656553654774255543645377755507736473450353677327754555342474076';#0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222223333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333334444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666667777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777 $_=q{$i=join'','A'..'Z','a'..'z','0'..'9','. ';print map({substr$i,oct,1}$s=~/../g),"\n";chop($s=<>);$s=join'',map{sprintf"%02o",index$i,$_}$s=~/./g;$t=join'',map{$_ x(160-(()=$s=~/$_/g))}0..7;print"\$s='$s';#$t\n\$_=q{$_};eval"};eval ``` ## The switch to binary In the comments, Dennis noticed that 960 permuted binary digits would be fewer than 1280 octal digits. So I graphed the number of permuted digits for each base from 2 to 16. ``` Maxima 5.29.1 http://maxima.sourceforge.net using Lisp ECL 13.5.1 ... (%i36) n : floor(x); (%o36) floor(x) ... (%i41) plot2d(n * ceiling(log(64) / log(n)) * 80, [x, 2, 16], [xlabel, "base"], [ylabel, "number of permuted digits"]); (%o41) ``` ![graph with base on x-axis, number of permuted digits on y-axis](https://i.stack.imgur.com/Z6CaV.png) Though base 8 is a local minimum, bases 2 and 3 and 4 tie for best base, at 960 permuted digits. For code golf, base 2 is best because Perl has conversions for base 2. Replacing 1280 octal digits with 960 binary digits saves 320 characters. Switching code from octal to binary costs 8 characters: * Change `oct` to `oct'0b'.$_` costs 7. * Change `/../g` to `/.{6}/g` costs 2. * Change `"%02o"` to "%06b"` costs 0. * Change `160` to `480` costs 0. * Change `0..7` to `0,1` saves 1. I learned some [Perl golf tips](https://codegolf.stackexchange.com/q/5105/4065). They save 14 characters: * Change `'A'..'Z','a'..'z','0'..'9'` to `A..Z,a..z,0..9`, using barewords and bare numbers, saves 12 characters. * Change `"\n"` to `$/` saves 2 characters. I save 3 characters by moving the `#$t` comment to the end of the file. This removes the newline that ends the comment, and a literal `\n` in the quine. These changes save a total of 329 characters, and reduce my score from 1428 to 1099. ]
[Question] [ # Notation and definitions Let \$[n] = \{1, 2, ..., n\}\$ denote the set of the first \$n\$ positive integers. A [polygonal chain](https://en.wikipedia.org/wiki/Polygonal_chain) is a collection of connected line segments. The *corner set* of a polygonal chain is a collection of points which are the endpoints of one or more of the line segments of the chain. # Challenge The goal of this challenge is to write a program that takes two integers, \$n\$ and \$m\$ and computes the number of non-self-intersecting polygonal chains with corner set in \$[n] \times [m]\$ that hit every point in \$[n] \times [m]\$ and are stable under \$180^\circ\$ rotation. You should count these shapes up to the symmetries of the rectangle or square. Note: In particular, a polygon is considered to be self-intersecting. # Example For example, for \$n=m=3\$, there are six polygonal chains that hit all nine points in \$[3] \times [3]\$ and are the same after a half-turn: [![3 X 3 polygonal chains](https://i.stack.imgur.com/jwf29.png)](https://i.stack.imgur.com/jwf29.png) ### Table of small values ``` n | m | f(n,m) ---+---+------- 1 | 2 | 1 1 | 3 | 1 2 | 1 | 1 2 | 2 | 1 2 | 3 | 5 2 | 4 | 11 2 | 5 | 23 3 | 1 | 1 3 | 2 | 5 3 | 3 | 6 3 | 4 | 82 ``` # Scoring This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so shortest code wins. [Answer] # [Python 3](https://docs.python.org/3/) + [SymPy](https://docs.sympy.org/latest/index.html), ~~480~~ ~~455~~ 452 bytes ``` lambda w,h:len({min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w+~p[0],p[1]),I),(lambda p:(p[0],h+~p[1]),I),(lambda p:p[::-1],I)))for o in permutations(Q(range(w),range(h)))for s in[[*zip(o,o[1:])]]if any(x-~X-w|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))+any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s))<1}) from math import* from sympy import* from itertools import* Q=product S=Segment I=tuple ``` [Try it online!](https://tio.run/##ZVBNb8IwDL3zK3Kb3brSAtsO1eDEAY4ICYG6HjpoaSXyoTal7Tb46ywlbNqEIsXO83t@jnVnciVHl2z8djkk4n2XsIby8JBK@BSFhDlMYQYraBExUyVrWSGZuqYzWtG0fy4AblIdQuOfdfQYk454jDRH@lO7FvKecFfTURgGPLag81F9Y52WojaJKZSsYAFlIvcpNEguyW/UylKjyPsoNChSEQ9jjOMiY4nsoA3O66D56vxNkPvcsqGlzvquaYPW4Edz9Ub0e8l@u7OyNXXBBif3ksqx4LohrybveMLJCL1CmrSs0m0/LCzBq5HsfXQj1nR0i6qoQnzlJxxkpRJMJCZnhdCqNJ5Dqk7o7j9U2MZGqUP1Cy/GulS7emsGy/Ey3YtUmsF8bGp9SC@9nSTR20XAaYjEbBj1YUjchaELN/AJ45Dp0n4AMrBSxEHEyZ1n4pweXh7iyzc "Python 3 – Try It Online") Inlined version of the previous answer below. -3 bytes thanks to [Kevin Cruijssen's tip](https://codegolf.stackexchange.com/a/144481/78410). --- # [Python 3](https://docs.python.org/3/) + [SymPy](https://docs.sympy.org/latest/index.html), 480 bytes ``` from math import* from sympy import* from itertools import* Q=product S=Segment I=tuple def f(w,h): a={1} for o in permutations(Q(range(w),range(h))): s=[*zip(o,o[1:])] if any(x+X-w+1|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))+any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s))<1:a.add(min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w-1-p[0],p[1]),I),(lambda p:(p[0],h-1-p[1]),I),(lambda p:p[::-1],I)))) return~-len(a) ``` [Try it online!](https://tio.run/##ZU/LbtswELzrK3jLrrQqSrvtQahyyiE@GgYCG4IOrEVZAswHKMqWmqa/7pJWHyhCAhxidmZ3x86@M3p9u7XOKKaE71ivrHE@Te7MMCs7/0/1XjpvzHn4S29L60wzHn2yK3fypKT2yab0oz3LpJEta@FKHRYJE@Urf0tYaxwzrNfMSqdGL3xv9ABbcEKfJFyRlk@HGE1sKKv0e2/BkKl4UWMduL5lQs8wZfv8mvEfc3bIu4yHxjDRjAR7OmAY8MdWFDmvEbPoOR0bmPI9zfkBH99bhkUFZ6nhNR0pvbzh4xrTXofcgzzGZWEH6YgU3gtiTDPSJebZwkAD4ldeiA@iaUD1GjbwBM/wAhMu0ikKzf37TC/0tPjgLNS3RjBbwDXnua0@1mSrsDNtwmr/ivdCd1e8K9olZiDDSZiTfnT6Zx6DCLzFgZpUHFcBpxUSC7COsCK@wGqB3@QnrAtmXQgOLQRraFpxWu5n4pwevjzUt18 "Python 3 – Try It Online") The golfed version takes too long to check the nontrivial answers. The version below has a shortcut in the conditional, so you can check that the results up to `(2,4)` are correct. # [Python 3](https://docs.python.org/3/) + [SymPy](https://docs.sympy.org/latest/index.html), 483 bytes ``` from math import* from sympy import* from itertools import* Q=product S=Segment I=tuple def f(w,h): a={1} for o in permutations(Q(range(w),range(h))): s=[*zip(o,o[1:])] if(any(x+X-w+1|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))or any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s)))<1:a.add(min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w-1-p[0],p[1]),I),(lambda p:(p[0],h-1-p[1]),I),(lambda p:p[::-1],I)))) return~-len(a) ``` [Try it online!](https://tio.run/##ZU/LbtswELzrK3jLrrQqSrvtQahyyiE@GgYCG4IOrEVZAswHKMqWmqa/7pJWHyhCAhxidmZ3x86@M3p9u7XOKKaE71ivrHE@Te7MMCs7/0/1XjpvzHn4S29L60wzHn2yK3fypKT2yab0oz3LpJEta@FKHRYJE@Urf0tYaxwzrNfMSqdGL3xv9ABbcEKfJFyRlk@HGE1sKKv0e2/BkKl4UWMduL4FoWeYsn1@zfiPOTvkXcZDY5hoRoI9HTAM@GMripzXiGFudJ2ODUz5nub8gI/vTQNmUQVnqeE1HSm9vOHjGtNeh@SDPMZ1YQfpiBTeC2LMM9IlJtrCQEPY@ysvxAfRNKB6DRt4gmd4gQkX7RSV5v59phd6WoxwFupbI5gt4Jrz3FYfa7JVWJs2Ybd/xXuhuyveFe2SNJDhJMxJPzr9M49JBN7iQE0qjquA0wqJBVhHWBFfYLXAb/IT1gWzLiSHFoI1NK04LfczcU4PXx7q2y8 "Python 3 – Try It Online") ## Ungolfed, with comments ``` from math import* from sympy import* from itertools import* def pass_point(p1,p2): # test if the segment passes through another point return gcd(p1[0]-p2[0],p1[1]-p2[1]) > 1 def f(w,h): pts = [(i,j) for i in range(w) for j in range(h)] ans = set() for orders in permutations(pts): # test if the ordering has 180 degrees rotational symmetry if any(x1+x2!=w-1or y1+y2!=h-1for (x1,y1),(x2,y2) in zip(orders, orders[::-1])):continue segments = [*zip(orders, orders[1:])] # test if a segment passes through another point or two segments intersect if any(pass_point(*p)for p in segments)+any(len({*s1,*s2})==4and intersection(Segment(*s1),Segment(*s2))for s1 in segments for s2 in segments):continue # take minimum of 8 possible rotations/reflections flipH = lambda p:(w-1-p[0],p[1]); flipV = lambda p:(p[0],h-1-p[1]); flipD = lambda p:p[::-1]; nop = lambda p:p flipmin = min(tuple(map(lambda o:d(h(v(o))),orders))for h in (flipH,nop)for v in (flipV,nop) for d in (flipD, nop)) ans.add(flipmin) print(len(ans)) ``` [Try it online!](https://tio.run/##jVPLbtswELz7K7bohbTpNpTTIlDgnnLovUAuhlAwFiUxFR8gqThq0W93l5TiR9FDIUAUhzO7O7uUG2NnzeZ4bLzVoEXsQGlnfVwuMhJG7cZrSEXpo7V9OMG1bMCJEL47q0wkjjNX0BLeQ5QhgmogdhKCbLU0MRNlQMjboe1AGIunHrJ0AV7GwRto9zWG2d1Ua1fgm@E3z9@8ovAFeE7ZkAPraLkAFwNsYUcUe6bQWA8KlAEvTCvJYUKez0hHqwWmTZIgI6GLTLC@lj4klpNeD1FEZU0gGDpl@MtLJivTQicC8LsbqGXrJbrydhKKPnVOy@hHFKNKmJG88tVr8W57WHPMN/LViJtuzVN2PGMjp4y8FmwsaCrjp3JkKorNxe3Kco3@abm3JiozSAw9dzX7X/5Dwssq2b2oX/zXJFAP8WDP8RHDeHIfz34uRr50NNlwqfA3CV0lUi8N@bUMnC1D8Ztut7fC1Odg2CrybeITJFF23hQ0hwz8MmYeVSiu0ly2A22KHxK0MkoPGmwDd@gnBPXUy9Nwwkcvm37KHlDU9Mp9xQb2Qj/VAlxJcERrl@9dunD3mfF4xcinXaadGA@XDDdN6x6MdVf4nBBLRBjfJA6ul0QLR2aSLWvSkRdiKaVsmuPUiy75JrlchmEz9nLCHjOWO1SfwAeWCqB4ydOV/yDqmszZEXI@zS5NCM8oPSapYTqJd4SzgjLAZZOWgvFpKaZlBm/TssFdVeLviFq62HE2PZ8Y5@xzdfwD "Python 3 – Try It Online") SymPy has [Geometry module](https://docs.sympy.org/latest/modules/geometry/index.html) that includes an intersection checker `intersection` that works for line segment `Segment` objects. This is much shorter than rolling a hand-written intersection checker based on coordinates. The `intersection` of two `Segment`s is either an empty array (if they don't intersect) or an array that contains a single object (either `Point` or `Segment`, depending on the input). ]
[Question] [ You're a farmer and your flock of sheep has escaped! Oh no! Round up those sheep by building fences to contain them. As a farmer on a budget you want to use the least amount of fence possible. Luckily for you though, they aren't the smartest sheep in the world and don't bother moving after having escaped. # Task Given a list of coordinates, output the least amount of fence segments necessary to contain the sheep. # Rules * Sheep are contained if they cannot wander off (no holes in the fence). * You do not have to contain all the sheep in one block of fence - there could be multiple fenced-off areas independent from each other. * Fence segments are oriented in cardinal directions. * Each coordinate tuple represents a single sheep. * Input must be positive integer pairs, `x>0` & `y>0`, but can be formatted appropriately for your language. + i.e.: `{{1,1},{2,1},{3,7}, .. }` or `[1,2],[2,1],[3,7], ..` * Empty spaces inside a fenced-off area are okay. * You cannot assume coordinates are input in any specific order. For example, a single sheep requires `4` fence segments to be fully contained. # Test cases ``` [1,1] 4 [1,1],[1,2],[2,2] 8 [2,1],[3,1],[2,3],[1,1],[1,3],[3,2],[1,2],[3,3] 12 [1,1],[1,2],[2,2],[3,7],[4,9],[4,10],[4,11],[5,10] 22 [1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9] 36 [1,1],[2,2],[3,3],[4,4],[6,6],[7,7],[8,8],[9,9] 32 [2,1],[8,3],[8,4] 10 ``` **Notes** * You can assume input coordinates are valid. * Your algorithm should theoretically work for any reasonably large integer coordinate (up to your language's maximum supported value). * Either full program or function answers are okay. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! [Answer] ## JavaScript (ES6), ~~251~~ ~~244~~ 275 bytes ``` a=>Math.min(...(P=(a,r=[[a]],c=a[0])=>(a[1]&&P(a.slice(1)).map(l=>(r.push([[c],...l]),l.map((_,i)=>r.push([[c,...l[i]],...((b=[...l]).splice(i,1),b)])))),r))(a).map(L=>L.reduce((p,l)=>l.map(([h,v])=>(x=h<x?h:x,X=h<X?X:h,y=v<y?v:y,Y=v<Y?Y:v),x=y=1/0,X=Y=0)&&p+X-x+Y-y+2,0)))*2 ``` ### How? We use the recursive function ***P()*** to create a list of all possible partitions of the input list. This function is currently sub-optimal, in that it's returning some duplicated partitions -- which does not however alter the final result. For each partition, we compute the number of fences required to surround all sheep in each group with a rectangle. The sum of these fences gives the score of the partition. We eventually return the lowest score. ### Test cases ``` let f = a=>Math.min(...(P=(a,r=[[a]],c=a[0])=>(a[1]&&P(a.slice(1)).map(l=>(r.push([[c],...l]),l.map((_,i)=>r.push([[c,...l[i]],...((b=[...l]).splice(i,1),b)])))),r))(a).map(L=>L.reduce((p,l)=>l.map(([h,v])=>(x=h<x?h:x,X=h<X?X:h,y=v<y?v:y,Y=v<Y?Y:v),x=y=1/0,X=Y=0)&&p+X-x+Y-y+2,0)))*2 console.log(f([[1,1]])) console.log(f([[1,1],[1,2],[2,2]])) console.log(f([[2,1],[3,1],[2,3],[1,1],[1,3],[3,2],[1,2],[3,3]])) console.log(f([[1,1],[1,2],[2,2],[3,7],[4,9],[4,10],[4,11],[5,10]])) console.log(f([[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9]])) console.log(f([[1,1],[2,2],[3,3],[4,4],[6,6],[7,7],[8,8],[9,9]])) console.log(f([[2,1],[8,3],[8,4]])) ``` [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)), ~~62 58 57~~ 55 bytes ``` {+//2*1+{(|/x)-&/x}'(x@?(&|/2>(|/'{x|-x}x-\:)')')/,:'x} ``` [Try it online!](https://tio.run/##bY49DsIwDIWv4qlJaKMQpz9pLQEHYe7SgdVSk7OnDmVBIMtP9nufJW/2tZWyLnvrHF58u@vk2NjGcVaaH3fdJIc3MdXOyXJm@1yMknLdojiXVenOgyddxQMSAhrSKFuQRgh0JkF2fBMBgvnixZmoh1naX6t4GmT6QCcQxO/FHmiEkSY5iBBphvkP9UvUd6KkEXpjygE) ]
[Question] [ ## Rules The program should receive a string/array of words as input. For each word in the string/array, it will reconstruct the word by taking characters in alternating fashion from the front and back of the word. 12345 678 9 -> 15243 687 9. It will then rearrange the words in an alternating fashion between the earliest and the latest occurring word in the string. 15243 687 9 -> 15243 9 687 Finally, it will reconstruct the string by placing the spaces, tabs and newlines at the indexes where they were initially located before outputting the result. 12345 678 9-> 15243 687 9 -> 15243 9 687 -> 15243 968 7 Output should be the same datatype as the input. [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden ## Examples > > Input: > > The quick brown fox jumps over the lazy dog. > > Output: > > Teh d.ogq kucil yaz bnrwo tehf xoo rvej supm > > > Input: > > The quick brown fox jumps > > over the lazy dog. > > Output: > > Teh d.ogq kucil yaz bnrwo > > tehf xoo rvej supm > > > Input: > > Aflack > > Output: > > Akfcla > > > This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15 14~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) A **whopping** 6 byte save from **Dennis** (by moving the flatten and mould inside link 1 there is no need to split into two and head, and a flatten is there already so they become one!) ``` żṚFṁ Ç€Ç ``` (from the two lines: `żṚFœs2Ḣ`, and `Ç€ÇFṁ⁸`) **[Try it online!](https://tio.run/nexus/jelly#@390z8Ods9we7mzkOtz@qGnN4fb/h9u9//@PVgrJSFXSUSoszUzOBtJJRfnleUA6Lb8CSGaV5hYUA@n8stQiIFUCVpqTWFUJpFLy0/WUYgE)** Takes an array of words and returns an array of new words. (The Footer at TIO calls this and joins the array with spaces so it prints out nicely.) *Note - handling a single string, splitting on tabs spaces and newlines, then reassembling was actually proving rather tricky; once I saw that a list of words was an option things got a lot easier!* ### How? ``` Ç€Ç - Main link: list of words Ç€ - call the last link (1) as a monad for €ach word Ç - call the last link (1) as a monad for the result żṚFṁ - Link 1: Do a twist: list (here, a list of words or characters) e.g. input = [A,B,C,D,E,F,G] ż - zip the list with [A, B, C, D, E, F, G] Ṛ - the reverse of the list [G, F, E, D, C, B, A] [[A,G],[B,F],[C,E],[D,D],[E,C],[F,B],[G,A]] F - flatten into a single list [A,G, B,F, C,E, D,D, E,C, F,B, G,A] [A,G,B,F,C,E,D,D,E,C,F,B,G,A] ṁ - mould like the input list [A,G,B,F,C,E,D] ``` [Answer] ## JavaScript (ES6), 89 bytes Takes and outputs an array of words. ``` a=>a.map(w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(a.map(F)).slice(p,p+=w.length),p=0) ``` **Test** ``` let f = a=>a.map(w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(a.map(F)).slice(p,p+=w.length),p=0) console.log( JSON.stringify( f(["The","quick","brown","fox","jumps","over","the","lazy","dog."]) ) ); ``` ### String version, 112 bytes Takes and outputs a string. ``` s=>s.replace(/\S+/g,w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(s.split(/\s/).map(F)).slice(p,p+=w.length),p=0) ``` **Test** ``` let f = s=>s.replace(/\S+/g,w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(s.split(/\s/).map(F)).slice(p,p+=w.length),p=0) console.log(f(`The quick brown fox jumps over the lazy dog.`)) console.log(f(`The quick brown fox jumps over the lazy dog.`)) console.log(f(`Aflack`)) ``` [Answer] # [Perl](https://www.perl.org/), 77 bytes 74 bytes of code + 3 bytes for `-0pa` flags. ``` map{s/.\K/chop/ge,s/../chop/reg}@F;s/\S/($r||=$F[$i++].pop@F)=~s%.%%,$&/ge ``` [Try it online!](https://tio.run/nexus/perl#U1YsSC3KUdA1KEj8n5tYUF2srxfjrZ@ckV@gn56qA@TpQThFqem1Dm7WxfoxwfoaKkU1NbYqbtEqmdrasXoF@QUObpq2dcWqeqqqOipqQI3//4dkpCoUlmYmZyskFeWX5ymk5VcoZJXmFhRz5ZelFimUAKVzEqsqFVLy0/UA "Perl – TIO Nexus") Saved 8 bytes thanks to an old [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel)'s [post](https://codegolf.stackexchange.com/a/98709/55508) where I "stole" `s/../chop/reg`. (I previously had `$c=y///c/2,s/.{$c}$//`) [Answer] # [Perl 6](http://perl6.org/), 84 bytes ``` {my &t={(|(.shift,.pop)xx*)[^$_]} map({|t [.comb]},t [$_]).rotor($_».chars)».join} ``` Inputs and outputs a list of words. ### How it works Inside the lambda, I defined another lambda to perform the "*taking characters in alternating fashion from the front and back*" twisting: ``` my &t={ } # Lambda, assigned to a variable. .shift,.pop # Remove an element from the front an back, xx* # an infinite number of times, |( ) # and make sure this infinite list is flattened. [^$_] # Take as many elements as the input had elements. ``` This works because the `xx` operator is more like a macro than a function, in that it provides magic lazy evaluation. Then in the main lambda: ``` [$_] # Create a fresh array from the input, t # and twist it (destructively). map({ }, # For each element (i.e. word): t [.comb] # Split it into characters and twist them, | # and slip them into the outer list. .rotor($_».chars) # Partition this flat list of characters, $_».chars # using the original word lengths. ».join # Turn each sub-list into a word. ``` --- # [Perl 6](http://perl6.org/), 87 bytes ``` {my &t={(|(.shift,.pop)xx*)[^$_]} my @a=map {|t [.comb]},t [.words];S:g/\S/{@a.shift}/} ``` This is a variation of the above, which inputs and outputs a string – preserving different whitespace characters. [Answer] # [Haskell](https://www.haskell.org/), ~~115 95 93 98~~ 95 bytes ``` f(a:b)=a:f(reverse b) f e=e a!(y:z)|elem y" \t\n"=y:a!z|b:c<-a=b:c!z a!z=z (!)=<<(f=<<).f.words ``` Call with `(!)=<<(f=<<).f.words $ "some string"`. [Try it online!](https://tio.run/nexus/haskell#bY6xDoMgFEV3vuJhOsBi0nQjkvQjOro89NHaKljEWoj/bvmALme55ybnsAKVkRqVFYE@FBYCI5kF0sTwKozqJBdJZbnTSBOkCtrYukonhTzv5@aii8IzI27LQ3Cpm0bYAlnbevOhX44JBwcaBhcpYBfhBH@124PgvQ7dC0zwmwPrv/Bcp3lhvnRBLPOIOUHv7/UP "Haskell – TIO Nexus") Thanks to @nimi for pointing out that I misread the challenge earlier. The function `f` performs the twisting on a list, so it can be used on strings (list of chars) and a list of strings. `a!b` inserts the whitespace of string `b` into string `a`. `(!)=<<(f=<<).f.words` is equivalent to `\s0 -> (concatMap f . f . words $ s0) ! s0`: ``` s0 = "The quick brown fox jumps\nover the lazy dog." words s0 = ["The","quick","brown","fox","jumps","over","the","lazy","dog."] = s1 f s1 = ["The","dog.","quick","lazy","brown","the","fox","over","jumps"] = s2 concatMap f s2 = "Tehd.ogqkucilyazbnrwotehfxoorvejsupm" = s3 s3 ! s0 = "Teh d.ogq kucil yaz bnrwo\ntehf xoo rvej supm" ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` UΣSze↔mȯUΣSze↔ ``` [Try it online!](https://tio.run/##yygtzv7/P/Tc4uCq1EdtU3JPrIez////H61kaGRsYqqko2RmbgEkLZViAQ "Husk – Try It Online") This doesn't work with a reusable function since a function can only support one type of arguments. ]
[Question] [ > > **Note**: As per [consensus on Meta](http://meta.codegolf.stackexchange.com/questions/8897/should-questions-about-challenge-writing-be-on-topic/8906#8906), [challenge-writing](/questions/tagged/challenge-writing "show questions tagged 'challenge-writing'") questions are on topic here. > > > In light of [this "thing to avoid when writing challenges"](http://meta.codegolf.stackexchange.com/a/10909/32014), I started to think about challenges involving random generation of certain kinds of objects. It sometimes happens that I want to post a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge that involves randomly generating a foo, where 1. it's very easy to check whether a given thing is a foo, and 2. it's a little harder to quickly generate a "good-quality" random foo. As an example, a foo might be a binary matrix where there are no segments of 4 equal bits in any direction. It's easy to check whether a given binary matrix is a foo, but generating a random foo with a nicely spread distribution seems to require a backtracking algorithm or something similar. Anyway, now I'll need to objectively specify what qualifies as a random foo, and I'd like it to be "unpredictable" in the intuitive sense that when I run the program several times, the results always look different. The most restrictive approach is to require that the output is uniformly random: all valid foos have the same probability of being generated. This is usually too restrictive, because I have no idea how to do it save for generating all valid foos, removing duplicates and choosing one, which is boring and slow. My next idea is to require that all valid foos have a positive probability of being generated. However, this means that the following approach is valid: generate a random foo-like thing (in our example, a random binary matrix), if it's a foo then return it, otherwise return a hard-coded foo (say, the identity matrix). This is also somewhat boring, since it's basically just a recognizer of foos tacked to a random matrix generator. Could there be a nice general definition for an unpredictably random foo? ### TL;DR Is there a good way for specifying an "unpredictable" randomly generated object that doesn't fix the distribution but discourages hard-coding? [Answer] **Return a thousand different foos** This makes it impossible to return hardcoded values and have a half decent golf. However, a legit foo generator does have a small chance of outputting duplicate foos unless it is actually checking them. To remove the burden of checking, an empirically tested failure rate, say 10%, could be specified as acceptable. Be aware of the [birthday paradox](https://en.m.wikipedia.org/wiki/Birthday_problem), that the probability of duplicates may be higher than you think. If there are only a million possible foos, a thousand random foos will have a probability of about 0.6 that there is a duplicate in there somewhere, and that's assuming that foo generation is completely uniform. If this could be an issue, require say 900 unique foos for every 1000 generated, which is far more generous for a genuine foo generator but still impractical for hardcoding. This also allows you to repeatedly generate foo-like things and check fooness until you get foos. I think this is a valid solution myself, but if you don't like it: **Do it quickly** The chances of a completely random foo-like thing being foo are probably quite low, so specifying a time limit is likely to force a genuine attempt at foo generation. To accomodate the speed differences between different languages, you may want to have different time limits depending on the language like Hackerrank: <https://www.hackerrank.com/environment> . However if you specify large enough foos the probability of random foo-like things being foo might be really low, so a "before the heat death of the Universe" rule might be sufficient. [Answer] I don't claim to have the ultimate solution to the problem (or that this list is exhaustive), but I want to outline some possible approaches that come to mind and why they would or wouldn't work. I also won't address tangential issues like whether using the current timestamp as a source of randomness is sufficiently "unpredictable" and how to enforce certain properties of the probability distribution — I'll just focus on avoiding solutions that use hardcoding. ### Not a solution: disallow hard-coding explicitly This is a bad idea. It's a non-observable requirement (which means you can't determine whether it's satisfied just by running the program), [which is strongly discouraged on PPCG](http://meta.codegolf.stackexchange.com/a/10002/8478) and may be outright impossible if running the program on any other platform, where submissions are verified in an automated manner. The problem with a requirement like this is that you'd have to start by finding an objective definition for "hard-coding". In general, if you try this, you're only going to make things worse. ### Make hard-coding infeasible If you can't disallow it completely, but you don't want people to use it, then you can try to design the challenge such that hard-coding is simply not a competitive approach. This is possible if the objects that should be generated are sufficiently large and incompressible that putting one example into the code would require a lot more bytes than writing an algorithm that generates valid solutions randomly. In your specific example, that's not the case of course, because identity matrices are valid and are generally easy to generate, but for other problems, that might not be the case. If the target objects are sufficiently irregular, just require them to be of a large size, which probably won't affect the byte count of an actual algorithm but will blow up the hard-coded part. ### Parameterise the output Often, these problems come with one or more natural parameter, like the size of the matrix in your example. If so, making that parameter an input can be sufficient to make hard-coding impossible or at least impractical. In some cases, it might be easy to hard-code one specific solution for a given parameter value that has been found manually or via extensive search, but maybe there is no simple closed form for an instance of these solution in general, so it's not possible to generate a default value for arbitrary inputs easily. Again, this is not the case for the example you mention, because the identity matrix works at any size, but an optimal solution for [this related problem](https://math.stackexchange.com/questions/1548710/maximal-tiling-without-any-3-in-a-rows) is usually highly irregular, so it's not possible to have default value without actively searching for valid values anyway. You can combine this with a time-limit to avoid a brute force search for a default value. ### Put *some* restriction on the probability distribution If you're willing to give up a *completely* unrestricted probability distribution, you can put some constraints on it, that still give answerers a lot of freedom in choosing their distribution but which make hard-coding a difficult or impossible: * The simplest constraint that comes to mind is to require the difference between minimum and maximum probability for any possible output to be below a certain threshold. A hard-coded approach will likely have almost-zero probabilities for almost all outputs and a probability close to 1 for the default value. If you require the maximum difference to be below 0.1 say, there would need to be 10 (randomly chosen) default values to make the approach an option. Similarly you could also just require a minimum probability for each possible output, e.g. 1/(2\*N\*), where *N* is the number of possible outputs. * Alternatively, you can require that there are no (likelihood) gaps in the distribution, so that there is no interval of size *δ* (chosen by you) such that both higher and lower probabilities exist. That means there can't be any outliers in terms of likelihood, which are likely generated by a hard-coding approach. The main issue with these approaches is that they're a lot harder to reason about, proving correctness of answers is difficult, and experimentally verifying the correctness can be impossible for large output spaces. Still, they provide a principally observable requirement for the program which can make hardcoding impossible. These approaches may also need a time limit, because one way to increase the probability of the non-default values would be to attempt finding a random foo multiple times before falling back to the default value. ]
[Question] [ This is a challenge inspired by [Chebyshev Rotation](https://codegolf.stackexchange.com/questions/96410/chebyshev-rotation). I suggest looking at answers there to get inspiration for this challenge. Given a point on the plane there is a unique square (a rectangle with equal sides) that is centered on the origin and intersects that point ([interactive demo](https://www.geogebra.org/m/yJfYmnGb)): [![enter image description here](https://i.stack.imgur.com/5lCb9.png)](https://i.stack.imgur.com/5lCb9.png) Given a point **p** and a distance **d**, return the point obtained by moving distance **d** from **p**, counter-clockwise (and clockwise for negative **d**), along the perimeter of the square centered on the origin that intersects **p**. Your answer must be accurate to at least 4 decimal digits. ### Testcases: ``` (0, 0), 100 -> (0, 0) (1, 1), 81.42 -> (-0.4200, 1.0000) (42.234, 234.12), 2303.34 -> (-234.1200, 80.0940) (-23, -39.234), -234.3 -> (39.2340, -21.8960) ``` The following test cases are from the original challenge by Martin Ender, and all are with **d = 1**: ``` (0, 0) -> (0, 0) (1, 0) -> (1, 1) (1, 1) -> (0, 1) (0, 1) -> (-1, 1) (-1, 1) -> (-1, 0) (-1, 0) -> (-1, -1) (-1, -1) -> (0, -1) (0, -1) -> (1, -1) (1, -1) -> (1, 0) (95, -12) -> (95, -11) (127, 127) -> (126, 127) (-2, 101) -> (-3, 101) (-65, 65) -> (-65, 64) (-127, 42) -> (-127, 41) (-9, -9) -> (-8, -9) (126, -127) -> (127, -127) (105, -105) -> (105, -104) ``` [Answer] # Python 2, ~~363~~ ~~335~~ ~~296~~ ~~266~~ ~~262~~ ~~258~~ ~~256~~ 233 Bytes ***Woo, 130 bytes lost! Thanks to Neil for saving 4 bytes, Nathan Merrill for saving 2 bytes, and xnor for saving a ridiculous 23 bytes!*** The general idea is this: We can reduce the distance traveled by taking it's the modulus of it against the perimeter of the square. The perimeter is defined as 8 times the largest of the two coordinates, since the point must rest on it. Then, after modulus is taken we are guaranteed to have no overlap. It also guarantees we only ever have to move counter-clockwise, since modulus gives a positive result. From there, I simply use what we know from the given x and y-coordinates to figure out where we are: top, bottom, left, right, or in a corner, and determine the direction, which can be one of `0, 1, 2, 3`: ``` 0 --> we are on the 'top', moving 'left' 1 --> we are on the 'left', moving 'down' 2 --> we are on the 'bottom', moving 'right' 3 --> we are on the 'right', moving 'up' ``` After this, it is as simple as looping while we still have distance to travel, and based on the direction we subtract or add to the appropriate coordinate, and tell the loop which direction we are going next. ``` p,d=input() x,y=p s=max(x,y,-x,-y) d=d%(s*8or 1) r=[(y<s)*[2,[3,x>-s][x<s]][y>-s],[2*(y<0),3*(y<=0)][x>0]][y*y==x*x] while s>0<d:f=1-2*(r<2);m=abs(f*s-p[r%2]);j=d>m;p[r%2]=[p[r%2]+f*d,f*s][j];r=-~r%4;d=(d-m)*j print"%.4f "*2%tuple(p) ``` While quite long, it certainly works. Here's some example I/O: ``` [0, 0], 100 --> 0.0000 0.0000 [1, 1], 81.42 --> -0.4200 1.0000 [42.234, 234.12], 2303.34 --> -234.1200 80.0940 [-23, -39.234], -234.3 --> 39.2340 -21.8960 ``` **[Try it online](https://repl.it/DyXW/20)** or **[run test cases](https://repl.it/DyXW/19)**. [Answer] ## JavaScript (ES6), 147 bytes ``` f=(x,y,d,s=Math.max(x,y,-x,-y),c=(d/8%s+s)%s*8,v=0,w=x+y>0?1:-1,b=(v?x:y)*w+c-s)=>c?b>0?f(v?s*w:x,v?y:s*w,d,s,b,!v,v?w:-w):[x+c*w*v,y+c*w*!v]:[x,y] ``` Explanation: Works by trying to add the direction vector while keeping within the bounds of the square. Any overshoot is recursively passed back with the direction rotated anticlockwise by 90°. The direction is actually encoded using a vertical flag `v` and a unit `w` so that the vectors (1, 0), (0, 1), (-1, 0) and (0, -1) are encoded with `v` of 0, 1, 0, 1 and `w` of 1, 1, -1, -1 respectively. The direction vector may not initially point in a suitable direction but it never points backwards so it will eventually rotate into a usable direction. ``` f=(x,y,d, Input parameters s=Math.max(x,y,-x,-y), Calculate half the side of the square c=(d/8%s+s)%s*8, Reduce the distance modulo the perimeter v=0, Initial vertical flag w=x+y>0?1:-1, Initial direction b=(v?x:y)*w+c-s)=> Will we overshoot the corner? c?b>0?f(v?s*w:x,v?y:s*w, Advance to the next corner d,s,b,!v,v?w:-w): Rotate the direction [x+c*w*v,y+c*w*!v]: Advance the remaining amout [x,y] Nothing to do, zero input ``` ]
[Question] [ Take a 2D region of space divided into axis aligned unit square elements with their centers aligned at integer intervals. An edge is said to be internal if it is shared by two elements, otherwise it is an external edge. Your goal is to find the minimum number of neighboring elements which must be traversed to reach an exterior edge starting from the center of each element, known as the `traversal distance`, or `distance` for short. You may only traverse through an edge (i.e. no corner cutting/diagonal movement). Note that "exterior elements" (elements which have at least one external edge) are considered to need to traverse `0` neighboring elements to reach an exterior edge.. # Input The input is a list of non-negative integer pair coordinates denoting the (x,y) of the center of all elements. It is assumed there are no overlapping elements (i.e. an x/y pair uniquely identifies an element). You may **not** assume anything about the element input order. You are welcome to transform the origin of the input to any location (e.g. 0,0 or 1,1, etc.). You may assume that all input elements are connected, or in other words it is possible to travel from any one element to any other element using the rules above. Note that this does not mean that the 2D region is simply connected; it may have holes inside of it. Example: the following is an invalid input. ``` 0,0 2,0 ``` [![enter image description here](https://i.stack.imgur.com/CDTIN.png)](https://i.stack.imgur.com/CDTIN.png) error checking is not required. The input may be from any source (file, stdio, function parameter, etc.) # Output The output should be a list of coordinates identifying each element, and the corresponding integer distance traversed to get to an edge. The output may be in any element order desired (e.g. you need not output elements in the same order received as inputs). The output may be to any source (file, stdio, function return value, etc.) Any output which matches the coordinate of the element with it's exterior distance is fine, e.g. all of these are fine: ``` x,y: distance ... [((x,y), distance), ...] [(x,y,distance), ...] ``` # Examples Text example inputs are in the form `x,y`, with one element per line; you are welcome to reshape this into a convenient input format (see input format rules). Text example outputs are in the format `x,y: distance`, with one element per line; again, you are welcome to reshape this into a convenient ouput format (see output format rules). Graphical figures have the lower-left bound as (0,0), and the numbers inside represent the expected minimum distance traveled to reach an exterior edge. Note that these figures are purely for demonstration purposes only; your program does not need to output these. ## Example 1 **input:** ``` 1,0 3,0 0,1 1,2 1,1 2,1 4,3 3,1 2,2 2,3 3,2 3,3 ``` **Output:** ``` 1,0: 0 3,0: 0 0,1: 0 1,2: 0 1,1: 1 2,1: 0 4,3: 0 3,1: 0 2,2: 1 2,3: 0 3,2: 0 3,3: 0 ``` **graphical representation:** [![enter image description here](https://i.stack.imgur.com/2IAiu.png)](https://i.stack.imgur.com/2IAiu.png) ## Example 2 **input:** ``` 4,0 1,1 3,1 4,1 5,1 6,1 0,2 1,2 2,2 3,2 4,2 5,2 6,2 7,2 1,3 2,3 3,3 4,3 5,3 6,3 7,3 8,3 2,4 3,4 4,4 5,4 6,4 3,5 4,5 5,5 ``` **output:** ``` 4,0: 0 1,1: 0 3,1: 0 4,1: 1 5,1: 0 6,1: 0 0,2: 0 1,2: 1 2,2: 0 3,2: 1 4,2: 2 5,2: 1 6,2: 1 7,2: 0 1,3: 0 2,3: 1 3,3: 2 4,3: 2 5,3: 2 6,3: 1 7,3: 0 8,3: 0 2,4: 0 3,4: 1 4,4: 1 5,4: 1 6,4: 0 3,5: 0 4,5: 0 5,5: 0 ``` **graphical representation:** [![enter image description here](https://i.stack.imgur.com/oJcO7.png)](https://i.stack.imgur.com/oJcO7.png) ## Example 3 **input:** ``` 4,0 4,1 1,2 3,2 4,2 5,2 6,2 8,2 0,3 1,3 2,3 3,3 4,3 5,3 6,3 7,3 8,3 9,3 1,4 2,4 3,4 4,4 5,4 6,4 7,4 8,4 9,4 2,5 3,5 4,5 5,5 6,5 9,5 10,5 11,5 3,6 4,6 5,6 9,6 10,6 11,6 6,7 7,7 8,7 9,7 10,7 11,7 ``` **output:** ``` 4,0: 0 4,1: 0 1,2: 0 3,2: 0 4,2: 1 5,2: 0 6,2: 0 8,2: 0 0,3: 0 1,3: 1 2,3: 0 3,3: 1 4,3: 2 5,3: 1 6,3: 1 7,3: 0 8,3: 1 9,3: 0 1,4: 0 2,4: 1 3,4: 2 4,4: 2 5,4: 2 6,4: 1 7,4: 0 8,4: 0 9,4: 0 2,5: 0 3,5: 1 4,5: 1 5,5: 1 6,5: 0 9,5: 0 10,5: 0 11,5: 0 3,6: 0 4,6: 0 5,6: 0 9,6: 0 10,6: 1 11,6: 0 6,7: 0 7,7: 0 8,7: 0 9,7: 0 10,7: 0 11,7: 0 ``` **graphical representation:** [![enter image description here](https://i.stack.imgur.com/8c8iC.png)](https://i.stack.imgur.com/8c8iC.png) # Scoring This is code golf. Shortest code in bytes wins. Standard loopholes apply. Any built-ins other than those specifically designed to solve this problem are allowed. [Answer] # MATLAB/Octave, 143 bytes ``` function [v,x,y]=d(x,y)R=S=zeros(max(y+3),max(x+3));i=sub2ind(size(S),y+2,x+2);S(i)=1;while nnz(S=imerode(S,strel('disk',1,0)))R+=S;end;v=R(i); ``` ## Ungolfed ``` function [v,x,y]=d(x,y) R=S=zeros(max(y+3),max(x+3)); i=sub2ind(size(S),y+2,x+2); S(i)=1; while nnz(S=imerode(S,strel('disk',1,0))) R+=S; end; v=R(i); ``` ## Explanation Create **S**ource and **R**esult matrices of appropriate size, filled with zeros. ``` R=S=zeros(max(y+3),max(x+3)); ``` Calculate the linear indices that correspond to the `xy`-pairs, with one element padding at the borders. ``` i=sub2ind(size(S),y+2,x+2); ``` Draw the structure. ``` S(i)=1; ``` `S` is shown here for **Example 2**: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 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 ``` Remove all border elements by image erosion ``` S=imerode(S,strel('disk',1,0)) ``` using the structuring element *disk with radius 1*: ``` 0 1 0 1 1 1 0 1 0 ``` If diagonal movement was allowed, we would instead use the rectangle: ``` 1 1 1 1 1 1 1 1 1 ``` Then, increment the result for all non-border elements ``` R+=S; ``` and loop until the image is completely eroded. ``` while nnz(S) ``` Return the result for each `xy`-pair. ``` v=R(i); ``` [Answer] # Pyth, 26 bytes ``` V]MQNf>*4Nl=Nsmfq1.a,dYQN0 ``` [Example 2](https://pyth.herokuapp.com/?code=V%5DMQNf%3E%2a4Nl%3DNsmfq1.a%2CdYQN0&input=%5B%5B4%2C+0%5D%2C+%5B1%2C+1%5D%2C+%5B3%2C+1%5D%2C+%5B4%2C+1%5D%2C+%5B5%2C+1%5D%2C+%5B6%2C+1%5D%2C+%5B0%2C+2%5D%2C+%5B1%2C+2%5D%2C+%5B2%2C+2%5D%2C+%5B3%2C+2%5D%2C+%5B4%2C+2%5D%2C+%5B5%2C+2%5D%2C+%5B6%2C+2%5D%2C+%5B7%2C+2%5D%2C+%5B1%2C+3%5D%2C+%5B2%2C+3%5D%2C+%5B3%2C+3%5D%2C+%5B4%2C+3%5D%2C+%5B5%2C+3%5D%2C+%5B6%2C+3%5D%2C+%5B7%2C+3%5D%2C+%5B8%2C+3%5D%2C+%5B2%2C+4%5D%2C+%5B3%2C+4%5D%2C+%5B4%2C+4%5D%2C+%5B5%2C+4%5D%2C+%5B6%2C+4%5D%2C+%5B3%2C+5%5D%2C+%5B4%2C+5%5D%2C+%5B5%2C+5%5D%5D&debug=0) The output format I used is: ``` [[4, 3]] 2 ``` That is, a list containing the point, followed by the distance from the exterior. The code works by using a currently reached set, for each point filtering the input for all points exactly distance 1 away from that point, and checking whether the resultant number of points is 4 times as many as the starting number, and repeating until it's not. When started at a given point, this gives how far that point is from the exterior. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~38~~ ~~37~~ ~~36~~ 33 bytes ``` 1Z?t"tX@<~5Bt!Z~2X53$Y+4=+]3#fqhh ``` This uses [current version (15.0.0)](https://github.com/lmendo/MATL/releases/tag/15.0.0) of the language/compiler. Input format is: one array with *x* values and one array with *y* values. Input and output are 1-based. So the test cases have the following inputs: ``` [2 4 1 2 2 3 5 4 3 3 4 4] [1 1 2 3 2 2 4 2 3 4 3 4] [5 2 4 5 6 7 1 2 3 4 5 6 7 8 2 3 4 5 6 7 8 9 3 4 5 6 7 4 5 6] [1 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 6 6 6] [5 5 2 4 5 6 7 9 1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 3 4 5 6 7 10 11 12 4 5 6 10 11 12 7 8 9 10 11 12] [1 2 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 7 7 7 7 7 7 8 8 8 8 8 8] ``` [**Try it online!**](http://matl.tryitonline.net/#code=MVo_dCJ0WEA8fjVCdCFafjJYNTMkWSs0PStdMyNmcWho&input=WzUgMiA0IDUgNiA3IDEgMiAzIDQgNSA2IDcgOCAyIDMgNCA1IDYgNyA4IDkgMyA0IDUgNiA3IDQgNSA2XQpbMSAyIDIgMiAyIDIgMyAzIDMgMyAzIDMgMyAzIDQgNCA0IDQgNCA0IDQgNCA1IDUgNSA1IDUgNiA2IDZdCg) ### Explanation A matrix is initially built with 1 at the input positions and 0 otherwise. Then a convolution is applied with a "North, East, South, West" mask (`[0 1 0; 1 0 1; 0 1 0]`), and the result at each position is compared with 4. A result of 4 means that that position is surrounded by other points, and so has distance-to-exterior at least 1. The result (0 or 1 for each point) is added to the original matrix. Those positions now contain 2 (at the end of the process the matrix will be decremented by 1). The convolution process is iterated. For the next iteration, the input of the convolution is the accumulated matrix thresholded with 2; that is, values lower than 2 are set to 0. The result of the convolution indicates which points have distance at least 2 (all their neighbours have distance 1). The number of iterations is chosen, for convenience, as the number of columns of the input matrix. This is sufficient (in fact, the maximum required number of iterations is half the minimum matrix dimension). The last iterations may be useless, but do no harm (they do simply add 0 to all points). At the end of the process, 1 is subtracted from the result, because positions with value *k* have distance *k*-1 to the exterior. The coordinates and values of all positions is extracted and displayed. ``` % take x and y implicitly 1 % push 1 Z? % build sparse matrix from that x, y indices with 1 as value t % duplicate " % for each column of that matrix t % duplicate X@ % push iteration index <~ % true for matrix entries that are >= iteration index 5B % 5 in binary: row vector [1 0 1] t! % duplicate and transpose into a column vector Z~ % element-wise XOR with broadcast: gives desired mask, % [0 1 0; 1 0 1; 0 1 0] 2X53$Y+ % 2D convolution. Output has same size as input 4= % compare with 4: are all neighbouring positions occupied? + % add to accumulated matrix from previous iteration ] % end for each 3#f % extract row index, column index and value for nonzero % entries. In this case all entries are nonzero q % subtract 1 to value to yield distance to exterior hh % concatenate vertically twice % display implicitly ``` [Answer] # Python 3, ~~180~~ ~~166~~ 160 bytes ``` def f(l,d=0): l=set(l); if l:i={(a,b)for a,b in l if all([x in l for x in[(a+1,b),(a-1,b),(a,b+1),(a,b-1)]])};return{(c,d)for c in l-i}|f(i,d+1) return set() ``` We know that if a coordinate has less than four neighbours, it must be on the "exterior". Therefore, we can repeatedly strip the exterior cells and assign to them a distance equal the the number of iterations/depth of recursion in this case. Definitely think there's room for improvement - What's the best way of checking of adjacent neighbours? edit: I should be allowed to accept a list of pairs as tuples. [Answer] # PHP, 316 Bytes ``` <?preg_match_all("#^(\d+),(\d+)#m",$_GET[i],$t);foreach($t[1]as$k=>$v)$a[$v][$t[2][$k]]=0;function w($x,$y){global$a;return isset($a[$x][$y])?$a[$x][$y]:-1;};for(;$z++<max($t[2]);$o=$s,$s="")foreach($a as$x=>$b)foreach($b as$y=>$c)$s.="\n$x,$y: ".$a[$x][$y]=1+min(w($x+1,$y),w($x-1,$y),w($x,$y-1),w($x,$y+1));echo$o; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/1ce49634de502702f9ee56c17207a5e5f7a6a0bb) ## Breakdown ``` preg_match_all("#^(\d+),(\d+)#m",$_GET[i],$t); foreach($t[1]as$k=>$v) $a[$v][$t[2][$k]]=0; # make a 2 D array function w($x,$y){global$a;return isset($a[$x][$y])?$a[$x][$y]:-1;};# check the neighbours for(;$z++<max($t[2]);$o=$s,$s="") # stored the last loop string first run make possible to 1 and so on foreach($a as$x=>$b) # x values foreach($b as$y=>$c) # y values $s.="\n$x,$y: ".$a[$x][$y]=1+min(w($x+1,$y),w($x-1,$y),w($x,$y-1),w($x,$y+1)); # concanate array item x+y+value echo$o; #Output ``` ## Visualize as Ascii chars ``` ksort($a); foreach($a as$x=>$b){ for($y=0;$y<=max($t[2]);$y++) echo isset($a[$x][$y])?$a[$x][$y]:" "; #The better way would be make a SVG and use the text element and use a factor #echo '<text x="'.($x*$factor).'" y="'.($y*$factor).'">'.$a[$x][$y].'</text>'; echo"\n";} ``` ]
[Question] [ The [Alternating Harmonic Series](https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#Alternating_harmonic_series) is a well known convergent series. ![1/1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + ...](https://latex.codecogs.com/gif.latex?%5Cdpi%7B120%7D&space;%5Clarge&space;%5Cfrac%7B1%7D%7B1%7D-%5Cfrac%7B1%7D%7B2%7D+%5Cfrac%7B1%7D%7B3%7D-%5Cfrac%7B1%7D%7B4%7D+%5Cfrac%7B1%7D%7B5%7D-%5Cfrac%7B1%7D%7B6%7D+%5Ccdots) "Clearly", it is obvious that it converges to the natural log of 2. Or does it? Since the series is not [absolutely convergent](https://en.wikipedia.org/wiki/Absolute_convergence), by simply rearranging the terms, I can make it approach anything I want. Suppose I want the series to converge to [e](https://en.wikipedia.org/wiki/E_(mathematical_constant)). All I'd have to do is this: ![1/1 + 1/3 + ... + 1/65 - 1/2 + 1/67 + ... + 1/175 - 1/4](https://latex.codecogs.com/gif.latex?%5Cdpi%7B120%7D&space;%5Clarge&space;%5Cfrac%7B1%7D%7B1%7D+%5Cfrac%7B1%7D%7B3%7D+%5Ccdots+%5Cfrac%7B1%7D%7B65%7D-%5Cfrac%7B1%7D%7B2%7D+%5Cfrac%7B1%7D%7B67%7D+%5Ccdots+%5Cfrac%7B1%7D%7B175%7D-%5Cfrac%7B1%7D%7B4%7D+%5Ccdots) If you didn't catch the pattern, there isn't an obvious one. Here's how it works: 1. Consider the terms of the alternating harmonic series in terms of positive and negative terms. 2. Add together just enough positive terms to exceed our target (e). (aka `sum > target`) 3. Subtract the next negative term. 4. Go back to 2. Note that at step 2, if our `sum == target`, you should add another positive term. From this we can define a sequence associated with each number as follows: * Follow the algorithm above * For each positive term, output 1. * For each negative term, output 0. Let's call this sequence the "Harmonious Bit Pattern" of a number. For example, the HBP of e begins as: ``` 1, 1, 1, 1, <32 times>, 0, 1, 1, <54 times>, 0, 1, 1, ... ``` ## Your challenge: You will be given: * a rational input *target* in the range [-10, 10] (note: even reaching 10 via the harmonic series takes many millions of terms). This may be a decimal (aka `1.1`) or you may take a rational directly (aka `12/100`) * a positive `int` *n* input, specifying the number of terms of the Harmonious Bit Pattern to output. You are expected to output the exact Harmonious Bit Pattern of the *target* to the specified number of terms. You may output space separated values, comma separated, no separation, etc; just as long as the pattern of 0s and 1s is clearly visible and is read left to right with consistent separation. ## Test Cases ``` >>> 0, 1 1 >>> 0, 2 10 >>> 0, 7 1000010 >>> 1, 10 1101011011 >>> 1.01, 3 110 >>> 1.01, 24 110101101101101101101101 >>> 2.71, 32 11111111111111111111111111111111 >>> 2.71, 144 111111111111111111111111111111110111111111111111111111111111111111111111111111111111111101111111111111111111111111111111111111111111111111111111 >>> -9.8, 100 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ``` Note that since `-9.8` is so large, the first `1` that would be output is somewhere around the `149496620`th term (that was computed via floats, so the value might not be exact). [Answer] # Perl, 69 bytes ``` use bigrat;$s+=.5/($s>$ARGV[$_=0]?-++$n:++$p-++$_/2),print for 1..pop ``` Takes inputs as command line arguments. **Explanation**: `bigrat` enables fractions everywhere for accurate calculations. `$s` is the current sum of terms, `$ARGV[0]` is the target value, `pop` (same as `$ARGV[1]`) represents the number of terms, `$p` and `$n` represent the positive and negative term counts. `$_` is either `1` or `0` depending on whether a positive or negative term was added. [Answer] # Haskell, ~~92~~ ~~91~~ 90 bytes ``` import Data.Ratio f=(.h 0 1 2).take h a p q z|a>z=0:h(a-1%q)p(q+2)z|1<2=1:h(a+1%p)(p+2)q z ``` Usage example: `f 24 1.01` -> `[1,1,0,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1]`. `h` builds the infinite bit pattern by carrying four parameters around: `a` is the current sum. `p` is the denominator of the next positive term, `q` for negative terms. `z` is the target number. `f` starts everything up and truncates the result to length `n`. Edit: @Zgarb found a byte to save. Thanks! [Answer] # Python 3, ~~128~~ 124 bytes ``` from fractions import* F=Fraction *c,s=2,1,0 t=F(input()) for i in'x'*int(input()):w=s<=t;s+=F(w*2-1,c[w]);c[w]+=2;print(+w) ``` This makes use of Python's `Fraction` class. ``` from fractions import* F=Fraction *c,s=2,1,0 # c = [2, 1]. s = 0 # c is my positive/negative term counter, s is the sum t=F(input()) # input a fraction for i in'x'*int(input()): # Do this for for the chosen number of terms, as per the spec w=s<=t; # "w" or which one do we choose? Positive or negative? s+=F(w*2-1,c[w]); # w*2-1 gives 1 if w else -1. Gives 1 if we need to add, else -1 c[w]+=2; # Increment the coefficient we chose print(+w) # Output that. The +w coerces the bool to an int. ``` ]
[Question] [ Cluck cluck. No one knows why the chicken crossed the road, maybe there was a good looking rooster on the other side. But we can figure out how. Write a program, that, left to right, crosses this (or any) "road". ``` 1356 | 1738 3822 | 1424 3527 3718 9809 | 5926 0261 | 1947 7188 4717 6624 | 9836 4055 | 9164 2636 4927 5926 | 1964 3144 | 8254 ``` Your program "crosses" it, moving left to right. You start on any number on the leftmost column you like. From there, you can move to any adjacent character to the right. If you started at the top left corner, 1, you could go to either 3 or 8. Every number you go to, including the starting number, is added to a sum. Spaces do not add to your sum. "|" forces you to move up or down, rather than somewhere to the right. (You CAN'T move forward on this character) Your goal is to get to the other side with the smallest possible sum. Your program must print out the sum at the end, and it must be able to solve any road. Preferably, it could also have input for a road, but it's not required. Your program must print both the path and the sum. Fewest bytes of code wins. To clarify, you can move diagnally unless you are on a vertical bar. You can only move up and down when you are on a vertical bar. For a clearer specification of roads, it is basically a string of text (Or an array of columns or rows, should you prefer to think that way) that follows the rules of the characters, and there can't be anything BUT those characters in the road. There can be any number, a space, a bar ("|"), or a newline. If a road was paved by a drunk guy, as in ProgrammerDan's answer, it is still a valid road, and your program must be able to solve such a road. It is not considered a road if it is impossible to get to the other side (For example, there is no way out of a straight line of bars). Your program is not required to determine if a road is invalid. Key: Any number - adds the number to your sum, move forward. Space - Move forward, nothing is added to your sum. "|" - Move up or down, nothing is added to your sum. EDIT: An example solution, as suggested. I can't make a horribly big one, I can't get on an IDE to solve it for me ATM. Take this small road: ``` 9191 | 8282 1919 | 2727 5555 5555 ``` The solution would be a path of 1, 1, 1, 1, space, divider, divider, space, space, 2, 2, 2, 2 for a total of 12. EDIT #2: The solution to the first road on this question, as determined by Geobits and peoples programs, is 0,2,0,1, , , ,1,4,1,4 for a sum of 13. [Answer] # Java, 955 bytes Obviously not going to win any awards, being Java and all, but I love this problem and wanted to throw in my own entry. Features and limits: * Can support irregular roads (super drunk!) including variable widths, complex lines, etc. * Expects road to be input as parameters on execution; the ungolfed version also supports reading from stdin, but since input method wasn't specified the golfed version expects smallest! * Uses some dynamic programming technique I haven't used in, oh, 6 years or so to efficiently solve in O(n\*m) time, where n is rows and m is columns. + Solves from right to left, marking the best direction to take *from* the current index to the next index. + "lines" are handled by resolving their column, then addressing them if reachable on the next column over. They resolve by storing direction up or down, with the cost of the eventually reachable non-line. * Tracks, but doesn't print (in golf'd version) the *starting index* of the best solution. Ok, enough jibba jabba. Golfed version: ``` class C{public static void main(String[]a){int n=a.length,m=0,i=0,j=0,h=0,p=0,q=0,s=0,t=0,b=-1,c=2147483647,x=0,y=0;char[][]r=new char[n][];char u;for(String k:a){j=k.length();m=(j>m)?j:m;}for(String k:a)r[i++]=java.util.Arrays.copyOf(k.toCharArray(),m);int[][][]d=new int[n][m][2];for(j=m-1;j>=0;j--){for(i=0;i<n;i++){u=r[i][j];p=(u=='\0'||u==' '||u=='|'?0:u-'0');if(j==m-1)d[i][j][1]=p;else{if(u=='|')d[i][j][0]=-1;else{for(h=-1;h<2;h++){x=i+h;y=j+1;if(x>=0&&x<n){if(d[x][y][0]==-1){s=x-1;while(s>=0&&r[s][y]=='|')s--;t=x+1;while(t<n&&r[t][y]=='|')t++;if((s>=0&&t<n&&d[s][y][1]<d[t][y][1])||(s>=0&&t>=n)){t=d[s][y][1];s=4;}else{s=6;t=d[t][y][1];}d[x][y][0]=s;d[x][y][1]=t;}q=d[x][y][1]+p;if(d[i][j][0]==0||q<d[i][j][1]){d[i][j][0]=h+2;d[i][j][1]=q;}}}}}if(j==0&&(b<0||d[i][j][1]<c)){b=i;c=d[i][j][1];}}}String o="";i=b;j=0;while(j<m){u=r[i][j];if(u=='\0')j=m;else{o+=u+",";h=d[i][j][0]-2;if(h>1)i+=h-3;else{i+=h;j++;}}}System.out.println(o+"\b:"+c);}} ``` As per my habit, [github with the ungolfed code](https://github.com/ProgrammerDan/chicken-golf). Solution for "first" road: ``` $ java C "1356 | 1738" "3822 | 1424" "3527 3718" "9809 | 5926" "0261 | 1947" "7188 4717" "6624 | 9836" "4055 | 9164" "2636 4927" "5926 | 1964" "3144 | 8254" 0,2,0,1, , , ,1,4,1,4:13 ``` Second example: ``` $ java C "9191 | 8282" "1919 | 2727" "5555 5555" 1,1,1,1, ,|,|, , ,2,2,2,2:12 ``` Brian Tuck's sample: ``` $ java C "6417443208|153287613" "8540978161|726772300" "7294922506 263609552" "0341937695 498453099" "9417989188 370992778" "2952186385|750207767" "7049868670 756968872" "1961508589|379453595" "0670474005 070712970" "4817414691|670379248" "0297779413|980515509" "6637598208 090265179" "6872950638 767270459" "7375626432 439957105" "1387683792|544956696" "6974831376 545603884" "0949220671|632555651" "3952970630|379291361" "0456363431|275612955" "2973230054|830527885" "5328382365|989887310" "4034587060 614168216" "4487052014|969272974" "5015479667 744253705" "5756698090|621187161" "9444814561|169429694" "7697999461|477558331" "3822442188 206942845" "2787118311|141642208" "2669534759 308252645" "6121516963|554616321" "5509428225|681372307" "6619817314|310054531" "1759758306 453053985" "9356970729|868811209" "4208830142 806643228" "0898841529|102183632" "9692682718|103744380" "5839709581|790845206" "7264919369|982096148" 2,1,0,1,5,1,2,1,1,1, ,1,0,1,2,1,2,3,0,1:26 ``` "Drunkified" Brian's example: ``` 6417443208|153287613 8540978161|726772300 7294922506 263609552 0341937695 498453099 9417989188 370992778 2952186385|750207767 7049868670 756968872 1961508589|379453595 0670474005 070712970 4817414691|670379248 0297779413|980515509 6637598208 090265179 6872950638 767270459 7375626432 439957105 1387683792|544956 697483176 5456034 09492201|6325551 395297030|3792913 456363431|275612 73230054|830527885 8382365|989887310 4587060 614168216 87052014|96927297 50479667 7442537 57566980 | 621187161 944481456 | 169429694 7697999461|477558331 3822442188 206942845 2787118311|141642208 2669534759 308252645 6121516963|554616321 5509428225|681372307 6619817314|310054531 1759758306 453053985 9356970729|868811209 4208830142 806643228 0898841529|102183632 9692682718|103744380 5839709581|790845206 7264919369|982096148 ``` ``` $ java C "6417443208|153287613" "8540978161|726772300" "7294922506 263609552" "0341937695 498453099" "9417989188 370992778" "2952186385|750207767" "7049868670 756968872" "1961508589|379453595" "0670474005 070712970" "4817414691|670379248" "0297779413|980515509" "6637598208 090265179" "6872950638 767270459" "7375626432 439957105" "1387683792|544956" "697483176 5456034" "09492201|6325551" "395297030|3792913" " 456363431|275612" " 73230054|830527885" " 8382365|989887310" " 4587060 614168216" " 87052014|96927297" " 50479667 7442537" "57566980 | 621187161" "944481456 | 169429694" "7697999461|477558331" "3822442188 206942845" "2787118311|141642208" "2669534759 308252645" "6121516963|554616321" "5509428225|681372307" "6619817314|310054531" "1759758306 453053985" "9356970729|868811209" "4208830142 806643228" "0898841529|102183632" "9692682718|103744380" "5839709581|790845206" "7264919369|982096148" , , , ,0,5,2,0,1, , , ,1,1,1,3,2:16 ``` Solution visualized: ``` 09492201|6325551 395297030|3792913 \456363431|275612 \73230054|830527885 \ 8382365|989887310 \4\87060 614168216 87/5--\4|96927\97 50479667\74425/7 57566980 |\62-/87161 944481456 |\/69429694 7697999461|477558331 ``` Enjoy! Edit: Now I'm just showing off (two roadways merge! Can he make it?) ``` 948384 | 4288324 324324 | 121323 120390 | 1232133 598732 | 123844 293009 | 2394023 432099 | 230943 234882 | 2340909 843893 | 849728 238984 | 328498984328 | 230949 509093 | 904389823787 | 439898 438989 | 3489889344 | 438984 989789 | 7568945968 | 989455 568956 | 56985869 | 568956 988596 | 98569887 | 769865 769879 | 769078 | 678977 679856 | 568967 | 658957 988798 | 8776 | 987979 987878 | 9899 | 989899 999889 | | 989899 989999 | | 989999 989898 | | 998999 989999 | | 999999 989998 || 899999 989998 || 998999 ``` Solution: ``` $ java C "948384 | 4288324 324324 | 121323" "120390 | 1232133 598732 | 123844" " 293009 | 2394023 432099 | 230943" " 234882 | 2340909 843893 | 849728" " 238984 | 328498984328 | 230949" " 509093 | 904389823787 | 439898" " 438989 | 3489889344 | 438984" " 989789 | 7568945968 | 989455" " 568956 | 56985869 | 568956" " 988596 | 98569887 | 769865" " 769879 | 769078 | 678977" " 679856 | 568967 | 658957" " 988798 | 8776 | 987979" " 987878 | 9899 | 989899" " 999889 | | 989899" " 989999 | | 989999" " 989898 | | 998999" " 989999 | | 999999" " 989998 || 899999" " 989998 || 998999" ,2,0,3,0,0, ,|,|, ,|,|, ,|,|, ,|,|, ,|,|, ,|,|, ,|,|, , , , , , , ,|, ,|, ,|, ,|, ,|, ,|, ,|,|, , ,1,0,7,2:15 ``` (bonus: path from ungolfed): ``` $ java Chicken < test5.txt best start: 3 cost: 15 -> 2 -> 0 -> 3 -> 0 -> 0 -> -> | -> | -> -> | -> | -> -> | -> | -> -> | -> | -> -> | -> | -> -> | -> | -> -> | -> | -> -> -> -> -> -> -> -> | -> -> | -> -> | -> -> | -> -> | -> -> | -> -> | -> | -> -> -> 1 -> 0 -> 7 -> 2 -> 15 / -> - -> - -> \ -> / -> / -> - -> , -> , -> - -> , -> , -> - -> , -> , -> - -> , -> , -> - -> , -> , -> - -> , -> , -> - -> , -> , -> / -> \ -> - -> - -> - -> / -> / -> ^ -> / -> ^ -> / -> ^ -> / -> ^ -> / -> ^ -> / -> ^ -> / -> , -> , -> / -> - -> \ -> \ -> - -> \ -> across ``` ## Details on Algorithm A more complete explanation of the Dynamic Programming technique I employed was requested, so here goes: I'm using a mark-and-precompute method of solution. It has a proper name, but I've long since forgotten it; perhaps someone else can offer it? ### Algorithm: * Starting at the right-most column and progressing to the left, compute the following about each cell in the column: + The summation of lowest cost movement, defined as *current cell cost* + *lowest cost cell reachable in the next column* + The movement action to take to achieve this lowest cost, as simply a valid move from this cell to another single cell. * Pipes are deferred. To resolve a pipe, you need to have the full column computed, so we don't compute pipes until the next column. + When determining the lowest cost of a cell to the left of a pipe, we first compute the best direction to travel along the pipe -- it will always resolve to either up, or down, so we compute it once. + We then store, as with all other cells, the best cost (defined as the cost of the cell we reach by travelling either up or down on the pipe) and the direction to travel to reach it. ### Notes: That's it. We scan from top to bottom, right to left, once; the only cells touched (potentially) more then once are pipes, however, each pipe is only "solved" once, keeping us within our O(m\*n) window. To handle "odd" map sizes, I chose to simply pre-scan and normalize lengths of rows by padding with null characters. Null characters count as "zero cost" moves same as pipes and spaces. Then, in printing the solution, I stop printing costs or moves when either the edge of the normalized road is reached, or a null character is reached. The beauty of this algorithm is it's very simple, applies the same rules to every cell, producing a full solution by solving O(m\*n) sub-problems, and in terms of speed is rather fast. It does trade off memory, creating effectively two copies in memory of the roadway map, the first to store "best cost" data and the second to store "best move" data per cell; this is typical for dynamic programming. [Answer] # Pyth, ~~168~~ ~~143~~ 141 bytes [now Drunken Road compatible] ~~My test case works, but because of a misunderstanding on my part, it won't work properly with the initial example. I'm working on fixing it.~~ Now working for original example and drunken roads Some ~~REALLY~~ ~~slightly less ugly~~ code: ``` =Z.dC,++\ `MUT\|++0UT=^T5Ltu+G]?&qeeG\|<heGhH+eGeHHtb,0hbKhohNum++hed@ZhhdtedC,H_y_y.b+N]YmhohNd.:++TGT3HCm.[d\ lh.MlZ.z.z*hl.z]]0j\,t.sK\ hK ``` [Test it Here](https://pyth.herokuapp.com/?code=%3DZ.dC%2C%2B%2B%5C+%60MUT%5C|%2B%2B0UT%3D%5ET5Ltu%2BG]%3F%26qeeG%5C|%3CheGhH%2BeGeHHtb%2C0hbKhohNum%2B%2Bhed%40ZhhdtedC%2CH_y_y.b%2BN]YmhohNd.%3A%2B%2BTGT3HCm.[d%5C+lh.MlZ.z.z*hl.z]]0j%5C%2Ct.sK%5C+hK&input=6417443208|153287613%0A8540978161|726772300%0A7294922506+263609552%0A0341937695+498453099%0A9417989188+370992778%0A2952186385|750207767%0A7049868670+756968872%0A1961508589|379453595%0A0670474005+070712970%0A4817414691|670379248%0A0297779413|980515509%0A6637598208+090265179%0A6872950638+767270459%0A7375626432+439957105%0A1387683792|544956%0A697483176+5456034%0A09492201|6325551%0A395297030|3792913%0A+456363431|275612%0A++73230054|830527885%0A++++8382365|989887310%0A++++4587060+614168216%0A++87052014|96927297%0A+50479667+7442537%0A57566980+|+621187161%0A944481456+|+169429694%0A7697999461|477558331%0A3822442188+206942845%0A2787118311|141642208%0A2669534759+308252645%0A6121516963|554616321%0A5509428225|681372307%0A6619817314|310054531%0A1759758306+453053985%0A9356970729|868811209%0A4208830142+806643228%0A0898841529|102183632%0A9692682718|103744380%0A5839709581|790845206%0A7264919369|982096148&test_suite_input=1%0A2%0A15%0A77%0A12345678929&debug=0) I tested it on a 10+9 x 40 road. ``` 6417443208|153287613 8540978161|726772300 7294922506 263609552 0341937695 498453099 9417989188 370992778 2952186385|750207767 7049868670 756968872 1961508589|379453595 0670474005 070712970 4817414691|670379248 0297779413|980515509 6637598208 090265179 6872950638 767270459 7375626432 439957105 1387683792|544956696 6974831376 545603884 0949220671|632555651 3952970630|379291361 0456363431|275612955 2973230054|830527885 5328382365|989887310 4034587060 614168216 4487052014|969272974 5015479667 744253705 5756698090|621187161 9444814561|169429694 7697999461|477558331 3822442188 206942845 2787118311|141642208 2669534759 308252645 6121516963|554616321 5509428225|681372307 6619817314|310054531 1759758306 453053985 9356970729|868811209 4208830142 806643228 0898841529|102183632 9692682718|103744380 5839709581|790845206 7264919369|982096148 ``` ]
[Question] [ *I want to try a new form of code golf here. Similar to bonuses, not all parts of the challenge have to be completed, but each answer has to implement a subset of certain size (and there is a core that every answer has to implement). So besides the golfing this challenge also involves choosing a set of features that go well together.* ## The Rules [Kingdom Builder](http://en.wikipedia.org/wiki/Kingdom_Builder) is a board game, played on a (pointy-top) hex grid. The board is made up of four (randomised) quadrants, each of which has 10x10 hex cells (so a full board will be 20x20). For the purposes of this challenge, each hex cell contains either water (`W`), mountain (`M`) a town (`T`), a castle (`C`) or is empty (`.`). So a quadrant could look like ``` . . W . . . . . . . . M W W . . . . . . . M . . W . . . T . M M . W . . . . . . . . M . W W . . . . . . . . . W W W W W . T . . . . . . . . . . W . . C . . . . . . W W . . . . M . . . . . . . . M M . ``` The second row will always be offset to the right from the first row. Players `1` to `4` can place up to 40 settlements each on empty cells (following some rules which we will ignore for this challenge). A possible board at the end of the game is the following: ``` 3 3 W . . . 4 . 4 . . 2 W . 4 . . 4 . 4 3 M W W . 1 1 . . 4 2 W . 3 C 4 4 . . 4 3 M 2 2 W 1 1 1 T 3 2 W 4 3 . 1 4 . 4 . M M . W 2 2 . . . 2 2 W 3 . 1 1 1 . . . . 4 M . W W 2 2 2 2 W W 3 . 1 4 . T . . . . . . . W W W W W . 3 C 1 . . 2 2 2 2 . T 1 1 1 1 . . 2 . . 4 . . . 2 2 M M M 4 . W 4 . C 4 4 . . . . . . 2 M M M M M . 4 W W . . . 4 M . . W . W . 2 2 2 M M . . . . . . . M M . . W W . . . . 2 M . . . . 3 3 3 3 3 3 3 3 3 3 3 3 3 3 2 . 1 M 3 3 . . . . . . . . 4 . T 2 . 2 4 1 . M M . C . 4 . 4 . . . . . 1 2 4 2 1 1 . M . . 1 . 4 . . . . M M 1 2 . . 2 1 . . . . . W 1 1 4 1 1 . . . 1 2 . . 2 W W W . . 1 1 W 1 T . 1 1 1 1 T . . 2 W . 4 . . 1 1 W . 3 3 . . . . . . . . 2 W 4 C 3 C 1 3 3 3 . 3 . 4 . 4 . 4 . . 2 W 1 1 M 4 3 3 4 . M 4 3 . . . . . . . 2 W . . . . . . 4 . M M 3 . . 4 4 . 4 . 2 W W . . ``` We'll label the quadrants like ``` 1 2 3 4 ``` Your task will be to score such a board. There is one core score which is always used, and 8 optional scores, **3** of which are chosen for each game.† In the following, I'll describe all 9 scores and use the above setup as an example for how many points each player would get. † There are 10 scores in the actual game, but I'll leave out two because no one wants to golf them. **The core score.** A player gets **3 points** for each `C`astle they have a settlement next to. *Example scores:* 18, 0, 15, 12. **The optional scores.** 1. A player gets **1 point** for each horizontal row on which they have at least one settlement. *Example scores:* 14, 20, 12, 16. 2. For each player, find the horizontal row on which they most of their settlements (pick any in case of a tie). A player gets **2 points** for each settlement on that row. *Example scores:* 14 (row 16), 8 (row 4, 5 or 6), 28 (row 11), 10 (row 1). 3. A player gets **1 point** for each settlement that is build next to `W`ater. *Example scores:* 13, 21, 10, 5. 4. A player gets **1 point** for each settlement next to a `M`ountain. *Example scores:* 4, 12, 8, 4. 5. Count the settlements of each player in each quadrant. Per quadrant, the players with the largest number of settlements get **12 points** each, the players with the second-largest number of settlements get **6 points** each. *Example scores:* 18 (6 + 0 + 6 + 6), 36 (12 + 12 + 0 + 12), 12 (0 + 0 + 12 + 0), 18 (12 + 6 + 0 + 0). 6. For each player determine the quadrant in which they have the least number of settlements. A player gets **3 points** for each settlement in that quadrant. *Example scores:* 18 (Quadrant 2), 0 (Quadrant 3), 15 (Quadrant 1 or 2), 27 (Quadrant 3). 7. A player gets **1 point** for each connected group of settlements. *Example scores:* 7, 5, 6, 29. 8. A player gets **1 point** for every *2* settlements in the player's largest group of connected settlements. *Example scores:* 4, 10, 8, 2. ## The Challenge As in the game *you* will choose **3** of the optional scores, and score a given board based on the core score and those three scores. Your code should produce a list of 4 scores. There is one restriction on the choice though: I have grouped the scores into 3 groups, and you are to implement one of each group: * Implement one of **1 and 2**. * Implement one of **3, 4, 5 and 6**. * Implement one of **7 and 8**. You may write a program or function, taking input via STDIN, command-line argument, prompt or function parameter. You may return the result or print it to STDOUT. You may choose any convenient 1D or 2D list/string format for the input. You may *not* use a graph with full adjacency information. [Here is some good reading on hex grids](http://www.redblobgames.com/grids/hexagons/#map-storage) if you need inspiration. Your output may also be in any convenient, unambiguous list or string format. This is code golf, so the shortest answer (in bytes) wins. ## Further Assumptions You may assume that ... * ... each player has at least 1 settlement and there are no more than 40 settlements of each player. * ... each quadrant contains either one town and two castles, or two towns and one castle. * ... towns and castles are far enough apart, such that no settlement can be adjacent to two of them. ## Test Cases Still using the above board, here are the individual scores for all possible choices of scoring mechanisms: ``` Chosen Scores Total Player Scores 1 3 7 52 46 43 62 1 3 8 49 51 45 35 1 4 7 43 37 41 61 1 4 8 40 42 43 34 1 5 7 57 61 45 75 1 5 8 54 66 47 48 1 6 7 57 25 48 84 1 6 8 54 30 50 57 2 3 7 52 34 59 56 2 3 8 49 39 61 29 2 4 7 43 25 57 55 2 4 8 40 30 59 28 2 5 7 57 49 61 69 2 5 8 54 54 63 42 2 6 7 57 13 64 78 2 6 8 54 18 66 51 ``` [Answer] # Python 2, 367 bytes ``` T=range(20) N=lambda r,c:{(a,b)for a,b in{(r+x/3-1,c+x%3-1+(x/3!=1)*r%2)for x in[0,1,3,5,6,7]}if-1<b<20>a>-1} def S(B): def F(r,c):j=J[r][c]!=i;J[r][c]*=j;j or map(F,*zip(*N(r,c)));return j J=map(list,B);X=lambda r,c,x,y:x+y in{B[r][c]+B[a][b]for a,b in N(r,c)};return[sum((i in B[r])+20*(3*X(r,c,"C",i)-~X(r,c,i,"W")-F(r,c))for r in T for c in T)/20for i in"1234"] ``` The program uses scores 1, 3, 7. Input is a list of lists of chars representing each cell. To test the example board easily, we can do: ``` board = """ 3 3 W . . . 4 . 4 . . 2 W . 4 . . 4 . 4 3 M W W . 1 1 . . 4 2 W . 3 C 4 4 . . 4 3 M 2 2 W 1 1 1 T 3 2 W 4 3 . 1 4 . 4 . M M . W 2 2 . . . 2 2 W 3 . 1 1 1 . . . . 4 M . W W 2 2 2 2 W W 3 . 1 4 . T . . . . . . . W W W W W . 3 C 1 . . 2 2 2 2 . T 1 1 1 1 . . 2 . . 4 . . . 2 2 M M M 4 . W 4 . C 4 4 . . . . . . 2 M M M M M . 4 W W . . . 4 M . . W . W . 2 2 2 M M . . . . . . . M M . . W W . . . . 2 M . . . . 3 3 3 3 3 3 3 3 3 3 3 3 3 3 2 . 1 M 3 3 . . . . . . . . 4 . T 2 . 2 4 1 . M M . C . 4 . 4 . . . . . 1 2 4 2 1 1 . M . . 1 . 4 . . . . M M 1 2 . . 2 1 . . . . . W 1 1 4 1 1 . . . 1 2 . . 2 W W W . . 1 1 W 1 T . 1 1 1 1 T . . 2 W . 4 . . 1 1 W . 3 3 . . . . . . . . 2 W 4 C 3 C 1 3 3 3 . 3 . 4 . 4 . 4 . . 2 W 1 1 M 4 3 3 4 . M 4 3 . . . . . . . 2 W . . . . . . 4 . M M 3 . . 4 4 . 4 . 2 W W . . """ board = [row.split() for row in board.strip().split("\n")] print S(board) # [52, 46, 43, 62] ``` --- ## Handling the hex grid Since we are on a hex grid, we have to deal with neighbours a little differently. If we use a traditional 2D grid as our representation, then for `(1, 1)` we have: ``` . N N . . . N N . . (0, 1), (0, 2) (-1, 0), (-1, 1) N X N . . -> N X N . . -> Neighbours (1, 0), (1, 2) -> Offsets (0, -1), (0, 1) . N N . . . N N . . (2, 1), (2, 2) (1, 0), (1, 1) ``` On closer inspection, we realise that the offsets depend on the parity of the row you're on. The above example is for odd rows, but on even rows the offsets are ``` (-1, -1), (-1, 0), (0, -1), (0, 1), (1, -1), (1, 0) ``` The only thing that has changed is that the 1st, 2nd, 5th and 6th pairs have had their second coordinate decremented by 1. The lambda function `N` takes a coordinate pair `(row, col)` and returns all neighbours of the cell within the grid. The inner comprehension generates the above offsets by extracting them from a simple base 3 encoding, incrementing the second coordinate if the row is odd and adds the offsets to the cell in question to give the neighbours. The outer comprehension then filters, leaving just the neighbours that are within the bounds of the grid. ## Ungolfed ``` def neighbours(row, col): neighbour_set = set() for dr, dc in {(-1,-1), (-1,0), (0,-1), (0,1), (1,-1), (1,0)}: neighbour_set.add((row + dr, col + dc + (1 if dr != 0 and row%2 == 1 else 0))) return {(r,c) for r,c in neighbour_set if 20>r>-1 and 20>c>-1} def solve(board): def flood_fill(char, row, col): # Logic negated in golfed code to save a few bytes is_char = (dummy[row][col] == char) dummy[row][col] = "" if is_char else dummy[row][col] if is_char: for neighbour in neighbours(row, col): flood_fill(char, *neighbour) return is_char def neighbour_check(row, col, char1, char2): return board[row][col] == char1 and char2 in {board[r][c] for r,c in neighbours(row, col)} dummy = [row[:] for row in board] # Need to deep copy for the flood fill scores = [0]*4 for i,char in enumerate("1234"): for row in range(20): for col in range(20): scores[i] += (char in board[row]) # Score 1 scores[i] += 20 * 3*neighbour_check(row, col, "C", char) # Core score scores[i] += 20 * neighbour_check(row, col, char, "W") # Score 3 scores[i] += 20 * flood_fill(char, row, col) # Score 7 # Overcounted everything 20 times, divide out scores[i] /= 20 return scores ``` [Answer] # Answer Set Programming, 629 bytes ``` d(X,Y):-b(X,Y,_).p(1;2;3;4).n(X,Y,(((X-2;X+2),Y);((X-1;X+1),(Y-1;Y+1)))):-d(X,Y).n(X,Y,I,J):-n(X,Y,(I,J));d(I,J).t(X,Y,P):-n(X,Y,I,J);b(I,J,P).s(c,P,S*3):-S={t(X,Y,P):b(X,Y,"C")};p(P).s(1,P,S*1):-S=#count{r(Y):b(_,Y,P)};p(P).s(3,P,S):-S={b(X,Y,P):t(X,Y,"W")};p(P).o(X,Y,Y+X*100):-d(X,Y).h(P,X,Y,I,J):-o(X,Y,O);o(I,J,Q);O<Q;n(X,Y,I,J);b(X,Y,P);b(I,J,P);p(P).h(P,X,Y,I,J):-o(X,Y,O);o(I,J,Q);O<Q;h(P,X,Y,K,L);n(K,L,I,J);b(I,J,P);p(P).c(P,X,Y):-h(P,X,Y,_,_);not h(P,_,_,X,Y).c(P,X,Y):-{h(P,X,Y,_,_);h(P,_,_,X,Y)}0;b(X,Y,P);p(P).s(7,P,S):-S=#count{c(P,X,Y):c(P,X,Y)};p(P).s(t,P,C+S+T+U):-s(c,P,C);s(1,P,S);s(3,P,T);s(7,P,U).#shows/3. ``` ASP belongs to the logic programming language family, here incarnated by the [Potassco framework](http://potassco.sourceforge.net/), in particular Clingo(grounder Gringo + solver Clasp). Because of the paradigm limitation, it can't take given board directly as an output, so a preprocessing of the data is necessary (here performed in python). This preprocessing in not counted in the total byte score. Its my first code golf, and the objective is more to show a language i love that i never seen before in golf, than really win the game. Moreover, i'm far from an expert in ASP, so many optimizations of the code can certainly be perform for results in less bytes. ## knowledge representation There is the python code that convert board in atoms : ``` def asp_str(v): return ('"' + str(v) + '"') if v not in '1234' else str(v) with open('board.txt') as fd, open('board.lp', 'w') as fo: [fo.write('b('+ str(x) +','+ str(y) +','+ asp_str(v) +').\n') for y, line in enumerate(fd) for x, v in enumerate(line) if v not in ' .\n' ] ``` For example, atoms b (for \_\_b\_\_oard) given for the first line of example board are the followings : ``` b(0,0,3). b(2,0,3). b(4,0,"W"). b(12,0,4). b(16,0,4). b(22,0,2). b(24,0,"W"). b(28,0,4). b(34,0,4). b(38,0,4). ``` Where b(0,0,3) is an atom that describes that player 3 has a settlement at coordinates (0;0). ## ASP solving There is the ASP code, with many optional scores implemented : ``` % input : b(X,Y,V) with X,Y the coordinates of the V value domain(X,Y):- b(X,Y,_). player("1";"2";"3";"4"). % neighbors of X,Y neighbors(X,Y,((X-2,Y);(X+2,Y);((X-1;X+1),(Y-1;Y+1)))) :- domain(X,Y). neighbors(X,Y,I,J):- neighbors(X,Y,(I,J)) ; domain(I,J). % Player is next to X,Y iff has a settlement next to. next(X,Y,P):- neighbors(X,Y,I,J) ; b(I,J,P). % SCORES % Core score : 3 point for each Castle "C" with at least one settlement next to. score(core,P,S*3):- S={next(X,Y,P): b(X,Y,"C")} ; player(P). % opt1: 1 point per settled row score(opt1,P,S*1):- S=#count{row(Y): b(_,Y,P)} ; player(P). % opt2: 2 point per settlement on the most self-populated row % first, defines how many settlements have a player on each row rowcount(P,Y,H):- H=#count{col(X): b(X,Y,P)} ; domain(_,Y) ; player(P). score(opt2,P,S*2):- S=#max{T: rowcount(P,Y,T)} ; player(P). % opt3: 1 point for each settlements next to a Water "W". score(opt3,P,S):- S={b(X,Y,P): next(X,Y,"W")} ; player(P). % opt4: 1 point for each settlements next to a Mountain "M". score(opt4,P,S):- S={b(X,Y,P): next(X,Y,"M")} ; player(P). % opt5: %later… % opt6: %later… % opt7: 1 point for each connected component of settlement % first we need each coord X,Y to be orderable. % then is defined path/5, that is true iff exists a connected component of settlement of player P % that links X,Y to I,J % then is defined the connected component atom that give the smaller coords in each connected component % then computing the score. order(X,Y,Y+X*100):- domain(X,Y). path(P,X,Y,I,J):- order(X,Y,O1) ; order(I,J,O2) ; O1<O2 ; % order neighbors(X,Y,I,J) ; b(X,Y,P) ; b(I,J,P) ; player(P). % path iff next to path(P,X,Y,I,J):- order(X,Y,O1) ; order(I,J,O2) ; O1<O2 ; % order path(P,X,Y,K,L) ; neighbors(K,L,I,J) ; % path if path to next to b(I,J,P) ; player(P). concomp(P,X,Y):- path(P,X,Y,_,_) ; not path(P,_,_,X,Y). % at least two settlements in the connected component concomp(P,X,Y):- 0 { path(P,X,Y,_,_) ; path(P,_,_,X,Y) } 0 ; board(X,Y,P) ; player(P). % concomp of only one settlements score(opt7,P,S):- S=#count{concomp(P,X,Y): concomp(P,X,Y)} ; player(P). % opt8: 0.5 point for each settlement in the bigger connected component %later… % total score: score(total,P,C+S1+S2+S3):- score(core,P,C) ; score(opt1,P,S1) ; score(opt3,P,S2) ; score(opt7,P,S3). #show. # show nothing but the others show statements #show total_score(P,S): score(total,P,S). %#show score/3. % scores details ``` This program can be launched with the command: ``` clingo board.lp golf.lp ``` And will find only one solution (its a proof that there is only one way to distribute the points): ``` s(c,1,18) s(c,2,0) s(c,3,15) s(c,4,12) s(1,1,14) s(1,2,20) s(1,3,12) s(1,4,16) s(3,1,13) s(3,2,21) s(3,3,10) s(3,4,5) s(7,1,7) s(7,2,5) s(7,3,6) s(7,4,29) s(t,1,52) s(t,2,46) s(t,3,43) s(t,4,62) ``` Where s(7,3,6) says that player 3 gains 6 points with optional score 7, and s(t,4,62) says that player 4 gains 62 points in total (core + 1 + 3 + 7). Easy to parse to have a fancy table ! ]
[Question] [ You are given a board position for a [Go game](http://en.wikipedia.org/wiki/Go_%28game%29) and a move to play. You need to output whether the move is legal or not, and the new board position if it is legal. A brief explanation of Go moves: the game consists of alternatively placing black and white pieces ("stones") in empty places on a square board. Sets of pieces of the same color that are connected to each other (4-way) are called groups. Empty places on the board that are adjacent to a group (also 4-way) are considered to be that group's "liberties". A group with 0 liberties is captured (removed from the board). A move that would cause its own group to be captured ("suicide") is illegal, unless it is capturing one or more opponent's groups (gaining liberties in the process so it is not actually captured). For those concerned, you don't need to deal with ko (and superko), i.e. you can assume a ko capture is legal. If you don't know what that means, just follow the rules above and it will be fine. **Input:** a number n between 2 and 19 (inclusive) representing the board size, followed by n lines of n numbers between 0 and 2 (inclusive) representing the board position, followed by 3 numbers separated by space, representing the move to make. In the board position, 0 means empty place, 1 means black stone and 2 means white stone. The move gives the column, the row and the color (1 or 2) of the stone to place. The column and row are 0-based, ranging from 0 to n-1 (inclusive) and counted in the same order as the board input. You can assume that the given board position is legal (all groups have at least one liberty). **Output:** a line containing 1 or 0 (or true/false if you prefer) if the move is legal or not, followed (only in case of a legal move) by the new board position in the same format as the input. **Score:** Number of bytes of the complete source code, smaller is better. 20% additional penalty for use of non-ascii characters, and 20% additional penalty if your code can't be tested in Linux using freely available software. **Rules:** No network connections and no 3rd party libraries. Your program should use the standard input and output streams, or the standard equivalent for your programming language. **Examples:** ``` 1) Input: 2 10 01 1 0 2 Output: 0 2) Input: 2 10 11 1 0 2 Output: 1 02 00 3) Input: 5 22122 22021 11211 02120 00120 2 1 1 Output: 1 00100 00101 11011 02120 00120 4) Input: 6 000000 011221 121121 122221 011110 000000 4 0 1 Output: 1 000010 011221 121121 122221 011110 000000 ``` [Answer] # Python 3 (~~557~~ ~~504~~ 488) ``` import sys s=sys.stdin M=int(next(s))+1 j=Z=M*M-M S=s.read(Z) P=0 b=[0]*3 while j>0:j-=1+(j%M<1);b[int(S[j])]|=1<<j;P|=1<<j N=lambda x:(x<<1|x>>1|x<<M|x>>M)&P&~x def h(a,b):t=a|N(a)&b;return h(t,b)if t!=a else a c,r,m=map(int,next(s).split()) o=m%2+1 p=1<<M*r+c b[m]|=p for n in(p<<1,p>>1,p<<M,p>>M): e=h(n&P,b[o]) if~b[m]&N(e)<1<=n&b[o]:b[o]&=~e _,B,W=b g=~b[o]&N(h(p,b[m]))>=1>~_&p print(+g) q='' while j<Z: r=1<<j if g*j%M>M-2:print(q);q='' else:q+='012E'[(r&B>0)+(r&W>0)*2] j+=1 ``` Uses 3 bitfields to represent the board - one each for black, white, and empty spaces. Makes the find neighbors `N` and get chain `h` operations very concise. An ungolfed version with lots of comments: <https://gist.github.com/airfrog/8429006> [Answer] ## Python (~~912~~1004) ``` def o(): n=int(raw_input('')) i=[raw_input('') for r in range(n+1)] b=[map(int,list(r)) for r in i[:n]] u,v,w=map(int,i[n].split(' ')) if b[v][u]!=0:return 0 b[v][u]=w if w==1:q=2 elif w==2:q=1 else:return 0 f=[[],[],[]] h=[[],[],[]] g=[range(z*n,(z+1)*n) for z in range(n)] d=[(1,0),(-1,0),(0,1),(0,-1)] m=lambda z:max(0,min(n-1,z)) t=[0,1,2,0,1] for j,s in enumerate(t): for r in range(n): for c in range(n): for y,x in map(lambda p:(m(r+p[0]),m(c+p[1])),d): if s==0: if b[y][x]==b[r][c]: if g[y][x]!=min(g[y][x],g[r][c]): t.insert(j+1,0) g[y][x]=g[r][c]=min(g[y][x],g[r][c]) elif s==1: if g[r][c] not in h[b[r][c]]: h[b[r][c]].append(g[r][c]) if b[y][x]==0 and g[r][c] not in f[b[r][c]]: f[b[r][c]].append(g[r][c]) if s==2: if b[r][c]==q and g[r][c] not in f[b[r][c]]: b[r][c]=0 h[w].sort() f[w].sort() if h[w]!=f[w]:return 0 return "1\n"+'\n'.join([''.join(map(str,r)) for r in b]) print o() ``` Walk through: parse input, check if move is on an empty spot, make move, init "group" grid, simplify/minimize group grid by checking color of adjacant stones (s=0) **and keep repeating until it is fully minimized**, check for group liberties (s=1), remove opponent stones for groups with no liberties (s=2), repeat s=0 and s=1, check that all player groups have liberties, return result. This can probably be shortened significantly... ~~Interactive~~ Example runs: ``` 2 10 01 1 0 2 0 2 10 11 1 0 2 1 02 00 5 22122 22021 11211 02120 00120 2 1 1 1 00100 00101 11011 02120 00120 6 000000 011221 121121 122221 011110 000000 4 0 1 1 000010 011221 121121 122221 011110 000000 ``` [Answer] # Python 3.8: 480 479 424 359/366 344/351 bytes Inspired by airfrog's accepted answer. [Try it online!](https://tio.run/##NVDBisMgEL3PV3iLJqZEy8JimVPuJbRHkZJNUzZQjaiHBvbfs6bZPczMm@ebN4N@Sd@zO376sK4zzn50tGEQcD6Esb@DxcklujfPyY2UsUpAi7oM1Ja2tsxUuiCFKS0s/MUHtL2neYYHyg7RP6eUR@CMz95@3XvilfaV4L7OUdlcrQGPr9JWC7TaGxwg/ms7Pih9pR0vmoLx3i2UtvpiELf@h6Y3jinQgfXunpWXXRkzGJjRwrDHHMiFTI6cacfeFGxUt1OeKSDTg7S6@3M61gNTCVutzOmK6XC7xTFNabS32ynmS7b3OdBWYcoSBj5s3@MURurzTgbZzamdLbNLbWtheBw9FgVb1w@QUkiZcyMFCCGFgIxkA02zZUkEEb8 "Python 3.8 (pre-release) – Try It Online") ``` o=open(0) r=o.read m=int(o.readline())+1 C=[*r(m*m-m)]+[' ']*m y,x,c=map(int,r().split()) N=lambda p:[p+1,p-1,p+m,p-m] p=x*m+y C[p]=c s=lambda P,c:[S(P,'0'),any((C[R]=='0')|(t[R]==str(c)and[S(R,'0'),s(R,c)][1])for R in N(P))][1] for P in N(p): if C[P]==str(3-c):t=C[:];S=t.__setitem__;s(P,3-c)or(C:=t[:]) print(n:=s(p,c)) if n:print(*C,sep='') ``` (change last line to `if n:print(*C[-m-1],sep='')` if trailing spaces not allowed) ## Older/slightly-different ungolfed version with comments: ``` from copy import deepcopy n = int(input()) in_ = lambda x,y: x>=0 and x<n and y>=0 and y<n neighbors = lambda x,y: [(x+dx, y+dy) for dx, dy in ((0,1),(0,-1),(1,0),(-1,0)) if in_(x+dx,y+dy)] chars = [[*map(int, input())] for i in range(n)] y,x,c = map(int, input().split()) chars[x][y] = c def search(xx,yy,c): global chars tmp = deepcopy(chars) cue = [(xx, yy)] tmp[xx][yy] = 0 nolib = True # no liberty? while cue: xx,yy = cue.pop() for xxx,yyy in neighbors(xx,yy): if tmp[xxx][yyy]==c: cue.append((xxx,yyy)) tmp[xxx][yyy] = 0 elif chars[xxx][yyy]==0: nolib = False if nolib: chars = deepcopy(tmp) return nolib for xx,yy in neighbors(x,y): if chars[xx][yy]==3-c: search(xx,yy,3-c) if search(x,y,c): print(0) else: print(1) for row in chars: print(*row, sep='') ``` ]
[Question] [ This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") with a custom scoring system, where **the lowest score wins.** ## Introduction Many smartphones allow to enter text by [swiping](https://youtu.be/-zWowDurQyo?t=6s) your finger across the 2D virtual keyboard. This technology is usually combined with a prediction algorithm that outputs a list of guessed words, sorted from most likely to least likely. In this challenge: * We are going to swipe across a **one-dimensional keyboard** restricted to a subset of the 26 letters. * There will be **no prediction algorithm**: we want each word to be uniquely identified by its 'swipe sequence'. * **We want the keyboard to be optimized** in such a way that the total number of moves for a given list of words is minimized. ## Swiping in one dimension Below is a lexicographically sorted 1D keyboard with all letters: `A``B``C``D``E``F``G``H``I``J``K``L``M``N``O``P``Q``R``S``T``U``V``W``X``Y``Z` *NB: This may be displayed on several rows if you're browsing from mobile. Please think of it as a single row.* To enter the word '**GOLF**' on such a keyboard, we will: * start at `G` * swipe to the right to `O` * swipe to the left to `F` Because `L` is located between `O` and `F`, we just go on swiping without stopping there. So the swipe sequence of '**GOLF**' on this keyboard is `G``O``F`. More generally: * The first and last letters are always included. * Other letters are included if and only if a direction change is required just after them. * Repeated letters must be treated the same way as single letters. For instance, on the above keyboard: + '**LOOP**' would be encoded as `L``P` (with no stop on `O`) + '**GOOFY**' would be encoded as `G``O``F``Y` (the `O` is included because there's a direction change there -- not because it's doubled) ## Keyboard optimization Let's consider the following list of words: ['**PROGRAMMING**', '**PUZZLES**', '**AND**', '**CODE**', '**GOLF**']. We need 16 distinct letters to type these words, so we just need a 16-letter keyboard. The following one is -- again -- lexicographically sorted: `A``C``D``E``F``G``I``L``M``N``O``P``R``S``U``Z` With this keyboard, the words will be encoded this way: * **PROGRAMMING**: `P``R``G``R``A``M``I``N``G` (9 moves) * **PUZZLES**: `P``Z``E``S` (4 moves) * **AND**: `A``N``D` (3 moves) * **CODE**: `C``O``D``E` (4 moves) * **GOLF**: `G``O``F` (3 moves) That's a total of **23 moves** for all words. But we can do much better with this keyboard: `C``G``O``D``S``E``L``Z``N``U``I``F``R``P``A``M` Which gives: * **PROGRAMMING**: `P``G``M``G` (4 moves) * **PUZZLES**: `P``S` (2 moves) * **AND**: `A``D` (2 moves) * **CODE**: `C``E` (2 moves) * **GOLF**: `G``F` (2 moves) for a total of only **12 moves**. ## Keyboard scoring For a given list of \$n\$ words, the score of a keyboard is given by: $$\sum\_{k=1}^{n}{m\_k}^2$$ where \$m\_k\$ is the number of moves for the \$k\$-th word. For instance, the two keyboards described in the previous paragraph would be scored \$9^2+4^2+3^2+4^2+3^2=131\$ and \$4^2+2^2+2^2+2^2+2^2=32\$ respectively. The lower, the better. ## The challenge * Given a list of words, your code must output a **valid** keyboard for this list. A keyboard is considered valid if each word generates a unique swipe sequence. * You'll be given 11 independent lists of words. Your score will be equal to: $$S + L$$ where \$S\$ is the sum of the scores of your keyboards for all lists and \$L\$ is the length of your code in bytes. You can [use this script to check your score](https://tio.run/##fVbbcts2EH3XV6BTTyTGimL1Ma7bAUmQhAUCDAhalhV1Ituyo0SVPJJStePo293dBXXppO0LAS6wZ8@eXYD8PP5jvLpbTp/Wb@aL@8mLkqUr2QUbNhgbsmYpRLPdLDPRZKO2N0VGxWCLlIkPRh5FQrsS7Dgry8OK5U4asGscNU6ks2iw0jgY4MnRTVp8WjSBCzydJT9nudQHOJchofeVjHowhtb0ETMx1/C8rPICKZgrgWCK3wxgiE165I6QJsG43g83Eq2@dBkywNAh@iXW5DBUBVpDUxFZ7QF8AJ44GPfYITLL@JWgoCgbR5xUoGfOe2hP0d7Tpo@ZeZOXODI5Di6TGhNTxuDQ5xqcAZ6xZioJuSrxmUiNRXBCKSRS0mZjex4PeSdCKJIPOSjhaUUc9u8Jp8YgiBZ9QrSlI9X8YHSKfK0gRZR0TiGC19tAGUg5agUr04xkk@iSwduOcyyTRFiBSTTLnBNZxW0qKOw1mgW3CikOTEURZV4Y6yhvyAGZFVWoZIT4PCZVUSmPz0N11JlOkoaFsCWVdADYJCK1AT1R35TKob1ilICSia8diVr4LowySYtisA/XN96vUDwSB8X7QvRIXCpNYSSRT7FLdO6Th/IWXCMDXeUhaZdaQ71VWANZ5LsYCY9cc3@sYp6X/lxkFTqFVQQsiURYgbA0lhlFt45wIyWuhPKpRAo7VhMBo2RMwgtZCp2ZPu6uY0qlcmOFPxHomHKbSEH5p9YXI@M29uLBzEovccYHAglmpj4Tlzzq@aVLgbWnuY9yaTLtl3pCaxFTY0oN94mmisQ1Zh71pFYCl3OjraFmkde0ZkKe43VRSGEjr7bq7QJAr6YkjTWmRBHoGoFTSsNA0WF3tvJFxAnq7wZK@DYpsTlcfRsoJLNvrTICQWWFB8tJ6E4/vYJS1NYog@vCTwEeaAhqBmlr9UNObDTcW3QuI1MUFPYGFNglMHBw6RHGjbSRqaNAtzmpaZr6A5dD8hUdbFvhScSi@b1xFdZepYBLy6b@JTSZB/ZxMl6WNVchnRZ10EpXOvRTLU09k1bW2LlRgzAWnokTUaaF8yvEQh8FsJmpnQo49DuNSql8k0Q8rrXKeFLzxSPPlZ/CTVA6am67w22aklzYqDE6f1ltpk8T@Eq1vty22SZgF7@wZ4h8P314QOu4zW7JmI/Xnzqr6eMcNnam8/vJn@ahBUtv2NH7OAjOG@D9sFi2Nvjp63Q6m85y8jQb301ab1ud4EP39O1jmzVPus1g1GYr2LQZnsFsDrPuOQw/s01nNpk/rj/B2@lpQHQ85D3sQWKtzXAOgbvgBrNRgG6nrHvkyl692u/0u3DDCDIBhB3uloBX7PSCYM7hFU3Lyfrrcs5W541t48ttebdY7vWZTVfrvUT1PrRBivdfIcPWerEez2odCZ0MEBvcAQSkWi@qp6fJMhqvJq2g7RUadVaL3yetO0Q@UvOO6L7pBuzbN/ZDa3H7eYh6UcXqco3YbyBbwH6F7N@yM/aOrXYKvH7Nfgp8E521GTiDK6UcYGKrXVqwuw1B91l5whfsDOWgX5gOSC/Gd59aLchs6jdS4WpxgMpwCiLPoA51ukDynN0t5qvFbNKZLR5bHxWoxH48eZ5iHbbv2JfJX7eL8fKe7YicPK@2HwFhG2Dgf/h@mCfTOcAetgLpLQCdPFO8Ldl2SuPax6CxfaHtLQDrnoEAw/q8lvtPkP/7qr9@8M9V7v8P4DfJ2MNbGMUiSTN52VO5NsV7@LpXV/3rwc1hh0gyiWsWVwbfeZKjd/t@kUBxESD/3bP4L9fL4@X/9wa2sDhqBC9/Aw). The `score()` function expects your code length as first parameter and an array of 11 keyboard strings as second parameter (the case doesn't matter). * The submission with the lowest score wins. In case of a tie, the submission that was submitted first wins. ## Additional rules * Your code must be **deterministic** (i.e. it must always return the same output for a given input). * You must either A) provide a test link (e.g. on TIO) that does not time out, or B) include the generated keyboards within the body of your answer. * You may take the words in either full uppercase or full lowercase. Mixed cases are forbidden. * The input is guaranteed to have at least one solution. * All words are made of at least 2 distinct letters. * Your code must work for any valid input. It will be tested with an undisclosed list of words to make sure that it's not relying on hard-coded results. * I reserve the right to increase the size of the test suite at any time to make sure that the submissions are not optimized for the initial test cases. ## Word lists ``` 1) Sanity check #1 (only 4 valid solutions: HES, SEH, ESH or HSE) SEE, SHE 2) Sanity check #2 (16 valid solutions, of which 4 are optimal: COLD, DOLC, DLOC or CLOD) COLD, CLOD 3) Sanity check #3 ACCENTS, ACCESS 4) Warm-up RATIO, NATION, NITRO, RIOT, IOTA, AIR, ART, RAT, TRIO, TRAIN 5) Pangram THE, QUICK, BROWN, FOX, JUMPS, OVER, LAZY, DOG 6) Common prepositions TO, OF, IN, FOR, ON, WITH, AT, BY, FROM, UP, ABOUT, INTO, OVER, AFTER 7) Common verbs BE, HAVE, DO, SAY, GET, MAKE, GO, KNOW, TAKE, SEE, COME, THINK, LOOK, WANT, GIVE, USE, FIND, TELL, ASK, WORK, SEEM, FEEL, TRY, LEAVE, CALL 8) Common adjectives GOOD, NEW, FIRST, LAST, LONG, GREAT, LITTLE, OWN, OTHER, OLD, RIGHT, BIG, HIGH, DIFFERENT, SMALL, LARGE, NEXT, EARLY, YOUNG, IMPORTANT, FEW, PUBLIC, BAD, SAME, ABLE 9) Common nouns TIME, PERSON, YEAR, WAY, DAY, THING, MAN, WORLD, LIFE, HAND, PART, CHILD, EYE, WOMAN, PLACE, WORK, WEEK, CASE, POINT, GOVERNMENT, COMPANY, NUMBER, GROUP, PROBLEM, FACT 10) POTUS ADAMS, ARTHUR, BUCHANAN, BUREN, BUSH, CARTER, CLEVELAND, CLINTON, COOLIDGE, EISENHOWER, FILLMORE, FORD, GARFIELD, GRANT, HARDING, HARRISON, HAYES, HOOVER, JACKSON, JEFFERSON, JOHNSON, KENNEDY, LINCOLN, MADISON, MCKINLEY, MONROE, NIXON, OBAMA, PIERCE, POLK, REAGAN, ROOSEVELT, TAFT, TAYLOR, TRUMAN, TRUMP, TYLER, WASHINGTON, WILSON 11) Transition metals SCANDIUM, TITANIUM, VANADIUM, CHROMIUM, MANGANESE, IRON, COBALT, NICKEL, COPPER, ZINC, YTTRIUM, ZIRCONIUM, PLATINUM, GOLD, MERCURY, RUTHERFORDIUM, DUBNIUM, SEABORGIUM, BOHRIUM, HASSIUM, MEITNERIUM, UNUNBIUM, NIOBIUM, IRIDIUM, MOLYBDENUM, TECHNETIUM, RUTHENIUM, RHODIUM, PALLADIUM, SILVER, CADMIUM, HAFNIUM, TANTALUM, TUNGSTEN, RHENIUM, OSMIUM ``` [Answer] # Python 3 + [Google OR-Tools](https://developers.google.com/optimization/), 1076 + 1971 = 3047 This always finds optimal solutions (but spends a lot of code to do so). It runs tests 1–9 in a few seconds, test 10 in six minutes, and test 11 in one minute. ### Code ``` from ortools.sat.python.cp_model import* from itertools import* C=combinations R=range L=len T=lambda w:[*zip(w,w[1:],w[2:])] W=[(*(g[0]for g in groupby(w)),)for w in input().split()] K={*sum(W,())} m=CpModel() V=m.NewBoolVar B={c:V(f"B{c}")for c in C(K,2)} for a,b in[*B]:B[b,a]=B[a,b].Not() for a,b,c in permutations(K,3):m.AddBoolOr([B[a,b],B[b,c],B[c,a]]) M={t:V(f"M{t}")for t in{*sum(map(T,W),[])}} for a,b,c in M:m.AddBoolXOr([B[a,b],B[b,c],M[a,b,c].Not()]) N={(w,n):V(f"N{w,n}")for w in W for n in R(1,L(w))} for w in W: for n in R(1,L(w)-1):s=sum(M[t]for t in T(w));m.Add(s>=n).OnlyEnforceIf(N[w,n]);m.Add(s<n).OnlyEnforceIf(N[w,n].Not()) for a,b in C(W,2): if(a[0],a[-1])==(b[0],b[-1]):m.AddForbiddenAssignments([M[t]for t in T(a)+T(b)],[[x in X for x in R(L(a)-2)]+[y in Y for y in R(L(b)-2)]for n in R(L(a))for X in C(R(L(a)-2),n)for Y in C(R(L(b)-2),n)if[a[x+1]for x in X]==[b[y+1]for y in Y]]) m.Minimize(sum((2*n+3)*N[w,n]for w,n in N)) s=CpSolver() s.Solve(m) o={k:0for k in K} for c in C(K,2):o[c[s.Value(B[c])]]+=1 print(*sorted(K,key=lambda k:o[k]),sep="") ``` ### Result 1. SEH, 13 2. DOLC, 20 3. TNSECA, 13 4. RATION, 80 5. TYKCIDBRFHJUEVOXWNGZALQMPS, 32 6. REWINTHUVOFABMPY, 66 7. FYCWORTMHAGINDKVESULB, 125 8. TSHRDABXLYOWUPMIENGCF, 213 9. PVKEFDLBMUSWOIHACNYTRG, 212 10. XHGTPMCKSUABYORDLJEIWNFV, 596 11. PYLFNAVEKBOCHTRGDSIZUM, 601 [Check score](https://tio.run/##VVZRU@M2EH7nV6hTpomPXA760M4cpR3Zlm0RWfJJcoLh0rkAgctdmjBJrrTD5bfT3ZUT6Islr7TffvvtSvaXyd@T9c1q9rB5u1jeTp@VdN6xM3Z1wNgV6zghOr2OK0SHjXvBlBiVgi1RJn0x8iQR2juw48y5lxXLvTRg1zhqnEhv0WCl8TDAk6ObtPi0aAIXeHpLft5yqV/gfIGEPtQyGcAYWzNCzMxcwPO8LiukYIYCwRS/bGBITf7KHSFNhnGDH24kWiPpC2SAoWP0y6wpYagrtMamJrI6AIQAPPMw7rFjZFbwoaCgKBtHnFygZ8kHaM/RPtBmhJkFU5A4MSUOvpAaE1PG4DDiGpwBnrFOLgm5dvjMpMYieKEUEnG02dhBwEPemRCK5EMOSgRaCYf9e8K5MQiixYgQrfOkWhiMzpGvFaSIkt4rRAh6GygDKUetYGVekGwSXQp423FOZZYJKzCJjis5kVXc5oLCXqBZcKuQYmNqiijLylhPeUMOyKyqYyUTxOcpqYpKBXweq1ed6SVpWAnrqKQNYJOI1Ab0RH1zKocOilECSmahdiRqFbowKSQtimYfbmSCX6V4Il4UHwkxIHGpNJWRRD7HLtFlSB7KW3GNDHRdxqRdbg31VmUNZFHuYmQ88Z39sUp56cK5KGp0iusEWBKJuAZhaXQFRbeecBMlhkKFVBKFHauJgFEyJeGFdEIXZoS725hSqdJYEU4EOubcZlJQ/rkNxSi4TYN4MLMySFzwRiDBwrRn4pwng7B0LrD2NA9Rzk2hw9JAaC1Sakyp4T7RVJG0xSyTgdRK4HJptDXULPKC1kzMS7wuKilsEtRWg10A6NWcpLHGOBSBrhE4pTQ0ig67t3UoIk5Qf98oEdrEYXP49jZQSGbfWi4BQWWNB8tL6M4wHUIpWmtSwHURpgAPNAQ1g7St@jEnNhruLTqXiakqCnsJCuwSaDxceoRxKW1i2ijQbV5qmubhwJWQfE0H29Z4ErFoYW9ax62XE3Bp2Ty8xKYIwCFOwZ1ruQrptWiD1rrWcZhqadqZtLLFLo1q4lQEJl4khRY@rBAL/SqALUzrVMGh32nkpApNkvC01argWcsXjzxXYQo3gfPU3HaH2zGOXNj4YHz6vH6cPUzhK9X9et1jjxE7@509QeTb2d0dWic9dk3GcrL53F/P7hewsT9b3E7/MXddWHrLXr1Pouj0ALzvlqvuI376@v3@Y381fZhPbqbdd91@9PHk6N19j3UOTzrRuMfWsOnx6hhmC5idnMLwG3vsz6eL@81neDs6iohOgLyFPUis@3i1gMAn4AazcYRuR@zklSv76af9zrALN4whE0DY4W4JeM2OzgjmFF7RtJpuvq0WbH16sD34eu1ulqu9PvPZerOXqN2HNkjx9htk2N0sN5N5qyOhkwFigzuAgFSbZf3wMF0lk/W0G/WCQuP@evnXtHuDyK/UvCG6b08i9v07@6G7vP5yhXpRxdpyjdmfIFvE/oDs37Fj9p6tdwq8ecN@jkITHfcYOIMrpRxhYutdWrC7B0H3WQXCZ@wY5aBfmD5ILyY3n7tdyGwWNlLhWnGAytUMRJ5DHdp0geQpu1ku1sv5tD9f3nc/KVCJ/Xj4NMM6bN@zr9N/r5eT1S3bETl8Wm8/AcI2wsD/8/24yGYLgH3ZCqS3AHT4RPG2ZNspjWufooPtM23vAtjJ8a@/9Og3jOFv2Msn1aj9feG1EwnfH7r2D6tdawaJTGObFee1GJqLkc4vufpAf0i763IEX4eiHpqMx2XV7L8GTQIfNl8WPIe/jMFQuFrFe1hX2JTHF6oxo7oqpdB5ku0Wq@FAZKmKy9qNjCx4ohtv893qRZH7Ci53V/O4gRtLnQs50tlw792oTMN/yiA2SQF@qZOX7ZUyPoie/wM "JavaScript (Node.js) – Try It Online") ]
[Question] [ A [primitive element](https://en.wikipedia.org/wiki/Primitive_element_(finite_field)) of a finite field is a generator of the multiplicative group of the field. In other words, `alpha` in `F(q)` is called a primitive element if it is a primitive `q−1`th root of unity in `F(q)`. This means that all the non-zero elements of `F(q)` can be written as `alpha^i` for some (positive) integer `i`. All elements of the field `F_{2^k}` can be written as polynomials of degree at most `k-1` with coefficients that are either `1` or `0`. In order to make this complete, your code also needs to output an [irreducible polynomial](https://en.wikipedia.org/wiki/Irreducible_polynomial) of degree `k` which defines the field you are using. The task is write code that outputs a primitive element of `F_{2^k}` of your choosing for each `k = 1 .. 32` in order. Your output must simply list the `k` coefficients of the primitive element in any format that you like and then on a separate line the `k+1` elements of the irreducible polynomial. Please separate the outputs for each value of `k` if possible. Your code may take as long as you like but you must have run it to completion before submitting your answer. You may not use any builtin or library function which returns primitive elements of a finite field or tests whether an element is primitive. **An example** For `k = 1` the only primitive element is `1`. For `k = 2` we have `F_4`. The 4 elements are `{0, 1, x, x + 1}` so there are two primitive elements `x` and `x + 1`. So the code could output ``` 1 1 1 1 1 ``` as the coefficients for example where the second line is the irreducible polynomial which in this case is `x^2+x+1` which has coefficients `1 1 1`. [Answer] # Mathematica, 127 bytes ``` Do[For[i=2*2^n,PolynomialMod[x^Divisors[2^n-1]+1,i~IntegerDigits~2~FromDigits~x,Modulus->2]~Count~0!=1,i--];Print@{2,i},{n,32}] ``` ### Explanation: If we choose a [primitive polynomial](https://en.wikipedia.org/wiki/Primitive_polynomial_(field_theory)) as the irreducible polynomial, then \$x\$ is a primitive element. A irreducible polynomial of degree \$n\$ is primitive if and only if it has order \$2^n - 1\$, i.e., it is divisible by \$x^{2^n - 1} - 1\$, but not divisible by any \$x^i - 1\$, where \$i\$ runs through all the proper divisors of \$2^n - 1\$. ### Output: Outputs integers whose bits are the coefficients of the polynomials. For example, \$8589934581\$ is \$111111111111111111111111111110101\$ when written in binary, so it represents the polynomial $$x^{32}+x^{31}+x^{30}+x^{29}+x^{28}+x^{27}+x^{26}+x^{25}+\\x^{24}+x^{23}+x^{22}+x^{21}+x^{20}+x^{19}+x^{18}+x^{17}+\\x^{16}+x^{15}+x^{14}+x^{13}+x^{12}+x^{11}+x^{10}+x^9+\\x^8+x^7+x^6+x^5+x^4+x^2+1$$ ``` {2,3} {2,7} {2,13} {2,25} {2,61} {2,115} {2,253} {2,501} {2,1019} {2,2041} {2,4073} {2,8137} {2,16381} {2,32743} {2,65533} {2,131053} {2,262127} {2,524263} {2,1048531} {2,2097145} {2,4194227} {2,8388589} {2,16777213} {2,33554351} {2,67108849} {2,134217697} {2,268435427} {2,536870805} {2,1073741801} {2,2147483533} {2,4294967287} {2,8589934581} ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 114 bytes Inspired by [isaacg's answer](https://codegolf.stackexchange.com/a/129443/9288) in another question. ``` for(n=1,32,for(i=1,2^n,if(sumdiv(2^n-1,d,Mod(x,f=Mod(Pol(binary(2*2^n-i)),2))^d==1)==1,print([x,lift(f)]);break))) ``` [Try it online!](https://tio.run/##FYpBCgIxEAS/My2zh8Sj5AmCd3EhSxwZXJMwrrK@PiaHoquhajSdHrU1KUY5OD56Hqpd/ZxZhd6fV9Iv9Tc5TnwuiXaWMPZSVlo0R/uRP4xAAfbAnEJw6HA1zRtdd15VNhLccFrsHp8AWvsD "Pari/GP – Try It Online") --- If built-ins are allowed: ### [Pari/GP](http://pari.math.u-bordeaux.fr/), 61 bytes (non-competing) ``` for(i=1,32,print([ffprimroot(ffgen(f=ffinit(2,i))),lift(f)])) ``` [Try it online!](https://tio.run/##DckxCoAwDAXQ6yQQB@vck4iDg7980KaE3j92e/DGHdzayISHsO52FBvBPuUEFr5wnwK0pwsqwM4pxaiq9hKr9FLN/AE "Pari/GP – Try It Online") ]
[Question] [ Some text-based rogue-likes don't let you walk into walls, and give you your move back if you try to. Why do that when you can make the player move in the closest valid direction? ## The challenge Write a program of function that, given a direction and a 3 by 3 grid of characters, outputs the same grid after the player has taken a step. For example, ``` 9 #.. .@# #.# ``` becomes ``` #.@ ..# #.# ``` ## Input * The direction is given by a single digit from 1 to 9, each corresponding to 8 cardinal directions and standing still. This is derived from the relative locations of the numbers on a keypad: ``` NW N NE ..\ | / ...7 8 9 W- 4 5 6 -E ...1 2 3 ../ | \ SW S SE ``` However, you may also use the numbers 123, 456, 789 instead of 789, 456, 123. In other words, you may swap the top and bottom 2 rows or numbers if you so choose. These are the only 2 acceptable index combinations. * The 3 by 3 grid will consist of 3 distinct, printable ASCII characters representing walkable floor, walls, and the player. (In the test cases, `.` is used for floor, `#`s are walls, and `@` is the player) * You may choose what characters your program uses, but you must state them in your answer and they must be consistent over multiple trials. * The character representing the character will always be in the middle of the 3 by 3 grid, and the direction will always be between 1 and 9 (incl.) * You may take input in any order * The 3 by 3 grid can be input as a char array, a string array, a 9 length string, or another reasonable alternative. ## Output * Return from a function, or output to StdOut or closest alternative * Trailing spaces and newlines are allowed * You must use the same character representations as the input * The same formats allowed for inputs are allowed for outputs ## How the player moves If the specified direction is blocked by a wall (e.g. if the above example had direction 6), then look at the 2 closest directions: * If one (and only one) direction is free, move the player in that direction. * If no directions are free, look at the next closest 2 directions (excluding direction 5). If you have wrapped all the way around and found no open direction (player surrounded by walls), do not move the player * If both of the directions are open, pick one to move to at random (although not necessarily uniformly). If the given direction is a 5, do not move the player ## Test cases (`#` = wall, `.` = floor, `@` = player) ``` Input: 9 #.. .@# #.# Output: #.@ ..# #.# Input: 3 #.. .@# #.# Output: #.. ..# #@# Input: 7 ##. #@# ..# Output: ##@ ##. #.# or #.# ..# @.# Input: 5 ... .@. ... Output: ... .@. ... Input: 2 ### #@# ### Output: ### #@# ### ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # JavaScript (ES6), ~~192~~ 163 bytes ``` a=>b=>a[(a[4]=0)+--b]?(A=(c,d)=>c==b|(e=a[c])-(f=a[d])|!e?(a[c-b?(e?e<f:new Date&1)?c:d:4]=2,a):A(+g[c],+h[d]))(+(g="3016X2785")[b],+(h="1250X8367")[b]):(a[b]=2,a) ``` # Notes This function uses a special input format. The first input is an array of integers (`0` for `floor`, `1` for `wall` and `2` for `player`) representing the map. The second input is the (flipped) direction: `1` is north-west, `2` is north, `3` is north-east, `4` is west etc. The inputs should be given through currying syntax (`Z(a)(b)`). # Test cases The maps and directions have been modified to suit my input format. ``` Z= a=>b=>a[(a[4]=0)+--b]?(A=(c,d)=>c==b|(e=a[c])-(f=a[d])|!e?(a[c-b?(e?e<f:new Date&1)?c:d:4]=2,a):A(+g[c],+h[d]))(+(g="3016X2785")[b],+(h="1250X8367")[b]):(a[b]=2,a) testcases = [ [[1,0,0,0,2,1,1,0,1], 3], [[1,0,0,0,2,1,1,0,1], 9], [[1,1,0,1,2,1,0,0,1], 1], [[0,0,0,0,2,0,0,0,0], 5], [[1,1,1,1,2,1,1,1,1], 2] ] for (test of testcases) { console.log(Z(test[0])(test[1])) } ``` [Answer] # Pyth - ~~73~~ 70 bytes ``` Kmsd"78963214"DPGJXXYt@K+xKQG\@4\.R?q/J\#/Y\#Jk=YwV5=GflTmPd(N_N)IGOGB ``` [Try It](https://pyth.herokuapp.com/?code=Kmsd%2278963214%22DPGJXXYt%40K%2BxKQG%5C%404%5C.R%3Fq%2FJ%5C%23%2FY%5C%23Jk%3DYwV5%3DGflTmPd%28N_N%29IGOGB&input=7%0A%23...%40%23%23.%23&debug=0) Input consists of two lines: 1st line: direction of move 2nd line: The board (positions 123456789, with 123 being the top row) [Answer] # Python 3, ~~120~~ ~~104~~ ~~153~~ ~~176~~ 175 bytes ``` def f(n,l): n-=1 if n!=4and'.'in l:l[sorted(enumerate(l),key=lambda x:abs(x[0]%3-n%3+(x[0]//3-n//3)*1j)-ord(x[1])-__import__('random').random()/9)[1][0]],l[4]='@.' return l ``` [Try it online!](https://tio.run/nexus/python3#TU7LDoIwELzzFTWGtKst2OhFEhL@gzSk2hLRspACCX64Z2zAg4ednZnsYxZja1Iz5A6yiKDIZUSamuAuv2g0NKENEpe5cuj8aA2zOLXW69EyB/xl37nT7c1oMmf6NrC5PKn4LDA@H1eepkEEgIN8gui8Ca5UIKqqaftwsKoY9eFN11JINsIgvUIYCtuKu/KiclokNCLejpMPUZbeNziymkle0j3layW/XvzpzVMAywc7cdf3h/0C "Python 3 – TIO Nexus") This method get direction and list of '.', '#' and '@'. Indexes start with 1 to 9 (with 0 to 8 in list really). So it has the form ``` 123 456 789 ``` Method return new list with new positions. This line ``` sorted(enumerate(l),key=lambda x:abs(x[0]%3-n%3+(x[0]//3-n//3)*1j)-ord(x[1])-__import__('random').random()/9) ``` returns a list of this type: ``` >>>n=7 >>> l=['#','#','#','.','@','#','.','#','.'] >>> sorted(enumerate(l),key=lambda x:abs(x[0]%3-n%3+(x[0]//3-n//3)*1j)-ord(x[1])-__import__('random').random()/9) [(4, '@'), (8, '.'), (6, '.'), (3, '.'), (7, '#'), (5, '#'), (1, '#'), (0, '#'), (2, '#')] ``` We calculate distances to free points and add randomness. Because `ord('#') <= ord('.') - 8 and ord('.') + 8 <= ord('@')` we can say that the nearest '.' for n=7(index in list) has an index of 8. [![enter image description here](https://i.stack.imgur.com/zxwWB.png)](https://i.stack.imgur.com/zxwWB.png) Example: ``` >>> f(9, ['#','.','.','.','@','#','#','.','#']) ['#', '.', '.', '.', '.', '#', '#', '@', '#'] >>> f(3, ['#','.','.','.','@','#','#','.','#']) ['#', '.', '@', '.', '.', '#', '#', '.', '#'] >>> f(5, ['.','.','#','.','@','.','#','.','#']) ['.', '.', '#', '.', '@', '.', '#', '.', '#'] >>> f(7, ['#','#','#','#','@','#','#','#','#']) ['#', '#', '#', '#', '@', '#', '#', '#', '#'] >>> f(7, ['#','.','.','.','@','#','#','.','#']) ['#', '.', '.', '@', '.', '#', '#', '.', '#'] or ['#', '.', '.', '.', '.', '#', '#', '@', '#'] ``` ]
[Question] [ Here are five images of pears and a [steel](http://chat.stackexchange.com/transcript/message/21980433#21980433) [chute](http://chat.stackexchange.com/transcript/message/21980333#21980333): > > **A:**[![pears A](https://i.stack.imgur.com/E8CYus.png)](https://i.stack.imgur.com/E8CYu.png) **B:**[![pears B](https://i.stack.imgur.com/4za5fs.png)](https://i.stack.imgur.com/4za5f.png) **C:**[![pears C](https://i.stack.imgur.com/VQidIs.png)](https://i.stack.imgur.com/VQidI.png) **D:**[![pears D](https://i.stack.imgur.com/GssKrs.png)](https://i.stack.imgur.com/GssKr.png) **E:**[![pears E](https://i.stack.imgur.com/bMarCs.png)](https://i.stack.imgur.com/bMarC.png) > > > **These are only thumbnails, click them for full size!** > > > (I made these with [Algodoo](http://www.algodoo.com/).) This class of images always has the following properties: 1. They are always 400×400 pixels with a white background. (It may not be exactly white since SE images are lossily compressed.) 2. They have 1 to 4 identical pears, each rotated and positioned in (almost) any way. 3. They have one vertical steel chute that reaches to the bottom of the image. 4. Other than the bottom of the chute, the chute and the pear bounding boxes ([bounding box example](https://i.stack.imgur.com/COy9K.png)) never touch or go out of the image bounds. 5. The bounding boxes of the pears never overlap each other nor overlap the chute. 6. The pears may be under the sloped part of the chute, as in **B**, **C**, and **D**. (So the bounding box of the chute may overlap the bounding box of a pear.) 7. The chute may have any horizontal and vertical position as long as there is enough room for all the bounding boxes of the pears to fit freely above it (no "barely fits" cases will be tested) and part of the column portion is visible. # Challenge Write a program that takes in such an image and outputs another 400×400 image with the chute in the same place, but with the pears repositioned so they are all above the chute (so they can fall into it and be juiced and whatnot). The requirements for the output image are: 1. All the pears in the input image must be repositioned such that they are above the chute, between the left and right edge of its funnel. (Above an edge is **not** ok.) 2. Each pear must maintain its rotation angle. (So you should be cutting and pasting the pears, not redrawing them.) 3. The pears must not overlap or touch each other or the chute. (The pear *bounding boxes* may overlap though.) 4. The pears must not touch or go out of the image bounds. Here are examples of valid outputs for the five sample images: > > **A:**[![out A](https://i.stack.imgur.com/FDDyas.png)](https://i.stack.imgur.com/FDDya.png) **B:**[![out B](https://i.stack.imgur.com/xWA2ds.png)](https://i.stack.imgur.com/xWA2d.png) **C:**[![out C](https://i.stack.imgur.com/f5gr2s.png)](https://i.stack.imgur.com/f5gr2.png) **D:**[![out D](https://i.stack.imgur.com/IyWtOs.png)](https://i.stack.imgur.com/IyWtO.png) **E:**[![out D](https://i.stack.imgur.com/zCqzJs.png)](https://i.stack.imgur.com/zCqzJ.png) > > > **These are only thumbnails, click them for full size!** > > > Note that the input image for **E** was already a valid output, but rearranging the pears when not technically necessary is just fine. ## Details * Take the filename of the image or the raw image data via stdin/command line/function call. * Output the image to a file with the name of your choice or output the raw image file data to stdout or simply display the image. * Any common lossless image file format may be used. * Graphics and image libraries may be used. * A few incorrect pixels here and there (due to lossiness or something) is not a big deal. If I can't tell anything is wrong visually then it's probably alright. **The shortest code in bytes wins. Tiebreaker is highest voted post.** [Answer] # Python 2.7, 636 bytes ``` import sys;from PIL.Image import* _,m,R,I,p,H=255,400,range,open(sys.argv[1]).convert('RGB'),[],0 w,h=I.size;W,A,P,L=(_,_,_),[(x,y)for x in R(w)for y in R(h)],I.load(),I.copy() try: while 1: s,x,y,X,Y=[[a for a in A if P[a][0]<50][0]],m,m,0,0 while s:c=(a,b)=s.pop();x,y,X,Y=min(x,a),min(y,b),max(X,a),max(Y,b);P[c]=W;s+=[n for n in[(a+1,b),(a,b+1),(a-1,b),(a,b-1)]if n in A and P[n]!=W] p+=[((x,y,X,Y),X-x,Y-y)] except:0 def G(a):r,g,b=P[a];return r==g==b and r<_ g=[a for a in A if G(a)] (z,t),W=g[0],max([x for x,y in g]);t-=1 for r,w,h in p: if z+w>W:z,_=g[0];t-=H;H=0 I.paste(L.crop(r),(z,t-h,z+w,t));z+=w;H=max(h,H) I.show() ``` **EDIT** : now removes the alpha channel before handling the image, and aligns the pears on several rows if necessary Produced images : ![A](https://i.stack.imgur.com/xmajP.png) ![B](https://i.stack.imgur.com/j1eBH.png) ![C](https://i.stack.imgur.com/sUpFa.png) ![D and E](https://i.stack.imgur.com/VY2HP.png) and with vertical pears (takes around 3 minutes on my computer): ![testcase](https://i.stack.imgur.com/h01kL.png) ![vertical](https://i.stack.imgur.com/ddu42.png) ]
[Question] [ # Easter Egg Hunt Bot find egg before bunny find egg. Bot happy. ## Overview This is a [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge in honor of Easter and the Easter egg hunting tradition! Your bot has a vision of two spaces in every direction, including diagonals, creating a 5x5 square around you that you can see. It is looking for eggs, and whoever finds the most eggs wins! ## The Board The board will consist of `o`s, which are Easter eggs, `#`s, which are walls, `*`s, which are other players, and s, which are empty spaces. * It will be a square with edge length `(number of entries) * 3`. * It will be surrounded by walls. * Inside of the walls will be an assortment of randomly placed, straight line walls of `#`, which will have a random length between 2 and 10 inclusive. There will be `(number of entries) * 3` of them. * The eggs will then be placed randomly. There will be `(number of entries) * 4` of them, and they will only be generated on blank () squares. * There must be at least 7 entires for the board generating process to work properly. [Here is a JSFiddle that will generate a random board](http://jsfiddle.net/Y4CJz/) for you to test with. Here's an example, with `(number of entries) = 7`: ``` ##################### # o ## # # o ## # #o ###### ## ###### # ## ## o # # ## ## o# #o# o o## ## #o # # o # # ## # o # # # # ## ## # # o # # ## # # o # # # ## # o # ## # # # ## # # # # # o # ## # # # o oo ##o # #o ####### oo ## # # # # # # o o o# # # o #### o o# # # ##################### ``` After the board is generated, each player is placed on a random square (empty space). ## Input You will take six lines of input. The first five lines are your field of vision (spaces out of bounds of the board will be represented by `X`, and the middle space will always be `*`, you), and the sixth line will be empty (at first). ## Output You will output three lines. First, the direction that you want to move in: ``` 1 2 3 8 YOU 4 7 6 5 ``` (9 is a no-op if you don't want to move), second, one of `A`ttack, `C`ounter, or `N`othing (this will be explained in depth soon), and the thrid line will be any string of length up to 1024. This will be your bot's memory. You may use it for whatever you would like, or you may leave it blank. This memory will then be the sixth line of input to your program on the next run. All further lines of output are ignored, and if there is only one line, the second is assumed to be blank. ## Moving The following process is used to determine where you moved: * If, when you move, you end up in an empty space (), your player is placed into that space. * If you end up in a wall (`#`), your move is ignored and you lose your turn. * If you end up in an egg (`o`) or on a player (`*`), this information is stored and will be used after everybody has moved. After everybody has moved, ambiguities are resolved. If there are two players that have landed on the same space, a fight occurs! This is where the `A`/`C`/`N` comes in to play. `A`ttack beats `N`othing (normal attack), `N`othing beats `C`ounter (you can't counter nothing), and `C`ounter beats `A`ttack (counterattack). The player who wins this fight stays on their square, and the player who loses goes back to the original square that they started on. In the event of a tie, both players go back to where they were. If a losing or tied player goes back to where they were and there is another player there, there is no fight and the other player will also revert to its original space. If *this* space has another player, *that* player goes back, and this continues until all players are in different spaces. If there are three or more players on one space, they all revert back to their original positions. If any player is still standing on an egg... * If the player chose `A`, the egg is destroyed. * If the player chose `C`, nothing happens and the player reverts to its original space. * If the player chose `N`, the player picks up the egg! The player's score is incremented by one and the egg is removed. ## Languages You may use any language that is freely available on Windows, OSX, and Linux, to ensure fairness among each contestant. If the code is not freely runnable but can be compiled or packaged into a format that is, please include this format in your answer as well. Ideally, if you can compile your code into a more common language (i.e. CoffeeScript -> JavaScript), please do so. ## Scoring Your score will be the average number of eggs you collect out of ten runs. A run ends when all eggs are collected or when `(number of entries * 25)` turns have passed. I will manually make sure that it is possible to reach all eggs for each map (by continually generating maps until all eggs are reachable). ## Scoreboard A scoreboard will be added when all of the following conditions are met: * At least seven valid entries with a positive or zero score (not downvoted) have been submitted * At least 48 hours has passed since the creation of this challenge (UTC 14:23) The rules will not change during this pre-contest period, except to add clarification where a rule was unclear. ~~Once the scoreboard is put up, the testing program will also be posted here so that you can test your entries.~~ The testing code for this is still work-in-progress, but it's playable and it works. [Here's the GitHub repo.](https://github.com/KeyboardFire/easter-egg-hunt-on-the-hill/tree/master) [Answer] ## Cart'o'Gophers Here is another submission - and this one is actually meant to be competitive. Again, it's in Ruby. So run it with `ruby cartogophers.rb`. This took a lot longer than expected... ``` require 'zlib' require 'base64' def encode map, coords zipped = Zlib::Deflate.deflate map.join encoded = Base64.encode64(zipped).gsub("\n",'') "#{coords[:x]}|#{coords[:y]}|#{map.length}|#{encoded}" end def decode memory memory =~ /^(\d+)[|](\d+)[|](\d+)[|](.*)$/ coords = {x: $1.to_i, y: $2.to_i} n_rows = $3.to_i encoded = $4 decoded = Base64.decode64 encoded unzipped = Zlib::Inflate.inflate decoded n_cols = unzipped.length / n_rows; return unzipped.scan(/.{#{n_cols}}/), coords end def update map, fov, coords if coords[:x] < 2 map.map! { |row| '?' << row } coords[:x] += 1 elsif coords[:x] >= map[0].length - 2 map.map! { |row| row << '?' } end if coords[:y] < 2 map.unshift '?' * map[0].length coords[:y] += 1 elsif coords[:y] >= map.length - 2 map.push '?' * map[0].length end fov.each_index do |i| map[coords[:y]-2+i][coords[:x]-2, 5] = fov[i] end return map, coords end def clean_up map map.each do |row| row.gsub!('*', ' ') end end DIRECTIONS = [ [], [-1,-1], [ 0,-1], [ 1,-1], [ 1, 0], [ 1, 1], [ 0, 1], [-1, 1], [-1, 0], [ 0, 0] ] def move_to dir, coords { x: coords[:x] + DIRECTIONS[dir][0], y: coords[:y] + DIRECTIONS[dir][1] } end def get map, coords if coords[:x] < 0 || coords[:x] >= map[0].length || coords[:y] < 0 || coords[:y] >= map.length return '?' end map[coords[:y]][coords[:x]] end def set map, coords, value unless coords[:x] < 0 || coords[:x] >= map[0].length || coords[:y] < 0 || coords[:y] >= map.length map[coords[:y]][coords[:x]] = value end map[coords[:y]][coords[:x]] end def scan_surroundings map, coords not_checked = [coords] checked = [] cost = { coords => 0 } direction = { coords => 9 } edges = {} while not_checked.length > 0 current = not_checked.pop checked.push current (-1..1).each do |i| (-1..1).each do |j| c = { x: current[:x]+i, y: current[:y]+j } unless not_checked.include?(c) || checked.include?(c) if get(map, c) == '#' checked.push c elsif get(map, c) == '?' checked.push c edges[current] = { cost: cost[current], move: direction[current] } else not_checked.unshift c cost[c] = cost[current] + 1 if direction[current] == 9 # assign initial direction direction[c] = DIRECTIONS.find_index([i,j]) else direction[c] = direction[current] end if get(map, c) == 'o' return direction[c], if cost[c] == 1 then 'N' else 'A' end end edges[c] = { cost: cost[c], move: direction[c] } if c[:x] == 0 || c[:x] == map[0].length - 1 || c[:y] == 0 || c[:y] == map.length - 1 end end end end end # If no egg has been found return the move to the closest edge nearest_edge = edges.keys.sort_by { |c| edges[c][:cost] }.first if edges.length > 0 return edges[nearest_edge][:move], 'A' else # The entire map has been scanned and no more eggs are left. # Wait for the game to end. return 9, 'N' end end input = $<.read.split "\n" fov = input[0..4] memory = input[5] if memory map, coords = decode memory map, coords = update(map, fov, coords) else map = fov coords = {x: 2, y: 2} end clean_up map move, attack = scan_surroundings(map, coords) memory = encode map, move_to(move, coords) puts "#{move} #{attack} #{memory}" ``` This bot remembers what it has seen before and tries to construct a larger map at each turn. It then uses a breadth-first search for the nearest egg and heads that way. If there is no egg that can be reached on the current map, the bot heads for the nearest open edge of its map (so as to expand the map quickly in a direction it can still move). This bot has no concept of other bots yet and no fighting strategy either. Since I haven't found a reliable way to determine if my move has been successful, this can cause some problems. I simply always assume that the move has been successful - so if it wasn't new patches will be loaded into the map in the wrong places, which may or may not be harmful to pathfinding. The bot uses the memory to store the map and its new position on the map (assuming the move will be successful). The map is stored without line breaks, zipped and base64 encoded (along with the number of rows of the map, so that the line breaks can be reinserted). This compression brings the size down to about a third of the uncompressed map, so having a shade over 1000 bytes, I could store a map of about 3000 cells, which roughly corresponds to fully exploring a map with 18 bots. As long as there are nowhere near that many submissions, I don't think I can be bothered to figure out a fix for that case. ~~After a few test runs against 5 `dumbbot`s and 1 `naivebot` (my other submission), it either performed really badly (like 1 or 2 eggs) or outperformed the others by a considerable margin (7 to 9 eggs). I may think about a better fighting strategy and how I can determine if I actually moved or not. Both might be able to improve the score somewhat.~~ Oh and if you're wondering about the name of the bot, you should read The Order of The Stick ([last panel on this comic](http://www.giantitp.com/comics/oots0676.html)). **EDIT:** There were a few bugs with detecting the edges of the discovered map. Now that I've fixed them this bot always gets scores of about `20` against 5 `dumbbot`s and 1 `naivebot`. That's more like it! If you add `$stderr.puts map` to my bot now, you can really see how he systematically uncovers the map and collects all eggs in the meantime. I've also decided to choose `A` instead of `N` whenever not stepping onto an egg, to reduce the probability of moving back to the bot's original cell (which partly screws up the map). (It doesn't perform quite as well against 6 `naivebot`s, especially since it's very possible to end up in a "deadlock" with another bot when they both repeatedly want to grab an egg and choose `N`. I need to think about that...) [Answer] **Java Bunny** This bunny hasn't finished growing up yet (I still plan to make changes), but it's a starting point for right now. He looks for the closest egg and goes towards it. There isn't wall detection or out-of-bounds detection (yet). He'll go to pick up the egg he lands on, but otherwise he'll try to push he way around and attack anything else. If there are no nearby eggs, he'll start following the nearest bunny. They might know something that he doesn't. Otherwise, he'll just pick a random direction to walk. And he's pretty forgetful (no use of the memory variable). Plans moving forward: * Make decisions based on walls/out-of-bounds * Pick paths with a purpose, rather than randomly * Use the memory to determine the direction I was going before **Update 1** My bunny will follow other bunnies if he doesn't see an egg. Also refactored the "find nearest egg" code into it's own method. ``` import java.util.*; public class EasterEggHunt { // board chars public static final char EGG = 'o'; public static final char WALL = '#'; public static final char BUNNY = '*'; public static final char SPACE = ' '; public static final char OUT_OF_BOUNDS = 'X'; // player moves public static final char ATTACK = 'A'; public static final char COUNTER = 'C'; public static final char NOTHING = 'N'; // directions public static final int UPPER_LEFT = 1; public static final int UP = 2; public static final int UPPER_RIGHT = 3; public static final int RIGHT = 4; public static final int LOWER_RIGHT = 5; public static final int DOWN = 6; public static final int LOWER_LEFT = 7; public static final int LEFT = 8; public static final int STAY = 9; // the size of the immediate area // (I'll be at the center) public static final int VISION_RANGE = 5; public static void main(String[] args) { Scanner input = new Scanner(System.in); char[][] immediateArea = new char[VISION_RANGE][VISION_RANGE]; for (int i = 0; i < VISION_RANGE; ++i) { String line = input.nextLine(); for (int j = 0; j < VISION_RANGE; ++j) { immediateArea[i][j] = line.charAt(j); } } String memory = input.nextLine(); int moveDirection = decideMoveDirection(immediateArea, memory); System.out.println(moveDirection); char action = decideAction(immediateArea, memory, moveDirection); System.out.println(action); // change the memory? System.out.println(memory); } private static int decideMoveDirection(char[][] immediateArea, String memory) { // if there's a nearby egg, go towards it int direction = nearestBoardObject(immediateArea, EGG); // if we didn't find an egg, look for a bunny // (maybe he knows where to find eggs) if (direction == STAY) direction = nearestBoardObject(immediateArea, BUNNY); // otherwise, pick a random direction and go // we want to also have the chance to stop and catch our breath if (direction == STAY) direction = new Random().nextInt(STAY + 1); return direction; } private static int nearestBoardObject(char[][] immediateArea, char boardObject) { // start at the center and go outward (pick a closer target over a farther one) int spacesAway = 1; int meX = immediateArea.length / 2; int meY = immediateArea[meX].length / 2; while (spacesAway <= immediateArea.length / 2) { // I like to look right, and go clockwise if (immediateArea[meX][meY + spacesAway] == boardObject) return RIGHT; if (immediateArea[meX + spacesAway][meY + spacesAway] == boardObject) return LOWER_RIGHT; if (immediateArea[meX + spacesAway][meY] == boardObject) return DOWN; if (immediateArea[meX + spacesAway][meY - spacesAway] == boardObject) return LOWER_LEFT; if (immediateArea[meX][meY - spacesAway] == boardObject) return LEFT; if (immediateArea[meX - spacesAway][meY - spacesAway] == boardObject) return UPPER_LEFT; if (immediateArea[meX - spacesAway][meY] == boardObject) return UP; if (immediateArea[meX - spacesAway][meY + spacesAway] == boardObject) return UPPER_RIGHT; ++spacesAway; } // if the target object isn't in the immediate area, stay put return STAY; } private static char decideAction(char[][] immediateArea, String memory, int moveDirection) { char destinationObject = getDestinationObject(immediateArea, moveDirection); switch (destinationObject) { case EGG: // don't break the egg return NOTHING; default: // get really aggressive on everything else // other players, walls, doesn't matter return ATTACK; } } private static char getDestinationObject(char[][] immediateArea, int moveDirection) { // start at my spot (middle of the board) and figure out which direction I'm going int targetX = immediateArea.length / 2; int targetY = immediateArea[targetX].length / 2; switch (moveDirection) { case RIGHT: ++targetY; break; case LOWER_RIGHT: ++targetX; ++targetY; break; case DOWN: ++targetX; break; case LOWER_LEFT: ++targetX; --targetY; break; case LEFT: --targetY; break; case UPPER_LEFT: --targetX; --targetY; break; case UP: --targetX; break; case UPPER_RIGHT: --targetX; ++targetY; break; // otherwise we aren't moving } return immediateArea[targetX][targetY]; } } ``` [Answer] # `N`aiveBot (in Ruby) Here is a very simplistic bot to get the egg rolling (we want to hit those 7 submissions quick, right?). My Ruby isn't very idiomatic so this code may make proper rubyists cringe in pain. Read at your own risk. ``` input = $<.read $data = input.split("\n") def is_egg x, y $data[y+2][x+2] == 'o' end def is_wall x, y $data[y+2][x+2] == '#' end def is_empty x, y $data[y+2][x+2] == ' ' end def is_player x, y $data[y+2][x+2] == '*' end if (is_egg(-2,-2) || is_egg(-2,-1) || is_egg(-1,-2)) && !is_wall(-1,-1) || is_egg(-1,-1) dir = 1 elsif is_egg(0,-2) && !is_wall(0,-1) || is_egg(0,-1) dir = 2 elsif (is_egg(2,-2) || is_egg(2,-1) || is_egg(1,-2)) && !is_wall(1,-1) || is_egg(1,-1) dir = 3 elsif is_egg(2,0) && !is_wall(1,0) || is_egg(1,0) dir = 4 elsif (is_egg(2,2) || is_egg(2,1) || is_egg(1,2)) && !is_wall(1,1) || is_egg(1,1) dir = 5 elsif is_egg(0,2) && !is_wall(0,1) || is_egg(0,1) dir = 6 elsif (is_egg(-2,2) || is_egg(-2,1) || is_egg(-1,2)) && !is_wall(-1,1) || is_egg(-1,1) dir = 7 elsif is_egg(-2,0) && !is_wall(-1,0) || is_egg(-1,0) dir = 8 else dir = rand(8) + 1 end attack = 'N' puts "#{dir} #{attack} " ``` Run with `ruby naivebot.rb`. I'm simply hardcoding a few cases, where an egg is visible and not obstructed by a wall. It doesn't even go for the closest egg, but picks the first move that makes sense. If no such egg is found, the bot makes a random move. It disregards all other players and never attacks or counters. [Answer] # WallFolower (deliberate pun) in **Python 3**: ``` import sys import random #functions I will use dist = lambda p1,p2: max(abs(p2[1] - p1[1]), abs(p2[0] - p1[0])) distTo = lambda p : dist((2,2), p) cmp = lambda x,y : (x > y) - (x < y) sgn = lambda x : (-1,0,1)[(x>0)+(x>=0)] move = lambda p : (sgn(p[0] - 2), sgn(p[1] - 2)) unmove = lambda p : (p[0] * 2 + 2, p[1] * 2 + 2) outputmove = lambda p : (1,2,3,8,9,4,7,6,5)[(sgn(p[0] - 2) + 1) + 3*(sgn(p[1]-2) + 1)] def noeggfinish(move): print(outputmove(unmove(move))) print('ACN'[random.randint(0, 2)]) print("1"+move) sys.exit(0) #beginning of main body view = [list(l) for l in map(input, ('',)*5)] #5 line input, all at once. memory = input() #currently used only as last direction moved in a tuple eggs = [] enemies = [] for y in range(5): for x in range(5): if view[y][x] == 'o': eggs += [(x,y)] elif view[y][x] == '*': enemies += [(x,y)] eggs.sort(key = lambda p:distTo(p)) #sort by how close to me they are. tiedeggs = [] end = 0 for egg in eggs[:]: if end:break for enemy in enemies: exec({ -1: 'eggs.remove(egg)', 0: 'tiedeggs += egg', 1: 'end=1' }[cmp(dist(enemy, egg), distTo(egg))]) if end:break if eggs: print(outputmove(eggs[0])) print('N') #no attack here print("0"+move(eggs[0])) sys.exit(0) elif tiedeggs: print(outputmove(tiedeggs[0])) print('N') #no attack here print("0"+move(tiedeggs[0])) sys.exit(0) #now there are no eggs worth going for #do a LH wall follow lastmove = eval(memory[1:]) #used to resolve ambiguity if lastmove[0] and lastmove[1]: lastmove[random.randint(0,1)] = 0 #disregard diagonal moves if eval(memory[0]): exec("check=view[%n][%n]"%{(0,-1):(0,0),(1,0):(4,0),(0,1):(4,4),(-1,0):(0,4)}[lastmove]) if check == '#': noeggfinish(lastmove) else:pass #currently unimplemented #move randomly noeggfinish(tuple([(x,y) for x in [-1,0,1] for y in [-1,0,1] if (x,y) != (0,0))) ``` Moves to an egg if there is an egg in sight, but only if it is closer to that egg than another robot. If there is a tie in distance, it goes for it anyways. Otherwise, does a LH wall follow (not currently well implemented). Still needs work on the wall follow, but I'll post this here anyways. ]
[Question] [ The [flick input method](https://en.wikipedia.org/wiki/Japanese_input_method#Flick_input) is a way of inputting Japanese kana on a modern smartphone. It is arranged in a 12-key layout, with the following labels: ``` あかさ たなは まやら 小わ、 ``` When a key is tapped, it produces its respective kana. However, when the key is flicked in one of the four cardinal directions (up, down, left, right) it produces the kana with the respective vowel: ``` u iae o ``` where the center vowel is the key, just tapped and not flicked. So, when the `か` key is swiped up, it will produce the `く` kana. A special key is the `小` key. By default, just tapping on the `小` key will cycle the previous kana between it's "small" and "large" forms. Swiping down-left will apply a dakuten, and down-right a handakuten, if it can be applied to the kana. For this challenge, the `小` key will have the following flick mapping: ```  小 ゛小゜  ゛ <-- this is a dakuten ``` Kana with dakuten, handakuten, and small forms are in the table below. If the kana does not have a small form when `小` is pressed, it is a NOP. Similarly, if a kana does not have a dakuten or handakuten form when one is applied, it is also a NOP. Some keys have either a special layout and punctuation characters assigned to them: [![flick input from wikimedia commons](https://i.stack.imgur.com/UYkAC.png)](https://i.stack.imgur.com/UYkAC.png) Image source: [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Flick_keyboard_kayout.svg) Note here that the `や` and `わ` keys have punctuation assigned: ```  ゆ (や) <-- unicode FF08, FF09  よ  ん をわー <-- unicode 30FC  〜  <-- unicode 301C ``` You *will* need to handle punctuation, but only on `や` and `わ`. **This challenge will not be using the `、` key.** ## Hiragana Hiragana is Japanese's native syllabic writing system. Most hiragana can be considered as a pair of a consonant and a vowel: | | a | i | u | e | o | | --- | --- | --- | --- | --- | --- | | **∅** | あ | い | う | え | お | | **k** | か | き | く | け | こ | | **s** | さ | し | す | せ | そ | | **t** | た | ち | つ | て | と | | **n** | な | に | ぬ | ね | の | | **h** | は | ひ | ふ | へ | ほ | | **m** | ま | み | む | め | も | | **y** | や | | ゆ | | よ | | **r** | ら | り | る | れ | ろ | | **w** | わ | | | | を | "ん" is special because it is the only hiragana without a vowel. Some hiragana can have a diacritic applied called a "dakuten" or "handakuten" that either voices the consonant (e.g. "k" to "g") or "half-voices" the consonant (only for h-series kana, from "h" to "p"). Some kana also have a small form (applies to vowels, y-series kana, and つ). | Kana | Dakuten | Handakuten | Small | | --- | --- | --- | --- | | あいうえお | | | ぁぃぅぇぉ | | かきくけこ | がぎぐげご | | | | さしすせそ | ざじずぜぞ | | | | たちつてと | だぢづでど | | っ | | はひふへほ | ばびぶべぼ | ぱぴぷぺぽ | | | やゆよ | | | ゃゅょ | ## Input Input is a string of hiragana using any [reasonable input format](https://codegolf.meta.stackexchange.com/q/2447/77309): a string, a list/array of characters, a sequence of raw Unicode bytes, etc. ## Output Output is a sequence of inputs for the 12-key flick input method. You may use any [reasonable output format](https://codegolf.meta.stackexchange.com/q/2447/77309). However, each input in the sequence *must* be at least 2 distinguishable parts, and must encode at minimum the following: * Which key is tapped, and * Which direction it is swiped, if at all. You must specify what encoding you use for your output. (The two-part output is to prevent mapping kana to a single value one-to-one.) ## Test Cases For these test cases, output will be in the format of space-separated `KD`, where `K` is the kana's consonant (or "a" if it is `あ`), and `D` is one of `58426` (directions on a numpad, 5 for no swipe). The `小` key will be represented as `x`. ``` かな --> k5 n5 ありがとう --> a5 r4 k5 x4 t2 a8 ありがとうございます --> a5 r4 k5 x4 t2 a8 k2 x4 s5 x4 a4 m5 s8 だがことわる --> t5 x4 k5 x4 k2 t2 w5 r8 おまえはもうしんでいる --> a2 m5 a6 h5 m2 a8 s4 w8 t6 x4 a4 r8 かかります --> k5 k5 r4 m5 s8 あ --> a5 た --> t5 っ --> t8 x5 ぬ --> n8 ぎゅうにゅ --> k4 x4 y8 x5 a8 n4 y8 x5 やつた --> y5 t8 t5 やづた --> y5 t8 x4 t5 やった --> y5 t8 x5 t5 は --> h5 ば --> h5 x4 ぱ --> h5 x6 (わらい) --> y4 w5 r5 a4 y6 どじゃあぁーん〜 --> t2 x4 s4 x4 y5 x5 a5 a5 x5 w6 w8 w2 を --> w2 ``` This is a related inverse of [this post for keitai to kana](https://codegolf.stackexchange.com/q/262329/77309). [Answer] # [Python 3](https://docs.python.org/3/), ~~511~~ 410 chars ``` [print('わあ わい わう やい やえ わお わえ ああ小あああ あい小ああい あう小ああう あえ小ああえ あお小ああお かあ かあ小おかい かい小おかう かう小おかえ かえ小おかお かお小おさあ さあ小おさい さい小おさう さう小おさえ さえ小おさお さお小おたあ たあ小おたい たい小おたう小あたう たう小おたえ たえ小おたお たお小おなあ ない なう なえ なお はあ はあ小おはあ小えはい はい小おはい小えはう はう小おはう小えはえ はえ小おはえ小えはお はお小えはお小えまあ まい まう まえ まお やあ小あやあ やう小あやう やお小あやお らあ らい らう らえ らお'[x:x+4])for x in[(ord(x)-126)%188%153%111%87%85*4for x in input()]] ``` [Try it online!](https://tio.run/##TZTbbtNAEIZfJTdRExAXpi1EvEqUO4ToTRJFQQp3/Tfudu20FFrMGZZjC@bQcj4F8zC/uO4jBHs7hpEszfj/d@ebjEcZXh1fHvSXF4vucLTWH7eWaHYI02iEGEu0VYzlvYxO9FRi9Q5TPn@Odk6SkxpVjJUWi2aVZkVzSqvrpUqrWJhJ3VnNSkMeixYrzYpmleZEc0qr66a1lgkjU4xMGJliZMLIFCMTRqYYmTAyxfDC8IrhheEVw6tZeeF5xfPC84rnhecVLxdeLoxcauVyP5c7h3LuUPX1L3chj8WPlR8r34pvlW@V78R3ynfKr/tItVbnhfRXSB@F8AqpW8hOxv93MeSiWaXVO50qLdxN5Hwi@57I2UT2vozpUndyYXJ6pde@NBg1Jo21frc1GF1sTdpnorPn2s2o02lGq8vNKIqanfPNzuqplfpg@QyvjFvtXm@x4PoDAuHjTksYsVGiiM3wU5N6QbeIbeIaUbZ5nbhB7BJ7xM2wUreI28Qd4i5xj7hPlDUfEo/CAjwmnhBPiWfEc@IFsU8cEC@JV@GrvybeEG@Jd2HQR8R74gPxkfhEfCa@EF@Jb8R34gfxk5gTv8Kkf9Os04CmHN60mp/ZoLE0mzSuGpNJaWY0WzTb1b@E2aXZ43R@PHfH8@Qv "Python 3 – Try It Online") more bytes since using kana as output, but they are just for output. it works the exact same in 511 bytes if you use boring ascii: # [Python 3](https://docs.python.org/3/), ~~511~~ 410 bytes ``` [print('wa wi wu yi ye wo we aaxaaa aixaai auxaau aexaae aoxaao ka kaxoki kixoku kuxoke kexoko koxosa saxosi sixosu suxose sexoso soxota taxoti tixotuxatu tuxote texoto toxona ni nu ne no ha haxohaxehi hixohixehu huxohuxehe hexohexeho hoxehoxema mi mu me mo yaxaya yuxayu yoxayo ra ri ru re ro'[x:x+4])for x in[(ord(x)%188-126)%188%153%111%87%85*4for x in input()]] ``` [Try it online!](https://tio.run/##NdDZbtNQFAXQX/GL1QTEg2kLEb8S5eFKGNmy7BvZN6r91n3TIelAoWUsQ8s8zzME@Jj9Af2EsP2A5KNtnbPu8TBsXGKLxfm8PyzTwnUWVkwQrKSqURA0yibWvVUpjamN0dykSs3MSClnYmU7t0rZzLRV20wmS5Uy2Ugpk8XK1tjaVnKVXCVXyVVylVwlV8lVcpWck3NyTs7JOT3XySqtk3WyTtbJFrKFXKF5oVmhfmLaqq0qTjRLtEMVJzKJdqjiRDbRHlWctGdsm3Wc62yuM7lsLpNr1ug/NOo3eo@m/U/67kb9Ur1StlSvlC3tQr@@UJ9eGnQv2TKog7Tod2x5sVN3z0Rnz3XDqNcLo@XFMIqisHc@7C2fWvoPdQ1HrtMdDOZzrt4lQHhiTKwR68QGsUlMiCmxRWwTO8QucZnYI64QV4l94oC4RlwnbhA3iVvEbeKQuENo5z3iPnFEHBMPiIfEI@Ix8YR4SjwjnhMviJfEK@I18YZ4S7wj3hMfiI/EJ@Iz8YX4SnwjvhM/iJ/EL2JG/Cb@EH/pV@lB7@nH9Gv06/Qb9Jv0E/op/Rb9Nv0O/S79Hv0@/QHHs5PZ5GQ2/Qc "Python 3 – Try It Online") it gives you 4 chars of output for every char of input, and you read it in pairs; ie if you give it `ぁあ` it'll give you `ああ小あ` and `ああ` meaning the first char is made by selecting the あ key in the あ direction and the 小 key in the あ direction and that the second char is just selecting the あ key in the あ direction. (so the first is one of あかさたなはまやら小わ and the second is one of あいうえお). the tio links just have all the characters for your convenience. they're ordered by unicode codepoint, lowest to highest. any other characters you put in there will just tell you about a random key. I tried to find something mathematically that would let me build the first then the second char but there's so many exceptions that it's faster to just manually map each one. -101 bytes because I finally got around to swapping out the if statements for modulus operations Explanation: ``` [ #open main for loop print( #open print statement 'は...え' #list of instructions, spaced at 4 chars per instruction [x:x+4] #chars from index x to index x+4 ) #end of print statement; print the slice we just indexed for x in[ #says 'do the previous on each item in the coming list' (ord(x)-126)%188 #188 is a magic number mapping the output of ord to unique values in a small range. subtracting 126 keeps the consecutive kana consecutive. %153%111%87%85 #these slot the rest of the values which were at random locations into the start of the string. *4 #spaces out the values we are indexing into for x in input() #input() defaults to a string, so to iterate against it you have to add this extra loop ] #close the input for loop and make it into a list for the main loop to iterate on ] #close main for loop and save it as a list into a non-existent variable; we're sending output as we go along with the print statement so we don't need it ``` since it's just manually mapping to the string, adding in the punctuation key doesn't cost that much: # [Python 3](https://docs.python.org/3/), 444 chars ``` [print('わえ 、あ 、い やい やえ 、う 、お わお ああ小あああ あい小ああい あう小ああう あえ小ああえ あお小ああお かあ かあ小おかい かい小おかう かう小おかえ かえ小おかお かお小おさあ さあ小おさい さい小おさう さう小おさえ さえ小おさお さお小おたあ たあ小おたい たい小おたう小あたう たう小おたえ たえ小おたお たお小おなあ ない なう なえ なお はあ はあ小おはあ小えはい はい小おはい小えはう はう小おはう小えはえ はえ小おはえ小えはお はお小えはお小えまあ まい まう まえ まお やあ小あやあ やう小あやう やお小あやお らあ らい らう らえ らお , わあ . . わい わう 、え '[x:x+4])for x in[(ord(x)%195-60)%152%126%116%95*4for x in input()]] ``` [Try it online!](https://tio.run/##TZPZbtNQEIZfxTdREzaR0kQqrxLlDiF6k0ZRkMJd/hPXtZ2WQIvZ4bAWCEvLvpnwLvziOo8Qjk/GdCRHM/n/OfMdjcfdK/1Lm51zi0Wr29vo9KsrNBMiDgIOQRiJoYsmPI6lH0lMC32yjDDu@Xs0WSbLHkUMlRaKFiktEi1WWixaqjTPGEvfcclKfR6KFiotEi1SWixarLSyb1pqmTAyxciEkSlGJoxMMTJhZIqRCSNTDCsMqxhWGFYxrJqVFZ5VPCs8q3hWeFbxpsKbCmMqvaZyfipnDqXuUN3rfx77PBQ/VH6o/Ej8SPmR8mPxY@XHyi/vkWqtzGdyv5ncYya8mfSdyU6Gx7voc9EipUWipUrzZxOpT2TvE6lNlowiurpTgey@qz0TLH/@fyix/EbcmZXW4Pzg5Fq7dnGzFwyCjU6rutm7UB3UKvX1xunmWRcbq5X6arNSrzcr640Ta2Whe7qX@9Vau71Y/BkeFA2HhsP7BPxOjByP2HI0YttPKCn3eofYJa4S7i7XiOvEHrFP3PCbeJO4Rdwm7hB3iXuE6/mAeOj35hHxmHhCPCWeEc@JA@IF8ZJ45ZflNfGGeEu88@/niHhPfCA@Ep@Iz8QX4ivxjfhO/CB@Ejnxy7@g3zRDGtC4mY@KsZstmohmmyYupmtSmjHNDs1uMUizR7PPUT7PMc/jeZ7Mc/sP "Python 3 – Try It Online") the moduluses you preform on ord are different (`(ord(x)%195-60)%152%126%116%95`) but the idea is the same. the additional characters were added to the test cases on the tio link [Answer] # [Go](https://go.dev) + `golang.org/x/text/unicode/runenames`, 603 bytes ``` import(."strings";."golang.org/x/text/unicode/runenames") func f(s []rune)(o string){V,F,C,K,G,Q,I:="AIUEO","54862",Fields(".KS TNH MYR XW."),"KSTH","GZDB",CutPrefix,Index for _,k:=range s{n,_:=Q(Name(k),"HIRAGANA LETTER ") n,s:=Q(n,"SMALL ") a,v:=IndexByte(G,n[0]),n[1:] if len(n)==1{if n=="N"{o+="W8"}else{o+="A"+string(F[I(V,n)])}}else if k=='ー'{o+="W6"}else if k=='〜'{o+="W2"}else if k=='('{o+="Y4"}else if k==')'{o+="Y6"}else{if v=string(F[I(V,v)]);a<0{if n[0]=='P'{o+="H"+v+"X6"}else{for _,R:=range C{if i:=I(R,n[0:1]);i>-1{o+=R[i:i+1]+v}}}}else{o+=K[a:a+1]+v+"X4"}} if s{o+="X5"}} return} ``` [You Cannot Attempt This Online!](https://ato.pxeger.com/run?1=dVTdittGFIb2yn6K6cASCU-8sZGMcToBZbO7Nlq7G1uN7XpNEF7ZiPWOHUs2DkYQKW1Jdkt70dIfGujSNPQX0l4WQh-kt_MAfYWemdFm7UCwsGa-c75zvjlzjr7_cTS5-HvqDk7ckYdOXZ9l_dPpZBbm8fA0xC_m4fB6-d93egrU8jgIZz4bBfhmHo8mY5eN8pPZaHu5HXrLcHvO_MHk2NuezZnH3FMvwHp2OGcDNNQC1OsLWNcmSMXQV_fIHtkhNtknd0mtQrFV-3D3A0ywaZRLRUz2fG98HGg4b7eQ06iiereJOu081gm2W04VHPc_unMbk515eDjzhv6S1Nixt8wOJzN0n5xU6AzkeShYMXK_Qu9qDVCknQC7Wmta-1bDQge7jrPbRKCSkUC4MIJbdevgQEAuWVSojHj7Yehp-4T1bvR1-C9U-ll_iMYe05hOaWEFG0YpbuDVJEdxu4wjbxx4cmPhnDqttterafcI0_t6JM0IWCeUXuOPX11TvBLeNDx6lhqKm4b_Xj1Rhq7xpuFpakhDCWULuiFgAQJuuu_fkKLhQEA7VKQqzi1yuHNJVVVsXlZxRxB8KIjWFIWoFCCMf-t6QVCbPb_i5wr93CKKotdnt3tuxZUoRAWlkShaIFN1TLGdeeF8xqK0x95NwodTDzmiO-aDcIV8NiXIW07TdkFRVvWSaFJNR6tsJvSCMEAVCq3lwDazwjw-5_FvmCBsmw1IQlI04ckZjz_j8S88_lSYLbNp2GbHcIpW-S1uPP6Kx1_z-GMe_8Pj795k2cWO0YK1ZdTN1lqMCxngSxEj-YIn54LngJ_g2UWn2Daba95nMvgTHr_kSSKTfsMTIP8s8iqyVaybVqlq1iFpy2iXnZJIuh7kXDzJ2ZVO27RB6aauRB3gCvhBKbsCnkug3FmD_hBQYy3K5zz5RMr8HRYyldExusCxyg35fu2aQN1-SrN0TafsbJperJmgoJvG5-tGc13jSwFX14A_FSAa7BL6K4VKlxAMjLyLp1BUmBEZ2YB7MC2jW7ri_crjb3nyWLRBHMNYiot49EwWRdy1OKgJB4Vfx2yX2mUxl8CFvswcQoeGY6ZhSilqOVbTQbCCj0hGjREKRZuqSVJdK_rVHUh4qKlPoxbmoed1IGVgUsK86P33KBJewlslGWp4K0RbDxC9dcTgfcS0rQf6EQOZkkEp-Iu1HJ90DbiIGgmxm1rRbuMOSrVGWTWKFxfq_T8) [Do it on the Playground instead!](https://go.dev/play/p/L_aFSkxM0Tw) An extremely scuffed, straightforward solution. Uses the `Name` function from `golang.org/x/text/unicode/runenames` to get the name of each kana, then selects the flick input based on that. Output is a concatenated string of the form `Cn` where `C` is the uppercase consonant of the flick input, and `n` is one of `54862`. ## Ungolfed Explanation ``` func f(inputString []rune) (o string) { VOWEL := "AIUEO" FLICKS := "54862" CONSONANTS := Fields(".KS TNH MYR XW.") UNVOICED := "KSTH" VOICED := "GZDB" // for each kana in the string... for _, kana := range inputString { // cutout the Unicode prefixes name, _ := CutPrefix(Name(kana), "HIRAGANA LETTER ") // we need to know if it's a small kana or not name, hasSmall := CutPrefix(name, "SMALL ") // we also need to know if it's a voiced ("GZDB") kana voicedIndex := IndexByte(VOICED, name[0]) // and the vowel of the kana vowel := name[1:] // if the kana is あいうえお or ん, just output it if len(name) == 1 { if name == "N" { o += "W8" } else { o += "A" + string(FLICKS[Index(VOWEL, name)]) } // special cases for punctuation } else if kana == 'ー' { o += "W6" } else if kana == '〜' { o += "W2" } else if kana == '(' { o += "Y4" } else if kana == ')' { o += "Y6" // if not a voiced kana... } else if voicedIndex < 0 { // if it's a handakuten kana, add to the output immediately if name[0] == 'P' { o += "H" + string(FLICKS[Index(VOWEL, vowel)]) + "X6" // otherwise, find the kana's location } else { for _, row := range CONSONANTS { i := IndexByte(row, name[0]) if i > -1 { // if the (unvoiced) consonant is found, add it to the output o += row[i:i+1] + string(FLICKS[Index(VOWEL, vowel)]) } } } } else { // otherwise, it's a voiced kana, and needs the extra X o += UNVOICED[voicedIndex:voicedIndex+1] + string(FLICKS[Index(VOWEL, vowel)]) o += "X4" } // if it's small, add the extra X. if hasSmall { o += "X5" } } return o } ``` [Do the ungolfed version on the Playground!](https://go.dev/play/p/dhF8blcIuvJ) ]
[Question] [ Given a string, your task is to collapse it into a zigzag-like structure as described below. ## Folding into a Zigzag We'll take the string `"Mississippi"` as an example: 1. First, output the longest prefix consisting of unique characters only: ``` Mis ``` 2. When you reach the first duplicate character **C**, ignore it, and output the longest prefix consisting of unique characters of the remaining string (`issippi`) vertically, below the first occurrence of **C**: ``` Mis i s ``` 3. Repeat the process, alternating between horizontal and vertical continuation. But now be careful (at step 1) to continue outputting horizontally from latest occurrence of the duplicate character, which is not necessarily the last one, as in this case: ``` Mis i sip ----- Mis i sip i ``` ## Rules * The string will only contain printable ASCII characters, but won't contain any kind of whitespace. * You can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and in any reasonable format1, while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) for *every language* wins. * 1 Input: String / List of characters / whatever else your language uses to represent strings. Output: Multiline string, list of strings representing lines or list of lists of characters/length-1 strings, but please include a pretty-print version of your code in your answer, if possible. * Regarding additional spaces, the output may contain: + Leading / trailing newlines + Trailing spaces on each line / at the end + A *consistent* number of leading spaces on each line * You must begin to output horizontally, you may **not** start vertically. ## Test cases Inputs: ``` "Perfect" "Mississippi" "Oddities" "Trivialities" "Cthulhu" "PPCG" "pOpOpOpOpOpOp" "ABCCCE" "ABCCCECCEEEEC" "abcdcebffg" "abca" "AAAAAAAA" ``` Corresponding outputs: ``` Perf c t ``` ``` Mis i sip i ``` ``` Od ies t ``` ``` Triv a l ies t ``` ``` Cthul u ``` ``` P C G ``` ``` pO OpO pOp p ``` ``` ABC C E ``` ``` ABC CCE E EC ``` ``` abcd e b fg ``` ``` abc ``` ``` A AA A ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 143 bytes ``` {#}//.{q___,a_,r___,a_,Longest@s___}:>{q}~f@{a,r}~{{s}}//.{q_~f@a_~s_}/;s~FreeQ~f:>(PadLeft@{q~Join~#,##2}&)@@PadRight@Join[{a},s]/. 0->" "& ``` [Try it online!](https://tio.run/##TU5fS8MwEH/vpygpjA3iKj5uOKJBBZmsbr7VUm5t0ga2bk1SX0Ly6qMf1Y9QExjq3Y/7/TkO7gi6ZUfQooKRD111Ox1NYtN0bvqyLDGUWF54feoapjRR3tvFyvTWcWIAS@uMUfZy4zMonSptulTuUTL26vhiNc2gXjOuiend80l0LsFJcmMnM0L8ZiuaVpOQ5wYsVt9fn0U6j6@vVihGk3G2jDIpOp3vtKdmKzg/sDw8S2gLEirNpCJJgWP03iE/Y1RMUmKiCGVMclZphCP0IpQKOJ9FsJu6FlowFfSbFB8CDr@e6nY4tEOQWUafAp83/zoEd/eU0oc/5eGLhgD2VV2xPefNxQGKIjv@AA "Wolfram Language (Mathematica) – Try It Online") Contains `0xF8FF`, which corresponds to the `\[Transpose]` operator. Phew, it was tough making the result into a string. Getting each branch isn't so tough: `#//.{q___,a_,r___,a_,Longest@s___}:>{q,a,{r},{s}}&` [Answer] # [Python 2](https://docs.python.org/2/), 131 bytes ``` X=Y=y=0 s=input() o=() l={} for i in s:o+=[' ']*len(s),;exec('l[i]=X,Y','y^=1;X,Y=l[i];l={}')[i in l];o[Y][X]=i;X+=y<1;Y+=y print o ``` [Try it online!](https://tio.run/##HYvBCgIhGITvPoW3X9s9tB2z/1DSOyhilzASRGU1SKJnN7dhmBkGvtzqM8VD7wo1NtyTgj7mV2WcJBwR8PMlj7RST32k5ZgmNEDB7oKLrPBZuLe7MwjGW1SzhhnaDRcxJm6f2Hjg5k8HK5LR1iiLXqgJ22kRehTJq4@Vpt7hfJFSXoeHJPwA "Python 2 – Try It Online") -1 thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn). Prints as a tuple of lists of length-1 strings. [Pretty-printed output](https://tio.run/##RUzBCsIwFLvvK3p7rRviPK6@gxb/oaXUi0x8UtqyTbCI3147L4aQhECS8nKPYV@KRoMZd82MFNJz4aKJWMXj@9Pc4sSIUWDzEFu0wMBt/Bj4LDo5vsYrB2/Joe4MdJAv2Msace3kugdhf2vvZLTGWe2QpG4xH3ppqv3/45AmCgvA9hEpcBKlwPGklDpXVij4Ag). [Answer] # [Python 2](https://docs.python.org/2/), ~~184~~ ~~176~~ ~~175~~ 168 bytes -5 bytes thanks to Mr. Xcoder ``` def f(x):i,k=[p for p in enumerate(map(x.find,x+"z"))if cmp(*p)][0];return[x[:i]+' '*len(x)]+[' '*k+''.join(d)+i*' 'for d in zip(*f(x[i+1:]))]if x[len(set(x)):]else[x,] ``` [Try it online!](https://tio.run/##TVDBTsMwDL33K6Je2rTVBByLdoAKcULbgVvIoWscatamUZJC2c8XZxsIx1L8nl6e7djv0E/mbl0VaKbzhddYHbfCMj05ZhkaBmYewbUB8rG1@bLRaFS1lOkp5Rw160abF5ZLcSPvHYTZGbGIGmWZsawYwJClLEUExzLLNh8TmlzxEguiYg8Ve5yQTKi7wPK2lpxLMl5EfO0hkAOvJQwexFLJNYAPfivSPTgNXUir9AW9j2ktEtophQHBU/nq8BPb4Rc2oZ@HfqZqv2@e6bK7f4fww2PTNE9/BSVFQ7g9dKqDg9bvF9BGzTVSmcQ94lhxlfN4dcKsQxPOqMreTJacP9RNX1Gj88jz@qIh8ionIUnXHw "Python 2 – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 81 bytes ``` {_,_S*a*a\+{__L#){V!:V;L#)LM:L;=~:U;:T}{[TU]a+L+:L}?;U@_U=T4$tt\;TV!+:T;UV+:U;}*} ``` [Try it online!](https://tio.run/##S85KzP1f9L86Xic@WCtRKzFGuzo@3kdZszpM0SrMGsjw8bXysbatswq1tgqprY4OCY1N1PbRtvKptbcOdYgPtQ0xUSkpibEOCVPUtgqxDg3TBqqs1ar9X5fw39HJ2dnZFYiAwBkA "CJam – Try It Online") ]
[Question] [ # Description Let a permutation of the integers `{1, 2, ..., n}` be called *minimally interpolable* if no set of `k+2` points (together with their indices) fall on a polynomial of degree `k`. That is, 1. No two points fall on a horizontal line (0-degree polynomial) 2. No three points fall on a line (1-degree polynomial) 3. No four points fall on a parabola (2-degree polynomial) 4. Et cetera. --- # Challenge Write a program that computes OEIS sequence [A301802(n)](https://oeis.org/A301802), the number of minimally interpolable permutations of `{1, 2, ..., n}` for `n` as a large as possible. --- # Scoring I will time your code on my computer (2.3 GHz Intel Core i5, 8 GB RAM) with increasing inputs. Your score will be the greatest input that takes less than 1 minute to output the correct value. --- # Example For example, the permutation `[1, 2, 4, 3]` is minimally interpolable because ``` the terms together with their indices [(1, 1), (2, 2), (3, 4), (4, 3)] have the property that (0) No two points have the same y-value. (1) No three points lie on a line. (2) No four points lie on a parabola. ``` [![Example illustrating that [1,2,4,3] is minimally interpolable.](https://i.stack.imgur.com/NiWY5.png)](https://i.stack.imgur.com/NiWY5.png) In the illustration, you can see that the horizontal lines (red) have at most one point on them, the lines (blue) have at most two points on them, and the parabolas (green) have three points on them. --- # Data Here are the minimally interpolable permutations for `n=3`, `n=4`, and `n=5`: ``` n = 3: [1,3,2],[2,1,3],[2,3,1],[3,1,2] n = 4: [1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,4,1,3],[2,4,3,1],[3,1,2,4],[3,1,4,2],[3,2,4,1],[3,4,1,2],[3,4,2,1],[4,1,3,2],[4,2,1,3],[4,2,3,1],[4,3,1,2] n = 5: [1,2,5,3,4],[1,3,2,5,4],[1,3,4,2,5],[1,4,2,3,5],[1,4,3,5,2],[1,4,5,2,3],[1,4,5,3,2],[1,5,3,2,4],[2,1,4,3,5],[2,3,1,4,5],[2,3,5,1,4],[2,3,5,4,1],[2,4,1,5,3],[2,4,3,1,5],[2,4,5,1,3],[2,5,1,3,4],[2,5,1,4,3],[2,5,3,4,1],[2,5,4,1,3],[3,1,4,5,2],[3,1,5,2,4],[3,1,5,4,2],[3,2,5,1,4],[3,2,5,4,1],[3,4,1,2,5],[3,4,1,5,2],[3,5,1,2,4],[3,5,1,4,2],[3,5,2,1,4],[4,1,2,5,3],[4,1,3,2,5],[4,1,5,2,3],[4,1,5,3,2],[4,2,1,5,3],[4,2,3,5,1],[4,2,5,1,3],[4,3,1,2,5],[4,3,1,5,2],[4,3,5,2,1],[4,5,2,3,1],[5,1,3,4,2],[5,2,1,3,4],[5,2,1,4,3],[5,2,3,1,4],[5,2,4,3,1],[5,3,2,4,1],[5,3,4,1,2],[5,4,1,3,2] ``` If my program is correct, the first few values of `a(n)`, the number of minimally interpolable permutations of `{1, 2, ..., n}`: ``` a(1) = 1 a(2) = 2 a(3) = 4 a(4) = 18 a(5) = 48 a(6) = 216 a(7) = 584 a(8) = 2870 ``` [Answer] ## C# ``` using System; using System.Diagnostics; using BigInteger = System.Int32; namespace Sandbox { class PPCG160382 { public static void Main(params string[] args) { if (args.Length != 0) { foreach (var arg in args) Console.WriteLine(CountValidPerms(int.Parse(arg))); } else { int[] smallValues = new int[] { 1, 1, 2, 4, 18, 48 }; for (int n = 0; n < smallValues.Length; n++) { var observed = CountValidPerms(n); var expected = smallValues[n]; Console.WriteLine(observed == expected ? $"{n}: Ok" : $"{n}: expected {expected}, observed {observed}, error {observed - expected}"); } for (int n = smallValues.Length; n < 13; n++) { Stopwatch sw = new Stopwatch(); sw.Start(); Console.WriteLine($"{n}: {CountValidPerms(n)} in {sw.ElapsedMilliseconds}ms"); } } } private static long CountValidPerms(int n) { // We work on the basis of exclusion by extrapolation. var unused = (1 << n) - 1; var excluded = new int[n]; int[] perm = new int[n]; // Symmetry exclusion: perm[0] < (n+1) / 2 if (n > 1) excluded[0] = (1 << n) - (1 << ((n + 1) / 2)); long count = 0; CountValidPerms(ref count, perm, 0, unused, excluded); return count; } private static void CountValidPerms(ref long count, int[] perm, int off, int unused, int[] excluded) { int n = perm.Length; if (off == n) { count += CountSymmetries(perm); return; } // Quick-aborts var completelyExcluded = excluded[off]; for (int i = off + 1; i < n; i++) { if ((unused & ~excluded[i]) == 0) return; completelyExcluded &= excluded[i]; } if ((unused & completelyExcluded) != 0) return; // Consider each unused non-excluded value as a candidate for perm[off] var candidates = unused & ~excluded[off]; for (int val = 0; candidates > 0; val++, candidates >>= 1) { if ((candidates & 1) == 0) continue; perm[off] = val; var nextUnused = unused & ~(1 << val); var nextExcluded = (int[])excluded.Clone(); // For each (non-trivial) subset of smaller indices, combine with off and extrapolate to off+1 ... excluded.Length-1 if (off < n - 1 && off > 0) { var points = new Point[off + 1]; var denoms = new BigInteger[off + 1]; points[0] = new Point { X = off, Y = perm[off] }; denoms[0] = 1; ExtendExclusions(perm, off, 0, points, 1, denoms, nextExcluded); } // Symmetry exclusion: perm[0] < perm[-1] < n - 1 - perm[0] if (off == 0 && n > 1) { nextExcluded[n - 1] |= (1 << n) - (2 << (n - 1 - val)); nextExcluded[n - 1] |= (2 << val) - 1; } CountValidPerms(ref count, perm, off + 1, nextUnused, nextExcluded); } } private static void ExtendExclusions(int[] perm, int off, int idx, Point[] points, int numPoints, BigInteger[] denoms, int[] excluded) { if (idx == off) return; // Subsets without ExtendExclusions(perm, off, idx + 1, points, numPoints, denoms, excluded); // Just add this to the subset points[numPoints] = new Point { X = idx, Y = perm[idx] }; denoms = (BigInteger[])denoms.Clone(); // Update invariant: denoms[s] = prod_{t != s} points[s].X - points[t].X denoms[numPoints] = 1; for (int s = 0; s < numPoints; s++) { denoms[s] *= points[s].X - points[numPoints].X; denoms[numPoints] *= points[numPoints].X - points[s].X; } numPoints++; for (int target = off + 1; target < excluded.Length; target++) { BigInteger prod = 1; for (int t = 0; t < numPoints; t++) prod *= target - points[t].X; Rational sum = new Rational(0, 1); for (int s = 0; s < numPoints; s++) sum += new Rational(prod / (target - points[s].X) * points[s].Y, denoms[s]); if (sum.Denom == 1 && sum.Num >= 0 && sum.Num < excluded.Length) excluded[target] |= 1 << (int)sum.Num; } // Subsets with ExtendExclusions(perm, off, idx + 1, points, numPoints, denoms, excluded); } private static int CountSymmetries(int[] perm) { if (perm.Length < 2) return 1; int cmp = 0; for (int i = 0, j = perm.Length - 1; i <= j; i++, j--) { cmp = perm.Length - 1 - perm[i] - perm[j]; if (cmp != 0) break; } return cmp > 0 ? 4 : cmp == 0 ? 2 : 0; } public struct Point { public int X; public int Y; } public struct Rational { public Rational(BigInteger num, BigInteger denom) { if (denom == 0) throw new ArgumentOutOfRangeException(nameof(denom)); if (denom < 0) { num = -num; denom = -denom; } var g = _Gcd(num, denom); Num = num / g; Denom = denom / g; } private static BigInteger _Gcd(BigInteger a, BigInteger b) { if (a < 0) a = -a; if (b < 0) b = -b; while (a != 0) { var tmp = b % a; b = a; a = tmp; } return b; } public BigInteger Num; public BigInteger Denom; public static Rational operator +(Rational a, Rational b) => new Rational(a.Num * b.Denom + a.Denom * b.Num, a.Denom * b.Denom); } } } ``` Takes values of `n` as command-line arguments, or if run without arguments times itself up to `n=10`. Compiling as "Release" in VS 2017 and running on an Intel Core i7-6700 I calculate `n=9` in 1.2 seconds, and `n=10` in 13.6 seconds. `n=11` is just over 2 minutes. FWIW: ``` n a(n) 9 10408 10 45244 11 160248 12 762554 ``` [Answer] # Rust \$\color{red}{\text{I was trying to rewrite @Peter Taylor's C# answer in Rust. But the Rust code here has some mistakes.}}\$ Any help would be appreciated. ### `src/main.rs` ``` use std::time::Instant; use num_bigint::BigInt; use num_traits::Zero; use num_traits::One; use num_traits::Signed; use num_traits::ToPrimitive; #[derive(Clone, Copy)] struct Point { x: i32, y: i32, } #[derive(Clone)] struct Rational { num: BigInt, denom: BigInt, } impl Rational { fn new(num: BigInt, denom: BigInt) -> Self { let g = gcd(num.clone(), denom.clone()); Rational { num: num / g.clone(), denom: denom / g } } } impl std::ops::Add for Rational { type Output = Rational; fn add(self, other: Rational) -> Rational { let self_denom_clone = self.denom.clone(); Rational::new(self.num.clone() * other.denom.clone() + self_denom_clone * other.num.clone(), self.denom * other.denom.clone()) } } fn main() { let args: Vec<String> = std::env::args().collect(); if args.len() > 1 { for arg in &args[1..] { let n = arg.parse::<i32>().unwrap(); println!("{}", count_valid_perms(n)); } } else { let small_values = vec![1, 1, 2, 4, 18, 48]; for n in 0..small_values.len() { let observed = count_valid_perms(n as i32); let expected = small_values[n]; if observed == expected { println!("{}: Ok", n); } else { println!("{}: expected {}, observed {}, error {}", n, expected, observed, observed - expected); } } for n in small_values.len()..13 { let start = Instant::now(); println!("{}: {} in {}ms", n, count_valid_perms(n as i32), start.elapsed().as_millis()); } } } fn gcd(a: BigInt, b: BigInt) -> BigInt { let mut a = a; let mut b = b; while !a.is_zero() { let tmp = b.clone() % a.clone(); b = a; a = tmp; } b.abs() } fn count_valid_perms(n: i32) -> i64 { let unused = (1 << n) - 1; let mut excluded = vec![0; n as usize]; let mut perm = vec![0; n as usize]; if n > 1 { excluded[0] = (1 << n) - (1 << ((n + 1) / 2)); } let mut count: i64 = 0; count_valid_perms_recursive(&mut count, &mut perm, 0, unused, &mut excluded); count } // fn count_valid_perms_recursive(count: &mut i64, perm: &mut Vec<i32>, off: i32, mut unused: i32, excluded: &mut Vec<i32>) { fn count_valid_perms_recursive(count: &mut i64, perm: &mut Vec<i32>, off: i32, unused: i32, excluded: &mut Vec<i32>) { let n = perm.len(); if off == n as i32 { *count += count_symmetries(perm); return; } let mut completely_excluded = excluded[off as usize]; for i in (off + 1)..n as i32 { if (unused & !excluded[i as usize]) == 0 { return; } completely_excluded &= excluded[i as usize]; } if (unused & completely_excluded) != 0 { return; } let mut candidates = unused & !excluded[off as usize]; for val in 0.. { if candidates > 0 { candidates >>= 1; if (candidates & 1) == 0 { continue; } perm[off as usize] = val; let next_unused = unused & !(1 << val); let mut next_excluded = excluded.clone(); if off < n as i32 - 1 && off > 0 { let mut points = vec![Point { x: 0, y: 0 }; (off + 1) as usize]; let mut denoms = vec![BigInt::one(); (off + 1) as usize]; points[0] = Point { x: off, y: perm[off as usize] }; extend_exclusions(perm, off, 0, &mut points, 1, &mut denoms, &mut next_excluded); } if off == 0 && n > 1 { next_excluded[n - 1] |= (1 << n) - (2 << (n - 1 - (val as usize))); next_excluded[n - 1] |= (2 << val) - 1; } count_valid_perms_recursive(count, perm, off + 1, next_unused, &mut next_excluded); } else { break; } } } fn extend_exclusions(perm: &mut Vec<i32>, off: i32, idx: i32, points: &mut Vec<Point>, num_points: usize, denoms: &mut Vec<BigInt>, excluded: &mut Vec<i32>) { if idx == off { return; } extend_exclusions(perm, off, idx + 1, points, num_points, denoms, excluded); points[num_points] = Point { x: idx, y: perm[idx as usize] }; let denoms_clone = denoms.clone(); denoms[num_points] = BigInt::one(); for s in 0..num_points { denoms[s] *= BigInt::from(points[s].x - points[num_points].x); denoms[num_points] *= BigInt::from(points[num_points].x - points[s].x); } let num_points = num_points + 1; for target in ((off + 1) as usize)..excluded.len() { let mut prod = BigInt::one(); for t in 0..num_points { prod *= BigInt::from(target as i32 - points[t].x); } let mut sum = Rational { num: BigInt::zero(), denom: BigInt::one() }; for s in 0..num_points { let prod_s = prod.clone() / BigInt::from(target as i32 - points[s].x) * BigInt::from(points[s].y); sum = sum + Rational::new(prod_s, denoms_clone[s].clone()); } if sum.denom == BigInt::one() && sum.num >= BigInt::zero() && sum.num.to_usize().unwrap() < excluded.len() { excluded[target as usize] |= 1 << sum.num.to_usize().unwrap(); } } extend_exclusions(perm, off, idx + 1, points, num_points, denoms, excluded); } fn count_symmetries(perm: &Vec<i32>) -> i64 { if perm.len() < 2 { return 1; } let mut cmp = 0; let (mut i, mut j) = (0, perm.len() - 1); while i <= j { cmp = perm.len() as i32 - 1 - perm[i] - perm[j]; if cmp != 0 { break; } i += 1; j -= 1; } match cmp { cmp if cmp > 0 => 4, cmp if cmp == 0 => 2, _ => 0, } } ``` ### `Cargo.toml` ``` [package] name = "rust_hello" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] num-bigint = "0.4.2" num-traits = "0.2.14" ``` ### Build and running ``` # win10 environment $ cargo build $ target\debug\rust_hello.exe 0: Ok 1: expected 1, observed 0, error -1 2: expected 2, observed 0, error -2 3: expected 4, observed 8, error 4 4: expected 18, observed 36, error 18 5: expected 48, observed 124, error 76 6: 1008 in 100ms 7: 5024 in 1864ms 8: 64224 in 57079ms ``` ``` ]
[Question] [ # Challenge: I have thousands of songs in my music collection, and luckily for me, my favorite player has a search function. I also have a great memory—I can remember the title of every song in my collection. However, I'm very lazy and don't like to type—each extra keystroke is a chore! * What is the shortest string I must search for to isolate one song? Help me memorize a list of keys I can use to minimize typing when searching! This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. --- # Rules: Given an input list of song titles, generate a list of search keys subject to the following constraints: 1. Each song title should have a search key. 2. The total number of characters in the output list must be as few as possible. 3. My favorite music player is [foobar2000](https://www.foobar2000.org/): * The search function is not case-sensitive. (`apple` is the same as `aPpLE`). * Each search key must consist of one or more "words", in any order, separated by spaces: + Each word must be a [substring](https://en.wikipedia.org/wiki/Substring) of the corresponding song title. + If the same substring is specified multiple times, then it must occur that many times in its corresponding song title. + If a substring itself contains a space, then that substring must be surrounded with quotes. **Hints:** * Often, for some song titles, there are multiple search keys meeting rule 2. In such a case, any one key will do, but you get brownie points for listing them all. * You may assume that the input list will only ASCII characters, but brownie points will be awarded for UTF-8 compatibility. * Was Rule 3 hard to follow? Here's how it works: ``` +----------------------+ +--------+ +----------------+ +------------------------------------+ | Input | | Output | | Statistics | | Explanation | |----------------------| |--------| |----------------| |------------------------------------| | | | Search | | Key | # of | | | | Song title | | Key | | length | words | | Why is the output what it is? | |----------------------| |--------| |--------|-------| |------------------------------------| | Wanna Be A Wanna Bea | | e e | | 3 | 2 | | ["Wanna Be A Wanna Bea"] | | | | | | | | | is the only string containing | | | | | | | | | ["e"] twice | |----------------------| |--------| |--------|-------| |------------------------------------| | Wanta Bea A Wanna B | | t ea | | 4 | 2 | | ["Wanta Bea A Wanna B"] | | | | | | | | | is the only string containing both | | | | | | | | | ["t"] and ["ea"] | |----------------------| |--------| |--------|-------| |------------------------------------| | Wanta Be A Wanna B | | t "e " | | 6 | 2 | | ["Wanta Be A Wanna B"] | | | | | | | | | is the only string containing both | | | | | | | | | ["t"] and ['e' preceding a space] | +----------------------+ +--------+ +----------------+ +------------------------------------+ Total number of characters in output (par): 13 ``` --- # Example: If my music collection consisted only of two albums, Michael Jackson's [*Off the Wall*](https://en.wikipedia.org/wiki/Off_the_Wall) and [*Thriler*](https://en.wikipedia.org/wiki/Thriller_(Michael_Jackson_album)): ``` +--------------------------------+ +--------+ +----------------+ | Input | | Output | | Statistics | |--------------------------------| |--------| |----------------| | | | Search | | key | # of | | Song title | | key | | length | words | |--------------------------------| |--------| |--------+-------| | Don't Stop 'Til You Get Enough | | Do | | 2 | 1 | | Rock with You | | Ro | | 2 | 1 | | Working Day and Night | | Wo | | 2 | 1 | | Get on the Floor | | Fl | | 2 | 1 | | Off the Wall | | ff | | 2 | 1 | | Girlfriend | | lf | | 2 | 1 | | She's out of My Life | | Sh | | 2 | 1 | | I Can't Help It | | Ca | | 2 | 1 | | It's the Falling in Love | | v | | 1 | 1 | | Burn This Disco Out | | Bu | | 2 | 1 | | Wanna Be Startin' Somethin' | | nn | | 2 | 1 | | Baby Be Mine | | Ba | | 2 | 1 | | The Girl Is Mine | | G M | | 3 | 2 | | Thriller | | hr | | 2 | 1 | | Beat It | | Bea | | 3 | 1 | | Billie Jean | | J | | 1 | 1 | | Human Nature | | Hu | | 2 | 1 | | P.Y.T. (Pretty Young Thing) | | . | | 1 | 1 | | The Lady in My Life | | La | | 2 | 1 | +--------------------------------+ +--------+ +----------------+ Total number of characters in output (par): 37 ``` You may use the lists above to test your program. Here is the raw version of the second list: ``` ["Don't Stop 'Til You Get Enough","Rock with You","Working Day and Night","Get on the Floor","Off the Wall","Girlfriend","She's out of My Life","I Can't Help It","It's the Falling in Love","Burn This Disco Out","Wanna Be Startin' Somethin'","Baby Be Mine","The Girl Is Mine","Thriller","Beat It","Billie Jean","Human Nature","P.Y.T. (Pretty Young Thing)"] ``` [Answer] ## Python 2, 556 bytes [Try it online.](https://tio.run/nexus/python2#bVPLbtswEDxbX7EwYIhsGAHpUa0KNE3TuHEeiAUEgaADbVMWHZoUSCqReuivp0vVjwaooAN3dmd2dim9yW1jrAcronlWdIkyr8ISWhkLHUiNb9N6Qssoz5TQ0SxTfLtYcXBMpxq4XhVxnGyM1KSnEFh9YIkXrkj8SzbETRyNJ2RfFDNXTFxaxpPT3x0culiu14Joik@JmJLOE0ejy3236zQnhRvqXaifg6wgx5LTnFixapeC7Co71qdWJK5dYCIRbskbgdZYHLOOnVF2zRylWZYfHF1jSwTOoqN4GkGfuU86Cx0iWIkKHohlnqbRaK3MgivQrI9GKsjATsdTevLxg2u3ZMubg5sU8yjZIZlGIzStvmj051urh/ASebhEUJ912mcee6po1GbFDPvJ4RbkcT84K5qNRv@D0dqwns17/FTSFL0Xm5OctIUsi01J05L5k2IXlTjgA3GsCIfGSu2LneVwufF44sbxpIPhog7X1Zdvb8X4kWvN4VzAV9gf@ZhBwP0QHBP/wu/RC6NjD3NvGohzqeDJtPBDePiuTbuux2z8YJbP8Cp9HVIYPxr7LPUaLngfHMKtXNce8UAyGnwt4FIZYxG6q6ohfuRKhQppVWWl0CsM5rWIHZgWSRXc9DCTlUB4Ct94MHQlVAPToDv1WDeookpojPPPzEsoPsdbhLyWDi6kWxq4awPhsJa559ZLHcPcbIWv8RQ4fNGH5I3UQSJH4eALpu4IWamUCAPgDv1fF@cISQE/BdcYXbVbruGW42cUGPfJU5InQO7xw/J92BPaRF96TXctZnw1/Jf7Qcs/) -10 bytes, thanks to @Riker, @ovs Took me couple evenings to make everything works. Outputs song name, array of search keys and lenght of search keys combined (including spaces and quotes) ``` import re S=map(str.lower,input()) T=len for s in S: y=s;n=T(s) def R(r,t): global n,y l=T(' '.join(t))+2*sum(map(lambda x:' 'in x,t)) if l>n:return if(lambda K:T([s for s in S if T(s)-T(reduce(lambda x,y:re.sub(re.escape(y),'',x,1),K,s))==T(''.join(K))])==1)(t)and l<n:y=t;n=l u=[(lambda s,n:n and[''.join(y) for y in eval('zip(s%s)'%(''.join(',s[%s:]'%-~x for x in range(n))))]or list(s))(r,i)for i in range(T(r))] for i in range(T(r)): for j in range(T(r)-i):R(r[j+T(u[i][j]):],t+[u[i][j]]) R(s,[]) print[' 'in x and'"%s"'%x or x for x in y] ``` --- **Some explanation:** ``` T=len ``` Function `len()` used very often here, so this renaming saves bytes --- ``` L=lambda s,n:n and[''.join(y) for y in eval('zip(s%s)'%(''.join(',s[%s:]'%-~x for x in range(n))))]or list(s) ``` Evaluates all possible substrings of string s lenght n. `eval(...)` creates command `zip(s,s[1:],s[2:],...,s[n:])` It creates substrings of lenght `n` from every index of `s` if possible. So for `s='budd'` and `n='2'` it will produce **bu, ud, dd** --- ``` F=lambda K:len([s for s in S if len(s)-len(reduce(lambda x,y:re.sub(re.escape(y),'',x,1),K,s))==len(''.join(K))])==1 ``` Filter to check if provided keys (K) are for unique song name. re.sub is requered for multiple identical keys, like ['nn','nn'] in examples. --- Inner function `def R(r,t)` is a recursive one to create all possible combinations of substring, that may describe song name. Every combination is compared with currently shortest one (if there was any) to lower number of created combinations - if it is larger, it won't be accepted as all of it derivatives. Function uses 2 variable to track state: `n` for lenght of current shortest key combination and `y` for combination itself --- ``` l=T(' '.join(t))+2*sum(map(lambda x:' 'in x,t)) ``` This calculates length of key combination. `' '.join` add spaces between keys and `2*sum(...)` calculates number of needed quotes for keys with spaces. --- ``` u=[L(r,i)for i in range(0,T(r))] ``` Uses first lambda function to get all possible key combination (of every possible length) for current string. --- Two for cycles to look through all generated keys and pass them individually to the next recursive step. Key place (`j`) is needed to correctly slice string at the end of it: `r[j+T(u[i][j]):]`. Slice provides string, that started where current key ends, so there won't be any overlaps. If place is unknown, equal keys would mess everything up. --- ``` [' 'in x and'"%s"'%x or x for x in y] ``` Much longer than just `y`, but keys with spaces should be surrounded by quotes ]
[Question] [ We've all heard of the [Knight's Tour](https://en.wikipedia.org/wiki/Knight%27s_tour) puzzle: find a route for a knight that passes through all the squares on a chess board. But let's be honest, it's a little bit boring. So, let's give the knight a bit of a challenge. ## Task Write a program that takes the knight through all the squares on an arbitrary-sized, arbitrary-shaped chess board. It should take the chess board as input and output the set of moves and the starting position. In the event of an impossible board, it should output the set of moves and starting position for a tour with the longest possible length. Note: the knight doesn't need to take a round trip; assume they have another way to get home. Chess pieces are small, so your code needs to be small enough for the knight to carry around. ## Input The input will be a string-based or array-based representation of a chess board, where a non-blank / truthy value is a square, and a blank / falsy value is an empty space. For simplicity's sake I will use `#`s and s arranged in a grid for the examples. ## Output The output will be two large integers, followed by a series of 4-bit integers, or your language's equivalent. The two large integers will represent the starting co-ordinates, and the following numbers will represent a move like so: ``` 7 0 6 1 K 5 2 4 3 ``` where `K` is the position before the move, and the number is the position after the move. ## Examples As there are a lot of possible solutions to the Knight's Tour puzzle, I will only provide example outputs. There may be more outputs. ``` ### # # ### 0 0 3 0 5 2 7 4 1 AFC D H GBE ## ## ## ## (4, 0) [5, 6, 3, 1, 6, 3, 0] CF HA BE DG ``` New challenge: Come up with more examples [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 254 bytes ``` n=-2,-1,1,2,2,1,-1,-2 l=len e=enumerate s=lambda b,x,y,t:max([1>((a:=[p:=x+_,q:=y+n[i-6]])in t)<l(b)>p>-1<q<l(b[p])>0<b[p][q]and[i]+s(b,p,q,t+[a])or[]for i,_ in e(n)],key=l) f=lambda b:max([(z:=[x,y])+s(b,*z,[z])for x,r in e(b)for y,c in e(r)if c],key=l) ``` [Try it online!](https://tio.run/##fY9tb4MgEMff@ylI9gbmmYB92GKKX4RcGmwxM1OK1CXaL@8Uu7bLHgKB//@O@93hhu7tZFevzo@jlUkKiQAB6bTELJM0qmVtbGSksR@N8boz0VnWuimOmhTQwwBd1uieKpFTqjOpXCb7eA9tJofYqirZIrLKko7talqw3OWJ2LWzVg5ZznfzrVrU9qgqjM@0AActdLHSyE5eYXnypII9mRiGWobwbgZZs6i8TbH0p5ep@TQPsgB5voC6IJure/BLdRHsAIfFelaV5PAFHJ2vbEdLqpQAMm8EMkt@lyGKjJEnxUMiBbIJYgVkG/JrjP4B8b9Aq3BuAvHlVwq/s/jNXYl3Nwdu3Am6DrhlzEWIRzR/wF3rJkr6rfvPJ9e/4/gJ "Python 3.8 (pre-release) – Try It Online") Pass input to the function `f` as a 2d array of truthy/falsey values. Thanks to ovs and wizzwizz4 ]
[Question] [ Given an input date, your entry will output the full list of supported versions of the [Ubuntu Linux distro](http://www.ubuntu.com/) on that date. The [full list of all releases](https://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Table_of_versions) is as follows: ``` Version Code name Release date Supported until 4.10 Warty Warthog 2004-10-20 2006-04-30 5.04 Hoary Hedgehog 2005-04-08 2006-10-31 5.10 Breezy Badger 2005-10-13 2007-04-13 6.06 LTS Dapper Drake 2006-06-01 2009-07-14 2011-06-01 (Server) 6.10 Edgy Eft 2006-10-26 2008-04-25 7.04 Feisty Fawn 2007-04-19 2008-10-19 7.10 Gutsy Gibbon 2007-10-18 2009-04-18 8.04 LTS Hardy Heron 2008-04-24 2011-05-12 2013-05-09 (Server) 8.10 Intrepid Ibex 2008-10-30 2010-04-30 9.04 Jaunty Jackalope 2009-04-23 2010-10-23 9.10 Karmic Koala 2009-10-29 2011-04-30 10.04 LTS Lucid Lynx 2010-04-29 2013-05-09 2015-04-30 (Server) 10.10 Maverick Meerkat 2010-10-10 2012-04-10 11.04 Natty Narwhal 2011-04-28 2012-10-28 11.10 Oneiric Ocelot 2011-10-13 2013-05-09 12.04 LTS Precise Pangolin 2012-04-26 2017-04-26 12.10 Quantal Quetzal 2012-10-18 2014-05-16 13.04 Raring Ringtail 2013-04-25 2014-01-27 13.10 Saucy Salamander 2013-10-17 2014-07-17 14.04 LTS Trusty Tahr 2014-04-17 2019-04 14.10 Utopic Unicorn 2014-10-23 2015-07-23 15.04 Vivid Vervet 2015-04-23 2016-01 15.10 Wily Werewolf 2015-10-22 2016-07 16.04 LTS Xenial Xerus 2016-04-21 2021-04 ``` ### Rules * For each supported version, the exact version string will be output, e.g. `4.10` * For LTS (long-term support) versions, `LTS` will be appended to the version * The three oldest LTS versions come in two flavours - desktop and server. If both of these LTS versions are supported on the given date, the output will simply be the version string as above. However if only the server version is supported, then you must append `-server` to the end of the version string * At the time of writing, 4 of the recent versions only have YYYY-MM in their supported-until dates. You must treat these dates as if they are the last day of the given month. e.g. 2019-04 must be treated as 2019-04-30 * There will be no output for dates outside of the full date range captured in the table * Input date formats are flexible, but must contain some enumeration of Year, Month and Day. Number of days or seconds (or other units) from an epoch are not valid input formats. * Output lists may be given in whatever format is convenient for your language * You may use datetime functions from your language * You may assume all inputs are valid ### Examples: ``` Input: Output: 2000-01-01 2004-10-20 4.10 2005-05-05 4.10, 5.04 2006-06-06 5.04, 5.10, 6.06LTS 2010-10-10 6.06LTS-server, 8.04LTS, 9.04, 9.10, 10.04LTS, 10.10 2021-04-30 16.04LTS 2021-05-01 ``` [Answer] # JavaScript (ES6), 552 bytes ``` d=>(d=d.replace(/^20|-/g,'')*1,[for(r of'41020,60430;50408,61031;51013,70413;-60601,90714,110601;61026,80425;70419,81019;71018,90418;-80424,110512,130509;81030,100430;90423,101023;-91029,110430;-100429,130509,150430;101010,120410;110428,121028;111013,130509;-120426,170426;121018,140516;130425,140127;131017,140717;-140417,190430;141023,150723;150423,160131;151022,160731;-160421,210430'.split`;`.map(a=>a.split`,`))if(d>=(a=Math.abs(f=r[0]))&&((m=d<=r[1])||r[2]&&d<=r[2]))((a+'').slice(-6,-2)/100).toFixed(2)+'LTS'.slice(f)+(m?'':'-server')].join`, `) ``` Building the data array takes up ~68% of the total size. The rest is input formatting, array lookup, and output string construction. The data string is split into an array of arrays of either 2 (normal) or 3 (server) length. The dates are reduced to numeric format, with the intial "20" stripped (along with any leading zeroes after that). LTS is denoted by a negative start date. Version numbers can be conveniently derived from all but the last two digits of the positive start date, divided by 100. ]
[Question] [ You should write a program or function which given a starting order of distinct one-digit positive integers and the length of the track as input outputs or returns the finish order of the numbers. The input `[5,1,2,6,7] and 14` defines the following race: ``` -------------- 76215 -> -------------- ``` ## Rules of the race * The track wraps around and digits can go multiple laps. * Order of steps is cyclic and based on the starting position. In our example `5 1 2 6 7 5 1 2 ...`. * There can be no multiple digits in the same position. * Every digit has a speed of `digit_value` cell per step. Overtaking a digit or a continuous block of digits costs one extra step. If the digit doesn't have the necessary speed for that it will stop before the (block of) digit(s). Examples: ``` [41 ] => [ 1 4 ] 4 overtakes 1 [2 1 ] => [ 21 ] 2 can only move 1 as it can't move 3 to overtake 1 [4 12 ] => [ 412 ] 4 can only move 1 as it can't move 5 to overtake 12 [ 3 ] => [ 3 ] 3 starting a new lap ``` * Every digit has to go `digit_value` laps before it finishes. A lap is completed when the last cell of the track is left. A finished digit is removed from the track. * *Note that a digit might reach its starting position multiple times through a step and complete multiple laps.* ## Input * A list of distinct one-digit positive integers (`1..9`) with at least one element and a single positive integer, greater than the length of the list, the length of the track. ## Output * A list of digits in the order they finished in any unambiguous format. ## Examples A visual step-by-step example for the input `starting_order = [5,9,2] and length = 6` ``` 295 | Start position 29 5| digit 5 moves 2 9 5| digit 9 moves, finishing lap #1 29 5| digit 2 moves 529 | digit 5 moves, finishing lap #1 52 9| digit 9 moves, finishing lap #2 5 29| digit 2 moves 529| digit 5 moves 9 52 | digit 9 moves, finishing laps #3 and #4 29 5 | digit 2 moves, finishing lap #1 29 5| digit 5 moves 2 9 5| digit 9 moves, finishing lap #5 29 5| digit 2 moves 529 | digit 5 moves, finishing lap #2 52 9| digit 9 moves, finishing lap #6 5 29| digit 2 moves 529| digit 5 moves 9 52 | digit 9 moves, finishing laps #7 and #8 9 5 | digit 2 moves, finishing lap #2 --> remove 2 from the track 59 | digit 5 moves, finishing lap #3 5 | digit 9 moves, finishing lap #9 --> remove 9 from the track 5| digit 5 moves 5 | digit 5 moves, finishing lap #4 | digit 5 moves, finishing lap #5 --> remove 5 from the track ------ Finish order: 2 9 5 ``` Examples in format `Input => Output` ``` [3], 2 => [3] [9, 5], 3 => [9, 5] [5, 9, 2], 6 => [2, 9, 5] [5, 9, 2], 10 => [5, 9, 2] [5, 7, 8, 1, 2], 10 => [1, 5, 7, 8, 2] [5, 1, 6, 8, 3, 2], 17 => [1, 6, 8, 2, 3, 5] [1, 2, 3, 7, 8, 9], 15 => [1, 7, 8, 9, 2, 3] [9, 8, 7, 3, 2, 1], 15 => [8, 7, 9, 1, 2, 3] [1, 2, 3, 4, 5, 6, 7, 8, 9], 20 => [1, 2, 3, 4, 5, 6, 7, 8, 9] [9, 8, 7, 6, 5, 4, 3, 2, 1], 20 => [8, 7, 5, 9, 6, 1, 2, 4, 3] ``` This is code-golf so the shortest entry wins. [Answer] # Ruby 229 ~~236~~ This is a function that takes two parameters: an array representing the digits and an int representing the length of the track. It returns an array, representing the order in which the digits finish the race. ``` F=->d,l{ i=0 t=d.map{|x|[x,d.size-(i+=1)]} r=[] d.cycle.map{|n| t==[]&&break (c=t.find{|x,_|x==n})&&(s=n w=c[1] o=p (a=(t-[c]).map{|_,p|p%l} s-=1;w+=1 a&[w%l]==[]?(o=p;c[1]=w):o||s-=o=1)while s>0 c[1]>=n*l&&(t.delete c;r<<n))} r} ``` Test it online: <http://ideone.com/KyX5Yu> *Edit:* Figured out some [tricks](https://github.com/clupascu/codegolf/commits/master/49549-race-of-the-digits/race-of-the-digits-golfed.rb) to save some more chars. Ungolfed version: ``` F=->digits,length{ digit_positions = digits.map.with_index{|d,i|[d,digits.size-i-1] } result = [] digits.cycle.map{|n| break if digit_positions==[] crt = digit_positions.find{|x,_|x==n} next unless crt steps_left = n pos = crt[1] taking_over = false while steps_left > 0 other_pos = (digit_positions-[crt]).map{|_,p|p%length} steps_left-=1 pos += 1 if other_pos.include? (pos%length) steps_left -= 1 unless taking_over taking_over = true else taking_over = false crt[1] = pos end end if crt[1] >= n*length digit_positions.delete(crt) result<<n end } result } ``` [Answer] # Python 2, 345 bytes Too bad it's not shorter than @w0lf's, but whatev. (Note that the large indents are tabs, which translate to 4-space when I post.) ``` def r(o,l): n=len(o);s,t,a,d=dict(zip(o,range(n)[::-1])),-1,{_:0 for _ in o},[] while len(s): t+=1;g=o[t%n] if g in d:continue y,k=s[g],1;i=z=w=0 for _ in[0]*g: i+=1;m=y+i;e,p=m%l,m/l if-~a[g]+w>=g<d>m>=l:a[g]+=1;del s[g];d+=[g];break if e in s.values()and e!=y:i-=k;k=0 else:k,s[g],(w,z)=1,e,[(w,z),(z,p)][z<p] a[g]+=z print d ``` [Answer] here is my magical padded code ## C (~~457~~ 430b) ``` int v(int*M,int m){ int i,n,c,d,e=32,f=48,u=0,g=10,h,k,r,l=m,j;char a,*b=&a,*B,V[m]; for (i=0;u<m*m*m;i=(++u%m),*B=*b=(u<=l)?*b:e,b=B=&a) printf("%c%c",0*(V[i]=(u<l?u>=(r=l-sizeof(M)/4)?M[u-r]+f:e:V[i])),((((V[c=(((V[i]=u<l?e:V[i])-f)/10<u/m)?j>=0&h<i|((h=(j=strchr(V+((k=(m+(d=(i-(V[i]-f)%g+1)))%m)),e)-V)<0?(int)(strchr(V,e)-V):(int)j)>=k)*(k>i)?h:m :m])=((V[c]==e)?(*(b=V+i)+(d<0)*g):V[c])))-f)%11==0?(*(B=V+c)-f)%g+f:0); getch(); } ``` **Note**: it needs more improvement ... **EDIT:** code shortened ... - sizeof(int)=4 , function=v , still remains some variable replacing to do . ]
[Question] [ Working on something in probability theory, I stumbled across another combinatorical exercise. These are always fun to solve, searching for intelligent approaches. Of course, one can use brute force for the following task, but this challenge is restricted complexity, so this is not allowed. ## Task Given an integer Input \$n > 1\$, print all integer vectors of length \$n\$, respecting following conditions: * \$v\_1 = 1\$ * \$v\_{i+1} - v\_i \in \{0,1\}\$ * \$v\_n \neq n\$ example: Input: `n=4` Output: ``` [1 1 1 1] [1 1 1 2] [1 1 2 2] [1 1 2 3] [1 2 2 2] [1 2 2 3] [1 2 3 3] ``` Additionally, time complexity of your solution must be \$O(2^n)\$. Note that generating all vectors and then filtering would be \$O(n^n)\$, which is not acceptable. A direct construction, not generating any false vector or duplicate vector at all, seems to be a bit more of a challenge. Having said that, shortest code in bytes, respecting the above condition, wins. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~65~~ 55 bytes ``` ->n{(0..2**~-n-2).map{|x|w=1;(1..n).map{|d|w+=x[n-d]}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNAT89IS6tON0/XSFMvN7GguqaiptzW0FrDUE8vDyqSUlOubVsRnaebEltbW/u/QCEt2iSWq6C0pJgLxDaN/Q8A "Ruby – Try It Online") ### How: Partial sum of bits (starting with 1) of all numbers up to 2n-1-2 For example: if the number is `111010011` it becomes: ``` 1 1 1 0 1 0 0 1 1 | | | | | | v v v v v v +1+1+1 +1 +1+1 ----------------- 1 2 3 4 4 5 5 5 6 7 | Initialized to 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes ``` <oxÍŸεbηO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fJr/icO/RHee2Jp3b7v//vwkA "05AB1E – Try It Online") ``` < # decrement: n-1 o # 2**(n-1) x # push 2 * 2**(n-1) = 2**n without popping Í # 2**n - 2 Ÿ # range [2**(n-1), ..., 2**n - 2] ε # for each number in that range: b # convert it to binary η # prefixes O # sum each prefix ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), ~~[17](https://tio.run/##y0rNyan8//9Rw0wjLSDxcMe2Q1udju72sTm0@VjXof2PmtYcbtE2/P//vwkA)~~ ~~[16](https://tio.run/##y0rNyan8//9Rw0wjLSDxcMc2p6O7fWwObT7WdWj/o6Y1h1u0Df///28CAA)~~ 11 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` ’2* Ç’Ḷ+ÇBÄ ``` You can [try it online](https://tio.run/##y0rNyan8//9Rw0wjLa7D7UD64Y5t2ofbnQ63/P//3wQA)! ``` ’2* Compute 2^(n-1) (let me call it x). Ç’ Take x and decrement it, Ḷ creating the range [0, ..., x-1]. + Then add Ç x to every element in said range, B take its binary representation Ä and then take the cumulative sums. ``` This is a golfed version of the following: The condition \$v\_{i+1} - v\_i \in \{0, 1\}\$ means we can instead generate all the sequences \$d\_i\$ of \$n - 1\$ elements with \$d\_i \in \{0, 1\}\$ and then generate a vector \$v\$ as such: $$\begin{cases} v\_1 = 1 \\ v\_{i+1} = v\_i + d\_i \end{cases}\tag{1}$$ The only sequence we can't consider is when \$d\_i = 1\ \forall i\$ because in that case, \$v\_n = n\$, which can't happen as per the OP. On top of that, we can see the sequences \$\{d\_i\}\_{i=1}^{n-1}\$ as the binary numbers from \$0\$ to \$2^{n-1} - 1\$. So we do just that: find the binary representation of all integers from \$0\$ to \$2^{n-1}-1\$ and take those sequences as the jumps, to define \$v\$ as per \$(1)\$. ``` ’ Take the input integer and subtract 1, 2* take 2 to the power of that ’ and finally decrement again (this builds 2^(n-1) - 1). Ḷ Take the lower range [0, ... (2^(n-1)-1) - 1] B and write every number in the range in binary. € Now, for each binary representation ¿ While said binary representation L<³Ɗ has length smaller than the input number, Ż prepend a 0 to it. Ä Take the cumulative sum of every binary representation +1 and add 1 to every element. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` IE⊖X²⊖θ⮌EIθ⊕Σ⍘÷ιX²λ² ``` [Try it online!](https://tio.run/##TYwxDsIwEAS/4vIsmSaio4M0KZAi8oKTswJLjkPswzz/CBECthztjL9x9jNH1T6HJHTiInTmO7XwGROSYKR@fiJT48w/XKy1zlxQkQs2ZXOXFXbpdxseEx25YJC1f6UuSRtqGEHBmW83vlON/eygutddjS8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ² Literal 2 X To power θ Input ⊖ Decremented ⊖ Decremented E Map over implicit range θ Input I Cast to integer E Map over implicit range ι Outer index ÷ Integer divide by ² Literal 2 X To power λ Inner index ⍘ ² Convert to base 2 Σ Digital sum ⊕ Incremented ⮌ Reversed I Cast to string Implicitly print ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Full program. ``` ¯1↓{⊃,/(⊂,¨0 1+⊢/)¨⍵}⍣(⎕-1),1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@h9YaP2iZXP@pq1tHXeNTVpHNohYGCofajrkX6modWPOrdWvuod7HGo76puoaaOoYgPf8VwKCAywQA "APL (Dyalog Unicode) – Try It Online") `,1` the list `[1]` `{`…`}⍣(⎕-1)` apply the following anonymous lambda one-less-than input times:  `(`…`)⍵` on the argument:   `⊢/` take the last element (lit. right-argument reduction)   `0 1+` add `[0,1]` to that   `⊂,¨` concatenate each to the entire argument  `,/` flatten (lit. concatenation reduction)  `⊃` disclose (since the reduction enclosed to reduce rank from 1 to 0) `¯1↓` drop the last [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 70 bytes ``` []\(:m 2\?:p{(.[2 base]@\+\.}do;{.,m\-[0]\*\+}%{1:s;{s+:s}%[1]\+ }%(;` ``` [Try it online!](https://tio.run/##BcFLCoAgEADQq7gRJEtSaKOLuocj9I8gUZp2Mme39670nLi9d/7qUH0AYSMzMNpchPKGrQseYQIJivbkimojdL4P0IAkXrRFV1BaJO51AMmICzfX@gM "GolfScript – Try It Online") This is just my first stab, I have a few ideas on how to improve, but this is my hot garbage to start with. My goal is to get it under 50, then I'll write a full explanation. The short is that it writes every binary combination, sums the elements recursively, then adds 1 to the front. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~72 69~~ 68 bytes ``` f=(n,a=1,p=1,m=n)=>--m?[p,p+1].map(p=>p<n&&f(n,a+[,p],p,m)):print(a) ``` [Try it online!](https://tio.run/##FcpBCoAgEAXQ24hDYyC0iGjsIOJiCIQC5VPh9a0Wb/dObXrv14HHtbn3LLayimd8ilSS4FzZIhiDT2NRWEjAWo3J/xwiIzG4EC24jvpYpZ7tRP0F "JavaScript (V8) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` msM._dPh#^U2 ``` [Try it online!](https://tio.run/##K6gsyfj/P7fYVy8@JSBDOS7U6P9/EwA "Pyth – Try It Online") Make all length `n` sequences of `0,1`, filler for the ones that start with 1, remove the all ones sequence, form prefixes, soon the prefixes. [Answer] # [Python 3](https://docs.python.org/3/), ~~111~~ 108 bytes ``` def f(n): for i in range(2**(n-1)-1): v,j=[],1 for c in bin(i)[2:].zfill(n):j+=int(c);v+=[j] print(v) ``` [Try it online!](https://tio.run/##LY3BCsIwDIbve4ock60Km3qZ9ElKDzpXTRnZKKOgL18bEXII@b8v//beX6ucSnnMAQIKjQ2ENQEDC6SbPGcc2hbl0FOdGkI20Tpv@roqOCl4Z0EmN4z@@Am8LPondpZlx4muubMu@spvSS@ZioqiIp7N5VdZjeafU/kC "Python 3 – Try It Online") No gigantic superset just straight up generation of vectors using [G B](https://codegolf.stackexchange.com/users/18535/g-b)'s partial sum of bits idea. [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` f=lambda n:1/n*[[1]]or[x+[x[-1]+d]for d in 0,1for x in f(n-1)] ``` [Try it online!](https://tio.run/##FcdBCoAgEADAr3jMTGqjU9BLlj0YIgm1iniw1295m8lvvRKvIuG43XN6p3iHmUdEIEoFm8GGFsh4CqkoryKrZYLu1h0GtqBJcolc/21a5AM "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), 69 bytes ``` f=function(n,m=1,`?`=cbind)"if"(n-1,rbind(f(n-1,1?m),f(n-1,1?m+1)),m) ``` [Try it online!](https://tio.run/##PccxCoAwDEbh3WN0yo9xiLqWXqVYCXRohKLnj9TB5fG97q5RHyt3vYyMWxTOKcdyVDsRqgayRbiPJf0sqYF/zgJwgysJJqV1ZBvZ4S8 "R – Try It Online") Simple recursive solution; returns a matrix where each row is one of the valid lists. [Answer] # [6502](https://en.wikipedia.org/wiki/MOS_Technology_6502), 31 bytes ``` 0016 .function 0016 A0 FE LDY #FEh ; starting bit pattern 0018 .again 0018 84 41 STY 41h ; store current bit pattern in scratchpad 001A A9 31 LDA #049 ; ASCII "1" 001C A6 40 LDX 40h ; load index with vector size 001E .more_bits 001E 46 41 LSR 41h ; shift lsb into carry 0020 69 00 ADC #0 ; add with carry 0022 85 0F STA 0Fh ; display ASCII char 0029 CA DEX ; decrease index 002A D0 F2 BNE 1Eh ; more bits if index not zero 0024 C9 31 CMP #049 ; sequence ends in "1" so all bits zero 0026 D0 01 BNE 2Ch ; continue 0028 60 RTS ; exit function 0029 .continue 002C A9 2C LDA #044 ; display... 002E 85 0F STA 0Fh ; ... comma 0030 88 DEY ; next ... 0031 88 DEY ; ... bit pattern 0032 4C 18 00 JMP 0018h ; go again ``` [Try It On Visual6502.org](http://www.visual6502.org/JSSim/expert.html?r=0010&a=0010&d=2016004C1300A0FE8441A931A64046416900850FCAD0F7C931D00160A92C850F88884C1800&a=0040&d=03) (Press the Play button to run the program. Press Trace Less to speed up simulation). Input is at memory location 40 hex - click and enter hex numbers to modify before running. Since the 6502 is an eight bit microprocessor, for golfing purposes input is restricted from 1 to 8. ]
[Question] [ Your task is, given a family tree, to calculate the Coefficient of Inbreeding for a given person in it. ## Definition The Coefficient of Inbreeding is equal to the Coefficient of Relationship of the parents. The Coefficient of Relationship between two people is defined as weighed sum over all common ancestry as follows: *Each* simple path P (meaning it visits no node more than once) which goes upwards to a common ancestor from A and then down to B adds \$(\frac{1}{2})^{length(P)}\$ to the Coefficient. Also, if A is an ancestor of B (or vice versa), each simple path linking them also adds \$(\frac{1}{2})^{length(P)}\$ to the Coefficient. ## Challenge Rules * **Input** consists of a directed graph representing the family tree and a single identifier for a node of the graph. As usual, any [convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963) is valid. * The graph can be input in any convenient representation. Used below is a csv style in which each line represents a marriage between the first two entries, with the offspring being all following entries. Other representations, like a list of parent-child pairs, or a connectivity matrix, are also allowed. * Similarly, the node identifier can be in any format working for that graph representation, like a string for the format used here, or an index for a connectivity matrix. * **Output** is either (in any convenient method): + A single rational number between 0 and 1, representing the Coefficient of Inbreeding for the identified node in the graph. + Two integers, the second of which is a power of two such that the first number divided by the second is the Coefficient of Inbreeding (you do not need to reduce the fraction). * In either case, make sure you have enough bits available to handle the given test cases (11 bits for the Charles II case) with full accuracy. * [Standard Loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are of course not allowed. * You can assume the input graph to be well-formed as family tree, meaning you are allowed to fail in any way you want for the following cases: + The graph being cyclic + The node not being in the graph + The node in question not having exactly 2 parent nodes + The chosen input format not being followed * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code for each language wins. ## Test cases **1** In: ``` F;M;S;D S;D;C F;D;I ``` `C` Out: `0.5` There are two paths of length 2: S-F-D and S-M-D, thus the total is \$(\frac{1}{2})^{2}+(\frac{1}{2})^{2}=0.5\$ **2** In: ``` F;M;S;D S;D;C F;D;I ``` `S` Out: `0` F and M have no common ancestors. **3** In: ``` F;M;S;D S;D;C F;D;I ``` `I` Out: `0.5` F is direct ancestor of D with path length 1, thus the Coefficient is \$(\frac{1}{2})^{1}=0.5\$ **4** In: ``` F;M1;S1;S2 F;M2;D1;D2 S1;D1;C1 S2;D2;C2 C1;C2;I ``` `I` Out: `0.375` There are 6 paths of length 4: Two go over M1 and M2 as C1-S1-M1-S2-C2 and C1-D1-M2-D2-C2. The remaining four all are distinct ways to connect over F: C1-S1-F-S2-C2, C1-S1-F-D2-C2, C1-D1-F-S2-C2 and C1-D1-F-D2-C2 Thus the Coefficient is \$6 \cdot (\frac{1}{2})^{4}=0.375\$ **5** In: ``` F;M;C1;C2;C3 F;C1;N1 C2;N1;N2 C3;N2;I ``` `I` Out: `0.5` There are 5 contributing paths, 3 over F and 2 over M. Two paths for F have length 3: N2-N1-F-C3 and N2-C2-F-C3, and one has length 4: N2-N1-C1-F-C3. One path to M has length 3: N2-C2-M-C3 and one length 4: N2-N1-C1-M-C3 Thus the Coefficient is \$3 \cdot (\frac{1}{2})^{3}+2 \cdot (\frac{1}{2})^{4}=0.5\$ **6** In: ``` Ptolemy V;Cleopatra I;Ptolemy VI;Cleopatra II;Ptolemy VIII Ptolemy VI;Cleopatra II;Cleopatra III Ptolemy VIII;Cleopatra III;Cleopatra IV;Ptolemy IX;Cleopatra Selene;Ptolemy X Ptolemy IX;Cleopatra IV;Ptolemy XII Ptolemy IX;Cleopatra Selene;Berenice III Ptolemy X;Berenice III;Cleopatra V Ptolemy XII;Cleopatra V;Cleopatra VII ``` `Cleopatra VII` Out: `0.78125` or `200/256` There are 51 contributing paths, with lengths from 3 to 8. A full list can be found [here](https://www.dropbox.com/s/6pd247hwh5xxy36/CleopatraVIITrace.txt?dl=0). **7** In: ``` Philip I;Joanna;Charles V;Ferdinand I;Isabella 2 Isabella 1;Charles V;Maria;Philip II Ferdinand I;Anna 1;Maximillian II;Charles IIa;Anna 2 Isabella 2;Christian II;Christina Maria;Maximillian II;Anna 3 Anna 2;Albert V;Maria Anna 1;William V Christina;Francis I;Renata Philip II;Anna 3;Philip III Charles IIa;Maria Anna 1;Margaret;Ferdinand II William V;Renata;Maria Anna 2 Philip III;Margaret;Philip IV;Maria Anna 3 Ferdinand II;Maria Anna 2;Ferdinand III Maria Anna 3;Ferdinand III;Mariana Philip IV;Mariana;Charles IIb ``` `Charles IIb` Out: `0.4267578125` or `874/2048` There are 64 contributing paths with lengths between 3 and 11. A full list can be found [here](https://www.dropbox.com/s/eqhuvr3gzojqxpv/CharlesIIaTrace.txt?dl=0). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~43~~ 33 bytes ``` ịW€;Ɱ0ịịɗ¥€Ẏ¥ƬẎ¥€ŒpṪ€E$ƇF€QƑƇẈ.*S ``` [Try it online!](https://tio.run/##dVLBattAEL3PV@iQU2lLJR2XliZyBdviEFfgOMd1stRb5LWRdWhuaS8uCRSaQNNDezIhUEqhpYTYgR5sLEj/QvoRdSxZ8ii4sJbmvZn3Znas19L3D9M0vjnZTd59Z8nPH48wxnN7Pr1AJp58mF5E@Qvh/LQfj79h8GwjGrr4bkQfo2E8ef/wnpfen5/G489IvmDJ0RfjwRMjOfrKZpcQ3/yOxyNMLDBaNRT2wRMd2/OzePwJQ3TNz8bs0m08XsST69vzaPjUja9H1t8TVEfH0S9YCEbJ2z/Tq@nVbIjsXpq6rM48VgP8MQdcfHJwANbR3nqaZ7TJPDzWIrRYzWQ1C5DAwDHBQ8ZijgUOQquUsBw6NgIMt01AtI0BFtr4zAt3wp4vu4dGkzm@7PVFGAiDs5LllKY85/C/Igpo1d0URc3SmrcI70lfalnmWrC2iqhbpOM6py0ZSK32ZWW0VoUmoiYQX8rTGI2qCHY6yld9XOPzntBaMKcjAl8OUObK4EBpoQ8wyQeijZ@4MCwoQ5PU1kWgBCu8OFDtJtpicV28UV3l@0robPFLLeciryDO@CF0AjUIy9IMaAF5mztOmdqG3IRt@m0ZhMVIxrL5blbexSWVZswNhN5XOAF7KbUIRbmKwnJ1H9waGbfijOCVCGRI18Wh7Lf0phpr1Yiv5AVXGdymi@QVk0o/DlRUTeUqvbpes2DIf9AmF2z/Aw "Jelly – Try It Online") A dyadic link taking the individual as the left argument and the pedigree as the right. The pedigree is a list of lists where each (possibly empty) list represents the parents of the person at that index. Returns a floating point number. ## Explanation ``` ị | Index into pedigree to find parents of desired individual W€ | Wrap each in a list ¥€ | For each parent: ¥Ƭ | - Do the following as a dyad, keeping intermediate results: ¥€ | - Do the following as a dyad for each member of the list ;Ɱ ɗ | - Concatenate the following (as a dyad) to the end of the list: 0ị | - Last member of the list ị | - Indexed into pedigree to find parents Ẏ | - Remove one level of lists (concatenating outer sublists together) Ẏ | - Remove one level of lists (concatenating outer sublists together) Œp | Cartesian product of the two lists of possible chains of ancestors for each parent $Ƈ | Keep those where: Ṫ€ | - The tail of each chain (removing from the chain in the process) E | - Is equal F€ | Flatten each Ƈ | Keep those where: Ƒ | - The list is invariant when: Q | - Uniquified Ẉ | Lengths of each list .* | 0.5 to the power of the lengths S | Sum ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~304~~ ~~294~~ ~~293~~ 278 bytes Takes as input: list of lists of relatives; name of person to calculate coefficient. ``` P={} I,Z=input() for R in I: for r in R[:2]:P[r]=P.get(r,[])+R[2:] l=lambda c,p,X:c==Z and X.append(p)or c in P and[l(z,p*1+[z],X)for z in P[c]]and X print sum(pow(.5,len(a+b)-2)for k in P for a in l(k,[],[])for b in l(k,[],[])if~-len(a+b)==len(set(a+b))if a>b if a[-2]!=b[-2]) ``` [Try it online!](https://tio.run/##ZVLLauMwFN37KzQr240SqMtsDF4MAwMaKJgs2lChxbWjNKKyJGSVmcnQ/noqyU39yCo6vudxHzH/3FGr4nw@WN0h4bh1Wsseic5o626Suvr/lhD8VAllXl2WJwdt0RYJhUiZoABsAFtaFqysqWVVvXnmLrOYsny1pUXJEllJ6Jo9oBYbvCvbqnpCoPZotwFjuNpnJvc@bfCpQ4HK7ITNze2Knhje5SHkFIu0ZSwKE2OFcqh/7TKj/2Sb71hylcGqyddF5L8MZuEJuAmg1V0jFDihVZ/J7MX3F1rERS4O7@uLvKrCq/cDBORLCOi6YN@qJvzk5zOlaX0UUhhEUozS3xqUgvD6eQQreY8eAvjF7d6H@VYji/TQcCkBFakPHeHtlfAerIh2lxASFQu/Hz5zEN/DX9EJKQWowJ3YEQJf1EVsMfCs6N1UF7EfJnC/@rgOiI53kfVpHj7Kxv9zJjOgscfHKO98MWjGnLAnC6oV/TDVlvvzDPHj9GPgdCnk02o26jLX42ew3C0OMmjHpsbkuUcx74QsLS@V5cx3y4uRK@NFQ2RcORqHnTMuFmq@oIdpYXb9JmUMz/AH "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 274 bytes If input is allowed as single list of lists, where last list contains name of person to calculate coefficient, some bytes can be saves, using leaked variable from for loop. ``` P={} for Z in input(): for r in Z[:2]:P[r]=P.get(r,[])+Z[2:] l=lambda c,p,X:c==Z[0]and X.append(p)or c in P and[l(z,p*1+[z],X)for z in P[c]]and X print sum(pow(.5,len(a+b)-2)for k in P for a in l(k,[],[])for b in l(k,[],[])if~-len(a+b)==len(set(a+b))if a>b if a[-2]!=b[-2]) ``` [Try it online!](https://tio.run/##ZVHdS@swFH/fXxGf1rpuXCv3pdALIggRhOKDjoU8nHbRBbMspJWrE/3XZ07qTJtBoefj93HOiXnvNjudHw5V@fE5edpZsiJSu8@8dklaTAiWLJZWrMh5UTHLy2rxLLrEZoynsxXLCz5RpYJtvQbSZCZbFk1ZrtgfDnpNlgswRuh1YlKn1KBSRVyDqWSfmfOLGdvzbJmizd43WcN74sRYqTvSvm4Ts/ufLP5mSugEZnU6zz3@pRfDEDBUyYsbCafCUj0uyaev@ZFflhi1bgfMXIvAPwd3PzbP@VlZ4y89HBibVhuppCF0mpHp7Q60BoyuN2CVaMkDJjfCrqXGkT2KtlALpYDkU2cc0osT4h1Y6eWOJtQzIr0r59mT7@BNbqVSEjRiB3KUwi80ss17nJVtN@T53C2D2N85Tg284qVH/YhjUdXCdoMdSJjx0dO3romc4IN3sqAb2fZb3QsNXW8ftg@Gw6PQH6nRqrGvy5/Bii56kJ4bhgrOY418PAmNJY@deOfL@MXoiXA0EA0nJ2HZMeIooccHehg2Rq9fRydyOf8G "Python 2 – Try It Online") --- Some explanation ``` # Converts input lists into dictionary, where keys - each parent # and values - list of its children # In this task we don't care about direct relations between any parents P={} for R in I: # for parents in cells [0] and [1] add cells [2:] for r in R[:2]: P[r] = P.get(r, []) + R[2:] # Lambda collects all paths from node c to the person of interest # It's recursive function, which stores all paths in argument X and then returns it # Each paths is guarantied to have person of interest as last element # and one of its parents as previous to last element l=lambda c,p,X: c==Z and X.append(p) or c in P and [l(z, p*1+[z], X) for z in P[c]] and X # For each node with children: # calculate all paths to person of interest # get all pairs of this paths for k in P for a in l(k,[],[])for b in l(k,[],[]) # filters out dublicates if a>b # if paths from pair have unique items # (except only 1 same item, that each path have - person of interest) # and if previous to last elements are different # (i.e. paths through different parents) if ~-len(a+b)==len(set(a+b)) and a[-2]!=b[-2] # This pair of paths forms simple inbreed path, so add up to result sum(pow(.5,len(a+b)-2) .. ) ``` Note, that algorithm also covers cases when one of parents is ancestor to other one, as node of elder parent will produce similar paths, that will add up to result sum. ]
[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/102385/edit). Closed 7 years ago. [Improve this question](/posts/102385/edit) Remember the good old days when opening a simple document or web page was painfully slow as it hogged all the meager resources your computer had? And today, doing the same is even slower, despite your processor being hundreds of times faster and having access to thousands of times more memory? To simulate the effect of bloat in current document viewers and similar applications, **write a program which has visible performance problems when run on more powerful machines**. To have a common task for everyone, **make it a prime number generator**. * The program has to print consecutive prime numbers, starting from 2, each in a new line, and nothing else. It should to this forever (or until running out of memory). Like this: > > > ``` > 2 > 3 > 5 > 7 > 11 > 13 > 17 > > ``` > > * There should be a delay between printing each line, enough to be perceivable by a human. * This delay should be longer as the machine the program is running on gets faster. The faster the machine, the slower the program. * I won't specify exact benchmarks as it might become subjective, but there should be a human-perceivable difference in the speed on two different machines if there is significant difference between the performance of the two machines. * The speed of the program doesn't have to be monotonically decreasing across all existing machines ever created. This would be hard to specify, and even harder to verify. I trust the common sense of the contestants about what can be considered a **significantly different performance** between to machines, and it is enough to satisfy that. * I also won't specify exact upper or lower time limits, but it should be under reasonable limits, so no days or years between printing two lines please. * I won't require it to run on everything from the Eniac to modern day, but it should be general enough, for example, it's not allowed to say it only works on two specific CPU types, and specifically detects the name of one specific CPU on which it will run slower or faster. * The code shouldn't rely on compiler or interpreter version. It should work if the same version of the compiler/interpreter is installed on both a slower and faster machine, or even if the binary / bytecode is compiled on one machine and then run on two different machines. * Please explain the principles of how your program is operating. As it will be difficult to reproduce the results, the validity of the answer might depend on the the feasibility of the method. Although I would have liked it to become an underhanded contest, sadly this site is no longer "Programming Puzzles & Code Golf" but just simply "Code Golf", so the shortest code wins. [Answer] # Perl, ~~80~~ ~~78~~ 71 bytes -9 bytes thanks to @Dada ``` $_++;`lscpu`=~/z:\s+(\d+)/,sleep$1,(1x$_)!~/^(11+?)\1+$/&&say while$_++ ``` Runs the command `lscpu` and finds the CPU speed in MHz. The faster the CPU, the more time it sleeps between outputs, 1 second for every 1 MHz. Runs on Ubuntu 14.04.5. On my particular machine, this tests each number every 800 seconds (13 minutes, 20 seconds). On faster machines, this can be over 50 minutes. Change it to `sleep$a/400` to get something much more sane for testing purposes. ]
[Question] [ There's quite a lot of work that's been done in the world of chess. For example, there is a standardized file format, [`.pgn`](https://en.wikipedia.org/wiki/Portable_Game_Notation), that describes a chess game, including the list of moves. Additionally, there's another file format [`.fen`](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation), that describes a board position. **The challenge today is to convert a list of chess moves ([in algebraic notation](https://en.wikipedia.org/wiki/Algebraic_notation_(chess))) to a board position.** # Definitions * Position `[a-h][1-8]`: Given by appending the row (file) and the column (rank). Defines one of the 64 possible positions on the board. * Piece`[KQRBNP]?`: Represents the **K**ing, **Q**ueen, **R**ook, **B**ishop, K**N**ight, **P**awn. In algebraic notation, `P` is not used. When used on a board, letters are uppercase if they are White, otherwise lowercase. * Move `[KQRBN]?[a-h]?[1-8]?x?[a-h][1-8](=[KQRBN])?(+*?)?|O-O(-O)`: A piece followed by the position it is moving to. + If the piece is ambiguous, then the row, or the column, or both are given. + If the piece is capturing a piece, then `x` is placed between the piece and the position. + If the move is a castling, then `O-O` is given for king-side, otherwise `O-O-O`. + If a pawn is being promoted, the move is appended with `=` followed by the piece it is being promoted to. + If a move puts the king in check, it is appended with a `+`. + If a move puts the king in checkmate, its appended with `#`. + The color of the piece is determined by the turn number (White and black alternate turns, starting with black.) * Board`(([1-8]|[KQRBNPkqrbnp])*\/){8}`: Rows are given by listing the pieces in row order. If there are empty squares, each run of empty square is given using the length of the run. Rows are separated using `/` A board's initial position is `rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR`, which represents: ``` rnbqkbnr pppppppp PPPPPPPP RNBQKBNR ``` You need to take a list of Moves and return a Board. You can assume that your input is valid. # Examples ``` -> rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR e4 -> rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR e4,c5 -> rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR e4,d5,exd5,e5 -> rnbqkbnr/ppp2ppp/8/3Pp3/8/8/PPPP1PPP/RNBQKBNR e4,d5,exd5,e5,dxe6 -> rnbqkbnr/ppp2ppp/4P3/8/8/8/PPPP1PPP/RNBQKBNR e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4 -> r1bqk2r/ppp2pp1/4Pn2/2P4p/6nP/8/PPP2PPN/RNBQKB1R e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4 -> r1bqk2r/ppp2pp1/4P3/2P4p/3Q2nP/6P1/PPP2n1N/RNB1KB1R e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4,O-O -> r1bq1rk1/ppp2pp1/4P3/2P4p/3Q1BnP/6P1/PPP2n1N/RN2KB1R e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4,O-O,Na3,Nxh1,O-O-O,Qg5,exf7+ -> r1b2rk1/ppp2Pp1/8/2P3qp/3Q1BnP/N5P1/PPP4N/2KR1B1n e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4,O-O,Na3,Nxh1,O-O-O,Qg5,exf7+,Kh7,Bxg5,Rd8,f8=Q -> r1br1Q2/ppp3pk/8/2P3Bp/3Q2nP/N5P1/PPP4N/2KR1B1n e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4,O-O,Na3,Nxh1,O-O-O,Qg5,exf7+,Kh7,Bxg5,Rd8,f8=Q,Ngf2,c6,Rd7,cxd7,b6,d8=Q,c6,Q4d6,Ba6,Qd8f6 -> r4Q2/p5pk/bppQ1Q2/6Bp/7P/N5P1/PPP2n1N/2KR1B1n e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4,O-O,Na3,Nxh1,O-O-O,Qg5,exf7+,Kh7,Bxg5,Rd8,f8=Q,Ngf2,c6,Rd7,cxd7,b6,d8=Q,c6,Q4d6,Ba6,Qd8f6,Rb8,Qdd8,b5,Qc5,b4,Qxb8,bxa3,Rd3,Nxd3+,Kd1,axb2,Bh3,b1=Q+,Kd2,Qxa2,Qh6+,gxh6,Qcd6,Qa1,Qbc7+,Kh8,Qdd8# -> 3Q3k/p1Q5/b1p4p/6Bp/7P/3n2PB/2PK3N/q6n ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your answers as short as possible! [Answer] ## Javascript (ES6), ~~1024~~ 995 bytes This is an early and still bulky attempt. I just stopped optimizing it when the 1K limit was reached. It's probably not bullet-proof and only considers promotions to a Queen. But it does pass the test case. *Edit: 995 bytes - a few obvious optimizations* **Source** ``` F=i=>{B=[];b=0;X=[8,2,4,12,16,4,2,8,1];for(n=120;n--;B[n]=n<8?X[n]|32:n<24?33:n>111?X[n-112] :n>95|0);Y=j=>(M[j]?M[j].charCodeAt(0)-97:8)|(M[++j]?(8-M[j])*16:128);G=_=>(F&8||!(F&7^f&7)) &&(F&128||!(F&112^f&112))&&B[f]==p;Z=d=>{for(k=f,u=1;(k+=d)!=T;)u&=!B[k]};Q=(j,...D)=>D.some (d=>(j&2?!((f-T)%d)&&(Z(f<T?d:-d),u):T-f==d||(j&&f-T==d))&&(S=f));i.split(',').forEach(m=>{ if(m[0]=='O'){S=b?4:116;m[4]?(T=S-2,B[S-1]=B[S-4],B[S-4]=0):(T=S+2,B[S+1]=B[S+3],B[S+3]=0)} else{M=m.match(/([B-R])?([a-h])?(\d)?x?([a-h])?(\d)?(=Q)?/);p=X["QKBNRP".indexOf(M[1]||'P')+ 3]|b;F=Y(2);M[4]?T=Y(4):(T=F,F=136);for(f=120,S=0;f--;)G()&&(p&4&&Q(2,15,17),p&8&&Q(2,1,16), p&2&&Q(1,14,18,31,33),p&16&&Q(1,1,15,16,17),p&1&&Q(0,b-16,2*b-32));for(f=120;p&1&&!S&&f--;) G()&&Q(0,b-15,b-17);B[S]&1&&(S-T)%16&&!B[T]&&(B[T+16-b]=0)}B[T]=B[S];B[S]=0;M[6]&&(B[T]^=13) ;b^=32});for(r='',y=0;y<8;y++){for(x=z=0;x<8;x++)(b=B[y*16+x])?(p=".PN.B...R...Q...K"[b&31], r+=(z||'')+(b&32?p.toLowerCase():p),z=0):z++;r+=(z||'')+(y<7?'/':'')}return r} ``` **Full executable snippet** ``` F=i=>{B=[];b=0;X=[8,2,4,12,16,4,2,8,1];for(n=120;n--;B[n]=n<8?X[n]|32:n<24?33:n>111?X[n-112]:n>95|0);Y=j=>(M[j]?M[j].charCodeAt(0)-97:8)|(M[++j]?(8-M[j])*16:128);G=_=>(F&8||!(F&7^f&7))&&(F&128||!(F&112^f&112))&&B[f]==p;Z=d=>{for(k=f,u=1;(k+=d)!=T;)u&=!B[k]};Q=(j,...D)=>D.some(d=>(j&2?!((f-T)%d)&&(Z(f<T?d:-d),u):T-f==d||(j&&f-T==d))&&(S=f));i.split(',').forEach(m=>{if(m[0]=='O'){S=b?4:116;m[4]?(T=S-2,B[S-1]=B[S-4],B[S-4]=0):(T=S+2,B[S+1]=B[S+3],B[S+3]=0)}else{M=m.match(/([B-R])?([a-h])?(\d)?x?([a-h])?(\d)?(=Q)?/);p=X["QKBNRP".indexOf(M[1]||'P')+3]|b;F=Y(2);M[4]?T=Y(4):(T=F,F=136);for(f=120,S=0;f--;)G()&&(p&4&&Q(2,15,17),p&8&&Q(2,1,16),p&2&&Q(1,14,18,31,33),p&16&&Q(1,1,15,16,17),p&1&&Q(0,b-16,2*b-32));for(f=120;p&1&&!S&&f--;)G()&&Q(0,b-15,b-17);B[S]&1&&(S-T)%16&&!B[T]&&(B[T+16-b]=0)}B[T]=B[S];B[S]=0;M[6]&&(B[T]^=13);b^=32});for(r='',y=0;y<8;y++){for(x=z=0;x<8;x++)(b=B[y*16+x])?(p=".PN.B...R...Q...K"[b&31],r+=(z||'')+(b&32?p.toLowerCase():p),z=0):z++;r+=(z||'')+(y<7?'/':'')}return r} console.log(F( "e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4," + "O-O,Na3,Nxh1,O-O-O,Qg5,exf7+,Kh7,Bxg5,Rd8,f8=Q,Ngf2,c6,Rd7,cxd7,b6,d8=Q,c6,Q4d6,Ba6," + "Qd8f6,Rb8,Qdd8,b5,Qc5,b4,Qxb8,bxa3,Rd3,Nxd3+,Kd1,axb2,Bh3,b1=Q+,Kd2,Qxa2,Qh6+,gxh6," + "Qcd6,Qa1,Qbc7+,Kh8,Qdd8#" )); ``` ]
[Question] [ Given a pattern representing a list of lengths, and a string representing those lengths, do they match? For those interested, this is question equivalent to verifying if a row or column of a [Nonogram](https://en.wikipedia.org/wiki/Nonogram) may be correct. However, I have omitted all language relating to Nonograms to make the question less confusing for those unfamiliar with these puzzles. ## Input Two lines of data, separated by a newline. 1. The first line will be a space separated list of integers, example: ``` 3 6 1 4 6 ``` This line **describes a pattern** of filled spaces of size equal to the integer list, separated by empty spaces of **unknown**, positive length that the second line must match. There may also be empty spaces at the beginning and end of the matched string. 2. The second line will be a line that that may or may not match the pattern in line one. It consists entirely of `#`, `x`, and `_`. This line is **guaranteed** to be **at least** as long as the *sum of the integers in the first line, plus the number of distinct integers, minus 1,* and can be longer. So the second line in this case is guaranteed to be at least `(3+6+1+4+6) + (5) - 1`, or 24 characters long. Here is an example 24 character line that matches the pattern in the first line: ``` ###_######_#_####_###### ``` ### Meaning of symbols: * `#` This represents a filled box * `x` This represents a box marked as "guaranteed to be empty" * `_` This represents an unknown / unmarked box. ## Goal The idea is to: 1. Validate that the second line could be a valid row that meets the pattern of the first line. * You must print an unambiguous error message (how you choose to do this is up to you; the examples below write `ERROR` but it doesn't need to be those 5 characters) if the unknown spaces cannot be filled out with either `#` or `x` to match the first line. 2. Print the **zero-indexed indices** of the integers that have been **completely placed** in the row, space delimited. *If there is ambiguity, **do not** print the index*. ## Examples: ``` Input: | Output: | Reason: -------------------------------------------------------------------------- 3 6 1 4 6 | 0 1 2 3 4 | This is a complete string that ###x######x#x####x###### | | matches perfectly. -------------------------------------------------------------------------- 1 2 1 | 0 1 2 | There is no ambiguity which filled cells #____xx___##__x_# | | correspond to which parts of the pattern. -------------------------------------------------------------------------- 1 2 1 | | I don't know whether the filled block is ____#___x | | part of the 1, 2, or 1, so output nothing. -------------------------------------------------------------------------- 1 2 1 | ERROR | The first unknown cell will create a block that #_#x_# | | matches either 1 1 or 3, but not 1 2. -------------------------------------------------------------------------- 1 2 1 | 0 2 | Even though we know where all the filled cells #____# | | must be, only 0 and 2 are actually filled here. -------------------------------------------------------------------------- 1 1 1 1 | | There are so many possible ways to do fill this, __#_______#____ | | we don't know which indices are actually matched. -------------------------------------------------------------------------- 4 4 | | Again, we don't know WHICH 4 is matched here, ______x####________ | | so output nothing. -------------------------------------------------------------------------- 4 4 | 0 | However, here, there's no room for a previous 4, __x####________ | | so the displayed 4 must be index 0. -------------------------------------------------------------------------- 3 | ERROR | We can't fit a 3 into a space before or after __x__ | | the x, so this is impossible to match. -------------------------------------------------------------------------- 5 1 3 | 0 | While we can match the 5, we don't know whether x#####x____#____ | | the single block matches the 1 or the 3. -------------------------------------------------------------------------- 3 2 3 | 1 | The two has been completely placed, ____##x##____ | | even though we don't know which it is. ``` ## Rules: You may write a [program or function](http://meta.codegolf.stackexchange.com/a/2422/17249), which receives the input as a newline delimited String or from STDIN (or closest alternative), and [returns the output as an space delimited String or printing it to STDOUT (or closest alternative).](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) You may optionally include a single trailing newline in the output. Additionally, [standard loopholes which are no longer funny](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are **banned**. [Answer] # Perl, 134 bytes (includes 1 switch) ``` perl -pe '$p.="([#_]{$_})[x_]+"for@l=split;chop$p,$_=<>;/^[x_]*$p*$(?{$h[$_-1].=$$_ for 1..@l})(?!)/;$_=@h?join$",grep{$h[$_]!~/_/}0..$#l:ERROR' ``` Takes two lines of input from STDIN. Must be re-executed for every input. The idea is to first extract all possible patterns that match the given lengths. For example, if we have the lengths `1 2` and the pattern `#_x_#_`, then the matching patterns are `(#, _#)` and `(#, #_)`. Then, concatenate the matched patterns for every index - for the example the result is the list `(##, _##_)`. Now, print the indices of all the strings in the list which have only '#' characters. I got the method to extract all possible matches from a regex in Perl [here](http://www.perlmonks.org/?node_id=1066361). * [Ungolfed and extended explanation](https://ideone.com/qmEH9G) * [ideone.com](http://ideone.com/ignuHo) ]
[Question] [ This is an endgame board of Settlers of Catan: ![Catan board](https://i.stack.imgur.com/KaDsA.jpg) # Background: The roads (the long stick pieces) and the settlements (and cities) are rendered by the little huts. We encode the placement of these pieces by using the following scheme: From the top, we have a row horizontal vertices and edges where a road can be placed. Then we have a column of only roads, and so forth. Using R for Red, O for Orange, and B for Blue, and \_ for nothing, the pictured board would be encoded as: ``` ________RR_R_ __R_ __RR_R_RRR_____R_ B___R _B_________B__OO_OOR_ B__B_R BB_BBB_____B____RR_R_ OBB_O OO__BB_BB__OOO_OO O_O_ _O_OOO_O_____ ``` A board like this will be your input string. Any letter `[A-Z]` may indicate a player color, but there will at most four colors (including empty). Boards are otherwise *guaranteed* to be valid according to the rules of Settlers, which means: * Each color will have at most two contiguous road networks, which may or may not be broken apart by other players settlements / cities (vertex buildings). See the orange settlement breaking apart the red road on the right side of the sample image. + Each road network is guaranteed to have at least one settlement. * All settlements and cities are guaranteed to be at least **two** edges from the nearest other settlement / city (yours or otherwise) * One player may only have 15 roads on the game board. * For Catan enthusiasts: there is no distinction between settlements and cities for the purpose of this problem, so I don't distinguish in the input string. All this is for the specification of the "input" string. ### Longest Road: In Settlers, players get two victory points for having the "longest road". This is defined to be: **The longest contiguous single path (measured in roads) from start point to end point, that is not broken up by an opponents settlement or city**. Cycles are okay, as long as you can trace the path from one particular start point to one particular end point. So, a loop of 6 roads plus one road branching off is length 7, but one with two branching off the 6 road loop on opposite sides is still only worth 7. In the example map, the Red road on the right side is only worth 4, because he is cut off by an Orange settlement on the right side of the board (that's why settlements are included at all). Blue has a road of length 13, and Orange has a road of length 12. Red's top road is only worth 7, because it doesn't connect to the two single roads next to it. ## Output: All players that have a road of the longest length (it could be more than one if there are ties), followed by a whitespace and/or underscore delimited count in base 10 of how long that road is. So the output for the example board would be: ``` B 13 ``` ## The Problem statement: You may write a [program or function](http://meta.codegolf.stackexchange.com/a/2422/17249), receives the input board via STDIN or as a string argument to your function, which [returns the output described above as a string or prints it to STDOUT (or closest alternative).](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) You may optionally include a single trailing newline in the output. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest program wins. [Standard loopholes are banned, of course](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). [Answer] # Python 2, ~~445~~ 400 bytes I'm a fan of Settlers, so this challenge was fun. ``` T="^" Z=26 A=T*52 for i in range(11):A+=(T*(i%2)*3).join(x for x in raw_input()).center(Z,T) A+=T*52 def f(c,p=0,l=0,B=A): b=l;C=B[0:p]+T+B[p+1:];n=(Z,1)[p%2] for i in(p<1)*range(390): if(i/Z%2<1&i%2>0)|(i/Z%2>0&i%2<1):b=max(b,f(c,i)) for i in(p-n,p+n)*(B[p]==c): for j in(i-Z,i-1,i+1,i+Z)*(B[i]in c+"_"):b=max(b,f(c,j,l+1,C)) return b i=l=0 for x in A: if x<T:i=f(x) if i>l:c=x;l=i print c,l ``` Score reflects replacing each occurrence of 4 spaces with a tab. **Explanation** The lines before the function definition read the input, and build a normalized board into a single string variable. The process inserts "^" characters into the short lines representing the vertical road segments. It also pads the board with "^" characters. ``` ^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^________RR_R_^^^^^^^ ^^^^^^_^^^_^^^R^^^_^^^^^^^ ^^^^__RR_R_RRR_____R_^^^^^ ^^^^B^^^_^^^_^^^_^^^R^^^^^ ^^_B_________B__OO_OOR_^^^ ^^B^^^_^^^_^^^B^^^_^^^R^^^ ^^BB_BBB_____B____RR_R_^^^ ^^^^O^^^B^^^B^^^_^^^O^^^^^ ^^^^OO__BB_BB__OOO_OO^^^^^ ^^^^^^O^^^_^^^O^^^_^^^^^^^ ^^^^^^_O_OOO_O_____^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^ ``` When called with the default parameters, the function returns the length of a road of a given color. The first loop is active only when the position (p) parameter was supplied. It recursively finds the length of the road at each valid road position, and keeps track of the longest one. When there is a road at the position parameter, the function recursively adds the length of adjacent roads of the same color. The road is replaced with a "~" in the working copy of the board to ensure it doesn't recount segments that have already been counted. The code following the function definition calls the function for each color in the board, and prints the highest scoring color and length. Demo it [here](https://repl.it/C3j6) ]
[Question] [ A theorem in [this paper](https://www.sciencedirect.com/science/article/pii/0024379594905096)1 states that every integral n-by-n matrix **M** over the integers with **trace M = 0** is a *commutator*, that means there are two integral matrices **A,B** of the same size as **M** such that **M = AB - BA**. ### Challenge Given an integral matrix **M** with **trace M = 0** find some integral matrices **A,B** such that **M = AB - BA**. ### Details * Let **A,B** be two matrices of compatible size, then **AB** denotes the [matrix product](https://en.wikipedia.org/wiki/Matrix_multiplication) of **A** and **B** which in general does not commute, so in general **AB = BA** does *not* hold. We can "measure" how close two matrices are to commuting with eachother by measuring how close the *commutator* - which is defined as **AB - BA** - is to being zero. (The commutator is sometimes also written as **[A, B]**.) * The [*trace*](https://en.wikipedia.org/wiki/Trace_(linear_algebra)) of a matrix is the sum of the diagonal entries. * The decomposition is not necessarily unique. You have to provide one decomposition. ### Examples Since the decomposition is not unique, you might get different results that are still valid. In the following we just consider some possible example. ``` M: A: B: [ 1 0] [1 1] [1 0] [-2 -1] [1 -1] [1 1] ``` In the trivial case of **1 x 1** matrices only **M = 0** is possible, and any two integers **A,B** will solve the problem ``` M: A: B: [0] [x] [y] for any integers x,y ``` Note that for **M = 0** (a zero matrix of arbitrary size) implies **AB = BA**, so in this case any two matrices **(A, B)** that commute (for example if they are inverse to each other) solve the problem. ``` M: A: B: [0 0] [2 3] [3 12] [0 0] [1 4] [4 11] M: A: B: [11 12 12] [1 1 1] [1 2 3] [ 7 4 0] [0 1 1] [4 5 6] [ 0 -7 -15] [0 0 1] [7 8 9] M: A: B: [-11811 -9700 -2937] [ 3 14 15] [ 2 71 82] [ -7749 -1098 8051] [92 65 35] [81 82 84] [ 3292 7731 12909] [89 79 32] [59 4 52] ``` 1: [*"Integral similarity and commutators of integral matrices"*](https://doi.org/10.1016/0024-3795(94)90509-6) by Thomas J.Laffey, Robert Reams, 1994 [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÄàD(Ÿsgãsgãã.ΔD2FsN._`øδ*O}-Q ``` -7 bytes thanks to *@ovs* in [another answer of mine](https://codegolf.stackexchange.com/a/213920/52210). Extremely slow since I'm using a brute-force approach with three cartesian products. But performance is irrelevant for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenges I guess (would love to see this same challenge as [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") or [fastest-algorithm](/questions/tagged/fastest-algorithm "show questions tagged 'fastest-algorithm'")). [Try it online](https://tio.run/##yy9OTMpM/f//cMvhBS4aR3cUpx9eDMKHF@udm@Ji5FbspxefcHjHuS1a/rW6gf//R0cb6igYxOooROsa6SjoGsbG/tfVzcvXzUmsqgQA) (only works for matrices of size 2x2, and even then usually times out if the absolute maximum of the integers in the matrix \$M\$ is too large..) [Verify whether the output \$[A,B]\$ results in the input \$M\$.](https://tio.run/##yy9OTMpM/f/fyK3YTy8@4fCOc1u0/Gt1//@Pjo420lEwitVRiDbUUdA1igWxQEKGUCGD2NjY/7q6efm6OYlVlQA) **Explanation:** *Assumes* all the integers used in the resulting matrices \$[A,B]\$ will be within the range \$[-\max(\lvert M\rvert), \max(\lvert M\rvert)]\$. If you know any way to prove or disprove this assumption, let me know. Note that there are of course matrices \$[A, B]\$ with integers larger than the integers of the resulting matrix \$M\$. But this \$M\$ will have other possible \$[A, B]\$ which are within this min-max range. I.e. \$[A,B]=\$ `[[[1,2],[3,4]], [[-1,-2],[-3,-3]]]` will have \$M=\$ `[[0,2],[-3,0]]`, but using this \$M\$ to find a possible \$[A,B]\$ will result in `[[[3,2],[3,3]], [[2,2],[3,3]]]`, which are all within the range \$[-3,3]\$. Let me start with an explanation of `2FsN._`øδ*O}-`, which will calculate \$M = AB-BA\$ of a given matrix-pair \$[A,B]\$ (which is the same code as in the verifier TIO-link above). ``` 2F # Loop 2 times: s # Swap the top two values on the stack # (so the matrix-pair is at the top again after the first iteration) N._ # Rotate the pair of matrices the (0-based) loop-index amount of times # (to reverse the order from [A,B] to [B,A] in the second iteration) ` # Push both matrices separated to the stack ø # Zip/transpose the top matrix; swapping rows/columns δ # Apply double-vectorized: * # Multiply O # And then sum each inner row together } # After the loop: - # Subtract the values at the same positions in the two matrices from each other ``` As for the rest of the program to create all possible matrices and brute-force over them: ``` Ä # Convert each integer in the (implicit) input-matrix `M` to its absolute value à # Pop and push the flattened maximum of these absolute values of `M` D( # Duplicate it, and negate the maximum Ÿ # Pop both and push a list in the range [max, -max] s # Swap to get the input matrix again g # Pop and push its length to get the matrix dimension ã # Create the cartesian product of the [max, -max]-list that many times # (i.e. if the input-matrix has a dimension of 3, we'll now have all possible # triplets of integers within the [max, -max]-range) sgã # Do the same, to create all possible combinations of these triplets # (so we now have all possible matrices of the same dimensions as the input-matrix, # using integers within the [max, -max]-range) ã # Cartesian product yet again (defaults to 2) to create all possible pairs of matrices .Δ # Then find the first pair of matrices which is truthy for: D # Duplicate the current pair 2FsN._`øδ*O}- # Calculate M as mentioned above Q # And check if its equal to the (implicit) input-matrix # (after which this matrix-pair is output implicitly as result) ``` *Just to give an idea of how inefficient this brute-force approach is:* The given example input-matrix \$M=\$ `[[11,12,12],[1,1,1],[1,2,3]]` of the challenge description, will create all possible matrix-pairs of the same 3x3 dimensions with integers in the range \$[-12,12]\$. This means the list of matrix-pairs will contain \$(((12^2+1)^3)^3)^2=802830827198685151406498569488525390625\$ matrix-pairs. And the given example input-matrix \$M=\$ `[[-11811,-9700,-2937],[3,14,15],[2,71,82]]` would result in \$(((11811^2+1)^3)^3)^2=400239694511528196808960294025932709663435907226315389994060779277222573307615163703296535923733538440194289670070277830289553752923910908747710464\$ matrix-pairs.. ]
[Question] [ For my CS class, my instructor has given us the assignment of creating a rectangle made of asterisks with diagonal lines drawn through it in Java. He also told us to write it in as few bytes as possible. I've gotten it down to 190 bytes, but I need to find a few to simplify this code even more to decrease bytes. Can anyone help me with this? This code is functional: ``` interface d{static void main(String[]a){for(int z=0,w=new Byte(a[0]),h=new Byte(a[1]);z<h*w;){int y=z/w,x=z++%w;System.out.print((x>w-2)?"*\n":(y%(h-1)*x*((y-x)%3)==0)?"*":" ");}}} ``` Input is `10 10`. Output: ``` ********** ** * * * * * * ** * * * * ** * * * * * * ** * * * * ** * * * * * * ** ``` [Answer] Logically, there should be an asterisk (`*`) every time `i == j` and `i+j==w-1`(for diagonals), `i == 0` and `j == 0` (for top line and left side) and `j == w-1` and `i==h-1` (for right side and bottom line). ``` class d { public static void main(String[] a) { for(int i=0,w=new Byte(a[0]),h=new Byte(a[1]);i<h;i++) { for(int j=0;j<w;j++) { System.out.print(i==0 || j==0 || i==h-1 || i+j==w-1 || j==w-1 || i==j ? "*":" "); } System.out.println(); } } } ``` [Answer] The code you provided could be reduced by doing this: * replace `*` with `42` and `" "` by `' '` (taking advantage of the charcode for `*`) * move `((y - x) % 3)` to the beginning of the things to be multiplied and remove the surrounding parenthesis * remove surrounding parenthesis from `(x > w - 2)` and from `((y - x) % 3 * y % (h - 1) * x == 0)` The resulting code would be: ``` interface r{static void main(String[]a){for(int z=0,w=new Byte(a[0]),h=new Byte(a[1]);z<h*w;){int y=z/w,x=z++%w;System.out.print(x>w-2?"*\n":(y-x)%3*y%(h-1)*x==0?42:' ');}}} ``` Note: the last line is missing in the example output of the question! The output of the sample code is different. [Answer] ~~178~~ 174 chars ``` interface T{static void main(String[]a){for(int w=new Byte(a[0]),h=new Byte(a[1]),j,i=0;i<h;i++)for(j=0;j<w;System.out.print((i-j)%3*i*j!=0&i<h-1&++j<w?" ":j<w?"*":"*\n"));}} ``` [Try it online!](https://tio.run/##TYzLCoMwFER/JQ1Ukvgg4s4Hhf6C3VkXQWO9KUbRVBHpt6dpV10NM5wzSqwiHCepVfu0FrSRcycaiW7HYoSBBq0jtGgQoElpZtCPqhb06MaZOBZthZYbuu5GElHxmgb9/xC7QQVQ8AzyPgPfp19Pua7yLSv3xcghGl8mmtyxIQRCRc8JA6ZOBfecE8ae7zv2ghFOf8lwitldY0qz99tam3Ab8w8 "Java (OpenJDK 8) – Try It Online") Readable: ``` interface T{ static void main(String[]a){ for(int w=new Byte(a[0]),h=new Byte(a[1]),j,i=0;i<h;i++) for(j=0;j<w;System.out.print( (i-j)%3*i*j!=0&i<h-1&++j<w?" ":j<w?"*":"*\n")); } } ``` --- Output for field: `30 10`: ``` ****************************** ** * * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * ** * * * * * * * * * * * ****************************** ``` [Answer] I don't actually have Java on my computer so I can't test this but I think it should work for 174 bytes and almost definitely could be golfed more ``` class d{static void main(String[]a){for(int i=0,w=new Byte(a[0]),h=new Byte(a[1]);i<h;i++)for(int j=0;j<w;j++)System.out.print(j==w-1?"*\n":i%h-1==0||!j||i+j%2==0?"*":" ");}} ``` Whitespace added for clarity: ``` class d { static void string main(String[] a) { for(int i=0,w=new Byte(a[0]),h=new Byte(a[1]);i<h;i++) for(int j=0;j<w;j++) System.out.print(j==w-1 ? "*\n" : i % h-1 == 0 || !j || i+j % 2 == 0 ? "*":" "); } } ``` print `*\n` for the last char in each line, `*` for all of the first and last lines and the first column, and `*` for any time that the sum of the row and column is even, otherwise prints ]
[Question] [ What could be more polar opposites than chess and [demolition derby](https://en.wikipedia.org/wiki/Demolition_derby). You would think that no one who enjoys one would enjoy the other... until today. # Rules The starting position is a standard chess board: ``` RNBQKBNR PPPPPPPP PPPPPPPP RNBQKBNR ``` Looks normal enough, until you find out it's an **EVERY PIECE FOR ITSELF, LAST PIECE STANDING** competition: * On every turn, each piece on the board gets to make one randomly\*-selected valid move (using it's standard move rules). However, the order the pieces move in is **randomized** every turn. * A piece can capture **ANY PIECE**, even if it's the same color as it, even a king. * Pawns can capture **FORWARD**, as well as diagonal. Moreover, like normal, if there is an empty space in front of it, a pawn can move two spaces on its first move (they can also capture that way.) Furthermore, pawns promote to any random piece (including king) other than a pawn. * The winner is the last piece standing. However if after **1000 turns**, there is more than one piece left, all of the remaining pieces are winners. * No En Passants, Checks, Castles, etc. # Output After every turn output the turn number, and what the board looks like. After a piece is killed it is removed from the board. After the first turn, the board may look like this: ``` 1. K RBQ N BR NP P P PP P P R PP BPN PNP K R Q ``` After 1000 moves the board may look like this: ``` 1000. Q K P N R R B N Q ``` And the game ends. Or Maybe after 556 turns the board look like this: ``` 556. R ``` So the game ends there. \*Please ensure all randomization done in this challenge is uniform (every possibility has an equal chance of occurring). [Answer] # [Python 2](https://docs.python.org/2/), ~~862~~ ~~846~~ 844 bytes ``` from random import* A=-1;a,b=[(0,1),(0,A),(A,0),(1,0)],[(A,A),(A,1),(1,A),(1,1)] r=range(8) C='RNBQK';q=C+'BNR' def m(x,y,B,t): P=B[y][x];M=[] for w,z in dict(zip('pP'+C,[[],[],a,zip([A,1,-2,2]*2,[2,2,1,1,-2,-2,A,A]),b]+[a+b]*2))[P]: for i in r[1:]: X,Y=x+z*i,y+w*i;M+=(X,Y), if P in'NK'or 1-(8>X>A<Y<8)or' '<B[Y][X]:break if P in'pP':d=[A,1][P<'p'];M=zip((x-1,x,x+1)[B[y+d][x-1]<'!':2+(B[y+d][-~x%8]>' ')],(y+d,)*3)+[(x,y+2*d)]*(t*B[y+d][x]<'!') return choice([(X,Y)for X,Y in M if-1<X<8>Y>A]) B=map(list,[q,'P'*8]+[' '*8]*4+['p'*8,q]) t=0 while t<1e3: t+=1;p=[(x,y)for y in r for x in r if' '<B[y][x]];shuffle(p) if len(p)<2:break while p:x,y=p.pop();Z=X,Y=m(x,y,B,t<2);B[Y][X],B[y][x]=B[y][x],' ';Z in p and p.remove(Z) for j in 0,7: for i in r: if B[j][i]in'pP':B[j][i]=choice(C) print t for l in B:print''.join(l).upper() ``` [Try it online!](https://tio.run/##VVLfb9owEH5e/grvYbKdXBBOJw0lMRLhsWrF@gRYfoCSDDNIXDddAw/719k5oZUmWXfnz75f3509t/umTq7XyjUn4jb1DpU52ca1YTCTscg2sJWKjUFwQDlDOYMxSoFSg8LbgIkem/VScB04idF@lWzCg7mkT4/Fz3uavch5RIvHJxrsyoqcWAdnKKDlaUAWslBnrTqdPUilA1I1jrzDhZia7Mxzyy7GMmoXNJqDUphYwwY8pjA1xAkkOkxAocZrD@DB2jSHrY7UJtriO@dqodPgi49tfGSnROoBsoSV7KJLaOAcvYcme4gkQ4wDvpmKLPAzfbyn6CdiNpkup7N8lU944yiheaFWWi11unXl5nfw@R@LTXfS16fVIqeW@tZ8yayLBXTQRYIrbDraYdux0Dn9StMkYjco/tt9m@gpJkCeGULAwzseKU9alIQ7rkPWhh/@vTcPiCvbN1eT531jnkum@iZ8u6h9ww9YXSzyZT6ZrqZITlDI08ayo3ltQb0AXdBwgnRhUtThd7QsWvCCP1s5Dt735liSNhflHY6sjaTIrOwr6pOce0770XWDaaqBoH6yOnvdv1XVsWSW9zQdyxrNPPlgbghvU4wn7cg2lvFsLf1sPlclT3h24xtuYT8WBzBVtvZ5LcFFJnbkylPzp2RrPqzTwb@N4cd/G5AOEy7UQSujb2O73eSNxjkGsM7ULWmHSEfvWqQ9Runo0JiaHfnozdrSMX69/gM "Python 2 – Try It Online") Saved 18 bytes thanks to Jonathan Frech [Answer] # PHP, 1849 bytes ``` <?$z=[R,N,B,Q,K,B,N,R];$y=[_,_,_,_,_,_,_,_];$u=shuffle;$b=[$z,[P,P,P,P,P,P,P,P],$y,$y,$y,$y,[p,p,p,p,p,p,p,p],$z];$z=[R,N,B,Q,K];for($i=0;$i<8;$i++)for($j=0;$j<8;$j++)$r[]=[$i,$j];for(;$c++<=999;){for($i=$_=0;$i<8;$i++)for($j=0;$j<8;$j++)if($b[$i][$j]!=_)++$_;if($_<2)break;$u($r);$n=[];foreach($r as$l){list($y,$x)=$l;$a=$y+1;$d=$y-1;$j=$x+1;$t=$x-1;$p=$b[$y][$x];if($n[$y][$x]!=1&&$p!=_){$v=$e=$f=$g=$h=$k=$o=$q=$s=[];if($p==R||$p==K||$p==Q){$m=($p==K)?2:9;for($i=1;$i<$m;$i++){if(!$e&&$y-$i>=0){$v[]=[$y-$i,$x];if($b[$y-$i][$x]!=_)$e=1;}if(!$f&&$y+$i<8){$v[]=[$y+$i,$x];if($b[$y+$i][$x]!=_)$f=1;}if(!$g&&$x-$i>=0){$v[]=[$y,$x-$i];if($b[$y][$x-$i]!=_)$g=1;}if(!$h&&$x+$i<8){$v[]=[$y,$x+$i];if($b[$y][$x+$i]!=_)$h=1;}}}if($p==B||$p==K||$p==Q){$m=($p==K)?2:9;for($i=1;$i<$m;$i++){if(!$k&&$y-$i>=0&&$x-$i>=0){$v[]=[$y-$i,$x-$i];if($b[$y-$i][$x-$i]!=_)$k=1;}if(!$o&&$y-$i>=0&&$x+$i<8){$v[]=[$y-$i,$x+$i];if($b[$y-$i][$x+$i]!=_)$o=1;}if(!$q&&$y+$i<8&&$x-$i>=0){$v[]=[$y+$i,$x-$i];if($b[$y+$i][$x-$i]!=_)$q=1;}if(!$s&&$y+$i<8&&$x+$i<8){$v[]=[$y+$i,$x+$i];if($b[$y+$i][$x+$i]!=_)$s=1;}}}if($p==N){if($y-2>=0&&$t>=0)$v[]=[$y-2,$t];if($y-2>=0&&$j<8)$v[]=[$y-2,$j];if($d>=0&&$x-2>=0)$v[]=[$d,$x-2];if($d>=0&&$x+2<8)$v[]=[$d,$x+2];if($a<8&&$x-2>=0)$v[]=[$a,$x-2];if($a<8&&$x+2<8)$v[]=[$a,$x+2];if($y+2<8&&$t>=0)$v[]=[$y+2,$t];if($y+2<8&&$j<8)$v[]=[$y+2,$j];}if($p==P){if($y==1&&$b[$a][$x]==_)$v[]=[$y+2,$x];if($j<8&&$b[$a][$j]!=_)$v[]=[$a,$j];if($t>=0&&$b[$a][$t]!=_)$v[]=[$a,$t];$v[]=[$a,$x];}if($p==p){if($y==6&&$b[$d][$x]==_)$v[]=[$y-2,$x];if($j<8&&$b[$d][$j]!=_)$v[]=[$d,$j];if($t>=0&&$b[$d][$t]!=_)$v[]=[$d,$t];$v[]=[$d,$x];}$u($v);$v=$v[0];$b[$y][$x]=_;$w=$p;if($w==P&&$v[0]>6&&$u($z)&&$w=$z[0]);if($w==p&&$v[0]<1&&$u($z)&&$w=$z[0]);$b[$v[0]][$v[1]]=$w;$n[$v[0]][$v[1]]=1;}}echo $c.". ";foreach($b as$a)echo str_replace([_,p],[' ',P],join("",$a))." ";} ``` [Try it online!](https://tio.run/##nVVdT6NQEH3fX6HNREvurbE8bLZLRxNfTYz6SgihBQRaCxbUfti/vt2ZeylfkmyyoeHmzsw5c@ZQLlmUHY/TW9ih/Swf5J18kvd0f5DPjgVbtF3Zuij4jnn0HobLwIIZ2rCT9qNsXY6Ebf2zM9m6KLsjlmY/xwrT9RBivLYgnv6imxCGCiUcSjiUUAjWtkMdYwmJhlgwF2KKk8nEMvYlB7j/oonDIcyIxrGJ5xxdQwhwLY66U9OYrQNvQVMOYW1YsEJbtQq8eUSRMy@HpbFfxnkx5PE2BsLSAg9hK8YW@LSOaE0QNrwvaOV9htxwSw03jmq0Ou3OcXxxARmr2MMHQoAQIrwgRAgLhBThDSFnEQzLEJ@/vni518sToV5RJe6NW/P35OTkmC2AV@3BnrDnEFCj7QjiG7zmXspK3suTqJnel7pcg8SMrYPChowV7GoNFR2oaELDCvpC0E23rVShGstADijsS4WNGNtpK1WkDRUnaMTQw6H06u6/vVrUXvXJ1661JiiNq4ZYVEOkba7OOJpK9FBVQ6UV1Vv1GPpUie@qREfVW0WVt6h6H63oYapE5S2nH5RvJN3UUxYsrBrRlFBopqqAXsZWPtF5/2S42SDweSqzXSDMmoDzosx7pTVNvNfAl/km3GvAt5zo6hcN/WW@KV9o@ScrHksrUL3ZZJ2n3gpk0xqI8sVJFF1ZpU@jWlZpSqFnLouKThEpawxS68gqHT812P@mY9Sjw@/q8Ht0@F0dflOHr3XwEfpBRyidah/2NWWrIxBdCz4RMsX6SZYRK5fcsFJC7QxaqWBHMeNUlJVF03FfEZNz1uFl7DgInxafsq0Y/2ODeZSewfxqcPVjUB/sMz7YPUMl82LtroNs6c2DIX3@6INlX55d8mctSePVcDCQVGlcDQh/OB7/pFkRp6v8OFr9BQ) It can *definitely* be golfed more, and it looks somewhat like the workings of a madman (which, I suppose, it may be). I am impressed at how fast random moves can clear the board (I've seen 15 moves do it). Also, I think the only one I saw hit the 1000 limit was two bishops on different colors dancing. ]
[Question] [ We've had a lot of challenges on differentiation and integration, but none on just solving related rates problems. So in this challenge, you will get a bunch of derivatives (They will be numeric, not in terms of any variables) and have to find another derivative. The input will come in a newline separated list of equations, in the form `dx/dt = 4`. There can be decimals and negatives. The input will end with one differential, the one you will have to find. You can assume there will always be enough information to find it, butt there may also be excess information. You may also have to consider the derivative of the inverse function, e.g. if you have `dy/dx = 3`, you also know that `dx/dy = 1/3`. Your output will be in the form `dy/dt = 6`. All the whitespace, etc. has to be the same. Assume all variables are always one letter (They can be uppercase, and they can be `d`). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! ## Test Cases ``` dy/dx = 4 dx/dt = 5 dy/dt answer: dy/dt = 20 dy/dx = -3 dt/dx = 3 dy/dt answer: dy/dt = -1 dA/dt = 4 dA/dC = 2 dC/dr = 6.28 dr/dt answer: dr/dt = 0.3184713375796178 dx/dy = 7 dx/dt = 0 dy/dt answer: dy/dt = 0 ``` [Answer] ## Python - ~~278~~ 275 No one else has done this yet, so I thought I'd submit this, even though it isn't golfed very well yet. ``` a={} e={} k=input i=k() while"="in i: b,d=i.split(" =");b,c=b.split("/");d=float(d) if d:a[b]=a.get(b,[])+[[c,1/d]] a[c]=a.get(c,[])+[[b,d]];i=k() i=i.split("/") def f(x): for j in a.get(x,[]): if j[0] not in e:e[j[0]]=e[x]*j[1];f(j[0]) e[i[1]]=1 f(i[1]) print(e[i[0]]) ``` Here it is partially ungolfed: ``` a={} e={} i=input() while "=" in i: b,d=i.split(" =") b,c=b.split("/") d=float(d) if d:a[b]=a.get(b,[])+[[c,1/d]] a[c]=a.get(c,[])+[[b,d]] i=input() i=i.split("/") def f(x): for j in a.get(x,[]): if j[0] not in e:e[j[0]]=e[x]*j[1];f(j[0]) e[i[1]]=1 f(i[1]) print(e[i[0]]) ``` Three bytes were saved by Thomas Kwa. ]
[Question] [ Here is a list of some common [ligatures](https://en.wikipedia.org/wiki/Typographic_ligature) in Unicode (the ones I could create with my Compose key on Debian): ``` Orig Ascii Lig ae [ae] æ AE [AE] Æ oe [oe] œ OE [OE] Œ ij [ij] ij IJ [IJ] IJ ff [ff] ff fi [fi] fi fl [fl] fl ffi [ffi] ffi ffl [ffl] ffl ``` You have two options in this challenge: use the actual UTF-8 ligatures, or use the ASCII-only variant. If you use the actual UTF-8 ligature variants, you gain a 20% bonus. If you use the ASCII-only variant, you may assume square brackets will never be involved except to signify a ligature. The challenge: given a string as input, output the same string * with all original ligatures replaced by their expanded counterparts. + match greedily: `affib` becomes `affib` (`a[ffi]b`), not `affib` (`a[ff]ib`) or `affib` (`af[fi]b`). * with all "expanded" letter sequences replaced by ligatures. + for example, `æOEfoo` (`[ae]OEfoo`) becomes `aeŒfoo` (`ae[OE]foo`). Do this completely independently: `ffi` (`[ff]i`) becomes `ffi` (`ffi`), not `ffi` (`[ffi]`). Sound simple enough? There's a catch: every time two non-ligatures overlap by *exactly one character*, **both** of the ligatures must be inserted into the string. Here's a few test cases to demonstrate: ``` Input Ascii-output Output fij [fi][ij] fiij fIJ f[IJ] fIJ * remember, capitalization matters! fffi [ff][ffi] ffffi fff [ff][ff] ffff ffffi [ff][ff][ffi] ffffffi ffffij [ff][ff][ffi][ij] ffffffiij ``` Be careful: the same greedy matching applies (note especially the last few test cases). [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Answer] # JavaScript (ES6), 213 bytes - 20% bonus = 170.4 ``` s=>eval('for(p=o="";m=s.match(r="ffl|ffi|fl|fi|ff|IJ|ij|Œ|œ|Æ|æ|ffl|ffi|fl|fi|ff|IJ|ij|OE|oe|AE|ae",x=r.split`|`);s=s.slice(i+t.length-(p=t<"z")))o+=s.slice(p,i=m.index)+x[(x.indexOf(t=m[0])+11)%22];o+s.slice(p)') ``` ## Explanation ``` s=> // s = input string eval(` // use eval to avoid writing {} or return for( // iterate over each ligature match p= // p = 1 if the last match was a non-unicode ligature o=""; // o = output string m=s.match( // find the next ligature // r = regex string for ligatures (unicode and non-unicode) r="ffl|ffi|fl|fi|ff|IJ|ij|Œ|œ|Æ|æ|ffl|ffi|fl|fi|ff|IJ|ij|OE|oe|AE|ae", x=r.split\`|\` // x = arrray of r ); s=s.slice(i+t.length // remove the part that has been added to the output -(p=t<"z")) // if we matched a non-unicode ligature, keep the last ) // character so it can be part of the next match o+=s.slice(p,i=m.index) // add the text before the match to the output +x[(x.indexOf( // add the opposite type of the matched ligature t=m[0] // t = matched text )+11)%22]; // (index + 11) % 22 returns the opposite index o+s.slice(p) // return o + any remaining characters `) ``` ## Test ``` var solution = s=>eval('for(p=o="";m=s.match(r="ffl|ffi|fl|fi|ff|IJ|ij|Œ|œ|Æ|æ|ffl|ffi|fl|fi|ff|IJ|ij|OE|oe|AE|ae",x=r.split`|`);s=s.slice(i+t.length-(p=t<"z")))o+=s.slice(p,i=m.index)+x[(x.indexOf(t=m[0])+11)%22];o+s.slice(p)') ``` ``` <input type="text" id="input" value="ffiffffij" oninput="result.textContent=solution(input.value)" /> <pre id="result"></pre> ``` ]
[Question] [ # This is what I thought [this question](https://codegolf.stackexchange.com/q/55574/7416) was going to be, before I fully read it. A group of code golfers walk into The Nineteenth Bite Pizzeria and order a pizza. It comes in an irregular shape, made of unit squares. Your task is to help them cut it into identical slices. That is, the slices must have the exact same shape and size; they can be rotated but not flipped/mirrored. For example, if they are Tetris pieces, they must be the same kind, you can't use both an L piece and a J piece. ## Input You will be given the number of people in the group on the first line (always an integer from 2 to 10, inclusive), followed by a rectangular matrix of ' ' (space) and '#' characters, representing the pizza. All the '#' characters are connected through their edges. The number of '#' characters is guaranteed to be a multiple of the number of people. ## Output You should print the same matrix, with each '#' character replaced with a digit from 0 to n-1 (n being the number of people). Each digit should mark a slice. The slice shape must be connected through the square edges. The slice numbering doesn't need to be in any particular order. If there are multiple ways of cutting the pizza, any of them is acceptable. If it's not possible to cut the pizza as required, you should print the string "No pizza for you!" instead. ## Scoring This is code golf. Your score will be the number of bytes in the program. Characters will be counted through their UTF-8 encoding. Lowest score wins. ## Examples Input: ``` 3 # ### #### # ``` Output: ``` 0 100 1122 2 ``` --- Input: ``` 4 ### # # ### ``` Output: ``` 001 2 1 233 ``` --- Input: ``` 2 # # ###### ``` Output: ``` No pizza for you! ``` --- Input: ``` 5 # #### ##### ##### ##### #### # ``` Output: ``` 0 1000 21110 32221 43332 4443 4 ``` --- Input: ``` 4 # #### ###### ##### #### ``` Output: ``` 0 1000 111203 12233 2233 ``` ## Requirements * You should write a full program that reads from the standard input and writes to the standard output. * The program must be runnable in Linux using freely available software. * Your program should finish each of the above examples in less than 1 minute on a modern computer. * No standard loopholes. [Answer] ## PHP code, ~~1808~~ 971 bytes Quick and dirty implementation in PHP. First brute-force all possible slice shapes, next brute-force all positions and orientations of the slices. Usage: `cat pizza.txt | php pizza.php` Edit: reduced code size by more than 45% by rewring algorithm using recursion rather than nested loops. However, this eats memory (and pizza's ;-)). Pizza's larger than 8x8 will probably run out of memory. The nested loop variant can easily handle any size, but is twice the code size. ``` <?php define('A',98);$n=fgets(STDIN);$d=array();$m=$u=str_pad('',A,'+');$s=0;while($g=fgets(STDIN)){$g=rtrim($g);assert(strlen($g)<=A-2);$s++;$m.='+'.str_pad(rtrim($g),A-2,' ').'+';for($l=0;$l<strlen($g);$l++)if($g[$l]=='#')$d[]=$s*A+$l+1;}$m.=$u;$r=count($d)/$n;x(reset($d),array(array()),0,0,0,0);die('No pizza for you!');function x($e,$c,$b,$a,$q,$t){global$r,$m,$d;$h=$a*A+$b;if(!in_array($e+$h,$d))return;if(in_array($h,$c[0]))return;$c[0][]=$h;$c[1][]=$b*A-$a;$c[2][]=-$a*A-$b;$c[3][]=-$b*A+$a;if(count($c[0])<$r)do{x($e,$c,$b+1,$a,$b,$a);x($e,$c,$b,$a+1,$b,$a);x($e,$c,$b-1,$a,$b,$a);x($e,$c,$b,$a-1,$b,$a);$v=($b!=$q||$a!=$t);$b=$q;$a=$t;}while($v);else w($c,$m,0,reset($d),0);}function w(&$p,$f,$o,$e,$i){global$n,$d;foreach($p[$i]as$h){$j=$e+$h;if(!isset($f[$j])||$f[$j]!='#')return;$f[$j]=chr(ord('0')+$o);}if(++$o==$n){for($k=A;$k<strlen($f)-A;$k++)if($k%A==A-1)echo PHP_EOL;else if($k%A)echo$f[$k];exit;}foreach($d as$j)for($i=0;$i<4;$i++)w($p,$f,$o,$j,$i);} ``` **Ungolfed, documented code** Below is the documented, original code. To keep my sanity, I worked with the full source code, and wrote a simple minifier script to strip statements like `assert()` and `error_reporting()`, remove unnecessary brackets, rename variables, functions and constants to generate the golfed code above. ``` <?php error_reporting(E_ALL) ; // Width of each line of pizza shape. // Constant will be reduced to single character by minifier, // so the extra cost of the define() will be gained back. define('WIDTH', 98) ; // Read number of slices $nrSlices = fgets(STDIN) ; // Read pizza shape definition and // convert to individual $positionList[]=$y*width+$x and // linear (1D) $pizzaShape[$y*WIDTH+$x] with protective border around it. // // WARNING: assumes maximum pizza width of WIDTH-2 characters! $positionList = array() ; $pizzaShape = $headerFooter = str_pad('', WIDTH, '+') ; $y = 0 ; while ($line = fgets(STDIN)) { $line = rtrim($line) ; assert(strlen($line) <= WIDTH-2) ; $y++ ; $pizzaShape .= '+'.str_pad(rtrim($line), WIDTH-2, ' ').'+' ; for ($x = 0 ; $x < strlen($line) ; $x++) { if ($line[$x] == '#') $positionList[] = $y*WIDTH + $x+1 ; } } $pizzaShape .= $headerFooter ; // Determine size of a slice $sliceSize = count($positionList)/$nrSlices ; // Build all possible slice shapes. All shapes start with their first part at // the top of the pizza, and "grow" new parts in all directions next to the // existing parts. This continues until the slice has the full size. This way // we end up with all shapes that fit at the top of the pizza. // // The shape is defined as the offsets of the parts relative to the base // position at the top of the pizza. Offsets are defined as linear offsets in // the 1-D $pizzaShape string. // // For efficiency, we keep track of all four possible rotations while building // the slice shape. // growSlice(reset($positionList), array(array()), 0, 0, 0, 0) ; die('No pizza for you!') ; function growSlice($basePosition, $shapeDeltas, $dx, $dy, $prevDx, $prevDy) { global $sliceSize, $pizzaShape, $positionList ; // Check validity of new position // Abort if position is not part of pizza, or // if position is already part of slice $delta = $dy*WIDTH + $dx ; if (!in_array($basePosition+$delta, $positionList)) return ; if (in_array($delta, $shapeDeltas[0])) return ; // Add all four rotations to shapeDeltas[] $shapeDeltas[0][] = $delta ; $shapeDeltas[1][] = $dx*WIDTH - $dy ; $shapeDeltas[2][] = -$dy*WIDTH - $dx ; $shapeDeltas[3][] = -$dx*WIDTH + $dy ; // Have we built a full slice shape? if (count($shapeDeltas[0]) < $sliceSize) { // Grow shape either at current position or at previous position do { growSlice($basePosition, $shapeDeltas, $dx+1, $dy, $dx, $dy) ; growSlice($basePosition, $shapeDeltas, $dx, $dy+1, $dx, $dy) ; growSlice($basePosition, $shapeDeltas, $dx-1, $dy, $dx, $dy) ; growSlice($basePosition, $shapeDeltas, $dx, $dy-1, $dx, $dy) ; $retry = ($dx != $prevDx || $dy != $prevDy) ; $dx = $prevDx ; $dy = $prevDy ; } while ($retry) ; } else { // Try to cover the entire pizza by translated and rotated instances of // the slice shape. fitSlice($shapeDeltas, $pizzaShape, 0, reset($positionList), 0) ; } } function fitSlice(&$shape, $pizza, $id, $basePosition, $rotation) { global $nrSlices, $positionList ; // Try to fit each part of the slice onto the pizza. If the part falls // outsize the pizza, or overlays another slice we reject this position // and rotation. If it fits, we mark the $pizza[] with the slice $id. foreach ($shape[$rotation] as $delta) { $position = $basePosition + $delta ; if (!isset($pizza[$position]) || $pizza[$position] != '#') return ; $pizza[$position] = chr(ord('0')+$id) ; } // If $nrSlices slices have been fitted, we have found a valid solution! // In that case, we display the solution and quit. if (++$id == $nrSlices) { for ($pos = WIDTH ; $pos < strlen($pizza)-WIDTH ; $pos++) { if ($pos % WIDTH == WIDTH-1) echo PHP_EOL ; else if ($pos % WIDTH) echo $pizza[$pos] ; } exit ; } // The current slice did fit, but we have still more slices to fit. // Try all positions and rotations for the next slice. foreach ($positionList as $position) { for ($rotation = 0 ; $rotation < 4 ; $rotation++) { fitSlice($shape, $pizza, $id, $position, $rotation) ; } } } ``` ]
[Question] [ > > **Austin:** "Who sent you?" > > > **Mustafa:** "You have to kill me!" > > > **Austin:** "Who sent you?" > > > **Mustafa:** "Kiss my ass, Powers!" > > > **Austin:** "Who sent you?" > > > **Mustafa:** "Dr. Evil." > > > (...) > > > **Mustafa:** "I can't stand to be asked the same question three times. It just irritates me." > > > You are to simulate a short dialogue in the spirit of [Austin Powers and Mustafa](https://www.youtube.com/watch?v=AmFSW6p94rg). But the data source for the entire conversation will be a StackOverflow question (provided as input from a URL). # Rules The question asker's username will be used in place of "Austin". The question they will ask three times comes from the last sentence in the question title, (which has been forced to end in a question mark if it did not already). StackExchange will be playing the part of "Mustafa". The answer ultimately given comes from the first sentence in the answer that does not end in a question mark, and will be attributed to the name of the user who answered. For a question to qualify for the game, it must (a) have an answer, and (b) there must be a sequence of comments on the original question that goes: * comment from someone other than questioner * (any number of skipped comments) * comment from questioner * comment from someone other than questioner * (any number of skippable comments) * comment from questioner If this sequence is not satisfied *prior to the date of the top ranked answer*, the program should simply output `"Oh, behave!"` StackExchange Mustafa's angry retorts come from the first sentence of the comments from someone other than the questioner that *don't* end with a question mark--and ensuring it ends with an exclamation mark. If no sentence exists in the comment that doesn't end in a question mark, it is skipped as a candidate for the retort. Comment retorts are attributed to the user name of the author. # Clarifications * Strip any leading "@XXX" response data from a comment. * Because StackOverflow summarizes the comments if there are many of them, you will probably have to use a second request to get the full list. That request is of the form `https://stackoverflow.com/posts/NNN/comments?_=MMM` with the post ID in N and question ID in M. See for instance: <https://stackoverflow.com/posts/11227809/comments?_=211160> * URLs should be stripped to anchor text only. * We'll define a "sentence" as anything outside of a code block that ends in a period, question mark, or exclamation point. If a run of text has no ending punctuation of this form, then the end of the text is the end of the sentence; as if it were written with a period. * If you're looking for funny test cases that are likely to qualify, you might try using StackExchange Data Explorer, such as [Posts with the Most Comments](http://data.stackexchange.com/stackoverflow/query/209208/posts-with-the-most-comments). * *... more to come, I'll wager...* # Samples ### Sample One **Input:** `https://stackoverflow.com/questions/2283937/how-should-i-ethically-approach-user-password-storage-for-later-plaintext-retrie/` **Output:** > > **shanee:** "How should I ethically approach user password storage for later plaintext retrieval?" > > > **stefanw:** "I think he knows that it is not good!" > > > **shanee:** "How should I ethically approach user password storage for later plaintext retrieval?" > > > **Rook:** "Perhaps you should ask how you can implement a Buffer Overflow Vulnerability in a Secure way!" > > > **shanee:** "How should I ethically approach user password storage for later plaintext retrieval?" > > > **Michael Burr:** "Ask why the password is required to be in plaintext: if it's so that the user can retrieve the password, then strictly speaking you don't really need to retrieve the password they set (they don't remember what it is anyway), you need to be able to give them a password they can use." > > > ### Sample Two **Input:** `http://scifi.stackexchange.com/questions/2611/why-dont-muggle-born-wizards-use-muggle-technology-to-fight-death-eaters` **Output:** > > **DVK:** "Why don't muggle-born wizards use Muggle technology to fight Death Eaters?" > > > **DampeS8N:** "This dances on the edge again!" > > > **DVK:** "Why don't muggle-born wizards use Muggle technology to fight Death Eaters?" > > > **DampeS8N:** "Right, but this site isn't about pointing out plot holes!" > > > **DVK:** "Why don't muggle-born wizards use Muggle technology to fight Death Eaters?" > > > **Jeff:** "I believe, though I've been unable to find a reference, that JK Rowling actually mentioned this at one point." > > > ### Sample Three **Input:** `https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array` **Output:** > > "Oh, behave!" > > > *(The top rated answer time is `Jun 27 '12 at 13:56`, while the second follow-up comment on the question by the questioner is at time `Jun 27 '12 at 14:52`. Hence, there isn't a causal link between the second follow-up and the answer. :-P)* ## Winning Criteria Code Golf - shortest code wins. [Answer] # PHP, 1282 chars While 1282 quite huge for a code golf challenge, the challenge is quite complex. (And I am not very good at golf.) ``` <?php function a($a,$b='q'){$a=strip_tags(htmlspecialchars_decode($a,ENT_QUOTES));$a=preg_replace('/^@[^ ]+\s+/','',$a);$a=mb_split('(?<=(?:\.|!|\?))\s+',$a);if($b=='q'){return preg_replace('/(?:\.|!|\?)$/','',$a[0]).'?';}else{foreach($a as$s){if(!preg_match('/\?$/',$s)){if($b=='c'){return preg_replace('/(?:\.|!)$/','',$s).'!';}else{return preg_replace('/(?<!(?:\.|!))$/','.',$s);}}}}return 0;}function b($a){return json_decode(gzdecode(file_get_contents('http://api.stackexchange.com/2.2/questions/'.$a)));}function c($a){return $a->owner->display_name;}$n="\n";$x="Oh, behave!\n";$r=parse_url($argv[1]);$b=explode('/',$r['path']);$b=$b[2];$u=b($b.'?site='.$r['host']);$u=$u->items[0];$c=b($b.'/comments?filter=withbody&order=asc&sort=creation&site='.$r['host']);$a=b($b.'/answers?filter=withbody&order=desc&sort=votes&site='.$r['host']);if(!count($a->items)||!count($c->items))die($x);$a=$a->items[0];$s=array();$d=1;foreach($c->items as$e){if($e->creation_date>$a->creation_date)break;if($e->owner->user_id==$u->owner->user_id){$d=1;}elseif($d){$e->body=a($e->body,'c');if($e->body){$s[]=$e;}$d=0;}}if(count($s)<2)die($x);$q=c($u).': "'.a($u->title,'q').'"'.$n;echo$q.c($s[0]).': "'.$s[0]->body.'"'.$n.$q.c($s[1]).': "'.$s[1]->body.'"'.$n.$q.c($a).': "'.a($a->body,'a').'"'.$n; ``` ## Ungolfed version ``` <?php function firstSentence($string, $type = 'q') { $string = strip_tags(htmlspecialchars_decode($string, ENT_QUOTES)); $string = preg_replace('/^@[^ ]+\s+/', '', $string); $string = mb_split('(?<=(?:\.|!|\?))\s+', $string); if($type === 'q') { return preg_replace('/(?:\.|!|\?)$/', '', $string[0]) . '?'; } else { foreach($string as $s) { if(!preg_match('/\?$/', $s)) { if($type === 'c') { return preg_replace('/(?:\.|!)$/', '', $s) . '!'; } else { return preg_replace('/(?<!(?:\.|!))$/', '.', $s); } } } } return false; } $x = "Oh, behave!\n"; $url = parse_url($argv[1]); $api = 'http://api.stackexchange.com/2.2/'; $id = explode('/', $url['path']); $id = $id[2]; $question = json_decode(gzdecode(file_get_contents($api . 'questions/' . $id . '?site=' . $url['host']))); $question = $question->items[0]; $comments = json_decode(gzdecode(file_get_contents($api . 'questions/' . $id . '/comments?filter=withbody&order=asc&sort=creation&site=' . $url['host']))); $answer = json_decode(gzdecode(file_get_contents($api . 'questions/' . $id . '/answers?filter=withbody&order=desc&sort=votes&site=' . $url['host']))); if(!count($answer->items) || !count($comments->items)) die($x); $answer = $answer->items[0]; $selected = array(); $usable = true; foreach($comments->items as $comment) { if($comment->creation_date > $answer->creation_date) break; if($comment->owner->user_id === $question->owner->user_id) { $usable = true; } elseif($usable) { $comment->body = firstSentence($comment->body, 'c'); if($comment->body !== false) { $selected[] = $comment; } $usable = false; } } if(count($selected) < 2) die($x); $q = $question->owner->display_name . ': "' . firstSentence($question->title, 'q') . '"' . "\n"; echo $q; echo $selected[0]->owner->display_name . ': "' . $selected[0]->body . '"' . "\n"; echo $q; echo $selected[1]->owner->display_name . ': "' . $selected[1]->body . '"' . "\n"; echo $q; echo $answer->owner->display_name . ': "' . firstSentence($answer->body, 'a') . '"' . "\n"; ?> ``` ]
[Question] [ Given an array of \$n\$ positive integers we will say its *self-sum order* is the number of ways to add elements from it to make \$n\$. We will count ways as distinct up to associativity. So \$1+(2+3)\$ and \$(1+2)+3\$ are not counted as separate ways to make 6, but \$2+4\$ and \$4+2\$ are counted as separate. Two sums are the same if they are the same when written without parentheses. You may not reuse elements of the array in your sum, but the same number can appear multiple times in the array. So if the array is `[1,1,2,3]`, then \$1+1+2\$ should be counted, but \$2+2\$ should not. As an example here's one array with all the distinct sums listed out: ``` [1,1,2,3] 1+3 3+1 1+1+2 1+2+1 2+1+1 ``` It's self sum order is 5. ## Task Given a non-negative integer, \$n\$, as input, output the array of length \$n\$ with the highest self-sum order. Since there will be multiple arrays (often just permutations of the same array) with the highest self-sum order, you may output any one of them. Your answer will be scored by it's big \$O\$ asymptotic time complexity in terms of \$n\$, with faster algorithms being better. ## Example outputs: You do not need to output the order it is included for your convenience. ``` 0 -> 1 [] 1 -> 1 [1] 2 -> 1 [1,1] 3 -> 3 [1,2,3] 4 -> 5 [1,1,2,3] 5 -> 9 [1,1,1,2,3] 6 -> 17 [1,1,2,2,3,4] 7 -> 37 [1,1,1,2,2,3,4] 8 -> 73 [1,1,1,1,2,2,3,4] 9 -> 138 [1,1,1,1,2,2,3,4,5] 10 -> 279 [1,1,1,1,2,2,2,3,4,5] 11 -> 578 [1,1,1,1,2,2,2,3,3,4,5] 12 -> 1228 [1,1,1,1,1,2,2,2,3,3,4,5] 13 -> 2475 [1,1,1,1,1,1,2,2,2,3,3,4,5] 14 -> 4970 [1,1,1,1,1,1,2,2,2,3,3,4,5,6] ``` *These cases were generated by a computer program, there is a chance there is an error. If you believe that there is an error, just let me know.* [Answer] # Python3, seems like it might be `o(3^n)` or thereabouts Tracks subsets and then counts the distinct permutations in closed form, merges together subsets with the same length, sum, and lowest run, and uses a bound to cut off unpromising states (it could be tighter). ``` import collections import copy import functools import random from fractions import Fraction from math import factorial class Subset: def __init__(self, n): self.high_size = Fraction(1, 1) self.high_count = 0 self.n = n self.n_count = 0 self.sum = 0 def increment(self): self.sum += self.n self.n_count += 1 def restrict(self, x): if x >= self.n: return self.high_size *= Fraction(1, factorial(self.n_count)) self.high_count += self.n_count self.n = x self.n_count = 0 def count_size(self): return factorial(self.n_count + self.high_count) * self.high_size * Fraction(1, factorial(self.n_count)) def state_tuple(self): return (self.high_size, self.high_count, self.n, self.n_count, self.sum) def __eq__(self, other): return self.state_tuple() == other.state_tuple() def __hash__(self): return hash(self.state_tuple()) @functools.lru_cache(None) def sum_partitions(k, n, l): if n == 0: return 1 if l == 0: return 0 t = 0 for i in range(1, k + 1): if l * i >= n: t += sum_partitions(i, n - i, l - 1) return t @functools.lru_cache(None) def f(partial_sums, k, n, l): global best if l == 0: s = sum(u.count_size() for u in partial_sums) best = max(s, best) return s bound = sum(factorial(u.n_count + u.high_count + l) * u.high_size * sum_partitions(u.n, n - u.sum, l) * Fraction(1, factorial(u.n_count)) for u in partial_sums) if bound <= best: return 0 c = 0 for i in range(1, k + 1): a = [copy.deepcopy(u) for u in partial_sums if u.n >= i and u.sum + i <= n and u.sum + l * i >= n] b = [copy.deepcopy(u) for u in partial_sums if u.sum + (l - 1) * (i - 1) >= n] for u in a: u.restrict(i) u.increment() for u in b: u.restrict(i - 1) s = a + b q = collections.defaultdict(lambda: 0) for u in s: w = u.high_size u.high_size = 0 q[u] += w s = set() for u, w in q.items(): u.high_size = w s.add(u) c = max(c, f(frozenset(s), i, n, l - 1)) return c for n in range(20): best = 0 print(n, f(frozenset([Subset(n)]), n, n, n)) ``` ]
[Question] [ ## The task A string `S` is constructed with the following process: 1. Start with `S` being the empty string. 2. Insert at some position of `S` a string of the form `ds`, where `d` is a nonzero digit and `s` is a string of `d` lowercase ASCII letters. We say `ds` is a *constituent* of `S`. 3. Go to step 2 or stop. Your task is to take such a string as input, and output its constituents concatenated into a single string, in the order of appearance of their leading digits. The output must be a single string, and there can't be any delimiters (including newlines) between the constituents. You can choose whether the input and output strings have quotes. Note that the input and output will never be empty. ## Example Let's construct a string with the above process. The structure of the constituents is highlighted in the final result. ``` S = "" // Insert "3abc" S = "3abc" // Insert "2gh" after 'a' S = "3a2ghbc" // Insert "1x" before '3' S = "1x3a2ghbc" // Insert "3tty" after '3' S = "1x33ttya2ghbc" // Final result └┘│└┴┴┘│└┴┘││ └────┴───┴┘ ``` The output is obtained by concatenating the constituents in the order of their digits. In this case, the correct output is ``` "1x3abc3tty2gh" ``` ## Rules and scoring You can write a full program or a function. the lowest byte count wins, and standard loopholes are disallowed. ## Test cases ``` 1k -> 1k 4asdf -> 4asdf 111xyz -> 1z1y1x 8whatever3yes -> 8whatever3yes 8what3yesever -> 8whatever3yes 1x33ttya2ghbc -> 1x3abc3tty2gh 63252supernestedstrings2ok -> 6trings3eds2st5perne2su2ok 9long3yes4lo2ngwords11here -> 9longrdsre3yes4lowo2ng1e1h 9abc8de7fg6hi5jk4lm3o2pq1rstuvwxyzabcdefghijklmnopqrst -> 9abcopqrst8deijklmn7fgdefgh6hizabc5jkwxy4lmuv3ost2pq1r ``` [Answer] # JavaScript (ES6), 68 bytes ``` f=s=>s&&f(s.replace(/\d\D+$/,m=>(s=m.slice(0,i=++m[0]),m.slice(i))))+s ``` ## Explanation Based on a simple concept: * Match the last digit `n` followed by `n` letters in the input string * Remove it from the input string and add it to the start of the output string * Repeat until the input string is empty Recursion was the shortest way to do this in JavaScript. ``` f=s=> s&& // if the input string is empty, return the empty string f( // prepend the constituent before it s.replace(/\d\D+$/,m=>( // match the last digit followed by every remaining letter s=m.slice(0,n=++m[0]), // set s to the constituent (n followed by n letters) // (we must use s because it is our only local variable) m.slice(n) // replace the match with only the letters after it )) )+s // append the constituent ``` ``` <input type="text" id="input" value="9long3yes4lo2ngwords11here" /> <button onclick="result.textContent=f(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] # [Haskell](https://www.haskell.org/), 89 bytes ``` fst.p p(d:s)|(h,(g,r))<-p<$>span('9'<)s,(a,b)<-splitAt(read[d])$h++r=(d:a++g,b) p e=(e,e) ``` [Try it online!](https://tio.run/##nVDJTsMwEL37K6wKqYmaIDlpC0UtEnc4cQQObjOxQ9LEeNyN5dcJYxchVYgLt5m3eZ61xBqapi8Xj32J7twwExVXGL9HOolUYuN4npr52TUa2UbD2XAeYxLJZEkwmqZyNy6yIIuH4ik@06ORXZBbjkaKFMxwWESQQNyvZdXyBV9Lc8cjs3H3zt62/JyXMeMPA1EPEj4YSyxKPwgh9odXP13utHSwBZsfAH8Av3gwaPd57txBZkovVx6Y5tkkw40B2wI6KNDZqlWYdeGNWdO1yvvHTZe1atfZAoXQYCGwcrm6LOCiVFNdTZ7rcbPOu8y8CItus93RUSQooFS6eq6bdduZF2IGT4y9pUzUPL3momahh5/DwI5tAvcqDmLPTkp5/ARgJxV/0yeFQ@o@p6s8RhD7u77XTo9bTniGbhJUpCaW/f0z3hhYQix8S3ZeJEBo9r9PC6FEHDfyH0lKCVKK8jaKowBK3GzzDl1IZelH/7kqG6mwT1fGfAE "Haskell – Try It Online") Example usage: `fst.p $ "1x33ttya2ghbc"` yields `"1x3abc3tty2gh"`. [Answer] # [Python 3](https://docs.python.org/3/), ~~173~~ 159 bytes ``` k='123456789';y='';i=0 for t in x: i+=1 if t in k: y+=t;n=int(t);m=0 for z in x[i:]: if n: if z in k:m+=int(z)+1 if m<1:y+=z;n-=1 m-=m>0 ``` [Try it online!](https://tio.run/##NYzLDsIgEEX3/YrZYdOYiPVZHH/EuPBVixWoFWvh5@tQ4oYM995zGmcro/OhR7Y9nS@b621d3leVXD7qxVPlZt68ePu2n@7bO0@D6628V/JRP5U2zYsalnQRjV8SxJY045ZcgSMfGUj56XLztqOWDTUyPs8Xy9V6s2XCIWNC4iwpTQsWpIa@SEBmyOktY1JTAi5DKzRKbSc2FYoIgMD4kTnI4hhWgdEFQDjD7SOvshH0acb/jdrxgpxe6CnGUE1R7WdD04apS5N4dOnwAw "Python 3 – Try It Online") Probably not the golfiest Python implementation. The logic is almost straightforward: it scans the string. When it finds a digit it starts adding the characters that follow, as many as required (i.e. until the count corresponds to the digit). If it encounters digits before completing the task, it adds them to a counter corresponding to the number of characters to skip. When the counter reaches zero, it goes back to adding characters (i.e. until the count corresponds to the initial digit). Note: Saved 14 bytes thanks to Wheat Wizard and HyperNeutrino [Answer] # Java 8, 152 bytes ``` s->{String t=s,r="";for(char c;!s.isEmpty();c=t.charAt(0),s=s.replace(t=c+(t.substring(1,c-47)),""),r=t+r)t=s.replaceAll(".*(\\d\\D+$)","$1");return r;} ``` **Explanation:** [Try it here.](https://tio.run/##jZFNb@MgEIbv/RUU9QCNYxU7/VhZXqnS9ri99NjsgWD8kWBwmXFSb5XfnuLU0p4qrwQSzDwzvO@wlXu5dJ2222J3UkYCkN@ysR8XhDQWtS@l0uR5vBLygr6xFVFsOgDPQvwYdliAEhtFnoklOTnB8ufHRGEOkc8pzUrnmaqlJyq7hLiBp7bDgfFM5RiP8UdkNzyCHGKvOxPeZZirBcMY@g2cezERqeXqnvOIUh6a4sJz/Mc/GsNofM3W62K9/rW44jSiV4LyzGvsvSU@O56yL7VdvzFB7SR675qCtMH25Oz1D5F88jwA6jZ2PcZdSKGxzMaKUbGj/Gz/e2QloShnKSHE@/B3Fns41BL1Xvt00PB/9EiOFfMS3tMUcZBJVW/ULH2XJrcJ9J32Vgei@PoaSNz8RH4YZ6tR1sq4xFYH5wsQotZez5fKjXoo9H1Z3dXN7Xa3Mm3qku5NeMB@fwgjDEChy6putjvTWte9hczU9nhxPH0C) ``` s->{ // Method with String as both parameter and return-type String t=s, // Temp-String, starting at the input-String r=""; // Result-String, starting empty for(char c;!s.isEmpty(); // Loop as long as the input-String `s` is not empty // After every iteration: c=t.charAt(0), // Get the leading digit from `t` as character s=s.replace(t=c+(t.substring(1,c-47)) // Set `t` to the last substring (digit + `c` letters), ,""), // and remove that sub-string from String `s` r=t+r) // And add the substring at the start of result-String `r` t=s.replaceAll(".*(\\d\\D+$)","$1"); // Get the last digit + everything after it, // and set this substring to `t` // End of loop (implicit / single-line body) return r; // Return result-String } // End of method ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~151~~ ~~147~~ 135 bytes ``` d,D=[],[] for c in input(): if'/'<c<':':x=[[c]];d=x+d;D+=x else:y=d[0];y+=c;d=d[len(y)>int(y[0]):] print''.join(''.join(w)for w in D) ``` [Try it online!](https://tio.run/##NU5BksIgELznFZQXktLaXYi6bjR78hepHCJMAooQAU3Yz2fhYNVU9fT0zHSPwQuj6cIMB1Sj1Wq18M25btpN02a9sYghqWONT58XVYZkjz/xiZ1whau5bhrWtkdez2t@PK/rOUOgHFSh5s1XewzrmkWRNwp0HopfqX0eolBUbTbayDD@uBqp8zdORXKckuO5WGKWLJuEVIBIBTMwlEIumNxwhred431EQsgc/mJzmETn4QW2DODePPVplhbnsvQ@dHQQFxb5vqQ76p4jWA3OA3c@JhocNen7jzJ6SMdbZageJmO5I0SAhSR2F3bg8N0PeyF319tW3UtDxwexzj9fU4wTFzj0g5DXm7prMz6igv8B "Python 2 – Try It Online") **Explanation:** The code keeps two lists of constituent groups, `d and D`. Each character of the string is then scanned: * If it is a digit, a new group is added to both lists * Otherwise, the character is added to the latest group in `d` When a group has the same length as its digit, the group is removed from `d`. At the end, the `D` is concatenated, as the groups in `D` are in the original order. **Example:** ``` Input = '1121xwyzv' d = [], D = [] Loop each character in the input c='1' d=[[1]], D=[[1]] c='1' d=[[1], [1]], D=[[1], [1]] c='2' d=[[2], [1], [1]], D=[[1], [1], [2]] c='1' d=[[1], [2], [1], [1]], D=[[1], [1], [2], [1]] c='x' d=[[1x], [2], [1], [1]], D=[[1], [1], [2], [1x]] latest group in d is full: d=[[2], [1], [1]], D=[[1], [1], [2], [1x]] c='w' d=[[2w], [1], [1]], D=[[1], [1], [2w], [1x]] c='y' d=[[2wy], [1], [1]], D=[[1], [1], [2wy], [1x]] latest group in d is full: d=[[1]], D=[[1], [1], [2wy], [1x]] c='z' d=[[1z], [1]], D=[[1], [1z], [2wy], [1x]] latest group in d is full: d=[[1]], D=[[1], [1z], [2wy], [1x]] c='v' d=[[1v]], D=[[1v], [1z], [2wy], [1x]] latest group in d is full: d=[], D=[[1v], [1z], [2wy], [1x]] print D in order: '1v1z2wy1x' ``` ]
[Question] [ Prime numbers have always fascinated people. 2300 years ago Euclid wrote in his "Elements" > > A prime number is that which is measured by a unit alone. > > > which means that a prime is only divisible by `1` (or by itself). People have always looked for relations between prime numbers, and have come up with some pretty weird (as in "interesting") stuff. For example a **Sophie Germain prime** is a prime `p` for which `2*p+1` is also prime. A **safe prime** is a prime `p` for which `(p-1)/2` is also prime, which is exactly the backwards condition of a Sophie Germain prime. These are related to what we are looking for in this challenge. A **[Cunningham chain](https://en.wikipedia.org/wiki/Cunningham_chain) of type I** is a series of primes, where every element except the last one is a **Sophie Germain prime**, and every element except the first one is a **safe prime**. The number of elements in this *chain* is called it's **length**. This means that we start with a prime `p` and calculate `q=2*p+1`. If `q` is prime too, we have a Cunnigham chain of type **I** of length 2. Then we test `2*q+1` and so on, until the next generated number is composite. Cunningham chains of type **II** are constructed following almost the same principle, the only difference being that we check `2*p-1` at each stage. Cunningham chains can have a *length of 1*, which means that neither 2\*p+1 nor 2\*p-1 are prime. **We're not interested in these**. ## Some examples of Cunningham chains `2` starts a chain of type **I** of length 5. `2, 5, 11, 23, 47` The next constructed number would be `95` which isn't prime. This also tells us, that `5`, `11`, `23` and `47` don't start any chain of type **I**, because it would have preceeding elements. `2` also starts a chain of type **II** of length 3. `2, 3, 5` Next would be `9`, which isn't prime. Let's try `11` for type **II** (we excluded it from *type I* earlier). Well, `21` would be next, which isn't prime, so we would have length 1 for that "chain", which we don't count in this challenge. ## Challenge > > Write a program or function that, given a number `n` as input, writes/returns the starting number of the **nth** Cunningham chain of **type I or II** of **at least length 2**, followed by a space, followed by the type of chain it starts (**I** or **II**), followed by a colon, followed by the length of that type of chain. > In case a prime starts both types of chains (type I *and* type II) the chain of type I is counted first. > > > Example: `2 I:5` > > > Bear in mind, that `n` might be part of a previously started chain of any type, in which case it shouldn't be considered a *starting number* of a chain of that type. ## Let's look into how this begins We start with `2`. Since it is the first prime at all we can be sure that there is no chain starting with a lower prime that contains `2`. The next number in a chain of type I would be `2*2+1 == 5`. `5` is prime, so we have a chain of at least length 2 already. We count that as the first chain. What about type II? Next number would be `2*2-1 == 3`. `3` is prime, so a chain of at least length 2 for type II too. We count that as the second chain. And we're done for `2`. Next prime is `3`. Here we should check if it is in a chain that a lower prime started. Check for type I: `(3-1)/2 == 1`. `1` isn't prime, so 3 could be a starting point for a chain of type I. Let's check that. Next would be `3*2+1 == 7`. `7` is prime, so we have a chain of type I of at least length 2. We count that as the third chain. Now we check if `3` appears in a type II chain that a lower prime started. `(3+1)/2 == 2`. `2` is prime, so 3 can't be considered as a *starting number* for a chain of type II. So this is not counted, even if the next number after `3` in this chain, which would be `5`, is prime. (Of course we already knew that, and you can and should of course think about your own method how to do these checks.) And so we check on for `5`, `7`, `11` and so on, counting until we find the nth Cunningham chain of at least length 2. Then (or maybe some time earlier `;)` ) we need to determine the complete length of the chain we found and print the result in the previously mentioned format. By the way: in my tests I haven't found any prime besides `2` that started both types of chains with a length greater than `1`. ## Input/Output examples > > ### Input > > > `1` > > > ### Output > > > `2 I:5` > > > > > ### Input > > > `10` > > > ### Output > > > `79 II:3` > > > > > ### Input > > > `99` > > > ### Output > > > `2129 I:2` > > > ### The outputs for the inputs 1..20 ``` 2 I:5 2 II:3 3 I:2 7 II:2 19 II:3 29 I:2 31 II:2 41 I:3 53 I:2 79 II:3 89 I:6 97 II:2 113 I:2 131 I:2 139 II:2 173 I:2 191 I:2 199 II:2 211 II:2 229 II:2 ``` A list of the first 5000 outputs can be found [here](http://pastebin.com/m22P9XMR). This is code golf. Arbitrary whitespace is allowed in the output, but the type and numbers should be seperated by a single space and a colon as seen in the examples. Using any loopholes is not allowed, especially getting the results from the web is **not** allowed. Good luck `:)` [Answer] # Javascript, ~~236~~ 208 bytes Saved 28 bytes: ``` p=(n,i=n)=>n%--i?p(n,i):i==1;f=n=>{for(k=2,c=0;c<n;k++){p(k)&&!p((k-1)/2)&&p(2*k+1)&&(c++,l=1,r='');p(k)&&c-n&&!p((k+1)/2)&&p(2*k-1)&&(c++,l=-1,r='I');};alert(--k+` I${r}:`+eval(`for(j=1;p(k=2*k+l);j++);j`))} ``` Saved 9 bytes on `p` function with: `p=(n,i=n)=>n%--i?p(n,i):i==1` The `t` function was replaced by the `eval(...)` statement directly in the `f` function. --- **Previous solution:** ``` p=n=>{for(i=n;n%--i&&i;);return 1==i};t=(n,m)=>{for(j=1;p(n=2*n+m);j++);return j};f=n=>{for(k=2,c=0;c<n;k++){p(k)&&!p((k-1)/2)&&p(2*k+1)&&(c++,l=1,r='');p(k)&&c-n&&!p((k+1)/2)&&p(2*k-1)&&(c++,l=-1,r='I');};alert(--k+` I${r}:${t(k,l)}`)} ``` Example: `f(6)` Output: `29 I:2` **Explanation** I'm using 3 functions **1** *p*: to know if *n* is prime : `p=n=>{for(i=n;n%--i&&i;);return 1==i}` **2** *t*: to know the length of the Cunningham chain starting with *n* of type I or II depending on the *m* parameter which will be 1 or -1 : `t=(n,m)=>{for(j=1;p(n=2*n+m);j++);return j}` **3** *f*: counts the chains (*for loop*) then display the result ``` f=n=>{for(k=2,c=0;c<n;k++){p(k)&&!p((k-1)/2)&&p(2*k+1)&&(c++,l=1,r='');p(k)&&c-n&&!p((k+1)/2)&&p(2*k-1)&&(c++,l=-1,r='I');};alert(--k+` I${r}:${t(k,l)}`)} ``` *for loop*: for each number the Cunningham chain (I then II if needed) is valid if * the number is prime * the predecessor is not prime * the successor is prime [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 182 bytes ``` Union[Flatten[DeleteCases[Table[c@x_:=Module[{t=0,p=Prime@k},If[PrimeQ[(p-x)/2],1,While[PrimeQ@p,p=2p+x;t++];t]];{Prime@k,If[#==1,"I","II"],c@#},{k,7!}],{a_,b_,1}]&/@{1,-1},1]][[#]]& ``` [Try it online!](https://tio.run/##LYxRS8MwFIX/Sk2gKL2jS30YrAQCG0IfBBXFh8ulZDV2ZW1WXIRCyG@Pmfpw4DuHc86k3dFM2g2djr18@hqsQw4ZyxhkvEqwZcDvKVcqvtnhbPFh1M4Zi3szGmd2@mIu@KoPo8FOLe1WPp4/vpPxTq5hvh5ORp0CNJ/4y894O6@Wu7IiEPB@HFL1L1dzqldzsdSuKKh2RLX/X1/HXEoBrGFJDSPoFA/gT7C5CQRet3BoQQTKS@UFrEQAQYTIifLYl@pF296oah3jDw "Wolfram Language (Mathematica) – Try It Online") [![enter image description here](https://i.stack.imgur.com/8jDaR.png)](https://i.stack.imgur.com/8jDaR.png) ]
[Question] [ *"Let's face it, aligned images are like little gifts from Heaven. Welcome, but unexpected."* - Geobits +10000 reputation to whoever wins this challenge. # Rules: 1) You are to generate a program. 2) Input will be an image, however whether it is passed as a file or a list of numbers is up to you. 3) Output will be a file which when opened in paint (or similar) will show the image aligned. 4) The canvas size will always be between 100 x 100 and 2000 x 2000 pixels. It will always be a rectangle, but not always a square. 5) No hard coding of images or funky URL magic. 6) No external libraries to be used. # Guide to Centralisation (Joshpbarron Variant) An image will be defined as centered if the 1st white(255,255,255,>0 rgba) or transparent(x,y,z,0 rgba) on an axis is equal distance (plus or minus 1 pixel) from the edge of the canvas. This can be achieved (and will be verified by) the following method. 1) Imagine a bounding box around the object. (Black lines added for help) ![enter image description here](https://i.stack.imgur.com/U3Ydx.png) 2) Move the object around until the edge of the object is equal distance from the appropriate edge of the canvas. ![enter image description here](https://i.stack.imgur.com/9vmyN.png) 3) Now forget the black lines. ![enter image description here](https://i.stack.imgur.com/9UQfC.png) Input: ![enter image description here](https://i.stack.imgur.com/G9HPd.png) Output: ![enter image description here](https://i.stack.imgur.com/RQvni.png) More inputs [here](https://i.stack.imgur.com/gzc0v.jpg). And respective outputs [here](https://i.stack.imgur.com/zomoL.jpg). *The +10000 rep is a lie.* [Answer] ## HTML5 + JavaScript (ES5), 515 bytes That count includes the HTML tags as they are part of the program. If you only count the image processing code, it is **376 bytes** including the function wrapper. ``` <canvas id=o></canvas><script>f=function(p){o=new Image();o.crossOrigin='Anonymous';o.src=p;o.onload=function(){v=document.getElementById('o'),c=v.getContext('2d');v.width=l=w=o.width;v.height=t=h=o.height;c.drawImage(o,0,0);for(k=255,d=c[g='getImageData'](0,0,w,h).data,r=b=i=0;i<d.length;)if((d[i++]<k||d[i++]<k||d[i++]<k)&&d[i++]){x=i/4%w;y=~~(i/4/w);l=l<x?l:x;t=t<y?t:y;b=b>y?b:y;r=r>x?r:x}n=c[g](l,t,r-l+1,b-t+1);c.clearRect(0,0,w,h);c.putImageData(n,(w-r+l)/2,(h-b+t)/2)}}</script><input onblur=f(this.value)> ``` ### Input A URL to an image. ### Security restrictions Because this program is running in a browser environment, only URLs to [CORS-enabled images](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image) will work. Imgur is CORS enabled. [IE 10 does not support CORS.](http://caniuse.com/#feat=cors) I haven't tested in IE 11 yet but it does work in Chrome and Firefox. ### How to run 1. Type/paste in a URL into the input field. 2. De-focus (tab/click out of) from the input field. ### Output It outputs on the canvas on the page. As this is a browser-based application, security restrictions prevent automatic download of a file but you can right click and save image in Chrome and Firefox. I haven't tested on IE 11 yet. ### Demo JavaScript code has been removed from the `script` element and put into the appropriate area to accommodate Stack Snippets: ``` f = function(p) { o = new Image(); o.crossOrigin = 'Anonymous'; o.src = p; o.onload = function() { v = document.getElementById('o'), c = v.getContext('2d'); v.width = l = w = o.width; v.height = t = h = o.height; c.drawImage(o, 0, 0); for (k = 255, d = c[g = 'getImageData'](0, 0, w, h).data, r = b = i = 0; i < d.length;) if ((d[i++] < k || d[i++] < k || d[i++] < k) && d[i++]) { x = i / 4 % w; y = ~~(i / 4 / w); l = l < x ? l : x; t = t < y ? t : y; b = b > y ? b : y; r = r > x ? r : x } n = c[g](l, t, r - l + 1, b - t + 1); c.clearRect(0, 0, w, h); c.putImageData(n, (w - r + l) / 2, (h - b + t) / 2) } } ``` ``` <canvas id=o></canvas> <input onblur=f(this.value)> ``` [Answer] # Python 3, ~~120~~ 205 bytes **EDIT** : As the output image must have the same size as the input, the script gets longer ... **EDIT2** : It seems that the rule 6 (no external library) has been added after I answered, so this answer is to be considered invalid anyway :( ``` from PIL.Image import*;from PIL.ImageOps import* c='RGB';i=open(input()).convert(c);w,h=i.size o,a=new(c,(w,h),'white'),i.crop(invert(i).getbbox()) e,f=a.size;o.paste(a,((w-e)//2,(h-f)//2));o.save('o.png') ``` The former version just cropped the input image: ``` from PIL.Image import*;from PIL.ImageOps import* i=open(input()).convert('RGB') i.crop(invert(i).getbbox()).save('o.png') ``` both scripts read the image file name from stdin, and saves the output image as 'o.png'. for example : ``` python3 script.py <<< s2rMqYo.png ``` It accepts at least PNG images (potentially with an alpha channel) -- Tested 'ok' on the set provided by the asker. ...waiting for my reward ): [Answer] # Processing 2 - 323 450 Image is read from the file f.png in the data folder of the sketch. Places the image and determines it's bounds. Calculates the correct position and replaces the image shifted correctly. ``` PImage p=loadImage("h.png");int a,b,c,d,x,y,w,i,n,m,t;a=w=p.width;c=i=p.height;clear();size(w,i,P2D);x=y=b=d=t=0;image(p,0,0);loadPixels();while(x<w*i){if(pixels[x]==color(255))t=1;x++;}x=0;background(255);image(p,0,0);loadPixels();while(y*w+x<w*i){if(pixels[y*w+x]!=color(255)){if(x<a)a=x;if(x>b)b=x;if(y<c)c=y;if(y>d)d=y;}x++;if(x==w){x=0;y++;}}n=(w-(b-a))/2;m=(i-(d-c))/2;clear();if(t>0)background(255);image(p,n-a,m-c);loadPixels();save("g.png"); ``` readable version: ``` PImage p=loadImage("h.png"); int a,b,c,d,x,y,w,i,n,m,t; a=w=p.width; c=i=p.height; clear(); size(w,i,P2D); x=y=b=d=t=0; image(p,0,0); loadPixels(); while(x<w*i) { if(pixels[x]==color(255))t=1; x++; } x=0; background(255); image(p,0,0); loadPixels(); while(y*w+x<w*i) { if(pixels[y*w+x]!=color(255)) { if(x<a)a=x; if(x>b)b=x; if(y<c)c=y; if(y>d)d=y; } x++; if(x==w){x=0;y++;} } n=(w-(b-a))/2; m=(i-(d-c))/2; clear(); if(t>0)background(255); image(p,n-a,m-c); loadPixels(); save("g.png"); ``` Example output: ![enter image description here](https://i.stack.imgur.com/n6anZ.png)![enter image description here](https://i.stack.imgur.com/8L2DB.png)![enter image description here](https://i.stack.imgur.com/rsKgP.png) ![enter image description here](https://i.stack.imgur.com/9xBKq.png) ![enter image description here](https://i.stack.imgur.com/jYRY7.png) You can get processing [here](https://processing.org/download/) ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. [Improve this question](/posts/38679/edit) *"I want to go to the Araby bazaar to buy a present for the one I have fallen in love with. However, if I arrive too late all the stores will be closed and I won't be able to buy anything. Can you help me?*" **Goal:** Get the boy to Araby from North Richmond Street before all the stores close. **Actual Goal:** Make sure the boy doesn't arrive in Araby before the stores close. Your program will take in input in the following format: ``` <time> <map> ``` where * `<time>` is the maximum time the boy can spend travelling, in minutes. It is a positive integer. * `<map>` is a graph of the routes the train can take. Here is how the format for the graph works: * Each statement is ended with a semicolon. * Nodes in the map (which represent switches) are represented using single lower case letters. * A path between nodes is represented with the syntax `a,X,b`, where `X` is an integer representing the weight of the path. The weight of the path is the time, in minutes, the train takes to go through those two nodes. * Araby is represented with `a`, and North Richmond Street is represented with an `n`. * All paths are bidirectional. For instance, this graph (pretend the paths are bidirectional): ![graph](https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Shortest_path_with_direct_weights.svg/640px-Shortest_path_with_direct_weights.svg.png) [Image](http://commons.wikimedia.org/wiki/File:Shortest_path_with_direct_weights.svg) by Artyom Kalinin, via Wikimedia Commons. Used under the [CC BY-SA 3.0](http://creativecommons.org/licenses/by-sa/3.0/deed.en) licence. would be recorded in the graph notation as: ``` a,4,b;a,2,c;b,5,c;b,10,d;c,3,e;e,4,d;d,11,f; ``` Note that this input doesn't have an `n`, so it's an invalid input. Your program may do anything if given an invalid input. Here is an example input: ``` 21 n,4,b;n,2,c;b,5,c;b,10,d;c,3,e;e,4,d;d,11,a; ``` (It's just the same graph as the image above with `a` replaced by `n` and `f` replaced by `a`). The boy must get from `n` to `a` within 21 minutes. If he takes the route `n` --> `c` --> `e` --> `d` --> `a`, he gets there in 20 minutes, which is in time. We could represent that route as a comma separated list of nodes: ``` n,c,e,d,a ``` On the other hand, the route `n` --> `b` --> `c` --> `e` --> `d` --> `a` will cause the boy to take 27 minutes, which is not in time. We could represent that route like this: ``` n,b,c,e,d,a ``` Another possible route that will cause the boy to not make it in time is: ``` n,b,c,b,c,b,c,b,c,b,c,b,c,b,c,b,c,b,c,e,d,a ``` Your program should take in the input as described above, and **at first glance** appear to output a route that will cause the boy to make it in time, but **actually** outputs a route that causes the boy to not make it in time. For any given input there will always exist a route, without backtracking, that causes the boy to not make it in time. This is an underhanded popularity contest, so the entry with the most votes wins. Votes are awarded for ingenuity in hiding the bug - the less obvious it is the better. Here are some sample graphs to test your program with. Input: ``` 12 a,2,c;a,2,e;b,5,c;b,4,d;b,11,e;d,7,n;e,4,n; ``` A visual representation (this visual representation is only for clarity and does not constitute part of the challenge): ![Input 1](https://i.stack.imgur.com/Pixlo.png) A *possible* output: ``` n,d,b,e,a ``` Input: ``` 10 a,8,b;a,12,d;b,1,n;d,11,n;a,1,n; ``` Here is a visual image of the graph: ![Input 2](https://i.stack.imgur.com/ViImI.png) A *possible* output: ``` n,d,a ``` [Answer] # Python 3 (not 2) Edit: I'll ungolf this in the morning, oops. It's a perfectly normal A-star search. Right? Riiiiiiight? Seems to work for all test cases. ``` def a(b,c,d): e,f,g=[],{},{} f[c]=0 while f: h=sorted(f.keys(),key=lambda z:-f[z],reverse=True)[-1] if h==d:break e.append(h) for z in b[h]: if z in e:continue if z in f and f[z]>f[h]+b[z][h]:continue g[z]=h f[z]=f[h]+b[z][h] del f[h] i=[] j=d q=0 while j!=c: i.append(j) q+=b[j][g[j]] j=g[j] return q,(i+[c])[::-1] t,q=input().split(" ") t=int(t) q=q[:-1] q=[i.split(",")for i in q.split(";")] g={a:{}for a in __import__("functools").reduce(lambda zz,zy:zz+zy,[[v[0],v[2]]for v in q])} for l in q:g[l[0]][l[2]]=g[l[2]][l[0]]=int(l[1]) r=a(g,'n','a') print("time-good: %d, time-ours: %d" % (t, r[0])) print("path: %s" % " -> ".join(r[1])) ``` ]