text
stringlengths
180
608k
[Question] [ Currently at my work we moved to a new building. It's supposed to be state of the art and has automatic lights, automatic roll-down shutters, and is now known as the most eco-friendly building in this town. However, it doesn't really work all that well.. The roll-down shutters sometimes go down on cloudy days and up when the sun starts to shine, and the lights sometimes cause disco effects by alternating turning on and off every 5-10 minutes. Also, we don't have any manual way of controlling these roll-down shutters, nor the temperature, BUT we do have a remote for the lights. These remotes however came without instruction manual and contain little over 20 buttons doing all kind of stuff except for what you seem to want.. PS: I wrote this challenge 1.5 months ago in the Sandbox. Currently we, kinda, know how the remotes work.. One big advantage about this building, it's 30+ degrees Celcius outside, but inside it stays the same 21 room temperature at all time. So, that was the intro, and the remote control for the lights inspired this challenge. # Challenge: Let's say we initially have a lamp turned off: ``` L ``` Then we push all kind of buttons and output the state of the lamp afterwards. We use the following numbers for the different functions of the remote control for the lamp. When a minus symbol is in front of that number, we do the opposite. * `1` = ON; `-1` = OFF. * `2` = Increase strength by 25%; `-2` = Decrease (dim) strength by 25%. * `3` = Increase spread by 50%; `-3` = Decrease spread by 50%. * `4` = Toggling the type of light. So, this is all pretty vague, so let's go a little more in depth what each thing means: So, `-1` (OFF) is pretty obvious, and `1` will go to the initial ON-state (50% for `2` and 50% for `3`): ``` // // L ==== \\ \\ ``` `2` and `-2` is how far the light travels (`==` is appended for every 25%): ``` 0% (equal to a light bulb that is OFF) L 25% L == 50% L ==== 75% L ====== 100% L ======== ``` `3` and `-3` is how far the light spreads: ``` 0%: L ==== 50%: // // L ==== \\ \\ 100%: || // ||// L ==== ||\\ || \\ ``` (NOTE: When `2` and `3` are both at 100%, you'll have this state: ``` || // || // || // ||// L ======== ||\\ || \\ || \\ || \\ ``` `4` is to toggle the type of light. ``` Default: // L == \\ After toggling (note the single space before '/' instead of two): / L -- \ ``` **Input:** You will receive an input containing the possible button-presses. For example: ``` 12-34 ``` **Output:** The state of the light lamp after all the buttons of the input are sub-sequential pressed. So with the example input above, we have the following output: ``` L ------ ``` **Challenge rules:** * The input only contains `1234-` (and never a `-` before the `4`). * You can never go below 0% or above 100%. If a number would increase/decrease beyond these boundaries you can ignore it. * When the lamp is turned off, you can ignore any actions and when turned back on again it resets back to the initial ON-state (50% for both `2` and `3`, and default `4`). For example: `12-1-341` will just print the initial ON-state mentioned above. (TIP: You can ignore everything before the final `1` of the input - excluding `-1`.) * Trailing spaces equal to the length of the light or a single trailing new line is uninhibited. Adding extra unnecessary new lines isn't however. * You are allowed to take the input as a list of integers instead of a single string. So instead of `12-34`, you can have `[1,2,-3,4]` as input. **General rules:** * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. **Test cases:** ``` 12-34 L ------ 12-1-341 // // L ==== \\ \\ 14-3224333-2 || // || // ||// L ====== ||\\ || \\ || \\ 142-1-314-3-322 L -------- 1324-2-3 / / L ---- \ \ 134 | / |/ L ---- |\ | \ 1-2-2-214-3-3-3 L ---- ``` [Answer] # Python 2, 221 bytes ``` for b in[-1]+input():exec["p=b>0;d=2;s=1;t=2","d+=b/2*(-2<d+b<6)","s+=b/3*(-3<s+b<5)","t=3-t"][abs(b)-1] i=c=(s>0)*d*p q='print" |"[s/2]*t+" "*i+t*%r;' exec('i-=1;'+q%'/')*c print"L "+" -="[t]*2*d*p exec(q%'\\'+'i+=1;')*c ``` This wound up being longer than I expected. The first line calculates the state of the lamp, the rest implement the printing. Input is given via STDIN in the array form. See the test cases on [**ideone**](http://ideone.com/0QYlNh) [Answer] # R, ~~323~~ 320 bytes ``` z=scan();a=c=1;b=d=2;for(i in 1:sum(1|z)){s=sign(y<-z[i]);switch(y/s,b<-d<-2*(c<-a<-y),b<-b+s,c<-c+s,d<-2-d);b=min(b,4);c=min(c,2);b=b*(b>0);c=c*(c>0)} s="/";v=if(c>1)"|"else" ";for(i in a*b:-b){if(i)cat(v,if(d)v,rep(" ",abs(i)-1),s,if(d)s,"\n",sep="")else{cat("L ",if(d)rep("==",b)else rep("--",b),"\n",sep="");s="\\"}} ``` Ungolfed: ``` z=scan() ``` reads a line of input (integers separated with spaces) ``` a=c=1;b=d=2 ``` initialises variables a (on-ness), b (brightness), c (width), d (beam type). `d` is either zero or two, which means we can call if(d) later rather than a longer if(d>1) or similar and save a couple of bytes. ``` while(any(z|1)) ``` A golf-y way of writing `while(length(z))` where z is an integer vector. The rest of the first line handles the input via a `switch` statement. The second line prints out. It is possible that some of the `<-` can be replaced with `=`, but I think you get eaten alive by lexical scoping... Also note that in R, backslashes need to be escaped. `c*(c>0)` is a golf-y way of writing `max(c,0)` that saves a character. If the light isn't on, then since `*` has lower precedence than `:`, the `for(i in a*b:-b)` loop only iterates over `0:0` . Update; saved 3 bytes by replacing the loop in the first line with a for (rather than while). Note that `1:sum(1|z)` is fewer characters than `1:length(z)` or `seq_along(z)`. `seq(z)` would work in most cases, but not when `z` is of length one. The solution given will not work for input of length zero but I hope that is outside the scope of the competition. [Answer] # [Kotlin](https://kotlinlang.org), 445 bytes My first Kotlin golf, 38 bytes less than Java :) ``` fun f(z:IntArray)={var a=1<0;var b=2;var c=1;var d=a z.map{when(it){1->{a=1>0;b=2;c=1;d=!a}-1->a=1<0;2->if(b<4)b+=1;-2->if(b>0)b-=1;3->if(c<2)c+=1;-3->if(c>0)c-=1;4->d=!d}} var r="";val l=if(c>1)if(d)"|" else "||" else if(d)" " else " " if(c>0)for(i in b downTo 1)r+="${l+" ".repeat(i-1)+if(d)"/" else "//"}\n" r+="L ${(if(d)"--" else "==").repeat(b)}\n" if(c>0)for(i in 1..b)r+=l+" ".repeat(i-1)+"${if(d)"\\" else "\\\\"}\n" if(a)r else "L"}() ``` With white-space and tests: ``` fun f(z: IntArray) = { var a = false // ON / OFF var b = 2 // Strength [0,4] var c = 1 // Spread [0,2] var d = a // Type // Find state to print z.map { when (it) { 1 -> { a = true b = 2 c = 1 d = !a } -1 -> a = false 2 -> if (b < 4) b += 1 -2 -> if (b > 0) b -= 1 3 -> if (c < 2) c += 1 -3 -> if (c > 0) c -= 1 4 -> d = !d } } var r = "" val l = if (c > 1) if (d) "|" else "||" else if (d) " " else " " // Print state if (c > 0) for (i in b downTo 1) { r += "${l + " ".repeat(i - 1) + if (d) "/" else "//"}\n" } r += "L ${(if (d) "--" else "==").repeat(b)}\n" if (c > 0) for (i in 1..b) { r += "${l + " ".repeat(i - 1) + if (d) "\\" else "\\\\"}\n" } /* return */ if (a) r else "L" }() fun main(args: Array<String>) { println(f(intArrayOf(1, 2, -3, 4))) println(f(intArrayOf(1, 2, -1, -3, 4, 1))) println(f(intArrayOf(1, 4, -3, 2, 2, 4, 3, 3, 3, -2))) println(f(intArrayOf(1, 4, 2, -1, -3, 1, 4, -3, -3, 2, 2))) println(f(intArrayOf(1, 3, 2, 4, -2, -3))) println(f(intArrayOf(1, 3, 4))) println(f(intArrayOf(1, -2, -2, -2, 1, 4, -3, -3, -3))) } ``` Interestingly, rather than define the function normally and `print` or `return` the created string, it was shorter to use function assignment (the `fun f() =` of an evaluated lambda. (Does that description make sense?) I just wish SE had proper Kotlin syntax highlighting [Answer] # Java 8, ~~484~~ ~~483~~ ~~452~~ ~~446~~ 440 bytes ``` z->{int a=1,b=2,c=1,d=0,j,k;for(int i:z){d=i==1?0:i>3?1-d:d;a=i*i==1?i:a;b+=i==1?2-b:i==2&b<4?1:i==-2&b>0?-1:0;c+=i==1?1-c:i==3&c<2?1:i==-3&c>0?-1:0;}String t=d<1?"=":"-",q=d<1?"//":"/",x=d<1?"\\\\":"\\",n="\n",y=" ",w=d<1?y+y:y,g=c>1?d<1?"||":"|":w,r="";if(c>0)for(r+=g,j=b;j-->0;r+=q+n+(j>0?c>1?g:w:""))for(k=j;k-->0;r+=y);for(r+="L ",j=b;j-->0;r+=t+t);r+=n;if(c>0)for(r+=g;++j<b;r+=x+n+(j<b-1?g:""))for(k=j;k-->0;r+=y);return a>0?r:"L";} ``` Finally.. Ok, my own challenge is a bit harder than I expected.. ;P This can without a doubt be golfed by using a completely different approach.. I now first determine what to do, and then print it. The printing is actually the hardest of this challenge, imho. -6 bytes thanks to *@ceilingcat*. **Explanation:** [Try it here.](https://tio.run/##lVLNctsgEL77KRgOGakCW0g@gZBeIM2lx6YH9GMPsoMTGceRHT27uyC5nXamM5UAsct@u9/CbqveFW3r3a3aq@MRfVXaXBcIaWObbqOqBj05FaFvttNmi6oALN9/oEso4HiABfNoldUVekIGSXS70PwKIKQkI6VMSAV7LWPSkp3YHDoXAGl@Ca@11FKyIuY6TwtGa14LJfUXf6i5EmU0AhJachCShzJbF8yJFOQ8LijjsagmFKOVM6UPVZZMKJDvqGHK38o6YwWWmGOKyduorVagrjD5GNVn@OAAfsRI/Gww6SVGmJy9uY963pOtrHJWePjnJ4BhnUknMRZ6EwBr6G7aRXJLWlmKltI8FqC@RSYKWkjKeW/5mWMceuhOtmJ3R/WhmNzxI/D@EcFGNnS7@ZtIRFGblc704UmykjqKfxF0jT11BinIpeP4EYvhJhZQy9dTuYdaTiV9P@gavUBPBOP7QeVVODVEf7TNy/JwsstXMNm9CcyyCkxzRr5FrowkhKZkPYS@V/7Xg3knwua4rZ1PAmNNUj9oMs/9zjuFGqPNCZF6cupuPM9t1vO4@H7@zvMX37AYbj8B) ``` z->{ // Method with integer-array parameter and String return-type int a=1, // ON/OFF flag, initially ON b=2, // Strength, initially 50% c=1, // Spread, initially 50% d=0, // Type of light, initially two lines j,k; // Index-integers for(int i:z){ // Loop over the input-array d=i==1?0:i>3?1-d:d; // Determine the new type of light a=i*i==1?i:a; // Determine if the light is ON/OFF b+=i==1?2-b:i==2&b<4?1:i==-2&b>0?-1:0; // Determine the new strength c+=i==1?1-c:i==3&c<2?1:i==-3&c>0?-1:0;} // Determine the new spread String t=d<1?"=":"-", // Horizontal light symbol q=d<1?"//":"/", // Upper diagonal light symbol x=d<1?"\\\\":"\\", // Bottom diagonal light symbol n="\n", // New-line y=" ", // Space w=d<1?y+y:y, // One or two spaces? g=c>1?d<1?"||":"|":w,// Space(s) or vertical light symbol(s)? r=""; // Result String, starting empty if(c>0) // Do we have spread >0%? for(r+=g,j=b;j-->0;r+=q+n+(j>0?c>1?g:w:""))for(k=j;k-->0;r+=y); // Create upper light part r+="L "; // Light-bulb for(j=b;j-->0;r+=t+t); // Horizontal light next to the light-bulb r+=n; if(c>0) // Do we have spread >0%? for(r+=g;++j<b;r+=x+n+(j<b-1?g:""))for(k=j;k-->0;r+=y); // Create bottom light part return a>0? // Is the light turned ON? r // Return the created result-String : // Else: "L";} // Return just "L" ``` [Answer] ## Batch, 552 bytes ``` @echo off for %%a in (1 %*) do call:l %%a set/aw*=o,l*=o if %w% gtr 0 for /l %%a in (%l%,-1,1)do call:w %%a / set s=---- if %t%==1 set s===== call echo L %%s:~-%l%%%%%s:~-%l%%% if %w% gtr 0 for /l %%a in (1,1,%l%)do call:w %%a \ exit/b :w set v= set u=%2 if %w%==2 set v=l if %t%==1 set u=%2%2&set v=%v%%v% set s= call set s=%%s:~-%1%% echo %v:l=^|%%s:~1%%u% exit/b :l if %1==1 set/ao=w=t=1,l=2 if %1==-1 set/ao=0 if %1==2 set/al+=1-l/4 if %1==-2 set/al-=!!l if %1==3 set/aw+=1-w/2 if %1==-3 set/aw-=!!w if %1==4 set/at^=1 ``` Note: `set v=` contains one trailing space and `set s=` contains three. This was really awkward, as you can't easily print a variable number of `|`s in Batch, so you have to use a placeholder and replace it in the echo statement. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 106 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` “/|= L“•Wθ¨S9ƒTª»þúÙ•6вèJ¶¡sŽ8ÃS«1¡θΣÄ}.γÄ}ODd*©н8‚ß8αF樚NÈi¨]R®θ8Öi"||//="2ô…|/-S:}®Ås3/©_iθ}®i'|ð:}».∊ ``` Input as a list of integers. [Try it online](https://tio.run/##yy9OTMpM/f//UcMc/RpbBS4fIONRw6LwczsOrQi2PDYp5NCqQ7sP7zu86/BMoLDZhU2HV3gd2nZoYfHRvRaHm4MPrTY8tPDcjnOLD7fU6p3bDCT9XVK0Dq28sNfiUcOsw/Mtzm10O9J@aMXRhX6HOzIPrYgNOrTu3A6Lw9MylWpq9PVtlYwOb3nUsKxGXzfYqvbQusOtxcb6h1bGZ57bAeRlqtcc3gAU3q33qKPr//9oEx1jIDTSMQSTJjq6Rjq6xrEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX@mio@RfWgLh6fx/1DBHv8ZWgcsHyHjUsCj83I5DK4Itj00KObTq0O7D@w7vOjwTKGx2YdPhFV6Hth1aWHx0r8Xh5uBDqw0PLTy349ziwy21euc2A0l/lxStQysv7LV41DDr8HyLcxvdjrQfWnF0od/hjsxDK2prgw6tO7fD4vC0TKWaGn19WyWjw1seNSyr0dcNtqo9tO5wa7Gx/qGV8ZnndgB5meo1hzcAhXfrPero@q9zaJv9/@hoQx0jHV1jHZNYHQUI2xDM1TGECJiAeEZAaKJjDIa6RjAJmFqoIog6iKQxWIMuyGSYANQCkBgYIXRB1EDMB4kbQbUbwYyMBQA). **Explanation:** ``` “/|= L“ # Push string "/|=\nL" •Wθ¨S9ƒTª»þúÙ• # Push compressed integer 9569494169631511496055972036 6в # Converted to Base-6 as list: [5,3,2,2,2,2,2,2,2,2,4,1,1,0,0,4,1,1,3,0,0,4,1,1,3,3,0,0,4,1,1,3,3,3,0,0] è # Index each into the string J # Join everything together ``` We now have the string: ``` L ======== ||// || // || // || // ``` Then we'll: ``` ¶¡ # Split it by newlines: ["L ========","||//","|| //","|| //","|| //"] s # Swap to take the (implicit) input-list Ž8à # Push compressed integer 2234 S # Converted to a list of digits: [2,2,3,4] « # Append it at the end of the input-list # i.e. [4,3,3,2,1,3,2,4,-2,-3] → [4,3,3,2,1,3,2,4,-2,-3,2,2,3,4] 1¡ # Then split on 1 # i.e. [4,3,3,2,1,3,2,4,-2,-3,2,2,3,4] # → [[4,3,3,2],[3,2,4,-2,-3,2,2,3,4]] θ # Only leave the last inner list # i.e. [[4,3,3,2],[3,2,4,-2,-3,2,2,3,4]] → [3,2,4,-2,-3,2,2,3,4] ΣÄ} # Sort on the absolute value # i.e. [3,2,4,-2,-3,2,2,3,4] → [2,-2,2,2,3,-3,3,4,4] .γÄ} # Then group by absolute value # i.e. [2,-2,2,2,3,-3,3,4,4] → [[2,-2,2,2],[3,-3,3],[4,4]] O # Then take the sum of each group # i.e. [[2,-2,2,2],[3,-3,3],[4,4]] → [4,3,8] Dd # Duplicate it, and check for each if it's non-negative (>= 0) # i.e. [4,3,8] → [1,1,1] * # Multiply the two lists # i.e. [4,3,8] and [1,1,1] → [4,3,8] © # And store the result in the register (without popping) н # Now take the first value (the strength) # i.e. [4,3,8] → 4 8‚ # Pair it with 8 # i.e. 4 → [4,8] ß # Pop and push the minimum of the two # i.e. [4,8] → 4 8α # And then calculate the absolute difference with 8 # i.e. 4 → 4 F # Loop that many times: ć # Extract the head of the string-list # i.e. ["L ========","||//","|| //","|| //","|| //"] → "L ========" ¨ # Remove the last character # i.e. "L ========" → "L =======" š # And prepend it back to the list again # i.e. ["||//","|| //","|| //","|| //"] and "L =======" # → ["L =======","||//","|| //","|| //","|| //"] NÈi # And if the loop-index is even: ¨ # Also remove the last item of the string-list # i.e. ["L =======","||//","|| //","|| //","|| //"] # → ["L =======","||//","|| //","|| //"] ] # Close both the if and loop # i.e. ["L ========","||//","|| //","|| //","|| //"] and 4 # → ["L ====","||//","|| //"] R # Then reverse the list # i.e. ["L ====","||//","|| //"] → ["|| //","||//","L ===="] ® # Push the list from the register again θ # Now take the last value (the toggle) # i.e. [4,3,8] → 8 8Öi } # If it's divisible by 8: # i.e. 8 → 1 (truthy) "||//=" # Push string "||//=" 2ô # Split into parts of size 2: ["||","//","="] …|/- # Push string "|/-" S # Split into characters: ["|","/","-"] : # And replace all of them in the string-list # i.e. ["|| //","||//","L ===="] → ["| /","|/","L ----"] ® # Push the list from the register again Ås # Now take the middle value (the spread) # i.e. [4,3,8] → 3 3/ # Divide it by 3 # i.e. 3 → 1 © # Store it in the register (without popping) _i } # If it's exactly 0: # i.e. 1 → 0 (falsey) θ # Only leave the last value of the string-list ®i } # If it's exactly 1 instead: # i.e. 1 → 1 (truthy) '|ð: '# Replace all "|" with spaces " " # i.e. ["| /","|/","L ----"] → [" /"," /","L ----"] » # Then join the string-list by newlines # i.e. [" /"," /","L ----"] → " /\n /\nL ----" .∊ # And finally intersect mirror everything vertically # (which automatically converts the slashes) # i.e. " /\n /\nL ----" → " /\n /\nL ----\n \\n \" # (And output the result 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 `•Wθ¨S9ƒTª»þúÙ•6в` is `[5,3,2,2,2,2,2,2,2,2,4,1,1,0,0,4,1,1,3,0,0,4,1,1,3,3,0,0,4,1,1,3,3,3,0,0]`; and `Ž8Ã` is `2234`. ]
[Question] [ What general tips do you have for golfing in [Retina](https://github.com/mbuettner/retina)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Retina (e.g. "remove comments" is not an answer). Please post one tip per answer. For reference, the online compiler is [here](http://retina.tryitonline.net/). @Sp3000 pointed out there is also [Tips for Regex Golf](https://codegolf.stackexchange.com/questions/47428/tips-for-regex-golf). Answers here should focus specifically on Retina features and not on general regex golfing tips. [Answer] ## Combine loops if possible In non-trivial computations you'll often find yourself using several loops to process data: ``` +`stage1 +`stage2 +`stage3 ``` So this runs `stage1` until the output converges, then `stage2` until the output converges and then `stage3` until the output converges. However, it's always worth examining the stages in detail. Sometimes it's possible to run the loop in an interleaved fashion as `stage1, stage2, stage3, stage1, stage2, stage3, ...` instead (this depends a lot on what the stages actually do, but sometimes they make completely orthogonal changes or work well as a pipeline). In this case you can save bytes by wrapping them in a single loop: ``` {`stage1 stage2 }`stage3 ``` If `stage1` is the first stage or `stage3` is the last stage of the program you can then even omit on of those parentheses as well (which means this can already save bytes for a loop of two stages). A recent use of this technique [can be seen in this answer](https://codegolf.stackexchange.com/a/71890/8478). [Answer] ## Splitting strings into chunks of equal length `n` As in most "normal" languages TMTOWTDI (there's more than one way to do it). I'm assuming here that the input doesn't contain linefeeds, and that "splitting" means splitting it into lines. But there are two quite different goals: if the length of the string isn't a multiple of the chunk length, do you want to keep the incomplete trailing chunk or do you want to discard it? ### Keeping an incomplete trailing chunk In general, there are three ways to go about the splitting in Retina. I'm presenting all three approaches here, because they might make a bigger difference when you try to adapt them to a related problem. You can use a replacement and append a linefeed to each match: ``` .{n} $&¶ ``` That's 8 bytes (or a bit less if `n = 2` or `n = 3` because then you can use `..` or `...` respectively). This has one issue though: it appends an additional linefeed if the string length *is* a multiple of the chunk length. You can also use a split stage, and make use of the fact that captures are retained in the split: ``` S_`(.{n}) ``` The `_` option removes the empty lines that would otherwise result from covering the entire string with matches. This is 9 bytes, but it doesn't add a trailing linefeed. For `n = 3` it's 8 bytes and for `n = 2` it's 7 bytes. Note that you can save one byte overall if the empty lines don't matter (e.g. because you'll only be processing non-empty lines and getting rid of linefeeds later anyway): then you can remove the `_`. The third option is to use a match. With the `!` option we can print all the matches. However, to include the trailing chunk, we need to allow for a variable match length: ``` M!`.{1,n} ``` This is also 9 bytes, and also won't include a trailing linefeed. This also becomes 8 bytes for `n = 3` by doing `..?.?`. However note that it reduces to *6* bytes for `n = 2` because now we only need `..?`. Also note that the `M` can be dropped if this is the last stage in your program, saving one byte in any case. ### Discarding an incomplete trailing chunk This gets really long if you try to do it with a replacement, because you need to replace the trailing chunk with nothing (if it exists) and also with a split. So we can safely ignore those. Interestingly, for the match approach it's the opposite: it gets shorter: ``` M!`.{n} ``` That's 7 bytes, or less for `n = 2`, `n = 3`. Again, note that you can omit the `M` if this is the last stage in the code. If you do want a trailing linefeed here, you can get that by append `|$` to the regex. ### Bonus: overlapping chunks Remember that `M` has the `&` option which returns overlapping matches (which is normally not possible with regex). This allows you to get all overlapping chunks (substrings) of a string of a given length: ``` M!&`.{n} ``` [Answer] ## Horizontal or Vertical Mirroring in [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d) If the amount of mirroring is a constant, then it's easy enough: duplicate the string, then reverse the appropriate half. For instance, suppose the buffer is known to contain 10 characters, and you want to mirror them about the last character: ``` saippuakiv ``` The following program would then achieve that: ``` .$ $&$` 10>O$^`. ``` [Try it online!](https://tio.run/##K0otycxL/P9fT4VLRU0lgcvQwM5fJS5B7///4sTMgoLSxOzMMgA "Retina 0.8.2 – Try It Online") Explanation: The first stage copies the first 9 characters to the end of the line, then the second stage reverses the characters after the first 10. Note that the second stage consists of two lines but the second (empty) line may be omitted if it's the last stage. If you want to mirror to the left, then you can prepend the suffix and sort the first 9 characters instead. ``` ^. $'$& 9O$^`. ``` [Try it online!](https://tio.run/##K0otycxL/P8/To9LRV1FjcvSXyUuQe///7LM7MTSgoLMxGIA "Retina 0.8.2 – Try It Online") (Mirrors `vikauppias` to the left.) Similarly, you can mirror a fixed number of lines. Suppose for instance you wanted a mirror copy of all three lines: ``` | | | | | =~=~=~=~= ######### ``` The following program would then achieve that: ``` $ ¶$` 3>O$^` ``` [Try it online!](https://tio.run/##K0otycxL/P9fhevQNpUELmM7f5W4hP//axSgkMu2Dgq5lGEAAA "Retina 0.8.2 – Try It Online") Explanation: The first stage duplicates the entire buffer, while the second stage reverses the lines after the first three. If you want to mirror up, then remove the `>`, so the first `3` lines are reversed instead. If the amount of mirroring is a variable, then it might still be possible, but you would need to use .NET balancing groups to ensure that only the characters or lines that need to be reversed are processed by the `O` command. ## Horizontal Mirroring in Retina 1 Horizontal mirroring is straightforward in [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1: simply use the `$^` function to reverse a substitution. For instance, to horizontally mirror `saippuakiv` as above: ``` .$ $&$^$` ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@FS0VNJU4l4f//4sTMgoLSxOzMMgA "Retina – Try It Online") Explanation: The reversed prefix of the input is appended to it, thus mirroring the input. (The code would be even simpler if the last character could be duplicated as well.) ## Vertical Mirroring of Horizontally Mirrored Text in [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1 If you are mirroring horizontally mirrored text, then a very similar approach will allow you to vertically mirror the whole text. ``` $ ¶$^$` ``` [Try it online!](https://tio.run/##K0otycxLNPz/X4Xr0DaVOJWE//9rFKCQy7YOCrmUYQAA "Retina – Try It Online") Explanation: The whole buffer is duplicated, but the second copy is reversed. This only works because the horizontal mirroring turns the string reversal into a line reversal. Both of these examples are readily adapted to mirror to the left or up. If the text is not already horizontally mirrored then you will need to adapt the Retina 0.8.2 examples (note that the limits syntax changes so that `3>` is now `3,` and `3` is now `,2`). You can use the `V` command instead to avoid the second line of the stage: `3,V0^` instead of `3,O$^` (the `0` is needed to avoid reversing the characters of the lines). [Answer] ## Arithmetic in Retina 1 In Retina you need to do your arithmetic in unary. However, Retina 1 makes things slightly easier for you in certain cases, principally because of two constructs: * The repetition operator `*` accepts an expression as its RHS, whereas the `$*` operator in Retina 0.8.2 only accepted a character as its RHS * Retina 1 now includes a `$(...)` grouping construct, which accepts the length modifier `$.(...)` It thus becomes possible to perform some arithmetic operations in both unary or decimal, depending on which is convenient. In particular, the group length construct `$.(...)` calculates the sum of the lengths of its contents, taking any products using arbitrary precision integers, so it's not limited in value. ### Addition This is straightforward. * Convert any decimal numbers to unary using `*_` * Concatenate the numbers to give a unary result * Group the sum using `$(...)` if you intend to multiply it or `$.(...)` to convert it to decimal 2-argument examples: * Unary + Unary = Unary: `$1$2` * Unary + Unary = Decimal: `$.($1$2)` * Unary + Decimal = Unary: `$1$2*_` * Unary + Decimal = Decimal: `$.($1$2*)` (see below) * Decimal + Decimal = Unary: `$1*_$2*_` * Decimal + Decimal = Decimal: `$.($1*_$2*)` ### Multiplication Note that `*` normally takes one decimal and one unary parameter and returns a unary result. * If the numbers are all decimal, add an extra unary parameter of 1 * Convert all but one number to decimal using the length modifier * Take the product to give a unary result * Convert the product to decimal by enclosing in `$.(...)` if desired 2-argument examples: * Unary \* Unary = Unary: `$.1*$2` * Unary \* Unary = Decimal: `$.($.1*$2)` * Decimal \* Unary = Unary: `$1*$2` * Decimal \* Unary = Decimal: `$.($1*$2)` * Decimal \* Decimal = Unary: `$1*$2*_` * Decimal \* Decimal = Decimal: `$.($1*$2*)` (see below) A Retina replacement string to take the cube of a matched decimal number would be `$.(***` (see below). ### Further savings * Only the first non-negative integer contained in the the LHS of a `*` operator is significant; there is no limit on junk characters (including `-`s). In particular this makes it easier to use `$&`. * If the LHS of a `*` is indeed `$&`, then it is not necessary at the start of a `$(` construct or replacement string or after another `*`. Example: `$.(*__)` * The `_` after a `*` is not necessary at the end of a `$(` construct or replacement string. Example: `$.($1*_$2*)` * It is not necessary to close your `$(` constructs if they end at the end of the replacement string. Example: `$.($1$2` * When adding the constant values 1 or 2 it is shorter to express them in unary. [Answer] ## Using balancing groups to capture the same count twice. Occasionally you need to capture a balancing group twice, such as to match the substring `nice` when the letters are equally spaced in the input. The naive approach is to capture the characters between `n` and `i` twice, and then use balancing groups to ensure that the same number of character exist between `i` and `c` and `c` and `e`, like this: ``` n((.))*i(?<-1>.)*(?(1)^)c(?<-2>.)*(?(2)^)e ``` However, you can capture into capture group `2` while popping from capture group `1`, allowing you to then pop the same count from capture group `2` later, saving a byte: ``` n(.)*i(?<2-1>.)*(?(1)^)c(?<-2>.)*(?(2)^)e ``` (Normally you would use `(?!)` to force the match to fail if the count is too low but obviously in code golf we just use the shortest regex that we know will fail; `^` usually works.) [Answer] ## Actualising a transliteration pattern in [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d) In [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1, it's easy to produce the contents of a transliteration pattern, here the 64 characters used by MIME Base-64: ``` 64* Y`\_`Lld+/ ``` [Try it online!](https://tio.run/##K0otycxLNPz/n8vMRIsrMiEmPsEnJ0Vb//9/AA "Retina – Try It Online") Explanation: The first stage inserts 64 `_`s, and the second stage cyclically transliterates `_`s to the 64 base 64 characters in turn. You can also cyclically extend the string should you want, say, 10 copies of each of the digits; just cyclically translate 100 `_`s into digits. But it turns out not to be that difficult in Retina 0.8.2. Here is the required program: ``` T`Lld+/`_o }`$ / ``` [Try it online!](https://tio.run/##K0otycxL/P8/JMEnJ0VbPyE@n6s2QYVL//9/AA "Retina 0.8.2 – Try It Online") Explanation: Each pass through the loop, the characters in the string get transliterated through the contents of the pattern, with the first character of the pattern being deleted, and a new copy of the last character is appended. The loop becomes idempotent when the buffer equals the contents of the pattern, as then the deletion of the first character and the append of the last character is balanced by the transliteration of the intervening characters. You can generate a prefix of a pattern by using the appropriate ending character in the append stage. The code as shown is designed to be used to produce input as part of a larger program, which is why it does not begin with a loop block; it would need an extra `{` if it was embedded within a larger program. If the code actually appears at the end, or it is the desired program, then you can go on to remove the trailing loop block instead, saving a byte. Note that when embedded within a larger program the code will normally delete any other copies of the output pattern present within the work buffer while appending a copy of the output pattern. You may be able to avoid the deletion by use of a suitable pattern to restrict the scope of the transliteration. It is also possible to adapt the code to prefix rather than append the desired output. ]
[Question] [ # Task Your task is to write a program that will output ASCII boxes at the locations specified by the input. ## Input You will be given a list of numbers. The format here is a bit flexible, in that you can use any deliminator you want (e.g. `1,2,3,4`, `1 2 3 4`, `[1,2,3,4]`). The list is in groups of 4 and specifies the `xywh` of each box. The width and height of each box will be at least 2. `x` and `width` are left-to-right. `y` and `height` are top-to-bottom. ## Output Rendering can be thought of as right to left, with the box on the right drawn first, and every box after that is over it. Trailing spaces are allowed, as well as one trailing newline. ## How to handle overlapping boxes The box on the left of the input is the top box, and nothing will overlap it. Every box after it is rendered only in the space that is not contained in a box already and will not replace the border of a already rendered box. ## Style The style of the boxes are fairly standard, with `+` used for corners, `-` used for horizontal lines, and `|` used for vertical lines. # Examples: (`>>>` denotes input) ``` >>>0 0 11 4 7 2 8 4 3 5 8 3 +---------+ | | | |---+ +---------+ | | | +---+------+ | | +------+ >>>0 3 11 4 7 5 8 4 3 8 8 3 4 0 13 5 +-----------+ | | | | +---------+ | | |-----+ | |---+ +---------+ | | | +---+------+ | | +------+ >>>0 0 2 2 ++ ++ >>>2 2 5 3 1 1 7 5 0 0 9 7 +-------+ |+-----+| ||+---+|| ||| ||| ||+---+|| |+-----+| +-------+ >>>0 0 3 3 2 0 3 3 +-+-+ | | | +-+-+ ``` [Answer] # APL, 116 bytes ``` {⎕IO←0⋄K←' '⍴⍨⌽+⌿2 2⍴⌈⌿↑⍵⋄K⊣{x y W H←⍵-⌊.5×⍳4⋄K[Y←y+⍳H;X←x+⍳W]←' '⋄K[Y;A←x+0 W]←'|'⋄K[B←y+0 H;X]←'-'⋄K[B;A]←'+'}¨⌽⍵} ``` This is a function that takes an array of arrays and returns a character matrix. Tests: ``` t1← (0 0 11 4)(8 2 8 4)(3 5 8 3) t2← (0 3 11 4)(8 5 8 4)(3 8 8 3)(4 0 13 5) t3← (⊂0 0 2 2) t4← (2 2 5 3)(1 1 7 5)(0 0 9 7) {⎕IO←0⋄K←' '⍴⍨⌽+⌿2 2⍴⌈⌿↑⍵⋄K⊣{x y W H←⍵-⌊.5×⍳4⋄K[Y←y+⍳H;X←x+⍳W]←' '⋄K[Y;A←x+0 W]←'|'⋄K[B←y+0 H;X]←'-'⋄K[B;A]←'+'}¨⌽⍵} ¨ t1 t2 t3 t4 ┌───────────────────┬─────────────────────┬────┬───────────┐ │+---------+ │ +-----------+ │++ │+-------+ │ │| | │ | | │++ │|+-----+| │ │| |----+ │ | | │ │||+---+|| │ │+---------+ | │+---------+ | │ │||| ||| │ │ | | │| |-----+ │ │||+---+|| │ │ +----+------+ │| |----+ │ │|+-----+| │ │ | | │+---------+ | │ │+-------+ │ │ +------+ │ | | │ │ │ │ │ +----+------+ │ │ │ │ │ | | │ │ │ │ │ +------+ │ │ │ │ │ │ │ │ │ │ │ │ │ └───────────────────┴─────────────────────┴────┴───────────┘ ``` Explanation: * `⎕IO←0`: set the index origin to `0`. * Create a matrix of the right size: + `⌈⌿↑⍵`: find the largest values for x, y, w, and h + `+⌿2 2⍴`: x+w and y+h + `K←' '⍴⍨⌽`: make a matrix of x+w\*y+h spaces and store it in `K`. * Draw the boxes into it: + `{`...`}¨⌽⍵`: for each of the boxes, in reverse order, - `x y W H←⍵-⌊.5×⍳4`: assign the coordinates to `x`, `y`, `W`, and `H`, and subtract 1 from both `W` and `H`. (coordinates are exclusive, APL array ranges are inclusive.) - `K[Y←y+⍳H;X←x+⍳W]←' '`: fill the current box with spaces - `K[Y;A←x+0 W]←'|'`: draw the vertical sides - `K[B←y+0 H;X]←'-'`: draw the horizontal sides - `K[B;A]←'+'`: set the edges to '+' + `K⊣`: afterwards, return `K`. [Answer] ## ES6, ~~228~~ ~~223~~ ~~217~~ ~~208 201~~ 198 bytes Accepts an array of arrays of coordinates and returns a string. ``` a=>a.reverse().map(([x,y,w,h])=>[...Array(y+h)].map((_,i)=>(s=r[i]||'',r[i]=i<y?s:(s+' '.repeat(x)).slice(0,x)+(c=>c[0]+c[1].repeat(w-2)+c[0])(y-i&&y+h-1-i?'| ':'+-')+s.slice(x+w))),r=[])&&r.join`\n` ``` Where `\n` represents a newline character. Edit: Saved 5 bytes by reversing my conditions. Saved a further 6 bytes by switching from an array of char arrays to an array of strings. Saved a further 9 bytes by introducing a temporary variable. Saved a further 7 bytes by introducing a helper function. Saved a further 3 bytes by undoing a previous saving! [Answer] # Ruby, ~~153~~ 143 ``` ->n{a=(0..m=3*n.max).map{$b=' '*m} (*n,x,y,w,h=n v=w-2 h.times{|i|a[y+i][x,w]=i%~-h<1??++?-*v+?+:?|+' '*v+?|} )while n[0] a.delete($b);puts a} ``` **Ungolfed in test program** ``` f=->n{ #worst case width when x=w=large number, is max input*2+1 a=(1..m=3*n.max).map{$b=' '*m} #find m=max value in input, make an a array of 3*m strings of 3*m spaces ( *n,x,y,w,h=n #extract x,y,w,h from the end of n, save the rest back to n v=w-2 #internal space in rectangle is w-2 h.times{|i| #for each row a[y+i][x,w]= #substitute the relevant characters of the relevant lines of a i%~-h<1? #i%~-h = i%(h-1). This is zero (<1) for first and last lines of the rectangle ?+ + ?-*v + ?+ :?| + ' '*v +?| # +--...--+ or | ... | as required } )while n[0] #loop until data exhausted (n[0] becomes falsy as it does not exist) a.delete($b);puts a} #delete blank rows ($b is a global variable) and display ``` [Answer] # SmileBASIC, ~~128~~ 125 bytes ``` DEF B A WHILE LEN(A)H=POP(A)W=POP(A)-2Y=POP(A)X=POP(A)FOR I=0TO H-1LOCATE X,Y+I?"+|"[M];"- "[M]*W;"+|"[M]M=I<H-2NEXT WEND END ``` ### Screenshots (cropped) [![screenshot](https://i.stack.imgur.com/kv4Al.png)](https://i.stack.imgur.com/kv4Al.png) [![screenshot](https://kland.smilebasicsource.com/i/btape.bmp)](https://kland.smilebasicsource.com/i/btape.bmp) [![screenshot](https://i.stack.imgur.com/wr0V9.png)](https://i.stack.imgur.com/wr0V9.png) [![screenshot](https://i.stack.imgur.com/cuUHH.png)](https://i.stack.imgur.com/cuUHH.png) [![screenshot](https://i.stack.imgur.com/F8FO1.png)](https://i.stack.imgur.com/F8FO1.png) ### Explanation ``` DEF B A 'make a function and add 12 bytes :( WHILE LEN(A) 'repeat until array is empty H=POP(A):W=POP(A)-2 'get width/height Y=POP(A):X=POP(A) 'get x/y FOR I=0 TO H-1 'draw one row at a time LOCATE X,Y+I 'position the cursor PRINT "+|"[M]; 'draw left edge PRINT "- "[M]*W; 'draw middle PRINT "+|"[M] 'draw right edge M=I<H-2 NEXT WEND END ``` `M` stores whether it's on the first/last row of the box (`0`=`+--+`, `1`=`| |`). On the first pass through the loop, `M` is 0, and on all others until the last, it's 1. [Answer] # Pyth, ~~162~~ 145 bytes ``` J\+K*h.MZm+@d1@d3Q]*h.MZm+@d0@d2QdD:GHb XKHX@KHGb;V_QDlTR@NTVl3Vl2:+l0b+l1H?|qHtl3qH0\-?|qbtl2qb0\|d)):l0l1J:+l0tl2l1J:l0+l1tl3J:+l0tl2+l1tl3J;jK ``` You can try it [here](https://pyth.herokuapp.com/?code=J%5C%2BK%2ah.MZm%2B%40d1%40d3Q%5D%2ah.MZm%2B%40d0%40d2QdD%3AGHb+XKHX%40KHGb%3BV_QDlTR%40NTVl3Vl2%3A%2Bl0b%2Bl1H%3F%7CqHtl3qH0%5C-%3F%7Cqbtl2qb0%5C%7Cd%29%29%3Al0l1J%3A%2Bl0tl2l1J%3Al0%2Bl1tl3J%3A%2Bl0tl2%2Bl1tl3J%3BjK&input=%5B%5B0%2C0%2C11%2C4%5D%2C%5B8%2C2%2C8%2C4%5D%2C%5B3%2C5%2C8%2C3%5D%5D&test_suite=1&test_suite_input=%5B%5B0%2C0%2C11%2C4%5D%2C%5B8%2C2%2C8%2C4%5D%2C%5B3%2C5%2C8%2C3%5D%5D%0A%5B%5B0%2C0%2C2%2C2%5D%5D%0A%5B%5B2%2C2%2C5%2C3%5D%2C%5B1%2C1%2C7%2C5%5D%2C%5B0%2C0%2C9%2C7%5D%5D%0A%5B%5B0%2C0%2C3%2C3%5D%2C%5B2%2C0%2C3%2C3%5D%5D&debug=0) Output of test suite: ``` +---------+ | | | |----+ +---------+ | | | +----+-+----+ | | +------+ ++ ++ +-------+ |+-----+| ||+---+|| ||| ||| ||+---+|| |+-----+| +-------+ +-+-+ | | | +-+-+ ``` Horrible solution! Just waiting for someone to beat it ]
[Question] [ What general tips do you have for golfing in Forth (and its clones)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Forth (e.g. "remove comments" is not an answer). [Answer] ## Avoid explicit loops at all costs Forth has two looping constructs, `x y do` ... `loop`, and lesser known `[begin]` ... `[until] x y` where `x` and `y` are values for limit and index, or conditions to be noted, respectively. These are very slow, very wordy (haha) and overall rather bloaty, so only use them if you need to. Instead, like a proper functional language (which Forth is, really), one should prefer recursivity over explicit loops because it tends to be shorter and makes a better use of the language. [Answer] Forth has a **lot** of cool builtin words, many of which are helpful for crafting the sorts of algorithms found on PPCG. A bad but illustrative example of this are the words for increment (`1+`) and decrement (`1-`). They save a byte over writing `1 +` to increment the top of the stack. Additonally, [here](http://astro.pas.rochester.edu/Forth/forth-words.html) is a handy list of many (probably not all) words found in modern distributions like `gforth`. [Answer] ## Leave the junk Programs aren't required to be stack-safe. Instead, they can leave extra junk on the stack if it saves you bytes. In Forth, the "return value" is leaving something on top of the stack. It probably doesn't matter what junk you have below that on the stack unless you're using recursion and stack depth matters. [Answer] ## Watch the stack When writing your code, pay attention to what happens on the stack at each command. I usually draw it out as I go, like so: ``` 6 6 7 7 6 * DUP 42 42 ``` As you go like this, you may find it easier to recognize when you can make use of stack operations like `ROT`, `-ROT`, `2DUP`, `2OVER`, etc... [Answer] ## (gforth-specific) Utilize the separate floating-point stack gforth has a separate stack for floating-point numbers. Even if you're only dealing with integers, offloading some work and storage to the FP stack may result in shorter code overall, either by avoiding explicit stack manipulation or using FP-specific operations not available on the main stack. Returning to the FP stack is also a perfectly valid option (except when the task is to return a boolean). * FP-related operations (arithmetic, stack manipulation) usually cost one more byte each (the `f` prefix, as in `f+`, `fdup` etc.). FP number literals also cost one more byte (postfix `e`, as in `1e`), but some numbers can tie or even save a byte (e.g. `1e3` instead of `1000`). * Some operations are missing on the FP stack, probably the most painful being `1+` and `1-`. * FP stack's unique operations include `f**` (power), `falog` (power of 10), `fsqrt`, and various exp, log, trigonometry-related ones. * You can move numbers between main and FP stacks via `s>f` (single to float), `f>s` (float to single), `d>f` (double to float), `f>d` (float to double). At times, the "double" variations may be used to produce or consume an extra zero. [Answer] # Try using various double-cell words This includes double-cell [arithmetic](https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Double-precision.html#Double-precision), [bitwise](https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Bitwise-operations.html#Bitwise-operations), [number comparison](https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Numeric-comparison.html#Numeric-comparison) and [stack manipulation](https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Data-stack.html#Data-stack) words. Double-cell integer literals also count. * Appending a period on an integer literal (e.g. `1.`) gives a double-cell literal. For small numbers, it means pushing an extra zero at the cost of only one byte. * `m+` = `0 d+` ~= `under+` (not exactly, since overflow may occur.) * `d2*` and `d2/` could be used to extract/push one bit from a word. * `a b c d d=` = `a c = b d = and` * `a b c d d<>` = `a c <> b d <> or` * Words that copy two numbers at once, e.g. `2dup`, `2over`, `2tuck` have a good chance to win over local variables. ]
[Question] [ ## Background The **Rearrangement Inequality** is an inequality that is based on rearranging numbers. If I have two lists of numbers of the same length, x0, x1, x2...xn-1 and y0, y1, y2...yn-1 of the same length, where I am allowed to rearrange the numbers in the list, a way to maximize the sum x0y0+x1y1+x2y2+...+xn-1yn-1 is to sort the 2 lists in non-decreasing order. Read the [Wikipedia](https://en.wikipedia.org/wiki/Rearrangement_inequality) article here. ## Task You would write a program that takes input from STDIN or a function that accepts 2 arrays (or related containers) of numbers (which are of the same length). Assuming you write a function which accepts 2 arrays (a and b), you are going to find the number of ways you can rearrange the numbers in the second array (b) to maximize: ``` a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+...+a[n-1]*b[n-1] ``` In this case, if the array b is [10, 21, 22, 33, 34] (indices for clarity), [10, 21, 22, 33, 34], [10, 21, 22, 34, 33], (swap the two 3's) [10, 22, 21, 33, 34] (swap the two 2's) [10, 22, 21, 34, 33] (swap the two 3's and swap the two 2's) are considered different arrangements. The original array, itself, also counts as a possible rearrangement if it also maximizes the sum. For STDIN input, you may assume that the length of the arrays is provided before the arrays (please state so that you use it), or that the arrays are provided on different lines (also please state). Here are the 4 possible inputs (for convenience): ``` 5 1 1 2 2 2 1 2 2 3 3 (length before arrays) 1 1 2 2 2 1 2 2 3 3 (the 2 arrays, concatenated) 1 1 2 2 2 1 2 2 3 3 (the 2 arrays on different lines) 5 1 1 2 2 2 1 2 2 3 3 (length before arrays and the 2 arrays on different lines) ``` For output, you are allowed to return the answer (if you write a function) or print the answer to STDOUT. You may choose to output the answer mod 109+7 (from 0 to 109+6) if it is more convenient. ## Test Cases (and explanation): ``` [1 1 2 2 2] [1 2 2 3 3] => 24 ``` The first 2 entries have to be 1 and 2. The last 3 entries are 2, 3 and 3. There are 2 ways to arrange the 2's between the first 2 entries and the last 2 entries. Among the first 2 entries, there are 2 ways to rearrange them. Among the last 2 entries, there are 6 ways to rearrange them. ``` [1 2 3 4 5] [6 7 8 9 10] => 1 ``` There is only 1 way, which is the arrangement given in the arrays. ``` [1 1 ... 1 1] [1 1 ... 1 1] (10000 numbers) => 10000! or 531950728 ``` Every possible permutation of the second array is valid. Dennis' Testcase: [Pastebin](http://pastebin.com/b9QhK0QM#) => 583159312 (mod 1000000007) ## Scoring: This is code-golf, so shortest answer wins. In case of tie, ties will be broken by time of submission, favouring the earlier submission. ## Take note: The containers may be unsorted. The integers in the containers may be zero or negative. The program has to run fast enough (at most an hour) for modestly sized arrays (around 10000 in length). Inspired by [this question](https://math.stackexchange.com/questions/1516103/maximum-sum-of-polynomial-choice-of-coefficient-and-variables/1516119 "Rearrangement Inequality") on Mathematics Stack Exchange. [Answer] # Pyth, ~~29~~ 28 bytes ``` M/*FPJm*F.!MhMrd8aFCB,SGSHeJ ``` Try it online in the [Pyth Compiler](https://pyth.herokuapp.com/?code=M%2F%2aFPJm%2aF.%21MhMrd8aFCB%2CSGSHeJ%0A%0Ag%5B1+1+2+2+2%29%5B1+2+2+3+3%29). ### Algorithm The result does not depend on the order of **A**, so we can assume it to be sorted. This means that **B** must also be sorted to attain the maximal dot product. Now, if **r1, … rn** are the length of the runs of the sorted **A**, there are **∏rk!** different rearrangements of the elements of **A** that still result in ascending order. Likewise, if **s1, … sn** are the length of the runs of the sorted **B**, there are **∏sk!** different rearrangements of the elements of **B** that still result in ascending order. However, this counts all pairings multiple times. If we take the pairs of of the corresponding elements of sorted **A** and sorted **B** and define **t1, … tn** as the length of the runs of the resulting array, **∏tk!** is the aforementioned multiplier. Thus, the desired result is **(∏rk!) × (∏sk!) ÷ (∏tk!)**. ### Code ``` M/*FPJm*F.!MhMrd8aFCB,SGSHeJ M Define g(G,H): SGSH Sort G and H. , For the pair of the results. CB Bifurcated zip (C). This returns [[SG, SH], zip([SG, SH])]. aF Reduce by appending. This returns [SG, SH, zip([SG, SH])]. m Map; for each d in the resulting array: rd8 Perform run-length encoding on d. hM Mapped "head". This returns the lengths. .!M Mapped factorial. *F Reduce by multiplication. J Save the result in J. P Discard the last element. *F Reduce by multiplication. / eJ Divide the product by the last element of J. Return the result of the division. ``` ### Verification I've pseudo-randomly generated 100 test cases of length 6, which I've solved with the above code and this brute-force approach: ``` Ml.Ms*VGZ.pH M Define g(G,H) (or n(G,H) on second use): .pH Compute all permutations of H. .M Filter .pH on the maximal value of the following; for each Z in .pH: *VGZ Compute the vectorized product of G and Z. s Add the products. This computes the dot product of G and Z. l Return the length of the resulting array. ``` These were the results: ``` $ cat test.in 6,9,4,6,8,4,5,6,5,0,8,2 0,7,7,6,1,6,1,7,3,3,8,0 3,6,0,0,6,3,8,2,8,3,1,1 2,3,0,4,0,6,3,4,5,8,2,4 9,1,1,2,2,8,8,1,7,4,9,8 8,3,1,1,9,0,2,8,3,4,9,5 2,0,0,7,7,8,9,2,0,6,7,7 0,7,4,2,2,8,6,5,0,5,4,9 2,7,7,5,5,6,8,8,0,5,6,3 1,7,2,7,7,9,9,2,9,2,9,8 7,2,8,9,9,0,7,4,6,2,5,3 0,1,9,2,9,2,9,5,7,4,5,6 8,4,2,8,8,8,9,2,5,4,6,7 5,2,8,1,9,7,4,4,3,3,0,0 9,3,6,2,5,5,2,4,6,8,9,3 4,2,0,6,2,3,5,3,6,3,1,4 4,8,5,2,5,0,5,1,2,5,9,5 6,8,4,4,9,5,9,5,4,2,8,7 8,9,8,1,2,2,9,0,5,6,4,9 4,7,6,8,0,3,7,7,3,9,8,6 7,5,5,6,3,9,3,8,8,4,8,0 3,8,1,8,5,6,6,7,2,8,5,3 0,9,8,0,8,3,0,3,5,9,5,6 4,2,7,7,5,8,4,2,6,4,9,4 3,5,0,8,2,5,8,7,3,4,5,5 7,7,7,0,8,0,9,8,1,4,8,6 3,9,7,7,4,9,2,5,9,7,9,4 4,5,5,5,0,7,3,4,0,1,8,2 7,4,4,2,5,1,7,4,7,1,9,1 0,6,2,5,4,5,1,8,0,8,9,9 3,8,5,3,2,1,1,2,2,2,8,4 6,1,9,1,8,7,5,6,9,2,8,8 6,2,6,6,6,0,2,7,8,6,8,2 0,7,1,4,5,5,3,4,4,0,0,2 6,0,1,5,5,4,8,5,5,2,1,6 2,6,3,0,7,4,3,6,0,5,4,9 1,4,8,0,5,1,3,2,9,2,6,5 2,7,9,9,5,0,1,5,6,8,4,6 4,0,1,3,4,3,6,9,1,2,7,1 6,5,4,7,8,8,6,2,3,4,1,2 0,3,6,3,4,0,1,4,5,5,5,7 5,4,7,0,1,3,3,0,2,1,0,8 8,6,6,1,6,6,2,2,8,3,2,2 7,1,3,9,7,4,6,6,3,1,5,8 4,8,3,3,9,1,3,4,1,3,0,6 1,4,0,7,4,9,8,4,2,1,0,3 0,4,1,6,4,4,4,7,5,1,4,2 0,0,4,4,9,6,7,2,7,7,5,4 9,0,5,5,0,8,8,9,5,9,5,5 5,7,0,4,2,7,6,1,1,1,9,1 3,1,7,5,0,3,1,4,0,9,0,3 4,4,5,7,9,5,0,3,7,4,7,5 7,9,7,3,0,8,4,0,0,3,1,0 2,4,4,3,1,2,5,2,9,0,8,5 4,8,7,3,0,0,9,3,7,3,0,6 8,9,1,0,7,7,6,0,3,1,8,9 8,3,1,7,3,3,6,1,1,7,6,5 6,5,6,3,3,0,0,5,5,0,6,7 2,4,3,9,7,6,7,6,5,6,2,0 4,8,5,1,8,4,4,3,4,5,2,5 7,5,0,4,6,9,5,0,5,7,5,5 4,8,9,5,5,2,3,1,9,7,7,4 1,5,3,0,3,7,3,8,5,5,3,3 7,7,2,6,1,6,6,1,3,5,4,9 9,7,6,0,1,4,0,4,4,1,4,0 3,5,1,4,4,0,7,1,8,9,9,1 1,9,8,7,4,9,5,2,2,1,2,9 8,1,2,2,7,7,6,8,2,3,9,7 3,5,2,1,3,5,2,2,4,7,0,7 9,6,8,8,3,5,2,9,8,7,4,7 8,8,4,5,5,1,5,6,5,1,3,3 2,6,3,5,0,5,0,3,4,4,0,5 2,2,7,6,3,7,1,4,0,3,8,3 4,8,4,2,6,8,5,6,2,5,0,1 7,2,4,3,8,4,4,6,5,3,9,4 4,6,1,0,6,0,2,6,7,4,9,5 6,3,3,4,6,1,0,8,6,1,7,5 8,3,4,2,8,3,0,1,8,9,1,5 9,6,1,9,1,1,8,8,8,9,1,4 3,6,1,6,1,4,5,1,0,1,9,1 6,4,3,9,3,0,5,0,5,3,2,4 5,2,4,6,1,2,6,0,1,8,4,0 3,5,7,6,3,6,4,5,2,8,1,5 6,3,6,8,4,2,7,1,5,3,0,6 9,1,5,9,9,1,1,4,5,7,3,0 1,6,7,3,5,8,6,5,5,2,6,0 2,8,8,6,5,5,2,3,8,1,9,8 0,4,5,3,7,6,2,5,4,3,2,5 5,1,2,3,0,3,4,9,4,9,4,9 5,8,2,2,0,2,4,1,1,7,0,3 0,6,0,0,3,6,3,6,2,2,2,9 2,4,8,1,9,4,0,8,8,0,4,7 3,9,1,0,5,6,8,8,2,5,2,6 5,3,8,9,1,6,5,9,7,7,6,1 8,6,9,6,1,1,6,7,7,3,2,2 7,2,1,9,8,8,5,3,6,3,3,6 9,9,4,8,7,9,8,6,6,0,3,1 8,3,0,9,1,7,4,8,0,1,6,2 8,2,6,2,4,0,2,8,9,6,3,7 1,0,8,5,3,2,3,7,1,7,8,2 $ while read; do > pyth -c 'M/*FPJm*F.!MhMrd8aFCB,SGSHeJMl.Ms*VGZ.pHAc2Q,gGHnGH' <<< "$REPLY" > done < test.in [4, 4] [4, 4] [8, 8] [4, 4] [8, 8] [2, 2] [4, 4] [4, 4] [4, 4] [36, 36] [2, 2] [8, 8] [24, 24] [8, 8] [2, 2] [2, 2] [6, 6] [2, 2] [8, 8] [2, 2] [12, 12] [2, 2] [8, 8] [12, 12] [4, 4] [12, 12] [4, 4] [6, 6] [8, 8] [8, 8] [6, 6] [4, 4] [48, 48] [8, 8] [4, 4] [1, 1] [4, 4] [4, 4] [8, 8] [4, 4] [12, 12] [2, 2] [96, 96] [2, 2] [4, 4] [2, 2] [6, 6] [24, 24] [24, 24] [48, 48] [4, 4] [8, 8] [12, 12] [8, 8] [4, 4] [2, 2] [24, 24] [16, 16] [2, 2] [8, 8] [24, 24] [4, 4] [24, 24] [4, 4] [12, 12] [8, 8] [12, 12] [4, 4] [8, 8] [4, 4] [16, 16] [4, 4] [8, 8] [8, 8] [4, 4] [4, 4] [4, 4] [4, 4] [72, 72] [24, 24] [4, 4] [4, 4] [4, 4] [2, 2] [12, 12] [4, 4] [8, 8] [4, 4] [36, 36] [6, 6] [12, 12] [8, 8] [4, 4] [2, 2] [8, 8] [24, 24] [6, 6] [1, 1] [2, 2] [2, 2] ``` To verify my submission satisfies the speed requirement, I've ran it with [this test case](http://pastebin.com/dD7uk8Pr). ``` $ time pyth -c 'M/*FPJm*F.!MhMrd8aFCB,SGSHeJAc2QgGH' < test-large.in | md5sum 5801bbf8ed0f4e43284f7ec2206fd3ff - real 0m0.233s user 0m0.215s sys 0m0.019s ``` [Answer] # CJam, ~~30~~ 26 bytes ``` q~](/:$_za+{e`0f=:m!:*}//* ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%5D(%2F%3A%24_za%2B%7Be%600f%3D%3Am!%3A*%7D%2F%2F*&input=5%0A1%201%202%202%202%0A1%202%202%203%203). It completes [this test case](http://pastebin.com/b9QhK0QM) in less than a second: ``` $ time cjam <(echo 'q~](/:$_za+{e`0f=:m!:*}%)\:*\/N') < test-large.in | md5sum 5801bbf8ed0f4e43284f7ec2206fd3ff - real 0m0.308s user 0m0.667s sys 0m0.044s ``` Running it in the online interpreter should take less than 10 seconds. ### Algorithm The result does not depend on the order of **A**, so we can assume it to be sorted. This means that **B** must also be sorted to attain the maximal dot product. Now, if **r1, … rn** are the length of the runs of the sorted **A**, there are **∏rk!** different rearrangements of the elements of **A** that still result in ascending order. Likewise, if **s1, … sn** are the length of the runs of the sorted **B**, there are **∏sk!** different rearrangements of the elements of **B** that still result in ascending order. However, this counts all pairings multiple times. If we take the pairs of of the corresponding elements of sorted **A** and sorted **B** and define **t1, … tn** as the length of the runs of the resulting array, **∏tk!** is the aforementioned multiplier. Thus, the desired result is **(∏rk!) × (∏sk!) ÷ (∏tk!)**. ### Code ``` q~ Read and evaluate all input. ] Wrap the resulting integers in an array. ( Shift out the first (length). / Split the remainder into chunks of that length. :$ Sort each chunk. _z Push a copy and transpose rows with columns. This pushes the array of corresponding pairs. a+ Wrap in array and concatenate (append). { }/ For A, B, and zip(A,B): e` Perform run-length encoding. 0f= Select the runs. :m! Apply factorial to each. :* Reduce by multiplication. / Divide the second result by the third. * Multiply the quotient with the first result. ``` [Answer] ## Matlab, 230 bytes > > Edit: Many things fixed to match dennis' test cases, and nnz is replaced by numel due to nil values. > > > ``` f=1;t=-1;q=1;a=sort(input(''));b=sort(input(''));for i=unique(a)c=b(find(a==i));r=numel(c(c==t));f=f*factorial(numel(c))*sum(arrayfun(@(u)nchoosek(max(q,r),u),0:min(q,r)));z=c(end);y=numel(c(c==z));q=(t==z)*(q+r)+(t~=z)*y;t=z;end,f ``` --- ## Execution ``` [2 2 1 2 1] [3 2 3 2 1] f = 24 ``` ## Dennis' Testcase: ``` A = importdata('f:\a.csv'); for i=1:100,a=sort(A(i,1:6));b=sort(A(i,7:12)); f=1;t=-1;q=1;for i=unique(a)c=b(find(a==i));r=numel(c(c==t));f=f*factorial(numel(c))*sum(arrayfun(@(u)nchoosek(max(q,r),u),0:min(q,r)));z=c(end);y=numel(c(c==z));q=(t==z)*(q+r)+(t~=z)*y;t=z;end; disp(f);end ``` **Outputs:** ``` 4 4 8 4 8 2 4 4 4 36 2 8 24 8 2 2 6 2 8 2 12 2 8 12 4 12 4 6 8 8 6 4 48 8 4 1 4 4 8 4 12 2 96 2 4 2 6 24 24 48 4 8 12 8 4 2 24 16 2 8 24 4 24 4 12 8 12 4 8 4 16 4 8 8 4 4 4 4 72 24 4 4 4 2 12 4 8 4 36 6 12 8 4 2 8 24 6 1 2 2 ``` [Answer] ## C++, 503 bytes (just for fun, a non-golfing language) ``` #import<iostream> #import<algorithm> #define U 12345 #define l long long using namespace std;int N,X=1,Y=1,Z=1,x[U],y[U],i=1;l p=1,M=1000000007,f[U];l e(l x,int y){return y?y%2?(x*e(x,y-1))%M:e((x*x)%M,y/2):1;}main(){for(f[0]=1;i<U;i++)f[i]=(f[i-1]*i)%M;cin>>N;for(i=0;i<N;i++)cin>>x[i];for(i=0;i<N;i++)cin>>y[i];sort(x,x+N);sort(y,y+N);for(i=1;i<N;i++)x[i]^x[i-1]?p=p*f[X]%M,X=1:X++,y[i]^y[i-1]?p=p*f[Y]%M,Y=1:Y++,x[i]^x[i-1]|y[i]^y[i-1]?p=p*e(f[Z],M-2)%M,Z=1:Z++;cout<<p*f[X]%M*f[Y]%M*e(f[Z],M-2)%M;} ``` Ungolfed version: ``` #include <cstdio> #include <algorithm> #define MOD 1000000007 using namespace std; int N; // number of integers int x[1000010]; // the 2 arrays of integers int y[1000010]; long long product = 1; long long factorial[1000010]; // storing factorials mod 1000000007 long long factorialInv[1000010]; // storing the inverse mod 1000000007 long long pow(long long x, int y) { if (y == 0) return 1; if (y == 1) return x; if (y%2 == 1) return (x*pow(x, y-1))%MOD; return pow((x*x)%MOD, y/2); } int main(void) { //freopen("in.txt", "r", stdin); // used for faster testing //precomputation factorial[0] = factorial[1] = 1; for (int i=2;i<=1000000;i++) { factorial[i] = (factorial[i-1]*i)%MOD; factorialInv[i] = pow(factorial[i], MOD-2); } // input scanf("%d", &N); for (int i=0;i<N;i++) { scanf("%d", &x[i]); } for (int i=0;i<N;i++) { scanf("%d", &y[i]); } // sort the 2 arrays sort(x, x+N); sort(y, y+N); int sameX = 1; int sameY = 1; int sameXY = 1; for (int i=1;i<N;i++) { if (x[i]==x[i-1]) { sameX++; } else { product *= factorial[sameX]; product %= MOD; sameX = 1; } if (y[i]==y[i-1]) { sameY++; } else { product *= factorial[sameY]; product %= MOD; sameY = 1; } if (x[i]==x[i-1] && y[i]==y[i-1]) { sameXY++; } else { product *= factorialInv[sameXY]; product %= MOD; sameXY = 1; } } product *= factorial[sameX]; product %= MOD; product *= factorial[sameY]; product %= MOD; product *= factorialInv[sameXY]; product %= MOD; printf("%lld\n", product); return 0; } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` Ṣ€ZṭµŒɠ!P)×:ƭ/ ``` [Try it online!](https://tio.run/##y0rNyan8///hzkWPmtZEPdy59tDWo5NOLlAM0Dw83erYWv3///9HG@ooAJERBMXqKETDecZAFAsA "Jelly – Try It Online") Implements [Dennis' method](https://codegolf.stackexchange.com/a/64453/66833). Ignoring time requirements leads to an **8** byte solution: ``` Œ!ḋÐṀ¥@L ``` [Try it online!](https://tio.run/##y0rNyan8///oJMWHO7oPT3i4s@HQUgef////RxvqKACREQTFgvkQjjEQxQIA "Jelly – Try It Online") which can be **6** bytes if we take input in reverse order: ``` Œ!ḋÐṀL ``` [Try it online!](https://tio.run/##y0rNyan8///oJMWHO7oPT3i4s8Hn////0YY6CkZgZAxEsWA@XMgoFgA "Jelly – Try It Online") ## How they work ``` Ṣ€ZṭµŒɠ!P)×:ƭ/ - Main link. Takes a pair of lists [A, B] Ṣ€ - Sort each Z - Transpose to get all pairs ṭ - Append that to [A, B], yielding [A, B, zip(A, B)] µ - Call that triple T and start a new link with T as the argument ) - Over each element in T: Œɠ - Lengths of runs ! - Factorial of each P - Product / - Reduce the triple: ƭ - Tie 2 dyads and cycle them: × - Multiplication : - Integer division For the triple [r, s, t], this yields (r×s):t ``` The 8 byte solution works in the following way: ``` Œ!ḋÐṀ¥@L - Main link. Takes A on the left and B on the right ¥ - Group the previous 2 links into a dyad f(B, A): Œ! - All permutations of B ÐṀ - Keep those which yield a maximal value under: ḋ - Dot product with A @ - Run f(B, A) L - Length ``` The `¥@` is simply to compensate for inputs being in the wrong order. Of course, the **8** and **6** byte versions have complexity proportional to \$\text{length}(B)!\$, which grows very fast. ]
[Question] [ Write two code fragments, which we will call s\_zero and s\_one. Program (l, n) consists of l copies of s\_zero and s\_one corresponding with the digits of n in binary, padded with s\_zero on the left. For example, if s\_zero = `foo` and s\_one = `bar` then Program (4, 0) = `foofoofoofoo` Program (4, 1) = `foofoofoobar` Program (4, 2) = `foofoobarfoo` etc. Program (l, n) must print the source of Program (l, (n + 1) mod (2^l)) to standard out. In the example above, `foobarfoofoo` must print `foobarfoobar` when executed. Your score is the sum of the lengths of fragments s\_zero and s\_one [Answer] # CJam, 29 + 29 = 58 bytes The 0 code: ``` 0{"_~"]]z(3\+2b(2b2>a\+z~[}_~ ``` The 1 code: ``` 1{"_~"]]z(3\+2b(2b2>a\+z~[}_~ ``` ### Explanation ``` 0 " Push the current bit. "; {"_~" " The basic quine structure. "; ] " Make an array of the current bit, the function and _~. That is the code fragment itself. "; ] " Make an array of all code fragments in the stack. "; z( " Extract the array of the bits. "; 3\+2b(2b2> " Convert from base 2, decrease by one and convert back, keeping the length. "; a\+z " Put the bits back to the original position. "; ~ " Dump the array of code fragments back into the stack. "; [ " Mark the beginning position of the array of the next code fragment. "; }_~ ``` [Answer] # CJam, 47 + 47 = 94 bytes The 0 code: ``` {`"_~"+]:+T2*0+:T)\AsSerS/_,(@2Y$#+2bU@->]zs}_~ ``` The 1 code: ``` {`"_~"+]:+T2*1+:T)\AsSerS/_,(@2Y$#+2bU@->]zs}_~ ``` Excuse the expletive. I'm sure I can still shave off a few bytes there. I'll add an explanation once I decide that I can't be bothered to golf it any further. [Test it here.](http://cjam.aditsu.net/) [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~264 250~~ 120 + 120 = 240 bytes ## Code 0: (120 bytes) ``` for i in(c:=[]),0: c+=0,;exec(s:="i or print(end=f'for i in(c:=[]),0:\\n c+={c[0]^all(c:=c[1:-1])},;exec(s:=%r)#'%s)")# ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/Py2/SCFTITNPI9nKNjpWU8fAikshWdvWQMc6tSI1WaPYylYpUwGopqAoM69EIzUvxTZNHVNPTEweSFd1crRBbFxiTg5IJjna0ErXMFazFmGUapGmsrpqsaaSpvL//wA "Python 3.8 (pre-release) – Try It Online") ## Code 1: (120 bytes) ``` for i in(c:=[]),0: c+=1,;exec(s:="i or print(end=f'for i in(c:=[]),0:\\n c+={c[0]^all(c:=c[1:-1])},;exec(s:=%r)#'%s)")# ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/Py2/SCFTITNPI9nKNjpWU8fAikshWdvWUMc6tSI1WaPYylYpUwGopqAoM69EIzUvxTZNHVNPTEweSFd1crRBbFxiTg5IJjna0ErXMFazFmGUapGmsrpqsaaSpvL//wA "Python 3.8 (pre-release) – Try It Online") ## Test Suite [Try it online!](https://tio.run/##vZDRasIwFIbv8xSHiNjYOBqFbXTkLXZXO6gx1YyahDSCQ3z2LmltxzbY5S4Sfjj/f853jv3wR6M3z9Z1nciAg8MY18aBAqUTkfOiJDTLEYiUZ/RFXqRI2pxjBcFjndI@kXrP68XvzHarY@oqiqx8q5omVkTB8hUrye2r1dyR2WLeEkxmYTRCgv1Nwf6FAtXOnGB3Vo1XugV1ssb5YRRULViEzNnz4NzL@k6wvNAIgbcak4B6aMyuaiDYUPwg5YABP7ybQHchabAisGMoPIL6XsLsZdJIffBHqmMfJ/3ZacD3aCEyKlhZxImKlDBuDLtQXC@XQzTVpFgNMi/vnV9l68fOoH8i2qTG1pmDq05wHVw3Cld9yzFB0J/pOxqJmf6L23H@jRx0ygjtT9FvHy@FeoANzcio2KTWk9pM6nFST6TrPgE "Python 3.8 (pre-release) – Try It Online") ## How it works: * `c` store the binary number of the program on the form of a list The for loop execute twice : * the first time, it assigns `c` to the correct value * the second time, it prints the code replacing a char by 1 or 0 depending on `c`. The `n`th time `c[0]^all(c:=c[1:-1])` is called, it returns the `n`th leftmost bit of `c+1` the next for loop are ignored thanks to the comment `#` The printing is a derivate of this quine : `exec(s:="print('exec(s:=%r)'%s)")` [Answer] # CJam, 45 + 45 = 90 bytes The **0** code: ``` {`]W=L0+:L,Ua*L2b)2b+L,W*>\f{X$!s/\s*"_~"}}_~ ``` The **1** code: ``` {`]W=L1+:L,Ua*L2b)2b+L,W*>\f{X$!s/\s*"_~"}}_~ ``` Explanation soon. [Try it online here](http://cjam.aditsu.net/) [Answer] # GolfScript, 37 + 37 = 74 bytes ``` 0{`".~"+:q;]-2%1\{1$^.@&q@}%\;-1%~}.~ ``` ``` 1{`".~"+:q;]-2%1\{1$^.@&q@}%\;-1%~}.~ ``` Not quite as short as [user23013's CJam solution](https://codegolf.stackexchange.com/a/44962), but I figured I'd post this anyway, if only to (marginally) increase the diversity of the languages used. My solution not directly based on any of the existing solutions (and, indeed, I haven't examined them in detail, as I still don't read CJam very well), but they all feature variants of the same basic quine structure (`{".~"}.~` in GolfScript, `{"_~"}_~` in CJam). That's not really very surprising, since it seems to be one of the most efficient ways to write a quine with an arbitrary payload in these languages. There are several parts of this code I don't really like, and I suspect it may be possible to golf this further, but I've spent too much time on this as it is. ]
[Question] [ ### The Challenge: In this question: [Name the poker hand](https://codegolf.stackexchange.com/questions/6494/name-the-poker-hand) you had to take a five card poker hand and identify it. This question is similar, with two twists: First, the output will be in all lower case. This allows for more golfing, as you don't have to worry about the capitalization of `flush` and `straight` ``` high card one pair two pair three of a kind straight flush full house four of a kind straight flush royal flush ``` Secondly, with the popularity of Texas Hold'em and 7 card stud, we here at code golf should be able to score a **seven card** poker hand am I right? When scoring a seven card hand, use the five best cards for your hand and ignore the two you don't need. ### Reference: List of poker hands: <http://en.wikipedia.org/wiki/List_of_poker_hands> ## Input (lifted directly from the previous thread) 7 *cards* from either stdin or commandline arguments. A card is a two letter string on the form `RS`, where R is rank and S is suit. The **ranks** are `2` - `9` (number cards), `T` (ten), `J` (Jack), `Q` (Queen), `K` (King), `A` (Ace). The **suits** are `S`, `D`, `H`, `C` for spades, diamonds, hearts and clubs respectively. ### Example of cards ``` 5H - five of hearts TS - ten of spades AD - ace of diamonds ``` ### Example of input => desired output ``` 3H 5D JS 3C 7C AH QS => one pair JH 4C 2C 9S 4H JD 2H => two pair 7H 3S 7S 7D AC QH 7C => four of a kind 8C 3H 8S 8H 3S 2C 5D => full house AS KC KD KH QH TS JC => straight ``` Notice in the second example there are actually three pairs, but you can only use five cards, so it's `two pair`. In the fifth example, there are both a `three of a kind` and a `straight` possible, but a `straight` is better, so output `straight`. ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! ### Errata 1. You may not use external resources. 2. Ace is both high and low for straights. [Answer] # Haskell ~~618 603 598 525 512 504 480~~ 464 Cards taken as a line of input. I think I've golfed this to death, but will easily be beaten by ruby etc using the same trick: if you generate all permutations, you get the forward sorts you want to look for straights, plus the reverse sorts you want for testing N of a kind. ``` import Data.List m=map z=take 5 q=m(\x->head[n|(f,n)<-zip"A23456789TJQK"[1..],f==x!!0]) l=m length v=" of a kind" w="flush" y="straight" c f s p r|f&&r="9royal "++w|f&&s='8':y++" "++w|f='5':w|s||r='4':y|True=case p of 4:_->"7four"++v;3:2:_->"6full house";3:_->"3three"++v;2:2:_->"2two pair";2:_->"1one pair";_->"0high card" d x=c([5]==l(group$m(!!1)x))(q x==z[head(q x)..])(l$group$q x)$q x==1:[10..13] k h=tail$maximum$m(d.z)$permutations$words h main=interact k ``` Edited to inline "pair" and use number prefixes after seeing @FDinoff's entry, also composed map functions to shave one more char. [Answer] # Ruby 353 This was based off of [Chron's answer](https://codegolf.stackexchange.com/a/6495/8265) from the original question. This takes input as command line arguments. Basically we just iterate over all combinations of size 5 to get what type of hand it is. Each hand type was modified so that is starts with a number. ("royal flush" -> "0royal 4flush", "high card" -> "9high card"). This allows us to sort strings that were returned. The first string after sorting is the best possible hand. So we print that after removing all numbers from the string. ``` o,p=%w(4flush 1straight) f=/1{5}|1{4}0+1$/ puts $*.combination(5).map{|z|s=[0]*13;Hash[*z.map{|c|s['23456789TJQKA'.index c[0]]+=1;c[1]}.uniq[1]?[f,'5'+p,?4,'2four'+a=' of a kind',/3.*2|2.*3/,'3full house',?3,'6three'+a,/2.*2/,'7two pair',?2,'8one pair',0,'9high card']:[/1{5}$/,'0royal '+o,f,p+' '+o,0,o]].find{|r,y|s.join[r]}[1]}.sort[0].gsub(/\d/,'') ``` [Answer] # C++, ~~622~~ 553 chars four unnecessary newlines added below for clarity. ``` #include"stdafx.h" #include"string" std::string c=" flush",d=" of a kind",e="straight",z[10]={"high card","one pair","two pair","three"+d,e,c,"full house","four"+d,e+c,"royal"+c}, x="CDHSA23456789TJQK";char h[99];int main(){__int64 f,p,t,g,u,v,w,l=1,a=78517370881,b=a+19173960,i,j,q=0;gets_s(h,99);for(i=28;i-->7;){f=p=0; for(j=7;j--;)if(j!=i%7&j!=(i+i/7)%7){f+=l<<x.find(h[j*3+1])*6;p+=l<<x.find(h[j*3])*3-12;} v=p&b*2;u=v&v-1;w=p&p/2;g=p*64&p*8&p&p/8&p/64;f&=f*4;t=f&&p==a?9:f&&g?8:p&b*4?7:u&&w?6:f?5:g||p==a?4:w?3:u?2:v?1:0; q=t>q?t:q;}puts(z[q].c_str());} ``` **Things changed in the golfed version:** Rev 1: Changed all numeric variables to `__int64` for single declaration. Rev 1: Golfed increment and condition of `for` loops Rev 0: Changed octal constants to decimal. Rev 0: Changed `if` statements to assignments with conditional operator. Rev 1: Rearranged further into a single expression for `t`. This required new variable `v` for one of the intermediate values Rev 0: Deleted verbose output. Only outputs the best overall hand. ~~Rev 0: Gave up on compressing the output text (difficult in C because you can't concatenate strings using the + operator.) Writing "flush" only once saved me 12 characters but cost me 15, making me 3 chars worse off overall. So I just wrote it 3 times instead.~~ Rev 1: used `std::string` instead of `char[]` as suggested by FDinoff, making it possible to concatenate with `+`. **Ungolfed version, 714 noncomment nonwhitespace characters.** Loops through all 21 possible hands that can be made from 7 cards and rejects 2 cards each time. The suit and rank of the five chosen cards are totalised in variables f and p with a different octal digit for each suit/rank. Various bit operations are performed to determine the hand type, which is then stored in t (all 21 possibilities are output in the ungolfed version.) Finally the best possible hand is output. ``` #include "stdafx.h" #include "string.h" char x[] = "CDHSA23456789TJQK", h[99], z[10][99] = { "high card", "one pair", "two pair","three of a kind", "straight","flush","full house","four of a kind","straight","royal" }; int main(void) { int i,j,q=0; //i,j:loop counters. q:best possible hand of 7 card scanf_s("%s/n", &h, 99); getchar(); for (i = 7; i < 28; i++){ //f,p: count number of cards of each suit (2 octal digits) and rank (1 octal digit.) //t: best hand for current 5 cards. g:straight flag. u,w: flags for pairs and 3's. //l: constant 1 (64bit leftshift doesn't work on a literal.) //octal bitmasks: a=ace high straight, b=general purpose __int64 f=0,p=0,t=0,g,u,w,l=1,a=01111000000001,b=a+0111111110; for (j = 0; j < 7; j++){ if (j != i %7 & j != (i+i/7) %7){ f += l << (strchr(x,h[j*3+1])-x)*6; p += l << (strchr(x,h[j*3])-x-4)*3; printf_s("%c%c ",h[j*3], h[j*3+1]); } } w=p&b*2; //if 2nd bit set we have a pair if (w) t=1; u= w & w-1; //if there is only one pair w&w-1 evaluates to 0; +ve for 2 pair. if (u) t=2; w = p & p/2; // if 2nd and 1st bit set we have 3 of kind. if (w) t=3; g = p*64 & p*8 & p & p/8 & p/64; // detects all straights except ace high. pattern for ace high in a. if (g||p==a) t=4; f&=f*4; //for a flush we want 5 cards of the same suit, binary 101 if (f) t=5; if (u&&w) t=6; //full house meets conditions of 2 pair and 3 of kind if (p & b*4) t=7; //four of a kind if (f && g) t=8; //straight flush if (f && p==a) t=9; //royal flush printf_s("%s %s \n",z[t],t>7?z[5]:""); q=t>q?t:q; } printf_s("%s %s",z[q],q>7?z[5]:""); getchar(); } ``` **Ungolfed output** ![enter image description here](https://i.stack.imgur.com/9GAnV.png) [Answer] ## perl (>=5.14), ~~411~~ ~~403~~ ~~400~~ ~~397~~ 400 **Edit**: inlined a sub that was only called once, saving 8 chars. **Edit 2**: removed a `.""` that was left over from an early attempt **Edit 3**: instead of a temp variable that preserves the original `$_`, use one to make it unnecessary. Net gain 3 chars. **Edit 4**: fixed failure to detect over-full full house (2x 3-of-a-kind). cost 3 chars. Not quite a winner, but the straight detector is an interesting concept, I think. ``` sub j{join"",sort@_}sub o{j(map{{A=>10}->{$_},11+index(j(2..9).TJQKA,$_)}$h=~/(.(?=@_))/g)=~/.*(..)(??{j map$1+$_.'.*',1..4})/?$1:()}$h=$_=<>;if(j(/(\S)\b/g)=~/(.)\1{4}/){$w=$_==19?royal:straight for o$f=$1}$_=j(/\b(\S)/g)=~s/(.)\1*/length$&/rge;$k=" of a kind";print$w?"$w flush":/4/?four.$k:/3.*2|[23].*3/?"full house":$f?flush:(o".")?straight:/3/?three.$k:/2.*2/?"two pair":/2/?"one pair":"high card" ``` Expanded version: ``` # We'll be doing a lot of sorting and joining sub j { return join "", sort @_; } # r() expects $_ to contain a rank, and converts it to a numeric code. The # code starts at 10 so the numbers will sort correctly as strings, and a list # of 2 values is returned because A is both 10 and 23. All other ranks have # undef as the first value and their proper 11..22 value as the second value. sub r { return ({A=>10}->{$_}, 11+index(j(2..9).TJQKA,$_)); } # Sequence-detector. Factored into a sub because it's run twice; once over # the ranks in the flush suit to find a straight flush and once over all the # ranks to find a straight. On successful match, returns the lowest rank of # the straight (in the 10..23 representation). # Required parameter: the suit to search, or "." for all suits. sub o { j(map r,$h=~/(.(?=@_))/g) # The list of ranks, in increasing order, # with ace included at both ends... =~ # ...is matched against... /.*(..)(??{j map$1+$_.'.*',1..4})/ # ...a pattern requiring 5 consecutive # numbers. ?$1:() # A note about this regexp. The string we're matching is a bunch of numbers # in the range 10..23 crammed together like "121314151619" so you might # worry about a misaligned match starting on the second digit of one of the # original numbers. But since that would make every pair of digits in the # match end with a 1 or a 2, there's no way 5 of them will be consecutive. # There are no false matches. # Another note: if we have a royal flush and also have a 9 in the same # suit, we need to return the T rank, not the 9, which is why the regexp # starts with a .* } # Read a line into $_ for immediate matching with /.../ and also save it into # $h because $_ will be clobbered later and we'll need the original string # afterwards. $h = $_ = <>; if(j(/(\S)\b/g) =~ /(.)\1{4}/) { # flush detector: sorted list of all suits # contains 5 consecutive identical chars # $f=$1 comes first, so $f will be true later if there's a flush. # Then o() is called with the flush suit as arg to detect straight flush. # If there's no straight flush, o() returns the empty list and for loop # runs 0 times, so $w is not set. If there is a straight flush, the return # value of o() is compared to 19 to detect royal flush. $w = ($_==19 ? "royal" : "straight") for o($f=$1); } $_ = j(/\b(\S)/g) # Get the sorted+joined list of ranks... =~ s/(.)\1*/length $&/rge; # ... and turn it into a list of sizes of # groups of the same rank. The /r flag # requires perl 5.14 or newer. print $w ? "$w flush" : /4/ ? "four of a kind" : /3.*2|[23].*3/ ? "full house" : $f ? "flush" : (o".") ? "straight" : /3/ ? "three of a kind" : /2.*2/ ? "two pair" : /2/ ? "one pair" : "high card" ``` [Answer] ## JavaScript 600 usage with nodeJS: `node code.js "7H 3S 7S 7D AC QH 7C"` ``` function a(o){s="";for(k in o)s+=o[k];return s} b=process.argv[2] c={S:0,H:0,D:0,C:0} v={A:0,K:0,Q:0,J:0,T:0,"9":0,"8":0,"7":0,"6":0,"5":0,"4":0,"3":0,"2":0} d=b.split(" ") for(i=d.length;i--;){e=d[i];c[e[1]]++;v[e[0]]++} c=a(c);v=a(v) f=g=h=j=k=l=m=false if((st=c.indexOf(5))!=-1)g=!g if(v.match(/[1-9]{5}/))h=!h if(st==0)f=!f if(v.indexOf(4)!=-1)j=!j if(v.indexOf(3)!=-1)k=!k if(n=v.match(/2/g))if(n)if(n.length>=2)m=!m;else l=!l p=" of a kind" q="Flush" r="Straight" console.log(f&&g?"Royal "+q:h&&g?r+" "+q:j?"Four"+p:k&&(l||m)?"Full House":g?q:h?r:k?"Three"+p:m?"Two pairs":l?"Pair":"High card") ``` ]
[Question] [ Any positive integer can be obtained by starting with **1** and applying a sequence of operations, each of which is either **"multiply by 3"** or **"divide by 2, discarding any remainder"**. **Examples** (writing f for \*3 and g for /2): `4 = 1 *3 *3 /2 = 1 ffg` `6 = 1 ffggf = 1 fffgg` `21 = 1 fffgfgfgggf` Write a program with the following behavior: **Input**: any positive integer, via stdin or hard-coded. (If hard-coded, the input numeral will be excluded from the program length.) **Output**: a string of f's and g's such that `<input> = 1 <string>` (as in the examples). Such a string in reverse order is also acceptable. NB: The output contains only f's and g's, or is empty. The winner is the entry with the fewest bytes of *program-plus-output* when 41 is the input. [Answer] ### GolfScript, score 64 (43-2+23) ``` 0{)1.$2base:s{{3*}{2/}if}/41=!}do;s{103^}%+ ``` (41 is hardcoded, therefore -2 characters for the score). The output is ``` fffgffggffggffgggffgggg ``` which is 23 characters (without newline). By construction the code guarantees that it always returns (one of) the shortest representations. [Answer] We're getting dirty, friends! **JAVA ~~210 207~~ 199 characters** ``` public class C{public static void main(String[] a){int i=41;String s="";while(i>1){if(i%3<1){s+="f";i/=3;}else if(i%3<2){s+="g";i+=i+1;}else{s+="g";i+=i+(Math.random()+0.5);}}System.out.println(s);}} ``` non-golfed: ``` public class C { public static void main(String[] a) { int i = 41; String s = ""; while (i > 1) { if (i % 3 == 0) { s += "f"; i /= 3; } else { if (i % 3 == 1) { s += "g"; i += i + 1; } else { s += "g"; i += i + (Math.random() + 0.5); } } } System.out.println(s); } } ``` output : depending on the faith of the old gods, the shortest i had was 30. Note that the output must be read from the right. **234** ``` 1 ggfgfgfgfggfggfgffgfggggfgffgfggfgfggggfgffgfggfgfggfgfggfgfgggggfffgfggfgfggfgfgggffgggggfffgfggggfgffgfggfgfggfgfggfgfggfgfggfgfggfgfggggfgffgfggfgfggfgfggfgfggfgfggfgfggggggggggggfgfgfggggfgfgfggfffgfgfggffgfgfggfgfggggffgfgfffff ``` **108** ``` 1 gggffgfgfggggggfggggfgffggggfgfgfgfgfgffgggfgggggfggfffggfgfffffgggffggfgfgggffggfgfgggffggggggfgfgffgfgfff ``` *edit* **45** ``` 1 ggfgfgfgfgggfggfffgfggfgfgggggggffgffgfgfff ``` **points : ~~318~~ 199+30 = 229** **edit1** (2\*i+1)%3==0 --> (2\*i) % 3 ==1 Nota Bene if you use Java 6 and not Java 7 while golfing, you can use ``` public class NoMain { static { //some code System.exit(1); } } ``` 39 characters structure instead of a standard structure which is 53 characters long. [Answer] ## Python, score 124 (90-2+36) ``` x=41;m=f=g=0 while(3**f!=x)*(m!=x): f+=1;m=3**f;g=0 while m>x:m/=2;g+=1 print'f'*f+'g'*g ``` 90 chars of code (newlines as 1 each) - 2 for hard-coded input numeral + 36 chars of output Output: ``` ffffffffffffffffgggggggggggggggggggg ``` [Answer] ## Python, score 121 (87 - 2 + 36) ``` t=bin(41) l,n,f=len(t),1,0 while bin(n)[:l]!=t:f+=1;n*=3 print(len(bin(n))-l)*'g'+f*'f' ``` [Answer] ## Perl, score 89 (63 - 2 + 28) ``` $_=41;$_=${$g=$_%3||$_==21?g:f}?$_*2+$_%3%2:$_/3while$_>print$g ``` ***Conjecture:*** If the naive approach described in my original solution below ever reaches a cycle, that cycle will be *[21, 7, 15, 5, 10, 21, ...]*. As there are no counter-examples for *1 ≤ n ≤ 106*, this seems likely to be true. To prove this, it would suffice to show that this is the only cycle which *can* exist, which I may or may not do at a later point in time. The above solution avoids the cycle immediately, instead of guessing (wrongly), and avoiding it the second time through. Output (28 bytes): ``` ggfgfgfgfggfggfgfgfggfgfgfff ``` --- ## Perl, score 100 (69 - 2 + 33) ``` $_=41;1while$_>print$s{$_=$$g?$_*2+$_%3%2:$_/3}=$g=$_%3||$s{$_/3}?g:f ``` Using a guess-and-check approach. The string is constructed using inverse operations (converting the value to *1*, instead of the other way around), and the string becomes mirrored accordingly, which is allowed by the problem specification. Whenever a non-multiple of three is encountered, it will be multiplied by two, adding one if the result would then be a multiple of three. When a multiple of three is encountered, it will be divided by three... unless this value has previously been encountered, indicating a cycle, hence guess-and-check. Output (33 bytes): ``` ggfgfgfgfggfggfgffgfgggfggfgfgfff ``` [Answer] # J, score 103 (82-2+23) \*Note: I named my verbs `f` and `g`, not to be confused with output strings `f` and `g`. Hard-coded: ``` f=:3 :'s=.1 for_a.y do.s=.((<.&-:)`(*&3)@.a)s end.' 'gf'{~#:(>:^:(41&~:@f@#:)^:_)1 ``` General functions: ``` f=:3 :'s=.1 for_a.y do.s=.((<.&-:)`(*&3)@.a)s end.' g=:3 :'''gf''{~#:(>:^:(y&~:@f@#:)^:_)1' ``` Did away with operating on blocks of binary numbers, which was the most important change as far as compacting `g`. Renamed variables and removed some whitespace for the heck of it, but everything's still functionally the same. (Usage: `g 41`) ### J, score 197 (174+23) ``` f =: 3 : 0 acc =. 1 for_a. y do. acc =. ((*&3)`(<.&-:)@.a) acc end. ) g =: 3 : 0 f2 =: f"1 f. l =. 0$0 i =. 1 while. 0=$(l=.(#~(y&=@:f2))#:i.2^i) do. i=.>:i end. 'fg'{~{.l ) ``` Output: `ffffffffggggggggfgffggg` `f` converts a list of booleans into number, using 0s as `*3` and 1s as `/2` (and `floor`). `#:i.2^i` creates a rank 2 array containing all the rank 1 boolean arrays of length `i`. ]
[Question] [ I have a weakness for 3d nets which when cut out and folded allow you to make 3d shapes out of paper or card. The task is simple, written the shortest program you can that draws nets for the 13 Archimedean solids. The output should be an image file in any sensible format (png, jpg). All thirteen shapes are described at <http://en.wikipedia.org/wiki/Archimedean_solid> and in the following table taken from there. ![enter image description here](https://i.stack.imgur.com/KkixZ.png) **Input:** An integer from 1 to 13. Assume the shapes are numbered exactly as in the table above so that the "truncated tetrahedron" is number 1 and the "snub dodecahedron" is number 13. **Output:** An image file containing the net for that shape. Just the outline including the internal lines is OK. There is no need to fill it in with colors You can use any programming language you like as well as any library that was not made especially for this competition. Both should be available freely however (in both senses) online. I will accept the answer with the smallest number of characters in exactly one week's time. Answers will be accepted whenever they come. **(No) Winner yet.** Sadly no valid entrants. Maybe it is too hard? [Answer] # Java, 1552 ``` import java.awt.*;import java.awt.image.*;import java.io.*;import javax.imageio.*;class A{public static void main(String[]x)throws Exception{String[]a={"33623368356:356;66","33413341334535463547354735473444","33823382338:3586338>358>358>358?88","66456:466:466845684668466766","334144453546354635474746464646464647354634463446344744","88456:466:466:4668458<468<468<468:456846684668466788","33343535353231333535313133353447353434353534313133353447353545343535313133353447353545343444","33513351335233593554335433593554335935543359355433593559355835593559355935593455","33:233:233:433:B35:833:833:B35:833:B35:833:B35:833:B35:B35:833:B35:B35:B35:B35:C::","66566:576:57696869576969586969586:586969576969586857685868586766","334155453546354635463547594658465846584658473546354634463546344635463446354634463547584657465746574657473546344634463446344755","::456:466:466:466:466845:@46:@46:@46:@46:>4568466:4668466:4668466:4668466:4668466845:>46:>46:>46:>46:<45684668466846684667::","333531333434343132333434353531313335343434323232323334343435353231333133343556343434313233323335345935353532313331313132333233353535343557343133343556343434355934353535593432333234355935323335345935323335345935323335345935343459313334353455"};BufferedImage m=new BufferedImage(1300,1300,1);Graphics2D g=m.createGraphics();g.translate(500,500);String s=a[Integer.valueOf(x[0])-1];int f=1,i=0,n,t;while(i<s.length()){n=s.charAt(i++)-48;t=s.charAt(i++);while(t-->48){g.drawLine(0,0,20,0);g.translate(20,0);g.rotate(f*Math.PI*2/n);}f=-f;}ImageIO.write(m,"png",new File("o.png"));}} ``` Ungolfed: ``` import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class A { static int f = 1; static Graphics2D g; static void fixtrans() { double[] m = new double[6]; g.getTransform().getMatrix(m); for (int i = 0; i < 6; ++i) { if (Math.abs(m[i] - Math.round(m[i])) < 1e-5) { m[i] = Math.round(m[i]); } } g.setTransform(new AffineTransform(m)); } static void d(String s) { for (int i = 0; i < s.length();) { int n = s.charAt(i++) - '0'; int t = s.charAt(i++) - '0'; for (int j = 0; j < t; ++j) { g.drawLine(0, 0, 20, 0); g.translate(20, 0); g.rotate(f * Math.PI * 2 / n); fixtrans(); // optional, straightens some lines } f = -f; } } public static void main(String[] args) throws Exception { String[] a = { "33623368356:356;66", "33413341334535463547354735473444", "33823382338:3586338>358>358>358?88", "66456:466:466845684668466766", "334144453546354635474746464646464647354634463446344744", "88456:466:466:4668458<468<468<468:456846684668466788", "33343535353231333535313133353447353434353534313133353447353545343535313133353447353545343444", "33513351335233593554335433593554335935543359355433593559355835593559355935593455", "33:233:233:433:B35:833:833:B35:833:B35:833:B35:833:B35:B35:833:B35:B35:B35:B35:C::", "66566:576:57696869576969586969586:586969576969586857685868586766", "334155453546354635463547594658465846584658473546354634463546344635463446354634463547584657465746574657473546344634463446344755", "::456:466:466:466:466845:@46:@46:@46:@46:>4568466:4668466:4668466:4668466:4668466845:>46:>46:>46:>46:<45684668466846684667::", // bad "333531333434343132333434353531313335343434323232323334343435353231333133343556343434313233323335345935353532313331313132333233353535343557343133343556343434355934353531333459343434355935323335345935323335345935323335345935323335345935353455" "333531333434343132333434353531313335343434323232323334343435353231333133343556343434313233323335345935353532313331313132333233353535343557343133343556343434355934353535593432333234355935323335345935323335345935323335345935343459313334353455"}; BufferedImage img = new BufferedImage(1300, 1300, BufferedImage.TYPE_INT_RGB); g = img.createGraphics(); g.translate(500, 500); d(a[Integer.parseInt(args[0]) - 1]); String f = args[0] + ".png"; ImageIO.write(img, "png", new File(f)); } } ``` Results (trimmed, negated, joined and scaled): ![results](https://i.stack.imgur.com/GvjQc.png) The shapes are quite unusual :) but correct as far as I can tell (let me know if you find any errors). They were generated (in a separate program) by constructing the face graph and cutting cycles in a DFS. I'm sure this can be golfed quite a lot more using e.g. python and turtle. **Edit:** oops, the last case was self-intersecting a bit. I fixed the code (by hand), here's the updated image: ![13 corrected](https://i.stack.imgur.com/Su6gU.png) [Answer] ## Mathematica Out of competition, not a free language ``` f[n_] := PolyhedronData[Sort[PolyhedronData["Archimedean", {"FaceCount", "StandardName"}]][[n, 2]], "NetImage"] ``` Usage: ``` f /@ Range@13 ``` ![Mathematica graphics](https://i.stack.imgur.com/7kakN.png) ]
[Question] [ Often a task requires real arrays. Take for instance the task to implement Befunge or ><>. I tried to use the `Array` module for this, but it's really cumbersome, as it feels like I'm coding much too verbose. Can anybody help me how to solve such code-golf tasks less verbose and more functional? [Answer] The glib answer is: Don't use arrays. The not-so-glib answer is: Try to rethink your problem so that it doesn't need arrays. Often, a problem with some thought can be done without any array like structure at all. For example, here's my answer to Euler 28: ``` -- | What is the sum of both diagonals in a 1001 by 1001 spiral? euler28 = spiralDiagonalSum 1001 spiralDiagonalSum n | n < 0 || even n = error "spiralDiagonalSum needs a positive, odd number" | otherwise = sum $ scanl (+) 1 $ concatMap (replicate 4) [2,4..n] ``` What gets expressed in the code here is the pattern of the sequence of numbers as they grow around the rectangular spiral. There was no need to actually represent the matrix of numbers itself. The key to thinking beyond arrays is to think about what the problem at hand actually means, not how you might represent it as bytes in RAM. This just comes with practice (perhaps a reason I code-golf so much!) Another example is how I solved the [finding maximal paths](https://codegolf.stackexchange.com/questions/1720/finding-maximum-paths/1760#1760) code-golf. There, the method of passing the partial solutions as a wave through the matrix, row by row, is expressed directly by the fold operation. Remember: On most CPUs, you can't deal with the array as a whole at once: The program is going to have to operate through it over time. It may not need the whole array at once at any time. Of course, some problems are stated in such a way that they are inherently array based. Languages like ><>, Befunge, or Brainfuck have arrays at their heart. However, even there, arrays can often be dispensed with. For example, see my solution to [interpreting Brainfuck](https://codegolf.stackexchange.com/questions/84/interpret-brainfuck/944#944), the real core of its semantics is a [zipper](http://en.wikibooks.org/wiki/Haskell/Zippers). To start thinking this way, focus on the patterns of access, and the structure closer to the meaning of problem. Often this needn't be forced into a mutable array. When all else fails, and you do need to use an array - @Joey's tips are a good start. [Answer] First of all, I recommend looking at [Data.Vector](http://hackage.haskell.org/package/vector), a nicer alternative to [Data.Array](http://hackage.haskell.org/packages/archive/array/latest/doc/html/Data-Array.html) in some cases. `Array` and `Vector` are ideal for some memoization cases, as demonstrated in [my answer to "Finding maximum paths"](https://codegolf.stackexchange.com/questions/1720/finding-maximum-paths/1721#1721). However, some problems simply aren't easy to express in a functional style. For example, [Problem 28](http://projecteuler.net/index.php?section=problems&id=28) in [Project Euler](http://projecteuler.net/) calls for summing the numbers on the diagonals of a spiral. Sure, it should be pretty easy to find a formula for these numbers, but constructing the spiral is more challenging. [Data.Array.ST](http://hackage.haskell.org/packages/archive/array/latest/doc/html/Data-Array-ST.html) provides a mutable array type. However, the type situation is a mess: it uses a [class MArray](http://hackage.haskell.org/packages/archive/array/latest/doc/html/Data-Array-MArray.html#t:MArray) to overload every single one of its methods except for [runSTArray](http://hackage.haskell.org/packages/archive/array/latest/doc/html/Data-Array-ST.html#v:runSTArray). So, unless you plan on returning an immutable array from a mutable array action, you'll have to add one or more type signatures: ``` import Control.Monad.ST import Data.Array.ST foo :: Int -> [Int] foo n = runST $ do a <- newArray (1,n) 123 :: ST s (STArray s Int Int) -- this type signature is required sequence [readArray a i | i <- [1..n]] main = print $ foo 5 ``` Nevertheless, [my solution to Euler 28](https://ideone.com/OYSxW) turned out pretty nicely, and did not require that type signature because I used `runSTArray`. ## Using Data.Map as a "mutable array" If you're looking to implement a mutable array algorithm, another option is to use [Data.Map](http://hackage.haskell.org/packages/archive/containers/latest/doc/html/Data-Map.html) . When you use an array, you kind of wish you had a function like this, which changes a single element of an array: ``` writeArray :: Ix i => i -> e -> Array i e -> Array i e ``` Unfortunately, this would require copying the entire array, unless the implementation used a copy-on-write strategy to avoid it when possible. The good news is, `Data.Map` has a function like this, [insert](http://hackage.haskell.org/packages/archive/containers/latest/doc/html/Data-Map.html#v:insert): ``` insert :: Ord k => k -> a -> Map k a -> Map k a ``` Because `Map` is implemented internally as a balanced binary tree, `insert` only takes O(log n) time and space, and preserves the original copy. Hence, `Map` not only provides a somewhat-efficient "mutable array" that is compatible with the functional programming model, but it even lets you "go back in time" if you so please. Here is a solution to Euler 28 using Data.Map : ``` {-# LANGUAGE BangPatterns #-} import Data.Map hiding (map) import Data.List (intercalate, foldl') data Spiral = Spiral Int (Map (Int,Int) Int) build :: Int -> [(Int,Int)] -> Map (Int,Int) Int build size = snd . foldl' move ((start,start,1), empty) where start = (size-1) `div` 2 move ((!x,!y,!n), !m) (dx,dy) = ((x+dx,y+dy,n+1), insert (x,y) n m) spiral :: Int -> Spiral spiral size | size < 1 = error "spiral: size < 1" | otherwise = Spiral size (build size moves) where right = (1,0) down = (0,1) left = (-1,0) up = (0,-1) over n = replicate n up ++ replicate (n+1) right under n = replicate n down ++ replicate (n+1) left moves = concat $ take size $ zipWith ($) (cycle [over, under]) [0..] spiralSize :: Spiral -> Int spiralSize (Spiral s m) = s printSpiral :: Spiral -> IO () printSpiral (Spiral s m) = do let items = [[m ! (i,j) | j <- [0..s-1]] | i <- [0..s-1]] mapM_ (putStrLn . intercalate "\t" . map show) items sumDiagonals :: Spiral -> Int sumDiagonals (Spiral s m) = let total = sum [m ! (i,i) + m ! (s-i-1, i) | i <- [0..s-1]] in total-1 -- subtract 1 to undo counting the middle twice main = print $ sumDiagonals $ spiral 1001 ``` The bang patterns prevent a stack overflow caused by the accumulator items (cursor, number, and Map) not being used until the very end. For most code golfs, input cases should not be big enough to need this provision. ]
[Question] [ ## How to play the duck game **This is a 2-player game.** First, we start with a line of blue rubber ducks (represented here as circles): > > > ``` > 🔵🔵🔵🔵🔵🔵🔵 > > ``` > > Now, in each turn, the current player can turn either one blue duck or two adjacent blue ducks red. So, a valid move would be indexes 2 and 3 (0-indexed): > > > ``` > 🔵🔵🔴🔴🔵🔵🔵 > > ``` > > Then, the other player could choose index 0: > > > ``` > 🔴🔵🔴🔴🔵🔵🔵 > > ``` > > And so on. The last player to move loses. ### Example game Starting with 7 blue ducks: > > Initial board > > > > ``` > 🔵🔵🔵🔵🔵🔵🔵 > > ``` > > > > Player 1 chooses **3,4** > > > > ``` > 🔵🔵🔵🔴🔴🔵🔵 > > ``` > > > > Player 2 chooses **0** > > > > ``` > 🔴🔵🔵🔴🔴🔵🔵 > > ``` > > > > Player 1 chooses **6** > > > > ``` > 🔴🔵🔵🔴🔴🔵🔴 > > ``` > > > > Player 2 chooses **1,2** > > > > ``` > 🔴🔴🔴🔴🔴🔵🔴 > > ``` > > > > Player 1 chooses **5** > > > > ``` > 🔴🔴🔴🔴🔴🔴🔴 > > ``` > > Player 1 was the last one to move, so Player 2 wins. --- ## Challenge The duck game can be solved. Your challenge today is to accept a board state and output one of the moves which will guarantee a win for the current player. For example, with the board state `🔵🔵🔵🔴🔴🔵🔵`, choosing either index 0 or index 2 will guarantee a win for the current player (feel free to try it). ## Input/Output * You should take in a list/array/etc. containing two distinct values representing blue and red ducks. For example, `🔵🔵🔵🔴🔴🔵🔵` could be `[1, 1, 1, 0, 0, 1, 1]`. * You should output one or two integers representing the ducks which should be taken in the next move. For example, the input `🔵🔵🔵🔴🔴🔵🔵` could have output `[0]` or `[2]`. ## Clarifications * The input board state will always have at least one move which guarantees a win for the current player. * You may output **any** of the moves which guarantee a win. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest solution in bytes wins. ## Test cases These test cases use 1 for blue ducks and 0 for red ducks. The output side contains all possible outputs. ``` Input -> Output [1, 1, 1, 0, 0, 1, 1] -> [0], [2] [1, 1, 1, 1, 1, 1, 1] -> [1], [3], [5] [1, 1, 0, 1, 1, 1, 1] -> [0,1], [3,4], [5,6] [1, 0, 1, 1, 0, 1, 1] -> [0] [1, 1, 1] -> [0,1], [1,2] [1, 0, 0, 1, 1, 0, 0, 1] -> [3], [4] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~71~~ 52 bytes ``` F⊕⍘⮌S²⊞υ⎇ιΦ⁺Eθ⟦λ⟧Eθ⟦λ⊕λ⟧∧⁼ΣX²κ&ΣX²κ鬧υ⁻ιΣX²κ⟦⟦⟧⟧I⊟υ ``` [Try it online!](https://tio.run/##bY9PawIxEMXv/RTB0wRScPXoaZVaPFgW7U08hN2pGTabaP4o/fRpUq210AdDwptM3m9aJV1rpU6p9p4OBubS4zY4MgfY4BmdR1iZYww3j3PBJrkUnz010SuIgo3z/cM6Boqz77M2n9Do6GEtj3ASrLEXdDARTJfxm/lOA3qY/u2W/qtDGbLzcopSe@gFm1O4kMfadECC9eXRwkYTSviaTA662lnsB4oKYEYOsJA@wJJ0@fORatfvf2l2OWZlWocDmoAd9Hz/yPJmA9yTlmS6WusyNqpG/B8cJdg2DnDfjPhVs5Sqalxlpeez/gI "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of `0`s and `1`s representing red and blue ducks respectively and outputs a double-spaced list of winning `0`-indexed duck moves. Explanation: Uses dynamic programming to find winning moves. ``` F⊕⍘⮌S² ``` Loop over numeric positions indices from `0` to the input as a position index, some of which will be unreachable from the input position. ``` ⊞υ⎇ιΦ⁺Eθ⟦λ⟧Eθ⟦λ⊕λ⟧∧⁼ΣX²κ&ΣX²κ鬧υ⁻ιΣX²κ⟦⟦⟧⟧ ``` Find all legal moves that result in forced losses from this position, but special case a list of an empty list for position index `0` which should really be a loss for the player to move (this would save `6` bytes). ``` I⊟υ ``` Output all winning moves from the input position. [Answer] # Python3, 333 bytes: ``` def M(l): for i,a in enumerate(l): if a: yield[i] if i<len(l)-1and l[i+1]:yield[i,i+1] def K(l): for m in M(l): L=l[:] for i in m:L[i]=0 yield L,m def P(l,p=1): F=1 for L,_ in K(l): if any(L): if p in(u:=[*P(L,not p)]):yield from u;F=0 if F:yield not p f=lambda l:[m for L,m in K(l)if any(L)and not any(P(L))] ``` [Try it online!](https://tio.run/##fY9Ba8QgEIXv@RVz1K4Lhl6Krddc1sLeJRRLlApqJCSH/PrUSdLu0t0tDMSZ9@Z9kzyPX316fsnDsnTWwTsJVFTg@gE8M@AT2DRFO5jRbgp4Bwa/MHsbOu1bfJehfws2Fc@xNqmDoP2hbsXuYdhUmH@65EdM33mgZNACo1YyKlGoEi55tZNAsbhGnElgWda41sh6y1LsA3dOVzemmai1wS4XlUxC6qczUSz1I2Ta0u08cEMfYXptkFW8zT5eXZWTwcTPzkAQOu6s@MP65eAvox@7QqC0XfLg00gc0TWDrfha@G4prW71S93R@X86v0I8yr@zw/9cdrNWBss3) [Answer] # [JavaScript (V8)](https://v8.dev/), 78 bytes -5 bytes from Arnauld ``` f=x=>x.some(r=(v,i,[...e])=>v?r=f(e,e[i]=0)?f(e,e[i-1]=0)?0:[i-1,i]:[i]:0)?r:r ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P822wtauQq84PzdVo8hWo0wnUydaT08vNVbT1q7Mvsg2TSNVJzU6M9bWQNMeytY1BPMMrEBMncxYIB1rBRQosir6X1CUmVeikaYRbaijAEEGYARix2pqcmHKIxAWeQN88gZIVuAyH4seAzSXAZX8BwA "JavaScript (V8) – Try It Online") # [JavaScript (V8)](https://v8.dev/), 81 bytes ``` f=(x,e)=>x.some((v,i)=>r=v?f(e=[...x],e[i]=0)?f(e,e[i-1]=0)?0:[i-1,i]:[i]:0)?r:!e ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P81Wo0InVdPWrkKvOD83VUOjTCcTyCuyLbNP00i1jdbT06uI1UmNzoy1NdAECYHYuoZgnoEViKmTGQukY62AAkVWiqn/C4oy80o00jSiDXUUIMgAjEDsWE1NLkx5BMIib4BP3gDJClzmY9FjgOYyFCUQMQNs2oBi/wE "JavaScript (V8) – Try It Online") returns `false` if impossible, returns `true` if win immediately because of endgame. [Answer] # [Haskell](https://www.haskell.org), 178 bytes ``` z f=zipWith f[0..] n=Nothing f x|and x=Just[] f x|h:_<-filter(\j->all(\k->k<length x&&not(x!!k))j&&n==f((\k->z(\i y->y||elem i k)x)j))$concat$z(\i _->[[i],[i,i+1]])x=Just h f x=n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVKxTsMwEBVrvuIqVZUtnCotBaGqycYAAyuDa7VRiRs3jlM1Lkqr_AlLF8TO35SvwXaAliCdfGf7vbt3Z7--p3GZJVIeDm9bzf3b48ceeLgX6yehU-A06PeZp8LHQqdCLT0OVR2rZ6jCh22pKXMH6Xg28bmQOtmg6cqPYinRNPOjbCITtTRpql5PFRpVnU6G8cpswpAjB9mjqYCdH-3qOpFJDgIyXOEVxt1FoRax7jrAzI8oFYxQQcTlgDHclIfUlg9Vo_zz4kUnpV7EZVLCeAwU0XulGQHqPMPMO92HQD0ARAcEGguc2dgwDCWwxKFhkb-4kzU46-iVXa5b4OA_OCANnIwcgdycU4IzKec6WhJcQ9-JBmTYyhC0-nFoJ2_kJuDlsVCm-_VGKA0UOKA8XgMyzwN90MWd2uYYBIa5fY452Es36qKEGpAgJsAw8eF3lMxrxv_zgb4A) ]
[Question] [ [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) has once tried to come up with [a parsing problem](https://codegolf.stackexchange.com/q/233453/78410) unsuitable for regex, but it failed due to [Anders Kaseorg's Perl regex answer](https://codegolf.stackexchange.com/a/233465/78410). This is the second attempt. Now that we know that Perl regex is far more powerful than we've imagined, this challenge aims to be un-golfy for it instead. ## Introduction A **lambda term** is recursively defined as follows: * A *variable* is a lambda term. * A *lambda abstraction* of a lambda term is a lambda term. * A *function application* of two lambda terms is a lambda term. This is concisely written as follows (where `e` is a term and `x` is any valid variable name): ``` e = x | λx. e | e e ``` A variable is often a string (as in Wheat Wizard's challenge), but it suffers from name shadowing problem. To avoid it and for an easier encoding, we use [de Bruijn indices](https://en.wikipedia.org/wiki/De_Bruijn_index) instead. In this notation, a variable is replaced with a positive integer, which is equal to "the number of binders that are in scope between that occurrence and its corresponding binder". The grammar is simplified to the following: ``` e = i | λ e | e e ``` Some examples in this notation: * `λx. x` is written as `λ 1`, as the inner `x` binds to the first (and only) `λ` in scope. * `λx. λy. x` is written as `λ λ 2`, as the inner `x` binds to the second `λ`, counting from the closest one. * `λx. λy. x (λz. z y)` is written as `λ λ 2 (λ 1 2)`. ## Ternary lambda calculus This is an encoding of a lambda term similar to [Binary lambda calculus](https://tromp.github.io/cl/Binary_lambda_calculus.html), but in ternary (a string of digits 0, 1, and 2). A lambda term written using de Bruijn indexes is converted to Ternary lambda calculus as follows: * A variable of index `i` is converted to binary (using 0 and 1), and then a `2` is added at the end. Since `i` is positive, this always starts with a 1. * A lambda abstraction `λ e` is recursively converted to `0<e>`, where `<e>` denotes the Ternary conversion of `e`. * A function application `e1 e2` is recursively converted to `2<e1><e2>`. Examples: * `λ 1` is encoded to `012`. (`1` encodes to `12`, and a single lambda abstraction adds a `0`) * `λ λ 2` is encoded to `00102`. * `λ λ 2 (λ 1 2)` is encoded to `0021020212102`. The original BLC requires that the lambda term is **closed**, i.e. all variables are bound to some lambda abstraction. This means the variable index `i` is limited by the current "lambda depth"; in particular, no variables may appear at the top level at all. Using the lambda depth (a non-negative integer) as the context, the grammar to match becomes the following: ``` TermAtDepth(d) = bin(i) "2" where 1 ≤ i ≤ d | "0" TermAtDepth(d+1) | "2" TermAtDepth(d) TermAtDepth(d) e = TermAtDepth(0) ``` ## Code ``` tlc :: Int -> Parser () tlc depth = do choice [ do char '1' idx <- many $ charBy (`elem` "01") guard $ foldl (\x y->x*2+y) 1 [fromEnum x-48|x<-idx] <= depth char '2' return () , do char '0' tlc (depth + 1) , do char '2' tlc depth tlc depth ] return () ``` [Try it online!](https://tio.run/##pVTbattAEH3XVwxOIavaDpboQwm2wUkbCDQQaN8c46ytlS2yurBaJzJNv92dvclrue1LQ5B3Zs7MnrntltYvjPPDz@EFfKPFZkc3DO44a7IVZ/dFLWmxZjVcDH8FWV6VQsKjYHyXMNhmSVZsAgACdFXjb@gQt2UhRcmvZlXFszWV2SvTMJ6lchbjcQAzLpkotAnI1VX4J/eHsqCJdnwts0S7IT2R@NgvVFIFNAACZDwNz@y3Wyq0NatnvNpSDQgK9ib3FYNHKmomgMIE9VYg36XA5GA4hbk9D4CGC3SjmNQerq@Pfgj6C9yCiYVWIdT6lgp/gyCz1YW7XbGWpXAR37ZMqIKlOa0gRZsfQLm3ND8YDNGfFh6GUHnRvS50b6h2gkFzGpPAE9ReOrVNpwkXqmpguwjpkVUUHs/xKUV9hE7QpLRqNAiWRwMQrMYg4yHGsrgTRKwRsUHEoHxau2ByJwoHS3Uog7aQ0KuFHqluFRx1mE4nGOC/6HfZ2wFILcRj7tPyt6FDjuWV3J93aKmbozoC4KUQwfh92kpxd1pO82hrDf2@AlvBJ0bMauEsw2QKVnC9RqVjmfs09VQZjTJhCViRWJsdHqsMgjWu5o1eJ6K2VNG6KUseqoO9Rm@vxVWCJWqWmb@sG9UPxwRQBELhGlZuEgHmQFZqIeHdi0Bh4fBYyBa6MKQUJceoS8SujOVEmskEa2arh27Hx8A6GoVDKFcp6CtDm46hLiwzrDb6zl1tF54/dQDlmpY8wRnAPodmOA6Sr5XrfSE9HxIGSp@wSm61n51aE6mtizfLOrPL6LJVZEmjZjqnxR5nx2X7zDjLn6E3inphC9XvsnqOkBwH8tTAfjhtPsb9fQgRzFNR5l@LXQ7N8NPn92Y8xNALGE8MvQ6D@PJst91Fg3O@oyNa5UtMwn2I/uETn/qckuhqzJC0TA7pjvMHKtdbqEyl8UnHuGz9gvmbdW8NbiiNeU56vQEs8R2dwA@xOxqWqLijvGZBTrMCBc0Yd@RhCaTCoZFwBcd7iaI4Ck2Cc9WJuBeYVHujUTTypRhF/MSnWvcXjbr6GJHqgx7m69nbgzKcCL6MbMy/0SwOvwE "Haskell – Try It Online") ## Challenge Given a ternary string (a string that entirely consists of digits 0, 1, and 2), determine if it is a valid Ternary lambda calculus code. You may take the input as a string or a list of digit values. The input may be empty, and your code should give a false output on it. For output, you can choose to * output truthy/falsy using your language's convention (swapping is allowed), or * 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. The shortest code in bytes wins. ## Test cases ``` -- Truthy 012 00102 0021020212102 000000000010102 00002210022112122112102 -- Falsy (empty) 2112 2112112 012012012 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes ``` 4ŀ1Ẹ?‘} 1;œṡ2Ṫ0ḢḄ<ɗ? ñ⁹ñ Ḣ‘$ŀ ç1 ``` [Try it online!](https://tio.run/##y0rNyan8/9/kaIPhw1077B81zKjlMrQ@OvnhzoVGD3euMni4Y9HDHS02J6fbcx3e@Khx5@GNXEAhoDKVow1ch5cb/g971LTmcDuX9aOGOQq6dgqPGuZaA7kPd2853A6Uifz/3wAIjIwMwYShkSGENDDiMjAEYgMwywAkACQg4nBgaADjY9PPBWKACRANNA2CAA "Jelly – Try It Online") A full program taking a list of integers and returning an empty list (falsy) for valid and a non-empty list (truthy) for invalid. ## Explanation ### Helper link 1 (handles 0…) ``` Ẹ? | If the list is non-empty: 4ŀ ‘} | - Call helper link 4 with the depth increased by 1 1 | - Else return 1 ``` ### Helper link 2 (handles 1…) ``` 1; | Prepend 1 œṡ2 | Split at 2s ḢḄ<ɗ? | If the first part of the list converted from binary is less than the depth: Ṫ | - Return the second part of the list 0 | - Else return 0 ``` ### Helper link 3 (handles 2…) ``` ñ⁹ñ | Call helper link 4 twice, preserving depth ``` ### Helper link 4 (handles next part) ``` Ḣ‘$ŀ | Call the helper link indicated by the first list member plus 1, preserving the same depth ``` ### Main link ``` ç1 | Call helper link 4 with 1 as the right argument (depth) ``` [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 86 bytes ``` q x=cx[do χ 1;k<-my$kB(<2);gu$x>lF(pl.db)1 k;χ 2,χ 0*>q(x+1),χ 2*>q x*>q x] x1$q 1 ``` *Takes input as a list of integers* hgl is a library I am making for golfing in Haskell. It has pretty decent parsing capabilities. It however does not yet have a function to convert from binary. Which is a bit of a problem for this answer. The code I came up with to do the task is `lF(pl.db)0`. This code follows same structure of the parsing code given in the question. That's because both parsing libraries are written by me and use the same theoretic underpinning. We use `cx` which is analygous to the `choice` in the question selecting between 3 options. ``` q x = cx [ do χ 1 k<-my$kB(<2) gu$x>lF(pl.db)1 k χ 2 , χ 0*>q(x+1) , χ 2*>q x*>q x ] ``` The last two don't use `do` notation since it would cost bytes, but they can be written with it. ``` q x = cx [ do χ 1 k<-my$kB(<2) gu$x>lF(pl.db)1 k χ 2 , do χ 0 q(x+1) , do χ 2 q x q x ] ``` As one might guess now `χ` parses a single integer. We have `gu` which is `guard`, `m` which is `fmap` and `kB` which is the `charBy` function. The remainder is `lF(pl.db)1` which converts from binary. In regular haskell this is ``` foldl((+).(*2))1 ``` [Answer] # JavaScript, 121 bytes ``` f=d=>(s=s.slice(1),s[0]<1?f(d+1):s[0]>1?f(d)&f(d):(s=s.replace(/[01]+/,x=>parseInt(x,2)>d||''))[0]>1),a=>f(0,s=0+a)&!s[1] ``` [Try it online!](https://tio.run/##PYzBboMwDIbve4v20MYipU6O1ZKd9wyA1AgCYktDhNHUSn13moRtlvXZv/3bX@bHUDuPYTlRGDs73yb/bR/roNjaq05pRopKcmNrmQBOFTbv4qNnXSHgkpTOCg4Jl2yebXAm2s8ViqY487vSwcxkP/3C7lyC7p7P4xEgHwM3SvcMOSksDBx2VIlmhbd28jQ5W7ppYHsUsvaIAnORsUbIX/kXAv8HMu4SomdjWtQ@tRtzE79uWXsh9yUFNy7X2l/LmwlsAFhf "JavaScript (SpiderMonkey) – Try It Online") The first function called, which is the unnamed arrow function at the end of the code, calls `f` while using an extra argument to initialise `s` to the provided string with `0` prepended. `f` does the main parsing, removing characters from `s` as it goes, returning false on failure. It begins by unconditionally removing one character, which is the reason for the prepended `0`. The first two cases are simple: `s[0]<1` (begins with `0`) leads to `f(d+1)`, a recursive call with depth increased, and `s[0]>1` (begins with `2`) leads to `f(d)&f(d)`, parsing two subterms. The final case covers `s` beginning with `1`, and also `s` being empty (in which case `s[0]` is `undefined`, making both comparisons false). It uses the regexp `/^[01]+/` to pick out the binary number. The replacer function (`x=>parseInt(x,2)>d||''`) checks whether the number is too high, returning `true` if it is and an empty string otherwise. The function then checks whether the remaining string begins with a digit greater than 1; if the number was too high, it begins with `t` and that is false. In the case of `s` being empty, no replacement occurs, and `""[0]>1` is also false. Finally, back in the unnamed arrow function, `!s[1]` checks whether the whole string was parsed, in which case all but one character will have been removed from it. [Answer] # [Haskell](https://www.haskell.org/), 106 bytes ``` (y%q)x|2:z<-q=[z|y<x]|w:z<-q=(2*y+w)%z$x|1>0=[] x#(z:y)=[(1+x)#y,1%y$x,x#y>>=(x#)]!!z x#_=[] ([[]]==).(1#) ``` [Try it online!](https://tio.run/##bYvRCoMwDEXf9xVKFdrZDdNHsf5IKcOH4WQqug1MS/@9qzqGjHFDcpJ7c6uf92vXeU9NOjF0orDlaZLKOlOidvO2UnE02cxSm6CDKpdKH5BQWxgmFYUMGTEcUpMgR2KqSlIkTMexDanLEm4kVUprKdmZAmG@r9tBjo92eCV9PUZNpFTOgQvNw1wo//Kv4I8vgmBHsPY9b/lQn9P6vFi7rrV/Aw "Haskell – Try It Online") Quite different from my Haskell + hgl answer, and still decently short, all things being considered. This uses a more bootleg parse than that, but if you squint you can see the similarities. [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 86 bytes ``` d#(0:x)=(d+1)#x d#(1:i++[2])|all(<2)i&&foldl((+).(2*))1 i<=d=1 d#(2:x++y)=d#x*d#y (0#) ``` [Try it online!](https://tio.run/##TYrNCsMgEITvPoUghN1sW1yPEp8k5CARQWp/SCgo9N2tbS/hg@EbZtbXttXz01/XvbWgQNuCDgIxqiJ6Z5uIZrPg2@cMk8E0DPGRQwYgvIAZEVmmyQXH37uxhaiiC6qMQVURHWiF7ebTXToZ5axPf0yHD8a/PHpfliY@ "Curry (PAKCS) – Try It Online") Returns `1` for truth, and nothing otherwise. ]
[Question] [ [Gaussian integers](https://en.wikipedia.org/wiki/Gaussian_integer) are complex numbers \$x+yi\$ such that \$x\$ and \$y\$ are both integers, and \$i^2 = -1\$. The norm of a Gaussian integer \$N(x+yi)\$ is defined as \$x^2 + y^2 = |x+yi|^2\$. It is possible to define a [Euclidean division](https://en.wikipedia.org/wiki/Euclidean_division) for Gaussian integers, which means that it is possible to define a [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) to calculate a [greatest common divisor](https://en.wikipedia.org/wiki/Gaussian_integer#Greatest_common_divisor) for any two Gaussian integers. Unfortunately, a Euclidean algorithm requires a well-defined [modulo operation](https://en.wikipedia.org/wiki/Modulo_operation) on complex numbers, which most programming languages don't have (e.g. [Python](https://tio.run/##K6gsycjPM/7/v6AoM69Ew1TbOEtBVcFI1yJL8/9/AA), [Ruby](https://tio.run/##KypNqvz/v0BBw1TbOFNBVcFI1yJT8/9/AA)), meaning that such an algorithm fails. ### [Gaussian division](https://en.wikipedia.org/wiki/Gaussian_integer#Euclidean_division) It is possible to define the division \$\frac a b = x+yi\$ (where \$a\$ and \$b\$ are both Gaussian integers) as finding a quotient \$q\$ and a remainder \$r\$ such that $$a = bq + r, \text{ and } N(r) \le \frac {N(b)} 2$$ We can further limit this to \$q = m + ni\$, where \$-\frac 1 2 < x - m \le \frac 1 2\$ and \$-\frac 1 2 < y - n \le \frac 1 2\$, and \$r = b(x - m + (y - n)i)\$ From here, a Euclidean algorithm is possible: repeatedly replace \$(a, b)\$ by \$(b, r)\$ until it reaches \$(d, 0)\$. \$d\$ can then be called the greatest common divisor of \$a\$ and \$b\$ Complex GCDs are not unique; if \$d = \gcd(a, b)\$, then \$d, -d, di, -di\$ are all GCDs of \$a\$ and \$b\$ --- You are to take 2 Gaussian integers \$a, b\$ as input and output \$\gcd(a, b)\$. You may take input in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and any reasonable format, including two complex numbers, two lists of pairs `[x, y], [w, z]` representing \$\gcd(x+yi, w+zi)\$ etc. Additionally, the output format is equally lax. You may output **any** of the 4 possible values for the GCD, and you don't need to be consistent between inputs. If your language's builtin \$\gcd\$ function already handles Gaussian integers, and so would trivially solve this challenge by itself, please add it to the Community Wiki of trivial answers below. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Test cases ``` 5+3i, 2-8i -> 1+i 5+3i, 2+8i -> 5+3i 1-9i, -1-7i -> 1+i -1+0i, 2-10i -> 1+0i (outputting 1 here is also fine) 4+3i, 6-9i -> 1+0i (outputting 1 here is also fine) -3+2i, -3+2i -> 2+3i -6+6i, 3+5i -> 1+i 4+7i, -3-4i -> 2+i -3+4i, -6-2i -> 1+2i 7-7i, -21+21i -> 7+7i ``` [Answer] # Python 3, 70 bytes ``` f=lambda a,b:b and f(b,a-b*((t:=a/b+.5+.5j).real//1+t.imag//1*1j))or a ``` [Answer] # Community Wiki answer for trivial answers Please add your language to this if the builtin GCD function correctly handles Gaussian integers. ## [J](http://jsoftware.com/), 2 bytes ``` +. ``` [Try it online!](https://tio.run/##Zc6/CsIwEAbwvU/x4VKLtuRfEw04CU5OvkAGscgtvv8UL2lSIQ7hwv347o7ibuoXXDx6HCHg@Y0Tro/7LR6mOHSv5/uD/UwaCxSFE4ABo4ck2dhG3CgkKZzZEPjj2hw3xTpUimqimMkzYVO@taBJMeaSSW37giXLpGn@u9KQW0PBoMbkb6JJyOtUzaliLl3OprglszlyXfwC "J – Try It Online") ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 3 bytes ``` GCD ``` [Try it online!](https://tio.run/##XcwxC4MwEIbhvb/i9vPAS2LSDkJBoWTr3jqEUqmDDpL/n8abEqeDh@/eNcTfdw1x@YQ0Qw/v9BjG9NyXLd5hfnWofQOKrn66nBErZLplBGJyJRNjKwVuSzaSAJufyrFGlVlOyRZtZo1dnXCyJXNKmIMtVQlHMlaMiv2U/g "Wolfram Language (Mathematica) – Try It Online") ## [Pari/GP](http://pari.math.u-bordeaux.fr/), 3 bytes ``` gcd ``` [Try it online!](https://tio.run/##XYwxDoAgEAR7X2Epnpt4gKCFD/AZRqOxMcT4fwzQCNUlM3vj1ufC6fwx@3PbvXuu@22OZiDVLl0tMbaLEFWJKceMKWAwbMbB1KcM95nQqWPC33@vSMZQvH9hyAShaCg6Nu2hy5COwiAPWaQHySQ5GP8B "Pari/GP – Try It Online") ]
[Question] [ The brainiacs at *New Scientist* tweeted this morning that "The word STABLE has the neat property that you can cycle the first letter to the end to make a new word: TABLES. And you can do it again to make ABLEST." (<https://twitter.com/newscientist/status/1379751396271124480>) This is of course correct. It is not, however, unique. Let us demonstrate that we can use computational force to match their linguistic cleverness. You are to write a program that generates two sets of outputs based on the dictionary words revealed when rotating the letters of another dictionary word. Using the dictionary at <https://gist.githubusercontent.com/wchargin/8927565/raw/d9783627c731268fb2935a731a618aa8e95cf465/words>, 1. find all the dictionary words with more than two characters for which every possible rotation yields another dictionary word. Show only one example of each rotation set (so, for example, show only one of "car", "arc", and "rca"). 2. find the words for which the largest number of valid rotations exist. You should find multiple words that tie with the same number of valid rotations. As above, show only one member of each set. Additional rules: * You can assume that the dictionary has been downloaded outside your code, and can be passed to your code as input or in a variable. * If you need to process the word list to put it in a format more natural for your programming language (a list for example), you may exclude this code from your byte count. However this process should not remove any words; any bytes associated with, for example, removing two-letter and one-letter words from the dictionary must be included in your byte total. * Anything in the words list counts as a word, even if we know it's really an acronym, or contains punctuation marks, or is not English (e.g. "AOL" or "Abdul's"). Treat all characters as letters. * Treat all letters as identically cased (so "India" and "india" are the same, and "eAt" is a valid word). * No shortcuts based on already knowing the answer, or knowing the maximum number of rotations. Your code needs to actually solve for that. Using these rules and some ungolfed Wolfram Language, I found four completely rotateable words and 15 words tied at the level of maximum rotateability. This is a code golf challenge, and I imagine it won't be hard to do it more concisely than I did. I plan to call out any particularly creative solutions as well, regardless of length. -- Intended output (assuming I coded it correctly) completely rotatable words: aol, arc, asp, eat (each of these words can be presented with the letters in any rotation) maximum rotatable words: all of the words above, plus ablest, alan, ales, anal, ankh, aver, emit, ernst, errant, evan, evil (each of this latter group also has two valid rotations) [Answer] # [Python 3.10](https://docs.python.org/3.10/), 166 bytes Based on [Manish Kundu's answer](https://codegolf.stackexchange.com/a/223097/64121). The assignment expression in the set comprehension would need parentheses in version 3.8. ``` def f(a,m=0): a={*map(str.lower,a)};b=c=[] while a:w,*_=a;k={w:=w[1:]+j for j in w}&a;p=len(k);a-=k;c+=[w]*(p==len(w)>2);b=b*(p<=m)+[w][p<m:];m=max(m,p) return b,c ``` Local output: ``` >>> f(words) (['lesa', 'ernst', 'mite', 'hank', 'ablest', 'car', 'ola', 'spa', 'rave', 'alan', 'vile', 'vane', 'aral', 'eat', 'errant'], ['car', 'ola', 'spa', 'eat']) ``` With a recursive lambda this gets down to 165 bytes, but it crashes for the full word list: ``` f=lambda a,m=0,b=[],c=[]:(a:={*map(str.lower,a)})and(w:=min(a))and f(a-(k:={w:=w[1:]+j for j in w}&a),max(m,p:=len(k)),b*(p<=m)+[w][p<m:],c+[w]*(p==len(w)>2))or(b,c) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~269~~ 266 bytes ``` def f(a,m=0,b=[],c=[]): a=[k.lower()for k in a] while a: w,k,u=a[0],[],1 for i in range(len(w)): x=w[i:]+w[:i] u,k=x in a and(u,k+[x])or(0,k) p=len(k) for j in{*k}:a.remove(j) if u and len(w)>2:c+=[w] if p==m:b+=[w] if p>m:m,b=p,[w] return b,c ``` [Try it online!](https://tio.run/##TY9BjsMgDEX3PYWXMLGqdLpDci@CWJCUtJQAEUpKqqpnz0C6mY1lf7//LU@v@R7DeduuZoCBafTUYkdSYV8KFwfQJN1xjNkkxoeYwIENoNUB8t2OBnRBIKPDhbRsFRbnqSiVtJVMOtwMG01gmdc4gJWytEI1WQqrqrCgo3VPBR2urIyNXBWPibXoeCEmqv69rbmPwr5/3EfoYzI@Pg171JUdYKkB8D12@RV9QzKr72oi8qL7L1y88OXVCXcpmXlJATrst@0P "Python 3 – Try It Online") Takes a list of words as input. First convert all words to lowercase, then for each word check all it's rotations and if they are valid, remove them from the list. Outputs two lists containing maximum rotatable words and completely rotatable words respectively. Needless to say this is not optimal at all and takes several minutes to execute for the provided input. Output I got for the given dictionary: `(['aol', 'alan', 'alar', 'ernst', 'evan', 'hank', 'lesa', 'levi', 'rca', 'terran', 'vera', 'ablest', 'asp', 'ate', 'emit'], ['aol', 'rca', 'asp', 'ate'])` *-3 bytes thanks to pxeger* [Answer] # Java, 369 bytes ``` d->{var o=new HashSet<String>();Set a[]={new HashSet(),new HashSet()};for(var s:d)o.add(s.toLowerCase());int l=0;for(var s:o){int v=1,i=0,b=s.length(),g=0,h=0;for(;++i<b;){var c=s.substring(i)+s.substring(0,i);if(a[0].contains(c))++g;if(a[1].contains(c))++h;if(o.contains(c))++v;}if(v==b&b>2&g<1)a[0].add(s);if(h<1&v>=l){if(v>l)a[1].clear();l=v;a[1].add(s);}}return a;} ``` Full program: ``` import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; public class Main { public static void main(String[] args) throws IOException { Function<Set<String>,Set[]> f= d->{var o=new HashSet<String>();Set a[]={new HashSet(),new HashSet()};for(var s:d)o.add(s.toLowerCase());int l=0;for(var s:o){int v=1,i=0,b=s.length(),g=0,h=0;for(;++i<b;){var c=s.substring(i)+s.substring(0,i);if(a[0].contains(c))++g;if(a[1].contains(c))++h;if(o.contains(c))++v;}if(v==b&b>2&g<1)a[0].add(s);if(h<1&v>=l){if(v>l)a[1].clear();l=v;a[1].add(s);}}return a;} ; Set<String> dictionary = new BufferedReader( new InputStreamReader( new URL("https://gist.githubusercontent.com/wchargin/8927565/raw/d9783627c731268fb2935a731a618aa8e95cf465/words").openStream() )).lines().collect(Collectors.toSet()); System.out.println(Arrays.toString(f.apply(dictionary))); } } ``` [Answer] # [R](https://www.r-project.org/), ~~182~~ 191 bytes *Edit: +9 bytes to fix bug after discovering that some entries are present twice (with different capitalization) in the dictionary* ``` function(d,e=tolower(d),x=unique(e),`?`=nchar,s=substring,S=sapply,z=S(e,function(w){y=x%in%S(1:?w,function(n,w)paste0(s(w,n+1),s(w,1,n)),w);x<<-x[!y];sum(y)}))list(d[z>2&z==?e],d[z==max(z)]) ``` [Try it online!](https://tio.run/##bZPNjtsgFIX3eYp2pGlBpVLT5czQaBaz6KKrzG4UZa7NTczIhpSf2k7VZ09tDNipuuI758AFccFctHe2AeP2rsJ9oQ8HqSy/HLwqndSKCIbc6Vq3aIigrONeyZ8eCVL2unnlqqzAMMutL6wzUh3Zlls4neqenfmWIMuFWvq7592tVLdbsr7btHOiWEtPYB1@IZa0TH1aUzbCmilKh@y@e3j43L2873f31jekp38oraV1RLycv339cOZ8gzs2CM4b6MiZ7uilkUruhQwbgOl5SW4eC6xv2LswfrSJwIiEVqsF5ilGII7BKos5UuCq/kqkTIo3UAsM/lhCHkHGc8gaFY64dVDUgZ5HiCUGcCM9QRieEaYSLsx8amSwvztsxvGHnPzHQqHJkI5joIImniDwHDQZFl4kC7WOuX@L2xe9tcPtwmRHkZZGqa5VTMupQJkkiFglUHZPvi71klNSonLeYKwSVQ4NZEge/kKhF5j8ChBiSyfOARY40@wOvTWJ0zOZMPW1rGSdOhc5LdeqhKOHK5Ez6@K1Bhxsulr970uSf140XV3@Ag "R – Try It Online") Function "`outsmart_the_boffins`" with input parameter `d`=dictionary in the form of a vector of words. TIO link includes a mini-dictionary that encompasses at least some of the intended output words. Outputs a list of completely-rotatable words, and then maximum-rotatable words. **Ungolfed code** ``` outsmart_the_boffins= function(d){ e=tolower(d) # first convert dictionary to lower case (e), x=unique(e) # make a copy of unique elements (x); r=function(n,w) # define function r=rotates letters of word w by r steps paste0(substring(w,n+1), # by paste-ing the second half substring(w,1,n)) # in front of the first half; z=sapply(e,function(w){ # now calculate z=valid rotations for each word w in e: y=x %in% sapply(1:nchar(w),r,w); # define y as the positions of matches in x to all rotations of w, x<<-x[!y]; # delete them all from x (so we don't find the other members of the set later), sum(y) # and return the number of them; }) list(d[z>2 & z==nchar(e)], # finally, output the words with >2 characters whose valid rotations equals their length, d[z==max(z)]) # and those whose valid rotations is equal to the maximum found. ``` Run on the full dictionary (took a few minutes): ``` > outsmart_the_boffins(scan(file="words.txt",what="abc")) Read 99171 items [[1]] [1] "AOL" "RCA" "asp" "ate" [[2]] [1] "AOL" "Alan" "Alar" "Ernst" "Evan" "Hank" "Lesa" "Levi" [9] "RCA" "Terran" "Vera" "ablest" "asp" "ate" "emit" ``` [Answer] # JavaScript (ES6), ~~211~~ 203 bytes Expects an array of words. ``` a=>[(a=[...new Set(a.map(w=>w.toUpperCase(m=g=(w,W=k=w)=>(W=W.slice(1)+W[0])==w?k:g(w,W,k=W<k?W:k))))]).filter(w=>g[w]^(n=w.length)|n<3?0:m>n?1:m=n,a.map(w=>g[g(w)]=-~g[k])),a.filter(w=>g[g(w)]=g[k]==m)] ``` [Try it online!](https://tio.run/##TY7LasMwEEV/pTtL1BEJ3ZmMvegnlKCFUEFWZdXRy9giikPpr7tjCqWzOGdxhztzVTe16Hmc8iGmD7MNsCloBVEgGGPRlKc3k4liQU2kQFtYTpdpMvOrWgwJYIGUmoODQqElHDhb/KgNOdFnLo6SApTONXZfqh3ws@t44yiOpGwYfTbz3mpFke8kQmHeRJs/6Vc8v3THJrSxOzUBYv33gBVYRiUcvq1wklJM/vf8hnsEEKjcdIpL8ob5ZMlARKV6XdVVrxVSqx5Z7usDtT7KHYVcUUNKyJSGCk9sPw "JavaScript (Node.js) – Try It Online") ## Output on the full dictionary ``` [ [ 'AOL', 'ARC', 'ASP', 'ATE' ], [ 'AOL', 'ALAN', 'ALAR', 'ERNST', 'EVAN', 'HANK', 'LESA', 'LEVI', 'RCA', 'TERRAN', 'VERA', 'ABLEST', 'ASP', 'ATE', 'EMIT' ] ] timer: 329.15ms ``` ## Commented ### Helper function The helper function `g` turns a word into a normalized rotation form, i.e. the first one in lexicographical order. The result is also saved in `k`. ``` m = g = ( // m = maximum 'rotatability' w, // w = input word W = // W = current rotation of w k = w // k = first rotation in lexicographical order ) => // (W = W.slice(1) + W[0]) // rotate W by one position == w ? // if W is equal to w: k // stop and return k : // else: g( // do a recursive call: w, // pass w unchanged W, // pass the updated W k = W < k ? W : k // update k to min(W, k) ) // end of recursive call ``` ### Main function ``` a => [ // a[] = list of words ( a = // convert a[] to: [...new Set( // the list of unique words in a[] ... a.map(w => // w.toUpperCase(...) // ... in upper case ) // (NB: m and g are actually defined here) )] // ) // end of conversion .filter(w => // for each word w in a[]: g[w] ^ (n = w.length) | // if the length of w is not equal to the number of n < 3 ? 0 // rotations or is less than 3: discard this entry : m > n ? 1 : m = n, // otherwise, update m to max(m, n) and keep this entry a.map(w => // for each word w in a[]: g[g(w)] = -~g[k] // increment g[k], where k = normalized rotation of w ) // end of map() ), // end of filter() a.filter(w => // for each word w in a[]: g[g(w)] = g[k] == m // keep the words that have m rotations // and update g[k] in such a way that each word can // appear only once ) // end of filter ] // ``` ]
[Question] [ The goal of this challenge is to extend the On-Line Encyclopedia of Integer Sequences (OEIS) sequence [A038375](https://oeis.org/A038375). > > Maximal number of spanning paths in tournament on n nodes. > > > A [tournament](https://en.wikipedia.org/wiki/Tournament_(graph_theory)) on \$n\$ vertices is a directed graph where for each pair of vertices \$(v\_i, v\_j)\$ there is either a directed edge \$v\_i \rightarrow v\_j\$ or a directed edge \$v\_j \rightarrow v\_i\$. A [spanning path](https://en.wikipedia.org/wiki/Hamiltonian_path) or Hamiltonian path is an ordering of all of the vertices of a graph, \$(v\_1, v\_2, ..., v\_n)\$ such that there is an edge \$v\_i \rightarrow v\_{i+1}\$ for all \$i<n\$. # Example ![A tournament on 4 vertices.](https://upload.wikimedia.org/wikipedia/commons/thumb/8/89/4-tournament.svg/360px-4-tournament.svg.png) In the above tournament, there are five Hamiltonian paths: * \$(1,2,4,3)\$ * \$(1,4,3,2)\$ * \$(2,4,3,1)\$ * \$(3,1,2,4)\$ * \$(4,3,1,2)\$ Moreover, it is not possible to construct a tournament on four vertices with more than five Hamiltonian paths, so \$A038375(4) = 5\$. --- The way to win this [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge is to write a program that can compute the largest value of A038375 deterministically in under 10 minutes on my machine, a 2017 MacBook Pro with 8GB RAM and a 2.3 GHz i5 processor. In the case of a tie at the end of ten minutes, the winning code will be the one that got its final value fastest. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), \$N=10\$ ``` #include <algorithm> #include <iostream> #include <vector> #include <cstring> #include <ctime> //a rewrite for vector<int> struct vi { int l,a[9]; const int& operator[](int u) const {return a[u];} int& operator[](int u) {return a[u];} }; bool operator < (const vi&a,const vi&b) { for(int i=0;i<a.l;++i) if(a[i]!=b[i]) return a[i]<b[i]; return 0; } bool operator == (const vi&a,const vi&b) { for(int i=0;i<a.l;++i) if(a[i]!=b[i]) return 0; return 1; } std::vector<vi> g[13]; void dfs(int x,int u,const vi&c,int*w) { ++w[u]; if(c[x]&u) for(int o=c[x]&u;o;o^=o&-o) dfs(__builtin_ctz(o),u^(o&-o),c,w); } void dfsf(int x,int u,const vi&c,int*w) { ++w[u]; if((~c[x])&u) for(int o=(~c[x])&u;o;o^=o&-o) dfsf(__builtin_ctz(o),u^(o&-o),c,w); } int main() { g[0].push_back(vi()); for(int i=0;i<9;++i) { for(auto t:g[i]) { int m1=0,m=0; for(int j=0,r;j<i;++j) { if((r=__builtin_popcount(t[j]))>m1) m=0,m1=r; if(r==m1) m|=1<<j; } for(int e=0;e<(1<<i);++e) if(__builtin_popcount(e)>m1 ||(__builtin_popcount(e)==m1&&((e&m)==m))) //ensure the node has the highest degree { vi u; u.l=i+1; for(int p=0;p<=i;++p) //enumerate position { bool s=(p==0); int x; #define yield(l,c) do{if((x=(c))>u[l]&&!s) goto skip; else s|=x<u[l],u[l]=x;}while(0) for(int a=0;a<p;++a) yield(a,((t[a]>>p)<<(p+1))|(t[a]&((1<<p)-1))|((!((e>>a)&1))<<p)); yield(p,((e>>p)<<(p+1))|(e&((1<<p)-1))); for(int a=p;a<i;++a) yield(a+1,((t[a]>>p)<<(p+1))|(t[a]&((1<<p)-1))|((!((e>>a)&1))<<p)); skip:; #undef yield } g[i+1].push_back(u); } } std::sort(g[i+1].begin(),g[i+1].end()); g[i+1].erase(std::unique(g[i+1].begin(),g[i+1].end()),g[i+1].end()); int sz=g[i+1].size(); std::vector<vi> h(sz); #pragma omp parallel for for(int w=0;w<sz;++w) { vi u=g[i+1][w],v; auto sw=[&](int x,int y) { std::swap(v[x],v[y]); for(int s=0;s<v.l;++s) { int&o=v[s]; if(((o>>x)^(o>>y))&1) o^=(1<<x)|(1<<y); } }; for(int x=0;x<=i;++x) for(int y=x+1;y<=i;++y) { {v=u;sw(x,y);u=std::min(u,v);} for(int z=y+1;z<=i;++z) { {v=u;sw(x,y);sw(y,z);u=std::min(u,v);} {v=u;sw(x,y);sw(x,z);u=std::min(u,v);} {v=u;sw(y,z);sw(x,z);u=std::min(u,v);} {v=u;sw(y,z);sw(x,y);u=std::min(u,v);} {v=u;sw(x,z);sw(x,y);u=std::min(u,v);} {v=u;sw(x,z);sw(y,z);u=std::min(u,v);} } {v=u;sw(x,y);u=std::min(u,v);} } h[w]=u; } std::sort(h.begin(),h.end()); h.erase(std::unique(h.begin(),h.end()),h.end()); g[i+1]=h; } std::cout<<"pre ("<<clock()*1./CLOCKS_PER_SEC<<"s)\n"; for(int o=0;o<=9;++o) { int mx=0; const int s=g[o].size(); #pragma omp parallel for reduction(max:mx) for(int t=0;t<s;++t) { int a[9<<9],b[9<<9]; memset(a,0,sizeof(int)*(o<<o)); memset(b,0,sizeof(int)*(o<<o)); for(int i=0;i<o;++i) dfs(i,((1<<o)-1)^(1<<i),g[o][t],a+(i<<o)), dfsf(i,((1<<o)-1)^(1<<i),g[o][t],b+(i<<o)); int r[9][9],c=(1<<o)-1,vx[1<<9]; for(int p=0;p<o;++p) { int*A=a+(p<<o),vn=0; for(int x=0;x<=c;++x) if(A[x]) vx[vn++]=x; for(int q=0;q<o;++q) if(p!=q) { int*B=b+(q<<o),su=0; for(int u=0;u<vn;++u) su+=A[vx[u]]*B[c^vx[u]]; r[p][q]=su; } } int m1=0,m=0; for(int j=0,pc;j<o;++j) { if((pc=__builtin_popcount(g[o][t][j]))>m1) m=0,m1=pc; if(pc==m1) m|=1<<j; } for(int i=0;i<(1<<o);++i) if(__builtin_popcount(i)>m1 ||(__builtin_popcount(i)==m1&&((i&m)==m))) { int tot=(o==0); for(int j=0;j<o;++j) if(i&(1<<j)) { tot+=a[j<<o]; for(int ii=c^i;ii;ii^=ii&-ii) tot+=r[j][__builtin_ctz(ii)]; } else tot+=b[j<<o]; mx=std::max(mx,tot); } } std::cout<<"a("<<o+1<<") = "<<mx<<" ("<<clock()*1./CLOCKS_PER_SEC<<"s)\n"; } } ``` [Try it online!](https://tio.run/##rVdRb9s2EH62fwWTAgYZy42NPTUSDbRFnzZgw/qoKQEt0xZTSVRESpadeD992ZGSbMlxs3QbkFjy8e67j3e84znMssk6DJ@f34k0jIslRx6L1zIXOkrmw6NQSKVzznqykoda5l1JCEoiXfdEWiR8Pry@ZijnG8DlaCVzVNt6ItXzIRgVoUalGD4OByBBscP8D4E7HIQyVRqBaIRkxnMGJn6AjUpBUL34mHNd5ClifhG4e2t/TvlEbe8OF1LGB0XkIVzjlWLEnMPrghhOQNjiCDp1hcfex@54LAgSK8x8EVzQBXwSdPAgAs9IgH8jmrrD/Yk/Sv83h9Ojo5lxpPTy5qaJbynmaO3PfgIypRRLtFwpC1w5Ni5Hv6ERXG2s9/F4Y6IEsVzh0K@CUUGGgwMnSWuZK115S@VoIs3qwCDf3S0KEWuR3oV6hyVxiltsFZzQ2RDDrSWx@jEW@E/jk5wSOYhfclm9gYwBSZhIsfW39qfB@6xQ0d2Chd9wKTABrZNUfLCJGA4eGx6s0BLpm7XJB4iM2J7gZEanTkJNao6E70GWu/eeAJB7S9Tq2w3m9Mg3k1koi1Rj7d8HhMyTGUGJwZvR3G0tckqt/InOPO/eivddZxyccw/DoiDgj9vTc8YHN/jG8Onp/LLxMxphzEeJeSeEoOtrnqoi50hHHKUSyjxiyn6JxDrikMslX@ecH7dYClS4qHgfUzGe1XtoiWZANPOoCUpWQxeJKRKOMqmEFjK16jXOwFaRojijdEpcZE9RjTd4t@QrkXK0FTxe4tgJCVrKRxPciuIQ4lj4cTAaXSiC1hLSpr6JzEU8VhypJ1p5ZtkxH7Ry95tIxBxPSQ3dcmXAlXkZUGXNyqD2xhwM2WLBfJ4Rz8PZeEbIk5VA5CAHGZlYCb6AQM7njIzgqxGThnwNkzl2uYvBuwCt9pFPBnzEGT7j2X9lZMJz04a2SCG4dWStxB41KBnIZrdoCnI4iObfdiIlc40bzQVfm3Jzmq88XdZF1iJB3hXH1qxIxUPBXzV8CWNiona0kSux49jKT1tihNXOLrzLcrZOGJJJhjKWszjmsbmfOm1mAznfeGoHQd4catyc58aNvwmc0m7bNgO1of4o6LS3LVw@Nlp1NDYswyV0Laf0twHpl4ICV8orbbtXpHvsza0maemroMmIOdZYzucVuTWPLTH5Q9AETW4ryCs8tg28Tda@14oq8FTVRVeRHoctraBCt/XatkfisaSFqza4cgC5oHY/CaSlcEri7vsnc0e3ALOrYXbN4Wxw@kDw3Dq77wK@UK7eomwRf1x5@xYa/0L5tQ3u3xxc@xnBeQPNFxUWHWok6hREdKakXmr2TOpTTSN4Bw/WEK4C7XmXGXR8fOl5YSyh1snV7P31519@/fzz17vfvvx@9/XLZ9BR5I/0snNtSjho0qPm3pTNvWnvx6q@Gw8DHpz9tS@7Nfu90oSxZwnjItwLOGHVTVJ1ZwINsNpT4E337mOYJz3vQ@As6qethYQnimto3VPHeJV2JiFXWHqebLpgo7J4RaU/H8hmPmgGIuHYXitNr72t72LHbNPXgcPGWFgYp1Vfvaq/aPXddlM5DMnw54S0NXLKyp8dNti/YaW9YDtTB0xaHymwyIytU6bNtHLaI0LbI8z08NEMWwhclOl4bG7JnvoDqD9YLw9WO7ugD6c97OoThW08WIeqaB0eIIyk8MoUMIr2PlPFmH70wWkRBFef/PC2fm0scz8L/IeAqqLb6v5xCstCGMPkmTEsC8/NYU0KXkxjANNaguHr81h9PupEHab5M77E6/OYOMxj4jCP9XKKtNQUSzse9fID@@5t2tIWI8Ponpw0aMAYU@bfA9k20seNCBreCleYv1sqxGgiRJus2jCHQPn98RtUWqCm39m5y6ovun6gMdStj1U4qRxQODNSNP2ImWYkx7CBS4Iogi9JBe9v7lHwM/D5@a9wFbO1ep78umJKP09WRZrLOJ5Av5nEUmawskrlRGmYbyZZLrWdIkBo1CcJ09EzfOZhRFOmRclhBX7kpUkGL5tIxtwYrXOW/A0 "C++ (gcc) – Try It Online") Compile with `g++` and `-Ofast -funroll-all-loops -ffast-math -fno-stack-protector -march=native -fopenmp`. Note that OpenMP is used for parallelism. Output on my modest computer: ``` pre (5.217s) a(1) = 1 (5.218s) a(2) = 1 (5.218s) a(3) = 3 (5.219s) a(4) = 5 (5.221s) a(5) = 15 (5.221s) a(6) = 45 (5.222s) a(7) = 189 (5.223s) a(8) = 661 (5.225s) a(9) = 3357 (5.318s) a(10) = 15745 (18.634s) ``` The run time may differ a lot because of the use of OpenMP parallelism. --- Explanation for \$N=9\$ version: This code is two-fold. First, it will try to generate all tournament graphs up to isomorphism. Then, it will count the number of hamilton paths on these generated graphs. Adjacency matrices of graphs are stored as arrays of bitmasks (i.e. arrays of uint) for performance reasons. The second part is relatively easier. We can just use depth-first-search to search for all possible paths and use bitmasks to speed up. The time complexity is \$O(\text{no. of paths in all graphs})\$. It's also possible to use bitmask dynamic programming to do it, with \$O(2^NN^2)\$. The above code used the former while the latter one should be faster when N goes higher. OpenMP parallelization is used to speed it up. The first part is harder. My approach is incremental: first generating all tournament graphs of \$t\$ nodes, then add one node to be tournament graphs of \$t+1\$ nodes. The trick here is to find an order for adding nodes. Here, instead of adding any node, we restrict the added node to have the greatest degree in the result graph. Therefore, a graph won't be generated too many times. Graph-isomorphism isn't a easy thing to check too. Therefore we're not really trying to make every graph unique, but to have some degree of tolerance. I have two strategies used here. First, the newest \$t+1\$-th node won't be directly assigned number \$t\$. Instead, we try all the possible numbers from \$0\$ to \$t\$ and take the result graph with the smallest lexicographic order (you can use early-stopping when comparing lexicographic order, so not much overhead). After generating all \$t+1\$-node graphs in this way, we remove the found duplicates by sorting and making them unique. This alone can cut down the number of found graphs for \$N=9\$ to around \$3\times 10^6\$. The second strategy is that, after found such candidates, we further try to remove duplicates by trying to swap every two nodes and see if we can get a graph with smaller lexicographic order. We then proceed by sorting and making them unique. These two strategies cut down the number of found graphs for \$N=9\$ to around \$10^6\$. (This strategy alone is more powerful than I thought, cutting down to around \$1.1\times 10^6\$) --- Explanation for \$N=10\$ version: Some improvements are made upon the \$N=9\$ version. First, instead of swapping two positions, three positions are swapped to achieve a better result. This successfully cut the number of graphs generated at \$N=9\$ to less than \$5 \times 10^5\$ (~50% improvement). OpenMP parallelization is also introduced here to speed up. Generating all graphs for \$N=10\$ sounds unfeasible, so instead I try to expand the last step. We still try to add one node for graphs with \$9\$ nodes, but instead of actually generating these new graphs, we can actually count the hamilton paths in them directly! Consider the relationship between a hamilton path and the new node. The new node can be the first end of the path so we need to find an edge from the new node and continue the path from that node. The new node can also be the second end so we can find an edge to the new node and trace back the path starting from that node. Of course, the new node can be in the middle of the path. In this case, we can enumerate the two nodes in front and on the back of it. We can then enumerate the subset of nodes both halves of the path contain and then multiply them to get the result. Notice that the contribution is the same for every pair of nodes adjacent to the new node regardless of other edges to the new node, so we can get that precalculated for every two nodes. In order to get the number of paths starting and ending on each node covering a certain subset of nodes, we can use depth-first-search from each starting and ending point. (A bitmask dynamic programming could work too, but I guess it's slower) [Answer] # [JavaScript (Node.js)](https://nodejs.org), \$N=8\$ Simple brute-force. Finds \$a(8)=661\$ in approximately 45 seconds on my laptop. Computing \$a(9)\$ with this code would take several hours. ``` function search(n) { let m = Array(n).fill(0), max = 0; function count(m) { let res = 0; for(let y = 0; y < n; y++) { (function path(y, visited) { if((visited |= 1 << y) == (1 << n) - 1) { res++; return; } for(let msk = m[y] & ~visited, b; msk; msk ^= b) { path(31 - Math.clz32(b = msk & -msk), visited); } })(y); } return res; } (function build(x, y) { if(y == n - 1) { max = Math.max(max, count(m)); } else { for(let j = (x == y + 1 ? 1 : 0); j <= (x == n - 1 && !y ? 0 : 1); j++) { m[y] = m[y] & ~(1 << x) | j << x; m[x] = m[x] & ~(1 << y) | (j ^ 1) << y; x + 1 < n ? build(x + 1, y) : build(y + 2, y + 1); } } })(1, 0); return max; } ``` [Try it online!](https://tio.run/##ZVNbbqNAEPz3KSpS5AwCW3b8sVIwWuUAOcEqUTDGG7wwRDwiZh1ydaea4WErSDBNdU13dQ0cw4@wjIrkvVrofB@f7@oyRlkVSVTd@edDraMqyTXKOCyiN6UdnGZAGlfIEOCxKEJDcHlI0lStHI85ubKwYXblz/g@lojyWlcqsxVsjSIuRx6ZeaEENR3GZQvNxXWHLYAaq72H1ZsyHj6SMqni/UQBkoNSPYzPAGtstzAOggCqiznEAuvLHRAlrutfAVVd6Alpx2iQmZX/KDT7Y54xx1ff0MPOl0z3wEuA3XWfTvZmTQFPjJZR@n9zr3ZSh/Q5Flycaaif7VtHmR62kNUp@gVtxcnJpF2dpHvVeDK@VUFvjDihry2wB9ZJYqh4e@N5XbWLU34ew67BiSP3qkbKGrj0@zfvB6wcn5ntkOo6Yj7HjSFhRcJaCJenC@vmZKo9r8bBp1Ri5F8wG8tsLphGmOqIF5lN3id@0ynj4bN5b4sgnTUPPSLq7z07xOh9O05P78nnWGJy7zud8mfteXBCU9LG58Kxf3EdpotyXeZpvEzzv@o1VLcn3fKDxO1p/K/aV0cKfQM "JavaScript (Node.js) – Try It Online") ]
[Question] [ In a challenge of CodingGame, there is a challenge that ask you to decode a string composed by reversed words ('Hello world' > 'olleH dlrow') then each characters converted into ascii value separeted by space: ``` >>> decode('111 108 108 101 72 32 100 108 114 111 119 32 41 58') Hello world :) ``` The challenge is to be the fastest to write the `decode` function, but I later tried to write it with the fewest character possible. Here is my result (104 characters): ``` def decode(m,s=' '):return s.join([w[::-1]for w in(''.join([chr(int(c))for c in m.split(s)]).split(s))]) ``` The name of the function doesn't matter, it can be shorter, but only rename variable isn't good enough for an answer. Is it possible to improve this result ? [Answer] ### Use lambdas ``` def f(a,b):return c ``` can be shortened to ``` f=lambda a,b:c ``` (the `f=` can also be removed per CGCC site standards) ### Remove excess `[]`s ``` x.join([a for b in c]) ``` can be ``` x.join(a for b in c) ``` since join can take a generator instead of a list ### Split is on spaces by default *Thanks ElPedro for reminding me about this* So the `split(' ')`s can be shortened, which in turn means the `s=' '` doesn't help (and it only broke even in the first place). ### Take input from STDIN and output to STDOUT `print` will automatically print arguments with space as a separator if you use `*` to [unpacks the sequence/collection into positional arguments](https://stackoverflow.com/a/2921893/6251742), and taking input via `input()` is shorter. Also, setting `s` to space doesn't actually save any bytes. Altogether, this is 79 bytes: ``` print(*[w[::-1]for w in(''.join(chr(int(c))for c in input().split()).split())]) ``` [Try it online!](https://tio.run/##RYpbCoQwFEO3cv9sBcX4QMetiF8FsSJtqR3E1dfbcUBIyCGJu8JqTROj89oEkU/nNI4F5sV6OkkbkWXlZjnV6kV6KCnTpnhjuW8QsjzcrjlfmGWMAAjV8Deor6mpmaqnQUu/Bz6pbkHdcAM "Python 3 – Try It Online") or, if you're dedicated to having a function, 82 bytes: ``` lambda m:' '.join(w[::-1]for w in(''.join(chr(int(c))for c in m.split()).split())) ``` [Try it online!](https://tio.run/##PY3NDoIwEIRfZW5tDxIWMCIJT6IesMVQQ3@CNcSnr60QD5PMfDOb9Z8wOVtHNUqnRvS4xnkwdzXAdAyseDpt@XrpugPdHm7BipTZzuW0cG0Dl0LkTqYOpnj5WQcuxN@I6Jc8236kC//eMBGBynYX4VShrpIrN0INfgs6Z9wQju0X "Python 3 – Try It Online") plus seven or so characters if you really need the function to be called `decode` [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` lambda m:' '.join(x[::-1]for x in''.join(map(chr,map(int,m.split()))).split()) ``` [Try it online!](https://tio.run/##PYrbCsIwGINfJeymFebYXyfOgk@iXlSlrLIeqBXm09duDgMh4UvCJw3eiaxxwiWPyt4eClYysObpjePTWcotXbWPmGAcW7FVgd@HWM9pXKpt8wqjSXxT9K85xLJxXR7hvWy5IiJQ268mHAR2orT2R6jD8qDjjDvCvq@@ "Python 2 – Try It Online") **Edit** changed to a Python 2 answer as the `lambda` is shorter than the `print`/`input` version in Python 2. This uses a couple of `map`s to get the list of characters which we then `join` on "", `split` again on space, reverse each element then re`join` again on space for 78. Also works in Python 3. Just a pity that it needs so many brackets :-( [Answer] # [Python 3](https://docs.python.org/3/), 75 bytes ``` lambda a:' '.join(''.join(map(chr,map(int,a.split())))[::-1].split()[::-1]) ``` [Try it online!](https://tio.run/##NYzRCoMwDEV/JW@t4MSoY1rYl2x7yKxgh7bB1Qe/vqvWBcJNDifhzY/O1kEPvdMD3OEZJprfmoCUAFF8nLFSnDkTy35c8j2N9TkVX56Ml1msh1IXfP1B2rLAS/Rkeh5PeD3kgIiAZXs2wq2CuopTmQg2cBjY7bhBuLY/ "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 70 bytes If taking input from STDIN and outputing to STDOUT is fine then it takes only 70 bytes this is mostly because the spread operator (`*`) is shorter than `' '.join()` ``` print(*''.join(map(chr,map(int,input().split())))[::-1].split()[::-1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0tdXS8rPzNPIzexQCM5o0gHRAMldDLzCkpLNDT1igtyMoE0EERbWekaxsIEIDzN//8NDQ0VDA0soNhQwdxIwdgIyDKAiBiaKIBVGFqChE0MFUwtAA "Python 3 – Try It Online") ]
[Question] [ # A guess the word game The [agreed dictionary](https://gist.github.com/lesshaste/775f70d4da6778807ff9a8a42c293169#file-agreeddict-txt). All words are 6 letters long with all letters distinct Rules: This is a game of two players and the task will be to implement Player 2. Player 1 chooses a word from the agreed dictionary Player 2 repeatedly guesses a word from the agreed dictionary. At each turn, Player 1 tells Player 2 how many letters the guess has in common with the secret word. For example, `youths` and `devout` have three letters in common. # Goal Player 2's goal is to guess the word in as few turns as possible. # Task The task is to implement player 2 to minimize the maximum number of guesses they ever have to make. Your score is the maximum number of guesses made when considered over all the words in the agreed dictionary. A lower score is better. You should test your code by choosing each word from the agreed dictionary in turn and see how many guesses your implementation of Player 2 needs. You should then output the maximum. # Objective winning criteria Answers will first be compared by the score they get using the rules above. Two answers with the same score will then be compared using [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules. That is by the number of bytes in the code. [Answer] # [Ruby](https://www.ruby-lang.org/), 418 bytes, score 12 (on 'palest') ``` $dict = File.readlines('agreeddict.txt').map(&:chomp) def search(wrd) words = 0 fdic = $dict.clone guess = '' starters = ['earths','blowup','coding'] chs = wrd.chars while guess!=wrd do guess = starters.pop || fdic.pop words += 1 ghs = guess.chars chars = (chs|ghs).size fdic.select!{|w|(w.chars|ghs).size == chars} end words end upp = 0; p $dict.map{|w| [search(w),w] }.max ``` [Try it online!](https://tio.run/##RVBBbsMgELzzCiJVxVYj1F5bce0nohwIbAySYxBgkSbO290FYuU2Ozszu5own/7W9U1blaigv3YEHkDq0U4QOyaHAKDLkqdrYj2/SN@9fyvjLr4nRMOZRpBBmS4H3RNKsws6YtAn4jP6ENZsrkY3AZLDDLEIGMMhJhkShDIfGOYkE9menUaXZ49AOW2ngR0JSpUpKrzClZEhFiob/LYF7gRuqHbIvk5s6dw7T5el/lNwFbVHPwT9ap4aX53PA4WtCPkOry8o6Xm0N6irGhZhBJV29yUvXW6@l4wK0QIeaIBJk60eUofZ@9LTDyH@WRF2W5JQdthK7ff5SB64ua7rPw "Ruby – Try It Online") Runs in 15 seconds on my machine. TIO link for reference only - does not work if the file is not in the current directory. ### The trick Instead of brute-force elimination, try a list of initializers first. A lot of words differ by only 1 character and it's easy to get stuck in a single-letter elimination loop. The most difficult words to guess are those with 4-5 very common characters (a e r s t), 1-2 'outsiders' (c p x z...) and some anagrams in the dictionary. For example, when we reach a word containing the letters "a e r s t" and the answer is 5: if we just filter all the entries containing these 5 characters, we are left with a dictionary of 40 similar words, and then we have to try almost all of them, removing only a few words at each step. We need to remove these words first, and we filter on the least common character, so if we get to "earths", and Player 1 answers 5, we don't have a lot of words to check. The first 2 words we always check are "coding" and "blowup" (no pun intended). Now we can try with a word containing the 5 most common letters ("earths"). If the answer is 4 or 5 (which is likely), we don't have a lot of words to choose from, because we already filtered all the words containing only 1 or 2 uncommon letters (and we only used 3 guesses to get here). Finding the right initializers was a little tricky, I started with a list of 5 "quasi orthogonal" words (with as few letters as possible in common, a good start was "sporty fuzing hawked climax jumble", missing only the letter z) and got to 13, then started a test on automatically generated smaller lists. 'palest' seems to be a worst case, having 6 anagrams and 4 very common letters, but it's not the only word requiring 12 guesses, so I don't think I could get a better score with this approach. I don't want to golf this. [Answer] # [Python 3.8](https://docs.python.org/3.8/), 730 bytes, score 13 ``` p='https://gist.github.com/lesshaste/775f70d4da6778807ff9a8a42c293169/raw/c36b8d3b3d501106de781cb2c3b4c8f6e9d47b33/agreeddict.txt' from urllib.request import urlopen as o w=str(o(p).read(),encoding='utf-8').split('\n') from collections import* g=lambda x:lambda s:len(set(x)&set(s)) s=dict() for x in w: f=g(x) #the answer function from Player 1. Nothing else knows x y=w[:] #init the word set c=0 #tries counter wd='muting' while len(set(frozenset(i) for i in y))>1: #till we have only one set of letters c+=1 m=f(wd) y=[i for i in y if len(set(i)&set(wd))==m] #filter words #print('%2d'%c,wd,'answer:%d'%m,'variants left:%4d'%len(y)) d=dict() for i in y: r=Counter(len(set(i)&set(j)) for j in y) d[i]=max(r.items(),key=lambda x:x[1]) #-math.log(d[i]/len(y),2) is the info in worst case wd=min(d.items(),key=lambda x:x[1][1])[0] s[x]=(c,len(y)) assert set(y[0])==set(x) print(x,c,len(y),flush=True) print(max(sum(i) if i[1]!=1 else i[0] for i in s.values())) ``` [Try it online!](https://tio.run/##dZLPspsgFMbX@hR0U6FN/RNzo8kM3fQVurNZIKByi2gBq@nLp4fJTdPpTFcc9ON3vvPBfPXDZMp6trfbTJPB@9mds6xXzqe98sPSpnwaMy2dG5jzMquql67KxUGwY1XVdV513YnV7LDn@1NZHE@ZZWvGy2Nbi7ItxUteFPlRyKoueLvnZXvgdXeUJ3Go2rLMWG@lFEJxn/rNJ3FnpxEtVmvVplb@WKTzSI3zZH34Os3SIObQFK/UeYsnPBOQMYHJTho@CWV6miy@@1QnJHWzVh4n30xC7lw@aS25V5Nxb9APcU81G1vB0HZ@K9xZS4Od9Hgj78PiCIkdDR4xgCaLNqQMWs9x1NEeRHF0pWtzvsQRp3kcrYIm4@LBSgKbQWmJHkBw8UuaUCmCAkkF0pWQzwXQIv6RFrCMtMOrACxwG/WXDqnuD0rdvYGOUDpC70g8LEbR80jARpZ@mRbjpcX/nH4ldxuvdxtBKxp1oSPbsE2Vl6ODZL/L6zOkrSkuQQhTjspg8X9VEDY5OHPNdqGY70JzmDWOmHMSLjQ4uIICBrinHUezVQaq3UO86/TiBvrVLpLE95/Bm1vGkCDEoaDLO1ogqZ2ETX55xuXSn0zDA8KEkNvtNw "Python 3.8 (pre-release) – Try It Online") (doesn't seem to work, you can download it from there and run with `python3` (likely 3-4 hours)) -- the result is [here](https://pastebin.com/e892MZED). The [working version](https://tio.run/##dbfZDqxIsiX6nPkVKbV0M7OpWwQzlLRbgmAmGIIZquuBeZ5nfv40u@pUn74t3XgJBzd3zJabm601Xms59Ag5zv8R/4h/9780XdAs@L9/B310UgWOOCx@hKRYyf2E8O/Imo4iOa90dHNvktuUg6EXtTduLUdxx58CIlfsu5fUhhIvjGnecG3sIiDTqFYD2pSPFQgyDB0spgzoIQmDnXueL4683bLXieu7doiJeupS1AEslKi@1Ozqpx/Z6NyZs9F7oEVhX8@U8t161r8@lkz8q8C/JqRLwPfiVvsdRY1mLmSXMmwxZK7QJHqy3gc5Ibjy5dAAl4v7Qk6tYTZBn1CGuWiD58Q5WGbxlEEPNnOC71bSBciaM@gCPtP7vGFvxELzPOzo9VHEpSVHVnofMAhYcqRkEHctu0dvnRTcBg50fF2AMOgu8EQWcNkcmfuB/ZFDqkIA2VSLyvnUPBUMpnXAxJP8bglB5@vVk1/QFF6vIWu0dpGEr7JVUqevB9lMBx/NLfmOP/ItKG1oxtw0@NIh5zeSIMblXEhrgB@JJLzr7nBegPaXbdgGJk58FX9D5iO8UZoMMA4HE/QLbDwHCAHkGbjcsXEUpmDoXOLyjTRWM5ZKj3WPfNe8B5DWIO0JeSnNmPm0EW5Gz@9fA@2vbulHiwgGYRAzTFtAeP6Y1saHtmxD5o4BqD5C0Lhe8dqkDclB4JBQqQ@h35vIyowyYCVjcNgWkIRL1W@CkpnetwXJeTNgNQ4mKmXqucseyhexkOR5GYD/brfYewPqrHlA8FIia9XSfFbP3NyNTxUPBNqYnCzpuH4F3jlTLr935khMtZAgdz1nfr5Eea@5JSftgXGCyH182/aE93VZJauHqtM/dELp83rocE2nJgrXs0h2c@vla@dReuqdtKm1fMmVD2eVLoWgCgYM@qitHPLuzJfZ6hOTvPqOkvaIpZ6l73PxkmFdC6F2xybkbg1wiJgfe0YvxHOlddf2DEPYfIHQidzfMtkitWcLajN/LdL7JsmIrKHWhaAkFVK7K9l4rW@XxEMqUvDbYJWtBcyxaGXnqoc8ms3AP33tKp1puCUo9hVt/SA3NHv3297eFe93CJsNbxrdMPELKNOqOBB@hKo@xk6v1bGFEueH9ihPbOAZt7eUBFUhXUklpBOJvONmFQyTyYZScSl9D3AB4MvgW16sNbZpnpHR2lVKwA8u612gIh9s7xNpfkeYRl6ocL/K1E9beRcaWcdRsi1giaFLYsuhYGTD7TIs2EKhOkG6zzpGUns7enEkraLYAHLwIngeyGut@@a4DX3zCVWxpQbf017NT6a5LkXunEq8yXS@@Et8@9Cxn3zBo1LAxaglIzXevyUzRIm8@GRLy9@fSvfpZkdVcCLLwBGsPo4M/4sm1j6@dGAZcUQjcofz4HZ89ZvkvSpMpDFD1b1rDu6851QVBXoBc3vWcZU14R2JSxJwC@yLrGU2SA45aCFDDnDnVMvP8Kp9qmO6b1Bfg6o9VWp7728dY8PParByjYD2/iq1gzcYaDqXJlVvGn1VrLtz5@nr03gf3QDECNpcbqB2QGbjIwKGyo7l1lXJ9B6apKxq3qli6JIfibDqBrDAiosaTHW6kIMx6RzZ9068YnsPD9ex52LzUDiToDmEvWD96uDq41YWI7LSB8Od8qPkdh@8ncB31LG7SJVNZpin0EdOMoJD/L0WJpqBfv7y0DL5bL/lwTy85WGmNP0AJq@30jdb73RFWzjvwGKNnmq4u@Nt3EXRj/1sczCfXDYomvg7ahWbVWLGoM9kzRXD2V6CWgo9GSrLJ8i8K5bePbKuLs/eV5MQS2Wugq4PsJf2ctsWlUS@IEs39rWUP/piTXSE@jUY8d@CN@r3YRLLyEQJ1FHVYQHMhSH67UCcNAwjSSpvFqQrA3oBxFriu0CN83RdwFayX8rPRLicOSWtxMHUA402sMv8tO49e@sUvWRXtXAHm5Nt41LGI6tvXlNEPdoLqEGhVjcVFFRQVKcZ/@6ZaI8iDSMSWWkFqQmsJjLL6sXyL7d2tSyrls8@ubxKPs/EMMByxBO48ZpubZYk1DEI/CNonP19KuycQHLd6gqFWVzVGGooq@tSsDz6eZxJUd4J49bjjff9Mo1N4uqkdHtSSWpeR3rgo8t@vCsbmclfQWPKeNaHcf5MfRLRdI31oQMi1vggPVX7Au6j2KvaceJUjbobLwHyc1x70feIjuw1xD6kIRSCzSqdk6kjUR04qUdfETrL4FLqJnunVgzVefEO1Dws0n6LG@OhGAXACiq4mis9R6iZz4Lb2kuf7BD4UurbjsQPnCcQ5MBbtT69roDf6GuHpvk9XgCYqs@RLk7I@8tQiXo0cYbnwSsgCdJpdfwyfHe3Pgtr@NQNrDVhxMKjLKDK0r8W7qj7Cdpqpj5aoBU7lmWtrvY4LLheU/muXR@6FrwYZjApBjcAQown59aa510jrAicM8uDwG/@OdcEPxquqg16VSjxgxi@qZtkxUyNuNa4tlwrykzMZ7NqZp1Iinb29kQSwADfAooIDFDqwwbOjJGDDoi6QfuCmS8uq35Ja40P8TRSje67u1vAiDlmp6piUrgzS8FFPDDiHk@zaCDABNYT1IUqUHA6sYtlNp9umfDvmISn8kn66RT2iVC6ViF8zJgCbPPlpA2ktHdSn0IFWwCw7xdgOpn0aCIKvgS@WO0rsB0O6HkRbzFImbBgyZvCJl8Z@DLOOlVnmBcXOn@HGYeW3g559YvWQWdsgCZucNStwTI/qH4OIr1lRmrmed/L2VxCGykqvsASvvvuldzd3FEL2GfKBNytOk5hw7BUrS9GM6qHs3BtP2fle39x5hNRCSHE6pF@4yqWVylzDH2wkJd2RzcSS6s@zLtIKOQcCVa0JzESNLts5iwj@c4SE8i4WNVZLmbJoHl@ExQ5umr@nDnnALX23YlWR21Ed5YUUbQmeKHHkkVAhBau61SCQOqJZOginxffVMNvFkmlSIrZSoOKGzd1cYsrQU9nf6Qppcwyv5ERQyFUHU4PVMM1DeJv1Gs07jvXx67vi@Me1fqSsjVE0lE@Bc39sJmGTCG6IfvyagMXfwpH/TVtuCBNlhll4jMl2VNVAmLTFFJhPEsWiXLPIGA/CbINzlB1uzVcHTypgaxaMyHUtFGNYkIsOnWws47bgPyIrAJTlZwfav/sgXx7wXGKfbftkOLkbufNdAKAm0vzsCdGTuVgmsQXWIZJbOyCn9SZ9YbqjuXXDoKpq@dNsLTu5lVL7efIS3dSTUzymYQhWZdhYH1EvvQQD4OzV0S0x0YybWG45ayxWOIROua8fN4mLX@pAGvb@pxvDbOZBVU7s7kZxWozHPmEF3BRAI6zdQY04kkoZH8gV1aDsRPC/BYi2e5@KE7HQxA82S4wpLsY2IGvZWxaZZ5TNvsDdnmwDNrdaDFaXAssEG8v3SzO2GdN2AlP6/0ECd8NHH7FQYWcvaiYj10RcivMqWhUuZZMYYEq4PSRNdAH6ypg9Aoh8rDL27uICWgOEMewFkQkG14SUwVIVhFl3pPArK9K5fOtE9xgPQqyO92QNQzQfB26KJQvke0Vm7E3QargYiMInUc@xoR0RT9zTqc515XII7yAD/IfnsztFPJv5I20pL3v@uzc6x1UxHyM787cb2l1lQRffJvU4uXachoeQbt/vXGgmbrET@2kjW9qmDLVo/iRRgRtKsWgRGlfKEQZZ9GgsAum4o@cD0eBNXaZPnJwZAEiY0hbVJhSMBet4E3ngEACYKw0zNCIyWcDuhsLfg16qHB49xlYkmrCNe8OON01GyLmIZbKBWffZ/gcWay37XBaUBr7/VfN6WtZvWg64k2dEt4vO37P0dfp9NuBJSOkFPcdl8N5VTfj8e0KmYOXXF8Hd2F2hQXSPOPncha0pb3J@5sdN4h2CR421ouPIgLlCqrw2ZILVJr48mmXBNt9pDHqwd2rSwyOCELm4jXFftthtqK2jOdRKyEfqydSpjyHxn34EX@vDaNsigzMLxX7MEaK@Rs@uCQhCEyLNWyubH3N6dE1CohN0tZ7uooUq/ElRcMBOEskQZ@GJZOUMJlDbbpkKOWUEZOMidyanwEOhJokf3WFp3FZfzsTfU2A33rr@0PZfC/KDV4OrHh@DotcQfQU4x1kOxGD7d5nWJ3eqihV1/Hlp4mTQ8/9WUN4OQHb0TDKl@lvv6KK7XFflR/iG9VsDoAbZLofPUMY78p4e7VaUxb@Oji38SrdkZnxUucghw87VFGczlM4p0JsE/kPz4xvG8L4/nKr1KQ@tuA@hEVhP0B4xDh25w767m0fnp3O26hG2OS1AXTVAdyQ6neXOS/7qXn0ibf5VLaXINdf/MOU0HCu9Xd6IqzC1hWkyJC8rxbt3z320cHx4g2nsrFewEE2q4aKG6guZyUu9CvER1g39b19z85CM/gLnoP4y0kfDUVPQOE7EaQ1NAgyPTy@ft/Q0eqT2rHEBA5KJIVWS6YzZSd8AV54g21ScLLAYI9qTJdi@R65AkImZzYq64cCkUGTV7jcy3F6NTM89RvnOONBWdyG8i6blznAJbyiKJ0@En1BO/VjhMnMkdMb5kseekg2Db9xrRjMPVLPkwCyQ@4vlFClALN5SIsv9fOmXq2Z2lMVXsZQED7FSsb7q80LZU9A9jrchTfKRHBz6E3SzlN7bMpXz8YCSNwUJbFDyA8CYh/O8knecTR49@smD@UIyII7Wtc1PJN9tNLGrN@eDxCsDB72tqqhTu9OnmXXbnQi@dyhxkhgtIE6tx9ZvneU4JBu58QYOQBbelgSOirOg1wbFoP35KOzdJ8yiaf05@LvpC/HPLXbibbknHsd5b1z@JoTL//C2YmQCjhX2g0G5Jl5ZDFfjxOfSOPw@tIS1QDnZMWgf7XIfoOQttmwY@Vv7GxSW3qPyumQzKf70lm5kUvAdmRcc81jYG6FiGGHcmhE3GQQ/3SMdiBcrtjjURssak3MpwR8uSwIhFj59qEIrsJRTk4zFZwjqDR7FnMWT@MEc@6xO7vYPhzgRtnXeH65vb4WjpvrUYm9h92n5sMuDuOaqC1eQk6p2Wz0fUYf9tqlOEvxIPxFf1593WRAqJs1SaaL5X686kwq@kBsgwOKYKUbv52NpJmprP@EPMcOlDMIukDB7f3JCFmKlZsHPGXGQhrDKucTWly4veOGK1Hpc2FzDhtfRcBSdhvt1KWh4yzBt4SkrlwecSyxD7MgGNIS/Bc5rwxfVjv8saqyGTPJsAEpL2fm0aX6a0z3fUkoudmDW7bD8qhlyHi8gaPQLUb4nKoqNAB1uVWpsua3ucS11J2oS4NiV@0r4X3ws15JLu3WV7tMu3/3@3nFPobXTXJnwju5EENVCpB1ZoV8YxTn6G90qSFhhPcQivkdWMSd6lzpFGID0TlJHk@wGYhM/uySYQkfoRhQMOhwt7x091TZD/ctvjQgvkEsEKBLURkVbpj2nsGdFrzdV4BXc9SghQg0ABTnB0GhW3CYnR115S71WEE/4O2A4NMUpOD9kiLCBaQmIfPiOiZnldIvnBFGA1d2Gcsof30k1p5nfePJR@cd6Bo2PDd942C1kT6MP2GIgIzpOXqcIJW3xt8cX90EXQPEo@9oYpZttZOh4vQL@XbhcX@UEPwKwEQt67hqHwOp1vPaXVQKY40xscQTvV2nqlaJHx7mcsJoRPAFQXV/d9UUdkRgoV/A0NIg1Y0tfw5WQcsM1quWW2BaDafzvP2O8j2/ragU6niN@mhSI30LR7U3npFKajXghD3UIF1hLLtJV9uY@UuPAhqHudqL1AZCLKc8barLD8@ybPMqqo8ve97HF1lqGksq1UP3hX1zSLsvk7ZrUsFZuTJ2niQK2ghFiXjyBAAn71O8EWXn7WymXUvkixKlMrjMmt0/DNeyLC9eJ64phI5BAfrgYIDTQrWWNRM7yjCCn@xwclipSM/S30hOPMLKMugZChEBV154sRaXt@oSg6eYCjDqzAmh3Q0vTDsnxtAmgaA1@b2bwTPn1p2f89BHrMeOLI8Ut2LCVyG06JqTb/LBfISubVGOh0bLbZX6y7bwvj0cI/RdN29CPe8XIftaA4q3b9SWPkL7cYcBA5cTmk9KI3vTuy02csV67WJgFb@nDKqxBEZEhTvjcy/S0dJdyhCUbt8RCAquVrUChKmc1HkovylbxtsaYAZfV9HlIMQdCpkrAJOE6/d2DYVdWviUIA3wKNI6IqmSo@8uPoHTRv3jY6aPUlzJqYTngjDk43G0eyhsYkqh4vtZPqkeJ2dHaJH5qVEhBC7Ot3VDN5fgCRpni2BGFyeru@czsT@@b7Uwu@/Y3GVFzwQEt2kml0TzFpeqySMrFfoL4dCiea2lDK2Gb/hoLvli1JjuqTWyUBWdhCLw0w2tFhUtVnGeYWx@39w3ET/no/RVu56cnbnfw7c9J/E9UBBqKNRpWFcifY1p0wpUBrD6G1G5rEwqI9z@@orYrXyTVmET3WFF6efCgyiDXTHVrnQBZtYvErp635NzqoDqh6P0MMAiACjBqonxqzWovn97czwH2ThWm0eSQAHhoaVcTCR6Vt1rTOSHNPXNxQC5XeTZl8J@QftLPT3ly0K6WGIfSz@0vBCUmjFnGwyew6cWYdktzq0LdsbVKoh2RnuD9n4LvMe1I3VF1kQRb@wYpZM15XJB2LNMHGGMPPzMufnz0hCeVXmzFK9x/@KGY26ofCGzbMHpnIRSJh7KK9x5D7Lfh5fA5PsrxBCniLJ3vI@7@tLtVq6YCiFkTtjUljaXxIHfF6ZyBZTi2tp5XknKgtjWjVzaQCQL9EuvGZBVHq0bsZ1mulz0BeQyaUsrfprowi@sbQf6OJJFcWTnzgyjiQAu1xf6R6PPDZCXg8FQAkJXbfD6px4U3JlREgyWZc981zqtnWoOe8xFv@83KXiptqogty0IVsG4v3b5fnntjpWR6X@xyUMtVQNbadcPBn94Q75MJYXHO9S0iVH3YxItYgQE0zL0A1@GRfR2HgHMUJH5aalxlbdIKaFcRKkBj9vcSzTH6KBM@XbPlfrMdso20adb59CXAencOeVs6YzalLlrGqmNPkD3esgOdCrUEkEGmfnZPgYwOQTeMdtMtGF2HWwdSij1tnQYf73L68NxpwbGip69iS8u33fRS7E7xeM@EWkIiuOgCuwbUxrVL7UsC23/GpUCrqPVtIAJCIxaW91VUIctwwu70m82mM6WUlJpdzs8hBvaeKBqPGFrqnGAbo4cAaj6sq/n5kk@6ormZYmd9C7oYK/Jb7yxfS/CymQTmD@KiyNMfuKA9Z5sedgq6slu3MvsnTv6fhzv06Saz2MSPC8IugL0PonLbVifU1GbUHJEq62u3aHMAosSJOBWlbW470SgoZWtfK3KD@6kUgn1RxbgD8thQIyniixyoJoalcfu36H1IwtLW3uzFrXvL5JWKW7Ho@rCiA7Z@gAiw9K0bIWpUSy9N63e1XKg7sjWLAp9SRxlWhdeNnPpxpMj2eaoadzOdz4QnbaBSWUCqWtTE98D6ZcUATY@kV2aReOMuu74hbIKtA3hkLrMyyqsOs6J/XtJ7wWNuBHCRRdYSwTm@vHycDuR7Jd@Jzdq7hT28snNTWrzBnVVZRQSMJl32LmR6LH3NQdCl1vqNaUmjBvWtPRfsTI@5qvozBZQX0v9zhqA26IKm2gCE1kk5ON3h6logOyjryqpujtsd62RPFAzA5d4zEjSofPiArqPjMW7qU/S3aatvj7i@sW6muiFSjfSadapQ7RN75gtQSqqkFtGEGcd5l2dOmq7Gh1GJd8ZTfClu6VdvcqnX7J9ThQVFxxiOccXhbVEgGkYv/saSjZgY1txdqfXlCELHtJMhbXlJWjfIELLRPGYHv6im@cqLtESAg8xqELb6tSD3Heh3ybL3/x7sZdpI2wjdXyPP5Z28sXGtkU0GPx6@FRnhglsw9SdozAfEK5eT8fKOxKXXuINP6th/OrFdI3linBurp/fp4CA9Iq4npg2gw4P90dVviqbOzbA6pfaQCPcMl7AFQ9jh9A6otsPHyvX8v7Cxk5pElglxpCO3kajPlMN8lqmXp2gfgec4CHnroOP/gGwj8QRdXmBlcBdaCxROuQMKy55XesWJbgxQktnZq9mu@Rboo6shlVZktxP4Aolw3JW2X996/Xy46nSu@XLE68ZOl3ft3AFhl/4w/o8UU34umegRISlroaY88GnnAGLURwpCokRXQ@ZGHv6wxoarzovAlo7PLXM0mTGNQ1vxNdCm0Nk0m20fX6oDqAA6lxEKiWHi7XpRBCLNLXvLjBFN7bjbTsPZgJ1QBRBrPPwjvGmzYVEc5LqlfRr8uAjOKdkKyE80Qc@beD8PBGN/BBZnkMq1ohp67EsLkxP2@UjrAxbDgt3ar5ii/92ChrwCPNFABk31g/sN5AovoaH9h9ohPF44PwU0jKxBViCHz7tRpKpM3YQk5/RpKKxXQyjzhg80PrqY7/S6GGgwuujAW4bgZyQl1i3bZj1qOUqYfUXL9q6fw0SDWUY94HvZuyKtnuRX8gLVqpUxEeMH8127K0/b/kU4bjWWiPybow2JFUyPB8WBbwqy@axpPCkkN9sdtHxinf6uZaL8I0D0v3kHGKcVN7zJpOxojZxu6eOiiTJ1ODxdrC8w5mefMomw1h4H8OBytAVbKlz7nGf0ILfvZvP4potJNqFz3NCge5uoUvt4ccy0PtRuKVozKiB4AejxD4kHMoJXil25@49ti7XpgHTeQAwPBDehQ7QEH/1LYQAvkPlykk8ckTI3qxsoyS6qfmoPEK6yJjrNmr6hb1VwL33xMaObP0Qr1WmDhm1cR2ImpBkpl130ErWmxEbh008Mbkv9tsndq1QCjOL4RfEIkTs5MRp@eowX8gSCjwt7vS4@Zr4CPAiyd63XwNd6AG@7/YfYYvX3hDSdfyA7cM0S1wgiyeDua7Yy01wKw0GNdlDLCCMVNWEA07D9dLLQsuH3fU77Tm3AZ/KktlUtyez1WiYXVFHvlblHC5Xs6QJun0FFCMoT6s3srSET29QtSxqYzbSW1ythScKyfkYwzuiVgQMIq847lg0gjBWm0i85xri01MmetHTAkXN0IKFZ77@ktVGe@XqHAQfgTeQXHTmt@QHrC6@cS5DR6Q6kmMoHhIRiyrKIxv88LwTUbOiNUHA9EUuGyU6Uk2g4cGt2Nwc6oRpJKV7eDdYtMZ2LPsxnTG1bSwBGuj7SWqD/G1ggEKoyZdO2OwMoDG6ngO1RhAmNufMGc4XFg8nnGhlbWLQOd1R5UvUBwA@Yvr1CFOBD/OJ3Q/uaCpfuGA8tLaXI7y9Sx5DoA/XN49hnCyRuZlmCU4PoCjK1nkR5xTaLDXj2TjH8dW2kmwJr221CO2DrNuYb@XOGvK6ZaJXWJeqoFePwlvj4Dp@X6Cw1a@nd9LFkqJoKFdhoWCSnoQQPxwwIbazNu4rB5R03B@XQ2sHFA6bPoS5/vRbBSdg0hvPya8dNlgiLz@nZWdiDz6DkzsTquqGTPUcoarrTXkH/tzTElTXtH9lIIIWGHBhSwUSKxBwBy20Z@W4IhlPbehB2KP64Q1CJp9En/LzmdUPzYmEIlEtu9KQiEsrSWBql81IEOUlaRuP9u3YReMG@U2MWVWdY8neajWclOB4dunSkJryfVpF@sS93O0j/HSg8pFz832npPsTPKNAC3AFY2/Y8UlgHPhA1uB2mB5eQNAPM57plyG5u1ynAN42aPfRqWPcndbci08RpLfpBZ7MgXC0TvfQ12zVIgrRpHTbfwCNX63jeL15edzxr5ain2hoggO3O36YTaWL1DC@ubWGK33kaKDSkitPNtgEt9mI7k8KIIz09QoTA6n6kwrBj99/zeeh@y2OlgxHf6u6cZjX32IcfdJjSLPfouW37F8W7d1F/57/OdmNc7YsPw3SX48f6R/ZH/Gff/4aLUv2GLRZ/8fx548fMIoQyG9Rn/7rzV@Xsa3WP@Lf/2f/@5/PNIKS8D9no7b946dF9bzEf8uH@bfqt6r/7f9a8B//bfzxe7mu4/I3ECyqZf1rUa3lFv/18QZsH2/KaFkzkCCwnHilaBrhBEGSLyLPqYiMUDiBKQTCKXCODjBB8JhMkRhJsRcEvfA0I0goieEEidGEzPGMSlEiRhAwKuYsS9MqWf@6nuvvv/63f6KxzW1bxX@ds2nLlvXfuDxvhzHrf4IyPKAs6/zH8Zesf5Cs@uLH79ua/7/k73/@Z1D/jOlf2CZD22bJWg398p9b/fdfix9t1MVp9Nv5t/8cLH/7CdGSrX@cf/4/P/@WB/Dlx0/X/ng2ekA7/wna3/@G/QP4@@9j9ECy/v6X37NznaPlGQxztGY/B3Eb3Vn6@19@@72Lij5b/znK1sfJ3//xt19/yX8Uzyd@/eX68ez1j19/SX68fv3lSH/83m3/tHkeyqrNfvu3O08Md9b/HFV//tfhXX/@@T@gZ7dfEuAH9Px1P/I/jvTZ9tn379X/Yfdblf/vrap/RfbYPZnQPd/@Jf13gL/88l9Lfm77y/zjPWz9ms1//F@r6z//5Ub9Lzd@2qZ/r/7xo4vOP@a/VmvWLX/8@Zcmu/4L4vPv0D9@Gj5RdlX/R/r/b/XT8O@vx7Pl7@c/fvyR/OXnx59Yf/3lP3P/pwfXY/EE8K@z@vWXca76Z/SXfxv/JW@3pfxhz1v256//mvzp27J1/x8El7/uUfvk1x9/Prn/H/8L "Python 3.8 (pre-release) – Try It Online") with `5` first words+`['palest','extras','orates']` for shorter amount of time (with words-list lzma-compressed). At every step we choose such word from the list of words left, as even the worst answer form Player 1 gives us the most of information over all worst cases. We need `~11.77` bits of information. Output is word, number of tries to get set of letters, number of words with such set. The maximum: ``` 1 muting answer:1 variants left:1149 2 charts answer:4 variants left: 133 3 alerts answer:5 variants left: 32 4 averts answer:5 variants left: 19 5 prates answer:5 variants left: 16 6 rawest answer:5 variants left: 13 7 skater answer:5 variants left: 10 8 stared answer:5 variants left: 7 9 barest answer:5 variants left: 5 10 faster answer:5 variants left: 3 11 ersatz answer:5 variants left: 2 12 extras answer:5 variants left: 1 orates 12 1 ``` (compared with "palest") ``` 1 muting answer:1 variants left:1149 2 charts answer:3 variants left: 344 3 dactyl answer:3 variants left: 102 4 adepts answer:5 variants left: 18 5 basted answer:4 variants left: 11 6 palest answer:6 variants left: 6 ``` [Answer] # Haskell, haven't bothered to golf, 14 If I can get down to 13, I'll try to golf this, but I don't have time right now: ``` {-# LANGUAGE TemplateHaskell #-} module Main where import Control.Monad.State.Lazy import Control.Lens import Data.List (intersect) import System.Environment import Text.Printf data World = World { _wDictionary :: [String] , _wAnswer :: String , _wScore :: Int } makeLenses ''World main :: IO () main = do [answer] <- getArgs dictionary <- fmap lines getContents let score = evalState solve $ World dictionary answer 0 putStrLn $ printf "Correctly guessed answer %s in %d attempts" answer score solve :: State World Int solve = do word <- uses wDictionary head result <- guess word if result == 6 then use wScore else do wDictionary %= filter ((== result) . length . intersect word) solve guess :: String -> State World Int guess word = do wScore += 1 uses wAnswer $ length . intersect word ``` Words scoring 14 are "streak", "skater", and "takers." I can't add TIO because it doesn't have the lens package. ]
[Question] [ We have many challenges based on base 10, base 2, base 36, or [even base -10](https://codegolf.stackexchange.com/q/105992/60043), but what about all the other rational bases? # Task Given an integer in base 10 and a rational base, return the integer in that base (as an array, string, etc.). # Process It's difficult to imagine a rational base, so let's visualize it using [Exploding Dots](http://gdaymath.com/courses/exploding-dots/): Consider this animation, expressing 17 in base 3: [![enter image description here](https://i.stack.imgur.com/K3TLC.gifv)](https://i.stack.imgur.com/K3TLC.gifv) Each dot represents a unit, and boxes represent digits: the rightmost box is the one's place, the middle box is the 3^1 place, and the leftmost box is the 3^2 place. We can begin with 17 dots at the one's place. However, this is base 3, so the ones place has to be less than 3. Therefore, we "explode" 3 dots and create a dot on the box to the left. We repeat this until we end up with a stable position with no explodable dots (i.e. 3 dots in the same box). So 17 in base 10 is 122 in base 3. --- A fractional base is analogous to exploding some number of dots to more than one dots. Base 3/2 would be exploding 3 dots to create 2. Expressing 17 in base 3/2: [![enter image description here](https://i.stack.imgur.com/krcd7.gifv)](https://i.stack.imgur.com/krcd7.gifv) So 17 in base 10 is 21012 in base 3/2. --- Negative bases work similarly, but we must keep track of signs (using so-called anti-dots, equal to -1; represented by an open circle). Expressing 17 in base -3: [![enter image description here](https://i.stack.imgur.com/Egxs5.gifv)](https://i.stack.imgur.com/Egxs5.gifv) **Note, there are extra explosions to make the sign of all the boxes the same (ignoring zeros).** Thus, 17 in base 10 is 212 in base -3. Negative rational bases work similarly, in a combination of the above two cases. # Rules * No standard loopholes. * The sign of each "digit" in the output must be the same (or zero). * The absolute value of all digits must be less than the absolute value of the numerator of the base. * You may assume that the absolute value of the base is greater than 1. * You may assume that a rational base is in its lowest reduced form. * You may take the numerator and the denominator of the base separately in the input. * If a number has multiple representations, you may output any one of them. (e.g. 12 in base 10 can be `{-2, -8}` and `{1, 9, 2}` in base -10) # Test cases: Format: `{in, base} -> result` ``` {7, 4/3} -> {3, 3} {-42, -2} -> {1, 0, 1, 0, 1, 0} {-112, -7/3} -> {-6, -5, 0, -1, 0} {1234, 9/2} -> {2, 3, 6, 4, 1} {60043, -37/3} -> {-33, -14, -22, -8} ``` Since some inputs may have multiple representations, I recommend testing the output using [this Mathematica snippet on TIO.](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvxMGtKD/XJTM9s6Q4motLQ0shKLUgJzE5VaE8syRDoTK/tEghBSyroKXJVW2oo2Cpo2BUy6WDQ21SYnEqSKWuoQEXV@z//wA) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so submissions with shortest byte counts in each language win! --- For more information on exploding dots, visit [the global math project website](https://www.theglobalmathproject.org/)! They have a bunch of cool mathy stuff! [Answer] # [Python 2](https://docs.python.org/2/), 42 39 bytes ``` n,a,b=input() while n:print n%a;n=n/a*b ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P08nUSfJNjOvoLREQ5OrPCMzJ1Uhz6qgKDOvRCFPNdE6zzZPP1Er6f9/MwMDE2MdBV1jcx0FYwA "Python 2 – Try It Online") Thanks to @xnor for finding the shorter form. Obsolete version (42 bytes): ``` f=lambda n,a,b:n and[n%a]+f(n/a*b,a,b)or[] ``` [Try it online!](https://tio.run/##RZDBboMwEETv/oq5VMF0UTCmSRuJHvsTKAeTgGqp2JEhUqoo307XhDQXa3d2/Ga1p9/x27timrrqx/TN0cCRoWbnYNyxdi9m/9olbm3SJsrSh3o/dcH36II5jNa7AbY/@TCmQqxWK3HdEsq1viH7xFUT9E1cs7IgZMVdU4Sc8HzjXKlo2D6@ZRvu3mZHtlhUoUvCx3qBsJ3ZbGNR8XiT5yULmX4ydOxVGYMj/P02rycOZmgHVKgFku38X0vietmRcfd2WekxXvIJxdw@86JB7EXnw/1wsA5zxk7Acw4fj2AIjRQ4BevGxP9XDlWF4dwnX8stE5OmFiku7OdKImItXSK0dee@DWZsGSDl9Ac "Python 2 – Try It Online") Parameters: input, numerator (with sign) and denominator. Returns an array, lowest digit first. This just works because the division and modulo in Python follows the sign of the denominator, so we don't have to care about same signs explicitly. Test case output: ``` f(7, 4, 3) == [3, 3] f(-42, -2, 1) == [0, -1, -1, -1, -1, -1, -1] f(-112, -7, 3) == [0, -1, 0, -5, -6] f(1234, 9, 2) == [1, 4, 6, 3, 2] f(60043, -37, 3) == [-8, -22, -14, -33] ``` [Answer] # [Aheui (esotope)](https://github.com/aheui/pyaheui), 91 bytes ``` 벙수벙섞벙석 희빠챠쌳뻐삭빠빠싻싸삯라망밣밭따맣사나삮빠싸사땨 ``` [Try it online!](https://tio.run/##S8xILc38///1pplvOmaAyJZ5YHIu19u5a17vXPBm44I3PZtf757wpmktkAsS6d79pnvHm6b1r@fueb187usNi19vWPt6yobXyxe/aVrzumnGm6Z1YGU7QNypK/7/NzMwMDHm0jU25zLmAgA "Aheui (esotope) – Try It Online") Takes `integer`, `numerator of base`, and `denominator of base`. Due to the limitation of the TIO interpreter, each input must end with a newline. Implementation of [@Bubbler's Python 2 answer](https://codegolf.stackexchange.com/a/157232/60043). Luckily, this Aheui interpreter is written in Python, so we can use the same trick. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes ``` [D_#²‰`,³* ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/2iVe@dCmRw0bEnQObdb6/9/MwMDEmEvX2JzLGAA "05AB1E – Try It Online") Takes `integer`, `numerator of base` and `denominator of base` like all answers. Since 05AB1E interpreter is written in Python(?), Bubbler's Python 2 answer trick can be used in 05AB1E too. **Explanation** ``` [D_#²‰`,³* [ Infinite Loop D_# If the number is 0, exit loop (implicit input in the first iteration) ² Get the numerator of base ‰ Divmod ` Push all elements into the stack , Print the remainder ³ Get the denominator of base * Multiply it. ``` So the program works roughly the same as this Python code: ``` i1, i2, i3 = input() stack = [] while 1: stack = (stack or [i1]) stack += [stack[-1]] if not stack[-1]: break stack += [i2] stack = stack[:-2] + [divmod(stack[-2], stack[-1])] stack = stack[:-1] + list(stack[-1]) print stack[-1] stack = stack[:-1] stack += [i3] stack = stack[:-2] + [stack[-2] * stack[-1]] ``` 11 > 10 Thanks Neil ]
[Question] [ **Standard ML** (or golfier: SML) is a general-purpose, modular, functional programming language with compile-time type checking and type inference. (from [Wikipedia](https://en.wikipedia.org/wiki/Standard_ML)) Though you almost certainly will never win a code golf challenge with SML, (ab-) using it for golfing can nevertheless be quite `fun` (<- keyword for function declaration). So without further ado ... # What tips do you have for golfing in Standard ML? Please only post tips which are somewhat unique to SML. General golfing tips belong to [Tips for golfing in all languages](https://codegolf.stackexchange.com/q/5285/56433). [Answer] # Use symbolic identifiers From [*The Definition of Standard Ml (revised)* [PDF]](http://sml-family.org/sml97-defn.pdf), Section 2.4: > > An identifier is either *alphanumeric*: any sequence of letters, > digits, primes (`'`) and underbars (`_`) starting with a letter or > prime, or *symbolic*: any non-empty sequence of the following symbols: > > > > ``` > ! % & $ # + - / : < = > ? @ \ ~ ‘ ^ | * > > ``` > > In either case, however, reserved words are excluded. This means that for > example `#` and `|` are not identifiers, but `##` and `|=|` are identifiers. > > > The important part (concerning golfing) is that you do not need white space between symbolic identifiers and alphanumeric identifiers or keywords. ### Example ``` fun f a b c=if b then a else c ``` By replacing `f` by `$` and `b` by `!`, we can save 6 bytes: ``` fun$a!c=if!then a else c ``` Note, however, that a symbolic identifier needs white space when next to other symbols. That's why we cannot replace `a` and `c` in the above example to get to the same byte count: ``` fun f$b!=if b then$else! (* syntax error because != is parsed as one token *) ``` [Answer] # [List functions](https://smlfamily.github.io/Basis/list.html#SIG:LIST.tl:VAL) Lists are the standard data structure usually used recursively with `::` constructor. Indexing must be done using `nth`. Short and maybe useful functions are * `@`: append * `hd`: head, but also try pattern matching * `tl`: all but head * `last`: tail * `take`: first n elements * `drop`: drop first n elements and return * `rev`: reverse Higher order functions: * `map`: map * `foldr`, `foldl`: fold and reverse fold * `filter`: filter * `exists`, `all`: exists, all bool cond [Answer] # Pattern matching in functions Concise way to extract the values and write cases for recursive functions. Case statements are probably too long. Extracting values: ``` fn(x,y)=>x+y (* lambda fn *) fun f x y=x+y (* curried bound function *) ``` Recursive function with base case (this basic list sum is equivalent to `foldl op+ 0`): ``` fun f(x::L)=x+f L|f _=0 ``` [Answer] # Use wildcard matching instead of explicit matching This broadly applies to any pattern matching construct with a fallthrough or wildcard: in some situations you can use the wildcard to match a pattern instead of an explicit pattern. Empty list example (with formatting for clarity): ``` fun f([]) = 0 | f(x::L) = x + f L ``` versus matching with wildcard saving a byte: ``` fun f(x::L) = x + f L | f(_) = 0 ``` ]
[Question] [ Consider the following 3x3 blocks which the [marching squares algorithm](https://en.wikipedia.org/wiki/Marching_squares) would identify for every cell (with 0-based labeled ID): ``` 0: ... ... ... 1: ... ... \.. 2: ... ... ../ 3: ... --- ... 4: ..\ ... ... 5: /.. ... ../ 6: .|. .|. .|. 7: /.. ... ... 8: /.. ... ... 9: .|. .|. .|. 10: ..\ ... \.. 11: ..\ ... ... 12: ... --- ... 13: ... ... ../ 14: ... ... \.. 15: ... ... ... ``` The goal of this challenge is given a 2D matrix of block ID's, draw the full contour plot by tiling these smaller cells together. Note that there are some repeated cases (ex.: 0 and 15 visually are the same) ## Input Your program/function should take as input a 2D rectangular matrix of integers in the range `[0+a,15+a]` (where `a` is an arbitrary integer shift of your choice; this allows you to use zero-based indexing or 1-based indexing for the blocks). This may be from any source desired (stdin, function parameter, etc.). ## Output Your program/function should output a single string representing the full contour plot. There should be no extra leading/trailing whitespace, but a single trailing newline is allowed. There should be no separation between adjacent blocks vertically or horizontally. Note that you do not have to do any kind of special treatment for blocks which map to a "saddle"; just draw the block with the given ID as-is. The output may be to any sink desired (stdout, return value, etc.) ## Examples All examples below use 0-based block ID's. ``` case 1: 2 1 4 8 ...... ...... ../\.. ..\/.. ...... ...... case 2: 15 13 12 14 15 13 8 0 4 14 11 1 0 2 7 15 11 3 7 15 ............... ......---...... ...../...\..... .../.......\... ............... ../.........\.. ..\........./.. ............... ...\......./... .....\.../..... ......---...... ............... case 3: 12 12 12 8 4 0 0 0 0 2 0 0 0 2 7 0 2 3 7 15 ........./....\ ---------...... ............... ............... ............... ............../ ............/.. ............... .........../... ........./..... ......---...... ...../......... case 4: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ............ .........--- ...\..../... ..\/...|./.. .......|.... ...../.|.... /...|...\..\ ....|....... ....|.\..... ............ ---......... ...../\..... case 5: 0 0 0 0 6 15 15 0 0 0 0 6 15 15 0 0 0 0 6 15 15 0 0 0 2 7 15 15 0 0 2 5 14 15 15 0 2 5 8 4 12 14 0 4 8 0 0 0 6 0 0 0 0 0 0 4 .............|....... .............|....... .............|....... .............|....... .............|....... .............|....... .............|....... .............|....... .............|....... ............/........ ..................... .........../......... ........./........... ..................... ......../../\........ ....../../....\...... ...............---... ...../../.........\.. .....\/............|. ...................|. ...................|. ....................\ ..................... ..................... ``` ## Scoring This is code golf; shortest code in bytes wins. Standard loopholes apply. [Answer] # Mathematica, ~~353~~ 326 bytes ``` s=Table[".",3,3];z=Reverse;l@0=l@15=s;y=s;y[[3,1]]="\\";l@1=l@14=y;y=s;y[[3,3]]="/";l@2=l@13=y;y=s;y[[2,All]]="-";l@3=l@12=y;y=l@4=l@11=z/@z@l@1;y[[3,1]]="\\";l@10=y;y=s;y[[All,2]]="|";l@6=l@9=y;y=l@7=l@8=z/@z@l@2;y[[3,3]]="/";l@5=y;StringReplace[ToString@Grid@Map[Column,Map[StringJoin,Map[l,#,{2}],{3}],{2}],{"\n\n"->"\n"}]& ``` **input** > > [{{15, 13, 12, 14, 15}, {13, 8, 0, 4, 14}, {11, 1, 0, 2, 7}, {15, 11, > 3, 7, 15}}] > > > [Answer] ## JavaScript (ES6), 195 bytes ``` a=>a.map((r,y)=>r.map((i,x)=>[...s='76843210_'].map((_,j)=>(o[Y=y*3+j/3|0]=o[Y]||[])[x*3+j%3]='.\\/-\\/|/\\'[[0,64,256,56,4,257,146,1,68][k=s[i-8]||i]>>j&1&&k])),o=[])&&o.map(r=>r.join``).join` ` ``` ### Test cases ``` let f = a=>a.map((r,y)=>r.map((i,x)=>[...s='76843210_'].map((_,j)=>(o[Y=y*3+j/3|0]=o[Y]||[])[x*3+j%3]='.\\/-\\/|/\\'[[0,64,256,56,4,257,146,1,68][k=s[i-8]||i]>>j&1&&k])),o=[])&&o.map(r=>r.join``).join` ` console.log(f([ [ 2, 1 ], [ 4, 8 ] ])); console.log(f([ [ 15, 13, 12, 14, 15 ], [ 13, 8, 0, 4, 14 ], [ 11, 1, 0, 2, 7 ], [ 15, 11, 3, 7, 15 ] ])); console.log(f([ [ 12, 12, 12, 8, 4 ], [ 0, 0, 0, 0, 2 ], [ 0, 0, 0, 2, 7 ], [ 0, 2, 3, 7, 15 ] ])); console.log(f([ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8, 9, 10, 11 ], [ 12, 13, 14, 15 ] ])); console.log(f([ [ 0, 0, 0, 0, 6, 15, 15 ], [ 0, 0, 0, 0, 6, 15, 15 ], [ 0, 0, 0, 0, 6, 15, 15 ], [ 0, 0, 0, 2, 7, 15, 15 ], [ 0, 0, 2, 5, 14, 15, 15 ], [ 0, 2, 5, 8, 4, 12, 14 ], [ 0, 4, 8, 0, 0, 0, 6 ], [ 0, 0, 0, 0, 0, 0, 4 ] ])); ``` [Answer] ## Mathematica, 173 bytes ``` StringRiffle[ArrayFlatten[ReplacePart[Table[".",16,3,3],{{2|11|15,3,1}|{5|11|12,1,3}->"\\",{3|6|14,3,3}|{6|8|9,1,1}->"/",{4|13,2,_}->"-",{7|10,_,2}->"|"}][[#]]&/@#],"\n",""]& ``` [Try it at the Wolfram sandbox!](https://sandbox.open.wolframcloud.com/) The "`\n`" should be replaced by an actual newline. The input is 1-indexed — for example, the third test case becomes `{{13,13,13,9,5},{1,1,1,1,3},{1,1,1,3,8},{1,3,4,8,16}}`. The output is a string. The idea is basically the same as [Jenny\_mathy's answer](https://codegolf.stackexchange.com/a/128334/66104) — make the sixteen squares by taking a 3x3 grid of `"."`s and replacing some of the characters, then stitch the squares together — but using slightly shorter functions to do it. (Thanks to [alephalpha](https://codegolf.stackexchange.com/a/128275/66104) for reminding me that `ArrayFlatten` exists!) It's possible that this can be done in fewer bytes by making the squares cleverly instead of basically hardcoding them, but that would require much more effort… [Answer] # [Retina](https://github.com/m-ender/retina), 165 bytes ``` T`d`L`1\d |\bB\B .+ X$&¶Y$&¶Z$& %{`[XYZ]$ ([XYZ])[69] .|.$1 X[^4-B] ...X X[4AB] ..\X X[578] /..X Y[^369C] ...Y Y[3C] ---Y Z[03478BCF] ...Z Z[1AE] \..Z Z[25D] ../Z ``` [Try it online!](https://tio.run/##Jco9DoJAEAXgfk4xBRKNYXHY5a8E1MrSgv2BoMHCxsLYybk8gBfDWWwm33vznrfX/XGZ5/MwDqeB3Ag4uWvtagCxhTYIvx/tjwlCWL0H22rTBQDrBRublR2ISQQEre1VVHMSouWgqsXOO82LDmLfa9vLrGyWleYkmVEUaTB2J1Ve1M1x@RkuqDp04P5O0r3vYzPPlCJJpARJIaXALnCHbAVESOwEc/ArQok5b34 "Retina – Try It Online") Link includes second example. Explanation: The first two stages convert from decimal to hexadecimal, allowing the spaces to be deleted. The third stage then triplicates each line, giving each new line a separate marker. These markers then traverse the hex digits, converting them into the contour plot as they go, until they reach the end of the line, at which point they are deleted. [Answer] # [Python 2](https://docs.python.org/2/), 247 bytes ``` J='...' print'\n'.join(map(''.join,sum([[sum([f[i*3:][:3]for i in j],[])for f in map(list,[J*4+'..\\/...|./../...|...\\..\\'+J*4,J*3+'---.......|........|.......---'+J*3,'...\\..../......../.|........|.\\'+J*3+'./\\.....'])]for j in input()],[]))) ``` [Try it online!](https://tio.run/##XY7PDoIwDMbvPgW3MijVMfBf4gvwCmMHL8QRGQviwcR3x455MC5Z82v79Wv9a76NrlyW5gJEBBs/WTdD64D60bp0uPoUIuPjOaRar7HTNlNno8/KdOOU2MS6pDeojQhpF9IwebePGXWTVTmbt@2WN7yJY4RQCh9yVmCTqRyKoqD43vQH3ApChfAdjDYU4UceDdmMtlFGYMR6Zh/uss4/51SsxwqxLFrvUGKJiisV1rjHA9MRTyi5IZlliVKhrFDWxnwA "Python 2 – Try It Online") -1 byte thanks to LeakyNun [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~106~~ 89 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` žj}² ³ ē0=?² {ā;{"⁰9═‼pnk№Ο|╚φ;“2─6nwEX .9*3n²Xƨ.ƨ-¹╬-}²X"č7_#‘3n}² /33³\13³\31³/11žj}┼}O ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTdFaiU3RCVCMiUyMCVCMyUwQSV1MDExMzAlM0QlM0YlQjIlMEEldTIxOTIlN0IldTAxMDElM0IlN0IlMjIldTIwNzA5JXUyNTUwJXUyMDNDcG5rJXUyMTE2JXUwMzlGJTdDJXUyNTVBJXUwM0M2JTNCJXUyMDFDMiV1MjUwMDZud0VYJTIwLjkqM24lQjJYJXUwMUE4LiV1MDFBOC0lQjkldTI1NkMtJTdEJUIyWCUyMiV1MDEwRDdfJTIzJXUyMDE4M24lN0QlQjIlMjAvMzMlQjMlNUMxMyVCMyU1QzMxJUIzLzExJXUwMTdFaiU3RCV1MjUzQyU3RE8_,inputs=JTVCJTVCMCUyQzAlMkMwJTJDMCUyQzYlMkMxNSUyQzE1JTVEJTJDJTVCMCUyQzAlMkMwJTJDMCUyQzYlMkMxNSUyQzE1JTVEJTJDJTVCMCUyQzAlMkMwJTJDMCUyQzYlMkMxNSUyQzE1JTVEJTJDJTVCMCUyQzAlMkMwJTJDMiUyQzclMkMxNSUyQzE1JTVEJTJDJTVCMCUyQzAlMkMyJTJDNSUyQzE0JTJDMTUlMkMxNSU1RCUyQyU1QjAlMkMyJTJDNSUyQzglMkM0JTJDMTIlMkMxNCU1RCUyQyU1QjAlMkM0JTJDOCUyQzAlMkMwJTJDMCUyQzYlNUQlMkMlNUIwJTJDMCUyQzAlMkMwJTJDMCUyQzAlMkM0JTVEJTVE) (that has an extra byte `→` for ease of input. This otherwise would expect the array already on stack) [Answer] # Python 2, ~~196~~ ~~191~~ ~~181~~ 176 bytes [Try it online!](https://tio.run/##jVDLTsMwELz7KzZCyHZJH@skJRT1UFVCKodeOIYcQppAWnAiJxwq8e9lHTc8JA5kI2v2MbNjN8fupdbqdLpfcj7Z15W@3S75o3aYlcvX7O1pl8FmsRVbcU/BH6cf4wlP1lOcj1U6EutLnMuyNrCGSsNb1oja7Hxee3vMHwqvxGfMVk8UGb5g1aPcy72dVz0csPQOXMokH91cBaP9Ik0WQWq1cqtletk9wWTmo6/SPje2tZGMXXRF20GetUXL2K4oafeh2OhuZUx2FJVu5IIBfabo3o2GJKl0J3IJ3/qTtjNVI@SkbV6rTnDgMoWvHaQwNOhBZOqW3AntQ3uWbgxpAl@TB@7r79KPZvtntRS/zLZS/hhjdwJ94JwrQBZCTEjaouqLGAEGgNQLASNGOIYZEA4ZIiBhBdfMTiEEcE0zAz9wfAXujyFkM3ChzshS7fmbGPbEGYlThxxFMKe5GG4AqYjM6gXOz0CJzhQXc7B@Iva/XPXLh1zRul7aFWwa2@vaB2D24vEg8iVnI3ROTqdP "Python 2 – Try It Online") A function which takes an array of arrays of ints and returns a string: ``` J=''.join;N='\n'.join f=lambda I:N(N(J(J('\/|-.'[C/16-2]*(C%16)for C in map(ord,'o!j1cSe!f1g1aAbAbAa1h1iAbAbAc!c!d!iSk1f!k'))[c*9+3*j:][:3]for c in r)for j in[0,1,2])for r in I) ``` EDIT: saved 5 bytes by assigning J,N; another 10 bytes because I forgot the input is already assumed to be an array of arrays of ints; and then another 5 bytes saved by smarter slicing... The concatenated string of all 16 3x3 cells (144 bytes, omitting linebreaks) is run-length-encoded to the 41 byte string: `o!j1cSe!f1g1aAbAbAa1h1iAbAbAc!c!d!iSk1f!k` where each RLE element `(cellType, length)` is encoded to the character `chr(32+16*cellType+length)` (it is handy that the maximum run is 15; and that `ord(' ')==32` is divisble by 16). When decoding, we take `'\/|-.'[cellType]` as the printable character. Nothing particularly clever after that... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 61 bytes ``` v•2mßklJFΘõÿ|åU‚ιØØ•6B5¡∊¶¡110bTǝ.BJ3ô3ôyèøJ»}»4ÝJð«"\./-|."‡ ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/7FHDIqPcw/Ozc7zczs04vPXw/prDS0MfNcw6t/PwjMMzgLJmTqaHFj7q6Dq07dBCQ0ODpJDjc/WcvIwPbwGiysMrDu/wOrS79tBuk8NzvQ5vOLRaKUZPX7dGT@lRw8L//6OjjXSMdQxjdaLNdAx0zIC0CZBvHhsLAA "05AB1E – Try It Online") --- The first half of the pattern can be compressed as: ``` 5 11111105 1111111125 1113335 1105 2111111125 141141145 25 ``` The second half would need to be: ``` 25 141141145 11011105 1105 1113335 1111111125 11111105 5 ``` We can just vertically mirror the first half, and insert `binary 110 (1101110)` in for the `2111111125`. --- Next we take this pattern and split on fives, then pad it with ones: ``` 1 = 111111111 2 = 111111011 3 = 111111112 4 = 111333111 5 = 110111111 6 = 211111112 7 = 141141141 8 = 211111111 9 = 141141141 A = 110111011 B = 110111111 C = 111333111 D = 111111112 E = 111111111 ``` Now we have our building blocks, the last parts just replace the matrix entries with the appropriate building blocks, zip together the rows and print to the user with replaced symbols: ``` 0 = ......... 1 = ......\.. 2 = ......../ 3 = ...---... 4 = ..\...... 5 = /......./ 6 = .|..|..|. 7 = /........ 8 = /........ 9 = .|..|..|. A = ..\...\.. B = ..\...... C = ...---... D = ......../ E = ......... ``` Can post formal operation explanation if anyone wants it, thanks. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 64 bytes ``` “¡_ḟ5⁸ṫ⁺Y"⁷ƘzƬɼ¥@TR/ṖQ½3yİ>ẎḄT¥⁹iḟQ¬Ɠl¹µŒ’ṃ“/-\|.”s3s3ṙ9ị@³ZY$€Y ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xDC@Mf7phv@qhxx8Odqx817opUetS4/diMqmNrTu45tNQhJEj/4c5pgYf2Glce2WD3cFffwx0tIYeWPmrcmQnUFnhozbHJOYd2Htp6dNKjhpkPdzYDTdTXjanRe9Qwt9i42PjhzpmWD3d3OxzaHBWp8qhpTeT///@jDU11DI11DI10DE10DE1jdaKBPAsdAx0gzwTEM9QxBPKMdMxBHKBaQx1jHXOQSqBWIx0IstABKTXQgUAjOBukCwA "Jelly – Try It Online") This uses a naive compression and could probably save many bytes with run-length encoding. **How it Works** ``` “¡_ḟ5⁸ṫ⁺Y"⁷ƘzƬɼ¥@TR/ṖQ½3yİ>ẎḄT¥⁹iḟQ¬Ɠl¹µŒ’ṃ“/-\|.”s3s3ṙ9ị@³ZY$€Y “¡_ḟ5⁸ṫ⁺Y"⁷ƘzƬɼ¥@TR/ṖQ½3yİ>ẎḄT¥⁹iḟQ¬Ɠl¹µŒ’ encodes the integer 4591777158889232952973696500124538798606476761349931038636020730336909822188496590423586252520 ṃ“/-\|.” - convert to base 5 and index into the string to get "/......../.........|..|..|...\...\....\.........---.........../......\.................\........../...---.....\....../......./.|..|..|." s3s3 - split every 9 characters into a 3x3 square submatrix ṙ9 - rotate left by 9 to line up the submatrix for 1 with index 1 ị@³ - index the input into this ZY$€Y - format ``` ]
[Question] [ Your task is to slowly calculate exponentiation, with the following steps: Given two inputs (in this example, 4 and 8), you must calculate the exponentiation by calculate the equation bit by bit. You would do `4^8`, have a greater base value (4) and a smaller exponent (8). You can do this using more exponentiation and division. You can divide the exponent by a value *X* (provided *X* is a prime divisor of the exponent), and make the base value (*B*) into `B^X`. For example, you can do: ``` 4^8 = (4 ^ 2)^(8 / 2) = 16^4 ``` I have replaced *X* with 2 in the previous equation. You can 'simplify' `16^4` further, again with `X = 2`: ``` 16^4 = (16 ^ 2)^(4 / 2) = 256^2 ``` And then finally calculate a number (again, `X = 2`): ``` 256^2 = (256 ^ 2)^(2 / 2) = 65536^1 = 65536 ``` Therefore, ``` 4^8 = 16^4 = 256^2 = 65536 ``` This is the output you should give. The output separator is a little flexible, for example, you can separate the equations by newlines or spaces instead of `=`. Or, you may put them into a list (but you mustn't use a digit or the `^` character as a separator). As Martin Ender pointed out, the `^` is also flexible. For example, you may use `[A, B]` or `A**B` instead of `A^B` in the output. *X* may only be prime, which means you cannot use `X = 8` to get straight to the solution, and the values of *X* will only be prime factors of the second input (the exponent). ### Examples: ``` (input) -> (output) 4^8 -> 4^8=16^4=256^2=65536 5^11 -> 5^11=48828125 2^15 -> 2^15=32^3=32768 (2^15=8^5=32768 is also a valid output) ``` Mind that the input format is also flexible (eg you may take `A \n B` or `A B` instead of `A^B`. Obviously, this wouldn't be a problem if you write a function taking two arguments. In the second example, we go straight to calculation, since `11` is prime and we cannot take any more steps. You may write a program or a function to solve this, and you may print or return the value, respectively. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), that shortest code wins! [Answer] # JavaScript (ES7), 55 bytes ``` f=(a,b,c=2)=>b>1?b%c?f(a,b,c+1):a+['^'+b,f(a**c,b/c)]:a ``` Uses `,` in place of `=` (`2^15,8^5,32768`). ### Test cases ``` f=(a,b,c=2)=>b>1?b%c?f(a,b,c+1):a+['^'+b,f(Math.pow(a,c),b/c)]:a g=(a,b)=>console.log(`f(${a}, ${b}):`,f(a,b)) g(4,8) g(5,11) g(2,15) ``` Note: the snippet uses `Math.pow` instead of `**` for cross-browser compatibility. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~22~~ 17 bytes Saved 5 bytes by noticing the flexible output format. ``` Ò©gƒ²®N¹‚£P`Šm‚Rˆ ``` [Try it online!](https://tio.run/nexus/05ab1e#@3940qGV6ccmHdp0aJ3foZ2PGmYdWhyQcHRBLpAVdLrt/39DUy4jAA "05AB1E – TIO Nexus") **Explanation** Example for `2^15` ``` Ò© # calculate primefactors of exponent and store in register # STACK: [3,5] g # length # STACK: 2 ƒ # for N in range[0 ... len(primefactors)] do ² # push base # STACK: 2 ® # push primefactors # STACK: 2, [3,5] N¹‚£ # split into 2 parts where the first is N items long # 1st, 2nd, 3rd iteration: [[], [3, 5]] / [[3], [5]] / [[3, 5], []] P # reduce each by product # STACK 1st iteration: 2, [1,15] ` # split list to items on stack # STACK 1st iteration: 2, 1, 15 Š # move down the current exponent # STACK 1st iteration: 15, 2, 1 m # raise base to the rest of the full exponent # STACK 1st iteration: 15, 2 ‚ # pair them up # STACK 1st iteration: [15,2] R # reverse the pair # STACK 1st iteration: [2,15] ˆ # store it in global list # print global list at the end of execution ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` *Uż:Ṫ ÆfṪ1;×\ç@€ ``` **[Try it online!](https://tio.run/nexus/jelly#@68VenSP1cOdq7gOt6UBKUPrw9NjDi93eNS05v///9FGOoamsQA)** Input is a single list `[base, exponent]`. The return value of the lower monadic link is a list of lists, as a full program a representation of that list is printed, for example `2^15=8^5=32768^1` is printed as: ``` [[2, 15], [8, 5], [32768, 1]] ``` ### How? ``` ÆfṪ1;×\ç@€ - Main link: [base, exponent] e.g. [4,12] Æf - prime factorization array (vectorises) [[2,2],[2,2,3]] Ṫ - tail (tailing first costs bytes) [2,2,3] 1; - 1 concatenated with the result [1,2,2,3] ×\ - reduce with multiplication (make factors) [1,2,4,12] ç@€ - call last link (1) as a dyad for €ach with reversed @rguments - implicit print if running as a full program *Uż:Ṫ - Link 1, an entry in the equality: [base, exponent], factor e.g. [4, 12], 4 * - exponentiate (vectorises) : [base ^ factor, exponent ^ factor] [256, 20736] U - upend [20736, 256] : - integer division: [base // factor, exponent // factor] [1, 3] ż - zip [[20736, 1], [256, 3]] Ṫ - tail [256, 3] ...i.e at a factor of 4: 4 ^ 12 = 256 ^ 3 ``` --- It could be formatted as a grid for 2 bytes by a trailing `µG`, e.g.: ``` 2 15 8 5 32768 1 ``` ...or fully formatted, including trimming off the `^1`, for 9, with a trailing `j€”^j”=ṖṖ`, e.g.: ``` 2^15=8^5=32768 ``` [Answer] # C, ~~125~~ 123 + 4 (`-lm`) = ~~129~~ 127 bytes ``` i;f(n,m)double n;{if(m-1){printf("%.0f^%d=",n,m);for(i=2;i<=m;i++)if(!(m%i))return f(pow(n,i),m/i);}else printf("%.0f",n);} ``` Takes a double and an integer. [Try it online!](https://tio.run/nexus/c-gcc#VczRCoJAEIXh@57CFoQZXC0jIZh8lcByJwZ2V1mVLsRXb9vu6u7wcfijEIPXDvthuVuTeVqFwZU1rmMQPzOovDryLe9bpb8/4iGAtCeSa@tIigLTfw8uF8Rg5iX4jGEcXikqqN1BkDZjJ5P95lIqcXSdeMB1x3Cu9AVpXOYJlEJK0lS6rv/plKhJa4vvB9vuOcXSug8 "C (gcc) – TIO Nexus") [Answer] ## Haskell, 64 bytes ``` a#b|v:_<-[x|x<-[2..b],mod b x<1]=[a,b]:(a^v)#div b v|1<2=[[a^b]] ``` Usage example: `2 # 32` -> `[[2,32],[4,16],[16,8],[256,4],[65536,2],[4294967296]]`. [Try it online!](https://tio.run/nexus/haskell#DcixCoAgEADQXzmwocAEbRP9EjnjDhcHLSLEwX@3lje8SYJHs6fbQx/91yjFKMuVgKE7jT6QZLQrxbaJlNvfbWhnfAgUGXEWyhU83E@uLyxgxGHmBw "Haskell – TIO Nexus"). How it works: ``` a#b -- take input numbers a and b | -- if [x|x<-[2..b] ] -- the list of all x drawn from [2..b] ,mod b x<1 -- where x divides b v:_<- -- has at least one element (bind the first to v) = [a,b]: -- the the result is the [a,b] followed by (a^v)#div b v -- a recursive call with parameters (a^v) and (div b v) |1<2 -- else (i.e. no divisors of b) = [[a^b]] -- the result is the singleton list of a singleton list -- of a^b ``` [Answer] # Bash + GNU utilities, 82 ``` echo $1^$2 f=`factor $2|egrep -o "\S+$"` ((m=$2/f,r=$1**f,m-1))&&$0 $r $m||echo $r ``` Recursive shell script. This doesn't seem to work in TIO, but runs fine when saved as a script and executed: ``` $ ./expbit2.sh 4 8 4^8 16^4 256^2 65536 $ ./expbit2.sh 5 11 5^11 48828125 $ ./expbit2.sh 2 15 2^15 32^3 32768 $ ``` ]
[Question] [ The Wythoff matrix is an infinite matrix consisting of the [Grundy numbers](https://en.wikipedia.org/wiki/Sprague%E2%80%93Grundy_theorem) of each square on a chessboard in [Wythoff's game](https://en.wikipedia.org/wiki/Wythoff%27s_game). Each entry in this matrix is equal to the smallest nonnegative number that does not appear anywhere above, to the left, or diagonally northwest of the position of the entry. The top-left 20-by-20 square looks like this: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 1 2 0 4 5 3 7 8 6 10 11 9 13 14 12 16 17 15 19 20 2 0 1 5 3 4 8 6 7 11 9 10 14 12 13 17 15 16 20 18 3 4 5 6 2 0 1 9 10 12 8 7 15 11 16 18 14 13 21 17 4 5 3 2 7 6 9 0 1 8 13 12 11 16 15 10 19 18 17 14 5 3 4 0 6 8 10 1 2 7 12 14 9 15 17 13 18 11 16 21 6 7 8 1 9 10 3 4 5 13 0 2 16 17 18 12 20 14 15 11 7 8 6 9 0 1 4 5 3 14 15 13 17 2 10 19 21 12 22 16 8 6 7 10 1 2 5 3 4 15 16 17 18 0 9 14 12 19 23 24 9 10 11 12 8 7 13 14 15 16 17 6 19 5 1 0 2 3 4 22 10 11 9 8 13 12 0 15 16 17 14 18 7 6 2 3 1 4 5 23 11 9 10 7 12 14 2 13 17 6 18 15 8 19 20 21 4 5 0 1 12 13 14 15 11 9 16 17 18 19 7 8 10 20 21 22 6 23 3 5 13 14 12 11 16 15 17 2 0 5 6 19 20 9 7 8 10 22 24 4 14 12 13 16 15 17 18 10 9 1 2 20 21 7 11 23 22 8 25 26 15 16 17 18 10 13 12 19 14 0 3 21 22 8 23 20 9 24 7 27 16 17 15 14 19 18 20 21 12 2 1 4 6 10 22 9 13 25 11 28 17 15 16 13 18 11 14 12 19 3 4 5 23 22 8 24 25 21 26 10 18 19 20 21 17 16 15 22 23 4 5 0 3 24 25 7 11 26 12 13 19 20 18 17 14 21 11 16 24 22 23 1 5 4 26 27 28 10 13 25 ``` There is currently no known efficient algorithm for computing an arbitrary entry in the Wythoff matrix. However, your task in this problem is to try to design a heuristic function that will tell whether the number at a specific coordinate `wythoff(x, y)` is even or odd. Your program may not contain more than 64 KB (65,536 bytes) of source code, or use more than 2 MB (2,097,152 bytes) of working memory. In particular for memory usage, this means that the maximum resident set size of your program may not exceed 2 MB more than the maximum resident set size of an empty program in that language. In the case of an interpreted language, it would be the memory usage of the interpreter / virtual machine itself, and in the case of a compiled language, it would be the memory usage of a program that executes the main method and does nothing. Your program will be tested on the `10000 x 10000` matrix for row values in `20000 <= x <= 29999` and column values in `20000 <= y <= 29999`. The score of your program is the accuracy rate (number of correct guesses) your program achieves, with shorter code acting as a tiebreaker. [Answer] # Python; accuracy = 54,074,818; size = 65,526 bytes *Previous scores: 50,227,165; 50,803,687; 50,953,001* ``` #coding=utf-8 d=r'''<65,400 byte string>''' def f(x,y): a=max(x,y)-20000;b=min(x,y)-20000;c=(a*(a+1)//2+b)%523200 return(ord(d[c//8])>>(c%8))&1 ``` This approach divides all unique entries of the matrix into 523,200 groups and reads the best guess for the group **(x, y)** from a binary string. You can download the full source code from [Google Drive](https://drive.google.com/open?id=0Byb-iITM2Kk2RVZtUjRrVFlLT3M). I've used [@PeterTaylor's parities](https://codegolf.stackexchange.com/a/95723/12012) to generate the string and to compute the accuracy. [Answer] ## CJam (accuracy 50016828/100000000, 6 bytes) ``` {+1&!} ``` (In ALGOL-style pseudocode for non-CJammers: `return ((x + y) & 1) == 0`). This performs better than any of the other two dozen simple heuristics I've tried. It's even better than any combination with the next two best ones. --- The score assumes that my calculated section of the matrix is correct. Independent verification welcomed. I'm hosting the calculated parity bits at <http://cheddarmonk.org/codegolf/PPCG95604-parity.bz2> (8MB download, extracts to 50MB text file: since the matrix is symmetric about the main diagonal, I've only included each line starting from the main diagonal, so you have to offset, transpose, and bitwise OR to get the full square). The code which I used to calculate it is Java. It uses the definition fairly straightforwardly, but with a set data structure which run-length encodes the ranges so that it's quick to skip to the next permitted value. Further optimisation would be possible, but it runs on my moderately old desktop in about two hours and 1.5GB of heap space. ``` import java.util.*; public class PPCG95604Analysis { static final int N = 30000; public static void main(String[] args) { Indicator[] cols = new Indicator[N]; Indicator[] diag = new Indicator[N]; for (int i = 0; i < N; i++) { cols[i] = new Indicator(); diag[i] = new Indicator(); } int maxVal = 0; for (int y = 0; y < N; y++) { Indicator row = new Indicator(cols[y]); for (int x = y; x < N; x++) { Indicator col = cols[x]; Indicator dia = diag[x - y]; Indicator.Result rr = row.firstCandidate(); Indicator.Result rc = col.firstCandidate(); Indicator.Result rd = dia.firstCandidate(); while (true) { int max = Math.max(Math.max(rr.candidateValue(), rc.candidateValue()), rd.candidateValue()); if (rr.candidateValue() == max && rc.candidateValue() == max && rd.candidateValue() == max) break; if (rr.candidateValue() != max) rr = rr.firstCandidateGreaterThan(max - 1); if (rc.candidateValue() != max) rc = rc.firstCandidateGreaterThan(max - 1); if (rd.candidateValue() != max) rd = rd.firstCandidateGreaterThan(max - 1); } if (y >= 20000 && x >= 20000) System.out.format("%d", rr.candidateValue() & 1); maxVal = Math.max(maxVal, rr.candidateValue()); rr.markUsed(); rc.markUsed(); rd.markUsed(); } if (y >= 20000) System.out.println(); } } static class Indicator { private final int INFINITY = (short)0xffff; private final int MEMBOUND = 10000; private short[] runLengths = new short[MEMBOUND]; public Indicator() { runLengths[1] = INFINITY; } public Indicator(Indicator clone) { System.arraycopy(clone.runLengths, 0, runLengths, 0, MEMBOUND); } public Result firstCandidate() { // We have a run of used values, followed by a run of unused ones. return new Result(1, 0xffff & runLengths[0], 0xffff & runLengths[0]); } class Result { private final int runIdx; private final int runStart; private final int candidateValue; Result(int runIdx, int runStart, int candidateValue) { this.runIdx = runIdx; this.runStart = runStart; this.candidateValue = candidateValue; } public int candidateValue() { return candidateValue; } public Result firstCandidateGreaterThan(int x) { if (x < candidateValue) throw new IndexOutOfBoundsException(); int idx = runIdx; int start = runStart; while (true) { int end = start + (0xffff & runLengths[idx]) - 1; if (end > x) return new Result(idx, start, x + 1); // Run of excluded start += 0xffff & runLengths[idx]; idx++; // Run of included start += 0xffff & runLengths[idx]; idx++; if (start > x) return new Result(idx, start, start); } } public void markUsed() { if (candidateValue == runStart) { // Transfer one from the start of the run to the previous run runLengths[runIdx - 1]++; if (runLengths[runIdx] != INFINITY) runLengths[runIdx]--; // May need to merge runs if (runLengths[runIdx] == 0) { runLengths[runIdx - 1] += runLengths[runIdx + 1]; for (int idx = runIdx; idx < MEMBOUND - 2; idx++) { runLengths[idx] = runLengths[idx + 2]; if (runLengths[idx] == INFINITY) break; } } return; } if (candidateValue == runStart + (0xffff & runLengths[runIdx]) - 1) { // Transfer one from the end of the run to the following run. if (runLengths[runIdx + 1] != INFINITY) runLengths[runIdx + 1]++; if (runLengths[runIdx] != INFINITY) runLengths[runIdx]--; // We never need to merge runs, because if we did we'd have hit the previous case instead return; } // Need to split the run. From // runIdx: a+1+b // to // runIdx: a // runIdx+1: 1 // runIdx+2: b // runIdx+3: previous val at runIdx+1 for (int idx = MEMBOUND - 1; idx > runIdx + 2; idx--) { runLengths[idx] = runLengths[idx - 2]; } runLengths[runIdx + 2] = runLengths[runIdx] == INFINITY ? INFINITY : (short)((0xffff & runLengths[runIdx]) + runStart - 1 - candidateValue); runLengths[runIdx + 1] = 1; runLengths[runIdx] = (short)(candidateValue - runStart); } } } } ``` [Answer] # J, accuracy = 50022668/108 = 50.0227%, 4 bytes ``` 2|*. ``` Takes the coordinates as two arguments, computes the LCM between them and takes it modulo 2. A `0` means it is even and a `1` means it is odd. The performance is based on the parity bits provided by @[Peter Taylor](https://codegolf.stackexchange.com/a/95723/6710). The PRNG version before for 7 bytes, `2|?.@#.` had an accuracy of 50010491/108. ## Explanation ``` 2|*. Input: x on LHS, y on RHS *. LCM(x, y) 2| Modulo 2 ``` ]
[Question] [ # Introduction I found [this question](https://codegolf.stackexchange.com/questions/35727/calculate-the-riemann-zeta-function) that was closed because it was unclear, yet it was a nice idea. I'll do my best to make this into a clear challenge. The [Riemann Zeta function](https://en.wikipedia.org/wiki/Riemann_zeta_function) is a special function that is defined as the analytical continuation of [![enter image description here](https://i.stack.imgur.com/bKmHd.png)](https://i.stack.imgur.com/bKmHd.png) to the complex plane. There are many equivalent formulas for it which makes it interesting for code golf. # Challenge Write a program that takes 2 floats as input (the real and imaginary part of a complex number) and evaluates the Riemann Zeta function at that point. **Rules** * Input and output via console OR function input and return value * Built in complex numbers are not allowed, use floats (number, double, ...) * No mathematical functions except `+ - * / pow log` and real valued trig functions (if you want to integrate, use the gamma function, ... you must include this functions definition in the code) * Input: 2 floats * Output: 2 floats * Your code must contain value that gives theoretically arbitrary precision when made arbitrary large/small * The behaviour at input 1 is not important (this is the only pole of this function) Shortest code in bytes wins! # Example Input and Output Input: > > 2, 0 > > > Output: > > 1.6449340668482266, 0 > > > Input: > > 1, 1 > > > Output: > > 0.5821580597520037, -0.9268485643308071 > > > Input: > > -1, 0 > > > Output: > > -0.08333333333333559, 0 > > > [Answer] # Python - 385 This is a straightforward implementation of Equation 21 from <http://mathworld.wolfram.com/RiemannZetaFunction.html> This uses Python's convention for optional arguments; if you want to specify a precision, you can pass a third argument to the function, otherwise it uses 1e-24 by default. ``` import numpy as N def z(r,i,E=1e-24): R=0;I=0;n=0; while(True): a=0;b=0;m=2**(-n-1) for k in range(0,n+1): M=(-1)**k*N.product([x/(x-(n-k))for x in range(n-k+1,n+1)]);A=(k+1)**-r;t=-i*N.log(k+1);a+=M*A*N.cos(t);b+=M*A*N.sin(t) a*=m;b*=m;R+=a;I+=b;n+=1 if a*a+b*b<E:break A=2**(1-r);t=-i*N.log(2);a=1-A*N.cos(t);b=-A*N.sin(t);d=a*a+b*b;a=a/d;b=-b/d print(R*a-I*b,R*b+I*a) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~303~~ ~~297~~ 298 bytes This answer is based on [R.T.'s Python answer](https://codegolf.stackexchange.com/a/75540/47581) with several modifications: * First, `Binomial(n, k)` is defined as `p = p * (n-k) / (k+1)` which changes `Binomial(n,k)` to `Binomial(n,k+1)` with every pass of the for loop. * Second, `(-1)**k * Binomial(n,k)` became `p = p * (k-n) / (k+1)` which flips the sign at every step of the for loop. * Third, the `while` loop has been changed to immediately check if `a*a + b*b < E`. * Fourth, the bitwise not operator `~` is used in several places where they would aid in golfing, using identities such as `-n-1 == ~n`, `n+1 == -~n`, and `n-1 == ~-n`. This only works for ints, however, and not floats. Several other small modifications were made for better golfing, such as putting the `for` loop on one line and the call to `print` on one line with the code before it. Golfing suggestions welcome. [Try it online!](https://tio.run/##TVA7b8IwEN75FTfaZxvitF2wrhIDQwYYsiIGpwSwQpzIuGrC0L@exqr6WO6@7x7fPfoxXjv/NE2u7bsQobXxCvYO@8WpPsODBenklnStnjO@XkBJBXnKjKWK9AI@ru5Wg0UrKqxet3MBpExmetKmpRzx08@xcxegAechWH@pmZZe5Hy9o37VIAbTI7FGaeX5qjGRlMP98tZdWMONFbSb2Vt3Z5Gb6pvdnZ9ZmoXUmiqZUpA1haDKeJEW26TZTKvA/wvm3Ayk1eZPcaTNr6A50YCDGHE0oY7vwbMSB1XgyFcnOeNRFDjMeErnlBKKdNHhkEvIjhIOWoJOXumfwPIloWP6CkAfnI/swVIj59MX "Python 3 – Try It Online") **Edit:** -6 bytes from a number of small changes. **Edit:** +1 byte from fixing an error with float handling, with thanks to [mostlyWright](https://codegolf.stackexchange.com/users/120478/mostlywright) for pointing out the error. ``` import math as N def z(r,i,E=1e-40): R=I=n=0;a=b=1 while a*a+b*b>E: a=b=0;p=1;m=2**~n for k in range(1,n+2):M=p/k**r;p*=(k-1-n)/k;t=-i*N.log(k);a+=M*N.cos(t);b+=M*N.sin(t) a*=m;b*=m;R+=a;I+=b;n+=1 A=2**(1-r;t=-i*N.log(2);x=1-A*N.cos(t);y=A*N.sin(t);d=x*x+y*y;return(R*x-I*y)/d,(R*y+I*x)/d ``` [Answer] # Axiom, ~~413 315~~ 292 bytes ``` p(n,a,b)==(x:=log(n^b);y:=n^a;[y*cos(x),y*sin(x)]);z(a,b)==(r:=[0.,0.];e:=10^-digits();t:=p(2,1-a,-b);y:=(1-t.1)^2+t.2^2;y=0=>[];m:=(1-t.1)/y;q:=t.2/y;n:=0;repeat(w:=2^(-n-1);abs(w)<e=>break;r:=r+w*reduce(+,[(-1)^k*binomial(n,k)*p(k+1,-a,-b) for k in 0..n]);n:=n+1);[r.1*m-q*r.2,m*r.2+r.1*q]) ``` This would implement too the equation 21 from <http://mathworld.wolfram.com/RiemannZetaFunction.html> The above should be the one iterpreted Axiom function z(a,b) here 16x slower than this below function Zeta(a,b)[that should be the one compiled] all ungolfed and commented [1 second for Zeta() against 16 seconds for z() for one value of 20 digits afther the float point]. For the digit question, one would choose the precision by calling digits(); function, for example digits(10);z(1,1) should print 10 digits after the point, but digits(50);z(1,1) should print 50 digits after the point. ``` -- elevImm(n,a,b)=n^(a+i*b)=r+i*v=[r,v] elevImm(n:INT,a:Float,b:Float):Vector Float==(x:=log(n^b);y:=n^a;[y*cos(x),y*sin(x)]::Vector Float); -- +oo n -- --- --- -- 1 \ 1 \ n --zeta(s)= ---------- * / ------ * / (-1)^k( )(k+1)^(-s) -- 1-2^(1-s) ---n 2^(n+1) ---k k -- 0 0 Zeta(a:Float,b:Float):List Float== r:Vector Float:=[0.,0.]; e:=10^-digits() -- 1/(1-2^(1-s))=1/(1-x-i*y)=(1-x+iy)/((1-x)^2+y^2)=(1-x)/((1-x)^2+y^2)+i*y/((1-x)^2+y^2) t:=elevImm(2,1-a,-b); y:=(1-t.1)^2+t.2^2; y=0=>[] m:=(1-t.1)/y; q:=t.2/y n:=0 repeat w:=2^(-n-1) abs(w)<e=>break --- this always terminate because n increase r:=r+w*reduce(+,[(-1)^k*binomial(n,k)*elevImm(k+1,-a,-b) for k in 0..n]) n:=n+1 -- (m+iq)(r1+ir2)=(m*r1-q*r2)+i(m*r2+q*r1) [r.1*m-q*r.2,m*r.2+r.1*q] this is one test for the z(a,b) function above: (10) -> z(2,0) (10) [1.6449340668 482264365,0.0] Type: List Expression Float (11) -> z(1,1) (11) [0.5821580597 520036482,- 0.9268485643 3080707654] Type: List Expression Float (12) -> z(-1,0) (12) [- 0.0833333333 3333333333 3,0.0] Type: List Expression Float (13) -> z(1,0) (13) [] ``` ]
[Question] [ I have a chocolate bar and I need help eating it so you'll be writing a program just to do that. ## Explanation The first line is the input. Examples are separated by an empty line. ``` 7 ____ __|__| |__|__| |__|__| |__|__| 6 _______ |__|__| |__|__| |__|__| 5 ____ __|__| |__|__| |__|__| 0 1 ____ |__| ``` ## Spec Hopefully the examples clearly specify this challenge but to avoid any possible confusion, here's a spec: You can have a single optional trailing/leading whitespace An input of `0` is an empty output. If the input is even, the top rows looks like: ``` _______ |__|__| ``` If it's odd, the top row is: ``` ____ |__| ``` If it's odd and greater than 1, the top rows are: ``` ____ __|__| ``` --- The following rows are: ``` |__|__| ``` until the number of instances of `|__|` is the same as the input [Answer] # Haskell, 101 bytes Haskell has never been great for code golfing... ``` b="\n|__|__|" h=" ____\n " f 1=h++" |__|" f 2="_______"++b f 3=h++"__|__|"++b f n=f(n-2)++b f _="" ``` [Answer] # JavaScript ES6, 80 bytes ``` x=>(x%2?` ____ ${x<2?" ":"__"}|__|`:x?"_______":"")+` |__|__|`.repeat(x/2) ``` Uses the same technique as my Japt answer, and is surprisingly not much longer... [Answer] # Pyth, 55 bytes ``` K"|__|"IQ>7<*3%Q2r"3 7_"9?tQjb+XW%Q2J+KtKZd*/tQ2]J+*3dK ``` [Try it online.](http://pyth.herokuapp.com/?code=K%22%7C__%7C%22IQ%3E7%3C%2a3%25Q2r%223+7_%229%3FtQjb%2BXW%25Q2J%2BKtKZd%2a%2FtQ2%5DJ%2B%2a3dK&input=7&test_suite_input=5%0A6%0A1%0A0&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=K%22%7C__%7C%22IQ%3E7%3C%2a3%25Q2r%223+7_%229%3FtQjb%2BXW%25Q2J%2BKtKZd%2a%2FtQ2%5DJ%2B%2a3dK&input=7&test_suite=1&test_suite_input=5%0A6%0A1%0A0&debug=0) This is really quick and dirty, written on my phone. Will get to more golfing later. [Answer] # C, 104 102 bytes ``` f(x){x?x%2?printf(" ____\n%3s|__|\n",x<2?"":"__"):puts("_______"):0;for(x/=2;x>0;x--)puts("|__|__|");} ``` Maybe I can use some printf trickery to improve this... Apparently I can [Answer] # 𝔼𝕊𝕄𝕚𝕟, 53 chars / 67 bytes ``` ï%2?` ⟮__⟯Ⅰ ⦃ï<2?⍞ :⍞Ⅰ⦄|Ⅰ|`:ï?⍘_ď7:⬯⦄ |Ⅰ|Ⅰ|`ď ï/2 ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=1&code=%C3%AF%252%3F%60%20%20%20%E2%9F%AE__%E2%9F%AF%E2%85%A0%0A%20%E2%A6%83%C3%AF%3C2%3F%E2%8D%9E%20%20%3A%E2%8D%9E%E2%85%A0%E2%A6%84%7C%E2%85%A0%7C%60%3A%C3%AF%3F%E2%8D%98_%C4%8F7%3A%E2%AC%AF%E2%A6%84%0A%7C%E2%85%A0%7C%E2%85%A0%7C%60%C4%8F%20%C3%AF%2F2)` This is quite similar to the Javascript ES6 answer, even though I found it independently. Explanation to come when I finish golfing. [Answer] # PHP, 134 chars ``` <?$i=$argv[1];if($i>0){echo($i%2===0?"_______\n|__":" ____\n".($i>1?"___":" "))."|__|\n";echo str_repeat("|__|__|\n",($i-1)/2);}?> ``` Notes: * PHP was not built for code golfing * I sure had FUN making this snippet * It throws an error if argv is undefined * Any help to short it is appreciated. [Answer] # Retina, 69 bytes ``` r`(1?)1 $1__|__|¶ ^__(?=\D{5}$) ^. $0____¶ $0 ^\D ^1 ___ ?1 | ``` Takes input in unary. [Try it online here.](http://retina.tryitonline.net/#code=cmAoMT8pMQokMV9ffF9ffMK2Cl5fXyg_PVxEezV9JCkKICAKXi4KJDBfX19fwrYgJDAKXlxECiAgIApeMQpfX18KID8xCnw&input=MTExMTE) [Answer] # Japt, ~~60~~ 57 bytes ``` U%2?[S³'_²²RSU¥1?S²:'_²"|__|"]¬:U?'_p7 :P +" |__|__|"pU/2 ``` Just a basic answer. Can probably be improved. [Test it online!](http://ethproductions.github.io/japt?v=master&code=VSUyP1OzKydfsrIrIgoge1WlMT9TsjonX7J9fF9ffCI6VT8nX3A3IDpQICsiCnxfX3xfX3wicFUvMg==&input=Nw==) ]
[Question] [ ## Introduction to [Bézout's identity](https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity) The GCD of two integers A, B is the largest positive integer that divides both of them leaving no remainder. Now because of Euclid's property that each integer N can be divided by another integer M as follows:                                            [![Euclidean division](https://i.stack.imgur.com/TDPbo.gif)](https://i.stack.imgur.com/TDPbo.gif) there exist pairs u,v such that we can write:                                            [![Bézout's Identity](https://i.stack.imgur.com/eCSvB.gif)](https://i.stack.imgur.com/eCSvB.gif) Since there is an infinite amount of those pairs, we'd like to find special ones. There are in fact exactly (A,B not being zero) two such pairs that satify                                            [![Constraints for meaningful (u,v)-pairs](https://i.stack.imgur.com/BqAeD.gif)](https://i.stack.imgur.com/BqAeD.gif) --- e.g.                                    [![Example with 19 and 17](https://i.stack.imgur.com/RDYzD.gif)](https://i.stack.imgur.com/RDYzD.gif) --- ## Challenge The goal of this challenge is to find the (ordered) pair of coefficients (u,v) that satify the above constraints and where u must be positive. This narrows down the output to a unique pair. --- ## Input We may assume that the input is positive, also A will always be larger than B (A > B). --- ## Output The output of our program/function must be the (ordered) pair specified in the challenge. --- ## Rules One must not use built-in extended Euclidean algorithms (e.g. in Mathematica one is allowed to use `GCD` but not `ExtendedGCD` - which would fail for 5,3 anyways). The answer may be a full program (taking input via STDIN or similar and output via STDOUT) or a function (returning the pair). Beside the pair (u,v) there shall not be any output, trailing newlines or spaces are allowed. (brackets or commas are fine) This is code golf, all standard loopholes are forbidden and the program with the lowest byte count wins. --- ## Examples ``` (A, B) -> (u, v) (42, 12) -> (1, -3) (4096, 84) -> (4, -195) (5, 3) -> (2, -3) (1155, 405) -> (20, -57) (37377, 5204) -> (4365, -31351) (7792, 7743) -> (7585, -7633) (38884, 2737) -> (1707, -24251) (6839, 746) -> (561, -5143) (41908, 7228) -> (1104, -6401) (27998, 6461) -> (3, -13) (23780, 177) -> (20, -2687) (11235813, 112358) -> (8643, -864301) ``` [Answer] ## Haskell, 51 bytes ``` a#b=[(u,-v)|v<-[1..],u<-[1..v],gcd a b==u*a-v*b]!!0 ``` Usage example: `27998 # 6461` -> `(3,-13)`. This is a brute force approach which finds all combinations of `u` and `v` that are valid solutions ordered by `u` and picks the first one. This takes some time to run for large `|v|`. [Answer] # Python 3, ~~101~~ 106 bytes **Edit:** Added some improvements and corrections suggested by [Bruce\_Forte](https://codegolf.stackexchange.com/users/48198/bruce-forte). An answer that uses the extended Euclidean algorithm. It's a bit clunky in places though, and I hope to golf it some more. I could convert to Python 2 to save a byte on integer division (`//`) but I'm not sure how Python 2's `%` modulus operator works with a negative second argument, as that is crucial for getting the output right. ``` def e(a,b): r=b;x=a;s=z=0;t=y=1 while r:q=x/r;x,r=r,x%r;y,s=s,y-q*s;z,t=t,z-q*t return y%(b/x),z%(-a/x) ``` Ungolfed: ``` def e(a, b): r = b x = a # becomes gcd(a, b) s = 0 y = 1 # the coefficient of a t = 1 z = 0 # the coefficient of b while r: q = x / r x, r = r, x % r y, s = s, y - q * s z, t = t, z - q * t return y % (b / x), z % (-a / x) # modulus in this way so that y is positive and z is negative ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 37 ~~40~~ bytes ``` ZdXK2Gw/:1G*1GK/t_w2$:XI2G*!+K=2#fIb) ``` Uses [release (9.3.1)](https://github.com/lmendo/MATL/releases/tag/9.3.1), which is earlier than this challenge. This is a brute force approach, so it may not work for large inputs. [**Try it online!**](http://matl.tryitonline.net/#code=WmRYSzJHdy86MUcqMUdLL3RfdzIkOlhJMkcqIStLPTIjZkliKQ&input=MTE1NQo0MDU) The online compiler is based on a newer release, but produces the same results. ### Explanation ``` Zd % implicitly input A and B. Compute their GCD. Call that C XK % copy C to clipboard K 2Gw/: % vector [1, 2, ..., B/C] 1G* % multiply that vector by A 1GK/t_w2$: % vector [-A/C, -A/C+1 ..., A/C] XI % copy to clipboard I 2G* % multiply that vector by B !+ % all pairwise sums of elements from those vectors K=2#f % find row and column indices of sum that equals C Ib) % index second vector with column (indexing first vector with % row is not needed, because that vector is of the form [1, 2, ...]) ``` [Answer] # Mathematica, 80 bytes ``` f@l_:=Mod@@NestWhile[{Last@#,{1,-Quotient@@(#.l)}.#}&,{{1,0},{0,1}},Last@#.l>0&] ``` --- **Explanation**: [Extended Euclidean algorithm](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm) is used here, in a `Nest` style. The method that the coefficients are stored in arrays makes it possible to use `Dot`. Another possible representation is simply using symbolic expression, like `u a - v b` with `{a->19, b->17}`. Such representation makes use of the feature of Mathematica and is interesting, but it is much longer in bytes. --- **Test cases**: ``` f[{5, 3}] (* {2, -3} *) f[{42, 12}] (* {1, -3} *) f[{11235813, 112358}] (* {8643, -864301} *) ``` [Answer] # Ruby, 83 bytes I think there are a few ways to fine-tune and golf this solution, but I like it so far. Maybe I'll try an extended Euclidean algorithm solution next. ``` ->x,y{a=b=0;y.downto(0).map{|u|(-x..0).map{|v|a,b=u,v if u*x+v*y==x.gcd(y)}};p a,b} ``` **How it works** This code starts with a loop of `u` from `y` down to 0, with an inner loop of `v` from `-x` to 0, inside which we check every `u` and `v` if `u*x+v*y == gcd(x, y)`. Since there could be multiple matches along the way (this uses a very exhaustive search), we start far from 0 so that when we get the last of the multiple matches, it's the one where `|u|` and `|v|` are closest to 0. ``` def bezout(x,y) a=b=0 y.downto(0).each do |u| (-x..0).each do |v| if u*x + v*y == x.gcd(y) a,b=u,v end end end p a,b end ``` ]
[Question] [ ## Background Inspired by [this Unix.SE question](https://unix.stackexchange.com/questions/250740/replace-string-after-last-dot-in-bash) (and of course [my own answer](https://unix.stackexchange.com/a/250808/34061)). When an IP address is specified for an interface, it is often given in this dotted-decimal form: ``` a.b.c.d e.f.g.h ``` where `a.b.c.d` is the actual address and `e.f.g.h` is the netmask. The netmask, when represented in binary, is basically a bunch of `1` bits followed by a bunch of `0` bits. When the netmask is bitwise ANDed against the given IP address, result will be the *network* portion of the address, or simply the *network address*. This will be programmed into the host's route table so that the host knows to send anything destined for this network out this interface. The broadcast address for a network is derived by taking the network address (from above) and setting all the host-bits to 1. The broadcast address is used to send to *all* addresses within the given network. ## Challenge Given a dotted-decimal IP address and valid netmask as input, provide the network address and broadcast address as output, also in dotted-decimal format. * Input must be address and mask as two strings in dotted-decimal format. You may pass this as 2 separate strings, as list or array of 2 string elements or a single string with the address and mask separated by some sensible separator. * Output format is subject to the same constraints as input format. ## Examples ``` Input Output 192.168.0.1 255.255.255.0 192.168.0.0 192.168.0.255 192.168.0.0 255.255.255.0 192.168.0.0 192.168.0.255 192.168.0.255 255.255.255.0 192.168.0.0 192.168.0.255 100.200.100.200 255.255.255.255 100.200.100.200 100.200.100.200 1.2.3.4 0.0.0.0 0.0.0.0 255.255.255.255 10.25.30.40 255.252.0.0 10.24.0.0 10.27.255.255 ``` [Answer] # JavaScript (ES6), 92 bytes ``` (a,m)=>a.split`.`.map((n,i)=>(v=m[i],m[i]=n&v|v^255,n&v),m=m.split`.`).join`.`+" "+m.join`.` ``` ## Explanation ``` (a,m)=> a.split`.` .map((n,i)=>( v=m[i], m[i]=n&v|v^255, n&v ), m=m.split`.` ).join`.` +" "+m.join`.` ``` ## Test ``` var solution = (a,m)=>a.split`.`.map((n,i)=>(v=m[i],m[i]=n&v|v^255,n&v),m=m.split`.`).join`.`+" "+m.join`.` ``` ``` <input type="text" id="input" value="10.25.30.40 255.252.0.0" /> <button onclick="result.textContent=solution.apply(null,input.value.split` `)">Go</button> <pre id="result"></pre> ``` [Answer] # [MATL](https://github.com/lmendo/MATL/releases/tag/4.0.0), 47 bytes This answer uses [current version (4.0.0)](https://github.com/lmendo/MATL/releases/tag/4.0.0) of the language. ``` '%i.%i.%i.%i't32whh2:"j'\d+'XXU]tbZ&tb255Z~+hYD ``` ### Example ``` >> matl > '%i.%i.%i.%i't32whh2:"j'\d+'XXU]tbZ&tb255Z~+hYD > > 192.168.0.1 > 255.255.255.0 192.168.0.0 192.168.0.255 ``` ### Explanation ``` '%i.%i.%i.%i't32whh % format string: '%i.%i.%i.%i %i.%i.%i.%i' 2:" % for loop: do this twice j'\d+'XXU % input string and parse into 4-vector with the numbers ] % end tbZ& % compute network address tb255Z~+ % compute broadcast address hYD % concatenate into 8-vector and apply format string ``` [Answer] # Pyth, [~~44~~](https://codegolf.stackexchange.com/questions/66415/rolling-the-dice/66463#comment162348_66463) 42 bytes ``` LisMcb\.256Lj\..[04jb256'J.&yzKyw'+JxKt^2 32 ``` [Try it online.](http://pyth.herokuapp.com/?code=Lj%5C..%5B04jb256yJ.%26FAmisMcd%5C.256Qy%2BJxHt%5E2%2032&input=%5B%2210.25.30.40%22%2C+%22255.252.0.0%22%5D&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=Lj%5C..%5B04jb256yJ.%26FAmisMcd%5C.256Qy%2BJxHt%5E2%2032&test_suite=1&test_suite_input=%5B%22192.168.0.1%22%2C+%22255.255.255.0%22%5D%0A%5B%22192.168.0.0%22%2C+%22255.255.255.0%22%5D%0A%5B%22192.168.0.255%22%2C+%22255.255.255.0%22%5D%0A%5B%22100.200.100.200%22%2C+%22255.255.255.255%22%5D%0A%5B%221.2.3.4%22%2C+%220.0.0.0%22%5D%0A%5B%2210.25.30.40%22%2C+%22255.252.0.0%22%5D&debug=0&input_size=1) Expects the input as an array, like `["10.25.30.40", "255.252.0.0"]`. [Answer] # PHP, 126 bytes With input in $n: ``` preg_filter(~Ð×£ÔÖÐ,~Û¤¢Â×ÛÎÖÑ×ÛÔÔÁÌÀ×ÛÑÂ×ÛÂÛÁÊÀÝÑÝÅÝÝÖÑ×Û¤ÛÒÊ¢ÙÛÎÖÖÑ×ÛÑÂÛÑ×Û¤ÛÒÊ¢ÍÊÊÙÛÎÖÖÅÝÝÖ,$n);echo"$c $b"; ``` Hexdump: ``` 0000000: 7072 6567 5f66 696c 7465 7228 7ed0 d7a3 preg_filter(~... 0000010: 9bd4 d6d0 9a2c 7edb 9ea4 a2c2 d7db ced6 .....,~......... 0000020: d1d7 db96 d4d4 c1cc c0d7 db9c d1c2 d7db ................ 0000030: 8bc2 db96 c1ca c0dd d1dd c5dd ddd6 d1d7 ................ 0000040: db9e a4db 96d2 caa2 d9db ced6 d6d1 d7db ................ 0000050: 9dd1 c2db 8bd1 d7db 9ea4 db96 d2ca a283 ................ 0000060: cdca cad9 81db ced6 d6c5 dddd d62c 246e .............,$n 0000070: 293b 6563 686f 2224 6320 2462 223b );echo"$c $b"; ``` And a more readable version: ``` preg_filter( /* PCRE regex on input */ '/(\d+)/e', /* match all digits, execute the code for each one */ '$a[]=($1) /* push the matched value to the array $a */ .($i++>3 /* if we're at the 5th or higher digit */ ?($c.=($t=$i>5?".":"").($a[$i-5]&$1)) /* append to $c bitwise AND-ed number */ .($b.=$t.($a[$i-5]|255&~$1)) /* append to $b the broadcast address */ :"")', $n); echo"$c $b"; /* output $c and $b */ ``` `preg_filter` requires a single statement in the replacement pattern when using the `e` flag, so I 'append' the result of the calculations to the 5th and higher values of $a, because those are never reused. [Answer] # Perl, ~~90~~ 85 bytes *includes +6 for `-pF/\D/`* ``` for(0..3){push@a,$F[$_]&1*($y=$F[$_+4]);push@b,$F[$_]|~$y&255}$"='.';$_="@a @b" ``` Usage: ``` echo "192.168.0.1 255.255.255.0" | perl -pF/\\D/ file.pl ``` More readable: ``` for(0..3) { push @a, $F[$_] & 1*($y=$F[$_+4]); # calc/add network address 'byte' push @b, $F[$_] | ~$y & 255 # calc/add broadcast address 'byte' } $"='.'; # set $LIST_SEPARATOR $_="@a @b" # set output to network address and broadcast ``` The `-F/\D/` splits the input on non-digits and stores it in `@F`. [Answer] # Factor, 103 bytes ``` [ [ ipv4-aton ] bi@ 2dup bitand -rot dup bit-count 32 - abs on-bits pick bitor 2nip [ ipv4-ntoa ] bi@ ] ``` Nice. Ungolfed: ``` : mask-and-broadcast ( ip mask -- netaddr broadcast ) [ ipv4-aton ] bi@ 2dup bitand -rot dup bit-count 32 - abs on-bits pick bitor 2nip [ ipv4-ntoa ] bi@ ; ``` [Answer] # [PHP](https://php.net/), 74 bytes ``` <?=long2ip($i=ip2long($argv[1])&$m=ip2long($argv[2])),' ',long2ip($i|~$m); ``` As a standalone, input is via command line: ``` $ php ip.php 192.168.0.1 255.255.255.0 192.168.0.0 192.168.0.255 ``` [Try it online!](https://tio.run/##K8go@P/fxt42Jz8v3SizQEMl0zazwAjE01BJLEovizaM1VRTyUUTNIrV1NRRV1DXQWirqVPJ1bT@//@/oaWRnqGZhZ6BnuF/I1NTPRg2AAA "PHP – Try It Online") Or as a function, **80 bytes**: ``` function($a,$b){return[long2ip($i=ip2long($a)&$m=ip2long($b)),long2ip($i|~$m)];} ``` [Try it online!](https://tio.run/##rZJda4MwFIavm19xkDANhDSmdh84t6vBLgbrvZVhxU7HqkHtVdf9dXdSbe0cg10sIcl7Di9PziHRmW5v73WmgeYagna9LZImLwuHxpyu2K5Km21VhO9l8apy7dA8yLUyERrYBd0M4YoxPtg@PumGRf6@9QmhTVo3NQQQkkkItnujhHt5LaRwbQ62ms/FcUkbIg7dmE67c7DLM43uEUz@Jwwzv@P@CJOocfXnGGduMMAT7Lt9HHdIocRMeAYlxWGetTiMI7L3wOjavjqUYiaFh5X1hamfxKE6obyuUVRXJ1SEz7suqzROMgf6d45rVMBgRyZpkpXwVuaFY4HFMc04WMsmuDPRIW8DdkPNl2lCGXHc3Qg/EiweFy8Pz0/@hOxJ@wU "PHP – Try It Online") ***Ungolfed*** ``` function ip( $a, $b ) { $i = ip2long( $a ); // string IP to 32 bit int $m = ip2long( $b ); // string netmask to 32 bit int $n = $i & $m; // network is bitwise AND of IP and netmask $c = $i | ~$m; // broadcast is bitwise OR of IP and inverse netmask return [ long2ip( $n ), long2ip( $c ) ]; } ``` PHP has nice (albeit with long function names) built-ins to handle IPv4 dotted-string to binary and back. ***Output*** ``` 192.168.0.1 255.255.255.0 => 192.168.0.0 192.168.0.255 192.168.0.0 255.255.255.0 => 192.168.0.0 192.168.0.255 192.168.0.255 255.255.255.0 => 192.168.0.0 192.168.0.255 100.200.100.200 255.255.255.255 => 100.200.100.200 100.200.100.200 1.2.3.4 0.0.0.0 => 0.0.0.0 255.255.255.255 10.25.30.40 255.252.0.0 => 10.24.0.0 10.27.255.255 ``` ]
[Question] [ Relevant links [here](https://en.wikipedia.org/wiki/Kronecker_symbol) and [here](http://mathworld.wolfram.com/KroneckerSymbol.html), but here is the short version: You have an input of two integers \$a\$ and \$b\$ between negative infinity and infinity (though if necessary, I can restrict the range, but the function must still accept negative inputs). **Definition of the Kronecker symbol** You must return the Kronecker symbol \$(a|b)\$ for inputs \$a\$ and \$b\$ where $$(a|b) = (a|p\_1)^{e\_1} \cdot (a|p\_2)^{e\_2} \cdots (a|p\_n)^{e\_n}$$ where \$b = p\_1^{e\_1} \cdot p\_2^{e\_2} \cdots p\_n^{e\_n}\$, and \$p\_i\$ and \$e\_i\$ are the primes and exponents in the prime factorization of \$b\$. * For an odd prime \$p\$, \$(a|p)=a^{\frac{p-1}2} \mod p\$ as defined [here](http://mathworld.wolfram.com/LegendreSymbol.html). * For \$b = 2\$, $$ (n|2) = \begin{cases} 0 & \text{if } n \equiv 0 \mod 2 \\ 1 & \text{if } n \equiv \pm 1 \mod 8 \\ -1 & \text{if } n \equiv \mp 3 \mod 8 \end{cases} $$ * For \$b = -1\$, $$ (n|-1) = \begin{cases} -1 & \text{if } n < 0 \\ 1 & \text{if } n \ge 0 \end{cases} $$ * If \$a \ge b\$, \$(a|b) = (z|b)\$ where \$z = a\mod b\$. By this property, and as explained [here](https://en.wikipedia.org/wiki/Legendre_symbol) and [here](https://en.wikipedia.org/wiki/Kronecker_symbol), \$a\$ is a quadratic residue of \$b\$ if \$z\$ is, even though \$a \ge b\$. * \$(-1|b) = 1\$ if \$b \equiv 0,1,2 \mod 4\$ and \$-1\$ if \$b = 3 \mod 4\$. * \$(0|b)\$ is \$0\$ except for \$(0|1)\$ which is \$1\$, because \$(a|1)\$ is always \$1\$ and for negative \$a\$, \$(-a|b) = (-1|b) \times (a|b)\$. The output of the Kronecker symbol is always \$-1, 0 \text{ or } 1\$, where the output is \$0\$ if \$a\$ and \$b\$ have any common factors. If \$b\$ is an odd prime, \$(a|b) = 1\$ if \$a\$ is a [quadratic residue](https://codegolf.stackexchange.com/questions/65329/is-q-a-quadratic-residue-of-n) \$\mod b\$, and \$-1\$ if is it is not a quadratic residue. **Rules** * Your code must be a program or a function. * The inputs must be in the order `a b`. * The output must be either \$-1, 0 \text{ or } 1\$. * This is code golf, so your code does not have to be efficient, just short. * No built-ins that directly calculate the Kronecker or the related Jacobi and Legendre symbols. Other built-ins (for prime factorization, for example) are fair game. **Examples** ``` >>> kronecker(1, 5) 1 >>> kronecker(3, 8) -1 >>> kronecker(15, 22) 1 >>> kronecker(21, 7) 0 >>> kronecker(5, 31) 1 >>> kronecker(31, 5) 1 >>> kronecker(7, 19) 1 >>> kronecker(19, 7) -1 >>> kronecker(323, 455625) 1 >>> kronecker(0, 12) 0 >>> kronecker(0, 1) 1 >>> kronecker(12, 0) 0 >>> kronecker(1, 0) 1 >>> kronecker(-1, 5) 1 >>> kronecker(1, -5) 1 >>> kronecker(-1, -5) -1 >>> kronecker(6, 7) -1 >>> kronecker(-1, -7) 1 >>> kronecker(-6, -7) -1 ``` This is a complicated function, so please let me know if anything is unclear. [Answer] # Python 3, ~~747~~ ~~369~~ 335 bytes As an example answer, only slightly golfed, and to give you an idea of what an answer will look like. And yes, the prime factorization and run-length-encoding bits are cribbed from Pyth with apologies to [isaacg](http://chat.stackexchange.com/users/115644/isaacg). ``` from itertools import* def k(d,r): if d<0:a=-d;m=1 else:a=d;m=0 if r==1:return 1 p=1;w=r;n=2;f=[] while n*n<=w: while w%n<1:w//=n;f+=n, n+=1 if w>1:f+=w, z=[[k,len(list(g))]for k,g in groupby(f)] for i,j in z: if i==2:p*=pow(-1,(a*a-1)//8) x=pow(a,(i-1)//2,i) if x>1:x-=i p*=x**j if m:p*=pow(-1,(r-1)//2) return p ``` [Answer] ## CJam (70 bytes) ``` {_g\zmf+f{:P2+"W>2*( z1= ;1 7&4-z[0W0X0]= P%P+P(2/#P%_1>P*-"N/<W=~}:*} ``` [Online demo](http://cjam.aditsu.net/#code=%7B_g%5Czmf%2Bf%7B%3AP2%2B%22W%3E2*(%0Az1%3D%0A%3B1%0A7%264-z%5B0W0X0%5D%3D%0AP%25P%2BP(2%2F%23P%25_1%3EP*-%22N%2F%3CW%3D~%7D%3A*%7D%0A%0A49%2C24f-_m*f*%5Bq~%5D%3D%5B%22Error%22%20%22Passed%22%5D%3D&input=VXVVVXVXVVVXVWVVVWVWVVVWVXVVVXVXVVVXVWVVVWVWVVVWVWVXXXXWXWXXWWXXWWXWXWWWWVXXXXWXWXXWWXXWWXWXWWWWVXVWVWVWVXVWVWVVVWVXVXVXVWVXVWVWVWVXVVVXVXVWVXVXVXVVWXVWWVWWVVXVWXVXVVWWVXWVXWVXXVVWVWXVWVVXXVXXVWXVVWVWVXVXVVVXVXVWVWVVVWVWVXVXVVVXVXVWVWVVVWVWVXVXVWWXXWVXWWXXXXWXWXWWWWXXWVXWWXXXXWXWXWWWWXXWVXWWXXVXVVVWVWVVVXVWVVVXVXVVVWVXVVVWVWVVVXVWVVVXVXVVVWVWWWWXXWVWXWWWWXWWWWXWWWWVXXXXWXXXXWXXXXWXVXWWXXXXVXVWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVVWXVVWVWWVXXVXVVWXVVWVWWVXXVXVVWXVVWVWWVXXVXVVWXVVWVVVWVXVWVWVXVWVVVWVWVWVXVXVXVVVXVWVXVXVWVXVVVXVWXXXXWXWWWXVXWWWXWWXWXXWVXWWXWXXWXXXWVWXXXWXWWWWXVXVVVWVXVVVWVXVVVWVXVVVWVXVVVWVXVVVWVXVVVWVXVVVWVXWVXWXXXWWWXWVXWXXXWWWXWVXWXXXWWWXWVXWXXXWWWXWVXWVWVXVWVXVVVWVWVWVWVVVXVWVXVWVVVXVXVXVXVVVWVXVWVXVVXXVWXVWWVXWVXWVWXVWWVWWVXXVXXVWXVXWVXWVXXVWXVWWVVXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXWWVXXWXWWVXXWXWWVXXWXWWVXXWXWWVXXWXWWVXXWXWWVXXWVXVVVXVXVVVXVWVVVWVWVVVWVXVVVXVXVVVXVWVVVWVWVVVWVXWWWVXXXWVXXWXVWXWXVWWXWVXWXXVWXWXVWXWWVXWWWVXXXWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVXVWVVXWVXWVXWVXWVXWVXWVXWVXWVXWVXWVXWVXWVXWVXWVXWVXWVVXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXXXWWXWWWXXWXXWWWXXWWXWWXXXWXXWWXXXWWXWWXXXWXXWWWVVVVVVVVVVVVVVVVVVVVVVVXVXVVVVVVVVVVVVVVVVVVVVVVVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXVVXWVWWVWXVXXVXXVWWVWXVWXVXWVXWVWWVXXVXXVXWVWWVWXVVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXWWXVXWWXVXWWXVXWWXVXWWXVXWWXVXWWXVXWWXVXWWXVXWWXVXVVVXVWVVVWVWVVVWVXVVVXVXVVVXVWVVVWVWVVVWVXVVVXVXWWVWXXWXWVWXWWXXVXWXXXXVXXXXWXVXXWWXWVWXWXXWVWWXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXVXVWVWVXVVXXVXXVXXVXXVXXVXXVXXVXXVXXVXXVXXVXXVXXVXXVXXVXXVVWVWVWVWVVVXVWVXVWVVVXVXVXVXVVVWVXVWVXVVVWVWVWVWVXWVWXXWWXWWWWVWXWXXXXWWXVXWWXXXXWXWVWWWWXWWXXWVWXVXVVVWVWVVVXVXVVVWVWVVVXVXVVVWVWVVVXVXVVVWVWVVVXVWXXWWWWXXWXVXWXXWWWWXXWXVXWXXWWWWXXWXVXWXXWWWWXXWVWVVVWVWVWVXVXVXVVVXVWVXVXVWVXVVVXVXVXVWVWVWVVVWVVWXVVWVXXVXWVXVVXXVVXVXXVXXVXVVXXVVXVWXVXXVWVVXWVVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVWWWXWXXVXXWXWWWXXWWWXWXXVXXWXWWWXXWWWXWXXVXXWXWWWVXVVVWVXVVVWVWVVVXVWVVVXVXVVVWVXVVVWVWVVVXVWVVVXVWWXWXVWXXXXWXWWXWWWXXXWXVXWXXXWWWXWWXWXXXXWVXWXWWVWVXVXVWVVVWVXVXVWVVVWVXVXVWVVVWVXVXVWVVVWVXVXVWVVWXVXWVXXVVWVWWVWVVXXVWXVXWVXXVVWVWWVWVVXXVWXVXWVVWVXVWVWVWVXVVVXVXVWVXVXVXVXVWVXVXVVVXVWVWVWVXVWVWVXWWXXWXXXXWXWXXXWWXWXXVXXWXWWXXXWXWXXXXWXXWWXVWVXVVVXVWVVVWVWVVVWVXVVVXVXVVVXVWVVVWVWVVVWVXVVVXV) (test cases generated with Mathematica). ### Dissection ``` { e# Anonymous function. Stack: a b _g\zmf+ e# Factorise b, with special treatment for negatives e# CJam also gives special treatment to 0 and 1 e# Stack: e.g. a [-1 2 2 5]; or a [-1 1]; or a [0 0]; or a [1 2 2 5] f{ e# For each "prime" factor P, find (a|P) :P2+ e# Extract code for P from an array formed by splitting a string "W>2*( e# a -> (a|-1) z1= e# a -> (a|0) ;1 e# a -> (a|1) 7&4-z[0W0X0]= e# a -> (a|2) P%P+P(2/#P%_1>P*-" e# a -> (a|P) for odd prime P N/<W=~ e# Split string and select appropriate element } :* e# Multiply the components together } ``` I found several ways of evaluating `(a|2)` for the same character count, and have chosen to use the one with the clearest presentation. `integer array <W=` is IMO a quite elegant way of doing fallbacks: if the integer is greater than the length of the array, we select the last element. ### Other comments It's disappointing that for odd prime `p` the direct Fermat-style `(a|p)` is so short, because there's a very golfy way of finding `(a|n)` for positive odd `n` which I wanted to use. The basis is Zolotarev's lemma: > > If `p` is an odd prime and `a` is an integer coprime to `p` then the Legendre symbol `(a|p)` is the sign of the permutation `x -> ax (mod p)` > > > This was strengthened by Frobenius to > > If `a` and `b` are coprime positive odd integers then the Jacobi symbol `(a|b)` is the sign of the permutation `x -> ax (mod b)` > > > and by Lerch to > > If `b` is a positive odd integer and `a` is an integer coprime to `b` then the Jacobi symbol `(a|b)` is the sign of the permutation `x -> ax (mod b)` > > > See Brunyate and Clark, [*Extending the Zolotarev-Frobenius approach to quadratic reciprocity*](http://alpha.math.uga.edu/~pete/Brunyate-Clark_final.pdf), The Ramanujan Journal 37.1 (2014): 25-50 for references. And it can easily be strengthened one step further (although I haven't seen this in the literature) to > > If `b` is a positive odd integer and `a` is an integer then the Jacobi symbol `(a|b)` is the Levi-Civita symbol of the map `x -> ax (mod b)`. > > > Proof: if `a` is coprime to `b` then we use Zolotarev-Frobenius-Lerch; otherwise the map is not a permutation, and the Levi-Civita symbol is `0` as desired. This gives the Jacobi symbol calculation ``` {_2m*{~>},@ff*\ff%::-:*g} ``` But the special treatment required for `(a|-1)` and `(a|2)` mean that I haven't found a way of calculating the Kronecker symbol which is shorter with this approach: it's shorter to factorise and treat the primes individually. [Answer] # Mathematica, ~~169~~ ~~175~~ 165 bytes ``` (1|-1)~k~0=_~k~1=1 _~k~0=0 a_~k~-1=If[a<0,-1,1] a_~k~2=DirichletCharacter[8,2,a] a_~k~p_/;PrimeQ@p=Mod[a^((p-1)/2),p,-1] a_~k~b_:=1##&@@(a~k~#^#2&@@@FactorInteger@b) ``` [Answer] # LabVIEW, 44 Bytes [LabVIEW Primitives](https://codegolf.meta.stackexchange.com/a/7589/39490) ~~Since its symetrical i swapped the inputs if a was bigger than b.~~ Represents the real formula now counting like always according to [![](https://i.stack.imgur.com/5vgzN.png)](https://i.stack.imgur.com/5vgzN.png) [![](https://i.stack.imgur.com/cxXaV.gif)](https://i.stack.imgur.com/cxXaV.gif) for true case [![](https://i.stack.imgur.com/A8nBI.png)](https://i.stack.imgur.com/A8nBI.png) [Answer] # Julia, 195 bytes ``` k(a,b)=b==0?a∈[1,-1]?1:0:b==1?1:b==2?iseven(a)?0:a%8∈[1,-1]?1:-1:b==-1?a<1?-1:1:isprime(b)&&b>2?a%b==0?0:a∈[i^2%b for i=0:b-1]?1:-1:k(a,sign(b))*prod(i->k(a,i)^factor(b)[i],keys(factor(b))) ``` This is a recursive function `k` that accepts two integers and returns an integer. Ungolfed: ``` function k(a::Integer, b::Integer) if b == 0 return a ∈ [1, -1] ? 1 : 0 elseif b == 1 return 1 elseif b == 2 return iseven(a) ? 0 : a % 8 ∈ [1, -1] ? 1 : -1 elseif b == -1 return a < 1 ? -1 : 1 elseif isprime(b) && b > 2 return a % b == 0 ? 0 : a ∈ [i^2 % b for i = 1:b-1] ? 1 : -1 else p = factor(b) return k(a, sign(b)) * prod(i -> k(a, i)^p[i], keys(p)) end end ``` [Answer] # Haskell, 286 bytes ``` a#0|abs a==1=1|1<2=0 a#1=1 a#2|even a=0|mod a 8`elem`[1,7]=1|1<2=(-1) a#b|b<0=a`div`abs a*a#(-b)|all((/=0).mod b)[2..b-1]=if elem n[0,1] then n else(-1)|1<2=product$map(a#)$f b where n=a^(div(b-1)2)`mod`b f 1=[] f n|n<0=(-1):f(-n)|1<2=let p=head$filter((==0).mod n)[2..n]in p:f(div n p) ``` Probably not completely optimized, but a valiant effort. The Kronecker symbol is defined as the infix function a#b, i.e. ``` *Main>323#455265 1 ``` ]
[Question] [ [Prelude](http://esolangs.org/wiki/Prelude) is an esoteric programming language, which has very few, but unusual, restrictions on what constitutes a valid program. Any block of printable ASCII text ("block" meaning that lines of printable ASCII are separated by newlines - 0x0A) is valid provided that: * Every (vertical) column of text contains at most one of `(` and `)`. * Ignoring their vertical position, the `(` and `)` are balanced, that is, each `(` is paired with exactly one `)` to the right of it, and vice versa. Write a program or function which, given a string containing printable ASCII and newlines, determines if it constitutes a valid Prelude program. You may take input via STDIN (or closest alternative), command-line argument or function argument. The result may be returned or printed to STDOUT, using any two *fixed* [truthy/falsy](http://meta.codegolf.stackexchange.com/a/2194/8478) values of your choice. You must *not* assume that the input is rectangular. This is code golf, so the shortest submission (in bytes) wins. ## Examples The following are **valid** Prelude programs (in fact, they're even *real* Prelude programs): ``` ?1-(v #1)- 1 0v ^(# 0)(1+0)#)! (#) ^#1-(0 # ``` ``` 1(# 1) v # - 1+) vv (##^v^+ ? v-(0 # ^ #) ? 1+ 1-! ``` And here are a number of inputs, all of which are **invalid**: ``` #(#(##)##)##( )##(##(##)#)# ``` ``` #(#) )### ``` ``` #(## (##) ``` ``` (##) (#)# ``` ``` (##) (### ``` ``` #(#) (##) ``` ``` #(#) ###) ``` ``` #()# ()## ``` ``` #(#)## ### ###(#) ``` [Answer] # Python 2, ~~128~~ ~~119~~ 105 bytes ``` def F(p): v=n=1 for r in map(None,*p.split("\n")):A,B=map(r.count,"()");n+=B-A;v*=n<2>A+B return n*v>0 ``` Did you know that you can [map None](https://stackoverflow.com/questions/1277278/python-zip-like-function-that-pads-to-longest-length) in Python 2? ## Explanation We want to start by transposing the Prelude so that columns become rows. Usually we would do this with `zip`, but since `zip` truncates to the shortest row length and `itertools.zip_longest` is far too long for code-golf, it seems like there's no short way to do what we want... Except for mapping `None`: ``` >>> print map(None,*[[1,2,3],[4],[5,6]]) [(1, 4, 5), (2, None, 6), (3, None, None)] ``` Unfortunately (or rather, fortunately for all non-golf purposes), this only works in Python 2. As for `n` and `v`: * `n` acts like a stack, counting `1 - <number of unmatched '(' remaining>`. For every `(` we see we subtract 1, and for every `)` we see we add 1. Hence if `n >= 2` at any point, then we've seen too many `)`s and the program is invalid. If `n` doesn't finish on 1, then we have at least one unmatched `(` remaining. * `v` checks validity, and starts at 1. If the program is ever invalid (`n >= 2` or `A+B >= 2`), then `v` becomes 0 to mark invalidity. Hence if the program is valid, then by the end we must have `n = 1, v = 1`. If the program is invalid, then by the end we must either have `v = 0`, or `v = 1, n <= 0`. Therefore validity can be succinctly expressed as `n*v>0`. *(Thanks to @feersum for a multitude of good suggestions which took off 14 bytes!)* ## Previous, more readable submission: ``` def F(p): p=map(None,*p.split("\n"));v=n=0 for r in p:R=r.count;A=R("(");B=R(")");n+=A-B;v|=A+B>1or n<0 return n<1>v ``` [Answer] # CJam, ~~57~~ 56 bytes ``` qN/z_{_"()"--W<},,\s:Q,{)Q/({_')/,\'(/,-}:T~\sT0e>+z+}/! ``` Too long, can be golfed a lot. Explanation to be added once I golf it. **Brief explanation** There are two checks in the code: * First filter checks that each column as at most 1 bracket. The final output of the filter is the number of columns with more than 1 brackets. * Second we convert the input into column major format and then split it on each index into two parts. + In each of these two parts, (`Number of "(" - Number of ")"`) should be complimenting each other. So when you add them up, it should result to 0. Any part that fails this property makes the whole input have non matching brackets. + I also have to make sure that "(" are to the left of ")". This means that the value of `Number of "(" - Number of ")"` cannot be negative for the right side block. [Try it online here](http://cjam.aditsu.net/#code=qN%2Fz_%7B_%22()%22--W%3C%7D%2C%2C%5Cs%3AQ%2C%7B)Q%2F(%7B_')%2F%2C%5C'(%2F%2C-%7D%3AT~%5CsT0e%3E%2Bz%2B%7D%2F!&input=%23(%23(%23%23)%23%23)%23%23(%0A)%23%23(%23%23(%23%23)%23)%23) [Answer] # J, 64 bytes Input is a string with a trailing newline. Output is 0 or 1. ``` (0=(1<|s)s+[:(|@{:+(0>])s)[:+/\]s=.+/@:)@(1 _1 0{~[:'()'&i.];.2) ``` Example usage ``` ]in=.'#(#)##',LF,'###',LF,'###(#)',LF #(#)## ### ###(#) ((0=(1<|s)s+[:(|@{:+(0>])s)[:+/\]s=.+/@:)@(1 _1 0{~[:'()'&i.];.2)) in 0 ``` The method is the following * cut input at newlines and put into a matrix `];.2` * map `(` / `)` / `anything else` into `1` / `-1` / `0` `1 _1 0{~[:'()'&i.]` * define an `s=.+/@:` adverb which added to a verb sums the verbs array output * add values in columns `]s` + check positive `()` balance in every prefix `[:(0>])s)[:+/\]` + check equal `()` balance in the whole list (i.e. in the last prefix) `|@{:@]` * add abs(values) in columns and check every element for a max value of 1 `(1<|s)s` * as all the previous checks yielded positive at failure we add them up and compare to 0 to get the validity of the input `0=]` [Answer] # J, 56 bytes ``` 3 :'*/0<: ::0:(+/\*:b),-.|b=.+/+.^:_1]0|:''()''=/];.2 y' ``` That is an anonymous function accepting a string with a trailing newline and returning 0 or 1. Reading from right to left: * `];.2 y`, as in the other J submission, cuts the string `y` at all occurrences of its last character (which is why the input needs a trailing newline) and makes a rectangular matrix whose rows are the pieces, padded with spaces if necessary. * `'()'=/` compares every character in that matrix first with `(` and then with `)` returning a list of two 0-1 matrices. * `+.^:_1]0|:` turns that list of two matrices into a single matrix of complex numbers. So far the program turns every `(` in the input into a 1, every `)` into i, and every other character into 0. * `b=.+/` assigns the sum of the rows of that complex matrix to `b`. * `-.|b` makes a list of 1-|z| for every z in `b`. The condition that every column contain at most a single parenthesis translates to all these numbers 1-|z| being nonnegative. * `+/\*:b` is the vector of running sums of the squares of the numbers in `b`. If every column does contain at most one parenthesis, the squares of the numbers in `b` are all 0, 1 or -1. The `,` concatenates this vector with the vector of 1-|z|'s. * now all we need to do is test that the entries of our concatenated vector `v` are nonnegative reals numbers, this is almost `*/0<:v`, except that that causes an error if some entries of `v` are not real, so we replace `<:` with `<: ::0:` which just returns 0 in case of error. ]
[Question] [ Quines are fun. Polyglots are fun, too. Polyglot Quines exist, but we can raise the bar even higher. Write a file that contains a valid program for languages α, β, and γ. When the file is executed (possibly after compiling it) as a language α or β program, the program's output shall be of the same form as a valid submission to this contest. If your file is executed as a language γ program, it shall output a number. The value of this number is the chain of previous executions of the program interpreted as a binary number. This explanation might be a bit hard to understan, so here is an example. Let Α, Β, and Γ be functions that execute their input as a language α, β, or γ resp. program and return the output of these programs. Let *x* be a valid submission to this contest. Then the following expression, where we process *x* through language β, α, β, α, α, β, and γ in this order, shall yield 41, since 4110 = 1010012. > > Γ(Β(Α(Α(Β(Α(Β(*x*))))))) > > > You may not assume that penultimate execution in the chain is an execution in language β. For the case where your original submission is directly executed as a language γ program, it shall print 0. Your program shall behave correctly for up to sixteen compilations in the chain; that is, the highest number your program might print out at the end is 215 - 1. Of course, your program is allowed to support longer compilation chains. This is a popularity contest to encourage creative solutions. The submission with the highest vote tally wins. [Answer] # Python 2, Python 3, ><> (Fish) ``` #;n0 import sys x='\\\'\nn#;n0import sysx=v=int(1/2*2)sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851])n' v=int(1/2*2) sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851]) ``` ## Python explanation The Python 2 and Python 3 interpreters work similarly except the `v=int(1/2*2)` variable gets different values (`0` and `1`) as Python 2 uses float division and Python 3 uses integer division. In every run they add the expression `+0*2` or `+1*2` to the first line (after `#;n`) and to the `x` string (after the last write command). The ><> interpreter uses the first addition and the Pythons use the second one to create correct quines. Code after `B(A(B(B(x))))`: ``` #;n+1*2+0*2+1*2+1*20 import sys x='\\\'\nn#;n0import sysx=v=int(1/2*2)sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851])+1*2+0*2+1*2+1*2n' v=int(1/2*2) sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851]) ``` ## ><> (Fish) explanation When you run the ><> interpreter the code pointer bounces back from the `#` wraps around the first line and starting from the end of the first line and heading West starts pushing numbers onto the stack. If an operator comes (`+` or `*`) it pops the top two elements from the stack and pushes back the result. With this method we end up with the base2 representation of the previous runs (`13` in the former example). This is the desired number so we output it with `n` and terminate with `;`. ]
[Question] [ The knight is a chess piece that, when placed on the `o`-marked square, can move to any of the `x`-marked squares (as long as they are inside the board): ``` .x.x. x...x ..o.. x...x .x.x. ``` Eight knights, numbered from 1 to 8, have been placed on a 3×3 board, leaving one single square empty `.`. They can neither attack each other, nor share the same square, nor leave the board: the only valid moves are jumps to the empty square. Compute the minimum number of valid moves required to reach the following ordered configuration by any sequence of valid moves: ``` 123 456 78. ``` Output `-1` if it is not reachable. Example detailed: Possible in 3 moves ``` 128 12. 123 123 356 --> 356 --> .56 --> 456 7.4 784 784 78. ``` ## Input & Output * You are given three lines of three characters (containing each of the characters 1-8 and `.` exactly once) * You are to output a single integer corresponding to the smallest number of moves needed to reach the ordered configuration, or `-1` if it is not reachable. * You are allowed to take in the input as a matrix or array/list * You are allowed to use `0` or in the input instead of `.` ## Test cases ``` 128 356 7.4 -> 3 674 .25 831 -> -1 .67 835 214 -> -1 417 .53 826 -> 23 ``` ## Scoring This is code-golf, so shortest code wins! Credits to [this puzzle](https://www.codingame.com/ide/puzzle/knights-jam) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~54~~ 52 bytes ``` ≔⭆³Sθ≔⭆83270561§θIιθI⌈⟦±¹⁻²⁸↔⁻²⁸⁺×⁸⌕”)″“◨_'↷χ”⁻θ.⌕θ. ``` [Try it online!](https://tio.run/##ZY1LC4MwEITv/grJaQNWanwFPEmh4MEitLfSQ6piAxoficV/nwbF9tDDsjsfszPli01lz1qtUyl5I@CqJi6anA3gO3YmhlltBDB27BEn1p8PUZ/ExzDykGOnKhNVvcDo2CcmFXC8vxXGrmCFOVt4N3dwv9QNUzV4xpJzMUsg1EQ8Zd/OBv9Q0ZrjxrtaglFnLipAgU@9KCbbQnuA6UUuWktX21dj/DCTaB14seWGvkVJpA/v9gM "Charcoal – Try It Online") Link is to verbose version of code. Save 4 bytes if printing any negative number is acceptable for an unreachable configuration. Explanation: ``` ≔⭆³Sθ ``` Input the grid and join the lines together into a single string. ``` ≔⭆83270561§θIιθ ``` Reorder the digits from the string starting at the original bottom right corner and taking clockwise knight's moves. ``` I⌈⟦±¹⁻²⁸↔⁻²⁸ ``` Output the difference from 28 of the absolute difference with 28 (or `-1` if that is negative) of... ``` ⁺×⁸⌕”)″“◨_'↷χ”⁻θ.⌕θ. ``` ... finding the position of that string excluding the `.` in the compressed string `4381672438167`, multiplying that by 8, and adding on the position of the `.`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 331 bytes ``` (n,F=(i,I)=>(I%3-i%3)**2+((I/3|0)-(i/3|0))**2==5)=>Math.min(...(X=[...Array(9)].flatMap((e,i,a)=>F(i,n.search`0`)?[eval('for(k=0,N=n,S=[];!(t=S.filter(Z=>Z==N)[1])&&N!="123456780";(N=[...m=N],N[h=m.search`0`]=N[(H=k?a.findIndex((E,P)=>P!=M&F(P,h)):i,M=m.search`0`,H)],N[H]="0",S.push(N=N.join``),k++));t?-1:k')]:[])).length?X:[-1]) ``` [Try it online!](https://tio.run/##bU9Nb@IwFLz3VwSkwnNxTD4IZEGvaA9FcCBC4lI1ioRFnMZNcFjHpVtp/ztreuhWXS5@8sy8mXkv/MTbvZZH46omF@cCz6DoAkHSFcF7WN2GrrwNyd1dMABYDcM/HnFBfswLiBhZ2Zqbkh2kAsYYPGJqx0@t@Tv8IBkram7W/AggqKTcqhfWXLFWcL0vd96OzFNx4jX0i0ZDhR5NUNEtptmsAwa3rJC1ERqe8P4JMSGpn5FeL@lg1w/CUTSexF53BslH6AGTjCZpiYd/9hkmKSyxmnPrpPKVysVvgAe6sU02HVz3FrChJSFTSddf9@iSXLyWGXa9Lt2y42tb2piEvTRS7XaEVoMBITMzd/1p1SfZNM0IYbVQz6acP05T1/Y87xvVNrVgdfMMBfQ/G/cJcYZD5yS0LN4dU3JjH@HIXCgjjUVEa5w9b4Xz1uiqvbHaT6h1pHIanQvttGXzpi7fX6@WlY26@S8wDm2gN7KB37nxZOQFURz6VzjPlgyjwL@2N/InXhTGwfgKdznQ7kax5c5/AQ "JavaScript (Node.js) – Try It Online") Takes a 9-character string where the dot is replaced by a zero. ## Explanation As the trick is really fun to find, I've hidden it behind a spoiler. > > There are only two spaces that are a knight's move away from the zero. Let us consider one of the pieces. If we move it to the zero, then we can decide to move it back to where it was. However, that wastes moves. Since there are only two spaces that are a knight's move away from any given space, this means that only one other piece can be moved to the new position of the zero, other than the one we just moved. As a result, we must move that piece. Using the same reasoning as above, this means that there is only one "path" originating from a given move, because we only have one choice at each stage. Eventually, we will end up at the ideal arrangement. Now, to account for the impossible cases, notice that there are only so many possible moves. Eventually, we will reach an arrangement that we have already seen. If we do, that means the case is impossible and we can break out of the loop and return -1. > > > A problem I have is that this is way too long, so I'll try to keep golfing it. Fixed a bug that would create outputs of `Infinity` for certain inputs. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~40~~ ~~39~~ 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands) -1 byte porting [*@Neil*'s 54 bytes Charcoal approach](https://codegolf.stackexchange.com/revisions/242948/1): ``` •4Gв©Tв•8×I•55˜u•SèDðkUþJk8*X+D56α‚ß®M ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcMiE/cLmw6tDLmwCci2ODzdE0iZmp6eUwqkgw@vcDm8ITv08D6vbAutCG0XU7NzGx81zDo8/9A63///o010DHXMdZQUlHRMdYx1LHSMdMxiAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f9HDYtM3C9sOrQy5MImINvi8PRKIGVqenpOKZAOPrzC5fCG7NDD@7yyLbQitF1Mzc5tfNQw6/D8Q@t8/@toxvyPjjbUMdKx0DHWMdUx0zHXUVJQ0jGJ1VGIBnFMwFwjoBRIgSFIGCQAkoLoMNIxhKg2ATIgmk2BEhZACTOQsCFYyBhokClUlxFE2AhFEKgoNhYA). ***Original answer:*** ``` •þÜε•SDIðkk._Tиü2vÐ{QiND56α‚ßq}DyèyRǝ}® ``` [Try it online](https://tio.run/##AVgAp/9vc2FiaWX//@KAosO@w5zOteKAolNEScOwa2suX1TQuMO8MnbDkHtRaU5ENTbOseKAmsOfcX1EecOoeVLHnX3Crv//WzQsMSw3LCIgIiw1LDMsOCwyLDZd) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f9HDYsO7zs859xWICPYxfPwhuxsvfiQCzsO7zEqOzyhOjDTz8XU7NzGRw2zDs/XKax1qTy8ojLo@NzaQ@v@63CBjOIqz8jMSVUoSk1MUcjM40rJ51JQ0M8vKNGH2Ail0Bxho6ACVpuX@j/aUMdIx0LHWMdUx0zHXEdJQUnHJJYrGsQ2AfOMgDIgeUOgKIgPkoGoN9IxBKs1AdIQnaZAcQuguBlQ1BAsYgw0xRSqxwgsaoQiBlQTywUA). Both programs take a flattened list of digits as input with `" "` as empty square. **Explanation:** ``` •4Gв©Tв• # Push compressed integer 4381672438167 8× # Repeat it 8 times as string I # Push the input-list •55˜u• # Push compressed integer 83270561 S # Convert it to a list of digits è # Index each into the input D # Duplicate it ðk # Get the index of the space " " U # Pop and store this index in variable `X` þ # Remove the space by only keeping digits J # Join it together to a string k # Get the first 0-based index of this in the large string 8* # Multiply this by 8 X+ # Add index `X` D # Duplicate it 56α # Get the absolute difference with 56 ‚ # Pair both together ß # Pop and push the minimum ® # Push -1 M # Push the largest number on the stack # (after which it is output implicitly as result) ``` ``` •þÜε• # Push compressed integer 16507238 S # Convert it to a list of digits D # Duplicate it I # Push the input-list ðk # Get the index of the space " " k # Use that to index into the duplicated list of digits ._ # Rotate the list of digits that many times towards the left Tи # Repeat it 10 times as list ü2 # Get all overlapping pairs of this list v # Loop over each pair `y`: Ð # Triplicate the current list # (which will be the implicit input in the first iteration) { # Sort the top copy # (where the space will go to the end of the sorted digits) Qi # If the two lists are still the same N # Push the loop index D56α‚ß # Same as above q # Stop the program # (after which the result is output implicitly) } # Close the if-statement DyèyRǝ # Swap the values at indices `y`: D # Duplicate the list once more yè # Get the values at the `y` indices yR # Push the reversed pair `y` ǝ # Insert the values back into the list at those indices } # Close the loop ® # Push -1 # (which is output implicitly if we haven't encountered the `q`) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•4Gв©Tв•` is `4381672438167`; `•55˜u•` is `83270561`; and `•þÜε•` is `16507238`. [Answer] # [Python 3](https://docs.python.org/3/), 126 bytes ``` def f(a,s=[*range(1,9),0],m=0,n=8): for o in(3,2,7,0,5,6,1,8)*7:m+=a!=s or m-55;s[n],s[o],n=s[o],0,o return min(56-m or-1,m) ``` [Try it online!](https://tio.run/##XY9NDsIgFIT3PQXuQKcJ0D@s4SRNF01s1QXQ0Lrw9PVV3eCKZL6ZYd78Wu/BF9t2HSc28QGL7Y5x8LeRK5wFZA9nJbw1os3YFCIL7OF5AY0GEhVqKBhxbFp3ssPBLowsLq@qy9L5HksXegp/HomQsTiuz@iZo46qzh25cwUntjk@/Mon3ilqLlB@mhsYGiBEllBD/EslyoTuWkmqJr67VELlr3FPa1qdZktSvhcV5NGo//6VySpNdHsD "Python 3 – Try It Online") *-1 byte thanks to Jonathan Allan* *-3 bytes thanks to Arnauld* There are 56 possible permutations. From the starting position, we can walk a circular path 7 times, until we reach the starting position again. If the input is found, we return the number of steps `m` required. If the path is shorter the other way around, we return `56-m`. [Answer] # Excel, 158 bytes ``` =IFERROR(LET(a,MID(A1&A2&A3,{2;7;6;1;8;3;4;9},1)*1,b,CONCAT(FILTER(a,a)),d,"2761834",f,(FIND(2,b)*8+1-XMATCH(0,a))*(1-ISERROR(FIND(b,d&d)))-1,MIN(f,56-f)),-1) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnjI1USo458khv6xX?e=U6o00e) [Answer] # JavaScript (ES6), ~~110 108~~ 105 bytes This is very similar to [Jitse's answer](https://codegolf.stackexchange.com/a/242956/58563). Expects a comma-separated string. ``` a=>(b=[..."123456780"],g=k=>i=b!=a&&k--?g(k,b[(s="83270561")[k+1&7]]=b[p=s[k&7]],b[p]=0):k)(56)>28?56-i:i ``` [Try it online!](https://tio.run/##hc7LCoMwEAXQff@iWUhCR0liXhRGPyS40D7ERqrU0t@3sRRXlu6GuYc7c6tf9XR6dOMzvQ/ny3zFucaCNuizLCNC5kob6zipoMWARYfNHuskCWlatjRA4@mExOXScm0EYT4cRGKrChs/4uTDMkc0VsjZMTCqDSukK7VJu2M3n4b7NPSXrB9aeqVEgIQcFGgwYMEBJ4ztNg1fjfpheFT/jFsN3zRLomImo1qs2DD8e2NpkiA2e1Tc28/PeZQSTDTzGw "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~101~~ 98 bytes ``` ->n{a=[*1..8,0];z=j=-29 ("I`;-XAf#"*7).bytes{|i|j+=1;a==n&&z=j;a[i/9%9],a[i%9]=a[i%9],0} 28-z.abs} ``` [Try it online!](https://tio.run/##VY7djoIwEEbv@xSNZM0uTpEWFAjpJl76BiaEZItCUhNxF/ACf54dp5Q18Wom35k5M82l6IdKDuy7vimZudzzYvDz9CqPkomEfM62PynbbSpn5kZfXtF3ZXu76/txIXmqpKzncxxNVaaXyUeSAzZYpC3gP4iI2dVTRfsYfmmVZRwEBBDCCtYQgTmVU4fqQ1l3uuvpXrUlcfBGN7YtrZrzif5dMNDnmrwUMUqswodwVATUUpOFmArkZoqPlHFL/ems2RbAp91/GmJijCvkMfL1SEVA3l63DrRPu8MT "Ruby – Try It Online") Fairly straightforward. Cycle generates all 56 possible positions and compares with the input. Saved some bytes off the orignal version by counting from the solved position at `-28` through `0` to `+27`, and using `28-z.abs` to decode the output. ]
[Question] [ Given integer `n`, calculate a set of `n` random unique integers in range `1..n^2` (inclusive) such that the sum of the set is equal to `n^2` Random, in this case, means *uniformly* random between valid outputs. Each valid output for a given `n` must have a uniform chance of being generated. For example, `n=3` should have a 1/3 chance each of outputting `6, 1, 2`, `3, 5, 1`, or `4, 3, 2`. As this is a set, order is irrelevant, `4, 3, 2` is identical to `3, 2, 4` ## Scoring The winner is the program that can compute the highest `n` in under 60 seconds. *Note:* To prevent possible partial hardcoding, all entries must be under 4000 bytes ## Testing All code will be run on my local Windows 10 machine (Razer Blade 15, 16GB RAM, Intel i7-8750H 6 cores, 4.1GHz, GTX 1060 in case you want to abuse the GPU) so please provide detailed instructions to run your code on my machine. At request, entries can be run either via Debian on WSL, or on a Xubuntu Virtual Machine (both on the same machine as above) Submissions will be run 50 times in succession, final score will be an average of all 50 results. [Answer] # [Rust](https://www.rust-lang.org/), *n* ≈ 1400 ### How to run Build with `cargo build --release`, and run with `target/release/arbitrary-randomness n`. This program runs fastest with lots of memory (as long as it’s not swapping, of course). You can adjust its memory usage by editing the `MAX_BYTES` constant, currently set at 8 GiB. ### How it works The set is constructed by a sequence of binary decisions (each number is either inside or outside the set), each of whose probabilities are computed combinatorially by counting the number of possible sets constructible after each choice using dynamic programming. Memory usage for large *n* is reduced by using a version of [this binomial partitioning strategy](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.455.4143&rep=rep1&type=pdf). ### `Cargo.toml` ``` [package] name = "arbitrary-randomness" version = "0.1.0" authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"] [dependencies] rand = "0.6" ``` ### `src/main.rs` ``` extern crate rand; use rand::prelude::*; use std::env; use std::f64; use std::mem; const MAX_BYTES: usize = 8 << 30; // 8 gibibytes fn ln_add_exp(a: f64, b: f64) -> f64 { if a > b { (b - a).exp().ln_1p() + a } else { (a - b).exp().ln_1p() + b } } fn split(steps: usize, memory: usize) -> usize { if steps == 1 { return 0; } let mut u0 = 0; let mut n0 = f64::INFINITY; let mut u1 = steps; let mut n1 = -f64::INFINITY; while u1 - u0 > 1 { let u = (u0 + u1) / 2; let k = (memory * steps) as f64 / u as f64; let n = (0..memory) .map(|i| (k - i as f64) / (i as f64 + 1.)) .product(); if n > steps as f64 { u0 = u; n0 = n; } else { u1 = u; n1 = n; } } if n0 - (steps as f64) <= steps as f64 - n1 { u0 } else { u1 } } fn gen(n: usize, rng: &mut impl Rng) -> Vec<usize> { let s = n * n.wrapping_sub(1) / 2; let width = n.min(MAX_BYTES / ((s + 1) * mem::size_of::<f64>())); let ix = |m: usize, k: usize| m + k * (s + 1); let mut ln_count = vec![-f64::INFINITY; ix(0, width)]; let mut checkpoints = Vec::with_capacity(width); let mut a = Vec::with_capacity(n); let mut m = s; let mut x = 1; for k in (1..=n).rev() { let i = loop { let i = checkpoints.len(); let k0 = *checkpoints.last().unwrap_or(&0); if k0 == k { checkpoints.pop(); break i - 1; } if i == 0 { ln_count[ix(0, i)] = 0.; for m in 1..=s { ln_count[ix(m, i)] = -f64::INFINITY; } } else { for m in 0..=s { ln_count[ix(m, i)] = ln_count[ix(m, i - 1)]; } } let k1 = k - split(k - k0, width - 1 - i); for step in k0 + 1..=k1 { for m in step..=s { ln_count[ix(m, i)] = ln_add_exp(ln_count[ix(m - step, i)], ln_count[ix(m, i)]); } } if k1 == k { break i; } checkpoints.push(k1); }; while m >= k && rng.gen_bool((ln_count[ix(m - k, i)] - ln_count[ix(m, i)]).exp()) { m -= k; x += 1; } a.push(x); x += 1; } a } fn main() { if let [_, n] = &env::args().collect::<Vec<_>>()[..] { let n = n.parse().unwrap(); let mut rng = StdRng::from_entropy(); println!("{:?}", gen(n, &mut rng)); } else { panic!("expected one argument"); } } ``` [Try it online!](https://tio.run/##nVZLj9s2EL77V0x8WJBZWyulQVDIj6ItWmAPSQ8NigSLhUHJtE1IogRR2vVm13@97owetigrC6Q62CJnvplvHhwqL01xPJZGginWvi/1w2x0Wm0@vO@sEpnMRqMw1aaAj79@Wf329fMff/tQGvVNwgI8mM/hJ3cGNzf4vlWBCp4KORrJfSFzDePfx/A8AnyyMoCNhnUu9Pr9z4zDdAmVp8NohPuxXon1eiX3GRM@CSYQVP@tYmNGbUDAEoJmSQ8LYAqCO4TlDhry8B@uQVQaB5AxxtJRF6geXKoHtXrDx2SxKpgpZGaaYCeAqUjzp2ZZ8aqzcGJWqcOCsnL2l8uixEy4s8Y@/caygKQsoHQxhY2k3dO0hwH7/u2nP28/3X7@astLD@WVpx6O9qcDwMediiXBpuRvaZEjcIk4hpJr1OFwA@9mljgicR06vK0dcxCmqskNgutXG6MJ4zpODeMnGT1OIjL2ol6ARchINXhyzNoFUvEc3oNlebouw4LxsytMucaA6rQ30GcLVSW4nFl7VYL1ee@iQyqgNwD0esBeRbHSqECkXIyMdWlxmC9snlMyd/ZZusPdWnr1fu0VPTT9uZWa6W4r/iPDebVaNmhiZIgwVk07j7nIMqW3K1MGrFtmUntU62JHqk6iNDudcioJM1QMjjawlr5PDlbpxvfnGMOScc7PVtQeTbwkp@MSNW8vkKCNCE00xuy@xRMYpqWm1D3I8M1dr4XRLHMnNUV@b0PDnQyjLFW6oEAxA77/qIrdKhSZCFXxxGqUDRLDqrqnltAps7coPg@HIe1t0hxDUhqY5zgLzZ1cPuAYsU@WQkCcplmvt1pRh74TYz357EItol59aykKg2fAKTVVdJXm7Mrt4bABCbZAfrZferqmsjTr@6QnyKXA0LBDPVt46LtR5MUd8NLW9K4unuL3NOecS1@UxoTSSFk0A5b61pLW2tCk@z7ZwTNuEXB/lEB/k/LVNugrRC5LTFOFRmF95dBb1DY82aQh2asSkaZhQrwjt5qWziLyXguP1P9HhO2dbMmJK5qr1CYDUP5jSaB@9b7Xr00zvtaIVkuXZscir8Pg0BzY802YwJJ8XV1BqY3YYFd0vkoOMIeLaKM6I9OhWOvviB5zBKELm/QerhfdE3UOQtS09x3WXeVaUTSDPxE4ovn5m4Na6G41AU0Vu8IvOd8X@dbgiAjTOJZhgbOa7obVEsf1nePc92aUruZ@JnIjT2OlOxWyHBMb6zds/Oz/chhP6punnfsX5yoTWoWojFlB33INqZaAhMpE6mLcokaH4/Houe6/4SYWW3Oc/vUf "Rust – Try It Online") (Note: the TIO version has a few modifications. First, the memory limit is reduced to 1 GiB. Second, since TIO doesn’t let you write a `Cargo.toml` and depend on external crates like `rand`, I instead pulled in `drand48` from the C library using the FFI. I didn’t bother to seed it, so the TIO version will produce the same result on every run. Don’t use the TIO version for official benchmarking.) [Answer] # Java 7+, n=50 in ~30 sec on TIO ``` import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.Random; class Main{ public static void main(String[] a){ int n=50; Random randomGenerator = new Random(); int i = n+1; int squaredN = n*n; int[]randomIntegers = new int[i]; randomIntegers[n] = squaredN; while(true){ for(i=n; i-->1; ){ randomIntegers[i] = randomGenerator.nextInt(squaredN); } Set<Integer> result = new HashSet<>(); Arrays.sort(randomIntegers); for(i=n; i-->0; ){ result.add(randomIntegers[i+1] - randomIntegers[i]); } if(!result.contains(0) && result.size()==n){ System.out.println(result); return; } } } } ``` Ungolfed version of [my answer for the code-golf version of this challenge](https://codegolf.stackexchange.com/a/176296/52210) for now, with only one minor change: [`java.util.Random#nextInt(limit)`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) is used instead of [`(int)(Math.random()*limit)`](https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()) for an integer in the range `[0, n)`, since it's about [twice as fast](https://stackoverflow.com/a/738651/1682559). [Try it online.](https://tio.run/##bVKxbsIwEN3zFdcFOUWJYOgUgtSp7dAOZUQZXGLgaHKh9gVKK749dYgJDWHxSe89v3vn80buZLBJP6sK822hGTYWCEvGLHzUWh5M5PWIZ2nWM8U3mNvou6S0yCNvkUlj4FUi/XoA2/IjwwUYlmzLrsAUckuJGWuk1TwB6dcygNOBxEDxwyi6QI0t6FN5UqS05EJDDKT2jhR@1N7GmhmOL4D5KqVW6VuN31OLz5PG8YVYrZQ2zrBmMGlUXcGcEqs5uzWK/RozJViXyg0BsCy0wJgiwCCYjiNoiZ4f1n5XY4WkvtkqxLmPmwzg6Kp9@4mzmIJWpszYRXf7mkxFe6nZbWjsokS3eyvp5B11857cQ5mm4jr6cJxA0B@olxaX4s7ZLApiu3gjRj4MBmdzgz9K@HFM//rODoZVHhYlh1v7STgj0ahb@zobl5q67erz6B2r6g8) ## Explanation: **Approach used:** The code is split into two parts: 1. Generate a list of `n` amount of random integers that sum to `n squared`. 2. Then it checks if all values are unique and none are zero, and if either is falsey, it will try step 1 again, rinsing and repeating until we have a result. Step 1 is done with the following sub-steps: 1) Generate an array of `n-1` amount of random integers in the range `[0, n squared)`. And add `0` and `n squared` to this list. This is done in `O(n+1)` performance. 2) Then it will sort the array with the builtin [`java.util.Arrays.sort(int[])`](https://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort(int[])), This is done in `O(n*log(n))` performance, as is stated in the docs: > > Sorts the specified array of ints into ascending numerical order. The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n\*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. > > > 3) Calculate the difference between each pair. This resulting list of differences will contain `n` integers that sum to `n squared`. This is done in `O(n)` performance. Here an example: ``` // n = 4, nSquared = 16 // n-1 amount of random integers in the range [0, nSquared): [11, 2, 5] // Add 0 and nSquared to it, and sort: [0, 2, 5, 11, 16] // Calculate differences: [2, 3, 6, 5] // The sum of these differences will always be equal to nSquared sum([2, 3, 6, 5]) = 16 ``` So these three steps above are pretty good for performance, unlike step 2 and the loop around the whole thing, which is a basic brute-force. Step 2 is split in these sub-steps: 1) The differences list is already saved in a `java.util.Set`. It will check if the size of this Set is equal to `n`. If it is, it means all random values we generated are unique. 2) And it will also check that it contains no `0` in the Set, since the challenge asks for random values in the range `[1, X]`, where `X` is `n squared` minus the sum of `[1, ..., n-1]`, as stated by *@Skidsdev* in the comment below. If either of the two options above (not all values are unique, or a zero is present), it will generate a new array and Set again by resetting to step 1. This continues until we have a result. Because of this, the time can vary quite a bit. I've seen it finish in 3 seconds once on TIO for `n=50`, but also in 55 seconds once for `n=50`. **Prove of uniformity:** I'm not entirely sure how to prove this to be completely honest. The [`java.util.Random#nextInt`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt--) is uniform for sure, as is described in the docs: > > Returns the next pseudorandom, uniformly distributed `int` value from this random number generator's sequence. The general contract of `nextInt` is that one `int` value is pseudorandomly generated and returned. All 232 possible `int` values are produced with (approximately) equal probability. > > > The differences between these (sorted) random values themselves are of course not uniform, but the sets as a whole are uniform. Again, I'm not sure how to prove this mathematically, but [here is a script that will put `10,000` generated sets (for `n=10`) in a Map with a counter](https://tio.run/##bZLBbtswDIbveQo2h0JuasG@2nWAoRiGYsgOy7BLloNms5kyW/Ikuk025Nkz2XKcuGkOkiP@/PlR1Fa8iHBb/D4eZVVrQ7B1B7whWfK7dJKXwlpYCKn@TQDq5mcpc7AkyG0vWhZQuRBbkpFqs1qDCFoZQLdIRaCyOErPR1@FKnQFpts@oUIjSBvIQOFrH2RBOmTLTM3i81/7pxEGiy@ZulPD6Wrt3Z4U4QaN7c3aiFx71ViwUmunOXldwC1E/eA7uYdePIdGyWdtKkl7F@69vxnEVjy/ZCW01BaPI/fzx6@/ZInMB24yiPrLAXCOzPWWggzDeZzCELhilS3rm@viCnfkFOzUQ08BcOj3JdLD0IFB25R0gd5GB3SAD8aIveXWzZ6Nqw@SEW805u3cuSgK9hZ9Fq/Dq3auWOUzu@lNcq3IPSfLogBub0/WVv5FFmSZuqg6mgqv0GyQ9XLSfoYsuId4GGSS2KYaaoOfVhiOYfxau2xiowpd4mHilsun74XvvprK5Xja5d4SVlw3xDt9qdh0IXag87wxBlWOCUxnj7osMSepleWV2DGXz1GR2btZtY086qoWfvh59@nKPfni/GOrS5IN0ndRNhgEfZsOH86Ca8bOHxIY1wpguOV30Dsdd6U@454FMINp8oOmbh8CHQM7MRy6ezscj/8B), where most sets are unique; some repeated twice; and the maximum repeated occurrence is usually in the range `[4,8]`. **Installation instructions:** Since Java is a pretty well-known language with plenty of information available on how to create and run Java code, I will keep this short. All the tools used in my code are available in Java 7 (perhaps even already in Java 5 or 6, but let's use 7 just in case). I'm pretty sure Java 7 is already archived though, so I would suggest downloading Java 8 to run my code. **Thoughts regarding improvements:** I'd like to find an improvement for the check for zeros and check all values are unique. I could check for `0` before, by making sure the random value we add to the array isn't already in it, but it would mean a couple of things: the array should be an `ArrayList` so we can use the builtin method `.contains`; a while-loop should be added until we've found a random value that isn't in the List yet. Since checking for zero is now done with `.contains(0)` on the Set (which is only checked once), it's most likely better for performance to check it at that point, in comparison to adding the loop with `.contains` on the List, which will be checked at least `n` times, but most likely more. As for the uniqueness check, we only have our `n` amount of random integers that sum to `n squared` after step 1 of the program, so only then we can check whether all are unique or not. It might be possible to keep a sortable List instead of array, and check the differences in between, but I seriously doubt it will improve the performance than just putting them in a `Set` and check if the size of that Set is `n` once. [Answer] ## Mathematica n=11 ``` (While[Tr@(a=RandomSample[Range[#^2-#(#-1)/2],#])!=#^2];a)& ``` [Answer] # Scala, n=50 in ~45 sec on TIO Port of [@Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/a/176312/110802) in Scala. [Try it online!](https://tio.run/##lVI9U8MwDN3zK8TSs@kl1w4sPTowAQMM9Ji4Dm6itgZHbm2HUrj@9qB8laad8BDfi56eniT7VBlVljrfWBfAVygpgjbJi6LM5lEvkFpjMA3aUpIXQS0MJg/Kr2cYosgu3jkET0oT/EQAGS4hZyCUW/kJ3Dmn9m@z4DSt5nICr6QDTJnJVIBPZYAY3oyO0NX175HQqWAdBwl30LgS8kjz20I5zJ6rOFwDtQHX5j9SwBU636Y3LvjnXBAMYdzo9KmCJLM73cbfbq0NiuAKlHVz1VlaJzTcxkDxGIKFESz2EI//CBfCuhI@6ysh/ArMEF1B2WYf2rueBfrCVONqp9100DFPljbjXfGAk22h048KiL4F@Q/vdc1EZZk4b2PIxPiyuXPneimuWpXUUuC34MVIwmDQaXv9jTDlzZzW3fALCYZEw5EnfkLhqFei@h6iQ1SWvw) ``` import scala.util.Random import scala.collection.mutable.HashSet object Main { def main(args: Array[String]): Unit = { val n = 50 val randomGenerator = new Random() val squaredN = n * n var randomIntegers = new Array[Int](n + 1) randomIntegers(n) = squaredN while(true) { for(i <- n-1 to 0 by -1) { randomIntegers(i) = randomGenerator.nextInt(squaredN) } val result = HashSet[Int]() scala.util.Sorting.quickSort(randomIntegers) for(i <- n-1 to 0 by -1) { result.add(randomIntegers(i+1) - randomIntegers(i)) } if(!result.contains(0) && result.size == n) { println(result) return } } } } ``` [Answer] # [Python](https://www.python.org), *n* ≈ 4500 Runs in expected \$Θ(n^{5/2})\$ time. ``` import numpy as np def gen(n): target = n**2 k_bounds = [1 / ((n + 1) / 2 - target / n), 1 / ((n + 1) / 4 - target / n)] i = np.arange(n) while (k := (k_bounds[0] + k_bounds[1]) / 2) not in k_bounds: p = -np.expm1(k * (n - i)) k_bounds[int(((n - i) / p).sum() > target)] = k rng = np.random.default_rng() while True: output = rng.geometric(p=p).cumsum() if output.sum() == target: return output ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZFBTsMwEEXFNqeYpR1ImlQsUKVwCnZVVIXGSa3UY8uxBT0Lm25gzVFYcxomjpsCXkTOn-8_z563D3NyB43n87t3XfbwffMlldHWAXplTtCMgCZJWtFBL5Ah3yRAyzW2Fw4qwDRdB2XYPWuP7UjatoQVMIZwCyWn7Rqyy4EVIL-Df_X7v_U65Mkp3OSNbbAX1DeILwd5FMAG2FT0jR23RU1Jy19Zh54cUDuQuBRm8GkZis4oW7waVVJYCsSSgeR8sSxpEh1jsUyxhuejV4zDYyTmNYUNSThosZ-hibnVKqdHa_zR7Uhnv_mfrBdXGu2d8dNTki3vhVbCWblnpqJee69Cu8Usu-iPGFUVOa55gUQ4bzFa58F-GjvdZRpiWRQF57N8mfsP) ### How it works After selecting a constant \$k < 0\$ (explained below), we draw \$n\$ positive integers \$a\_0, a\_1, …, a\_{n-1}\$ independently from the geometric distributions of probabilities \$p\_i = 1 - e^{k(n - i)}\$. We build a candidate set from the prefix sums of the \$a\_i\$: $$S = \{a\_0, a\_0 + a\_1, …, a\_0 + a\_1 + … + a\_{n-1}\}.$$ The probability of generating any particular \$S\$ can be computed as $$\prod\_i (1 - p\_i)^{a\_i} p\_i = \prod\_i e^{k(n - i)a\_i} p\_i = e^{k \sum\_i (n - i)a\_i} \prod\_i p\_i = e^{k \sum S} \prod\_i p\_i,$$ which is proportional to \$e^{k \sum S}\$. In particular, the probability of generating each \$S\$ that sums to \$n^2\$ is the same! We accept \$S\$ if it sums to \$n^2\$, otherwise reject it and repeat the draw. Although the constant \$k\$ has no effect on correctness, it has a huge effect on the expected running time. We select \$k\$ using a binary search such that \$E[\sum S] = \sum\_i \frac{n - i}{p\_i}\$ is made equal to \$n^2\$, in order to optimize the probability of acceptance to \$Θ(n^{-3/2})\$. ]
[Question] [ If you have ever had any exposure to Japanese or East Asian culture you will have surely encountered the Amidakuji game: [![enter image description here](https://i.stack.imgur.com/TCkPr.jpg)](https://i.stack.imgur.com/TCkPr.jpg) As [Wikipedia explains](https://en.wikipedia.org/wiki/Ghost_Leg), it is a type of lottery drawn on paper and used to randomly select a permutation of N items. For example, it may be used to randomly assign a starting sequence to N people, or N prizes to N people, and so on. The trick to understanding why the game represents a permutation is to realize that every horizontal stroke (called a "leg") **swaps** its two items in place. The same Wikipedia page also explains that each permutation P of N items corresponds to an infinite number of Amidakuji diagrams. The one(s) with the least number of horizontal strokes (legs) are called the "primes" of that particular permutation P. Your task is to receive an Amidakuji diagram with 2 or more vertical lines (in this example they are 6) in this format (minus the letters): ``` A B C D E F | | | | | | |-| |-| |-| | |-| |-| | | | | | |-| | |-| |-| | | | |-| |-| | | |-| | | |-| | |-| | |-| |-| | | | |-| | |-| | | | | | | B C A D F E ``` And produce one of its primes (again, minus the letters): ``` A B C D E F | | | | | | |-| | | |-| | |-| | | | | | | | | | B C A D F E ``` The first and last lines with the letters are **not** part of the format. I have added them here to show the permutation. It is also **not** required that the first or last lines contain no legs `|-|`, **nor** that the output be as compact as possible. This particular input example is one of the (infinite) ASCII representations of the Amidakuji diagram at the top of the Wikipedia page. There is one non-obvious rule about these ASCII diagrams: adjacent legs are forbidden. ``` |-|-| <- NO, this does not represent a single swap! ``` Wikipedia explains a standard procedure to obtain a prime from a diagram, called "bubblization", which consists of applying the following simplifications over and over: 1) Right fork to left fork: ``` | |-| |-| | |-| | -> | |-| | |-| |-| | ``` 2) Eliminating doubles: ``` |-| | | |-| -> | | ``` I am not sure whether that explanation is unambiguous. Your code may use that technique or any other algorithm that produces the required primes. **Shortest code wins.** Standard rules and standard allowances apply. (If the input is not valid, your program may catch fire. Input/output formats may be stdin/stdout, string argument, list of lines, matrix of chars, whatever works best for you, etc.) [![enter image description here](https://i.stack.imgur.com/YchSY.jpg)](https://i.stack.imgur.com/YchSY.jpg) [Answer] # [Python 2](https://docs.python.org/2/), ~~322~~ 240 bytes ``` def f(X): X=[[c>' 'for c in s.split('|')]for s in X.split('\n')];h=L=len(X[0])-1;p=range(L) for x in X:p=[a-x[a]+x[a+1]for a in p] while h:h=i=0;exec"if p[i]>p[i+1]:print'|'+i*' |'+'-|'+(L-i-2)*' |';h=p[i],p[i+1]=p[i+1],p[i]\ni+=1\n"*~-L ``` [Try it online!](https://tio.run/##nVJNj5swED3Hv2KUi3GI05BV9@DUK60q9ZTTdlVFIhwQOIurYCwg2VRN@9ezY0NJutqq0oKwh@f5eH4z9kdbVGZxPudqC9tgzQSBtYzj7I4C3VY1ZKANNLPG7nQb0BNliUMbh67/oBuD8LKQK7lTJljH84TxaGllnZonFawYARdz9DHCyjjlxzhNQlzCyKdL3ZFNCDwXeqegEIXUcr5UR5WN9RZsrJM7XNBb2FqbFnmEekIBN8pxCVZc8wXzCPJw/tPOX3ab@0s2Rocy2pjx5DdfnR9BAqX0xE/Qf2SwwNvd@xZ@8e9sh/PhjwzeMMRe/LsXKxOiS1vVLaBMeVUS1wGr6vJLVZe@ESNsBHYhbMK@F2@pfqX5h8WV5st7GbueRGT0SvzwJ8oEVMynqB3uPJoiwKmIfsXHeDFJRRKLm@Svxoxq1e5rNImn@aTMfanzNDD78ttKG9VMAc2H6rlxvGvVoLgxhnX9dAwRY596H3QZ1V7@2fdK45kXYJYVlc5UQIFzylx17ap3FxoK8YgxDMepMFULFF29kwBXNMSqbjbw6zMzZ1/4O9H6E@TTXaZVTdvpbZHTVQcQcMMGVF49dEChz5QVdXD7MTx4yocLZXdry9iQZv2vSDvTJlfH4MD@k2JI8KDyfaZy8R4y2@ubvZsJ6RKMH1E8@Jw2SsCYeCUf2XD4tSpVP92gjmlpd6oRY/KqtTdOeh86jNXtNJpjrfP5BQ "Python 2 – Try It Online") A function which takes the string in the specified form, and prints out the reduced Amidakuji in that form as well. The basic idea here is to first convert the input into a permutation (in the `for x in X` loop); and then in the `while` loop, perform a bubble sort of that permutation, since as the wikipedia article notes, this results in a 'prime' Amidakuji. [Answer] # [Haskell](https://www.haskell.org/), 288 bytes ``` p x(_:[])=x p(x:y:z)(_:b:c)|b=='-'=y:p(x:z)c|0<1=x:p(y:z)c c 0='-' c _=' ' _#1="|" m#n='|':c m:(m-1)#(n-1) p?q=(p:fst q,snd q) f%b|b==f b=b|0<1=f%f b f l=reverse$snd$(g 0)%(foldl p[1..n]l,[])where n=1+div(length$l!!0)2;g b((x:y:z),a)|x>y=y?g(b+1)(x:z,a++[b#n])|0<1=x?g(b+1)(y:z,a);g _ x=x ``` [Try it online!](https://tio.run/##bU/BcoMgEL3zFdtoRhg1oz3S0Bx6bU89ZjKOKJpMkRC1KWb8d4sxsTmUHZbHe49ddp82X0LKYdBgcEK3O8IM0tjQjl6IJTjNSM8Z80KPdXQULiTro3XMjL2NpgxlEI26PRPmgYcSJ2aLfoEqRzGv92gGFcVVGBMHK5uR3pwY1rRoWjgFjcrhRFCx5GObAjjj1/LF0mJUgGS1OIu6Ea51uriEiCxxcZS5BL2NVyu1k4H99c9e1AIUi/38cMZSqLLdu/LpKSLPLyVwfJsoSElvXjvWbUrM/ZiM8wSp72@5o3ZkmusudaNE7OsEDDNDlR4UMMiPCG7LwDqEUrRvR9UK1TazUKX6A/R3@9nW7wpcKADLgxINGIKGHuZAfWjztNGM4Iqn@I//80/4XufuCR94mBX02PcX "Haskell – Try It Online") ### Explanation ``` -- the function p performs the permutation of a list -- according to a single line from amidakuji board p x (_:[]) = x p (x:y:z) (_:b:c) | b == '-' = y : p (x : z) c | otherwise = x : p (y : z) c -- helper to select either leg '-' or empty cell c 0 = '-' c _ = ' ' -- the # operator generates an amidakuji line containing one leg -- which corresponds to one swap during bubble sort -- terminal case, just one edge left _ # 1 = "|" -- each cell contains an edge '|' and either space or a '-' for the "active" cell m # n = '|' : c m : (m - 1) # (n - 1) -- helper to find the limit value of a function iteration f % b | b == f b = b -- return the value if it is unchanged by the function application | otherwise = f % f b -- otherwise repeat -- helper to appropriately combine q which is the result of invocation of -- the function g (see below), and a character p p ? q = (p : fst q, snd q) -- the function that does the work f l = reverse $ snd $ (g 0) % (foldl p [1..n] l, []) where -- number of lines on the board n = 1 + div (length $ l !! 0) 2 -- apply one iteration of bubble sort yielding (X, Y) -- where X is partially sorted list and Y is the output amidakuji g b ((x:y:z), a) -- if we need to swap two elements, do it and add a line to our board | x > y = y ? g (b + 1) (x:z, a ++ [b # n]) -- if we don't need to, just proceed further | otherwise = x ? g (b + 1) (y:z, a) -- terminal case when there is only one element in the list g _ x = x ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 105 bytes ``` $ ¶$%` r`.?.\G 1$.'$* +r-1=`\|(-?.?[- 1]*¶.*)(1+) $2$1 - 1G` ;{`\b(1+) \1 $1-$1 *`1+ | (1+)-(1+) $2 $1 ``` [Try it online!](https://tio.run/##bYsxDsIwDEX3fwoPRrSJHMmsCHXsIQiSQWJgYYjYyLl6gF4sJbQKC7Js/f/8f7q/Hs9rKYx54p0hWRhCHEHKYc8OPomeLOZOhjCchfTi5im4vlPfgw@sEBB0NBzfFm8VU1SwyuflTD0yKpStQKylZMm0LZqir17nH//lV125NIeWptatdwE "Retina 0.8.2 – Try It Online") Explanation: ``` $ ¶$%` ``` Duplicate the last line. ``` r`.?.\G 1$.'$* ``` Number the columns in the last line. ``` +r-1=`\|(-?.?[- 1]*¶.*)(1+) $2$1 ``` Move the numbers up until they get to the first line. At each iteration, only the rightmost number `-1=` is moved. It is moved to the rightmost `|` unless it is preceded by a `-` in which case it is moved to the previous `|`. (The `r` indicates that the regex is processed as if it was a lookbehind, which makes it marginally easier to match this case.) This calculates the permutation that the Amidakuji transforms into sorted order. ``` - 1G` ``` Keep just the list of numbers, deleting the `-`s and anything after the first line. ``` ;{` ``` The rest of the program then is then repeated sort the list back into order, but the final list is not printed, however as it takes an iteration for Retina 0.8.2 to notice that the list is in order, a line with no legs is generated at the end, which I believe is acceptable. ``` \b(1+) \1 $1-$1 ``` Mark all available pairs of adjacent unsorted numbers with `-`s for the legs. ``` *`1+ | ``` Print the legs but with the numbers replaced with `|`s. ``` (1+)-(1+) $2 $1 ``` Actually perform the swaps. [Answer] # [Python 3](https://docs.python.org/3/), ~~524~~ ~~488~~ 486 bytes *-38 bytes thanks to ovs!* ``` from numpy import* A=array;E=array_equal K=[0] def r(a,m,n): X=len(m);Y=len(m[0]);W,H=a.shape for x in range(W-X+1): for y in range(H-Y+1): if E(a[x:x+X,y:y+Y],A(m)):a[x:x+X,y:y+Y]=A(n) return a def p(a): b=A([[j>" "for j in i]for i in[i.split("|")for i in a.split("\n")]]) while E(a,b)<1:a=b;Z=K*3;O=[0,1,0];T=[K+O,O+K]*2;D=[O,O],[Z,Z];P=[Z,O],[O,Z];*R,_=T;_,*L=T;b=r(r(r(r(r(r(a[any(a,1)],R,L),*D),*P),L,R),*D),*P) for i in a:print("",*[" -"[j]for j in i[1:-1]],"",sep="|") ``` [Try it online!](https://tio.run/##hVDRasIwFH22XxHy1LQ3sm5vzTIQHAwUFBGmZkEiqzNiYxaVWfDfXdJOZXsZob3n3HOScxNb7Vdb83A@L922ROZQ2grp0m7dPok6XDmnKvbc1HnxeVCbqMfFnYzeiyVysYISDMmj1oRvChOXhE0b4C2EvcILV@3dStkiai23Dh2RNsgp81HEr3SSZmFnLVQ34YVOf4SWXqLnWIljfkwnUOVVOpXQ8SEk/93kndiQqOWK/cEZpOrZbKzCIQuvCbF@wgiHnHXI0TJA7aHQ7Z3d6H2MT5hcmkhdmm8GEyn9yV8rvSnCLLAgj1mu@ILNeC95YAP/FpDBnWRjLnrpAAZpTyb3rMuFxxLEDGaSDbmvgQ0CS0Yw52M2h6Tvy4K7@LaUUKbyMRmRMII@gaTrvyGBPoyupHnLZtTcOm38qBgSgRHFYi1v9xRZTjMpwau7wvJwybP1XnyiJ1Qveorqf8MumNaYXll0daN//H899JfHJ5PzNw "Python 3 – Try It Online") This converts the Amidakuji to a 2D binary array, and directly reduces it using the rules. [Answer] # [Stax](https://github.com/tomtheisen/stax), 45 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ⌐φ²MC½↕uö∩┴║%≤Oo╧i╕ïô§ê{δ¿k>┴ê◘►╢lµ∙→Z↔8╨─(·£ ``` [Run and debug it](https://staxlang.xyz/#p=a9edfd4d43ab127594efc1ba25f34f6fcf69b88b9315887beba86b3ec1880810b66ce6f91a5a1d38d0c428fa9c&i=%7C+%7C+%7C+%7C+%7C+%7C%0A%7C-%7C+%7C-%7C+%7C-%7C%0A%7C+%7C-%7C+%7C-%7C+%7C%0A%7C+%7C+%7C+%7C+%7C-%7C%0A%7C+%7C-%7C+%7C-%7C+%7C%0A%7C+%7C+%7C-%7C+%7C-%7C%0A%7C+%7C+%7C-%7C+%7C+%7C%0A%7C-%7C+%7C+%7C-%7C+%7C%0A%7C-%7C+%7C-%7C+%7C+%7C%0A%7C+%7C-%7C+%7C+%7C-%7C%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%0A%7C-%7C+%7C-%7C+%7C%0A%7C+%7C-%7C+%7C-%7C%0A%7C-%7C+%7C-%7C+%7C%0A%7C+%7C-%7C+%7C-%7C%0A%0A%7C-%7C%0A%7C-%7C%0A%7C-%7C%0A%0A%7C+%7C-%7C+%7C%0A%7C+%7C+%7C-%7C%0A%7C-%7C+%7C+%7C%0A%7C+%7C+%7C-%7C%0A%7C+%7C-%7C+%7C%0A&a=1&m=1) ]
[Question] [ As per [Luke's request](https://codegolf.stackexchange.com/questions/68678/tic-tac-toe-with-only-crosses#comment168138_68678) and [Peter Taylor's addition](https://codegolf.stackexchange.com/a/69097/34388) to this challenge. ### Introduction Everyone knows the game tic-tac-toe, but in this challenge, we are going to introduce a little twist. We are only going to use **crosses**. The first person who places three crosses in a row loses. An interesting fact is that the maximum amount of crosses before someone loses, is equal to **6**: ``` X X - X - X - X X ``` That means that for a 3 x 3 board, the maximum amount is **6**. So for N = 3, we need to output 6. Another example, for N = 4, or a 4 x 4 board: ``` X X - X X X - X - - - - X X - X ``` This is an optimal solution, you can see that the maximum amount of crosses is equal to **9**. An optimal solution for a 12 x 12 board is: ``` X - X - X - X X - X X - X X - X X - - - X X - X - X - X - X X - - - X X X - - - X X - X X - X - - X X - - - X - - - - X X X - X X - X - X X - - - - X X - X - X X - X X X - - - - X - - - X X - - X - X X - X X - - - X X X - - - X X - X - X - X - X X - - - X X - X X - X X - X X - X - X - X ``` This results in **74**. ### The task Your task is to compute the results as fast as possible. I will run your code on the test case `13`. This will be done 5 times and then the average is taken of the run times. That is your final score. The lower, the better. ### Test cases ``` N Output 1 1 2 4 3 6 4 9 5 16 6 20 7 26 8 36 9 42 10 52 11 64 12 74 13 86 14 100 15 114 ``` More information can be found at <https://oeis.org/A181018>. ### Rules * This is [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'"), so the fastest submission wins! * You must provide a *full program*. * Please also provide how I have to run the program. I am not familiar with all programming languages and how they work, so I need a little bit of help here. * Of course, your code needs to compute the *correct* result for each test case. ### Submissions: * **feersum** (C++11): 28s * **Peter Taylor** (Java): 14m 31s [Answer] ## Java, 14m 31s This is essentially the program which I posted to OEIS after using it to extend the sequence, so it's a good reference for other people to beat. I've tweaked it to take the board size as the first command-line argument. ``` public class A181018 { public static void main(String[] args) { int n = Integer.parseInt(args[0]); System.out.println(calc(n)); } private static int calc(int n) { if (n < 0) throw new IllegalArgumentException("n"); if (n < 3) return n * n; // Dynamic programming approach: given two rows, we can enumerate the possible third row. // sc[i + rows.length * j] is the greatest score achievable with a board ending in rows[i], rows[j]. int[] rows = buildRows(n); byte[] sc = new byte[rows.length * rows.length]; for (int j = 0, k = 0; j < rows.length; j++) { int qsc = Integer.bitCount(rows[j]); for (int i = 0; i < rows.length; i++) sc[k++] = (byte)(qsc + Integer.bitCount(rows[i])); } int max = 0; for (int h = 2; h < n; h++) { byte[] nsc = new byte[rows.length * rows.length]; for (int i = 0; i < rows.length; i++) { int p = rows[i]; for (int j = 0; j < rows.length; j++) { int q = rows[j]; // The rows which follow p,q cannot intersect with a certain mask. int mask = (p & q) | ((p << 2) & (q << 1)) | ((p >> 2) & (q >> 1)); for (int k = 0; k < rows.length; k++) { int r = rows[k]; if ((r & mask) != 0) continue; int pqrsc = (sc[i + rows.length * j] & 0xff) + Integer.bitCount(r); int off = j + rows.length * k; if (pqrsc > nsc[off]) nsc[off] = (byte)pqrsc; if (pqrsc > max) max = pqrsc; } } } sc = nsc; } return max; } private static int[] buildRows(int n) { // Array length is a tribonacci number. int c = 1; for (int a = 0, b = 1, i = 0; i < n; i++) c = a + (a = b) + (b = c); int[] rows = new int[c]; int i = 0, j = 1, val; while ((val = rows[i]) < (1 << (n - 1))) { if (val > 0) rows[j++] = val * 2; if ((val & 3) != 3) rows[j++] = val * 2 + 1; i++; } return rows; } } ``` Save to `A181018.java`; compile as `javac A181018.java`; run as `java A181018 13`. On my computer it takes about 20 minutes to execute for this input. It would probably be worth parallelising it. [Answer] # C++11, 28s This also uses a dynamic programming approach based on rows. It took 28 seconds to run with argument 13 for me. My favorite trick is the `next` function which uses some bit bashing for finding the lexicographically next row arrangement satisfying a mask and the no-3-in-a-row rule. ### Instructions 1. Install the latest [MinGW-w64](https://sourceforge.net/projects/mingw-w64/) with SEH and Posix threads 2. Compile the program with `g++ -std=c++11 -march=native -O3 <filename>.cpp -o <executable name>` 3. Run with `<executable name> <n>` ``` #include <vector> #include <stddef.h> #include <iostream> #include <string> #ifdef _MSC_VER #include <intrin.h> #define popcount32 _mm_popcnt_u32 #else #define popcount32 __builtin_popcount #endif using std::vector; using row = uint32_t; using xcount = uint8_t; uint16_t rev16(uint16_t x) { // slow static const uint8_t revbyte[] {0,128,64,192,32,160,96,224,16,144,80,208,48,176,112,240,8,136,72,200,40,168,104,232,24,152,88,216,56,184,120,248,4,132,68,196,36,164,100,228,20,148,84,212,52,180,116,244,12,140,76,204,44,172,108,236,28,156,92,220,60,188,124,252,2,130,66,194,34,162,98,226,18,146,82,210,50,178,114,242,10,138,74,202,42,170,106,234,26,154,90,218,58,186,122,250,6,134,70,198,38,166,102,230,22,150,86,214,54,182,118,246,14,142,78,206,46,174,110,238,30,158,94,222,62,190,126,254,1,129,65,193,33,161,97,225,17,145,81,209,49,177,113,241,9,137,73,201,41,169,105,233,25,153,89,217,57,185,121,249,5,133,69,197,37,165,101,229,21,149,85,213,53,181,117,245,13,141,77,205,45,173,109,237,29,157,93,221,61,189,125,253,3,131,67,195,35,163,99,227,19,147,83,211,51,179,115,243,11,139,75,203,43,171,107,235,27,155,91,219,59,187,123,251,7,135,71,199,39,167,103,231,23,151,87,215,55,183,119,247,15,143,79,207,47,175,111,239,31,159,95,223,63,191,127,255}; return uint16_t(revbyte[x >> 8]) | uint16_t(revbyte[x & 0xFF]) << 8; } // returns the next number after r that does not overlap the mask or have three 1's in a row row next(row r, uint32_t m) { m |= r >> 1 & r >> 2; uint32_t x = (r | m) + 1; uint32_t carry = x & -x; return (r | carry) & -carry; } template<typename T, typename U> void maxequals(T& m, U v) { if (v > m) m = v; } struct tictac { const int n; vector<row> rows; size_t nonpal, nrows_c; vector<int> irow; vector<row> revrows; tictac(int n) : n(n) { } row reverse(row r) { return rev16(r) >> (16 - n); } vector<int> sols_1row() { vector<int> v(1 << n); for (uint32_t m = 0; !(m >> n); m++) { auto m2 = m; int n0 = 0; int score = 0; for (int i = n; i--; m2 >>= 1) { if (m2 & 1) { n0 = 0; } else { if (++n0 % 3) score++; } } v[m] = score; } return v; } void gen_rows() { vector<row> pals; for (row r = 0; !(r >> n); r = next(r, 0)) { row rrev = reverse(r); if (r < rrev) { rows.push_back(r); } else if (r == rrev) { pals.push_back(r); } } nonpal = rows.size(); for (row r : pals) { rows.push_back(r); } nrows_c = rows.size(); for (int i = 0; i < nonpal; i++) { rows.push_back(reverse(rows[i])); } irow.resize(1 << n); for (int i = 0; i < rows.size(); i++) { irow[rows[i]] = i; } revrows.resize(1 << n); for (row r = 0; !(r >> n); r++) { revrows[r] = reverse(r); } } // find banned locations for 1's given 2 above rows uint32_t mask(row a, row b) { return ((a & b) | (a >> 1 & b) >> 1 | (a << 1 & b) << 1) /*& ((1 << n) - 1)*/; } int calc() { if (n < 3) { return n * n; } gen_rows(); int tdim = n < 5 ? n : (n + 3) / 2; size_t nrows = rows.size(); xcount* t = new xcount[2 * nrows * nrows_c]{}; #define tb(nr, i, j) t[nrows * (nrows_c * ((nr) & 1) + (i)) + (j)] // find optimal solutions given 2 rows for n x k grids where 3 <= k <= ceil(n/2) + 1 { auto s1 = sols_1row(); for (int i = 0; i < nrows_c; i++) { row a = rows[i]; for (int j = 0; j < nrows; j++) { row b = rows[j]; uint32_t m = mask(b, a) & ~(1 << n); tb(3, i, j) = s1[m] + popcount32(a << 16 | b); } } } for (int r = 4; r <= tdim; r++) { for (int i = 0; i < nrows_c; i++) { row a = rows[i]; for (int j = 0; j < nrows; j++) { row b = rows[j]; bool rev = j >= nrows_c; auto cj = rev ? j - nrows_c : j; uint32_t m = mask(a, b); for (row c = 0; !(c >> n); c = next(c, m)) { row cc = rev ? revrows[c] : c; int count = tb(r - 1, i, j) + popcount32(c); maxequals(tb(r, cj, irow[cc]), count); } } } } int ans = 0; if (tdim == n) { // small sizes for (int i = 0; i < nrows_c; i++) { for (int j = 0; j < nrows; j++) { maxequals(ans, tb(n, i, j)); } } } else { int tdim2 = n + 2 - tdim; // get final answer by joining two halves' solutions down the middle for (int i = 0; i < nrows_c; i++) { int apc = popcount32(rows[i]); for (int j = 0; j < nrows; j++) { row b = rows[j]; int top = tb(tdim2, i, j); int bottom = j < nrows_c ? tb(tdim, j, i) : tb(tdim, j - nrows_c, i < nonpal ? i + nrows_c : i); maxequals(ans, top + bottom - apc - popcount32(b)); } } } delete[] t; return ans; } }; int main(int argc, char** argv) { int n; if (argc < 2 || (n = std::stoi(argv[1])) < 0 || n > 16) { return 1; } std::cout << tictac{ n }.calc() << '\n'; return 0; } ``` [Answer] # matlab, cplex, baseline? This code is modified from the MATLAB code provided on [A181018](https://oeis.org/A181018) ## how to run? 1. download `cplex` and `yalmip` folder, then place them in matlab `toolbox` folder 2. matlab ui, HOME->Set Path->Add Folder With Subfolders, add the 2 folders and their subfolders to path 3. run `main.m` ``` % A181018.m function v = A181018(n) % Grid = [1:n]' * ones(1, n) + n*ones(n, 1)*[0:n-1]; f = -ones(n^2, 1); A = sparse(4*(n-2)*(n-1), n^2); count = 0; for i =1:n for j = 1:n-2 count = count+1; A(count, [Grid(i, j), Grid(i, j+1), Grid(i, j+2)]) = 1; end end for i = 1:n-2 for j = 1:n count = count+1; A(count, [Grid(i, j), Grid(i+1, j), Grid(i+2, j)]) = 1; end end for i = 1:n-2 for j = 1:n-2 count = count+2; A(count-1, [Grid(i, j+2), Grid(i+1, j+1), Grid(i+2, j)]) = 1; A(count, [Grid(i, j), Grid(i+1, j+1), Grid(i+2, j+2)]) = 1; end end b = 2*ones(4*(n-2)*(n-1), 1); options = cplexoptimset; options.MaxTime = 120; options.Algorithm = 'auto'; % [x, v, exitflag, output] = cplexbilp(f, A, b,options); [~, v, ~, ~] = cplexbilp(f, A, b,options); % Solve binary integer programming problems. v=-v; end ``` ``` % main.m clear all;close all;clc; tic for n = 1:11 A(n) = A181018(n); end A % Robert Israel, Jan 14 2016 toc ``` ## Reference See [*Getting Started with CPLEX for MATLAB*](https://www.researchgate.net/profile/Mohamed_Mourad_Lafifi/post/do_cplex_solver_in_GAMS_and_CPLEX_software_have_same_results/attachment/59d6479379197b80779a268d/AS%3A463101872087041%401487423498775/download/Getting+Started+with+CPLEX+for+MATLAB.pdf) for a quick start. [cplexbilp - IBM Documentation](https://www.ibm.com/docs/en/icos/12.8.0.0?topic=functions-cplexbilp) ]
[Question] [ There are many ways to generate random words. You can take random syllables from a set, you can use n-tuples, *probably* neural networks (what can't they do?), alternating between consonants and vowels, etc. The method this challenge is based off of is by far the worst. It uses a Markov chain to generate random words. If you are familiar Markov chains, you probably know why this method is so terrible. If you want to read about Markov chains, [click here](http://setosa.io/ev/markov-chains/). Your program will take an input one or more words and generate a single random word, through the method of a weighted Markov chain. Since that probably makes sense to no one but me, here is an explanation through the use of a picture of the Markov chain with the input of `abba`: [![A Markov chain for <code>abba</code>](https://i.stack.imgur.com/WF8IB.png)](https://i.stack.imgur.com/WF8IB.png) (All edge weights are the same for all pictures) Your program will output the path through a Markov chain based on the input text. As you can see, there is a 1/2 chance it will output `a`, 1/8 chance of `aba`, 1/16 chance of `abba`, 1/32 chance of `ababa`, etc. Here are some other example Markov chains: `yabba dabba doo` [![enter image description here](https://i.stack.imgur.com/cpOwH.png)](https://i.stack.imgur.com/cpOwH.png) `wolfram` [![enter image description here](https://i.stack.imgur.com/owgRc.png)](https://i.stack.imgur.com/owgRc.png) `supercalifragilisticexpialidocious` [![enter image description here](https://i.stack.imgur.com/VKlOE.png)](https://i.stack.imgur.com/VKlOE.png) If you want more examples, use [this](https://www.wolframcloud.com/objects/95c2a3b2-7505-4441-ada4-12fef3c73fbf). (I worked way too hard on it) Details of challenge: * Input can be taken as a list of strings, or as a space, comma, or newline separated string * You may assume that all the words will be entirely lowercase with no punctuation (ASCII 97-122) * You may write either a program or a function * To test, you could probably input the examples and see if all inputs line up with the Markov chains This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so your program is scored in bytes. Let me know if any part of this is unclear, and I will try to make it make more sense. [Answer] # Pyth, ~~38~~ 32 bytes ``` VQJK1FZacN1k XKH]Z=KZ;WJ=JO@HJpJ ``` Thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for 5 bytes! To be honest I started writing Python answer when I noticed somebody posted a very similiar one so I decided to challenge myself with something new so I rewrote my answer (which was basically Pietu's answer) in Pyth. Input is an array of strings `["Mary" , "had" , "a" , "little"]` [Answer] # Python 2, ~~138~~ 133 bytes ``` from random import* M={} for w in input(): P=p=1 for k in list(w)+[""]:M[p]=M.get(p,[])+[k];p=k while P:P=choice(M[P]);k+=P print k ``` Takes in an array of string such as `["yabba", "dabba", "doo"]`. Example outputs with that input: ``` do ya dabbbbbbbaba do ya yaba da dabba yabbababbababbbbababa do ``` I also want to highlight this result. ``` stidoupilioustialilisusupexpexpexpicexperagilidoupexpexpilicalidousupexpiocagililidocercagidoustilililisupialis ``` [Answer] # Ruby, 112 107 101 99 Input is stdin, newline-seperated strings. QPaysTaxes helped a lot with golfing it down! ``` M={} while gets k='' $_.each_char{|c|M[k]||=[];M[k]<<c;k=c} end k='' print k=M[k].sample while M[k] ``` [Answer] # Matlab, 160 bytes Takes input as a cell array of strings, like `{'string1','string2','string3'}`. ``` s=input('');n=[];l=96;for i=1:numel(s);n=[n 96 double(s{i}) 123];end while(l(end)<123);p=n(find(n==l(end))+1);l=[l p(randsample(nnz(p),1))];end char(l(2:end-1)) ``` This reads the words, and converts them to a vector of ASCII values, with a 96 to mark the start of a word, and a 123 to represent the end of a word. To construct a random word, start with a 96. The search for all the integers that follow 96 in the vector, and take a random sample from those to pick the next letter. Repeat this, looking for all the integers that follow the current one, until 123 is reached, which signals the end of the word. Convert it back to letters, and display. The input `{'yabba','dabba','doo'}` produces results like `da`. Here are the results of ten runs: `yabababbbababa`,`da`,`doo`,`doooooo`,`ya`,`da`,`doooo`,`ya`,`do`,`yaba`. ]
[Question] [ On Github, there is a list [of the 10,000 most common passwords.](https://github.com/neo/discourse_heroku/blob/master/lib/common_passwords/10k-common-passwords.txt) I've also generated [my own list of random passwords](https://gist.github.com/nathanmerrill/0cb670ad52548ee56738). Your job is to identify the difference between the two lists (with 100% accuracy). Therefore, your program needs to accept a string, and return: 1. A truthy value if the password is on the common passwords list 2. A falsy value if the password is on the random passwords list 3. Anything you'd like if the password isn't on either For those that are interested, my program generates passwords between 5-10 characters in length, and each character is either a lowercase letter or a digit. Note: You should not use these passwords in anything secure. My generation algorithm is not secure at all, and the results are posted online for all to see [Answer] # CJam, ~~2262~~ ~~908~~ ~~620~~ ~~512~~ 503 bytes ``` 0000000: 6c3a4c412c73277b2c39373e2b3a422d2c4c4c65752e3d65 l:LA,s'{,97>+:B-,LLeu.=e 0000018: 602c33653c5f333d5c5b513222011523a1d079937afebb7b `,3e<_3=\[Q2"..#..y.z..{ 0000030: 31a4ddf41a5e5038ef2aced9debeac5dc01fc4d27d809e0a 1....^P8.*.....]....}... 0000048: 2631e25b9e7d3314f1438f227b3235366233366242663d2f &1.[.}3..C."{256b36bBf=/ 0000060: 2b7d3a447e332205a4f76b4584be674d02001a36a250f949 +}:D~3"...kE..gM...6.P.I 0000078: 7bd0f1966deff2baab26a259813a0caa266155328064f0ee {...m....&.Y.:..&aU2.d.. 0000090: 20245dfab515c8faf39b08e80880c6e06c51728c57c153ec $].............lQr.W.S. 00000a8: 9907a8365894bb8163bacd3a67173b50641c928f3ca87e89 ...6X...c..:g.;Pd...<.~. 00000c0: 81c1e95e5f049b61688fc7316e6a639876d00cdf4c01a100 ...^_..ah..1njc.v...L... 00000d8: 998bd12ccf3fb8ca61c89f5a57cedf8170b4b062653d947e ...,.?..a..ZW...p..be=.~ 00000f0: 9f6d5ba729db151b79151ae044cd6416274c73110e777172 .m[.)...y...D.d.'Ls..wqr 0000108: 22445132220133e9dcda9e224435224dc7621a0ae9224433 "DQ2".3...."D5"M.b..."D3 0000120: 220980cb1f885db429b742f47062cc1190767d82e6e956b7 ".....].).B.pb...v}...V. 0000138: 1de25dd9c2be7bf5224451322201c9167dd15a8c8cdd110f ..]...{."DQ2"...}.Z..... 0000150: e956678cd6467ed95c22d7700c1d37a5b1ad94d3b3a3531e .Vg..F~.\".p..7.......S. 0000168: 639ba99f27cde7e9c81c686adb874d6d5ac411d8d5e44363 c...'.....hj..MmZ.....Cc 0000180: deff8759ed48c97a32b5eeed5ef23be112773a0e0454e6a5 ...Y.H.z2...^.;..w:..T.. 0000198: d064d43adf998c7050910c723616dccb5874a8b3640e39e0 .d.:...pP..r6...Xt..d.9. 00001b0: b7545841c7b3152d13ab3e83857530313cb737c799837a4b .TXA...-..>..u01<.7...zK 00001c8: 396a39e68c9722443322d87648012832adde4e33e27615e2 9j9..."D3".vH.(2..N3.v.. 00001e0: 4b6bf7e94bec9022445d3d7b4c5c23297d253a2b215e7c Kk..K.."D]={L\#)}%:+!^| ``` This prints a positive integer for common passwords and zero for others. ### Verification ``` $ xxd -c 24 -g 24 testall.cjam 0000000: 714e257b3a4c412c73277b2c39373e2b3a422d2c4c4c6575 qN%{:LA,s'{,97>+:B-,LLeu 0000018: 2e3d65602c33653c5f333d5c5b513222011523a1d079937a .=e`,3e<_3=\[Q2"..#..y.z 0000030: febb7b31a4ddf41a5e5038ef2aced9debeac5dc01fc4d27d ..{1....^P8.*.....]....} 0000048: 809e0a2631e25b9e7d3314f1438f227b3235366233366242 ...&1.[.}3..C."{256b36bB 0000060: 663d2f2b7d3a447e332205a4f76b4584be674d02001a36a2 f=/+}:D~3"...kE..gM...6. 0000078: 50f9497bd0f1966deff2baab26a259813a0caa2661553280 P.I{...m....&.Y.:..&aU2. 0000090: 64f0ee20245dfab515c8faf39b08e80880c6e06c51728c57 d.. $].............lQr.W 00000a8: c153ec9907a8365894bb8163bacd3a67173b50641c928f3c .S....6X...c..:g.;Pd...< 00000c0: a87e8981c1e95e5f049b61688fc7316e6a639876d00cdf4c .~....^_..ah..1njc.v...L 00000d8: 01a100998bd12ccf3fb8ca61c89f5a57cedf8170b4b06265 ......,.?..a..ZW...p..be 00000f0: 3d947e9f6d5ba729db151b79151ae044cd6416274c73110e =.~.m[.)...y...D.d.'Ls.. 0000108: 77717222445132220133e9dcda9e224435224dc7621a0ae9 wqr"DQ2".3...."D5"M.b... 0000120: 224433220980cb1f885db429b742f47062cc1190767d82e6 "D3".....].).B.pb...v}.. 0000138: e956b71de25dd9c2be7bf5224451322201c9167dd15a8c8c .V...]...{."DQ2"...}.Z.. 0000150: dd110fe956678cd6467ed95c22d7700c1d37a5b1ad94d3b3 ....Vg..F~.\".p..7...... 0000168: a3531e639ba99f27cde7e9c81c686adb874d6d5ac411d8d5 .S.c...'.....hj..MmZ.... 0000180: e44363deff8759ed48c97a32b5eeed5ef23be112773a0e04 .Cc...Y.H.z2...^.;..w:.. 0000198: 54e6a5d064d43adf998c7050910c723616dccb5874a8b364 T...d.:...pP..r6...Xt..d 00001b0: 0e39e0b7545841c7b3152d13ab3e83857530313cb737c799 .9..TXA...-..>..u01<.7.. 00001c8: 837a4b396a39e68c9722443322d87648012832adde4e33e2 .zK9j9..."D3".vH.(2..N3. 00001e0: 7615e24b6bf7e94bec9022445d3d7b4c5c23297d253a2b21 v..Kk..K.."D]={L\#)}%:+! 00001f8: 5e7c7d2524656070 ^|}%$e`p $ echo $LANG en_US $ cjam testall.cjam < 10k-common-passwords.txt [[9989 1] [4 2] [2 3] [3 5] [2 7]] $ cjam testall.cjam < generated_passwords.txt [[1000 0]] ``` [Answer] ## Python, ~~719~~ 664 bytes ``` import re lambda s:re.search(r"(?!.*([xvonkj]0|p[9q5]|i2|q[4rt]|xk|m8|jp|jg|4k|2n|0b|y.[xj7]|mnw|c.3|7.2|4wu|061|zt[ub]|r6[d8]|o.0|jd[be]|j[wz]o|hk[cj]|^(wb|wd|v3|ub|s2|s1|pb|ml|j5|hv|h1|g8|g6|ft|f4|94|0t)|(we|ha|93|80)4|(xj|x5|03|qa|fz|w)9|3[65]0|zbx|(w.|v|o.?|54)7|[th]82|ssg|g(lc|ij|v|1[34]|bx|bk)|wvf|uax|mss|uhl|306|4.[mr]|9p|rob$))^.*((^([14]?\D+|\D*\d+|\d{3}\D{5}|(?=^\D*\d\D*$).{6}|\D+4\D+|[1-4a-eqwr]+)|sx|[ekru]s|t4u|zx|[avy]y|x[prs]|w[mp2]|uz|tp|tn|sc|qq|qj|p[mov]|r[deq]|oo|n[4tu]|me|k[23c]|jf|[2ag]t|ed|bq|a1|3r|5g)$|\W|123|^(nc|tr|w0|sa|rj|q[bnqu]|ni|mo|mw|le|kc|ib|hz|g9|f0|cb|b9|8d|7k|6u|5w|3m|1q)|z.g|bo|em|x35|t.d|p.o|p39|mar|ki4|id8|ebk|53x)",s) ``` I'm having a bit of trouble testing this in [Retina](https://github.com/mbuettner/retina), so here's Python for now. Test by giving the `lambda` a name and running it on the word lists: ``` >>> len([x for x in common if f(x)]) 10000 >>> len([x for x in generated if f(x)]) 0 ``` It's a *very* large regex, so I'm taking a break from golfing it for a bit. [Answer] # Bash - 5324 bytes ``` gunzip -c rp.gz|grep $1|wc -l ``` where rp.gz is located at <http://dl.tyzoid.com/rp.gz> This returns 1 if on the random list. This is falsy, as bash evalutes 0 as a truty value. [Answer] # Haskell, 8047 bytes ``` main=interact$show.flip notElem(words"viy130k57 d69z0 iz7q4d u26q3h 4mr6bhwa4 d36p5d 83554s 70r310py dz3js3 i1w86i0 2c4bk9 26w4kg52 u8i1g22ge 86k4br 875orut1 kw5786758 4k87v nfi5f2h9 x303978 43r4qb 963lnbs h5c1vq6s2 0iyv53vr2 nf5tmbp8 31ieq5xlh 9b450m ohv69d 5297m29 jvsxd20k fuha432 o8i84sh mss63 56vl8kzv8 73hh251 zr3r3zph 5f195v3kq 4o224g8 yi3y1lgi7 5ihcc t1krtr8w6 g7x9cuv4 128ov7 10adfe9 1p3lw 2523v xpj3h6z w2546kzx5 4042nle 0vv7i7ng xxzmf5vl efh601zby 19i0o63 8l20191 xm7e96pl 691p7m3p2 ksx29c2q3 auhli 7jq5e9e 786wo1q 1gwiaj7y8 3r19f26 x2nnr7 3u235s 076zr95m xzr32d 0lo70 v6o391 72pm08fo 79p1v9 uw98b 9mh7q3 2mh6bz a4qqw8d zve8z 790gkwc t975y 7d206t06 0zkvd9q0e y0cb34 9tltcs41w 079bp2y lwk12f 58gz4p 7lrkl io89he175 49dcu m2qg1 1ic76l kt9k9525i 6jwd8 4m9xwe86 3212janr r694ax 2raflx7s s26km575 n0z3hsdhj 9zl3x5 88c96968n 1lbw1v 20kri 799934a91 6c51846 61o78mjun 3d1yn 13113u8ev z22n5ni 0jxuc 79zwnl3tx xv4h4kz7 001n9 2u0f2 8msf6t g83r6v 81j4tt5e 20ucmaf j576783 v64ar 3u16pj83p r817zu6d xgc63 4y1rpo0 031606p 43q08m3x 1sg237d1n dt85c vg30a u4ge5t 4bv27l432 0612939 8glq6zo g64m0r4 593erv6 962a24u 94rop d28fs6k xy78efw3 yd0kyj1 y02rl 3n21q esg5y9m9 8408qpscw 5lapn9k26 4x1k27 7mb8054 4s1x7olv5 10s7726 00eib 84pu58e6 505l3s6 ldgx9e7d hv4d6u56s 5ren77w uf6pmf2 0sfum 1ik8mx vzqtj77 cvjc1ta us90844jb 84r0d4td plab52n 7946vj4l7 qy5gjtr 49lpq 4w49fm 44y0rh472 07jt8 1tju72 q0733u1 375ojd0 1t28s9ag1 ppj60t704 wi67b877 jgrrh388 ftvu98 h214l3x 3nirvrdu mrg14 52s65y 9f587 2629v os80p7 3h89mqk xt5845q9m 68h53w 8b3309g 16967k 38356nk 34oyt he3v5vn2 m1g2c8 8n324x6 2by0e7x 1a4mit7 ge91p60y b170o 9v5rys 6wq3959ue ed9u3 kd4wy1 c853gz k56gel09h 789ygx5pk 1f9f2 84fxtdx d02fdz9i 6gj4i4 6p8jtsax 3v38hkcs2 80090i 8084xb4m c4xv4x79 pilbux017 9m193zg5 qwq5o6x5 90cw69n96 n237351i cm40sj1x 3727d9p q0x74ityn 3ez6679 t7vs045 r7jg22xyr 3z34a96 miu8lm62 cpzjf226u vb2545x 4f9qg7sdq 2rf6t kq0ixi32n rjdeuj g8x5p3 d776c 4x1385 830nug s1tysl o679090 93kgz18 91pu8l n05i73 mdmq4c 31her5 6r10e0il i02np063 75jf619gg 1cft96o9 9j9x4g 12to97 5z6o922 2z1mtcg 3ea7l4 12h2gl0 bl12h638 k1sd9a4y v06po5yn 3ac6le459 0f1ljw ctkjzo4 u9k5rzx82 pa5d2om 32c4713q2 1bp33y 9384p7 v12i1aqp7 nb2w98 76ss0 24cy672 lasprob p1y3g4 ssekkgij 8x1o4 n1rgsm51d 2f73n9t 7gq430y 7lu476llc l8y3oa yjjb67d8 9n01v95gy w7792 061d339f xj989 v3tm27h rqytegr1c qoe96g o81680pg 563bmt680 s2lx9qc14 wpd4o1jb x67a06h83 ll508m 13067 m6578u vn64b 8zm25nd v0ny28346 nh5etpuub 6sl8acai 3hbd5 94103 981by1ri n4k4jzi m5704w7lt a6x3f 9chs9 ivk55n 14j50d 77p684h nt569aek br6yv97 iso7qi 7h1eh 0801fwq 54en7 8celizu j4c1i1409 9di5p1 to3re10m1 t1v246wkb 1n0l9r9 x46l2vwbp m4st1un7u 5apkz94 z9lp3i 3754cl r67up 446exk983 40n6454sf b6y1z1uf b8ca9w0je n9ga6 06156 3n551 71860lr sh9n3 zo6x54 5qwx9 6p2ko1d lzafd6a esv073963 871fu3 64wd2 68j49k4q 3s6b901 3k6x0 3br349yx2 2ev963aa op5t394ig jdbh9 sk364u8 u25m3s0r1 1050ln80w 322ggt12 7xq6z75 279q2 oxys3id7 c78v2 7jfjk1 8aq82y4b 0f43100 4afw4ck p88s6h0k azuaxn q128b 7y0ewmp ikpgn519d 54zq981 18chi4u 5xski3b ztb242 8199b0 886f7 lytj1 d52kr nv060 68tdhr01 0nky3o r9y6g fn24cg3 2i585fw0 c5oj4 d8220hbh rtjwom45 x8ws8 l0vk6945 140jsy6 cx70q6vc s26536 3un5314 koxd24tgw khpz47o 8h0wcv10m dc33280 14i9770 cnj67sv n142iu 3yysx7e6d k5g38u4 7vs103i5 21o1tmi bz7di 4u3m7y2m5 407z8ln9o 3dvz58 372fz3lhq lc8g15yp p9f6lq 5zaz5n5y f4j25y46 s369474nb 6qtfog8 x69wy42 ma2b56i34 e2tv3 jqp515 agbkd95 x3h7kqa0 v27rnd 14zo577s im809s n8pr1y3 o6w6u915z 4v1566be 1k8v4 ie2t65f yoci2 43f3741pr 1iihw59 99k77378o 081sgssg 8e472q 86ui90 9154298yg 03azelrv it3500 8p52k hc5tj my7ok34u9 4k2l9 svys9nx3s 6jc7b54 4wuhh ehkc19 7m242 1p5255e20 7uj997 8gsxl 4m4l4 u0057w 698u0vd8 1pbh99 g30zxku dvj20a7a uyt82 3nhy7i794 98aps9z f9zhx9i5 k686or3 2pc8fo086 f12p2r5y4 gg133 7d7moa92 6787230in ro8113t5 sk01s6ua y219c2679 4p2j48u tww6708 8g0ze8kxh ox2up4c06 acyflgv r2cf66p 51hgd6biq cepo0k5 3gkz3 so47e745 d1550k5 084h64t n5402i a2354hgu 1969f31xc 4ug5te 88av1 psaao7r r73zl z0dupumi 8o3ln n1k76r 3yj1i14 7ea10s8ny ek468v2 07sqhdn pc52r 3q01f1 dhku90f 1wqu1pitk 4xq2d se6v9du e99e82qt 0094y96 36cjds546 2ga756498 63w66053i 76pe39 5j9645gq ld8l156 m0bcb9hj 32kuy b751a8e25 02v61 j4zf5q6 80x964nyd 52ij7 u26vv r718r2d 09czm6116 1bd9a 12t874q5b 7i4ro i07mwc7g5 i4jug5y6 0srfbc0g9 l7j853e p0bcges6 46g56mn c6p6g38v7 5rr875 atpqnbl w177s30 e4pm1d117 y79mt10c 7xa2l69 nw7rrm4z8 36te6593 6r1x9z xai3b 4t6r0uz87 9m568v573 u40y29157 vvl2t4 f1kc0m wp56h1qkm 3xq8ivnr3 535i062 69m2kwb1 d4w2ze 1wjqh0 pb948 w9874d j5oo220d 28hro vx873f55x 5n2q70f 74358tngl 038048 662b16s i0psi7chi 3e98l80d5 hu7rwtl 3j7igy914 0v98t 9s17y8t 61g71jq6 375h1d icx59 plyp2n nm26m22c 3k2028 n13j9l9gh 1sy2a 76f4f glcn1 h3z12 0ctw14 ws2qr p97658 ann1oe63 67i2c5sp 5c6yu 894g7 kl8i8 kqlr6d 29w3z wk8qh26 62ma13brr ho08mctfw 65q3h2 8se1b7 970y4c577 c3f793 2mu9e od8vjhyt 17628 81pfy7 ee14q69t4 005r25c86 50w71m3l9 6se3p8l 9d9c5r7 hdq9rfb0b y29cf26 729xvd u4n91c 35u2q h16334 36xk98 ov1t6 54h6k9 ml63553 2c27tlqc fv1tv v767658 x1u10k 92q1j7b9 40e5is 6su1q59 h90636ll 757m459y0 ke163r6 qf5v8f2n m6h2a 4p88p yfmq2975a g4bv1t k8d8whp65 qz175so3 520g61e 55m6bh235 j6n5y 6w0t76th b0wtl7q lcuw96 mp2l8d1c w4kr923y1 d8741bp4v l245i3 fcmnw 9m4kg85z 6bis4cjs 1sf0g8gq uu36o4l0 a3h31u pvy4em 5q1t37g sb5cbsv3g yejeol og087z9 3d26hrlw7 05s7g2 4yp46v6 1sd3ot g04evj87 d1w1ra6 89g5t8 64a42ihm coh4kq 01ejx 4frus6 3k938303 0y0z1xyx 799v26 7651514aw 3ddi4i8l oc8aa 9u42f 70t17439 vg7o54 xw8c3yz 1i1aq3p23 k6i4j4 41et377k 9r25jic 65o4n1s zt8s9a8 4n88b7 or0974 96it6 ox041b kkk0hi 5ocny 316547 r873o h1z5mb wbw0497 6i422j 54d54bt reh822 r6818 dogwoi2n7 wvfur h51y36k 49d0lhf3m 73714y 3ukt0 45eeq s6686xxn 3395o i67mh66 68093462 4j9ls 74047i54o 1k6i5fawg p3m491 mqy94h6 666kf ue5ry g6g6xw 0bmgtx 75j9nsvf 90g583 hkjhib2 p9460431 a3wi5nd5 hgc0w7 9r1spo63z 87913e 6bz0fc m82jox78 q4c87t 8i6i51c83 ezp12r 6g5i7 ubarl 14k71597 901b2 kb2ya9 xkl93 awh7jmblw q2gbkmvk 91nw3a05i 6qga3 lcg5m 01wur23b 29t7171u cs9u8 a4v3xg0 j5kqpfciu u1o31 xjt16f5v 02165z3 17ow5 lqrq9 v9jt5 g8113 qa9637 ez29eqc9t 2a6ra1r 00767x y9pjem d8xw7s 2i5c5 kve255m7u 41v7yn8 o952s446 q26okdrbr f50xm5 a3l8v744 l8q977 ub2ag2 2307p 079pv6 n4wup 5b46t 0i599u7q t46j1ush8 03a6x c5idf535 566f3l8 r42t11p9 966e5412 82rl29tn9 k032o4 hlra31t2 87f8q8s 57u1vt5o8 g6081 pny7v101a g7ar1z zw697yh4 v96p1180 dg86uo9qh 0oo5r2n1 wse3c6 87qf041y hylxbrj yul0jc1 70394 3i44dn yoi246 7ccmsts0 2c2iqn qytx7c42w hgy3zx1k 0h76k267 vf528wz84 24i92r34t i15h1 0l2n93b 4ysso34 gb4p098p9 5x0p4pk5v la00fg39 2596p esno00 pfz9149 3tl43q0 p9mw947g xrd60n2g 5pcp2n 22vu57d1 169vqkf s6uwxk7 4cx1s 5z89490d8 u2o88803m f4236 94xpjzu 975gcg2b1 2s6ow85w0 r68w68 4valqzgs1 j967p577 wdz4t oy567kh05 v382yl ma0k273m 0qv13 3h79r 1a7286 xlv11nqg g64q2pq7f hh7bl2t65 8oqmq 3230i 9kspnz0 1o58m8 g3g8un0 9s70irfzh 4mqjge4 0pmjw 87jq5lvc 6rr41zav6 146v3 2pj9i leawe46 aojfx1h rbz7s7n0 aka0x 4q31u e069n swj06 l52s891 w7ta9p7 8641c3bj5 o8p3jx mci7g yb0mx95 jperua8 x1sh6whl q13u23s p9h3m 4u561 544u556g psm8vv 5338dmhe 6nmacyod 7qk0e0cx4 1s6zv2ycy 40360 2m3w8h2ee 110o27 w730108t 4547b0 0e998 d62io mjri4m90m 822xgu 7404u73i3 6g73d1 292uv351 789e6 f6721070g 5752261 y5l2i vh471uy 1p06933q o2l85722 axoz605ic yd97s 78whg y8eeb5b sr76mqe wc0855h6j 4ztui 4bc8n5 hvyuovxl4 0tifec 2coog5s6n j2mbd344h bgbx7 m7a4t2j77 vdc2d854 mizbxb2 1xj676 5oi49bw66 t451834gd 1xh7o t006va 6c0jy 126ly2n5 i432l5t61 myrou93w v0t5fi5s4 1zne2o rysfj8k 44x53c 9kk15 8938quif d6f7x 3nz3p cjg70t v309011 07nw947ey 6rc18 n11551so 24dtm5159 qpd4p40 f3794b9y9 8hcx5oo5 570bu cl442vxg l59bl10jx lj5gz00u b7tn6uu08 45m43uf53 t62861qf9 780288ew 3867o8p7 3k8uc we7zh sub593fof qxyi7 q634jlqz 9acjc 24v0eksmu ltx1crj 0y0b73qt 64c8yd 5hbes3 c791g97o2 tg9j2 8736l v2am0 4yq2yg943 193di7141 ss6xq y60lv92r 77b1v383 o9acsyje 163449n0 mnw167 2skcq u5z4v3i 4u70jc 8w872 42q9k44f fshyn004 qr1fa 59599zxbh g25wi69l 61vfy6 01474kb7 6mp11b 62t63e3l 198njo 673s491p ab8dr4qz 2s243 7hwz6lq79 d999oo3 6vsy1 6pf862 79x2dmq85 7q6q48i2 21g4mzy25 do85ib82x r0wb2 6zq2rmf 5q2jp41 bc60yv x18t30 5c0zt6m3 na80h6tc y5r6n o40r45v 0ufog 49w11ce0 10i3cbapw 606z0ti kowx5iro l59quc0 4t00o8") ``` This seems to be the best that I can figure out without breaking out compression algorithms, and none of the languages I like to use really have a brief built-in compression method. The "algorithm" is extremely simple; check if it's in the list of random passwords and return False if it is and True if it isn't. ]
[Question] [ # Background I have a bunch of square-shaped boxes of equal size, and since I'm a neat person, I want to arrange them all into a square formation. However, their number is not necessarily a perfect square, so I may have to approximate the square shape. I want you to find me the most aesthetically pleasing arrangement -- programmatically, of course. # Input Your input is a single positive integer `k`, representing the number of boxes. # Output Your program shall choose two positive integers `m, n` such that `m*(n-1) < k ≤ m*n` holds. They represent the width and height of the large square-like shape we are arranging. Since we are looking for aestethically pleasing shapes, the quantity `(m - n)2 + (m*n - k)2` shall be minimal, so that the shape is close to a square, and its area is close to `k`. If there are still several candidates for the pair `(m, n)`, choose the one where the width `m` is maximal. Now, your actual output shall *not* be the numbers `m` and `n`. Instead, you shall print the arrangement of boxes, using the character `#` to represent a box. More specifically, you shall print `n-1` rows, each of which consists of `m` characters `#`, and then one row of `k - m*(n-1)` characters `#`. Note that the output contains exactly `k` characters `#`. # Rules and Scoring There shall not be any leading or trailing whitespace in the output, except that the last row may be padded with trailing spaces to be of length `m`, if desired. There may be one trailing newline, but no preceding newlines. You may use any printable ASCII character in place of `#`, if desired. You may write a full program, or return a string from a function. The lowest byte count wins, and standard loopholes are disallowed. # Test Cases Here are the correct outputs for a few input values. ``` 1 # 2 ## 3 ## # 4 ## ## 8 ### ### ## 13 ##### ##### ### 17 ###### ###### ##### 18 ##### ##### ##### ### 20 ##### ##### ##### ##### 21 ###### ###### ###### ### 22 ###### ###### ###### #### 23 ##### ##### ##### ##### ### ``` [Answer] # Pyth, 28 bytes ``` jbc*\#Qho.a,,N*NJ_/_QN,JQ_SQ ``` [Try it online.](https://pyth.herokuapp.com/?code=jbc*%5C%23Qho.a%2C%2CN*NJ_%2F_QN%2CJQ_SQ&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A8%0A13%0A17%0A18%0A20%0A21%0A22%0A23&debug=0) The crux is that I sort potential m on the following property: ``` (m - ceil(k/m))^2 + (m*ceil(k/m) - k)^2 ``` Note the total absence of `n`. The total shape is defined merely by `m`. Then I transform the above property once more, and my final sorting weight is defined as the Euclidean distance between the following two points: ``` (m, m*ceil(k/m)) and (ceil(k/m), k) ``` This changes the weight values, but not their ordering. [Answer] # Python 3, 202 bytes I know that its longer than the CJam or Pyth solutions, but nevertheless, here is a way of solving this problem in Python: ``` k=int(input()) r,d,s=range(k+1),{},'#'*k for n in r: for m in r: if m*n>=k: d[m,n]=(m-n)**2+(m*n-k)**2 x,y=max(i for i in d.keys()if d[i]==min(d.values())) [print(s[i*x:(i*x+x])for i in range(y+1)] ``` The basic principle is that we know m and n are both less than k. Also, m\*n >= k . That means that we can simply find the minimum of the expression given in the challenge for all m,n < k, excluding values whose product is greater than k. [Answer] ## CJam (44 42 bytes) ``` qi_,{)_2$d\/m]_2$-_*@@*2$-_*+~}$W=)'#@*/N* ``` [Online demo](http://cjam.aditsu.net/#code=qi_%2C%7B)_2%24d%5C%2Fm%5D_2%24-_*%40%40*2%24-_*%2B~%7D%24W%3D)'%23%40*%2FN*&input=22) I was rather expecting there to be a simpler solution involving square roots, but it's not at all that simple. E.g. for input `31` the row width is two greater than the ceiling of the square root; for `273` (square root just over 16.5) the best approximate square is a perfect 21x13 rectangle. [Answer] # CJam, 42 bytes ``` li:K_,f-{:XdK\/m]:YX-_*XY*K-_*+}$0='#K*/N* ``` [Try it online](http://cjam.aditsu.net/#code=li%3AK_%2Cf-%7B%3AXdK%5C%2Fm%5D%3AYX-_*XY*K-_*%2B%7D%240%3D'%23K*%2FN*&input=17) Explanation: ``` li Get and interpret input. :K Store in variable K for later use. _ Copy. , Build sequence [0 .. K-1]. f- Subtract from K, to get sequence [K .. 1]. Larger values have to come first so that they are ahead in ties when we sort later. { Begin block for calculation of target function for sort. :X Store width in variable X. d Convert to double. K\/ Calculate K/X. m] Ceiling. :Y Store height in variable Y. X- Calculate Y-X. _* Square it. XY* Calculate X*Y... K- ... and X*Y-K _* Square it. + Add the two squares. }$ Sort by target function value. 0= Get first element, this is the best width. '#K* Build string of K '# characters. / Split using width. N* Join with newlines. ``` ]
[Question] [ Counting the amount of triangles in a picture is a task commonly used in brain tests. You are given a picture that contains shapes consisting of triangles. You then must find all possible triangles in the picture. # Task You are given a list of lines in a format of your choice. You must then output a list of triangles found in that ## Input You are given a list of lines, each given by four integer coordinates (eg. `x1 y1 x2 y2`). You may choose the input format, as long as it is clearly documented. Examples: ``` 0 4 8 1 0 4 9 5 8 1 9 5 2 8 0 4 9 5 2 8 [[0, 4, 8, 1], [0, 4, 9, 5], [8, 1, 9, 5], [2, 8, 0, 4], [9, 5, 2, 8]] ``` Here's the same input as an image: ![triangle drawing](https://i.stack.imgur.com/qt5Si.png) Another one, with intersections (only in one format to save space): ``` [[2, 1, 5, 0], [2, 1, 2, 7], [5, 0, 6, 6], [5, 0, 2, 7], [6, 6, 2, 1], [2, 7, 6, 6]] ``` ![triangle drawing](https://i.stack.imgur.com/cfJzs.png) ## Output You must output a list of all triangles, each given by six floating-point coordinates (eg. `x1 y1 x2 y2 x3 y3`), in the picture specified by the input. These might not be integers, since the lines may cross at any point. You may choose the output format, as long as it is clearly documented. Example outputs for the example inputs above: ``` 0 4 8 1 9 5 0 4 9 5 2 8 [[0, 4, 8, 3, 9, 5], [0, 4, 9, 5, 2, 8]] ``` ``` [[2, 1, 5, 0, 2, 7], [2, 1, 5, 0, 6, 6], [5, 0, 6, 6, 2, 7], [2, 1, 6, 6, 2, 7], [2, 1, 5, 0, 3.674, 3.093], [5, 0, 6, 6, 3.674, 3.093], [6, 6, 2, 7, 3.674, 3.093], [2, 7, 2, 1, 3.674, 3.093]] ``` ## You may assume that * there are no edge cases where a line crosses an intersection but not any lines, like ``` [[0, 9, 1, 8], [1, 8, 2, 9], [2, 9, 3, 8], [3, 8, 4, 9], [4, 9, 0, 9]] ``` * there are no angles over 179 degrees, like ``` [[0, 0, 0, 1], [0, 1, 0, 2], [0, 2, 0, 0]] ``` ## Rules * You may use any language you want. * No external resources must be used. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in **bytes** wins. [Answer] # Mathematica ~~915 395 401~~ 405 **Update** This programming challenge is much more difficult than it first appears to be. The present approach works with simple cases, where there is but a single intersection along the length of any line segment. With multiple crossings along one segment, it is necessary to keep track of all of the intersection points along each line and create new sub-segments (hence additional graph edges) connecting the new intersection to all the intersection points along the target line. Despite that limitation, it may be worth sharing the logic underlying the current approach. --- The input line segments are treated as regions. If they intersect, the centroid will be the coordinates of the intersection. We need to eliminate those intersections that occur at the vertices of line segments. Lines that do not intersect will have an indeterminate centroid. Four new edges are created for each intersection point. They connect the intersection point to the four vertices of the two intersecting lines. A graph such as the one below on the right is generated using both the old and new edges. The vertices are the coordinates of the respective points. Cycles, i.e., closed loops of three vertices will be triangles provided that the three vertices are not collinear. Presently we check to see whether any "triangle" has an indeterminate area. (For some reason it does not return an area of 0 for three collinear points.) --- ## A simple example Below are (a) the figure plotted in the coordinate plane and (b) the graph showing the given nodes as well as the intersection node, `{114/23, 314/69}`. In the latter, the vertices are not located at the respective Cartesian coordinates. It may appear that their are more edges in the right figure than in the left. But remember that there are overlapping graph edges on the left. Each diagonal actually corresponds to 3 graph edges! --- ![graphs](https://i.stack.imgur.com/GGtjM.png) ``` f@w_ :=(h@{a_, b_, c_, d_} := (r = RegionCentroid@RegionIntersection[Line@{a, b}, Line@{c, d}]; {r <-> a, r <-> b, r <-> c, r <-> d}); Cases[FindCycle[Graph[Union@Join[w /. {{a_, b_Integer}, {c_, d_}} :> {a, b} <-> {c, d}, Cases[Flatten[h /@ Cases[{Length[Union@#] < 4, #} & /@ (FlattenAt[#, {{1}, {2}}] & /@ Subsets[w, {2}]),{False, c_} :> c]], Except[{Indeterminate, _} <-> _]]]], {3}, 50], x_ /; NumericQ[RegionMeasure@Triangle[x[[All, 1]]]]][[All, All, 1]]//N//Grid) ``` Each row below is a triangle. ``` f[{{{2,8},{8,1}},{{0,4},{8,1}},{{0,4},{9,5}},{{8,1},{9,5}},{{2,8},{0,4}},{{9,5},{2,8}}}] ``` ![coords](https://i.stack.imgur.com/7Jvhk.png) --- ## A more complex example ``` f@{{{9, 5}, {0, -10}}, {{9, 5}, {0, 2}}, {{9, 5}, {2, -1}}, {{0, -10}, {2, -1}}, {{0, -10}, {-2, -1}}, {{-9, 5}, {0, -10}}, {{-9, 5}, {0, 2}}, {{-9, 5}, {-2, -1}}, {{0, 2}, {0, -10}}, {{-9, 5}, {2, -1}}, {{9, 5}, {-2, -1}}, {{-9, 5}, {9, 5}}} ``` Here's the graph corresponding to the **input** coordinates. The vertices are at their expected Cartesian coordinates. (If you run the golfed code it will display the vertices elsewhere while respecting the vertex labels and edges. For readability, I assigned the vertex coordinates using a smattering of additional code, not necessary for the solution.) ![graph2](https://i.stack.imgur.com/EX3DC.png) --- Here's the derived graph. It includes the derived point of intersection `(0,1/11)`, where some of the input lines cross. ![nineteen](https://i.stack.imgur.com/ifcdQ.png) The code found 19 triangles. Nine of them have the point, `(0,1/11)` as one of the vertices. ![nineteen2](https://i.stack.imgur.com/Xxvpq.png) [Answer] # Java, ~~1051~~ 1004 *(Fully working program)* I thought this is a nice challenge not just to golf some code, but mainly to practice writing mathematical functions. And to draw a "baseline" I made this one in Java **\*Waits for everyone to start laughing\***. **Code** ``` import java.util.*;class P{double x,y;static P l(double... i){double a=i[0],b=i[1],c=i[2],d=i[3],e=i[4],f=i[5],k,l,x=(k=i[7]-f)*(c-a)-(l=i[6]-e)*(d-b),n=(l*(b-f)-k*(a-e))/x,m=((c-a)*(b-f)-(d-b)*(a-e))/x;P p=new P();p.x=a+n*(c-a);p.y=b+n*(d-b);return(n>=0&n<=1&m>=0&m<=1&x!=0)?p:null;}public static void main(String[]p){Set<String>v=new HashSet();P q,w,e;Integer a,b,c,d,k,f,g,h,i,j,m,l,r,t,y,z;int[][]x=new int[l=p.length/4][4];for(c=0;c<l;c++){for(d=0;d<4;){x[c][d]=l.parseInt(p[c*4+d++]);}}z=x.length;for(r=0;r<z;r++){a=x[r][0];b=x[r][1];c=x[r][2];d=x[r][3];for(t=0;t<z;t++){if(t!=r){k=x[t][0];f=x[t][1];g=x[t][2];h=x[t][3];q=l(a,b,c,d,k,f,g,h);if(q!=null){for(y=0;y<z;y++){if(y!=r&y!=t){i=x[y][0];j=x[y][1];m=x[y][2];l=x[y][3];w=l(a,b,c,d,i,j,m,l);e=l(k,f,g,h,i,j,m,l);if(w!=null&&e!=null&&q.x!=e.x&q.y!=e.y&!v.contains(""+r+y+t)){v.add(""+r+t+y);v.add(""+r+y+t);v.add(""+t+r+y);v.add(""+t+y+r);v.add(""+y+r+t);v.add(""+y+t+r);System.out.printf("%s %s %s %s %s %s\n",q.x,q.y,w.x,w.y,e.x,e.y);}}}}}}}}} ``` --- **Input** Space separated integers. In pairs of 4 (x1, y1, x2, y2) ``` 2 1 5 0 2 1 2 7 5 0 6 6 5 0 2 7 6 6 2 1 2 7 6 6 ``` --- **Output (real output does not round to 3 decimals)** Each line contains one triangle Each line consist out of space separated floating points in pairs of 2 (x1, y1, x2, y2, x3, y3). *(Note: the order of the 3 points that form the triangle is undefined.)* ``` 5.0 0.0 2.0 1.0 6.0 6.0 5.0 0.0 2.0 1.0 2.0 7.0 5.0 0.0 2.0 1.0 3.674 3.093 2.0 7.0 2.0 1.0 3.674 3.093 2.0 1.0 2.0 7.0 6.0 6.0 5.0 0.0 6.0 6.0 3.674 3.093 5.0 0.0 6.0 6.0 2.0 7.0 3.674 3.093 2.0 7.0 6.0 6.0 ``` --- **Explanation** I started to write a method to find the intersection between two not-infinite lines. The resulting method is for a Java style one pretty short (246). Instead of letting the method input consists out of 8 double's or two Points (P) I choose to use a arbitrary parameter to safe massive amounts of characters. To minimize the array operator usage each parameter used more than 2 times is placed in it's own variable. ``` static P l(double... i){double a=i[0],b=i[1],c=i[2],d=i[3],e=i[4],f=i[5],k,l,x=(k=i[7]-f)*(c-a)-(l=i[6]-e)*(d-b),n=(l*(b-f)-k*(a-e))/x,m=((c-a)*(b-f)-(d-b)*(a-e))/x;P p=new P();p.x=a+n*(c-a);p.y=b+n*(d-b);return(n>=0&n<=1&m>=0&m<=1&x!=0)?p:null;} ``` More explanation to be added... (this answer can probably be golfed even more) [Answer] # PostGIS, 162 I think this complies with the rules, It is a query for PostGIS, which is an extension of PostgreSQL. The input is assumed to be a table of coordinates for each line called L The output is a set of rows with the polygon definition for the triangles formed. ``` SELECT ST_AsText(D)FROM(SELECT(ST_Dump(ST_Polygonize(B))).geom D FROM(SELECT ST_Union(ST_MakeLine(ST_Point(A,B),ST_Point(C,D)))B FROM L)A)B WHERE ST_NPoints(D)=4; ``` In use it looks like the following ``` -- Create a table for the input CREATE TABLE L (A INT, B INT, C INT,D INT); INSERT INTO L VALUES(2, 1, 5, 0), (2, 1, 2, 7), (5, 0, 6, 6), (5, 0, 2, 7), (6, 6, 2, 1), (2, 7, 6, 6); SELECT ST_AsText(D)FROM(SELECT(ST_Dump(ST_Polygonize(B))).geom D FROM(SELECT ST_Union(ST_MakeLine(ST_Point(A,B),ST_Point(C,D)))B FROM L)A)B WHERE ST_NPoints(D)=4; -- Cleanup DROP TABLE L; ``` The output is as follows ``` POLYGON((5 0,2 1,3.67441860465116 3.09302325581395,5 0)) POLYGON((6 6,5 0,3.67441860465116 3.09302325581395,6 6)) POLYGON((3.67441860465116 3.09302325581395,2 7,6 6,3.67441860465116 3.09302325581395)) POLYGON((2 7,3.67441860465116 3.09302325581395,2 1,2 7)) ``` [Answer] # BBC BASIC Emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> I'm expecting this to golf down into the 400's. **Input / Output** Every time the user enters a new line, the program checks if any new triangles have been created, and outputs them immediately, see below. A new triangle is created wherever the new line intersects with two pre-existing lines that are also mutually intersecting (except when all three lines intersect at a point, which is a special case that has to be dealt with.) ![enter image description here](https://i.stack.imgur.com/IqySZ.png) **Code** The main program is about as simple as can be. At the end is the function, which performs the complex task of detecting intersections, according to the formula in <http://en.wikipedia.org/wiki/Line%E2%80%93line_intersection> The function returns zero if there is no intersection and a nonzero floating point number if there is. It also has a side effect: the coordinates of the intersection are appended to the string z$. Additionally, in BBC basic the variables of a function are visible to the main program provided the main program does not have a variable of the same name (even after the function has finished.) Therefore the main program has access to the variables `x` and `y`, and `m` and `n`, which store the coordinates of the current and previous intersections. This is used to detect if we have really found a triangle and not just three lines intersecting at a point. ``` DIM a(99),b(99),c(99),d(99) :REM declare 4 arrays to hold the ata y=0 :REM x and y are only initialized x=0 :REM to avoid a no such varialbe error later FOR i=0 TO 99 :REM for each input line INPUT a(i),b(i),c(i),d(i) FOR j=0 TO i-1 :REM iterate through all combinations of 2 previous lines FOR k=0 TO j-1 z$="" :REM clear z$, three function calls on next line will write the triangle (if found) to it IF i>j AND j>k AND FNf(i,j)*FNf(i,k)*FNf(j,k)<>0 IF x<>m OR y<>n PRINT z$:REM to avoid printing the same triangle twice, print only if j,k,i in lexicographic order. Also reject if x,y (3rd FNf call) and m,n (2nd FNf call) are the same: this means a point, not a triangle. NEXT NEXT NEXT DEF FNf(g,h) :REM returns zero if no intersection found, otherwise a floating point value m=x :REM backup previous x and y n=y :REM to use in test for point versus triangle p=a(g)-c(g) q=b(g)-d(g) r=a(h)-c(h) s=b(h)-d(h) t=a(g)*d(g)-b(g)*c(g) u=a(h)*d(h)-b(h)*c(h) e=p*s-q*r :REM following method in wikipedia, calculate denominator of expression IF e<>0 x=(t*r-u*p)/e : y=(t*s-u*q)/e: z$=z$+" "+STR$(x)+" "+STR$(y) :REM if denominator not zero, calculate x and y and append a string copy to z$ IF (a(g)-x)*(c(g)-x)>0 OR (b(g)-y)*(d(g)-x)>0 OR(a(h)-x)*(c(h)-x)>0 OR(b(h)-y)*(d(h)-y)>0 e=0 =e :REM return e :REM previous line sets e to zero if the intersection falls outside the line segment. This is detected when both are on the same side of the intersection, which yields a positive multiplication result. ``` ]
[Question] [ Inspired from the assortment of other 'Tips for golfing in language xyz'. As usual, please only suggest tips that are specific to OCaml and not programming in general. One tip per answer please. [Answer] ## Use functions instead of match ``` let rec f=function[]->0|_::t->1+f t ``` is shorter than ``` let rec f x=match x with[]->0|_::t->1+f t ``` [Answer] ## Never use begin […] end This: ``` begin […] end ``` is always synonymous with this: ``` ([…]) ``` [Answer] ## Define several variables or functions at once Thanks to tuples, you can define several variables at once. And as functions are first-class citizens…: ``` let f,g=(fun x->x+1),fun x->2*x ``` You can’t, however, write: ``` let f,g=(fun x->x+1),fun x->2*f x ``` > > Error: Unbound value f > > > Unfortunately, you can’t avoid the issue by using `rec`: ``` let rec f,g=(fun x->x+1),fun x->2*f x ``` > > Error: Only variables are allowed as left-hand side of `let rec` > > > [Answer] ## Exploit [curryied](https://en.wikipedia.org/wiki/Currying) functions Functions in OCaml are curryied. It might be useful to exploit that fact sometimes. ``` let n y=f x y ``` can be written ``` let n=f x ``` If you need arithmetic operations, you can surround them with parentheses so they behave like standard, prefix functions. `(+)`, `(-)`, … ``` let n=(+)1;; n 3;; ``` > > `- : int = 4` > > > [Answer] # `downto` If you're not sure how to loop downwards, `downto` is usually the one to go for. Instead of: ``` for i=0 to 1000 do Printf.printf"%d "(1000-i) done ``` You can do: ``` for i=1000 downto 0 do Printf.printf"%d "i done ``` [Answer] # `print_string` Instead of the usual `Printf.printf""`, you can actually use the below (ONLY for strings, no formatting): ``` print_string"wassup" ``` Which is 1 byte shorter than: ``` Printf.printf"wassup" ``` ]
[Question] [ The code should take text from standard input: ``` The definition of insanity is quoting the same phrase again and again and not expect despair. ``` The output should be a PNG file containing the [word cloud](http://en.wikipedia.org/wiki/Tag_cloud) corresponding to that text: ![enter image description here](https://i.stack.imgur.com/RBT3E.png) The above [word cloud](http://en.wikipedia.org/wiki/Tag_cloud) was created [using a specialized online application](http://worditout.com/word-cloud/make-a-new-one) and it filtered the word `The` and other common words (`of`, `is`, `and`, `not`, and `the`). Since this is code golf, the common words will not be filtered and I leave secondary aesthetics of the word cloud to the choice of each coder. Unlike the image exampled here, no words should be excluded, common or otherwise. The definition of a word is defined below. In this case a word is anything alpha-numeric; numbers are not acting as separators. So, for example, `0xAF` qualifies as a word. Separators will be anything that is not alpha-numeric, including `.`(dot) and `-`(hyphen). Thus `i.e.` or `pick-me-up` would result in 2 or 3 words, respectively. Should be case sensitive - `This` and `this` would be two different words, `'` would also be separator so `wouldn` and `t` will be 2 different words from `wouldn't`. The tags should appear clustered but not overlapping and the font size should be directly proportional to the number of occurrences of that word in the text. The word should appear only once. Specific font color is not required in this case. Semantic association is not a requirement. **Hint** - This other code golf could help: [Count the words in a text and display them](https://codegolf.stackexchange.com/questions/19568/count-the-words-in-a-text-and-display-them) [Answer] ![Output example](https://i.stack.imgur.com/wA1Zf.png) # Python 3, 363 308 293 274 characters ``` import os,sys,re,collections as C c=C.Counter() n=sys.argv[1] o="graph d{" for w in re.findall("\w*",open(n).read()):c[w]+=1 for w,x in c.most_common(75)[1:]:o+="%s[fontsize=%s,shape=none];"%(w,x/5) open(n+'.dot','w').write(o+"}") os.system("fdp -Tpng %s.dot>%s.png"%(n,n)) ``` Call it like this: `python cloud.py file.txt`. The script uses Graphviz's `fdp` force-directed graph generator to generate the image (it will spit out a GraphViz file to file.txt.dot and a PNG image file to file.txt.png). *This means you'll need to have Graphviz installed.* The image above is the cloud it makes of Shakespeare's Hamlet - you can tell, since it contains "To be or not to be". There's also some delightful nonsense to be found: > > It is, to You and I, the Ham of Not thatO lord have us, what now... > > > [Answer] ## JAVASCRIPT 473 ``` var wordCloud=function(e){var t=e.split(/[\s-.,;]+/);var n={},r;for(r in t){var i=t[r];n[i]=n[i]+1||1}var s=document;var o=s.createElement("canvas");o.width=600;o.height=400;o.style.display="none";s.body.appendChild(o);var u=o.getContext("2d");var a=0,f=50;for(var i in n){u.font=n[i]*50+"px monospace";u.fillText(i,a,f+n[i]*5);a+=i.length*n[i]*50;if(a>o.width*.6){a=0;f+=n[i]*5+100}}var l=o.toDataURL("image/png");var c=s.createElement("img");c.src=l;s.body.appendChild(c)} ``` ### [Ungolfed demo](http://codepen.io/rafaelcastrocouto/pen/Lzmga/) ``` wordCloud("string;abc,test-omg shouldn't test omg lalala. s2 s2 s2") ``` ![enter image description here](https://i.stack.imgur.com/TnjpX.png) ]
[Question] [ As in [this challenge](https://codegolf.stackexchange.com/questions/262032/vertices-of-a-regular-dodecahedron), the task is to generate the vertices of a polyhedron. The polyhedron here is the one obtained by dividing a regular icosahedron's triangular faces into smaller triangles so that each edge is divided into \$b\$ segments (denoted \$\{3,5+\}\_{b,0}\$ [here](https://en.wikipedia.org/wiki/Geodesic_polyhedron)) and projecting onto the unit sphere. Your program or function should take \$b\$ as input. The vertices can be in any order (and the polyhedron can have any orientation), but each should appear exactly once, and the precision should be whatever's reasonable in your language for floating-point arithmetic. (After typing this up, it occurred to me that a simple solution probably involves deduping points that are on the icosahedron's edges, but I'm hoping someone has a clever way of traversing the icosahedron and including exactly the right points instead.) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~162~~ 146 bytes ``` Nθ⊞υ⟦⁰¦¹⊘⊕₂⁵⟧≔⟦⟧ηFυFE²⊞OΦιν×⊖⊗κ§ι⁰F¬№υκFΦ⊞Oυκ⁼⁴ΣXEμ⁻ξ§κπ²⊞η⟦κμ⟧FηF…¹θ⊞υE§ι⁰⁺×κλ×⁻θκ§§ι¹μFηFΦυ⬤ι№η⟦μκ⟧F…²θF…¹λ⊞υE§ι⁰⁺⁺×μν×⁻λμ§§ι¹ξ×⁻θλ§κξIEυ∕ι₂ΣXι² ``` [Try it online!](https://tio.run/##jZK9bsIwFIX3PoVHW3IlQHTqhKBVGaAIuqEMBlxixT@JY9O8fXodJyRBqtQsTux77/nOcc4ps2fDZF2vde7d1qsTt7ggr087X6bYU3ScUDSl6IPJG7/gtT5brrh28H4oPLN8b4zDL4SQBJoWZSmuGh8TilL4/DYWYU9Qs25YjmcUhbmfObfMGYvfhXSgJyjShKIvoXiJV7yXWBl/krBmBI4Xbq0vvArVExKeOHcL@kvjtQu02X27HT2SawooegNwWeI5RQev8M78QF2gUxRthPYlrnqxjKKcBPVZlGxiSSEWOFBJ5zFtRfdMXzmGuIquFCTD6BE7hCBBJdqFOfLuPcoXEbPrGfROYVs1IA/CrVtQW0gZKmMiARRcZUkfV0ScRcQxtPwH9IBcDW8tksuA9yd51QT54FSSUdhV625nBfAvWemaqwGilbiJCw@zBj9ef4GiuyLorut5/XyTvw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `b`. ``` ⊞υ⟦⁰¦¹⊘⊕₂⁵⟧≔⟦⟧η ``` Start with one vertex and no edges of an icosahedron of side `2`. ``` Fυ ``` Process all vertices as they are discovered. ``` FE²⊞OΦιν×⊖⊗κ§ι⁰ ``` Generate more vertices by rotating about the line `x=y=z` and reflecting in the `xy` plane. (This is the same procedure as for the regular dodecahedron in the linked question.) ``` F¬№υκ ``` Ignore previously discovered vertices. ``` FΦ⊞Oυκ⁼⁴ΣXEμ⁻ξ§κπ²⊞η⟦κμ⟧ ``` Save the new vertex and also discover any edges by checking for previously found vertices that are `2` away. (Very fortunately, `ϕ²+1²+(ϕ-1)²=2²` under floating-point arithmetic.) Since only previously found vertices are checked, each edge is only detected once, and has a specific direction. ``` Fη ``` Loop over the edges. ``` F…¹θ ``` Loop over the intermediate points. ``` ⊞υE§ι⁰⁺×κλ×⁻θκ§§ι¹μ ``` Extrapolate a point along the edge. (Sadly Charcoal doesn't have a way of adding two vectors which would really simplify this. Maybe if it had octonions...) ``` Fη ``` Loop over the edges again. ``` FΦυ⬤ι№η⟦μκ⟧ ``` Loop over the vertices that have edges to both vertices of that edge. (Note that because the edges have a specific direction, each face can only be detected once.) ``` F…²θF…¹λ ``` Loop over the interior points of the face. ``` ⊞υE§ι⁰⁺⁺×μν×⁻λμ§§ι¹ξ×⁻θλ§κξ ``` Extrapolate a point inside the face. (Due to the normalisation, it's not necessary to interpolate.) ``` IEυ∕ι₂ΣXι² ``` Normalise all the points. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 99 bytes ``` mcR.add+Ksm.>L+0d3*_B1_B.n3s+mm+V*Rkhd*R-QkedStQJf&SITq.aT2^K2mmsMC.b*RlNYkdfq3lT./UQf.A}RJ>3PyT^K3 ``` [Try it online!](https://tio.run/##K6gsyfj/Pzc5SC8xJUXbuzhXz85H2yDFWCveyTDeSS/PuFg7N1c7TCsoOyNFK0g3MDs1Jbgk0CtNLdgzpFAvMcQoztsoN7fY11kvSSsoxy8yOyWt0DgnRE8/NDBNz7E2yMvOOKAyJM7b@P9/EwA "Pyth – Try It Online") We begin with the vertices of the regular icosahedron made by all cyclic permutations and sign flips of \$(0,1,\phi)\$. Then we find all unordered pairs of edges that have distance 2, interpolate along the edge they specify. Then we find all unordered triplets where all the pairs are in the list of edges, and using partitions of the input we interpolate along the face they specify. Finally we normalize all points. [Answer] # Python3, 421 bytes: ``` def f(l,r=[]): if[]==l:yield r;return for i in l[0]:yield from f(l[1:],r+[i]) C=lambda n=0,b=[0,1,(1+5**.5)/2]:[]if n==3 else[*f([[[i,-i],[0]][i==0]for i in b[n:]+b[:n]])]+C(n+1) def G(w): c,R=C(),[] for x in c: for y in c: if sum((a-b)**2 for a,b in zip(x,y))**.5==2: R+=[x,y] for v in range(1,w):R+=[[((w-v)*a+v*b)/w for a,b in zip(x,y)]] return{tuple(i/sum(j**2 for j in p)**.5 for i in p)for p in R} ``` [Try it online!](https://tio.run/##bVA9c8IwDJ2bX@ENy3FKAuWul54nBnZWnYYE4tZcMD4TPtJef3tqh0KXbnp6T3pPcn33cbDzV@eHYdtopnkrvUKCMmFGIynVlr1p2i3zb77pTt4mTB88M8xY1mJOv6z2h30cxqIk6VM0BMlStdW@3lbMqlzWCnNZSF6kCyGeFzCdUYlkdCDVnDXtsUGhOSIamRmSYTOhUSqnh1uNtqS0xtISAaVLbtMCkhh6xS8x70au1ZKDRLplvMapTSBG1D9QOIwdT3vOq6wGIWYjXck6Cj6N41fZA8SQSs1GPVunCkOXRhDV56j1lX1veCGDeRQg55fsDKJKz6KG6eW/tRRW3N741Z1c23AzjUl29xS7KHaj@d@bHcTSxXL9PTzad/siD8c/OW9sx1fcANzBJJuIlxyGHw) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~161 153 148~~ 146 bytes ``` ->n{(n*n*10+2).times{|k|b=k/10%n e=b-a=k/10/n r=n*c=1i**0.4 r+=e<0?b/c-c*a:a/c-b*c+e p 2*r*c**k/s=(r.abs*2i+z=n-e*=e<0?5**0.5-1:2).abs,z*~0**k/s}} ``` [Try it online!](https://tio.run/##HY1LCsIwGIT3OYUboU5M88Buir8eRFwkIYVSDCVVxD68eqxdDcN8M5Ne7pMbyuISpyIiQituDuWzfYRhmrvZUSe12kcWyAm7GRlZoghPugVUeWKJUzirq5NeeNjarurgeWD9ziDBA50cqEildQNMy0eKImDrVP@FSuh6/VzT44iv2vBlyW9qbuaefw "Ruby – Try It Online") Golfed version of the original 175-byte concept. Now competing with the golfing languages! * Eliminated variable `j=k/10`. Introduced new variable `e=a-b`. * `a` & `b` are now integers (not normalised by dividing by `m=n*1.0`, with other values scaled up by `n` accordingly.) * Conditionals used for selection instead of arrays. `d` was revised `true/false` instead of `0/1`, then eliminated completely. `e<0?` (used twice) is overall shorter than `d ?` because it doesn't require whitespace, or prior definition of `d=0>e`. * Instead of using pythagoras (squaring then square root) to calculate scale factor `s`, multiply `r.abs` by `1i`, add `z` and take `abs` of the result. This allowed `z` to be calculated on the same line as the scale factor calculation (but means the output is now `x+yi` before `z`.) * Moved `~0**k` to allow deletion of parentheses. Similarly redistributed calculation of `c` and `r` (Multiplying `r.abs` by `2i` instead of `1i` as previously allows movement of `2*r*c**k` and deletion of parentheses.) * Removed `[]` around output. This alters readability because it prints each point over 2 lines instead of 1, but saves 2 bytes. # [Ruby](https://www.ruby-lang.org/), 175 bytes first working version ``` ->n{(n*n*10+2).times{|k|j=k/10;a=j/n/m=n*1.0;b=j%n/m z=(1+(a-b)*[5**0.5-1,2][d=a>b ?0:1])*~0**k r=((c=1i**0.4)+[b/c-a*c,b-b*c+a/c-a][d])*c**k*2 p [z/s=(r.abs2+z*z)**0.5,r/s]}} ``` [Try it online!](https://tio.run/##HY1BDoMgFAX3nsJNE/iIgKmbmm8PQlwArUk1kkbaRVF7dYtdTt5M3vy2n73Hnbd@IR48KMkqWr4e0z0s67gOOAolG4OD8GLCtJeysTicEmURiWLEcEtB1wCyrLkqqk7f0LQ2v8qL6ih8JcCYzUiIQ/U4rDNl2grHDbjCcguOmYNSl3SXbKiyZ66jCEjm0thQsQiR/g@KWYRu2/Zeq27/AQ "Ruby – Try It Online") A function that takes an argument `n` and prints the vertices in the format `[z,x+yi]`. One pair of opposite vertices is aligned with the `z` axis; these vertices are printed last. The code generates each vertex exactly once with no duplicates, per OP's comment in the post. **Explanation** According to <https://mathworld.wolfram.com/RegularIcosahedron.html> `A construction for a icosahedron... places the end vertices at (0,0,+/-1) and the central vertices around two staggered circles of radii 2/sqrt(5) and heights +/- 1/sqrt(5)` This code produces the `z`coordinates of the icosahedron at a scaled up size of `0,0,sqrt(5)` for the end vertices, which puts the other vertices at `z=+/-1`. For calculation of the x and y coordinates, the radius of the circle is conveniently set to 1, but the coordinates are doubled for compatability with the z coordinates prior to normalization. The icosahedron is split into 10 identical diamonds as below. We include only the points marked with an `X` because the points marked with `O` are included as part of the adjacent diamond. We do however have to include the poles (marked as `?`) once. The diamond is folded at the join of the two triangles. Looking down the `z` axis at the `x+yi` plane, the polar apex is at `0+0i`, and the other apex is at `1+0i`. The right vertex is at a 1/10th rotation, `c=i**0.4 = 0.809+0.588i`. The left vertex is at the conjugate, `0.809-0.588i`. As the absolute value of `c` is 1, the conjugate is conveniently generated by `1/c.` ``` North Pole ? x+yi=0 z=sqrt(5) / \ O X / \ / \ O X X x+yi / \ / \ / \ x+yi =1/c O---X---X---X =c=i**0.4 z=1 =0.809 \ / \ / \ / =0.809 -0.588i O X X +0.588i Note: x,y coordinates at half \ / \ / the scale of z coordinates O X (they are doubled before normalization) \ / O x+yi=1 z=-1 ``` We work through the `n*n` points in the diamond with increments in the value of `j`. we start at `[r=x+yi=c,z=1]`, with increasing value of `b=j%n` moving diagonally towards the bottom corner and `a=j/n` moving diagonally towards the top corner. different vectors (selected by `d=a>b`) must be added to the starting point for the upper and lower triangle. ``` x+yi z Upper triangle a>b a*(0-c)+b*(1/c-0) (a-b)*(5**0.5-1) Lower triangle a<=b b*(1-c)+a*(1/c-1) (a-b)*2 ``` For each value of `j` we generate 10 images by 1/10 rotation of the value `r=x+yi` by multiplying by `c**k` and flipping the `z` value by multiplying by `-1**k` (due to priority of operators in Ruby, this is represented as `~0**k`) After `n*n*10` iterations, we have covered all points up to `a=b=n-1`. It remains to add the polar vertices. This just requires another 2 iterations where the value of `j` is `n*n`, `a=n` and `b=0`. Finally, the last line normalizes the points to a sphere and outputs them. ]
[Question] [ Your goal is to write a program or function that takes in as input a string representing the path to a file, and outputs a truthy value if that file is not empty and contains no non-null bytes -- i.e., all bits are 0 -- and a falsey value otherwise. I realize it is a very simple problem and I guess I could hack something, but I suspect there must be some short and elegant way of doing it, and that gave me the idea to make a challenge out of it. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. (My own preference would go to the fastest solution, but that is too implementation dependent...) **Related questions**: [Pad a file with zeros](https://codegolf.stackexchange.com/questions/125661/pad-a-file-with-zeros) **Motivation** : *This is only to tell where the problem comes from, in case you are interested. You do not need to read it.* ISO images of CDs and DVDs, copied with "dd" or other means, often terminate with a sequence of useless blocks containing only null bytes. Standard techniques to remove these blocks are known and simple (see <https://unix.stackexchange.com/questions/74827/> ) but they may sometimes remove non null useful data because the medium can lie about its own size. So I want to check that the removed blocks contain only null bytes. Removing these blocks is important for defining a normalised version of ISO-images. [Answer] # Pyth, ~~6~~ 5 bytes ``` !sCM' ``` [Try it online!](https://tio.run/##K6gsyfj/X7HY2ff/f6UYAxBUAgA) Takes a filename from STDIN, opens and reads the file, converts it to a list of `int`s (think Python `ord`) `sum`s the list (will return `0` iff file is all null bytes), and `not`s the result, printing it. --- Hey, This looks a lot like a general programming question. These belong on [Stack Overflow](https://stackoverflow.com/). However, from the comments under the main post, I can see that this was not your intent. That said, I feel that the discussion has been unnecessarily hostile on both sides, so I've decided to pick up the slack and give you the proper PPCG welcome! Generally, we ask that any challenges are first posted to [our sandbox](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges) for proper feedback. You can take a look at the current submissions in there to see what format we prefer for challenges. Please give it a try next time! Just in case we've all misunderstood you and you *are* looking for a general solution, here's a solution in Python 3: ``` def main(string): with open(string) as file: return not any(map(ord,file.read())) ``` [Answer] # [GNU sed -zn](https://www.gnu.org/software/sed/manual/sed.html), 5 bytes The input file is passed to sed as a command-line parameter. Output as a standard shell return code - i.e. 0 is TRUE, 1 is FALSE. ``` /./q1 ``` Normally `sed` works on newline-delimited input records (AKA "lines"). `-z` changes this to nul-delimited input records. If any input records match the `.` regex, then `q`uit with exit code 1. [Try it online!](https://tio.run/##VYvLCsIwEEX3@YpLqBsh0q6Fit/hA2IzsYE4U5PoQvz32I1U7/Lccy42j9XbGGWwhWAiunYeXpQkb5wt6sH2Nh8WPVh44V4SCuXiQyQEXoo/bQsnakqBi4deZZgeGrr5hlplKjDmF1VxMHtG072viSaY@xOHc3vE@lRpGAXNTjlhqh8 "Bash – Try It Online") [Answer] ## DOS, 37 bytes ``` 100:BE 80 00 MOV SI, 0080 103:AD LODSW ;get command-line length 104:98 CBW ;only a byte 105:93 XCHG BX,AX 106:88 40 FF MOV [BX+SI-01], AL ;zero end of name 109:B4 3D MOV AH, 3D 10B:89 F2 MOV DX, SI 10D:CD 21 INT 21 ;open file 10F:93 XCHG BX, AX ;handle into BX 110:AF SCASW ;DI=0 111:B4 3F MOV AH, 3F 113:B1 01 MOV CH, 01 115:CD 21 INT 21 ;read 1 byte 117:91 XCHG CX, AX 118:E3 06 JCXZ 0120 ;quit on EOF 11A:97 XCHG DI, AX ;set true for later 11B:38 2C CMP [SI], CH 11D:74 F2 JZ 0111 ;loop while zero 11F:4F DEC DI ;set false 120:97 XCHG DI, AX 121:B4 4C MOV AH, 4C ;return 123:CD 21 INT 21 ``` It opens the file named on the command-line, returns 0 if empty or contains non-zero, otherwise returns 1. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 24 bytes ``` Zero@Max&0@Ords@FileRead ``` [Try it online!](https://tio.run/##fZBNS8QwEIbv@RVDEQ9aJHUPgqBbEDwIfrAKgjWHsZ1qME1KJoUK/vfallXMsjS3fDzPm3cwBCw/aKjh/AKGF/Iuv8X@UOb3vuL8WhvaEFbDeg2tazuDgYBdQ1CPNyzE9ODZ60BF8mbQfp6EPiQpJImCpTXqgu/oP57Zzphf/LWXckGxB/doK9ds@UdsWkMFcql1CpmUCr4v4cZpq7Z4jYYjfkrnKB6OYDNLC5nCqVRqKb5xHMzXXkm2Wp3B8bzP5k5/8WISEQcWd0QVFwdtW74r8eC1DU/j@RUycVGnsDPcaFRR8bjG7qeUGn4A "Attache – Try It Online") ## Explanation This is a composition of 4 functions, executed one after the other: * `FileRead` - takes a file name as input, returns the contents of that file * `Ords` - returns the ASCII code points of each character in a list * `Max&0` - this is equivalent to, for argument `x`, `Max[x, 0]`; this in turn computes the maximum of all entries in `x` and `0` (yielding `0` for the empty list) * `Zero` - this is a predicate that checks if this number is in fact 0, and returns that boolean. [Answer] # [C](https://port70.net/~nsz/c/c11/n1570.html) (32bit platform), 65 bytes ``` main(x,v)int*v;{for(v=fopen(v[1],"r");!(x=fgetc(v)););return++x;} ``` Assumes sizes of pointers are all the same, which is almost always true. Returns with a `0` exit code on success (file contains only `NUL` characters), some other value otherwise. Behavior is undefined if command line argument isn't a path to a readable file. [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 26 bytes ``` od -An $1|grep -qv [^0\ *] ``` Input filename is given as a command-line parameter. Output as a standard shell return code - i.e. 0 is TRUE, 1 is FALSE. [Try it online!](https://tio.run/##VYvLCsIwEEX3@YpLqBsh0q6Fit/hA2IzsYE4U5PoQvz32I1U7/Lccy42j9XbGGWwhWAiunYeXpQkb5wt6sH2Nh8WPVh44V4SCuXiQyQEXoo/bQsnakqBi4deZZgeGrr5hlplKjDmF1VxMHtG072viSaY@xOHc3vE@lRpGAXNTjlhqh8 "Bash – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes ``` BinaryReadList@#~MatchQ~{0..}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfKTMvsagyKDUxxSezuMRBuc43sSQ5I7Cu2kBPr1YNKh1elFmSGq2UmltQUqmko1BdG2vNhSKTV5qTUwySMdBRACFMBfklyGoMjXUUjExNgQxzkFKugKLMvJLoNJgVsUAxuBBEH6oQzDSg6H8A "Wolfram Language (Mathematica) – Try It Online") ## Explanation ``` & (* Function which returns whether *) BinaryReadList (* the list of bytes *) @ (* of *) # (* the input *) ~MatchQ~ (* matches *) {0..} (* a list of a one or more zeros *) ``` # Alternate solution, 22 bytes If empty files are supposed to pass, then this can be shortened to: ``` Tr@BinaryReadList@#<1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/A/pMjBKTMvsagyKDUxxSezuMRB2cZQ7T9ELLwosyQ1Wik1t6CkUklHobo21poLRSavNCenGCRjoKMAQpgK8kuQ1Rga6ygYmZoCGeYgpVwBRZl5JdFpMCtigWJwIYg@VCGYaUDR/wA "Wolfram Language (Mathematica) – Try It Online") [Answer] # Java, 149 bytes ``` boolean b(String f)throws Exception{java.io.InputStream s=new java.io.FileInputStream(f);int i=Math.abs(s.read());while(i==0)i+=s.read();return i<0;} ``` [Answer] # Perl 5, 20 bytes `$\=0;exit<>=~/^\0+$/` Takes a file name in command line args and returns the response in the exit code of the program [Answer] # Python 3, 59 bytes ``` f=lambda s:any(open(s,'rb').read())+not len(open(s).read()) ``` Returns 0 for success (all bytes zero). Returns 1 for failure (at least one nonzero byte, or zero length file). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 bytes Full program. Prompts for filename from stdin. ``` 0=⌈/11 ¯1⎕MAP⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@B7aOeDn1DQ4VD6w0f9U31dQx41DsPJPVfAQw0izMUCooy80rSFJSUFOwUUnMLSiq5IHIFXMg8ZJWJSckgxXn5eXmlOTlw5ah8ZA0xBiAI0pOYk4OiB8oHAA "APL (Dyalog Unicode) – Try It Online") `⍞` prompt for filename `11 ¯1⎕MAP` map that file to a packed bit array `⌈/` maximum (reduction); smallest float if empty, otherwise 0 or 1 `0=` is zero equal to that? [Answer] # Haskell, 49 bytes ``` import Data.ByteString f=(all(<1)<$>).getContents ``` Obviously if the import is not included, then it is 26 bytes. [Answer] # JavaScript (ES8), 52 bytes Takes a url as an argument and returns a promise that resolves to `true` if the file isn't empty and contains no null bytes. ``` async p=>!/\0|^$/.test(await(await fetch(p)).text()) ``` [Answer] # [Zsh](https://www.zsh.org/), 35 bytes ``` ! for c (${(s::)"$(<$1)"})((i|=#c)) ``` [Try it online!](https://tio.run/##bY7NCsIwEITveYqxRpoIgt6kVZ@kl1ITGojb0sSDf88e1xZFxN3LwOzsN9fQpn5wFC3yaj1tjgPo7L34NvBxujiaBWtz6uNFWKVVmsF2AxooeVOhKHQm1U5udPbQSrn7ft5onbQQryMLR1gKZ1lJWyK2hgR43rzFNsAFJtFqJKCmI2rvx1YV5ZwSxgfzL2QcvxumZmAY1/2NWpee "Zsh – Try It Online") Outputs via exit code. Read in, split on characters, and bitwise-or each codepoint together. If the file is empty, the body of the loop is never run and so the loop returns truthy. If the truthy-falsy values can be swapped, the leading `!` can be removed for a 2-byte save. ]
[Question] [ It's Christmas in July, so what better way to celebrate than a virtual white elephant gift exchange! For this King of the Hill challenge, you must create a bot that plays in a [White Elephant exchange](https://en.wikipedia.org/wiki/White_elephant_gift_exchange) simulation, trying to get the highest-valued present it can. # Game Rules * The game will be played over many rounds, each made up of a variable number of turns. * **Round Setup**: There will be as many presents as there are players in the game, each valued randomly uniformly in the range [0...1), with this value being unknown until the present is "opened". Players will be put in a random order in a queue. The first player will be popped from the front of the queue. * When it is a player's turn, they may either open a present or steal another player's present, passing turn to the player whose present was stolen. + Each present may be stolen up to 3 times. + You cannot steal from the player that just stole from you. + Each player can only have one present at a time. * After a present is opened, play advances to the next player popped from the front of the queue. This will be the next player in turn order who has not yet had a turn. * **Round End**: When all presents have been opened, the round ends, and the value of the present held by each player is added to that player's score. A new round begins, with each player now holding no present and the player order shuffled. * **Game End**: The game will end when at least one player has at scored 100 500 points, with victory being awarded to the player with the highest total value of presents. # Coding All submissions should be compatible with Python 3.7. You must write a class that directly inherits from `WhiteElephantBot`. For instance: ``` class FooBot(WhiteElephantBot): # Your implementation here ``` You may provide an `__init__` method (which takes one argument, `name`) in your bot class, which must call `super().__init__(name)`. Your class must have a `take_turn` method expecting the following arguments in this order: * `players`: The list of player names, in turn order, of all players that do not yet have presents. * `presents`: A dictionary that maps player names to 2-tuples containing the present value held by that player and the number of times that present has been stolen. This will only include other players who are currently holding presents. * `just_stole`: If the last action taken was a steal, this will be the name of the player who just stole. If not, it will be `None`. Each argument will be immutable or a new object so that mutating any of them will not have an effect on the game. You may keep a copy of any of the arguments if you so desire. An example value for `presents`: ``` { 'Alice': (0.35, 0), 'Bob': (0.81, 2), 'Charlie': (0.57, 1) } ``` Your `take_turn` method should return the name of the player you wish to steal from or `None` to open a present. If it raises an exception, returns something other than a `str` or `None`, or the name of a player you cannot steal from, you will open a present by default. Your constructor will be called at the beginning of each round, so you do not get to remember state from round to round. By inheriting from `WhiteElephantBot`, you will have access to a `steal_targets` method that will take the presents dict and `just_stole` and return a list of names of players you can steal from. Any modules your script needs must be imported at the top of your entry. # Test Driver The test driver can be found [here](https://github.com/Beefster09/pcg-general/blob/master/white_elephant.py). You do not need to include `from white_elephant import WhiteElephantBot` in your posted answer, however a local module will need to do that. # Baseline Competitors * **Random**: Chooses randomly whether to open a new present or to steal, with the steal target chosen uniformly randomly. * **Greedy**: steal the most valuable present that can be stolen. If no presents can be stolen, open a present. * **Nice**: Always opens a new present. Never steals. # Additional Rules * It is your responsibility to catch all exceptions. If your class fails to catch an exception, it will be disqualified. In addition, please do not catch KeyboardInterrupts. * Do not use files or other methods to bypass the inability to save state between games. You may not, for instance, save a neural network state to a file mid-run. * Your bot must be self-contained within class code and related constants. * You may only use standard library imports. * There is no strict performance requirement. Be reasonable and prudent. If performance becomes an issue, I reserve the right to add time limits. * One entry per person. If you submit more than one entry, your bots may not work together. I'm going to allow multiple entries per person for now, though I may reban it later if it becomes a problem. * This is an open competition with no distinct end date. It will be rerun any time I am able when there have been significant changes. EDIT1: Changed winning score from 100 to 500 so that rankings are more consistent. The test driver has a new bugfix and also reflects the win score changes. EDIT2: Clarifying note on required imports. --- # Leaderboard (as of Aug 8, 2018) 1. SampleBot (500.093) 2. LastMinuteBot (486.163) 3. RobinHood (463.160) 4. OddTodd (448.825) 5. GreedyBot (438.520) 6. SecondPlaceBot (430.598) 7. ThresholdBot (390.480) 8. Gambler (313.362) 9. NiceBot (275.536) 10. RandomBot (256.172) 11. GoodSamaritan (136.298) [Answer] # LastMinuteBot (With big thanks to @Mnemonic for the skeleton of the code, since I barely know Python.) ``` class LastMinuteBot(WhiteElephantBot): def take_turn(self, players, presents, just_stole): targets = self.steal_targets(presents, just_stole) if len(targets) <= 1: return None target = None # If most of the presents are already distributed, try to steal an # un-restealable gift of high value if len(presents) > (len(players) + len(presents)) * 0.75: at_threshold = [t for t in targets if presents[t][1]==2 and presents[t][0]>=0.8] if at_threshold: target = max(at_threshold, key=lambda x: presents[x][0]) # Otherwise, take the best available if not target: target = max(targets, key=lambda x: presents[x][0]) return target if presents[target][0] > 0.5 else None ``` Take advantage of the fact that gifts can't be stolen more than thrice, do the third stealing yourself if you find a high value gift and most presents have been opened. [Answer] # Odd Todd ``` class OddTodd(WhiteElephantBot): def take_turn(self, players, presents, just_stole): targets = self.steal_targets(presents, just_stole) # if none to steal, pick present if len(targets) <= 1: return None # steals the best gift that he can, as long as he's the 1st/3rd steal targets = [t for t in targets if presents[t][1] % 2 == 0] if targets: return max(targets, key=lambda x:presents[x][0]) else: return None ``` Steals the best gift that he can, but doesn't want to be the second person to steal a gift, because if it gets stolen from him he can't get it back. [Answer] # SecondPlaceBot ``` class SecondPlaceBot(WhiteElephantBot): def take_turn(self, players, presents, just_stole): targets = self.steal_targets(presents, just_stole) if len(targets) <= 1: return None # If most of the presents are already distributed, take the second best. if len(presents) > (len(players) + len(presents)) * 0.8: target = sorted(targets, key=lambda x: presents[x][0])[-2] # Otherwise, take the best and hope someone steals it later. else: target = max(targets, key=lambda x: presents[x][0]) return target if presents[target][0] > 0.5 else None ``` Everyone's going to be fighting for the most valuable gift. The next best gift is almost as good, but much less likely to be stolen. [Answer] # ThresholdBot ``` import random class ThresholdBot(WhiteElephantBot): def __init__(self, name): self.name = name # Choose a minimum value to be happy. self.goal = 1 - random.random() ** 2 def take_turn(self, players, presents, just_stole): # Find who has a gift that's sufficiently valuable. targets = self.steal_targets(presents, just_stole) targets = [x for x in targets if presents[x][0] >= self.goal] targets = sorted(targets, key=lambda x: presents[x][0]) if not targets: return None # Choose a target (biased toward the best gifts). weighted = [] for i, target in enumerate(targets, 1): weighted += [target] * i ** 2 return random.choice(weighted) ``` We don't really care about getting the *best* gift, just something *good enough*. So long as there's something worth stealing, we'll do it. [Answer] # GoodSamaritan ``` class GoodSamaritan(WhiteElephantBot): def take_turn(self, players, presents, just_stole): targets = self.steal_targets(presents, just_stole) #if only one player has a gift, don't steal it! if len(presents)<=1 or len(targets)==0: return None else: #Steal the worst present return min(targets, key=lambda x: presents[x][0]) ``` Give unlucky people another chance at good fortune [Answer] # SampleBot ``` import random class SampleBot(WhiteElephantBot): def rollout(self, values, counts, just_stole, next_move): targets = set() move_chosen = False for i, (v, n) in enumerate(zip(values, counts)): if v and n < 3 and i != just_stole and i != 0: targets.add(i) for i in range(len(values)): if values[i]: break while True: if not targets: break if move_chosen: j = max(targets, key=lambda i: values[i]) if values[j] < 0.5: break else: move_chosen = True if next_move is None: break j = next_move values[i] = values[j] counts[i] = counts[j] + 1 values[j] = 0 counts[j] = 0 if just_stole is not None and counts[just_stole] < 3: targets.add(just_stole) if j in targets: targets.remove(j) just_stole = i i = j values[i] = random.random() for player in (just_stole, i): if player is not None and values[player] and counts[player] < 3: targets.add(player) return values[0] def take_turn(self, players, presents, just_stole, n_rollouts=2000): names = [self.name] + players + list(presents.keys()) values = [presents[name][0] if name in presents else None for name in names] counts = [presents[name][1] if name in presents else 0 for name in names] if just_stole is not None: just_stole = names.index(just_stole) targets = [None] for i, (v, n) in enumerate(zip(values, counts)): if v and n < 3 and i != just_stole and i != 0: targets.append(i) if len(targets) == 1: return targets[0] scores = [0. for _ in targets] n = n_rollouts // len(targets) for i, target in enumerate(targets): for _ in range(n): scores[i] += self.rollout(list(values), list(counts), just_stole, target) / float(n) target_index = targets[scores.index(max(scores))] if target_index is None: return None return names[target_index] ``` Runs 2000 simulations with each player acting greedily and chooses the best action. [Answer] # RobinHood ``` class RobinHood(WhiteElephantBot): def take_turn(self, players, presents, just_stole): #get the possible steal targets targets = self.steal_targets(presents, just_stole) #who stole his gift? targets = [x for x in targets if presents[x][1] > 0] #sort by value targets = sorted(targets, key=lambda x: presents[x][0]) #only steal back if it's worth it targets = [x for x in targets if presents[x][0] > 0.5] if len(targets)>0: return targets.pop() ``` Steal from the rich who didn't earn their present [Answer] # Gambler ``` class Gambler(WhiteElephantBot): def take_turn(self, players, presents, just_stole): #get the possible steal targets targets = self.steal_targets(presents, just_stole) #last player if len(players)==0: #lets gamble! Try and get the highest score return None #If you are not last, steal the best gift that can be restolen so maybe you can become the last player targets = [t for t in targets if presents[t][1]<2 ] if targets: return max(targets, key=lambda x: presents[x][0]) ``` The Gambler is addicted, he tries to be the last player, then he gambles on a new present to beat all the other players. [Answer] # Top3Bot ``` class Top3Bot(WhiteElephantBot): def __init__(self, name): super().__init__(name) self.firstturn = True def take_turn(self, players, presents, just_stole): if self.firstturn: num_presents = len(players) + len(presents) + 1 self.value_limit = (num_presents - 3) / num_presents self.firstturn = False targets = self.steal_targets(presents, just_stole) if players: targets += None return max( targets, key=lambda name: self.steal_ranking(name, presents, len(players)) ) def steal_ranking(self, name, presents, presents_remaining): if name is None: return (0, 0) present_value = presents[name][0] num_steals = presents[name][1] if present_value >= self.value_limit: if num_steals == 2: return (5, present_value) elif num_steals == 0: return (4, -presemt_value) elif num_steals == 1 and presents_remaining == 0: return (3, -present_value) else: return (-1, present_value) else: if num_steals < 2: return (2, present_value) else: return (-2, present_value) ``` This bot does not try to get the best present possible, but tries to get a present that is valued >= (n-3)/n, where n is the number of presents. In most of the cases, there will be presents valued that much, and Top3Bot will try to get its hands on one of these, but he doesn't really care which of those he gets. ]
[Question] [ ## Introduction Today's challenge is all about teeth. Specifically, how long it takes to brush from one tooth to another. Your challenge is, given the locations of two teeth, output the shortest amount of time possible to brush from the first to the second. ## Challenge For this challenge we will be using a layout of an average adult human mouth: [![Layout of human mouth.](https://i.stack.imgur.com/Hnpbj.gif)](https://i.stack.imgur.com/Hnpbj.gif) This diagram shows the widely used [ISO numbering system](https://en.wikipedia.org/wiki/Dental_notation#ISO_System_by_the_World_Health_Organization). The system divides the mouth in four parts and assigns them each a number: upper right (1), upper left (2), lower left (3), and lower right (4). They then number the teeth of each section from the middle of the mouth out from 1-8. Therefore the fourth tooth from the center in the upper right side (section 1) is tooth number 14. Let's assume brushing one tooth takes 1 unit of time. Moving from one tooth to the next one sideways takes 0 units of time. You can also cross from a tooth to the tooth directly above or below it, which also takes 1 unit of time. So how long does it take you to brush from tooth 14 to tooth 31? By looking at the diagram above, you will see it takes 7 units of time. Here is how that's calculated: ``` Action : Unit of time Brushing tooth 14 : 1 unit Brushing tooth 13 : 1 unit Brushing tooth 12 : 1 unit Brushing tooth 11 : 1 unit Brushing tooth 21 : 1 unit Cross to bottom of mouth : 1 unit Brushing tooth 31 : 1 unit ------------------------------ Total: 7 units ``` Note his is not the only route we could have took, but there are no shorter routes. So your challenge is: * You will write a full program or function which accepts two arguments that are teeth numbers, and outputs (or returns) the shortest time to brush from one to the other. * You make take input as numbers or strings, and output how ever you wish ([within acceptable methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)). * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. * This question is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest bytecount wins. * Here are some testcases (*Thanks Jonathan Allan*): ``` 14, 21 => 5 14, 44 => 3 14, 14 => 1 33, 37 => 5 ``` Good luck! [Answer] ## JavaScript (ES6), 65 bytes ``` f=([s,t],[u,v])=>s<3^u<3?f(s+t,5-u+v)+2:s-u?t-+-v:t<v?++v-t:++t-v for(i=1;i<5;i++)for(j=1;j<9;j++){let o=document.createElement("option");o.text=""+i+j;s.add(o);t.add(o.cloneNode(true));} ``` ``` <div onchange=o.textContent=f(s.value,t.value)><select id=s></select><select id=t></select><pre id=o>1 ``` Takes input as strings. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` d30%20ị2¦⁵R;C$¤)ạ/Ḅ‘ ``` A monadic link accepting a list of two integers (e.g. `[14,31]` for the from 14 to 31 example) which yields the brushing-time. **[Try it online!](https://tio.run/##AS8A0P9qZWxsef//ZDMwJTIw4buLMsKm4oG1UjtDJMKkKeG6oS/huITigJj///8xNCwzMQ "Jelly – Try It Online")** --- [Previous 24 byter](https://tio.run/##y0rNyan8/98iyNpZxVn7UeOWUB3tk9OBNNfDHa0WhxYdnZz5aOO6h7sW6j/c0fKoYcb///@jDXVMYnWijXUMYwE "Jelly – Try It Online") built the mouth and used base 8, input was a list of lists of digits: ``` 8R;C$C+⁴U,+ɗ⁴ ḅ8¢œiⱮạ/Ḅ‘ ``` [Answer] # [Python 2](https://docs.python.org/2/), 91 bytes ``` def f(a,b):A,B=a/10,b/10;return[abs(a-b)%10+1+2*(A!=B),a%10+b%10+2-(A+B)%2*2][A!=B!=A+B!=5] ``` [Try it online!](https://tio.run/##Nc7BDoIwDAbgszxFdyBsUKIbIAlmGngNssMWIXIBMvHg0@MGcmjTb3/TbP4ur2kU6/rseuipRsOqGhupz/yCxrWb7ZaPHVtt3lSnhoX8kvBExLQmsmGovY1vIqV10rBQxEK1PiTSmchCrf1kwV1GC8MILbQ8R8g4Qqlwh3AoDuQ@PbCVR5a51/JYc0N2dUmhQFXBabbDuMD2e4zkPcL@Pz9IFNMdRFoWrD8 "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 67 bytes ``` ([a,b],[x,y])=>(u=(a==x)+3*!(a+x-5))?Math.abs(b-y)+u:2*!(a-x&1)+b+y ``` Expects inputs as two 2-element arrays of digits. `12` -> `[1, 2]` I hope this is acceptable. [Try it online!](https://tio.run/##XczRCoIwFAbg@55i3eROOxvMKUIwe4KeQHYxTawQDZ0xn96SUKyrw3f@n/9hX7YvuvvT8aa9llOlJ5pZzA1mHkcDOqWDplZrD0wd99Qyz2OA88W6m7B5T3M@AhtO4Zxxf5DAcjZOjmhChRC2q3ogOiVF2/RtXYq6rej8RBLwNEBSrS3YOZpJjAySLERpto4@Z2u5WKGarTBZnHytfvrqb2/tr/uxgekN "JavaScript (Node.js) – Try It Online") Looks like a near duplicate to [@Chas Brown's Python answer](https://codegolf.stackexchange.com/a/169106/81410), so I can remove it if necessary (unsure of the conventions here). # Explanation ``` var g = ([a,b], [x,y]) => (u = (a == x) // if same quadrant of mouth + 3 * !(a + x - 5)) // or strictly traversing vertically (e.g. 1 to 4, or 2 to 3) ? Math.abs(b - y) + u // absolute difference plus additional units of time : 2 * !(a - x & 1) // = 2 if traversing diagonally + b + y ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~80~~ 78 bytes Probably some golfing opportunities here still ``` lambda s,e,l=(range(11)+range(0,-9,-1))*2:abs(l[s%30]-l[e%30]+s/30*2-e/30*2)+1 ``` An unnamed function accepting two integers, `s` and `e`, which returns the brushing-time. **[Try it online!](https://tio.run/##LcxBDoIwEIXhvaeYjaEDU6WUxEiCF0EXJRYlKYVQNoZw9tqKs5jvrf7ps7xHW/iuvnujhvapwJEmU7NZ2ZdmQmC2r5z4lbhATItKtY6Zxh1l/uCm0dHMnWWeFlz/wEz4bpxDCzT0FhgTJUmBFC3@luWuiEpJ8oJYHSDcNPd2gWTdCNYN@C385BR6g1pYTBJ0QY3ovw "Python 2 – Try It Online")** [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~134~~ ~~128~~ 126 bytes ``` import StdEnv @n=hd[i\\i<-[0..]&k<-[18,17..11]++[21..28]++[48,47..41]++[31..38]|n==k]rem 16 $a b=abs(@a- @b)+a/30bitxor b/30+2 ``` [Try it online!](https://tio.run/##JY6xDoIwFEV3vuINxGiASqFRBpsw6GDCxggMr4DaQIsBNJr47daq27lnObfuW9RGDc2tb0Gh1Eaq6zDOkM/NQd@dVPNLU8iylLugCAmpFp0Fmvh0SwillecVESUkSr7EEp9ZzX46tjpOqpfmvKvGVgHdOC6C4CimZYoBpGLl4ToOhZwfwwjCoheZfEZb5@ACZRBT865PPZ4nExwzs39qVLL@D3swk@ID "Clean – Try It Online") Defines the function `$ :: Int Int -> Int`, which just finds the distance between the two teeth as Cartesian coordinates. Pretty boring solution really. ]
[Question] [ [Inspiration](https://szkopul.edu.pl/problemset/problem/t5FLaUejqAvkMfX7RnLzfEI_/site). Consider a list `l`, consisting of numbers. Define a block operation at index `i` on the list `l` to be the act of moving 3 consecutive elements starting from `i` in `l` to the end. Example: ``` l, i (1-indexing) -> l (after applying block operation at index i) [1,2,3,4,5], 1 -> [4,5,1,2,3] [1,2,3,4,5,6,7], 3 -> [1,2,6,7,3,4,5] ``` Given a list consisting of only 0 and 1, your challenge is to partition it so that zeros are at the front, and ones are at the back, using only block operations. Output should be the indices in the order they are applied on the list. Because this is impossible for the list `[1,0,1,0]`, the list length is guaranteed to be at least 5. # Test cases (1-indexing) (there are other valid outputs) ``` [1,1,1,0,0] -> [1] [0,1,0,1,0] -> [1,2,1,1] [0,0,0,1,1,1,0,0,0] -> [4] ``` Use [this script](https://tio.run/##y/r/vygxLyU/N744NTXFVs/U3MLA0NTIxIQrLz41JzUXKGJgwMVlqWhlbK6gYaAQD4KaIL6hApJGrgpbPQUlKwV7BYg2ZSOu1OSMfIUKhaKCnGQFdQV1a3Udda7UiswSBXX1//8B) to generate more test cases. (only input. The `rplc ' ';','` part is used to **r**e**pl**a**c**e spaces with commas in the output) # Winning criteria [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") is the main winning criteria, and [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") is the tie-breaker. In particular: * The solution with the shortest output length (least number of block operations) with the test case (`n_elem` = 500, `random_seed` = {secret value}) wins. You should be able to run your solution to completion with the test case (`n_elem` = 500, `random_seed` = 123456). * In case of ties, the solution that can handles the largest power-of-2 value of `n_elem` with `random_seed` = {secret value} within 10 seconds (for me) wins. * In case of ties, the solution that takes less time on that test case wins. [Answer] # [Python 3](https://docs.python.org/3/), (0.397 n + 3.58) steps 1000-point polynomial regression by [`numpy.polyfit`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html). --- * Number of steps for version 1: 0.0546 n² + 2.80 n - 221 * Number of steps for version 2: 0.0235 n² + 0.965 n - 74 * Number of steps for version 3: 0.00965 n² + 2.35 n - 111 * Number of steps for version 4: 1.08 n - 36.3 * Number of steps for version 5: 0.397 n + 3.58 --- * Secret test case score for version 1: 14468 * Secret test case score for version 2: 5349 * Secret test case score for version 3: 4143 * Secret test case score for version 4: 450 * Secret test case score for version 5: 205 --- ``` def partite(L): endgame5 = [9,9,1,9,0,0,1,9, 0,1,0,1,0,1,1,9, 0,0,1,0,0,0,1,0, 0,0,0,1,0,0,0,9] endgame6 = [9,9,2,9,1,1,2,9,0,2,0,0,1,2,2,9, 0,1,2,1,0,1,2,1,0,1,0,2,1,1,0,9, 0,0,1,0,1,0,1,1,0,0,0,0,1,1,1,1, 0,0,2,2,0,0,2,2,0,0,0,0,0,0,0,9] endgame = [9,9,3,9,2,2,3,9,1,0,3,0,2,0,3,9,0,1,3,3,2,2,3,0,1,0,1,0,2,1,0,9, 0,0,2,1,0,0,2,2,1,0,1,2,0,0,0,2,0,1,3,3,3,3,3,0,1,1,1,1,1,3,0,9, 0,0,0,0,1,0,1,1,1,0,3,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,0,2,0,1,0, 0,0,2,0,0,0,2,0,0,0,2,0,0,0,2,0,0,0,3,0,3,0,3,0,3,0,2,3,3,0,0,9] offset = 1 steps = [] def update(L,steps,ind): steps.append(offset + ind) if 0 <= ind and ind+3 < len(L): return (steps,L[:ind]+L[ind+3:]+L[ind:ind+3]) else: print(offset,ind,L) raise if len(L) == 5: while endgame5[L[0]*16+L[1]*8+L[2]*4+L[3]*2+L[4]] != 9: steps, L = update(L,steps,endgame5[L[0]*16+L[1]*8+L[2]*4+L[3]*2+L[4]]) return steps if len(L) == 6: while endgame6[L[0]*32+L[1]*16+L[2]*8+L[3]*4+L[4]*2+L[5]] != 9: steps, L = update(L,steps,endgame6[L[0]*32+L[1]*16+L[2]*8+L[3]*4+L[4]*2+L[5]]) return steps if 1 not in L: return [] while len(L) > 7 and 0 in L: wf_check = len(L) while L[0] != 0: pos = [-1] wf_check2 = -1 while True: i = pos[-1]+1 while i < len(L): if L[i] == 0: pos.append(i) i += 1 else: i += 3 assert len(pos) > wf_check2 wf_check2 = len(pos) space = (pos[-1]-len(L)+1)%3 ind = -1 tail = pos.pop() i = len(L)-1 while i >= 0: if tail == i: while tail == i: i -= 1 tail = pos.pop() if pos else -1 i -= 2 elif i < len(L)-3 and L[i+space] == 0: ind = i break else: i -= 1 if ind == -1: break steps, L = update(L, steps, ind) pos = pos or [-1] if L[0] == 0: break pos = [-1] while L[0] != 0: pos = [-1] found = False for i in range(1,len(L)): if L[i] == 0: if i%3 == (pos[-1]+1)%3: pos.append(i) else: found = found or i if found > len(L)-4: found = False if not found: break triple = [] for i in range(1,len(L)-1): if L[i-1] == 1 and L[i] == 1 and L[i+1] == 1: triple.append(i) if len(triple) > 3: break space = (pos[-1]-len(L)+1)%3 if space == 0: if found >= 2 and found-2 not in pos and found-1 not in pos: # ... _ 1 _ [0] 0 ... if found-2 in triple: triple.remove(found-2) if found-3 in triple: triple.remove(found-3) if L[-1] == 1: steps, L = update(L, steps, found-2) steps, L = update(L, steps, len(L)-4) steps, L = update(L, steps, len(L)-4) elif triple: steps, L = update(L, steps, found-2) if found < triple[0]: triple[0] -= 3 steps, L = update(L, steps, triple[0]-1) steps, L = update(L, steps, len(L)-4) else: break assert L[-3] == 0 elif found >= 1 and found-1 not in pos and found+1 not in pos: # ... _ 1 [0] _ 0 ... if found-2 in triple: triple.remove(found-2) if L[-2] == 1 and L[-1] == 1: steps, L = update(L, steps, found-1) steps, L = update(L, steps, len(L)-5) steps, L = update(L, steps, len(L)-5) elif triple: steps, L = update(L, steps, found-1) if found < triple[0]: triple[0] -= 3 steps, L = update(L, steps, triple[0]-1) steps, L = update(L, steps, len(L)-5) elif L[-1] == 1: steps, L = update(L, steps, found-1) steps, L = update(L, steps, len(L)-4) steps, L = update(L, steps, len(L)-4) steps, L = update(L, steps, len(L)-4) else: break assert L[-3] == 0 else: break elif space == 1: # ... 1 1 [0] 0 ... if found >= 2 and found-2 not in pos and found-1 not in pos: if found-2 in triple: triple.remove(found-2) if found-3 in triple: triple.remove(found-3) if triple: steps, L = update(L, steps, found-2) if found < triple[0]: triple[0] -= 3 steps, L = update(L, steps, triple[0]-1) steps, L = update(L, steps, len(L)-5) elif L[-2] == 1 and L[-1] == 1: steps, L = update(L, steps, found-2) steps, L = update(L, steps, len(L)-4) steps, L = update(L, steps, len(L)-5) else: break assert L[-2] == 0 else: break else: if found+1 not in pos and found+2 not in pos: # ... 0 [0] _ 1 _ ... if found+2 in triple: triple.remove(found+2) if found+3 in triple: triple.remove(found+3) if L[-2] == 1 and L[-1] == 1: steps, L = update(L, steps, found) steps, L = update(L, steps, len(L)-5) elif L[-1] == 1: steps, L = update(L, steps, found) steps, L = update(L, steps, len(L)-4) steps, L = update(L, steps, len(L)-4) elif triple: steps, L = update(L, steps, triple[0]-1) if triple[0] < found: found -= 3 steps, L = update(L, steps, found) steps, L = update(L, steps, len(L)-5) else: break assert L[-1] == 0 elif found >= 1 and found-1 not in pos and found+1 not in pos: # ... 0 _ [0] 1 _ ... if found+2 in triple: triple.remove(found+2) if L[-1] == 1: steps, L = update(L, steps, found-1) steps, L = update(L, steps, len(L)-4) elif triple: steps, L = update(L, steps, triple[0]-1) if triple[0] < found: found -= 3 steps, L = update(L, steps, found-1) steps, L = update(L, steps, len(L)-4) else: break assert L[-1] == 0 else: break if L[0] == 0: break if 0 in L[::3]: assert L[::3].index(0) < wf_check wf_check = L[::3].index(0) steps, L = update(L, steps, 0) assert L[0] == 0 offset += L.index(1) del L[:L.index(1)] continue if 0 in L: offset -= 7-len(L) L = [0]*(7-len(L))+L assert(len(L) == 7) while endgame[L[0]*64+L[1]*32+L[2]*16+L[3]*8+L[4]*4+L[5]*2+L[6]] != 9: steps, L = update(L,steps,endgame[L[0]*64+L[1]*32+L[2]*16+L[3]*8+L[4]*4+L[5]*2+L[6]]) return steps ``` [Try it online!](https://tio.run/##1Vtdbxu7EX2WfsVeF0YkSzI4u7ZTq3GA4gJ90kuBPiQQBEOxVs7iypK6WvU6vz7lkFyKnEN/5qNpjHgtcjg7Qw5nzhnD2y/N5826@FrdbTd1k9Xz9WJz13Wf1vu77ZduU@6a3dV0qobuazb0P5P/mYJx8uMUyFMgT4E8eXkK9FOgnwL9FOinQD8F@inQT14/BfZTYD8F9lNgPwX2U2A/BfZTYD8F9lNgPwX2U2A/BfZTYD8F9lNgv9//6ARUNEfx6cTnE51QfHbi9OLzi05QRXMUn258vtEJx2cvTj8@/ygCVDRHcXTE8RFFSBw7Inri@IkiSEVzFEdXHF9RhMWxJ6Ivjr8oAlU0R3F0xvEZRWgcuyJ64/iNIlhFcxRHdxzfUYTHsS@iP47/6AaoaI7i2xHfj@iGxHdH3J74/kQ3SEVzFN@u@H5FNyy@e@L2yfsnbqAS8yRvqLyj4pbKOwy3WN5jcZNFHha3WeYBmQkwF0A2kPlAZAQl5klmDJkzRNaQOQWyiswrIrOIuiKyi8xLMjNhboLsJPOTyFBKzJPMYDKHiSwmcxxkOZnnRKYTdVJkO5knZabEXAnZUuZLkTGVmCeZUWVOFVlV5lzIujLviswr6r7IvjJvy8yNuRuyt8zfIoMrMU8yw8scL7K8rAFQBWQdEJVA4BhRDWQdkZUEawlUE1lPREVRYp5kxZE1R1QdWZOgKsm6JCqTwGWiOsm6Jisb1jaobrK@iQqnxDzJCihroKiCskZClZR1UlRKgTNFtZR1VlZarLVQbWW9FRVXiXmSFVnWZFGVZc2Gqi3rtqjcAjeL6i3rvqz8WPuh@mP9BwSgQIYQJSBOAKSAWCKBJhBPAKIAXgCoAnEJIpMUNkmgE8QngFAUyBCiGMQxgGQQ6yTQDuIdQDzAfwD1IG5C5JTCTgn0hPgJEJQCGUKUhTgLkBZisQQaQzwGiAx4HqAyxHWI7FLYLoHuEN8BwlMgQ4gCEQcCEkSsmECLiBcBMQKfBdSIuBORZwp7JtAn4k9AoApkCFEq4lRAqohlE2gW8SwgWuDtgGoRFyMyTmHjBDpGfAwIWYEMIYpGHA1IGrF2Am0j3gbEDf0JQN2I2xG5p7B7Ar0jfgcEr0CGEOUjzgekj1wgwQaQDwAjgD4MsALkFcgsUtwiwS6QXwDDUCBDyEKQhwATQa6SYCvIV4CxQL8JWAvyHmQ@Ke6TYD/If4ABKZAhZEnIk4ApIZdKsCnkU8CooK8GrAp5GTKzFDdLsDPkZ8DQFMgQsjjkccDkkOsl2B7yPWB80D8E1oe8EZljijsm2CPyR2CQCmQIWSbyTGCayEUTbBT5KDBS6JMCK0Vei8w2xW0T7Bb5LTBcBTKELBh5MDBh5MoJtox8GRgz9IOBNSPvRuad4t4J9o38Gxi4AhlClo48HZg6cvkEm0c@D4we@t7A6rEvgJ2BVG8g0R3A/gB0CBTIEHYRsI8AnQTsNSS6DdhvgI4D9Peh64B9C@xcpHoXie4F9i@gg6FAhrDLgX0O6HRgLyTRDcF@CHRE4PcY0BXBvgp2VlK9lUR3Bfsr0GFRIEPYhcE@DHRisFeT6NZgvwY6NvD7GujaYN8HOz@p3k@i@6NlZl8X5TLbzuumasrepD/udsr14nZ@V55nV9n0cnipxS7dNlwOu51OzAjcUEy13NBh8HLm1V60anOjmsxT6e9WPjef3Wty95rcvzJ3zkWvFRXGe@dEcqe8fR6@ArNaqwpjWW6erLFwthXGStLPws2ryKjApNyZkgf2KzfSqrBfYSkoQhWirxC9TfBK73ceb374ztSzEP9zZ5Hdlc1yuSsbvSnU7eyacrvj/dHjHCz77WLOsTI0E8NqveCosWKn8@1W72jPrR9kPKsnq2WmsndX/DGb6//6OSiyd9mqXNug63TqstnX66xntU6mYy0zG0ymRnTsfhqbTzNWWa52pVm4rat1497I1gwnfaNvXu3KLr/ZviS7usrOecGfn6tVmbVRPp1M1eyELrR@mp38VT/y2cmZfhSzk1w/zmaz7Ler7NK8ytqWTfRuiF14gTq2zjlr1gobL8DGC6u0yK1Sozy3ygur/MwqP3@RrS9Rm7SZsvWm0UeZTcaHaY4Sa71z6X321hy58pJ/Lq9vPpc3f2jLrIx3mA1iD5Q92I0JuxHN@FO7KtdjIzIjZs2/6r2Ng06lZ/QaXjAwAk6iigPNRKOOphnvtnJD/LI2eKu@G6uygbkB/M@HWztemA/z3a6sG6Nea2BvvZ3WgsDqVshM7LbzG846PWfxyFo4oP6x1cxXpfW008yrlfXudLvZ9vreX7tqFLv7/uCXdtWu1XevNd@KwbDWN/Lu4iszrYpPhDeiNcutydst0iKHzR4V5tz1Tg@Ms/F@W/cq9@lTXc7/SG20t4hV8xLeEjd9WJSK9cwNugzUhhN/39Q@qkwoqNA0r1WEXyJAhUhnudkbr/4xX3HqMSO13hEd@PV8fVv2aGi35rFAZEePCx7q@WDWMeFPKRWo4Z55K@yTDWg30I68b8/nzC1Bs7UsX20zAZvd1NV2VbqC8LCPI4q91I6wU9QGRfxp4GZbL@xLpKMuUdpJvmx@W4JYePJiLTMnE10Ttzk6mo1N5uMob1Mcn/RhmILh1oK/ZKenp9m1duk64yhR/Plwpq0@vcia78/LuVqXd5v/lD0n15cri2euLIKVk@lIbOujN0W8@lHZNoReJWwShfDlJYb503rntOj99oo6foiTR/Ec/X6FjtnX@RNcvyCVtdVBn0NhL3mQKH280QOBdRgePB5v7Or194s3bW0eXc5XBNGL9vH8VcKvCyL61YIo9ufHb/bZz7jeL70OB/mDuNkPn6jb/bBRTy7qg5j/Dhn8f5Sl//8TIcTwN@ePH1eEzl8QpflzotSPtocxeCCJ5w8mceVSOEMHTOKDZ4bjAMJx8MxwHBTfN/3/3Pz36@GV1DXyGvio30XQ2kPw517Tb9nkJ4OefhBSUQ4Xf8cg/4nV8pcMgR8HV@nJzPcIcTbNPm72TMfjwtUjr5qHTjUnL@97qq93oW2QRN0S7YWQ7D7ho5HwL1He/LYRqRU6XWbPFuWK33AYYyp7s1k31Xpvm4aHdpVToU/m7cj3q9gI7p712rH@YOIt6B26eW/7sptnu24XZ7brZrpvueu@Fbb7dma7b@e2@3bxoqbeK7RrC8PWnvmFgDmFVjfzeEPyea94W8zo@LDhbWtXz7rmbnmvL/S7Q3tvcmUbuuU99zNMK5dFxv7nEY3dmD6J9hx5A3ebuikXrKXLNkxMmuA/3Ru7zvRV@8uL6X3GEsbCCXsVO9HtfrA9i4/2IdsWSg31f@Jv7PDNvq5dj4MlryNJ09n4EHUnJldT@1eGp/zgjrTW18/E2soE2hN2m3e3ynkLrQNmJnapc1fO19rKN8e7N9lxtlxt5k3vzfFpccsfzd85nrJIjzWygl2zyJ6Q1yJe3LbWj6r1dm96nLfN53F2vPgbi34q62yztLGQ7XflYpz1nDnHOkR3C/ND/@jY3YYhT2rDF6z442l537B75k1d@572efT31cqecbblUFj8dtTvrirW3Ox1@uw9YL7d7TXvo3Vlu1l9WVZN78Pwoz6Lfvff@/nim5TkWsnN/lN1801air73dFKty3md1eVtXe521Watt3en1w304@hY@@wl/6ltr@eNfrUUPjnJjbxfxm76db8bc3FN4dbAauNf/@t/AQ "Python 3 – Try It Online") [Answer] # Python 3, ~179 steps for n=500 (on average) A heuristic greedy approach. Kinda slow but still works. Uses an optimal solver for small sizes. ``` def incomplete_groups(l): r = 0 ones = 0 for x in l: if x == "1": ones += 1 else: if ones % 3: r += 1 ones = 0 # Ones at the end don't count as an incomplete group. return r def move(l, i): return l[:i] + l[i+3:] + l[i:i+3] def best_pos(l, hist): r = [] cleanup = incomplete_groups(l) == 0 candidates = [] for i in range(len(l) - 3): block = l[i:i+3] if block == "111" and cleanup: return i elif block == "111": continue new = move(l, i) bad_start = i < 3 and "10" in l[:3] candidates.append((new not in hist, -incomplete_groups(new), bad_start, block != "000", i)) candidates.sort(reverse=True) return candidates[0][-1] def done(l): return list(l) == sorted(l) class IDAStar: def __init__(self, h, neighbours): """ Iterative-deepening A* search. h(n) is the heuristic that gives the cost between node n and the goal node. It must be admissable, meaning that h(n) MUST NEVER OVERSTIMATE the true cost. Underestimating is fine. neighbours(n) is an iterable giving a pair (cost, node, descr) for each node neighbouring n IN ASCENDING ORDER OF COST. descr is not used in the computation but can be used to efficiently store information about the path edges (e.g. up/left/right/down for grids). """ self.h = h self.neighbours = neighbours self.FOUND = object() def solve(self, root, is_goal, max_cost=None): """ Returns the shortest path between the root and a given goal, as well as the total cost. If the cost exceeds a given max_cost, the function returns None. If you do not give a maximum cost the solver will never return for unsolvable instances.""" self.is_goal = is_goal self.path = [root] self.is_in_path = {root} self.path_descrs = [] self.nodes_evaluated = 0 bound = self.h(root) while True: t = self._search(0, bound) if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated if t is None: return None bound = t def _search(self, g, bound): self.nodes_evaluated += 1 node = self.path[-1] f = g + self.h(node) if f > bound: return f if self.is_goal(node): return self.FOUND m = None # Lower bound on cost. for cost, n, descr in self.neighbours(node): if n in self.is_in_path: continue self.path.append(n) self.is_in_path.add(n) self.path_descrs.append(descr) t = self._search(g + cost, bound) if t == self.FOUND: return self.FOUND if m is None or (t is not None and t < m): m = t self.path.pop() self.path_descrs.pop() self.is_in_path.remove(n) return m def h(l): """Number of groups of 1 with length <= 3 that come before a zero.""" h = 0 num_ones = 0 complete_groups = 0 incomplete_groups = 0 for x in l: if x == "1": num_ones += 1 else: while num_ones > 3: num_ones -= 3 h += 1 complete_groups += 1 if num_ones > 0: h += 1 incomplete_groups += 1 num_ones = 0 return complete_groups + incomplete_groups def neighbours(l): inc_groups = incomplete_groups(l) final = inc_groups == 0 candidates = [] for i in range(len(l) - 3): left = l[:i] block = l[i:i+3] right = l[i+3:] cand = (1, left + right + block, i) # Optimal choice. if final and (block != "111" or i >= len(l.rstrip("1"))): continue candidates.append(cand) candidates.sort(key=lambda c: c[2], reverse=True) return candidates def is_goal(l): return all(l[i] <= l[i+1] for i in range(len(l)-1)) opt_solver = IDAStar(h, neighbours) def partite(l): if isinstance(l, list): l = "".join(map(str, l)) if len(l) < 10: return [i + 1 for i in opt_solver.solve(l, is_goal)[1]] moves = [] hist = [l] while not done(l): i = best_pos(l, hist) l = move(l, i) moves.append(i+1) hist.append(l) return moves ``` ]
[Question] [ # Executive summary Given input representing two vectors and their respective "weights", produce output that also represents the weighted sum of those vectors. # Challenge The input will consist of one or more lines of the following characters: * exactly one occurrence of the digit 0, which represents the origin in a two-dimensional plane; * exactly two other digits (1-9; may or may not be the same digit), whose positions relative to the origin represent vectors, and whose values represent the weights attached to thse vectors; * some number of "background characters". The solver may choose a specific background character; for example, I will choose "." (mostly for human readability). Alternately, the background characters can be anything that look like blank space. (The solver can choose whether the input is a single multi-line string or an array of one-line strings.) For example, the input ``` ....2 .0... ...3. ``` represents a vector at coordinates (3,1) with weight 2, and a vector at coordinates (2,-1) with weight 3. The output should be almost the same as the input, with the following changes: * a "result character", chosen by the solver, to be added at the position specified by weighted sum of the input vectors (equivalently, at the position that is the appropriate linear combination of the input vectors); * as many background characters as are needed to fit the origin, the two input vectors, and the output vector in the same picture. Extra background characters can be included if desired; the only constraint is that, if the background character is a visible character, then the entire output must be rectangular in shape and every character not representing a vector must be the background character. (If blank space is used as background characters, then these constraints don't need to be enforced.) (In general, if we have one vector (v,w) with weight a and second vector (x,y) with weight b, their weighted sum is a(v,w)+b(x,y) = (av+bx,aw+by).) In the previous example, the appropriate linear combination is 2\*(3,1) + 3\*(2,-1) = (12,-1). If we use "X" as the result character, then the output could look like ``` ....2......... .0............ ...3.........X ``` or ``` ................ ...2............ 0............... ..3.........X... ................ ................ ``` Usual [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") scoring: the shortest answer, in bytes, wins. # Example input and output If blank space is used, the above input would look like ``` 2 0 3 ``` and the output would look like ``` 2 0 3 X ``` Leading/trailing whitespace characters/lines are irrelevant; if they're invisible to the reader, it's fine. (That being said, for the rest of the examples I'll go back to using "." for the background character, to make it easier to read.) If both vectors have weight 1, then the result will look like a parallelogram: the input ``` .1. ... 1.0 ``` leads to the output ``` X.1. .... .1.0 ``` Note this parallelogram can be degenerate if the input vectors are collinear: the input ``` 0.1..1 ``` leads to the output ``` 0.1..1.X ``` It is possible for the result vector to equal one of the input vectors or the origin; in this case, it simply overwrites the input character. For example, the input ``` ..2.0.1... ``` yields the output ``` ..X.0.1... ``` (where in input and/or output, the leading and trailing periods could be deleted). The input ``` .....3 ...... ...0.. ...... ...... 2..... ``` yields the output ``` .....3 ...... ...X.. ...... ...... 2..... ``` Finally, the input ``` 90 .8 ``` yields the output ``` ........90 .........8 .......... .......... .......... .......... .......... .......... X......... ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 48 bytes ``` tZyyX:UX>*Yat48-tt0>*3#fbbhb~2#fh-*s7M+'X'wZ}4$( ``` The background character is space. Input is a 2D char array with rows separated by semicolons. So the tests cases have respective inputs: ``` [' 2'; ' 0 '; ' 3 '] [' 1 '; ' '; '1 0'] ['0 1 1'] [' 2 0 1 '] [' 3'; ' '; ' 0 '; ' '; ' '; '2 '] ['90'; ' 8'] ``` The output includes a significant amount of padding whitespace. [**Try it online!**](http://matl.tryitonline.net/#code=dFp5eVg6VVg-KllhdDQ4LXR0MD4qMyNmYmJoYn4yI2ZoLSpzN00rJ1gnd1p9NCQo&input=WycgICAgMic7ICcgMCAgICc7ICcgICAzICdd) [Answer] # Python 3, ~~374~~ 355 bytes Not too refined python solution that is very generous with padding (uses maximum chessboard distance). Input is a single line where rows are separated with pipes | (although the algorithm can easily use anything not alphanumerical that isn't a newline or a EOF). Anything non alphanumeric or | works for input padding, output padding uses periods. Feedback and improvement from more seasoned python golfers is appreciated. *Edit: Some improvements thanks to @TheBikingViking. Also added even more margins since I wasn't quite generous enough with padding.* ``` s=input() l=[len(s),1+s.find('|')]['|'in s] P=sorted([int(c),i%l,i//l]for i,c in enumerate(s)if c.isalnum()) L=X=Y=0 P[0][0]=-sum(p[0]for p in P) for w,x,y in P:L=max(abs(x),abs(y),L);X+=x*w;Y+=y*w P+=[['X',P[0][1]+X,P[0][2]+Y]] P[0][0]=0 L=2*max(abs(X),abs(Y),L) S=[2*L*["."]for _ in[0]*2*L] for w,x,y in P:S[L+y][L+x]=str(w) for s in S:print(''.join(s)) ``` [Answer] # JavaScript, 534 528 502 bytes ``` n="indexOf" J="join" B=X=>X.split(O) O='\n' w=i[n](O)+1 h=B(i).length Z=(X,Y,R)=>{C[R]+=X-1;return Array(X)[J](Y)} C=[0,0,0] G=(X,E,T,U,R)=>X>0&E>=0?Z(X+E+1+T,U,R):"" o=i[n]("0") L=X=>Math.floor(X/(w-1)) l=L(o) c=o%w x=y=0 j=i for(z="1";z<="9";z++){while(p=~j[n](z)){j=j.replace(z," ") x+=~p%w-l y+=L(~p)-c}} I=B(i).map(X=>G(-x,-l,0," ",0)+X+G(x,l-w+2,0," ",2)) N=Z(I[0].length+1," ",2) A=B(G(-y,-c,0,N+O,1)+I[J](O)+G(y,c-h,1,O+N,2)) M=y+c+C[1] O="" m=B(A[M]) m[x+l+C[0]/h]="x" A[M]=m[J]("") A[J]("\n") ``` Note that the padding is optimal. This program assumes that i contains the raw string, with the lines separated by `\n` characters. The padding is done with spaces, and the result character is a lowercase `x`. This is my first attempt at code-golfing. Technical stuff: - The program's size roughly doubled (and its complexity went up dramatically) to just take into account the result character, mostly because JavaScript strings are immutable. --- Line by line explanation: ``` n="indexOf" J="join" B=X=>X.split(O) ``` I use those a lot, so storing them in strings saved me some space. You can see below that for the `split` function, I have simply created an alias; this is because I only needed one argument, the other one being constant. For `indexOf` and `join`, it would however have been longer. ``` O='\n' w=i[n](O)+1 h=B(i).length ``` Nothing complicated here, I'm reading the width and height of the initial array. Note the use of `i[n]` to access `indexOf`, while `split` is handled differently. ``` Z=(X,Y,R)=>{C[R]+=X-1;return Array(X)[J](Y)} ``` This is getting interesting. This function basically creates concatenates J-1 times the string X and returns it. This is used to generate strings of spaces for the padding. ``` C=[0,0,0] ``` This array will contain the number of lines and columns added by the padding (off by a factor h in the first case). The last cell is a junk one, and prevents me from having an additional argument in the function below. ``` G=(X,E,T,U,R)=>X>0&E>=0?Z(X+E+1+T,U,R):"" ``` This function alone handles the padding (both lines and columns); it determines, based on a coordinate of the result vector (X), and the number of lines/columns to generate (E), whether it is necessary to create one. the `X+E+1+T` is just a trick to save some space, `U` is the filling string (a space for columns, and an entire line for lines), and we'll come back to `R`. This function basically returns, in the case of a line, the padding required at the beginning or the end of said line, and, in the case of a column, it returns the padding lines required either before or after the original lines. ``` o=i[n]("0") L=X=>Math.floor(X/(w-1)) l=L(o) c=o%w ``` Here we read the position of the origin, and we retrieve its coordinates. L is a function to convert an index into a line number. ``` x=y=0 j=i for(z="1";z<="9";z++){ while(p=~j[n](z)){ j=j.replace(z," ") x+=~p%w-l y+=L(~p)-c } } ``` I added some whitespace to make this easier to read. What happens here is that for each possible number, we keep looking for it in the original string. The `~` trick is relatively common in Javascript; it is the bitwise NOT operator, but all that matters here is that `~-1==0`, which allows me to test for the end of the loop. I then erase the character in the string (which is why I made a copy), this allowing me to continue the search as long as needed. I then add the coordinates of the vector to `(x, y)`, using a simple substraction. ``` I=B(i).map(X=>G(-x,-l,0," ",0)+X+G(x,l-w+2,0," ",2)) ``` I here split the original string into lines, and for each line, I call `G` which will generate the padding before and after the lines. The `l-w+2` and so on come from a simple index calculation which allows me to test whether I need to add padding or not. For example, if `x>0` and `x+l-w+1>0`, then `(x+l-w+1)+1` spaces must be added after the line. The `+x` is being removed due to it being the first parameter, and the `X+E+1+T` used in the definition of `G`. A similar thing is done for the first characters, and then for the columns. There is a lot of factorization here allowing me to use only one function. Note the last parameter; in the first case, I want to write to `C[0]` to be able to know later how many columns I added at the beginning of each line; this allows me to retrieve the final position of the result character. I do however not care about the columns added after the original line, which is why the second call to `G` writes to the junk cell `C[2]` which is unused. ``` N=Z(I[0].length+1," ",2) ``` Here I simply read the new length of the lines, and create a line of spaces from it. This will be used to create the vertical padding. ``` A=B(G(-y,-c,0,N+O,1)+I[J](O)+G(y,c-h,1,O+N,2)) ``` This is exactly the same as two lines above. The only difference is writing to `C[1]` this time, and using the separators `N+O` and `O+N`. Remember that `O` is a newline, and `N` is a line of spaces. I then apply `B` on the result to split it again (I need to retrieve the line containing the result character to edit it). ``` M=y+c+C[1] ``` This is the vertical index of the resulting character. ``` O="" m=B(A[M]) m[x+l+C[0]/h]="x" ``` Here I am forced to modify `O` to be able to split the appropriate line into an array of characters. This is because JavaScript strings are immutable; the only way to edit a string is to convert it into an array (which is what I'm doing here), edit at the right position, and join the string again. Also note the `h` factor, which is because the `G` function was called once per initial line. ``` A[M]=m[J]("") A[J]("\n") ``` I finally replace the new string in the array, and join it again into a string. Woohoo! ]
[Question] [ ## Context [Straw Poll](http://strawpoll.me/) is a website that is meant for the creation of simple/informal polls. Provided with a list of options, the user can select their choice(s), and the votes are tallied up. There's two very important features of a Straw Poll: * It is possible to view the current results before voting * It is often possible to select multiple options, which is treated the same way as if you voted multiple times, one for each option. The one thing that's more fun than making Straw Polls is messing with the results. There's two main types of disruption: * Simple disruption, in which you vote for all the options * Advanced disruption, in which you strategically pick which options to vote for in order to maximize the effect. In this challenge, you will write a program for *advanced* disruption. ## The Math To simply things mathematically, we can say that *the higher the entropy of the votes, the more disrupted a poll is.* This means that a poll where a single option has all the votes isn't disrupted at all, while a poll where every option has an equal number of votes is maximally disrupted (this being the ultimate goal). The entropy of a list of numbers \$[x\_1, x\_2, \dots x\_n]\$ is given by the following equation from Wikipedia. \$P(x\_i)\$ is the probability of \$x\_i\$, which is \$\frac {x\_i} {\sum^n\_{i=1} x\_i}\$. If an option has received zero votes so far, it is simply not included in the summation (to avoid \$\log(0)\$). For our purposes, the logarithm can be in any base of your choice. $$H(X) = \sum^n\_{i=1} P(x\_i) I(x\_i) = -\sum^n\_{i=1} P(x\_i) \log\_b P(x\_i)$$ As an example, the entropy of \$[3,2,1,1]\$ is approximately \$1.277\$, using base \$e\$. The next step is to determine what voting pattern leads to the greatest increase in entropy. I can vote for any subset of options, so for example my vote could be \$[1,0,1,0]\$. If these were my votes, then the final tally is \$[4,2,2,1]\$. Recalculating the entropy gives \$1.273\$, giving a *decrease* in entropy, which means this is a terrible attempt at disruption. Here are some other options: ``` don't vote [3,2,1,1] -> 1.277 vote for everything [4,3,2,2] -> 1.342 vote for the 1s [3,2,2,2] -> 1.369 vote for the 2 and 1s [3,3,2,2] -> 1.366 ``` From this, we can conclude that the **optimal voting pattern** is \$[0,0,1,1]\$ since it gives the greatest increase in entropy. ## Input Input is a non-empty list of non-increasing, non-negative integers. Examples include \$[3,3,2,1,0,0]\$, \$[123,23,1]\$, or even \$[4]\$. Any reasonable format is allowable. ## Output Output is a list (the same length as input) of truthy and falsey values, where the truths represent the options for which I should vote if I desired to cause maximal disruption. If more than one voting pattern gives the same entropy, either one can be output. ## Winning Criterion This is code-golf, fewer bytes are better. ## Test Cases ``` [3,2,1,1] -> [0,0,1,1] (from 1.227 to 1.369) [3,3,2,1,0,0] -> [0,0,0,1,1,1] (from 1.311 to 1.705) [123,23,1] -> [0,1,1] (from 0.473 to 0.510) [4] -> [0] OR [1] (from 0 to 0) [7,7,6,6,5] -> [0,0,1,1,1] (from 1.602 to 1.608) [100,50,1,1] -> [0,1,1,1] (from 0.707 to 0.761) ``` [Answer] # Mathematica, ~~19~~ 44 bytes ...(loud complaining) ``` (x=Median@#[[;;Mod[Length@#,2]-3]];#≤x&/@#)& ``` Test: ``` {Test, data, goes, here}; (x=Median@#[[;;Mod[Length@#,2]-3]];#≤x&/@#)& %%+Boole/@% ``` [Answer] # Pyth - 25 bytes ``` hosm*FlBcdsGfT=G+VQN^U2lQ ``` [Test Suite](http://pyth.herokuapp.com/?code=hosm%2aFlBcdsGfT%3DG%2BVQN%5EU2lQ&test_suite=1&test_suite_input=%5B3%2C2%2C1%2C1%5D%0A%5B123%2C23%2C1%5D%0A%5B4%5D%0A%5B7%2C7%2C6%2C6%2C5%5D%0A%5B3%2C3%2C2%2C1%2C0%2C0%5D&debug=0). [Answer] # [MATL](https://esolangs.org/wiki/MATL), 24 bytes ``` FTinZ^tG+!ts/tYl*s4#X<Y) ``` This works with [version 13.0.0](https://github.com/lmendo/MATL/releases/tag/13.0.0) of the language/compiler, which is earlier than the challenge. [**Try it online!**](http://matl.tryitonline.net/#code=RlRpblpedEcrIXRzL3RZbCpzNCNYPFkp&input=WzcsNyw2LDYsNV0) ### Explanation ``` FT % array [0 1] in % take input and push its length Z^ % Cartesian power. This gives all possible vote patterns, each on a row t % duplicate (will be indexed into at the end to produce the result) G % push input again + % element-wise addition with broadcast ! % transpose ts/ % duplicate. Divide each column by its sum tYl % duplicatte. Take natural logarithm * % element-wise multiplication s % sum of each column. Gives minus entropy produce by each vote pattern 4#X< % arg max Y) % index into original array of voting patterns. Implicitly display ``` ### Example Here's an example of how it works. For input `[3 2 2]`, the array of possible voting patterns (produced by `Z^`) is ``` [ 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 ] ``` where each row is a pattern. This is added to the original `[3 2 0]` with broadcast (`G+`). That means `[3 2 0]` is replicated `8` times vertically and then added element-wise to give ``` [ 3 2 2 3 2 3 3 3 2 3 3 3 4 2 2 4 2 3 4 3 2 4 3 3 ] ``` This is transposed and each column is divided by each sum (`!ts/`): ``` [ 0.4286 0.3750 0.3750 0.3333 0.5000 0.4444 0.4444 0.4000 0.2857 0.2500 0.3750 0.3333 0.2500 0.2222 0.3333 0.3000 0.2857 0.3750 0.2500 0.3333 0.2500 0.3333 0.2222 0.3000 ] ``` Multiplying by its logarithm and summing each column (`tYl*s`) gives minus the entropy: ``` [ -1.0790 -1.0822 -1.0822 -1.0986 -1.0397 -1.0609 -1.0609 -1.0889 ] ``` The minus entropy is minimized (`4#X<`) by the `4`th vote pattern, which corresponds (`Y)`) to the [final result `[0 1 1]`](http://matl.tryitonline.net/#code=RlRpblpedEcrIXRzL3RZbCpzNCNYPFkp&input=WzMgMiAyXQ). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` LØ.ṗ+ḟ0÷SḋÆl$ƊɗÐṂ ``` [Try it online!](https://tio.run/##y0rNyan8/9/n8Ay9hzunaz/cMd/g8Pbghzu6D7flqBzrOjn98ISHO5v@H25/uGPR0UkPd87QjPz/P9pYx0jHUMcwVgfIgrANdAyAPEMjIM8YLGECxOY65jpmQGgKkjIw0DE1AOsCAA "Jelly – Try It Online") ## How it works ``` LØ.ṗ+ḟ0÷SḋÆl$ƊɗÐṂ - Main link. Takes a list A on the left L - Length of A Ø.ṗ - Cartesian power of [0, 1] to the length of A ɗÐṂ - Output the bitlist B with the minimum value f(B, A): + - Add the elements of B to A ḟ0 - Remove any zeros Ɗ - Last 3 links as a monad g(A+B \ {0}): ÷S - Divide each by the sum $ - Last 2 links as a monad h([A+B \ {0}] ÷ sum): Æl - Natural log of each ḋ - Dot product ``` ]
[Question] [ ## Task Read the contents of a table given a set of coordinates. ## Table formatting Tables will be in this basic format: ``` |[name]|[name]| --------------------- [name]| [val]|[val] | [name]| [val]|[val] | ``` Column names are always unique *within columns*. Row names are also unique *within rows*. This includes names that are the same except whitespace. Values, col names and row names will never have `|-` inside them. Names and values will never have spaces inside them, but may have leading or trailing space. Col width is adjustable based on the header/content. Column width is always consistent from top to bottom. ### Input A table and a space separated list of `[name]`s. Example ``` [table] row col ``` If you are writing a function, these can be separate strings, otherwise the `row col` will always be the very last line in the input. `row col` has some flexibility for the format and may be represented many ways. (e.g. `(row, col)`, `r, c`, ...). The only hard requirement is that it be one line, and that it must appear in the order `col row`. ### Output The contents of a cell specified by the input *with no leading or trailing space from the cell*. ## Examples ``` In: |a|z |_*| ------------ atb|1|85|22| b |5|6 |e$| /+*|8|we|th| atb a Out: 1 In: | x| b | ---------- ab|l |mmm| b |le| l | b b Out: l In: |a|z |_*| ab | ------------------- atb|1|85|22| 5 | b |5|6 |e$| 8 | /+-|8|we|th| 126 | atb ab Out: 5 ``` [Answer] # JavaScript (ES6), 108 ``` t=>(S=s=>s.split(/ *\| */),t=t.split` `,[y,x]=t.pop().split` `,S(t.find(r=>S(r)[0]==y))[S(t[0]).indexOf(x)]) ``` **TEST** in Firefox ``` f=t=>( S=s=>s.split(/ *\| */), t=t.split`\n`, [y,x]=t.pop().split` `, S(t.find(r=>S(r)[0]==y))[S(t[0]).indexOf(x)] ) function test(){ r=f(T.value); O.textContent=r } test() ``` ``` #T { width: 50%; height: 9em} ``` ``` Input<br><textarea id=T> |a|z |_*| ab | ------------------- atb|1|85|22| 5 | b |5|6 |e$| 8 | /+-|8|we|th| 126 | atb ab</textarea><br> <button onclick="test()">Find</button> <span id=O></span> ``` [Answer] ## Haskell, ~~117~~ ~~116~~ 111 bytes ``` import Data.Lists s=splitOn"|".filter(>' ') (t#b)a|l<-lines t=[c|r<-l,(d,c)<-zip(s$l!!0)$s r,d==a,s r!!0==b]!!0 ``` Usage example: ``` *Main> (" | x| b |\n----------\nab|l |mmm|\nb |le| l |\nb b" # "b") "b" "l" ``` How it works: ``` s=splitOn"|".filter(>' ') -- helper function to remove spaces and split a -- line at bars into words l<-lines t -- split table at \n into lines and bind to l [c|r<-l, ] -- take c for every line r in l, where (d,c)<-zip(s$l!!0)$s r -- a pair (d,c) is made by zipping the (split) -- header of the table with the (split) line r ,d==a -- and d (=header element) equals parameter a ,s r!!0==b -- and the first word in r equals parameter b !!0 -- pick the first (and only) element ``` [Answer] # Retina, 90 bytes ``` s`^(?=.*\n(.*) (.*))((?<a>\|)|.)*\|\s*\2\s*\|.*\n\1\s*((?<-a>\|)|[^|])*\|\s*([^\s|]*).* $5 ``` My first [balancing group](https://stackoverflow.com/a/17004406/2056269) regex. It should be still well golfable. Will try to do it later. The main idea is counting the pipes until the column name and then using the same amount of pipes up in the row starting with the desired row's name. After that we capture the next value which is the result. [Try it online here.](http://retina.tryitonline.net/#code=c2BeKD89LipcbiguKikgKC4qKSkoKD88YT5cfCl8LikqXHxccypcMlxzKlx8LipcblwxXHMqKCg_PC1hPlx8KXxbXnxdKSpcfFxzKihbXlxzfF0qKS4qCiQ1&input=ICAgfGF8eiB8Xyp8ICBhYiAgfAotLS0tLS0tLS0tLS0tLS0tLS0tCmF0YnwxfDg1fDIyfCA1ICAgIHwKYiAgfDV8NiB8ZSR8ICA4ICAgfAovKy18OHx3ZXx0aHwgMTI2ICB8CmF0YiBhYg) ]
[Question] [ This challenge is based on Downgoat's [Adjust your chair](https://codegolf.stackexchange.com/questions/66994/adjust-your-chair). ## Challenge You just adjusted your new chair! It fits you perfectly. However, the wheel is squeaky and you know the repair people will change the adjustment. Problem is, you don't have a ruler, so you'll have to write a program to measure it for you. [![Example of an adjustable chair](https://i.stack.imgur.com/dg3mt.jpg)](https://i.stack.imgur.com/dg3mt.jpg) The repair people can only wait for so long. So your code needs to be as short as possible. ## Examples ``` O | | | _ | | |_|_ | | O 5,3,2,2,1 ``` ``` O | _ | | |__|__ | | __|__ OOOOO 3,5,2,3,5 ``` ``` O | _ |______|______ ______|______ OOOOOOOOOOOOO 2,13,1,1,13 ``` ## Chair parts The chair has various components: ``` O <- Headrest | | <- Backrest | _ <- Armrest | | |__|__ <- Seat | | <- Leg _|_ OOO <- Wheels ``` ## Detailed Chair Descriptions The parts of the chair are: --- **Headrest:** There will always be one headrest above the backrest ``` O | ``` **Backrest:** The number of `|` is the **Backrest Height** ``` O | | ``` **Seat:** The number of `_` is the **Seat Width**, there is a `|` in the middle for the armrest. ``` __|__ ``` **Armrest:** The number of `|` is the **Armrest Height**. This will be inserted in the middle of the seat. ``` _ | | ``` **Leg:** The number of `|` is the **Leg Height** ``` | | ``` **Wheels:** The wheels are centred below the legs. If they are more than one, all but the centre wheel will have `_` in the line above them. ``` _ _ OOO ``` ## Output Given a chair, you will be outputting various variables. The output should be in the following order: 1. Backrest Height 2. Seat Width **always odd** 3. Armrest Height **Always less than backrest height** 4. Leg Height 5. Wheel count **Always less than or equal to seat width** and **Always odd** The output may have a trailing newline, or be in an array / list form if it is a function. ## Leaderboard ``` /* Configuration */ var QUESTION_ID = 67522; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 43394; // This should be the user ID of the challenge author. /* App */ 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,]*[^\s,]),.*?(\d+(?:[.]\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, }); }); 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; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || { lang: a.language, 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 > b.lang) return 1; if (a.lang < b.lang) 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); } } ``` ``` 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; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr> <td></td> <td>Author</td> <td>Language</td> <td>Size</td> </tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr> <td>Language</td> <td>User</td> <td>Score</td> </tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr> <td>{{PLACE}}</td> <td>{{NAME}}</td> <td>{{LANGUAGE}}</td> <td>{{SIZE}}</td> <td><a href="{{LINK}}">Link</a> </td> </tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr> <td>{{LANGUAGE}}</td> <td>{{NAME}}</td> <td>{{SIZE}}</td> <td><a href="{{LINK}}">Link</a> </td> </tr> </tbody> </table> ``` 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 leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` [Answer] ## Lua, 187 Bytes I think I might be able to golf it some more, but I think this is good at the moment. Also, if the output needs to be comma-separated I can fix that, but this still meets the requirements methinks. Also, input is fed in one line at a time. After the wheels are input, press enter with an an empty line to finalize input. ``` c={}i=1t=""while c[i-1]~=""do c[i]=io.read():gsub("%s+","")t=t..c[i]a=(not a and c[i]:find("_")and i or a)s=(not s and c[i]:find("_|_")and i or s)i=i+1 end print(s-1,c[s]:len()-1,s-a,#c-s-2,c[#c-1]:len()) ``` **Ungolfed** ``` c={} i=1 while c[i-1]~=""do c[i]=io.read():gsub("%s+","") --remove spaces a=(not a and c[i]:find"_"and i or a) --armrest position s=(not s and c[i]:find"_|_"and i or s) --seat position i=i+1 end print(s-1, c[s]:len()-1, s-a, #c-s-2, c[#c-1]:len()) ``` (Positions are measured top-to-bottom, so the top 'O' is position 1, and the wheels are the largest position. * Backrest height is the position of the seat minus one, compensating for the 'O' at the top. * Seat size is the length of th string at the seat's position minus one, compensating for the backrest. * Armrest height is the position of the seat minus the position of the armrest. * Leg height is the height of the chair (`#c`) minus the position of the seat minus 2, to compensate for the wheels and seat. * Wheel count is the length of the final string. [Answer] # Groovy, 161 bytes!!! Yay!! Not in last!! ``` f={s->a=s.split(/\n/) b=a.findIndexOf{it.contains('|_')} d=b-a.findIndexOf{it.contains('_')} print"$b,${a[b].count('_')+1},$d,${a.size()-b-2},${s.count('O')-1}"} ``` Ungolfed: ``` f={String s -> split = s.split(/\n/) bottomOfChairBack = split.findIndexOf {it.contains('|_')} armHeight = bottomOfChairBack-split.findIndexOf {it.contains('_')} width = split[bottomOfChairBack].count('_')+1 height = split.size() - bottomOfChairBack - 2 wheelCount = s.count('O')-1 return [bottomOfChairBack, width, armHeight, height, wheelCount] } ``` Tests of ungolfed program: ``` assert f('''O | | | _ | | |_|_ | | O''') == [5, 3, 2, 2, 1] assert f('''O | _ | | |__|__ | | __|__ OOOOO''') == [3,5,2,3,5] assert f('''O | _ | | |__|__ | | __|__ OOOOO''') == [3,5,2,3,5] assert f('''O | _ |______|______ ______|______ OOOOOOOOOOOOO''') == [2,13,1,1,13] ``` [Answer] # Pyth, 57 54 53 50 bytes Probably can be golfed further. -3 bytes thanks to [issacg](https://codegolf.stackexchange.com/users/20080/isaacg) for the single character string trick. ``` =kjb.z =H/k+b\| -/k\_=G-/k\O2 --/k\|H=Nt/k+bd N hG ``` Explanation: ``` =kjb.z =k Assign k z Input jb. Join list by newlines =H/k+b\| =H Assign H / +b\| Count occurrences of "\n|" k In input (Implicit: print backrest height) -/k\_=G-/k\O2 =G Assign G -/k\O2 The number of wheels minus 1 -/k\_ Count the number of "_" (Implicit: print seat width) --/k\|H=Nt/k+bd =N Assign N /k+bd Count the number of lines starting with " " t Subtract 1 (N is now the leg height) /k\| Count the number of "|" - H Subtract the "|" for the backrest - Subtract leg height (Implicit: print armrest height) N Print leg height hG Print the number of wheels ``` [Answer] # Perl, ~~93+2=95~~ ~~90+1=91~~ 83+1= 84 bytes *Apparently the output doesn't need comma-separating* Invoke with `perl -n chair.pl chairInput` (1B penalty for the flag). ``` END{print$b,2+$u-$o,$a,$.-$b-2,$o-1}$u+=s/_//g;$o+=s/O//g;s/^\|//&&$b++&&/\|/&&$a++ ``` Ungolfed: ``` END{ # Put the END block first to save 1 ; print $b, 2+$u-$o, $a, $.-$b-2, # $. is the number of lines total $o-1 } $u+=s/_//g; # count _s incrementally $o+=s/O//g; # count Os incrementally s/^\|// && $b++ # it's backrest if it starts with | && /\|/ && $a++ # and it's armrest if it has another one ``` --- ## Previous version: Invoke with `perl -0n chair.pl < chairInput` ``` s/^\|//&&$b++?/\|/&&$a++:$h++for split" ",$_;$,=",";print$b,2+s/_//g-($o=s/O//g),$a,$h-3,$o-1 ``` Explanation: ``` s/^\|// && $back++ # the backrest is all lines starting with | ? /\|/ && $arm++ # the armrest is all of those lines with another | : $height++ # otherwise it counts for the seat height for split" ",$_; # literal newline for 1 byte saved $,=","; # output separator print $back, 2+s/_//g-($o_count=s/O//g), # you can find the seat size # from the different between the number # of Os and _s $arm, $height-3, $o_count-1 ``` [Answer] # Python 3, ~~160~~ 158 bytes This code works but only on the following conditions: 1) `armrest height > 0` otherwise the `_` count breaks and 2) `seat width > 1` otherwise the armrest blocks the width-one seat and the `_` count breaks. ``` def f(s): a=s.split("\n");x=[];y=[];l=len(a) for i in range(l): m=a[i].count("_") if m:x+=i,;y+=m, return x[1],y[1]+1,x[1]-x[0],l-x[1]-2,s.count("O")-1 ``` ]
[Question] [ Joe is your average BF developer. He is about to check in his code changes to their repository when he gets a call from his boss. "Joe! The new client's machine is broken! The brainfuck interpreter sets all the cells to random values before program execution. No time to fix it, your code will have to deal with it." Joe doesn't think much of it, and is about to write a program to set the first million cells to zero, when his boss interrupts him again - "... and don't think about using brute force, the code has to be as small as possible." Now you have to help poor Joe! ## Specifications * You will get some valid brainfuck code as input * Your program will then modify the code so that it should work on a randomized brainfuck interpreter * This means that before program execution, the cells can be set to any value. * The new program should have the exact same behavior no matter the initial conditions. * The interpreter will have max-cell value of 255 with wrapping, and an infinite length tape. ## Scoring Your score is **10 times the compiler size in bytes** plus the **sum of the test case sizes**. Lowest score obviously wins.To mitigate against test-case optimization, I reserve the right to change the test-cases around if I suspect anything, and probably will do so before picking a winner. ## Test Cases (I got these from the [esolangs page](https://esolangs.org/wiki/Brainfuck) and this webpage: <http://www.hevanet.com/cristofd/brainfuck/>). Also thanks to @Sparr for the last test case. * Hello World: `++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.` * Reverse Input: `>,[>,]<[.<]` * Powers of Two (Infinite Stream): `>++++++++++>>+<+[[+++++[>++++++++<-]>.<++++++[>--------<-]+<<]>.>[->[ <++>-[<++>-[<++>-[<++>-[<-------->>[-]++<-[<++>-]]]]]]<[>+<-]+>>]<<]` * Squares Under 10000: `++++[>+++++<-]>[<+++++>-]+<+[>[>+>+<<-]++>>[<<+>>-]>>>[-]++>[-]+>>>+[[-]++++++>>>]<<<[[<++++++++<++>>-]+<.<[>----<-]<]<<[>>>>>[>>>[-]+++++++++<[>-<-]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-]` * Fibonacci Stream: `>++++++++++>+>+[[+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[[-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>]<<<]` * ASCII Sequence till input: `,[.[>+<-]>-]` (This one requires varying cell numbers based on the input) [Answer] # sed, 46 byte compiler ``` s/</<</g s/>/>[->[-]>[-]+<<]>/g s/^/[-]>[-]+</ ``` I didn't notice that the output was also supposed to be golf until after writing the program, so I will go for the short compiler. Also it was far too much work to test, so please notify if it does not function correctly :) [Answer] ## C++ Compiler size : 630 bytes ( -10 bytes thanks to Zacharý ) Hello World compile result size : 139 Square under 10000 : 319 Compiler : ``` #include<string> #include<map> #include<stack> #define B break #define C case #define S 30000 #define R m[(p<0)?(p%S)+S:p] using s=std::string;using P=std::pair<int,int>;s a(s c){char m[S];memset(m,0,S);int p=0,i=0;P r{0,0};std::map<int,int>j;std::stack<int>t;for(int d=0;d<c.size();++d){if(c[d]==91)t.push(d);if(c[d]==93){j[d]=t.top();j[t.top()]=d;t.pop();}}while(i<c.size()){switch(c[i]){C'>':++p;B;C'<':--p;B;C'+':++R;B;C'-':--R;B;C'[':if(!R)i=j[i];B;C']':i=j[i]-1;B;default:B;}++i;r.first=p<r.first?p:r.first;r.second=p>r.second?p:r.second;}s n;for(int i=r.first;i<r.second;++i){n+="[-]>";}n+="[-]"+s(r.second,60)+c;return n;} ``` The randomized brainfuck interpreter : ``` void interpret(const std::string& code) { char memory[30000]; for (int i = 0; i < 30000; ++i) memory[i] = std::rand()%256; int memPtr = 0, insPtr = 0; std::map<int, int> jump_map; { std::stack<int> jstack; for (int i = 0; i < code.size(); ++i) { if (code[i] == '[') jstack.push(i); if (code[i] == ']') { jump_map[i] = jstack.top(); jump_map[jstack.top()] = i; jstack.pop(); } } } while (insPtr < code.size()) { switch (code[insPtr]) { case '>': ++memPtr; break; case '<': --memPtr; break; case '+': ++memory[memPtr]; break; case '-': --memory[memPtr]; break; case '.': std::cout << memory[memPtr]; break; case ',': std::cin >> memory[memPtr]; break; case ']': if (memory[memPtr] != 0) insPtr = jump_map[insPtr]; break; case '[': if (memory[memPtr] == 0) insPtr = jump_map[insPtr]; break; default:break; } ++insPtr; } } ``` Some notes : * The compiler will execute the program to determine the memory cells that are used. If your program is an infinite loop, the compiler will loop infinitely. [Answer] # [rs](https://github.com/kirbyfan64/rs), 33 bytes, Score: 2659 Mostly just a simple port of the `sed` answer. ``` </<< >/>[->[-]>[-]+<<]> [-]>[-]+< ``` ]
[Question] [ *99* is a programming language I invented earlier this week for my challenge [Write an interpreter for 99](https://codegolf.stackexchange.com/q/47588/26997). (Invented but never needed to implement thanks to half a dozen of you. ;) ) The full language spec is in that challenge so I'm not bothering to repost it all here. In *99* you can print individual [ASCII](http://www.asciitable.com/) characters to stdout, but due to the constraints of the language, it is not always clear how to print a particular character as concisely as possible. For each of the 128 ASCII characters, write a *99* program that takes no input and outputs that sole character. You may code any or all of these answers by hand, or you can write another program (in any language you like) to generate them for you. The sum of the characters in each of your 128 *99* programs is your score. **The lowest score wins.** Newlines count as one character. Remember, in *99*, only even sized variables like `9999` output ASCII characters (odd sized variables output integers). Their value is divided by 9 and then taken mod 128, so values do not need to be in a certain range to map to ASCII characters. For example, the internal values 297, 1449, and -855 all correspond to the character `!` because when they are divided by 9 and taken mod 128, they all become 33, which is the character code for `!`. If you need an interpreter for *99*, I'd suggest [Mac's Python answer](https://codegolf.stackexchange.com/a/47593/26997). I know [I said](http://meta.codegolf.stackexchange.com/q/4887/26997) my next challenge would be more interactive but I'm still working on the stuff for that one. [Answer] # One assignment, 2075 (optimal) This should be the optimal value (unless I have a big error in reasoning or my testing sucks). First of all. There are only 7 different numbers (mod 128) you can express in 99. All values of 7 or more 9 evaluate to the same number 71. (Because 10^8 mod 128 == 0, 10^9 mod 128 == 0, ...) If one of the 4 values you can express with an even number of nines, than outputting this number is clearly the optimal solution. Otherwise I try to reach the number with one assignment statement (assign to 99) and print 99. As it turns out the maximal program size with this approach is 22 char. Clearly using Goto takes definitely more than that. The only possibility that a one-assignment solution might be beaten is a solution with two assignments. I tested this (hopefully with no errors, the code for this is quite messy), and found no solution for any ASCII char. Therefore only checking the 4 direct numbers and the one-assignment approach should be enough to find the optimal solution. The following Python (2 and 3 compatible) program generates all programs and sums up their lengths. It uses a simple IDA\* approach. ``` from itertools import count def nines_to_dec(nines): return ((10**nines - 1) // 9) % 128 def shortest_representation(ascii_value): # try simple output, # max code length is 8, (8 nines == 10 nines == 12 nines == ...) # if this works, than this is the shortest representation for nines in range(2, 9, 2): if nines_to_dec(nines) == ascii_value: return "9" * nines # otherwise try one assignment for length in count(1): result = assignment(ascii_value, length, []) if result: return "99 " + result + "\n99" def assignment(value, left, nines_list): if left == 0: eval_numbers = [nines_to_dec(nines) for nines in nines_list] if (sum(eval_numbers[::2]) - sum(eval_numbers[1::2])) % 128 == value: return " ".join("9" * nines for nines in nines_list) else: return False for nines in range(1, 8): left2 = left - nines - 1 # -1 for space if left2 >= 0: result = assignment(value, left2, nines_list + [nines]) if result: return result return False lengths = [] for i in range(128): program =shortest_representation(i) lengths.append(len(program)) print("ASCII-value: {}, ASCII-char: {}".format(i, chr(i))) print(program) print(sorted(lengths)) print(sum(lengths)) ``` The output is of the following form: ``` .... ASCII-value: 65, ASCII-char: A 99 9 999999 9999999 99 ASCII-value: 66, ASCII-char: B 99 9 99 9999 99 99 ASCII-value: 67, ASCII-char: C 99 9 99 9 99 9999 99 .... ``` You can find the complete output at: <http://pastebin.com/bKXLAArq> The char with the shortest program (2 char) is `vertical tab - 11` with a program length of 2, the chars with the longest programs (22 char) are `bell - 7` and `A - 65`. The sum for all programs is 2075. And by the way, I used the [k/q interpreter from tmartin](https://codegolf.stackexchange.com/a/47704/29577). I hat quite some troubles with the other ones (Python, Perl, CJam). Not sure if it was my fault. [Answer] # A Variety of Techniques, 42109 For the numbers, instead of calculating the large ASCII character, I just calculated the number's value. You only said to be able to output the character, so this should still work. EDIT: Switched the numbers to use the ASCII characters, so disregard that. I left the original number code in the Java code but commented out in case anyone wanted to use it. Some of these I did by hand, most I just wrote a program to type out. These are made up of 1-4 lines each, so they're fairly friendly to just copy and paste into a program. It should be noted that they don't work in succession due to my generated code not preserving variable states. The most common technique used here was the same as orlp's approach: > > Keep subtracting 9 from 99, then output. > > > My version differs by using some custom cases and composing a lot of the math onto just one line. Custom cases are just where the character can be represented with just a bunch of 9's and no math or my generation code could be shortened. ## Programs I've put the output on Pastebin for those of you who don't feel like running the program: <http://pastebin.com/Cs6WZUfb> ## Java Code I used: ``` public class AsciiGen99 { public static void main(String[] args) { long totalsize = 0; for (int i = 0; i < 128; i++) { System.out.println("\n The program for ASCII code " + i + " is as follows:\n"); String yea = find(i); if (yea != null) { System.out.println(yea); totalsize += yea.length(); } else { String v = "99 9 9\n9 99 9"; if (i != 0) { v += "\n99"; for (int j = 0; j < i; j++) { v += " 99 9"; } } v += "\n99"; System.out.println(v); totalsize += v.length(); } } System.out.println(totalsize); } public static String find(int i) { switch (i) { case '\0': return "99 9 9\n99"; case '\1': return "99 9\n99"; } // if (48 <= i && i <= 57) { // switch (i) { // case '0': // return "9 9 9\n9"; // case '1': // return "9"; // case '2': // return "999 9 9\n9 999 9\n999 999 9 999 9\n999"; // case '3': // return "999 9 9\n9 999 9\n999 999 9 999 9 999 9\n999"; // case '4': // return "999 9 9\n9 999 9\n999 999 9 999 9 999 9 999 9\n999"; // case '5': // return "999 9 9\n9 999 9\n999 999 9 999 9 999 9 999 9 999 9\n999"; // case '6': // return "99 9 9\n9 99 9\n999 99 9 99 9 99 9 99 9 99 9 99 9\n999"; // case '7': // return "99 9 9\n9 99 9\n999 99 9 99 9 99 9 99 9 99 9 99 9 99 9\n999"; // case '8': // return "99 9 9\n9 99 9\n999 99 9 99 9 99 9 99 9 99 9 99 9 99 9 99 9\n999"; // case '9'://ironic // return "99 9 9\n9 99 9\n999 99 9 99 9 99 9 99 9 99 9 99 9 99 9 99 9 99 9\n999"; // } // } int x, a; for (x = 0; x < 100000; x++) { a = i + 128 * x; String s = "" + a*9; if (containsOnly9(s) && (s.length() & 1) == 0) { return ("" + (a * 9)); } } return null; } public static boolean containsOnly9(String s) { for (char c : s.toCharArray()) { if (c != '9' && c != ' ' && c != '\n' && c != '\r' && c != '\t') { return false; } } return true; } } ``` [Answer] # Repeated subtraction, 65280 A trivial solution to compare against. Keep subtracting 9 from 99, then output. Example for ASCII character 10: ``` 99 99 9 99 ``` There are 128 programs. The first program is two characters long (99), each one after that is 8 characters (99 99 9\n) longer than the previous one. Python program generating programs seperated by empty lines, and computing score: ``` score = 0 for n in range(128): program = "99 99 9\n" * n + "99" score += len(program) print(program + "\n") print(score) ``` ]
[Question] [ I am trying to golf down some C++. Is it possible to make this condition shorter? `X > 3 & X - Y > 1` (Apart from removing whitespace, of course.) So, `X` is at least `4` but `X >= Y + 2`. `X` and `Y` are integers in the [0,5] interval. I have tried to find some bitwise formula but failed. [Answer] After brute forcing every useful combination of symbols under 9 characters, I've found there to be no smaller solution than `x>3&x-y>1`. For fun here's some funky 9 character solutions the brute forcer found: ``` -x<~y>4>x ~y+x>2>>y x*x-y*y>9 ~y>x/~3*x -3>>y>y-x ~y+x<<y>2 ``` --- Brute forcing was done in Python, building top-down syntax trees where no child may have an operator with precedence lower than its parent according to C's rules. To cut down on possibilities I only allowed single digit literals, and no binary operator may have two constant children. I could not possibly think of any solution that would have a two digit literal, or one that builds a constant using a binary operator. Then each expression was evaluated for [0, 5] and if it matches it gets printed. [Answer] In response to the (awesome) golfs by `orlp`: # Correctness must come first * Most of these break down for some integer types. This includes the version from the OP * Interestingly they *do* work for `int16_t` - so there is the assumption. Probably the bit shifts would need to +16 for 32 bit ints (that's pretty much everywhere these days). This makes them a character bigger... The only "correct" way to write it, IMO is `(x>3) && (x > y+1)`, which may be golfed down to `x>3&x>y+1` (9 characters). *(You really need to take the possibility of (larger) unsigned types into consideration, especially since unsigned-ness is "contagious" in C++ expressions. I suppose "fixing" that with the appropriate `static_cast<>`s would kinda defeat the purpose...)* **UPDATE** With the following tests I've been able to figure out which expressions *actually* work reliably: **`[Live On Coliru](http://coliru.stacked-crooked.com/a/134a46600e9fe193)`** ``` #define REPORT(caption, expr) do {\ do_report(caption, [](T x, T y) -> bool { return (expr); }, #expr); } while (false) template <typename T> struct driver { static void run() { std::cout << "\n" << __PRETTY_FUNCTION__ << "\n"; // the only two correct implementations: REPORT("MASTER" , (x>3) && (x>y+1)); REPORT("GOLF" , x>3&x>y+1); REPORT("lookup" , "000000000000000000000000111000111100"[x*6+y]-'0'); // failing sometimes: REPORT("question", (x>3)&(x-y>1)); REPORT("orlp0" , x>3&x-y>1); REPORT("orlp2" , ~y+x>2>>y); REPORT("orlp3" , x*x-y*y>9); REPORT("orlp4" , ~y>x/~3*x); REPORT("orlp5" , -3>>y>y-x); REPORT("orlp6" , ~y+x<<y>2); // failing always REPORT("orlp1" , -x<~y>4>x); } private: static void do_report(std::string const& caption, bool (*f)(T,T), char const* expression) { std::string r; for (T x = 0; x < 6; ++x) for (T y = 0; y < 6; ++y) r += f(x, y)?'1':'0'; bool const correct = "000000000000000000000000111000111100" == r; std::cout << (correct?"OK\t":"ERR\t") << r << "\t" << caption << "\t" << expression << "\n"; } }; int main() { driver<int8_t>::run(); driver<int16_t>::run(); driver<int32_t>::run(); driver<int64_t>::run(); driver<uint8_t>::run(); driver<uint16_t>::run(); driver<uint32_t>::run(); driver<uint64_t>::run(); } ``` Output on coliru, here for reference: ``` static void driver<T>::run() [with T = signed char] OK 000000000000000000000000111000111100 MASTER (x>3) && (x>y+1) OK 000000000000000000000000111000111100 GOLF x>3&x>y+1 OK 000000000000000000000000111000111100 lookup "000000000000000000000000111000111100"[x*6+y]-'0' OK 000000000000000000000000111000111100 question (x>3)&(x-y>1) OK 000000000000000000000000111000111100 orlp0 x>3&x-y>1 OK 000000000000000000000000111000111100 orlp2 ~y+x>2>>y OK 000000000000000000000000111000111100 orlp3 x*x-y*y>9 OK 000000000000000000000000111000111100 orlp4 ~y>x/~3*x OK 000000000000000000000000111000111100 orlp5 -3>>y>y-x OK 000000000000000000000000111000111100 orlp6 ~y+x<<y>2 ERR 000000000000000000000000000000000000 orlp1 -x<~y>4>x static void driver<T>::run() [with T = short int] OK 000000000000000000000000111000111100 MASTER (x>3) && (x>y+1) OK 000000000000000000000000111000111100 GOLF x>3&x>y+1 OK 000000000000000000000000111000111100 lookup "000000000000000000000000111000111100"[x*6+y]-'0' OK 000000000000000000000000111000111100 question (x>3)&(x-y>1) OK 000000000000000000000000111000111100 orlp0 x>3&x-y>1 OK 000000000000000000000000111000111100 orlp2 ~y+x>2>>y OK 000000000000000000000000111000111100 orlp3 x*x-y*y>9 OK 000000000000000000000000111000111100 orlp4 ~y>x/~3*x OK 000000000000000000000000111000111100 orlp5 -3>>y>y-x OK 000000000000000000000000111000111100 orlp6 ~y+x<<y>2 ERR 000000000000000000000000000000000000 orlp1 -x<~y>4>x static void driver<T>::run() [with T = int] OK 000000000000000000000000111000111100 MASTER (x>3) && (x>y+1) OK 000000000000000000000000111000111100 GOLF x>3&x>y+1 OK 000000000000000000000000111000111100 lookup "000000000000000000000000111000111100"[x*6+y]-'0' OK 000000000000000000000000111000111100 question (x>3)&(x-y>1) OK 000000000000000000000000111000111100 orlp0 x>3&x-y>1 OK 000000000000000000000000111000111100 orlp2 ~y+x>2>>y OK 000000000000000000000000111000111100 orlp3 x*x-y*y>9 OK 000000000000000000000000111000111100 orlp4 ~y>x/~3*x OK 000000000000000000000000111000111100 orlp5 -3>>y>y-x OK 000000000000000000000000111000111100 orlp6 ~y+x<<y>2 ERR 000000000000000000000000000000000000 orlp1 -x<~y>4>x static void driver<T>::run() [with T = long int] OK 000000000000000000000000111000111100 MASTER (x>3) && (x>y+1) OK 000000000000000000000000111000111100 GOLF x>3&x>y+1 OK 000000000000000000000000111000111100 lookup "000000000000000000000000111000111100"[x*6+y]-'0' OK 000000000000000000000000111000111100 question (x>3)&(x-y>1) OK 000000000000000000000000111000111100 orlp0 x>3&x-y>1 OK 000000000000000000000000111000111100 orlp2 ~y+x>2>>y OK 000000000000000000000000111000111100 orlp3 x*x-y*y>9 OK 000000000000000000000000111000111100 orlp4 ~y>x/~3*x OK 000000000000000000000000111000111100 orlp5 -3>>y>y-x OK 000000000000000000000000111000111100 orlp6 ~y+x<<y>2 ERR 000000000000000000000000000000000000 orlp1 -x<~y>4>x static void driver<T>::run() [with T = unsigned char] OK 000000000000000000000000111000111100 MASTER (x>3) && (x>y+1) OK 000000000000000000000000111000111100 GOLF x>3&x>y+1 OK 000000000000000000000000111000111100 lookup "000000000000000000000000111000111100"[x*6+y]-'0' OK 000000000000000000000000111000111100 question (x>3)&(x-y>1) OK 000000000000000000000000111000111100 orlp0 x>3&x-y>1 OK 000000000000000000000000111000111100 orlp2 ~y+x>2>>y OK 000000000000000000000000111000111100 orlp3 x*x-y*y>9 OK 000000000000000000000000111000111100 orlp4 ~y>x/~3*x OK 000000000000000000000000111000111100 orlp5 -3>>y>y-x OK 000000000000000000000000111000111100 orlp6 ~y+x<<y>2 ERR 000000000000000000000000000000000000 orlp1 -x<~y>4>x static void driver<T>::run() [with T = short unsigned int] OK 000000000000000000000000111000111100 MASTER (x>3) && (x>y+1) OK 000000000000000000000000111000111100 GOLF x>3&x>y+1 OK 000000000000000000000000111000111100 lookup "000000000000000000000000111000111100"[x*6+y]-'0' OK 000000000000000000000000111000111100 question (x>3)&(x-y>1) OK 000000000000000000000000111000111100 orlp0 x>3&x-y>1 OK 000000000000000000000000111000111100 orlp2 ~y+x>2>>y OK 000000000000000000000000111000111100 orlp3 x*x-y*y>9 OK 000000000000000000000000111000111100 orlp4 ~y>x/~3*x OK 000000000000000000000000111000111100 orlp5 -3>>y>y-x OK 000000000000000000000000111000111100 orlp6 ~y+x<<y>2 ERR 000000000000000000000000000000000000 orlp1 -x<~y>4>x static void driver<T>::run() [with T = unsigned int] OK 000000000000000000000000111000111100 MASTER (x>3) && (x>y+1) OK 000000000000000000000000111000111100 GOLF x>3&x>y+1 OK 000000000000000000000000111000111100 lookup "000000000000000000000000111000111100"[x*6+y]-'0' ERR 000000000000000000000000111001111100 question (x>3)&(x-y>1) ERR 000000000000000000000000111001111100 orlp0 x>3&x-y>1 ERR 111111011111001111000111111011111101 orlp2 ~y+x>2>>y ERR 011111001111000111000011111001111100 orlp3 x*x-y*y>9 ERR 111111111111111111111111111111111111 orlp4 ~y>x/~3*x ERR 111111011111001111000111111011111101 orlp5 -3>>y>y-x ERR 111111011111001111000111111011111101 orlp6 ~y+x<<y>2 ERR 000000000000000000000000000000000000 orlp1 -x<~y>4>x static void driver<T>::run() [with T = long unsigned int] OK 000000000000000000000000111000111100 MASTER (x>3) && (x>y+1) OK 000000000000000000000000111000111100 GOLF x>3&x>y+1 OK 000000000000000000000000111000111100 lookup "000000000000000000000000111000111100"[x*6+y]-'0' ERR 000000000000000000000000111001111100 question (x>3)&(x-y>1) ERR 000000000000000000000000111001111100 orlp0 x>3&x-y>1 ERR 111111011111001111000111111011111101 orlp2 ~y+x>2>>y ERR 011111001111000111000011111001111100 orlp3 x*x-y*y>9 ERR 111111111111111111111111111111111111 orlp4 ~y>x/~3*x ERR 111111011111001111000111111011111101 orlp5 -3>>y>y-x ERR 111111011111001111000111111011111101 orlp6 ~y+x<<y>2 ERR 000000000000000000000000000000000000 orlp1 -x<~y>4>x ``` # Summary Since this about the "cost" of repeating source code elements, you might use a lookup table. You can "hide" the lookup table, so it is either ``` LUT[x][y] ``` or ``` LUT[x*6+y] ``` Of course you can be pedantic and obtuse and rename the LUT ``` L[x][y] ``` So my "version" is ... ***7 characters***. (Or make if a function and `L(x,y)` is even shorter). Or, more importantly: correct, testable and maintainable. ]
[Question] [ Contest (!): In the language of your choice, write a program that will traverse the directory tree of a given directory and output a tree (i.e., an array of arrays) corresponding to it. Assume the directory is a predefined variable D. Smallest character count wins. **Rules:** * You must use recursion * See Rules Note: Assume that there are no recursion depth limits. In other words, your code just needs to work for sufficiently small directory trees, and in principle for larger ones. **For instance:** Directory tree is ``` dir1 ├── dir11 │   ├── file111 │   └── file112 ├── dir12 │   ├── file121 │   ├── file122 │   └── file123 ├── file11 ├── file12 └── file13 ``` Output tree is ``` [[[],[]],[[],[],[]],[],[],[]] ``` First code golf here so lemme know if I'm doing something wrong. Have fun :) [Answer] # Mathematica ~~120~~ ~~21~~ 20 ![enter image description here](https://i.stack.imgur.com/YFiT4.png) Explicit recursion (thanks alephalpha for saving one char): ``` f=f/@__~FileNames~#& f["~/StackExchange/dir1"] ``` > > {{{}, {}}, {{}, {}, {}}, {}, {}, {}} > > > ``` TreeForm[%] ``` ![enter image description here](https://i.stack.imgur.com/0CJiK.png) Previous overcomplicated solution: ``` d="~/StackExchange/dir1" f@{x___,Longest@s:{y_,___}..,z___}:=f@{x,f@Drop[{s},1,1],z} f[FileNameSplit/@FileNames[__,SetDirectory@d;"",∞]]/.f->(#&) ``` [Answer] ## Powershell - 182 Char ``` function A([string]$b){write-host -NoNewline '['; ls -path $b|foreach{if($_.PSIsContainer){A($_.FullName)}ELSE{write-host -NoNewline $f'[]';$f=', '}};write-host -NoNewline ']'};A($D) ``` Fairly simple. Could be reduced by 10 characters if the commas weren't required. Takes input from $D (as stated in question), returns output on STD-Out as the example in the question went. Really wishing aliases could use options! I'm being killed by the 'write-host -NoNewline's! [Answer] ## Ruby, 38 chars If you don't mind some extra whitespace in the output: ``` f=->n{Dir[n+'/*'].map{|c|f[c]}} p f[D] ``` Example usage: ``` D='C:/work/dir1' f=->n{Dir[n+'/*'].map{|c|f[c]}} p f[D] ``` Output: ``` [[[], []], [[], [], []], [], [], []] ``` If I can't have the whitespace, something like this for the second line: ``` puts"#{f[D]}".tr' ','' ``` [Answer] # Python 2.7, 111 chars Takes the target path from stdin. ``` import os def R(d):return[R(f)for f in[d+'/'+e for e in os.listdir(d)]if os.path.isdir(f)] print R(raw_input()) ``` [Answer] # C# 200 chars Outputting a string, not an actual array. Takes a path as the first argument. ``` using D=System.IO.DirectoryInfo;class P{static string R(D d){var r="[";foreach(D e in d.GetDirectories())r+=R(e);return r+"]";}static void Main(string[] a) {System.Console.WriteLine(R(new D(a[0])));}} ``` Ungolfed: ``` using D = System.IO.DirectoryInfo; class P { static string R(D d) { var r = "["; foreach (D e in d.GetDirectories()) r += R(e); return r + "]"; } static void Main(string[] a) { System.Console.WriteLine(R(new D(a[0]))); } } ``` [Answer] ## C++, 318 bytes ``` #include <cstdio> #include <dirent.h> #include <string> #define s std::string #define n e->d_name s l(s p){s r;dirent*e;DIR*d;if(d=opendir(p.c_str())){int c=0;while(e=readdir(d))if(s("..")!=n&s(".")!=n)r+=&",["[!c++]+(e->d_type==DT_DIR?l(p+'/'+n):"")+"]";closedir(d);}return r;}main(){puts((s("[")+l(D)+"]").c_str());} ``` Here is a slightly ungolfed version: ``` #include <cstdio> #include <dirent.h> #include <string> #define s std::string #define n e->d_name s l(s p) { s r; dirent*e; DIR*d; if (d=opendir(p.c_str())) { int c=0; while (e=readdir(d)) if (s("..")!=n&s(".")!=n) r+=&",["[!c++]+(e->d_type==DT_DIR?l(p+'/'+n):"")+"]"; closedir(d); } return r; } main() { puts((s("[")+l(D)+"]").c_str()); } ``` Please notice that since -- per instructions -- D is assumed to be a predefined variable, the code does not build without somehow supplying D. Here is one way to build: ``` g++ -Dmain="s D=\".\";main" -o tree golfed.cpp ``` [Answer] ## Batch script - 146, 157, 152 127 bytes ``` set x= :a set x=%x%,[ cd %1 goto %errorlevel% :0 for /f %%a in ('dir/b') do call:a %%a cd.. :1 set x=%x:[,=[%] cls @echo %x:~1% ``` Run with: ``` scriptfile.cmd folderroot ``` ]
[Question] [ The task of this challenge is as following: Write a program that reads a file of reasonable size (let's say <16 MB) from stdin or anywhere else (however you like, but must not be hardcoded), and put's the compressed output onto stdout. The output must be a valid gzip compressed file and if the compressed file runs through gunzip, it should yield exactly the same file as before. ## Rules * The programming language used must be known *before* this competition started * The score of your program is the number of characters of the source code or the assembled program (whatever is shorter) * You're not allowed to use any kind of existing compression libraries. * Have fun! [Answer] # C# (534 characters) ``` using System.IO;using B=System.Byte;class X{static void Main(string[]a){var f=File.ReadAllBytes(a[0]);int l=f.Length,i=0,j;var p=new uint[256];for(uint k=0,r=0;k<256;r=++k){for(j=0;j<8;j++)r=r>>1^(r&1)*0xedb88320;p[k]=r;}uint c=~(uint)0,n=c;using(var o=File.Open(a[0]+".gz",FileMode.Create)){o.Write(new B[]{31,139,8,0,0,0,0,0,4,11},0,10);for(;i<l;i++){o.Write(new B[]{(B)(i<l-1?0:1),1,0,254,255,f[i]},0,6);c=p[(c^f[i])&0xFF]^c>>8;}c^=n;o.Write(new[]{(B)c,(B)(c>>8),(B)(c>>16),(B)(c>>24),(B)l,(B)(l>>8),(B)(l>>16),(B)(l>>24)},0,8);}}} ``` ### Much more readable: ``` using System.IO; using B = System.Byte; class X { static void Main(string[] a) { // Read file contents var f = File.ReadAllBytes(a[0]); int l = f.Length, i = 0, j; // Initialise table for CRC hashsum var p = new uint[256]; for (uint k = 0, r = 0; k < 256; r = ++k) { for (j = 0; j < 8; j++) r = r >> 1 ^ (r & 1) * 0xedb88320; p[k] = r; } uint c = ~(uint) 0, n = c; // Write the output file using (var o = File.Open(a[0] + ".gz", FileMode.Create)) { // gzip header o.Write(new B[] { 31, 139, 8, 0, 0, 0, 0, 0, 4, 11 }, 0, 10); for (; i < l; i++) { // deflate block header plus one byte of payload o.Write(new B[] { (B) (i < l - 1 ? 0 : 1), 1, 0, 254, 255, f[i] }, 0, 6); // Compute CRC checksum c = p[(c ^ f[i]) & 0xFF] ^ c >> 8; } c ^= n; o.Write(new[] { // CRC checksum (B) c, (B) (c >> 8), (B) (c >> 16), (B) (c >> 24), // original file size (B) l, (B) (l >> 8), (B) (l >> 16), (B) (l >> 24) }, 0, 8); } } } ``` ### Comments: * Expects path to file as first command-line argument. * Output file is input file + `.gz`. * I am not using any libraries to do the gzip, deflate or CRC32. It’s all in there. * This “compressor” increases the filesize by a factor of 6. But it’s in valid gzip format! * Tested using GNU gunzip and WinRAR. ]
[Question] [ # Introduction One question that I have come across recently is the possibility of dissecting a staircase of height 8 into 3 pieces, and then re-arranging those 3 pieces into a 6 by 6 square. Namely, is it possible to dissect the following into 3 pieces: ``` x xx xxx xxxx xxxxx xxxxxx xxxxxxx xxxxxxxx ``` And rearrange those 3 pieces into the following shape: ``` xxxxxx xxxxxx xxxxxx xxxxxx xxxxxx xxxxxx ``` # Task In this challenge, you will be tasked to find out exactly this. Specifically, given two shapes created from adjacent (touching sides, not diagonally) squares of the same size and a natural number `n`, return whether it is possible to dissect one of the shapes into `n` pieces, with all cuts along the edges of the squares, and then rearrange those `n` pieces to form the other shape. Just like the input shapes, each piece also has to be formed from adjacent squares and thus form one contiguous region. The pieces can be moved, rotated, and flipped in any way in order to form the other shape, but nothing else like shrinking or stretching the piece. The shapes can be represented in any reasonable form, including a 2d matrix with one value representing empty space and the other representing the actual shape, or a list of coordinates representing the positions of each individual square. Additionally, you can assume that both shapes will consist of the same amount of squares, and that `n` will never exceed the number of squares within either of the shapes. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! # Test Cases In these test cases, each square is represented by one `#`, and an empty space is represented by a space. I made all the test cases by hand so tell me if there are any mistakes. ### Truthy ``` shape 1 shape 2 n ------------------------------------- x xx xxx xxxx xxxxx xxxxxx xxxxxxx xxxxxxxx xxxxxx xxxxxx xxxxxx xxxxxx xxxxxx xxxxxx 3 xxx xxx xx x xxxxx x xxx 3 xxxx xxxx xxxx xxxx xxxxx x x x x x x xxxxx 4 x x xxx xxx xx x xxxxx xxxxxx 10 ``` ### Falsey ``` shape 1 shape 2 n ------------------------------------- xxx xxx xxxxx x 2 xxxx xxxx xxxx xxxx xxxxx x x x x x x xxxxx 3 ### ### ### ######### 2 ##### ## # ### # ## # ## ### #### # ## # 3 ``` [Answer] # Python3, 1163 bytes: ``` import itertools as I E=enumerate Q=lambda b:[(x,y)for x,r in E(b)for y,t in E(r)if t] R=lambda x,f,n=3:[]if 0==n else[(X:=[*zip(*x)])]+R([X[::-1],[i[::-1]for i in X]][f],f,n-1) D=[(0,1),(0,-1),(1,0),(-1,0)] def V(t): q=[t.pop(0)] while q: x,y=q.pop(0) for X,Y in D: if(c:=(x+X,y+Y))in t:q+=[c];t.remove(c) return[]==t def W(a,b): for i in b: q=[(a[0],i,{*a}-{a[0]},{*b}-{i},[a[0]],[i])] while q: (x,y),(j,k),A,B,S,s=q.pop() if not A:yield B-{*s};break F=0 for X,Y in D: c,C=(x+X,y+Y),(j+X,k+Y) if c in A and c not in S and C in B:q+=[(c,C,A-{c},B,S+[c],s+[C])] elif c in A and c not in S and C not in B:F=1 if F:break def f(a,b,n): q,G,g,P=[(Q(a),Q(b),n)],eval(str(a)),eval(str(b)),[] while q: q=sorted(q,key=lambda x:len(x[0])) a,b,n=q.pop(0) if[]==[*a]+[*b] and n==0:return 1 if all([a,b,n]): for i,_ in[*E(a,1)][::-1]: for t in I.combinations(a,i): if V([*t]): T=[[0 for _ in i]for i in G] for X,Y in t:T[X][Y]=1 for o in[T,*R(T[::-1],0),*R([u[::-1]for u in T],1)]: if Q(o): for B in W(Q(o),b): if str(p:=([*{*a}-{*t}],B,n-1))not in P:q+=[p];P+=[str(p)] ``` [Try it online!](https://tio.run/##jVVRU9s4EH4@/woN9xDZUZg4CZSa0QOh0OnLDdBMG0bVdOzEvgoc27FF6xyT3053ZSe2gfb6EGlXu/vtt6uVk230tzQZn2T505NaZWmuidJhrtM0LohfkA/WBQ@Th1WY@zq0rnnsr4KlTwJP0JJt7CjNSclyohJyQQOjbpiu1NxWEdHSutkFlSxiCR97QoJhyHlCwrgIBZ17XDj/qYw6pS1t2b@hYi48b@BKJlQlILBC2LmUIpIINHBt6x0XdMhcm8E6wM1lQ1gHuElrGUbkE9W2Z5E1F/owSzOK5@THNxWHZA3nwGnD17UFVMwzZ7eY6R2aiYrowuO07M/Zpn9r22DQ3rrPxUKe6sM8XKXfQ7qA0DzUD3kiJOfaJP5MfRZg6j31AAGBCPXFUDLFHh1/O3hEZQtyALLaMoE61i2RaJspMQ1n9I7d2@yMTdlHVtTU7YopSVJNzryNCuMlmQ4enWJ7GuShf4/mSz7E7UWBZMHOm/oAHqR7kIwNMBfoekb8ZAkiJgD1o1HPUZyaZlAAYWeDx8UWefWhOazoi/OqBgLX/D9AtTr1Lrlb13LpVdSxlxH2kiXmItl79i@7gpTX1LfZNQwdGCQLv/sxLXQOh3ajBKCI7oWveQFDHi7pmt2Hm/1oenGY0BJ6b2PlJl17LlSENyscX/aFE0hDO@F86FXXTlzjQ/w4psIES9vbtVuxr1CccC6gCteW1UBXvUezqfzD4SJdBSrxtUqTAhxVFW9QP1HhaLk7IDMuxNCEIi5RzeN4L2uX1i1rbybmUtzKqrO1MUVGM@bc0Fn90uDdgCYemvf2gOEziZx3qZHNNU33VCqwKTp@pmioRp403ngLGTwg4VTj7uithBnB12vXt35lRiiTp1ewGX9bPhUu4eTg4MAqd2BWWTZSWyxbYkcuG6ncC6WFqMVoB1@d/cFmwsZNGLFIZcUkmMk4TNq4cL6PPGoZni/G4fhZJHybumvj@obXnal@L7nUZE7akKRTyNvGZO0P3SFvGJCmKNflv6XujvgfMnfHz/I2lkmD0fI/6pYAZVaAsBJUarfj9rRY@5sn1p5SfdwqC78sOv0apH6@pAXM7V/1YxZCJZrecd4re@Yv7e7ZO4tUDP@R9J80CRkpDossVpr2viQ9Gz541t9ZjvERbcDhr6mVagTaGL4zL/3GHb/JL/2OOn7HoE3A75XEbzqOJ6C5wz1ib9BzRsPX8N92wiCEkdHrCdxuae6va3O7xbmT34B263OPK9Cnnw) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 60 bytes ``` ƛṖvøṖÞf'L⁰=;'ƛhw"λhn÷:k□ẊṠJ↔";Ẋ≈;A;ƛƛ3(:k+v*Ṙ)Wƛgv-s;g;s;;ƒ↔ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwi4pahwqTigqzDt+KIh1wixpt2ZlxceMOeSTt3JErCqFMiLCLGm+G5lnbDuOG5lsOeZidM4oGwPTsnxptod1wizrtobsO3OmvilqHhuorhuaBK4oaUXCI74bqK4omIO0E7xpvGmzMoOmsrdirhuZgpV8abZ3YtcztnO3M7O8aS4oaUIiwiIiwieHh4XG4geFxuIHhcblxueHh4XG54IHhcblxuMyJd) Very slow. Takes input as a list of lists of coordinates of the two shapes and then the number pieces. Outputs truthy value if it is possible and falsy otherwise. Works by finding all possible dissections into \$n\$ connected pieces for both of the shapes and then checking if they have any in common. Get all dissections into \$n\$ pieces: ``` ṖvøṖÞf'L⁰=; ``` Keep only those where all the pieces are connected: ``` 'ƛhw"λhn÷:k□ẊṠJ↔";Ẋ≈;A; ``` Transform all of the pieces into a unique representation by getting all rotations, sorting the coordinates by dictionary ordering, translating them so the first coordinate is `[0, 0]` and then taking the smallest one. ``` ƛƛ3(:k+v*Ṙ)Wƛgv-s;g;s; ``` ]
[Question] [ ## Background We will be using a 3x3 cube for this challenge. Rubik's cubers have their own notation for movements on the cube: * Each of the 6 faces has a clockwise turn notated with a single capital letter: `UDLRFB`. There are three additional letters `MES` denoting the three center slices. * Counterclockwise rotations have a prime symbol appended: `U => U'`. The prime symbol for this challenge will be an ASCII apostrophe. * A move rotated twice (either CW or CCW) has a `2` appended: `U => U2`. * A move cannot be rotated twice and prime at the same time. * Individual moves are separated by spaces: `U F D' B2 E M' S2` * This challenge **will not** be using lowercase letters, which signify moving two layers at the same time. [Commutators](https://en.wikipedia.org/wiki/Commutator), coming from group theory, is an operation of two elements \$g,h\$ such that \$\left[g,h\right]=ghg^\prime h^\prime\$, where \$g^\prime\$ is the inverse of \$g\$, e.g. `R U F' => F U' R'` Rubik's cubers use a similar notation to describe commutators, used for swapping two or three pieces without disturbing any others. Some examples of commutators: ``` [F U R, D B] = (F U R) (D B) | (R' U' F') (B' D') [F' U2 R, D B2] = (F' U2 R) (D B2) | (R' U2 F) (B2 D') // note how B2 and U2 aren't primed ``` ## The Challenge Given a Rubik's cube commutator, expand the commutator to list out all the moves performed in it. ### Input Input is a Rubik's cube commutator. Each side of the commutator are guaranteed to be at least 1 move long. Each part of the commutator can be a separate value. Each move in each commutator part can be separate values, as long as a CCW/prime or double move is within the value of the move (e.g. `[[R2], ...]` is valid, but `[[R,2], ...]` is not). ### Output Output is a list of moves of the commutator. All moves must be capital letters in the set `UDLRFBMES`, with an optional prime `'` or double move `2`. ## Test Cases ``` [[F U R], [D B]] = F U R D B R' U' F' B' D' [[F' U2 R], [D B2]] = F' U2 R D B2 R' U2 F B2 D' [[U F' R2 F' R' F R F2 U' F R2], [F U2 F' U2 F2]] = U F' R2 F' R' F R F2 U' F R2 F U2 F' U2 F2 R2 F' U F2 R' F' R F R2 F U' F2 U2 F U2 F' [[M2 E2 S2], [B2 D2 F2]] = M2 E2 S2 B2 D2 F2 S2 E2 M2 F2 D2 B2 [[F], [B]] = F B F' B' [[U], [U]] = U U U' U' ``` ### 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! [Answer] # [R](https://www.r-project.org/), ~~85~~ 82 bytes Or **[R](https://www.r-project.org/)>=4.1, 68 bytes** by replacing two `function` occurrences with `\`s. ``` function(g,h,`[`=gsub,`!`=function(s)rev("''"["","(\\D)$"["\\1'",s]]))c(g,h,!g,!h) ``` [Try it online!](https://tio.run/##fVFNb4MwDL3vV5hsUhIpl/k6cUGUWy9UOTWV2FChlSo2Edq/zxxnndTS9ILM8/tw7HHu8rk7D@10/B5Ubw6m2TZ5789fpsma/L/j9bi/KCGl2AphhHKu1G9UO/cuhfG7ndYty7PeZAc9d2p/Un4a/c/pOClRgYWadCC0NnDTKqH4a@iP9pMANwj9CjmwBqgNtQQroZJQSCjly703dfGJOybsoywEICcgJVK5DLCBWyN/aQzSVMgDEfg4tWK36JmIf2YKN3oC@PGkwEiWgR1hlmBg8g8z7@dfI6wQNolZw5PTY161cKWFmpA112XAF/dI5KSuXMTLLrb@2Mam1mnDKqycfwE "R – Try It Online") Input as two vectors of strings. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` í''««˜ε¤ºK2£ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8Fp19UOrD60@Pefc1kNLDu3yNjq0@P//6GglNyUdpVAjIBGkrhSrE63kAmQ6GSnFxgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8Nr1dUPrT60@vScc1sPLTm0y9vo0OL/tTr/o6OjldyUdJRCgThIKVYnWskFyHJSio3VUQBJqYPkjFAljWCyIE1gFUFGcBaIcAOrB9Ig4VC4iBHYCDeYiQiz3eAm@oK4riAiGKLaCcR2QVXkBpFBuALEBZKxsQA). **Explanation:** ``` í # Reverse each inner list of the (implicit) input-pair ''« # Append a "'" to each inner-most string « # Merge this modified list to the (implicit) input-list ˜ # Flatten it to a single list of strings ε # Map over each string: ¤ # Push its last character (without popping the string) º # 'Double' it with a horizontal mirror K # Remove all those substrings from the string # (which will only remove potential "''") 2£ # Only leave (up to) the first two characters of the string # (after which the result is output implicitly) ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 20 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` ∾⊢∾(¬∘≠↓·⍷∾⟜"'")¨∘⌽¨ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oi+4oqi4oi+KMKs4oiY4omg4oaTwrfijbfiiL7in5wiJyIpwqjiiJjijL3CqAoKSm9pbiDihpAge+KIvuKfnPCdlajiirjiiL7CtPCdlal9Cj4oKCcgJyBKb2luwqgg4oqiKSDii4ggJyAnIEpvaW4gRinCqOKfqCgiRiLigL8iVSLigL8iUiIp4oC/KCJEIuKAvyJCIikKKCJGJyLigL8iVTIi4oC/IlIiKeKAvygiRCLigL8iQjIiKQooIk0yIuKAvyJFMiLigL8iUzIiKeKAvygiQjIi4oC/IkQyIuKAvyJGMiIpCuKfqCJGIuKfqeKAv+KfqCJCIuKfqQrin6giVSLin6nigL/in6giVSLin6nin6k=) `¬∘≠↓·⍷∾⟜"'"` is a function that inverts a single move: `∾⟜"'"` Append a prime symbol `⍷` Deduplicate, This removes one `'` if the move already contained one. `¬∘≠` Complement (1-) of the length of the move. -1 for length 2 moves, 0 for length 1. `↓` Drop this many characters (from the end because the value is negative) ``` (⍷∾⟜"'")¨ "U"‿"U'"‿"U2" # → U' U' U2' ¬∘≠¨ "U"‿"U'"‿"U2" # → 0 ¯1 ¯1 (¬∘≠↓·⍷∾⟜"'")¨ "U"‿"U'"‿"U2" # → U' U U2 ``` `⌽¨` Reverse each list `( ... )¨∘` Invert each move inside of each list `⊢∾` Prepend the input to the result of that `∾` Flatten by one level [Answer] # [Ruby](https://www.ruby-lang.org/), 65 bytes ``` ->a{[a,a.map{|x|x.reverse.map{|m|(m+?').sub("''","")[0,2]}}]*" "} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6xOjpRJ1EvN7GguqaipkKvKLUstag4FSKQW6ORq22vrqlXXJqkoaSurqSjpKQZbaBjFFtbG6ulpKBU@7@gtKRYIS1aITpayU1JR0EpFEQEKcXqKEQruYDYTkqxsQqx/wE "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḟ;ċ?”'ḣ2)Ṛ)⁸;Ẏ ``` A monadic Link accepting a list of lists (parts) of lists of characters (moves) which yields a list of lists of characters (moves). **[Try it online!](https://tio.run/##AT0Awv9qZWxsef//4bifO8SLP@KAnSfhuKMyKeG5minigbg74bqO/@G7tOG4suKCrMOHS///RicgVTIgUgpEIEIy "Jelly – Try It Online")** ### How? ``` ḟ;ċ?”'ḣ2)Ṛ)⁸;Ẏ - Link: list of lists of moves, A ) - for each Part of A: ) - for each Move in that part: ”' - yield a quote character ? - if... ċ - ...condition: count (X' -> 1, X -> 0, X2 -> 0) ḟ - ...then: filter discard (X' -> X) ; - ...else: concatenate (X -> X', X2 -> X2') ḣ2 - head to index 2 (X -> X, X'-> X', X2' -> X2) Ṛ - reverse (this Part) ⁸ - A ; - concatenate (the reversed, altered Part) Ẏ - tighten from a list of four parts to a list of all of the resulting moves ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` s+Qm_m+-k\'*\'hI ``` [Try it online!](https://tio.run/##K6gsyfj/v1g7MDc@V1s3O0ZdK0Y9w/P//@hoJTclHaVQIyARpK4UqxOt5AJkOhkpxcYCAA "Pyth – Try It Online") ``` s+Qm_m+-k\'*\'hIkdQ Q parsed input (Q is implicit) m take each sublist d: m d map each move k inside the sublist d to (d is implicit) -k\' the move k without the prime symbol + and append hIk 1 if the move k contains only one symbol, 0 otherwise (k is implicit, actually checks if taking the first character is still the complete move, alternatively !tk also works) *\' repeats of the prime symbol _ reverse the sublists +Q prepend the complete input s and merge everything into a single list of moves ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` WS⊞υι⪫⁺υEυ⪫E⮌⪪ι ⁺⁻λ'×'№αλ ¦ ``` [Try it online!](https://tio.run/##ZY7BCsIwEETv/Yqll24gguTakwgBBaG09gNCjTY0JCVNqn59bAKC4GUY3gyzO4zCDVboGJ@j0hLwZObgO@@UeSAh0IRlxEBBkbq4WwfYaTVIDD/R2SqDFzFjK1fpFondrJVHRaGEkhAKV@mMcG882mA8CgrTBhsdFpy2TlX@VRJmCW/m4E/mJl@J7QlJc3m1LprtRY/5ePjCGHvgFbQsawUcWuAM@uxYwaHPSVJWxN2qPw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated string of space-separated moves. Explanation: ``` WS⊞υι ``` Input the list of moves. ``` ⪫⁺υEυ⪫E⮌⪪ι ⁺⁻λ'×'№αλ ¦ ``` Extend the list by taking the list of moves, splitting on spaces, reversing, inverting each move, and joining with spaces, then join the extended list with spaces and output the result. Moves are inverted by removing any `'` but then adding a `'` if the move was a single letter. [Answer] # [Python 3](https://www.python.org), ~~113~~ ~~107~~ 83 bytes ``` lambda g,h:g+h+[r(r(m+"'","2'","2"),"''","")for m in g[::-1]+h[::-1]] r=str.replace ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZCxbtswEIaRVXMf4MCFVEwLCKfCgBHUcLVlsaGlEgclpiQWsiRQTNEgyJN0ydI-QN-meZoej7aLLOVAnf77_rvj_fg1PfluHF5_2-M0Og_z0yzBmaRZVz8ffbP8-Gff18f7Qw2t7FbtoluUTjhxXDDOJFN0sVQyHiKWNqODI9gB2nK1Wt7oRRe_OnHr2bvMmamvH0ws_Xb1IfB94LFvNvuDHVYJiN40HqewbedTWEOPGWcnkWbz1FsvGGosTSBgGDqTzY_3wjFRflp-0WXFlb5NGRbgrLphkksi03NzwaVGjWv-r4b5VvfUFqXJ2cG_myGBEZlGXJ-Iep4N7ooDz76OdhAjTrmOrISG5bXtzQGeA_0iqwHwmO-TefCoVuyZwJeKxQyddvQhM6LK4nJe3672ZZlDATstodzCRmscggTAP9hxKDjkHDYctjxBFgV1oVXEoxYMihwKK2BIhiKkd4purIRYrqgmiqFKTng0xXL_c8A7_EQVFNKYuwvFyXUx4CR3Cj4r2FPXMN2l4TkBZzXEqNxRvA16eDn5TvvZxJ2E9wW5OA1ehL4Fj8v9Cw) Input is two lists of strings. Naive string operations. * -6 bytes from @pajonk: alias `str.replace` to `r` * -24 bytes from @Kevin Cruijssen: output a list instead of a string ]
[Question] [ ## Description You are given the results of a range function where every element has been rounded down to the nearest whole number. Your goal is to recover the original list. For example, the following function (in Python3) will produce an input for your program: ``` from numpy import arange, floor def floored_range(A, B, C): return list(floor(arange(A, B, C))) ``` The output of your program should be a valid guess of the original data. Here, valid guess means that it must exactly match the input when floored and it must be a possible output of a range function (ie, when graphed it must form a perfectly straight line). ## Examples ``` Input: [1,2,3,4] Output: [1,2,3,4] Input: [1,2,3,4] Output: [1.9,2.7,3.5,4.3] Input: [1,2,3,4,5,5] Output: [1.9,2.7,3.5,4.3,5.1,5.9] Input: [1,1,2,2,3,3,4,4] Output: [1,1.5,2,2.5,3,3.5,4,4.5] Input: [1,1,2,3,3,4] Output: [1,1.7,2.4,3.1,3.8,4.5] Input: [56, 54, 52, 50, 48, 45, 43, 41, 39, 37, 35, 32, 30, 28, 26, 24, 22, 19, 17, 15, 13, 11] Output: [56.7 , 54.541, 52.382, 50.223, 48.064, 45.905, 43.746, 41.587, 39.428, 37.269, 35.11 , 32.951, 30.792, 28.633, 26.474, 24.315, 22.156, 19.997, 17.838, 15.679, 13.52 , 11.361] ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 82 bytes ``` function y=f(x) while any(floor(y=linspace(x(1)+rand,x(end)+rand,numel(x)))-x),end ``` Running time is non-deterministic, but the code ends in finite time with probability 1. [**Try it online!**](https://tio.run/##fY3NasMwEITveYq9lEh0DZVktc0hTxJyEJZEBe4q2E5jP707pj@HQnr4QMx@o6ndFD7SuuardFOpQssxq1nvbm@lTxRkUbmvdVDLsS8yXkKX1KyMfhyCRJ5Vkvj9lut76tHUupk1I18BPZDUiSSlmCLlOlCg36WYchHERahMI9WbUMboLpbxorI6GbbsuD1r/RXtm6bZ679n9uzPdNfZrM3bzH@@Mj/SPcU/M/kWWPDE1L4CDxwwTO4AXgAyB8fBsXAsehY9i8zAMXAMHIOeMVhbPwE "Octave – Try It Online") ### Explanation The code defines a `function` of `x` that outputs `y`. The function consists of a `while` loop. In each iteration, the right amount (`numel(x)`) of linearly spaced values are generated (`linspace`), starting at `x(1)+rand` and ending at `x(end)+rand`. These two calls to the `rand` function give random offsets between `0` and `1`, which are applied to the initial and final values of `x`. The loop is repeated for as long as `any` of the `floor`ed results differs (`-`) from the corresponding entry in `x`. [Answer] # [Python 3](https://docs.python.org/3/), 189 bytes ``` def f(l): R=range(len(l));e=1-1e-9 for j in R: for I in range(j*4): i=I//4;L=[((l[i]+I//2%2*e)*(x-j)-(l[j]+I%2*e)*(x-i))/(i-j)for x in R] if[x//1 for x in L]==l:return L return l ``` [Try it online!](https://tio.run/##bZDLboMwEEX3fIU3lWx6EfErCUT@gEhZZYtYVKpJjSwSISqRrydj0qab7uaeOXMXc7tPX9dBL8un71jHo6gzdnbjx3DxPPqBgDh4Jwvpiypj3XVkPQsDO5O2pmNKT73PTbpmLLhjWZrDyTWcxya07xTVm8q9yPlc9KIg2hN9oSBEyQNtUuO89rdrUdfMZSnZC59a52I9@ul7pJCxnykuyYjJaLJGQkHDtPhvhIV9xgQSStD8If17YLewpCvYDcwexsLQRkJX0DtoC03yBmoPtYUyUAqygtxBWkgNKamkrW9jGCaeHiuWBw "Python 3 – Try It Online") Cubic time. Has some numerical issues. [Answer] # [R](https://www.r-project.org/), 86 bytes ``` function(n){while(any(n-(x=seq(n[1]+runif(1),tail(n,1)+runif(1),l=sum(n|1)))%/%1))0;x} ``` [Try it online!](https://tio.run/##RcjBCoJQEAXQfV/RRrhDIzXlLv2ScCHi0IPXjdRHRvbtr3atDpwx@7Yusyf2c7gTlPfzGuKAji@wxNJMwwO8WLsbE4PDROcuRFBN/hWbKd3A1USk2Bc/Duflkx09TI960kpk46gkfwE "R – Try It Online") R port of [Luis Mendo's answer](https://codegolf.stackexchange.com/a/162561/67312); it does issue a number of warnings because of `any` coercing to `logical` but these can be ignored. [Answer] # [Python 3](https://docs.python.org/3/), 168 bytes ``` def f(l):r=range(len(l));g=lambda n:[(l[b]+n-l[a])/(b-a)for a in r for b in r if b>a]or[0];s=(max(g(-1))+min(g(1)))/2;m=min(a*s-l[a]for a in r);return[a*s-m for a in r] ``` [Try it online!](https://tio.run/##RZDNboQgFIX3fQqW0DlmBGR@NPRFCAvMqDVBNGiT9uktzKSV1Xe/czkJLD/b5xzkvj@6nvTUszrq6MLQUd@FNLJm0N5N7cORUBvqTWtPofDGWXambeFYP0fiyBhIJBnbF449aT@cnaMpbbNqOrlvOtCCM3aaxpAwETuLZtJ5dO/rs/LoYk3stq8YTI4mcgR2z@wTmzfDISBRWfwjFNRrzCKrLKtDyb8L6gKV1gVUieqGSqFKCYe8Q14hFWRaLiFuEBeICkKA38Gv4ApcgvNUYusljmGjHvnn4LX247qlxy406adMZ/8F "Python 3 – Try It Online") Explanation: `g` calculates the limiting values for `C` that lie just outside the range for `A` and `B` to exist. The average is then taken to give a usable value for `C`, and then the lowest possible range is then generated. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 31 bytes ``` ṾṚ”.;V×LḶ$}+©1ị$}IEȧḞ⁼¥ʋ 0ç1#®ḷ ``` [Try it online!](https://tio.run/##AU0Asv9qZWxsef//4bm@4bma4oCdLjtWw5dM4bi2JH0rwqkx4buLJH1JRcin4bie4oG8wqXKiwoww6cxI8Ku4bi3////WzEsMSwyLDMsMyw0XQ "Jelly – Try It Online") **Warning**: Floating-point inaccuracies. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 94 bytes, assuming input length > 1 ``` f=x=>(t=x.map(_=>a+=b,b=x[1]+(c=Math.random)(a=x[0]+c())-a,a-=b)).map(Math.floor)+''==x?t:f(x) ``` [Try it online!](https://tio.run/##fcvdCoJAEIbh827EGXaUrI6CsSvoCkRiXN1@UEd0ib37TYWOgk6/53tf8pbZTs/Rp4M2bYyOIZBwKPeVActX8Y9skqHRHgGpXiCvjAVMhTyHrJcRblyI4Zok5RqRC7@tW@k61QlNkjCHiz87CBitDrN2bdbpHRyUOR3oSKcKcfcjq626@J/H8dvHDw "JavaScript (Node.js) – Try It Online") 97 bytes ``` f=x=>(t=x.map(_=>a+=b,b=x[1]+(c=Math.random)(a=x[0]+c())-a||0,a-=b)).map(Math.floor)+''==x?t:f(x) ``` [Answer] # [Python 2](https://docs.python.org/2/), 212 bytes ``` def f(l): C=[(0,1.,0,1.)] for a,A,b,B in C: x,y=(A+a)/2,(B+b)/2;r=[l[0]+x+i*(l[-1]+y-l[0]-x)/(~-len(l)or 1)for i in range(len(l))];C+=[(x,A,y,B),(a,x,y,B),(x,A,b,y),(a,x,b,y)] if[n//1for n in r]==l:return r ``` [Try it online!](https://tio.run/##bVLLboMwELzzFT7aYUmwCX3Khya/0BtClaNAiuRA5FIJLv31dLakSZXmsF57dvbtw9i/d605HrdVLWrp1VMk1raQKek58aHKSNRdEI5eaEMr0bRiDY4YaLTyJXZqYUiu4g30c7CFL9IyHuJmJn2R6DIeE0aSQS3kV@KrFhkQTCsO2XCw4NpdJSeLKp/XMZIPyDXSSpF0NJxuw0/@8YTxDYWJpi7axUJztPYnWmmtfwpV/xnwODb7Qxd6sXf9e8QN7qYGg@VOoSfe3h0kU@a177pAQSEGiRBFh9C0PZwKXaq/LzKU0fIKY5RxWG7asn8@@R2JfAkxkJTE8gGSQzKIJpE9Qu4hwDJwMnAMOAZ@Bn4GmAZHg6PB0fDTN0ulnHLGT/PAzLfdPmL1Wn30H7YoIx7h22UhOk15Uo42dmLPJyXVDCbS6ewKTvJIeFtc5igdfsHmetF/vFAivplJFW/yvJLfmmKO9X8v5ak35708c9XxGw "Python 2 – Try It Online") ]
[Question] [ > > In the beginning there was NCSA Mosaic, and Mosaic called itself **`NCSA_Mosaic/2.0 (Windows 3.1)`**, and Mosaic displayed pictures along with text, and there was much rejoicing. > > > ***15 years later...*** > > And then Google built Chrome, and Chrome used Webkit, and it was like Safari, and wanted pages built for Safari, and so pretended to be Safari. And thus Chrome used WebKit, and pretended to be Safari, and WebKit pretended to be KHTML, and KHTML pretended to be Gecko, and all browsers pretended to be Mozilla, and Chrome called itself **`Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13`**, and the user agent string was a complete mess, and near useless, and everyone pretended to be everyone else, and confusion abounded. > > > [Read full story here...](http://webaim.org/blog/user-agent-string-history/) Given a User Agent string, return the browser that it corresponds to. You must support: * Chrome/Chromium\* * Opera * Firefox * IE * Edge * Safari Your code only needs satisfy all of these test cases. ``` Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4 Safari Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko IE Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8 Safari Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393 Edge Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063 Edge Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 6.3; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (Windows NT 6.1; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko IE Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Chrome Mozilla/5.0 (X11; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0 Firefox Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.2.5 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.5 Safari Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/59.0.3071.109 Chrome/59.0.3071.109 Safari/537.36 Chromium Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko IE Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30 Safari Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/52.0 Firefox Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0 Firefox Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0 Firefox Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/603.2.5 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.5 Safari Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 OPR/46.0.2597.57 Opera Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36 OPR/46.0.2597.32 Opera Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko IE Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36 Chrome Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; Trident/5.0) IE Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0) IE Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:54.0) Gecko/20100101 Firefox/54.0 Firefox Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8 Safari Mozilla/5.0 (Windows NT 6.1; rv:52.0) Gecko/20100101 Firefox/52.0 Firefox Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36 Chrome Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/58.0.3029.110 Chrome/58.0.3029.110 Safari/537.36 Chromium Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 OPR/46.0.2597.39 Opera Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko IE Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Chrome Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0 Firefox Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0 Firefox ``` Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the least bytes wins. --- \* Chromium and Chrome can be interchanged. [Answer] # [Retina](https://github.com/m-ender/retina), ~~53~~ 51 bytes ``` .+Tr.+ IE .+E.+ Edge .+P.+ Opera .+?([CFS]\w+).+ $1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fTzukSE@by9OVS0/bFchwTUlPBTIDgEz/gtSiRCDbXiPa2S04NqZcWxMoqmL4/z8A "Retina – Try It Online") Explanation: Opera can be identified by its `(O)P(R/)` platform and IE by its `Tr(ident)` engine. The other browsers include their full name in their user agent, but Edge puts theirs last so it has to be processed separately from the others. Edit: Saved 1 byte by detecting Edge after Trident and 1 byte by detecting Opera using just the `P` both thanks to @ThePirateBay. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` -7ịO%25ị“ðh³`Ẹ|Ḥ©®jḋƝ,Ṁ⁵»Ḳ¤ ``` A monadic link accepting and returning lists of characters. **[Try it online!](https://tio.run/##y0rNyan8/1/X/OHubn9VI1Mg9ahhzuENGYc2JzzctaPm4Y4lh1YeWpf1cEf3sbk6D3c2PGrcemj3wx2bDi35//@/b35VZk5Oor6pnoGCRnhmXkp@ebGCX4iCmZ6htQKQb2ZirVABIorKrExN9Aw0FdxTk7Pz9Y0MDA2AyFDBLbMoNS2/Qh8kCQA "Jelly – Try It Online")** or see a [test suite](https://tio.run/##1VjLbtNAFN33K2YBUiu143l4xjGRkBAqULUhiAZaViFNXeLWtSMngYBYFDZd9BforhsQQgiolNJdKvEfzo8E2yEkaU0a22OTSFGisTPnnHvPnTtj72qG8brbXVKc86P8TcLcn87Bh4uvlfb3587P1lunddL@2P6y67SOfh0vOmcHnXen7XOn9a190vW@T52zT4urF4c3dt1pYOk26BwczznnPy4OO@8/P@t2c9Yb3TBKEoMIzG/o5rb1qgYeFgBGEGWBe4HLWdDk8gK4U60a2oa2tarXJUYVSDmYX31QyK0tAkPf08B9rbxnLYC7Fdva1ySmQgQpUjDEmIH10k7J1vvTen@ZG6HOlcq6WbdqlSxYMeuaAdwLIL8ONl0lRUyKLGkBQ7FzSKcndFzkSQvYxDgL1nSz0QTNDC8mH/FIrvH/Li2eYrixl1XGpyaqS40ExC7P0LLiLjNRiQwzSuzIUcoNBU@T6SxpAdEbypOthllv9ED1xv5w0pEa4IR7MYIT@Y1Ue1zcRc@RR40xgUpGgP10@veTkPV2KdfpW5tGQQncpTM87Kohs30gSq1/BXQoWcCSRbN0BIzWk9PqjgL3ppGqSmivJtPvPPbOZQqSXee5gIjxLB3H/8auXC765e0XmoTdpMhUpf4oORXEVyFTNwE8UAaDmCE@mQxvL8sC@@UtJntbqU8lEYSR@8Hgnm5rO1ZT8m72BxOctuIA@hXaW3yjlRoHdFwVQkwEJeCys8LyShMwKqlk4tjmizL9H2BkHBiZuM5Fu8z6pgjSN6iXaIDB2ZPZGDDvZpSSQaLrOnYKrzRHOg6RRjBFKGDB1rc1sy4psJdKjD30wd4BVpYnCzUOkC8oHgCNLqRs7VdLdX3L0LIgt76yDNQ/vXiAjgawzBsMjxaiAOJQgBPlvGA1ypWoHibyyJZ/9FiS/ZdxTFUgU0C@qtmlFKRceWwdVUJJakquSwpVg6SEfC/HEYUEyoGKnmp2TbdMyWuWEPe19Gf0hrHegntQFGauJyfD5N6M8OQ4iJxAFjpyFily@So5dm2@ln2Y258QnhwFe55O5Fi0578B "Jelly – Try It Online") (shows `expected output -> output`; tests sorted by browser). ### How? ``` -7ịO%25ị“ðh³`Ẹ|Ḥ©®jḋƝ,Ṁ⁵»Ḳ¤ - Link: list of character, userAgentString -7ị - -7 index into userAgentString (last character is 0) O - cast to ordinal %25 - modulo by 25 ¤ - nilad followed by link(s) as a nilad: “ðh³`Ẹ|Ḥ©®jḋƝ,Ṁ⁵» - compression of dictionary words: - = "IE Firefox Opera Safari Chrome Edge" Ḳ - split at spaces ị - index into (1-indexed and modular) ``` [Answer] # JavaScript, ~~113~~ ~~83~~ 82 bytes Same approach as the [Retina answer](https://codegolf.stackexchange.com/a/137817/22867) by Neil. ``` f=_=>_[x=`includes`]`P`?`Opera`:_[x]`Tr`?`IE`:_[x]`E`?`Edge`:_.match(/[CFS]\w+/)[0] ``` Previous attempts: ``` // With String.prototype.test, 83 bytes f=_=>/P/.test(_)?`Opera`:/Tr/.test(_)?`IE`:/E/.test(_)?`Edge`:_.match(/[CFS]\w+/)[0] // With array filtering, 113 bytes f=_=>_[o=`Opera`,i=`includes`]`P`?o:[o,`Edge`,`Firefox`,`Chromium`,`Chrome`,`Safari`].filter(b=>_[i](b))[0]||`IE` ``` ## Try it: ``` const f=_=>_[x=`includes`]`P`?`Opera`:_[x]`Tr`?`IE`:_[x]`E`?`Edge`:_.match(/[CFS]\w+/)[0] const testData = { 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4': 'Safari', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko': 'IE', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8': 'Safari', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393': 'Edge', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063': 'Edge', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (Windows NT 6.1; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko': 'IE', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36': 'Chrome', 'Mozilla/5.0 (X11; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0': 'Firefox', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.2.5 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.5': 'Safari', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/59.0.3071.109 Chrome/59.0.3071.109 Safari/537.36': 'Chromium', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko': 'IE', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30': 'Safari', 'Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/52.0': 'Firefox', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0': 'Firefox', 'Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0': 'Firefox', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/603.2.5 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.5': 'Safari', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 OPR/46.0.2597.57': 'Opera', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36 OPR/46.0.2597.32': 'Opera', 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko': 'IE', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36': 'Chrome', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; Trident/5.0)': 'IE', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)': 'IE', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:54.0) Gecko/20100101 Firefox/54.0': 'Firefox', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8': 'Safari', 'Mozilla/5.0 (Windows NT 6.1; rv:52.0) Gecko/20100101 Firefox/52.0': 'Firefox', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36': 'Chrome', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/58.0.3029.110 Chrome/58.0.3029.110 Safari/537.36': 'Chromium', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 OPR/46.0.2597.39': 'Opera', 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko': 'IE', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36': 'Chrome', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0': 'Firefox', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0': 'Firefox' } Object.keys(testData).forEach(ua => { console.log('Expected: %s; actual: %s (input: %s)', testData[ua], f(ua), ua) }) ``` [Answer] # [Perl 5](https://www.perl.org/), 64 + 1 (-p) = 65 bytes ``` $_=/P/&&Opera||/Edge|Firefox/&&$&||/C/&&Chrome||/Tr/&&IE||Safari ``` [Try it online!](https://tio.run/##1Vhbb9owFH7vr/BDVRVpdXx8Cxnaw1R1W9UyqpWtfUMB3DVqSKIQOjbx28ccaFeugZALrcQDduTz@Zzj853PDlToinHf/l0bH7Y@GFfG0VEjUKE9Ghln3Z9q9MkJ1Z0/1NOHR3ruVP85vQ/9ntKDZqhH52ej0bV9Z4fOeFz3/ziuaxsCE3R843hd/1cffW0iIJjUkJ6QvIaGklfQxyBw1Y1qXziRIZiJmUTHF1@a9ct3yHUeFPqsOg9@BU2hDGFhghkxAQMINEV7WnYwh1m3O44X@f37Gjr3IuUiPYEa1@hWb6EFtCVeC7IkDFPMV0L/UGHf8T1DR03DPoM@rTjYEOPGTRzj8PG94JhUpiYNSoDoH6DnbMYf11qSGPIyxF5B1qElC0O@BR2qS8cbDNGwKlsF@jhB@t4eeNFgHjF7sgvb85oz1QydrvIiw4wPrN48QLz5F6Dtk4uB7uL@plqVZUQkMydWJ5jU0pgkCzPJZWZiuLqZmegsM@kVW3taRMr4m0iZPuiYmoRj05qHRHGvNYBj4MxihRGqjPEtynHVLMtlOnGZMx1mudJngUEQydKkmxTYx5einVdDzWRhrrnnyZ@Qi1YonsSWGu0u@15jhCYZoWmZSOyJyGEVkVMsUktMkZfEmaqVqZvOoDdbg8RaUZjESi0mypMumbrXorV0FZwjHUsS@w9AsVnNohnY3u5RfPmQgza88ZTPnvF4wdoQi2eyTkcLCfendIZWkxQXCUbij3nfS7YlpYXDWaIMK7T@UwqQvXPtkn9VWZbCWx9S1Lj6ZvCJ6BSWiYVZwiYW/V7YA6MJZUvf6GvFDrU6q23TdaM8nzwIz9IKyJt41klWNR2/F9iR03ZVDdWvz8@Q9VQIL4kiLxkS8WB2VEltDba3lnxzIPlf46H4twiZU3cvXIHlKLvn6CFjfy@nUzBrh5tw0x907jNeiGNaoa@YVv4/IAGRWagTStZp05pjSTXHUijqjYb@@kGkyaE/PqlrW0DGJ4H7Dw "Perl 5 – Try It Online") The header and the -l in the TIO link are just to make the output easier to read when feeding the entire list of User-Agents. Without those, this meets the challenge, taking one string and returning the browser name. [Answer] # [Kotlin](https://kotlinlang.org), ~~133~~ ~~130~~ 128 bytes ``` "Tr|IE_E|Edge_P|Opera_mi|Chromium_C|Chrome_A|Safari".split("_").map{it.split("|")}.firstOrNull{it[0] in this}?.get(1)?:"Firefox" ``` ## Beautified ``` "Tr|IE_E|Edge_P|Opera_mi|Chromium_C|Chrome_A|Safari" .split("_") .map { it.split("|") } .firstOrNull { it[0] in this }?.get(1) ?: "Firefox" ``` ## Test ``` fun String.f(): String = "Tr|IE_E|Edge_P|Opera_mi|Chromium_C|Chrome_A|Safari".split("_").map{it.split("|")}.firstOrNull{it[0] in this}?.get(1)?:"Firefox" data class Test(val input: String, val output: String) val tests = listOf( Test( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4", "Safari" ), Test( "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko", "IE" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8", "Safari" ), Test( "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393", "Edge" ), Test( "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063", "Edge" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (Windows NT 6.1; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko", "IE" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (X11; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0", "Firefox" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.2.5 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.5", "Safari" ), Test( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/59.0.3071.109 Chrome/59.0.3071.109 Safari/537.36", "Chromium" ), Test( "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko", "IE" ), Test( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30", "Safari" ), Test( "Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/52.0", "Firefox" ), Test( "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0", "Firefox" ), Test( "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0", "Firefox" ), Test( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/603.2.5 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.5", "Safari" ), Test( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 OPR/46.0.2597.57", "Opera" ), Test( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36 OPR/46.0.2597.32", "Opera" ), Test( "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko", "IE" ), Test( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; Trident/5.0)", "IE" ), Test( "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)", "IE" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:54.0) Gecko/20100101 Firefox/54.0", "Firefox" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8", "Safari" ), Test( "Mozilla/5.0 (Windows NT 6.1; rv:52.0) Gecko/20100101 Firefox/52.0", "Firefox" ), Test( "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/58.0.3029.110 Chrome/58.0.3029.110 Safari/537.36", "Chromium" ), Test( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 OPR/46.0.2597.39", "Opera" ), Test( "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko", "IE" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Chrome" ), Test( "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0", "Firefox" ), Test( "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0", "Firefox" )) fun main(args: Array<String>) { val answers = tests .map { (i, o) -> Triple(i, o, i.f()) } val t = answers .groupBy { it.second } .mapValues { it.value.groupBy { it.second == it.third }.mapValues { it.value.size } } for (f in t) { println(f) } println(answers.groupBy { it.second == it.third }.mapValues { it.value.size }) } ``` ## TIO [TryItOnline](https://tio.run/##5Vptb+I4EP7OrxjxKZE4Y+cN0h676q2422q3y+rKbVc6naIUAlgNCUqcbncLv71n54XSktI3SpI24gNxMs7j8XiembHPfOZS76o2ijw4ZgH1xmgkyXvpf+hc1fvB/LBrdefd4dixvs57MyewrSmdf5gE/pRGU+tD8texDubH9sgOaB2FM5cyqW7VZTS1Z5eUZS3zurxAIxqErBd8iVyXP/oX/wfUAzah4eI9GjtMIvL7vfqfNHBG/kX9qja0mQ0D1w5D6Dshk85tlwvMIpahbIBo8iO20ibXaqKRcYEQOuBS/sWRVIP0ijta3mVX/cj/RV3XbuoIg3RCvaH/I4QvfSAY4X3gDYa2DxeGJsPBbOY6J87pJ8qautpCqgHSp4/9o88N/q0zB/5yBme+DIlmmrqJMFJxiyBCdEi0lIrVG+swEqn68oHceBTwI3tAPeaHk3049JjjAm+A3jF85+OwiGLprwq+gVWkIC0X/zcnCKnvNfn8cewZ8lQiD3pqwE+Fvm4yvRNhMsH5nq4hLCe4mgommP8IpEbeFA/z4GSLYAt4DETKBUd9LQuKWEa54X8nfOo/Uy+6gIu2YZVd2zHcf04jj0U3YZdlHZVbfXes+X5Ah47Hmi3hlrgeCRF6vEabh+Sw+yJLBhGluKm8j12Myszus4OSdgxcMTlwXDirG+usrqL2/ayurLI6l9gJqy91Xl471t6OHXNPhpQW1lDLvIkbRM7SJBoimmqqeaMQL5QhnDHEEExFQ+1WpVSvxKrXVG4zRq7udUR0bGxf95vNH5c9x1kznXLlCSXAcSN/KlXwQkqUz1WE/NcykOJUeAcUZRMUpRgK16sc0ZG8iE5B+qPrNPoLRHRPz4iTvBSy4ucqbWAzh0uw+cB54J1tN+WrWJZagpD6NqYds84W4zIDi7kkREGtduGZnVrtcrO27sYIR3evH1v1YkLgZRNTPQvbiiCyDWXmIuDkU7ymb4AiHu4ESrkp/ZYLqloJofy098i09XXETGuabhuVKnLcbSHQ+/p3U4uLN7rZQnorbyTxjnm5BnJ7Am6NQ1VedBwGUt7y3l9RHn210LTj0HabO5BYKzwkxG9nv/fB+evT4Q786cxm9NR19uHo+LALZurmrg0XX1usLm5W7+Qt2+oD4JAdwtlci8Rl3YAiFdnQM0qVN1Uj4d9i9ewGFz6DILdUPdtdqKiauwgVc8i+70eDSdGbKIJElddOosttaYKNwkMWUsVcPvHM6ibPrO68orUdOHItPnI9takn2cE43IODILB//p6cXn4nw2X8rjjDbHvhD06Q0ElOMy/7EEer4RIk2gA+bb+9E+ucz3B83wAqznHLsFh2w3gHaVfXXYwDP5r98ZN3I85oOwPfG6Yi2Re+2W7khMkL5+J/rkynI27YhAZcPl8spL8cWKS9j/wApFF87jsbqrhmfPDM9aSRHDcl72aNKfjnfV+uLa7+Bw) ## Edits * -3 [jrtapsell](https://codegolf.stackexchange.com/users/73772) - Swapped destructuring for array access * -2 [jrtapsell](https://codegolf.stackexchange.com/users/73772) - Replaced contains with in ]
[Question] [ Golf the leaderboard of this question (id=111735). Your program should issue **one** HTTP or HTTPS request to StackExchange API, parse it and present to user in form similar to a typical [Leaderboard Snippet](http://meta.codegolf.stackexchange.com/questions/5139/leaderboard-snippet) Sample output (for the question [47338](https://codegolf.stackexchange.com/questions/47338) instead of this): ``` Leaderboard Author Language Size 1. FryAmTheEggman Pyth 19 2. Peter Taylor CJam 24 3. Martin Ender CJam 27 3. Peter Taylor GolfScript 27 5. randomra J 32 5. Optimizer CJam 32 7. Timtech TI-Basic 83/84 40 8. mollmerx k 41 9. Sp3000 ><> 45 10. Sherlock9 Ruby 47 11. Martin Ender Mathematica 49 12. Alex A. Julia 57 13. Sp3000 Python 2 58 14. Zgarb Haskell 68 15. Timtech GML 76 16. Jakube Python 2 79 16. nimi Haskell 79 18. coredump Common Lisp 91 19. Jim Large Ruby 92 Winners by Language Language User Score Python 2 Sp3000 58 CJam Peter Taylor 24 Julia Alex A. 57 TI-Basic 83/84 Timtech 40 ><> Sp3000 45 Haskell Zgarb 68 GolfScript Peter Taylor 27 Common Lisp coredump 91 Pyth FryAmTheEggman 19 k mollmerx 41 J randomra 32 Ruby Sherlock9 47 Mathematica Martin Ender 49 GML Timtech 76 ``` **Note the repeated ranks 3, 5 and 16. Maybe I'll even add a special non-competing answer just to force correct, non-simplified handing of the score duplicates.** The output should consist of: 1. The line "Leaderboard" 2. The line "\tAuthor\tLanguage\tSize" 3. For each answer, tab-separated line of rank and a `.`, then answer author name, then language name, then score; in ascending order for score 4. The line "Winners by Language" 5. The line "Language\tUser\tScore" 6. For each used language, tab-separated language name, author of the lower score answer and the score In other words, something like as if one copies and pastes result of the leaderboard snippet of this question to a text file (without "\tLink" things). See also the [reference implementation in Python](https://codegolf.stackexchange.com/a/111736/7773). ## Rules * No network access apart from one API request to `api.stackexchange.com` * No usage of API features or languages that appeared after the submission of this question. * First line of the answer post should be Leaderboard-compatible. If it breaks the leaderboard script attached to the question then answer is non-competing. * If newly added answer renders some existing answer broken then the author of the old answer should fix it (or it becomes non-competing). * Links to languages, striked out scores, etc. should be handleded. * Ranks should be handled like in the snippet (e.g. equal score => equal rank => gap in ranks). Accepted answer is the answer with the lowest score after sufficient amount of inactivity (minimum 1 month). ## Good idea * To test with question IDs 47338 (for duplicate score handling + striked out score handling) and 17005 (for links handling). This bumps the answer from Valid to Good and protects from breaks from later submissions. * To include output examples both for this and for overridden ID versions. ## Not necessary * Handling of more than 100 answers (limit of API for single request) * Handling of comment overrides * Sorting of "Winners by Language" section * Discrimination of competing and broken answers ## Leaderboard ``` var QUESTION_ID=111735,OVERRIDE_USER=7773;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Python 3, ~~860~~ 856 bytes Golfed slightly, just to bootstrap the leaderboard and provide some template for other golfers: ``` import json,re,html as h,requests as r p=print u=h.unescape;a=[];n={} for i in json.loads(r.get("https://api.stackexchange.com/2.2/questions/111735/answers?page=1&pagesize=100&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe").text)["items"]: m=re.match(r'<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)',i["body"].splitlines()[0]);l=u(m.group(1));t=u(i["owner"]["display_name"]);s=m.group(2);a.append((t,l,s)) if l not in n: n[l]=[] n[l].append((t,s)) p("Leaderboard\n\tAuthor\tLanguage\tSize") z=0;y=None for i in enumerate(sorted(a,key=lambda x:x[2])): if y==i[1][2]:z+=1 else:z=0;y=i[1][2] p("%d.\t%s\t%s\t%s"%(i[0]+1-z,i[1][0],i[1][1],i[1][2])) p("Winners by Language\nLanguage\tUser\tScore") for i in n.keys(): n[i].sort(key=lambda x:x[1]) print("%s\t%s\t%s"%(i,n[i][0][0],n[i][0][1])) ``` Indented with tabs. The last `print` is deliberately not replaced by `p` to create a score tie with the [Mathematica answer](https://codegolf.stackexchange.com/a/112195/7773). Ungolfed: ``` import json import re import html import requests url="https://api.stackexchange.com/2.2/questions/111735/answers?page=1&pagesize=100&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe" data=json.loads(requests.get(url).text) answers=[] languages={} for i in data["items"]: header=i["body"].splitlines()[0] m=re.match(r'<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)', header) lang=html.unescape(m.group(1)) author=html.unescape(i["owner"]["display_name"]) score=m.group(2) answers.append((author, lang, score)) if lang not in languages: languages[lang]=[] languages[lang].append((author, score)) answers.sort(key=lambda x:x[2]) print("Leaderboard") print("\tAuthor\tLanguage\tSize") rankadj=0 prevscore=None for i in enumerate(answers): if prevscore == i[1][2]: rankadj+=1 else: rankadj=0 prevscore=i[1][2] print("%d.\t%s\t%s\t%s" % (i[0]+1-rankadj, i[1][0], i[1][1], i[1][2])) print("Winners by Language") print("Language\tUser\tScore") for i in languages.keys(): w=languages[i] w.sort(key=lambda x:x[1]) print("%s\t%s\t%s" % (i, w[0][0], w[0][1])) ``` Note: it does not yet handle links correctly, so fails for, for example, question [17005](https://codegolf.stackexchange.com/questions/17005). [Answer] # Perl + Mojolicious, ~~468~~ ~~456~~ ~~469~~ 504 bytes Using [Mojolicious](https://metacpan.org/pod/ojo) library. ``` use v5.10;use ojo;while(@i=@{(g("http://api.stackexchange.com/2.2/questions/111735/answers?site=codegolf&filter=withbody&page=".++$p)->json//{})->{items}}){push@r,[$_->{owner}{display_name},(($h=x($_->{body})->at("h1,h2")||next)->at("a")||$h)->text=~/\s*([^,]+)\s*/,$h->text=~/(\d+)[^\d]*$/]for@i}$,=" ";say"Leaderboard ",Author,$l=Language,Size;say+(++$i,$s{@$_[2]}//=$i).".",@$_ for@r=sort{@$a[2]-@$b[2]}@r;%h=map{@$_[1],$_}reverse@r;say"Winners by $l $l",User,Score;say$_,$h{$_}[0],$h{$_}[2]for keys%h ``` Ungolfed: ``` use v5.10; use ojo; my @r; while (my @i = @{ (g("http://api.stackexchange.com/2.2/questions/111735/answers?site=codegolf&filter=withbody&page=" . ++$p)->json // {})->{items} }) { my $h = x($_->{body})->at("h1,h2") or next; push(@r, [$_->{owner}{display_name}, ($h->at("a") || $h)->text =~ /\s*([^,]+)\s*/, $h->text =~ /(\d+)[^\d]*$/]) for @i; } $, = "\t"; my %s; say("Leaderboard\n", "Author", (my $l = "Language"), "Size"); say((++$i, $s{$_->[2]} //= $i) . ".", @$_) for @r = sort { $a->[2] <=> $b->[2] } @r; my %h = map { $_->[1] => $_ } reverse(@r); say("Winners by $l\n$l", "User", "Score"); say($_, $h{$_}[0], $h{$_}[2]) for keys(%h); ``` [Answer] # Bash + JQ, 399 bytes Note, this can almost certainly be golfed further, by optimizing the `jq` expression logic. **Golfed** ``` curl api.stackexchange.com/2.2/questions/111735/answers?site=codegolf\&filter=withbody|zcat|jq -r '[.items[]|{o:.owner.display_name}+(.body|capture("^<h1>(?<l>.*?),.*?(?<b>\\d*)\\D*</h"))]|sort_by(.b|tonumber)|("Leaderboard\n\tAuthor\tLanguage\tSize",(keys[] as $i|.[$i]|"\($i+1).\t"+.o+"\t"+.l+"\t"+.b),"Winners by Language\nLanguage\tUser\tScore",(group_by(.l)|.[]|min_by(.b)|.l+"\t"+.o+"\t"+.b))' ``` **Sample Output** ``` Leaderboard Author Language Size 1. zeppelin Bash + JQ 399 2. Tom JavaScript ES6 454 3. Denis Ibaev Perl 456 4. Vi. Python 3 860 Winners by Language Language User Score Bash + JQ zeppelin 399 JavaScript ES6 Tom 454 Perl Denis Ibaev 456 Python 3 Vi. 860 ``` [Answer] # Mathematica, ~~852~~ 856 bytes Uses the built-in `JSONTools` package. This isn't the kind of thing Mathematica's meant to be used for...so I used it! ``` p=Print;S=StringRiffle;L=Length;r=Range;out=Association@JSONTools`FromJSON[Import["http://api.stackexchange.com/2.2/questions/111735/answers?site=codegolf&filter=withbody"]];l={};i=Association/@(out["items"]); (f=("body"/.i)[[#]];h=StringPosition[f,{"<h1>","</h1>"}];a="display_name"/.("owner"/.i)[[#]];s=StringSplit[StringTake[f,{h[[1]][[2]]+1,h[[2]][[1]]-1}],{",","<a>","</a>",">","<s>","</s>"," bytes","<strike>","</strike>"}];AppendTo[l,{a,s[[1]],ToExpression@s[[-1]]}])&/@r@L["body"/.i];l=SortBy[l,Last];o=r@L@l;If[l[[#]][[3]]==l[[#-1]][[3]],o[[#]]=o[[#-1]]]&/@r[2,L@l]; p@"Leaderboard" p@"\tAuthor\tLanguage\tSize" For[i=1,i<=L@l,i++,p[ToString@o[[i]]<>"."<>S[l[[i]][[#]]&/@r@3,"\t"]]] l=SortBy[l,{#[[2]],#[[3]]}&];l=DeleteDuplicatesBy[l,#[[2]]&]; p@"Winners by Language" p@"Language\tUser\tScore" For[i=1,i<=L@l,i++,p[S[l[[i]][[#]]&/@{2,1,3},"\t"]]] ``` ]
[Question] [ **ISO Paper Sizes Defined:** The A series paper sizes are defined by the following requirements: ``` The length divided by the width is the square root of 2. The A0 size has an area of 1 unit. Each subsequent size A(n) is defined as A(n-1) cut in half parallel to its shorter sides. ``` [![enter image description here](https://i.stack.imgur.com/tDQjn.gif)](https://i.stack.imgur.com/tDQjn.gif) **Task:** given an input `f[n]` output A0 divided into `n` subdivisions. **Test cases:** `f[1]` to `f[12]`: [![enter image description here](https://i.stack.imgur.com/Ji01L.gif)](https://i.stack.imgur.com/Ji01L.gif) *Here, A0 is given by* `f[1]`*, but this indexing isn't essential.* **Winning criteria:** The shortest code in bytes wins. [Answer] ## JavaScript (ES6) + HTML, ~~96~~ 94 + 34 = ~~130~~ 128 bytes ``` f=(n,w=297,h=210)=>n--&&f(n,h<w?w/2:w,h<w?h:h/2,(C=c.getContext`2d`).rect(0,0,w,h),C.stroke()) f(8) ``` ``` <canvas id=c width=300 height=300> ``` [Answer] # BBC BASIC 49 ASCII characters **Tokenised filesize 44 bytes** ``` I.n:F.i=0TOn:RECTANGLE0,0,1189>>i/2+.5,841>>i/2N. ``` Much shorter than before! I always forget about the bitshift operators in BBC BASIC for windows as they weren't available on my old computer back in the day. # BBC BASIC 63 ASCII characters **Tokenised filesize 58 bytes** Dowload interpreter at <http://www.bbcbasic.co.uk/bbcwin/download.html> ``` A%=841C%=1189d=4I.n:F.i=0TOn:RECTANGLE0,0,C%,A%:d!^B%/=2d=-d:N. ``` Uses zero indexing, which I prefer. Thus 0 outputs the paper for A0, 1 outputs A0 divided into a pair of A1s, etc. It is necessary to alternate between halving the X and Y coordinates, but doing that in an array would have cost too many bytes. Instead I use the fact that BBC basic has a block of static integer variables `A%..Z%` of 4 bytes each stored in contiguous memory. I store the X and Y values in `A%` and `C%` and access using the pointer to `%B` modified by the value of d, which alternates between `4` and `-4`. **Ungolfed** ``` A%=841 C%=1189 d=4 INPUTn FORi=0TOn RECTANGLE0,0,C%,A% d!^B%/=2 d=-d NEXT ``` **Output** [![enter image description here](https://i.stack.imgur.com/4TGQ9.png)](https://i.stack.imgur.com/4TGQ9.png) [Answer] # Mathematica, ~~87~~ 85 bytes Thanks @martin for 1 byte. ``` Graphics@{EdgeForm@Thin,White,Rectangle[#,0{,}]&/@NestList[Sort[#/a]&,{1,a=√2},#]}& ``` [Answer] ## JavaScript (ES6)/SVG (HTML5), 170 bytes ``` a=prompt();document.write('<svg width=297 height=210>');for(w=297,h=210;a--;h>w?h/=2:w/=2)document.write(`<rect fill=none stroke=#000 x=0 y=0 width=${w} height=${h} />`); ``` Uses 1-based indexing. ]
[Question] [ Partition an `n X n` square into multiple non-congruent integer-sided rectangles. `a(n)` is the least possible difference between the largest and smallest area. ``` ___________ | |S|_______| | | | L | | |_|_______| | | | | | |_____|___| |_|_________| (fig. I) ``` The largest rectangle (`L`) has an area of `2 * 4 = 8`, and the smallest rectangle (`S`) has an area of `1 * 3 = 3`. Therefore, the difference is `8 - 3 = 5`. **Given an integer `n>2`, output the least possible difference.** All known values of the sequence at the time of posting: ``` 2, 4, 4, 5, 5, 6, 6, 8, 6, 7, 8, 6, 8, 8, 8, 8, 8, 9, 9, 9, 8, 9, 10, 9, 10, 9, 9, 11, 11, 10, 12, 12, 11, 12, 11, 10, 11, 12, 13, 12, 12, 12 ``` So `a(3)=2`, `a(4)=4`, ... [**OEIS A276523**](http://oeis.org/A276523) [Related](https://codegolf.stackexchange.com/questions/102012/piet-mondrians-puzzle) - this related challenge allows non-optimal solutions, has time constraints, and is not code-golf. *For more information, watch [this video by Numberphile](https://www.youtube.com/watch?v=49KvZrioFB0)* [Answer] # Befunge, 708 bytes ``` p&>:10p1-:>20p10g:20g\`v`\g02:-1\p00+1g<>g-#v_10g:*30p"~":40p50p060p070p$>^ 1#+\#1<\1_^# !`0::-1$ _:00g3p\:00g2p00^^00:>#: >>:2-#v_$30p50p60p70g1-70p ^<<<<<:#<<<<<<$$$_v#:!g87g78g79$ _v#!\-1:g88$<_ 98p87g97g*00 v:+!\`*84g++7< ^>$1-:77p1g:2g\3g1>78p97p87p10g97g->88p10g87g-0^!\-1:g89_v#-!\_$1-:v>/88g+7^ ^|!-3$< >\87g/88g+77++p:#v_$ ^>:5->v ^+g89%g78:\g77:-1<>98g88g48*577g387g97g98g88v ^>77g87g97v:^g78\+g< ^ v-4:_$77p88p98p:97p\:87p*^^g79g7>#8\#$_40pv5+"A"g77g< ^14g88g89g<>:87g%98^ ^v_$88p98p97p87p:77p60g50g-:40g\`#^_$$>>>>>>> >#4!_::80p2g\3g*:90p30g`!v>>>#@>#.>#g^#0 ^v:g06p03:-g09\2:g03g05g06_^^_7#<0#<g#<3#<1#<<`g04_$00g1->:#-8#10#\g#1`#:_>$ ^>90g\-:0`*+:60p50g:90g-:0`*-:50p-80g70g:1+70p1p\!^ ``` [Try it online!](http://befunge.tryitonline.net/#code=cCY+OjEwcDEtOj4yMHAxMGc6MjBnXGB2YFxnMDI6LTFccDAwKzFnPD5nLSN2XzEwZzoqMzBwIn4iOjQwcDUwcDA2MHAwNzBwJD5eCjEjK1wjMTxcMV9eIyAhYDA6Oi0xJCAgXzowMGczcFw6MDBnMnAwMF5eMDA6PiM6CgoKPj46Mi0jdl8kMzBwNTBwNjBwNzBnMS03MHAKXjw8PDw8OiM8PDw8PDwkJCRfdiM6IWc4N2c3OGc3OSQgIF92IyFcLTE6Zzg4JDxfIDk4cDg3Zzk3ZyowMCB2OishXGAqODRnKys3PApePiQxLTo3N3AxZzoyZ1wzZzE+NzhwOTdwODdwMTBnOTdnLT44OHAxMGc4N2ctMF4hXC0xOmc4OV92Iy0hXF8kMS06dj4vODhnKzdeCl58IS0zJDwgICA+XDg3Zy84OGcrNzcrK3A6I3ZfJApePjo1LT52ICAgXitnODklZzc4OlxnNzc6LTE8Pjk4Zzg4ZzQ4KjU3N2czODdnOTdnOThnODh2IF4+NzdnODdnOTd2Ol5nNzhcK2c8Cl4gdi00Ol8kNzdwODhwOThwOjk3cFw6ODdwKl5eZzc5Zzc+IzhcIyRfNDBwdjUrIkEiZzc3ZzwgXjE0Zzg4Zzg5Zzw+Ojg3ZyU5OF4KXnZfJDg4cDk4cDk3cDg3cDo3N3A2MGc1MGctOjQwZ1xgI15fJCQ+Pj4+Pj4+CiA+IzQhXzo6ODBwMmdcM2cqOjkwcDMwZ2Ahdj4+PiNAPiMuPiNnXiMwCl52OmcwNnAwMzotZzA5XDI6ZzAzZzA1ZzA2X15eXzcjPDAjPGcjPDMjPDEjPDxgZzA0XyQwMGcxLT46Iy04IzEwI1xnIzFgIzpfPiQKXj45MGdcLTowYCorOjYwcDUwZzo5MGctOjBgKi06NTBwLTgwZzcwZzoxKzcwcDFwXCFe&input=Ng) This is obviously not going to win any awards for size, but it's actually reasonably fast considering it's a basic bruce force implementation in an esoteric language. On the Befunge reference interpreter it can handle up to n=6 in a couple of seconds. With a compiler it can handle up to n=8 before it starts getting sluggish; n=9 takes a couple of minutes and n=10 is close on 2 hours. In theory the upper limit is n=11 before we run out of memory (i.e. there's not enough space left in the playfield to fit a larger square). However, at that point, the time taken to calculate the optimal solution is probably longer than anyone would be willing to wait, even when compiled. The best way to see how the algorithm works is by running it in one of the Befunge "visual debuggers". That way you can watch as it attempts to fit the various rectangle sizes into the available space. If you want to "fast forward" to the point where it has a good match, you can put a breakpoint on the `4` in the sequence `$_40p` near the middle of the tenth line (9 if zero-based). The value at the top of the stack at that point is the current area difference. Below is an animation showing the first few frames of this process for n=5: ![Animation showing the rectangle fitting process](https://i.stack.imgur.com/m291H.gif) Each distinct rectangle is represented by a different letter of the alphabet. However, note that the final rectangle is never written out, so that section of the square will just be blank. I've also written a debug version of the code that outputs the current layout each time it finds a new best match ([Try it online!](http://befunge.tryitonline.net/#code=cCY+OjEwcDEtOj4yMHAxMGc6MjBnXGB2YFxnMDI6LTFccDAwKzFnPD5nLSN2XzEwZzoqMzBwIn4iOjQwcDUwcDA2MHAwNzBwJD5eCjEjK1wjMTxcMV9eIyAhYDA6Oi0xJCAgXzowMGczcFw6MDBnMnAwMF5eMDA6PiM6CgoKPj46Mi0jdl8kMzBwNTBwNjBwNzBnMS03MHAKXjw8PDw8OiM8PDw8PDwkJCRfdiM6IWc4N2c3OGc3OSQgIF92IyFcLTE6Zzg4JDxfIDk4cDg3Zzk3ZyowMCB2OishXGAqODRnKys3PApePiQxLTo3N3AxZzoyZ1wzZzE+NzhwOTdwODdwMTBnOTdnLT44OHAxMGc4N2ctMF4hXC0xOmc4OV92Iy0hXF8kMS06dj4vODhnKzdeCl58IS0zJDwgICA+XDg3Zy84OGcrNzcrK3A6I3ZfJApePjo1LT52ICAgXitnODklZzc4OlxnNzc6LTE8Pjk4Zzg4ZzQ4KjU3N2czODdnOTdnOThnODh2IF4+NzdnODdnOTd2Ol5nNzhcK2c8Cl4gdi00Ol8kNzdwODhwOThwOjk3cFw6ODdwKl5eZzc5Zzc+IzhcIyRfNDB2djUrIkEiZzc3ZzwgXjE0Zzg4Zzg5Zzw+Ojg3ZyU5OF4KXnZfJDg4cDk4cDk3cDg3cDo3N3A2MGc1MGctOjQwZ1xgI15fJCQ+Pj4+PiA+CiA+IzQhXzo6ODBwMmdcM2cqOjkwcDMwZ2Ahdj4+PiNAPiMuPiNnXiMwCl52OmcwNnAwMzotZzA5XDI6ZzAzZzA1ZzA2X15eXzcjPDAjPGcjPDMjPDEjPDxgZzA0XyQwMGcxLT46Iy04IzEwI1xnIzFgIzpfPiQKXj45MGdcLTowYCorOjYwcDUwZzo5MGctOjBgKi06NTBwLTgwZzcwZzoxKzcwcDFwXCFePiIgPSAtIjYwZy4sLDUwZy4sLDQwZy4gLCwKICAgICAgICAgICAgIHY8ODQ6ZysrNzdnODg6LTE8ZzAxcDg4Oi0xPGcwMTw+NTUrOjosXgogICAgICAgICAgICAgPiotISIhIiorLDQ4Kiw6I15fJDU1Kyw6PiNeXyRwPl4&input=Ng)). For the smaller sizes, the first match is often the optimal solution, but once you get past n=6 you'll likely get to see several valid but non-optimal layouts before it settles on the final solution. The best layout found for n=10 looks like this: ``` H F F F A A A C C I H F F F A A A C C I H J G G A A A C C I H J G G A A A C C I H J D D D D D C C I H J D D D D D C C I H J K K K K K K K I H J B B B E E E E I H J B B B E E E E I H J B B B L L L L L 12 - 4 = 8 ``` [Answer] # CJam, 178 ``` ri_1a*a*L{_:+1&{_[3{_\zW%}*]{_z}%:e<_@={:A0=_1#:X0<{;A1>j}{X>0+0#AzX=0+0#,\,m*1ff+{[_$\~1a*0aX*\+a*A\..-_])s'-&{;}&}%{~j\:X;{Xa&!},Xaf+:$~}%_&}?}{j}?}{;La}?}j{,(},{::*$)\0=-}%:e< ``` [Try it online](http://cjam.aditsu.net/#code=ri_1a*a*L%7B_%3A%2B1%26%7B_%5B3%7B_%5CzW%25%7D*%5D%7B_z%7D%25%3Ae%3C_%40%3D%7B%3AA0%3D_1%23%3AX0%3C%7B%3BA1%3Ej%7D%7BX%3E0%2B0%23AzX%3D0%2B0%23%2C%5C%2Cm*1ff%2B%7B%5B_%24%5C~1a*0aX*%5C%2Ba*A%5C..-_%5D)s'-%26%7B%3B%7D%26%7D%25%7B~j%5C%3AX%3B%7BXa%26!%7D%2CXaf%2B%3A%24~%7D%25_%26%7D%3F%7D%7Bj%7D%3F%7D%7B%3BLa%7D%3F%7Dj%7B%2C(%7D%2C%7B%3A%3A*%24)%5C0%3D-%7D%25%3Ae%3C&input=4). It's veeery slow though, I wouldn't recommend going above 6. To verify that it's really doing the work, you can check this slightly [modified program](http://cjam.aditsu.net/#code=ri_1a*a*L%7B_%3A%2B1%26%7B_%5B3%7B_%5CzW%25%7D*%5D%7B_z%7D%25%3Ae%3C_%40%3D%7B%3AA0%3D_1%23%3AX0%3C%7B%3BA1%3Ej%7D%7BX%3E0%2B0%23AzX%3D0%2B0%23%2C%5C%2Cm*1ff%2B%7B%5B_%24%5C~1a*0aX*%5C%2Ba*A%5C..-_%5D)s'-%26%7B%3B%7D%26%7D%25%7B~j%5C%3AX%3B%7BXa%26!%7D%2CXaf%2B%3A%24~%7D%25_%26%7D%3F%7D%7Bj%7D%3F%7D%7B%3BLa%7D%3F%7Dj%7B%2C(%7D%2C%3Ap&input=4) that prints all the possible partitions (each partition is shown as an array of rectangle dimension pairs). ]
[Question] [ Given consecutive side lengths `s1, s2, s3... s_n` of an n-gon inscribed in a circle, find its area. You may assume that the polygon exists. In addition, the polygon will be convex and not self-intersecting, which is enough to guarantee uniqueness. Built-ins that specifically solve this challenge, as well as built-in functions that calculate the circumradius or circumcenter, are banned (this is different from a previous version of this challenge). Input: The side lengths of the cyclic polygon; may be taken as parameters to a function, stdin, etc. Output: The area of the polygon. The answer should be accurate to 6 decimal places and must run within 20 seconds on a reasonable laptop. This is code golf so shortest code wins! Specific test cases: ``` [3, 4, 5] --> 6 [3, 4, 6] --> 5.332682251925386 [3, 4, 6, 7] --> 22.44994432064365 [5, 5, 5, 5] --> 25 [6, 6, 6, 6, 6] --> 61.93718642120281 [6.974973020933265, 2.2393294197257387, 5.158285083300981, 1.4845682771595603, 3.5957940796134173] --> 21.958390804292847 [7.353566082457831, 12.271766915518073, 8.453884922273897, 9.879017670784675, 9.493366404245332, 1.2050010402321778] --> 162.27641678140589 ``` Test case generator: ``` function randPolygon(n) { var left = 2 * Math.PI; var angles = []; for (var i = 0; i < n - 1; ++i) { var r = Math.random() * left; angles.push(r); left -= r; } angles.push(left); var area = 0; var radius = 1 + Math.random() * 9; for (var i = 0; i < angles.length; ++i) area += radius * radius * Math.sin(angles[i]) / 2; var sideLens = angles.map(function(a) { return Math.sin(a / 2) * radius * 2; }); document.querySelector("#radius").innerHTML = radius; document.querySelector("#angles").innerHTML = "[" + angles.join(", ") + "]"; document.querySelector("#inp").innerHTML = "[" + sideLens.join(", ") + "]"; document.querySelector("#out").innerHTML = area; draw(angles); } function draw(angles) { var canv = document.querySelector("#diagram"), ctx = canv.getContext("2d"); var size = canv.width ctx.clearRect(0, 0, size, size); ctx.beginPath(); ctx.arc(size / 2, size / 2, size / 2, 0, 2 * Math.PI, true); ctx.stroke(); ctx.beginPath(); ctx.moveTo(size, size / 2); var runningTotal = 0; for (var i = 0; i < angles.length; ++i) { runningTotal += angles[i]; var x = Math.cos(runningTotal) * size / 2 + size / 2; var y = Math.sin(runningTotal) * size / 2 + size / 2; ctx.lineTo(x, y); } ctx.stroke(); } document.querySelector("#gen").onclick = function() { randPolygon(parseInt(document.querySelector("#sideLens").value, 10)); } ``` ``` <div id="hints"> <p><strong>These are to help you; they are not part of the input or output.</strong> </p> Circumradius: <pre id="radius"></pre> Angles, in radians, of each sector (this are NOT the angles of the polygon): <pre id="angles"></pre> </div> <hr> <div id="output"> Input: <pre id="inp"></pre> Output: <pre id="out"></pre> </div> <hr> <div id="draw"> Diagram: <br /> <canvas id="diagram" width="200" height="200" style="border:1px solid black"></canvas> </div> Number of side lengths: <input type="number" id="sideLens" step="1" min="3" value="3" /> <br /> <button id="gen">Generate test case</button> ``` [Answer] # Python 2, ~~195~~ 191 bytes ``` from math import* C=sorted(input());l,h=0,1/max(C) while h-l>2e-16:m=(l+h)/2;a=[asin(c*m)for c in C[:-1]];f=pi-sum(a);l,h=[l,m,h][sin(f)/m>C[-1]:][:2] print sum(sin(2*t)/l/l for t in a+[f])/8 ``` Uses a binary search to find the inverse diameter, then calculates the area of each segment by the angle/radius. It finds the radius by first summing all but the largest chord angle, and checking the remaining angle to the remaining chord. Those angles are then also used to compute the area of each segment. A segment's area can be negative, if it's angle is bigger than 180 degrees. We do a binary search over the inverse diameter so the domain is bounded and well-behaved. Readable implementation: ``` def segment_angles(line_segments, invd): return [2*math.asin(c*invd) for c in line_segments] def cyclic_ngon_area(line_segments): line_segments = list(sorted(line_segments)) lo, hi = 0, 1/max(line_segments) while hi - lo > 2e-16: mid = (lo + hi) / 2 angles = segment_angles(line_segments[:-1], mid) angles.append(2*math.pi - sum(angles)) if math.sin(angles[-1]/2) / mid > line_segments[-1]: lo = mid else: hi = mid return sum([math.sin(a)/lo/lo/8 for a in angles]) ``` [Answer] # PARI/GP, 182 bytes ``` A(v)=n=#s=vecsort(v);g=1^s;h=sum(k=1,n-1,asin(s[k]/S=s[n]))<Pi/2;g[n]-=2*h;d=solve(D=S,S/(vecsum(s)/2/S-1),sum(k=1,n,g[k]*asin(s[k]/D))-Pi*!h);sum(k=1,n,g[k]*s[k]*sqrt(d^2-s[k]^2))/4 ``` Using @alephalpha's hints that global variables can be used and his improved chained assignments, significantly shorter code is possible. Also an unnecessary factor 8 in calculation of Dmax was removed. ## Version with comments ``` AreaCyclicPolygon(VectorofSidelenghts) = { my( s = vecsort(VectorofSidelenghts), \\ allows access to longest side \\ and loop over shorter sides n = #s, S = s[n], \\ assignment postponed into loop in golfed code g = vector(n,i,1), \\ Auxiliary vector of ones d, h = sum ( k=1, n-1, asin(s[k]/S)) < Pi/2, \\ determine whether the triangle \\ with longest side makes an angle > Pi. Dmax = S/sqrt(vecsum(s)/2/S - 1) \\ upper limit of diameter from asymptotic \\ expansion showing 1/sqrt(eps) dependency. \\ In "golfed" version sqrt can be ommitted \\ drastically overestimating Dmax; solve still works ); g[n] -= 2*h; \\ factor = -1 for largest triangle \\ when the polygon only occupies less than half of the circle d = solve ( D=s[n], Dmax, sum (k=1, n, g[k]*asin(s[k]/D)) - Pi*!h); \\ solve sum of angles equation \\ including special case of \\ large angle for longest side sum (k=1, n, g[k]*s[k]*sqrt(d^2 - s[k]^2))/4 \\ return value: use solution for d in sum \\ of triangle areas, again with potentially \\ negative contribution of triangle \\ with longest side }; ``` ## Examples ``` AreaCyclicPolygon([3,4,5]) 6.000000000000000000 AreaCyclicPolygon([3,4,6]) 5.3326822519253854377215978803358864040 AreaCyclicPolygon([0.25,0.25,0.499999]) 0.00012499968750010937502343751074219391159 AreaCyclicPolygon([5,5,5,5]) 25.000000000000000000000000000000000000 AreaCyclicPolygon([6,6,6,6,6]) 61.937186421202809219324431185989945578 AreaCyclicPolygon([1e6,1e6,2e6-1]) 999999375.00005468750292968783569307190 ``` ## Note on estimating the maximum diameter Regardless of whether the diameter (or equivalently the radius) is calculated using bisection or with a function for solving a non-linear equation (like PARI's solve here), a bracketing interval is required for the solution value. Trivially, the diameter cannot be smaller than the longest side. However, since the polygon can degenerate when the sum of the shorter sides approaches the longest side, the diameter of the polygon can become arbitrarily large. In order to estimate this diameter, it is sufficient to use a triangle as a model. From the well-known Heron formula for the area A one gets the radius $$ r(a,b,c) = \frac{a b c}{\sqrt{(a+b-c) (a-b+c) (-a+b+c) (a+b+c)}} $$ If one assumes a model triangle \$\left(\frac{1}{4},\frac{1}{4},\frac{1}{2}-\epsilon \right)\$ normalized to an approximate perimeter of 1 with a scaled length deficit \$\epsilon\$ of the longest side, then r becomes $$ r = \frac{\frac{1}{2}-\epsilon }{16 \sqrt{\left(\frac{1}{2}-\epsilon \right)^2 (1-\epsilon ) \epsilon }} $$ Assuming \$\epsilon\$ to be small, r can be expanded r in a series $$ r = \frac{1}{16 \sqrt{\epsilon }}+\frac{\sqrt{\epsilon }}{32}+\frac{3 \epsilon ^{3/2}}{128}+O\left(\epsilon ^{5/2}\right) $$ The leading term contains the singularity \$\frac{1}{\sqrt{\epsilon }}\$, which must be taken into account when calculating the upper bound. It doesn't matter whether you use the circumference or the longest side to scale back. Whether one computes \$\epsilon\$ as $$ \epsilon = \frac{a+b+c}{2 c}-1 = \frac{a+b-c}{2 c} $$ which is the **vecsum(s)/2/S - 1** in the program, or as $$ \epsilon = 1-\frac{2 c}{a+b+c} $$ makes no essential difference for small \$\epsilon\$. [Answer] # Octave, 89 bytes ``` r=sum(s=input(''));while sum(a=asin(s/2/r))<pi r*=1-1e-4;b=a;end;disp(sum(cos(b).*s/2*r)) ``` ## Explanation The angle `a` spanned by a segment of length `s` is `2*asin(s/2/r)`, given a circumradius `r`. Its area is `cos(a)*s/2*r`. ### Algorithm 1. Set `r` to something too large, such as the perimeter. 2. If the cumulated angle is smaller than `2pi`, reduce `r` and repeat step 2. 3. Calculate the area. ]
[Question] [ [Elixir](http://elixir-lang.org/) is a relatively new functional language, which I've taken a deep interest in. I'd like to get general tips about golfing in Elixir and learn techniques that can be applied to code-golf problems that are somewhat specific to Elixir in general. --- *Based on so many similar questions about [Python](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python), [Ruby](https://codegolf.stackexchange.com/questions/363/tips-for-golfing-in-ruby), [Javascript](https://codegolf.stackexchange.com/questions/2682/tips-for-golfing-in-javascript), etc. I'll also try to post tips as I learn more about the language.* [Answer] ### String and char arguments don't need spaces For example, `IO.puts"Hello, World!"` and `IO.puts'cat'` are valid programs. [Answer] ### Don't use the Pipe operator or parenthesis for calling methods ``` # With Pipe arg |> M.a |> M.b |> M.c # 24 Bytes arg|>M.a|>M.b|>M.c # 18 Bytes # With Parenthesis M.c(M.b(M.a(arg))) # 18 Bytes # Only Spaces M.c M.b M.a arg # 15 Bytes ``` [Answer] ## Inject code into strings Instead of concatenating something into a string, like: ``` "prefix"<>code<>"suffix" ``` You can use `#{}` to insert it into the string: ``` "prefix#{code}suffix" ``` This will save 3 bytes. [Answer] # Avoid arrow functions where possible ...and use the `&<func>(&1,&2...)` notation. For example: ``` each 0..25,fn x->IO.puts slice(concat(a,a),x,26) # 48 bytes each 0..25,&IO.puts slice(concat(a,a),&1,26) # 44 bytes ``` [Answer] ### Map Arguments don't need spaces either Like [LegionMammal978's answer](https://codegolf.stackexchange.com/a/65843/19584), you can leave out space when passing Map as an argument to a method: ``` IO.inspect%{a: 1,b: 2} ``` [Answer] # `use Bitwise` Say you want to import the module `Bitwise`, usually you would do: ``` import Bitwise ``` But there may be an alternative that works in some versions of Elixir: ``` use Bitwise ``` to save 3 bytes! Even better if your only using a bit wise operator once, you can do: ``` Bitwise.&&&() ``` `&&&` being one of the many bitwise operators useable. ]
[Question] [ ## Introduction The LaTeX typesetting system uses macros for defining accents. For example, the letter ê is produced by `\hat{e}`. In this challenge, your task is to implement an ASCII version of this functionality. ## Input Your input is a non-empty string of printable ASCII characters. It will not contain newlines. ## Output Your output is a string consisting of two lines. The first line contains accents, and the second line the characters they belong to. It is obtained from the input as follows (`A` denotes an arbitrary character): * Every `\bar{A}` is replaced by `A` with `_` on top of it. * Every `\dot{A}` is replaced by `A` with `.` on top of it. * Every `\hat{A}` is replaced by `A` with `^` on top of it. * **For a -10% bonus:** every `\tilde{A}` is replaced by `A` with `~` on top of it. * All other characters have a space above them. For example, the input ``` Je suis pr\hat{e}t. ``` results in the output ``` ^ Je suis pret. ``` ## Rules and scoring You can assume that the characters `\{}` only occur in the macros `\bar{}`, `\dot{}` and `\hat{}` (and `\tilde{}` if you go for the bonus). All macro arguments are exact one character long, so `\dot{foo}` and `\dot{}` will not occur in the input. The output can be a newline-separated string, or a list/pair of two strings. Any amount of trailing and preceding whitespace is allowed, as long as the accents are in the correct places. In particular, if there are no accents, the output can be a single string. You can write a full program or a function. The lowest byte count (after bonuses) wins, and standard loopholes are disallowed. ## Test cases Without bonus: ``` Input: No accents. Output: No accents. Input: Ch\hat{a}teau Output: ^ Chateau Input: Som\bar{e} \dot{a}cc\hat{e}nts. Output: _ . ^ Some accents. Input: dot hat\dot{h}a\hat{t}\hat{ }x\bar{x}dot Output: . ^^ _ dot hathat xxdot Input: \hat{g}Hmi\hat{|}Su5Y(\dot{G}"\bar{$}id4\hat{j}gB\dot{n}#6AX'c\dot{[}\hat{)} 6\hat{[}T~_sR\hat{&}CEB Output: ^ ^ . _ ^ . .^ ^ ^ gHmi|Su5Y(G"$id4jgBn#6AX'c[) 6[T~_sR&CEB ``` With bonus: ``` Input: Ma\tilde{n}ana Output: ~ Manana Input: \dot{L}Vz\dot{[}|M.\bar{#}0\hat{u}U^y!"\tilde{I} K.\bar{"}\hat{m}dT\tilde{$}F\bar{;}59$,/5\bar{'}K\tilde{v}R \tilde{E}X` Output: . . _ ^ ~ _^ ~ _ _ ~ ~ LVz[|M.#0uU^y!"I K."mdT$F;59$,/5'KvR EX` ``` [Answer] # Pyth, ~~51~~ ~~46~~ ~~45~~ ~~43~~ ~~41~~ 40 bytes I remove the curly braces and split at `\`, just like Reto Koradi's CJam answer does. The codes `bar`, `dot` and `hat` are recognized simply by the last decimal digit of the character code of the first character, modulo 3. I just add ~~`barf`~~ (RIP) `""""` to the first part and remove it in the end to save the code for handling the first part specially. ``` jtMsMCm,+@".^_"eChd*\ -ld4>d3c-+*4Nz`H\\ ``` [Try it online.](https://pyth.herokuapp.com/?code=jtMsMCm%2C%2B%40%22.%5E_%22eChd*%5C%20-ld4%3Ed3c-%2B*4Nz%60H%5C%5C&input=dot%20hat%5Cdot%7Bh%7Da%5Chat%7Bt%7D%5Chat%7B%20%7Dx%5Cbar%7Bx%7Ddot&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=jtMsMCm%2C%2B%40%22.%5E_%22eChd*%5C%20-ld4%3Ed3c-%2B*4Nz%60H%5C%5C&test_suite=1&test_suite_input=No+accents.%0ACh%5Chat%7Ba%7Dteau%0ASom%5Cbar%7Be%7D+%5Cdot%7Ba%7Dcc%5Chat%7Be%7Dnts.%0Adot+hat%5Cdot%7Bh%7Da%5Chat%7Bt%7D%5Chat%7B+%7Dx%5Cbar%7Bx%7Ddot%0A%5Chat%7Bg%7DHmi%5Chat%7B%7C%7DSu5Y%28%5Cdot%7BG%7D%22%5Cbar%7B%24%7Did4%5Chat%7Bj%7DgB%5Cdot%7Bn%7D%236AX%27c%5Cdot%7B%5B%7D%5Chat%7B%29%7D+6%5Chat%7B%5B%7DT%7E_sR%5Chat%7B%26%7DCEB&debug=0) [Answer] # Julia, ~~204~~ 184 bytes \* 0.9 = 165.6 ``` x->(r=r"\\(\w)\w+{(\w)}";t=[" "^endof(x)...];while ismatch(r,x) m=match(r,x);(a,b)=m.captures;t[m.offsets[1]-1]=a=="b"?'_':a=="d"?'.':a=="h"?'^':'~';x=replace(x,r,b,1)end;(join(t),x)) ``` This is an anonymous function that accepts a string and returns a tuple of strings corresponding to the top and bottom lines. The top line will have trailing whitespace. To call the function, give it a name, e.g. `f=x->...` Ungolfed: ``` function f(x::AbstractString) # Store a regular expression that will match the LaTeX macro call # with capture groups for the first letter of the control sequence # and the character being accented r = r"\\(\w)\w+{(\w)}" # Create a vector of spaces by splatting a string constructed with # repetition # Note that if there is anything to replace, this will be longer # than needed, resulting in trailing whitespace t = [" "^endof(x)...] while ismatch(r, x) # Store the RegexMatch object m = match(r, x) # Extract the captures a, b = m.captures # Extract the offset of the first capture o = m.captures[1] # Replace the corresponding element of t with the accent t[o-1] = a == "b" ? '_' : a == "d" ? '.' : a == "h" ? '^' : '~' # Replace this match in the original string x = replace(x, r, b, 1) end # Return the top and bottom lines as a tuple return (join(t), x) end ``` [Answer] # CJam, 53 bytes ``` Sl+'\/(_,S*\@{(i2/49-"_. ^"=\3>'}-_,(S*@\+@@+@@+\}/N\ ``` [Try it online](http://cjam.aditsu.net/#code=Sl%2B'%5C%2F(_%2CS*%5C%40%7B(i2%2F49-%22_.%20%5E%22%3D%5C3%3E'%7D-_%2C(S*%40%5C%2B%40%40%2B%40%40%2B%5C%7D%2FN%5C&input=Je%20suis%20pr%5Chat%7Be%7Dt.) Explanation: ``` S Leading space, to avoid special case for accent at start. l+ Get input, and append it to leading space. '\/ Split at '\. ( Split off first sub-string, which does not start with an accent. _, Get length of first sub-string. S* String of spaces with the same length. \ Swap the two. First parts of both output lines are now on stack. @ Rotate list of remaining sub-strings to top. { Loop over sub-strings. ( Pop first character. This is 'b, 'd, or 'h, and determines accent. i Convert to integer. 2/ Divide by two. 49- Subtract 49. This will result in 0, 1, or 4 for the different accents. "_. ^" Lookup string for the accents. = Get the correct accent. \ Swap string to top. 3> Remove the first 3 characters, which is the rest of the accent string and the '{. '}- Remove the '}. All the macro stuff is removed now. _,( Get the length, and subtract 1. This is the number of spaces for the first line. S* Produce the spaces needed for the first line. @\+ Bring accent and spaces to top, and concatenate them. @@+ Get previous second line and new sub-string without formatting to top, and concatenate them. @@+ Get previous first line and new accent and spacing to top, and concatenate them. \ Swap the two lines to get them back in first/second order. }/ End loop over sub-strings. N\ Put newline between first and second line. ``` [Answer] ## Haskell, 156 \* 0.9 = 140.4 bytes ``` g('\\':a:r)=(q,l):g s where q|a=='b'='_'|a=='d'='.'|a=='h'='^'|a=='t'='~';(_,_:l:_:s)=span(<'{')r g(a:b)=(' ',a):g b g""=[('\n','\n')] f=uncurry(++).unzip.g ``` Usage example: ``` *Main> putStr $ f "\\dot{L}Vz\\dot{[}|M.\\bar{#}0\\hat{u}U^y!\"\\tilde{I} K.\\bar{\"}\\hat{m}dT\\tilde{$}F\\bar{;}59$,/5\\bar{'}K\\tilde{v}R \\tilde{E}X`" . . _ ^ ~ _^ ~ _ _ ~ ~ LVz[|M.#0uU^y!"I K."mdT$F;59$,/5'KvR EX` ``` How it works: go through the input string character by character and build a list of pairs of characters, the left for the upper output string, the right for the lower output string. If a `\` is found, take the appropriate accent, else a space for the left element. Finally transform the list of pairs into a single string. [Answer] # Python 3, 203 bytes Without bonus: ``` l=list(input()) b=list(" "*len(l)) try: while 1:s=l.index("\\");t=l[s+1];del l[s+6];del l[s:s+5];b[s] = "b"==t and "_" or "d"==t and "." or "h"==t and "^" or "*"; except:print("".join(b)+"\n"+"".join(l)); ``` I really hope there is a shorter version. ]
[Question] [ **Revised formatting and instructions** Given a list of moves for a [Cracker Barrel peg board game](http://www.memory-improvement-tips.com/pegs.html), or as @Steveverrill stated, Peg Triangle Solitaire: ``` Game 1 Game 2 Game 3 1: 0 ,-1, -1 C, -1, -1 4, -1, -1 #starting point 2: 3, 1, 0 3, 7, C B, 7, 4 #jump_from, jump_over, jump_to 3: A, 6, 3 0, 1, 3 D, C, B 4: 8, 4, 1 6, 3, 1 5, 8, C 5: B, 7, 4 5, 2, 0 1, 4, 8 6: 2, 4, 7 C, 8, 5 E, 9, 5 7: D, C, B A, B, C 6, 3, 1 8: 9, 5, 2 D, C, B 2, 5, 9 9: 1, 3, 6 9, 5, 2 B, C, D 10: 0, 2, 5 1, 4, 8 9, 8, 7 11: 6, 7, 8 0, 2, 5 0, 1, 3 12: 5, 8, C 5, 8, C 3, 7, C 13: B, C, D B, C, D D, C, B 14: E, D, C E, D, C A, B, C ``` **Here is your task** * Write a program that takes a list of moves, each move has three arguments which are slots on the board (jump\_from, jump\_over, jump\_to). Move the peg from jump\_from to jump\_to and remove jump\_over. (If that is unclear then read the instructions linked at the top) * Print the board for each move + The direction of the move a.k.a. the arrow + The slot jumped from a.k.a. the `*` + The slot jumped to (if peg 3 was in slot 3, and jumped to slot 0, then print a 3 in slot 0) + print a `.` for any empty slots **How to play** -If you don't understand these rules then there is a link at the top. I've provided three different games that result in one peg remaining. The idea of the game is to start with one peg missing in the board and remove pegs until there is one left. A move is jumping over a peg into an empty slot and removing the peg you jumped over. Valid moves are diagonals and horizontal moves only. Example (assume slots 1, 2, 3, and 6 are open): > > 8 over 4 to 1 is valid > > > 8 over 7 to 6 is valid > > > 8 over 7 or 4 to 3 is invalid > > > B over 7 and 4 is invalid > > > Your output should look like the following. Each board printed is one move (Use hex instead of decimal since printing the board in decimal causes the last row to be too wide) ``` This is Game 1 from the move set at the top / 0 \ #This is the board with all slots filled / 1 2 \ / 3 4 5 \ / 6 7 8 9 \ / A B C D E \ / * \ #Move 1: remove the first peg which is 0 / 1 2 \ / 3 4 5 \ / 6 7 8 9 \ / A B C D E \ / 3 \ #Move 2: Move peg 3 from slot 3 over slot 1 to slot 0 / ↗ 2 \ Remove peg 1 from slot 1 / * 4 5 \ / 6 7 8 9 \ / A B C D E \ / 3 \ #Move 3 / . 2 \ / A 4 5 \ / ↗ 7 8 9 \ / * B C D E \ / 3 \ #Move 4 / 8 2 \ / A ↖ 5 \ / . 7 * 9 \ / . B C D E \ / 3 \ #Move 5 / 8 2 \ / A B 5 \ / . ↗ . 9 \ / . * C D E \ / 3 \ #Move 6 / 8 * \ / A ↙ 5 \ / . 2 . 9 \ / . . C D E \ / 3 \ #Move 7 / 8 . \ / A . 5 \ / . 2 . 9 \ / . D ← * E \ / 3 \ #Move 8 / 8 9 \ / A . ↖ \ / . 2 . * \ / . D . . E \ / 3 \ #Move 9: / * 9 \ Move peg 8 from slot 1 over slot 3 to slot 6 / ↙ . . \ Remove peg A / 8 2 . . \ / . D . . E \ / * \ #Move 10 / . ↘ \ / . . 3 \ / 8 2 . . \ / . D . . E \ / . \ #Move 11 / . . \ / . . 3 \ / * → 8 . \ / . D . . E \ / . \ #Move 12 / . . \ / . . * \ / . . ↙ . \ / . D 3 . E \ / . \ #Move 13 / . . \ / . . . \ / . . . . \ / . * → D E \ / . \ #Move 14 / . . \ / . . . \ / . . . . \ / . . E ← * \ ``` The `*` represents the most recent peg removed. That is why the board starts with a `*` at slot `0` instead of a `0`. `.` represents an empty slot. The slots stay in the same position but the pegs are numbered and move around so for the very last move `peg E moves from slot E over peg/slot D to slot C` The direction of the move is the unicode characters `u2190` through `u2199` This is code golf so lowest number of bytes wins. Good Luck! **If something is unclear don't hesitate to ask. I will do my best to clarify.** [Answer] # [Ruby](https://www.ruby-lang.org/) `-pa`, 181 bytes ``` $_=b||=+-s=(1..5).map{|i|"/ #{[*:A6310[-i]..?E][0,i]*' '} \\".center 13}*$/+$/ f,o,t=$F.map{|i|s=~/#{i}/} b.tr!(a='→↙↘*↖↗←',?.)?(b[t],b[o]=b[f],a[(o-f)/7]):$><<b b[f]=?* ``` [Try it online!](https://tio.run/##Ncy5boNAGATg/n@KiY3EYVhYY45Y3iBfeYn1KmIjW6KIsWxSRIaU1FGKHK/Hg4SQItIUo9GnOT/rl743HoSuazHxLsLijEU2e8pP17qoRz7GV@nMl3HIA@kVirFsq2TgFsoxYTbY7UbscX@s9mfwsHEMf2L4dHBLtxLG/f/LRbz642vR@A1pVp1vrFyYXfvetd9d@@V07UfXfnbtm@lmzM4sLSvlalkqoeVBubm0Su9g@4my58bdYqHpbxaZ0/cBPD6EQnAEtESMkFLMwGmFBDOaDj2hDdZY0S0iTIkjREwBpogoHkxKEVKsB7/GhrYY7E95qoryeOm9U/4L "Ruby – Try It Online") The score would be 169 if counted by characters. It's unfortunate that the arrow characters are 3 bytes each, but using them directly is shorter than every method I tried for generating their codepoints (which are irregularly spaced). ## Explanation The board, stored as a multiline string, is padded out to a rectangular grid with leading and trailing spaces on each line. Let \$f\$ and \$o\$ be the indices within this string of the slots being jumped from and over, respectively. Then the following table describes all jumps, independent of the specific slots involved: | Direction | \$o-f\$ | \$\left\lfloor(o-f)/7\right\rfloor\$ | | --- | --- | --- | | `←` | \$\phantom{1}{-2}\$ | \$-1\$ | | `→` | \$\phantom{-1}2\$ | \$\phantom{-{}}0\$ | | `↖` | \$-15\$ | \$-3\$ | | `↗` | \$-13\$ | \$-2\$ | | `↘` | \$\phantom{-{}}15\$ | \$\phantom{-{}}2\$ | | `↙` | \$\phantom{-{}}13\$ | \$\phantom{-{}}1\$ | Conveniently, we see that \$\left\lfloor(o-f)/7\right\rfloor\$ yields a unique value between \$-3\$ and \$2\$ for each jump direction, ideal for indexing into a string (`a`) containing the arrow characters. ##### Flags `-p`: Loop through the code for every line of input and implicitly print the contents of `$_` at the end of each iteration. `-a`: Form the array `$F` by splitting the input on spaces. ##### Line by line ``` $_=b||=+-s=(1..5).map{|i|"/ #{[*:A6310[-i]..?E][0,i]*' '} \\".center 13}*$/+$/ ``` Two boards are saved: `s` is the starting configuration (all slots filled) whereas `b` (shadowed by `$_`) is the current configuration. For each line \$i\in[1,5]\$ in `s`, slot numbers are generated by taking the first \$i\$ elements of a character range beginning with `0`, `1`, `3`, `6`, or `A` and always ending with `E`. Each line is padded with leading and trailing spaces (`.center 13`), the lines are joined by newlines (`*$/`), and a trailing newline is appended (`+$/`). On the first iteration only, `s` is cloned into `b` (`b||=+-s`). `$_` is set equal to `b` so that the board will be printed at the end of each iteration. Since `b` and `$_` point to the same string object, all subsequent operations on `b` affect `$_` too. ``` f,o,t=$F.map{|i|s=~/#{i}/} ``` Map the input slot numbers to indices in `s`, saving the results in `f` (jump\_from), `o` (jump\_over), and `t` (jump\_to). The mapping is as follows: `0 → 6, 1 → 19, 2 → 21, 3 → 32, 4 → 34, 5 → 36, 6 → 45, 7 → 47, 8 → 49, 9 → 51, A → 58, B → 60, C → 62, D → 64, E → 66`. ``` b.tr!(a='→↙↘*↖↗←',?.)?(b[t],b[o]=b[f],a[(o-f)/7]):$><<b ``` In `b`, replace the `*` and arrow character from the previous jump with `.`. The shouty `.tr!` modifies `b` in place, returning `nil` (falsey) on the first move (no previous jump so no replacements performed) and `b` (truthy) on all other moves. If it is the first move, print the board with all slots filled (`$><<b`). Otherwise, update the jump\_to slot with the peg from the jump\_from slot and set the jump\_over slot to the appropriate arrow character by indexing into `a` as described above. ``` b[f]=?* ``` Set the jump\_from slot to `*`, after which the board is implicitly printed. ]
[Question] [ ## Introduction The number 101 is a palindrome, since it reads the same backwards and forwards. The number 105 is not. However, 105 in base eight is written as 151, which *is* palindromic. On the other hand, 103 is not a palindrome in *any* base from 2 to 101. Hence, 103 is **[strictly non-palindromic](https://en.wikipedia.org/wiki/Strictly_non-palindromic_number)**. The precise definition is: A nonnegative integer *n* is strictly non-palindromic if it is not a palindrome in any base between 2 and n-2, inclusive. The first few strictly non-palindromic numbers are `0, 1, 2, 3, 4, 6, 11, 19, 47, 53, 79, 103, 137, 139, 149, 163, 167, 179, 223, 263, 269...` ([A016038](https://oeis.org/A016038)) Write a full program that takes a number *x* from STDIN and prints the *x*th strictly non-palindromic number. For example, the input `5` would produce the output `4`. ## Challenge The challenge is to write multiple (one or more) programs, each solving this task in a different language. Then, you must put all of the programs in a rectangular grid of characters. The programs can be accessed Boggle-style. That is, go from one character to a neighboring character (including diagonally), never using the same character more than once. For example, the following grid: ``` abc bdc ``` includes the words `abc`, `ccd`, `bbad`, and `bcdb`, but not `ac`, `bdd`, `bcb`, or `cbbc`. Each program must be found in the grid using these rules. However, you may use the same character in multiple programs. ## Score Your score is the number of characters in the grid, divided by the number of programs. Lowest score wins! ## Rules * Two languages are considered different if they usually go by different names, ignoring version numbers. For example, C and C++ are different, but Python 2 and Python 3 are the same. * The characters in the grid must all be from printable ASCII, i.e., from to `~`, code points `20` through `FE`. * Each program must consist only of printable ASCII, plus newlines. When inserting a program into the grid, replace each newline with a space. + A space in the grid may represent a space in one program and a newline in another. * The grid must be a rectangle. * Not every character needs to be used in a program. [Answer] # 19x2 = 38, 2 programs, Score: ~~26~~ ~~19.5~~ 19 Here is the board: ``` -:\~{.,><1\b_W%}}g} 1Wq{)_2W{$ase.=,do* ``` This contains the following programs: # CJam (27 bytes) ``` Wq~{{)_,2>W<{1$\b_W%=},}g}* ``` [Test it here.](http://cjam.aditsu.net/#code=Wq~%7B%7B)_%2C2%3EW%3C%7B1%24%5Cb_W%25%3D%7D%2C%7Dg%7D*&input=10) These are the characters of the board used for this code: ``` ~{ ,><1\b_W%}}g} Wq{)_2W{$ =, * ``` # GolfScript (34 bytes) ``` -1:W\~{{).,2>W<{1$\base.W%=},}do}* ``` [Test it here.](http://golfscript.apphb.com/?c=OyIxMCIKCi0xOldcfnt7KS4sMj5XPHsxJFxiYXNlLlclPX0sfWRvfSo%3D) These are the characters of the board used for this code: ``` -:\~{.,><1\b W%}} } 1W {) 2W{$ase.=,do* ``` ]
[Question] [ Our new bank needs a teller transaction system but there is a problem. There is only a few hundred bytes of space left on our server, so you will have to write very compact code. ## Database Thankfully our database is very simple (it was built by the schoolboy son of our bank president), and we only have a few customers so far. file `Bank.data` is: ``` Account Firstname Lastname Balance Date 123 Maree Jones 346.22 2014-12-13 035 Thomas Breakbone 3422.02 2015-01-03 422 Henrietta Throsby-Borashenko 277847.74 2014-11-21 501 Timmy Bongo 7.95 2014-11-04 105 William Greene 893.00 2015-01-06 300 Mary Galoway 1228.73 2014-12-28 203 Samantha Richardson 2055.44 2014-11-01 151 Bruce Wayne 956119.66 2014-10-09 166 Chip Stonesmith 266.71 2014-12-15 888 Alexandria Cooper 1299.82 2014-12-30 ``` ## Application Specification Our bank application must implement the following commands: `open <firstname> <lastname>` Creates (opens) a new account printing a unique 3 digit account number. `withdraw <account> <amount>` Withdraw amount from an account. `deposit <account> <amount>` Deposit amount into an account. `close <account>` Close account if empty. `report <fieldname>` Print a report of the database sorted by fieldname. Move the fieldname column to the first position. Each column width will be the maximum of the widest data and fieldname width, separated by one space. The first line will be the field titles. The balances only must be right justified with a leading `$` sign. `print <account>` Print the fieldnames and record for this account formated like the report. Each time a record is changed, the `Date` field in the record must be updated to the current date. The application will show a "# " prompt when waiting for a command. If a command fails (such as an operation on an unknown account or insufficient funds), the application must print the informative error message "failed". The program must write changes back to the file after each change, and read from the file on each command as there are many teller programs around the world operating on the file concurrently (we don't need file locking - that may reduce performance). **EDIT:** String fields are simple ASCII (a-z,A-Z,-) without white space and the amount will always be between 0.00 and 1000000000.00 (1 billion) dollars with 2 decimal places indicating cents. The date will be in local time at each branch (a simple solution but may lead to some problems later...). ## Output Answers will need to demonstrate that they meet the specification. Please attach the output from your program after processing the following commands: ``` report Balance open Clark Kent print 001 deposit 001 4530 withdraw 105 893 close 105 report Date ``` Ensure you use an original copy of the `Bank.data` file given above. ## Scoring This is code-golf, so your score will be the byte count of your code. Standard loopholes are prohibited. [Answer] ## T-SQL 1919 Called with "exec q 'Your command here'" I don't think T-SQL can actually get user input, so I think this is as close as it can be. Uses the bcp utility for I/O which I haven't tried before because it comes with SQL Server 2014. I'm not sure if it would be better or worse to use only the main stored procedure and put the rest of the code in there. ``` CREATE PROC q @ CHAR(99)AS CREATE TABLE ##(A CHAR(3),F CHAR(99),L CHAR(99),B MONEY,D DATE)bcp ## in Bank.data -t " " -T DECLARE @g INT,@w MONEY,@z CHAR(9),@y CHAR(99),@x CHAR(99)SET @g=patindex('% %',@)SET @z=substring(@,1,@g-1)SET @=substring(@,@g+1,99)SET @g=patindex('% %',@)SET @y=substring(@,1,@g-1)SET @=substring(@,@g+1,99)SET @g=patindex('% %',@)SET @x=substring(@,1,@g-1)SET @w=CONVERT(MONEY,@x)*2*(LEN(@z)-7.5)IF @z='open'exec o @y,@x IF @z='close'exec c @y IF @z='withdraw'exec w @y,@w IF @z='deposit'exec w @y,@w IF @z='print'exec p @y IF @z='report'exec r @y bcp ## out Bank.data -t " " -T SELECT'#' CREATE PROC r @q CHAR(9)AS DECLARE @a char(9)='A Account',@f char(11)='F Firstname',@l char(10)='L Lastname',@b char(45)='CONCAT(''$'',SPACE(9-LEN(B)),B) Balance',@d char(6)='D Date',@ varchar(999)='SELECT ' IF @q='Account'SET @+=@a+','+@f+','+@l+','+@b+','+@d IF @q='Balance'SET @+=@b+','+@a+','+@f+','+@l+','+@d IF @q='Date'SET @+=@d+','+@a+','+@f+','+@l+','+@b IF @q='Lastname'SET @+=@l+','+@a+','+@f+','+@b+','+@d IF @q='Firstname'SET @+=@f+','+@a+','+@l+','+@b+','+@d IF LEN(@)<9 BEGIN SELECT'failed'RETURN END SET @+=' FROM ## ORDER BY '+@q exec(@)CREATE PROC p @ CHAR(3)AS DECLARE @r CHAR(9)=(SELECT 1 FROM ## WHERE A=@)IF @r IS NULL SELECT'failed'ELSE SELECT*FROM ## WHERE A=@ CREATE Proc o @f CHAR(99),@l CHAR(99)AS DECLARE @ INT=0,@r CHAR(9)=(SELECT 1 FROM # WHERE A='000')WHILE @r IS NOT NULL BEGIN SET @+=1 SET @r=(SELECT 1 FROM # WHERE CONVERT(INT,A)=@)END IF @>999 SELECT'failed'ELSE INSERT INTO # OUTPUT Inserted.A VALUES(REPLICATE('0',3-LEN(@))+CONVERT(CHAR(3),@),@f,@l,0,GETDATE())CREATE PROC w @ CHAR(3),@b MONEY AS DECLARE @r CHAR(9)=(SELECT 1 FROM ## WHERE A=@ AND B>@b)IF @r IS NULL SELECT'failed'ELSE UPDATE ## SET B=B-@b,D=GETDATE()WHERE A=@ CREATE Proc c @q CHAR(3)AS DECLARE @r CHAR(9)=(SELECT 1 FROM ## WHERE A=@q AND B=0)IF @r IS NULL SELECT'failed'ELSE DELETE FROM ## WHERE A=@q ``` [Answer] # Cobra - 1505 ``` class P var m='Account Firstname Lastname Balance Date' def main while[d=DateTime.now.toString('yyyy-MM-dd'),z='0.00'] print'#'stop try,branch (c=Console.readLine.split)[r=0] on'open' post while u in for x in.f get x[0],u=(r+=1).toString('000') print u .f=.f.toList+[@[u,c[1],c[2],z,d]] on'deposit'or 'withdraw' n=.z(if(c[0]>'deposit','-','')+c[2]) assert.z(.i(c[1])[3])+n>=0 .f=for x in.f get if(x[0]==c[1],@[x[:3].join(' '),'[(.z(x[3])+n).toString(z)]',d],x) on'close' assert.i(c[1])[3]==z .f=for x in.f where.i(c[1])<>x on'report',.a(.f,c[1]) on'print',.a([.i(c[1])]) else,assert 0 catch print'failed' def z(s='')as float return float.parse(s) pro f as String[]?* get return for x in File.readAllLines('Bank.data')[1:]get x.split set File.writeAllLines('Bank.data',[.m]+for x in value get x.join(' ')) def a(f as String[]?*,c='Account') i,l=(m=.m.split).toList.indexOf(c),[7,9,8,8,4] assert c in m print (for q in (for z in (for x in[m]+f.toList.sorted(do(a as String[],b as String[]))get for y in 5 get[t=try' '.repeat(l[y]-x[y].length)catch get'',if(y-3,x[y]+t,t+if(x==m,' ','$')+x[y])][1])get[z[i]]+for p in z where p<>z[i])get q.join(' ')).join('\n') for v in[a,b],for k in 5,if (u=v[k].length)>l[k],l[k]=u return[d=a[i].compareTo(b[i]),d,d,.z(a[3]).compareTo(.z(b[3])),DateTime.parse(a[4]).compareTo(DateTime.parse(b[4]))][i] def i(s='')as String[]? return (for x in.f where x[0]==s)[0] ``` Output: ``` #report Balance Balance Account Firstname Lastname Date $7.95 501 Timmy Bongo 2014-11-04 $266.71 166 Chip Stonesmith 2014-12-15 $346.22 123 Maree Jones 2014-12-13 $893.00 105 William Greene 2015-01-06 $1228.73 300 Mary Galoway 2014-12-28 $1299.82 888 Alexandria Cooper 2014-12-30 $2055.44 203 Samantha Richardson 2014-11-01 $3422.02 035 Thomas Breakbone 2015-01-03 $277847.74 422 Henrietta Throsby-Borashenko 2014-11-21 $956119.66 151 Bruce Wayne 2014-10-09 #open Clark Kent 001 #print 001 Account Firstname Lastname Balance Date 001 Clark Kent $0.00 2015-02-04 #deposit 001 4530 #withdraw 105 893 #close 105 #report Date Date Account Firstname Lastname Balance 2014-10-09 151 Bruce Wayne $956119.66 2014-11-01 203 Samantha Richardson $2055.44 2014-11-04 501 Timmy Bongo $7.95 2014-11-21 422 Henrietta Throsby-Borashenko $277847.74 2014-12-13 123 Maree Jones $346.22 2014-12-15 166 Chip Stonesmith $266.71 2014-12-28 300 Mary Galoway $1228.73 2014-12-30 888 Alexandria Cooper $1299.82 2015-01-03 035 Thomas Breakbone $3422.02 2015-02-04 001 Clark Kent $4530.00 ``` [Answer] # Ruby, 918 This question is quite long to golf as it consists of many small parts. For a moment, I almost wanted to define some additional classes to make things neater with polymorphism etc... (but in the end I didn't). ``` l=->a,i{a.map{|x|x[i].to_s.size}.max} y=1..-1 d=File.open(f="bank.data").each.map(&:split) j=[k=%w{Account Firstname Lastname Balance Date}] _=->{puts"Failure"} q=->t,v=0{z=-1;puts t.map{|r|([v]+((0..4).to_a-[v])).map{|c|b=l[t,c];c!=3?r[c].ljust(b):(?$*(z+=z<1?1:0)+r[c]).rjust(b>7?b+1:b)}*' '}} w=->d{File.open(f,?w).write(d.map{|x|x*' '}*?\n)} s=->i,m=!0{o=d.select{|r|r[0]==i};o==[]?_[]:m ?q[[k]+o]:1} u=->{Time.now.to_s[0..9]} ($><<"# ";i=gets.split;o=i.size;("report"==h=i[0])?((v=k.index i[1])?q[j+d[y].sort_by{|x|v!=3?x[v]:x[v].to_f},v]:_[]):h=="print"?s[i[1],0]:h=="close"?(s[m=i[1]]?w[d=j+d[y].select{|r|r[0]!=m}]:0):h=="open"?((o==3&&t=((1..999).map{|x|'%03d'%x}-d.map{|x|x[0]})[0])?(w[d=d+[[t,i[1],i[2],'0.00',u[]]]];puts t):_[]):h=="withdraw"||h=="deposit"?(o==3&&s[i[1]]?w[d=j+d[y].map{|r|i[1]==r[0]?(b=(c=r[3].to_f)+i[2].to_f*(i[0][0]==?w?-1:1);0>b&&(b=c;_[]);r[0..2]+["%.2f"%b,u[]]):r}]:_[]):_[])while 1 ``` Probably can be golfed further. But as of now, I can't even keep track of what I did in the last line. Output: ``` # report Balance Balance Account Firstname Lastname Date $7.95 501 Timmy Bongo 2014-11-04 $266.71 166 Chip Stonesmith 2014-12-15 $346.22 123 Maree Jones 2014-12-13 $893.00 105 William Greene 2015-01-06 $1228.73 300 Mary Galoway 2014-12-28 $1299.82 888 Alexandria Cooper 2014-12-30 $2055.44 203 Samantha Richardson 2014-11-01 $3422.02 035 Thomas Breakbone 2015-01-03 $277847.74 422 Henrietta Throsby-Borashenko 2014-11-21 $956119.66 151 Bruce Wayne 2014-10-09 # open Clark Kent 001 # print 001 Account Firstname Lastname Balance Date 001 Clark Kent $0.00 2015-02-01 # deposit 001 4530 # withdraw 105 893 # close 105 # report Date Date Account Firstname Lastname Balance 2014-10-09 151 Bruce Wayne $956119.66 2014-11-01 203 Samantha Richardson $2055.44 2014-11-04 501 Timmy Bongo $7.95 2014-11-21 422 Henrietta Throsby-Borashenko $277847.74 2014-12-13 123 Maree Jones $346.22 2014-12-15 166 Chip Stonesmith $266.71 2014-12-28 300 Mary Galoway $1228.73 2014-12-30 888 Alexandria Cooper $1299.82 2015-01-03 035 Thomas Breakbone $3422.02 2015-02-01 001 Clark Kent $4530.00 # ``` [Answer] # Python 2 - 2205 bytes Here is a rather verbose attempt at a solution. ``` import sys, time, re def db(recs): text = '\n'.join(' '.join(row) for row in [titles]+recs) open('Bank.data', 'wt').write(text+'\n') def wid(col, recs): w = max(len(r[col]) for r in [titles]+recs) return w if col == 3 else -w while 1: inp=raw_input('# ').split() try: cmd = inp.pop(0) data = [d.split() for d in open('Bank.data', 'rt').readlines()] titles = data.pop(0) today = '-'.join('%02u' % v for v in time.localtime()[:3]) alist = set(int(r[0]) for r in data) if cmd == 'open': assert re.match(r'[-a-zA-Z]{2,}', inp[0]+inp[1]) acct = '%03u'%([n for n in range(1, 1000) if n not in alist][0]) rec = [acct] + inp + ['0.00', today] db(data+[rec]) print acct elif cmd == 'withdraw': a, m = inp[0], float(inp[1]) rec = [r for r in data if r[0] == a][0] b = float(rec[3]) assert b >= m rec[3] = '%.2f' % (b-m) rec[4] = today db(data) elif cmd == 'deposit': a, m = inp[0], float(inp[1]) rec=[r for r in data if r[0]==a][0] rec[3]='%.2f'%(float(rec[3])+m) rec[4]=today db(data) elif cmd=='close': rec=[r for r in data if r[0]==inp[0]][0] assert int(rec[3])==0 data=[r for r in data if r!=rec] db(data) elif cmd=='report': for r in data: r[3]='$'+r[3] fmtlist=['%'+str(wid(c,data))+'s' for c in range(5)] loc=titles.index(inp[0]) for r in data: r.insert(0,r.pop(loc)) data.sort(key=lambda x: float(x[0][1:]) if loc==3 else x[0]) titles.insert(0,titles.pop(loc)) fmtlist.insert(0,fmtlist.pop(loc)) for r in [titles]+data: print ' '.join(fmtlist)%tuple(r) elif cmd=='print': for r in data: r[3]='$'+r[3] rec=[r for r in data if r[0]==inp[0]][0] fmt=' '.join('%'+str(wid(c,[rec]))+'s' for c in range(5)) for r in [titles,rec]: print fmt%tuple(r) else: raise() except: print 'failed' ``` Here is a sample of the application in use: ``` # report Balance Balance Account Firstname Lastname Date $7.95 501 Timmy Bongo 2014-11-04 $266.71 166 Chip Stonesmith 2014-12-15 $346.22 123 Maree Jones 2014-12-13 $893.00 105 William Greene 2015-01-06 $1228.73 300 Mary Galoway 2014-12-28 $1299.82 888 Alexandria Cooper 2014-12-30 $2055.44 203 Samantha Richardson 2014-11-01 $3422.02 035 Thomas Breakbone 2015-01-03 $277847.74 422 Henrietta Throsby-Borashenko 2014-11-21 $956119.66 151 Bruce Wayne 2014-10-09 # open Clark Kent 001 # print 001 Account Firstname Lastname Balance Date 001 Clark Kent $0.00 2015-01-13 # deposit 001 4530 # withdraw 105 893 # close 105 # report Date Date Account Firstname Lastname Balance 2014-10-09 151 Bruce Wayne $956119.66 2014-11-01 203 Samantha Richardson $2055.44 2014-11-04 501 Timmy Bongo $7.95 2014-11-21 422 Henrietta Throsby-Borashenko $277847.74 2014-12-13 123 Maree Jones $346.22 2014-12-15 166 Chip Stonesmith $266.71 2014-12-28 300 Mary Galoway $1228.73 2014-12-30 888 Alexandria Cooper $1299.82 2015-01-03 035 Thomas Breakbone $3422.02 2015-01-13 001 Clark Kent $4530.00 # ``` [Answer] ## Batch - 1827 Batch is not built for this kind of thing. ``` @echo off&setLocal enableDelayedExpansion&set B=Bank.data&echo wscript.echo eval(wscript.arguments(0))>%temp%\eval1.vbs&set Z=goto :EOF&set V=call&set F=for /l %%a in (1,1, :m set C=-1&set D=%date:~-4%-%date:~-7,2%-%date:~-10,2% for /f "tokens=1-5" %%a in (%B%)do set/aC+=1 &set !C!=%%a %%b %%c %%d %%e&set !C!n=%%a&set !C!f=%%b&set !C!s=%%c&set !C!b=%%d&set !C!d=%%e&set A=%%a&set/aA+=1 set/pI="#" %V% :%I% 2>nul||echo failed&goto m goto m :open echo %A% %1 %2 0.00 %D%>>%B%&echo %A%&%Z% :close echo !0!>%B%&%F%!C!)do if "!%%an!" NEQ "%1" (echo !%%a!>>%B%)else if !%%ab! GTR 0.00 echo failed & echo !%%a!>>%B% %Z% :deposit %F%!C!)do if "!%%an!"=="%1" set p=%%a %V% :c "!%p%b!+%2" set %p%b=%r%&set %p%d=%D%&%V% :u %Z% :withdraw %F%!C!)do if "!%%an!"=="%1" set p=%%a %V% :c "!%p%b!-%2"&if "%r:~0,1%"=="-" echo failed&%Z% set %p%b=%r%&set %p%d=%D%&%V% :u %Z% :report for /l %%a in (1,1,50)do set H= !H! for /l %%a in (0,1,!C!)do ( %V% :l !%%an!&set %%anl=!l!&if !l! GTR !tn! set/atn=!l! %V% :l !%%af!&set %%afl=!l!&if !l! GTR !tf! set/atf=!l! %V% :l !%%as!&set %%asl=!l!&if !l! GTR !ts! set/ats=!l! %V% :l !%%ab!&set %%abl=!l!&if !l! GTR !tb! set/atb=!l! ) for /l %%a in (0,1,!C!)do %V% :c "%tn%-!%%anl!"&set sn=!r:~0,-3!&%V% :t !sn!&set pn=!x!&%V% :c "%tf%-!%%afl!"&set sf=!r:~0,-3!&%V% :t !sf!&set pf=!x!&%V% :c "%ts%-!%%asl!"&set ss=!r:~0,-3!&%V% :t !ss!&set ps=!x!&%V% :c "%tb%-!%%abl!"&set sb=!r:~0,-3!&%V% :t !sb!&set pb=!x!&echo !%%an!!pn! !%%af!!pf! !%%as!!ps! !pb!$!%%ab! !%%ad! %Z% :l set S=%1&for /f usebackq %%a in (`Powershell "'!S!'.Length"`)do set l=%%a %Z% :t set x=!H:~0,%1! %Z% :u echo !0!>%B%&%F%!C!)do echo !%%an! !%%af! !%%as! !%%ab! !%%ad!>>%B%&%Z% :c for /f %%a in ('cscript //nologo %temp%\eval1.vbs "round(%1,2)"')do set r=%%a if "%r:~-3,1%" NEQ "." set r=%r%.00 ``` Yet to implement Sort (within report), and Print functions. [Answer] ## STATA 1506 Didn't try to golf it too much. I figured a statistical language would be better at this, but apparently. ``` set more off while 1<2{ qui insheet using Bank.data,delim(" ")clear case form A %-03.0f form B %10.2f form D %-10s form F %-50s form L %-50s g K="$"+string(B,"%10.2f") di"#",_r(q) loc s: di %tdCCYY-NN-DD date(c(current_date),"DMY") if word("$q",1)=="open"{ forv x=0/999{ egen c=anymatch(A),v(`x') if c<1{ egen m=min(A) cap expand 2 if A==m,gen(z) replace A=`x' if A==m&z>0 replace B=0 if A==`x' replace F=word("$q",2) if A==`x' replace L=word("$q",3) if A==`x' replace D="`s'" if A==`x' di"`x'" outsheet A-D using Bank.data,delim(" ")replace continue, br } if `x'==999{ di"failed" } drop c } continue } if word("$q",1)=="report"{ ren B R ren K Balance if word("$q",2)=="Account"{ so A l A-L B D,clean noo } else if word("$q",2)=="Date"{ so D l D A-L B,clean noo } else if word("$q",2)=="Lastname"{ so L l L A F B D,clean noo } else if word("$q",2)=="Balance"{ so R l B A-L D,clean noo } else if word("$q",2)=="Firstname"{ so F l F A L B D,clean noo } else{ di"failed" } continue } gen i=real(word("$q",2)) egen p=min(abs(A-i)) if p>0{ di"failed" continue } if word("$q",1)=="close"{ egen c=count(i) drop if A==i&B==0 qui cou if c==r(N){ di"failed" continue } } if word("$q",1)=="print"{ drop Balance ren K Balance l A-L B D if A==i,noo clean ab(9) continue } gen j=real(word("$q",3)) if word("$q",1)=="withdraw"{ replace B=B-j if A==i egen c=min(B) if c<0{ di"failed" continue } } if word("$q",1)=="deposit"{ replace B=B+j if A==i } replace D="`s'" if A==i outsheet A-D using Bank.data,delim(" ")replace } ``` [Answer] # C# - 1952 1883 I will show some output when I get in tomorrow. For now, here's the submission: ``` using System;using System.Collections.Generic;using System.IO;using System.Linq;using S=System.String;using O=System.Func<dynamic,string,string>;class I{char[]c={' '};Action<string>w;Func<S,S,S,S,S,dynamic>n;Func<string>N;List<dynamic>T;private static void Main(string[]a){while(true){Console.Write("# ");new I().Parse(Console.ReadLine());}}I(){w=Console.WriteLine;n=(g,h,i,j,k)=>new{a=g,f=h,l=i,b=j,d=k};N=()=>DateTime.Now.ToString("yyyy-MM-dd");}List<dynamic>G(){return File.ReadAllLines("test.data").Select(l=>l.Split(c)).Select(ac=>n(ac[0],ac[1],ac[2],ac[3],ac[4])).ToList();}void W(){File.WriteAllLines("test.data",T.Select(a=>(S)(a.a+" "+a.f+" "+a.l+" "+a.b+" "+a.d)));}void Parse(string inp){var C=true;try{Func<object,float>v=Convert.ToSingle;Func<string,bool>s=string.IsNullOrEmpty;var i=inp.Split(c);T=G();Func<S,int>F=m=>T.IndexOf(T.FirstOrDefault(a=>a.a==m));C=!s(i[1]);var g=F(i[1]);switch(i[0]){case"open":if(C){int an=0;var cs="000";while(T.Any(A=>cs==A.a)){an++;cs=an.ToString("D3");}T.Add(n(cs,i[1],i[2],"0.00",N()));w(cs);}break;case"withdraw":case"deposit":var D=i[0]=="deposit";C=(D||v(T[g].b)>=v(i[2]));var ba=(v(T[g].b)+v(i[2])*(D?1:-1)).ToString("F");if(C)T[g]=n(T[g].a,T[g].f,T[g].l,ba,N());break;case"close":C=g>-1&&v(T[g].b)<=0;if(C)T.RemoveAt(g);break;case"report":case"print":var X=i[0]=="print";var B=1;O o=(x,p)=>((Type)x.GetType()).GetProperty(p).GetValue(x);O K=(k,j)=>{var r=(j=="b"?"$":"");var P=T.Max(_=>(o(_,j)).Length);return r==""?(o(k,j)).PadRight(P):((B<1?r:"")+(o(k,j))).PadLeft(P+1);};var q=i[1];Action<dynamic,S>U=(u,t)=>{S l=""; foreach(var h in t)l+=K(u,h.ToString())+" "; w(l);};q=q=="Account"?"a":q=="Firstname"?"f":q=="Lastname"?"l":q=="Balance"?"b":q=="Date"?"d":"a"; var V=(q+"afldb".Replace(q,""));U(T.First(),V);B=0;foreach(var M in(X?T.Skip(1).Take(1):T.Skip(1).OrderBy(df=>o(df,q))))U(M,V);break;}W();}catch{}if(!C)w("Failed");}} ``` [Answer] **C# - 1870 1881 Bytes** Abusing `using` aliases, `Action`, `Func`, exceptions for flow control and more. Was considering exploiting that "report" didn't specify how things should be sorted. Bank.data must use unix line breaks or this code will break. Edited to fix a potential issue sorting by fields other than Date and Balance. ``` using System;using System.Collections.Generic;using System.IO;using System.Linq;using Ac=System.Action;using Cn=System.Console;using F1=System.Func<string,int>;using F2=System.Func<string>;using S=System.String;class P{static void Main(S[] args){S fn="Bank.data";List<S>ad=null;F1 L=(s)=>s.Length;F2 dt=()=>S.Format("{0:yyyy-MM-dd}",DateTime.Now);Func<S,S[]>sp=(s)=>s.Split(' ');Action<S,S>wl=(s,fm)=>Cn.WriteLine(S.Format(fm,sp(s)));Func<S,S>rs=(s)=>{var t=sp(s);t[3]="$"+t[3];return S.Join(" ",t);};F2 fs=()=>{int[]sz={7,9,8,7};ad.Skip(1).ToList().ForEach(b=>{for(int c=0;c<4;c++){sz[c]=Math.Max(sz[c],L(sp(rs(b))[c]));}});return"{0,-"+sz[0]+"} {1,-"+sz[1]+"} {2,-"+sz[2]+"} {3,"+sz[3]+"} {4,-10}";};F1 k=(s)=>sp(ad[0]).ToList().FindIndex(a=>a==s);Ac Sv=()=>File.WriteAllText(fn,S.Join("\n",ad));Ac Ld=()=>ad=File.ReadAllText(fn).Split('\n').ToList();Action<int,S>R=(r,a)=>{var s=sp(ad[r]);s[3]=S.Format("{0:#.00}",Convert.ToDouble(s[3])+Convert.ToDouble(a));s[4]=dt();ad[r]=S.Join(" ",s);};Ac f=()=>wl("failure","{0}");F1 ri=(n)=>{for(int w=1;w < ad.Count;w++){if(ad[w].StartsWith(n))return w;}return -1;};F2 nm=()=>{var s="";for(int i=1;i<1000;i++){s=S.Format("{0:000}",i);if (ri(s)<0)break;}return s;};for(;;){Cn.Write("# ");S i=Cn.ReadLine();var it=sp(i+" ");Ld();var n=ri(it[1]);it=sp(i);var a=new Dictionary<S,Ac>(){{"deposit",()=>R(n,it[2])},{"withdraw",()=>R(n,"-"+it[2])},{"close",()=>(sp(ad[n])[3]==".00"?()=>ad.RemoveAt(n):f)()},{"open",()=>{var nn=nm();ad.Add(S.Format("{0} {1} {2} .00 {3}",nn,it[1],it[2],dt()));wl(nn,"{0}");}},{"print",()=>{wl(ad[0],fs());wl(rs(ad[n]),fs());}},{"report",()=>{var ks=sp(fs()).ToList();var ki=k(it[1]);ks.Insert(0,ks[ki]);ks.RemoveAt(ki+1);var kf=S.Join(" ",ks);wl(ad[0],kf);ad.Skip(1).OrderBy(b=>(ki==3?new S('0',11-L(sp(b)[ki])):"")+sp(b)[ki]).ToList().ForEach(b=>wl(rs(b),kf));}}};try{a[it[0]]();Sv();}catch(Exception){f();}}}} ``` Output: ``` # report Balance Balance Account Firstname Lastname Date $7.95 501 Timmy Bongo 2014-11-04 $266.71 166 Chip Stonesmith 2014-12-15 $346.22 123 Maree Jones 2014-12-13 $893.00 105 William Greene 2015-01-06 $1228.73 300 Mary Galoway 2014-12-28 $1299.82 888 Alexandria Cooper 2014-12-30 $2055.44 203 Samantha Richardson 2014-11-01 $3422.02 035 Thomas Breakbone 2015-01-03 $277847.74 422 Henrietta Throsby-Borashenko 2014-11-21 $956119.66 151 Bruce Wayne 2014-10-09 # open Clark Kent 001 # print 001 Account Firstname Lastname Balance Date 001 Clark Kent $.00 2015-02-03 # deposit 001 4530 # withdraw 105 893 # close 105 # report Date Date Account Firstname Lastname Balance 2014-10-09 151 Bruce Wayne $956119.66 2014-11-01 203 Samantha Richardson $2055.44 2014-11-04 501 Timmy Bongo $7.95 2014-11-21 422 Henrietta Throsby-Borashenko $277847.74 2014-12-13 123 Maree Jones $346.22 2014-12-15 166 Chip Stonesmith $266.71 2014-12-28 300 Mary Galoway $1228.73 2014-12-30 888 Alexandria Cooper $1299.82 2015-01-03 035 Thomas Breakbone $3422.02 2015-02-03 001 Clark Kent $4530.00 # ``` ]
[Question] [ # Pigpen Cipher Encryption Your mission is simple: to write a program which receives text as input and outputs an ASCII representation of it in the [Pigpen Cipher](http://en.wikipedia.org/wiki/Pigpen_cipher). ## Input ASCII-only (no Unicode) characters. You must be able to handle at least 16384 characters and 256 lines. ## Output * Replace all characters which are not new lines or in `ABCDEFGHIJKLMNOPQRSTUVWXYZ` or `abcdefghijklmnopqrstuvwxyz` with spaces. * Case-insensitively, replace each letter with its encrypted form (see next section), inserting a trailing space on each of the three lines after each. Each encoded character is a 3\*3 block of ASCII art. Replace spaces with 3\*3 blocks of spaces. * All the characters should be on the same three lines (call these three lines one pigpen-line), unless there is a new line, which starts a new pigpen-line. Leave a normal line blank between pigpen-lines. ## The Cipher ``` | | | | .| |.| |. --+ for J +-+ for K +-- for L --+ +-+ +-- .| |.| |. --+ for M +-+ for N +-- for O --+ +-+ +-- .| |.| |. | for P | | for Q | for R (ABCDEFGHI are the same as JKLMNOPQR, but with the . replaced by a space) \./ V for W (note the row of 3 spaces on the top) ^ /.\ for Z (note the 3 spaces on the bottom) \ .> / for X (note the leading spaces) / <. \ for Y (note extra trailing spaces) (STUV are like WXYZ, but with the . replaced by a space) ``` ## Example The input "hEllo,wORLd" should produce: ``` +-+ +-+ | | +-- +-- +-- | --+ | | | | |. |. |. \./ |. |. |. | | | +-+ +-- +-- +-- V +-- | +-- --+ ``` The base64 encoding of the above, with a trailing new line, is below. The md5sum is `6f8ff1fed0cca4dd0492f9728ea02e7b`. ``` Ky0rICstKyB8ICAgfCAgICstLSAgICAgICAgICstLSArLS0gfCAgIC0tKwp8IHwgfCB8IHwuICB8 LiAgfC4gICAgICBcLi8gfC4gIHwuICB8LiAgICB8CnwgfCArLSsgKy0tICstLSArLS0gICAgICBW ICArLS0gfCAgICstLSAtLSsK ``` Without a trailing new line, the md5sum is `581005bef7ee76e24c019d076d5b375f` and the base64 is: ``` Ky0rICstKyB8ICAgfCAgICstLSAgICAgICAgICstLSArLS0gfCAgIC0tKwp8IHwgfCB8IHwuICB8 ``` LiAgfC4gICAgICBcLi8gfC4gIHwuICB8LiAgICB8CnwgfCArLSsgKy0tICstLSArLS0gICAgICBW ICArLS0gfCAgICstLSAtLSs= ## Rules * [Standard loopholes](http://tinyurl.com/ppcgloopholes) are forbidden. * This is code golf. Shortest code wins. * In languages which cannot accept multiple lines of input at a time (e.g. JavaScript with `prompt()`), use `*` (or some other character) as a line separator. ## Erranda * The example was missing a few spaces (A space should consist of the trailing spaces of the previous character, if any, itself, and its own trailing spaces). This has now been fixed. [Answer] # JavaScript (ES6) 312 ~~327 340 372 446~~ Not counting indentation white space and newlines ~~- could be golfed more~~. Using an '\*' to mark new lines in input, as `prompt` accepts a single line. ``` console.log(prompt().split('*').map(s=> [0,1,2].map(r=> [...s].map(c=>o+=n+ ' \\1/ \\ /1\\ / V ^ 1><1 --++-++-- 1||1||1 '.substr( (c=(32|c.charCodeAt())-97)<0|c>25?0:c<18 ?27+3*'330441552030141252033144255'[f=8,c%9*3+r] :3*'482630015274'[f=21,c%4*3+r],3,n=' ') .replace(1,' .'[r&c>f]) ,n='\n'),o='' )&&o).join('\n')) ``` **Test** in FireFox/FireBug console Input: ABCDEFGHI\*JKLMNOPQR\*STUV\*WXYZ\*HeLlO WoRlD! ``` | | | | --+ +-+ +-- --+ +-+ +-- | | | | | | | | | | | | --+ +-+ +-- --+ +-+ +-- | | | | | | | | --+ +-+ +-- --+ +-+ +-- .| |.| |. .| |.| |. .| |.| |. --+ +-+ +-- --+ +-+ +-- | | | | \ / ^ \ / > < / \ V / \ \ / ^ \./ .> <. /.\ V / \ +-+ +-+ | | +-- +-- +-- | --+ | | | | |. |. |. \./ |. |. |. | | | +-+ +-- +-- +-- V +-- | +-- --+ ``` [Answer] # C# - ~~921~~ 720 Obviously not a winning entry, but this looked like too much fun to pass off :) Program takes input as a single, then prints the pigpen. To input multiple lines, use an underscore (\_) as seen in **output**. ### Code ``` using System;class P{static void Main(){ int i,y,j,k,w,z;string[]g=Console.ReadLine().ToLower().Split('_'); var d="_________ |b .|b--+_| |b|.|b+-+_| b|. b+--_--+b .|b--+_+-+b|.|b+-+_+--b|. b+--_--+b .|b |_+-+b|.|b| |_+--b|. b| _____ b\\./b v _ \\ b .>b / _ / b<. b \\ _ ^ b/.\\b _ b b ".Replace('b','\n').Split('_'); for(i=0;i<d.Length;i++){if(d[i]==""){d[i]=i<17?d[i+9]:d[i+4];d[i]=d[i].Replace('.',' ');}} for(y=0;y<g.Length;y++){string o="",s,e=g[y];var r=new string[z=e.Length][]; for(i=0;i<z;i++){if(e[i]-97<0|e[i]-97>25)e=e.Replace(e[i],'{'); o+=d[e[i]-97]+'_';r[i]=(o.Split('_')[i].Split('\n'));} for(j=0;j<3;j++)for(k=0;k<(w=r.Length);k++){ s=r[k][j];Console.Write(k==w-1?s+'\n':s+' ');}} Console.ReadLine();}} ``` ### Concept The cipher uses a some character sequences that get duplicated quite a bit. For example, '--' shows up 16 times and '\_\_' (two spaces) shows up 20 times. I replace these sequences with single-character symbols and switch them out at runtime, cutting the number of characters needed to store the pigpen cipher in half. Similarly, a newline usually requires two characters, but is replaced by a symbol (n) and switched out later. The program handles multiple lines of input by splitting the input into an array where each element is a single line of input. The program then simply runs the cipher on each line separately. This is my first golf in any language, so there is probably a lot that can be done to improve this code. ### Output ``` hEllo,wORLd +-+ +-+ | | +-- +-- +-- | --+ | | | | |. |. |. \./ |. |. |. | | | +-+ +-- +-- +-- v +-- | +-- --+ code_golf | +-- --+ +-+ | |. | | | +-- +-- --+ +-+ --+ +-- | +-- | |. |. | | +-- +-- +-- multi_line_input --+ / | \ +-- .| < |. > | --+ \ +-- / | | +-- +-+ +-+ |. | |.| | | +-- | +-+ +-+ +-- +-+ --+ / \ | |.| .| < > | +-+ | \ / ``` [Answer] # Python 2, 180 + 78 + 1 + 3 = 262 characters The 180-byte program (last two newlines are tabs): ``` L=open('f','rb').read().decode('zip') while 1: n=raw_input() for s in(0,3,6): for c in n:w=ord(c.lower())-97;print''.join(L[w+(s+i)*26]for i in(0,1,2))if-1<w<27 else' ', print ``` Requires a 78-byte file called 'f' to be same directory (+1 byte for filename), which contains the following: ``` $ hexdump f 0000000 9c78 a853 d1a9 d6d5 2206 3805 0103 c174 0000010 c100 8b88 07d1 9ae1 051a 4ab0 385d ae03 0000020 2803 8a82 3a80 406c ae18 0f42 6006 0c1c 0000030 0a2d 31fa 6076 ee8c a030 0e14 2987 8428 0000040 7501 3080 c39a 5a10 0014 21c7 7333 000004e ``` The base64 encoding of file `f` is: ``` eJxTqKnR1dYGIgU4AwF0wQDBiIvRB+GaGgWwSl04A64DKIKKgDpsQBiuQg8GYBwMLQr6MXZgjO4w oBQOhykohAF1gDCawxBaFADHITNz ``` The program exits with an exception, `2>_` suppresses the error (+3 bytes): ``` $ echo "hEllo,wORLd" | python pigpen.py 2>_| ./md5.py 7ed49b7013a30cc3e84aa807f6585325 ``` **Explanation**: I created a look-up table, `L`, which is a mapping of `{position_in_3x3_block: {letter_being_encrypted: symbol_for_letter_at_position}}`, stored in a flat array. The program prints the letters by doing a simple look-up for each position. [Answer] # [Perl 5](https://www.perl.org/) `-lF`, ~~297 288 261~~ 231 bytes ``` $,=$";$_=' .||.||. ';chomp@F;map{@r=/.../g;say map{/[a-z]/i?$r[-65+ord uc]:$"x3}@F}(y/./ /r.y/.| /-+-/r x2)x2 .' \\ / ^ 'x2,y/./ /r x3 .$_ x3 .'\\ / >< / \\\\./ .><. /.\\',(y/.| /-+-/r x2 .y/./ /r)x2 .' V / \\ 'x2;say'' ``` [Try it online!](https://tio.run/##VY5BT4NAEIXv@ysmDcnWlJ1tIXiQUrnISa/GpFSCUAsKXVxau1T618Xdhosvk7xk5st702xl5Q2DZQfWxLeSgAL2vRmgflaIugkjv06bn1AGHBH5zm/TDsyGr1N23vDy3pJrduvNhMzhmG3urIlyL2F0mXYcOXCJ2nvgbMa4BOXcKAeQglYcA3CAV6DKsUcYlAtoJVejGtD31dJgsZYmcLVE4BjH1J7@zwUcI8aC52u46QBTYN6mdBiKh8dKJCchq3zhuC8kfctIvn0nu6IkH58VqfeCNF@StIfjNzmp7vwrmkMp9u3AnjycL@YDq6I/ "Perl 5 – Try It Online") There's probably still a bit here that could be golfed further. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 139 bytes ``` ⇧×/ƛƛkAnc[C83<[»ƛ_F∆a⋎⁺^9⟨C¨¼ḢO[½ċeẇɽ»`| -+`τ9/nC⇩9%inC73>[4\.Ȧ]|` \ / V ^ / \ \ > / / < \ `4/nC›4%inC86>[4\.Ȧ]]|ð9*]3/;ÞTvṄ¤J;f ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%E2%87%A7%C3%97%2F%C6%9B%C6%9BkAnc%5BC83%3C%5B%C2%BB%C6%9B_F%E2%88%86a%E2%8B%8E%E2%81%BA%5E9%E2%9F%A8C%C2%A8%C2%BC%E1%B8%A2O%5B%C2%BD%C4%8Be%E1%BA%87%C9%BD%C2%BB%60%7C%20-%2B%60%CF%849%2FnC%E2%87%A99%25inC73%3E%5B4%5C.%C8%A6%5D%7C%60%20%20%20%5C%20%2F%20V%20%20%5E%20%2F%20%5C%20%20%20%20%5C%20%20%20%3E%20%2F%20%20%2F%20%3C%20%20%20%5C%20%604%2FnC%E2%80%BA4%25inC86%3E%5B4%5C.%C8%A6%5D%5D%7C%C3%B09*%5D3%2F%3B%C3%9ETv%E1%B9%84%C2%A4J%3Bf&inputs=ABCDEFGHI*JKLMNOPQR*STUV*WXYZ*HeLlO%20WoRlD!&header=&footer=) What. A. Mess. ]
[Question] [ # Objective I have a nice picture that I want to hang on my wall. And I want it to hang there in a spectacular way, so I chose to hang it on `n` nails where `n` is any positive integer. But I'm also indecisive, so if I change my mind, I don't want a lot of trouble taking the picture down. Therefore, removing any one of the `n` nails should make the picture fall down. Did I mention that there is no friction in my house? Can you help me? # Rules 1. Your program must read the number `n` from stdin and print to stdout (or your language's equivalents). 2. The output must be the solution according to the output specification without any other trailing or leading characters. However, trailing whitespace and/or newlines is acceptable. 3. You must use *exactly* `n` nails. 4. Assuming a friction-less world, your solution must fulfill the following conditions: 1. Hanging the picture as described by your solution, the picture must not fall down. 2. If any one of the nails is removed, the picture must fall down. 5. Standard loopholes apply. In particular, you may not make requests to, e.g., the verification program to brute-force solutions. Note that 4.2 already implies that all `n` nails must be involved. # Output Specification * All nails are named from left to right with the position they are in, starting at `1`. * There are two fundamental ways to put the string around a nail: clockwise and counter-clockwise. We denote a clockwise step with `>` and a counter-clockwise step with `<`. * Everytime the string is put around a nail, it comes out on top of the nails, so skipping nails means the string will go across the top of the intermediate nails. * Every solution must start on nail `1` and end on nail `n`. * The output must consist of a sequence of steps wherein a step is a combination fo the nail's name and the direction in which to put the string around it. ## Example Output Here is an example output for `n=5` and `n=3`: ``` 1>4<3<2>4>5< # n=5, incorrect solution 1>2<1<2>3<2<1>2>1<3> # n=3, correct solution ``` And here is a visual representation of the incorrect solution for `n=5` (awsumz gimp skillz) ![Visual Representation](https://i.stack.imgur.com/OBLvv.png) The correct solution for `n=1` is simply `1>` or `1<`. For multiple nails, there can be different solutions. You must only output one since this is part of your score. # Verification You can verify whether a solution is correct here: [www.airblader.de/verify.php](http://airblader.de/verify.php). It uses a GET request, so you can call it directly if you want. For example, if `foo` is a file containing a solution on each line, you can use ``` cat foo | while read line; do echo `wget -qO- "www.airblader.de/verify.php?solution=$line" | grep "Passed" | wc -l`; done ``` If you believe a solution is correct but the verifier marks it as incorrect, please let me know! *Edit:* And if your output is so long that a GET request won't cut it, let me know and I'll make a POST request version. :) # Scoring This is code-golf. The score is the number of bytes of your source-code in UTF-8 encoding, e.g., use [this tool](http://mothereff.in/byte-counter). However, there is a potential bonus for every submission: Run your program for all `n` in the range `[1..20]` and add the *length* of all outputs up to determine your *output score*. Subtract your output score from `6291370` to get the number of *bonus points* that you may deduct from your byte count to get your *overall score*. There is no penalty if your output score is higher than this number. The submission with the lowest overall score wins. In the unlikely case of a tie, the tie breakers are in this order: higher bonus points, lower byte count, earlier submission date. Please post both the individual parts (byte count, bonus points) of the score and the final score, e.g., "`LOLCODE (44 - 5 = 39)`". [Answer] ## GolfScript (51 67 bytes + (7310 7150 - 6,291,370) = -6,284,153) ``` ~,{.,({.,.[1]*{(\(@++}@((*1=/{C}%.~+2/-1%{~'<>'^}%*}{[~)'>']}if}:C~ ``` This is based on Chris Lusby Taylor's\* [recursive commutator construction](http://www.mathpuzzle.com/hangingpicture.htm), better expounded in [Picture-Hanging Puzzles](http://arxiv.org/abs/1203.3602), Demaine et al., *Theory of Computing Systems* 54(4):531-550 (2014). Outputs for the first 20 inputs: ``` 1> 1>2<1<2> 1>2<1<2>3<2<1>2>1<3> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4> 1>2<1<2>3<2<1>2>1<3>5<4>5>4<3<1>2<1<2>3>2<1>2>1<4>5<4<5> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>7<5>6<5<6>7>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>7<6<5>6>5<7> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8> 1>2<1<2>3<2<1>2>1<3>5<4>5>4<3<1>2<1<2>3>2<1>2>1<4>5<4<5>9<8>9>8<6>7<6<7>8>9<8<9>7<6>7>6<5<4>5>4<1>2<1<2>3<2<1>2>1<3>4>5<4<5>3<1>2<1<2>3>2<1>2>1<6>7<6<7>9<8>9>8<7<6>7>6<8>9<8<9> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>10<9>10>9<7>8<7<8>9>10<9<10>8<7>8>7<6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<7>8<7<8>10<9>10>9<8<7>8>7<9>10<9<10> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>7<5>6<5<6>7>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>7<6<5>6>5<7>11<10>11>10<8>9<8<9>10>11<10<11>9<8>9>8<7<5>6<5<6>7>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>7<6<5>6>5<7>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<8>9<8<9>11<10>11>10<9<8>9>8<10>11<10<11> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>13<12>13>12<9>10<9<10>11<10<9>10>9<11>12>13<12<13>11<9>10<9<10>11>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>11<10<9>10>9<11>13<12>13>12<11<9>10<9<10>11>10<9>10>9<12>13<12<13> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>14<13>14>13<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>13>14<13<14>12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>14<13>14>13<12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<13>14<13<14> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>15<13>14<13<14>15>14<13>14>13<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>13>14<13<14>15<14<13>14>13<15>12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>15<13>14<13<14>15>14<13>14>13<12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<13>14<13<14>15<14<13>14>13<15> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>16<15>16>15<13>14<13<14>15>16<15<16>14<13>14>13<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>13>14<13<14>16<15>16>15<14<13>14>13<15>16<15<16>12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>16<15>16>15<13>14<13<14>15>16<15<16>14<13>14>13<12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<13>14<13<14>16<15>16>15<14<13>14>13<15>16<15<16> 1>2<1<2>3<2<1>2>1<3>5<4>5>4<3<1>2<1<2>3>2<1>2>1<4>5<4<5>9<8>9>8<6>7<6<7>8>9<8<9>7<6>7>6<5<4>5>4<1>2<1<2>3<2<1>2>1<3>4>5<4<5>3<1>2<1<2>3>2<1>2>1<6>7<6<7>9<8>9>8<7<6>7>6<8>9<8<9>17<16>17>16<14>15<14<15>16>17<16<17>15<14>15>14<10>11<10<11>13<12>13>12<11<10>11>10<12>13<12<13>14>15<14<15>17<16>17>16<15<14>15>14<16>17<16<17>13<12>13>12<10>11<10<11>12>13<12<13>11<10>11>10<9<8>9>8<6>7<6<7>8>9<8<9>7<6>7>6<1>2<1<2>3<2<1>2>1<3>5<4>5>4<3<1>2<1<2>3>2<1>2>1<4>5<4<5>6>7<6<7>9<8>9>8<7<6>7>6<8>9<8<9>5<4>5>4<1>2<1<2>3<2<1>2>1<3>4>5<4<5>3<1>2<1<2>3>2<1>2>1<10>11<10<11>13<12>13>12<11<10>11>10<12>13<12<13>17<16>17>16<14>15<14<15>16>17<16<17>15<14>15>14<13<12>13>12<10>11<10<11>12>13<12<13>11<10>11>10<14>15<14<15>17<16>17>16<15<14>15>14<16>17<16<17> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>10<9>10>9<7>8<7<8>9>10<9<10>8<7>8>7<6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<7>8<7<8>10<9>10>9<8<7>8>7<9>10<9<10>18<17>18>17<15>16<15<16>17>18<17<18>16<15>16>15<11>12<11<12>14<13>14>13<12<11>12>11<13>14<13<14>15>16<15<16>18<17>18>17<16<15>16>15<17>18<17<18>14<13>14>13<11>12<11<12>13>14<13<14>12<11>12>11<10<9>10>9<7>8<7<8>9>10<9<10>8<7>8>7<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>7>8<7<8>10<9>10>9<8<7>8>7<9>10<9<10>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<11>12<11<12>14<13>14>13<12<11>12>11<13>14<13<14>18<17>18>17<15>16<15<16>17>18<17<18>16<15>16>15<14<13>14>13<11>12<11<12>13>14<13<14>12<11>12>11<15>16<15<16>18<17>18>17<16<15>16>15<17>18<17<18> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>7<5>6<5<6>7>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>7<6<5>6>5<7>11<10>11>10<8>9<8<9>10>11<10<11>9<8>9>8<7<5>6<5<6>7>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>7<6<5>6>5<7>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<8>9<8<9>11<10>11>10<9<8>9>8<10>11<10<11>19<18>19>18<16>17<16<17>18>19<18<19>17<16>17>16<12>13<12<13>15<14>15>14<13<12>13>12<14>15<14<15>16>17<16<17>19<18>19>18<17<16>17>16<18>19<18<19>15<14>15>14<12>13<12<13>14>15<14<15>13<12>13>12<11<10>11>10<8>9<8<9>10>11<10<11>9<8>9>8<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>7<5>6<5<6>7>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>7<6<5>6>5<7>8>9<8<9>11<10>11>10<9<8>9>8<10>11<10<11>7<5>6<5<6>7>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>7<6<5>6>5<7>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<12>13<12<13>15<14>15>14<13<12>13>12<14>15<14<15>19<18>19>18<16>17<16<17>18>19<18<19>17<16>17>16<15<14>15>14<12>13<12<13>14>15<14<15>13<12>13>12<16>17<16<17>19<18>19>18<17<16>17>16<18>19<18<19> 1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>20<19>20>19<17>18<17<18>19>20<19<20>18<17>18>17<13>14<13<14>16<15>16>15<14<13>14>13<15>16<15<16>17>18<17<18>20<19>20>19<18<17>18>17<19>20<19<20>16<15>16>15<13>14<13<14>15>16<15<16>14<13>14>13<12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<13>14<13<14>16<15>16>15<14<13>14>13<15>16<15<16>20<19>20>19<17>18<17<18>19>20<19<20>18<17>18>17<16<15>16>15<13>14<13<14>15>16<15<16>14<13>14>13<17>18<17<18>20<19>20>19<18<17>18>17<19>20<19<20> ``` NB I think that the longer answers will fail the online test because it uses `GET` rather than `POST` and URLs are not guaranteed to be handled correctly if they're longer than 255 chars. There are two tweaks on the standard construction: 1. In order to ensure that it finishes on the last nail, I actually form the commutator `[x_1, x_2^-1]` instead of `[x_1, x_2]`. 2. Following xnor's example, I don't split 50-50. It turns out that to balance it so the larger numbers are used less frequently\*\* the ideal split is according to [A006165](http://oeis.org/A006165). I'm using David Wilson's observation to calculate it. \* No relation, as far as I'm aware. \*\* Well, within the same recursive commutator approach. I'm not claiming to have solved the open problem of proving it optimal. [Answer] # Python 2 (208 bytes + (7230 - 6,291,370) = -6,283,932) ``` def f(a,b): if a<b+2:return[a] m=(a+b+1)/2 while all(8*x!=2**len(bin(x))for x in[a-m,m-b]):m+=1 A=f(a,m);B=f(m,b) return[-x for x in A+B][::-1]+B+A print"1<1>"+"".join(`abs(x)`+"<>"[x>0]for x in f(input(),0)) ``` The function `f` recursively makes an answer by combining half-solutions as A^{-1}\*B^{-1}\*A\*B, represents inverses by negation. `f(a,b)` is a solution for the numbers in the half-open interval `[a,b)`. *Edit:* To comply with the requirement to start with `1` and end with `n`, I flipped the order to always end with `n` by using reversed intervals, and simply append `"1<1>"` to the beginning. *Edit*: Saved 136 symbols in output by rounding the other way in picking intervals, causing intervals with larger numbers (and so likelier to have two digits) to be shorter. *Edit*: Saved 100 symbols by splitting the intervals unevenly so the one with larger numbers is shorter. This doesn't lengthen the number of operations used as long as the lengths never cross powers of 2. *Edit*: Reintroduced favorable rounding, -50 symbols, 2+ code chars. Outputs for 1 through 20: ``` 1<1>1> 1<1>1<2<1>2> 1<1>2<1<2>1>3<1<2<1>2>3> 1<1>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4> 1<1>3<2<1<2>1>3>1<2<1>2>5<4<5>4>2<1<2>1>3<1<2<1>2>3>4<5<4>5> 1<1>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>5<6<5>6> 1<1>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>7<6<5<6>5>7>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>7<5<6<5>6>7> 1<1>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8> 1<1>5<4<5>4>3<2<1<2>1>3>1<2<1>2>4<5<4>5>2<1<2>1>3<1<2<1>2>3>9<8<9>8>7<6<7>6>8<9<8>9>6<7<6>7>3<2<1<2>1>3>1<2<1>2>5<4<5>4>2<1<2>1>3<1<2<1>2>3>4<5<4>5>7<6<7>6>9<8<9>8>6<7<6>7>8<9<8>9> 1<1>6<5<6>5>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>10<9<10>9>8<7<8>7>9<10<9>10>7<8<7>8>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>5<6<5>6>8<7<8>7>10<9<10>9>7<8<7>8>9<10<9>10> 1<1>7<6<5<6>5>7>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>7<5<6<5>6>7>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>11<10<11>10>9<8<9>8>10<11<10>11>8<9<8>9>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>7<6<5<6>5>7>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>7<5<6<5>6>7>9<8<9>8>11<10<11>10>8<9<8>9>10<11<10>11> 1<1>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12> 1<1>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>13<12<13>12>11<10<9<10>9>11>9<10<9>10>12<13<12>13>10<9<10>9>11<9<10<9>10>11>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>11<10<9<10>9>11>9<10<9>10>13<12<13>12>10<9<10>9>11<9<10<9>10>11>12<13<12>13> 1<1>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>14<13<14>13>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>13<14<13>14>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>14<13<14>13>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>13<14<13>14> 1<1>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>15<14<13<14>13>15>13<14<13>14>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>14<13<14>13>15<13<14<13>14>15>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>15<14<13<14>13>15>13<14<13>14>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>14<13<14>13>15<13<14<13>14>15> 1<1>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>16<15<16>15>14<13<14>13>15<16<15>16>13<14<13>14>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>14<13<14>13>16<15<16>15>13<14<13>14>15<16<15>16>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>16<15<16>15>14<13<14>13>15<16<15>16>13<14<13>14>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>14<13<14>13>16<15<16>15>13<14<13>14>15<16<15>16> 1<1>9<8<9>8>7<6<7>6>8<9<8>9>6<7<6>7>5<4<5>4>3<2<1<2>1>3>1<2<1>2>4<5<4>5>2<1<2>1>3<1<2<1>2>3>7<6<7>6>9<8<9>8>6<7<6>7>8<9<8>9>3<2<1<2>1>3>1<2<1>2>5<4<5>4>2<1<2>1>3<1<2<1>2>3>4<5<4>5>17<16<17>16>15<14<15>14>16<17<16>17>14<15<14>15>13<12<13>12>11<10<11>10>12<13<12>13>10<11<10>11>15<14<15>14>17<16<17>16>14<15<14>15>16<17<16>17>11<10<11>10>13<12<13>12>10<11<10>11>12<13<12>13>5<4<5>4>3<2<1<2>1>3>1<2<1>2>4<5<4>5>2<1<2>1>3<1<2<1>2>3>9<8<9>8>7<6<7>6>8<9<8>9>6<7<6>7>3<2<1<2>1>3>1<2<1>2>5<4<5>4>2<1<2>1>3<1<2<1>2>3>4<5<4>5>7<6<7>6>9<8<9>8>6<7<6>7>8<9<8>9>13<12<13>12>11<10<11>10>12<13<12>13>10<11<10>11>17<16<17>16>15<14<15>14>16<17<16>17>14<15<14>15>11<10<11>10>13<12<13>12>10<11<10>11>12<13<12>13>15<14<15>14>17<16<17>16>14<15<14>15>16<17<16>17> 1<1>10<9<10>9>8<7<8>7>9<10<9>10>7<8<7>8>6<5<6>5>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>8<7<8>7>10<9<10>9>7<8<7>8>9<10<9>10>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>5<6<5>6>18<17<18>17>16<15<16>15>17<18<17>18>15<16<15>16>14<13<14>13>12<11<12>11>13<14<13>14>11<12<11>12>16<15<16>15>18<17<18>17>15<16<15>16>17<18<17>18>12<11<12>11>14<13<14>13>11<12<11>12>13<14<13>14>6<5<6>5>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>10<9<10>9>8<7<8>7>9<10<9>10>7<8<7>8>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>5<6<5>6>8<7<8>7>10<9<10>9>7<8<7>8>9<10<9>10>14<13<14>13>12<11<12>11>13<14<13>14>11<12<11>12>18<17<18>17>16<15<16>15>17<18<17>18>15<16<15>16>12<11<12>11>14<13<14>13>11<12<11>12>13<14<13>14>16<15<16>15>18<17<18>17>15<16<15>16>17<18<17>18> 1<1>11<10<11>10>9<8<9>8>10<11<10>11>8<9<8>9>7<6<5<6>5>7>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>7<5<6<5>6>7>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>9<8<9>8>11<10<11>10>8<9<8>9>10<11<10>11>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>7<6<5<6>5>7>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>7<5<6<5>6>7>19<18<19>18>17<16<17>16>18<19<18>19>16<17<16>17>15<14<15>14>13<12<13>12>14<15<14>15>12<13<12>13>17<16<17>16>19<18<19>18>16<17<16>17>18<19<18>19>13<12<13>12>15<14<15>14>12<13<12>13>14<15<14>15>7<6<5<6>5>7>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>7<5<6<5>6>7>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>11<10<11>10>9<8<9>8>10<11<10>11>8<9<8>9>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>7<6<5<6>5>7>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>7<5<6<5>6>7>9<8<9>8>11<10<11>10>8<9<8>9>10<11<10>11>15<14<15>14>13<12<13>12>14<15<14>15>12<13<12>13>19<18<19>18>17<16<17>16>18<19<18>19>16<17<16>17>13<12<13>12>15<14<15>14>12<13<12>13>14<15<14>15>17<16<17>16>19<18<19>18>16<17<16>17>18<19<18>19> 1<1>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>20<19<20>19>18<17<18>17>19<20<19>20>17<18<17>18>16<15<16>15>14<13<14>13>15<16<15>16>13<14<13>14>18<17<18>17>20<19<20>19>17<18<17>18>19<20<19>20>14<13<14>13>16<15<16>15>13<14<13>14>15<16<15>16>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>16<15<16>15>14<13<14>13>15<16<15>16>13<14<13>14>20<19<20>19>18<17<18>17>19<20<19>20>17<18<17>18>14<13<14>13>16<15<16>15>13<14<13>14>15<16<15>16>18<17<18>17>20<19<20>19>17<18<17>18>19<20<19>20> ``` [Answer] # C - (199 bytes - 0) = 199 ``` p,n,i;main(int x,char **a){for(n=atoi(a[x=i=1]);i<n;i++)x=x*2+2;int o[x];*o=1;for(x=2;n/x;o[++p]=-x++)for(o[i=(++p)]=x;i;o[++p]=-o[--i]);for(i=0;i<=p;printf("%d%s",abs(o[i]),(o[i]<0)?"<":">"),i++);} ``` **With line breaks:** ``` p,n,i; main(int x,char **a) { for(n=atoi(a[x=i=1]);i<n;i++) x=x*2+2; int o[x]; *o=1; for(x=2;n/x;o[++p]=-x++) for(o[i=(++p)]=x;i;o[++p]=-o[--i]); for(i=0;i<=p;printf("%d%s",abs(o[i]),(o[i]<0)?"<":">"),i++); } ``` Probably a fairly naive algorithm given that I don't know that much about knot theory. Basically just adds the next higher number, then reverses the whole instruction set to unwind it. This would likely much more concise in a language that handles sets better... The total output length for `n` in the range `[1..20]` was 6,291,370 bytes of output (3,145,685 instructions). This was huge enough that I only posted [sample outputs](http://pastebin.com/qh8DdFRJ) for `n` in the range `[1..10]`. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 8 years ago. [Improve this question](/posts/8554/edit) This is the 3rd of my series of C/C++ puzzles; in case you missed the first 2 they are here: (1) [m3ph1st0s's programming puzzle 1 (C++)](https://codegolf.stackexchange.com/questions/8506/m3ph1st0ss-programming-puzzle-1-c) (2) [m3ph1st0s's programming puzzle 2 (C++): "Call hard!"](https://codegolf.stackexchange.com/questions/8529/m3ph1st0ss-programming-puzzle-2-c-call-hard) I must say that my puzzles are 100% original. If not, I will always state so in the text. My 3rd puzzle has 2 parts as follows: Puzzle 3.1 This part (3.1) is not an original puzzle of mine, it is collected from some internet page I've read a while ago. I use it here as a starting point and a warm-up for you. Solve this one and then move on to the 2nd part. Some one tried to print the "+" sign 20 times and came up with the following program: ``` #include <stdio.h> int main() { int i; int n = 20; for( i = 0; i < n; i-- ) printf("+"); return 0; } ``` The fact that it did not have the expected result is obvious - the program never ends. Fix it! Easy? Now fix the program by changing ONLY ONE CHARACTER - non-space character of course! For this challenge there are 3 solutions. Find all 3 of them. Just to make it clear: the program must output 20 "+" signs and must end fast. Before criticizing me on what "fast" means, I'll say it means at most a couple of seconds (which by the way is too much but just to make it crystal clear). Puzzle 3.2 **EDITED** ***It was pointed to me earlier that the solution for the 3.2.2 puzzle might be compiler-dependent. In order to eliminate any possible discussion on the subject, I'll modify the idea and improve it on a next puzzle when I'll take extra care not to generate controversy. However, in order to keep this puzzle going, I'll make a small modification for 3.2.2 (the solution will be easier but cleaner).*** When I first saw the puzzle I found it pretty awesome. I did manage to solve it but not immediately since it requires some careful attention. If you are here it means you too solved it. If you did so by writing a program to replace all possible characters with all possible values and test every solution, you are lost. Hard working guy though. Now having corrected the program that writes 20 "+" signs: 3.2.1: Insert **one single letter** and nothing more in the code so that the result is valid and outputs the same thing in all 3 corrected programs. Needless to say, the letter must be before the enclosing } of main (I say that because I don't want to hear people who just put a letter after the program and somehow their compiler was very friendly). **EDITED (see bellow) - For these final questions consider that the counter i starts from -1 instead of 0.** 3.2.1.5: Repeat all previous problems with the condition that the output is at least 19 "+" signs (but still a finite output). Changing spaces is allowed. Now you might have found more solutions than in the first case. Some of these will most definitely fit for the 3.2.2 question. 3.2.2: Choose another value to initialize the variable n so that the resulting output will remain the same for at least one corrected programs in 3.2.1.5(not necessarily for all of them). **LAST EDIT1**: changing the program so that it outputs 21 "+" signs is still a good solution, as the original text did not say "exactly" 20 signs. However, the infinite output is forbidden. Obviously this doesn't mean let's all start outputting hundreds of "+"signs since it's not forbidden. But eliminating a beautiful 21 output would not be in the spirit of this competition. **LAST EDIT2**: considering LAST EDIT1 and **accepting space changing** it seems that now we have 5 possible solutions, four of which have already been pointed out in the responses. The last challenge however hasn't been touched and I must make it clear once more: **n** must be assigned **another value**, solutions that assign 20 to n by some tricks won't do it (like n=20L). Also I prefer to see the 3rd solution that does not change spaces. **LAST EDIT3**: I've edited the last questions, please read! The challenge is to solve both parts of the puzzle. The first one to do it wins. I hope it's all clear, if not please post any questions and I'll edit as quickly as possible. Cheers. *emphasized text* [Answer] ## 3.1 ``` for( i = 0;-i < n; i-- ) for( i = 0; i < n; n-- ) for( i = 0; i + n; i-- ) ``` Any of these changes will make the program output 20 '+' signs. This one is close: ``` for( i = 0;~i < n; i-- ) ``` It outputs 21 '+' signs. ## 3.2.1 I found at least 112 ways to solve this problem inserting one letter. Not all of them may work on all compilers. ``` int n = 20L; int n = 20f; int n = 20d; uint n = 20; for( i = 0L; ... ) for( i = 0f; ... ) for( i = 0d; ... ) iprintf("+"); printf("+x"); printf("x+"); ``` For the last two, substitute any letter for `x` to give you 104 possible solutions. Using either of the last two lines will change the output, but the output will still be the same for all 3 corrected programs. ## 3.2.2 All I've come up with are some things that get cast back to the number 20 on assignment to `int`. ``` int n = 20L; int n = 20.001; int n = 20.999; int n = 20 + 0x100000000L; ``` [Answer] 3.1 Yet another puzzle. But normal solutions are boring, what about something special? Solution one: ``` #include <stdio.h> int main() { int i; int n = 20; for( i = 0; i < n; i++ ) printf("+"); return 0; } ``` I decided to change ONLY ONE CHARACTER, that is, `-`. No characters other than `-` were changed. Solution two: ``` #include <stdio.h> int main() { int i=printf("++++++++++++++++++++");exit(0); int n = 20; for( i = 0; i < n; i-- ) printf("+"); return 0; } ``` This changes exactly one character - the semicolon after `int i` into `=printf("++++++++++++++++++++");exit(0);`. Solution three: ``` #include <stdix.h> int main() { int i; int n = 20; for( i = 0; i < n; i-- ) printf("+"); return 0; } ``` This loads the `stdix.h` system header. In the system include path, insert the following file, called stdix.h. It has to contain the following contents. ``` static inline void printf(const char *string) { int i; for(i = 0; i < 20; i--) putchar('+'); exit(0); } ``` --- 3.2 Now to insert one letter. Well, that's simple, replace `int main()` with `int main(a)`. This is not valid according to standards, but who cares? [Answer] ## Puzzle 3.1 Answers 1. Change `i--` to `n--` (demo: <http://ideone.com/l0Y10>) 2. Change `i < n` to `i + n` (demo: <http://ideone.com/CAqWO>) 3. Change `[SPACE]i < n` to `-i < n`. (demo: <http://ideone.com/s5Z2r>) ## Puzzle 3.2.1 Change `int n = 20` to `int n = 20L` (add an `L` to the end). ## Puzzle 3.2.2 Haven't found an answer yet... [Answer] 3.1 1. Change `i--` to `n--` 2. `i<n` to `-i<n` 3. (Unfortunately invalid answer because I wasn't checking with compiler before seeing other answers) 3.2.1 ``` int n = 20 ``` to ``` uint n = 20 ``` (Compiler dependent...) 3.2.2 ``` int n =-20L; for(i = -1; i%n; i--) ``` prints 19 + signs, same as with `int n = 20L;`. However, I wouldn't have come up with it if I hadn't seen other answers to 3.2.1 [Answer] ``` #include <stdio.h> int main() { int i; int n = 20; for( i = 0; i < n; i++ ) printf("+"); printf("\n"); return 0; } ``` ]
[Question] [ Which values of x and y will cause a crash with some C compilers? ``` int f(int x, int y) { return (y==0) ? 0 : (x/y); } ``` [Answer] -2147483648 (INT\_MIN) and -1 ``` #include <stdio.h> #include <limits.h> int f(int x, int y) { return (y==0) ? 0 : (x/y); } int main() { int r = f(INT_MIN, -1); printf("%d\n", r); return 0; } ``` $ gcc -Wall division.c && ./a.out # => zsh: floating point exception ./a.out [Answer] The right answer is already given, but I immediately thought about [Microsoft Pex](https://research.microsoft.com/en-us/projects/pex/). > > Pex automatically generates test suites with high code coverage. Right > from the Visual Studio code editor, Pex finds interesting input-output > values of your methods, which you can save as a small test suite with > high code coverage. Microsoft Pex is a Visual Studio add-in for > testing .NET Framework applications > > > After [adding your puzzle](http://www.pexforfun.com/default.aspx?language=CSharp&code=jQDsvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee__997o7nU4n99%2f%2fP1xmZAFs9s5K2smeIYCqyB8%2ffnwfPyLWTbG8SF9fN22_OExSevif1XpSFtN0WmZNk76sq4s6W6S%2fmL_yXzZt1tKPYtmmL9c%2f_EGZb_HXdyP_5PqObZ6mdd6u62W6df3ZZzt30t8j3UkfpVvv7l7fOdQmv4R%2f%2fpL%2fJwAA%2f%2f8%3d) in the sandbox site, it finds the answer in a few seconds, the same as eregons answer. (click ask pex) *Note: it does it in C#, but the language is not really relevant.* * x: int.MinValue * y: -1 * Exception: OverflowException * Message: Arithmetic operation resulted in an overflow. ]
[Question] [ Pretend you have an arbitrary text file (which you may choose). Give the sequence of keystrokes that is most destructive (\*) if it was intended to be inserted to the text, but instead was entered in normal mode (i.e. `i`/`a` was not pressed). You may not enter visual mode and not quit Vim. Destructive is defined as follows: The ratio of changed/deleted characters by the number of necessary keystrokes. You get bonus points if your changes cannot be undone by a fixed number of `u`ndos. --- Example: Input file without line breaks. Input sequence: `d``f``s`. [Answer] ``` : 0,0 w :r ``` ruins everything no undo [Answer] ``` :set ul=-1 ggdG :w ``` This clears contents of file and saves it. No undo is possible because `undolevel` is set to a negative number, which disables undo operation. Edit: It's better to write `:g/^/d` instead of `ggdG`, because in the latter case you can use `p` (put) to roll-back the changes. [Answer] ``` :set ul=-1 :%s///g :r!head -c1G</dev/urandom :w ``` 1. Disables undo 2. Deletes characters 3. Reads 1G of data from /dev/urandom 4. Saves Bending the rules, because I am adding characters (a character that isn't there and now is, means a character was changed). I can add as much characters as I want so this score is theoretically infinite. [Answer] 5 bytes: ``` :bd! ``` followed by a press of enter. Throws away the current state of the file you're editing from memory, so all unsaved changes in that file are lost. If you have other files open, they are not affected. This does not quit vim even if you have only one file open. ]
[Question] [ Dealing with equations in the absence of a good equation editor is messy and unpleasant. For example, if I wanted to express an integral and its solution, it might look something like this: Integral[x^3 e^(-m x^2 b /2), dx] = -((2 + b*m*x^2)/(b^2\*e^((b*m*x^2)/2)\*m^2)) At [integrals.wolfram.com](http://integrals.wolfram.com/index.jsp), this is called "input form." No one likes to see an equation in "input form." The ideal way of visualizing this equation would be: ![enter image description here](https://i.stack.imgur.com/uDj0k.png) (Wolfram calls this "traditional form") For this codegolf, write a program that will take some equation in "input form" as input and visualize that equation in an ascii representation of "traditional form." So, for this example we might get something like this: ``` /\ 3 | x | ------------ dx = | 2 \/ (m x b)/2 e 2 2 + b m x -(-----------------) 2 2 (b m x )/2 2 b e m ``` Requirements: 1. Don't shuffle, simplify or rearrange the input in any way. Render it in exactly the same form it was described by the input. 2. Support the four basic mathematical operations (+,-,\*,/). When not multiplying two adjacent numbers the \* symbol is implied and should be omitted. 3. Support for integration (as shown in the example above) is **not** required. Being able to support input with functions like Integrate[...] or Sqrt[...] is a bonus. 4. Support powers as shown in the example above (the nth root can be modeled by raising to the 1/nth power). 5. Redundant parenthesis (like those around the denomentator and numerator of the large fraction in the example above) should be omitted. 6. The expression in the denominator and numerator of a fraction should be centered above and below the horizontal division line. 7. You can choose whether or not to start a new line after an equal sign. In the example above, a new line is started. 8. Order of operations must be exactly the same in the output as it is in the input. Some examples of input and associated output for testing your solution: **Input:** ``` 1/2 + 1/3 + 1/4 ``` **Output:** ``` 1 1 1 - + - + - 2 3 4 ``` **Input:** ``` 3x^2 / 2 + x^3^3 ``` **Output:** ``` 2 3 3 x 3 ---- + x 2 ``` **Input:** ``` (2 / x) / (5 / 4^2) ``` **Output:** ``` 2 - x -- 5 -- 2 4 ``` **Input:** ``` (3x^2)^(1/2) ``` **Output:** ``` 2 1/2 (3 x ) ``` [Answer] ## Python 2, 1666 chars The layout is actually pretty easy - it's the parsing of the input that's a royal pain. I'm still not sure it is completely correct. ``` import re,shlex s=' ' R=range # Tokenize. The regex is because shlex doesn't treat 3x and x3 as two separate tokens. The regex jams a space in between. r=r'\1 \2' f=re.sub x=shlex.shlex(f('([^\d])(\d)',r,f('(\d)([^\d])',r,raw_input()))) T=[s] while T[-1]:T+=[x.get_token()] T[-1]=s # convert implicit * to explicit * i=1 while T[i:]: if(T[i-1].isalnum()or T[i-1]in')]')and(T[i].isalnum()or T[i]in'('):T=T[:i]+['*']+T[i:] i+=1 # detect unary -, replace with ! for i in R(len(T)): if T[i]=='-'and T[i-1]in'=+-*/^![( ':T[i]='!' print T # parse expression: returns tuple of op and args (if any) B={'=':1,',':2,'+':3,'-':3,'*':4,'/':4,'^':5} def P(t): d,m=0,9 for i in R(len(t)): c=t[i];d+=c in'([';d-=c in')]' if d==0and c in B and(B[c]<m or m==B[c]and'^'!=c):m=B[c];r=(c,P(t[:i]),P(t[i+1:])) if m<9:return r if'!'==t[0]:return('!',P(t[1:])) if'('==t[0]:return P(t[1:-1]) if'I'==t[0][0]:return('I',P(t[2:-1])) return(t[0],) # parenthesize a layout def S(x): A,a,b,c=x if b>1:A=['/'+A[0]+'\\']+['|'+A[i]+'|'for i in R(1,b-1)]+['\\'+A[-1]+'/'] else:A=['('+A[0]+')'] return[A,a+2,b,c] # layout a parsed expression. Returns array of strings (one for each line), width, height, centerline def L(z): p,g=z[0],map(L,z[1:]) if p=='*': if z[1][0]in'+-':g[0]=S(g[0]) if z[2][0]in'+-':g[1]=S(g[1]) if p=='^'and z[1][0]in'+-*/^!':g[0]=S(g[0]) if g:(A,a,b,c)=g[0] if g[1:]:(D,d,e,f)=g[1] if p in'-+*=,': C=max(c,f);E=max(b-c,e-f);F=C+E;U=[s+s+s]*F;U[C]=s+p+s;V=3 if p in'*,':U=[s]*F;V=1 return([x+u+y for x,u,y in zip((C-c)*[s*a]+A+(E-b+c)*[s*a],U,(C-f)*[s*d]+D+(E-e+f)*[s*d])],a+d+V,F,C) if'^'==p:return([s*a+x for x in D]+[x+s*d for x in A],a+d,b+e,c+e) if'/'==p:w=max(a,d);return([(w-a+1)/2*s+x+(w-a)/2*s for x in A]+['-'*w]+[(w-d+1)/2*s+x+(w-d)/2*s for x in D],w,b+e+1,b) if'!'==p:return([' - '[i==c::2]+A[i]for i in R(b)],a+2,b,c) if'I'==p:h=max(3,b);A=(h-b)/2*[s*a]+A+(h-b+1)/2*[s*a];return([' \\/|/\\ '[(i>0)+(i==h-1)::3]+A[i]for i in R(h)],a+3,h,h/2) return([p],len(p),1,0) print'\n'.join(L(P(T[1:-1]))[0]) ``` For the big input in the question, I get: ``` /\ 2 2 | - m x b 2 + b m x | -------- = - ------------- | 3 2 2 \/ x e dx b m x ------ 2 2 2 b e m ``` Here's some more tricky test cases: ``` I:(2^3)^4 O: 4 / 3\ \2 / I:(2(3+4)5)^6 O: 6 (2 (3 + 4) 5) I:x Integral[x^2,dx] y O: /\ 2 x | x dx y \/ I:(-x)^y O: y (- x) I:-x^y O: y (- x) ``` That last one is wrong, some precedence error in the parser. ]
[Question] [ You are given an encrypted string, encrypted using a very simple substitution cipher. **Problem** You do not know what the cipher is but you do know the ciphertext is English and that the most frequent letters in English are *etaoinshrdlucmfwypvbgkqjxz* in that order. The only allowed characters are uppercase letters and spaces. You can do basic analysis - starting from single letters, but you can migrate onto more complex multi-letter analysis - for example, U almost always follows Q, and only certain letters can come twice in a row. **Examples** ``` clear : SUBMARINE TO ATTACK THE DOVER WAREHOUSE AND PORT ON TUESDAY SUNRISE cipher: ZOQ DUPAEYSRYDSSDXVYSHEYNRBEUYLDUEHROZEYDANYKRUSYRAYSOEZNDMYZOAUPZE clear : THE QUICK BROWN FOX BEING QUITE FAST JUMPED OVER THE LAZY DOG QUITE NICELY cipher: TNAEPDHIGEMZQJLEVQBEMAHL EPDHTAEVXWTEODYUASEQKAZETNAERXFCESQ EPDHTAELHIARC clear : BUFFALO BUFFALO BUFFALO BUFFALO BUFFALO BUFFALO BUFFALO cipher: HV WRPDHV WRPDHV WRPDHV WRPDHV WRPDHV WRPDHV WRP ``` **Challenges** See if you can decrypt the text in each of these ciphers: * `SVNXIFCXYCFSXKVVZXIHXHERDXEIYRAKXZCOFSWHCZXHERDXBNRHCXZR RONQHXORWECFHCUH` * `SOFPTGFIFBOKJPHLBFPKHZUGLSOJPLIPKBPKHZUGLSOJPMOLEOPWFSFGJLBFIPMOLEOPXULBSIPLBP` `KBPBPWLIJFBILUBKHPGKISFG` * `TMBWFYAQFAZYCUOYJOBOHATMCYNIAOQW Q JAXOYCOCYCHAACOCYCAHGOVYLAOEGOTMBWFYAOBFF` `ACOBHOKBZYKOYCHAUWBHAXOQW XITHJOV WOXWYLYCU` * `FTRMKRGVRFMHSZVRWHRSFMFLMBNGKMGTHGBRSMKROKLSHSZMHKMMMMMRVVLVMPRKKOZRMFVDSGOFRW` I have the substitution matrices and cleartext for each, but I will only reveal them if it becomes too difficult or someone doesn't figure it out. **The solution which can decrypt the most messages successfully is the winner. If two solutions are equally good, they will be decided by vote counts.** [Answer] ## Python I've figured out all the secret phrases, but I won't post them here. Run the code if you care. The code works by picking a space character, enumerating all possible substitutions for each word, then searching for compatible substitutions. It also allows for some out-of-lexicon words to deal with misspellings in the cleartext :) I used a large lexicon (~500K words) from <http://wordlist.sourceforge.net/>. ``` import sys,re # get input message = sys.argv[1] # read in lexicon of words # download scowl version 7.1 # mk-list english 95 > wordlist lexicon = set() roman_only = re.compile('^[A-Z]*$') for word in open('wordlist').read().upper().split(): word=word.replace("'",'') if roman_only.match(word): lexicon.add(word) histogram={} for c in message: histogram[c]=0 for c in message: histogram[c]+=1 frequency_order = map(lambda x:x[1], sorted([(f,c) for c,f in histogram.items()])[::-1]) # returns true if the two maps are compatible. # they are compatible if the mappings agree wherever they are defined, # and no two different args map to the same value. def mergeable_maps(map1, map2): agreements = 0 for c in map1: if c in map2: if map1[c] != map2[c]: return False agreements += 1 return len(set(map1.values() + map2.values())) == len(map1) + len(map2) - agreements def merge_maps(map1, map2): m = {} for (c,d) in map1.items(): m[c]=d for (c,d) in map2.items(): m[c]=d return m def search(map, word_maps, outside_lexicon_allowance, words_outside_lexicon): cleartext = ''.join(map[x] if x in map else '?' for x in message) #print 'trying', cleartext # pick a word to try next best_word = None best_score = 1e9 for (word,subs) in word_maps.items(): if word in words_outside_lexicon: continue compatible_subs=0 for sub in subs: if mergeable_maps(map, sub): compatible_subs += 1 unassigned_chars = 0 for c in word: if c not in map: unassigned_chars += 1 #TODO: duplicates? if compatible_subs == 0: score = 0 elif unassigned_chars == 0: score = 1e9 else: score = 1.0 * compatible_subs / unassigned_chars # TODO: tweak? if score < best_score: best_score = score best_word = word if not best_word: # no words with unset characters, except possibly the outside lexicon ones print cleartext,[''.join(map[x] if x in map else '?' for x in word) for word in words_outside_lexicon] return True # use all compatible maps for the chosen word r = False for sub in word_maps[best_word]: if not mergeable_maps(map, sub): continue r |= search(merge_maps(map, sub), word_maps, outside_lexicon_allowance, words_outside_lexicon) # maybe this word is outside our lexicon if outside_lexicon_allowance > 0: r |= search(map, word_maps, outside_lexicon_allowance - 1, words_outside_lexicon + [best_word]) return r for outside_lexicon_allowance in xrange(3): # assign the space character first for space in frequency_order: words = [w for w in message.split(space) if w != ''] if reduce(lambda x,y:x|y, [len(w)>20 for w in words]): continue # obviously bad spaces # find all valid substitution maps for each word word_maps={} for word in words: n = len(word) maps = [] for c in lexicon: if len(c) != n: continue m = {} ok = 1 for i in xrange(n): if word[i] in m: # repeat letter if m[word[i]] != c[i]: ok=0; break # repeat letters map to same thing elif c[i] in m.values(): ok=0; break # different letters map to different things else: m[word[i]]=c[i] if ok: maps.append(m); word_maps[word]=maps # look for a solution if search({space:' '}, word_maps, outside_lexicon_allowance, []): sys.exit(0) print 'I give up.' ``` [Answer] ## PHP (Incomplete) This is an incomplete PHP solution which works using the letter frequency information in the question plus a dictionary of words matched with regular expressions based on the most reliable letters in the given word. At present the dictionary is quite small but with the appropriate expansion I anticipate that results would improve. I have considered the possibility of partial matches but with the current dictionary this results in degradation rather than improvement to the results. **Even with the current, small dictionary I think I can quite safely say what the fourth message encodes.** ``` #!/usr/bin/php <?php if($argv[1]) { $cipher = $argv[1]; // Dictionary $words = explode("/", "the/to/on/and/in/is/secret/message"); $guess = explode("/", "..e/t./o./a../i./.s/.e..et/.ess..e"); $az = str_split("_etaoinshrdlucmfwypvbgkqjxz"); // Build table for($i=0; $i<strlen($cipher); $i++) { $table[$cipher{$i}]++; } arsort($table); // Do default guesses $result = str_replace("_", " ", str_replace(array_keys($table), $az, $cipher)); // Apply dictionary $cw = count($words); for($i=0; $i<$cw*2; $i++) { $tokens = explode(" ", $result); foreach($tokens as $t) { if(preg_match("/^" . $guess[$i%$cw] . "$/", $t)) { $result = deenc($words[$i%$cw], $t, $result); echo $t . ' -> ' . $words[$i%$cw] . "\n"; break; } } } // Show best guess echo $result . "\n"; } else { echo "Usage: " . $argv[0] . " [cipher text]\n"; } // Quick (non-destructive) replace tool function deenc($word, $enc, $string) { $string = str_replace(str_split($enc), str_split(strtoupper($word)), $string); $string = str_replace(str_split($word), str_split($enc), $string); return strtolower($string); } ?> ``` ]
[Question] [ **Party time!** All of your guests are sitting around a round table, but they have very particular seating requirements. Let's write a program to organize them automatically! Guests are represented by letters: Female guests are uppercase, males are lowercase. Couples have the same letter, one lower and one upper, like `gG`, who just had their golden marriage (congrats!). **The rules** 1. Neither place a male between two other males nor a female between two other females. 2. Couples must sit next to each other. 3. Alphabetically adjacent letters of the same sex are rivals! Never place two rivals next to each other (like `BA`) or a rival next to the partner of an attendant partner (like `bBc`, but `xaBcz` is fine, because none of them have jealous partners at the party). Answering a comment: `A`and `Z` are not adjacent in any alphabet I'm aware of. (-; ## I/O You may take input as either a string or a list of letters `[a-zA-Z]` \*(or, only if your language of choice has no characters, integers from 1 to 52 representing them, males are even, females are odd :-), which will always be unique (i.e. no duplicates). Remember: this is a *round* table, so ensure that your answer takes wrapping into account. Your output has to be at least one of all possible table arrangements for the input. Where the cut is doesn't matter. If no valid arrangements exist for the input, give an output of your choice which is obviously no sitting arrangement, from an ugly program crash over empty output to some polite message (sorry, no extra score for that). **Examples** ``` A --> A (boring party, but valid) BbCc --> <none> gdefEDH --> HfdDgeE OMG --> <none> hiJk --> <none> hMJkK --> hJMkK NoP --> NoP rt --> rt qQXZxyz --> <none> BIGbang --> bIgGanB ``` *(P.S.: In case you miss same-sex couples, non-binaries, polycules, and such ‚Äì I like those at my personal party, but not in this challenge, to keep it simple.)* [Answer] # [Ruby](https://www.ruby-lang.org/), 151 bytes ``` f=->x{[x,x[1..-1]+x[0]].any?{|g|a=g.upcase g=~/[a-z]{3}|[A-Z]{3}/||a=~/(.).+\1/||a.bytes.each_cons(2).any?{|a,b|(a-b).abs==1}}?f[x.chars.shuffle*'']:x} ``` [Try it online!](https://tio.run/##LYzRboIwFEDf/QrTF0HoZeibSTXuxewPNrtmuW0omCAyKslFWn@dYbK3c5KT0/V6mCYr@J5GSSnJHIDnKiH5phRgMxxGX3oUJfStQVcsSvHMJPKHGrfByyM/vyDzc/LMIogh@c5fBnq4Fw4KNNWPuTUu2sT/N0y1j5Dr2bUTIg/hYCWBqbBz4Kre2rpYr1ZqR2GS7MhS9v5x0tiUM/1@DY/zJzEFV2xHT77tLs19acFgXUcUJ2zBwvQH "Ruby ‚Äì Try It Online") Shuffles input until valid, if can't find shuffles forever as undefined behavior [Answer] # Python3, 486 bytes: ``` R=lambda a,b:chr(ord(a)+1)!=b and chr(ord(a)-1)!=b K=lambda a,b:len(a)<2or a[-2].islower()!=b.islower() V=lambda a,i:K(a,i)and R(a[-1],i)and(len(a)<2 or R(a[-2],i)) def f(s): q=[(i,{*s}-{i})for i in s] for a,b in q: if not b: if V(a,a[0]):return a continue if(T:=a[-1].upper())in b: if K(a,T):q+=[(a+T,b-{T})];q+=[(T+a,b-{T})]*(len(a)==1) elif(T:=a[-1].lower())in b: if K(a,T):q+=[(a+T,b-{T})];q+=[(T+a,b-{T})]*(len(a)==1) else:q+=[(a+i,b-{i})for i in b if V(a,i)] ``` [Try it online!](https://tio.run/##rVBNU8IwEL33V8QTCaWM4MWp9oAfg8KgDtNhVKaHhKaQoaZtWkaR4bfXTaVA1KOXTN7bfW/fbrouFok8O09VWY69mL6xkCLaYu5soXCiQkyJ3SEnHkNUhuhAOhVpDY8lMZdQuewmCtGp0w3aIo@Td66wbj0Aa3IQCXeI4SXafIxB1Qm@Ea7NELhVla6uECvkEYpwTlwLZd4Ui9ammW@djdiSCDoFEhLlgYU0gEwaZtCKRIRkUiCm/xpMYCydngbEVbxYKYmoLswSWQi54pUA@65XJWqv0lQHJ2C2N9C5feJmNoSgtt9izsbfkuCiInyb1kRzt4nndQhIeXxsvLvI/xjnvBYJ3XN8EVavLEhQpkrIAke40WvAPffoil3PDGIOp769MajHUd/ACzFY/iKGBpM9v7x@rD/NUfd9RuXc4Ohg2ftj/J1pP/pp/5A8AS6/AA) A little long, but not naive brute force. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~49~~ 37 bytes ``` O-·π´?3;Od32·∫°∆ùS‚Äò1¬¶∆≤3∆§;·∫°∆ù‚Äô∆≤;≈íuƒ†I·ªä∆≤»¶ ≈í!√á∆á ``` [Try it online!](https://tio.run/##AZsAZP9qZWxsef//Ty3huas/MztPZDMy4bqhxp1T4oCYMcKmxrIzxqQ74bqhxp3igJnGsjvFknXEoEnhu4rGssimCsWSIcOHxof/w4fhuKMxCjvigJwgLT4g4oCdO8OHCuG7tMOH4oKsWf//QQpCYkNjCmdkZWZFREgKT01HCmhpSmsKaE1Ka0sKTm9QCnJ0CnFRWFp4eXoKQklHYmFuZw "Jelly ‚Äì Try It Online") (shows just one example for each case for brevity) *Thanks to @JonathanAllan for saving 2 bytes!* A pair of monadic links taking a list of characters and returning a list of lists of characters. Returns all possible arrangements except those where a couple is split across the join. Handling inputs with length 1 and 2 added more complexity than I would have expected! ## Explanation (outdated) ``` ≈íuƒ†I·ªä;O.·ªãj∆ä;-$L>2∆ä?:96E3∆§;%32IAS∆≤3∆§;I·ªä∆≤∆≤¬¨∆≤»¶ # ‚Äé‚ŰHelper link: takes a list of characters and returns 1 if it‚Äôs a valid arrangement and 0 if not ≈íu # ‚Äé‚Å¢Convert to upper case ƒ† # ‚Äé‚Å£Indices of like-members (partners here) grouped together I # ‚Äé‚ŧIncrements within each group ·ªä # ‚Äé‚Å¢‚Ű<= 1 (overall, this tests for rule 2; i.e. indices of partners are adjacent ; ∆≤ # ‚Äé‚Å¢‚Å¢Concatenate to the following, applied to the original helper link argument: O # ‚Äé‚Å¢‚Å£- Convert to codepoints L>2∆ä? # ‚Äé‚Å¢‚ŧ- If length of list >2: .·ªãj∆ä # ‚Äé‚Å£‚Ű - Then: Take the last and first members of the list, and respectively prepend and append them ;-$ # ‚Äé‚Å£‚Å¢ - Else: Concatenate -1 ∆≤ # ‚Äé‚Å£‚Å£- Following as a monad (argument to this is referred to as a in description below): :96 # ‚Äé‚Å£‚ŧ - z div 96 E3∆§ # ‚Äé‚ŧ‚Ű - Check whether each overlapping infix length 3 has three equal values ; ∆≤ # ‚Äé‚ŧ‚Å¢ - Concatenate to the result of the following applied to z: ∆≤3∆§ # ‚Äé‚ŧ‚Å£ - Apply the following to each infix of z of length 3: %32 # ‚Äé‚ŧ‚ŧ - Mod 32 I # ‚Äé‚Å¢‚Ű‚Ű - Increments S # ‚Äé‚Å¢‚Ű‚Å¢ - Sum A # ‚Äé‚Å¢‚Ű‚Å£ - Absolute ;I # ‚Äé‚Å¢‚Ű‚ŧ - Concatenate to increments of z ·ªä # ‚Äé‚Å¢‚Å¢‚Ű - Absolute of this <= 1 ¬¨ # ‚Äé‚Å¢‚Å¢‚Å¢- Not »¶ # ‚Äé‚Å¢‚Å¢‚Å£Any and all (flattened list contains no zeros) ≈í!√á∆á # ‚Äé‚Å¢‚Å£‚ŰMain link: takes a list of characters and returns a list of lists of characters ≈í! # ‚Äé‚Å¢‚Å£‚Å¢All permutations √á∆á # ‚Äé‚Å¢‚Å£‚Å£Keep those where the helper link returns 1 üíé ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~44~~ ~~43~~ 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ≈ì íƒÅ._¬ªA3√£Du¬´√•ylD√îs√ô√äyƒÜ√á√ºŒ±yƒÜl√á√ºŒ±ƒÜ√º¬´D√≠)Àú‚â†P ``` Outputs a list of all valid table-arrangements, or `[]` if none are. (If this is not allowed, `í` can be `.Œî` for +1 byte, so it'll output the first valid result, or `-1` if none are.) [Try it online](https://tio.run/##yy9OTMpM/f//6ORTk4406sUf2u1ofHixS@mh1YeXVua4HJ5SfHjm4a7KI22H2w/vObcRyMiBsIAiew6tdjm8VvP0nEedCwL@/09PSU1zdfEAAA). (Times out after 60 seconds, only outputting some of the valid results.) Here a slightly modified version (`A3√£Du¬´` to `D√°√º3Dlsu¬´`) which is fast enough to output all test cases: [Try it online](https://tio.run/##yy9OTMpM/f//6ORTk4406sUf2u1yeOHhPcYuOcWlh1YfXlqZ43J4SvHhmYe7Ko@0HW4/vOfcRiAjB8ICiuw5tNrl8FrN03MedS4I@P8/PSU1zdXFAwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5NPTTrSqBd/aLfL4YWH9xi75BSXHlp9eGlljsvhKcWHZx7uqjzSdrj98J5zG4GMHAgLKLLn0GqXw2s1T8951Lkg4H@tzv9oJUclHSWnJOdkIJWekprm6uIBZPn7ugPJjEyvbBDl65XtDaT98gOAZFEJkCgMjIiqqKwCafV0T0rMSweyHJ2UYgE). **Explanation:** ``` ≈ì # Get all permutations of the (implicit) input  í # Filter the list of permutation-strings by: ƒÅ._¬ªA3√£Du¬´√•)Àú‚â†P # Verify rule 1: ƒÅ # Push a list in the range [1,length] (without popping) ._ # For each value, convert it to a rotation of the permutation ¬ª # Join this list of rotation-strings by newlines A # Push the lowercase alphabet 3√£ # Cartesian power of 3 to create all possible lowercase triplets D # Duplicate this list of triplets u # Uppercase each string in the copy ¬´ # Merge the lowercase and uppercase lists of triplets together √• # Check for each triplet if it's a substring of the joined # rotations of the current permutation ... # (rules 2 and 3) ) # Wrap all checked rules into a list (of lists/values) Àú # Flatten it ‚â†P # Verify that none are truthy ylD√îs√ô√ä)Àú‚â†P # Verify rule 2: y # Push the permutation string again l # Convert the string to lowercase D # Duplicate it √î # Connected uniquify its characters s # Swap so the lowercase string is at the top again √ô # Regular uniquify its characters √ä # Check that they are NOT the same ... # (rule 3) )Àú‚â†P # Same as above: verify that it's not truthy, # which is why we've used an inverted equals-check `√ä` here yƒÜ√á√ºŒ±)Àú‚â†P # Verify rule 3a: y # Push the permutation string yet again ƒÜ # Enclose; append its own first character √á # Convert it to a list of codepoint integers √º # For each overlapping pair: Œ± # Get the absolute difference ... # (rule 3b) )Àú‚â†P # Same as above: verify that none are 1 yƒÜl√á√ºŒ±ƒÜ√º¬´D√≠)Àú‚â†P # Verify rule 3b: y # Push the permutation string yet again ƒÜ # Enclose; append its own first character l # Convert it to lowercase √á # Convert it to a list of codepoint integers √ºŒ± # For each overlapping pair: Get the absolute difference ƒÜ # Enclose this list as well √º¬´ # Join each overlapping pair of integers together to a string D # Duplicate this list of integer-strings √≠ # Reverse each string in the copy )Àú‚â†P # Same as above: verify that none are "01" # (after which the filtered list is output implicitly) ``` [Answer] # [sed](https://www.gnu.org/software/sed/) `-E`, ~~¬†455¬†~~ 448 bytes (theoretically 447 bytes, see explanation, but who cares as long as `sed` beats `python`?!) I finally added my own reference implementation using `sed` just because regex-golfing is fun. ``` G s/./&_-/ :1 s/(\S*)_(\S*)-(\S)(\S*\n)/\1\3_-\2\4\1_\2\3-\4/ t1 s/[-_]//g h :2 g /^$/q s/\S*.// x s/\n.*// s/(..)?.+/aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ #:&\1/ :r /:#/b4 /^(..)*(.)(.)(.)(.).*(\2\4|\3\5\3\2\5|\2\3\4|\3\4\5|\2\5\4)/b2 /(.).(..)*(.).(..)*(.).* .*(\1\3\5|\1\5\3|\3\1\5)/b2 :3 s/ (.*:)(.)/ \2\1/ t3 s/(\S*):/:\1/ br :4 s/^((..)*)(.)(.)(.*(\3\4|\4\3))/\1\5/ t4 /^(..)*(.)(.).*(\2.+\3|\3.+\2)/b2 s/.*#(..)?(...*)/\2/ ``` It's brute force, with the `1` loop producing all combinations of guests, ignoring duplicates in favor of size over speed. Yes, you could save one more byte with `s/^/_-/` in line two, but this will create so extremely amounts of duplicates that it will time out even for quite small parties. The `2` loop takes one combination after another from the hold space to test it. I need to waste a lot of bytes to teach `sed` the alphabet, but at the same time I can close the round table by duplicating the first two guest at the end. Here I originally had a giant regex for the rival test and another regex for the three-of-the-same-sex-test, both backwards and forwards. But then I discovered that the extra bytes for reverting the string in loop `3` and using loop `r` to check the reversed order pays out by having only half of the expressions. The test for couples sitting apart was more tricky: A simple regex check won't work, because if they are at the first two seats, they will look like sitting apart because of the first partner reappearing on the other end. I solved it by removing couples I found sitting next to each other from the alphabet in loop `4` before testing. I wonder if there are still some bytes to save! [Try it online!](https://tio.run/##XVHbTsJAEH3fr2iCId0l3Unb7cu@GC@Id0W8II40VrDgpVxaFAjfbp1dIiYm3Zmzkz1nzkzzfs9Ls1lZNlgOEqqxB0z7hF1sCR7b6FHkBmHGAX0MYw8DVOjHlEIPFbDCUB68@BEgZQOmA5Yy6G7BhMpElABsbmAmBUFSl5Jvyxo87SS7z3u9/X795SBtDA6HR6/Hbyfvpx9n2fnoYnw5aU6v8lZxPbv5vP26m7cX98uOU9FV9Mnm1HEY6AokinoZReFKvvmkcI3LFYYY0QkwWhm764pa3yJUHJKAgXn/q/AHhGNEfKOwokQyhkvAknRIgziuFNq0A4f0yFUR/i5PgzaFxNjUiqpd1ypvLJK2taMw5HaxEdH/zWKnkDXbmVJgO9OfEhW7QgpSEDeAspw02535Yvk9GhfDUZaXXv0H "sed ‚Äì Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~158~~ ~~133~~ ~~131~~ 114 bytes ``` ‚âî¬ßŒ∏‚Å∞Œ∑‚äûœÖŒ∑Ôº¶œÖ¬´‚âî‚Ū‚™™Œ∏¬π‚™™Œπ¬πŒ∂Ôº¶‚஌∂Œ∑¬´‚âî‚Å∫Œ∫ŒπŒ¥¬ø‚ஂÄπÔº¨Œ¥¬≥Ôπ™Œ£Ôº•‚ĶŒ¥¬≥‚ÑñŒ±Œª¬≥¬ø‚¨§‚ŪŒ∂‚ü¶Œ∫‚ü߬¨‚Ññ‚Ü•‚ŪŒπŒ∑‚Ü•Œª¬ø‚äñ‚Üî‚Ū‚ÑÖ‚Ü•Œ∫‚ÑÖ‚Ü•¬ßŒπ‚Å∞¬øŒ∂‚äûœÖŒ¥¬ø‚ஂÄπÔº¨Œπ¬≥Ôπ™Œ£Ôº•‚Ķ‚Å∫¬ßŒπ‚Å∞‚ÆåŒπ¬≥‚ÑñŒ±Œª¬≥¬ø¬¨‚Ññ‚Ü•‚úÇŒπ¬π¬±¬≤¬¶¬π‚Ü•Œ∑‚ü¶Œπ ``` [Try it online!](https://tio.run/##hZFNT8MwDIbP26/I0ZGKxMeRU7UhgcTYxMRp2qE0XhstS0o@Jhjaby9O2mogJjg0qmM/r53XZV3Y0hSqbXPnZKUh9w9a4Du8ZeySZ6zmt@NFcDWE7n9jLIPA2ed41AMzqYODZaOkj9AVQV0gY0DRgbBR4uYWDlEm4QO/UIRvMyapVMTSkdyk0kd0jg5d@RoEJW/omxkRlIFl2MGsaGDyUSqc1KYB0eUnJmgPRcYU5wmhXlEuV6oflAZYbdeUezIeuvKXpkFbFg77EplmzNjpPqr1SlMsLe5QexSQvzqjgh@4uRVSF@qb3jbK/L4ePJbRY37SPnA2eE1OMFQO2Rkz5H9mJEt/NMnYM@7RUm/J@d9WnfNlqWSJaaHkG1YFPfma9@s9VdXpIQsriV3JddzlcXxs20rg5m56317s1Rc "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Always places the first guest last but will output each solution twice, once with the guests in reverse order. Explanation: ``` ‚âî¬ßŒ∏‚Å∞Œ∑ ``` Get the first guest. ``` ‚äûœÖŒ∑Ôº¶œÖ¬´ ``` Start a breadth-first search with just the first guest seated so far. ``` ‚âî‚Ū‚™™Œ∏¬π‚™™Œπ¬πŒ∂ ``` Get the unplaced guests. (There is an alternative way of doing this using the newer version of Charcoal on ATO which is the same length but allows for a two byte saving later on.) ``` Ôº¶‚஌∂Œ∑¬´ ``` If there are unplaced guests, then loop over the guests, otherwise just check the first guest can sit after the last guest. ``` ‚âî‚Å∫Œ∫ŒπŒ¥ ``` Get the updated placement. ``` ¬ø‚ஂÄπÔº¨Œ¥¬≥Ôπ™Œ£Ôº•‚ĶŒ¥¬≥‚ÑñŒ±Œª¬≥ ``` Except on the first pass, check that this doesn't cause there to be three men or women in a row, by checking that the number of the last three guests which are women is not a multiple of 3. (The two guests sitting on either side of the first guest are checked later.) ``` ¬ø‚¨§‚ŪŒ∂‚ü¶Œ∫‚ü߬¨‚Ññ‚Ü•‚ŪŒπŒ∑‚Ü•Œª ``` Check that this doesn't separate a guest from their spouse. (The first guest's spouse is checked later.) ``` ¬ø‚äñ‚Üî‚Ū‚ÑÖ‚Ü•Œ∫‚ÑÖ‚Ü•Œµ ``` Check that this doesn't place a guest next to a rival. ``` ¬øŒ∂ ``` If there are more guests to check, then... ``` ‚äûœÖŒ¥ ``` ... save the updated placement for later processing. ``` ¬ø‚ஂÄπÔº¨Œπ¬≥Ôπ™Œ£Ôº•‚Ķ‚Å∫¬ßŒπ‚Å∞‚ÆåŒπ¬≥‚ÑñŒ±Œª¬≥ ``` Check that the first guest is not the middle of three men or women in a row. ``` ¬ø¬¨‚Ññ‚Ü•‚úÇŒπ¬π¬±¬≤¬¶¬π‚Ü•Œ∑ ``` Check that the first guest is sitting next to their spouse (if present). ``` ‚ü¶Œπ ``` Output the found placement on its own line. ]
[Question] [ We already have challenges dealing with simulating vanilla [Conway's Game of Life](https://codegolf.stackexchange.com/q/3434/110698), [Wireworld](https://codegolf.stackexchange.com/q/9292/110698) and [rule 110](https://codegolf.stackexchange.com/q/34505/110698), but so far none corresponding to a ([specific](https://codegolf.stackexchange.com/questions/203616)) non-totalistic rule. So here is one. In June 2000 David Bell described the [Just Friends](https://conwaylife.com/wiki/OCA:Just_Friends) rule, which uses the same square grid and two states as regular Life but has the following transitions: * A live cell remains live iff it has one or two live neighbours * A dead cell becomes live iff it has two live neighbours **and they are not vertically or horizontally adjacent** The birth restriction prevents the explosive behaviour that would otherwise be seen with birth-on-2-neighbours rules such as [Seeds](https://conwaylife.com/wiki/OCA:Seeds), and instead allows many interesting patterns. I've been searching for small oscillators of every period in this rule using [apgsearch](https://catagolue.hatsya.com/census/b2-as12), and by that program alone I have found a [stable reflector](https://conwaylife.com/forums/viewtopic.php?f=11&t=2442&start=25#p152722). ## Task Given a Just Friends input pattern and number of generations, output the resulting pattern. The simulation grid, if bounded, must have size at least 40×40 and use either of the following boundary conditions: * Wrap around like a torus * Off-grid cells are dead Pattern input and output may be in any reasonable format, such as binary matrices, lists of live cell positions and [RLE](https://conwaylife.com/wiki/Run_Length_Encoded). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins. ## Test cases These are in the form ``` input pattern number of generations output pattern. ``` ``` .... .*.. .**. .... 1 .... .*.. .**. .... ...... ..*... ..*... .*.... ...... ...... ...... 12 ...... ...... ...... ....*. ....*. ...*.. ...... ................. ........*........ ................. ......*.*........ ................. .**.............. .......**........ ................. ................. ................. ................. ................. ................. 59 ................. ................. ................. ................. .........*.*..*.. ..............*.. ...........*..... ................. ................. ................. .............*... .............*... ................. ........................ ...........*............ ........................ ......*....*.*.......... ......*................. .............*...*...... .....*.*...........**... .................*...... ........................ ........................ ...*.*.................. ....................*.*. .*.*.................... ..................*.*... ........................ ........................ ......*................. ...**...........*.*..... ......*...*............. .................*...... ..........*.*....*...... ........................ ............*........... ........................ 29 ........................ ............*........... ........................ ..........*.*....*...... .................*...... ......*...*............. ...**...........*.*..... ......*................. ........................ ........................ ..................*.*... .*.*.................... ....................*.*. ...*.*.................. ........................ ........................ .................*...... .....*.*...........**... .............*...*...... ......*................. ......*....*.*.......... ........................ ...........*............ ........................ ............... .*............. .*.***......... ..*...**....... .....*..*...... ..*...**....... .*.***......... .*............. ............... 15 ............... ....*.......... ....*.*****.... .....*.....**.. ..........*..*. .....*.....**.. ....*.*****.... ....*.......... ............... ........................... ..........*.....*.......... ..........*.....*.......... ........................... ........................... ........................... ........................... ........................... .*.......................*. .*.........**.**.........*. .*.......................*. .*.........**.**.........*. .*.......................*. ........................... ........................... ........................... ........................... ........................... ..........*.....*.......... ..........*.....*.......... ........................... 83 ........................... ..........*.....*.......... ..........*.....*.......... ........................... ........................... ........................... ........................... ........................... .*.......................*. .*.........**.**.........*. .*.......................*. .*.........**.**.........*. .*.......................*. ........................... ........................... ........................... ........................... ........................... ..........*.....*.......... ..........*.....*.......... ........................... ........... ..*........ ..*......*. ....*....*. .***.....*. ....*....*. ..*......*. ..*........ ........... 21 ........... ..*........ ..*......*. ....*....*. .***.....*. ....*....*. ..*......*. ..*........ ........... ............... ............... ..**.**.*****.. ..*.*.*.*****.. ...***..**.**.. ..*.*.*.*****.. ..**.**.*****.. ............... ............... 1 ............... ....*..*....... ..*...*........ ............... .*............. ............... ..*...*........ ....*..*....... ............... ``` [Answer] # JavaScript (ES11), 136 bytes Expects `(n)(binary_matrix)` and returns another binary matrix. ``` n=>g=m=>n--?g(m.map((r,y)=>r.map((v,x)=>[p=c=t=0,...'12587630'].map(d=>t+=(c|=p&(p=m[y+~-(d/3)]?.[x+d%3-1]),d)&&~~p)|6>>t&(v|~t&!c)))):m ``` [Attempt This Online!](https://ato.pxeger.com/run?1=xVXNjtMwED4i-SlCJBp72g5Nqy6FlbMnuHLYY9tDlJ8S1DohzVattvTMO3BZod2HgufgAchvmyZOWCQWcrAzP9_MN-Ox_PVe-LZz983lDzeR2598_yK4seArboh-_2pBV7gyA0rD3o5xI8yETW8bC9OAWzzigx4iavpwPHl1MRpo89TF5kbU5dTa86BDA76a7rqHPrVfjtj8Cqfbrv1i1NfnrGezTudwCNj-wjCiDt3sD1HnucXi780q5_MzdD7deKFDNXetMQwd037nLZ3rnbDogGHkX0ehJxaU4TpYehFVZ2ImVIauH741rQ90rXBDuSWKsnQixVS4sj45qqyniFjVNTHwA8ouY7fExUyLCBPkNK4uzIqyEllFUNETtrN979KEaYKxfLH2lw4u_QV1qWDUZKcIWdM2BXi6mTP86HuCahor_mZCY0pXSfdL8plltd_9eHYbp0eCkC4QL4mok3RPdInltEGulGz6sACVvqMGapqqD7T7AFQ1Oez3kZ9CM34tqVbiDk0GGQKyBeSGFkpw8iFYC5L1qJ78DNHMSm4ACSk5IvEkcn8pAlBO9zGssKlXZ-NTcCkhoIaokqoaoDiuR7Gqc2tGDOuzRWoE4_SlmvILetQUU1CiV7FX8e0NIPq4ed6x0pfT-ie2tpj_yCadUMR8fo8SlKcJngjXxvO_2f7e2U5GZ_NEzl8IKEKSY8y0XwBS_Zm_9D0gQ11yp2pydkQAaSKS3fGynDHID1Jir-Lb8-nZI_wL) ### Method In order to get the neighbors of the cell at \$(x,y)\$, we use \$d\in\{0,1,2,3,5,6,7,8\}\$ and do: $$\big(x+(d \bmod 3)-1,y+\lfloor d/3\rfloor-1\big)$$ which maps \$d\$ to: $$\begin{matrix}0&1&2\\3&&5\\6&7&8\end{matrix}$$ More specifically, we start with \$d=0\$ and go clockwise, ending with \$d=0\$ again. While doing so, we keep track of the number of live neighbors in \$t\$ and set \$c=1\$ as soon as we detect two consecutive live cells. The top-left cell is processed twice so that all consecutive pairs are tested (for the flag \$c\$), but we make sure to update \$t\$ only once. The distinction between the two passes is made possible by using the falsy integer `0` the first time and the truthy character `'0'` the second time. Using \$t\in[0,8]\$, \$c\in\{0,1\}\$ and the current value \$v\in\{0,1\}\$ of the cell, we compute the new state with: ``` // .-----------------> the LSB is set iff t=1 or t=2 // | .----------> always true if the cell is live // | | .---> true if t is even and c was not set // __|_ | __|__ // / \ | / \ 6 >> t & (v | ~t & !c) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 66 bytes ``` WS⊞υιυFN«UMυ⟦⟧FⅉFLθ«Jλκ⊞§υκ§.*⎇⁼*KK¬÷⊖№KM*²›⁼²№KM*№×²⪫KMω**»⎚Eυ⪫κω ``` [Try it online!](https://tio.run/##tZA9a8MwEIZn61cIT7JxMwQ6lEzFKSWhCYZmKaWDal9jYVlyFClpKfnt7kmJh6ZfUw8Ep9Pzvrq7suam1Fz2/b4WEiibqc7Ze2uEWrMkoYXb1sxlVCQTUmDRMofZizYncunaZzCefCfRgne5bluuKi95fEIyCuiDB0J2B2pta7Y5CqK5a7uVZjKjjYej8N21nakKXr1Hk2R0uMajNM7oCozi5o3dbByXWxb7WgHQ4A8ZXWqLbdmp2IkK2BRKAy0oCxXLtcPePbjQ2gBDGKVeM8Zza4BbHONkOs7oD/zwsBItBG6uhfqM7ZPAenMMHOpAolwCxyXh5bhDXJSfLoibIJmQQ9@PzoMMSfqlcs6kvzNp@r1z@rfzf1TI5VV/sZMf "Charcoal – Try It Online") Link is to verbose version of code. Takes input like the test cases except with a blank line between the pattern and number of generations. Explanation: ``` WS⊞υιυ ``` Read the pattern and write it to the canvas. ``` FN« ``` Repeat for each generation. ``` UMυ⟦⟧ ``` Start collecting the new pattern. ``` FⅉFLθ«Jλκ ``` For each cell... ``` ⊞§υκ§.*⎇⁼*KK¬÷⊖№KM*²›⁼²№KM*№×²⪫KMω** ``` ... apply the generation rules to the cell. ``` »⎚Eυ⪫κω ``` Write the new pattern to the canvas. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/) + my [LifeFind](https://github.com/AlephAlpha/LifeFind) package, 65 bytes ``` <<Life` Last@CellularAutomaton[{RuleNumber@"12/2-a",2,{1,1}},##]& ``` ]
[Question] [ During [the 49 days](https://en.wikipedia.org/wiki/Counting_of_the_Omer#Kabbalistic_interpretation) between [Passover](https://en.wikipedia.org/wiki/Passover) and [Pentecost](https://en.wikipedia.org/wiki/Shavuot), Jewish [liturgy](https://shulchanaruchharav.com/halacha/summary-of-laws-counting-the-omer/) provides four numerical problems that I've here phrased as code golf problems. ## Input/Arguments These four, in any order, and by any means: * A text \$L\$ consisting of exactly 7 sentences. + The first and last sentences have 7 words each, the middle one has 11 words, and the remaining four have 6 words each. + The 11-word sentence has 49 letters in total. + The sentences may have commas, and they all have a trailing period. + You can take this as a 7-element list of strings or as a single string with spaces or line breaks after the inner periods, and optionally after the last one as well. * A text \$A\$ consisting of 7 sentences. + Each sentence has exactly 6 words. + The sentences may have commas, and they all have a trailing period. + You can take this as a 7-element list of strings or as a single string with spaces or line breaks after the inner periods, and optionally after the last one as well. * A list \$S\$ consisting of exactly 7 words. + These are all-lowercase. + These have no punctuation. * An integer \$N\$ in the inclusive range 1 though 49. + You are **not** allowed to substitute with 0 through 48. Alternatively, you can use \$L\$, \$A\$, and \$S\$ as predefined variables, and only take \$N\$. ## Output/Results These four, in this precise order, though in any reasonable format, including with extra trailing whitespace: 1. The text “\$N\$ `days, namely` \$N\_1\$ `weeks` \$N\_0\$ `days`”, where \$(N\_1,N\_0)\_7\$ is \$N\$ in base seven, except for \$N=49\$ where \$N\_1=7\$ and \$N\_0=0\$. * You must omit the plural “`s`” after any number that is \$1\$. * You must omit any part that is \$0\$. * You must omit the second phrase (from and including the comma) if \$N≤6\$. * Examples: + \$N=1\$: “`1 day`” + \$N=6\$: “`6 days`” + \$N=7\$: “`7 days, namely 1 week`” + \$N=8\$: “`8 days, namely 1 week 1 day`” + \$N=13\$: “`13 days, namely 1 week 6 days`” + \$N=14\$: “`14 days, namely 2 weeks`” + \$N=15\$: “`15 days, namely 2 weeks 1 day`” 2. The text of \$L\$ but with the \$N\$th word highlighted, and the \$N\$th letter of the middle sentence highlighted. * The highlightings must consist of two distinct enclosures of your choice. * The enclosing characters must not be letters, nor space, comma, or period. All other visible characters are allowed. * For example, you can enclose the word in square brackets (“`[word]`”) and the letter in curly braces (“`l{e}tter`”), or you could enclose the word in double-asterisks (“`**word**`”) and the letter in single-asterisks (“`l*e*tter`”). * Spaces, commas, and periods must not be highlighted. * Be aware that there will be a value of \$N\$ for which the highlighted letter will appear inside the highlighted word (“`[co{m}bo]`” or (“`**co*m*bo**`” etc.). 3. The text of \$A\$ but with one word or sentence highlighted. * If \$N=1\$ then highlight the first word. * Otherwise, if \$N\$ is evenly divisible by \$7\$ then highlight the entire \$N\over7\$th sentence. * Otherwise, highlight the word that follows immediately after the highlighting done for \$N-1\$. * Commas and periods must not be highlighted when highlighting a word. * For example, for \$N=8\$, highlight the first word of the second sentence. 4. The text “\$S\_0\$ `in` \$S\_1\$”, where \$S\_0\$ is the \$(M\_0+1)\$th word of \$S\$ and \$S\_1\$ is the \$(M\_1+1)\$th word of \$S\$, and \$M=N-1\$. * For example, for \$N=8\$, \$M=N-1=7\$ which is \$(1,0)\_7\$, and therefore \$S\_0\$ is the second word of \$S\$ and \$S\_1\$ is the first word of \$S\$. * The trailing period must also be highlighted when highlighting a sentence. ## Examples For these examples, `[`…`]` is used to highlight words and sentences, `{`…`}` is used to highlight letters, and \$L\$ is: ``` God bless grace, face shine us forever. Know earth ways, saves all nations. Praise people Lord, all people praise. Folk sing joy, for judges people justly, guide earth folk ever. Praise people Lord, all people praise. Earth gives produce, bless our God. Bless God, fear Him all earth ends. ``` \$A\$ is: ``` Power please, great right, release captive. Accept prayer, strengthen people, Awesome purify. Please Mighty, Oneness seekers, eye guard. Bless cleanse, righteous mercy, bestow always. Powerful Holy, abounding goodness, guide congregation. Exalted One, people turn, remember holiness. Accept supplication, hear cry, thoughts knower. ``` \$S\$ is: ``` kindness might beauty victory glory groundedness royalty ``` ### For \$N=1\$ `1 day` ``` [God] bless grace, face shine us forever. Know earth ways, saves all nations. Praise people Lord, all people praise. {F}olk sing joy, for judges people justly, guide earth folk ever. Praise people Lord, all people praise. Earth gives produce, bless our God. Bless God, fear Him all earth ends. ``` ``` [Power] please, great right, release captive. Accept prayer, strengthen people, Awesome purify. Please Mighty, Oneness seekers, eye guard. Bless cleanse, righteous mercy, bestow always. Powerful Holy, abounding goodness, guide congregation. Exalted One, people turn, remember holiness. Accept supplication, hear cry, thoughts knower. ``` `kindness in kindness` ### For \$N=6\$ `6 days` ``` God bless grace, face shine [us] forever. Know earth ways, saves all nations. Praise people Lord, all people praise. Folk s{i}ng joy, for judges people justly, guide earth folk ever. Praise people Lord, all people praise. Earth gives produce, bless our God. Bless God, fear Him all earth ends. ``` ``` Power please, great right, release [captive]. Accept prayer, strengthen people, Awesome purify. Please Mighty, Oneness seekers, eye guard. Bless cleanse, righteous mercy, bestow always. Powerful Holy, abounding goodness, guide congregation. Exalted One, people turn, remember holiness. Accept supplication, hear cry, thoughts knower. ``` `groundedness in kindness` ### For \$N=7\$ `7 days, namely 1 week` ``` God bless grace, face shine us [forever]. Know earth ways, saves all nations. Praise people Lord, all people praise. Folk si{n}g joy, for judges people justly, guide earth folk ever. Praise people Lord, all people praise. Earth gives produce, bless our God. Bless God, fear Him all earth ends. ``` ``` [Power please, great right, release captive.] Accept prayer, strengthen people, Awesome purify. Please Mighty, Oneness seekers, eye guard. Bless cleanse, righteous mercy, bestow always. Powerful Holy, abounding goodness, guide congregation. Exalted One, people turn, remember holiness. Accept supplication, hear cry, thoughts knower. ``` `royalty in kindness` ### For \$N=8\$ `8 days, namely 1 week 1 day` ``` God bless grace, face shine us forever. [Know] earth ways, saves all nations. Praise people Lord, all people praise. Folk si{n}g joy, for judges people justly, guide earth folk ever. Praise people Lord, all people praise. Earth gives produce, bless our God. Bless God, fear Him all earth ends. ``` ``` Power please, great right, release captive. [Accept] prayer, strengthen people, Awesome purify. Please Mighty, Oneness seekers, eye guard. Bless cleanse, righteous mercy, bestow always. Powerful Holy, abounding goodness, guide congregation. Exalted One, people turn, remember holiness. Accept supplication, hear cry, thoughts knower. ``` `kindness in might` ### For \$N=13\$ `13 days, namely 1 week 6 days` ``` God bless grace, face shine us forever. Know earth ways, saves all [nations]. Praise people Lord, all people praise. Folk sing joy, f{o}r judges people justly, guide earth folk ever. Praise people Lord, all people praise. Earth gives produce, bless our God. Bless God, fear Him all earth ends. ``` ``` Power please, great right, release captive. Accept prayer, strengthen people, Awesome [purify]. Please Mighty, Oneness seekers, eye guard. Bless cleanse, righteous mercy, bestow always. Powerful Holy, abounding goodness, guide congregation. Exalted One, people turn, remember holiness. Accept supplication, hear cry, thoughts knower. ``` `groundedness in might` ### For \$N=14\$ `14 days, namely 2 weeks` ``` God bless grace, face shine us forever. Know earth ways, saves all nations. [Praise] people Lord, all people praise. Folk sing joy, fo{r} judges people justly, guide earth folk ever. Praise people Lord, all people praise. Earth gives produce, bless our God. Bless God, fear Him all earth ends. ``` ``` Power please, great right, release captive. [Accept prayer, strengthen people, Awesome purify.] Please Mighty, Oneness seekers, eye guard. Bless cleanse, righteous mercy, bestow always. Powerful Holy, abounding goodness, guide congregation. Exalted One, people turn, remember holiness. Accept supplication, hear cry, thoughts knower. ``` `royalty in might` ### For \$N=15\$ `15 days, namely 2 weeks 1 day` ``` God bless grace, face shine us forever. Know earth ways, saves all nations. Praise [people] Lord, all people praise. Folk sing joy, for {j}udges people justly, guide earth folk ever. Praise people Lord, all people praise. Earth gives produce, bless our God. Bless God, fear Him all earth ends. ``` ``` Power please, great right, release captive. Accept prayer, strengthen people, Awesome purify. [Please] Mighty, Oneness seekers, eye guard. Bless cleanse, righteous mercy, bestow always. Powerful Holy, abounding goodness, guide congregation. Exalted One, people turn, remember holiness. Accept supplication, hear cry, thoughts knower. ``` `kindness in beauty` ### For \$N=25\$ `25 days, namely 3 weeks 4 days` ``` God bless grace, face shine us forever. Know earth ways, saves all nations. Praise people Lord, all people praise. Folk sing joy, for judges [peop{l}e] justly, guide earth folk ever. Praise people Lord, all people praise. Earth gives produce, bless our God. Bless God, fear Him all earth ends. ``` ``` Power please, great right, release captive. Accept prayer, strengthen people, Awesome purify. Please Mighty, Oneness seekers, eye guard. Bless cleanse, righteous [mercy], bestow always. Powerful Holy, abounding goodness, guide congregation. Exalted One, people turn, remember holiness. Accept supplication, hear cry, thoughts knower. ``` `victory in victory` ### For \$N=49\$ `49 days, namely 7 weeks` ``` God bless grace, face shine us forever. Know earth ways, saves all nations. Praise people Lord, all people praise. Folk sing joy, for judges people justly, guide earth folk eve{r}. Praise people Lord, all people praise. Earth gives produce, bless our God. Bless God, fear Him all earth [ends]. ``` ``` Power please, great right, release captive. Accept prayer, strengthen people, Awesome purify. Please Mighty, Oneness seekers, eye guard. Bless cleanse, righteous mercy, bestow always. Powerful Holy, abounding goodness, guide congregation. Exalted One, people turn, remember holiness. [Accept supplication, hear cry, thoughts knower.] ``` `royalty in royalty` [Answer] # [Python 3](https://docs.python.org/3/), 365 bytes ``` import re i=N=int(input()) p=print Y=N//7 Z=N%7 p(N,"day"+"s"*(N>1)+(f", namely {Y} week{'s'*(N>13)}"+f" {Z} day{'s'*(Z>1)}"*(Z>0))*(N>6)) s="[]" def a(x):global i;i-=1;x=x.group();return i and x or x.join(s) b=re.sub L=b("\w+",a,L).split("\n") if Z:i=N-Y;A=b("\w+",a,A) else:i=Y;A=b(".+",a,A) s="{}" i=N L[3]=b("\w",a,L[3]) [*map(p,L)] p(A) p(S[~-N%7],"in",S[~-Y]) ``` [Try it online!](https://tio.run/##lVRda9swFH3Xr7gIRu3WdVc6VmjwIIN9wLKs0KcmDUO2rx21tiQkuYkJ2V/vruyk7GWwvdjW/Tj3nKObmN6vtbp6mUEG/EHx9FFLFUllOh/FUGkLP0EqsELVGF3HMTuk2PR/G@6oYfnXutWx7kW2RlsPFpnM5plU/ggeM5MZSwF2n80vLq7ZIpu/uWYmmie8FD0/446fRvMPl/FZVPEElGix6WF3v4cN4tPuxJ0M6at4z88qDrvFHqhvjC@obc/D@20ch7L3NM9lfLnirMQKRLSNb@pG56IBOZHn2eVkm23T2urORPHEou@sAglClbAFUrcdjXExyzOLqetyNsvyiD9szngiklmcOtNIHwUPyaQKFjek9/x@Mv2jahozbBxS5hBPj2GittvzYBGbLa9WY88ATKeYLU9bYSJDY1ZkENWb6G7565z8WiVcKp6E0/0qfnn5okvIG3QOaisKTKCiJ7i1VAidCxeFz2hT9k3pDaCwfg0b0bsEnHhGB6JpyGgvtXIpu7VCOgSD2jQIM23LZCg4BMyQTtln3TyBk6qGR90nwy48dmVNaIfCx875hjJ1J0s8DK1C00jlH8d8GvpqGWgaq8suqBul6s4CCU/Zx@FIn0SD5sBX2Q5Q40xUJalit3qDFghaOEKoLQpaT1mvfUJbOkShEMbToJRNiwKNDxx6tGSSt6hqv0Z1YJfAdINOt0Szs7LqSc2I8D0AkuYfClXg5Ghl0ZLP2CMZIewr24IaVGAycEBNt9SiLag3R@fplkQTbigdeVddA191cFPkulNlsL3WugxDjg4XWpGqerhG8m0rGo9lYJIcPQ3bHdS22ObkxVo3MgC86nWdoW0uBoQE1sHKwtJM@nPpiKSDJxXIkJlPUg2zWRvYsxxF53v2LAuvbc/oFxaeNjDFsc7qnvj0jF2@@w0 "Python 3 – Try It Online") -27 bytes thanks to RootTwo -6 bytes thanks to ovs Accepts \$L,A,S\$ as pre-defined variables. These definitions are in the header, but I am reading from STDIN just to make testing easier. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 323 bytes ``` ^.+ $* ^(1(1{7})*(1)*[\w\W]*¶¶)(?=(?<-3>.+¶)*(.+))(?<-2>.+¶)*(.+)(¶.+)* $1$4 in $5 ^((1{7})*(1)?(1)*¶(¶.+)+¶(?<-2>.*¶)*)(?(3)(.*¶(?<-4>\w+\W+)*)(\w+)|(.+)) $1$6<$7$8> ^(1(1)*¶¶(?<-2>\w+\W+)*)(\w+) $1<$3> ^(1(1)*¶¶(.+¶){3}<?(?<-2>\w\W*)*)(\w) $1{$4} ^(1{7})*(1)* $.& days, namely $#1 weeks $#2 days (,.*y)? 0.*|\b(1 \w+)s $2 ``` [Try it online!](https://tio.run/##jVFfb9MwEH/3pziJCCVpiNZ2MB7KqiEBkwCxtz1QJrnJNfGa2pHtrETbvlY/QL9YuXO6wd54sezz3e/fWfRKy8PhJh@JKBU38Tge3589Jmk8TtKfi@3i@le63@13STz/EM9nb6bn@YheaZyPkoQLk38K8X5HZyqicXQKSkP0lgD/4s0Zc78bumjoOJ7yOGHF0yTmB5dPzxfb0eJ6xB90Sx4CHwO/m0Vn0fvzQWkStA04LweodRZNX7YFoffTx9n8aWJxnQ4D3H8fnT5y/7N9EeWvoZS9y0DLDTY9RK/GsEVcO7pNwpeIszztkzmc5OnDYhmPgdmdiCaHw@REiC@mhGWDzkFlZYEZrOgEVyuN0DlYGYt3aHPxVZstoLS@hm1gdPIOHcimIW6vjHa5uLJSOYQWTdsgfDO2zELDsdCG71x8Ns0anNIV3Jo@Ywq47cqK0I6Nt53zDf1UnSrxSLrioUHKf9J8CnOVYpmtNWXH7garprNAxnPxMTzpSjKIBy7VJkANnKhLciWuzBYtELR0hFBZlB6sqmqfgcVQhUK2nohycVEU2HrW0KOlkLxFXfka9VFdBhdbdGZDMjurVj25GRC@MyB5/qFRsyZHW0RLOWOPFIS0z2oLGtCsJGhAQ1vaoC1odonO05ZkwxvKB92rroFLw2nKpel0ybFXxpRM8pRwYTS5qsIaKbffsvFYspLsKVPfWc1uN7hZUha1aRQDPPt1Xds2qggIGdQcZWGJ09emI5EO1prFUJhrpQO32LB6sUTZ@V7cqcIb24uqCadlpTj0WdOTnv4P "Retina 0.8.2 – Try It Online") Takes N, L, A and S as input, double-spaced from each other. Explanation: ``` ^.+ $* ``` Convert `N` to unary. ``` ^(1(1{7})*(1)*[\w\W]*¶¶)(?=(?<-3>.+¶)*(.+))(?<-2>.+¶)*(.+)(¶.+)* $1$4 in $5 ``` Divmod `N-1` by `7`, capturing the appropriate words from `S` and replacing `S` with the desired phrase. ``` ^((1{7})*(1)?(1)*¶(¶.+)+¶(?<-2>.*¶)*)(?(3)(.*¶(?<-4>\w+\W+)*)(\w+)|(.+)) $1$6<$7$8> ``` Divmod `N` by `7`. If the remainder was zero, then capture the `N/7`th line of A, otherwise capture the `N%7-1`th word on the following line. Surround it with `<>`s. ``` ^(1(1)*¶¶(?<-2>\w+\W+)*)(\w+) $1<$3> ``` Capture the `N`th word of `L` and surround it with `<>`s. ``` ^(1(1)*¶¶(.+¶){3}<?(?<-2>\w\W*)*)(\w) $1{$4} ``` Capture the `N`th letter of the middle line of `L` and surround it with `{}`s. ``` ^(1{7})*(1)* $.& days, namely $#1 weeks $#2 days ``` Divmod `N` by `7` again. Convert `N` back to decimal, as well as `N/7` and `N%7`, as the desired phrase, assuming all values exceed `1`. ``` (,.*y)? 0.*|\b(1 \w+)s $2 ``` Fix up `0` and `1` values. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~539...~~ 431 bytes ``` (L,A,S,N,B=N%7,J=N/7,u=D=>D>1?'s':'',z=/[. ,]/,g=w=>`[${w.replace(z,'')}]${z.test(w)?w.slice(-1):''}`)=>[N+` day${u(N)}${N>6?`, namely ${H=J|0} week${u(H)} ${B?B+` day`+u(B):''}`:''}`,(t=0)||(L[3]=L[3].replace(/[a-zA-Z]/g,c=>++t==N?`{${c}}`:c))&&L.join` `.split` `.map((e,i)=>i==N-1?g(e):e).join` `,A.map((e,i)=>N%7?i==~~J?((E=e.split` `)[--B]=g(E[B]))&&E.join` `:e:i==J-1?`[${e}]`:e).join` `,S[N%7?B:6]+' in '+S[N<8?0:N>48?6:J|0]] ``` [Try it online!](https://tio.run/##lVNNb@M2EL3rV8zBXUswLSftNrswKgs2Nm2QZt0F9lZXgGhpLNOhSYGkoiqO96@nQzk22p7aC0GR8z7mDbXjT9wWRtRurHSJr5vkNXxgc/aVLdkiWX73gd0ny8kH1iSfktmn2XU6tMPpcMiek8kqBpZNWJW0ySxfDQ5tbLCWvMDwmQ2H0TEbHJ5jh9aFbZS2sZWCrsbXEcGPeZTMVstRDiXvBocmXEbHwWE5u0lzBorvUXYwONwl9y9XR2gRH33NXXSkw0W6OMHyURMuTmT9wkKXXEUvL@HD6ocs8cvFz2TFx8/z8e/ZpGJFMhuNXJIs0/wwOBRHQhdR9O7dQ7zTQuWQx7aWwvnNntdhiEyQV0GA8XVahRhNMTqXsvnfayislOq@fbtPw/A2wQtRtBqPF1lShberRea1bs8EU5wS4p6YfYB4zPILe5CzrytPuZjeZKMhCAXDEZ389DG9mi5n7z@mN1OKJ8teJxP43/EHhVZWS4ylrsJNmP@iS1hLtBYqQxQMNrSC3QqF0FjYaINPaOLgV6VbQG7cFlreWQaWP6EFLiWNzQkijYMvhguLUKOuJcKDNiXrC94O6v46Dn7W8hGsUBXsdMe8BOyasiK2t8JdY52km6oRJb6JbjzoZOU/ytz2uEp4m7XRZeO7O7WqGwPUeBws@k/akg3SgTux76lOmqhKG5@fxR@KXmj@RbdogGS4JbbKIHdgRLV1DAz2p1Dw2pFoHMyLAmvn/XRoKDBnUFVui@rNKYN5i1bvyXJjxKajzk4Mnz0h9f@bQuX9WfoP0FDm2CGFws3FeUEA5Z30HlDTxPZoCsKuaf40MS79tIjZ@940Eu60T5avdaNKP4JK69KLnNOm50FdVf1IKcM/uXRYeifsnK9rjPLd7nG/piy2WgpPcOnXNjUFVvQMDLY@1sKQptvqhkxaeFTezL@CfRSq9xHsfSfBGnnjuuBJFE6bLqhkvxrvGk91RnfkrfsHy/c/RtHrXw "JavaScript (Node.js) – Try It Online") This is long. Like REALLY long. Takes `L`, `A` and `S` as arrays of strings. I also love how the code breaks the syntax highlighter. ## How does it work? Declares a huge amount of default arguments to save on bytes, as many of these arguments are referred to later. The first four arguments are simply the texts. `B` and `J` are simply values derived from N which are used extensively in the code. `u` is a helper function which returns an `s` depending on the value of the input. `z` is simply a regular expression characterized by a single character class containing all forbidden characters for highlighting: space, period and comma. `g` is a helper function called twice which highlights a word without forbidden characters being caught up in the word. In the function body, we return an array of four strings: * using rudimentary ternaries, get the formatted "days" string. * the `L`-string. Procedure: first, replace the fourth sentence with the same sentence but with one letter highlighted. Then do the word highlighting using the `g` function. * the `A`-string. Frankly, even I can't read my own code, but essentially highlights one word or one sentence. Can't go into detail on this one. * the `S`-string. A bunch of simple ternaries based on the value of `N`. ]
[Question] [ ## Introduction: You're a key maker, and want to access something from a safe that has a lock. Unfortunately, the key to that lock is lost, so you'll have to make a new one. You have access to a bunch of [blank keys](https://i.postimg.cc/6p0WbWCj/blank-key.jpg), to which you can add notches to turn it into [actual keys](https://i.postimg.cc/wjHxkyRR/key.jpg). You also have loads of keys with notches already applied lying around. ## Challenge: Given a list of list of digits (all of equal length) representing the list of keys with notches you have lying around, where each digit represents the height of the notch 'column', as well as an integer list of digits of the key you want to make for the lock of the safe, output the amount of keys you should potentially make in order to try to open the lock. How would we determine this? Here an example: Let's say the key that's supposed to go into the lock is `[7,5,2,5]` (where the first digit is at the opening of the lock). And let's say the list of keys you have available is `[[2,5,3,5],[3,7,5,8],[8,2,1,0],[6,3,6,6],[7,9,5,7],[0,2,2,1]]` (where the last digits are the tips of the keys). Here is how far we can insert each key into the lock: Let's take the first key `[2,5,3,5]` as more in-depth example: ``` [2,5,3,5] # First notch: 5<=7, so it fits [7,5,2,5] # Second notch: 5<=5 & 3<=7, so it fits # Third notch: 5>2 (& 3<=5 & 5<=7), so it can't be inserted that far into the lock # Based on this key we now know the following about the safe-key: # First notch: >=5 # Second notch: >=5 # Third notch: <5 ``` Here a visual representation, to perhaps better understand it, where the blue cells are key `[2,5,3,5]`, the yellow parts is the key that's supposed to go into the lock `[7,5,2,5]`, and the black parts are the lock itself: [![enter image description here](https://i.stack.imgur.com/TTqnP.png)](https://i.stack.imgur.com/TTqnP.png) As for the other keys: ``` [3,7,5,8] # First notch: 8>7, so it can't even be inserted into the lock at all [7,5,2,5] # base on this key we now know the following about the safe-key: # First notch: <8 [8,2,1,0] # First notch: 0<=7, so it fits [7,5,2,5] # Second notch: 0<=5 & 1<=7, so it fits # Third notch: 0<=2 & 1<=5 & 2<=7, so it fits # Fourth notch: (0<=5 & 1<=2 & 2<=5 &) 8>7, so it can't be inserted that far # Based on this key we now know the following about the safe-key: # First notch: >=2 & <8 # Second notch: >=1 # Third notch: >=0 (duh) # Fourth notch: nothing; we couldn't insert it to due to first notch [6,3,6,6] # First notch: 6<=7, so it fits [7,5,2,5] # Second notch: 6>5 (& 6<=7), so it can't be inserted that far # Based on this key we now know the following about the safe-key: # First notch: >=6 # Second notch: <6 [7,9,8,7] # First notch: 7<=7, so it fits [7,5,2,5] # Second notch: 7>5 & 8>7, so it can't be inserted that far # Based on this key we now know the following about the safe-key: # First notch: >=7 & <8 # Second notch: <7 [0,2,2,1] # First notch: 1<=7, so it fits [7,5,2,5] # Second notch: 1<=5 & 2<=7, so it fits # Third notch: 1<=2 & 2<=5 & 2<=7, so it fits # Fourth notch: 1<=5 & 2<=2 & 2<=5 & 0<=7, so it fits # Based on this key we now know the following about the safe-key: # First notch: >=2 # Second notch: >=2 # Third notch: >=2 # Fourth notch: >=1 ``` Combining all that: ``` # First notch: ==7 (>=7 & <8) # Second notch: ==5 (>=5 & <6) # Third notch: >=2 & <5 # Fourth notch: >=1 ``` Leaving all potential safe-keys (**27** in total, which is our output): ``` [[1,2,5,7],[1,3,5,7],[1,4,5,7],[2,2,5,7],[2,3,5,7],[2,4,5,7],[3,2,5,7],[3,3,5,7],[3,4,5,7],[4,2,5,7],[4,3,5,7],[4,4,5,7],[5,2,5,7],[5,3,5,7],[5,4,5,7],[6,2,5,7],[6,3,5,7],[6,4,5,7],[7,2,5,7],[7,3,5,7],[7,4,5,7],[8,2,5,7],[8,3,5,7],[8,4,5,7],[9,2,5,7],[9,3,5,7],[9,4,5,7]] ``` ## Challenge rules: * Assume we'll know all notches when it doesn't fit, even though the lock would in reality be a black box. Let's just assume the key maker is very experienced, and can feel such a thing. What I mean by this, is for example shown with key `[7,9,8,7]` in the example above. It fails at the second stage because of both `7>5` and `8>7`. In reality we wouldn't know which of those two caused it to be blocked and making us unable to insert the key any further, but for the sake of this challenge we'll assume we know all of them if there are more than one. + Also note that for `[8,2,1,0]` we don't know anything about the fourth notch, because we couldn't insert it past the third. + Also, in reality the key maker could test some of the keys he makes after testing all existing ones to further decrease the amount of potential keys he has to make, so the number would be much lower than `72` in the example, but for the sake of this challenge we'll just determine the amount of all possible safe-keys for the lock based on the given existing keys once. + EDIT/NOTE: Even the intended `[7,5,2,5]` key wouldn't be able to insert all the way into its intended lock `[7,5,2,5]` in how the keys and locks interact in this challenge. This doesn't change the actual challenge nor test cases, but does make the backstory pretty flawed.. :/ Key `[7,5,2,5]` in lock `[7,5,2,5]` would act like this: first notch: `5<=7`, so it fits; second notch: `5<=5 & 2<=7`, so it fits; third notch: `5>2 (& 2<=5 & 5<=7)`, so it can't be inserted that far. * You can take the I/O in any reasonable format. Can be a list of strings or integers (note that leading 0s are possible for the keys) instead of the list of lists of digits I've used. * You can assume all keys of the input have the same length, which is \$1\leq L\leq10\$. * You are allowed to take the safe-key input in reversed order, and/or all keys in the list in reversed order. **Make sure to mention this in your answer if you do!** * You can assume the safe-key is not in the list of other keys. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Input safe-key: [7,5,2,5] Input other keys: [[2,5,3,5],[3,7,5,8],[8,2,1,0],[6,3,6,6],[7,9,5,7],[0,2,2,1]] Output: 27 ([[1,2,5,7],[1,3,5,7],[1,4,5,7],[2,2,5,7],[2,3,5,7],[2,4,5,7],[3,2,5,7],[3,3,5,7],[3,4,5,7],[4,2,5,7],[4,3,5,7],[4,4,5,7],[5,2,5,7],[5,3,5,7],[5,4,5,7],[6,2,5,7],[6,3,5,7],[6,4,5,7],[7,2,5,7],[7,3,5,7],[7,4,5,7],[8,2,5,7],[8,3,5,7],[8,4,5,7],[9,2,5,7],[9,3,5,7],[9,4,5,7]]) (==7, ==5, >=2&<5, >=1) Input safe-key: [3] Input other keys: [[1],[6],[2],[9]] Output: 4 ([[2],[3],[4],[5]]) (>=2&<6) Input safe-key: [4,2] Input other keys: [[4,1],[3,7],[4,4],[2,0]] Output: 9 ([[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]) (>=1&<4, >=4&<7) Input safe-key: [9,8,7,5,3] Input other keys: [[4,6,7,0,6],[5,5,0,7,9],[6,3,3,7,6],[9,1,0,3,1],[3,8,5,3,4],[3,6,4,9,7]] Output: 48 ([[9,7,6,4,1],[9,7,6,4,2],[9,7,6,4,3],[9,7,6,5,1],[9,7,6,5,2],[9,7,6,5,3],[9,7,7,4,1],[9,7,7,4,2],[9,7,7,4,3],[9,7,7,5,1],[9,7,7,5,2],[9,7,7,5,3],[9,7,8,4,1],[9,7,8,4,2],[9,7,8,4,3],[9,7,8,5,1],[9,7,8,5,2],[9,7,8,5,3],[9,7,9,4,1],[9,7,9,4,2],[9,7,9,4,3],[9,7,9,5,1],[9,7,9,5,2],[9,7,9,5,3],[9,8,6,4,1],[9,8,6,4,2],[9,8,6,4,3],[9,8,6,5,1],[9,8,6,5,2],[9,8,6,5,3],[9,8,7,4,1],[9,8,7,4,2],[9,8,7,4,3],[9,8,7,5,1],[9,8,7,5,2],[9,8,7,5,3],[9,8,8,4,1],[9,8,8,4,2],[9,8,8,4,3],[9,8,8,5,1],[9,8,8,5,2],[9,8,8,5,3],[9,8,9,4,1],[9,8,9,4,2],[9,8,9,4,3],[9,8,9,5,1],[9,8,9,5,2],[9,8,9,5,3]]) (==9, >=7&<9, >=6, >=4&<6, >=1&<4) Input safe-key: [5,4] Input other keys: [[6,3]] Output: 30 ([[0,3],[0,4],[0,5],[1,3],[1,4],[1,5],[2,3],[2,4],[2,5],[3,3],[3,4],[3,5],[4,3],[4,4],[4,5],[5,3],[5,4],[5,5],[6,3],[6,4],[6,5],[7,3],[7,4],[7,5],[8,3],[8,4],[8,5],[9,3],[9,4],[9,5]]) (>=3&<6, n/a) ``` [Answer] # [Python 2](https://docs.python.org/2/), 196 bytes ``` l,o=input() b=[[[0],[10]]for _ in l] for k in o: R=range(len(l)) for i in R: for x in 0,1: for j in R[:i+1]: if(k[~i+j]>l[j])+x:b[j][~x]+=k[~i+j],;R*=x for a,b in b:x*=min(b)-max(a) print x ``` [Try it online!](https://tio.run/##LZDLboMwEEXX9Vd4FwhTCQLhVbm7dFsp6s6yKkidxgkBZBHV2eTX6YzJwsy9c0bzYLxPp6HfzIfhR3PBV6vV3MEgTD/epiBkrZBSxgpkEit1HCz/5qbnnWKkL6SHmvG9sE3/q4NO90EXhowTNUT3NXsh48jEkKD18OyhrE2UKMy9mGNwkQ8TndV7J88qjFzdYpQPpyLxJPC2XwvnJzfQUoO2dmtxNX3Qhq/XxgVNyEZr@om7GQ9h7O9kOs2/7E3jknyydwqca6cPnA5mpA96nPju82Nn7WCXgtbq5jLLArawgS1eLzFA6mUKlC5RlQgToJ@TI8shR1VAhbRAFSNFrhSTKXVIqA7fBl9F2QxIYkiWrvjNIKMK7Im8gtKPSpeqHE3sZ2wxGaOrnpNpI8pXtA26pV/pN868ziHDvQql/gE "Python 2 – Try It Online") **Commented**: ``` l,o=input() # input: safe-key/lock, other keys b=[[[0],[10]]for _ in l] # for each column in the lock b stores: # a list of inclusive lower bounds and # a list of exclusive upper bounds for k in o: # iterate over the other keys R=range(len(l)) for i in R: # each insertion-level i (0-indexed) for x in 0,1: # x=0: check if the key can't move there, update upper bounds # x=1: if the key fits, update lower bounds # this final value of x will be used later for j in R[:i+1]: # for each column: if(k[~i+j]>l[j])+x: # if the key doesn't fit at column j of the lock or x=1: b[j][~x]+=k[~i+j], # update the the right list of bounds R*=x # and, if x=0, set R to the empty list # if this happens the 'for j in R[:i+1]'-loop will complete, # but will then never run again for the current key for a,b in b: # for lower and upper bounds of each column x*=min(b)-max(a) # calculate the product in x (previously 1) print x # print the result ``` ]
[Question] [ Two Deterministic Finite Automata or [DFAs](https://en.wikipedia.org/wiki/Deterministic_finite_automaton) can be checked to see if they accept same set of strings in polynomial time. See [section 3.3 of this](https://scholarworks.rit.edu/cgi/viewcontent.cgi?article=7944&context=theses) for a long list of methods and this [SO](https://cs.stackexchange.com/questions/81813/is-the-equality-of-two-dfas-a-decidable-problem) question/answer for a much shorter list. **Input** Your input will be two [DFAs](https://en.wikipedia.org/wiki/Deterministic_finite_automaton). In order to be able to test your code, I have provided DFAs in the following format. This is taken directly from [GAP](https://www.gap-system.org/Manuals/pkg/automata-1.14/doc/chap2.html#X811E5FC2849C5644) (and slightly simplified). ``` Automaton( Type, Size, Alphabet, TransitionTable, Initial, Accepting ) ``` For the input, Type will always be "det". Size is a positive integer representing the number of states of the automaton. Alphabet is the number of letters of the alphabet. TransitionTable is the transition matrix. The entries are non-negative integers not greater than the size of the automaton. We may write a 0 to mean that no transition is present. Initial and Accepting are, respectively, the lists of initial and accepting states. You can assume there will be exactly one initial state. For example: ``` Automaton("det",4,2,[ [ 1, 3, 4, 0 ], [ 1, 2, 3, 4 ] ],[ 3 ],[ 2, 3, 4 ]) ``` This has transition table: ``` | 1 2 3 4 ----------------- a | 1 3 4 b | 1 2 3 4 Initial state: [ 3 ] Accepting states: [ 2, 3, 4 ] ``` And diagram: [![enter image description here](https://i.stack.imgur.com/GTJzK.png)](https://i.stack.imgur.com/GTJzK.png) It is equivalent to: ``` Automaton("det",3,2,[ [ 1, 3, 1 ], [ 1, 2, 3 ] ],[ 2 ],[ 2, 3 ]) ``` which has diagram: [![enter image description here](https://i.stack.imgur.com/oRVRl.png)](https://i.stack.imgur.com/oRVRl.png) In order to remove parsing as a significant part of this challenge, you are free to perform trivial parsing of the input format before giving it to your code. This means you can delete any part or parts, reorder and change one type of bracket to another before passing the input to your code. For example, the previous example can be given as ``` 3,2,[ [ 1, 3, 1 ], [ 1, 2, 3 ] ],[ 2 ],[ 2, 3 ] ``` if that helps. Here is a more complicated example, ``` Automaton("det",6,4,[ [ 0, 2, 3, 5, 0, 0 ], [ 1, 3, 5, 0, 0, 0 ], [ 1, 3, 5, 6, 0, 0 ], [ 2, 3, 5, 0, 0, 0 ] ],[ 1 ],[ 1, 4, 5, 6 ]) ``` has diagram: [![enter image description here](https://i.stack.imgur.com/T9t3Q.png)](https://i.stack.imgur.com/T9t3Q.png) It is equivalent to: ``` Automaton("det",5,4,[ [ 2, 2, 2, 4, 5 ], [ 2, 2, 3, 1, 4 ], [ 2, 2, 3, 1, 4 ], [ 2, 2, 5, 1, 4 ] ],[ 3 ],[ 1, 3 ]) ``` with diagram: [![enter image description here](https://i.stack.imgur.com/y3lA6.png)](https://i.stack.imgur.com/y3lA6.png) # More examples of equivalent DFAs 1. ``` Automaton("det",18,4,[ [ 2, 2, 6, 10, 2, 6, 7, 16, 14, 10, 18, 14, 7, 14, 15, 16, 7, 18 ], [ 3, 3, 7, 11, 3, 7, 15, 11, 7, 17, 15, 18\ , 18, 7, 15, 17, 15, 15 ], [ 4, 4, 8, 7, 4, 13, 15, 15, 16, 7, 8, 7, 15, 7, 15, 15, 16, 13 ], [ 5, 5, 9, 12, 5, 14, 7, 13, 9, 14, 17, 12, \ 13, 14, 15, 7, 17, 7 ] ],[ 1 ],[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18 ]) ``` ``` Automaton("det",16,4,[ [ 1, 2, 15, 15, 5, 6, 7, 7, 6, 2, 16, 12, 12, 16, 15, 16 ], [ 1, 3, 1, 7, 9, 15, 1, 1, 15, 8, 7, 3, 8, 15, 1, \ 15 ], [ 1, 1, 2, 1, 13, 4, 4, 10, 10, 1, 15, 15, 15, 2, 1, 15 ], [ 1, 15, 3, 4, 5, 16, 15, 3, 14, 4, 11, 16, 11, 14, 15, 16 ] ],[ 5 ],[ 2,\ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]) ``` 2. ``` Automaton("det",50,4,[ [ 2, 2, 9, 13, 17, 9, 13, 17, 9, 24, 28, 30, 13, 33, 36, 30, 17, 9, 13, 9, 13, 39, 30, 24, 25, 44, 42, 28, 24, 30, 47, 39, 33, 50, 36, 36, 42, 46, 39, 25, 24, 42, 43, 44, 36, 46, 47, 42, 25, 50 ], [ 3, 6, 10, 14, 18, 10, 14, 20, 10, 25, 14, 10, 32, 34, 34, 38, 20, 10, 14, 10, 14, 38, 10, 25, 43, 34, 25, 45, 46, 10, 32, 49, 34, 43, 34, 49, 50, 50, 49, 50, 46, 25, 43, 49, 49, 50, 45, 50, 43, 43 ], [ 4, 7, 11, 15, 19, 11, 15, 21, 22, 26, 26, 31, 15, 11, 25, 15, 21, 11, 15, 11, 15, 40, 15, 40, 43, 43, 44, 26, 26, 15, 44, 31, 41, 26, 47, 25, 25, 22, 40, 43, 40, 25, 43, 43, 47, 41, 44, 44, 44, 40 ], [ 5, 8, 12, 16, 5, 12, 16, 8, 23, 27, 29, 12, 23, 35, 37, 16, 8, 12, 16, 12, 16, 41, 23, 42, 25, 40, 27, 27, 29, 23, 48, 45, 37, 49, 35, 42, 37, 48, 42, 40, 41, 42, 43, 25, 45, 37, 27, 48, 49, 25 ] ],[ 1 ],[ 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, 44, 45, 46, 47, 48, 49, 50 ]) ``` ``` Automaton("det",39,4,[ [ 1, 2, 3, 3, 5, 24, 7, 8, 22, 20, 8, 32, 18, 18, 3, 19, 25, 18, 19, 20, 25, 22, 23, 24, 25, 25, 24, 23, 5, 2, 35, 32, 19, 19, 35, 36, 36, 36, 36 ], [ 1, 38, 1, 23, 15, 9, 11, 26, 23, 28, 26, 10, 9, 26, 1, 3, 22, 26, 3, 28, 22, 23, 1, 15, 3, 3, 15, 1, 28, 27, 10, 27, 23, 23, 38, 15, 28, 15, 28 ], [ 1, 5, 1, 1, 1, 4, 12, 6, 6, 31, 31, 37, 37, 30, 5, 5, 29, 37, 3, 21, 4, 21, 4, 4, 4, 29, 30, 29, 1, 5, 29, 37, 5, 3, 29, 3, 3, 2, 2 ], [ 1, 16, 3, 4, 3, 21, 7, 18, 33, 39, 14, 13, 13, 14, 15, 16, 17, 18, 19, 34, 21, 34, 3, 19, 19, 16, 38, 15, 4, 33, 17, 18, 33, 34, 16, 19, 34, 38, 39 ] ],[ 7 ],[ 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 ]) ``` 3. ``` Automaton("det",288,4,[[2, 6, 10, 14, 18, 6, 10, 14, 18, 25, 29, 33, 36, 40, 43, 46, 36, 53, 10, 14, 18, 10, 14, 18, 25, 29, 60, 36, 29, 67, 71, 75, 77, 81, 83, 87, 88, 90, 94, 40, 98, 46, 104, 108, 111, 46, 116, 120, 75, 123, 127, 129, 53, 10, 14, 131, 129, 71, 75, 136, 140, 143, 146, 87, 149, 75, 67, 68, 155, 153, 156, 159, 161, 163, 75, 165, 77, 170, 81, 172, 81, 67, 88, 123, 156, 146, 87, 88, 156, 90, 183, 186, 188, 87, 90, 183, 94, 192, 143, 197, 199, 116, 75, 104, 108, 204, 172, 108, 208, 120, 127, 159, 90, 199, 163, 159, 215, 156, 149, 120, 153, 217, 123, 218, 131, 221, 127, 159, 87, 123, 225, 88, 155, 67, 165, 136, 227, 143, 221, 123, 218, 221, 143, 68, 67, 88, 123, 127, 143, 217, 68, 67, 153, 154, 155, 156, 234, 235, 159, 120, 161, 237, 143, 217, 165, 143, 241, 199, 188, 242, 197, 75, 67, 165, 241, 217, 248, 250, 172, 146, 221, 161, 225, 234, 111, 186, 153, 75, 217, 75, 188, 192, 257, 188, 68, 120, 90, 186, 127, 90, 208, 146, 221, 259, 140, 120, 235, 208, 165, 262, 199, 188, 68, 120, 215, 267, 217, 218, 250, 83, 75, 165, 75, 215, 225, 208, 234, 71, 149, 153, 75, 235, 208, 234, 67, 265, 272, 233, 241, 143, 120, 242, 257, 155, 153, 143, 153, 248, 267, 250, 116, 120, 75, 237, 71, 235, 250, 163, 259, 227, 153, 262, 67, 75, 155, 233, 272, 265, 116, 241, 281, 272, 68, 149, 120, 155, 283, 163, 67, 208, 285, 265, 287, 233, 285, 68, 287, 68], [3, 7, 11, 15, 19, 7, 11, 15, 22, 26, 30, 15, 37, 41, 44, 47, 50, 54, 11, 15, 19, 11, 15, 22, 26, 30, 61, 37, 30, 68, 72, 30, 78, 47, 84, 26, 30, 91, 37, 96, 99, 102, 105, 109, 112, 115, 117, 109, 122, 124, 128, 130, 54, 11, 15, 130, 132, 72, 30, 137, 141, 122, 147, 132, 150, 30, 68, 154, 109, 68, 157, 109, 162, 164, 30, 166, 168, 99, 102, 173, 175, 176, 177, 124, 128, 147, 132, 30, 72, 168, 184, 115, 189, 132, 96, 99, 37, 166, 195, 96, 99, 201, 150, 105, 109, 205, 164, 109, 154, 109, 157, 109, 211, 112, 213, 109, 154, 72, 109, 195, 208, 215, 124, 208, 130, 150, 166, 224, 26, 124, 157, 30, 226, 217, 166, 115, 213, 150, 30, 124, 208, 150, 195, 208, 176, 177, 124, 72, 224, 208, 233, 217, 68, 154, 195, 214, 195, 208, 109, 109, 236, 117, 195, 208, 214, 195, 201, 99, 173, 166, 168, 177, 68, 246, 213, 215, 68, 251, 173, 147, 150, 254, 166, 195, 99, 175, 208, 30, 215, 122, 164, 166, 251, 173, 154, 195, 78, 258, 166, 168, 154, 147, 150, 260, 141, 226, 217, 154, 214, 254, 184, 263, 154, 195, 154, 109, 208, 208, 269, 84, 177, 246, 150, 154, 166, 215, 195, 166, 150, 208, 150, 208, 215, 195, 215, 213, 195, 208, 213, 150, 195, 166, 254, 109, 68, 224, 233, 68, 109, 236, 201, 226, 150, 213, 166, 208, 277, 117, 278, 213, 233, 236, 215, 279, 195, 208, 224, 201, 117, 280, 254, 195, 208, 109, 109, 226, 213, 213, 215, 215, 277, 280, 195, 208, 236, 233, 195, 208], [4, 8, 12, 16, 20, 8, 12, 16, 23, 27, 31, 34, 38, 42, 12, 48, 51, 55, 12, 16, 20, 12, 16, 23, 56, 58, 62, 51, 65, 69, 73, 76, 79, 69, 85, 42, 89, 92, 95, 42, 100, 48, 106, 31, 113, 48, 118, 68, 48, 125, 48, 51, 55, 12, 16, 62, 51, 133, 135, 138, 56, 144, 62, 148, 151, 48, 144, 154, 154, 155, 69, 118, 154, 69, 48, 161, 79, 171, 69, 174, 69, 69, 178, 180, 69, 85, 148, 138, 182, 92, 95, 155, 135, 42, 92, 95, 148, 193, 76, 198, 200, 118, 48, 202, 58, 62, 206, 207, 69, 209, 210, 89, 92, 200, 135, 178, 216, 69, 174, 68, 68, 138, 202, 65, 219, 222, 48, 118, 148, 56, 138, 118, 154, 69, 155, 138, 228, 144, 206, 106, 229, 174, 144, 154, 144, 138, 202, 48, 144, 138, 154, 144, 68, 154, 154, 69, 228, 133, 152, 165, 154, 69, 182, 240, 155, 135, 155, 200, 135, 243, 198, 210, 244, 155, 165, 152, 249, 144, 206, 219, 252, 154, 178, 255, 113, 155, 155, 210, 240, 135, 135, 65, 151, 48, 155, 209, 92, 155, 210, 92, 244, 62, 206, 138, 202, 68, 151, 144, 161, 68, 200, 135, 265, 165, 266, 73, 152, 207, 144, 62, 48, 161, 76, 249, 138, 69, 271, 133, 73, 265, 135, 151, 144, 266, 144, 155, 182, 133, 155, 182, 161, 274, 151, 161, 265, 135, 155, 266, 151, 144, 138, 161, 275, 69, 73, 276, 144, 135, 138, 249, 68, 68, 244, 135, 161, 151, 144, 155, 138, 155, 151, 144, 155, 151, 161, 161, 249, 69, 69, 244, 144, 155, 271, 276, 144, 155, 266, 265], [5, 9, 13, 17, 21, 9, 13, 17, 24, 28, 32, 35, 39, 28, 45, 49, 52, 9, 13, 17, 21, 13, 17, 24, 57, 59, 63, 64, 66, 70, 74, 32, 80, 82, 86, 28, 32, 93, 39, 97, 101, 103, 107, 110, 114, 66, 119, 121, 49, 126, 49, 52, 9, 13, 17, 63, 64, 134, 59, 139, 142, 145, 63, 64, 152, 66, 153, 68, 144, 70, 158, 160, 151, 134, 66, 167, 169, 101, 134, 59, 70, 82, 179, 181, 82, 86, 64, 66, 74, 169, 185, 187, 190, 97, 191, 101, 64, 194, 196, 191, 101, 160, 103, 203, 160, 63, 103, 121, 195, 110, 179, 110, 212, 114, 214, 167, 213, 134, 160, 153, 121, 158, 203, 187, 220, 223, 66, 119, 57, 142, 139, 59, 151, 134, 187, 66, 214, 152, 66, 107, 230, 231, 153, 144, 145, 139, 203, 103, 232, 187, 151, 152, 153, 154, 68, 70, 214, 187, 121, 160, 68, 238, 239, 230, 70, 214, 187, 101, 59, 194, 169, 179, 245, 247, 214, 232, 70, 152, 66, 220, 253, 144, 194, 196, 101, 70, 187, 194, 256, 190, 231, 66, 152, 66, 195, 196, 80, 247, 194, 169, 213, 63, 103, 139, 203, 261, 152, 68, 239, 121, 185, 264, 213, 214, 68, 268, 121, 121, 145, 63, 139, 270, 223, 195, 66, 238, 239, 187, 74, 230, 231, 121, 266, 153, 232, 195, 236, 273, 70, 74, 239, 66, 121, 268, 245, 119, 247, 153, 144, 153, 187, 270, 253, 195, 167, 230, 232, 119, 66, 70, 261, 153, 256, 264, 236, 144, 266, 273, 158, 247, 144, 68, 273, 121, 167, 282, 195, 70, 158, 284, 266, 286, 236, 288, 68, 286, 68, 288]],[1],[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, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288]) ``` ``` Automaton("det",266,4,[[1, 127, 50, 50, 115, 249, 50, 8, 257, 10, 151, 12, 13, 14, 81, 78, 34, 106, 137, 107, 21, 22, 82, 89, 71, 43, 43, 62, 63, 63, 44, 10, 179, 171, 214, 265, 206, 38, 137, 152, 21, 151, 71, 22, 41, 41, 47, 13, 49, 50, 50, 210, 50, 210, 116, 90, 64, 49, 207, 207, 207, 62, 232, 64, 64, 89, 151, 236, 236, 70, 71, 236, 116, 260, 128, 75, 13, 38, 77, 133, 14, 82, 13, 13, 77, 235, 64, 64, 231, 206, 138, 91, 91, 206, 90, 264, 137, 169, 10, 10, 41, 71, 232, 228, 232, 21, 21, 107, 106, 110, 111, 266, 256, 114, 114, 116, 251, 251, 116, 114, 114, 111, 266, 260, 122, 182, 127, 128, 129, 213, 132, 132, 129, 49, 49, 138, 138, 138, 249, 71, 43, 43, 210, 235, 183, 214, 132, 265, 206, 138, 232, 64, 64, 153, 153, 64, 152, 152, 82, 236, 236, 82, 116, 116, 64, 207, 266, 64, 231, 169, 171, 250, 227, 70, 175, 175, 176, 10, 47, 178, 178, 110, 111, 266, 260, 122, 266, 127, 213, 49, 49, 152, 257, 153, 257, 90, 90, 183, 250, 264, 62, 228, 229, 82, 82, 206, 64, 266, 249, 249, 249, 242, 213, 214, 64, 116, 114, 114, 50, 50, 236, 236, 261, 115, 152, 251, 8, 228, 229, 229, 231, 232, 237, 235, 235, 236, 237, 235, 235, 235, 235, 235, 235, 242, 242, 242, 115, 251, 249, 250, 116, 116, 116, 207, 64, 265, 266, 257, 256, 266, 264, 261, 260, 264, 265, 266], [1, 125, 1, 114, 114, 121, 115, 3, 23, 19, 13, 15, 230, 28, 201, 202, 16, 84, 123, 103, 105, 208, 114, 84, 172, 199, 199, 119, 83, 83, 123, 170, 16, 31, 27, 26, 25, 104, 102, 23, 28, 13, 120, 208, 48, 103, 19, 230, 239, 1, 114, 218, 115, 219, 82, 140, 23, 208, 204, 216, 216, 119, 174, 119, 119, 84, 13, 115, 115, 50, 120, 50, 82, 204, 262, 79, 230, 104, 203, 85, 28, 114, 230, 230, 203, 3, 23, 119, 96, 96, 96, 123, 102, 140, 208, 3, 200, 200, 98, 97, 103, 120, 119, 120, 119, 28, 105, 103, 105, 54, 3, 23, 141, 1, 250, 50, 82, 114, 50, 1, 250, 3, 3, 219, 219, 125, 54, 263, 124, 124, 27, 124, 223, 208, 239, 25, 208, 208, 120, 120, 217, 217, 217, 120, 120, 142, 142, 141, 140, 140, 174, 174, 174, 204, 216, 23, 119, 23, 250, 114, 114, 250, 162, 162, 159, 205, 159, 159, 208, 123, 170, 1, 219, 50, 208, 208, 123, 177, 177, 19, 170, 173, 172, 172, 199, 199, 23, 186, 185, 184, 184, 23, 120, 216, 23, 140, 208, 120, 1, 3, 119, 120, 114, 114, 250, 239, 119, 3, 121, 3, 120, 219, 212, 212, 23, 50, 1, 250, 1, 114, 50, 114, 219, 114, 23, 114, 3, 120, 114, 114, 208, 119, 125, 121, 3, 50, 54, 120, 3, 120, 121, 3, 120, 218, 219, 217, 114, 114, 3, 1, 250, 250, 250, 253, 252, 173, 172, 120, 125, 3, 3, 219, 219, 3, 54, 3], [1, 1, 249, 249, 6, 1, 1, 247, 7, 130, 167, 17, 11, 66, 33, 33, 131, 136, 10, 32, 150, 9, 112, 36, 149, 112, 149, 56, 167, 37, 181, 130, 35, 147, 139, 51, 139, 11, 10, 234, 147, 37, 148, 113, 136, 136, 146, 24, 249, 1, 1, 249, 249, 249, 139, 6, 238, 127, 134, 238, 134, 9, 148, 238, 134, 167, 36, 50, 249, 247, 73, 249, 51, 139, 112, 167, 76, 76, 11, 167, 80, 73, 67, 66, 66, 135, 58, 58, 112, 139, 233, 100, 100, 2, 6, 95, 10, 32, 130, 130, 99, 94, 94, 56, 149, 150, 147, 150, 136, 51, 51, 51, 7, 51, 51, 51, 7, 6, 139, 139, 139, 2, 58, 134, 139, 7, 1, 112, 112, 249, 238, 238, 112, 249, 127, 238, 233, 238, 1, 149, 112, 149, 249, 135, 7, 139, 238, 51, 139, 238, 112, 238, 233, 234, 234, 134, 234, 190, 112, 50, 249, 73, 139, 51, 238, 134, 51, 134, 148, 32, 147, 145, 145, 145, 258, 259, 180, 130, 146, 189, 189, 51, 51, 134, 134, 139, 2, 1, 249, 127, 249, 191, 191, 191, 188, 188, 188, 188, 198, 197, 196, 196, 195, 187, 187, 139, 233, 134, 127, 127, 127, 49, 249, 139, 243, 211, 211, 211, 210, 210, 210, 210, 95, 209, 241, 209, 126, 117, 117, 9, 112, 112, 50, 50, 50, 50, 50, 50, 49, 49, 127, 127, 127, 249, 249, 249, 7, 7, 1, 247, 51, 139, 211, 134, 134, 51, 51, 7, 7, 2, 126, 145, 139, 247, 51, 51], [1, 51, 3, 4, 4, 7, 7, 50, 73, 61, 11, 12, 40, 109, 101, 93, 45, 18, 19, 20, 21, 64, 161, 29, 193, 118, 193, 65, 11, 42, 19, 59, 30, 46, 163, 164, 163, 40, 39, 57, 46, 42, 246, 60, 18, 21, 61, 158, 72, 50, 51, 53, 53, 3, 55, 55, 57, 246, 156, 64, 65, 64, 155, 64, 65, 11, 29, 68, 69, 236, 160, 72, 73, 55, 157, 11, 154, 154, 40, 11, 46, 160, 225, 192, 192, 86, 87, 88, 157, 118, 155, 19, 39, 74, 161, 239, 92, 92, 166, 254, 20, 144, 88, 240, 65, 109, 108, 21, 21, 50, 50, 73, 73, 50, 247, 236, 73, 161, 72, 3, 5, 54, 86, 239, 3, 51, 50, 64, 64, 161, 165, 64, 157, 161, 245, 165, 60, 64, 51, 240, 161, 240, 4, 144, 51, 55, 57, 73, 55, 57, 157, 157, 155, 57, 64, 156, 64, 87, 118, 160, 161, 248, 163, 164, 165, 168, 164, 168, 60, 19, 108, 3, 3, 72, 64, 60, 19, 194, 194, 61, 59, 247, 247, 193, 193, 5, 74, 7, 69, 244, 69, 156, 240, 65, 74, 74, 246, 143, 219, 86, 88, 144, 222, 222, 226, 72, 60, 239, 52, 54, 143, 239, 72, 72, 215, 221, 219, 224, 219, 220, 221, 222, 239, 220, 215, 222, 54, 160, 160, 161, 64, 64, 160, 68, 236, 236, 236, 160, 239, 240, 244, 245, 246, 69, 72, 161, 51, 160, 50, 50, 248, 118, 226, 255, 255, 248, 248, 160, 160, 245, 245, 72, 72, 236, 236, 236]],[12],[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, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266]) ``` 4. ``` Automaton("det",9,4,[[1, 1, 2, 3, 1, 1, 2, 5, 2], [1, 1, 2, 8, 2, 2, 1, 6, 2], [1, 1, 2, 7, 2, 1, 2, 2, 2], [1, 1, 2, 9, 1, 1, 1, 1, 1]],[4],[2, 6]) ``` ``` Automaton("det",100,4,[[0, 1, 3, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 34, 36, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 52, 53, 54, 55, 56, 57, 58, 59, 60, 62, 63, 64, 65, 66, 68, 69, 71, 72, 73, 78, 79, 81, 84, 85, 86, 90, 93, 94, 95, 98, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 2, 4, 6, 7, 9, 10, 11, 12, 13, 15, 16, 19, 20, 21, 22, 23, 24, 25, 27, 28, 30, 31, 32, 35, 36, 37, 38, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 59, 60, 61, 64, 66, 67, 69, 70, 71, 75, 76, 78, 80, 81, 84, 85, 86, 87, 89, 92, 93, 95, 96, 97, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 15, 17, 19, 20, 22, 23, 26, 28, 29, 30, 32, 34, 35, 38, 40, 41, 45, 47, 49, 50, 53, 56, 57, 58, 59, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71, 72, 73, 74, 76, 77, 79, 81, 82, 83, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 12, 14, 15, 19, 21, 22, 23, 24, 26, 27, 28, 32, 33, 34, 35, 39, 40, 42, 43, 46, 47, 51, 54, 55, 59, 60, 61, 63, 64, 67, 71, 72, 73, 74, 75, 76, 77, 78, 79, 82, 84, 85, 89, 90, 91, 92, 93, 94, 96, 97, 98, 99, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],[39],[1, 2, 5, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 21, 24, 25, 28, 30, 31, 33, 35, 37, 41, 42, 43, 44, 49, 50, 52, 53, 57, 61, 63, 65, 66, 67, 69, 72, 73, 74, 75, 76, 77, 79, 80, 81, 82, 83, 85, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 100]) ``` 5. A [pair of equivalent DFAs](https://paste.ubuntu.com/p/GNTvfXCCt7/) # Non-equivalent DFAs ``` Automaton("det",100,4,[[0, 1, 2, 3, 5, 7, 9, 12, 13, 15, 20, 21, 23, 24, 25, 27, 29, 30, 31, 33, 34, 35, 36, 37, 40, 41, 42, 45, 46, 47, 48, 56, 57, 60, 62, 64, 65, 69, 70, 73, 74, 76, 80, 81, 82, 84, 86, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 9, 11, 12, 13, 16, 19, 20, 21, 22, 23, 24, 25, 26, 27, 30, 36, 37, 38, 39, 40, 42, 47, 49, 52, 53, 54, 59, 60, 61, 62, 63, 64, 65, 68, 69, 71, 72, 75, 76, 78, 81, 82, 84, 86, 87, 88, 89, 90, 91, 92, 95, 96, 97, 98, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 21, 24, 25, 26, 27, 28, 29, 30, 33, 35, 36, 37, 38, 39, 41, 43, 46, 50, 51, 53, 55, 56, 58, 59, 60, 61, 62, 63, 64, 65, 67, 68, 70, 73, 74, 76, 77, 78, 80, 83, 86, 87, 89, 91, 92, 93, 95, 98, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 6, 8, 13, 14, 15, 17, 19, 21, 22, 23, 25, 27, 28, 29, 30, 31, 32, 35, 36, 37, 40, 42, 46, 47, 48, 50, 51, 53, 54, 56, 58, 60, 61, 63, 64, 65, 66, 68, 70, 71, 72, 74, 75, 76, 79, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 93, 94, 95, 96, 97, 99, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],[52],[1, 5, 6, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 23, 24, 25, 26, 27, 28, 29, 30, 32, 34, 35, 36, 37, 39, 40, 41, 42, 44, 46, 47, 49, 51, 52, 53, 54, 55, 60, 61, 62, 66, 67, 70, 72, 73, 74, 75, 76, 77, 79, 80, 81, 82, 83, 84, 86, 87, 89, 90, 92, 94, 96, 97, 98, 99, 100]) ``` ``` Automaton("det",100,4,[[0, 2, 3, 4, 6, 7, 10, 11, 14, 15, 16, 17, 19, 20, 21, 22, 24, 25, 26, 27, 28, 31, 34, 35, 36, 37, 38, 40, 42, 43, 44, 46, 48, 49, 51, 55, 56, 57, 58, 59, 61, 62, 63, 64, 69, 71, 72, 73, 76, 78, 79, 80, 83, 86, 87, 88, 89, 90, 91, 95, 96, 99, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 17, 18, 19, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32, 34, 35, 36, 37, 40, 41, 42, 43, 45, 47, 48, 50, 51, 53, 56, 57, 59, 60, 62, 63, 64, 71, 72, 73, 75, 76, 77, 79, 80, 83, 85, 86, 87, 89, 90, 91, 92, 93, 96, 98, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 2, 3, 5, 6, 7, 8, 9, 10, 12, 13, 16, 18, 21, 23, 24, 26, 27, 28, 29, 30, 32, 34, 35, 36, 37, 39, 40, 41, 42, 45, 47, 48, 50, 51, 52, 53, 56, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 75, 76, 78, 79, 80, 82, 84, 85, 86, 89, 90, 93, 94, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 2, 6, 7, 8, 9, 10, 11, 12, 13, 16, 18, 21, 22, 23, 24, 28, 30, 31, 32, 34, 36, 37, 38, 39, 40, 42, 44, 45, 47, 48, 51, 52, 53, 56, 57, 59, 60, 61, 62, 63, 64, 65, 67, 70, 74, 76, 83, 84, 86, 88, 90, 91, 93, 94, 95, 96, 97, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],[17],[1, 6, 7, 8, 9, 10, 11, 12, 13, 16, 18, 19, 22, 23, 27, 28, 29, 30, 32, 35, 36, 38, 40, 41, 42, 44, 46, 47, 48, 50, 51, 53, 54, 55, 62, 64, 66, 71, 72, 74, 75, 76, 79, 83, 86, 88, 89, 90, 91, 92, 94, 95, 96, 97, 98, 99, 100]) ``` ``` Automaton("det",100,4,[[2, 3, 6, 7, 8, 9, 10, 12, 14, 15, 16, 20, 21, 25, 26, 28, 29, 30, 32, 35, 36, 37, 40, 42, 43, 44, 46, 47, 48, 50, 53, 54, 55, 57, 58, 59, 62, 63, 64, 65, 67, 68, 69, 72, 73, 75, 77, 79, 81, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 4, 5, 8, 13, 14, 15, 17, 18, 19, 20, 22, 23, 29, 30, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 58, 59, 60, 63, 64, 65, 66, 67, 68, 70, 71, 72, 74, 75, 77, 78, 79, 82, 83, 84, 85, 86, 87, 93, 95, 96, 97, 98, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 3, 6, 7, 9, 10, 12, 13, 14, 15, 16, 17, 19, 20, 21, 23, 25, 27, 28, 30, 31, 32, 37, 38, 40, 41, 42, 45, 47, 49, 50, 51, 52, 56, 59, 61, 63, 64, 65, 68, 70, 72, 73, 74, 76, 77, 78, 80, 81, 85, 86, 87, 88, 92, 93, 94, 96, 98, 99, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 3, 4, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 18, 20, 21, 22, 23, 24, 26, 27, 28, 30, 31, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 48, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 62, 64, 65, 66, 68, 69, 70, 71, 72, 74, 75, 76, 77, 79, 84, 86, 91, 92, 93, 96, 97, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],[46],[1, 2, 7, 8, 10, 12, 13, 15, 17, 18, 20, 22, 23, 24, 25, 27, 28, 29, 30, 32, 33, 35, 36, 37, 39, 41, 42, 44, 45, 47, 49, 50, 51, 52, 54, 55, 57, 59, 61, 63, 65, 66, 67, 68, 69, 70, 71, 73, 75, 76, 77, 79, 80, 81, 82, 85, 86, 88, 91, 92, 93, 94, 95, 96, 97, 98]) ``` ``` Automaton("det",100,4,[[0, 1, 4, 5, 7, 8, 9, 10, 11, 12, 15, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 33, 35, 36, 37, 39, 43, 44, 45, 46, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 62, 63, 67, 68, 70, 72, 73, 74, 76, 77, 78, 81, 82, 83, 85, 87, 93, 94, 95, 96, 97, 98, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 3, 4, 5, 8, 10, 12, 15, 16, 17, 18, 19, 20, 21, 27, 29, 30, 31, 32, 34, 35, 36, 39, 40, 42, 45, 46, 47, 49, 50, 51, 52, 55, 58, 59, 60, 61, 62, 63, 64, 66, 67, 70, 71, 72, 73, 74, 75, 77, 79, 80, 81, 82, 83, 84, 86, 87, 88, 89, 92, 94, 96, 98, 99, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 2, 3, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 20, 21, 23, 30, 31, 33, 34, 35, 37, 38, 39, 42, 43, 44, 46, 47, 48, 50, 52, 53, 54, 55, 56, 58, 59, 60, 61, 63, 64, 65, 66, 67, 70, 71, 75, 76, 77, 80, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 94, 98, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 3, 4, 7, 8, 9, 10, 11, 12, 14, 16, 17, 18, 19, 20, 21, 22, 24, 26, 27, 28, 29, 31, 33, 34, 35, 37, 38, 40, 41, 43, 49, 50, 51, 52, 53, 54, 55, 57, 58, 59, 62, 64, 65, 66, 67, 68, 69, 71, 72, 75, 76, 77, 80, 81, 82, 83, 86, 87, 88, 91, 93, 94, 95, 96, 97, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],[45],[2, 4, 6, 7, 11, 12, 14, 15, 16, 17, 19, 20, 24, 25, 27, 28, 29, 30, 37, 39, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 61, 62, 63, 64, 65, 67, 71, 72, 76, 81, 82, 83, 84, 85, 86, 87, 88, 91, 92, 94, 95, 99, 100]) ``` # Score This question is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and [restricted-time](/questions/tagged/restricted-time "show questions tagged 'restricted-time'"). Your code must be able to run all the test cases in less than a minute on TIO. Your code only needs to output something Truthy or Falsey depending on whether the two DFAs are equivalent or not. [[GAP](https://www.gap-system.org/) has a library function for this but I am not aware of any other languages that do. Please feel free to use whatever your language does provide however.] [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 101 bytes ``` {a:&,/~=\:/+/'x[2]=\:'!'#'*'*x:+@[;0;0,']'x;n:#**|*x;~#a^a^{?y@<y:y,/x@\:y}[,/'+\:'/(n;1)**x]/,n/x 1} ``` [Try it online!](https://tio.run/##7Vvbrh03cn2fr9iBg8hHVqDmvVudIP4PjQbjFwfBBAowmAcJjv3rTq21imx2731kY3ySIMjg7At3N1msKhZXXdjnT//48V8//vzz9@9@@O7dP7x5@9M///7d22/evvr0Pn6w5qu/e/XVq9evXn9698237/dlX968@vDq0/7x3VevX//n60/7T19994fv/vDDv3z@9p8@v/v85u2nb3//7vOP79@8ffWNDX779cc9PL1@/enD2zcf3366hR9//su7H/7@/eef/vzu@9un/Y//8af96z9@/92//fv@af@8//npw4@/@8v7r7/@OtzSLd@WPdwiWk972tX43e120@2gm097xK0n3AkfNHrhqHJbSMFbo13Zjsf1px20Mm6Rvk0Qb/izS3skLbt9aRW0wFe4TI6b9RYWfrVbsHbGz7Ci0fir4LI11z0ZSWsEfRW07FvNFS819Vn2bDzhmtFIuiRK3q8d10LaizG53QJ55cwJPzOpRRLIPqjdmpRAJVNHoLmR7zD1rhy8jmWIPqFGNPuM7BT5quKFeodcG3/jr5DjZJ@6UnZcjmiCASlsUU@94uhWnEeRJ1@ZXFZ@unqf9rL/kjTsd127jXfb9B3zLa63tOBCsldl23vwI224hH7llo2diAH20y7mxrtmbAtHVtzNFRetc2TnnDAKtyr6Y7ipdDHjoCGB1dUbkXqJxY0qmYiZr9VvubHxinoa9STOCibQqLzhom5Z25izlxrWR6Psp18p/LQrac8yV@hu80a0lTOWK14puBXH4rdCv2KfefFP0oLQGhWoNhubA36aDqCbArLeuUuCV0M3qFmvZYc1yd6Kf5s20i0aGdq/tZNZStOdMEy0cr7kCscczQfh4gq5bRBUVdAH7ZXrtZADLpz0mjgQd7Gsv24vlbGdoEpbPddjckOCahoNidZl2sFqc8UgTcWktshmSAc/2Rc5d2bKMu3VRMyLmQxhqsW@jaiQJpGNMvFTzvxwaCQJchBpAlvnxl/Y7euNeg3EHy4pqKxc6gU7yr5tPlmN7nAi392CNl5uNOLG8YmEC67z02ZyOAEAAG5pf3g1vsyowezGH1Bv1gf@pFTYx@iCqdHC1y3uRBQsIYdynRK3ehD6PlrFxBmwQq4bkCC7GYPDoCIs3Xzrpu1pb/v/mMFcMG8CmakZpRbinW9CrnBJV0wanSshDg3zBaYy8y0mSbitBvTWMJls8bFjb9sqKAJYGRkTEz@5LReMCzAGLL4ROyYEuNgFkQ4JnhU3oJ2KGYIZvN2x2St0DgSCKQFfsBJY0MShlZyFtoC70CK@KjnkxBghirhivza4b7ux2g27ZDf8ikkTtigeNqO4bZQCc7hsEd82g9orBaRkxhKIYERN/Bnp6SrFYLcCy2vkKULbCesdxvDVb5nyV8lbG2WDaiI6AZ84QATYtmumnUna3jE0vyGtZdcg9i62fZEWwVfF7j5GcUq0DYQozwrnF6mRNpjCXfSOGeaySCnwNWAKFGFD2BeweSi6cK0wBOoEtxtwurFdpUkuQ6UM1qR@nWQEszAP7BNjnvfARo2DSScCvUfjktwFcbcehlLUIYoGWGxBa@QcpuMOqGCShm3pGoFtYJbs3He7xHWsMPSBcdDJsQOg4BZEHHdqokhcVowyMao0U4rmwpxYCaNBXZtN4xqEHAYF2EwkhhnB9FrE8dpExX7XlT8rotPJ2femozZdeRq@uDGGyHexQe9cg0OyUTeurNFWjFqzd9jYYbPNBuTDhsEmAh1rM4Jo@h0RXALwsSPmORmhRaceaKBB3XPjnYAYbBE4ZBJj0@nCMCpjtlBtGexW56QBuRGFA37bMbuThSyRA8Kaxeu68Y6kYeABtC9@IS6BvHQRI76rOOqcdbYihEMMAyfg9wknGwlyDTEjXMAijZB0xTagbsluoe4jXERwdhiepa6UQQCDnfAsMKzLu9BOQht6RO@Qj1FgDZwDoDHZYLP3CdQstOqKxiSwOuzdkCgQfpagXtBzQTySD0VuXBLQTYtrQOtHyftIZ6@B2HpMh8udaF1oJ0M1JZNTTkbjPMj0tYmO5bFusF9wD9apOueRHGFI1fWu2rFem8MKVmAoKA31S4phpFR9InJ31UKNMTr1IF2SChYMSNZEkauVxFFsk9VwNYP6rq7d6xLGviDJuS2kj/6DDminIcWeR4jN8NKbjMZT8HgnMz804LN1KuXoPjqb17H1sh1pHQydTM@2mmaNxj90znDc9pg5hI3tsCwgFxZlIIHhewiEeLQQpZ9nE@0AxuHajCl63owbAUPsLr5ydl8of1g3ksVPa6KDARu0aliNe43X2QIcLM4uKSIQXKMzTTegvMIvoMtGKcMG@1o4E7yDYZC0EReoqYFoJDYsrgX2hhxc9DpYkY9LogGYR@AYY9cO5oTYaZ2lEmuwEMmPWaHZGEV16ATfTrurKq3jVt9oIkpi0HaJChh8LlNIzMtQB12UCxMZVa0UM2aPRzgUY7bBG4UCWczGrV5oAvK0xce7guxNElpdzkYN9o5QpqyAYnfVySAooi14XQ8ma/G4ot6axMMKuSV1A6li2KhBFU2G15JGpzKIg0rooq7RNeZtBElQf/GAqU4qI8yEYw3Yt2@c2JyqWzp4kWnEfhXBcR/vyy/1Tdd8XtLOm9s5KXgPCDbmcq6My72MYooFZqOpqopSyQ1tpK4W7se59@hrDszCHwQuplhTtfncjNG2xUw3FgOK2MYMDaE4oG2BzwQcYi9xXEBkgiQQX/Uyn6gHwygEj8z0AAal37CuVYFplbk3GC60vUg7SXMw4t3Egog1chkAFMiHyLALktUXIIGAHikSvgKHY1bmGHVc4mQmWIRw1oZ/QhPKAoxAVswDo2foJH8WGOAmMiR@fUxZRQoBIMJUQ1/XEyIQKMAUAX24gOhIB3coZEHsiDA7eGSbqTUMJGlwyzJDExXuVblVRIOLiDGdkXywTNgpCCC6mnqYBsDM5mprsEBARZPXRvy3dMYoT2eoq9EIoAd1DTdfqXPwzrWVRFCkdYZbzG3MBv11dbtssUqeKm4pAEPq7E6TIkZmGkFv2RMJNOkb04FdFxm8tXyoFNmM2x3VCEcLpwuXuKjnRq7ZcaVCsH5kvYtffImbq4QxRl@3yP7aVpIoUTMUI9UBTZEIt4qyIJ6XuGwIC8Sdb4u4@ijsTjCslAs/@bX@79XJ0sNSGQOEiIKDWabhF6KQBtdbWNsA8McOQVwxVRoq9zeqEpFhSmblo6LEYN7ILHRlnQG7PiFeNPtYe3VhZRXAtvZG7DJD8yyhoUbCBGRxLIuOZ9nzBm280MM1qi14upS475U2eRQO9QXPA6PnRUz/M8OjEKtXXFYWWZRNBeVNyXEjedkFGQ08RPIcm2mul0H65kdATDPx/LMsl83vxQ6mxKuXaBb3MFFFEYbzHkQTVFff9QsDLpYQmJzlc4KG2ItYuxBv6T1Zv8kOtFUAgKICUjUWYoJKOVtyrCgOu41BSGDetijsXqI2/5KZu/WwTHmB4jLkbdHzNiITw@d6FBkYiS2qVcCcWcnJqjNE1W8iC6PbQAJsVIXzKsgo9G4HVqKEjVwGpQYWZLKjYxVCZvn@yGQqMGiK3OqZQRO3fGnMlVhsqIIDFBuQBxEOavfrTWBTHceayg2R8UZm9IFYgOkCgjIgNfAUZQkEfWsSQAAt6b4bIaFXq2GLOpVgoqr9uaqC4pbUEcIo2gSwz8Vtc2kOEivTBGNNRwe@fbn7u58E38HlWlStBQmoRjFRI6XMwwlm/MeBCRbav7DPzIwqj1NkDHpDd7ZuwIwMZkBSC1cdNpQoV6WituQsboIRmHKSiNFLztAmQlhSo014lAoI0S94M4YxPQrBK0sOGBCMKlE6CEgIqQM@uLTYloSPLL5oKsGhpF/3vuQ5aotN8KFQI@odNz9LEmisIwgdC8MdA3RZtVswrK8IOw8NCjtGPIY3rMkVCi6CtAn9YAlq7aoSdASZv/FKFCkHcvCwTtixnhXiQtILR8VRLlDpRb3E723plWFOUpVI@DZexeoihqpyguN9YEXNJ127rbmI9M/BsyBblfWACUJFh4nmEDHDRHn8Jlzozc1WwoCJrk3aAax5QgAiRXUNZUeKZUYJnKFEntF0s4linqc5YfNTbOLbOqAVp3RZzokOz2sS2AZeS4dfZKl9o0tN6oz1ZP6PJeIhppxl9NOn4IXYRTWBRQdexNbNeWSZPShPhi0BUJPjenb89iQCPic4DzoQorflUSmmKYtWOxM@m2YK9BjptuoUK/Qob@FVacUIIgDgS0pwRlDrch/EExRmOZJpePbATEoBgnRXstPNPGIvnTO3LF3i3BhLOhzEwheDg8xjOPom14UfXp@ONBZ3bc3PLHRNYUH0EGHRm@5a76FWCR6TW53MRZXvqHfxQilzkc1n9mUn4728Nm40vXvAkDxgOAwo9jOd4rEBzzcli3hyvVOUW5r0fDBI68FRHq27D9/c@9P4hp7DUDuNbXMT4Fc6U156vFacrtfX49J7TrN5PME4L3dq7uf7O6lI0tVACuW08ox7kx7FcFiqN/1qfH5kURjGkwDb9YnPQyhK7A8WIM5T0T75SRb8NDymYjh4JYRkiNSLl9A3leJ0ZrDoFCirKwtVyaNOHcvBEPN2m7lUcQXcIhSiH2KItPJ7I5n@i0xUGktWjoSIJU88RPZBAK8nSnBWtqBXZeYLJ2CsIy1Y1ZtpavJQXQ/@IHqUPhhHLwjlEdznWz/ggxF4DRqSIfXgq83NKpb8zTKgAnEex3iwr2qYgsB1/KajSl6t54n8vBrSGB/@SRrr4g8SY2jWgvRv@Dc8UyT9tdTXr@u3lwmyHi1gClDGu4eWDM2hGqQJiIrWzYUOPpkEDocs@GaQ7m8G79ObQXrzoN1zeAb57Vgh0CWY6T2ZDuNlxuz9vZzemyqFDK8XFY@UVrXbNtZB4Dq/PEyY5pxtlruKNti1Hw4FdBtoUAOm6yWV7Cays4Oel0K3IiMNnj4DaRdVoSynyeWUQFcVMpHoIeEJqj3z@JD1dJZ8Eh8GOjIxPoeTWBjKfI4JiUXlo20gqWJSiz2TTnglJtIFY3RGUnv67AX17LPGzXNphsN18WyaaaIfPaqYnFkfyOqEdElpWzySag3wCuYGjpuLm3RmEMf5Cl1UvvHEeiEnVNnq4bEWsbFWW1QMYtyeVNbVQ4RGhhUOAijHeKjKVNYlbV43VbW4sg/jLD9PR22CrOiQojQXnsFlf/MnyVGLq4tZO431kjav3l65ShKMTxwqmta1TcWxysKa0sTmaTCkQzmjF3p5OFC7qnAna1WznAhWwM8MmNJGprKYTW4SxZWs3lgUntXqcD14QpzvE@Pkv9lPBCiwhO6q9qJhHe/gcyopPhLhuum0VmBT@0aNfiTC3Ju5cPF8eR3ziUTpjB@TPe0h7n@rY/3/rGPlv9Wy/m/Xsk6Pw@k55KTwEo8G@pPJK58IDwgx/UpTeNKfFdSjw/3vacdj4tXLWUoeTrCQ@3PdQoN7KLjgQHYE@MLe/9KWv@x3bfax07W7w7GpsZfHLub@XX7rHyv9meh4wcbiz0I@gMTmT167EiYYdD38egAc0Jc74g24E8qtHd9mZNs6oHU0A479Nj3IGE6eYlZF66qQHmZLiN0XDPELpZbI6bzoXwD5GeEF79sE7BdUfx7SX0YJV2eZ/fmxkyl013jyiHKE0R9N9ahY6z0WW/K3L3q12Jf83oddHNiL/T3tadsFMHqK9rkoIfSdMLZBf5b9hAKyAFl864KXydDvZb@48@LB2xccuWng8m82wf/Rpun/TLyap2087@FtYn6KZg4sm1GMRuyYlfvTP8thrwfb@S7@mHluL4Vcz5gvRJ/3bv1SWJeWuwgu9r07gOphdDZv2QFUz8kf/GGiF9qmz0gfr87s3npn073EtekunA2@hY@8sfgTYI9V0vyxgROECb7TBNxhwu71ZffvMAA4tHWSvp2hqzwK6Wfzj5PhD@lzf/5txrDuuI8Qfezm7ZmwfNjEBb1fCMye9hL5PxjyY24L8z@KaT88l@DEc2pz@T@W2rfH2ZUf5kBsa8uvwLZ8Vkh8AO0jUOuL2s6B2iyPVvcskj/aeAlQBj7XHpqEu@Bstu3ZN9cp6UqPNnoZD0v/9xj2ZV2HS7pPWS9xankUqpY7K6/9ma4pPD3Ev6xlemTW2t31JXFu7/87OmfxA9/XybP9emO@iB5d@l9Iw2c1DEOI0wbfpii9vdj6B/@/1Tt0H@KP9V8fpCcn95Yn2SfBj2W/w3U9zwQnP7bt@hjEXtTqD0QLbQ9fkP@w/8vaa@HXRxB2QfbSA5v6CMfTozDsUTGFkdgy/ocrXQ22w5YDVrnLJC5eKN1xPJKnAVV3PviILMuURvx1xaGXCEuy4ul0l16PdGqEIF8uqj2XUOa70ORu@17985xmnDUzp5UvF6DsixvD9kxisU0R@n2K3c5WPCeYUkHtXmuKUE9eeA7HwskOTnnVyydVD/Pr7RyXdKO4xun1rIjnDGQuu6zPFBrmmsul4HIfumnTEOlOHu03A9zTnuuuMtWcYc7y3xVaDnBIZ1cWznB@vyPaZBQPK8rpmeisp53PgMNUP3tUK3i4xX8x6djOZaOH@/uCee15K58z6PbihZIHVj2W8@GBwnPh2LDfMoXWQ@7yTLI1YuxL@eQLMfbai2Yvv809OLu450vZjMB23cZjDz/0dM9t4HCF91O9sPWI7KG/G577RTPPXUbwoGb28GjpEqbeaeQooj6sms6b4Lkq4qyLYQwD8MODDfECUVoue68ln6qGs4O7x7V7LHvo48sX66ijlFifPQs7RW2nYO3n/wI "K (ngn/k) – Try It Online") the argument `x` is a pair of dfa-s. a dfa is `(TransitionTable;InitialState;FinalStates)`. we prepend 0 to all rows in both transition tables. this way we can use 0-indexing, and state0 can act as a tarpit state to handle "no transition" transitions. consider a new dfa whose states are the cartesian product of those of dfa0 and dfa1. when state `i` from dfa0 is paired with state `j` from dfa1, the resulting state is labelled `(i*n)+j` where `n` is the number of states in dfa1. `a` is the list of states in the new dfa for which one of the original states was final and the other was not. we combine the initial states of dfa0 and dfa1 using the formula `(i*n)+j`. starting there, we compute the set of states in the new automaton that are reachable through its transitions. we test if that set is disjoint from `a` and return a boolean result. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 431 program + 5 interpreter = 436 bytes ``` m-->member. g(A):-read_string(user_input,"\n",[],_,S),term_string(A,S). f(I,T,S,R):-select(S,T,R),m(I,S),!;S=[I],R=T. x(S,R)-->[N],{nth1(S,R,N);S=0,N=0}. x(A,B,C,D)-->x(A,C),x(B,D). c(_,_,[]). c(M,E,[A,B|R]):-M=[S,T,C,D],(m(A,C)->m(B,D);\+m(B,D)),f(A,E,X,F),plus(B,N,0),(m(N,X)->c(M,E,R);f(N,F,Y,G),union(X,Y,Z),(P=..[x,A,B]),foldl(P,S,T,Q,R),c(M,[Z|G],Q)). r:-g(a(A,[B],C)),g(a(D,[E],F)),(c([A,D,C,F],[],[B,E])->R=y;R=n),print(R). ``` [Try it online!](https://tio.run/##7Vpbjx3FEX73r3B42qOMrb5N9wyWI2EwiAcsWPNAOBxZBBbHkr1Ga1sQhfx2Z@r7qqp7djeR8pYHP5zRXLrr3tVVX59fr16/fP383pvfXrx//@revb@8unj1t4ur@3een31y@Pje1cWPPz978/bqxeXzs3dvLq6evbj89d3b6aMfLj@ajqfp2fT0ML29uHplYz7ZXty/88vZl9O309PpfKPw5uLlxU9vz55uL84P06vtyzblTw@ePjx@eZrOH357/87vZzJyY318cpr@efn271FeTE8O26AwPXkY/iVjPpkeTZ9On8k4efj0MP1@9mh7vn/np7NnmyDHE26/mh5Px23sH@enjflXD4/CeJt3ms5eYdqmIeY9@OHPvDlMv2wfHk/fTZ8fpl9fvnuzvX0yhYNMeDJ9t00g1fPDg1@2F59Pf52@OEzvLl@8vjz7bnv4fhv59cP794@/Txvf00bu9cufX559PQnnb0RpmX/8/o8vTtM3h03Iq4/vPT/7ceN5fHTaBDpM8vTZdHx82iTYiP10tinw2Sb05yex8fHR9Pi0SXH@8B8Pzh9ebjJuln57dn64//79j2fHY5ru1uluDNuvbL/lxmOat9863c15@23fyvatbPel8nnO@/G3za2BY3Hfprstbr/tW9vul@1@2Wgscr/NWbexayGfdSGfGIRgEOox6qsolxRIKCaRIjW5rNdkylHfGtcoosSC7zJQyAn3WFYOEBGrMJtlNIjNMmXevscq5GpWUlW1iC1QldgSb6rqQ9Ew3xjhtbwRXaMoHxf5Lu/lu78WO8Q1maCrMFpXVR783TAJd8JcHxc1D60iooMsptesr1KcXbjVJojCKTYVPcGpYsSU4khu8RHi5sXsJXrDLDBzwvCSfbZR5KN8EEvvjdXnxNa/qyOK@0XI5yKX2ZwD@cVDKe9oUCA8lmhWEIapJDVsG2XHKMxMBXEczLilmuxggwgXIRCYdOOswYH58BJUEz@mueljNf/Q2VXVlif6zhklaIZwlfHQlkMgaU2jPk4Wnk2iENWIpsayC93ZRiajCm1atIhwZfJuAAiDv1glZbcsAhUCFNe3LyN8RXzBrKAC2@5WM5zXojHFAAlZWIIRBRqiejUbz7PJAYngcKFKV8qKxAcYaIh1mYUVKAwgD3RcZtNPwpx05V1d9FVdTtPdoxhH@AglccPuMUGOLfMFPotWIkyR7Lbdi14I52H6bXMl0GQu7jf@oobct4V0ltLHrjp2lewi9AIyAlIFyMsjmGFZ4J3wikkESVjq18WC/Dl1xpGLK9pcEQIDoqhkYnKpCgc@OT9EbC1Kq4rnZUQXt4k/4NQmH5Ffu3zODTZIOjsuxTRbVh1gRoC44LPO/W0KUSXu9km4qyZ4V6GLn2AXsWOKeRzH3LsqF4YR5BHRuWAZCaZ1Suo4Kjeri5O80qxVVSeyMusOFEHM@V2zFxaCj2UQxzZ6BzNj2dGACtAU@yQEGTTqg6P6DO5yN4I9lgkyWMxqBryao42HF0X6BEG6d1b1Pdjl4Ea0oKHpOiHXo4HBspMFHzurGjRuBxvLEGhFQbiYdoR7FCTfWlNdufCgLlSlL1wbio351b52nw3hsXoOhpMHU@fRwar3uKbo26x7aPcZXAMVySuag0gX8YFNoRkbxkY2sVPbhzFjKNq0xd12W9Sk7vbsms3KF3MHymCZB70lq26UsY2J1PJy/4gUv4WGZDpJIpIFE7/LpiKRgQ1nmD7OlbJBokSykIyVJC/OlGCS5SOqw7kz6Uo2ka171ecYAhnFUClFFD3xJuoOjAfZUW8TyBhHqI3aRXRgEVb4PYKCjMJNKV75WPlTV@WHV/KEkbJXwHmyfWJM0898QKYMXUMyyniduqLcsrOq7G8xeFVDxRWLIagc2NAlfZtxU4D1G5kl5s7QDcqp0J9xWEeJrZbJRhabcUSApcHckAm2y8t1i6gWiGAzI6SC61IyZoN9cec8u/HzMo7oucVYkQE8OierN10OMW0qYbQrKw83QWKBv6iNUvEyl5RAYB11oC3ADJIw/c0ajlpzzU7PbS0X0rTooiTqlT4HPrKApNm6Myw8aR2Jurrs9KmzF6iVi4tKhDaEeQ/ZavoJCxi02RJp2cjleeQKwrEbSoysHvBH1Ohw8ewle927gMk57hzNaUNiSM15@YKFvBanqX9Dg9gJegyqS/YfXCzyLGtfrCTpQ2GQQQ4XflNIkqbsncJJQkE8uH8Ue8l@KmWTlKIrn4uscGmY043Z41QpTaT2Ro0svhOXSvVVSFIyithb2hhjI2lC2KBpxd4RUC5h80HSUEIRda@wZFlebxXJWEfJ@eiIMpYDkuU8fJd51dqwagu4YfHBt8HMnk0Atn2ryWkcmmoVkVCBU6iOboNiE5FL0REDv8BNVIIQi618Hd9TFLFKgmnkEZUHnuADZF1YCzJgKbOEt6olssXLKreq5wTmxaijj0FjJrugGx51Lawo9oRh3TiYw1pmZ9mAlgi9aPTOrqgjQIcsoRr6AlgGdJmwrL5COxOMAREFswyWFRYaKKLa3w8VI0Li1f3QsHCQUJvVdWhdwqAAzdDF7r4RihhKV6IqrOpUKMvIMkPAPTIRFVFpoyjwSXenWyVVM0M13agzW87idZOaJ7Glj3axYCfFZg6FLFDOTQYlWtn5CoCCLw86B5UXCjHUQMEmraol5yxqWEQNde0WnD3CmpuWRWsPlaRzLXmoIbLamKrnOmb3xH1jMYa29/I9IwVFpanhyzwtTgNJCeoZQIJXvFlOp@kY5bc9bQlryz1bTAEEbSg7V0USoxZwWVHFmcUcWoiFvTthF@3dsybdmS1easyMQFKDVq9JUdWiSblqn78wcwJpjSzBgLgWTdiVfb/snsiUQYvMRORTFpbsDqh0GwuyWVFY7NRpyOQaNQZ5Vs17wEqTVsVF0dpKrFMqDVlni0KeyIqZ7ZAE8TLAnIvijpL0Vt0VZIl4I96I8rL5D75VJN8vivfnlnpibzjomujARtbUqBCH969wUXTUJzl0QbyxaLkeU3UYeVHUWOGPaBBH9lSbHUsGwIA9PjtWRzTMsdueH9ErMpwdi5rDLfnRoVmCaIsj0MFrhmRgLjtjbza5oy2eFYN2BMQwia@UmyAL2gPudkG3PNZRxKiLb3TVUiSQTQAuRJejAdZr9sQ6@87XtMaNxF@CtaohWXIMRUGY3j1o023tA/CX5PgLUzybzLoDO9krBENRsSoJVxfDO5Mh1Cjf0RD0XImMpY2xoczar7bdzlSCoYyAPIkyF9@Hqm1GxYrGRNwjav2emAOL1u/MhnNTNIOgZ7WECdATAAUTZu1lYLM0XX1naAZ7JlaxReta1JFsyNE3YNvEJgagFP3Kki2NYmdibdeYNA935OzIjgOQgIJBVZaSFoN/PbaH/ClshDMWUvA1FFpPoYs236ID0l8eUpemw14aQdPoFkFvvhhZWNnK8qb0kVojUyk6@LVrgkjzGyQSiW@xOBzIuLQLXCLRgoxaKDZ4abzUnlQVVKuGRkng8VCKAmMdZrOSWSzzA2LQmDBIvS9DhrU3qFdYLvfalr9iJkB4I@6zmgcmYoatY3JlfCEVMbkWU4ExHD3X9q8@jVomyyT75KqFa7KLvCv604S6jO3WGAvMBkjCiyUCUOkRwImjZzS1js0CLoh4dxYkjeYoGBvOrnUwvabWaOtZNGOinXeZNWiIMbkuNw3rFmJhlqygd0PM/SQl690ahmNC8q/WqnsuW0yxYHJX67PHyy6V1nLDmb4o3D4s3aIjExIByy6LMpX2LNo8gV7LovN/uzCf2oXpZY5jFu1eYkBiOe7zIjNpdWsXz6ThWhKVNjpaKbAL52T6ZpZ20TrT2XaMZdzLRBTslsnr/@BIKRa2H9ai8OGZ7qplVLaJiCYFGREVlQWlFkVWZi4qSzJcmeikiqkb2tpV4oluNDwNwY49LPtmW3w79QYd9UJ0QYsyZaE16waQNFQYdUW3q2ZiRG7vmXViMmuoiEG/mY2FD2pE/ak1XVwcEHgdoX8XINxg5hhqvqiQhxaT5hPZdo0hSjYNLNPCV4B9UAFBjtSVCk8NWEsWOow33a4oF@bxHEHr0eCVS/Ozd/ugRWTymjLYhSWcXQavmfVS9mVioaynqckus596sfdfXTCPQFW0H1sM35tdepmZvczcxXfqf3OYvZgs@p4GMNHdu9QfBh89udOFoS1frSfsBFevFHWtjI6Mo3O5LlYPSL3JN3mG3krMnaGf5aYwzNpL40UpW5Iy8PCasF@yobvdoKQ534xBbfqyJbAxv1dqqkVos4YGHYIeVkteRCOavdPRjcsPde3sOPtfRVDNoWayhgOlBnoGdLizn9WuduBhB9zB/jRRbBrx/OwNlf1dBguorF2H3d4FioZ5sLRgqb7o3aqk@xtKWjWci2EZKI/LXtCko9H3VhUd/1QJnFAVHsO2Lfqi015sLmGr7I1tAMRQ9SzFrMv2MrAFRmtc7DDIO0M/wYRh0Ovrr914rCa/X/RMRptW/Y@Ct8x2sqANzTK@Yy2S/fAYX28EgLpi1ugyWm7JgehAqlgM9DsUNDLOfdPyED/diR2hLIo2a0M9j5fePrGdhaXRfaM@X9Zut@iSmMXizgS4Y3PrF7a@@wub2@YNr4OEbJbbLirAjtuEXfaRzVaS/W6/hBuX1Q5w2IUGg9EV@2h9@bp1b/t5vbmX6dqaaxY/WDfdyXFnxiEgG@0JgTpAXDxyNWnN0eC3YtNmW2exA3DY@IJh9YIygOY1CK7aqRQQHGAR0c4u@c8gPcxVzFtCA5ExgCmZzLKC5EDdkjb0KNkX5WU4e0sDFpf5ywrFzSSifxSoA/jmB7qli5bWjsaxYayh43EEhvyPRnYMWRSmLDYeGIeiMWkPy@l0P5VaqWdzs2U79U7jPw9YjhTSAO5R/Z9FYelNpEVU0@O72eBxtsLZTv2IuGr9RJxWdzMl4m0b4S63V/MDMztmrDqa7YH/DRAYqgptB/Fz63ZkV9Uv@opc1E2L26p2usstyNvij4uGiBmGkdCsEbVPq50@VD3JUKCoOYBG8zQuCT8V5OF2HXyAEcUCrFh1AJ/70TchsKTAF6SxAgrYcbGpiAX9w5f@PTA6olb@A7aW/R1nGEUazSzXPepHPHW8RBdJcbUdkFZX@8uXJe46JLDk/wogskc0bXbobRmlUaLzoOkoCc4F0nb5cCrw4VTg/@lUoHw4GvhwNPC/HA2cDnfe33v7/urf "Prolog (SWI) – Try It Online") Pass arguments `-t r` to the interpreter to make `r` the top-level goal. Expects the DFAs on standard input, one per line, but with the initial `'Automaton("det", Size, Alphabet'` shortened to just `'a('`. Outputs a single character to standard output: `y` if the DFAs are equivalent, or `n` if they are not. A more legible version, with comments: ``` /* Parse a line from stdin as the term A. For this program, the term is expected to be a Deterministic Finite Automaton in the form a(TransitionTable, [Initial], Accepting). */ get(A) :- read_string(user_input, "\n", [], _, S), term_string(A,S). /* Find the Set in SetOfSets which contains I, and remove it from the larger SetOfSets. Or if no such Set exists, use the one-element Set [I] instead, and leave SetOfSets unchanged. */ find(I, SetOfSets, Set, Rest) :- select(Set, SetOfSets, Rest), member(I, Set), !. find(I, SetOfSets, [I], SetOfSets). /* Look up the next state from a row of a transition table, or two next states from corresponding rows. A zero is the failure state and always stays at zero without lookup. */ next_state(0,_) --> [0]. next_state(State,Row) --> [Next], {nth1(State,Row,Next)}. next_state(State1,State2,Row1,Row2) --> next_state(State1,Row1), next_state(State2,Row2). /* Check if two DFAs are equivalent! Equiv is a set of sets of positive state indices from DFA1, negative state indices from DFA2, and 0 for a common failure state. After the algorithm has examined a pair of states, it makes sure one element in Equiv contains both those states for future iterations. All such states in one set are tentatively presumed to be equivalent. Require is an even-length list. Every pair of elements is a state from DFA1 followed by a state from DFA2, and it must be shown that the pair of states is equivalent: 1. If one state is an accept state and the other is not, the DFAs are NOT equivalent. 2. Otherwise, if both states are in the same member of Equiv, no further processing is needed for the current pair, since those states or related states were already seen. 3. Otherwise, for each letter in the common alphabet, for equivalent DFAs it is necessary that the next states for the two DFAs are equivalent. 3a. Add these pairs of next states to Require for the next iteration. 3b. Merge sets containing the current states into a common set within Equiv for the next iteration. 4. Repeat until an Accept mismatch is found or until Require is empty. If Require is empty, the DFAs are equivalent. */ check(_,_,[]). check(Params,Equiv,[State1,State2|Require]) :- /* format("Equiv: ~p~nRequire: ~p~n", [Equiv, [State1,State2|Require]]), */ Params = [Trans1, Trans2, Accept1, Accept2], (member(State1,Accept1) -> member(State2,Accept2) ; \+member(State2,Accept2)), find(State1, Equiv, Set1, Equiv2), plus(State2, NegState2, 0), (member(NegState2,Set1) -> check(Params, Equiv, Require); find(NegState2, Equiv2, Set2, Equiv3), union(Set1, Set2, SetU), (P =.. [next_state, State1, State2]), foldl(P, Trans1, Trans2, RequireMore, Require), check(Params, [SetU|Equiv3], RequireMore)). /* Top-level goal. Parse two DFAs from standard input, and check for equivalence. */ run :- get(a(Transitions1, [Init1], Accept1)), get(a(Transitions2, [Init2], Accept2)), (check([Transitions1, Transitions2, Accept1, Accept2], [], [Init1, Init2]) -> R=y; R=n), print(R). ``` [Try it online!](https://tio.run/##7VpLb@TIkb73r6DnJHmrZWYymSRnMAYaaw8wgOeBntmTLDTYakoqTKmorWK1pm2v/3pvxhePTEqygb3tYRoQm4/MeHwRGRkRWQ@HeTffvj4@bj9//sPvqx/Hw3Gqxmq33U/VzWG@r47Lh@2@Go/VcjdVy3S4r95cvKqq6pv5kF5tj9XDYb49jPebPCC9nH59mK6X6UO1zNX7RJBm/Gmir9v99rhsr6tv0s0yVW9Oy3w/LvO@SlyIws18uKfRVTWe/XwY98ftsp33P4/vd9Omuvw2TdqOu6tN9eb6enpYtvvb84vq9394dTstZ2/Oqy9fV4dp/PDuuBzSp7PTcTq82@4fTsum@uKv@y8ShTT13ab66XwDWXXgm81P5xevXiUEklwfIMhP00Iypf9@uEmXY/V4t72@q67n/TJu98fq2001pqGH6X7@OFXbheFKM0n63Xi4nQ55MiD74VBtb6r9XB1PiRDRn35NYBw3VZITPOf99HraTffTfsH3y2@vkgzHJakEbiA9jR@nQqzT/vpu3N9OH4DDTRL/LIlm33G7qd5Ox4XgSRSOicP1cobXxTCM2FT30/376SAk0vPvLl6imQQrngW6v8zzL9XpAZrsp1@X5DvjIm40Vof5sZpv0s1iVq0WNut8IMWWx7mYduR51/PhMB0f5n3ywluiwVC@qf42HWbyNPjMuN2dDpPwI6uMu8fx05FepOu48OjH7XI3n5Zql@Q8PQAu4vcO087qzbvz6vXrP1aX9dVF@eEnum7ezo/y@fv0KWn/9/1y5/LHDb0@/5/nM90G/3ka5OjiQQc@/nwsDUqoP/3geSLj/J930/Uv5EqE2J@@eZM0TMpP/33afhx3yXV@94qI/5meCaExWXwh6I/kLun/h5ng/6h4JeturxXvRM4R@9uRRhCdlwd59v6a1mvicD3f3yd7rgxxUb25SWtMl8S4u50PyQL31d1IAWJMoSAFiLF6GLcHiAezb2gp3Y@/JF5HIpWWRCVLgqikFcmK2Tp8Py93icd8nMxxkkg3p4VmpxBzGMnVjkma3Q4rz5Q6EjWiT/gQhEtiAr13n1JYm46ne4tgGd0LoPuWXhCDhO@@mj5O@9fp420SZZeW9EX154/T4ZOpJgocxRy2LBAWE@JJ5N1ufkzc3n9aDSigJlhOx4WEOd7NjxQtk2OT@xMXomQYIgKbwF9yOHUX1bc3rC5bFJKPCKPFykEYSpcDDdjPC8d18jImQ5ZMen//w88rTPDBX1Q/0NTH7TGt6uSgsI3IRLMkxh/H@0kCDQkNgyanm43DzekAEdLekpzuSEufpJmmDwmiG@w8U3V9SqEhBUpSf1OlQdcT@4GREc5p/GHajbQdyZvHKQkz7mir@JSsP@1FgWalADGaxhSqd9NCjizSi6@Pu4e78T0FUYwzLIw7VmayGiQnNcbkEWa0VaQTjcr1bGSeoUxyjsmdP8BYR7Y/FnZJM7mt@qiSx2dbEQW19xfVd1PasDhCyMoi0EuYbckkyrbg0wQjQ/8oxNoS/bd8w0WS72FKaJz2y3ZHvshbenW/PaaMIMG@JWROyScTHR5UrLrp/mH5lHVIrv30Y/bcJ/Hx4lWK/NcURM/ebd5tLq9SXOXHlP6M98cNO@TlKnz/Q8hfyS6a4jClKuNy9gWGf1n98@GfexnED5RuiG//C1pXKdQnWaqKGVdfV5fIeVIIxv9e8xynN/5qk4afyS4tVGVM2lf@WJVfvHxJO85X1V//4@VP50QQW7xQ0/WYdnZ98EnOh93pqHOr76dbva3PS4nyB5oOiVbQKnFB4PwrsiC4FySZJyTQpyZJcNon9zljsfhTuv4X2FdnP1ZfX1xUl3njTF9FHyZ7xQMp1H7Ynf0oCBdIi0jfzYcpy4c5aw0uies/WKqr1bRz2aB/nh/SbpC2kep2HncXklXb6pa8OkXb8ZDiOqenFHvBB4CUEeV6QqpyOO0pvaVEt8yMSQOkxc6SYpds@nycl3Hexontz1i9yzXN9cznXohMmhlvKqZ7TqIng7/9@tNX6bInp0nZ9XL29vzi8@fx7PIyUYqbytXpL6S//tmjb9PfsKmaJv2lbyF9C@k@RH5um/X4l@bGmsfivttUXRKwS9@6dN@n@z7R6Ok@zRnS2CEwn6FnPq4mgjVRd05eObr4mgk5T1L4ji7DE5kaJ2@VqyNRXMB3GkjkiLsLAw8gESMxa2k0iLU0pU3fXSRysRFSUbRwXc2quM7zTRR9WDTMV0Z4TW9IV0fKu56@03v6bq8JBzd4FXQgRsMgyoO/AeNxR8zlsRd4GBUSHWQxPTbyyrvWhBt0AinsXSeiexiVQPTeleR6G0Fm7hUv0huwAGaP4aGx2UqRH@kDIb0GK89xXf4uhghmFyLfBLq0ahzITxbyzYoGC4TH4BQFYuiDF2C7UnaMwkwf4Me1ghuiyg428HASAo7JZmzFOTAfVoJqZEffdvIY1T5s7Chq0xPbzhh5aAZ3pfHQlodA0uhLfYwsLOtJIVbDqRr9ynVbHemVKrTpnHqEKdOsBoAw@BMqvjFk4agQIJi@eRnhK/wLsIIKsF2tZhivc8oUA8hlgQR7FGiQ6lExbluVAxLB4ESVTUkrEh8AUOHrNAsrkBhAHujYt6ofuTnTpXexl1exp2BL4BAfokRmWD16yJEiX83PpBUJEyi6pXvSC@5cTH9pLjkazcV94k9q0H3XM50@5LGDjB0ouhC9GhEBoQLk6RHMsCzwjng5T4J4LPWnYkH@xmfGjheX07kkBAY4UknF5KVKHPjJ@MFjYxBakSxPI7K4HdkDRu3oI@Jrls@4AQMvs10fVLN@kAEKAsQFn6HNb33tROKMj8ddVMGzCll8D1wIR@@achzH3kG4sBtBHhKdFyx7gmrtvRiOlWvFxJ5eSdSKohOzUnQLiiBm/J7ghYVgY9mJXVdaBzNdWNGACtAU@yQEKTTKg53YDOYyM4I9lgkimGsEBrxqnY6HFUl6D0GydQaxPdg1tYGoTsPQZUKmRwcG/UoWfMysYi1@W2BMQ6AVC8KLaUU4e4G3rdXHgRce1IWqbAvThsXG/Khfs80K9xgsBsPIBdRNaWDRu1xTbNtG9tBsM5gGKjIvpwZiuvAPbAqdsmHfaFRs363dmH3I6bTezPaS1/hs9sY0a4Uv5haUwbIp9KaomihjGyOp6eX6ESE@uQZFOgoiFAU9f6dNhTwDG04xvZxLaQN5CUUhGktBnoxJzkTLh1SHcVumS9GEtu5Bnl1dMyNXR5bCkZ5442QHxgPtqC8JpIwd1EbuQjpwEhb4uwMFGoWbECzz0fQnDsIPr@gJI2mvgPFo@8SYTj7zAyJlnTVkRg1e@6wob9mNqGxvMXgQoNyAxVCLHNjQKXwruL4G@h0z8xw76wwoT4X@7IexlFhzmUbJYjN2cDBfwA2ZgF3TP0VEtIAHK4yQCqbzXpkV@OLOeGbwm74ckWOLsmIGsGjrNd80OQhaH@oSV848DALPCX4vGPlgaS5TAoGh1IGxADNIwuGvFXeUnKs1eoY1XZimehdLIlbJc2AjdUiGLRtD3ZPRIa@L/Uqf2FqCGnlxsRJ1V7h5dtmo@hELANrpEukaJde0JVcQdhkoAlksYI/I0WHi1lL2uDYBB2e3MjRPKwKD74yXLVjIq37q8zcUiJmg@aCYZP3BxGKeYciLlUnaUABSyGHCJ4UoaNLeSZzIFciC60fCi/ZTSpsoFR34OdAKp4LZP5tdTqXUhHJv5MhkOzIpZV@BSVJEIbypjFE2FCaIDYpW7B010iVsPggaQsgh7yWWnJbHF0VS1o5iPiqiBssBwbItvtO8qGVY1AXcYfHBtrXC3qgAXPYNKqdy6EQrh4CKPoXoaBgEnYhYiooY/QvcOCEIsbiUj@V7FoVQ8YCGHpF54Ak2QNQFWpABS5lTeM1aHJd4jcgt6hmBtlfqqGNQmNEuaMAjrwWKhCeANXAwh3OZFbI1SiLUos4quyCGAB1mCdVQFwAZ0OWApfkVyplaGXBHQZHBssJCA0Vk@@uhBCIkHswOHRYOAmqneR1Kl7pQgGHIYmfbEEUMZVMiK4xiVCjLnqVAwDw0ERlR6EpRYJNsTkPFR4Uhqm6sM5ecwfImgcdzSe/0os7OFDs1KGSBcgYZlOjCylZoKNjyYOMg80Iihhyo1kmDaMlzegEWXsO6ZgRb87DOoOWkNbuKl7kaPASIRjBm1ZtYRnfP@0avDHXv5ffsKUgqVQ1b5r43GghKUE8bJHjFN/3V1ebS0V96SgErxZ7kU2iCdkg7B@kkOkngGukqtpzMoYTouXbntovU7o0E3ZZLPN9xZEQntZbs1UtXNUhQjlLn9xw50Wl1nIKh4xokYEeu@2n3RKSsJcn03PmkhUW7AzLdjhOyVrqw2Kl9EcnFa7TlGSXuoVfqJSsO0q2N3OukTIPWWS8tT0TFhsshcuK@aHP20nekoDfIrkBLxArxjru8XPzXtlV42y@C1ecaelwuONg0zhobjYRGaXFY/QoTOev6eGtdcL8xSLrufLQ2ci9dY2l/OG1xNBZqG@slo8GAPb6xXh13w6x3m@MjakV2Z@tFtfUL8dFas9xE660DXVvO4LWZy5WxFZu8o/UWFWupCLiHyf2V8LzJgvKAd7tatjzOo7hHHWyjixoi0dlEw4W7y04b1kNjgbW1na@THNdx/6XWUrX2GhzrIE2YXD1I0a3lA/ov3vovHOK5yIyrZifXCrV2UbEquV0dtN/ptUON9B0FQY6ViFhSGGuXWerVbrUzhVq7jGh5cpc52D4UdTMKmjR67ns4yd89x8Ag@TtHw7aTbgY3PaMGTDQ90aDggBlzGthpmI62M3Ta9vScxQbJa5FHckGOugHbJjYxNEpRr/SNhlHsTJzbdRw0z1/R2ZEeByAA1dqq0pDUa/vXfLuIn8SGOGMh1baG6i6H0F6Kb9IB4a8pQpeEw5waQVNniKA275UsUNa0vBP6CK2OQykq@CFrAk@zGwQS8m9CHAZkv9QLTELegogaWGzwEn@JOahKUy1qN4ocjw@lWGCsw0ZRUsQa/gAfVCbspFaXIcLqG@QrnC7n3Jb/gkIA94bfNwIPIOIIG8vgyv6FUMTBNagK7MPOYm3@atNYS6@RZB1cJXH1eqF3Qf4koPZluVX6AkcDBOFeAwGoZA/giaVlJLSWxQIu8HgzFiR1aiiADWPHWEAvodXpeibNONC2q8hai4txcO2fA2sIcWLmNaE3INp8ktLI3VAXx4TMP2qpbrGsV8VqlTtqnV1eVqE0hmfGtEVh@HDq5qwzQR7Qr6Ioh9IcRTsLoE@iaPvvLhxP9cLhpXVlFM1WYofEclzHRY6k0dAOFknrJ0GUyminqcDKnb3q23Bq57QybXXH6Mu9jETBbukt/6@tU4qFbYe1SHz4THeQNKrRifAmaTLCKyInlJIUaZrZiyxe@8rcnRQxZUMbskp8ouu0nwZnxx7W2GYbbDu1Ah35gjNBgzDlRKuVDcCLq7DXBdmuOhXD8fbecJ7oFQ0RsZZvijHxQY4of4KmiYsDAssj5OcC3G5QOIqcz0nLQ5JJtQltu8oQKZs4lmphK0A/iIAgx9SFCp8acC4Z2GB8k3FFutCW5wiSj9aWuXR29q4fJIn0llPWeuEUTi@F1RQ939gyUVeW01Svl9ZOvbj2H0ww80BRNB9bFN87veQ0s7E0c@XfPv/MobVkMsh7BkBFN@uy/gC8tORKF3Zt@qo1YSY4WKYoa6U0pCuNy@tiMIeUm@Y5zzqXEm1maGe5vi5mraWxpJRLklDwsJwwXxrt7mZAmWb73Ael6Gs0gJXxPbKmkoR2WtCgQpDDaoqLKEQbq3Rk47JDXT07buynIsjmkDNpwYFUAzUDKtzWzmoHPfDQA@5afzQRdBr38xsrqPTnMlhAYcg6rPYuUNSeB6cWnKr3cjcI6fyGJY3izkF7GUiPw1pQL6NR90YRHb9UqXlClPYYtm3SF5V2r3O5bdVYYVujxRDlLEXR5fKy5hIYpXHQwyCrDO0EE8Cg1pe/7tljVPntImcyUrTKbxSsZNaTBSlo@vId5yKNHR7j6zMHEFO04l1Ky5AsiBakgvpAvkNCQ@PMNl1T@E82Yu5QBuk2S0HdlpdcPnE5C6RRfSM/74eMmzNJFDG3ggB3XNzahUvf9YWL284KXmsScrHcrbwC7Hib0Mvas7mU5Ho3X@pnl0EPcLgKrbWNLr2PLi9fQ/elP8s31zI9WXOd@g/WTTayW8FYOGTHeEKg3CAO5rkStFqn7beg01pdZy434LDx1dqrpy4DaD5pwUU9lUIHB70Ip2eX/MsgOcyVnje5BjyjaKY0zKyRJjm6bl4KeqTsvfDSPnvni15cw3@NtOJaJiI/FIhF880OdEMWzQ@5G8cFY6xzP44bQ/ZDIz2GDNKmDDoePQ7pxvh1W06m26nUwHp2Blujp96@/OUBpyOBaaDvEe2XRXWfi0j1qE6O71ptj3Mp3OipH3dcJX/iPq3sZkLEyjZudxlenR2Y6TFjlNFcHtjPANFDFaH1IL7tMo5cVeWLvGIuYqbesIqZbv9C5623x15cRIFhT@i0ENVPg54@RDnJkEZRZw00hqfjJWGngny4HQsbYERQBwuaHcDmdvTNLTAvjS9IowkUesdBp8IX5Adf8vNAZx218C96a4294xlKkUFT5LJF7YgnlhdnIklfbdVIi4P@5EsDdywCmLdfBXBnj7tprbXe@lIaIdoWmpaS4FzAp8tvpwK/nQr8fzoVCL8dDfx2NPB/ORq4On/1@fXy@XDa/y8 "Prolog (SWI) – Try It Online") ]
[Question] [ # The objective Given a string of Hangul syllables, sort the characters in North Korean dictionary order. # Introduction to Hangul syllables Hangul(한글) is the Korean writing system invented by Sejong the Great. Hangul syllables are allocated in Unicode point U+AC00 – U+D7A3. A Hangul syllable consists of an initial consonant, a vowel, and an optional final consonant. The initial consonants are: ``` ㄱ ㄲ ㄴ ㄷ ㄸ ㄹ ㅁ ㅂ ㅃ ㅅ ㅆ ㅇ ㅈ ㅉ ㅊ ㅋ ㅌ ㅍ ㅎ ``` The vowels are: ``` ㅏ ㅐ ㅑ ㅒ ㅓ ㅔ ㅕ ㅖ ㅗ ㅘ ㅙ ㅚ ㅛ ㅜ ㅝ ㅞ ㅟ ㅠ ㅡ ㅢ ㅣ ``` The final consonants are: ``` (none) ㄱ ㄲ ㄳ ㄴ ㄵ ㄶ ㄷ ㄹ ㄺ ㄻ ㄼ ㄽ ㄾ ㄿ ㅀ ㅁ ㅂ ㅄ ㅅ ㅆ ㅇ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ ``` For example, `뷁` has initial consonant `ㅂ`, vowel `ㅞ`, and final consonant `ㄺ`. # South Korean dictionary order The consonants and vowels above are sorted in South Korean dictionary order. The syllables are firstly sorted by initial consonants, secondly by vowels, and finally by (optional) final consonants. The Unicode block for Hangul syllables contains every consonant/vowel combinations, and is entirely sorted in South Korean dictionary order. The Unicode block can be seen [here,](https://www.unicode.org/charts/PDF/UAC00.pdf) and the first 256 characters are shown for illustrative purpose: > > 가각갂갃간갅갆갇갈갉갊갋갌갍갎갏감갑값갓갔강갖갗갘같갚갛개객갞갟갠갡갢갣갤갥갦갧갨갩갪갫갬갭갮갯갰갱갲갳갴갵갶갷갸갹갺갻갼갽갾갿걀걁걂걃걄걅걆걇걈걉걊걋걌걍걎걏걐걑걒걓걔걕걖걗걘걙걚걛걜걝걞걟걠걡걢걣걤걥걦걧걨걩걪걫걬걭걮걯거걱걲걳건걵걶걷걸걹걺걻걼걽걾걿검겁겂것겄겅겆겇겈겉겊겋게겍겎겏겐겑겒겓겔겕겖겗겘겙겚겛겜겝겞겟겠겡겢겣겤겥겦겧겨격겪겫견겭겮겯결겱겲겳겴겵겶겷겸겹겺겻겼경겾겿곀곁곂곃계곅곆곇곈곉곊곋곌곍곎곏곐곑곒곓곔곕곖곗곘곙곚곛곜곝곞곟고곡곢곣곤곥곦곧골곩곪곫곬곭곮곯곰곱곲곳곴공곶곷곸곹곺곻과곽곾곿 > > > For example, the following sentence (without spaces and punctuations): ``` 키스의고유조건은입술끼리만나야하고특별한기술은필요치않다 ``` is sorted to: ``` 건고고기끼나다리만별술술스않야요유은은의입조치키특필하한 ``` In C++, if the string is in `std::wstring`, the sorting above is plain `std::sort`. # North Korean dictionary order North Korean dictionary has different consonant/vowel order. The initial consonants are sorted like: ``` ㄱ ㄴ ㄷ ㄹ ㅁ ㅂ ㅅ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ ㄲ ㄸ ㅃ ㅆ ㅉ ㅇ ``` The vowels are sorted like: ``` ㅏ ㅑ ㅓ ㅕ ㅗ ㅛ ㅜ ㅠ ㅡ ㅣ ㅐ ㅒ ㅔ ㅖ ㅚ ㅟ ㅢ ㅘ ㅝ ㅙ ㅞ ``` The final consonants are sorted like: ``` (none) ㄱ ㄳ ㄴ ㄵ ㄶ ㄷ ㄹ ㄺ ㄻ ㄼ ㄽ ㄾ ㄿ ㅀ ㅁ ㅂ ㅄ ㅅ ㅇ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ ㄲ ㅆ ``` Like South, the syllables are firstly sorted by initial consonants, secondly by vowels, and finally by (optional) final consonants. If the sentence above is given, the output must be: ``` 건고고기나다리만별술술스조치키특필하한끼않야요유은은입의 ``` # Rules 1. If the input contains a character not within U+AC00 – U+D7A3, it falls in *don't care* situation. 2. As this is a code-golf, the shortest code in bytes wins. [Answer] # JavaScript (ES6), ~~150 148~~ 137 bytes *Saved 10 bytes thanks to @Grimy* I/O: arrays of characters. ``` a=>a.map(c=>"ANBCODEFPGQSHRIJKLM"[(n=c.charCodeAt()-44032)/588|0]+"AKBLCMDNERTOFGSUPHIQJ"[n/28%21|0]+~(n%28%18==2)+c).sort().map(s=>s[4]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQCPZ1k7J0c/J2d/F1S3APTDYI8jTy9vHVylaI882WS85I7HIGajFsURDU9fExMDYSFPf1MKixiBWW8nR28nH2dfFzzUoxN/NPTg0wMMz0EspOk/fyELVyBCkpE4jTxXIMbSwtTXS1E7W1CvOLwIaBLa32NauONokVvN/cn5ecX5Oql5OfrpGmka0np6e0tumJW@6lryZO@PV5gVv5ix4s3DDq41b3sxteDOv9U3HgteNe14vW/N6ec/rphlvpu55OxWk7G3XztebW95OnfNqxwagGqDit1Nb3sya8mYnUE3X6@4lSrGaeln5mXka6uqamv8B "JavaScript (Node.js) – Try It Online") ### Splitting Hangul syllables Given a Hangul character of code point 0xAC00 + \$n\$, the initial consonant \$I\$, vowel \$V\$ and final consonant \$F\$ are given by: $$I=\left\lfloor\frac{n}{588}\right\rfloor,\ V=\left\lfloor\frac{n}{28}\right\rfloor\bmod 21,\ F=n\bmod 28$$ ### Commented ``` a => a.map(c => // for each character c in the input: "ANBCODEFPGQSHRIJKLM"[ // start with a letter from 'A' to 'S' (n = c.charCodeAt() - 44032) // for the initial consonant / 588 | 0 // ] + // "AKBLCMDNERTOFGSUPHIQJ"[ // append a letter from 'A' to 'U' n / 28 % 21 | 0 // for the vowel ] + // ~( // append "-2" for ㄲ or ㅆ (the only North n % 28 % 18 == 2 // Korean final consonants that are sorted ) + // differently) or "-1" otherwise c // append the original character ) // end of map() .sort() // sort in lexicographical order .map(s => s[4]) // isolate the original characters ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~47~~ ~~45~~ 38 bytes ``` Σ•¡®šúIтÝ„Š’#„λ†x!·“•4B33¡€.ā`ââyÇ68+è ``` [Try it online!](https://tio.run/##JdCxTsJgFAXg3bcwjhoXjHFxcTDxLdTEwclEFx1MfmpRhKqorYIWUpAIAzEHqdIqE9WVxFfoeP7bZ8DfuN3hO8k5d@9ga3t3Z7q0vrq4P508pao1bo5fvpvJx8aPldRT1fgOUlWbM8fkM1XB4ex4mCrfuKW1XG7cTK3e4ld@M2klraPkbHllPulOjxemhNJWVZfbuj7SnaKGK1ZPGhVBV@IwO1GZ4zB2tAsdB1KOpOOLZ8@YGBGxD752OQj4VuFbj0Ofw4gRCJ99l68OBzbDkEPFyOVgxPciwyrf2//5PHFC2ESBOCXOiCJxTpSIMuEQF8QlcUVUiGvihrglPOKOuCeqRI14IB4Ji3BnMqstpbbUq6aR@IE0wX4odSWNghQDnR/p557uOGaveKPM@2NZKdYDO/N809oYgzPPlgdXYmNK5i2/ "05AB1E – Try It Online") ``` Σ # sort characters of the input by: •...• # compressed integer 13096252834522000035292405913882127943177557 4B # converted to base 4: 211211121231211111033010101010231002310010331121111111111111111121111111 33¡ # split on 33: [2112111212312111110, 010101010231002310010, 1121111111111111111121111111] €.ā # enumerate each (pairs each digit with its index) `ââ # reduce by cartesian product (yields a list with 11172 elements) yÇ # codepoint of the current character 68+ # + 68 è # index into the large list (with wraparound) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 80 bytes ``` F”&→∧⁶⍘⎚%γD¦ρJG”F”E⎇↓Nη⊙��⭆Ws@}4”F”E↖hY9 t⟧⊙γIO↶5ε∧¬⁶⦃”Φθ⁼℅μΣ⟦⁴⁴⁰³²×⌕βι⁵⁸⁸⍘⁺κλ²⁸ ``` [Try it online!](https://tio.run/##RYzLSsNAGEZfZehqAhHaXNoUd4JuLdSduJjcJ5kk5uZaSwWJLg0EqRIh6MZFpS4s9Ik6k2eIE10Ih3/xn49juCgxIkS6zo4SAAfIMG3H9YLoMk5S3cJ@SAYC@HNDSRlrhulifySrE93xphay/@1IVtTxRJsi3TAtHsEeCcK@I/l8NEtwmMETTDIrgbEIjuMckRSeJiYOEYGBIIJ5HsBzRRnKkgjOcGClfB6aUBcB5lbVNH6PUGrNM95y4IzkKfRFQPhb0oQLQRAOu27/@bXf1D3fa3qzo4uK3jf07YO@P9DNkt3VPUXDyoKVO/b0yFY1e77@pWIvt@x1zbZVu2jaYtuWy7as2nLVHVyRHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Works by generating all 11172 Hangul syllables in North Korean dictionary order and checking to see which ones are present in the input (so all other characters get deleted; also somewhat slow: takes 18 seconds on TIO). Explanation: ``` F”&→∧⁶⍘⎚%γD¦ρJG” ``` Loop over the compressed string `acdfghjmopqrsbeiknl`. This represents the list of South Korean initial consonants (numbered using the Western lowercase alphabet) in North Korean dictionary order. ``` F”E⎇↓Nη⊙��⭆Ws@}4” ``` Loop over the compressed string `02468cdhik1357bgj9eaf`. This represents the list of South Korean vowels (numbered using ASCII digits and lowercase alphabet) in North Korean dictionary order. ``` F”E↖hY9 t⟧⊙γIO↶5ε∧¬⁶⦃” ``` Loop over the compressed string `013456789abcdefghijlmnopqr2k`. This represents the list of South Korean final consonants (using the same numbering as the vowels) in North Korean dictionary order. ``` Φθ⁼℅μΣ⟦⁴⁴⁰³²×⌕βι⁵⁸⁸⍘⁺κλ²⁸ ``` Concatenate the vowel and final consonant and decode as a base 28 number, then add on 588 times the initial vowel and 0xAC00. Print all characters from the input that have that as their ordinal. ]
[Question] [ This question has a similar set up to [Find an array that fits a set of sums](https://codegolf.stackexchange.com/questions/174252/find-an-array-that-fits-a-set-of-sums) although is quite different in its goals. Consider an array `A` of length `n`. The array contains only positive integers. For example `A = (1,1,2,2)`. Let us define `f(A)` as the set of sums of all the non-empty contiguous subarrays of `A`. In this case `f(A) = {1,2,3,4,5,6}`. The steps to produce `f(A)` are as follows: The subarrays of `A` are `(1), (1), (2), (2), (1,1), (1,2), (2,2), (1,1,2), (1,2,2), (1,1,2,2)`. Their respective sums are `1,1,2,2,2,3,4,4,5,6`. The set you get from this list is therefore `{1,2,3,4,5,6}`. We call an array `A` **unique** if there is no other array `B` of the same length such that `f(A) = f(B)`, except for the array `A` reversed. As an example, `f((1,2,3)) = f((3,2,1)) = {1,2,3,5,6}` but there is no other array of length `3` that produces the same set of sums. We will only consider arrays where the elements are either a given integer `s` or `s+1`. E.g. if `s=1` the arrays would only contain `1` and `2`. **Task** The task, for a given `n` and `s` is to count the number of unique arrays of that length. You can assume that `s` is between `1` and `9`. You should not count the reverse of an array as well as the array itself. **Examples** `s = 1`, the answer is always `n+1`. `s = 2`, the answers counting from `n = 1` up are: ``` 2,3,6,10,20,32,52,86 ``` `s = 8`, the answers counting from `n = 1` up are: ``` 2,3,6,10,20,36,68,130 ``` **Score** For a given `n`, your code should output the answer for all values of `s` from `1` to `9`. Your score is the highest value of `n` for which this completes in one minute. **Testing** I will need to run your code on my ubuntu machine so please include as detailed instructions as possible for how to compile and run your code. **Leaderboard** * **n = 24** by Anders Kaseorg in **Rust** (34 seconds) * **n = 16** by Ourous in **Clean** (36 seconds) * **n = 14** by JRowan in **Common Lisp** (49 seconds) [Answer] # [Rust](https://www.rust-lang.org/), n ≈ 24 Requires nightly Rust for the convenient `reverse_bits` feature. Compile with `rustc -O unique.rs` and run with (e.g.) `./unique 24`. ``` #![feature(reverse_bits)] use std::{collections::HashMap, env, mem, process}; type T = u32; const BITS: u32 = mem::size_of::<T>() as u32 * 8; fn main() { let args = env::args().collect::<Vec<_>>(); assert!(args.len() == 2); let n: u32 = args[1].parse().unwrap(); assert!(n > 0); assert!(n <= BITS); let mut unique = (2..=9).map(|_| HashMap::new()).collect::<Vec<_>>(); let mut sums = vec![0 as T; n as usize]; for a in 0 as T..=!0 >> (BITS - n) { if a <= a.reverse_bits() >> (BITS - n) { for v in &mut sums { *v = 0; } for i in 0..n { let mut bit = 1; for j in i..n { bit <<= a >> j & 1; sums[(j - i) as usize] |= bit; } } for s in 2..=9 { let mut sums_s = vec![0 as T; ((n + (n - 1) * s) / BITS + 1) as usize].into_boxed_slice(); let mut pos = 0; let mut shift = 0; let mut lo = 0; let mut hi = 0; for &v in &sums { lo |= v << shift; if BITS - shift < n { hi |= v >> (BITS - shift); } shift += s; if shift >= BITS { shift -= BITS; sums_s[pos] = lo; pos += 1; lo = hi; hi = 0; } } if lo != 0 || hi != 0 { sums_s[pos] = lo; pos += 1; if hi != 0 { sums_s[pos] = hi; } } unique[s as usize - 2] .entry(sums_s) .and_modify(|u| *u = false) .or_insert(true); } } } let mut counts = vec![n + 1]; counts.extend( unique .iter() .map(|m| m.values().map(|&u| u as T).sum::<T>()) .collect::<Vec<_>>(), ); println!("{:?}", counts); process::exit(0); // Avoid running destructors. } ``` [Answer] **Common Lisp SBCL, N = 14** call function (goahead n s) ``` (defun sub-lists(l m &optional(x 0)(y 0)) (cond; ((and(= y (length l))(= x (length l)))nil) ((= y (length l))m) ((= x (length l))(sub-lists l m 0(1+ y))) (t (sub-lists l (cons(loop for a from x to (+ x y) when (and(nth (+ x y)l)(nth a l)(< (+ x y)(length l))) ; while (nth a l) ;while(and(< (+ x y)(length l))(nth a l)) collect (nth a l))m) (1+ x)y)) )) (defun permutations(size elements) (if (zerop size)'(()) (mapcan (lambda (p) (map 'list (lambda (e) (cons e p)) elements)) (permutations (1- size) elements)))) (defun remove-reverse(l m) (cond ((endp l)m) ((member (reverse (first l))(rest l) :test #'equal)(remove-reverse (rest l)m)) (t (remove-reverse (rest l)(cons (first l)m))))) (defun main(n s) (let((l (remove-reverse (permutations n `(,s ,(1+ s)))nil))) (loop for x in l for j = (remove 'nil (sub-lists x nil)) collect(sort (make-set(loop for y in j collect (apply '+ y))nil)#'<) ) )) (defun remove-dups(l m n) (cond ((endp l)n) ((member (first l) (rest l) :test #'equal)(remove-dups(rest l)(cons (first l) m) n)) ((member (first l) m :test #'equal)(remove-dups(rest l)m n)) (t(remove-dups (rest l) m (cons (first l) n)))) ) (defun goahead(n s) (loop for a from 1 to s collect(length (remove-dups(main n a)nil nil)))) (defun make-set (L m) "Returns a set from a list. Duplicate elements are removed." (cond ((endp L) m) ((member (first L) (rest L)) (make-set (rest L)m)) ( t (make-set (rest L)(cons (first l)m))))) ``` here is the run times ``` CL-USER> (time (goahead 14 9)) Evaluation took: 34.342 seconds of real time 34.295000 seconds of total run time (34.103012 user, 0.191988 system) [ Run times consist of 0.263 seconds GC time, and 34.032 seconds non-GC time. ] 99.86% CPU 103,024,254,028 processor cycles 1,473,099,744 bytes consed (15 1047 4893 6864 7270 7324 7328 7328 7328) CL-USER> (time (goahead 15 9)) Evaluation took: 138.639 seconds of real time 138.511089 seconds of total run time (137.923824 user, 0.587265 system) [ Run times consist of 0.630 seconds GC time, and 137.882 seconds non-GC time. ] 99.91% CPU 415,915,271,830 processor cycles 3,453,394,576 bytes consed (16 1502 8848 13336 14418 14578 14594 14594 14594) ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux) Certainly not the most efficient approach, but I'm interested in seeing how well a naive by-value filter does. That said, there's still a bit of improvement to be made using this method. ``` module main import StdEnv, Data.List, System.CommandLine f l = sort (nub [sum t \\ i <- inits l, t <- tails i]) Start w # ([_:args], w) = getCommandLine w = case map toInt args of [n] = map (flip countUniques n) [1..9] _ = abort "Wrong number of arguments!" countUniques 1 n = inc n countUniques s n = length uniques where lists = [[s + ((i >> p) bitand 1) \\ p <- [0..dec n]] \\ i <- [0..2^n-1]] pairs = sortBy (\(a,_) (b,_) = a < b) (zip (map f lists, lists)) groups = map (snd o unzip) (groupBy (\(a,_) (b,_) = a == b) pairs) uniques = filter (\section = case section of [a, b] = a == reverse b; [_] = True; _ = False) groups ``` Place in a file named `main.icl`, or change the top line to `module <your_file_name_here>`. Compile with `clm -h 1500m -s 50m -fusion -t -IL Dynamics -IL StdEnv -IL Platform main`. You can get the version TIO (and myself) use from the link in the heading, or a more recent one from [here](https://clean.cs.ru.nl/Download_Clean). ]
[Question] [ Your challenge is to write a program to solve a 3x3x3 [Rubik's Cube](https://en.wikipedia.org/wiki/Rubik%27s_Cube). This challenge is based on [this one](https://codegolf.stackexchange.com/q/10768/61563) from 2013, rewritten to adhere to current [community standards](https://codegolf.meta.stackexchange.com/q/8047/61563), and reposted with the original [author's permission](https://chat.stackexchange.com/transcript/message/42189536#42189536) and help on [meta](https://codegolf.meta.stackexchange.com/q/14554/61563). # Input The input should represent an unsolved Rubik's Cube. You may read this input via any [standard means](https://codegolf.meta.stackexchange.com/q/2447/61563), and the input can be in any format you choose, except a sequence of moves to get the cube to an unsolved state (or anything similar); that would trivialize this challenge. That means that the input can look like this: ``` UUU UUU UUU LLLFFFRRRBBB LLLFFFRRRBBB LLLFFFRRRBBB DDD DDD DDD ``` `U` representing cubies on the top/upper face, `L` representing the left, etc. It could also look like a [Cubically](https://git.io/Cubically) [cube-dump](https://tio.run/##Sy5NykxOzMmp/A8EAA), an array of characters/integers, or the weird format in the [original challenge](https://codegolf.stackexchange.com/q/10768/61563); however you like. You must specify how input should be taken in your answer. You can translate a cube-dump to an `ULFRBD` scheme [here](https://tio.run/##JYqxDYAwDAT7TOEuFZLffi@AEBUVEgNARQ3Z3wSlOp3urvO9M9sjU5OqMGdUqce27vNSM0XEA6XD1H@AKNonV6qpsQSU1iNI9uLUAMLC/jswMMzhHw) or the other way around [here](https://tio.run/##Hcs7CoBAEIPh3lNMt5Xg8wJDSDVVYA6glbV6/3XX6oPw5zyeq9b3tvG1kkE5ipVpXtZtL7WaWbqGRmR0nD7QBaRAtC0jSbiid9EqEWLK/9r/E4EOqA8). # Output You will output, via any [allowed means](https://codegolf.meta.stackexchange.com/q/2447/61563), the moves that must be performed on the inputted Rubik's Cube to return it to the solved state. You may use any chosen notation or method to describe rotation; please specify what you use in your answer. I recommend that you use [Singmaster's notation](https://proofwiki.org/wiki/Definition:Singmaster_Notation) as it is the simplest and clearest: ``` R - turn the right face of the cube 90 degrees clockwise L - turn the left face of the cube 90 degrees clockwise U - turn the top face of the cube 90 degrees clockwise D - turn the bottom face of the cube 90 degrees clockwise F - turn the front face of the cube 90 degrees clockwise B - turn the back face of the cube 90 degrees clockwise ``` Append `'` to any move to make it counterclockwise and `2` to any move to make it 180 degrees. If you are unsure of the validity of an I/O method, feel free to comment or ping me in [chat](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte). # Examples Input is in the format of a cube-dump and a `ULFRBD` layout; output is in Singmaster's notation. [Input](https://pastebin.com/raw/ghVyNhHi) -> `D'U'R'L'R'L2R'F2U'D'U'D'LR'B'F'U'D'L2R'` [Input](https://pastebin.com/raw/iKPHvJpA) -> `RF2U2R2ULB2R2U2R'L'DB2U2D2B'R'F'B2DFU2RU2L'` [Input](https://pastebin.com/raw/qxfthfxB) -> `L2FL'R'FB'U2D'F'R'LBF2R2L'F2D2BL2F2RU2D'LF'` [Input](https://pastebin.com/raw/zs3jv9CP) -> `B'U'FURD'B'F'RBF2D'F2R2L2FU'R'U'R2L2F'B2R'F` [Input](https://pastebin.com/raw/fBkKEbR7) -> `R2FUF2D'FR'B'D2L2F'URB2R'U'D'R2L'UD'R2B2UD2` Your program may assume that the given cube is possible to solve; i.e. you do not need to handle the case that the inputted cube is unsolvable. # Restrictions Answers like [this](https://codegolf.stackexchange.com/a/152948/61563), while valid/interesting on other challenges, are not welcome here. You may not use an algorithm that iterates through every possible state of the cube and prints the moves as it goes, or anything similar. To define these restrictions, your program must be able to solve each of the test cases above on [TIO](https://tryitonline.net/). So it must: * Exit in under 60 seconds. * Output less than 128KiB. # Validation To validate that your program indeed solves the Rubik's Cube, you can obviously use a physical cube or an online cube emulator by mixing it how you like, feeding its state into your program, and then performing the output moves on the cube. However, if you choose to format your input as the cube dump (or the `ULFRBD` scheme and [translate it](https://tio.run/##Hcs7CoBAEIPh3lNMt5Xg8wJDSDVVYA6glbV6/3XX6oPw5zyeq9b3tvG1kkE5ipVpXtZtL7WaWbqGRmR0nD7QBaRAtC0jSbiid9EqEWLK/9r/E4EOqA8) to a cube dump), you can validate your program via Cubically's [online interpreter](http://cubically.tryitonline.net/) like so: 1. Go to the online interpreter. 2. Type `rs` into the `Code` section. 3. Paste your unsolved cube-dump into the `Input` section. 4. Run your program with the unsolved cube-dump. Copy the output into the `Footer` section. 5. Click `Run`. If your program is valid, `Solved!` will appear in the `Output` section. # Winning As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins! [Answer] # [Cubically](//git.io/Cubically), 3 bytes ``` rp▦ ``` [Try it online!](https://tio.run/##JcuxDYAwEEPRPlNkBN/5PBCkQkqBkChYhBEYjEUOAtX7Ltz2eWlT70fmtt7nlVlrdUcZQAOaFUEhRDDeQWM4RgeKGehyN9G/EzmA9BMP) You can use [this](https://tio.run/##Sy5NykxOzMmp/P//UduaR9MW/P8PAA) to print a random cube. Explanation: ``` r read cube from stdin p set PRINTMOVES flag to display moves as they are performed on the cube ▦ insert moves to solve the cube at the current point in the program ``` Capitalize the `P` to see prettier output (e.g. `RLD'U2` as opposed to `R1L1D3U2`). [Answer] # Python + [kociemba](https://github.com/muodov/kociemba), 27 bytes A non-trivial language, trivially using the [kociemba](https://github.com/muodov/kociemba) library ``` from kociemba import* solve ``` Call `solve()` with a cube in the ULFRBD scheme. Example, solve('DRLUUBFBRBLURRLRUBLRDDFDLFUFUFFDBRDUBRUFLLFDDBFLUBLRBD') returns u"D2 R' D' F2 B D R2 D2 R' F2 D' F2 U' B2 L2 U2 D R2 U" (PS, this answer isn't any "better" than the Cubically answer) ]
[Question] [ Your challenge is to compute the [Lambert W function](https://en.wikipedia.org/wiki/Lambert_W_function). \$W(x)\$ is defined to be the real value(s) \$y\$ such that $$y = W(x) \text{ if } x = ye^y$$ where \$e = 2.718281828...\$ is [Euler's number](https://en.wikipedia.org/wiki/E_(mathematical_constant)). Sometimes, \$y\$ may not be real. ### Examples ``` W(-1) = non-real W(-0.1) = -0.11183, -3.57715 W(1) = 0.56714 W(2) = 0.85261 ``` Here's a quick graph of what this function looks like. [![enter image description here](https://i.stack.imgur.com/DZzJS.png)](https://i.stack.imgur.com/DZzJS.png) --- ### Rules Your goal is to take an input and output either nothing, 1 solution, or 2 solutions, out to 5 significant figs. You should expect float inputs within the reasonable range of `-100..100`. This is code-golf, so shortest code wins. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~36~~ 34 bytes ``` @(x)(y=lambertw(-1:0,x))(~imag(y)) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0JTo9I2JzE3KbWopFxD19DKQKdCU1OjLjM3MV2jUlPzf5qGoSZXmoaugZ6h5v//IAoA "Octave – Try It Online") I solved this in 10 different ways without the builtin, but I couldn't get the solution for both the `-1` branch and the `0`-branch. I wasn't able to solve this without resorting to the builtin `lambertw` function. Even though it uses a builtin, it's far from straightforward. `lambertw` will only give out one value by default, namely the **W0(x)**, unless otherwise specified. The problem arises when we specifies that we want two values, both **W0(x)** and **W-1(x)**. If this is the case, and **x>=0**, it will return one real and one complex result. We therefore have to specify that we only want the results where the imaginary part of the result is zero. ### Breakdown: ``` @(x) % Anonymous function that takes x as input (y=lambertw(-1:0,x)) % The lambertw function, with both the -1 and 0 branches (~imag(y)) % Index, where the elements with imag(y)=0 is true ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~98~~ ~~86~~ ~~75~~ ~~74~~ 73 bytes -11 bytes thanks to @KevinCruijssen ``` žr(zV"Оrsm*I-d"UY‹iõë∞.ΔX.V}®s‚ΔDÅAX.Vǝ}н,0‹i∞.Δ(X.V}(®‚ΔDÅAX.V≠ǝ}IYÊiн, ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6L4ijaowpcMTgIziXC1P3RSl0MhHDTszD289vPpRxzy9c1Mi9MJqD60rftQw69wUl8OtjkD@8bm1F/bqGIDUQdRogBRpHFqHrOhR5wKgOs/Iw12ZQMX//@sa6BkCAA "05AB1E – Try It Online") Explanation: (I will let f(x)=x\*e^x) ``` žr(zV"Оrsm*I-d"U #Let Y=-1/e,X=str(ÐYsm*I-d) to save characters in the future Y‹iõ #if input<-1/e: print empty string ë∞.ΔX.V} #else: find least int k>=1 such that f(k)>=0 (evaluates string X as though it were a function) ®s‚ #make list [-1,k] ΔDÅAX.Vǝ} #find root of f(x)-input in the interval [-1,k] using bisection method #actually this outputs a list with 2 numbers which will be very close to each other, which represents the interval in which the root lies #e.g. the list [-3.00001,-3] would represent the interval [-3.00001,-3] н, #print the first item of the list; stack is currently empty 0‹i #if input<0: ∞.Δ(X.V}( #find greatest int k<=-1 such that f(k)>=0 ®‚ #make list [k,-1] ΔDÅAX.V≠ǝ} #find root of f(x)-input in the interval [k,-1] using bisection method #again, this outputs a list rather than a single number IYÊiн, #if input!=-1/e, print that root (done so that "-1" is not printed twice) ``` Visualization of the program's indentation: ``` žr(zV"Оrsm*I-d"UY‹iõë∞.ΔX.V}®s‚ΔDÅAX.Vǝ}н,0‹i∞.Δ(X.V}(®‚ΔDÅAX.V≠ǝ}IYÊiн, { { } { } { { } { } { ``` [Answer] # Ruby, 131 bytes ``` ->x{y,z,e,l=1,-1,Math::E,->t{Math::log t};100.times{z=x<0&&x>-1/e ?l[x/z]:p;y=x<-1/e ?"non-real":x>e ?l[x/y]:x*e**-y};p y;z&&(p z)} ``` [Try it online!](https://tio.run/##LYpPC8IgHEC/iuwgNfxtSjdNO3XsEwwPC1wFtsky8A9@divW6T0eb31fY51kBRVyJIkYYiUjwMhl9HfOzwSUz5vb5YZ8EYzSzj@e5pWTDEeKcVDAeoNOdgh90tyJ@O1bauZlhtWMtuFB/ZeoeWhN20IswqEoEsY7h9K@1GkA2h10rT98AA) Basically applies fixed-point iteration 100 times, as partially explained in [Lambert W function aproximation](https://math.stackexchange.com/a/2187158). [Answer] # C, 101 + 2 (`-lm`) bytes Returns how many real solutions, and store them in an array. This one is very slow, since it uses a brute-force approach to find roots. It handles up to x = 9e9. ``` f(a,b,p,t,c,x)float*b,a,x;{for(p=a<0,c=0,x=-50;x<9;x+=2e-6,p=t)(t=x*exp(x)>a)^p?b[c++]=x:0;return c;} ``` [Try it online!](https://tio.run/##RZBta8MgEMdfx09xZGxoY4rZQ8dm7D5I6cDY2Ap5kMQyoXQffdnZF5vInfy8//88TXk0Zlks1bzhngdueGS2G3VYNVzzKC92nKhXuhbcKMGjKl@EjPWbjIV6bMsN9yowGlRctdHTyLaaffqPZmeKYq/iu5BTG87TAEZelzs3mO58aKHudTitT1vyT@ZwcGNCxA0Beu0GysiFZLe3gB7mXSX2HLQkWSoImL9OrmuBfs9GD5bm9zbn8KAZA5RlfsKyRA@AOICCNGMyYgy1GY4FNDk5vBISU42m4IqCwZ/WJm3q7fY3kT@HmeZ5Ol/JdSnF@plgeNqkWJGywg8hgiAhFakEbkFeBa4fYzt9nJey638B "C (gcc) – Try It Online") # C, ~~148~~ 146 + 2 (`-lm`) bytes This function returns how many real solutions, and store them in the given pointers. Use binary search to find a solution. It handles up to about x = 108. ``` #define h(x)99;for(l=-1;x=(l+r)/2,fabs(l-r)>1e-6;)x*exp(x)>a?r=x:(l=x); f(a,b,c,l,r)float*b,*c,a,l,r;{r=h(*b)r=-h(*c)return-1/exp(1)>a?0:a<0?2:1;} ``` [Try it online!](https://tio.run/##ZVDRasMgFH2OXyEpK5pqq9koa9Ok33JjtBFsWoxlgdJ9@jLtw8YYeO@Rc849clX8pNQ8Lzpt7KBxTya621Xm4omruaymmriVp5uSGWhH4rinjdR8W9Gp0NM1uhs4@nraR/tEK2QIsJYp5pinxl0gFC0rFINEVHdf96Roqa95REW9Djc/cLlJSTIliT0cxLHcy@oxL@yg3K3T@HCG0K/7Bv0yY@jsJVHIDgGfwQ6EojvKnk9ikAxDGatCWdJDxI/eOo3J56hgMCR/MTnDS6AUx6ns6qMtsR2OdKjTFsuYsoSSxqWyzBpMAm6woPjHa5IX5B9d/tPLp369hZHkebo/0GPmYv2GYnvdpi4RL@OXIoEigySSIp5niQR69f6ljIPTOHN3/gY "C (gcc) – Try It Online") [Answer] # Casio BASIC, 192 Bytes A port of [My 05AB1E answer](https://codegolf.stackexchange.com/a/203664/94333) ``` ?→X "" If X≥-e^-1 Then 0→R While Re^R<X Isz R WhileEnd -1→L While Re^R>X .5(L+R→M If Me^M<X Then M→L Else M→R IfEnd WhileEnd If X<0 Then M◢ While Le^L<X Dsz L WhileEnd While Le^L≠X .5(L+R→M If Me^M<X Then M→R Else M→L IfEnd WhileEnd If M≠-1 Then M ``` Note that indents are actually not supported; I added them for legibility. [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 144 bytes ``` : N 99 for fover fover fnegate fexp f* fover 2e f** f+ fswap 1e f+ f/ next f. ; : f fdup 0e -1e fexp f- f> if 0e N fdup f0< if -2e N then then ; ``` [Try it online!](https://tio.run/##PYxNEoIwDIX3nOKtcYLQHeB4BO7AaB64qR2syO1rK8VF3s@XSfhc/CwTk4XQYUDbIrY4q/7V6jR6BXVzYJmpiaCM5QS@PqNDo798htXNgxX6ogPB@9uhVkhzPBDwigcTHPY160sCYhLxs9pd@pBucFsKk10OIFVO4Qs "Forth (gforth) – Try It Online") Being stuck with the floating-point stack hurts a lot (with all the `f`-prefixes), but I guess it's pretty good score for a non-built-in after all. Uses 100 iterations of Newton's method [described here](https://web.archive.org/web/20060824060948/http://www.whim.org/nebula/math/lambertw.html): given a previous estimate of \$w=W(x)\$, the next estimate \$w'\$ is calculated using the formula $$ w' = \frac{xe^{-w}+w^2}{w+1} $$ I simplified the starting points for the golf: starting at 0 for primary branch (if \$x \ge -1/e\$) and -2 (inflection point) for secondary branch (if \$-1/e \le x < 0\$) should suffice theoretically. ``` : N ( x w -- x ) 99 for \ ( x w ) run Newton's method 100 times... fover fover fnegate fexp f* \ ( x w x*e^-w ) fover 2e f** f+ \ ( x w x*e^-w+ww ) fswap 1e f+ f/ \ ( x (x*e^-w+ww)/(w+1) ) next f. \ Print the resulting w ; : f ( x -- ) fdup 0e -1e fexp f- \ ( x x -1/e ) f> if \ ( x ) if less than -1/e, no solution 0e N \ ( x ) print primary solution fdup f0< if \ ( x ) if less than 0, two solutions -2e N f. \ ( x ) print secondary solution then then ; ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes ``` x/.NSolve[#==E^x x,x,Reals]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8b9CX88vOD@nLDVa2dbWNa5CoUKnQicoNTGnOFbtv6Y1V0BRZl6JQ1q0roGeYex/AA "Wolfram Language (Mathematica) – Try It Online") Returns `x` for no-solution. This function should give all solutions because `NSolve` algorithm uses inverse functions, and there is a built-in inverse function of `x = y*(e^y)` called `ProductLog`. ### Explanation ``` #==E^x x ``` Equation `<input> = e^x * x` ``` NSolve[ ... ,x,Reals] ``` Find solutions in the domain of real numbers. ``` x/. ``` Replace `x` with the solutions. ### Alternative version, 35 bytes ``` N@ProductLog[{-1,0},#]~Cases~_Real& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d/PIaAoP6U0ucQnPz26WtdQx6BWRzm2zjmxOLW4Lj4oNTFH7b@mNVdAUWZeiUNatK6BnmHsfwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 258 bytes ``` e,f,X,R,L=2.7182818,lambda x:x*e**x,float(input()),0,-1 if X>=-1/e: while f(R)<X:R+=1 while f(R)>X: M=(L+R)/2 if f(M)<X:L=M else:R=M print(M) if X<0: while f(L)<X:L-=1 while f(L)!=X: M=(L+R)/2 if f(M)<X:R=M else:L=M if M!=-1:print(M) ``` [Try it online!](https://tio.run/##VY7NDoIwEITvPEW5FVh@igdJQ3mCcumpV4xtaFKBKEZ8emxRErzN7s58s9N77sfhtK4KNEgQwFmZnUlVVqQC290u1w4tdIlVHC@g7djN2AzTc8ZRBAWkJDAayYalJFc0QK/eWIU0FlEtqUgYOa4a6RyoZZgnIspLp11W49Z7OWvdrOxDUeHldDfD7E6B98i68MmdxLdA6uGHXcg2/B//ULBRfw3fMndrQ/c43bvWNS0y8gE "Python 3 – Try It Online") A port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/203664/94333) [Answer] # [SageMath](http://sagemath.org), 39 bytes ``` lambda z:[lambert_w(l,z)for l in[0,-1]] ``` [Try it on SageCell!](https://sagecell.sagemath.org/?z=eJxLs43hyknMTUpJVKiyigaxUotK4ss1cnSqNNPyixRyFDLzog10dA1jY7m40jR0DfQMNQHM-Q_a&lang=sage&interacts=eJyLjgUAARUAuQ==) ]
[Question] [ I somewhat miss those old demos showing the capabilities of computers when they were called x86 instead of i3, i5 and i7. One of the first I watched in my 386 was the [Unreal demo from Future Crew](https://youtu.be/VjYQeMExIwk) that is now celebrating its 25th anniversary. At [minute 0:43](https://youtu.be/VjYQeMExIwk?t=43) the first part of the demo starts and we see a scrolling text following a sinusoidal path. Let's try to imitate that effect in ASCII art! ### The challenge Given this path: ``` *** *** *** *** ** ** * * * * * * * * ** ** *** *** ****** ``` and an input text, draw the text following that path, like this: ``` Thi Golf! s i de Yay s Co ! P r d o n g a ra s mmi zle ng Puz ``` Note that the spaces count as characters in the path, and that the path repeats itself if the text is longer than the sample. ### The animation part Once you have drawn the text, wait for 100 ms (to create an animation of around 10 fps) and draw the text again but starting from the next position of the path. So, for frame `#n`, calculate `n modulo 40` and start drawing in the following position of the path with the text always aligned to the left of the canvas: ``` *** *** | *** *** | | ** ** | | * * | | * * | | * * | | * * | | ** ** | | *** *** | | ****** | Position 0 Position 39 ``` So for frame 10 we will have: ``` and Co es de zl Go z l u f T P ! h is ng Ya is mmi y! Progra ``` ### Notes * Input will be a single `string` (or `char` array, whatever) with the text to animate, and will always have at least 1 character. * Valid characters to animate are those in the [printable ASCII set](https://en.wikipedia.org/wiki/ASCII#Printable_characters). * The path to follow will be exactly as given. * Text will always be aligned to the left of the canvas, so the effect will be the text waving like a flag, with no text displacement. And by canvas I mean screen or [whatever you will use to show the text](https://codegolf.stackexchange.com/a/129278/70347). ;-) * Frames must be clear of any characters/pixels from previous frames unless the character/pixel is the same in both frames. * The speed of the animation does not matter as long as it runs smoothly or as fast as your device can (we can set a minimum of 5 fps, but this is not a requirement). Just adjust the speed to make it fluid and do not worry if the waiting times are not exactly the same. * The animation will loop endlessly. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program or function capable of animating the text win! [Answer] ## HTML + ES6, ~~241~~ ~~244~~ 237 bytes Breakdown: * HTML: 16 bytes * JS function: 221 bytes ``` let f = s=>setInterval(_=>o.innerHTML=[...s].map((c,i)=>([j,y]=[...Array(40)].map((_,k)=>[j=k%20,y,y+=77732>>j&1?k<20||-1:0],y=0)[(i+p)%40],a[y]=a[y]||[...s].fill` `)[x]=(x+=j!=9,c),x=0,a=[],p++)&&a.map(r=>r.join``).join` `,p=30) f("This is Programming Puzzles and Code Golf! Yay!") ``` ``` <pre id=o></pre> ``` ### How? **Building the path** The following code builds the path: ``` [...Array(40)].map((_, k) => [ j = k % 20, y, y += 77732 >> j & 1 ? k < 20 || -1 : 0 ], y = 0 ) ``` This gives an array of arrays `[j, y, z]` where ***j*** is the position modulo 20, ***y*** is the y-coordinate at this position and ***z*** is not used later (it just happens to be computed here to save some bytes). Because the path is symmetric, we only need to encode the 20 first positions. We do that by using a binary number where each `1` bit means that ***y*** must be updated (+1 for the first half, -1 for the second half). ``` 001 001 01 1 1 1 1 01 001 000 ``` With the first position being mapped to the least significant bit, this gives: ``` 00010010111110100100 as binary = 77732 as decimal ``` Because this binary number is itself also symmetric, we can read it in the same order for the 2nd half. Hence the formula: ``` y += (77732 >> j) & 1 ? (k < 20 ? 1 : -1) : 0 ``` which can also be written as: ``` y += (77732 >> j) & 1 ? k < 20 || -1 : 0 ``` where ***k*** is the position and ***j*** is the position modulo 20. Updating ***x*** is much easier: we just have one special case to detect by comparing the position modulo 20 with 9. **Drawing the text** In the following code, the path building code described above has been replaced by a `path` variable for readability. ``` s => setInterval( // set a periodic timer: _ => // with an anonymous callback o.innerHTML = // which updates the content of 'o' [...s].map((c, i) => ( // for each character c of the string s [j, y] = path[(i + p) % 40], // retrieve j and y from the path a[y] = a[y] || [...s].fill` ` // initialize a[y] if it's undefined )[x] = (x += j! = 9, c), // update a[y][x] / update x x = 0, // initialize x a = [], // initialize a[] p++ // increment the phase ) && // end of map() a.map(r => r.join``).join`\n`, // join everything together p = 30 // initial phase = interval period = 30 ) // end of timer definition ``` ]
[Question] [ Your mission today is to create a vortex given a single parameter. This parameter determines the length of each arm in characters. Each "layer" of each arm contains one more character than the last. Here's how the vortex will look, given the arm length: ``` 0: # 1: # ### # 2: # # # ### # # # 3: ## # # # ### # # # ## 4: # # ## # # # ### # # # ## # # 10: # # # # # #### # ### # ## # # # ### # # # ## # ### # #### # # # # # ``` Standard loopholes apply, trailing whitespace optional, any single non-whitespace character in ASCII can replace "#". This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins. [Answer] # [MATL](https://github.com/lmendo/MATL), 60 bytes ``` 3<G+Eqt&OlG8M+t&(1G:8*X^Q2/kG+G:Gq+&vG2=+Z{(XJ3:"J@X!+]g35*c ``` [Try it online!](https://tio.run/nexus/matl#@29s467tWlii5p/jbuGrXaKmYehuZaEVERdopJ/tru1u5V6orVbmbmSrHVWtEeFlbKXk5RChqB2bbmyqlfz/v5EhAA) Or verify test cases: [0](https://tio.run/nexus/matl#@29s467tWlii5p/jbuGrXaKmYehuZaEVERdopJ/tru1u5V6orVbmbmSrHVWtEeFlbKXk5RChqB2bbmyqlfz/vwEA), [1](https://tio.run/nexus/matl#@29s467tWlii5p/jbuGrXaKmYehuZaEVERdopJ/tru1u5V6orVbmbmSrHVWtEeFlbKXk5RChqB2bbmyqlfz/vyEA), [2](https://tio.run/nexus/matl#@29s467tWlii5p/jbuGrXaKmYehuZaEVERdopJ/tru1u5V6orVbmbmSrHVWtEeFlbKXk5RChqB2bbmyqlfz/vxEA), [3](https://tio.run/nexus/matl#@29s467tWlii5p/jbuGrXaKmYehuZaEVERdopJ/tru1u5V6orVbmbmSrHVWtEeFlbKXk5RChqB2bbmyqlfz/vzEA), [4](https://tio.run/nexus/matl#@29s467tWlii5p/jbuGrXaKmYehuZaEVERdopJ/tru1u5V6orVbmbmSrHVWtEeFlbKXk5RChqB2bbmyqlfz/vzEA), [10](https://tio.run/nexus/matl#@29s467tWlii5p/jbuGrXaKmYehuZaEVERdopJ/tru1u5V6orVbmbmSrHVWtEeFlbKXk5RChqB2bbmyqlfz/v6EBAA). This turned out to be funnier than I expected. Explaining is going to be harder, though... [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 48 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Rȯ1ĖŒṙ‘Ė’ḣµ;NµN0¦€U; Ç+;ẋ2W$+⁸<3¤µFṀR,þ$e€€ị⁾# Y ``` **[Try it online!](https://tio.run/nexus/jelly#AVkApv//UsivMcSWxZLhuZnigJjEluKAmeG4o8K1O07CtU4wwqbigqxVOwrDhys74bqLMlckK@KBuDwzwqTCtUbhuYBSLMO@JGXigqzigqzhu4vigb4jIFn///8xMA)** (Make it all more square by replacing the final `Y` with `G`, adding a space between each column). ### How? Builds a list of `#` coordinates of an arm relative to the centre. Transforms that to the coordinates of the four arms from the top-left corner and adds the centre coordinate. Builds a table of all the coordinates in the space and sets the arms to `#` and the space to and joins up the rows with newlines. ``` Rȯ1ĖŒṙ‘Ė’ḣµ;NµN0¦€U; - Link 1, arm coordinates relative to centre: arm-length a R - range: [1,2,...,a] ȯ1 - or 1 (stops Œṙ erroring with arm-length 0; builds no redundant coordinates in the end) Ė - enumerate: [[1,1],[2,2],...[a,a]] (or [[1,1]] if a=0) Œṙ - run-length decode: [1,2,2,...,a,a,...,a] (or [1] if a=0) ‘ - increment: [2,3,3,...,a+1,a+1,...,a+1] (or [2] if a=0) Ė - enumerate: [[1,2],[2,3],...,[T(a)-a,a+1],[T(a)-a+1,a+1],...,[T(a),a+1]] where T(a)=(a+1)*a/2 (or [[1,2]] if a=0) ’ - decrement: [[0,1],[1,2],...,[T(a)-a-1,a],[T(a)-a,a],...a[T(a)-1),a]] (or [[0,1]] if a=0) ḣ - head to a (first a of those) - these are an arm's relative coordinates from the central `#` at [0,0]) µ - monadic chain separation (call that list r) ; - r concatenated with N - negate r (gets the opposite arm) µ - monadic chain separation (call that list s) € - for €ach coordinate pair in s: 0¦ - apply to index 0 (the right of the two values): N - negate U - upend (reverse each pair of that, gives the other two arms) ; - concatenate that list with s (gives all four arms) Ç+;ẋ2W$+⁸<3¤µFṀR,þ$e€€ị⁾# Y - Main link: arm-length a Ç - call the last link(1) as a monad (get centre-relative coordinates) + - add a (make the coordinates relative to the top-left) $ - last two links as a monad: ẋ2 - repeat a twice: [a,a] W - wrap in a list: [[a,a]] (the centre coordinate) ; - concatenate (add the centre coordinate) ¤ - nilad followed by link(s) as a nilad: ⁸ - link's left argument, a <3 - less than three? + - add (a in 0,1,2 are special cases requiring a grid one-by-one more than all the rest) µ - monadic separation (call that c) F - flatten c into one list Ṁ - get the maximum (the side-length of the space) $ - last two links as a monad: R - range: [1,2,...,side-length] ,þ - pair table: [[[1,1],[1,2],...,[1,side-length]],[[2,1],[2,2],...,[2,side-length]],...,[[side-length,1],[side-length,2],[side-length, side-length]]] e€€ - exists in c? for €ach for €ach (1 if a # coordinate, 0 otherwise) ⁾# - literal ['#',' '] ị - index into Y - join with new line characters - implicit print ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` #NβFβ«¿ι«×#⌊⟦ιβ⟧A⁻βιβ↑»»‖←⟲O²⁴⁶ ``` ## Explanation ``` # Print "#" Nβ Input number to b Fβ« » For i in range(b) ¿ι« » If i is truthy (to skip 0) ×#⌊⟦ιβ⟧ Print "#" * minimum of i and b A⁻βιβ↑ Assign b-i to b ‖ Reflect right ⟲O²⁴⁶ Rotate overlap 90, 180 and 270 degrees ``` [Try it online!](https://tio.run/nexus/charcoal#AUsAtP//I@@8rs6y77ymzrLCq8K/zrnCq8OXI@KMiuKfps65zrLin6fvvKHigbvOss65zrLihpHCu8K74oCW4p@y77yvwrLigbTigbb//zk "Charcoal – TIO Nexus") [Answer] ## Mathematica ~~139~~ 172 Bytes The idea is to create a single arm with a function - `{⌊.5+.5(-7+8#)^.5⌋,#-1}` that spits out the index of each element of the arm assuming the middle element has index (0,0). No one has picked up on that yet, but I suspect this idea would result in a winning answer in a better golfing language. Then I rotate the arm through multiples of 90 degrees, re-index and construct the matrix. `SparseArray` seemed like the obvious choice for constructing the matrix, but could have gone with `BoxMatrix` and `ReplacePart`. ``` Grid[SparseArray[Max@#+#+1&[Join@@Table[RotationMatrix[i Pi/2].#&/@{{0,0}}~Join~Array[{⌊.5+.5(-7+8#)^.5⌋,#-1}&,#],{i,4}]]->X,2#+1,""]]& ``` Ungolfed (Hard coded for arm length=3,`%` means previous output): ``` {{0,0}}~Join~Table[{Floor[1/2 (1+Sqrt[-7+8x])],x-1},{x,1,3}] Table[RotationMatrix[i Pi/2].#&/@%,{i,4}] Flatten[%,1] Max[%]+%+1 Normal@SparseArray[%->X,Automatic,""] Grid[%/. 0->""] ``` Usage %@4 ``` X X X X X X X X X X X X X X X X X ``` As I've learned the output must be pure ASCII without extra spacing or formatting, the code has to get a little longer (172 bytes): ``` StringRiffle[ReplacePart[Array[" "&,{1,1}*2#+1],Max@#+#+1&[Join@@Table[RotationMatrix[i Pi/2].#&/@{{0,0}}~Join~Array[{⌊.5+.5(-7+8 #)^.5⌋,#-1}&,#],{i,4}]]->"#"],"\n",""] # # ## # # # ### # # # ## # # ``` ]
[Question] [ [TetraVex](https://en.wikipedia.org/wiki/TetraVex) is a tile-based edge-matching game that was originally coded by Scott Ferguson for the Microsoft Entertainment Pack 3 back in 1990. The game consists of a grid upon which square tiles are placed. The tiles have numbers or letters on each edge, and the goal is to place all tiles in the grid, with each pair of edges matching, in the fastest time. Since solving TetraVex is [known to be NP-Complete](http://dx.doi.org/10.1016/j.ipl.2006.04.010), we're instead just going to generate a solved board. For our purposes, each TetraVex tile is 5 characters wide by 3 tall, and follows the pattern: ``` \ # / # X # / # \ ``` where each `#` is replaced with an alphanumeric symbol matching `[A-Z0-9]` (capitals, not lowercase). When placed on the board, the tiles have additional spaces between them on the grid, in order to differentiate the tiles horizontally from each other. The grid is composed of `|`, `-`, and `+` symbols, as shown below. Note that there is no border on the outside of the gameplay area, and no trailing spaces to the right of the tiles. ``` \ # / | \ # / # X # | # X # / # \ | / # \ ------+------ \ # / | \ # / # X # | # X # / # \ | / # \ ``` ### Input * Two integers `1 < n,m <= 255` in any [convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963) (tuple, array, function argument, etc.). The numbers can be taken in either order (please specify in your answer which order). * These represent a board of `n` tiles wide by `m` tiles tall. + The smallest board output will thus be `2x2` tiles, or `13` characters wide by `7` characters tall. + The largest is `255x255` tiles, or `2037` characters wide by `1019` characters tall. ### Output * An ASCII representation of a TetraVex board of size `n x m`. * The board must follow the tile construction rules above, and must be a solved board (meaning the paired edges match). Non-paired edges (i.e., the border) can be any legal character. ### Rules * Each individual tile in the output must be unique. + Reflected or rotated tiles count as distinct, since during actual gameplay you're not permitted to rotate or flip the tiles in any manner. + For example, a tile with 1 `A` on top and 3 `B`s on the other edges is considered distinct from a tile with 1 `A` on the right and 3 `B`s on the other edges. * The output must be somewhat non-deterministic, meaning different runs of the code with the same `n` and `m` input should yield different boards. However, in the interests of complexity, not all possible `n x m` boards need have non-zero probability in your output -- only at least two of the possible boards must have non-zero probability of actually being produced. + For example, a `3 x 3` board, with full alphanumeric edges, already has somewhere around `36^24 ~= 2.25e37` possible boards. Since that number grows exponentially as the size increases, ensuring equal probability for all boards may become infeasible for many languages. + This does mean you could have two separate deterministic code paths produce two separate boards and then simply flip a coin to determine which to output -- that's fine. (For example, starting with the first tile all `A` in one path and all `B` in the other, and then generate the rest of the board using the same algorithm from there will guarantee two unique boards and is allowed) + Any of our [usual definitions](http://meta.codegolf.stackexchange.com/a/1325/42963) for randomness will suffice for determining this non-zero probability. + Rotations or reflections of the board *are* considered "different" boards, but note that you're not guaranteed a square grid, only a rectangular one. ;-) + Generating a board and then replacing a certain character with another (e.g., replacing all `A` with `Z`) *is* allowed, provided that each tile in the output is still unique. * Trailing spaces are not allowed but trailing newline(s) are OK. * [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 wins. ### Examples 1) Input: `3 3` ``` \ A / | \ B / | \ C / D X E | E X G | G X I / J \ | / K \ | / L \ ------+-------+------ \ J / | \ K / | \ L / M X N | N X O | O X P / Q \ | / R \ | / S \ ------+-------+------ \ Q / | \ R / | \ S / T X U | U X V | V X W / X \ | / Y \ | / Z \ ``` 2) Input: `5 3` ``` \ 0 / | \ B / | \ C / | \ A / | \ Z / D X E | E X F | F X I | I X A | A X Q / J \ | / 9 \ | / L \ | / L \ | / 6 \ ------+-------+-------+-------+------ \ J / | \ 9 / | \ L / | \ L / | \ 6 / M X N | N X 4 | 4 X P | P X P | P X T / R \ | / R \ | / S \ | / B \ | / K \ ------+-------+-------+-------+------ \ R / | \ R / | \ S / | \ B / | \ K / T X Z | Z X V | V X W | W X J | J X G / X \ | / Y \ | / Z \ | / X \ | / A \ ``` [Answer] # CJam, 116 ``` 26mr:D;q~:B;){[7B),f#10222@#f*2G#)f%_2ew:+23f%\W<26f%]{D+26%'A+}f%~"\/"f*_:$@2/'Xf*[@]'|f*Sf*~_'{f>"-+"f=\@}%2>-3<N* ``` [Try it online](http://cjam.aditsu.net/#code=26mr%3AD%3Bq~%3AB%3B)%7B%5B7B)%2Cf%2310222%40%23f*2G%23)f%25_2ew%3A%2B23f%25%5CW%3C26f%25%5D%7BD%2B26%25'A%2B%7Df%25~%22%5C%2F%22f*_%3A%24%402%2F'Xf*%5B%40%5D'%7Cf*Sf*~_'%7Bf%3E%22-%2B%22f%3D%5C%40%7D%252%3E-3%3CN*&input=100%2012) Uses only letters. **Explanation:** The first observation is that any rectangular piece of a solved board is a solved board. Since the program needs to work up to 255×255, it is enough to solve it for that case and use a piece of that board with the requested dimensions. I am using a fixed 255×255 board that I determined to be correct. I actually did 256×256 tiles first, choosing 2 numbers per tile (top and left), then copied the other numbers from adjacent tiles, discarding some edge numbers from the last row and last column. Each tile is first given an associated number, and then I calculate the remainders of that number modulo two other numbers (I used 23 and 26) to get the 2 numbers chosen for that tile. In order to avoid patterns which lead to duplication, I decided to make the associated numbers pseudo-random and unique. I used my favorite distinct not-very-random number generator, which is based on [primitive roots](https://en.wikipedia.org/wiki/Primitive_root_modulo_n): take a prime number slightly bigger than the desired range (65537) and a small prime number (7), then use the powers of the small number modulo the big number. After a few trials, I found that the combination of 7, 23 and 26 works well, giving 65025 (255²) unique tiles. For the random factor, I am just applying a random cyclic permutation to the value of each number. Then the numbers (0-25) are converted to letters (A-Z). Code explanation to follow. [Answer] # Ruby 196 This is an anonymous function that takes width and length as arguments and writes to stdout. ``` ->m,n{r=rand(9) t="" 128.times{|h|t<<"%02X"%((h+r)*17%256)} (m*n*4-m).times{|k|i=k%m;j=k/m s="\\ #{t[j/4]} / | #{t[i]} X #{t[i+1]} | / #{t[j/4+1]} \\ | ------+-"[j%4*8,8] i==m-1&&s[5,3]=$/ $><<s}} ``` **Explanation** Uniqueness of cells is guaranteed by having the contents of each cell correspond to its x,y coordinates, as below. As a result the pattern is always symmetrical about the NW-SE diagonal: ``` 00,00 01,00 02,00 03,00 04,00 05,00 06,00 07,00 08,00 09,00 10,00 11,00... 00,01 01,01 02,01 03,01 04,01 05,01 06,01 07,01 08,01 09,01 10,00 11,01... 00,00 01,02 02,02 03,02 04,02 05,02 06,02 07,02 08,02 09,02 10,02 11,02... . etc ``` The x values appear on the left and right edges of the tile, and the y values on the top and bottom edges. The astute will have noticed that we cannot simply write a 2-digit number across each tile, because the edges will not match. What is needed is a sequence of (at least) 255 digits where all combinations are unique. From this we can pick a pair of digits (e.g. 1 and 2) for the first tile , then follow naturally on to the next, where the last number of one tile becomes the first of the next (e.g. 2 and 3). I use a sequence containing just the hexadecimal digits 0-9A-F because the hexadecimal number representation is more golfable than some other arbitrary base. Therefore I need a 256 digit sequence where every one of the possible 2-digit combinations appears exactly once. Such a sequence is known as a [De Bruijn sequence](https://en.wikipedia.org/wiki/De_Bruijn_sequence). I have discovered a very golfy way of generating De Bruijn sequences of subsequence length 2 with digits from even base numbers. We simply take all the numbers from `0` to `b*b/2-1`, multiply them by `b+1`,take the last 2 digits, and concatenate the results. Here is an illustration of the sequence used with a bit more explanation as to how it works for base `b=16`. Basically each line contains all combinations with two of the possible differences between digits, which together add up to 1 or 17 (mod 16). It is necessary to think in modular base 16 arithmetic, where for example `-1` = `+F`. ``` 00112233445566778899AABBCCDDEEFF Difference between digits is +1 or +0 102132435465768798A9BACBDCEDFE0F Difference between digits is +2 or +F 2031425364758697A8B9CADBECFD0E1F Difference between digits is +3 or +E 30415263748596A7B8C9DAEBFC0D1E2F . . . . . 405162738495A6B7C8D9EAFB0C1D2E3F . . . . . 5061728394A5B6C7D8E9FA0B1C2D3E4F . . . . . 60718293A4B5C6D7E8F90A1B2C3D4E5F Difference between digits is +7 or +A 708192A3B4C5D6E7F8091A2B3C4D5E6F Difference between digits is +8 or +9 ``` Finally, to comply with the random requirement, the pattern can be shifted diagonally by a random number `0..8` so there are 9 possible boards that can be generated. **ungolfed in test program** ``` f=->m,n{ #width,height r=rand(9) #pick a random number t="" #setup empty string and build a DeBruijn sequence 128.times{|h|t<<"%02X"%((h+r)*17%256)} #with all 2-digit combinations of 0-9A-F (m*n*4-m).times{|k| #loop enough for rows*columns, 4 rows per tile, omitting last row. i=k%m;j=k/m #i and j are the x and y coordinates #lookup the 4 values for the current tile and select the appropriate 8-character segment # from the 32-character string produced, according to the row of the tile we are on. s="\\ #{t[j/4]} / | #{t[i]} X #{t[i+1]} | / #{t[j/4+1]} \\ | ------+-"[j%4*8,8] i==m-1&&s[5,3]=$/ #if i is on the rightmost row, delete the last 3 charaters of s and replace with \n $><<s}} #print the current horizontal segment of the current tile. f[20,20] ``` **Output for 20,20 where r=8** ``` \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ | / 0 \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ ------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------ \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / 8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3 / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 112 [bytes](https://github.com/abrudz/SBCS) ``` ⎕CY'dfns' {⍉¯2↓2↓⍉¯1↓1↓(1,⍨3 7×⍳¨⍵)box⊃⍪/,/⍵↑∘.{(7⍴0 1)\3 3⍴⍺@2 8⊢⍵@4 6,⍨'\//\X'}⍨2,/⎕A[(?5)+16|+\17|⊢∘-\32/⍳8]} ``` [Try it online!](https://tio.run/##LY4xT8JQFIV3fsXd2heK9b0HLZsYFplMxEHjY8CQuhAxcdEAk0lTmrxGYxpZZWpYGJCFsf6T@0fqvY3DPTk3Ofc7d/w0bU1ex9PZQ4VZPrjE@F2y6986k@jx2WnM0a7KncL4k6deJBkeV3poCw3h7xfafVmgPYj72Qumb2i3vufTjvEHJuuTuRui/TkFKYwGTRbtsaegi@mGQr02BExyjO@bG2dJVtF1lp/fuWcd0ZTBomlkuOB0sm4ZrQi9746WVUTvos2osdxp7sry4VWf9PpiMKxcPlh9Y7IVXv0FtVLP4b@gxmKScswrC8lsIYOa3YhAgSbV0CbtgP4D "APL (Dyalog Unicode) – Try It Online") An inline function that takes a single argument, a length-2 vector `n m`. The essential idea is taken from [Level River St's Ruby solution](https://codegolf.stackexchange.com/a/80211/78410), i.e. build a De Bruijn sequence of order 2 on a size-16 alphabet. The rest of the algorithm is just extracting alphabets (with random offset to the alphabet index), arranging into boxes, taking the top left corner of size of the input, and formatting to match the output format. A bit of work is offloaded to the [`dfns.box` library function](http://dfns.dyalog.com/n_box.htm), which inserts horizontal and vertical dividers at given indexes using either box-drawing Unicode chars or ASCII. ### How it works ``` ⍝ Load library to use the function `box` ⎕CY'dfns' f←{ ⍝ Generate the De Bruijn sequence using the observation by Level River St idxs←16|+\17|⊢∘-\32/⍳8 32/⍳8 ⍝ 1..8, each number copied 32 times ⊢∘-\ ⍝ Negate the even indexes (1-based) 17| ⍝ Modulo 17; gives 1 16 1 16 ... 2 15 2 15 ... 8 9 8 9 16|+\ ⍝ Cumul.sum mod 16 ⍝ Generate tile fragments in one dimension axis←2,/⎕A[idxs+?5] idxs+?5 ⍝ Add one of 1..5 (random) to all of idxs ⎕A[ ] ⍝ Index into the vector of uppercase letters 2,/ ⍝ Join adjacent pairs ⍝ Generate the matrix of tiles mat←⍵↑∘.{(7⍴0 1)\3 3⍴⍺@2 8⊢⍵@4 6,⍨'\//\X'}⍨axis ∘.{ }⍨axis ⍝ Self outer product over axis ,⍨'\//\X' ⍝ '\//\X\//\X' 3 3⍴ ⍝ Reshape to 3×3 so the ^ chars form X-frame ⍺@2 8⊢⍵@4 6 ⍝ Place chars of ⍺ vertically, ⍵ horizontally (7⍴0 1)\ ⍝ Insert blanks between columns and outside ⍵↑ ⍝ Take n rows and m columns of the entire matrix ⍝ Output formatting ⍉¯2↓2↓⍉¯1↓1↓(1,⍨3 7×⍳¨⍵)box⊃⍪/,/mat ⊃⍪/,/mat ⍝ Flatten chars to single matrix ( )box ⍝ Apply box drawing with the options of 3 7×⍳¨⍵ ⍝ inserting lines after every 3rd row and 7th col 1,⍨ ⍝ using ASCII ⍉¯2↓2↓⍉¯1↓1↓ ⍝ Fix formatting: drop 1 rows and 2 columns from the outside } ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 6, ~~244~~ 254 bytes [De Bruijn sequence](https://en.wikipedia.org/wiki/De_Bruijn_sequence) is a good idea. Thanks to [Level River St](https://codegolf.stackexchange.com/users/15599/level-river-st) ``` param($w,$h)for(;$z='A'..'Z'|?{"Z$x"-notmatch-join"$x$_"[-2..-1]}){$x+=''+$z[0]}$v=random 9 1..$h|%{$y=$_+$v ,(($r=1..$w)|%{"\ $($x[$y+$_-1]) /"})+,($r|%{$x[$_-1]+' X '+$x[$_]})+,($r|%{"/ $($x[$y+$_]) \"})|%{$_-join' | '} ,'-----'*$w*($_-ne$h)-join'-+-'} ``` [Try it online!](https://tio.run/##TZDRboMwDEXf@Yoo8uakISn0raqiaX8xlSKEVio2FVJlVaGFfDtztofNb773Hsv2xQ2N/2qb83mBE7NsWi61rzsBQwqtPDkvdvCw@IrG4B7nl4nvYeS6d9euvr63@tN99BxGqHihN8bovAxyglFZRAWPIisD3Kyv@6Pr2DbJjYF2fprgbqFScEtSIcDbKA@SdH5gIGAs4K6golmSrXmQKqVQpMiIqkL2xmh8bMs/m6//wYQeCI1U9bMksplhSFLUsXAFw0qQ1Td05m9AK41hCUnyTJ/IM7bJlm8 "PowerShell – Try It Online") 1. I've adapted [my answer](https://codegolf.stackexchange.com/a/173125/80745) from the topic [Generate the shortest De Bruijn](https://codegolf.stackexchange.com/questions/42728/generate-the-shortest-de-bruijn) for the case `{String:'A'..'Z', n:2}`. 2. The script loop by this sequence twice: each tail take two chars by row and by column 3. The shortest De Bruijn sequence contains 676 chars. That's enough for 255 rows and for 255 columns 4. The script add `random 9` to row numbers to comply with the random requirement 5. The last line fixed. Output contains extra trailing newline [No-duplicate test](https://tio.run/##TY7haoMwFIX/5ynu5G5RnGEW@mOUUMbeolIktLFxaCIxVlvNszvtBtuFy718h3M4jemlbZWsqhkL4DDOjbCiDrF/RRUVxoY7vHP6QRmjBzrtx@CAQ5Bo42rhTir5MqUOcMA8yJINY0l69NGIQ8wpjfGevR09XrkV@mxqeCcpY6im5xFvHPMYrw/Qr2DI8BZjvvjj9c9/zop@wZrsZ08InrumKk/CyXbp@7K03my3j50u1nQNTL2SVsKn6bSD5OIgJWURPv3zRTASWIYq0YI28KdQ4udv "PowerShell – Try It Online") generates `####` strings instead ASCII tails and is looking for duplicates. ]
[Question] [ I recently read up on graph theory, especially [hypercubes](http://mathworld.wolfram.com/HypercubeGraph.html) and thought about interesting ways to construct paths on them. Here's what I came up with. As you might know, you can construct an n-dimensional hypercube by taking all n-tuples consisting of `1` and `0` as vertices and connect them, iff they differ in one digit. If you interpret these binary digits as an integer number, you end up with a graph with nicely numerated vertices. For example for `n=3`: [![enter image description here](https://i.stack.imgur.com/5qCae.png)](https://i.stack.imgur.com/5qCae.png) Let's say you want to take a walk on this hypercube and start at the vertex `0`. Now, how do you determine which vertex you want to visit next? The rule I came up with is to take the number `a` of the vertex you are on, flip its `mod(a,n)`s bit (zero-based indexing) and go to the resulting vertex. Formally this rule can be recursively defined as ``` a[m+1] = xor(a[m], 2^mod(a[m],n)). ``` By following this rule, you will always stay on the cube and travel along the edges. The resulting path looks like this [![enter image description here](https://i.stack.imgur.com/4Y8cp.png)](https://i.stack.imgur.com/4Y8cp.png) As you can see, you will walk in a circle! In fact, in all dimensions and for all starting points your path will end up in a loop. For example for `n=14` and `a[0]=0` it looks like this [![enter image description here](https://i.stack.imgur.com/8gInK.png)](https://i.stack.imgur.com/8gInK.png) For the avid ambler, the length of his planned route is quite a crucial information. So, your job is to write a function or a program that takes the hypercube dimension `n` an the starting vertex `a[0]` as inputs and output the number of vertices in the resulting loop. ## Test cases ``` n a[0] Output ----------------- 3 0 6 14 0 50 5 6 8 17 3 346 ``` ## Rules * Standard loopholes are forbidden * Output/Input may be in any suitable format * You may assume `a[0]` to be a valid vertex ## Scoring Shortest code in bytes wins. If you have any additional information on this topic, I'd be glad to hear! [Answer] # Jelly, 9 bytes ``` %⁴2*^µÐḶL ``` Takes two command-line arguments. ``` %⁴2*^µÐḶL A monadic link. Inputs: a_0. b also taken from command line. %⁴2*^ Variadic link. Input: a %⁴ a modulo b. ⁴ is second input, b. 2* Get 2 to that power ^ and bitwise xor with a. µ Start a new, monadic link (input: a_0) ÐḶ All elements of the cycle created when the preceding link is applied repeatedly, starting with a_0. L Length. ``` Try it [here](http://jelly.tryitonline.net/#code=JeKBtDIqXsK1w5DhuLZM&input=&args=MA+MTQ). [Answer] # Haskell, 124 ``` import Data.Bits (y:z:w)%(x:s)|x==y||x==z=[i|(i,r)<-zip[1..]s,r==x]!!0|0<1=w%s g n=(tail>>=(%)).iterate(\a->xor a$2^mod a n) ``` This finds the circle by the two-pointers-going-around-in-different-speeds algorithm, and heavily uses/abuses Haskell's approach to lists (for example, the two pointers are actually lists). `g` is the function that computes the answer. give it `n` and then `a[0]` and it will return the number to you (note that `n` should be defined to be of type `Int` to avoid type ambiguity). [Answer] ## JavaScript (ES6), 69 bytes ``` (n,a)=>{g=m=>m^1<<m%n;for(c=1,b=a;(b=g(g(b)))!=(a=g(a));)c++;return c} ``` Returns 18812 for (23, 10). [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~38~~ ~~37~~ 28 bytes ``` xi`vt0)2y1G\^Z~yywP=fn~]2M1$ ``` This works in [current version(15.0.0)](https://github.com/lmendo/MATL/releases/tag/15.0.0) of the language. [**Try it online**!](http://matl.tryitonline.net/#code=eGlgdnQwKTJ5MUdcXlp-eXl3UD1mbn5dMk0xJA&input=MTQKMA) ### Explanation ``` x % take first input: n. Delete (gets copied into clipboard G) i % take second input: initial value of a ` % do...while loop v % concatenate all stack contents vertically t0) % duplicate. Get last element of that array: current a 2 % push 2 y % duplicate second-top element in stack: current a 1G % push first input (n) \ % a modulo n ^ % 2 raised to that Z~ % xor of that with current a yy % duplicate top two elements in stack: array of old a's and new a w % swap: move array of old a's to top P % reverse that array. So first entry is most recent a (before current) =f % indices of old values that equal current value. There may be 0 or 1 n~ % is it empty? ] % if so, continue with a new iteration 2M % push array of indices. It contains exactly 1 index 1$ % set 1 input for implicit display function, so it only displays the index ``` [Answer] ## Pyth, ~~22~~ 17 bytes ``` Lx^2%bQbl.uyNuyGE ``` Explanation: ``` Lx^2%bQbl.uyNuyGE Implicit: Q=first line n. E=second line a[0]. Lx^2%bQb y = lambda b: do one iteration Then uyGE Apply y until a previous result is found. This makes sure we're in the cycle. .uyN Then apply y again until a previous result is found. Keep all intermediate values but not the repeat. l Get the length; i.e. the length of the cycle. ``` Try it [here](https://pyth.herokuapp.com/?code=Lx%5E2%25bQbl.uyNuyGE&input=5%0A6&debug=0). ]
[Question] [ What general tips do you have for golfing in [D](https://dlang.org)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to D (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] Look, no parens! D's functions and template functions can be called as values, methods (won't help), and properties. I can't believe no one has said this yet. I'll list the ones that save bytes: * `fun()` and `fun!()()` shorten to `fun` (assuming there is no variable `fun`). * `fun(par)` shortens to `par.fun` (assuming `par` has no property/method `fun`, as well as `par` not being an expression like `5+2`). * `fun!(T)()` shortens to `fun!T` * `fun!(T)(par)` shortens to `par.fun!T` (assuming `par` has no property/method `fun`) And with objects: * `new cls()` shortens to `new cls` (More JavaScript anyone?) * `obj.fun()` and `obj.fun!()()` shorten to `obj.fun` * `obj.fun!(T)()` shortens to `obj.fun!T` One final thing, **use old versions**. It allows you to use deprecated features that shorten your code. That said, best advice: D isn't good for code-golf. It is a great language, just not for code-golf. [Answer] D is JavaScript. --- Obviously not. But, when dealing with `float`, `double` and `real`, `nan` is a value which must be handled, and, as specified by IEEE 754, NaN does not compare equal with itself. ``` writeln(double.nan == double.nan); // false ``` Meaning, ``` writeln(value!=value); // only true for nan ``` is way shorter than ``` import std.math; writeln(isNaN(value)); ``` Obviously, always use `math.isNaN` for *real* code. ;) [Answer] D has type inference and an `auto` keyword. If the object is not `int`, then `auto` is probably shorter. [Answer] D is great at method chaining, but: ``` str.toLower.strip().split("").sort(); ``` is the same as ``` sort(split(strip(str.toLower),"")); ``` and usually the non-chained one is shorter, which I just realised, which lets me shorten my answer to [Manage Trash So](https://codegolf.stackexchange.com/a/74344/46231) :D [Answer] D, as a multiparadigm (Object Functional) systems programming language, seems to embrace TIMTOWTDI, or There Is More Than One Way To Do It. Case in point, writing the program's argv: ``` import std.stdio, std.array, std.algorithm; void main(string[] args) { for(int i=0;i<args.length;writeln(args[i++])){}; foreach(a;args)writeln(a); each!writeln(args); } ``` Note the C-style for-loop requires `{}` as the empty block and will not accept a semicolon or nothing as a blank statement, *in this case*. Usually, or `;` are no-ops. [Answer] D has a few types of C#-style lambda expressions, which can be assigned and stand alone: ``` (int a,int b)=>a*b; auto a=(int a,int b)=>a*b; ``` However, unlike C#, the signature's types are still needed because D doesn't have Haskell-level type inferencing. <https://dlang.org/spec/expression.html#Lambda> [Answer] If the question requires a full program, the `module` declaration is surprisingly unnecessary. *\*cough\** Java, anyone? *\*clears throat\** *Actually*, D's `module` system is older than Java's. [Answer] Like C/C++, `main` can be `int` or `void`, but `void main(){}` will always be shorter than `int main(){return my_func_returning_int;}`. [Answer] Calling a function on an object with no other arguments ``` reverse(x); ``` can nearly always be shortened to ``` x.reverse; ``` to shave a byte or more. This is because the `.` makes the LHS an implicit first argument, and templating lets us choose the right function for the args. ]
[Question] [ In this challenge, you will write a program to output how many decimal places are in the input *string* and trim the input if needed. ## Examples ``` -12.32 2 32 0 3231.432 3 -34.0 0 -34 023 0 23 00324.230 2 324.23 10 0 00.3 1 0.3 0 0 -04.8330 3 -4.833 ``` ## Rules * Input will be a string which can be taken through, STDIN, function arguments or the closest equivalent * Output can be through function return, STDOUT, or the closest equivalent. * **There is no limit on the size for the input integer** except for your languages maximum *string* length. * If the input has any unnecessary (leading or trailing) zeros: 1. You should take them out 2. Output the amount of decimal place in the new number 3. Output the new number separated by a separator (e.g. space, newline, comma) * Input will always match this RegEx: `-?\d+(\.\d+)?`, or *if you don't speak RegEx*: + There *could* be a `-` at the beginning implying a negative number. Then there will be at *least* one digit. Then there *could* be... a `.` and some more digits. + To check if an input is valid, [check here](https://regex101.com/r/mU8fF2/1) * **No Regex** --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins [Answer] ## Python 2, ~~165~~ 180 bytes At first I was thinking about writing my first Pyth program, got it to count the digits after the potential comma. But then I got quite annoyed, I don't know how you'd enjoy that language, guess it's just for winning purposes. Anyway here's my solution (edited since it didn't work for large numbers): ``` def t(i): o,a='',i while a[-1]=='0': a=a[:-1] while a[0]=='0': a=a[1:] if a[-1]=='.':a=a[:-1] if'.'in a:o=str(len(a)-a.index('.')-1) else:o='0' if a!=i:o+=" "+a print o ``` In case anybody wants to build on my work in Pyth: `~b@+cz"."" "1Wq@b_1"0"~b<b_1)plrb6` To see where you're at, you might want to insert a p between `@+`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes (non-competitive) Damn, I was so close. Python parses very large floats using scientific notation, so I fixed this bug in the interpreter. However, this was done *after* the challenge and my submission is therefore non-competitive. Code: ``` DÞ'.¡0Üg,\DÞ0Ü'.ÜDrQ_i, ``` Explanation: ``` D # Duplicate top of the stack, or input when empty Þ # Convert to float '.¡ # Split on '.' (decimal point) 0Ü # Remove trailing zeroes g # Get the length , # Output top of the stack (the length) \ # Discard the top item D # Duplicate top of the stack Þ # Convert to float 0Ü # Remove trailing zeroes '.Ü # Remove trailing dots D # Duplicate top of the stack r # Reverse the stack Q_i, # If not equal, print top of the stack ``` Uses the [ISO 8859-1 encoding](http://www.ascii-code.com/). [Answer] # JavaScript (ES6), 156 ~~162~~ **Edit** Fixed bug for '-0' - thx @Fez Vrasta **Edit 2** 6 bytes saved thx @Neil It's a mess, but it's 100% string based - no limit due to numeric types ``` s=>(l=k=p=t=0,[...s].map(c=>++t&&c=='.'?p=t:+c&&(l=t,k=k||t)),m=p>l?p-1:p?l:t,k=k>p&&p?p-2:k-1,r=(s<'0'?'-':'')+s.slice(k,m),(p&&m>p?m-p:0)+(r!=s?' '+r:'')) ``` **Less golfed** ``` f=s=> ( // All values are position base 1, so that 0 means 'missing' // k position of first nonzero digit // l position of last non zero digit // p position of decimal point // t string length l=k=p=t=0, // Analyze input string [...s].map((c,i)=>c=>++t&&c=='.'?p=t:+c&&(l=t,k=k||t)), // m position of last digits in output // if the point is after the last nz digit, must keep the digits up to before the point // else if point found, keep up to l, else it's a integer: keep all m=p>l?p-1:p?l:t, // the start is the first nonzero digit for an integer // but if there is a point must be at least 1 char before the point k=k>p&&p?p-2:k-1, // almost found result : original string from k to m r=(s<'0'?'-':'')+s.slice(k,m), // but eventually prepend a minus (p&&m>p?m-p:0) // number of decimal digits +(r!=s?' '+r:'') // append the result if it's different from input ) ``` **Test** ``` F=s=>(l=k=p=t=0,[...s].map(c=>++t&&c=='.'?p=t:+c&&(l=t,k=k||t)),m=p>l?p-1:p?l:t,k=k>p&&p?p-2:k-1,r=(s<'0'?'-':'')+s.slice(k,m),(p&&m>p?m-p:0)+(r!=s?' '+r:'')) console.log=x=>O.textContent+=x+'\n'; // Test cases ;[['-12.32','2'],['32','0'],['3231.432','3'],['-34.0','0 -34'] ,['023','0 23'],['00324.230','2 324.23'],['10','0'],['00.3','1 0.3'] ,['0','0'],['-0','0'],['-04.8330','3 -4.833']] .forEach(t=>{ var i=t[0],k=t[1],r=F(i); console.log((k==r?'OK ':'KO ')+i+' -> '+r)}) function test(){var i=I.value,r=F(i);R.textContent=r;} test() ``` ``` input { width:90% } input,span { font-family: sans-serif; font-size:14px } ``` ``` Input: <input id=I oninput='test()' value='-000000098765432112345.67898765432100000'> Output: <span id=R></span><br> Test cases<br> <pre id=O></pre> ``` [Answer] ## ES6, ~~102~~ ~~180~~ 177 bytes ``` s=>(t=s.replace(/(-?)0*(\d+(.\d*[1-9])?).*/,"$1$2"),d=t.length,d-=1+t.indexOf('.')||d,t!=s?d+' '+t:d) ``` ``` s=>{t=[...s];for(m=t[0]<'0';t[+m]==0&&t[m+1]>'.';)t[m++]='';r=l=t.length;for(r-=1+t.indexOf('.')||l;t[--l]<1&&r;r--)t[l]='';t[l]<'0'?t[l]='':0;t=t.join``;return t!=s?r+' '+t:r} ``` Edit: Saved 3 bytes thanks to @edc65; saved 1 byte thanks to insertusernamehere. [Answer] # PHP 7, 142 bytes I somehow managed to squeeze everything into a single print statement: ``` <?=strlen((explode('.',$t=trim('-'==($_=$argv[1])[0]?$n=$_=trim($_,'-'):$_,0)))[1]).($t!==$_?($n?' -':' ').('.'==$t[0]?0:'').trim($t,'.'):''); ``` Runs from command line, like: ``` $ php trimandcount.php "-04833.010" ``` **Demo** See all test cases including a very long one (62 characters) in action: [Try before buy](https://3v4l.org/hAZrS)1 1 Hover over the box below "*Output for 7.0.0*" to see all results. [Answer] # C++, 180 bytes ``` int f(char*s,char*&p){int m=*s=='-',n=0;for(p=s+m;*p=='0';++p);for(;*++s-'.'&&*s;);p-=p==s;if(*s){for(;*++s;)++n;for(;*--s=='0';--n)*s=0;*s*=n>0;}if(m&&*p-'0'|n)*--p='-';return n;} ``` This is portable C++, that makes no assumptions of character encoding, and includes no libraries (not even the Standard Library). Input is passed in `s`. The number of decimal places is returned; the string is modified in-place and the new start is returned in `p`. By rights, I should return a `size_t`, but instead I'm going to claim that you should compile this for an OS that limits the size of strings to half the range of `int`. I think that's reasonable; it counts more than 2 billion decimal places on 32-bit architectures. ### Explanation ``` int f(char*s, char*&p){ int m=*s=='-', n=0; for(p=s+m;*p=='0';++p); // trim leading zeros for(;*++s-'.'&&*s;); // advance to decimal point p-=p==s; // back up if all zeros before point if(*s){ for(;*++s;)++n; // count decimal places for(;*--s=='0';--n)*s=0; // back up and null out trailing zeros *s*=n>0; // don't end with a decimal point } if(m&&*p-'0'|n)*--p='-'; // reinstate negative sign return n; } ``` ### Test program ``` #include <cstring> #include <cstdio> int main(int argc, char **argv) { for (int i = 1; i < argc; ++i) { char buf[200]; strcpy(buf, argv[i]); char *s; int n = f(buf, s); printf("%10s ==> %-10s (%d dp)\n", argv[i], s, n); } } ``` ### Test output ``` -12.32 ==> -12.32 (2 dp) 32 ==> 32 (0 dp) 3231.432 ==> 3231.432 (3 dp) -34.0 ==> -34 (0 dp) 023 ==> 23 (0 dp) 00324.230 ==> 324.23 (2 dp) 10 ==> 10 (0 dp) 00.3 ==> 0.3 (1 dp) -04.8330 ==> -4.833 (3 dp) -00.00 ==> 0 (0 dp) -00 ==> 0 (0 dp) 000 ==> 0 (0 dp) 0.00 ==> 0 (0 dp) -0.3 ==> -0.3 (1 dp) 5 ==> 5 (0 dp) -5 ==> -5 (0 dp) ``` ]
[Question] [ ## Objective Given input `r` and `n` find the first `n` natural numbers `x` such that if we rotate the first digit to the last place we obtain `x/r`. You may assume that `2 <= r <= 9` and `1 <= n <= 65535`. You may write a program which takes input from stdin or command-line arguments; or you may write a function which takes `r` and `n` as parameters. Output, however, should be to stdout. Output should be one line per value of `x`, formatted as `x/r=y`, in order of increasing `x`. Your solution must be able to handle all valid cases within one minute on a reasonable desktop computer. ### Test cases Input: `4 5` Output: ``` 102564/4=25641 205128/4=51282 307692/4=76923 410256/4=102564 512820/4=128205 ``` Input: `5 1` Output: `714285/5=142857` This is code-golf, so least bytes win. Winning answer will be accepted 4 weeks from now (2014-09-19). Credits for this question go to my colleague, who allowed me to post this question here :) [Answer] # Haskell, ~~182~~ 179 Second version, probably further golfable, but with "proper" algorithm this time. In particular, it finishes within a few minutes with `r=4` and `n=65535`, but then again my computer is neither reasonable nor a desktop, so chances are this stays within a minute on other machines. ``` n#r=take n$[s(10^k*a+d)++'/':s r++'=':s d++s a|k<-[0..],a<-[1..9],let(d,m)=divMod(a*(10^k-r))(10*r-1),m<1] s=show main=interact$unlines.(\(r:n:_)->n#fromIntegral r).map read.words ``` It is based on the idea that `x=10^k*a + m`, where its first digit `0≤a≤9` is moved to the end to obtain `y=10*m+a`. A little maths reveals that `m` can be obtained as `a*(10^k-r)/(10*r-1)`, so we simply scan `a` over `[1..9]` for every `k` from 0 to infinity, and keep and print the first `n` results for which the above expression for `m` is integral. The `fromIntegral` is required because `read`ing a list with `n` as one of its elements in `main`, in combination with the use of `n` in `take`, would force `r` to `Int` throughout, which results in nasty overflows with the big numbers in question. I could have used `genericTake`, but that requires an `import`. This code also has the benefit of being almost trivial to expand to bases other than 10. Input is read from `stdin`, the two values can be separated by any whitespace. [Answer] # C 468 ``` #include <stdlib.h> #include <stdio.h> #define a(s)fputs(s,stdout); #define b(c)putchar(c); int r;int z(char*s,int m){for(int i=0;i++<=m;)a(s)b(47)b(r+48)b(61)char*t=s; while(*++t==48);a(t)while(m--)a(s)b(*s)b(10)}char x[10][60]; int main(int c,char**v){r=atoi(v[1]);int n=atoi(v[2]),q=10*r-1,d=0,p; while(d++<9){p=r*d;char*y=x[d];do{p*=10;*y++=p/q+48;p%=q;}while(p!=r*d);} d=1;p=q=0;while(n--){r==5&p<6?z(x[7],7*q+p++):(z(x[d],(r==5&d==7)?7*q+6:q), ++d>9?q+=d=1,p=0:0);}} ``` (Some newlines not counted in the byte count have been added above to eliminate scroll bars. Yes, the final newline is counted.) Expects arguments on the command line, and assumes standard output accepts ASCII. Runtime is O(number of bytes output) = O(n\*n). No, I can't use `printf`. That takes too much time and pushes the program over the minute limit on my desktop. As it is, some test cases take about 30 seconds. The algorithm treats the output as strings, not numbers, since they quickly get enormous, and there are strong patterns in the output. Somewhat ungolfed: ``` #include <stdlib.h> #include <stdio.h> /* r is as in the problem description */ int r; void show_line(const char* num, int repeats) { for (int i=0; i <= repeats; ++i) fputs(num, stdout); printf("/%c=", '0'+r); /* Assume the repeated num is a solution. Just move the first digit and skip any resulting leading zeros. */ const char* num_tail = num; ++num_tail; while (*num_tail=='0') ++num_tail; fputs(num_tail, stdout); while (repeats--) fputs(num, stdout); printf("%c\n", *num); } /* sol[0] is unused. Otherwise, sol[d] is the repeating digits in the decimal representation of (r*d)/(10*r-1). */ char sol[10][60]; int main(int argc, char** argv) { r = atoi(argv[1]); int n = atoi(argv[2]); int q = 10*r-1; int d = 0; /* Populate the strings in sol[]. */ while (d++<9) { int p = r*d; char* sol_str = sol[d]; /* Do the long division p/q in decimal, stopping when the remainder is the original dividend. The integer part is always zero. */ do { p *= 10; *sol_str++ = p/q + '0'; p %= q; } while (p != r*d); } /* Output the answers. */ d = 1; int repeats = 0; int r5x7_repeats = 0; while (n--) { if (r==5 && r5x7_repeats<6) { show_line(x[7], 7*repeats + r5x7_repeats); } else { if (r==5 && d==7) show_line(x[d], 7*repeats + 6); else show_line(x[d], repeats); if (++d > 9) { d = 1; ++repeats; r5x7_repeats = 0; } } } } ``` ### Proof that the program solves the problem: (In the proof, take all operators and functions to be the real mathematical functions, not the computer operations that approximate them. `^` denotes exponentiation, not bitwise xor.) For clarity, I'll use a function `ToDec` to describe the ordinary process of writing a number as a sequence of decimal digits. Its range is the set of ordered tuples on `{0...9}`. For example, ``` ToDec(2014) = (2, 0, 1, 4). ``` For a positive integer `n`, define `L(n)` to be the number of digits in the decimal representation of `n`; or, ``` L(n) = 1+floor(log10(n)). ``` For a positive integer `k` and a non-negative integer `n` with `L(n)<k`, define `Rep_k(n)` to be the real number obtained by adding zeros in front of the decimal digits of `n`, if necessary to get `k` digits total, and then infinitely repeating those `k` digits after the decimal point. E.g. ``` Rep_4(2014) = .201420142014... Rep_5(2014) = .020140201402... ``` Multiplying `Rep_k(n) * 10^k` gives the digits of `n` before the decimal point, and the (zero-padded) digits of `n` infinitely repeated after the decimal point. So ``` Rep_k(n) * 10^k = n + Rep_k(n) Rep_k(n) = n / (10^k - 1) ``` Given a positive integer `r`, suppose `x` is a solution to the problem, and ``` ToDec(x) = ( x_1, x_2, ..., x_k ) ``` where `x_1 != 0` and `k = L(x)`. To be a solution, `x` is a multiple of `r`, and ``` ToDec(x/r) : ( x_2, x_3, ..., x_k, x_1 ). ``` Applying the `Rep_k` function gives a nice equation: ``` 10*Rep_k(x) = x_1 + Rep_k(x/r) ``` Using its closed form from above, ``` 10x / (10^k - 1) = x_1 + x / r / (10^k - 1) x = x_1 * r * (10^k-1) / (10r - 1) ``` `x_1` must be in the set `{1 ... 9}`. `r` was specified to be in the set `{2 ... 9}`. Now the only question is, for what values of `k` does the above formula for `x` give a positive integer? We'll consider each possible value of `r` individually. When `r` = 2, 3, 6, 8, or 9, `10r-1` is 19, 29, 59, 79, or 89, respectively. In all cases, the denominator `p = 10r-1` is prime. In the numerator, only `10^k-1` can be a multiple of `p`, which happens when ``` 10^k = 1 (mod p) ``` The set of solutions is closed under addition and under subtraction that does not result in a negative number. So the set comprises all the multiples of some common factor, which is also the least positive solution for `k`. When `r = 4` and `10r-1 = 39`; or when `r = 7` and `10r-1 = 69`, the denominator is 3 times a different prime `p=(10r-1)/3`. `10^k-1` is always a multiple of 3, and again no other factor in the numerator can be a multiple of `p`, so again the problem reduces to ``` 10^k = 1 (mod p) ``` and again the solutions are all the multiples of the least positive solution for `k`. [Not finished...] [Answer] # Python 3 - ~~223~~ 179 bytes Python implementation of TheSpanishInquisition's solution: ``` r,n=map(int,input().split());k=0 while 1: for a in range(1,10): D,M=divmod(a*(10**k-r),10*r-1) if M==0: print("%d/%d=%d"%(a*10**k+D,r,10*D+a));n-=1 if n==0:exit() k+=1 ``` Run: * `python3 <whatever you named it>.py` * Takes input on stdin * Input space separated Output: ``` $python3 <whatever you named it>.py 4 8 102564/4=25641 205128/4=51282 307692/4=76923 410256/4=102564 512820/4=128205 615384/4=153846 717948/4=179487 820512/4=205128 ``` Findings: <https://oeis.org/A092697> is the first value for each r. It seems that only certain values of k produce answers, and that the interval is regular. E.g. for r = 4: ``` Form: k [a, a, ...] 0 [] 1 [] 2 [] 3 [] 4 [] 5 [1, 2, 3, 4, 5, 6, 7, 8, 9] 6 [] 7 [] 8 [] 9 [] 10 [] 11 [1, 2, 3, 4, 5, 6, 7, 8, 9] 12 [] 13 [] 14 [] 15 [] 16 [] 17 [1, 2, 3, 4, 5, 6, 7, 8, 9] 18 [] 19 [] 20 [] 21 [] 22 [] 23 [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` The intervals are: * 2 = 18 * 3 = 28 * 4 = 6 * 5 = 6 (5 seems to be an anomaly, as for most values of r, there are clumps of 9, 5 forms clumps of 9 and 1 (with only a = 7 working), see below) * 6 = 58 * 7 = 22 * 8 = 13 * 9 = 44 This forms <https://oeis.org/A094224>. Using these values, a more efficient version can be built: ``` import math def A094224(n): return [18,28,6,6,58,22,13,44][n-2] r,n=map(int,input().split());k=A094224(r)-1 H={} while 1: for a in range(1,10): D,M=divmod(a*10**k-a*r,10*r-1) if M==0: print("%d/%d=%d"%(a*10**k+D,r,10*D+a));n-=1 if n==0:exit() k+=A094224(r) ``` However, I can't (yet) prove that this continues mathematically. Results for r = 5: ``` 0 [] 1 [] 2 [] 3 [] 4 [] 5 [7] 6 [] 7 [] 8 [] 9 [] 10 [] 11 [7] 12 [] 13 [] 14 [] 15 [] 16 [] 17 [7] 18 [] 19 [] 20 [] 21 [] 22 [] 23 [7] 24 [] 25 [] 26 [] 27 [] 28 [] 29 [7] 30 [] 31 [] 32 [] 33 [] 34 [] 35 [7] 36 [] 37 [] 38 [] 39 [] 40 [] 41 [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` ]
[Question] [   ![](https://i.stack.imgur.com/eoidS.jpg) **[Project Euler](http://projecteuler.net/)** is another fun programming challenge site to compete (well, play) on. Early problems start off gently, but then explode in difficulty beyond the first hundred or so. The first few problems have some commonality between finding primes, multiples, and factors, so there could be some interesting code micro-reuse opportunities to toy with. So, **write a program that solves, using no *a priori* knowledge, any of the first 9 [problems](http://projecteuler.net/problems).** 1. The problem is selected by the user, ASCII '1' through '9', inclusive, via an argument when calling or standard input while running. (You can compute all the answers, but only show one.) 2. The correct answer must be printed on a new line, in base 10, using ASCII. 3. Programs should execute in less than a minute (PE suggestion). 4. By "no *a priori* knowledge", I mean *your code* must derive the answer without external resources‡. A program like this would be considered invalid (otherwise correct though, assuming I didn't make a typo): ``` print[233168,4613732,6857,906609,232792560,25164150,104743,40824,31875000][input()-1] ``` ‡for problem #8 (involves a 1000-digit number), you may read the number from an external file, just specify how it's stored (e.g. binary, text, header, imported module) and/or include it in your answer post (does not count towards the length of the main program). 5. Score is by bytes. 6. Fifteen Unicorn Points™ awarded to the byte-count leader after 2 weeks. [Answer] ## Python, 505 ``` import f A,B,C,D=map(range,[22,1000,101,500]) R=reduce M=int.__mul__ a=x=0 b=1 n=2 p=[] while b<=4e6:a,b=b,a+b;x+=b*(b%2<1) while len(p)<=1e4:p+=[n]*all(n%i for i in p);n+=1 q=y=R(M,p[:8]) while any(y%(i+1)for i in A):y+=q print[ sum(i for i in B if i%3*(i%5)<1), x, max(i for i in p if 600851475143%i<1), max(a*b for a in B for b in B if`a*b`==`a*b`[::-1]), y, sum(C)**2-sum(i**2for i in C), p[-1], max(R(M,map(int,f.s[i:i+5]))for i in B), [a*b*(1000-a-b)for a in D for b in D if(a+b)*1e3==5e5+a*b][0] ][input()-1] ``` Whitespace is added to the last line for readability. The 1000-digit number is imported from a module named `f.py` containing the line: ``` s="7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450" ``` [Answer] ## Javascript **Solution: 1785 chars** execute code with nodeJS note on problem 7 : algorithm is ok, but it take a moment ! If someone has a more efficient solution... ``` z=process.argv[2] y=console.log if(z==1){b=0;for(i=1e3;i--;)if(i%3<1||i%5<1)b+=i;y(b)} if(z==2){d=e=1;f=0;while(e<=4e6)g=d+e,d=e,e=g,f+=e%2<1?e:0;y(f)} if(z==3){e=Math.sqrt(d=600851475143)|0+1;f=2;while(f<e){g=d/f;if(g==(g|0))h=f,d=g;f+=f==2?1:2}y(h)} if(z==4){for(a=b=100,c=0;a+b<1998;){d=a++*b;if(d==(""+d).split("").reverse().join("")&&d>c)c=d;if(a>999)a=b+1,b++}y(c)} if(z==5){for(a=c=1;c;){for(b=20;b>1;)a%b>0?b=0:b--;b==1?c=0:a++}y(a)} if(z==6){for(a=100,b=Math.pow(a*(a+1)/2,2),d=a+1;d--;)b-=d*d;y(b)} if(z==7){for(a=3,c=d=0;c<1e4;){for(b=a;b>2;){b=b>3?b-2:2;if(a%b<1)b=0}if(b>0)c++,d=a;a=a+2}y(d)} if(z==8){a="7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";for(e=0,b=996;b--;){d=eval(a.substr(b,5).split("").join("*"));if(d>e)e=d};y(e)} if(z==9){for(a=b=0;(c=a+b+Math.sqrt(a*a+b*b))!=1e3;)if(++a==500)a=0,b++;y(a,b,c-b-a)} ``` **problem 1: 39 chars** ``` b=0;for(i=1e3;i--;)if(i%3<1||i%5<1)b+=i ``` **problem 2: 49 chars** ``` d=e=1;f=0;while(e<=4e6)g=d+e,d=e,e=g,f+=e%2<1?e:0 ``` **problem 3: 85 chars** ``` e=Math.sqrt(d=600851475143)|0+1;f=2;while(f<e){g=d/f;if(g==(g|0))h=f,d=g;f+=f==2?1:2} ``` **problem 4: 105 chars** ``` for(a=b=100,c=0;a+b<1998;){d=a++*b;if(d==(""+d).split("").reverse().join("")&&d>c)c=d;if(a>999)a=b+1,b++} ``` **problem 5: 55 chars** ``` for(a=c=1;c;){for(b=20;b>1;)a%b>0?b=0:b--;b==1?c=0:a++} ``` **problem 6: 51 chars** ``` for(a=100,b=Math.pow(a*(a+1)/2,2),d=a+1;d--;)b-=d*d ``` **problem 7: 82 chars** ``` for(a=3,c=d=0;c<1e4;){for(b=a;b>2;){b=b>3?b-2:2;if(a%b<1)b=0}if(b>0)c++,d=a;a=a+2} ``` **problem 8: 1078 chars ^\_^** ``` a="7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450" for(e=0,b=996;b--;){d=eval(a.substr(b,5).split("").join("*"));if(d>e)e=d} ``` **problem 9: 58 chars** ``` for(a=b=0;a+b+Math.sqrt(a*a+b*b)!=1e3;)if(++a==500)a=0,b++ ``` [Answer] ### R 684 characters ``` f=function(N){r=rowSums;p=function(x,y)r(!outer(x,y,`%%`));S=sum;x=c(1,1);n=600851475143;a=900:999;b=20;c=1:100;m=2:sqrt(n);M=m[!n%%m];A=a%o%a;d=3;P=2;z=1:1e3;Z=expand.grid(z,z);Y=cbind(Z,sqrt(r(Z^2)));W=gsub("\n","",xpathApply(htmlParse("http://projecteuler.net/problem=8"),"//p",xmlValue)[[2]]);switch(N,S(which(p(1:999,c(3,5))>0)),{while(tail(x,1)<4e6)x=c(x,S(tail(x,2)));S(x[!x%%2])},max(M[p(M,M)<2]),max(A[sapply(strsplit(c(A,""),""),function(x)all(x==rev(x)))],na.rm=T),{while(any(b%%1:20>0))b=b+20;b},S(c)^2-S(c^2),{while(P<=1e4){d=d+2;if(sum(!d%%2:d)<2)P=P+1};d},max(sapply(5:nchar(W),function(i)prod(as.integer(strsplit(substr(W,i-4,i),"")[[1]])))),prod(Y[r(Y)==1000,][1,]))} ``` Indented: ``` f=function(N){ r=rowSums p=function(x,y)r(!outer(x,y,`%%`)) S=sum x=c(1,1) n=600851475143 a=900:999 b=20 c=1:100 m=2:sqrt(n) M=m[!n%%m] A=a%o%a d=3 P=2 z=1:1e3 Z=expand.grid(z,z) Y=cbind(Z,sqrt(r(Z^2))) W=gsub("\n","",xpathApply(htmlParse("http://projecteuler.net/problem=8"),"//p",xmlValue)[[2]]) switch(N,S(which(p(1:999,c(3,5))>0)), {while(tail(x,1)<4e6)x=c(x,S(tail(x,2)));S(x[!x%%2])}, max(M[p(M,M)<2]), max(A[sapply(strsplit(c(A,""),""),function(x)all(x==rev(x)))],na.rm=T), {while(any(b%%1:20>0))b=b+20;b}, S(c)^2-S(c^2), {while(P<=1e4){d=d+2;if(sum(!d%%2:d)<2)P=P+1};d}, max(sapply(5:nchar(W),function(i)prod(as.integer(strsplit(substr(W,i-4,i),"")[[1]])))), prod(Y[r(Y)==1000,][1,])) } ``` Usage: ``` > f(1) [1] 233168 > f(2) [1] 4613732 > f(3) [1] 6857 > f(4) [1] 906609 > f(5) [1] 232792560 > f(6) [1] 25164150 > f(7) [1] 104743 > f(8) [1] 40824 > f(9) [1] 31875000 ``` Separately: **1: 48 chars** `sum(which(rowSums(!outer(1:999,c(3,5),`%%`))>0))` **2: 64 chars** `x=c(1,1);while(tail(x,1)<4e6)x=c(x,sum(tail(x,2)));sum(x[!x%%2])` **3: 73 chars** `n=600851475143;m=2:sqrt(n);M=m[!n%%m];max(M[rowSums(!outer(M,M,`%%`))<2])` **4: 88 chars** `a=900:999;b=a%o%a;max(b[sapply(strsplit(c(b,""),""),function(x)all(x==rev(x)))],na.rm=T)` **5: 34 chars** `a=20;while(any(a%%1:20>0))a=a+20;a` **6: 25 chars** `a=1:100;sum(a)^2-sum(a^2)` **7: 54 chars** `d=3;P=2;while(P<=1e4){d=d+2;if(sum(!d%%2:d)<2)P=P+1};d` **8: 181 chars** First line reads the number from the project euler website, second line actualy perform the computation. ``` W=gsub("\n","",xpathApply(htmlParse("http://projecteuler.net/problem=8"),"//p",xmlValue)[[2]]) max(sapply(5:nchar(W),function(i)prod(as.integer(strsplit(substr(W,i-4,i),"")[[1]])))) ``` **9: 87 chars** `z=1:1e3;Z=expand.grid(z,z);Y=cbind(Z,sqrt(rowSums(Z^2)));prod(Y[rowSums(Y)==1000,][1,])` [Answer] ## J ~~245~~ ~~236~~ 232 ``` load'n' echo".>(<:".1!:1]1){<;._1'!+/I.+./0=5 3|,:~i.1e3!+/}:(],4&*@:{:+_2&{)^:(4e6>{:)^:_]0 2!{:q:600851475143!>./(#~(-:|.)@":"0),/*/~i.1e3!*./>:i.20!(([:*:+/)-[:+/*:)i.101!p:1e4!>./5*/\"."0 n!x:*/{.(#~1e3=+/"1)(+.,|)"0,j./~i.500' ``` n is a file containing the following: ``` n=:'7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450' ``` [Answer] ## TI-BASIC (Work in Progress) *For your TI-83 or TI-84 calculator* Main program, **15 bytes**: ``` Input X:OpenLib(1):X:ExecLib:Disp Ans ``` Library 1 (**4 bytes**) **does** count toward the total number of bytes: ``` L1(Ans ``` Then, we have List #1: ``` work in progress ``` ]
[Question] [ The goal of a Rosetta Stone Challenge is to write solutions in as many languages as possible. Show off your programming multilingualism! # The Challenge Your challenge is to implement a program that will input a list of numbers and output a box plot of the data, *in as many programming languages as possible*. The box plot will display the quartiles and outliers in the data, and it will even have a scale. You are allowed to use any sort of standard library function that your language has, since this is mostly a language showcase. ## What is a "box plot?" A [box plot](http://en.wikipedia.org/wiki/Box_plot) is a way of graphing data. A box plot has a few essential features. The first feature is a box, with either side being located at the first and third quartiles of the data. There is a line down the center of the box plot that gives the median. On either end of the box plot, there are "whiskers" that help show the variance of the data. The whisker extends from the box to the least and greatest points in the data set, excluding the outliers. The outliers are plotted as individual points. First, take the median of the data. Then, take all of the data points that are *strictly less than* the median, and compute the median of this set to become the first quartile (Q1). Take all of the data points that are *strictly greater than* the median, and compute the median of this set to become the third quartile (Q3). Find the value of `R = 1.5*(Q3 - Q1)`. Any numbers less `Q1 - R` this are outliers. Any numbers greater than `Q3 + R` are outliers. Take the set of all data points that are *not* outliers, and the minimum and maximum of this set determines the ends of the two whiskers. ## Input Input will begin with `n=` followed by a number. There will then be `n` numbers, one per line. All of the numbers will be integers from 0 to 63, inclusive. ``` n=8 29 1 22 18 12 16 16 22 ``` ## Output Output will be a rendition of the box plot. One possible way to draw the plot is by rendering it in ASCII. You can render the box plot in many ways other than ASCII, but the main requirement is that drawn large enough so that it is possible to tell the exact locations of the important features. The box plot should have a scale, consisting of around 5-10 numbers equally spaced. Here is one example plot of the above data: ``` +--+----+ | | | X +-+ | +------+ | | | +--+----+ 0 0 1 1 2 2 3 0 5 0 5 0 5 0 ``` # The Objective Winning Criterion As for an objective winning criterion, here it is: Each language is a separate competition as to who can write the shortest entry, but the overall winner would be the person who wins the most of these sub-competitions. This means that a person who answers in many uncommon languages can gain an advantage. Code-golf is mostly a tiebreaker for when there is more than one solution in a language: the person with the shortest program gets credit for that language. ## Rules, Restrictions, and Notes Your program can be written in any language that existed prior to April 11th, 2013. I will also have to rely on the community to validate some responses written in some of the more uncommon/esoteric languages, since I am unlikely to be able to test them. --- # Current Leaderboard This section will be periodically updated to show the number of languages and who is leading in each. * Julia (604) - plannapus * Mathematica (71) - chyanog * Python2.X (85) - Abhijit * R (34) - plannapus --- # Current User Rankings 1. plannapus - 2 2. Abhijit - 1 3. chyanog - 1 [Answer] ## R: 34 characters Of course, R being a language used for statistics, it comes with a function `boxplot` to do this (which needs a wrapper here to accomodate the input style): ``` f=function(x)boxplot(scan(x,sk=1)) ``` Usage: Given a file `input1.txt` containing the following: ``` n=10 29 1 22 19 9 13 15 22 63 2 ``` Then `f("input1.txt")` produces: ![enter image description here](https://i.stack.imgur.com/6XRAI.png) ## Julia: 604 characters This is my first ever function in Julia, so my apologies to fans of Julia if this is badly written. ``` function g(f) a=int(split(readall(open(f)),'\n')[2:]) b,c,d=int(quantile(a,[.25,.5,.75])) w=1.5*(d-b) o=a[a.<b-w] O=a[a.>d+w] t=int(b-w>0?b-w:0) u=int(d+w<63?d+w:63) S=s="" if !isempty(o) for i in 1:length(o) s=s*lpad('x',[0,o][i+1]-[0,o][i]-1,' ') end end if !isempty(O) for i in 1:length(O) S=S*lpad('x',[0,O][i+1]-[0,O][i]-u-1,' ') end end x="0" for i in 9:9:63 x=x*lpad(string(i),i-(i-9)," ") end v=isempty(o)?b-1:b-o[length(o)]-1 print(x*"\n"*lpad('+'*'-'^(d-b-1)*'+',d,' ')*'\n'*s*lpad('-'^(b-t-1),v,' ')*'|'*lpad('|',c-b,' ')*' '^(d-c-1)*'|'*'-'^(u-d)*S*'\n'*lpad('+'*'-'^(d-b-1)*'+',d,' ')) end ``` Usage: ``` g("input1.txt") 0 9 18 27 36 45 54 63 +-----------+ ---------| | |------------------ x +-----------+ ``` [Answer] **Python2.X 85 Characters, using matplotlib** ``` import matplotlib.pylab as p p.boxplot(map(input,['']*int(raw_input()[2:]))) p.show() ``` ![enter image description here](https://i.stack.imgur.com/uDnDC.png) [Answer] **Mathematica 71** ``` BoxWhiskerChart[Input/@x~Array~FromDigits@StringTake[InputString[],-1]] ``` ![enter image description here](https://i.stack.imgur.com/c5NBb.png) ]
[Question] [ **This question already has answers here**: [Is it a vampire number?](/questions/218772/is-it-a-vampire-number) (13 answers) Closed 3 years ago. *EDIT:* In the interest of increasing the complexity, i've added more to the challenge. > > In mathematics, a vampire number (or > true vampire number) is a composite > natural number v, with an even number > of digits n, that can be factored into > two integers x and y each with n/2 > digits and not both with trailing > zeroes, where v contains precisely all > the digits from x and from y, in any > order, counting multiplicity. x and y > are called the fangs. > > > More about [Vampire Number](http://en.wikipedia.org/wiki/Vampire_number) Pseudovampire numbers > > Pseudovampire numbers are similar to > vampire numbers, except that the fangs > of an n-digit pseudovampire number > need not be of length n/2 digits. > Pseudovampire numbers can have an odd > number of digits, for example 126 = > 6×21. > > > ### Input Accept Numbers from command line or stdin ### Output * "1260 = 21 \* 60" *(smaller fang first if the number is a Vampire.)* * "1261 is not a Vampire Number." *(if the number is not a Vampire number)* * "126 = 6 \* 21". *(if the number is a Pseudovampire number)* EDIT: If the number has multiple fangs, display it so. ``` x = fang1a * fang1b = fang2a * fang2b ``` [Answer] # Python - 188 chars Doesn't do Pseudovampire numbers ``` from itertools import* n=input() a=[] for i in map("".join,permutations(`n`)):x,y=int(i[::2]),int(i[::-2]);a+=[(x,y)]*(x*y==n) print n,a and"=%s*%s"%min(a)or"is not a Vampire Number" ``` [Answer] # Ruby, 190 chars ``` o=[] [*x.chars].permutation{|r|a=r.pop(x.size/2).join.to_i r=r.join.to_i o|=[[a,r]]if a<=r&&a*r==x.to_i} puts x+(o.any? ? o.map{|i|" = "+i*" * "}*"":" is not a Vampire Number.") ``` ]
[Question] [ The task here is simple: given a target location on an XY grid, and a rectangle on that grid, find the length of the shortest path from the origin to the target which does not intersect the rectangle. All parameter values are integers. You can assume that neither the target point nor the origin is inside or on the border of the rectangle. The rectangle can be specified in any reasonable format -- e.g. `(<left x coordinate>, <top y coordinate>, <width>, <height>)` or `(<left x coordinate>, <right x coordinate>, <top y coordinate>, <bottom y coordinate>)`. For the purposes of these examples I will use the format `(<left x coordinate>, <top y coordinate>, <width>, <height>)`. Your answer must be within one percent of the true answer for any input (ignoring errors due to floating point). Here is the example where the target coordinate is `(5, 5)` (shown in green) and the rectangle has top left corner of `(2, 4)` and width & height of `(2, 3)` (shown in maroon). The shortest path is shown in orange. [![shortest path between the origin and (5,5) with blocking rectangle with top left corner of (2, 4) and width & height of (2, 3)](https://i.stack.imgur.com/ObbGZ.png)](https://i.stack.imgur.com/ObbGZ.png) In this case, the shortest path has length \$\sqrt{2^2+4^2} + \sqrt{1^2+3^2}\ \approx 7.63\$. Note that the rectangle does *not* need to be obstructing the path between the origin and the target location -- take the same rectangle as the previous example, but with the target point of (-3, 5): [![shortest path between the origin and (-3,5) with blocking rectangle with top left corner of (2, 4) and width & height of (2, 3)](https://i.stack.imgur.com/3y1Av.png)](https://i.stack.imgur.com/3y1Av.png) In this case, the answer is \$\sqrt{3^2 + 5^2} \approx 5.83\$. ## Test cases | target x | target y | rectangle x | rectangle y | width | height | answer | | --- | --- | --- | --- | --- | --- | --- | | 5 | 5 | 2 | 4 | 2 | 3 | 7.6344136152 | | 5 | 5 | 4 | 2 | 3 | 2 | 7.0710678119 | | -3 | 5 | 2 | 4 | 2 | 3 | 5.83095189485 | | 0 | 0 | 100 | -50 | 50 | 30 | 0 | | 0 | 100 | -1 | -2 | 3 | 4 | 100 | | 8 | 0 | 1 | 2 | 3 | 4 | 9.7082039325 | | 8 | 0 | 1 | 3 | 3 | 5 | 9.7082039325 | Standard loopholes are forbidden. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 54 bytes ``` ΠÞx¾pƛ00"p⁰J;'2lƛ¹ΠǔI¨VYƛǔ-:ǔk+v*R¨£Þ•±≈;a;a¬;ƛ¯v∆/∑;g ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuItBVCIsIiIsIs6gw554wr5wxpswMFwicOKBsEo7JzJsxpvCuc6gx5RJwqhWWcabx5QtOseUayt2KlLCqMKjw57igKLCseKJiDthO2HCrDvGm8KvduKIhi/iiJE7ZyIsIiIsIltbMiwgNF0sIFsxLCA0XV0sIFtbNSwgNV1dXG5bWzQsIDddLCBbMiwgN11dLCBbWzUsIDVdXVxuW1syLCA0XSwgWzEsIDRdXSwgW1stMywgNV1dXG5bWzEwMCwgMTUwXSwgWy04MCwgLTUwXV0sIFtbMCwgMF1dXG5bWy0xLCAyXSwgWy02LCAtMl1dLCBbWzAsIDEwMF1dXG5bWzEsIDRdLCBbLTIsIDJdXSwgW1s4LCAwXV1cbltbMSwgNF0sIFstMiwgM11dLCBbWzgsIDBdXSJd) Takes input in the form of `[[left_x, right_x], [bottom_y, top_y]], [[target_x, target_y]]`. ## How? The first step is to generate all polygonal chains that begin with \$(0,0)\$ and end with the target and the rest of the vertices are some (or none) of the vertices of the rectangle. ``` ΠÞx¾pƛ00"p⁰J; Π # cartesian product of [left_x, right_x] and [bottom_y, top_y] Þx # all combinations without replacement ¾p # prepend an empty list ƛ ; # map: 00"p # prepend [0, 0] ⁰J # append the target ``` The second step is to filter out the chains that intersect the interior of the rectangle. This is done by checking if any of the segments intersects a diagonal of the rectangle at an interior point. The key observation is that if segments \$AB\$ and \$CD\$ are not on the same line, they intersect at an interior point iff \$ACBD\$ is a non-degenerate convex quadrilateral. This is checked by looking at the vectors \$C-A\$, \$B-C\$, \$D-B\$ and \$A-D\$ and for each adjacent pair rotating the second one by 90° and computing the dot product. If all the dot products have the same sign than the quadrilateral must be non-degenerate and convex. ``` '2lƛ¹ΠǔI¨VYƛǔ-:ǔk+v*R¨£Þ•±≈;a;a¬; ' ; # filter by: 2l # all overlapping pairs ƛ ; # map: ¹Π # cartesian product of the second to last input ǔ # rotate right I # split into two halves, this gives us the two diagonals ¨VY # interleave vectorized over the right operand ƛ ; # map: ǔ- # rotate right and subtract from itself : # duplicate ǔ # rotate right k+v* # multiply each by [1, -1] R # reverse each ¨£Þ• # zip and reduce each pair by dot product ± # sign ≈ # are all equal? a # any a # any ¬ # not ``` The last step is to calculate the lengths of all the remaining chains and get the minimum. ``` ƛ¯v∆/∑;g ƛ ; # map: ¯ # subtract adjacent pairs v∆/ # get the length of each vector ∑ # sum g # minimum ``` [Answer] # [Haskell](https://www.haskell.org/), 414 bytes ``` import Data.List t[[[a,b],[c,d]],[[e,f],[g,h]]]=((a-e)*(f-h)-(b-f)*(e-g))/((a-c)*(f-h)-(b-d)*(e-g)) w x=t x>0&&t x<1 v s t=not(w[s,t]&&w[t,s]) s[[x,y],[l,t],[w,h]]=minimum[sum$map(\[[a,b],[c,d]]->((c-a)^2+(d-b)^2)**0.5)q| c<-subsequences[[l,t],[l+w,t],[l+w,t-h],[l,t-h]],length c<3, p<-permutations c,let r=[0,0]:p++[[x,y]],let q=zipWith(\a b->[a,b])r(tail r), all(v[[l,t],[l+w,t-h]])q,all(v[[l+w,t],[l,t-h]])q] ``` [Try it online!](https://tio.run/##VY6xbsIwEIb3PIUHFNnkTAO0UlURpo7dOxhXcoIhVu2QxBdCq7576oCilsWfdb/u/q9U/lNbOwzG1acWyatCtXgzHiMUQijIJYgC9jJAaDgEHKGUUmaUKq7ZnB54yTjN@SH8NT8y9jAmxb9kPyVRTy4Zkss2jeOAzTI6E08wq05Ie@EBZRz3AsFLFnkhLvAV6mwYg@jH0syZyrjOCd@5mVM13d0Z8i2lBVfsY5XQPc8D2XyeLp5Y8xORYsN9l3vddLoqdLh@u2uT/o@8vPUFSrC6OmIZ9tYQkXrDa926DhWaU@VJEWIkbSZSSOVLnSQ3W3kdN9m3qd8NlnSnSM63V0fWUlTGkpaFc8paer5TGCtZA1MwWU2BHJwyVVa3psJZkH8OtSCWsArvGh6lHH4B "Haskell – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 213 bytes ``` (p=Join[{c={0.,0.}},#1,{#2}];Min[ArcLength/@If[RegionDisjoint[Polygon@#1,l=Line@{c,#2}],{l},m=MeshCoordinates@ConvexHullMesh@p;s=m[[FindShortestTour[m][[2]]]];g=Position[s,#2][[1, 1]];Line/@{s[[;;g]],s[[g;;]]}]])& ``` [Try it online!](https://tio.run/##nY9BS8MwGIbv/orCQBRi1natlxCITERlg6HeQg6lS9tIm4wmEyXkt9cvkzn0uJwe8uZ5vy9D5To5VE7V1dTQ6WpHn43S3NfUpxilOAQ0y5Cf5UGQNQR3Y72SunXdnD01/EW2yuh7Zd9Bcnxj@q/WaAZGT1dKS@ZrFFXk@4AGupa2WxozbpWunLRsafSH/Hzc931M2I5YOnD@oPT2tTMjvHBvZj/yQXCeCzikpRtjlYOZ3EIx3GcoySCIw@bMW84JaYVAAC0hQgQhri@nzQjbsYZ7f5NjEHBAiS/@UHGgQ1zETyc@A8RlEBdn2SXgAp9rR7z9Z8d9cnxMT/bi96489ZQ/PemxZ/oG "Wolfram Language (Mathematica)- Try It Online") Input must be *float*: array of all vertices and goal point. There are three main cases (orange is convex hull of all points): [![enter image description here](https://i.stack.imgur.com/3Dp7M.jpg)](https://i.stack.imgur.com/3Dp7M.jpg) [![enter image description here](https://i.stack.imgur.com/eCTMK.jpg)](https://i.stack.imgur.com/eCTMK.jpg) [![enter image description here](https://i.stack.imgur.com/Tg6e3.jpg)](https://i.stack.imgur.com/Tg6e3.jpg) All of them catch by the next (ungolfed, self-explained) algorithm: ``` shortestPath[vertices_, goal_] := Module[{polygon = Polygon@vertices, allPoints = Join[{{0., 0.}}, vertices, {goal}], directPath = Line[{{0., 0.}, goal}]}, paths = If[RegionDisjoint[polygon, directPath], {directPath}, convPoints = MeshCoordinates@ConvexHullMesh@allPoints; orderPoints = FindShortestTour[convPoints][[2]]; goalPosition = Position[orderPoints, 6][[1, 1]]; Line /@ {convPoints[[;; goalPosition]], convPoints[[goalPosition ;;]]} ]; Min[ArcLength /@ paths] ]; ``` Fortunately it is also works for *any convex polygon* (last test): [![enter image description here](https://i.stack.imgur.com/OvTAS.jpg)](https://i.stack.imgur.com/OvTAS.jpg) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 196 bytes ``` ¿∨⊙θ¬∨ι∧›⁰§ηκ‹⁰⁺§ηκ§η⁺²κ¬‹⌈Eθ∧ι∕⁺§ηκ∧‹ι⁰§η⁺²κ↔ι⌊Eθ∨¬ι∕⁺§ηκ∧›ι⁰§η⁺²κ↔ιI₂ΣX貫≔⟦⟧ζF²F⟦⁰§η⁻³ι⟧F²«F¬›∧λ§θι§ηι⊞⎇λζυE…η²⎇⁼ξιν⁺νκF¬‹∧λ§θι⁺§ηι§η⁺²ι⊞⎇λζυE…η²⎇⁼ξι⁺ν§η⁺²ι⁺νκ»I⌊Eυ⌊EζΣ⁺↔Eλ⁻ν§ιξE⟦ιEλ⁻§θξν⟧₂ΣXν² ``` [Try it online!](https://tio.run/##pVLBTsMwDD2vX@FjKgVpdNppp2kghMRgYtyqHsqW0Ygs3ZJmdEN8e3HSBlrYQIhcosTPfs/PXmSpWuSpqCq@AnKnyFjuyZbCbV7YF6cwlktypVhaMEX6@Cyu5ZKVJKPwHIYUbpjW9n8mjCadYAfrwpHLqU9N4bKnacnXZo33xlJbQuS94Du@ZORoXUS4TIT1f@DByKPOhSkY4Q3plMs2F7ZoZfDwVz5vwV8p7YGZ4rIgk1QXZL41qWL3ObLOUccsf8GiqCRyyFHAhGbwGvTGWvMnSeKEwgG/e6tcAYlCcHfcHQQ2hRIGFJAyaSAIxSp1mm3R67e9iM/srUvqVOO1ZKMz8sCUTNXeJhwoGOsf@jbZLwSbZPnGoiP89LBL7E1oUtoaFGRjjWysGbXluPGd0PJ1BPy439yb@2@lXuYJku99vAW91kjbO2W6K4Za3JRdR34xbED4qbVocbXKZksREfP6/kC2bCqtvThrrH5snaRfp@aMgreqiuMhhSGmxNjWOSIoDJKkOtuJdw "Charcoal – Try It Online") Link is to verbose version of code. Takes as input the target and the rectangle using the bottom left corner and size (note that this differs slightly from the test cases in the question). Explanation: ``` ¿∨⊙θ¬∨ι∧›⁰§ηκ‹⁰⁺§ηκ§η⁺²κ¬‹⌈Eθ∧ι∕⁺§ηκ∧‹ι⁰§η⁺²κ↔ι⌊Eθ∨¬ι∕⁺§ηκ∧›ι⁰§η⁺²κ↔ι ``` Use the [Liang-Barksy](https://en.wikipedia.org/wiki/Liang-Barsky_algorithm) algorithm to test whether the line intersects the rectangle; the first part of the expression covers the first two steps where the line is parallel to but not between two edges, while the rest calculates the intersections in terms of the parametric equation to see whether the line lies outside the rectangle. ``` I₂ΣXθ² ``` If it does not intersect the rectangle then just output the Euclidean distance to the target. ``` «≔⟦⟧ζ ``` Otherwise, separately prepare to collect the corners of the rectangle visible from the origin and the target. ``` F²F⟦⁰§η⁻³ι⟧F²« ``` Loop over the two axes, the length along that axis, and the origin and the target point. ``` F¬›∧λ§θι§ηι⊞⎇λζυE…η²⎇⁼ξιν⁺νκ ``` If the point is to the left or below the rectangle respectively, then collect the corners on that "near" side of the rectangle. ``` F¬‹∧λ§θι⁺§ηι§η⁺²ι⊞⎇λζυE…η²⎇⁼ξι⁺ν§η⁺²ι⁺νκ ``` If the point is to the right or above the rectangle respectively, then collect the corners on that "far" side of the rectangle. ``` »I⌊Eυ⌊EζΣ⁺↔Eλ⁻ν§ιξE⟦ιEλ⁻§θξν⟧₂ΣXν² ``` For each pair of points, calculate the Euclidean distance from the origin to the first point, the taxicab distance to the second point, and the Euclidean distance to the target, and output the minimum sum. ]
[Question] [ Imagine that there are \$n\$ different types of objects \$O\_1,O\_2,O\_3,\ldots,O\_n\$ and they each have a conversion factor \$k\_1,k\_2,k\_3,\ldots,k\_n\$. You can, for any \$1\le i\le n\$, convert \$k\_i\$ amount of \$O\_i\$ into \$1\$ of any **other** type of object. # Task Your objective is to output all the possible ending configurations of the amount of each of the \$n\$ objects after **all possible conversions have been made**, given the initial amount of each object \$A=a\_1,a\_2,a\_3,\ldots,a\_n\$ and a list \$K\$ of the conversion factor of each object. **Duplicate outputs are not allowed**. It is guaranteed that all conversion factors are greater than \$1\$ to prevent infinite conversions. # Example Let's say that the amount of each object is `A=[4,1,0]` and the conversion factors are `K=[2,3,4]`. One way to go about converting each of these is to first convert all the \$O\_1\$'s into \$O\_3\$'s, resulting in `[0,1,2]`. We can also convert some of the \$O\_1\$'s to \$O\_2\$'s and the rest to \$O\_3\$, resulting in `[0,2,1]`. But if we convert all the \$O\_1\$'s to \$O\_2\$'s, we get `[0,3,0]`, which can still be reduced. From `[0,3,0]` we can either convert to \$O\_1\$ or \$O\_3\$, resulting in `[1,0,0]` and `[0,0,1]` respectively. So the final output would be: ``` [0,1,2] [0,2,1] [1,0,0] [0,0,1] ``` # Test Cases ``` A, K -> output [4,1,0], [2,3,4] -> [0,1,2] [0,2,1] [1,0,0] [0,0,1] [99,99,99], [99,100,100] -> [1,0,99] [1,99,0] [1,0,0] [0,1,0] [0,0,1] [3,0,0], [3,3,3] -> [0,1,0] [0,0,1] [3,0,0,3], [3,3,3,3] -> [0,0,1,1] [0,1,0,1] [1,0,0,1] [0,1,1,0] [1,0,1,0] [1,1,0,0] [0,0,2,0] [0,2,0,0] [4,5], [3,3] -> [0,1] ``` If you want to generate more test cases, check out this [reference implementation](https://tio.run/##jVJdT8MgFH3fr7jZEyiazc5ETWqy5/0EJE1tqWI6aID5tey3T24p3ZZp4tIlcLjnnHsPdF/@1ejsrrP7fS0b6Ixz6rmVRWX0u7ROGe2IeX6TlXcMmrLyxjr6MAEr/cZq4ErX8hMaY6FfMVKuzUZ7FktpQEHqzVra0kvyrbpRLGmFkgYiCR7zwUJMJthNbMKfNcDA@dL6IloGgzouD40VrXIechiY15Xpvgg9OeVHGgKukrU7wU8Zo5GAyxzmYwrHnhBbb4oP5V@LetO1qgqzu1@GKHUf5RgehvXvC@hpQ0CFN8jdXthSv0jSSp0olO7gCra9/A5ZiSLrkM7f@Q7JHvQpctUfD2TUPHQIeQ5c9I44J@bFxzKBsGydjOfnWZ0LxrTGxMNmyPnXcNAx/9cdcBFEtfwoIoWLeB8t5hkgbDBM3YI2HqGhsu87sXC0dnwpCd6jzJLBCmmc8wWbs5kIhjcsYwuBK35/z/oPN2Exn83wH88yNov1WajPjrCwSWjCF@x2wITAzDurtCfNdLvcMdiuwhN4hClN@PRJT6/fjNJkXXbEecsasmQrGn6phO5/AA) that I wrote (if you find any bugs in it, please tell me! I'm not 100% sure that it's right...). --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes ``` ⊞υθFυFΦL鬋§ικ§ηκF⁻EΦLι⁻λκEι⎇⁼ξκ⁻ν§ηκ⁺ν⁼ξλυ⊞υλIΦυ⬤ι‹λ§ημ ``` [Try it online!](https://tio.run/##bY9NC8IwDIbv/oocM4jg182TiILgZAdvY4ei0xVjp/0Q/fW1axmi2Et4k7fPmxwaoQ@tYO8LZxp0BPdsPji1GtBlEOtasq01bmt1tg3KjGDX2iCNwYXdqGP9RElwCf1eNp3sXgLkUjmDubj9QaUZxw9BBU9g7WuthH7h6u4EG3wmerKq3xiCglP/Y@eYTuDCCv1dHO4qtFQWl8LYfpUwWDB3ofEg/qJfIyabe1@WM4IxwagiKCcEU4JZVfnhg98 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υθ ``` Start a breadth-first search for reachable configurations. ``` Fυ ``` Loop over the reachable configurations as they are found. ``` FΦL鬋§ικ§ηκ ``` Loop over the available conversion sources. ``` F⁻EΦLι⁻λκEι⎇⁼ξκ⁻ν§ηκ⁺ν⁼ξλυ ``` Loop over the possible conversion destinations, generating the resulting configurations, but exclude previously seen configurations. ``` ⊞υλ ``` Save the new configuration for further processing. ``` IΦυ⬤ι‹λ§ημ ``` Output only the ending configurations. [Answer] # [Python 3](https://docs.python.org/3/), ~~175~~ 173 bytes ``` def g(a,b,r,t=1): A=enumerate(a) for i,x in A: for j,y in A: if(i!=j)*x>=b[i]:c=[*a];c[i]-=b[i];c[j]+=1;t=g(c,b,r) if t:r+=[(*a,)] def f(a,b):g(a,b,r:=[]);return{*r} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZDRSsMwFIav26eId0l2Bq2t4FKOsOcIuchqMlMwGyGFDfFJRNiN3vlAvo1J14mokMB_zvfz5ycv7_tjfNj50-ltjHZ5-_lxbyzZUg0bCBCxZqIs1mj8-GiCjoZqVhZ2F4iDA3GerBOe5gGO33PhLHVXODB-uMONdEr0KLlWXZ_0ctokOagF1l3ELe3zYynXWRJFWKCkXANTZa5icxUm5kYCpWJdMHEM_omH57n06z44H6nklsoWaqgUEHkNDbSKKVb-oKsVTCcbkqirKt_frgaqc0aTMpp_aVpf-F9HCzczzeRc8vLDXw) Returns the set of arrays (as tuples). [Answer] # Python3, 225 bytes: ``` E=enumerate def f(a,b): q,s=[a],[a] while q: a,F=q.pop(0),0 for j,k in E(a): if k>=b[j]: F=1 for i,A in E(a): Y=eval(str(a));Y[j]-=b[j];Y[i]+=1 if Y not in s and i!=j:q+=[Y];s+=[Y] if 0==F:yield a ``` [Try it online!](https://tio.run/##bYzNbsMgEITvfortDZpthWtHahxRqYf4HSzEgcig4LjYxm6rPL0LNJX6J7HaZeabGS/LaXDF4@jX9cC1e33RXi06a7UBQxQeaZXBhDMXSmKYDN5PttcwBRkU1ny6H4eRMIosCGbw0OEZrIMDUTEKYA2cn/hRdDJ9oeZ52pG1@PyDBWi4flM9mRcfNLpvQuwuhcNp5eaajaUNuGGJ6RmUa8He8K6aNlw0cj@nlSWMcV5XF6v7FtQ6eusWIm4NESXmyCSCeMACS0klzb65ux2mF4Fw5IzF@U0VyD47itBR/OsG@cv/S5S4vbrRWT8A) [Answer] # JavaScript (ES6), 109 bytes Expects `(K)(A)`. Returns a set of strings. ``` (K,s=new Set)=>g=A=>K.map((v,i)=>A[i]<v||A.map((_,j,[...B])=>j-i&&g(B,B[i]-=v,A.u=++B[j])))|A.u?s:s.add(A+'') ``` [Try it online!](https://tio.run/##bY4xC4MwEIX3/opOmuAZtLaDpbHE1bFjkCIaxWCNNGoX/7uNupQi3MHdve89TmZjpvN33fVuqwoxl3RGCWjais/xIXpMo4oyGiXklXUIjVCbC@N1ehuniW3HJ0jghJA4NZp0a8uqUAyxgVw6AiMDdZyYyxRjbCzDXV81yYoCMce28ZyrVqtGkEZVqET8BAGcU4z4GXzwjOfwB4Qh@J639EKZba0dMDBJwcIE4O0mrcAPsox70PbNxYjzFw "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 155 bytes ``` import Data.List f v i l=take i l++v+l!!i:drop(i+1)l o!k|l<-[0..length o-1]=nub$(#k)=<<[f 1j$f(0-k!!i)i o|j<-l,i<-l,o!!i>=k!!i,j/=i] e#k|e!k>[]=e!k|1>0=[e] ``` [Try it online!](https://tio.run/##dZDPcoIwEMbveYpFPegQbAL2YIdw6rFvkMmBjlhjInGUcuLdaZaAf2bsDLCb/X777YZDeTWVtX2vT2d3aeCzbMr1l742ZA8taLCiKU2FSRy3sY0i/bG7uPNSx3xliYtMZ/NEsvXaVvVPcwCXcCXq3@/Fcm5WIs/lHvhxsV@yxPjelQbXHfPEUo0f50uFQIEe34RWpJqbropMIZXwoeMFE7JS/anUNQjYOQLni64bWIDcUE6ZimRKM7pRMCmz2QOz3dLh8ZiPnDF81Us0o2ywy7xd9o/dwHh1pJB7DW7oe4DQqCfSz6WpwphS7iMfhuGZ4ZncF6XwuCkkRYC9gomX2FM7f7YJl6Aw3QLbX0NenbA7iChX7dgT0mHWvYpeY/WWhnXa4JBOaTpWyfA3wrDbRor8AQ "Haskell – Try It Online") * Imported Data.List for removing duplicates using nub. * *f* modify element in list at *i* * *o!k* converts k\*1 of each *o* in every ways * *e#k* returns *e* if not convertible, else apply *!* again [Answer] # [Pyth](https://github.com/isaacg1/pyth), 51 bytes ``` DydI!s/VdQRaYdVldVldI&nNHg@dN@QN yXHXN=Gd_@QN1;yE{Y ``` [Try it online!](https://tio.run/##K6gsyfj/36UyxVOxWD8sJTAoMTIlLAeEPNXy/DzSHVL8HAL9FCojPCL8bN1T4oEcQ@tK1@rI//@jjXSMdUxiuaJNdAx1DGIB "Pyth – Try It Online") ### Explanation ``` Dyd define y(d) I!s/VdQRaYd if no conversions left, put d in Y and end function Vld for N in range(len(d)) Vld for H in range(len(d)) I&nNHg@dN@QN if N!=H and d[N] is large enough to be converted yXHXN=Gd_@QN1; convert type N to type H and recursively call y on the new list yE call y on the input list {Y remove duplicates from the output Y ``` ]
[Question] [ Given a list of positive integers as input you are to determine if there is a way to pair up the elements such that: * All but one element is in a pair * No element is in more than one pair * Every pair is of equal elements * No two pairs have elements separated by the same distance in the original list For example if the input is: ``` [2,2,1,2,3,3,1] ``` Then we can choose the following pairs: ``` [2,2,1,2,3,3,1] <- Input [2, 2] % Separated by 2 [1, 1] % Separated by 4 [3,3] % Separated by 1 ``` The first `2` is the element which is not in a pair. **Very importantly**, when you take the list of code points of your program it must satisfy the property. Answers which do not are invalid. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the size of your source code as measured in bytes while satisfying the constraints. To decide, your program should output one of two fixed values. The first if the solution there is a pairing of the input list as described and the second of the two values if there is not. # Test cases ### Pairing possible ``` [1] [1,1,1] [1,1,1,1,1] [2,2,1,1,1] [2,2,1,2,1] [2,2,1,2,3,3,1] [2,2,2,1,2,3,3] ``` ### Pairing not possible ``` [] [1,1] [1,2,3] [1,1,1,1] [2,2,1,2,3] [2,2,1,3,3] [1,1,1,1,1,1] [2,2,2,2,1,3,3] ``` [Answer] # [J](http://jsoftware.com/), 151 bytes ``` (1=1#.2|1#.=)*.1 e.[:(~.@;-:;)&>@,@{<@(i.@!@#<@(2|@-/\]}.~2|#)@A.])@I.@=NB. [[email protected]](/cdn-cgi/l/email-protection)@)].A@)#|2~.}]\/-@|2(@<#@[[email protected]](/cdn-cgi/l/email-protection)(@<{@,@>&);:-;@.~(:[.e 1.*)=.#1|2.#1=1( ``` [Try it online!](https://tio.run/##bY5NawIxEIbv/oqxAZOIeTXxljUyWhCE4qH0pnsoZUVLodCPQzHuX18jbVl1l2GGdx7m432t7iC3FDxJGtCIfEoDun98WFTKBivgYipB92GpwNqrEpwZn@nelAd8mLDag7ssknCRzXCTH1G6KDTPkGtegsNqDsJ8FRhL1jlmrEV0JY75Zmg4OsUTkS5gn8Qh3Zz2dOZNxiiVX6Mgi74OEDa6VIJVle4UL7t3kk8f31@7H/nbbclSrWyjuyQuRRtxLWSc4prWvPNnZPH89ln7kPLyc63PO7eemt@uybhlxzb8/E9WJw "J – Try It Online") What the hell, I'll kick things off with this grotesquerie of brute force. Looking forward to seeing more clever solutions.... [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~67~~ 63 bytes ``` &ff&{[[email protected]](/cdn-cgi/l/email-protection)%lQ2 " 2%UU-TTP.2RcYZ@Fnf!YMaI{ ``` [Try it online!](https://tio.run/##K6gsyfj/Xy0tTa3aM9E3UjEtz83BJzAqMjnISC8gJCdE1yc0MDRQNSfQSEFJwUg1NFQ3JCRAzygoOTLKwS0vTTHSN9Gz@v//aCMdIx1DIDYGQsNYAA "Pyth – Try It Online") -- [Truthy test suite](https://tio.run/##K6gsyfiv/F8tLU2t2jPRN1IxLc/NwScwKjI5yEgvICQnRNcnNDA0UDUn0EhBScFINTRUNyQkQM8oKDkyysEtL00x0jfRs/q/koKt6/9ow1iuaEMdIITRULaRjhEa2wiFbQyEMD5cJBYA "Pyth – Try It Online") -- [Falsey test suite](https://tio.run/##K6gsyfiv/F8tLU2t2jPRN1IxLc/NwScwKjI5yEgvICQnRNcnNDA0UDUn0EhBScFINTRUNyQkQM8oKDkyysEtL00x0jfRs/q/koKt6//oWK5oQx1DMGmkYwzh6UBEjIAiMFEI2xhZBZIqhCwA "Pyth – Try It Online") (Outputs `1` for true and `[]` for false) --- The `"` near the middle of the program is the unpaired character. Everything after it is part of a string literal. Most characters in the main program have a twin in the string literal. Below are the exceptions: | Character | Index A | Index B | Distance | | --- | --- | --- | --- | | `&` | 0 | 3 | 3 | | `f` | 1 | 2 | 1 | | `L` | 14 | 27 | 13 | | `Q` | 15 | 31 | 16 | | `l` | 24 | 33 | 9 | | `Q` | 29 | 34 | 5 | ### Explanation `-LUQUQ` - Build a list of lists of indexes, each list containing all but one index of the input `f ... cR2.PTlT` - for each list, generate all permutations, and split into chunks of size 2 `f ... !fnF@LQZY` - for each permutation, check whether the indexes of each pair correspond to equal elements of the input... `&{IaMY` - ... and that the differences between each pair is unique If no permutation for any list of indexes satisfies those conditions, the `&` short-circuits and `[]` is returned. Otherwise... `%lQ2` - ...return the length of the input mod 2 [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ā<œ.Δ¨2ôDÆÄDÙQiè€ËP]gÉqÉg]PË€èiQÙÄÆô2¨Δ.œ<ā ``` [Try it online.](https://tio.run/##yy9OTMpM/f//SKPN0cl656YcWmF0eIvL4bbDLS6HZwZmHl7xqGnN4e6A2PTDnYWHO9NjAw53g0RWZAYennm4Bahui9GhFeem6B2dbHOk8f//aCMdIx1DIDYGQsNYAA) The base program is 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage): `ā<œ.Δ¨2ôDÆÄDÙQiè€ËP]gÉ` - [try it online](https://tio.run/##yy9OTMpM/f//SKPN0cl656YcWmF0eIvL4bbDLS6HZwZmHl7xqGnN4e6A2PTDnf//RxvpGOkYArExEBrGAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVLqNL/I402RyfrnZtyaIXR4S0uh9sOt7gcnhmYGVF8eMWjpjWHuwNi0w93/lfSC9P5Hx1tGKsTbagDhDAayjbSMUJjG6GwjYEQxoeLAPkQY8CkEVjAEMMYYzjbGFkFkiqEbCwA). (Although [could be 21 bytes](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVLqNL/I402RyefmnRohdHhLS6H2w63uByeGZgZUXx4xaOmNYe7A2IPLzjc8V9JL0znf3S0YaxOtKEOEMJoKNtIxwiNbYTCNgZCGB8uAuRDjAGTRmABQwxjjOFsY2QVSKoQsrEA) if just truthy/falsey would have been allowed instead of two consistent values, where the truthy results are still `1`, but the falsey results would be either `""` or `0`.) Unfortunately, it only contains `D` as duplicated used character, and everything else is unique. So we'll just add a trailing `q` (the unique character) and the reversed program minus the two `D`s. **Explanation:** ``` ā # Push a list in the range [1, (implicit) input-length] < # Decrease each by 1 to the range [0,length) œ # Get all permutations of this list .Δ # Get the first list that's truthy for (or -1 if none are): ¨ # Remove the last index 2ô # Split all other indices into pairs D # Duplicate this list Æ # Reduce each inner pair by subtracting Ä # And then taking their absolute values DÙQi # If this list of absolute differences is unique: D # Duplicate Ù # Uniquify Q # Check if both lists are still the same i # Pop, and if this is truthy: è # Index the pairs into the (implicit) input-list €Ë # Check if for each pair of values if they're the same P # Check if this is truthy for all of them ] # Close the if-statement and find_first-loop g # Pop and push the length (2 for the -1 results) É # Check if this length is odd q # Stop the program, making everything after it no-ops # (and implicitly output the result) Ég]PË€èiQÙÄÆô2¨Δ.œ<ā # No-ops ``` ]
[Question] [ Basically the [tron light-cycle game](https://www.youtube.com/watch?v=Vpr5DtZ9_AA) as a king of the hill competition! [![Picture of an online version of the tron light-cycle video game](https://i.stack.imgur.com/R6OLg.jpg)](https://www.youtube.com/watch?v=Vpr5DtZ9_AA) ## Leaderboard **Updated as of 2022-04-05** ``` #1) Player Avoid by Agent Biscutt #2) Dodge West by Imanton1 #3) Space Finder by Spitemaster #4) Blind Bot by TheSilican ``` [Judge/Leaderboard Website](https://thesilican.github.io/code-golf-tron-koth) ## The Game Players will write bots that compete in a light-cycle tournament. A round of light-cycle starts with bots evenly spaced out along the edge of a rectangular play area: ``` +--------------------+ | @ @ | | | | | | | | | | | | | | @ @ | +--------------------+ ``` Each turn, each bot simultaneously must choose one of 4 directions to step (N, E, S, or W). The "head" of the bot steps in that direction, and the space that was once occupied by the head becomes part of the "body". ``` +--------------------+ | # @# | | @ | | | | | | | | | | @ | | @# # | +--------------------+ ``` The round ends as soon as one or more bots crash into a wall, or into the head or body of another bot (including its own body). ``` *CRASH* +-----------@--------+ | # ##### | | ### | | # | | @ @ | | # | | # @# | | # ### | | ## # | +--------------------+ ``` The bot(s) that crashed into the wall will be eliminated, and a new round will start with new starting positions. Bots are eliminated each round, until only 1 bot remains. **The leaderboard rankings are based on the order that the bots are eliminated.** ## Code / API For ease of judging and creating the judge website, *submissions will be restricted to javascript*. A bot is a javascript function with the following API: ``` (state) => { // state is an object with access to information about the game // bots can use the state to make decisions // bots return one of "N", "E", "S", "W" // e.g.: return "N"; } ``` The `state` parameter contains the following API calls: * `state.getDim()`: Returns a `[w, h]` tuple of the width and height of the arena. e.g. `[20, 10]` * `state.getSelf()`: Returns a `[x, y]` tuple of the current bot's head. e.g. `[3, 7]` * `state.get(x, y)`: Given integers `x` and `y`, returns a string corresponding to what is currently on the map at (x, y) + `"#"` - body of a bot, or out-of bounds of the map ("wall") + `"@"` - head of a bot + `" "` - empty cell * `state.getBoard()`: Returns a 2d array of the entire map. `state.getBoard()[x][y]` is equivalent to `state.get(x, y)` Coordinates: (0, 0) is the bottom-left corner of the playfield with x increasing to the right and y upwards. ## Code Submission ~~To make a bot submission, add your bot code to [this GitHub repository](https://github.com/thesilican/code-golf-tron-koth) with a pull request, in addition to posting an answer.~~ Edit: Opening a PR in GitHub is no longer necessary, simply post your submission here. Each user may only make one submission, however you may freely edit your submission after posting. [Answer] # Space Finder ``` (state) => { const [x, y] = state.getSelf(); let starts = [[x, y + 1, "N"], [x + 1, y, "E"], [x, y - 1, "S"], [x - 1, y, "W"]]; let toSearch = starts.slice(); toSearch = toSearch.filter(d => state.get(d[0], d[1]) == " "); let searched = []; let adjacent = [[0, 1], [1, 0], [0, -1], [-1, 0]]; let dirs = { N: toSearch.find(s => s[2] == "N") ? 1 : 0, E: toSearch.find(s => s[2] == "E") ? 1 : 0, S: toSearch.find(s => s[2] == "S") ? 1 : 0, W: toSearch.find(s => s[2] == "W") ? 1 : 0 }; let active = {...dirs}; // Determine the size of the spaces adjacent to each of the possible moves while (toSearch.length){ active[toSearch[0][2]]--; adjacent.forEach(a => { if (!toSearch[0]) return; let loc = [toSearch[0][0] + a[0], toSearch[0][1] + a[1], toSearch[0][2]]; let tile = state.get(loc[0], loc[1]); if (tile == " "){ let prev = searched.find(s => s[0] == loc[0] && s[1] == loc[1]); if (prev){ if (prev[2] == toSearch[0][2]){ return; } dirs[toSearch[0][2]] = prev[2]; searched.forEach(s => s[2] = s[2] == toSearch[0][2] ? prev[2] : s[2]); toSearch = toSearch.filter(d => d[2] != toSearch[0][2]); if (Object.values(dirs).filter(v => !isNaN(+v)).length == 2){ toSearch = [null]; return; } return; } searched.push(loc); toSearch.push(loc); dirs[loc[2]]++; active[loc[2]]++; } else if (tile == "@"){ dirs[loc[2]] /= 2; } }); toSearch.shift(); if ((active.N == 0) + (active.E == 0) + (active.S == 0) + (active.W == 0) == 3){ let key = Object.keys(active).find(k => active[k]); if (dirs[key] > Math.max(...Object.entries(dirs).filter(v => v[0] != key && !isNaN(+v[1])).map(v => v[1]))) break; } } // Pick the move with the largest space for (let key of Object.keys(dirs)){ if (isNaN(+dirs[key])) dirs[key] = dirs[dirs[key]]; if (isNaN(+dirs[key])) dirs[key] = dirs[dirs[key]]; } let best = Math.max(...Object.values(dirs)); let possible = Object.keys(dirs).filter(d => dirs[d] == best); // Pick the move with the fewest things adjacent to it if (possible.length > 1){ let scores = {" ": 0, "#": 0, "@": 1}; possible = possible.map(p => { let dir = starts.find(s => s[2] == p); return [p, adjacent.reduce((a, c) => a + scores[state.get(c[0] + dir[0], c[1] + dir[1])], 0)]; }); possible = possible.filter(p => p[1] == Math.min(...possible.map(p => p[1]))).map(p => p[0]); } return possible[0]; } ``` Space Finder checks each adjacent space to determine which is attached to the largest empty area. If it has multiple choices, it avoids other heads. [Answer] # Dodge West ``` (state) => { const [x, y] = state.getSelf(); if (state.get(x - 1, y) === " " && !(state.get(x - 2, y + 0) === "@" || state.get(x - 1, y + 1) === "@" || state.get(x - 1, y - 1) === "@")) return "W"; if (state.get(x, y + 1) === " " && !(state.get(x + 0, y + 2) === "@" || state.get(x + 1, y + 1) === "@" || state.get(x - 1, y + 1) === "@")) return "N"; if (state.get(x, y - 1) === " " && !(state.get(x + 0, y - 2) === "@" || state.get(x + 1, y - 1) === "@" || state.get(x - 1, y - 1) === "@")) return "S"; if (state.get(x + 1, y) === " " && !(state.get(x + 2, y + 0) === "@" || state.get(x + 1, y + 1) === "@" || state.get(x + 1, y - 1) === "@")) return "E"; if (state.get(x - 1, y) === " ") return "W"; if (state.get(x, y + 1) === " ") return "N"; if (state.get(x, y - 1) === " ") return "S"; if (state.get(x + 1, y) === " ") return "E"; return "N"; } ``` Much like 'Blind Bot', but tries to avoid head-on collisions by turning if another bot could collide with it. Tries to go West and hold on that side of the screen. [Answer] # Blind Bot Bot that simply checks each of the 4 adjacent directions, and goes in the first direction that is empty. Just to get the ball rolling for now, I may or may not edit this submission in the future. ``` (state) => { const [x, y] = state.getSelf(); if (state.get(x, y + 1) === " ") { return "N"; } else if (state.get(x + 1, y) === " ") { return "E"; } else if (state.get(x, y - 1) === " ") { return "S"; } else if (state.get(x - 1, y) === " ") { return "W"; } return "N"; } ``` [Answer] # Player Avoid This bott simply tries to avoid collision with other bots. Also, runs east instead of north as default, just to spice things up. ``` (state) => { const [x, y] = state.getSelf(); if (state.get(x + 1, y) === " " && (state.get(x + 1, y+1) ===" " || state.get(x + 1, y-1) ===" ") && (state.get(x+1, y + 1) != "@" && state.get(x+1, y-1)!= "@") && ((state.get(x-1, y + 1) != "@" && state.get(x-1, y-1)!= "@") || state.get(x+2, y)=="#") && ((state.get(x+2, y + 2) != "@" && state.get(x+2, y-2)!= "@")) && ((state.get(x-2, y + 2) != "@" && state.get(x-2, y-2)!= "@")) && ((state.get(x+2, y + 2) != "@" && state.get(x+2, y-1)!= "@")) && ((state.get(x-2, y + 2) != "@" && state.get(x-2, y-1)!= "@")) && state.get(x+2, y)!="@" ) { return "E"; } else if (state.get(x - 1, y) === " " && (state.get(x - 1, y+1) ===" " || state.get(x - 1, y-1) ===" ") && (state.get(x-1, y + 1) != "@" && state.get(x-1, y-1)!= "@") && ((state.get(x+1, y + 1) != "@" && state.get(x+1, y-1)!= "@") || state.get(x+2, y)=="#") && ((state.get(x+2, y + 2) != "@" && state.get(x+2, y-2)!= "@")) && ((state.get(x-2, y + 2) != "@" && state.get(x-2, y-2)!= "@")) && ((state.get(x+2, y + 2) != "@" && state.get(x+2, y-1)!= "@")) && ((state.get(x-2, y + 2) != "@" && state.get(x-2, y-1)!= "@")) && state.get(x-2, y)!="@" ) { return "W"; }else if (state.get(x, y + 1) === " " && (state.get(x+1, y + 1) != "@" && state.get(x-1, y + 1)!= "@") && state.get(x, y+2)!="@" ) { return "N"; } else if (state.get(x, y - 1) === " " && (state.get(x+1, y - 1) != "@" && state.get(x-1, y - 1)!= "@") && state.get(x, y+2)!="@" ) { return "S"; } if (state.get(x, y + 1) === " " && state.get(x, y + 2)!="@") { return "N"; } else if (state.get(x + 1, y) === " " && state.get(x+2, y)!="@") { return "E"; } else if (state.get(x, y - 1) === " " && state.get(x, y - 2)!="@") { return "S"; } else if (state.get(x - 1, y) === " " && state.get(x-2, y)!="@") { return "W"; } if (state.get(x, y + 1) === " ") { return "N"; } else if (state.get(x + 1, y) === " ") { return "E"; } else if (state.get(x, y - 1) === " ") { return "S"; } else if (state.get(x - 1, y) === " ") { return "W"; } return "S"; } ``` ]
[Question] [ ## The challenge Find the smallest feedforward neural network such that, given any 3-dimensional input vector \$(a,b,c)\$ with integer entries in \$[-10,10]\$, the network outputs the largest (i.e., "most positive") root of the polynomial \$x^3+ax^2+bx+c\$ with error strictly smaller than \$0.1\$. ## Admissibility The notion of admissibility in [my previous neural net golfing challenge](https://codegolf.stackexchange.com/questions/193624/sort-with-a-neural-network) seemed a bit restrictive, so for this challenge, we are using a more liberal definition of feedforward neural network: A **neuron** is a function \$\nu\colon\mathbf{R}^n\to\mathbf{R}\$ that is specified by a vector \$w\in\mathbf{R}^{n}\$ of **weights**, a **bias** \$b\in\mathbf{R}\$, and an **activation function** \$f\colon\mathbf{R}\to\mathbf{R}\$ in the following way: $$ \nu(x) := f(w^\top x+b), \qquad x\in\mathbf{R}^n. $$ A feedforward neural network with **input nodes** \$\{1,\ldots,n\}\$ is a function of \$(x\_1,\ldots,x\_n)\in\mathbf{R}^n\$ that can be built from a sequence \$(\nu\_k)\_{k=n+1}^N\$ of neurons, where each \$\nu\_k\colon\mathbf{R}^{k-1}\to\mathbf{R}\$ takes inputs from \$(x\_1,\ldots,x\_{k-1})\$ and outputs a scalar \$x\_k\$. Given some specified set \$S\subseteq\{1,\ldots,N\}\$ of **output nodes**, then the output of the neural network is the vector \$(x\_k)\_{k\in S}\$. Since activation functions can be tuned for any given task, we need to restrict the class of activation functions to keep this challenge interesting. The following activation functions are permitted: * **Identity.** \$f(t)=t\$ * **ReLU.** \$f(t)=\operatorname{max}(t,0)\$ * **SoftPlus.** \$f(t)=\ln(e^t+1)\$ * **Sigmoid.** \$f(t)=\frac{e^t}{e^t+1}\$ * **Sinusoid.** \$f(t)=\sin t\$ Overall, an admissible neural net is specified by input nodes, a sequence of neurons, and output nodes, while each neuron is specified by a vector of weights, a bias, and an activation function from the above list. For example, the following neural net is admissible, though it does not meet the performance goal of this challenge: * **Input nodes:** \$\{1,2\}\$ * **Neurons:** \$\nu\_k(x\_1,\ldots,x\_{k-1}):=x\_{k-2}+x\_{k-1}\$ for \$k\in\{3,\ldots,10\}\$ * **Output nodes:** \$\{5,9,10\}\$ This network consists of 8 neurons, each with zero bias and identity activation. In words, this network computes the generalized Fibonacci sequence generated by \$x\_1\$ and \$x\_2\$ and then outputs the 5th, 9th, and 10th numbers from this sequence, in that order. ## Scoring Given a real number \$x\$ with terminating decimal expansion, let \$p(x)\$ be the smallest nonnegative integer \$p\$ for which \$10^{-p}\cdot |x|<1\$, and let \$q(x)\$ be the smallest nonnegative integer \$q\$ for which \$10^q \cdot x\$ is integer. Then we say \$p(x)+q(x)\$ is the **precision** of \$x\$. For example, \$x=1.001\$ has a precision of \$4\$, whereas \$x=0\$ has a precision of \$0\$. Your score is the sum of the precisions of the weights and biases in your neural network. (E.g., the above example has a score of 16.) ## Verification While the roots can be expressed in terms of [the cubic formula](https://math.stackexchange.com/questions/61725/is-there-a-systematic-way-of-solving-cubic-equations), the largest root is perhaps most easily accessed by numerical means. Following @xnor's suggestion, I computed the largest root for every choice of integers \$a,b,c\in[-10,10]\$, and [the results can be found here](https://www.dropbox.com/s/w55rhtuqwelqbvw/roots.txt?dl=0). Each line of this text file is of the form `a,b,c,root`. For example, the first line reports that the largest root of \$x^3-10x^2-10x-10\$ is approximately \$10.99247140445449\$. **Edit:** The original file I posted had errors in cases where the polynomial exhibited a multiple root. The current version should be free of such errors. [Answer] # ~~14,674,000,667~~ ~~5,436,050~~ ~~5,403,448~~ ~~10,385~~ ~~5,994~~ ~~4,447~~ 3,806 total precision For a baseline, I investigated the following approach: Select \$M,\delta,\epsilon>0\$ such that if we sample the polynomial \$p(x)=x^3+ax^2+bx+c\$ at $$ S:=\{-M,-M+\delta,-M+2\delta,\ldots,M\}, $$ then the largest sample point \$s^\star\in S\$ satisfying \$p(s^\star)<\epsilon\$ necessarily exists and necessarily resides within \$0.1\$ of the largest root of \$p\$. One can show that for our collection of polynomials, one may take \$M=11\$, \$\delta=0.1\$, and \$\epsilon=10^{-4}\$. To design a neural net that implements this logic, we start with a layer of neurons that sample the polynomial on \$S\$. For each \$s\in S\$, we take $$ x\_{1,s} = s^2\cdot a + s\cdot b + 1\cdot c + s^3. $$ Next, we identify which of these are less than \$\epsilon=10^{-4}\$. It turns out that for \$s\in S\$, it holds that \$p(s)<10^{-4}\$ only if \$p(s)\leq 0\$. As such, we can use relu activations to exactly identify our samples: $$ \frac{\mathrm{relu}(10^{-4}-t) - \mathrm{relu}(-t)}{10^{-4}} = \left\{\begin{array}{cl}1&\text{if }t\leq 0\\0&\text{if }t\geq 10^{-4}.\end{array}\right.$$ We implement this with a few layers of neurons: $$ \begin{aligned} x\_{2,s} &= \mathrm{relu}(-1\cdot x\_{1,s}+10^{-4}), \\ x\_{3,s} & = \mathrm{relu}(-1\cdot x\_{1,s}), \\ x\_{4,s} &= 10^{4}\cdot x\_{2,s}-10^{4}\cdot x\_{3,s}. \end{aligned}$$ At this point, we have \$x\_{4,s}=1\$ when \$p(s)<10^{-4}\$, and otherwise \$x\_{4,s}=0\$. Recall that we seek the largest \$s^\star\$ for which \$x\_{4,s^\star}=1\$. To this end, we label \$x\_{4,M}\$ as \$x\_{5,M}\$ (for notational convenience), and for each \$k\geq 1\$, we iteratively define $$ x\_{5,M-k\delta} = 1\cdot x\_{4,M-k\delta}+2\cdot x\_{5,M-(k-1)\delta} = \sum\_{j=0}^k 2^{k-j}x\_{4,M-j\delta}. $$ Thanks to this transformation, every \$x\_{5,s}\$ is a nonnegative integer, and \$s^\star\$ is the unique \$s\$ for which \$x\_{5,s}=1\$. We may now identify \$s^\star\$ by another application of relu activations: $$ \mathrm{relu}(t-2)-2\cdot\mathrm{relu}(t-1)+t = \left\{\begin{array}{cl}1&\text{if }t=1\\0&\text{if }t\in\mathbf{Z}\_{\geq 0}\setminus\{1\}.\end{array}\right.$$ Explicitly, we define neurons by $$ \begin{aligned} x\_{6,s} &= \mathrm{relu}(1\cdot x\_{5,s} - 2), \\ x\_{7,s} &= \mathrm{relu}(1\cdot x\_{5,s} - 1), \\ x\_{8,s} &= 1\cdot x\_{6,s} - 2\cdot x\_{7,s} + 1\cdot x\_{5s}. \end{aligned} $$ Then \$x\_{8,s}=1\$ if \$s=s^\star\$ and otherwise \$x\_{8,s}=0\$. We linearly combine these to produce our output node: $$ x\_9 = \sum\_{s\in S} s\cdot x\_{8,s} = s^\star. $$ For the score, each layer has neurons with different levels of precision: (1) \$6+3+1+9=19\$, (2) \$1+4=5\$, (3) \$1\$, (4) \$5+5=10\$, (5) \$1+1=2\$, (6) \$1+1=2\$, (7) \$1+1=2\$, (8) \$1+1+1=3\$, (9) \$3|S|\$. Furthermore, all but two of the layers have \$|S|=221\$ neurons; layer 5 has \$|S|-1\$ neurons and layer 9 has \$1\$ neuron. **Edit:** Improvements: (1) We can sample the polynomial much more efficiently using finite differences. (2) We can bypass layers 2 through 4 by instead using a sigmoid activation. (3) The overflow issues in layer 5 can be averted (and subsequent layers can be combined) by more carefully applying relu activations. (4) The final sum is cheaper with [summation by parts](https://en.wikipedia.org/wiki/Summation_by_parts). What follows is the MATLAB code. To be clear, `prec` is a function (found [here](https://www.dropbox.com/s/a9wbib5klpyhx0v/prec.m?dl=0)) that computes the precision of a vector of weights or biases. ``` function sstar = findsstar2(a,b,c) relu = @(x) x .* (x>0); totprec = 0; % x1 samples the polynomial on -11:0.1:11 x1=[]; for s = -11:0.1:11 if length(x1) < 5 w1 = [s^2 s 1]; b1 = s^3; x1(end+1,:) = w1 * [a; b; c] + b1; totprec = totprec + prec(w1) + prec(b1); else w1 = [-1 4 -6 4]; x1(end+1,:) = w1 * x1(end-3:end,:); totprec = totprec + prec(w1); end end % x4 indicates whether the polynomial is nonpositive w4 = -6e5; b4 = 60; x4=[]; for ii=1:length(x1) x4(end+1) = sigmf(w4 * x1(ii) + b4, [1,0]); totprec = totprec + prec(w4) + prec(b4); end % x6 indicates which entries are less than or equal to sstar x5 = zeros(size(x1)); x6 = zeros(size(x1)); x5(end) = 0; x6(end) = 0; for ii = 1:length(x5)-1 w5 = [-1 -1]; b5 = 1; x5(end-ii) = relu(w5 * [x4(end-ii); x6(end-ii+1)] + b5); totprec = totprec + prec(w5) + prec(b5); w6 = -1; b6 = 1; x6(end-ii) = w6 * x5(end-ii) + b6; totprec = totprec + prec(w6) + prec(b6); end % a linear combination produces sstar w7 = 0.1*ones(1,length(x1)); w7(1) = -11; sstar = w7 * x6; %disp(totprec) % uncomment to display score end ``` [Answer] # ~~53,268~~ ~~29,596~~ 29,306 total precision Private communication with @A.Rex led to this solution, in which we construct a neural net that memorizes the answers. The core idea is that every function \$f\colon S\to\mathbf{R}\$ over a finite set \$S\$ enjoys the decomposition $$ f(x) = \sum\_{s\in S}f(s)\cdot \left\{\begin{array}{cl}1&\text{if }x=s\\0&\text{else}\end{array}\right\}. $$ As such, one may construct a neural net implementation of \$f\$ by first transforming the input into an indicator function of the input, and then linearly combining using the desired outputs as weights. Furthermore, relu activations make this transformation possible: $$ \mathrm{relu}(t-1)-2\cdot\mathrm{relu}(t)+\mathrm{relu}(t+1) = \left\{\begin{array}{cl}1&\text{if } t=0\\0&\text{if }t\in\mathbf{Z}\setminus\{0\}.\end{array}\right. $$ What follows is a MATLAB implementation of this approach. To be clear, `roots.txt` is the roots file posted above (found [here](https://www.dropbox.com/s/w55rhtuqwelqbvw/roots.txt?dl=0)), and `prec` is a function (found [here](https://www.dropbox.com/s/a9wbib5klpyhx0v/prec.m?dl=0)) that computes the total precision of a vector of weights or biases. **Edit 1:** Two improvements over the original: (1) I factored some neurons out of the for loops. (2) I implemented "[Lebesgue integration](https://en.wikipedia.org/wiki/Lebesgue_integration)" in the final sum by first combining terms from the same level set. This way, I pay for the higher-precision value of an output only once every level set. Also, it is safe to round outputs to the nearest fifth by the [rational root theorem](https://en.wikipedia.org/wiki/Rational_root_theorem). **Edit 2:** Additional minor improvements: (1) I factored more neurons out of a for loop. (2) I don't bother computing the term in the final sum for which the output is already zero. ``` function r = approxroot(a,b,c) relu = @(x)x .* (x>0); totalprec=0; % x4 indicates which entry of (-10:10) is a w1 = ones(21,1); b1 = -(-10:10)'-1; x1 = relu(w1 * a + b1); w2 = ones(21,1); b2 = -(-10:10)'; x2 = relu(w2 * a + b2); w3 = ones(21,1); b3 = -(-10:10)'+1; x3 = relu(w3 * a + b3); w4p1 = ones(21,1); w4p2 = -2*ones(21,1); w4p3 = ones(21,1); x4 = w4p1 .* x1 + w4p2 .* x2 + w4p3 .* x3; totalprec = totalprec + prec(w1) + prec(w2) + prec(w3) + prec(b1) + prec(b2) + prec(b3) + prec(w4p1) + prec(w4p2) + prec(w4p3); % x8 indicates which entry of (-10:10) is b w5 = ones(21,1); b5 = -(-10:10)'-1; x5 = relu(w5 * b + b5); w6 = ones(21,1); b6 = -(-10:10)'; x6 = relu(w6 * b + b6); w7 = ones(21,1); b7 = -(-10:10)'+1; x7 = relu(w7 * b + b7); w8p1 = ones(21,1); w8p2 = -2*ones(21,1); w8p3 = ones(21,1); x8 = w8p1 .* x5 + w8p2 .* x6 + w8p3 .* x7; totalprec = totalprec + prec(w5) + prec(w6) + prec(w7) + prec(b5) + prec(b6) + prec(b7) + prec(w8p1) + prec(w8p2) + prec(w8p3); % x12 indicates which entry of (-10:10) is c w9 = ones(21,1); b9 = -(-10:10)'-1; x9 = relu(w9 * c + b9); w10 = ones(21,1); b10 = -(-10:10)'; x10 = relu(w10 * c + b10); w11 = ones(21,1); b11 = -(-10:10)'+1; x11 = relu(w11 * c + b11); w12p1 = ones(21,1); w12p2 = -2*ones(21,1); w12p3 = ones(21,1); x12 = w12p1 .* x9 + w12p2 .* x10 + w12p3 .* x11; totalprec = totalprec + prec(w9) + prec(w10) + prec(w11) + prec(b9) + prec(b10) + prec(b11) + prec(w12p1) + prec(w12p2) + prec(w12p3); % x15 indicates which row of the roots file is relevant x15=[]; for aa=-10:10 w13 = 1; b13 = -2; x13 = w13 * x4(aa+11) + b13; totalprec = totalprec + prec(w13) + prec(b13); for bb=-10:10 w14p1 = 1; w14p2 = 1; x14 = w14p1 * x13 + w14p2 * x8(bb+11); totalprec = totalprec + prec(w14p1) + prec(w14p2); for cc=-10:10 w15p1 = 1; w15p2 = 1; x15(end+1,1) = relu(w15p1 * x14 + w15p2 * x12(cc+11)); totalprec = totalprec + prec(w15p1) + prec(w15p2); end end end % r is the desired root, rounded to the nearest fifth A = importdata('roots.txt'); outputs = 0.2 * round(5 * A(:,4)'); uniqueoutputs = unique(outputs); x16 = []; for rr = uniqueoutputs if rr == 0 x16(end+1,:) = 0; else lvlset = find(outputs == rr); w16 = ones(1,length(lvlset)); x16(end+1,:) = w16 * x15(lvlset); totalprec = totalprec + prec(w16); end end w17 = uniqueoutputs; r = w17 * x16; totalprec = totalprec + prec(w17); %disp(totalprec) % uncomment to display score end ``` ]
[Question] [ The [Blow-up](https://en.wikipedia.org/wiki/Blowing_up) is a powerful tool in algebraic geometry. It allows the removal of *singularities* from *algebraic sets* while preserving the rest of their structure. If you're not familiar with any of that don't worry, the actual computation is not difficult to understand (see below). In the following we are considering the *blow-up* of the point \$(0,0)\$ of an algebraic curve in 2D. An algebraic curve in 2D is given by the zero-locus of a polynomial in two variables (e.g. \$p(x,y) = x^2 + y^2 - 1\$ for the unit circle, or \$p(x,y) = y-x^2\$ for a parabola). The *blowup* of that curve (in \$(0,0)\$) is given by two polynomials \$r,s\$ as defined below. Both \$r\$ and \$s\$ do describe \$p\$ with the (possible) singularity at \$(0,0)\$ removed. ### Challenge Given some polynomial \$p\$, find \$r\$ and \$s\$ as defined below. ### Definition First of all note that everything I say here is simplified, and does not completely correspond to the actual definitions. Given a polynomial \$p\$ in two variables \$x,y\$ the *blowup* is given by two polynomials \$r,s\$ again each in two variables. To get \$r\$ we first define \$R(x,v) := p(x,vx)\$. Then \$R(x,v)\$ is probably a multiple of \$x\$, i.e. \$R(x,v) = x^n \cdot r(x,v)\$ for some \$n\$ where \$x\$ does not divide \$r(x,v)\$. Then \$r(x,v)\$ is basically what remains after the division. The other polynomial is defined exactly the same, but we switch the variables: First write \$S(u,y) := p(uy,y)\$. Then \$s\$ is defined such that \$S(u,y) = y^m \cdot s(u,y)\$ for some \$m\$ where \$y\$ does not divide \$s(u,y)\$. In order to make it clearer consider following ### Example Consider the curve given by the zero locus of \$p(x,y) = y^2 - (1+x) x^2\$. (It has a singularity at \$(0,0)\$ because there is no well defined tangent at that point. ) ![](https://i.stack.imgur.com/HqcUb.png) Then we find $$R(x,v) = p(x,vx) = v^2x^2-(1+x)x^2 = x^2 (v^2-1-x)$$ Then \$r(x,v) = v^2 -1 -x\$ is the first polynomial. Similarly $$S(u,y) = p(uy,y) = y^2 - (1+ uy) u^2 y^2 = y^2 (1 - (1 + uy)u^2)$$ Then \$s(u,y) = 1 - (1 + uy)u^2 = 1 - u^2 + u^3y\$. ![r](https://i.stack.imgur.com/fEHwl.png)![s](https://i.stack.imgur.com/u4gZb.png) ### Input/Output Format (Same as [here](https://codegolf.stackexchange.com/questions/86879/algebraic-curve-plotter).) The polynomials are represented given as`(m+1) x (n+1)` matrices/lists of lists of integer coefficients, in the example below the terms of the coefficients are given in their position: ``` [ 1 * 1, 1 * x, 1 * x^2, 1 * x^3, ... , 1 * x^n ] [ y * 1, y * x, y * x^2, y * x^4, ... , y * x^n ] [ ... , ... , ... , ... , ... , ... ] [ y^m * 1, y^m * x, y^m * x^2, y^m * x^3 , ..., y^m * x^n] ``` So an ellipse `0 = x^2 + 2y^2 -1` would be represented as ``` [[-1, 0, 1], [ 0, 0, 0], [ 2, 0, 0]] ``` If you prefer you can also swap `x` and `y`. In each direction you are allowed to have trailing zeros (i.e. coefficients of higher degrees that are just zero). If it is more convenient you can also have staggered arrays (instead of a rectangular one) such that all sub sub-arrays contain no trailing zeros. * The output format is the same as the input format. ### Examples More to be added ([source for more](https://codegolf.stackexchange.com/questions/86879/algebraic-curve-plotter)) ``` Trifolium p(x,y) = (x^2 + y^2)^2 - (x^3 - 3xy^2) r(x,v) = v^4 x + 2 v^2 x + x + 3 v^2 - 1 s(u,y) = u^4 y + 2 u^2 y + y - u^3 + 3 u ``` ![p](https://i.stack.imgur.com/m7LTP.png) ![r](https://i.stack.imgur.com/NFVqY.png) ![s](https://i.stack.imgur.com/Cl8ty.png) ``` Descartes Folium p(x,y) = y^3 - 3xy + x^3 r(x,v) = v^3 x + x - 3v s(u,y) = u^3 y + y - 3u ``` ![p](https://i.stack.imgur.com/cqwZ2.png) ![r](https://i.stack.imgur.com/3kNHR.png) ![s](https://i.stack.imgur.com/FJ98Q.png) ### Examples w/o pictures ``` Trifolium: p: [[0,0,0,-1,1], [0,0,0, 0,0], [0,3,2, 0,0], [0,0,0, 0,0], [1,0,0, 0,0]] r: (using the "down" dimension for v instead of y) [[-1,1], [ 0,0], [ 3,2], [ 0,0], [ 0,1]] s: (using the "right" dimension for u instead of x) [[0,3,0,-1,0], [1,0,2, 0,1]] Descartes Folium: p: [[0, 0,0,1], [0,-3,0,0], [0, 0,0,0], [1, 0,0,0]] r: [[ 0,1], [-3,0], [ 0,0], [ 0,1]] s: [[0,-3,0,0], [1, 0,0,1]] Lemniscate: p: [[0,0,-1,0,1], [0,0, 0,0,0], [1,0, 0,0,0]] r: [[-1,0,1], [ 0,0,0], [ 1,0,0]] s: [[1,0,-1,0,0], [0,0, 0,0,0], [0,0, 0,0,1]] Powers: p: [[0,1,1,1,1]] r: [[1,1,1,1]] s: [[0,1,0,0,0], [0,0,1,0,0], [0,0,0,1,0], [0,0,0,0,1]] ``` [Answer] # [Python 3](https://docs.python.org/3/) + numpy, ~~165~~ 134 bytes ``` lambda p:(r(p),r(p.T).T) from numpy import* def r(p):w,l=where(p);s=w+l;n=min(s);o=zeros((len(p),max(s)-n+1));o[w,s-n]=p[w,l];return o ``` [Try it online!](https://tio.run/##nVNNb5wwFLz7VzxtLqbxRktzY8WpaaVIPfSQG7uK3F2jIIFtPRuRbZXfvn12MR9tcylG4HlvPDNGxl78i9H317o8XFvZfT9LsAVHbjNBj7unjG5Wo@lA9529QNNZg/4DO6saAqsYRFsOLwoVgb0rh9t2r8uu0dxle1P@UGgc563SQbGTr1Te6ts8o2Y1CLfVx9LSpD3uUfkeNZirV84/n6RTDkqo2A08YVObtuk7xllV7UQY21zkR8FghECPEd6Lj0u46uYzJFxVk8rEAFr@R2VHnMgO2tF5FotW1GaZYJT0QbmTRNoAfImBizFxEJvyboNKihc7SW8E0QzSgkB/P9FCLE82Kc1X1emGAnlVTF8upF98uZX9bhVgwVywIJ8ZedLb/UtvgnOgb2ZQ6FKY/PdIWgsQemuhtUvECzR6sCNjrDYIVoB6terk1fkZF3MHjYb5eBUM6DK9D6TwCgeu5hJRXui4ZrEtnVPogUcalOVCObuTbcszAfXmUZ8MItVBakebPOhHbXtP/9JB/7RvASYChlJUo/LnUSzUZuG3zV/WbmXt/s/aJWv3nrUbrS022vPNp5XyJrv@Ag "Python 3 – Try It Online") The function takes one `numpy` 2D array `p` as input and returns a tuple of `(r,s)` of two `numpy` 2D arrays. The breakdown of the solution is as follows. In order to compute the polynomial \$r\$, we rewrite each term \$x^jy^i\$ of \$p\$ into \$x^{j+i}(\frac{y}{x})^i\$, and it becomes \$x^{j+i}u^i\$ in \$p(x,ux)\$. So we can rearrange the input \$(m+1)\times (n+1)\$ matrix \$P\$ into a \$(m+1)\times (m+n-1)\$ matrix \$D\$ corresponding to \$p(x,ux)\$ by setting \$D[i,j+i]=P[i,j]\$. Then we eliminate all-zero columns at the beginning and end of \$D\$ to perform a reduction and get the output matrix \$R\$ for \$r\$. To compute \$s\$, we simply swap \$x\$ and \$y\$, repeat the same process, and then swap them back. This corresponds to computing \$R\$ for \$P^T\$ and then transposes the outcome. The following ungolfed code shows the above computation process. # Ungolfed (Basic) ``` import numpy as np def r(p): num_rows, num_cols = p.shape deg_mat = np.zeros((num_rows, num_rows + num_cols - 1)) for i, row in enumerate(p): deg_mat[i, i:i+num_cols] = row non_zero_col_idx, = np.where(deg_mat.any(axis=0)) return deg_mat[:,non_zero_col_idx.min():non_zero_col_idx.max()+1] def rs(p): return r(p), r(p.T).T ``` [Try it online!](https://tio.run/##nVPLiuMwELzrK5rsRSaKsXduhpz2AQN7zM0TjHCUjSCWhCSTZJf59mxLkV/zuKwDjrq7uqrcbpubP2n1dL/LzmjrQfWduQF3oAwhB3EES01WEcALS43VF8fiqdVnB1swuTtxIyLgIH43HfeYVSb/I6x2lC6bwgnWU/8GyiyLvUdtQTJAAEgFAhHCci9G8Rl/jThZyfXAskdB7Ht41KoJyqHQyMOVPcxcTsIKmvpzrm6UX6XbFkncCt9bNfJX7C1N3klFs@p9ml9pti73aVRutJsYw/BYuOe7LN/dvXC@abkTYXI1@QI7K4/6LPuOUFLXBQu/TcnKPSOQQsBbCp/Y13m4qJZTiHFdjywjArD9TaZATEQH7qg8kUUpLJOMEXT6XbiWW3wA@BkNV8lxIBv9bgLLYC9WBr4URDEYGgL8c0czsnKQGdz8Ep2SaMiLapxccD@b3EK@WBiYIWcoKCdEOfAVH/GNYTRE8O2TsL6Ggbga0XpxaOzs7MJGT6/@sSC69wEU/sIy4OrgmnJr@Q1X5rGV3DmBXySNUNhuZ@xZzs9niqt1XD2rVluLeeDKXYR9Uc/K9B5M9aL@mtcQDgAbUpEN0z8SWchNxK@rd9JuIe3@T9oN0u4zaZekjZXK09W3BfMqu/8D "Python 3 – Try It Online") A further improvement of the solution computes the matrix \$R\$ in one single pass based on \$R[i,j+i-c]=P[i,j]\$, where \$c=\min\_{P[i,j]\neq 0}i+j\$. # Ungolfed (Improved) ``` import numpy as np def r(p): y_deg, x_deg = np.where(p) # Retrieve degrees of y and x for non-zero elements in p total_deg = y_deg + x_deg min_total_deg = total_deg.min() max_total_deg = total_deg.max() out = np.zeros((p.shape[0], max_total_deg - min_total_deg + 1)) out[y_deg, y_deg + x_deg - min_total_deg] = p[y_deg, x_deg] return out def rs(p): return r(p), r(p.T).T ``` [Try it online!](https://tio.run/##nVNNj5swEL37V4yyF9ASBN0bUk7drbRST1VuLIqsZGiQwLZsp0ta7W9Px475yjaXEgkYz5v3HpMZdbZHKZ4ul6ZTUlsQp06dgRsQirED1qAjFRcM6DrvDvgzgd49YEOA9P2IGikP8AA/0OoGfyFQViMakDUQkThAD7XUIKRY/0YtAVvsUFgDjQDlia20vA2sXgQeryo@2zViN0eM7ylloviK4f09DO8DRp7s1bVzYaJIpebIFZZZldzUr280HyGPR44ytGFh9LakIiVVzhtW@XqN9qSFownNNWN3Q8q1O3H3dBun24tFY3d7bqifGyjZA2x1U8u2OXUsYmWZJe63zpO8ShiEEOgWwqfkyzxcZPMppLgsR5YRAVR@c5IRxqMdt1eeyLwUpVmcMHL6jGbPNX0AfPOGi@DYkY1@145lsOczA18IvBgMBQ5@39GMLB9kBjffsRMNGbJYjJ1z7medW8hnCwMz5AwF@YTIB77sX3xj6A2xijHmdkIlgL3CvcXDTs/e/W5Mf30xzJ4DuYcbBhodmmWuNT/TyFzHkxuDtMORh8JmM2OPU962EY1WvXoVe6k1ndN2mnfUb@JVKFoOVbyJP@rDhQNAuyPPRscvgcydTcQfq0/SZiFt/k/aDNLmnrQJ0ko3wkarrwvmVXz5Cw "Python 3 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~38~~ 37 bytes 1 byte saved thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn) by using `+/∘⍴` in place of the dummy literal `0` ``` ⊢∘⍉\+/∘⍴{q↓⍨⊃⍸×∨/q←(-⍳≢⍉⍵)⊖⍺↑⍵}¨⊂,⊂∘⍉ ``` [Try it online!](https://tio.run/##XY3LCoJQEIb3PUW7io54e5xyIYVdkKxsE9GmQFI4YoTV2pX7CqKlvcn/IjYe7UIMM8w3888/5tSW@kvTdgY5wnjkwIuUHEGC3Rnc77Zl0VxXM3gH8BTBFvz@PGGXyjSKmhL4BX5CWvBbC8ER/AFvT7DOSL1hlKVXbpEePNQKjzB25z2qi@HIzc1iQTckC@Ox60yytNHpKKwISWWqwSqoUxGgM@0LPxv1C0ajLkwKqCwknb1vxLS8qNq3XrxUPk9/hMq/VC2DuGZlqfkC "APL (Dyalog Unicode) – Try It Online") (a train with `⎕io` (index origin) set as 0) `⊂` enclosed right argument `,` concatenated with * `⊂∘` enclosed * `⍉` transposed right argument \$s\$ is computed from the former, \$r\$ from the latter `¨` on each `+/∘⍴{ ... }` perform the following function with left argument * `+/` sum + - `⍴` the shape of the right argument, i.e. get rows+columns and the right argument will be each of the enclosed matrices. `⍺↑⍵` and take left argument `⍺` many rows from the right argument `⍵`, if `⍵` is deficient in rows (which it will be because rows+columns > rows), it is padded with enough 0s The computation of substituting \$vx\$ or \$uy\$ in place of \$y\$ or \$x\$ is done by rotating the columns of `⍵` by their index, and since `⍵` is padded with 0s, columns of `⍵` are effectively prepended by the desired amount of 0s. `⊖` rotate columns by * `⍉⍵` transposed `⍵` * `≢` count rows, all together, `≢⍉⍵` gets the number of columns in `⍵` * `⍳` range 0 .. count-1 * `-` negated, to rotate in the other direction and the default for `⊖`, to ultimately yield 0 ¯1 ¯2 ... -(count-1), this automatically vectorises across each column such that the 0-th column is rotated by 0, the 1-st by 1, ... `q←` assign this to variable `q` Now to divide the polynomial by the largest power of \$x\$ or \$y\$, the leading all-0 rows have to be removed. `∨/` reduce by LCM across each row, if the row is all-0s, this yields 0, otherwise it gives a positive number `×` get its sign, `0` → `0` and positive number → `1` `⍸` indices of truthies, i.e. indices of 1s `⊃` pick the first element, `⊃⍸` simply gets the index of the first 1 `q↓⍨` drops that many rows from `q`, again `⎕io←0` helps in `⍸` returning the correct value for dropping the leading all-0 rows (exit function) \$s\$ is already achieved, to get \$r\$ the second value has to be transposed via [`⊢∘⍉\`](https://codegolf.stackexchange.com/a/150153/41805) --- Other approaches are listed below. ``` ⍝(⊢∘⍉\+/∘⍴{q↓⍨⊃⍸×∨/q←(-⍳≢⍉⍵)⊖⍺↑⍵}¨⊂,⊂∘⍉)¨a ⍝(⊢∘⍉\∘⌽⍴{q↓⍨⊃⍸×∨/q←(-⍳⍺)⊖⍵↑⍨+/⍴⍵}¨⊂∘⍉,⊂)¨a ⍝(⊢∘⍉\⌽∘⍴{q↓⍨⊃⍸×∨/q←(-⍳⍺)⊖⍵↑⍨+/⍴⍵}¨⊂,⊂∘⍉)¨a ⍝(⊢∘⍉\0{q↓⍨⊃⍸×∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵}¨⊂,⊂∘⍉)¨a ⍝(⊢∘⍉\+/∘⍴({⍵↓⍨⊃⍸×∨/⍵}(-∘⍳1⊃⊢∘⍴)⊖↑)¨⊂,⊂∘⍉)¨a ⍝(⊂∘⍉∘⊃@0⍴{q↓⍨⊃⍸×∨/q←(-⍳⍺)⊖⍵↑⍨+/⍴⍵}¨⊂∘⍉,⊂)¨a ⍝{⊢∘⍉\{q↓⍨⊃⍸×∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵}¨⍵(⍉⍵)}¨a ⍝(⊢∘⍉\(({⍵↓⍨⊃⍸×∨/⍵}(-∘⍳1⊃⍴)⊖⊢↑⍨1⊥⍴)¨⊂,⊂∘⍉))¨a ⍝(0 1{⍉⍣⍺⊢q↓⍨⊃⍸×∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵}¨⊂,⊂∘⍉)¨a ⍝{⊢∘⍉\{q[;⍸×∨\∨⌿q←↑(,\0⍴⍨≢⍵),¨↓⍵]}¨⍵(⍉⍵)}¨a ⍝{⊢∘⍉\{q↓⍨1⍳⍨×∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵}¨⍵(⍉⍵)}¨a ⍝(⊢∘⍉\(((⊢↓⍨1⍳⍨0≠∨/)(-∘⍳1⊃⍴)⊖⊢↑⍨1⊥⍴)¨⊂,⊂∘⍉))¨a ⍝{⊢∘⍉\{q[⍸×∨\∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵;]}¨⍵(⍉⍵)}¨a ⍝{⊢∘⍉\{q↓⍨+/0=∨\∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵}¨⍵(⍉⍵)}¨a ⍝{⊢∘⍉\{q↓⍨⌊/+⌿∧⍀0=q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵}¨⍵(⍉⍵)}¨a ⍝(⌽∘⍉¨1↓({⊖⍉q[⍸×∨\∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵;]}\3/⊂))¨a ⍝{⊢∘⍉\{↑(↓q)/⍨∨\×∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵}¨⍵(⍉⍵)}¨a ⍝f←⊢∘⍉\⋄{f{q[⍸×∨\∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵;]}¨f⍵⍵}¨a ⍝{1↓⌽∘⍉¨{⊖⍉q[⍸×∨\∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵;]}\3/⊂⍵}¨a ⍝{f←{q[⍸×∨\∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵;]}⋄(f⍵)(⍉f⍉⍵)}¨a ⍝{⊢∘⍉\{↑(↓q)/⍨∨\0≠∨/q←(-⍳≢⍉⍵)⊖⍵↑⍨+/⍴⍵}¨⍵(⍉⍵)}¨a ⍝{⊢∘⍉\{(0~⍨∊⍵)@(↓⍉(⊢-⌊/)@1+⍀⍉↑⍸0≠⍵)⊢0⍴⍨,⍨⌈/⍴⍵}¨⍵(⍉⍵)}¨a ``` ]
[Question] [ [Paterson's worms](https://en.wikipedia.org/wiki/Paterson%27s_worms) are a kind of cellular automaton that exist on an infinite triangular grid and, every step, they turn in some direction and move one unit. Their defining properties are that they can never go over the same spot twice, and whenever they encounter the same surroundings, they make the same decision. A worm always "sees" from its own perspective with its tail located at 3 and its head located in the center of this hexagon: [![Image from wikipedia](https://i.stack.imgur.com/pKRfL.png)](https://i.stack.imgur.com/pKRfL.png) For example, consider the worm with the rules: 1. If 0, 1, 2, 4, and 5 are all blank, move in direction 2 2. If 0, 1, 4, and 5 are blank, and 2 is filled, move in direction 0 3. If 0, 1, and 5 are blank, and 2 and 4 are filled, move in direction 0 This results in the following path (from Wikipedia): [![Worm path](https://i.stack.imgur.com/sCYOR.gif)](https://i.stack.imgur.com/sCYOR.gif) If the worm finds itself in a situation where all surroundings are filled, it terminates. # Input A list of numbers. The nth number indicates what decision the worm should make on the nth new situation it encounters where it has to make a decision. Note that if all but one of its surroundings are filled, it must move in the only direction that is empty. This does not count as a "decision" and does not consume a number. To generate the example worm shown above, the input would be `[2, 0, 0]`. The input is guaranteed to produce a worm that terminates and does not retrace its path, and the input will never be too short. # Output Output a list of coordinates indicating where the head of the worm is, starting at `(1, 0)`. We will consider moving up and to the right to be a decrease in only the y-value, but moving up and to the left to be a decrease in the x-value and a decrease in the y-value. For example, the output of the path for the example input is ``` (1, 0), (1, 1), (0, 0), (-1, -1), (0, -1), (0, 0), (0, 1), (-1, 0), (0, 0) ``` # Test cases You can use the javascript snippet to run tests as well. ``` [2,0,0]: (1,0),(1,1),(0,0),(-1,-1),(0,-1),(0,0),(0,1),(-1,0),(0,0) [1,0,4,0,1,5]: (1,0),(2,1),(2,2),(1,2),(0,1),(0,0),(0,-1),(1,-1),(2,0),(2,1),(3,1),(4,2),(4,3),(3,3),(2,2),(1,1),(1,0),(2,0),(3,1),(3,0),(4,0),(5,1),(5,2),(4,2),(3,2),(2,1),(1,1),(0,0),(-1,0),(-2,-1),(-2,-2),(-1,-2),(0,-1),(1,0),(1,-1),(2,-1),(3,0),(4,1),(4,2),(5,3),(5,4),(4,4),(3,3),(3,4),(2,4),(1,3),(1,2),(1,1),(0,1),(-1,0),(-1,1),(-2,1),(-3,0),(-3,-1),(-2,-1),(-1,-1),(0,0) [1,0,5,1]: (1,0),(2,1),(2,2),(1,2),(0,1),(0,0),(0,-1),(1,-1),(2,0),(2,1),(3,2),(3,3),(2,3),(1,2),(0,2),(-1,1),(-1,0),(0,0),(1,1),(1,2),(1,3),(0,3),(-1,2),(-1,1),(-2,0),(-2,-1),(-1,-1),(0,0) [2,0,1,0]: (1,0),(1,1),(0,0),(-1,-1),(0,-1),(0,0),(-1,0),(-1,-1),(-1,-2),(0,-1),(1,0),(2,1),(1,1),(0,1),(0,0) ``` The following hastily assembled (possibly buggy) program will display the worms: ``` var canvas = document.querySelector("canvas"); var ctx = canvas.getContext("2d"); var input, memory; var log = str => { console.log(str); document.querySelector("textarea").value += str + "\n"; }; var orientations = [ [1, 0], [1, 1], [0, 1], [-1, 0], [-1, -1], [0, -1] ]; var arena = { grid: [[[1, 0, 0]]], maxX: 1, maxY: 0, expandGrid: function() { var grid = this.grid; var newWidth = grid[0].length + 2, newHeight = grid.length + 2; var createRow = () => { var result = []; for (let i = 0; i < newWidth; ++i) result.push([0, 0, 0]); return result; }; for (let row of grid) { row.push([0, 0, 0]); row.unshift([0, 0, 0]); }; grid.push(createRow()); grid.unshift(createRow()); }, gridWidth: function() { return this.grid[0].length }, gridHeight: function() { return this.grid.length }, get: function(x, y) { var colOffset = Math.floor(this.gridWidth() / 2), rowOffset = Math.floor(this.gridHeight() / 2); return this.grid[y + rowOffset][x + colOffset]; }, isAtEnd: function(x, y) { var colOffset = Math.floor(this.gridWidth() / 2), rowOffset = Math.floor(this.gridHeight() / 2); return x === -colOffset || x + colOffset + 1 === this.gridWidth() || y === -rowOffset || y + rowOffset + 1 === this.gridHeight(); }, getEdge: function(x, y, o) { if (o % 2 === 0) return this.get(x, y)[o / 2]; else { let a, b; [a, b] = orientations[(o + 3) % 6]; return this.get(x - a, y - b)[((o + 3) % 6) / 2]; } }, setEdge: function(x, y, o) { if (Math.abs(x) > this.maxX) this.maxX = Math.abs(x); if (Math.abs(y) > this.maxY) this.maxY = Math.abs(y); if (o % 2 === 0) { if (this.get(x, y)[o / 2]) throw new Error("Path already taken"); this.get(x, y)[o / 2] = 1; } else { let a, b; [a, b] = orientations[(o + 3) % 6]; if (this.get(x - a, y - b)[((o + 3) % 6) / 2]) throw new Error("Path already taken"); this.get(x - a, y - b)[((o + 3) % 6) / 2] = 1; } } }; var drawGrid = function(area) { var width = canvas.width, height = canvas.height; ctx.clearRect(0, 0, width, height); var gridWidth = arena.gridWidth(), gridHeight = arena.gridHeight(); var triangleLen = Math.floor(Math.min( width / (arena.maxX * 2 + arena.maxY), height / (arena.maxY * Math.sqrt(3)), width / 4 )); var convert = (x, y) => [(x - y / 2) * triangleLen, triangleLen * y * Math.sqrt(3) / 2]; var drawCirc = function(x, y) { var a, b; ctx.beginPath(); [a, b] = convert(x, y); ctx.arc(a, b, 5, 0, 2 * Math.PI); ctx.fill(); }; ctx.fillStyle = "black"; for (let y = 0; triangleLen * y * Math.sqrt(3) / 2 < height; ++y) { for (let x = Math.floor(y / 2); triangleLen * (x - y / 2) < width; ++x) { drawCirc(x, y); } }; var drawLine = function(a, b, c, d) { var x, y; ctx.beginPath(); [x, y] = convert(a, b); ctx.moveTo(x, y); [x, y] = convert(a + c, b + d); ctx.lineTo(x, y); ctx.stroke(); }; var centerY = Math.round(height / (triangleLen * Math.sqrt(3))); var centerX = Math.round(width / (2 * triangleLen) + centerY / 2); ctx.fillStyle = "red"; drawCirc(centerX, centerY); for (let row = -(gridHeight - 1) / 2; row < (gridHeight + 1) / 2; ++row) { for (let col = -(gridWidth - 1) / 2; col < (gridWidth + 1) / 2; ++col) { let lines = arena.get(col, row); for (let j = 0; j < lines.length; ++j) { if (lines[j]) { let or = orientations[2 * j]; drawLine(col + centerX, row + centerY, or[0], or[1]); } } } } }; var step = function(x, y, absoluteOrientation) { log('(' + x + ',' + y + ')'); var surroundings = 0; for (let i = 0; i < 6; ++i) { if (arena.getEdge(x, y, (absoluteOrientation + i) % 6)) { surroundings |= (1 << i); } } if (surroundings == 63) { console.log("Done!"); return; } var action; if (memory[surroundings] !== undefined) action = memory[surroundings]; else { action = input.shift(); memory[surroundings] = action; } absoluteOrientation = (absoluteOrientation + action) % 6; arena.setEdge(x, y, absoluteOrientation); var or = orientations[absoluteOrientation]; x += or[0]; y += or[1]; if (arena.isAtEnd(x, y)) arena.expandGrid(); drawGrid(arena); setTimeout(function() { step(x, y, absoluteOrientation); }, parseFloat(document.querySelector("input[type=number]").value)); }; var go = function() { input = document.querySelector("input[type=text]").value.split(",").map(x => parseInt(x, 10)); arena.grid = [[[1, 0, 0]]]; arena.maxX = 1; arena.maxY = 0; memory = {}; for (let i = 0; i < 6; ++i) { memory[(~(1 << i)) & 63] = i; } arena.expandGrid(); arena.expandGrid(); step(1, 0, 0); }; document.querySelector("button").onclick = go; ``` ``` canvas { border: 1px solid black; } ``` ``` Input: <input type="text" placeholder="Comma separated input"><br /> Delay (ms): <input type="number" placeholder="delay" value="500"/><button>Go</button><br /> <canvas width="500" height="400"></canvas><br /> <textarea></textarea> ``` [Answer] # JavaScript (ES6), ~~261 250~~ 249 bytes Takes the input list in reverse order. Returns a list of \$[x,y]\$ pairs. ``` a=>(G=[[[x=1]]],v=[0,1,1,0,-1,-1],F=y=>[[x,y],...v.every((_,i)=>k^=g(o+i)[q%3]<<i,k=63,g=o=>(r=G[Y=y-o%2*v[q=(o+3)%6]]=G[Y]||[])[X=x-o%2*v[-~q%6]]=r[X]||[])?F(y+v[g(o+=F[k]|=1/F[k]?0:k&~-k?a.pop():31-Math.clz32(k))[q%3]=1,o%6],x+=v[-~o%6]):[]])(o=0) ``` [Try it online!](https://tio.run/##NZBNT8JAEIbv/ooeQGZku7ZUOCADJzExUQ9eMOsoGyxQil0opKHy8ddxFyS7yXy8kyfzzkwXejXKk8Xaz8x3fBzTUVMXHkkptaGQmUVBKhChfYHwQ/tZ9KmkrtVFyUJKWci4iPMS4EskSN30kyZg6gmqZTXiTicRKbUiMSFjwTk9qncqfVNt3BRqSXYwwmqL2fV5t1OMakCbf90/LE9argZnrdeHsl4ox6e@SnlH4a2LvaCdXh/8tKflwiwA21HoP@v1VI7mv1EDUjwvQ6EwFig2dXJwl2NbMSMYCvB4r1TDugxYeMrZvRPOePNSNkXo0sapGzBfybHJH/RoCtqjrjcy2crMYzk3E3h6e32Rq3WeZJNkXIJGr@7VPrKaDWPQMncHW8WAKH/0AsCe0isZHWUIle1mLyrbco9DlDOTZFATtQsA8fgH "JavaScript (Node.js) – Try It Online") This is essentially a port of the demo snippet. [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 115 bytes ``` D,:-D:2\6 3;f:{d::0;m::2/=6;X::(!6),x;{m::?m,p:2/^(+':x)?(2*h:*|x)+/:D 6!d+!6;$[(~p)|^c:X m?p;x;x,,h+D 6!d+:c]}/,1 0} ``` (not counting the function naming part, `f:`) [Try it online!](https://tio.run/##lVHLbsIwELzzFYuE1JjEwt48DruquPARSDSIikepKBQhDkE8fj1dO07oreph7fV6dmc83unDx6GuJwnpCeFbASlv6LoiMrwnwtFrwVOiqF@opOKrlMb75Cj1eRS/UKXGEQ63NLxVKh7RBIr@Ku4XPJhFj6O6zZc0hf34yBVXSbKNm3talvdRYsHc6zNdB7PL40QbqHjxveNosXn//BL8hU@qvPfOMwQDhiOBswXL7qAtaJfp5mikrK1PjCp7a/JglCoCShN6RIOUFt@MAZFKZILI5NmpRNPhQMZjUo8xcm84lzz3WJQa@v5fkmRBN9qt6DViS2haUt1Oa1hzYcwhkzzz7KnsKGElt0FJ9zrtTtqRajdDlkBmO0OMEsMECyIXLOS8LkPBaf@XLRjsSAMSA3/wOZiEXqqR0LaD4NOKTlcZftL@8ZftS0PzLwefboeJ9Q8 "K (ngn/k) – Try It Online") `D,:-D:2\6 3` generates the six cardinal directions `(1 0;1 1;0 1;-1 0;-1 -1;0 -1)` `d::0` is the current direction, used as an index mod 6 in `D` `m::2/=6` generates the initial worm memory `32 16 8 4 2 1`. the bits of each number encode the surroundings (0=visited segment; 1=unvisited). initially `m` contains only unambiguous surroundings - those in which a single exit is available. `X::(!6),x` are the worm's rules. we prepend `0 1 2 3 4 5` to match the intial unambiguous surroundings in `m`. `{`...`}/,1 0` apply until convergence the function `{` `}` starting with a 1-element list containing `1 0`. the list will contain pairs of coordinates visited by the worm. `D 6!d+!6` the six cardinal directions starting from `d` and going around clockwise `h:*|x` last of the argument, i.e. the position of the worm's head `(2*h:*|x)+/:D 6!d+!6` multiply the head's coordinates by 2 and add the cardinal directions. this is our way to represent the segments between points. `+':x` add pairs of adjacent visited points - this gives us the representations of segments between them `^(`...`)?`... find out which of the head's surrounding segments haven't been visited yet `p:2/` binary encode and assign to `p` `m::?m,p` append to `m` and keep the distinct, i.e. append `p` to `m` only if `p` doesn't occur in `m` `$[`...`;`...`;`...`]` if-then-else `c:X m?p` find the index of `p` in `m` and use it as an index in `X`. out-of-bounds indexing results in `0N` ("null") `$[(~p)|^c:X m?p;x;`...`]` if `p` is 0 (no exit path) or `c` is `0N`, then return `x` which will force convergence and stop the loop `x,,h+D 6!d+:c` else append the new head to `x` and repeat ]
[Question] [ The game of [xiangqi](https://en.wikipedia.org/wiki/Xiangqi), also known as Chinese chess, is a chess-like game popular in China, Vietnam, Taiwan, and other East Asian countries. The colours of the two sides in xiangqi are red and black. There are 16 black pieces in xiangqi: the 1 general (G), 2 advisor (A), 2 elephant (E), 2 horse (H), 2 chariot (R), 2 cannon (C), and 5 soldier (S). The vertical lines are known as files (columns), and the horizontal lines are known as ranks (rows). [![enter image description here](https://i.stack.imgur.com/TSkVO.png)](https://i.stack.imgur.com/TSkVO.png) A notation system partially described in A Manual of Chinese Chess and used by several computer software implementations describes moves in relative terms as follows: ``` [single-letter piece abbreviation][former file][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed] ``` The file numbers are counted from each player's right to each player's left. For black, the file numbers are shown in the picture, white background. In case there are two identical pieces in one file, symbols `+` (front, higher rank) and `-` (rear, lower rank) are used instead of former file number. If there are more than two, `+`(highest rank), `2`(2nd highest rank), `3`(3rd highest rank), ... is used. It's fine either you use the number or `-` to mean the lowest rank if more than two exist. If more than one file contain multiple identical pieces, both former file and order can't be omitted, but the piece abbreviation can be omitted. ``` [former order in the file][single-letter piece abbreviation][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed] [former order in the file][former file][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed] ``` A plus sign(`+`) is used to indicate forward movement. A minus sign(`-`) is used to indicate backwards movement. A dot or period(`.`) or equal sign(`=`) is used to indicate horizontal or lateral movement. For a piece that moves diagonally, the plus or minus sign is used rather than the period. Thus, if the five soldiers are at `(5,6), (7,6), (9,6), (5,8), (7,8)`, then each of them moving one rank forward are expressed as `-5+1, -7+1, S9+1, +5+1, +7+1`; two horses at `(3,4)` and `(3,8)` each moving to `(4,6)` are expressed as `-H+4` and `+H-4`; five soldiers are at `(5,6), (7,6), (5,4), (5,8), (7,8)`, then each of them moving one rank forward are expressed as `25+1, -7+1, 35+1, +5+1, +7+1`; two horses at `(3,4)` and `(5,8)` each moving to `(4,6)` are expressed as `3H+4` and `5H-4`. Given the current position and destination of the piece to move, and a list/set containing all positions of the same kind of pieces, output its expression. Input format is quie flexible. Shortest code win. Samples: (use format that first item of the array is moved) ``` S [(5,6), (7,6), (9,6), (5,8), (7,8)] (5,7) -> -5+1 or -S5+1 S [(7,6), (5,6), (9,6), (5,8), (7,8)] (7,7) -> -7+1 or -S7+1 S [(9,6), (5,6), (7,6), (5,8), (7,8)] (9,7) -> S9+1 S [(5,8), (5,6), (7,6), (9,6), (7,8)] (5,9) -> +5+1 or +S5+1 S [(7,8), (5,6), (7,6), (9,6), (5,8)] (7,9) -> +7+1 or +S7+1 H [(3,4), (3,8)] (4,6) -> -H+4 H [(3,8), (3,4)] (4,6) -> +H-4 H [(3,8)] (4,6) -> H3-4 S [(5,4), (5,8), (7,8), (5,6), (7,6)] (5,5) -> 35+1 or -5+1 or 3S5+1 or -S5+1 S [(5,6), (5,8), (7,8), (5,4), (7,6)] (5,7) -> 25+1 or 2S5+1 S [(5,8), (5,6), (7,8), (5,4), (7,6)] (5,9) -> +5+1 or +S5+1 ``` Pieces starting places and moving rules about from place`(x0,y0)`, to place`(x,y)` and their distance `r`, if that helps: ``` G (5,1) r=1 & 3<x<7 & y<4 A (4,1)(6,1) r^2=2 & 3<x<7 & y<4 E (3,1)(7,1) r^2=8 & y<6 H (2,1)(8,1) r^2=5 R (1,1)(9,1) (x-x0)(y-y0)=0 C (2,3)(8,3) (x-x0)(y-y0)=0 S (1,4)(3,4)(5,4)(7,4)(9,4) r=1 & y>=y0 & (y>y0 | y>5) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 63 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÷Qa9═wë•Θ╣äUuâ£▼+∙8WU▓kw≈▲!.┤α@∟┐₧╨═ºî⌂z▼0╬⌂6╕ú▄O&⌂¼^Mgâ╗╕.î¡☼: ``` [Run and debug it](https://staxlang.xyz/#p=f6516139cd778907e9b9845575839c1f2bf9385755b26b77f71e212eb4e0401cbf9ed0cda78c7f7a1f30ce7f36b8a3dc4f267fac5e4d6783bbb82e8cad0f3a&i=%5B5,6%5D+%22S%22+%5B%5B7,6%5D,+%5B9,6%5D,+%5B5,8%5D,+%5B7,8%5D%5D+%5B5,7%5D%0A%5B7,6%5D+%22S%22+%5B%5B5,6%5D,+%5B9,6%5D,+%5B5,8%5D,+%5B7,8%5D%5D+%5B7,7%5D%0A%5B9,6%5D+%22S%22+%5B%5B5,6%5D,+%5B7,6%5D,+%5B5,8%5D,+%5B7,8%5D%5D+%5B9,7%5D%0A%5B5,8%5D+%22S%22+%5B%5B5,6%5D,+%5B7,6%5D,+%5B9,6%5D,+%5B7,8%5D%5D+%5B5,9%5D%0A%5B7,8%5D+%22S%22+%5B%5B5,6%5D,+%5B7,6%5D,+%5B9,6%5D,+%5B5,8%5D%5D+%5B7,9%5D%0A%5B3,4%5D+%22H%22+%5B%5B3,8%5D%5D++++++++++++++++++++++%5B4,6%5D%0A%5B3,8%5D+%22H%22+%5B%5B3,4%5D%5D++++++++++++++++++++++%5B4,6%5D%0A%5B3,8%5D+%22H%22+%5B%5D+++++++++++++++++++++++++++%5B4,6%5D%0A%5B5,4%5D+%22S%22+%5B%5B5,8%5D,+%5B7,8%5D,+%5B5,6%5D,+%5B7,6%5D%5D+%5B5,5%5D%0A%5B5,6%5D+%22S%22+%5B%5B5,8%5D,+%5B7,8%5D,+%5B5,4%5D,+%5B7,6%5D%5D+%5B5,7%5D%0A%5B5,8%5D+%22S%22+%5B%5B5,6%5D,+%5B7,8%5D,+%5B5,4%5D,+%5B7,6%5D%5D+%5B5,9%5D&m=2) Takes input as `<position before> <piece type> [<other pieces>] <position after>`. ## Unpacked: ``` ;x\EE-c:+"=+-"@s|aaE=s,h?$+Ydx]+MEsxh|I@|oc%vcaHX-xn^$'-?'+?z?,b'S<*!,h$*++y+ ``` [Run and debug it](https://staxlang.xyz/#c=%3Bx%5CEE-c%3A%2B%22%3D%2B-%22%40s%7CaaE%3Ds,h%3F%24%2BYdx%5D%2BMEsxh%7CI%40%7Coc%25vcaHX-xn%5E%24%27-%3F%27%2B%3Fz%3F,b%27S%3C*%21,h%24*%2B%2By%2B&i=%5B5,6%5D+%22S%22+%5B%5B7,6%5D,+%5B9,6%5D,+%5B5,8%5D,+%5B7,8%5D%5D+%5B5,7%5D%0A%5B7,6%5D+%22S%22+%5B%5B5,6%5D,+%5B9,6%5D,+%5B5,8%5D,+%5B7,8%5D%5D+%5B7,7%5D%0A%5B9,6%5D+%22S%22+%5B%5B5,6%5D,+%5B7,6%5D,+%5B5,8%5D,+%5B7,8%5D%5D+%5B9,7%5D%0A%5B5,8%5D+%22S%22+%5B%5B5,6%5D,+%5B7,6%5D,+%5B9,6%5D,+%5B7,8%5D%5D+%5B5,9%5D%0A%5B7,8%5D+%22S%22+%5B%5B5,6%5D,+%5B7,6%5D,+%5B9,6%5D,+%5B5,8%5D%5D+%5B7,9%5D%0A%5B3,4%5D+%22H%22+%5B%5B3,8%5D%5D++++++++++++++++++++++%5B4,6%5D%0A%5B3,8%5D+%22H%22+%5B%5B3,4%5D%5D++++++++++++++++++++++%5B4,6%5D%0A%5B3,8%5D+%22H%22+%5B%5D+++++++++++++++++++++++++++%5B4,6%5D%0A%5B5,4%5D+%22S%22+%5B%5B5,8%5D,+%5B7,8%5D,+%5B5,6%5D,+%5B7,6%5D%5D+%5B5,5%5D%0A%5B5,6%5D+%22S%22+%5B%5B5,8%5D,+%5B7,8%5D,+%5B5,4%5D,+%5B7,6%5D%5D+%5B5,7%5D%0A%5B5,8%5D+%22S%22+%5B%5B5,6%5D,+%5B7,8%5D,+%5B5,4%5D,+%5B7,6%5D%5D+%5B5,9%5D&m=2) ### Explanation: The first part calculates the last part: The direction of movement and the resulting file/change in rank: ``` ;x\EE-c:+"=+-"@s|aaE=s,h?$+Yd ;x Push position after and before \ Zip -> [[file after, file before], [rank after, rank before]] E Push files and ranks separately E- Difference in ranks (after - before) c:+ Copy and get the sign (-1, 0, +1) "=+-"@ Index into the string "=+-" (-1 means last one) s|a Get the absolute value of the difference in rank aE= Check whether file before = file after (pure vertical movement) s Swap with abs of difference in rank ,h Get file after ? If file before = file after: abs(rank after - rank before) Else: file after (this is the number in the end) $ Convert to string + Concat the sign (-=+) and number. Yd Store in Y register and delete from stack. ``` The second part calculates the index in the file (`+`, `-` or a digit): ``` x]+MEsxh|I@|oc%vcaHX-xn^$'-?'+?z? x]+ Append the position before to the list of other pieces ME Push list of files, then list of ranks s Swap the two xh|I Find indices with file = file before @ Get ranks of these |o Calculate destination index of each element if the ranks were sorted c%v Get length of the array - 1 (no. of other pieces in file) ca Get the array of dest. indices again HX Get the last index (= index of the moving pieces) and store in register X - Then subtract from the no. of other pieces xn^ ... and increment the result -> That's the index from big rank to small $ ... and convert to string '-? If register X = 0 (lowest rank): "-" Else: The index from big to small '+? If index from big to small = 0 (high rank): "+" Else: Result from above z? If length of array = 1: "" Else: Result from above ``` So this means: * If there are no other pieces in this rank, "" * Else if we have the highest rank, "+" * Else if we have the lowest rank, "-" * Else, the index of the rank as a string These conditionals work in a somewhat special way: First, all the conditions are produced, most important to least important, then the `true` branch of the first condition is made (the index as a string). After this we push the falsy value for each condition, least important to most important, directly before performing the conditional `?`. The third part checks whether we need to add the file number: ``` ,b'S<*!,h$* , Get the piece type b Copy both the result of part 2 and the piece type 'S< Test whether the piece type is NOT "S" (actually less than "S", because all other piece types come before S in ASCII) * Repeat the result of part 2 by the result of this test: "" if the piece type is "S" the result of part 2 otherwise ! Negate this, "" is falsey. => This means NOT (part 2 is empty AND NOT piece type is "S") => Part 2 is empty iff this is the only piece in the file => NOT (only piece in file AND NOT piece type is "S") => NOT only piece in file OR piece type is "S" ,h Push the file before $ and convert it to string * Repeat that string by the result of above check: "" unless other pieces in file or piece type is "S" ``` So, after parts 1-3, the stack looks like this: ``` <position in the file (+, -, or number)> <piece type> <file if necessary> ``` And the Y register contains the movement itself (from part 1). The final part combines these into a single string: ``` ++y+ "<position in the file>" "<piece type>" "<file if necessary>" + "<position in the file>" "<piece type><file if necessary>" + "<position in the file><piece type><file if necessary>" y "<position in the file><piece type><file if necessary>" "<movement>" + "<position in the file><piece type><file if necessary><movement>" ``` This final result is implicitly output. ]